text
stringlengths 54
60.6k
|
|---|
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
#include <stdio.h>
#include <toku_assert.h>
#include <toku_os.h>
#include "toku_affinity.h"
int main(void) {
int r;
toku_cpuset_t orig;
TOKU_CPU_ZERO(&orig);
r = toku_getaffinity(toku_os_getpid(), sizeof orig, &orig);
if (r) {
perror("toku_getaffinity");
return r;
}
toku_cpuset_t set;
TOKU_CPU_ZERO(&set);
TOKU_CPU_SET(0, &set);
r = toku_setaffinity(toku_os_getpid(), sizeof set, &set);
if (r) {
perror("toku_setaffinity");
return r;
}
toku_cpuset_t chk;
TOKU_CPU_ZERO(&chk);
r = toku_getaffinity(toku_os_getpid(), sizeof chk, &chk);
if (r) {
perror("toku_getaffinity");
return r;
}
// don't want to expose this api unless we use it somewhere
#if defined(HAVE_SCHED_GETAFFINITY) || defined(HAVE_CPUSET_GETAFFINITY)
r = CPU_CMP(&set, &chk);
#else
r = memcmp(&set, &chk, sizeof set);
#endif
return r;
}
<commit_msg>refs #5368 compile fix for test-affinity<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
#include <stdio.h>
#include <string.h>
#include <toku_assert.h>
#include <toku_os.h>
#include "toku_affinity.h"
int main(void) {
int r;
toku_cpuset_t orig;
TOKU_CPU_ZERO(&orig);
r = toku_getaffinity(toku_os_getpid(), sizeof orig, &orig);
if (r) {
perror("toku_getaffinity");
return r;
}
toku_cpuset_t set;
TOKU_CPU_ZERO(&set);
TOKU_CPU_SET(0, &set);
r = toku_setaffinity(toku_os_getpid(), sizeof set, &set);
if (r) {
perror("toku_setaffinity");
return r;
}
toku_cpuset_t chk;
TOKU_CPU_ZERO(&chk);
r = toku_getaffinity(toku_os_getpid(), sizeof chk, &chk);
if (r) {
perror("toku_getaffinity");
return r;
}
// don't want to expose this api unless we use it somewhere
#if defined(HAVE_CPUSET_GETAFFINITY)
r = CPU_CMP(&set, &chk);
#else
// hope this is good enough on linux
r = memcmp(&set, &chk, sizeof set);
#endif
return r;
}
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2014 by Contributors
* \file engine_empty.cc
* \brief this file provides a dummy implementation of engine that does nothing
* this file provides a way to fall back to single node program without causing too many dependencies
* This is usually NOT needed, use engine_mpi or engine for real distributed version
* \author Tianqi Chen
*/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#define NOMINMAX
#include "../include/rabit/engine.h"
namespace rabit {
namespace engine {
/*! \brief EmptyEngine */
class EmptyEngine : public IEngine {
public:
EmptyEngine(void) {
version_number = 0;
}
virtual void Allreduce(void *sendrecvbuf_,
size_t type_nbytes,
size_t count,
ReduceFunction reducer,
PreprocFunction prepare_fun,
void *prepare_arg) {
utils::Error("EmptyEngine:: Allreduce is not supported,"\
"use Allreduce_ instead");
}
virtual void Broadcast(void *sendrecvbuf_, size_t size, int root) {
}
virtual void InitAfterException(void) {
utils::Error("EmptyEngine is not fault tolerant");
}
virtual int LoadCheckPoint(ISerializable *global_model,
ISerializable *local_model = NULL) {
return 0;
}
virtual void CheckPoint(const ISerializable *global_model,
const ISerializable *local_model = NULL) {
version_number += 1;
}
virtual void LazyCheckPoint(const ISerializable *global_model) {
version_number += 1;
}
virtual int VersionNumber(void) const {
return version_number;
}
/*! \brief get rank of current node */
virtual int GetRank(void) const {
return 0;
}
/*! \brief get total number of */
virtual int GetWorldSize(void) const {
return 1;
}
/*! \brief whether it is distributed */
virtual bool IsDistributed(void) const {
return false;
}
/*! \brief get the host name of current node */
virtual std::string GetHost(void) const {
return std::string("");
}
virtual void TrackerPrint(const std::string &msg) {
// simply print information into the tracker
utils::Printf("%s", msg.c_str());
}
private:
int version_number;
};
// singleton sync manager
EmptyEngine manager;
/*! \brief intiialize the synchronization module */
void Init(int argc, char *argv[]) {
}
/*! \brief finalize syncrhonization module */
void Finalize(void) {
}
/*! \brief singleton method to get engine */
IEngine *GetEngine(void) {
return &manager;
}
// perform in-place allreduce, on sendrecvbuf
void Allreduce_(void *sendrecvbuf,
size_t type_nbytes,
size_t count,
IEngine::ReduceFunction red,
mpi::DataType dtype,
mpi::OpType op,
IEngine::PreprocFunction prepare_fun,
void *prepare_arg) {
if (prepare_fun != NULL) prepare_fun(prepare_arg);
}
// code for reduce handle
ReduceHandle::ReduceHandle(void) : handle_(NULL), htype_(NULL) {
}
ReduceHandle::~ReduceHandle(void) {}
int ReduceHandle::TypeSize(const MPI::Datatype &dtype) {
return 0;
}
void ReduceHandle::Init(IEngine::ReduceFunction redfunc, size_t type_nbytes) {}
void ReduceHandle::Allreduce(void *sendrecvbuf,
size_t type_nbytes, size_t count,
IEngine::PreprocFunction prepare_fun,
void *prepare_arg) {
if (prepare_fun != NULL) prepare_fun(prepare_arg);
}
} // namespace engine
} // namespace rabit
<commit_msg>fix empty engine<commit_after>/*!
* Copyright (c) 2014 by Contributors
* \file engine_empty.cc
* \brief this file provides a dummy implementation of engine that does nothing
* this file provides a way to fall back to single node program without causing too many dependencies
* This is usually NOT needed, use engine_mpi or engine for real distributed version
* \author Tianqi Chen
*/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#define NOMINMAX
#include "../include/rabit/engine.h"
namespace rabit {
namespace engine {
/*! \brief EmptyEngine */
class EmptyEngine : public IEngine {
public:
EmptyEngine(void) {
version_number = 0;
}
virtual void Allreduce(void *sendrecvbuf_,
size_t type_nbytes,
size_t count,
ReduceFunction reducer,
PreprocFunction prepare_fun,
void *prepare_arg) {
utils::Error("EmptyEngine:: Allreduce is not supported,"\
"use Allreduce_ instead");
}
virtual void Broadcast(void *sendrecvbuf_, size_t size, int root) {
}
virtual void InitAfterException(void) {
utils::Error("EmptyEngine is not fault tolerant");
}
virtual int LoadCheckPoint(Serializable *global_model,
Serializable *local_model = NULL) {
return 0;
}
virtual void CheckPoint(const Serializable *global_model,
const Serializable *local_model = NULL) {
version_number += 1;
}
virtual void LazyCheckPoint(const Serializable *global_model) {
version_number += 1;
}
virtual int VersionNumber(void) const {
return version_number;
}
/*! \brief get rank of current node */
virtual int GetRank(void) const {
return 0;
}
/*! \brief get total number of */
virtual int GetWorldSize(void) const {
return 1;
}
/*! \brief whether it is distributed */
virtual bool IsDistributed(void) const {
return false;
}
/*! \brief get the host name of current node */
virtual std::string GetHost(void) const {
return std::string("");
}
virtual void TrackerPrint(const std::string &msg) {
// simply print information into the tracker
utils::Printf("%s", msg.c_str());
}
private:
int version_number;
};
// singleton sync manager
EmptyEngine manager;
/*! \brief intiialize the synchronization module */
void Init(int argc, char *argv[]) {
}
/*! \brief finalize syncrhonization module */
void Finalize(void) {
}
/*! \brief singleton method to get engine */
IEngine *GetEngine(void) {
return &manager;
}
// perform in-place allreduce, on sendrecvbuf
void Allreduce_(void *sendrecvbuf,
size_t type_nbytes,
size_t count,
IEngine::ReduceFunction red,
mpi::DataType dtype,
mpi::OpType op,
IEngine::PreprocFunction prepare_fun,
void *prepare_arg) {
if (prepare_fun != NULL) prepare_fun(prepare_arg);
}
// code for reduce handle
ReduceHandle::ReduceHandle(void) : handle_(NULL), htype_(NULL) {
}
ReduceHandle::~ReduceHandle(void) {}
int ReduceHandle::TypeSize(const MPI::Datatype &dtype) {
return 0;
}
void ReduceHandle::Init(IEngine::ReduceFunction redfunc, size_t type_nbytes) {}
void ReduceHandle::Allreduce(void *sendrecvbuf,
size_t type_nbytes, size_t count,
IEngine::PreprocFunction prepare_fun,
void *prepare_arg) {
if (prepare_fun != NULL) prepare_fun(prepare_arg);
}
} // namespace engine
} // namespace rabit
<|endoftext|>
|
<commit_before>#include "fake_player.hpp"
#include <ctime>
#include <boost/random/discrete_distribution.hpp>
#include "exception.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
namespace Quoridor {
FakePlayer::FakePlayer(std::shared_ptr<Board> board,
std::shared_ptr<Pawn> pawn)
: board_(board), pawn_(pawn), fin_nodes_(), gen_()
{
board_->pawn_final_nodes(pawn_, &fin_nodes_);
gen_.seed(static_cast<unsigned int>(std::time(NULL)));
}
FakePlayer::~FakePlayer()
{
}
IMove *FakePlayer::get_move()
{
boost::random::discrete_distribution<> dist{0.6, 0.6};
if (dist(gen_) == 0) {
size_t min_path_len = 81;
std::list<int> path;
for (auto end_node : fin_nodes_) {
std::list<int> nodes;
if (board_->get_path(pawn_, end_node, &nodes)) {
if (min_path_len > nodes.size()) {
min_path_len = nodes.size();
path = nodes;
}
}
}
if (path.size() == 0) {
throw Exception("all pathes are blocked");
}
auto node_it = path.begin();
int next_node = *node_it;
if (board_->is_occupied(next_node)) {
// @todo
}
return new WalkMove(next_node);
}
else {
boost::random::discrete_distribution<> dist_2{8, 2};
boost::random::uniform_int_distribution<> dist_9(0, 8);
boost::random::discrete_distribution<> dist_8{1, 1, 2, 3, 3, 2, 1, 1};
return new WallMove(Wall(dist_2(gen_), dist_9(gen_), dist_8(gen_), 2));
}
}
} /* namespace Quoridor */
<commit_msg>Add logging to FakePlayer.<commit_after>#include "fake_player.hpp"
#include <ctime>
#include <boost/random/discrete_distribution.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include "exception.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, boost::log::sources::logger)
namespace Quoridor {
FakePlayer::FakePlayer(std::shared_ptr<Board> board,
std::shared_ptr<Pawn> pawn)
: board_(board), pawn_(pawn), fin_nodes_(), gen_()
{
board_->pawn_final_nodes(pawn_, &fin_nodes_);
gen_.seed(static_cast<unsigned int>(std::time(NULL)));
}
FakePlayer::~FakePlayer()
{
}
IMove *FakePlayer::get_move()
{
boost::random::discrete_distribution<> dist{0.6, 0.6};
boost::log::sources::logger &lg = my_logger::get();
if (dist(gen_) == 0) {
size_t min_path_len = 81;
std::list<int> path;
for (auto end_node : fin_nodes_) {
std::list<int> nodes;
if (board_->get_path(pawn_, end_node, &nodes)) {
if (min_path_len > nodes.size()) {
min_path_len = nodes.size();
path = nodes;
}
}
}
if (path.size() == 0) {
throw Exception("all pathes are blocked");
}
auto node_it = path.begin();
int next_node = *node_it;
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "moving to "
<< next_node;
if (board_->is_occupied(next_node)) {
// @todo
}
return new WalkMove(next_node);
}
else {
boost::random::discrete_distribution<> dist_2{8, 2};
boost::random::uniform_int_distribution<> dist_9(0, 8);
boost::random::discrete_distribution<> dist_8{1, 1, 2, 3, 3, 2, 1, 1};
return new WallMove(Wall(dist_2(gen_), dist_9(gen_), dist_8(gen_), 2));
}
}
} /* namespace Quoridor */
<|endoftext|>
|
<commit_before>#include <stdio.h>
#ifdef WIN32
#include <winsock2.h>
#include <iphlpapi.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
#ifdef __linux__
#define SOCKET_FLAGS MSG_NOSIGNAL
#else
#define SOCKET_FLAGS 0
#endif
#include "fixedSocket.h"
TcpSocket::TcpSocket()
{
backlog_data_block = NULL;
backlog_data_block_size = 0;
}
TcpSocket::~TcpSocket()
{
if (backlog_data_block)
delete[] backlog_data_block;
}
sf::Socket::Status TcpSocket::send(sf::Packet& packet)
{
if (backlog_data_block || !send_backlog.empty())
{
if (send_backlog.empty())
backlog_clock.restart();
send_backlog.push_back(packet);
return sf::Socket::Done;
}
private_send(packet);
return sf::Socket::Done;
}
void TcpSocket::private_send(sf::Packet& packet)
{
int size = packet.getDataSize();
const void* data = packet.getData();
sf::Uint32 packetSize = ::htonl(static_cast<sf::Uint32>(size));
int sent = ::send(getHandle(), reinterpret_cast<const char*>(&packetSize), sizeof(packetSize), SOCKET_FLAGS);
if (sent < 0) //Note: No disconnect caught here. It will be caught in the receive call.
sent = 0;
if (sent < static_cast<int>(sizeof(packetSize)))
{
backlog_data_block_size = sizeof(packetSize) - sent + size;
backlog_data_block = new uint8_t[backlog_data_block_size];
memcpy(backlog_data_block, reinterpret_cast<const char*>(&packetSize) + sent, sizeof(packetSize) - sent);
memcpy(backlog_data_block + sizeof(packetSize) - sent, data, size);
return;
}
sent = ::send(getHandle(), reinterpret_cast<const char*>(data), size, SOCKET_FLAGS);
if (sent < 0) //Note: No disconnect caught here. It will be caught in the receive call.
sent = 0;
if (sent < size)
{
backlog_data_block_size = size - sent;
backlog_data_block = new uint8_t[backlog_data_block_size];
memcpy(backlog_data_block, reinterpret_cast<const char*>(data) + sent, backlog_data_block_size);
return;
}
}
void TcpSocket::update()
{
if (backlog_data_block)
{
int sent = ::send(getHandle(), reinterpret_cast<const char*>(backlog_data_block), backlog_data_block_size, SOCKET_FLAGS);
if (sent < 1) //Note: No disconnect caught here. It will be caught in the receive call.
return;
if (sent < backlog_data_block_size)
{
uint8_t* new_block = new uint8_t[backlog_data_block_size - sent];
memcpy(new_block, backlog_data_block + sent, backlog_data_block_size - sent);
delete[] backlog_data_block;
backlog_data_block = new_block;
return;
}
delete[] backlog_data_block;
backlog_data_block = NULL;
}
if (!send_backlog.empty())
{
while(!backlog_data_block && !send_backlog.empty())
{
private_send(send_backlog.front());
send_backlog.pop_front();
}
if (backlog_clock.getElapsedTime().asSeconds() > 20.0)
disconnect();
}
}
void UDPbroadcastPacket(sf::UdpSocket& socket, sf::Packet packet, int port_nr)
{
#ifdef WIN32
//On windows, using a single broadcast address seems to send the UPD package only on 1 interface.
// So use the windows API to get all addresses, construct broadcast addresses and send out the packets to all of them.
PMIB_IPADDRTABLE pIPAddrTable;
DWORD tableSize = 0;
GetIpAddrTable(NULL, &tableSize, 0);
if (tableSize > 0)
{
pIPAddrTable = (PMIB_IPADDRTABLE)calloc(tableSize, 1);
if (GetIpAddrTable(pIPAddrTable, &tableSize, 0) == NO_ERROR)
{
for(unsigned int n=0; n<pIPAddrTable->dwNumEntries; n++)
{
sf::IpAddress ip(ntohl((pIPAddrTable->table[n].dwAddr & pIPAddrTable->table[n].dwMask) | ~pIPAddrTable->table[n].dwMask));
socket.send(packet, ip, port_nr);
}
}
free(pIPAddrTable);
}
#else
socket.send(packet, sf::IpAddress::Broadcast, port_nr);
#endif
}
<commit_msg>Add missing include for linux<commit_after>#include <stdio.h>
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
#include <iphlpapi.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
#ifdef __linux__
#define SOCKET_FLAGS MSG_NOSIGNAL
#else
#define SOCKET_FLAGS 0
#endif
#include "fixedSocket.h"
TcpSocket::TcpSocket()
{
backlog_data_block = NULL;
backlog_data_block_size = 0;
}
TcpSocket::~TcpSocket()
{
if (backlog_data_block)
delete[] backlog_data_block;
}
sf::Socket::Status TcpSocket::send(sf::Packet& packet)
{
if (backlog_data_block || !send_backlog.empty())
{
if (send_backlog.empty())
backlog_clock.restart();
send_backlog.push_back(packet);
return sf::Socket::Done;
}
private_send(packet);
return sf::Socket::Done;
}
void TcpSocket::private_send(sf::Packet& packet)
{
int size = packet.getDataSize();
const void* data = packet.getData();
sf::Uint32 packetSize = ::htonl(static_cast<sf::Uint32>(size));
int sent = ::send(getHandle(), reinterpret_cast<const char*>(&packetSize), sizeof(packetSize), SOCKET_FLAGS);
if (sent < 0) //Note: No disconnect caught here. It will be caught in the receive call.
sent = 0;
if (sent < static_cast<int>(sizeof(packetSize)))
{
backlog_data_block_size = sizeof(packetSize) - sent + size;
backlog_data_block = new uint8_t[backlog_data_block_size];
memcpy(backlog_data_block, reinterpret_cast<const char*>(&packetSize) + sent, sizeof(packetSize) - sent);
memcpy(backlog_data_block + sizeof(packetSize) - sent, data, size);
return;
}
sent = ::send(getHandle(), reinterpret_cast<const char*>(data), size, SOCKET_FLAGS);
if (sent < 0) //Note: No disconnect caught here. It will be caught in the receive call.
sent = 0;
if (sent < size)
{
backlog_data_block_size = size - sent;
backlog_data_block = new uint8_t[backlog_data_block_size];
memcpy(backlog_data_block, reinterpret_cast<const char*>(data) + sent, backlog_data_block_size);
return;
}
}
void TcpSocket::update()
{
if (backlog_data_block)
{
int sent = ::send(getHandle(), reinterpret_cast<const char*>(backlog_data_block), backlog_data_block_size, SOCKET_FLAGS);
if (sent < 1) //Note: No disconnect caught here. It will be caught in the receive call.
return;
if (sent < backlog_data_block_size)
{
uint8_t* new_block = new uint8_t[backlog_data_block_size - sent];
memcpy(new_block, backlog_data_block + sent, backlog_data_block_size - sent);
delete[] backlog_data_block;
backlog_data_block = new_block;
return;
}
delete[] backlog_data_block;
backlog_data_block = NULL;
}
if (!send_backlog.empty())
{
while(!backlog_data_block && !send_backlog.empty())
{
private_send(send_backlog.front());
send_backlog.pop_front();
}
if (backlog_clock.getElapsedTime().asSeconds() > 20.0)
disconnect();
}
}
void UDPbroadcastPacket(sf::UdpSocket& socket, sf::Packet packet, int port_nr)
{
#ifdef WIN32
//On windows, using a single broadcast address seems to send the UPD package only on 1 interface.
// So use the windows API to get all addresses, construct broadcast addresses and send out the packets to all of them.
PMIB_IPADDRTABLE pIPAddrTable;
DWORD tableSize = 0;
GetIpAddrTable(NULL, &tableSize, 0);
if (tableSize > 0)
{
pIPAddrTable = (PMIB_IPADDRTABLE)calloc(tableSize, 1);
if (GetIpAddrTable(pIPAddrTable, &tableSize, 0) == NO_ERROR)
{
for(unsigned int n=0; n<pIPAddrTable->dwNumEntries; n++)
{
sf::IpAddress ip(ntohl((pIPAddrTable->table[n].dwAddr & pIPAddrTable->table[n].dwMask) | ~pIPAddrTable->table[n].dwMask));
socket.send(packet, ip, port_nr);
}
}
free(pIPAddrTable);
}
#else
socket.send(packet, sf::IpAddress::Broadcast, port_nr);
#endif
}
<|endoftext|>
|
<commit_before>#include <Automaton.h>
#include "Atm_led.h"
Atm_led & Atm_led::begin( int attached_pin )
{
static const state_t state_table[] PROGMEM = {
/* ON_ENTER ON_LOOP ON_EXIT EVT_ON_TIMER EVT_OFF_TIMER EVT_COUNTER EVT_ON EVT_OFF EVT_BLINK ELSE */
/* IDLE */ ACT_INIT, ATM_SLEEP, -1, -1, -1, -1, ON, -1, START, -1, // LED off
/* ON */ ACT_ON, ATM_SLEEP, -1, -1, -1, -1, -1, IDLE, START, -1, // LED on
/* START */ ACT_ON, -1, -1, BLINK_OFF, -1, -1, ON, IDLE, -1, -1, // Start blinking
/* BLINK_OFF */ ACT_OFF, -1, -1, -1, START, IDLE, ON, -1, -1, -1,
};
Machine::begin( state_table, ELSE );
Machine::msgQueue( messages, MSG_END );
pin = attached_pin;
pinMode( pin, OUTPUT );
on_timer.begin( this, 500 );
off_timer.begin( this, 500 );
repeat_count = ATM_COUNTER_OFF;
counter.set( repeat_count );
return *this;
}
Atm_led & Atm_led::blink( int duration )
{
on_timer.set( duration ); // Time in which led is fully on
return *this;
}
Atm_led & Atm_led::pause( int duration )
{
off_timer.set( duration ); // Time in which led is fully off
return *this;
}
Atm_led & Atm_led::fade( int fade ) { return *this; } // Dummy for method compatibility with Atm_fade
Atm_led & Atm_led::repeat( int repeat )
{
repeat_count = repeat >= 0 ? repeat : ATM_COUNTER_OFF;
counter.set( repeat_count );
return *this;
}
int Atm_led::event( int id )
{
switch ( id ) {
case EVT_ON_TIMER :
return on_timer.expired();
case EVT_OFF_TIMER :
return off_timer.expired();
case EVT_COUNTER :
return counter.expired();
case EVT_ON :
return msgRead( MSG_ON, 1, 1 );
case EVT_OFF :
return msgRead( MSG_OFF, 1, 1 );
case EVT_BLINK :
return msgRead( MSG_BLINK, 1, 1 );
}
return 0;
}
void Atm_led::action( int id )
{
switch ( id ) {
case ACT_INIT :
counter.set( repeat_count );
digitalWrite( pin, LOW );
return;
case ACT_ON :
counter.decrement();
Serial.print( "decrement\n" );
digitalWrite( pin, HIGH );
return;
case ACT_OFF :
digitalWrite( pin, LOW );
return;
}
}
<commit_msg>Removed debug messages<commit_after>#include <Automaton.h>
#include "Atm_led.h"
Atm_led & Atm_led::begin( int attached_pin )
{
static const state_t state_table[] PROGMEM = {
/* ON_ENTER ON_LOOP ON_EXIT EVT_ON_TIMER EVT_OFF_TIMER EVT_COUNTER EVT_ON EVT_OFF EVT_BLINK ELSE */
/* IDLE */ ACT_INIT, ATM_SLEEP, -1, -1, -1, -1, ON, -1, START, -1, // LED off
/* ON */ ACT_ON, ATM_SLEEP, -1, -1, -1, -1, -1, IDLE, START, -1, // LED on
/* START */ ACT_ON, -1, -1, BLINK_OFF, -1, -1, ON, IDLE, -1, -1, // Start blinking
/* BLINK_OFF */ ACT_OFF, -1, -1, -1, START, IDLE, ON, -1, -1, -1,
};
Machine::begin( state_table, ELSE );
Machine::msgQueue( messages, MSG_END );
pin = attached_pin;
pinMode( pin, OUTPUT );
on_timer.begin( this, 500 );
off_timer.begin( this, 500 );
repeat_count = ATM_COUNTER_OFF;
counter.set( repeat_count );
return *this;
}
Atm_led & Atm_led::blink( int duration )
{
on_timer.set( duration ); // Time in which led is fully on
return *this;
}
Atm_led & Atm_led::pause( int duration )
{
off_timer.set( duration ); // Time in which led is fully off
return *this;
}
Atm_led & Atm_led::fade( int fade ) { return *this; } // Dummy for method compatibility with Atm_fade
Atm_led & Atm_led::repeat( int repeat )
{
repeat_count = repeat >= 0 ? repeat : ATM_COUNTER_OFF;
counter.set( repeat_count );
return *this;
}
int Atm_led::event( int id )
{
switch ( id ) {
case EVT_ON_TIMER :
return on_timer.expired();
case EVT_OFF_TIMER :
return off_timer.expired();
case EVT_COUNTER :
return counter.expired();
case EVT_ON :
return msgRead( MSG_ON, 1, 1 );
case EVT_OFF :
return msgRead( MSG_OFF, 1, 1 );
case EVT_BLINK :
return msgRead( MSG_BLINK, 1, 1 );
}
return 0;
}
void Atm_led::action( int id )
{
switch ( id ) {
case ACT_INIT :
counter.set( repeat_count );
digitalWrite( pin, LOW );
return;
case ACT_ON :
counter.decrement();
digitalWrite( pin, HIGH );
return;
case ACT_OFF :
digitalWrite( pin, LOW );
return;
}
}
<|endoftext|>
|
<commit_before>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "Scope.h"
namespace Halide {
using std::string;
using std::vector;
RVar::operator Expr() const {
return new Internal::Variable(Int(32), name(), domain);
}
Internal::ReductionDomain build_domain(string name0, Expr min0, Expr extent0,
string name1, Expr min1, Expr extent1,
string name2, Expr min2, Expr extent2,
string name3, Expr min3, Expr extent3) {
vector<Internal::ReductionVariable> d;
if (min0.defined()) {
Internal::ReductionVariable v = {name0, min0, extent0};
d.push_back(v);
}
if (min1.defined()) {
Internal::ReductionVariable v = {name1, min1, extent1};
d.push_back(v);
}
if (min2.defined()) {
Internal::ReductionVariable v = {name2, min2, extent2};
d.push_back(v);
}
if (min3.defined()) {
Internal::ReductionVariable v = {name3, min3, extent3};
d.push_back(v);
}
Internal::ReductionDomain dom(d);
return dom;
}
RDom::RDom(Expr min, Expr extent, string name) {
min = cast<int>(min);
extent = cast<int>(extent);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x", min, extent,
"", Expr(), Expr(),
"", Expr(), Expr(),
"", Expr(), Expr());
x = RVar(name + ".x", min, extent, domain);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) {
min0 = cast<int>(min0);
extent0 = cast<int>(extent0);
min1 = cast<int>(min1);
extent1 = cast<int>(extent1);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x", min0, extent0,
name + ".y", min1, extent1,
"", Expr(), Expr(),
"", Expr(), Expr());
x = RVar(name + ".x", min0, extent0, domain);
y = RVar(name + ".y", min1, extent1, domain);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) {
min0 = cast<int>(min0);
extent0 = cast<int>(extent0);
min1 = cast<int>(min1);
extent1 = cast<int>(extent1);
min2 = cast<int>(min2);
extent2 = cast<int>(extent2);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x", min0, extent0,
name + ".y", min1, extent1,
name + ".z", min2, extent2,
"", Expr(), Expr());
x = RVar(name + ".x", min0, extent1, domain);
y = RVar(name + ".y", min1, extent1, domain);
z = RVar(name + ".z", min2, extent2, domain);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, string name) {
min0 = cast<int>(min0);
extent0 = cast<int>(extent0);
min1 = cast<int>(min1);
extent1 = cast<int>(extent1);
min2 = cast<int>(min2);
extent2 = cast<int>(extent2);
min3 = cast<int>(min3);
extent3 = cast<int>(extent3);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x", min0, extent0,
name + ".y", min1, extent1,
name + ".z", min2, extent2,
name + ".w", min3, extent3);
x = RVar(name + ".x", min0, extent1, domain);
y = RVar(name + ".y", min1, extent1, domain);
z = RVar(name + ".z", min2, extent2, domain);
w = RVar(name + ".w", min3, extent3, domain);
}
RDom::RDom(Buffer b) {
Expr min[4], extent[4];
for (int i = 0; i < 4; i++) {
if (b.dimensions() > i) {
min[i] = b.min(i);
extent[i] = b.extent(i);
}
}
string names[] = {b.name() + ".x", b.name() + ".y", b.name() + ".z", b.name() + ".w"};
domain = build_domain(names[0], min[0], extent[0],
names[1], min[1], extent[1],
names[2], min[2], extent[2],
names[3], min[3], extent[3]);
RVar *vars[] = {&x, &y, &z, &w};
for (int i = 0; i < 4; i++) {
if (b.dimensions() > i) {
*(vars[i]) = RVar(names[i], min[i], extent[i], domain);
}
}
}
RDom::RDom(ImageParam p) {
Expr min[4], extent[4];
for (int i = 0; i < 4; i++) {
if (p.dimensions() > i) {
min[i] = 0;
extent[i] = p.extent(i);
}
}
string names[] = {p.name() + ".x", p.name() + ".y", p.name() + ".z", p.name() + ".w"};
domain = build_domain(names[0], min[0], extent[0],
names[1], min[1], extent[1],
names[2], min[2], extent[2],
names[3], min[3], extent[3]);
RVar *vars[] = {&x, &y, &z, &w};
for (int i = 0; i < 4; i++) {
if (p.dimensions() > i) {
*(vars[i]) = RVar(names[i], min[i], extent[i], domain);
}
}
}
int RDom::dimensions() const {
return (int)domain.domain().size();
}
RVar RDom::operator[](int i) {
if (i == 0) return x;
if (i == 1) return y;
if (i == 2) return z;
if (i == 3) return w;
assert(false && "Reduction domain index out of bounds");
return x; // Keep the compiler happy
}
RDom::operator Expr() const {
assert(dimensions() == 1 && "Can only treat single-dimensional RDoms as expressions");
return Expr(x);
}
RDom::operator RVar() const {
assert(dimensions() == 1 && "Can only treat single-dimensional RDoms as RVars");
return x;
}
}
<commit_msg>Give RVars more unique magic names to prevent name conflicts with pure vars.<commit_after>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "Scope.h"
namespace Halide {
using std::string;
using std::vector;
RVar::operator Expr() const {
return new Internal::Variable(Int(32), name(), domain);
}
Internal::ReductionDomain build_domain(string name0, Expr min0, Expr extent0,
string name1, Expr min1, Expr extent1,
string name2, Expr min2, Expr extent2,
string name3, Expr min3, Expr extent3) {
vector<Internal::ReductionVariable> d;
if (min0.defined()) {
Internal::ReductionVariable v = {name0, min0, extent0};
d.push_back(v);
}
if (min1.defined()) {
Internal::ReductionVariable v = {name1, min1, extent1};
d.push_back(v);
}
if (min2.defined()) {
Internal::ReductionVariable v = {name2, min2, extent2};
d.push_back(v);
}
if (min3.defined()) {
Internal::ReductionVariable v = {name3, min3, extent3};
d.push_back(v);
}
Internal::ReductionDomain dom(d);
return dom;
}
// We suffix all RVars with $r to prevent unintentional name matches with pure vars called x, y, z, w.
RDom::RDom(Expr min, Expr extent, string name) {
min = cast<int>(min);
extent = cast<int>(extent);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x$r", min, extent,
"", Expr(), Expr(),
"", Expr(), Expr(),
"", Expr(), Expr());
x = RVar(name + ".x$r", min, extent, domain);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) {
min0 = cast<int>(min0);
extent0 = cast<int>(extent0);
min1 = cast<int>(min1);
extent1 = cast<int>(extent1);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x$r", min0, extent0,
name + ".y$r", min1, extent1,
"", Expr(), Expr(),
"", Expr(), Expr());
x = RVar(name + ".x$r", min0, extent0, domain);
y = RVar(name + ".y$r", min1, extent1, domain);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) {
min0 = cast<int>(min0);
extent0 = cast<int>(extent0);
min1 = cast<int>(min1);
extent1 = cast<int>(extent1);
min2 = cast<int>(min2);
extent2 = cast<int>(extent2);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x$r", min0, extent0,
name + ".y$r", min1, extent1,
name + ".z$r", min2, extent2,
"", Expr(), Expr());
x = RVar(name + ".x$r", min0, extent1, domain);
y = RVar(name + ".y$r", min1, extent1, domain);
z = RVar(name + ".z$r", min2, extent2, domain);
}
RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, string name) {
min0 = cast<int>(min0);
extent0 = cast<int>(extent0);
min1 = cast<int>(min1);
extent1 = cast<int>(extent1);
min2 = cast<int>(min2);
extent2 = cast<int>(extent2);
min3 = cast<int>(min3);
extent3 = cast<int>(extent3);
if (name == "") name = Internal::unique_name('r');
domain = build_domain(name + ".x$r", min0, extent0,
name + ".y$r", min1, extent1,
name + ".z$r", min2, extent2,
name + ".w$r", min3, extent3);
x = RVar(name + ".x$r", min0, extent1, domain);
y = RVar(name + ".y$r", min1, extent1, domain);
z = RVar(name + ".z$r", min2, extent2, domain);
w = RVar(name + ".w$r", min3, extent3, domain);
}
RDom::RDom(Buffer b) {
Expr min[4], extent[4];
for (int i = 0; i < 4; i++) {
if (b.dimensions() > i) {
min[i] = b.min(i);
extent[i] = b.extent(i);
}
}
string names[] = {b.name() + ".x$r", b.name() + ".y$r", b.name() + ".z$r", b.name() + ".w$r"};
domain = build_domain(names[0], min[0], extent[0],
names[1], min[1], extent[1],
names[2], min[2], extent[2],
names[3], min[3], extent[3]);
RVar *vars[] = {&x, &y, &z, &w};
for (int i = 0; i < 4; i++) {
if (b.dimensions() > i) {
*(vars[i]) = RVar(names[i], min[i], extent[i], domain);
}
}
}
RDom::RDom(ImageParam p) {
Expr min[4], extent[4];
for (int i = 0; i < 4; i++) {
if (p.dimensions() > i) {
min[i] = 0;
extent[i] = p.extent(i);
}
}
string names[] = {p.name() + ".x$r", p.name() + ".y$r", p.name() + ".z$r", p.name() + ".w$r"};
domain = build_domain(names[0], min[0], extent[0],
names[1], min[1], extent[1],
names[2], min[2], extent[2],
names[3], min[3], extent[3]);
RVar *vars[] = {&x, &y, &z, &w};
for (int i = 0; i < 4; i++) {
if (p.dimensions() > i) {
*(vars[i]) = RVar(names[i], min[i], extent[i], domain);
}
}
}
int RDom::dimensions() const {
return (int)domain.domain().size();
}
RVar RDom::operator[](int i) {
if (i == 0) return x;
if (i == 1) return y;
if (i == 2) return z;
if (i == 3) return w;
assert(false && "Reduction domain index out of bounds");
return x; // Keep the compiler happy
}
RDom::operator Expr() const {
assert(dimensions() == 1 && "Can only treat single-dimensional RDoms as expressions");
return Expr(x);
}
RDom::operator RVar() const {
assert(dimensions() == 1 && "Can only treat single-dimensional RDoms as RVars");
return x;
}
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 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
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#define LOG_THIS BX_CPU_THIS_PTR
void
BX_CPU_C::SAHF(bxInstruction_c *i)
{
set_SF((AH & 0x80) >> 7);
set_ZF((AH & 0x40) >> 6);
set_AF((AH & 0x10) >> 4);
set_CF(AH & 0x01);
set_PF((AH & 0x04) >> 2);
}
void
BX_CPU_C::LAHF(bxInstruction_c *i)
{
AH = (get_SF() ? 0x80 : 0) |
(get_ZF() ? 0x40 : 0) |
(get_AF() ? 0x10 : 0) |
(get_PF() ? 0x04 : 0) |
(0x02) |
(get_CF() ? 0x01 : 0);
}
void
BX_CPU_C::CLC(bxInstruction_c *i)
{
set_CF(0);
}
void
BX_CPU_C::STC(bxInstruction_c *i)
{
set_CF(1);
}
void
BX_CPU_C::CLI(bxInstruction_c *i)
{
#if BX_CPU_LEVEL >= 2
if (protected_mode()) {
if (CPL > BX_CPU_THIS_PTR get_IOPL ()) {
//BX_INFO(("CLI: CPL > IOPL")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#if BX_CPU_LEVEL >= 3
else if (v8086_mode()) {
if (BX_CPU_THIS_PTR get_IOPL () != 3) {
//BX_INFO(("CLI: IOPL != 3")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#endif
#endif
BX_CPU_THIS_PTR clear_IF ();
}
void
BX_CPU_C::STI(bxInstruction_c *i)
{
#if BX_CPU_LEVEL >= 2
if (protected_mode()) {
if (CPL > BX_CPU_THIS_PTR get_IOPL ()) {
//BX_INFO(("STI: CPL > IOPL")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#if BX_CPU_LEVEL >= 3
else if (v8086_mode()) {
if (BX_CPU_THIS_PTR get_IOPL () != 3) {
//BX_INFO(("STI: IOPL != 3")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#endif
#endif
if (!BX_CPU_THIS_PTR get_IF ()) {
BX_CPU_THIS_PTR assert_IF ();
BX_CPU_THIS_PTR inhibit_mask |= BX_INHIBIT_INTERRUPTS;
BX_CPU_THIS_PTR async_event = 1;
}
}
void
BX_CPU_C::CLD(bxInstruction_c *i)
{
BX_CPU_THIS_PTR clear_DF ();
}
void
BX_CPU_C::STD(bxInstruction_c *i)
{
BX_CPU_THIS_PTR assert_DF ();
}
void
BX_CPU_C::CMC(bxInstruction_c *i)
{
set_CF( !get_CF() );
}
void
BX_CPU_C::PUSHF_Fv(bxInstruction_c *i)
{
if (v8086_mode() && (BX_CPU_THIS_PTR get_IOPL ()<3)) {
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
#if BX_CPU_LEVEL >= 3
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64) {
push_64(read_eflags() & 0x00fcffff);
}
else
#endif
if (i->os32L()) {
push_32(read_eflags() & 0x00fcffff);
}
else
#endif
{
push_16(read_flags());
}
}
void
BX_CPU_C::POPF_Fv(bxInstruction_c *i)
{
Bit32u changeMask = 0x004dd5;
Bit32u flags32;
#if BX_CPU_LEVEL >= 3
if (protected_mode()) {
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64) {
Bit64u flags64;
pop_64(&flags64);
flags32 = flags64;
changeMask |= 0x240000; // ID,AC
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
else
#endif // #if BX_SUPPORT_X86_64
if (i->os32L()) {
pop_32(&flags32);
changeMask |= 0x240000; // ID,AC
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
else
#endif // BX_CPU_LEVEL >= 3
{
Bit16u flags16;
pop_16(&flags16);
flags32 = flags16;
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
// Protected-mode: VIP/VIF cleared, VM unaffected.
// Does this happen for 16 bit case? fixme!
flags32 &= ~( (1<<20) | (1<<19) ); // Clear VIP/VIF
}
else if (v8086_mode()) {
if (BX_CPU_THIS_PTR get_IOPL() < 3) {
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
if (i->os32L()) {
pop_32(&flags32);
changeMask |= 0x240000; // ID,AC
}
else {
Bit16u flags16;
pop_16(&flags16);
flags32 = flags16;
}
// v8086-mode: VM,RF,IOPL,VIP,VIF are unaffected.
changeMask |= (1<<9); // IF
}
else { // Real-mode
if (i->os32L()) {
pop_32(&flags32);
changeMask |= 0x243200; // ID,AC,IOPL,IF
}
else { /* 16 bit opsize */
Bit16u flags16;
pop_16(&flags16);
flags32 = flags16;
changeMask |= 0x3200; // IOPL,IF
}
// Real-mode: VIP/VIF cleared, VM unaffected.
flags32 &= ~( (1<<20) | (1<<19) ); // Clear VIP/VIF
}
writeEFlags(flags32, changeMask);
}
void
BX_CPU_C::SALC(bxInstruction_c *i)
{
if ( get_CF() ) {
AL = 0xff;
}
else {
AL = 0x00;
}
}
<commit_msg>x86-64 emulation<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 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
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#define LOG_THIS BX_CPU_THIS_PTR
void
BX_CPU_C::SAHF(bxInstruction_c *i)
{
set_SF((AH & 0x80) >> 7);
set_ZF((AH & 0x40) >> 6);
set_AF((AH & 0x10) >> 4);
set_CF(AH & 0x01);
set_PF((AH & 0x04) >> 2);
}
void
BX_CPU_C::LAHF(bxInstruction_c *i)
{
AH = (get_SF() ? 0x80 : 0) |
(get_ZF() ? 0x40 : 0) |
(get_AF() ? 0x10 : 0) |
(get_PF() ? 0x04 : 0) |
(0x02) |
(get_CF() ? 0x01 : 0);
}
void
BX_CPU_C::CLC(bxInstruction_c *i)
{
set_CF(0);
}
void
BX_CPU_C::STC(bxInstruction_c *i)
{
set_CF(1);
}
void
BX_CPU_C::CLI(bxInstruction_c *i)
{
#if BX_CPU_LEVEL >= 2
if (protected_mode()) {
if (CPL > BX_CPU_THIS_PTR get_IOPL ()) {
//BX_INFO(("CLI: CPL > IOPL")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#if BX_CPU_LEVEL >= 3
else if (v8086_mode()) {
if (BX_CPU_THIS_PTR get_IOPL () != 3) {
//BX_INFO(("CLI: IOPL != 3")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#endif
#endif
BX_CPU_THIS_PTR clear_IF ();
}
void
BX_CPU_C::STI(bxInstruction_c *i)
{
#if BX_CPU_LEVEL >= 2
if (protected_mode()) {
if (CPL > BX_CPU_THIS_PTR get_IOPL ()) {
//BX_INFO(("STI: CPL > IOPL")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#if BX_CPU_LEVEL >= 3
else if (v8086_mode()) {
if (BX_CPU_THIS_PTR get_IOPL () != 3) {
//BX_INFO(("STI: IOPL != 3")); /* ??? */
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
}
#endif
#endif
if (!BX_CPU_THIS_PTR get_IF ()) {
BX_CPU_THIS_PTR assert_IF ();
BX_CPU_THIS_PTR inhibit_mask |= BX_INHIBIT_INTERRUPTS;
BX_CPU_THIS_PTR async_event = 1;
}
}
void
BX_CPU_C::CLD(bxInstruction_c *i)
{
BX_CPU_THIS_PTR clear_DF ();
}
void
BX_CPU_C::STD(bxInstruction_c *i)
{
BX_CPU_THIS_PTR assert_DF ();
}
void
BX_CPU_C::CMC(bxInstruction_c *i)
{
set_CF( !get_CF() );
}
void
BX_CPU_C::PUSHF_Fv(bxInstruction_c *i)
{
if (v8086_mode() && (BX_CPU_THIS_PTR get_IOPL ()<3)) {
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
#if BX_CPU_LEVEL >= 3
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64) {
if (i->os32L()) {
push_64(read_eflags() & 0x00fcffff);
}
else
{
Bit16u flags16;
flags16 = read_flags();
write_virtual_word(BX_SEG_REG_SS, RSP-2, &flags16);
RSP -= 2;
}
}
else
#endif
if (i->os32L()) {
push_32(read_eflags() & 0x00fcffff);
}
else
#endif
{
push_16(read_flags());
}
}
void
BX_CPU_C::POPF_Fv(bxInstruction_c *i)
{
Bit32u changeMask = 0x004dd5;
Bit32u flags32;
#if BX_CPU_LEVEL >= 3
if (protected_mode()) {
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64) {
Bit64u flags64;
if (i->os32L()) {
pop_64(&flags64);
flags32 = flags64;
changeMask |= 0x240000; // ID,AC
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
else
{
Bit16u flags16;
read_virtual_word(BX_SEG_REG_SS, RSP, &flags16);
RSP += 2;
flags32 = flags16;
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
}
else
#endif // #if BX_SUPPORT_X86_64
if (i->os32L()) {
pop_32(&flags32);
changeMask |= 0x240000; // ID,AC
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
else
#endif // BX_CPU_LEVEL >= 3
{
Bit16u flags16;
pop_16(&flags16);
flags32 = flags16;
if (CPL==0)
changeMask |= (3<<12); // IOPL
if (CPL <= BX_CPU_THIS_PTR get_IOPL())
changeMask |= (1<<9); // IF
}
// Protected-mode: VIP/VIF cleared, VM unaffected.
// Does this happen for 16 bit case? fixme!
flags32 &= ~( (1<<20) | (1<<19) ); // Clear VIP/VIF
}
else if (v8086_mode()) {
if (BX_CPU_THIS_PTR get_IOPL() < 3) {
exception(BX_GP_EXCEPTION, 0, 0);
return;
}
if (i->os32L()) {
pop_32(&flags32);
changeMask |= 0x240000; // ID,AC
}
else {
Bit16u flags16;
pop_16(&flags16);
flags32 = flags16;
}
// v8086-mode: VM,RF,IOPL,VIP,VIF are unaffected.
changeMask |= (1<<9); // IF
}
else { // Real-mode
if (i->os32L()) {
pop_32(&flags32);
changeMask |= 0x243200; // ID,AC,IOPL,IF
}
else { /* 16 bit opsize */
Bit16u flags16;
pop_16(&flags16);
flags32 = flags16;
changeMask |= 0x3200; // IOPL,IF
}
// Real-mode: VIP/VIF cleared, VM unaffected.
flags32 &= ~( (1<<20) | (1<<19) ); // Clear VIP/VIF
}
writeEFlags(flags32, changeMask);
}
void
BX_CPU_C::SALC(bxInstruction_c *i)
{
if ( get_CF() ) {
AL = 0xff;
}
else {
AL = 0x00;
}
}
<|endoftext|>
|
<commit_before>#include "highlighters.hh"
#include "assert.hh"
#include "window.hh"
#include "color_registry.hh"
#include "highlighter_group.hh"
#include "register_manager.hh"
#include "context.hh"
#include "string.hh"
#include "utf8.hh"
#include "utf8_iterator.hh"
#include <sstream>
#include <locale>
namespace Kakoune
{
using namespace std::placeholders;
typedef boost::regex_iterator<BufferIterator> RegexIterator;
template<typename T>
void highlight_range(DisplayBuffer& display_buffer,
BufferIterator begin, BufferIterator end,
bool skip_replaced, T func)
{
if (begin == end or end <= display_buffer.range().first
or begin >= display_buffer.range().second)
return;
for (auto& line : display_buffer.lines())
{
if (line.buffer_line() < begin.line() or end.line() < line.buffer_line())
continue;
for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it)
{
bool is_replaced = atom_it->content.type() == AtomContent::ReplacedBufferRange;
if (not atom_it->content.has_buffer_range() or
(skip_replaced and is_replaced))
continue;
if (end <= atom_it->content.begin() or begin >= atom_it->content.end())
continue;
if (not is_replaced and begin > atom_it->content.begin())
atom_it = ++line.split(atom_it, begin);
if (not is_replaced and end < atom_it->content.end())
{
atom_it = line.split(atom_it, end);
func(*atom_it);
++atom_it;
}
else
func(*atom_it);
}
}
}
typedef std::unordered_map<size_t, const ColorPair*> ColorSpec;
class RegexColorizer
{
public:
RegexColorizer(Regex regex, ColorSpec colors)
: m_regex(std::move(regex)), m_colors(std::move(colors)),
m_cache_timestamp(0)
{
}
void operator()(DisplayBuffer& display_buffer)
{
update_cache_ifn(display_buffer.range());
for (auto& match : m_cache_matches)
{
for (size_t n = 0; n < match.size(); ++n)
{
auto col_it = m_colors.find(n);
if (col_it == m_colors.end())
continue;
highlight_range(display_buffer, match[n].first, match[n].second, true,
[&](DisplayAtom& atom) {
atom.fg_color = col_it->second->first;
atom.bg_color = col_it->second->second;
});
}
}
}
private:
BufferRange m_cache_range;
size_t m_cache_timestamp;
std::vector<boost::match_results<BufferIterator>> m_cache_matches;
Regex m_regex;
ColorSpec m_colors;
void update_cache_ifn(const BufferRange& range)
{
const Buffer& buf = range.first.buffer();
if (m_cache_range.first.is_valid() and
&m_cache_range.first.buffer() == &buf and
buf.timestamp() == m_cache_timestamp and
range.first >= m_cache_range.first and
range.second <= m_cache_range.second)
return;
m_cache_matches.clear();
m_cache_range.first = buf.iterator_at_line_begin(range.first.line() - 10);
m_cache_range.second = buf.iterator_at_line_end(range.second.line() + 10);
m_cache_timestamp = buf.timestamp();
RegexIterator re_it(m_cache_range.first, m_cache_range.second, m_regex);
RegexIterator re_end;
for (; re_it != re_end; ++re_it)
m_cache_matches.push_back(*re_it);
}
};
HighlighterAndId colorize_regex_factory(Window& window,
const HighlighterParameters params)
{
if (params.size() < 2)
throw runtime_error("wrong parameter count");
try
{
static Regex color_spec_ex(R"((\d+):(\w+(,\w+)?))");
ColorSpec colors;
for (auto it = params.begin() + 1; it != params.end(); ++it)
{
boost::match_results<String::iterator> res;
if (not boost::regex_match(it->begin(), it->end(), res, color_spec_ex))
throw runtime_error("wrong colorspec: '" + *it +
"' expected <capture>:<fgcolor>[,<bgcolor>]");
int capture = str_to_int(String(res[1].first, res[1].second));
const ColorPair*& color = colors[capture];
color = &ColorRegistry::instance()[String(res[2].first, res[2].second)];
}
String id = "colre'" + params[0] + "'";
Regex ex(params[0].begin(), params[0].end(),
boost::regex::perl | boost::regex::optimize);
return HighlighterAndId(id, RegexColorizer(std::move(ex),
std::move(colors)));
}
catch (boost::regex_error& err)
{
throw runtime_error(String("regex error: ") + err.what());
}
}
class SearchHighlighter
{
public:
SearchHighlighter(const ColorSpec& colors)
: m_colors(colors), m_colorizer(Regex(), m_colors) {}
void operator()(DisplayBuffer& display_buffer)
{
memoryview<String> searches = RegisterManager::instance()['/'].values(Context{});
if (searches.empty())
return;
const String& search = searches[0];
if (search != m_last_search)
{
m_last_search = search;
if (not m_last_search.empty())
m_colorizer = RegexColorizer{Regex{m_last_search.begin(), m_last_search.end()}, m_colors};
}
if (not m_last_search.empty())
m_colorizer(display_buffer);
}
private:
String m_last_search;
ColorSpec m_colors;
RegexColorizer m_colorizer;
};
HighlighterAndId highlight_search_factory(Window& window,
const HighlighterParameters params)
{
if (params.size() != 1)
throw runtime_error("wrong parameter count");
try
{
ColorSpec colors;
colors[0] = &ColorRegistry::instance()[params[0]];
return {"hlsearch", SearchHighlighter{colors}};
}
catch (boost::regex_error& err)
{
throw runtime_error(String("regex error: ") + err.what());
}
};
void expand_tabulations(Window& window, DisplayBuffer& display_buffer)
{
const int tabstop = window.options()["tabstop"].as_int();
for (auto& line : display_buffer.lines())
{
for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it)
{
if (atom_it->content.type() != AtomContent::BufferRange)
continue;
auto begin = atom_it->content.begin();
auto end = atom_it->content.end();
for (BufferIterator it = begin; it != end; ++it)
{
if (*it == '\t')
{
if (it != begin)
atom_it = ++line.split(atom_it, it);
if (it+1 != end)
atom_it = line.split(atom_it, it+1);
int column = 0;
for (auto line_it = it.buffer().iterator_at_line_begin(it);
line_it != it; ++line_it)
{
assert(*line_it != '\n');
if (*line_it == '\t')
column += tabstop - (column % tabstop);
else
++column;
}
int count = tabstop - (column % tabstop);
String padding;
for (int i = 0; i < count; ++i)
padding += ' ';
atom_it->content.replace(padding);
break;
}
}
}
}
}
void show_line_numbers(Window& window, DisplayBuffer& display_buffer)
{
LineCount last_line = window.buffer().line_count();
int digit_count = 0;
for (LineCount c = last_line; c > 0; c /= 10)
++digit_count;
char format[] = "%?d ";
format[1] = '0' + digit_count;
for (auto& line : display_buffer.lines())
{
char buffer[10];
snprintf(buffer, 10, format, (int)line.buffer_line() + 1);
DisplayAtom atom = DisplayAtom(AtomContent(buffer));
atom.fg_color = Color::Black;
atom.bg_color = Color::White;
line.insert(line.begin(), std::move(atom));
}
}
void highlight_selections(Window& window, DisplayBuffer& display_buffer)
{
for (auto& sel : window.selections())
{
highlight_range(display_buffer, sel.begin(), sel.end(), false,
[](DisplayAtom& atom) { atom.attribute |= Attributes::Underline; });
const BufferIterator& last = sel.last();
highlight_range(display_buffer, last, utf8::next(last), false,
[](DisplayAtom& atom) { atom.attribute |= Attributes::Reverse;
atom.attribute &= ~Attributes::Underline; });
}
const Selection& back = window.selections().back();
highlight_range(display_buffer, back.begin(), back.end(), false,
[](DisplayAtom& atom) { atom.attribute |= Attributes::Bold; });
}
void expand_unprintable(DisplayBuffer& display_buffer)
{
for (auto& line : display_buffer.lines())
{
for (auto& atom : line)
{
if (atom.content.type() == AtomContent::BufferRange)
{
using Utf8It = utf8::utf8_iterator<BufferIterator>;
for (Utf8It it = atom.content.begin(), end = atom.content.end(); it != end; ++it)
{
Codepoint cp = *it;
if (cp != '\n' and not std::isprint((wchar_t)cp, std::locale()))
{
std::ostringstream oss;
oss << "U+" << std::hex << cp;
String str = oss.str();
highlight_range(display_buffer,
it.underlying_iterator(), (it+1).underlying_iterator(),
true, [&str](DisplayAtom& atom){ atom.content.replace(str);
atom.bg_color = Color::Red;
atom.fg_color = Color::Black; });
}
}
}
}
}
}
template<void (*highlighter_func)(DisplayBuffer&)>
class SimpleHighlighterFactory
{
public:
SimpleHighlighterFactory(const String& id) : m_id(id) {}
HighlighterAndId operator()(Window& window,
const HighlighterParameters& params) const
{
return HighlighterAndId(m_id, HighlighterFunc(highlighter_func));
}
private:
String m_id;
};
template<void (*highlighter_func)(Window&, DisplayBuffer&)>
class WindowHighlighterFactory
{
public:
WindowHighlighterFactory(const String& id) : m_id(id) {}
HighlighterAndId operator()(Window& window,
const HighlighterParameters& params) const
{
return HighlighterAndId(m_id, std::bind(highlighter_func, std::ref(window), _1));
}
private:
String m_id;
};
HighlighterAndId highlighter_group_factory(Window& window,
const HighlighterParameters& params)
{
if (params.size() != 1)
throw runtime_error("wrong parameter count");
return HighlighterAndId(params[0], HighlighterGroup());
}
void register_highlighters()
{
HighlighterRegistry& registry = HighlighterRegistry::instance();
registry.register_func("highlight_selections", WindowHighlighterFactory<highlight_selections>("highlight_selections"));
registry.register_func("expand_tabs", WindowHighlighterFactory<expand_tabulations>("expand_tabs"));
registry.register_func("expand_unprintable", SimpleHighlighterFactory<expand_unprintable>("expand_unprintable"));
registry.register_func("number_lines", WindowHighlighterFactory<show_line_numbers>("number_lines"));
registry.register_func("regex", colorize_regex_factory);
registry.register_func("search", highlight_search_factory);
registry.register_func("group", highlighter_group_factory);
}
}
<commit_msg>show_line_numbers does not need a window<commit_after>#include "highlighters.hh"
#include "assert.hh"
#include "window.hh"
#include "color_registry.hh"
#include "highlighter_group.hh"
#include "register_manager.hh"
#include "context.hh"
#include "string.hh"
#include "utf8.hh"
#include "utf8_iterator.hh"
#include <sstream>
#include <locale>
namespace Kakoune
{
using namespace std::placeholders;
typedef boost::regex_iterator<BufferIterator> RegexIterator;
template<typename T>
void highlight_range(DisplayBuffer& display_buffer,
BufferIterator begin, BufferIterator end,
bool skip_replaced, T func)
{
if (begin == end or end <= display_buffer.range().first
or begin >= display_buffer.range().second)
return;
for (auto& line : display_buffer.lines())
{
if (line.buffer_line() < begin.line() or end.line() < line.buffer_line())
continue;
for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it)
{
bool is_replaced = atom_it->content.type() == AtomContent::ReplacedBufferRange;
if (not atom_it->content.has_buffer_range() or
(skip_replaced and is_replaced))
continue;
if (end <= atom_it->content.begin() or begin >= atom_it->content.end())
continue;
if (not is_replaced and begin > atom_it->content.begin())
atom_it = ++line.split(atom_it, begin);
if (not is_replaced and end < atom_it->content.end())
{
atom_it = line.split(atom_it, end);
func(*atom_it);
++atom_it;
}
else
func(*atom_it);
}
}
}
typedef std::unordered_map<size_t, const ColorPair*> ColorSpec;
class RegexColorizer
{
public:
RegexColorizer(Regex regex, ColorSpec colors)
: m_regex(std::move(regex)), m_colors(std::move(colors)),
m_cache_timestamp(0)
{
}
void operator()(DisplayBuffer& display_buffer)
{
update_cache_ifn(display_buffer.range());
for (auto& match : m_cache_matches)
{
for (size_t n = 0; n < match.size(); ++n)
{
auto col_it = m_colors.find(n);
if (col_it == m_colors.end())
continue;
highlight_range(display_buffer, match[n].first, match[n].second, true,
[&](DisplayAtom& atom) {
atom.fg_color = col_it->second->first;
atom.bg_color = col_it->second->second;
});
}
}
}
private:
BufferRange m_cache_range;
size_t m_cache_timestamp;
std::vector<boost::match_results<BufferIterator>> m_cache_matches;
Regex m_regex;
ColorSpec m_colors;
void update_cache_ifn(const BufferRange& range)
{
const Buffer& buf = range.first.buffer();
if (m_cache_range.first.is_valid() and
&m_cache_range.first.buffer() == &buf and
buf.timestamp() == m_cache_timestamp and
range.first >= m_cache_range.first and
range.second <= m_cache_range.second)
return;
m_cache_matches.clear();
m_cache_range.first = buf.iterator_at_line_begin(range.first.line() - 10);
m_cache_range.second = buf.iterator_at_line_end(range.second.line() + 10);
m_cache_timestamp = buf.timestamp();
RegexIterator re_it(m_cache_range.first, m_cache_range.second, m_regex);
RegexIterator re_end;
for (; re_it != re_end; ++re_it)
m_cache_matches.push_back(*re_it);
}
};
HighlighterAndId colorize_regex_factory(Window& window,
const HighlighterParameters params)
{
if (params.size() < 2)
throw runtime_error("wrong parameter count");
try
{
static Regex color_spec_ex(R"((\d+):(\w+(,\w+)?))");
ColorSpec colors;
for (auto it = params.begin() + 1; it != params.end(); ++it)
{
boost::match_results<String::iterator> res;
if (not boost::regex_match(it->begin(), it->end(), res, color_spec_ex))
throw runtime_error("wrong colorspec: '" + *it +
"' expected <capture>:<fgcolor>[,<bgcolor>]");
int capture = str_to_int(String(res[1].first, res[1].second));
const ColorPair*& color = colors[capture];
color = &ColorRegistry::instance()[String(res[2].first, res[2].second)];
}
String id = "colre'" + params[0] + "'";
Regex ex(params[0].begin(), params[0].end(),
boost::regex::perl | boost::regex::optimize);
return HighlighterAndId(id, RegexColorizer(std::move(ex),
std::move(colors)));
}
catch (boost::regex_error& err)
{
throw runtime_error(String("regex error: ") + err.what());
}
}
class SearchHighlighter
{
public:
SearchHighlighter(const ColorSpec& colors)
: m_colors(colors), m_colorizer(Regex(), m_colors) {}
void operator()(DisplayBuffer& display_buffer)
{
memoryview<String> searches = RegisterManager::instance()['/'].values(Context{});
if (searches.empty())
return;
const String& search = searches[0];
if (search != m_last_search)
{
m_last_search = search;
if (not m_last_search.empty())
m_colorizer = RegexColorizer{Regex{m_last_search.begin(), m_last_search.end()}, m_colors};
}
if (not m_last_search.empty())
m_colorizer(display_buffer);
}
private:
String m_last_search;
ColorSpec m_colors;
RegexColorizer m_colorizer;
};
HighlighterAndId highlight_search_factory(Window& window,
const HighlighterParameters params)
{
if (params.size() != 1)
throw runtime_error("wrong parameter count");
try
{
ColorSpec colors;
colors[0] = &ColorRegistry::instance()[params[0]];
return {"hlsearch", SearchHighlighter{colors}};
}
catch (boost::regex_error& err)
{
throw runtime_error(String("regex error: ") + err.what());
}
};
void expand_tabulations(Window& window, DisplayBuffer& display_buffer)
{
const int tabstop = window.options()["tabstop"].as_int();
for (auto& line : display_buffer.lines())
{
for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it)
{
if (atom_it->content.type() != AtomContent::BufferRange)
continue;
auto begin = atom_it->content.begin();
auto end = atom_it->content.end();
for (BufferIterator it = begin; it != end; ++it)
{
if (*it == '\t')
{
if (it != begin)
atom_it = ++line.split(atom_it, it);
if (it+1 != end)
atom_it = line.split(atom_it, it+1);
int column = 0;
for (auto line_it = it.buffer().iterator_at_line_begin(it);
line_it != it; ++line_it)
{
assert(*line_it != '\n');
if (*line_it == '\t')
column += tabstop - (column % tabstop);
else
++column;
}
int count = tabstop - (column % tabstop);
String padding;
for (int i = 0; i < count; ++i)
padding += ' ';
atom_it->content.replace(padding);
break;
}
}
}
}
}
void show_line_numbers(DisplayBuffer& display_buffer)
{
LineCount last_line = display_buffer.range().first.buffer().line_count();
int digit_count = 0;
for (LineCount c = last_line; c > 0; c /= 10)
++digit_count;
char format[] = "%?d ";
format[1] = '0' + digit_count;
for (auto& line : display_buffer.lines())
{
char buffer[10];
snprintf(buffer, 10, format, (int)line.buffer_line() + 1);
DisplayAtom atom = DisplayAtom(AtomContent(buffer));
atom.fg_color = Color::Black;
atom.bg_color = Color::White;
line.insert(line.begin(), std::move(atom));
}
}
void highlight_selections(Window& window, DisplayBuffer& display_buffer)
{
for (auto& sel : window.selections())
{
highlight_range(display_buffer, sel.begin(), sel.end(), false,
[](DisplayAtom& atom) { atom.attribute |= Attributes::Underline; });
const BufferIterator& last = sel.last();
highlight_range(display_buffer, last, utf8::next(last), false,
[](DisplayAtom& atom) { atom.attribute |= Attributes::Reverse;
atom.attribute &= ~Attributes::Underline; });
}
const Selection& back = window.selections().back();
highlight_range(display_buffer, back.begin(), back.end(), false,
[](DisplayAtom& atom) { atom.attribute |= Attributes::Bold; });
}
void expand_unprintable(DisplayBuffer& display_buffer)
{
for (auto& line : display_buffer.lines())
{
for (auto& atom : line)
{
if (atom.content.type() == AtomContent::BufferRange)
{
using Utf8It = utf8::utf8_iterator<BufferIterator>;
for (Utf8It it = atom.content.begin(), end = atom.content.end(); it != end; ++it)
{
Codepoint cp = *it;
if (cp != '\n' and not std::isprint((wchar_t)cp, std::locale()))
{
std::ostringstream oss;
oss << "U+" << std::hex << cp;
String str = oss.str();
highlight_range(display_buffer,
it.underlying_iterator(), (it+1).underlying_iterator(),
true, [&str](DisplayAtom& atom){ atom.content.replace(str);
atom.bg_color = Color::Red;
atom.fg_color = Color::Black; });
}
}
}
}
}
}
template<void (*highlighter_func)(DisplayBuffer&)>
class SimpleHighlighterFactory
{
public:
SimpleHighlighterFactory(const String& id) : m_id(id) {}
HighlighterAndId operator()(Window& window,
const HighlighterParameters& params) const
{
return HighlighterAndId(m_id, HighlighterFunc(highlighter_func));
}
private:
String m_id;
};
template<void (*highlighter_func)(Window&, DisplayBuffer&)>
class WindowHighlighterFactory
{
public:
WindowHighlighterFactory(const String& id) : m_id(id) {}
HighlighterAndId operator()(Window& window,
const HighlighterParameters& params) const
{
return HighlighterAndId(m_id, std::bind(highlighter_func, std::ref(window), _1));
}
private:
String m_id;
};
HighlighterAndId highlighter_group_factory(Window& window,
const HighlighterParameters& params)
{
if (params.size() != 1)
throw runtime_error("wrong parameter count");
return HighlighterAndId(params[0], HighlighterGroup());
}
void register_highlighters()
{
HighlighterRegistry& registry = HighlighterRegistry::instance();
registry.register_func("highlight_selections", WindowHighlighterFactory<highlight_selections>("highlight_selections"));
registry.register_func("expand_tabs", WindowHighlighterFactory<expand_tabulations>("expand_tabs"));
registry.register_func("expand_unprintable", SimpleHighlighterFactory<expand_unprintable>("expand_unprintable"));
registry.register_func("number_lines", SimpleHighlighterFactory<show_line_numbers>("number_lines"));
registry.register_func("regex", colorize_regex_factory);
registry.register_func("search", highlight_search_factory);
registry.register_func("group", highlighter_group_factory);
}
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <sstream>
#include "cwmp-1-2.hxx"
class Cwmp_1_2_Test : public ::testing::Test {
public:
Cwmp_1_2_Test() {}
virtual ~Cwmp_1_2_Test() {}
};
TEST_F(Cwmp_1_2_Test, GenerateInform) {
const cwmp::cwmp_1_2::Manufacturer manufacturer("manufacturer_string");
const cwmp::cwmp_1_2::OUI oui("oui_string");
const cwmp::cwmp_1_2::ProductClass product_class("product_class_string");
const cwmp::cwmp_1_2::SerialNumber serial_number("serial_number_string");
const cwmp::cwmp_1_2::DeviceIdStruct device_id(
manufacturer, oui, product_class, serial_number);
const cwmp::cwmp_1_2::EventList event_list;
const xml_schema::unsigned_int envelopes = 200;
// 12:30:01.02 on June 4, 1970.
const cwmp::cwmp_1_2::Inform::CurrentTime_type date_time(
1970, 6, 4, 12, 30, 1.02);
const xml_schema::unsigned_int retry_count = 201;
const cwmp::cwmp_1_2::Inform::ParameterList_type parameter_list;
cwmp::cwmp_1_2::Inform inform(device_id, event_list, envelopes, date_time,
retry_count, parameter_list);
std::stringstream sstream;
cwmp::cwmp_1_2::Inform_(sstream, inform);
const std::string expected_xml(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n"
"<p1:Inform xmlns:p1=\"urn:dslforum-org:cwmp-1-2\">\n"
"\n"
" <DeviceId>\n"
" <Manufacturer>manufacturer_string</Manufacturer>\n"
" <OUI>oui_string</OUI>\n"
" <ProductClass>product_class_string</ProductClass>\n"
" <SerialNumber>serial_number_string</SerialNumber>\n"
" </DeviceId>\n"
"\n"
" <Event/>\n"
"\n"
" <MaxEnvelopes>200</MaxEnvelopes>\n"
"\n"
" <CurrentTime>1970-06-04T12:30:01.02</CurrentTime>\n"
"\n"
" <RetryCount>201</RetryCount>\n"
"\n"
" <ParameterList/>\n"
"\n"
"</p1:Inform>\n");
EXPECT_EQ(sstream.str(), expected_xml);
}
<commit_msg>Remove the XML declaration.<commit_after>#include <gtest/gtest.h>
#include <sstream>
#include "cwmp-1-2.hxx"
class Cwmp_1_2_Test : public ::testing::Test {
public:
Cwmp_1_2_Test() {}
virtual ~Cwmp_1_2_Test() {}
};
TEST_F(Cwmp_1_2_Test, GenerateInform) {
const cwmp::cwmp_1_2::Manufacturer manufacturer("manufacturer_string");
const cwmp::cwmp_1_2::OUI oui("oui_string");
const cwmp::cwmp_1_2::ProductClass product_class("product_class_string");
const cwmp::cwmp_1_2::SerialNumber serial_number("serial_number_string");
const cwmp::cwmp_1_2::DeviceIdStruct device_id(
manufacturer, oui, product_class, serial_number);
const cwmp::cwmp_1_2::EventList event_list;
const xml_schema::unsigned_int envelopes = 200;
// 12:30:01.02 on June 4, 1970.
const cwmp::cwmp_1_2::Inform::CurrentTime_type date_time(
1970, 6, 4, 12, 30, 1.02);
const xml_schema::unsigned_int retry_count = 201;
const cwmp::cwmp_1_2::Inform::ParameterList_type parameter_list;
cwmp::cwmp_1_2::Inform inform(device_id, event_list, envelopes, date_time,
retry_count, parameter_list);
std::stringstream sstream;
::xml_schema::namespace_infomap m;
cwmp::cwmp_1_2::Inform_(sstream, inform, m, "UTF-8",
xml_schema::flags::no_xml_declaration);
const std::string expected_xml(
"\n" // http://www.codesynthesis.com/pipermail/xsd-users/2009-December/002625.html
"<p1:Inform xmlns:p1=\"urn:dslforum-org:cwmp-1-2\">\n"
"\n"
" <DeviceId>\n"
" <Manufacturer>manufacturer_string</Manufacturer>\n"
" <OUI>oui_string</OUI>\n"
" <ProductClass>product_class_string</ProductClass>\n"
" <SerialNumber>serial_number_string</SerialNumber>\n"
" </DeviceId>\n"
"\n"
" <Event/>\n"
"\n"
" <MaxEnvelopes>200</MaxEnvelopes>\n"
"\n"
" <CurrentTime>1970-06-04T12:30:01.02</CurrentTime>\n"
"\n"
" <RetryCount>201</RetryCount>\n"
"\n"
" <ParameterList/>\n"
"\n"
"</p1:Inform>\n");
EXPECT_EQ(sstream.str(), expected_xml);
}
<|endoftext|>
|
<commit_before>
/*
Copyright 1995 The University of Rhode Island and The Massachusetts
Institute of Technology
Portions of this software were developed by the Graduate School of
Oceanography (GSO) at the University of Rhode Island (URI) in collaboration
with The Massachusetts Institute of Technology (MIT).
Access and use of this software shall impose the following obligations and
understandings on the user. The user is granted the right, without any fee
or cost, to use, copy, modify, alter, enhance and distribute this software,
and any derivative works thereof, and its supporting documentation for any
purpose whatsoever, provided that this entire notice appears in all copies
of the software, derivative works and supporting documentation. Further,
the user agrees to credit URI/MIT in any publications that result from the
use of this software or in any product that includes this software. The
names URI, MIT and/or GSO, however, may not be used in any advertising or
publicity to endorse or promote any products or commercial entity unless
specific written permission is obtained from URI/MIT. The user also
understands that URI/MIT is not obligated to provide the user with any
support, consulting, training or assistance of any kind with regard to the
use, operation and performance of this software nor to provide the user
with any updates, revisions, new versions or "bug fixes".
THIS SOFTWARE IS PROVIDED BY URI/MIT "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 URI/MIT BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE
OF THIS SOFTWARE.
*/
// Implementation for BaseType.
//
// jhrg 9/6/94
// $Log: BaseType.cc,v $
// Revision 1.18 1995/10/23 23:20:47 jimg
// Added _send_p and _read_p fields (and their accessors) along with the
// virtual mfuncs set_send_p() and set_read_p().
//
// Revision 1.17 1995/08/26 00:31:24 jimg
// Removed code enclosed in #ifdef NEVER #endif.
//
// Revision 1.16 1995/08/23 00:04:45 jimg
// Switched from String representation of data type to Type enum.
// Added type_name() member function so that it is simple to get the string
// representation of a variable's type.
// Changed the name of read_val/store_val to buf2val/val2buf.
//
// Revision 1.15 1995/07/09 21:28:52 jimg
// Added copyright notice.
//
// Revision 1.14 1995/05/10 15:33:54 jimg
// Failed to change `config.h' to `config_dap.h' in these files.
//
// Revision 1.13 1995/05/10 13:45:06 jimg
// Changed the name of the configuration header file from `config.h' to
// `config_dap.h' so that other libraries could have header files which were
// installed in the DODS include directory without overwriting this one. Each
// config header should follow the convention config_<name>.h.
//
// Revision 1.12 1995/03/16 17:26:36 jimg
// Moved include of config_dap.h to top of includes.
// Added TRACE_NEW switched dbnew debugging includes.
//
// Revision 1.11 1995/02/16 22:46:00 jimg
// Added _in private member. It is used to keep a copy of the input FILE *
// so that when the next chunk of data is read in the previous one can be
// closed. Since the netio library unlinks the tmp file before returning
// the FILE *, closing it effectively deletes the tmp file.
//
// Revision 1.10 1995/02/10 02:41:56 jimg
// Added new mfuncs to access _name and _type.
// Made private and protected filed's names start with `_'.
// Added store_val() as a abstract virtual mfunc.
//
// Revision 1.9 1995/01/18 18:33:25 dan
// Added external declarations for utility functions, new_xdrstdio and
// delete_xdrstdio.
//
// Revision 1.8 1995/01/11 16:06:47 jimg
// Added static XDR pointers to BaseType class and removed the XDR pointers
// that were class members - now there is only one xdrin and one xdrout
// for all children of BaseType.
// Added friend functions to help in setting the FILE * associated with
// the XDR *s.
// Removed FILE *in member (but FILE *out was kept as FILE * _out, mfunc
// expunge()).
// Changed ctor so that it no longer takes FILE * params.
//
// Revision 1.7 1994/12/16 22:01:42 jimg
// Added mfuncs var() and add_var() to BaseType. These print an error
// message when called with a simple BaseType (Int32, ...). Classes like
// Array use them and provide their own definitions.
//
// Revision 1.6 1994/11/29 19:59:01 jimg
// Added FILE * input and output buffers. All data set and all data received
// passes through these buffers. This simplifies testing and makes using
// the toolkit with files a little easier.
// Added xdrin and xdrout members (both are XDR *). These are the source and
// sink for xdr data.
// Modified ctor and duplicate() to correctly handle xdrin/out.
// Added expunge() which flushes the output buffer.
//
// Revision 1.5 1994/11/22 14:05:26 jimg
// Added code for data transmission to parts of the type hierarchy. Not
// complete yet.
// Fixed erros in type hierarchy headers (typos, incorrect comments, ...).
//
// Revision 1.4 1994/10/17 23:30:46 jimg
// Added ptr_duplicate virtual mfunc. Child classes can also define this
// to copy parts that BaseType does not have (and allocate correctly sized
// pointers.
// Removed protected mfunc error() -- use errmsg library instead.
// Added formatted printing of types (works with DDS::print()).
//
// Revision 1.3 1994/09/23 14:34:42 jimg
// Added mfunc check_semantics().
// Moved definition of dtor to BaseType.cc.
//
// Revision 1.2 1994/09/15 21:08:36 jimg
// Added many classes to the BaseType hierarchy - the complete set of types
// described in the DODS API design documet is now represented.
// The parser can parse DDS files.
// Fixed many small problems with BaseType.
// Added CtorType.
//
// Revision 1.1 1994/09/09 15:28:41 jimg
// Class for base type variables. Int32, ... inherit from this class.
#ifdef __GNUG__
#pragma implementation
#endif
#include "config_dap.h"
#include <stdio.h> // for stdin and stdout
#include "BaseType.h"
#include "util.h"
// Initial definition of the protected static members _xdrin and
// _xdrout. By default they use the stdin and stdout streams (resp).
XDR * BaseType::_xdrin = new_xdrstdio(stdin, XDR_DECODE);
XDR * BaseType::_xdrout = new_xdrstdio(stdout, XDR_ENCODE);
FILE * BaseType::_out = stdout;
FILE * BaseType::_in = stdin;
// Private copy mfunc
void
BaseType::_duplicate(const BaseType &bt)
{
_name = bt._name;
_type = bt._type;
_xdr_coder = bt._xdr_coder; // just copy this function pointer
}
// friend functions
// Delete the current XDR * assigned to _xdrin, free the storage, create a
// new XDR * and assign it to _xdrin.
void
set_xdrin(FILE *in)
{
delete_xdrstdio(BaseType::_xdrin);
if (BaseType::_in != stdin)
fclose(BaseType::_in);
BaseType::_xdrin = new_xdrstdio(in, XDR_DECODE);
BaseType::_in = in;
}
// Same as above except do it for _xdrout instead of _xdrin and store the
// OUT in private member _out. _out is used by mfunc expunge().
void
set_xdrout(FILE *out)
{
delete_xdrstdio(BaseType::_xdrout);
BaseType::_xdrout = new_xdrstdio(out, XDR_ENCODE);
BaseType::_out = out;
}
// Public mfuncs
// Note that the ctor (as well as the copy ctor via duplicate)
// open/initialize the (XDRS *)s XDRIN and XDROUT to reference sdtin and
// stdout. This means that writing to std{in,out} must work correctly, and
// probably means that is must be OK to mix calls to cout/cin with calls that
// write to std{out,in} (it is for g++ with libg++ at version 2.6 or
// greater).
BaseType::BaseType(const String &n, const Type &t, xdrproc_t xdr)
: _name(n), _type(t), _xdr_coder(xdr), _read_p(false), _send_p(false)
{
}
BaseType::BaseType(const BaseType ©_from)
{
_duplicate(copy_from);
}
BaseType::~BaseType()
{
}
BaseType &
BaseType::operator=(const BaseType &rhs)
{
if (this == &rhs)
return *this;
_duplicate(rhs);
return *this;
}
String
BaseType::name() const
{
return _name;
}
void
BaseType::set_name(const String &n)
{
_name = n;
}
Type
BaseType::type() const
{
return _type;
}
void
BaseType::set_type(const Type &t)
{
_type = t;
}
String
BaseType::type_name() const
{
switch(_type) {
case null_t:
return String("Null");
case byte_t:
return String("Byte");
case int32_t:
return String("Int32");
case float64_t:
return String("Float64");
case str_t:
return String("String");
case url_t:
return String("Url");
case array_t:
return String("Array");
case list_t:
return String("List");
case structure_t:
return String("Structure");
case sequence_t:
return String("Sequence");
case function_t:
return String("Function");
case grid_t:
return String("Grid");
default:
cerr << "BaseType::type_name: Undefined type" << endl;
return String("");
}
}
// Return the state of _read_p (true if the value of the variable has been
// read (and is in memory) false otherwise).
bool
BaseType::read_p()
{
return _read_p;
}
void
BaseType::set_read_p(bool state)
{
_read_p = state;
}
// Return the state of _send_p (true if the variable should be sent, false
// otherwise).
bool
BaseType::send_p()
{
return _send_p;
}
void
BaseType::set_send_p(bool state)
{
_send_p = state;
}
// Return a pointer to the contained variable in a ctor class. For BaseType
// this always prints an error message. It is defined here so that the ctor
// descendents of BaseType can access it when they are stored in a BaseType
// pointer.
BaseType *
BaseType::var(const String &name)
{
cerr << "var() should only be called for contructor types" << endl;
}
// See comment for var().
void
BaseType::add_var(BaseType *v, Part p)
{
cerr << "add_var() should only be called for constructor types" << endl;
}
// Using this mfunc, objects that contain a (BaseType *) can get the xdr
// function used to serialize the object.
xdrproc_t
BaseType::xdr_coder()
{
return _xdr_coder;
}
// Use these mfuncs to access the xdrin/out pointers.
XDR *
BaseType::xdrin() const
{
return _xdrin;
}
XDR *
BaseType::xdrout() const
{
return _xdrout;
}
// send a printed representation of the variable's declaration to cout. If
// print_semi is true, append a semicolon and newline.
void
BaseType::print_decl(ostream &os, String space, bool print_semi,
bool constraint_info)
{
os << space << type_name() << " " << _name;
if (constraint_info) {
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
os << ";" << endl;
}
// Compares the object's current state with the semantics of a particular
// type. This will typically be defined in ctor classes (which have
// complicated semantics). For BaseType, an object is semantically correct if
// it has both a non-null name and type.
//
// NB: This is not the same as an invariant -- during the parse objects exist
// but have no name. Also, the bool ALL defaults to false for BaseType. It is
// used by children of CtorType.
//
// Returns: true if the object is semantically correct, false otherwise.
bool
BaseType::check_semantics(bool all)
{
bool sem = (_type != null_t && (const char *)_name);
if (!sem)
cerr << "Every variable must have both a name and a type" << endl;
return sem;
}
// Flush the output buffer.
// Returns: false if an error was detected by fflush(), true otherwise.
bool
BaseType::expunge()
{
return fflush(_out) == 0;
}
<commit_msg>var(): now returns null for anything that does not define its own version. print_decl(): uses `constrained' flag.<commit_after>
/*
Copyright 1995 The University of Rhode Island and The Massachusetts
Institute of Technology
Portions of this software were developed by the Graduate School of
Oceanography (GSO) at the University of Rhode Island (URI) in collaboration
with The Massachusetts Institute of Technology (MIT).
Access and use of this software shall impose the following obligations and
understandings on the user. The user is granted the right, without any fee
or cost, to use, copy, modify, alter, enhance and distribute this software,
and any derivative works thereof, and its supporting documentation for any
purpose whatsoever, provided that this entire notice appears in all copies
of the software, derivative works and supporting documentation. Further,
the user agrees to credit URI/MIT in any publications that result from the
use of this software or in any product that includes this software. The
names URI, MIT and/or GSO, however, may not be used in any advertising or
publicity to endorse or promote any products or commercial entity unless
specific written permission is obtained from URI/MIT. The user also
understands that URI/MIT is not obligated to provide the user with any
support, consulting, training or assistance of any kind with regard to the
use, operation and performance of this software nor to provide the user
with any updates, revisions, new versions or "bug fixes".
THIS SOFTWARE IS PROVIDED BY URI/MIT "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 URI/MIT BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE
OF THIS SOFTWARE.
*/
// Implementation for BaseType.
//
// jhrg 9/6/94
// $Log: BaseType.cc,v $
// Revision 1.19 1995/12/06 21:49:53 jimg
// var(): now returns null for anything that does not define its own version.
// print_decl(): uses `constrained' flag.
//
// Revision 1.18 1995/10/23 23:20:47 jimg
// Added _send_p and _read_p fields (and their accessors) along with the
// virtual mfuncs set_send_p() and set_read_p().
//
// Revision 1.17 1995/08/26 00:31:24 jimg
// Removed code enclosed in #ifdef NEVER #endif.
//
// Revision 1.16 1995/08/23 00:04:45 jimg
// Switched from String representation of data type to Type enum.
// Added type_name() member function so that it is simple to get the string
// representation of a variable's type.
// Changed the name of read_val/store_val to buf2val/val2buf.
//
// Revision 1.15 1995/07/09 21:28:52 jimg
// Added copyright notice.
//
// Revision 1.14 1995/05/10 15:33:54 jimg
// Failed to change `config.h' to `config_dap.h' in these files.
//
// Revision 1.13 1995/05/10 13:45:06 jimg
// Changed the name of the configuration header file from `config.h' to
// `config_dap.h' so that other libraries could have header files which were
// installed in the DODS include directory without overwriting this one. Each
// config header should follow the convention config_<name>.h.
//
// Revision 1.12 1995/03/16 17:26:36 jimg
// Moved include of config_dap.h to top of includes.
// Added TRACE_NEW switched dbnew debugging includes.
//
// Revision 1.11 1995/02/16 22:46:00 jimg
// Added _in private member. It is used to keep a copy of the input FILE *
// so that when the next chunk of data is read in the previous one can be
// closed. Since the netio library unlinks the tmp file before returning
// the FILE *, closing it effectively deletes the tmp file.
//
// Revision 1.10 1995/02/10 02:41:56 jimg
// Added new mfuncs to access _name and _type.
// Made private and protected filed's names start with `_'.
// Added store_val() as a abstract virtual mfunc.
//
// Revision 1.9 1995/01/18 18:33:25 dan
// Added external declarations for utility functions, new_xdrstdio and
// delete_xdrstdio.
//
// Revision 1.8 1995/01/11 16:06:47 jimg
// Added static XDR pointers to BaseType class and removed the XDR pointers
// that were class members - now there is only one xdrin and one xdrout
// for all children of BaseType.
// Added friend functions to help in setting the FILE * associated with
// the XDR *s.
// Removed FILE *in member (but FILE *out was kept as FILE * _out, mfunc
// expunge()).
// Changed ctor so that it no longer takes FILE * params.
//
// Revision 1.7 1994/12/16 22:01:42 jimg
// Added mfuncs var() and add_var() to BaseType. These print an error
// message when called with a simple BaseType (Int32, ...). Classes like
// Array use them and provide their own definitions.
//
// Revision 1.6 1994/11/29 19:59:01 jimg
// Added FILE * input and output buffers. All data set and all data received
// passes through these buffers. This simplifies testing and makes using
// the toolkit with files a little easier.
// Added xdrin and xdrout members (both are XDR *). These are the source and
// sink for xdr data.
// Modified ctor and duplicate() to correctly handle xdrin/out.
// Added expunge() which flushes the output buffer.
//
// Revision 1.5 1994/11/22 14:05:26 jimg
// Added code for data transmission to parts of the type hierarchy. Not
// complete yet.
// Fixed erros in type hierarchy headers (typos, incorrect comments, ...).
//
// Revision 1.4 1994/10/17 23:30:46 jimg
// Added ptr_duplicate virtual mfunc. Child classes can also define this
// to copy parts that BaseType does not have (and allocate correctly sized
// pointers.
// Removed protected mfunc error() -- use errmsg library instead.
// Added formatted printing of types (works with DDS::print()).
//
// Revision 1.3 1994/09/23 14:34:42 jimg
// Added mfunc check_semantics().
// Moved definition of dtor to BaseType.cc.
//
// Revision 1.2 1994/09/15 21:08:36 jimg
// Added many classes to the BaseType hierarchy - the complete set of types
// described in the DODS API design documet is now represented.
// The parser can parse DDS files.
// Fixed many small problems with BaseType.
// Added CtorType.
//
// Revision 1.1 1994/09/09 15:28:41 jimg
// Class for base type variables. Int32, ... inherit from this class.
#ifdef __GNUG__
#pragma implementation
#endif
#include "config_dap.h"
#include <stdio.h> // for stdin and stdout
#include "BaseType.h"
#include "util.h"
// Initial definition of the protected static members _xdrin and
// _xdrout. By default they use the stdin and stdout streams (resp).
XDR * BaseType::_xdrin = new_xdrstdio(stdin, XDR_DECODE);
XDR * BaseType::_xdrout = new_xdrstdio(stdout, XDR_ENCODE);
FILE * BaseType::_out = stdout;
FILE * BaseType::_in = stdin;
// Private copy mfunc
void
BaseType::_duplicate(const BaseType &bt)
{
_name = bt._name;
_type = bt._type;
_xdr_coder = bt._xdr_coder; // just copy this function pointer
}
// friend functions
// Delete the current XDR * assigned to _xdrin, free the storage, create a
// new XDR * and assign it to _xdrin.
void
set_xdrin(FILE *in)
{
delete_xdrstdio(BaseType::_xdrin);
if (BaseType::_in != stdin)
fclose(BaseType::_in);
BaseType::_xdrin = new_xdrstdio(in, XDR_DECODE);
BaseType::_in = in;
}
// Same as above except do it for _xdrout instead of _xdrin and store the
// OUT in private member _out. _out is used by mfunc expunge().
void
set_xdrout(FILE *out)
{
delete_xdrstdio(BaseType::_xdrout);
BaseType::_xdrout = new_xdrstdio(out, XDR_ENCODE);
BaseType::_out = out;
}
// Public mfuncs
// Note that the ctor (as well as the copy ctor via duplicate)
// open/initialize the (XDRS *)s XDRIN and XDROUT to reference sdtin and
// stdout. This means that writing to std{in,out} must work correctly, and
// probably means that is must be OK to mix calls to cout/cin with calls that
// write to std{out,in} (it is for g++ with libg++ at version 2.6 or
// greater).
BaseType::BaseType(const String &n, const Type &t, xdrproc_t xdr)
: _name(n), _type(t), _xdr_coder(xdr), _read_p(false), _send_p(false)
{
}
BaseType::BaseType(const BaseType ©_from)
{
_duplicate(copy_from);
}
BaseType::~BaseType()
{
}
BaseType &
BaseType::operator=(const BaseType &rhs)
{
if (this == &rhs)
return *this;
_duplicate(rhs);
return *this;
}
String
BaseType::name() const
{
return _name;
}
void
BaseType::set_name(const String &n)
{
_name = n;
}
Type
BaseType::type() const
{
return _type;
}
void
BaseType::set_type(const Type &t)
{
_type = t;
}
String
BaseType::type_name() const
{
switch(_type) {
case null_t:
return String("Null");
case byte_t:
return String("Byte");
case int32_t:
return String("Int32");
case float64_t:
return String("Float64");
case str_t:
return String("String");
case url_t:
return String("Url");
case array_t:
return String("Array");
case list_t:
return String("List");
case structure_t:
return String("Structure");
case sequence_t:
return String("Sequence");
case function_t:
return String("Function");
case grid_t:
return String("Grid");
default:
cerr << "BaseType::type_name: Undefined type" << endl;
return String("");
}
}
// Return the state of _read_p (true if the value of the variable has been
// read (and is in memory) false otherwise).
bool
BaseType::read_p()
{
return _read_p;
}
void
BaseType::set_read_p(bool state)
{
_read_p = state;
}
// Return the state of _send_p (true if the variable should be sent, false
// otherwise).
bool
BaseType::send_p()
{
return _send_p;
}
void
BaseType::set_send_p(bool state)
{
_send_p = state;
}
// Defined by constructor types (Array, ...)
//
// Return a pointer to the contained variable in a ctor class.
BaseType *
BaseType::var(const String &name)
{
return (BaseType *)0;
}
// Defined by constructor types (Array, ...)
void
BaseType::add_var(BaseType *v, Part p)
{
}
// Using this mfunc, objects that contain a (BaseType *) can get the xdr
// function used to serialize the object.
xdrproc_t
BaseType::xdr_coder()
{
return _xdr_coder;
}
// Use these mfuncs to access the xdrin/out pointers.
XDR *
BaseType::xdrin() const
{
return _xdrin;
}
XDR *
BaseType::xdrout() const
{
return _xdrout;
}
// send a printed representation of the variable's declaration to cout. If
// print_semi is true, append a semicolon and newline.
void
BaseType::print_decl(ostream &os, String space, bool print_semi,
bool constraint_info, bool constrained)
{
// if printing the constrained declaration, exit if this variable was not
// selected.
if (constrained && !send_p())
return;
os << space << type_name() << " " << _name;
if (constraint_info) {
if (send_p())
cout << ": Send True";
else
cout << ": Send False";
}
if (print_semi)
os << ";" << endl;
}
// Compares the object's current state with the semantics of a particular
// type. This will typically be defined in ctor classes (which have
// complicated semantics). For BaseType, an object is semantically correct if
// it has both a non-null name and type.
//
// NB: This is not the same as an invariant -- during the parse objects exist
// but have no name. Also, the bool ALL defaults to false for BaseType. It is
// used by children of CtorType.
//
// Returns: true if the object is semantically correct, false otherwise.
bool
BaseType::check_semantics(bool all)
{
bool sem = (_type != null_t && (const char *)_name);
if (!sem)
cerr << "Every variable must have both a name and a type" << endl;
return sem;
}
// Flush the output buffer.
// Returns: false if an error was detected by fflush(), true otherwise.
bool
BaseType::expunge()
{
return fflush(_out) == 0;
}
<|endoftext|>
|
<commit_before>/********************************************************************************
** Form generated from reading UI file 'settings.ui'
**
** Created by: Qt User Interface Compiler version 5.3.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_SETTINGS_H
#define UI_SETTINGS_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QCheckBox>
#include <QtGui/QCommandLinkButton>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Settings
{
public:
QLabel *label;
QLabel *label_2;
QPushButton *pushButton;
QCheckBox *save_check_box;
QPushButton *pushButton_2;
QLabel *label_3;
QLineEdit *user_seq_len;
QLineEdit *min_seqs;
QLabel *label_4;
QCommandLinkButton *choose_directory;
void setupUi(QWidget *Settings)
{
if (Settings->objectName().isEmpty())
Settings->setObjectName(QString::fromUtf8("Settings"));
Settings->resize(485, 340);
label = new QLabel(Settings);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(10, 100, 351, 18));
label_2 = new QLabel(Settings);
label_2->setObjectName(QString::fromUtf8("label_2"));
label_2->setGeometry(QRect(10, 40, 231, 18));
pushButton = new QPushButton(Settings);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setGeometry(QRect(320, 280, 102, 28));
save_check_box = new QCheckBox(Settings);
save_check_box->setObjectName(QString::fromUtf8("save_check_box"));
save_check_box->setGeometry(QRect(230, 240, 131, 23));
pushButton_2 = new QPushButton(Settings);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setGeometry(QRect(60, 280, 102, 28));
label_3 = new QLabel(Settings);
label_3->setObjectName(QString::fromUtf8("label_3"));
label_3->setGeometry(QRect(340, 40, 151, 18));
user_seq_len = new QLineEdit(Settings);
user_seq_len->setObjectName(QString::fromUtf8("user_seq_len"));
user_seq_len->setGeometry(QRect(340, 90, 101, 41));
min_seqs = new QLineEdit(Settings);
min_seqs->setObjectName(QString::fromUtf8("min_seqs"));
min_seqs->setGeometry(QRect(240, 30, 91, 41));
label_4 = new QLabel(Settings);
label_4->setObjectName(QString::fromUtf8("label_4"));
label_4->setGeometry(QRect(10, 160, 341, 18));
choose_directory = new QCommandLinkButton(Settings);
choose_directory->setObjectName(QString::fromUtf8("choose_directory"));
choose_directory->setGeometry(QRect(270, 180, 195, 41));
retranslateUi(Settings);
QMetaObject::connectSlotsByName(Settings);
} // setupUi
void retranslateUi(QWidget *Settings)
{
Settings->setWindowTitle(QApplication::translate("Settings", "Form", 0));
label->setText(QApplication::translate("Settings", "Change the phrase length (the default is 6): ", 0));
label_2->setText(QApplication::translate("Settings", "Only show files with more than ", 0));
pushButton->setText(QApplication::translate("Settings", "Apply", 0));
save_check_box->setText(QApplication::translate("Settings", "Save changes", 0));
pushButton_2->setText(QApplication::translate("Settings", "Cancel", 0));
label_3->setText(QApplication::translate("Settings", "plagiarized phrases", 0));
label_4->setText(QApplication::translate("Settings", "Where do you want to save the results file to?", 0));
choose_directory->setText(QApplication::translate("Settings", "Choose directory...", 0));
} // retranslateUi
};
namespace Ui {
class Settings: public Ui_Settings {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_SETTINGS_H
<commit_msg>Delete ui_settings.hpp<commit_after><|endoftext|>
|
<commit_before>#include <Bitmask.hpp>
#include <NdbOut.hpp>
static
void print(const Uint32 src[], Uint32 len, Uint32 pos = 0)
{
printf("b'");
for(int i = 0; i<len; i++)
{
if(BitmaskImpl::get((pos + len + 31) >> 5, src, i+pos))
printf("1");
else
printf("0");
if((i & 7) == 7)
printf(" ");
}
}
#ifndef __TEST_BITMASK__
void
BitmaskImpl::getFieldImpl(const Uint32 src[],
unsigned shift, unsigned len, Uint32 dst[])
{
assert(shift < 32);
if(len <= (32 - shift))
{
* dst++ |= ((* src) & ((1 << len) - 1)) << shift;
}
else
{
abort();
while(len > 32)
{
* dst++ |= (* src) << shift;
* dst = (* src++) >> (32 - shift);
len -= 32;
}
}
}
void
BitmaskImpl::setFieldImpl(Uint32 dst[],
unsigned shift, unsigned len, const Uint32 src[])
{
assert(shift < 32);
Uint32 mask;
if(len < (32 - shift))
{
mask = (1 << len) - 1;
* dst = (* dst & ~mask) | (((* src++) >> shift) & mask);
}
else
{
abort();
}
}
#else
#define DEBUG 0
#include <Vector.hpp>
static void do_test(int bitmask_size);
int
main(int argc, char** argv)
{
int loops = argc > 1 ? atoi(argv[1]) : 1000;
int max_size = argc > 2 ? atoi(argv[2]) : 1000;
for(int i = 0; i<loops; i++)
do_test(1 + (rand() % max_size));
}
struct Alloc
{
Uint32 pos;
Uint32 size;
Vector<Uint32> data;
};
static void require(bool b)
{
if(!b) abort();
}
static int val_pos = 0;
static int val[] = { 384, 241, 32,
1,1,1,1, 0,0,0,0, 1,1,1,1, 0,0,0,0,
241 };
static int lrand()
{
#if 0
return val[val_pos++];
#else
return rand();
#endif
}
static
void rand(Uint32 dst[], Uint32 len)
{
for(int i = 0; i<len; i++)
BitmaskImpl::set((len + 31) >> 5, dst, i, (lrand() % 1000) > 500);
}
static
void simple(int pos, int size)
{
ndbout_c("simple pos: %d size: %d", pos, size);
Vector<Uint32> _mask;
Vector<Uint32> _src;
Vector<Uint32> _dst;
Uint32 sz32 = (size + pos + 32) >> 5;
const Uint32 sz = 4 * sz32;
Uint32 zero = 0;
_mask.fill(sz32, zero);
_src.fill(sz32, zero);
_dst.fill(sz32, zero);
Uint32 * src = _src.getBase();
Uint32 * dst = _dst.getBase();
Uint32 * mask = _mask.getBase();
memset(src, 0x0, sz);
memset(dst, 0x0, sz);
memset(mask, 0x0, sz);
rand(src, size);
BitmaskImpl::setField(sz32, mask, pos, size, src);
BitmaskImpl::getField(sz32, mask, pos, size, dst);
printf("src: "); print(src, size); printf("\n");
printf("msk: "); print(mask, size, pos); printf("\n");
printf("dst: "); print(dst, size); printf("\n");
require(memcmp(src, dst, sz) == 0);
};
static void
do_test(int bitmask_size)
{
#if 0
simple(rand() % 33, (rand() % 31)+1);
#else
Vector<Alloc> alloc_list;
bitmask_size = (bitmask_size + 31) & ~31;
Uint32 sz32 = (bitmask_size >> 5);
Vector<Uint32> alloc_mask;
Vector<Uint32> test_mask;
ndbout_c("Testing bitmask of size %d", bitmask_size);
Uint32 zero = 0;
alloc_mask.fill(sz32, zero);
test_mask.fill(sz32, zero);
for(int i = 0; i<5000; i++)
{
Vector<Uint32> tmp;
tmp.fill(sz32, zero);
int pos = lrand() % (bitmask_size - 1);
int free = 0;
if(BitmaskImpl::get(sz32, alloc_mask.getBase(), pos))
{
// Bit was allocated
// 1) Look up allocation
// 2) Check data
// 3) free it
size_t j;
int min, max;
for(j = 0; j<alloc_list.size(); j++)
{
min = alloc_list[j].pos;
max = min + alloc_list[j].size;
if(pos >= min && pos < max)
{
break;
}
}
require(pos >= min && pos < max);
BitmaskImpl::getField(sz32, test_mask.getBase(), min, max-min,
tmp.getBase());
if(DEBUG)
{
printf("freeing [ %d %d ]", min, max);
printf("- mask: ");
for(size_t k = 0; k<(((max - min)+31)>>5); k++)
printf("%.8x ", tmp.getBase()[k]);
printf("save: ");
size_t k;
Alloc& a = alloc_list[j];
for(k = 0; k<a.data.size(); k++)
printf("%.8x ", a.data[k]);
printf("\n");
}
int bytes = (max - min + 7) >> 3;
if(memcmp(tmp.getBase(), alloc_list[j].data.getBase(), bytes) != 0)
{
abort();
}
while(min < max)
BitmaskImpl::clear(sz32, alloc_mask.getBase(), min++);
alloc_list.erase(j);
}
else
{
Vector<Uint32> tmp;
tmp.fill(sz32, zero);
// Bit was free
// 1) Check how much space is avaiable
// 2) Create new allocation of lrandom size
// 3) Fill data with lrandom data
// 4) Update alloc mask
while(pos+free < bitmask_size &&
!BitmaskImpl::get(sz32, alloc_mask.getBase(), pos+free))
free++;
Uint32 sz = (lrand() % free);
sz = sz ? sz : 1;
sz = (sz > 31) ? 31 : sz;
Alloc a;
a.pos = pos;
a.size = sz;
a.data.fill(((sz+31)>> 5)-1, zero);
if(DEBUG)
printf("pos %d -> alloc [ %d %d ]", pos, pos, pos+sz);
for(size_t j = 0; j<sz; j++)
{
BitmaskImpl::set(sz32, alloc_mask.getBase(), pos+j);
if((lrand() % 1000) > 500)
BitmaskImpl::set((sz + 31) >> 5, a.data.getBase(), j);
}
if(DEBUG)
{
printf("- mask: ");
size_t k;
for(k = 0; k<a.data.size(); k++)
printf("%.8x ", a.data[k]);
printf("\n");
}
BitmaskImpl::setField(sz32, test_mask.getBase(), pos, sz,
a.data.getBase());
alloc_list.push_back(a);
}
}
#endif
}
template class Vector<Alloc>;
template class Vector<Uint32>;
#endif
<commit_msg>ndb - Fix arbitrary sized bitfields<commit_after>#include <Bitmask.hpp>
#include <NdbOut.hpp>
static
void print(const Uint32 src[], Uint32 len, Uint32 pos = 0)
{
printf("b'");
for(int i = 0; i<len; i++)
{
if(BitmaskImpl::get((pos + len + 31) >> 5, src, i+pos))
printf("1");
else
printf("0");
if((i & 31) == 31)
printf(" ");
}
}
#ifndef __TEST_BITMASK__
void
BitmaskImpl::getFieldImpl(const Uint32 src[],
unsigned shiftL, unsigned len, Uint32 dst[])
{
assert(shiftL < 32);
unsigned shiftR = 32 - shiftL;
while(len >= 32)
{
* dst++ |= (* src) << shiftL;
* dst = shiftL ? (* src) >> shiftR : 0;
src++;
len -= 32;
}
* dst++ |= (* src) << shiftL;
* dst = shiftL ? ((* src) >> shiftR) & ((1 << len) - 1) : 0;
}
void
BitmaskImpl::setFieldImpl(Uint32 dst[],
unsigned shiftL, unsigned len, const Uint32 src[])
{
/**
*
* abcd ef00
* 00ab cdef
*/
assert(shiftL < 32);
unsigned shiftR = 32 - shiftL;
while(len >= 32)
{
* dst = (* src++) >> shiftL;
* dst++ |= shiftL ? (* src) << shiftR : 0;
len -= 32;
}
Uint32 mask = ((1 << len) -1);
* dst = (* dst & ~mask);
* dst |= ((* src++) >> shiftL) & mask;
* dst |= shiftL ? ((* src) << shiftR) & mask : 0;
}
#else
#define DEBUG 0
#include <Vector.hpp>
static void do_test(int bitmask_size);
int
main(int argc, char** argv)
{
int loops = argc > 1 ? atoi(argv[1]) : 1000;
int max_size = argc > 2 ? atoi(argv[2]) : 1000;
for(int i = 0; i<loops; i++)
do_test(1 + (rand() % max_size));
}
struct Alloc
{
Uint32 pos;
Uint32 size;
Vector<Uint32> data;
};
static void require(bool b)
{
if(!b) abort();
}
static
bool cmp(const Uint32 b1[], const Uint32 b2[], Uint32 len)
{
Uint32 sz32 = (len + 31) >> 5;
for(int i = 0; i<len; i++)
{
if(BitmaskImpl::get(sz32, b1, i) ^ BitmaskImpl::get(sz32, b2, i))
return false;
}
return true;
}
static int val_pos = 0;
static int val[] = { 384, 241, 32,
1,1,1,1, 0,0,0,0, 1,1,1,1, 0,0,0,0,
241 };
static int lrand()
{
#if 0
return val[val_pos++];
#else
return rand();
#endif
}
static
void rand(Uint32 dst[], Uint32 len)
{
for(int i = 0; i<len; i++)
BitmaskImpl::set((len + 31) >> 5, dst, i, (lrand() % 1000) > 500);
}
static
void simple(int pos, int size)
{
ndbout_c("simple pos: %d size: %d", pos, size);
Vector<Uint32> _mask;
Vector<Uint32> _src;
Vector<Uint32> _dst;
Uint32 sz32 = (size + pos + 32) >> 5;
const Uint32 sz = 4 * sz32;
Uint32 zero = 0;
_mask.fill(sz32, zero);
_src.fill(sz32, zero);
_dst.fill(sz32, zero);
Uint32 * src = _src.getBase();
Uint32 * dst = _dst.getBase();
Uint32 * mask = _mask.getBase();
memset(src, 0x0, sz);
memset(dst, 0x0, sz);
memset(mask, 0xFF, sz);
rand(src, size);
BitmaskImpl::setField(sz32, mask, pos, size, src);
BitmaskImpl::getField(sz32, mask, pos, size, dst);
printf("src: "); print(src, size); printf("\n");
printf("msk: "); print(mask, sz32 << 5); printf("\n");
printf("dst: "); print(dst, size); printf("\n");
require(cmp(src, dst, size));
};
static void
do_test(int bitmask_size)
{
#if 0
simple(rand() % 33, (rand() % 63)+1);
#else
Vector<Alloc> alloc_list;
bitmask_size = (bitmask_size + 31) & ~31;
Uint32 sz32 = (bitmask_size >> 5);
Vector<Uint32> alloc_mask;
Vector<Uint32> test_mask;
ndbout_c("Testing bitmask of size %d", bitmask_size);
Uint32 zero = 0;
alloc_mask.fill(sz32, zero);
test_mask.fill(sz32, zero);
for(int i = 0; i<5000; i++)
{
Vector<Uint32> tmp;
tmp.fill(sz32, zero);
int pos = lrand() % (bitmask_size - 1);
int free = 0;
if(BitmaskImpl::get(sz32, alloc_mask.getBase(), pos))
{
// Bit was allocated
// 1) Look up allocation
// 2) Check data
// 3) free it
size_t j;
int min, max;
for(j = 0; j<alloc_list.size(); j++)
{
min = alloc_list[j].pos;
max = min + alloc_list[j].size;
if(pos >= min && pos < max)
{
break;
}
}
require(pos >= min && pos < max);
BitmaskImpl::getField(sz32, test_mask.getBase(), min, max-min,
tmp.getBase());
if(DEBUG)
{
printf("freeing [ %d %d ]", min, max);
printf("- mask: ");
print(tmp.getBase(), max - min);
printf(" save: ");
size_t k;
Alloc& a = alloc_list[j];
for(k = 0; k<a.data.size(); k++)
printf("%.8x ", a.data[k]);
printf("\n");
}
int bytes = (max - min + 7) >> 3;
if(!cmp(tmp.getBase(), alloc_list[j].data.getBase(), max - min))
{
abort();
}
while(min < max)
BitmaskImpl::clear(sz32, alloc_mask.getBase(), min++);
alloc_list.erase(j);
}
else
{
Vector<Uint32> tmp;
tmp.fill(sz32, zero);
// Bit was free
// 1) Check how much space is avaiable
// 2) Create new allocation of lrandom size
// 3) Fill data with lrandom data
// 4) Update alloc mask
while(pos+free < bitmask_size &&
!BitmaskImpl::get(sz32, alloc_mask.getBase(), pos+free))
free++;
Uint32 sz = (lrand() % free);
sz = sz ? sz : 1;
Alloc a;
a.pos = pos;
a.size = sz;
a.data.fill(((sz+31)>> 5)-1, zero);
if(DEBUG)
printf("pos %d -> alloc [ %d %d ]", pos, pos, pos+sz);
for(size_t j = 0; j<sz; j++)
{
BitmaskImpl::set(sz32, alloc_mask.getBase(), pos+j);
if((lrand() % 1000) > 500)
BitmaskImpl::set((sz + 31) >> 5, a.data.getBase(), j);
}
if(DEBUG)
{
printf("- mask: ");
print(a.data.getBase(), sz);
printf("\n");
}
BitmaskImpl::setField(sz32, test_mask.getBase(), pos, sz,
a.data.getBase());
alloc_list.push_back(a);
}
}
#endif
}
template class Vector<Alloc>;
template class Vector<Uint32>;
#endif
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2019 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. //
// ======================================================================== //
// ospray
#include "ISPCDevice.h"
#include "camera/Camera.h"
#include "common/Data.h"
#include "common/Group.h"
#include "common/Instance.h"
#include "common/Library.h"
#include "common/Material.h"
#include "common/Util.h"
#include "common/World.h"
#include "fb/ImageOp.h"
#include "fb/LocalFB.h"
#include "geometry/GeometricModel.h"
#include "lights/Light.h"
#include "render/LoadBalancer.h"
#include "render/RenderTask.h"
#include "render/Renderer.h"
#include "texture/Texture.h"
#include "texture/Texture2D.h"
#include "volume/VolumetricModel.h"
#include "volume/transferFunction/TransferFunction.h"
// stl
#include <algorithm>
#include <functional>
#include <map>
// openvkl
#include "openvkl/openvkl.h"
extern "C" RTCDevice ispc_embreeDevice()
{
return ospray::api::ISPCDevice::embreeDevice;
}
namespace ospray {
namespace api {
using SetParamFcn = void(OSPObject, const char *, const void *);
template <typename T>
static void setParamOnObject(OSPObject _obj, const char *p, const T &v)
{
auto *obj = (ManagedObject *)_obj;
obj->setParam(p, v);
}
#define declare_param_setter(TYPE) \
{ \
OSPTypeFor<TYPE>::value, [](OSPObject o, const char *p, const void *v) { \
setParamOnObject(o, p, *(TYPE *)v); \
} \
}
#define declare_param_setter_object(TYPE) \
{ \
OSPTypeFor<TYPE>::value, [](OSPObject o, const char *p, const void *v) { \
ManagedObject *obj = *(TYPE *)v; \
setParamOnObject(o, p, obj); \
} \
}
static std::map<OSPDataType, std::function<SetParamFcn>> setParamFcns = {
declare_param_setter(Device *),
declare_param_setter(void *),
declare_param_setter(bool),
declare_param_setter_object(ManagedObject *),
declare_param_setter_object(Camera *),
declare_param_setter_object(Data *),
declare_param_setter_object(FrameBuffer *),
declare_param_setter_object(Future *),
declare_param_setter_object(GeometricModel *),
declare_param_setter_object(Group *),
declare_param_setter_object(ImageOp *),
declare_param_setter_object(Instance *),
declare_param_setter_object(Light *),
declare_param_setter_object(Material *),
declare_param_setter_object(Renderer *),
declare_param_setter_object(Texture *),
declare_param_setter_object(TransferFunction *),
declare_param_setter_object(Volume *),
declare_param_setter_object(VolumetricModel *),
declare_param_setter_object(World *),
declare_param_setter(char *),
declare_param_setter(char),
declare_param_setter(unsigned char),
declare_param_setter(vec2uc),
declare_param_setter(vec3uc),
declare_param_setter(vec4uc),
declare_param_setter(short),
declare_param_setter(int),
declare_param_setter(vec2i),
declare_param_setter(vec3i),
declare_param_setter(vec4i),
declare_param_setter(unsigned int),
declare_param_setter(vec2ui),
declare_param_setter(vec3ui),
declare_param_setter(vec4ui),
declare_param_setter(long),
declare_param_setter(vec2l),
declare_param_setter(vec3l),
declare_param_setter(vec4l),
declare_param_setter(unsigned long),
declare_param_setter(vec2ul),
declare_param_setter(vec3ul),
declare_param_setter(vec4ul),
declare_param_setter(float),
declare_param_setter(vec2f),
declare_param_setter(vec3f),
declare_param_setter(vec4f),
declare_param_setter(double),
declare_param_setter(box1i),
declare_param_setter(box2i),
declare_param_setter(box3i),
declare_param_setter(box4i),
declare_param_setter(box1f),
declare_param_setter(box2f),
declare_param_setter(box3f),
declare_param_setter(box4f),
declare_param_setter(linear2f),
declare_param_setter(linear3f),
declare_param_setter(affine2f),
declare_param_setter(affine3f)};
#undef declare_param_setter
RTCDevice ISPCDevice::embreeDevice = nullptr;
ISPCDevice::~ISPCDevice()
{
try {
if (embreeDevice) {
rtcReleaseDevice(embreeDevice);
embreeDevice = nullptr;
}
} catch (...) {
// silently move on, sometimes a pthread mutex lock fails in Embree
}
}
static void embreeErrorFunc(void *, const RTCError code, const char *str)
{
postStatusMsg() << "#osp: embree internal error " << code << " : " << str;
throw std::runtime_error("embree internal error '" + std::string(str) +
"'");
}
///////////////////////////////////////////////////////////////////////////
// ManagedObject Implementation ///////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void ISPCDevice::commit()
{
Device::commit();
TiledLoadBalancer::instance = make_unique<LocalTiledLoadBalancer>();
if (!embreeDevice) {
// -------------------------------------------------------
// initialize embree. (we need to do this here rather than in
// ospray::init() because in mpi-mode the latter is also called
// in the host-stubs, where it shouldn't.
// -------------------------------------------------------
embreeDevice = rtcNewDevice(generateEmbreeDeviceCfg(*this).c_str());
rtcSetDeviceErrorFunction(embreeDevice, embreeErrorFunc, nullptr);
RTCError erc = rtcGetDeviceError(embreeDevice);
if (erc != RTC_ERROR_NONE) {
// why did the error function not get called !?
postStatusMsg() << "#osp:init: embree internal error number " << erc;
throw std::runtime_error("failed to initialize Embree");
}
}
vklLoadModule("ispc_driver");
VKLDriver driver = vklNewDriver("ispc_driver");
vklCommitDriver(driver);
vklSetCurrentDriver(driver);
}
///////////////////////////////////////////////////////////////////////////
// Device Implementation //////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
int ISPCDevice::loadModule(const char *name)
{
return loadLocalModule(name);
}
///////////////////////////////////////////////////////////////////////////
// OSPRay Data Arrays /////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPData ISPCDevice::newSharedData(const void *sharedData,
OSPDataType type,
const vec3i &numItems,
const vec3l &byteStride)
{
return (OSPData) new Data(sharedData, type, numItems, byteStride);
}
OSPData ISPCDevice::newData(OSPDataType type, const vec3i &numItems)
{
return (OSPData) new Data(type, numItems);
}
void ISPCDevice::copyData(const OSPData source,
OSPData destination,
const vec3i &destinationIndex)
{
Data *dst = (Data *)destination;
dst->copy(*(Data *)source, destinationIndex);
}
///////////////////////////////////////////////////////////////////////////
// Renderable Objects /////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPLight ISPCDevice::newLight(const char *type)
{
return (OSPLight)Light::createInstance(type);
}
OSPCamera ISPCDevice::newCamera(const char *type)
{
return (OSPCamera)Camera::createInstance(type);
}
OSPGeometry ISPCDevice::newGeometry(const char *type)
{
return (OSPGeometry)Geometry::createInstance(type);
}
OSPVolume ISPCDevice::newVolume(const char *type)
{
return (OSPVolume)Volume::createInstance(type);
}
OSPGeometricModel ISPCDevice::newGeometricModel(OSPGeometry _geom)
{
auto *geom = (Geometry *)_geom;
auto *model = new GeometricModel(geom);
return (OSPGeometricModel)model;
}
OSPVolumetricModel ISPCDevice::newVolumetricModel(OSPVolume _volume)
{
auto *volume = (Volume *)_volume;
auto *model = new VolumetricModel(volume);
return (OSPVolumetricModel)model;
}
///////////////////////////////////////////////////////////////////////////
// Model Meta-Data ////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPMaterial ISPCDevice::newMaterial(const char *renderer_type,
const char *material_type)
{
return (OSPMaterial)Material::createInstance(renderer_type,
material_type);
}
OSPTransferFunction ISPCDevice::newTransferFunction(const char *type)
{
return (OSPTransferFunction)TransferFunction::createInstance(type);
}
OSPTexture ISPCDevice::newTexture(const char *type)
{
return (OSPTexture)Texture::createInstance(type);
}
///////////////////////////////////////////////////////////////////////////
// Instancing /////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPGroup ISPCDevice::newGroup()
{
return (OSPGroup) new Group;
}
OSPInstance ISPCDevice::newInstance(OSPGroup _group)
{
auto *group = (Group *)_group;
auto *instance = new Instance(group);
return (OSPInstance)instance;
}
///////////////////////////////////////////////////////////////////////////
// Top-level Worlds ///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPWorld ISPCDevice::newWorld()
{
return (OSPWorld) new World;
}
box3f ISPCDevice::getBounds(OSPObject _obj)
{
auto *obj = (ManagedObject *)_obj;
return obj->getBounds();
}
///////////////////////////////////////////////////////////////////////////
// Object + Parameter Lifetime Management /////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void ISPCDevice::setObjectParam(OSPObject object,
const char *name,
OSPDataType type,
const void *mem)
{
if (type == OSP_UNKNOWN)
throw std::runtime_error("cannot set OSP_UNKNOWN parameter type");
if (type == OSP_BYTE || type == OSP_RAW) {
setParamOnObject(object, name, *(const byte_t *)mem);
return;
}
setParamFcns[type](object, name, mem);
}
void ISPCDevice::removeObjectParam(OSPObject _object, const char *name)
{
ManagedObject *object = (ManagedObject *)_object;
ManagedObject *existing =
object->getParam<ManagedObject *>(name, nullptr);
if (existing)
existing->refDec();
object->removeParam(name);
}
void ISPCDevice::commit(OSPObject _object)
{
ManagedObject *object = (ManagedObject *)_object;
object->commit();
object->checkUnused();
object->resetAllParamQueryStatus();
}
void ISPCDevice::release(OSPObject _obj)
{
ManagedObject *obj = (ManagedObject *)_obj;
obj->refDec();
}
void ISPCDevice::retain(OSPObject _obj)
{
ManagedObject *obj = (ManagedObject *)_obj;
obj->refInc();
}
///////////////////////////////////////////////////////////////////////////
// FrameBuffer Manipulation ///////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPFrameBuffer ISPCDevice::frameBufferCreate(
const vec2i &size,
const OSPFrameBufferFormat mode,
const uint32 channels)
{
FrameBuffer::ColorBufferFormat colorBufferFormat = mode;
FrameBuffer *fb = new LocalFrameBuffer(size, colorBufferFormat, channels);
return (OSPFrameBuffer)fb;
}
OSPImageOperation ISPCDevice::newImageOp(const char *type)
{
return (OSPImageOperation)ImageOp::createInstance(type);
}
const void *ISPCDevice::frameBufferMap(OSPFrameBuffer _fb,
OSPFrameBufferChannel channel)
{
LocalFrameBuffer *fb = (LocalFrameBuffer *)_fb;
return fb->mapBuffer(channel);
}
void ISPCDevice::frameBufferUnmap(const void *mapped, OSPFrameBuffer _fb)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
fb->unmap(mapped);
}
float ISPCDevice::getVariance(OSPFrameBuffer _fb)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
return fb->getVariance();
}
void ISPCDevice::resetAccumulation(OSPFrameBuffer _fb)
{
LocalFrameBuffer *fb = (LocalFrameBuffer *)_fb;
fb->clear();
}
///////////////////////////////////////////////////////////////////////////
// Frame Rendering ////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPRenderer ISPCDevice::newRenderer(const char *type)
{
return (OSPRenderer)Renderer::createInstance(type);
}
OSPFuture ISPCDevice::renderFrame(OSPFrameBuffer _fb,
OSPRenderer _renderer,
OSPCamera _camera,
OSPWorld _world)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
Renderer *renderer = (Renderer *)_renderer;
Camera *camera = (Camera *)_camera;
World *world = (World *)_world;
fb->setCompletedEvent(OSP_NONE_FINISHED);
fb->refInc();
renderer->refInc();
camera->refInc();
world->refInc();
auto *f = new RenderTask(fb, [=]() {
float result = renderer->renderFrame(fb, camera, world);
fb->refDec();
renderer->refDec();
camera->refDec();
world->refDec();
return result;
});
return (OSPFuture)f;
}
int ISPCDevice::isReady(OSPFuture _task, OSPSyncEvent event)
{
auto *task = (Future *)_task;
return task->isFinished(event);
}
void ISPCDevice::wait(OSPFuture _task, OSPSyncEvent event)
{
auto *task = (Future *)_task;
task->wait(event);
}
void ISPCDevice::cancel(OSPFuture _task)
{
auto *task = (Future *)_task;
return task->cancel();
}
float ISPCDevice::getProgress(OSPFuture _task)
{
auto *task = (Future *)_task;
return task->getProgress();
}
OSPPickResult ISPCDevice::pick(OSPFrameBuffer _fb,
OSPRenderer _renderer,
OSPCamera _camera,
OSPWorld _world,
const vec2f &screenPos)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
Renderer *renderer = (Renderer *)_renderer;
Camera *camera = (Camera *)_camera;
World *world = (World *)_world;
return renderer->pick(fb, camera, world, screenPos);
}
OSP_REGISTER_DEVICE(ISPCDevice, local_device);
OSP_REGISTER_DEVICE(ISPCDevice, local);
OSP_REGISTER_DEVICE(ISPCDevice, default_device);
OSP_REGISTER_DEVICE(ISPCDevice, default);
} // namespace api
} // namespace ospray
extern "C" OSPRAY_DLLEXPORT void ospray_init_module_ispc() {}
<commit_msg>use new name for OpenVKL ispc driver<commit_after>// ======================================================================== //
// Copyright 2009-2019 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. //
// ======================================================================== //
// ospray
#include "ISPCDevice.h"
#include "camera/Camera.h"
#include "common/Data.h"
#include "common/Group.h"
#include "common/Instance.h"
#include "common/Library.h"
#include "common/Material.h"
#include "common/Util.h"
#include "common/World.h"
#include "fb/ImageOp.h"
#include "fb/LocalFB.h"
#include "geometry/GeometricModel.h"
#include "lights/Light.h"
#include "render/LoadBalancer.h"
#include "render/RenderTask.h"
#include "render/Renderer.h"
#include "texture/Texture.h"
#include "texture/Texture2D.h"
#include "volume/VolumetricModel.h"
#include "volume/transferFunction/TransferFunction.h"
// stl
#include <algorithm>
#include <functional>
#include <map>
// openvkl
#include "openvkl/openvkl.h"
extern "C" RTCDevice ispc_embreeDevice()
{
return ospray::api::ISPCDevice::embreeDevice;
}
namespace ospray {
namespace api {
using SetParamFcn = void(OSPObject, const char *, const void *);
template <typename T>
static void setParamOnObject(OSPObject _obj, const char *p, const T &v)
{
auto *obj = (ManagedObject *)_obj;
obj->setParam(p, v);
}
#define declare_param_setter(TYPE) \
{ \
OSPTypeFor<TYPE>::value, [](OSPObject o, const char *p, const void *v) { \
setParamOnObject(o, p, *(TYPE *)v); \
} \
}
#define declare_param_setter_object(TYPE) \
{ \
OSPTypeFor<TYPE>::value, [](OSPObject o, const char *p, const void *v) { \
ManagedObject *obj = *(TYPE *)v; \
setParamOnObject(o, p, obj); \
} \
}
static std::map<OSPDataType, std::function<SetParamFcn>> setParamFcns = {
declare_param_setter(Device *),
declare_param_setter(void *),
declare_param_setter(bool),
declare_param_setter_object(ManagedObject *),
declare_param_setter_object(Camera *),
declare_param_setter_object(Data *),
declare_param_setter_object(FrameBuffer *),
declare_param_setter_object(Future *),
declare_param_setter_object(GeometricModel *),
declare_param_setter_object(Group *),
declare_param_setter_object(ImageOp *),
declare_param_setter_object(Instance *),
declare_param_setter_object(Light *),
declare_param_setter_object(Material *),
declare_param_setter_object(Renderer *),
declare_param_setter_object(Texture *),
declare_param_setter_object(TransferFunction *),
declare_param_setter_object(Volume *),
declare_param_setter_object(VolumetricModel *),
declare_param_setter_object(World *),
declare_param_setter(char *),
declare_param_setter(char),
declare_param_setter(unsigned char),
declare_param_setter(vec2uc),
declare_param_setter(vec3uc),
declare_param_setter(vec4uc),
declare_param_setter(short),
declare_param_setter(int),
declare_param_setter(vec2i),
declare_param_setter(vec3i),
declare_param_setter(vec4i),
declare_param_setter(unsigned int),
declare_param_setter(vec2ui),
declare_param_setter(vec3ui),
declare_param_setter(vec4ui),
declare_param_setter(long),
declare_param_setter(vec2l),
declare_param_setter(vec3l),
declare_param_setter(vec4l),
declare_param_setter(unsigned long),
declare_param_setter(vec2ul),
declare_param_setter(vec3ul),
declare_param_setter(vec4ul),
declare_param_setter(float),
declare_param_setter(vec2f),
declare_param_setter(vec3f),
declare_param_setter(vec4f),
declare_param_setter(double),
declare_param_setter(box1i),
declare_param_setter(box2i),
declare_param_setter(box3i),
declare_param_setter(box4i),
declare_param_setter(box1f),
declare_param_setter(box2f),
declare_param_setter(box3f),
declare_param_setter(box4f),
declare_param_setter(linear2f),
declare_param_setter(linear3f),
declare_param_setter(affine2f),
declare_param_setter(affine3f)};
#undef declare_param_setter
RTCDevice ISPCDevice::embreeDevice = nullptr;
ISPCDevice::~ISPCDevice()
{
try {
if (embreeDevice) {
rtcReleaseDevice(embreeDevice);
embreeDevice = nullptr;
}
} catch (...) {
// silently move on, sometimes a pthread mutex lock fails in Embree
}
}
static void embreeErrorFunc(void *, const RTCError code, const char *str)
{
postStatusMsg() << "#osp: embree internal error " << code << " : " << str;
throw std::runtime_error("embree internal error '" + std::string(str) +
"'");
}
///////////////////////////////////////////////////////////////////////////
// ManagedObject Implementation ///////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void ISPCDevice::commit()
{
Device::commit();
TiledLoadBalancer::instance = make_unique<LocalTiledLoadBalancer>();
if (!embreeDevice) {
// -------------------------------------------------------
// initialize embree. (we need to do this here rather than in
// ospray::init() because in mpi-mode the latter is also called
// in the host-stubs, where it shouldn't.
// -------------------------------------------------------
embreeDevice = rtcNewDevice(generateEmbreeDeviceCfg(*this).c_str());
rtcSetDeviceErrorFunction(embreeDevice, embreeErrorFunc, nullptr);
RTCError erc = rtcGetDeviceError(embreeDevice);
if (erc != RTC_ERROR_NONE) {
// why did the error function not get called !?
postStatusMsg() << "#osp:init: embree internal error number " << erc;
throw std::runtime_error("failed to initialize Embree");
}
}
vklLoadModule("ispc_driver");
VKLDriver driver = vklNewDriver("ispc");
vklCommitDriver(driver);
vklSetCurrentDriver(driver);
}
///////////////////////////////////////////////////////////////////////////
// Device Implementation //////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
int ISPCDevice::loadModule(const char *name)
{
return loadLocalModule(name);
}
///////////////////////////////////////////////////////////////////////////
// OSPRay Data Arrays /////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPData ISPCDevice::newSharedData(const void *sharedData,
OSPDataType type,
const vec3i &numItems,
const vec3l &byteStride)
{
return (OSPData) new Data(sharedData, type, numItems, byteStride);
}
OSPData ISPCDevice::newData(OSPDataType type, const vec3i &numItems)
{
return (OSPData) new Data(type, numItems);
}
void ISPCDevice::copyData(const OSPData source,
OSPData destination,
const vec3i &destinationIndex)
{
Data *dst = (Data *)destination;
dst->copy(*(Data *)source, destinationIndex);
}
///////////////////////////////////////////////////////////////////////////
// Renderable Objects /////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPLight ISPCDevice::newLight(const char *type)
{
return (OSPLight)Light::createInstance(type);
}
OSPCamera ISPCDevice::newCamera(const char *type)
{
return (OSPCamera)Camera::createInstance(type);
}
OSPGeometry ISPCDevice::newGeometry(const char *type)
{
return (OSPGeometry)Geometry::createInstance(type);
}
OSPVolume ISPCDevice::newVolume(const char *type)
{
return (OSPVolume)Volume::createInstance(type);
}
OSPGeometricModel ISPCDevice::newGeometricModel(OSPGeometry _geom)
{
auto *geom = (Geometry *)_geom;
auto *model = new GeometricModel(geom);
return (OSPGeometricModel)model;
}
OSPVolumetricModel ISPCDevice::newVolumetricModel(OSPVolume _volume)
{
auto *volume = (Volume *)_volume;
auto *model = new VolumetricModel(volume);
return (OSPVolumetricModel)model;
}
///////////////////////////////////////////////////////////////////////////
// Model Meta-Data ////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPMaterial ISPCDevice::newMaterial(const char *renderer_type,
const char *material_type)
{
return (OSPMaterial)Material::createInstance(renderer_type,
material_type);
}
OSPTransferFunction ISPCDevice::newTransferFunction(const char *type)
{
return (OSPTransferFunction)TransferFunction::createInstance(type);
}
OSPTexture ISPCDevice::newTexture(const char *type)
{
return (OSPTexture)Texture::createInstance(type);
}
///////////////////////////////////////////////////////////////////////////
// Instancing /////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPGroup ISPCDevice::newGroup()
{
return (OSPGroup) new Group;
}
OSPInstance ISPCDevice::newInstance(OSPGroup _group)
{
auto *group = (Group *)_group;
auto *instance = new Instance(group);
return (OSPInstance)instance;
}
///////////////////////////////////////////////////////////////////////////
// Top-level Worlds ///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPWorld ISPCDevice::newWorld()
{
return (OSPWorld) new World;
}
box3f ISPCDevice::getBounds(OSPObject _obj)
{
auto *obj = (ManagedObject *)_obj;
return obj->getBounds();
}
///////////////////////////////////////////////////////////////////////////
// Object + Parameter Lifetime Management /////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void ISPCDevice::setObjectParam(OSPObject object,
const char *name,
OSPDataType type,
const void *mem)
{
if (type == OSP_UNKNOWN)
throw std::runtime_error("cannot set OSP_UNKNOWN parameter type");
if (type == OSP_BYTE || type == OSP_RAW) {
setParamOnObject(object, name, *(const byte_t *)mem);
return;
}
setParamFcns[type](object, name, mem);
}
void ISPCDevice::removeObjectParam(OSPObject _object, const char *name)
{
ManagedObject *object = (ManagedObject *)_object;
ManagedObject *existing =
object->getParam<ManagedObject *>(name, nullptr);
if (existing)
existing->refDec();
object->removeParam(name);
}
void ISPCDevice::commit(OSPObject _object)
{
ManagedObject *object = (ManagedObject *)_object;
object->commit();
object->checkUnused();
object->resetAllParamQueryStatus();
}
void ISPCDevice::release(OSPObject _obj)
{
ManagedObject *obj = (ManagedObject *)_obj;
obj->refDec();
}
void ISPCDevice::retain(OSPObject _obj)
{
ManagedObject *obj = (ManagedObject *)_obj;
obj->refInc();
}
///////////////////////////////////////////////////////////////////////////
// FrameBuffer Manipulation ///////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPFrameBuffer ISPCDevice::frameBufferCreate(
const vec2i &size,
const OSPFrameBufferFormat mode,
const uint32 channels)
{
FrameBuffer::ColorBufferFormat colorBufferFormat = mode;
FrameBuffer *fb = new LocalFrameBuffer(size, colorBufferFormat, channels);
return (OSPFrameBuffer)fb;
}
OSPImageOperation ISPCDevice::newImageOp(const char *type)
{
return (OSPImageOperation)ImageOp::createInstance(type);
}
const void *ISPCDevice::frameBufferMap(OSPFrameBuffer _fb,
OSPFrameBufferChannel channel)
{
LocalFrameBuffer *fb = (LocalFrameBuffer *)_fb;
return fb->mapBuffer(channel);
}
void ISPCDevice::frameBufferUnmap(const void *mapped, OSPFrameBuffer _fb)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
fb->unmap(mapped);
}
float ISPCDevice::getVariance(OSPFrameBuffer _fb)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
return fb->getVariance();
}
void ISPCDevice::resetAccumulation(OSPFrameBuffer _fb)
{
LocalFrameBuffer *fb = (LocalFrameBuffer *)_fb;
fb->clear();
}
///////////////////////////////////////////////////////////////////////////
// Frame Rendering ////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
OSPRenderer ISPCDevice::newRenderer(const char *type)
{
return (OSPRenderer)Renderer::createInstance(type);
}
OSPFuture ISPCDevice::renderFrame(OSPFrameBuffer _fb,
OSPRenderer _renderer,
OSPCamera _camera,
OSPWorld _world)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
Renderer *renderer = (Renderer *)_renderer;
Camera *camera = (Camera *)_camera;
World *world = (World *)_world;
fb->setCompletedEvent(OSP_NONE_FINISHED);
fb->refInc();
renderer->refInc();
camera->refInc();
world->refInc();
auto *f = new RenderTask(fb, [=]() {
float result = renderer->renderFrame(fb, camera, world);
fb->refDec();
renderer->refDec();
camera->refDec();
world->refDec();
return result;
});
return (OSPFuture)f;
}
int ISPCDevice::isReady(OSPFuture _task, OSPSyncEvent event)
{
auto *task = (Future *)_task;
return task->isFinished(event);
}
void ISPCDevice::wait(OSPFuture _task, OSPSyncEvent event)
{
auto *task = (Future *)_task;
task->wait(event);
}
void ISPCDevice::cancel(OSPFuture _task)
{
auto *task = (Future *)_task;
return task->cancel();
}
float ISPCDevice::getProgress(OSPFuture _task)
{
auto *task = (Future *)_task;
return task->getProgress();
}
OSPPickResult ISPCDevice::pick(OSPFrameBuffer _fb,
OSPRenderer _renderer,
OSPCamera _camera,
OSPWorld _world,
const vec2f &screenPos)
{
FrameBuffer *fb = (FrameBuffer *)_fb;
Renderer *renderer = (Renderer *)_renderer;
Camera *camera = (Camera *)_camera;
World *world = (World *)_world;
return renderer->pick(fb, camera, world, screenPos);
}
OSP_REGISTER_DEVICE(ISPCDevice, local_device);
OSP_REGISTER_DEVICE(ISPCDevice, local);
OSP_REGISTER_DEVICE(ISPCDevice, default_device);
OSP_REGISTER_DEVICE(ISPCDevice, default);
} // namespace api
} // namespace ospray
extern "C" OSPRAY_DLLEXPORT void ospray_init_module_ispc() {}
<|endoftext|>
|
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_MATH_QUATERNION_HPP
#define OUZEL_MATH_QUATERNION_HPP
#include <cmath>
#include <cstddef>
#include <limits>
#include "math/Vector.hpp"
namespace ouzel
{
template <typename T> class Quaternion final
{
public:
T v[4]{0};
constexpr Quaternion() noexcept {}
constexpr Quaternion(const T x, const T y, const T z, const T w) noexcept:
v{x, y, z, w}
{
}
inline T& operator[](size_t index) noexcept { return v[index]; }
constexpr T operator[](size_t index) const noexcept { return v[index]; }
inline T& x() noexcept { return v[0]; }
constexpr T x() const noexcept { return v[0]; }
inline T& y() noexcept { return v[1]; }
constexpr T y() const noexcept { return v[1]; }
inline T& z() noexcept { return v[2]; }
constexpr T z() const noexcept { return v[2]; }
inline T& w() noexcept { return v[3]; }
constexpr T w() const noexcept { return v[3]; }
static constexpr Quaternion identity() noexcept
{
return Quaternion(0, 0, 0, 1);
}
constexpr const Quaternion operator*(const Quaternion& q) const noexcept
{
return Quaternion(v[0] * q.v[3] + v[1] * q.v[2] - v[2] * q.v[1] + v[3] * q.v[0],
-v[0] * q.v[2] + v[1] * q.v[3] + v[2] * q.v[0] + v[3] * q.v[1],
v[0] * q.v[1] - v[1] * q.v[0] + v[2] * q.v[3] + v[3] * q.v[2],
-v[0] * q.v[0] - v[1] * q.v[1] - v[2] * q.v[2] + v[3] * q.v[3]);
}
inline Quaternion& operator*=(const Quaternion& q) noexcept
{
constexpr T tempX = v[0] * q.v[3] + v[1] * q.v[2] - v[2] * q.v[1] + v[3] * q.v[0];
constexpr T tempY = -v[0] * q.v[2] + v[1] * q.v[3] + v[2] * q.v[0] + v[3] * q.v[1];
constexpr T tempZ = v[0] * q.v[1] - v[1] * q.v[0] + v[2] * q.v[3] + v[3] * q.v[2];
constexpr T tempW = -v[0] * q.v[0] - v[1] * q.v[1] - v[2] * q.v[2] + v[3] * q.v[3];
v[0] = tempX;
v[1] = tempY;
v[2] = tempZ;
v[3] = tempW;
return *this;
}
constexpr const Quaternion operator*(const T scalar) const noexcept
{
return Quaternion(v[0] * scalar,
v[1] * scalar,
v[2] * scalar,
v[3] * scalar);
}
inline Quaternion& operator*=(const T scalar) noexcept
{
v[0] *= scalar;
v[1] *= scalar;
v[2] *= scalar;
v[3] *= scalar;
return *this;
}
constexpr const Quaternion operator/(const T scalar) const noexcept
{
return Quaternion(v[0] / scalar,
v[1] / scalar,
v[2] / scalar,
v[3] / scalar);
}
inline Quaternion& operator/=(const T scalar) noexcept
{
v[0] /= scalar;
v[1] /= scalar;
v[2] /= scalar;
v[3] /= scalar;
return *this;
}
constexpr const Quaternion operator-() const noexcept
{
return Quaternion(-v[0], -v[1], -v[2], -v[3]);
}
constexpr const Quaternion operator+(const Quaternion& q) const noexcept
{
return Quaternion(v[0] + q.v[0],
v[1] + q.v[1],
v[2] + q.v[2],
v[3] + q.v[3]);
}
inline Quaternion& operator+=(const Quaternion& q) noexcept
{
v[0] += q.v[0];
v[1] += q.v[1];
v[2] += q.v[2];
v[3] += q.v[3];
return *this;
}
constexpr const Quaternion operator-(const Quaternion& q) const noexcept
{
return Quaternion(v[0] - q.v[0],
v[1] - q.v[1],
v[2] - q.v[2],
v[3] - q.v[3]);
}
inline Quaternion& operator-=(const Quaternion& q) noexcept
{
v[0] -= q.v[0];
v[1] -= q.v[1];
v[2] -= q.v[2];
v[3] -= q.v[3];
return *this;
}
constexpr bool operator==(const Quaternion& q) const noexcept
{
return v[0] == q.v[0] && v[1] == q.v[1] && v[2] == q.v[2] && v[3] == q.v[3];
}
constexpr bool operator!=(const Quaternion& q) const noexcept
{
return v[0] != q.v[0] || v[1] != q.v[1] || v[2] != q.v[2] || v[3] != q.v[3];
}
inline void negate() noexcept
{
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
v[3] = -v[3];
}
inline void conjugate() noexcept
{
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
}
inline void invert() noexcept
{
constexpr T n2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3]; // norm squared
if (n2 <= std::numeric_limits<T>::min())
return;
// conjugate divided by norm squared
v[0] = -v[0] / n2;
v[1] = -v[1] / n2;
v[2] = -v[2] / n2;
v[3] = v[3] / n2;
}
inline auto getNorm() const noexcept
{
constexpr T n = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
if (n == T(1)) // already normalized
return 1;
return std::sqrt(n);
}
void normalize() noexcept
{
constexpr T s = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
if (s == T(1)) // already normalized
return;
const T n = std::sqrt(s);
if (n <= std::numeric_limits<T>::min()) // too close to zero
return;
const T d = T(1) / n;
v[0] *= d;
v[1] *= d;
v[2] *= d;
v[3] *= d;
}
Quaternion normalized() const noexcept
{
constexpr T s = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
if (s == T(1)) // already normalized
return *this;
const T n = std::sqrt(s);
if (n <= std::numeric_limits<T>::min()) // too close to zero
return *this;
const T d = T(1) / n;
return *this * d;
}
void rotate(const T angle, const Vector<3, T>& axis) noexcept
{
const auto normalizedAxis = axis.normalized();
const T cosAngle = std::cos(angle / T(2));
const T sinAngle = std::sin(angle / T(2));
v[0] = normalizedAxis.v[0] * sinAngle;
v[1] = normalizedAxis.v[1] * sinAngle;
v[2] = normalizedAxis.v[2] * sinAngle;
v[3] = cosAngle;
}
void getRotation(T& angle, Vector<3, T>& axis) const noexcept
{
angle = T(2) * std::acos(v[3]);
const T s = std::sqrt(T(1) - v[3] * v[3]);
if (s <= std::numeric_limits<T>::min()) // too close to zero
{
axis.v[0] = v[0];
axis.v[1] = v[1];
axis.v[2] = v[2];
}
else
{
axis.v[0] = v[0] / s;
axis.v[1] = v[1] / s;
axis.v[2] = v[2] / s;
}
}
Vector<3, T> getEulerAngles() const noexcept
{
Vector<3, T> result;
result.v[0] = std::atan2(2 * (v[1] * v[2] + v[3] * v[0]), v[3] * v[3] - v[0] * v[0] - v[1] * v[1] + v[2] * v[2]);
result.v[1] = std::asin(-2 * (v[0] * v[2] - v[3] * v[1]));
result.v[2] = std::atan2(2 * (v[0] * v[1] + v[3] * v[2]), v[3] * v[3] + v[0] * v[0] - v[1] * v[1] - v[2] * v[2]);
return result;
}
inline auto getEulerAngleX() const noexcept
{
return std::atan2(T(2) * (v[1] * v[2] + v[3] * v[0]), v[3] * v[3] - v[0] * v[0] - v[1] * v[1] + v[2] * v[2]);
}
inline auto getEulerAngleY() const noexcept
{
return std::asin(T(-2) * (v[0] * v[2] - v[3] * v[1]));
}
inline auto getEulerAngleZ() const noexcept
{
return std::atan2(T(2) * (v[0] * v[1] + v[3] * v[2]), v[3] * v[3] + v[0] * v[0] - v[1] * v[1] - v[2] * v[2]);
}
void setEulerAngles(const Vector<3, T>& angles) noexcept
{
const T angleR = angles.v[0] / T(2);
const T sr = std::sin(angleR);
const T cr = std::cos(angleR);
const T angleP = angles.v[1] / T(2);
const T sp = std::sin(angleP);
const T cp = std::cos(angleP);
const T angleY = angles.v[2] / T(2);
const T sy = std::sin(angleY);
const T cy = std::cos(angleY);
const T cpcy = cp * cy;
const T spcy = sp * cy;
const T cpsy = cp * sy;
const T spsy = sp * sy;
v[0] = sr * cpcy - cr * spsy;
v[1] = cr * spcy + sr * cpsy;
v[2] = cr * cpsy - sr * spcy;
v[3] = cr * cpcy + sr * spsy;
}
inline const Vector<3, T> operator*(const Vector<3, T>& vector) const noexcept
{
return rotateVector(vector);
}
inline Vector<3, T> rotateVector(const Vector<3, T>& vector) const noexcept
{
constexpr Vector<3, T> q(v[0], v[1], v[2]);
const Vector<3, T> t = T(2) * q.cross(vector);
return vector + (v[3] * t) + q.cross(t);
}
inline Vector<3, T> getRightVector() const noexcept
{
return rotateVector(Vector<3, T>(1, 0, 0));
}
inline Vector<3, T> getUpVector() const noexcept
{
return rotateVector(Vector<3, T>(0, 1, 0));
}
inline Vector<3, T> getForwardVector() const noexcept
{
return rotateVector(Vector<3, T>(0, 0, 1));
}
inline Quaternion& lerp(const Quaternion& q1, const Quaternion& q2, T t) noexcept
{
*this = (q1 * (T(1) - t)) + (q2 * t);
return *this;
}
};
using QuaternionF = Quaternion<float>;
}
#endif // OUZEL_MATH_QUATERNION_HPP
<commit_msg>Make quaternion functions constexpr<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_MATH_QUATERNION_HPP
#define OUZEL_MATH_QUATERNION_HPP
#include <cmath>
#include <cstddef>
#include <limits>
#include "math/Vector.hpp"
namespace ouzel
{
template <typename T> class Quaternion final
{
public:
T v[4]{0};
constexpr Quaternion() noexcept {}
constexpr Quaternion(const T x, const T y, const T z, const T w) noexcept:
v{x, y, z, w}
{
}
inline T& operator[](size_t index) noexcept { return v[index]; }
constexpr T operator[](size_t index) const noexcept { return v[index]; }
inline T& x() noexcept { return v[0]; }
constexpr T x() const noexcept { return v[0]; }
inline T& y() noexcept { return v[1]; }
constexpr T y() const noexcept { return v[1]; }
inline T& z() noexcept { return v[2]; }
constexpr T z() const noexcept { return v[2]; }
inline T& w() noexcept { return v[3]; }
constexpr T w() const noexcept { return v[3]; }
static constexpr Quaternion identity() noexcept
{
return Quaternion(0, 0, 0, 1);
}
constexpr const Quaternion operator*(const Quaternion& q) const noexcept
{
return Quaternion(v[0] * q.v[3] + v[1] * q.v[2] - v[2] * q.v[1] + v[3] * q.v[0],
-v[0] * q.v[2] + v[1] * q.v[3] + v[2] * q.v[0] + v[3] * q.v[1],
v[0] * q.v[1] - v[1] * q.v[0] + v[2] * q.v[3] + v[3] * q.v[2],
-v[0] * q.v[0] - v[1] * q.v[1] - v[2] * q.v[2] + v[3] * q.v[3]);
}
constexpr Quaternion& operator*=(const Quaternion& q) noexcept
{
constexpr T tempX = v[0] * q.v[3] + v[1] * q.v[2] - v[2] * q.v[1] + v[3] * q.v[0];
constexpr T tempY = -v[0] * q.v[2] + v[1] * q.v[3] + v[2] * q.v[0] + v[3] * q.v[1];
constexpr T tempZ = v[0] * q.v[1] - v[1] * q.v[0] + v[2] * q.v[3] + v[3] * q.v[2];
constexpr T tempW = -v[0] * q.v[0] - v[1] * q.v[1] - v[2] * q.v[2] + v[3] * q.v[3];
v[0] = tempX;
v[1] = tempY;
v[2] = tempZ;
v[3] = tempW;
return *this;
}
constexpr const Quaternion operator*(const T scalar) const noexcept
{
return Quaternion(v[0] * scalar,
v[1] * scalar,
v[2] * scalar,
v[3] * scalar);
}
constexpr Quaternion& operator*=(const T scalar) noexcept
{
v[0] *= scalar;
v[1] *= scalar;
v[2] *= scalar;
v[3] *= scalar;
return *this;
}
constexpr const Quaternion operator/(const T scalar) const noexcept
{
return Quaternion(v[0] / scalar,
v[1] / scalar,
v[2] / scalar,
v[3] / scalar);
}
constexpr Quaternion& operator/=(const T scalar) noexcept
{
v[0] /= scalar;
v[1] /= scalar;
v[2] /= scalar;
v[3] /= scalar;
return *this;
}
constexpr const Quaternion operator-() const noexcept
{
return Quaternion(-v[0], -v[1], -v[2], -v[3]);
}
constexpr const Quaternion operator+(const Quaternion& q) const noexcept
{
return Quaternion(v[0] + q.v[0],
v[1] + q.v[1],
v[2] + q.v[2],
v[3] + q.v[3]);
}
constexpr Quaternion& operator+=(const Quaternion& q) noexcept
{
v[0] += q.v[0];
v[1] += q.v[1];
v[2] += q.v[2];
v[3] += q.v[3];
return *this;
}
constexpr const Quaternion operator-(const Quaternion& q) const noexcept
{
return Quaternion(v[0] - q.v[0],
v[1] - q.v[1],
v[2] - q.v[2],
v[3] - q.v[3]);
}
constexpr Quaternion& operator-=(const Quaternion& q) noexcept
{
v[0] -= q.v[0];
v[1] -= q.v[1];
v[2] -= q.v[2];
v[3] -= q.v[3];
return *this;
}
constexpr bool operator==(const Quaternion& q) const noexcept
{
return v[0] == q.v[0] && v[1] == q.v[1] && v[2] == q.v[2] && v[3] == q.v[3];
}
constexpr bool operator!=(const Quaternion& q) const noexcept
{
return v[0] != q.v[0] || v[1] != q.v[1] || v[2] != q.v[2] || v[3] != q.v[3];
}
constexpr void negate() noexcept
{
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
v[3] = -v[3];
}
constexpr void conjugate() noexcept
{
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
}
constexpr void invert() noexcept
{
constexpr T n2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3]; // norm squared
if (n2 <= std::numeric_limits<T>::min())
return;
// conjugate divided by norm squared
v[0] = -v[0] / n2;
v[1] = -v[1] / n2;
v[2] = -v[2] / n2;
v[3] = v[3] / n2;
}
inline auto getNorm() const noexcept
{
constexpr T n = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
if (n == T(1)) // already normalized
return 1;
return std::sqrt(n);
}
void normalize() noexcept
{
constexpr T s = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
if (s == T(1)) // already normalized
return;
const T n = std::sqrt(s);
if (n <= std::numeric_limits<T>::min()) // too close to zero
return;
const T d = T(1) / n;
v[0] *= d;
v[1] *= d;
v[2] *= d;
v[3] *= d;
}
Quaternion normalized() const noexcept
{
constexpr T s = v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
if (s == T(1)) // already normalized
return *this;
const T n = std::sqrt(s);
if (n <= std::numeric_limits<T>::min()) // too close to zero
return *this;
const T d = T(1) / n;
return *this * d;
}
void rotate(const T angle, const Vector<3, T>& axis) noexcept
{
const auto normalizedAxis = axis.normalized();
const T cosAngle = std::cos(angle / T(2));
const T sinAngle = std::sin(angle / T(2));
v[0] = normalizedAxis.v[0] * sinAngle;
v[1] = normalizedAxis.v[1] * sinAngle;
v[2] = normalizedAxis.v[2] * sinAngle;
v[3] = cosAngle;
}
void getRotation(T& angle, Vector<3, T>& axis) const noexcept
{
angle = T(2) * std::acos(v[3]);
const T s = std::sqrt(T(1) - v[3] * v[3]);
if (s <= std::numeric_limits<T>::min()) // too close to zero
{
axis.v[0] = v[0];
axis.v[1] = v[1];
axis.v[2] = v[2];
}
else
{
axis.v[0] = v[0] / s;
axis.v[1] = v[1] / s;
axis.v[2] = v[2] / s;
}
}
Vector<3, T> getEulerAngles() const noexcept
{
Vector<3, T> result;
result.v[0] = std::atan2(2 * (v[1] * v[2] + v[3] * v[0]), v[3] * v[3] - v[0] * v[0] - v[1] * v[1] + v[2] * v[2]);
result.v[1] = std::asin(-2 * (v[0] * v[2] - v[3] * v[1]));
result.v[2] = std::atan2(2 * (v[0] * v[1] + v[3] * v[2]), v[3] * v[3] + v[0] * v[0] - v[1] * v[1] - v[2] * v[2]);
return result;
}
inline auto getEulerAngleX() const noexcept
{
return std::atan2(T(2) * (v[1] * v[2] + v[3] * v[0]), v[3] * v[3] - v[0] * v[0] - v[1] * v[1] + v[2] * v[2]);
}
inline auto getEulerAngleY() const noexcept
{
return std::asin(T(-2) * (v[0] * v[2] - v[3] * v[1]));
}
inline auto getEulerAngleZ() const noexcept
{
return std::atan2(T(2) * (v[0] * v[1] + v[3] * v[2]), v[3] * v[3] + v[0] * v[0] - v[1] * v[1] - v[2] * v[2]);
}
void setEulerAngles(const Vector<3, T>& angles) noexcept
{
const T angleR = angles.v[0] / T(2);
const T sr = std::sin(angleR);
const T cr = std::cos(angleR);
const T angleP = angles.v[1] / T(2);
const T sp = std::sin(angleP);
const T cp = std::cos(angleP);
const T angleY = angles.v[2] / T(2);
const T sy = std::sin(angleY);
const T cy = std::cos(angleY);
const T cpcy = cp * cy;
const T spcy = sp * cy;
const T cpsy = cp * sy;
const T spsy = sp * sy;
v[0] = sr * cpcy - cr * spsy;
v[1] = cr * spcy + sr * cpsy;
v[2] = cr * cpsy - sr * spcy;
v[3] = cr * cpcy + sr * spsy;
}
inline const Vector<3, T> operator*(const Vector<3, T>& vector) const noexcept
{
return rotateVector(vector);
}
inline Vector<3, T> rotateVector(const Vector<3, T>& vector) const noexcept
{
constexpr Vector<3, T> q(v[0], v[1], v[2]);
const Vector<3, T> t = T(2) * q.cross(vector);
return vector + (v[3] * t) + q.cross(t);
}
inline Vector<3, T> getRightVector() const noexcept
{
return rotateVector(Vector<3, T>(1, 0, 0));
}
inline Vector<3, T> getUpVector() const noexcept
{
return rotateVector(Vector<3, T>(0, 1, 0));
}
inline Vector<3, T> getForwardVector() const noexcept
{
return rotateVector(Vector<3, T>(0, 0, 1));
}
constexpr Quaternion& lerp(const Quaternion& q1, const Quaternion& q2, T t) noexcept
{
*this = (q1 * (T(1) - t)) + (q2 * t);
return *this;
}
};
using QuaternionF = Quaternion<float>;
}
#endif // OUZEL_MATH_QUATERNION_HPP
<|endoftext|>
|
<commit_before>#include <libprecisegc/details/recorder.hpp>
namespace precisegc { namespace details {
recorder::recorder()
: m_heap_size(0)
, m_last_heap_size(0)
, m_last_alloc_time(gc_clock::now().time_since_epoch())
, m_last_gc_time(gc_clock::now().time_since_epoch())
, m_last_gc_duration(gc_clock::duration(0))
, m_gc_cnt(0)
, m_pause_cnt(0)
{}
void recorder::register_alloc_request()
{
m_last_alloc_time.store(gc_clock::now().time_since_epoch(), std::memory_order_release);
}
void recorder::register_allocation(size_t size)
{
// m_heap_size.fetch_add(size, std::memory_order_acq_rel);
}
void recorder::register_pause(const gc_pause_stat& pause_stat)
{
if (pause_stat.type != gc_pause_type::NO_PAUSE) {
m_pause_cnt.fetch_add(1, std::memory_order_acq_rel);
}
}
void recorder::register_sweep(const gc_sweep_stat& sweep_stat, const gc_pause_stat& pause_stat)
{
gc_clock::duration now = gc_clock::now().time_since_epoch();
size_t freed = sweep_stat.shrunk + sweep_stat.swept;
// we use std::memory_order_relaxed here because it is expected that this method will be called during stop-the-world pause
m_heap_size.fetch_sub(freed, std::memory_order_relaxed);
m_last_heap_size.store(m_heap_size.load(std::memory_order_relaxed), std::memory_order_relaxed);
m_last_alloc_time.store(now, std::memory_order_relaxed);
m_last_gc_time.store(now, std::memory_order_relaxed);
m_last_gc_duration.store(pause_stat.duration, std::memory_order_relaxed);
m_gc_cnt.fetch_add(1, std::memory_order_relaxed);
if (pause_stat.type != gc_pause_type::NO_PAUSE) {
m_pause_cnt.fetch_add(1, std::memory_order_relaxed);
}
}
gc_stat recorder::stat() const
{
gc_stat stat;
gc_clock::duration now = gc_clock::now().time_since_epoch();
stat.heap_size = m_heap_size.load(std::memory_order_acquire);
stat.heap_gain = stat.heap_size - m_last_heap_size.load(std::memory_order_acquire);
// stat.last_alloc_timediff = now - m_last_alloc_time.load(std::memory_order_acquire);
stat.last_alloc_timediff = gc_clock::duration(0);
stat.last_gc_timediff = now - m_last_gc_time.load(std::memory_order_acquire);
stat.last_gc_duration = m_last_gc_duration.load(std::memory_order_acquire);
return stat;
}
size_t recorder::gc_cycles_count() const
{
return m_gc_cnt.load(std::memory_order_acquire);
}
size_t recorder::pause_count() const
{
return m_pause_cnt.load(std::memory_order_acquire);
}
}}
<commit_msg>fix recorder<commit_after>#include <libprecisegc/details/recorder.hpp>
namespace precisegc { namespace details {
recorder::recorder()
: m_heap_size(0)
, m_last_heap_size(0)
, m_last_alloc_time(gc_clock::now().time_since_epoch())
, m_last_gc_time(gc_clock::now().time_since_epoch())
, m_last_gc_duration(gc_clock::duration(0))
, m_gc_cnt(0)
, m_pause_cnt(0)
{}
void recorder::register_alloc_request()
{
// m_last_alloc_time.store(gc_clock::now().time_since_epoch(), std::memory_order_release);
}
void recorder::register_allocation(size_t size)
{
m_heap_size.fetch_add(size, std::memory_order_acq_rel);
}
void recorder::register_pause(const gc_pause_stat& pause_stat)
{
if (pause_stat.type != gc_pause_type::NO_PAUSE) {
m_pause_cnt.fetch_add(1, std::memory_order_acq_rel);
}
}
void recorder::register_sweep(const gc_sweep_stat& sweep_stat, const gc_pause_stat& pause_stat)
{
gc_clock::duration now = gc_clock::now().time_since_epoch();
size_t freed = sweep_stat.shrunk + sweep_stat.swept;
// we use std::memory_order_relaxed here because it is expected that this method will be called during stop-the-world pause
m_heap_size.fetch_sub(freed, std::memory_order_relaxed);
m_last_heap_size.store(m_heap_size.load(std::memory_order_relaxed), std::memory_order_relaxed);
m_last_alloc_time.store(now, std::memory_order_relaxed);
m_last_gc_time.store(now, std::memory_order_relaxed);
m_last_gc_duration.store(pause_stat.duration, std::memory_order_relaxed);
m_gc_cnt.fetch_add(1, std::memory_order_relaxed);
if (pause_stat.type != gc_pause_type::NO_PAUSE) {
m_pause_cnt.fetch_add(1, std::memory_order_relaxed);
}
}
gc_stat recorder::stat() const
{
gc_stat stat;
gc_clock::duration now = gc_clock::now().time_since_epoch();
stat.heap_size = m_heap_size.load(std::memory_order_acquire);
stat.heap_gain = stat.heap_size - m_last_heap_size.load(std::memory_order_acquire);
// stat.last_alloc_timediff = now - m_last_alloc_time.load(std::memory_order_acquire);
stat.last_alloc_timediff = gc_clock::duration(0);
stat.last_gc_timediff = now - m_last_gc_time.load(std::memory_order_acquire);
stat.last_gc_duration = m_last_gc_duration.load(std::memory_order_acquire);
return stat;
}
size_t recorder::gc_cycles_count() const
{
return m_gc_cnt.load(std::memory_order_acquire);
}
size_t recorder::pause_count() const
{
return m_pause_cnt.load(std::memory_order_acquire);
}
}}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxExtension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/config.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/dir.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
const wxString wxExAlignText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out,
const wxExLexer& lexer)
{
const size_t line_length = lexer.UsableCharactersPerLine();
// Use the header, with one space extra to separate, or no header at all.
const wxString header_with_spaces =
(header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size());
wxString in = lines, line = header;
bool at_begin = true;
wxString out;
while (!in.empty())
{
const wxString word = wxExGetWord(in, false, false);
if (line.size() + 1 + word.size() > line_length)
{
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";
line = header_with_spaces + word;
}
else
{
line += (!line.empty() && !at_begin ? wxString(" "): wxString(wxEmptyString)) + word;
at_begin = false;
}
}
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out);
return out;
}
bool wxExClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString wxExClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void wxExComboBoxFromString(
wxComboBox* cb,
const wxString& text)
{
wxASSERT(cb != NULL);
wxStringTokenizer tkz(
text,
wxExFindReplaceData::Get()->GetFieldSeparator());
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
if (cb->FindString(val) == wxNOT_FOUND)
{
cb->Append(val);
}
}
if (cb->GetCount() > 0)
{
cb->SetValue(cb->GetString(0));
}
}
const wxString wxExComboBoxToString(
const wxComboBox* cb,
size_t max_items)
{
wxASSERT(cb != NULL);
wxString text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case 0:
text.clear();
// No change necessary, the string is already present as the first one.
for (size_t i = 0; i < max_items; i++)
if (i < cb->GetCount())
text += cb->GetString(i) + wxExFindReplaceData::Get()->GetFieldSeparator();
break;
case wxNOT_FOUND:
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < max_items - 1; i++)
if (i < cb->GetCount())
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb->GetString(i);
break;
default:
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb_element;
}
}
return text;
}
const wxString wxExConfigFirstOf(const wxString& key)
{
const wxString value = wxConfigBase::Get()->Read(key);
return value.BeforeFirst(wxExFindReplaceData::Get()->GetFieldSeparator());
}
#endif // wxUSE_GUI
const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
void wxExFindResult(
const wxString& find_text,
bool find_next,
bool recursive)
{
if (!recursive)
{
const wxString where = (find_next) ? _("bottom"): _("top");
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
_("Searching for") + " " + wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " +
_("hit") + " " + where);
#endif
}
else
{
wxBell();
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " + _("not found"));
#endif
}
}
const wxString wxExGetEndOfText(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int wxExGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxUniChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\r')) + 1;
}
else if (text.Find(wxUniChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\n')) + 1;
}
else
{
return 1;
}
}
int wxExGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
const wxString wxExGetWord(
wxString& text,
bool use_other_field_separators,
bool use_path_separator)
{
wxString field_separators = " \t";
if (use_other_field_separators) field_separators += ":";
if (use_path_separator) field_separators = wxFILE_SEP_PATH;
wxString token;
wxStringTokenizer tkz(text, field_separators);
if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
text = tkz.GetString();
text.Trim(false);
return token;
}
bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
#if wxUSE_GUI
void wxExOpenFiles(
wxExFrame* frame,
const wxArrayString& files,
long file_flags,
int dir_flags)
{
// std::vector gives compile error.
for (size_t i = 0; i < files.GetCount(); i++)
{
wxString file = files[i]; // cannot be const because of file = later on
if (file.Contains("*") || file.Contains("?"))
{
wxExDirOpenFile dir(frame, wxGetCwd(), file, file_flags, dir_flags);
dir.FindFiles();
}
else
{
int line = 0;
if (!wxFileName(file).FileExists() && file.Contains(":"))
{
line = atoi(file.AfterFirst(':').c_str());
file = file.BeforeFirst(':');
}
frame->OpenFile(file, line, wxEmptyString, file_flags);
}
}
}
void wxExOpenFilesDialog(
wxExFrame* frame,
long style,
const wxString& wildcards,
bool ask_for_continue,
long file_flags ,
int dir_flags);
{
wxExSTC* stc = frame->GetSTC();
wxArrayString files;
const wxString caption(_("Select Files"));
if (stc != NULL)
{
wxExFileDialog dlg(frame,
stc,
caption,
wildcards,
style);
if (ask_for_continue)
{
if (dlg.ShowModalIfChanged(true) == wxID_CANCEL) return;
}
else
{
if (dlg.ShowModal() == wxID_CANCEL) return;
}
dlg.GetPaths(files);
}
else
{
wxFileDialog dlg(frame,
caption,
wxEmptyString,
wxEmptyString,
wildcards,
style);
if (dlg.ShowModal() == wxID_CANCEL) return;
dlg.GetPaths(files);
}
wxExOpenFiles(frame, files, file_flags, dir_flags);
}
#endif // wxUSE_GUI
const wxString wxExPrintCaption(const wxFileName& filename)
{
if (filename.FileExists())
{
return filename.GetFullPath();
}
else
{
return _("Printout");
}
}
const wxString wxExPrintFooter()
{
return _("Page @PAGENUM@ of @PAGESCNT@");
}
const wxString wxExPrintHeader(const wxFileName& filename)
{
if (filename.FileExists())
{
return
wxExGetEndOfText(filename.GetFullPath(), 30) + " " +
filename.GetModificationTime().Format();
}
else
{
return _("Printed") + ": " + wxDateTime::Now().Format();
}
}
const wxString wxExQuoted(const wxString& text)
{
return "'" + text + "'";
}
const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<commit_msg>fixed compile error<commit_after>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxExtension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/config.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/dir.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
const wxString wxExAlignText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out,
const wxExLexer& lexer)
{
const size_t line_length = lexer.UsableCharactersPerLine();
// Use the header, with one space extra to separate, or no header at all.
const wxString header_with_spaces =
(header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size());
wxString in = lines, line = header;
bool at_begin = true;
wxString out;
while (!in.empty())
{
const wxString word = wxExGetWord(in, false, false);
if (line.size() + 1 + word.size() > line_length)
{
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";
line = header_with_spaces + word;
}
else
{
line += (!line.empty() && !at_begin ? wxString(" "): wxString(wxEmptyString)) + word;
at_begin = false;
}
}
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out);
return out;
}
bool wxExClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString wxExClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void wxExComboBoxFromString(
wxComboBox* cb,
const wxString& text)
{
wxASSERT(cb != NULL);
wxStringTokenizer tkz(
text,
wxExFindReplaceData::Get()->GetFieldSeparator());
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
if (cb->FindString(val) == wxNOT_FOUND)
{
cb->Append(val);
}
}
if (cb->GetCount() > 0)
{
cb->SetValue(cb->GetString(0));
}
}
const wxString wxExComboBoxToString(
const wxComboBox* cb,
size_t max_items)
{
wxASSERT(cb != NULL);
wxString text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case 0:
text.clear();
// No change necessary, the string is already present as the first one.
for (size_t i = 0; i < max_items; i++)
if (i < cb->GetCount())
text += cb->GetString(i) + wxExFindReplaceData::Get()->GetFieldSeparator();
break;
case wxNOT_FOUND:
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < max_items - 1; i++)
if (i < cb->GetCount())
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb->GetString(i);
break;
default:
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb_element;
}
}
return text;
}
const wxString wxExConfigFirstOf(const wxString& key)
{
const wxString value = wxConfigBase::Get()->Read(key);
return value.BeforeFirst(wxExFindReplaceData::Get()->GetFieldSeparator());
}
#endif // wxUSE_GUI
const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
void wxExFindResult(
const wxString& find_text,
bool find_next,
bool recursive)
{
if (!recursive)
{
const wxString where = (find_next) ? _("bottom"): _("top");
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
_("Searching for") + " " + wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " +
_("hit") + " " + where);
#endif
}
else
{
wxBell();
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " + _("not found"));
#endif
}
}
const wxString wxExGetEndOfText(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int wxExGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxUniChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\r')) + 1;
}
else if (text.Find(wxUniChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\n')) + 1;
}
else
{
return 1;
}
}
int wxExGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
const wxString wxExGetWord(
wxString& text,
bool use_other_field_separators,
bool use_path_separator)
{
wxString field_separators = " \t";
if (use_other_field_separators) field_separators += ":";
if (use_path_separator) field_separators = wxFILE_SEP_PATH;
wxString token;
wxStringTokenizer tkz(text, field_separators);
if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
text = tkz.GetString();
text.Trim(false);
return token;
}
bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
#if wxUSE_GUI
void wxExOpenFiles(
wxExFrame* frame,
const wxArrayString& files,
long file_flags,
int dir_flags)
{
// std::vector gives compile error.
for (size_t i = 0; i < files.GetCount(); i++)
{
wxString file = files[i]; // cannot be const because of file = later on
if (file.Contains("*") || file.Contains("?"))
{
wxExDirOpenFile dir(frame, wxGetCwd(), file, file_flags, dir_flags);
dir.FindFiles();
}
else
{
int line = 0;
if (!wxFileName(file).FileExists() && file.Contains(":"))
{
line = atoi(file.AfterFirst(':').c_str());
file = file.BeforeFirst(':');
}
frame->OpenFile(file, line, wxEmptyString, file_flags);
}
}
}
void wxExOpenFilesDialog(
wxExFrame* frame,
long style,
const wxString& wildcards,
bool ask_for_continue,
long file_flags,
int dir_flags)
{
wxExSTC* stc = frame->GetSTC();
wxArrayString files;
const wxString caption(_("Select Files"));
if (stc != NULL)
{
wxExFileDialog dlg(frame,
stc,
caption,
wildcards,
style);
if (ask_for_continue)
{
if (dlg.ShowModalIfChanged(true) == wxID_CANCEL) return;
}
else
{
if (dlg.ShowModal() == wxID_CANCEL) return;
}
dlg.GetPaths(files);
}
else
{
wxFileDialog dlg(frame,
caption,
wxEmptyString,
wxEmptyString,
wildcards,
style);
if (dlg.ShowModal() == wxID_CANCEL) return;
dlg.GetPaths(files);
}
wxExOpenFiles(frame, files, file_flags, dir_flags);
}
#endif // wxUSE_GUI
const wxString wxExPrintCaption(const wxFileName& filename)
{
if (filename.FileExists())
{
return filename.GetFullPath();
}
else
{
return _("Printout");
}
}
const wxString wxExPrintFooter()
{
return _("Page @PAGENUM@ of @PAGESCNT@");
}
const wxString wxExPrintHeader(const wxFileName& filename)
{
if (filename.FileExists())
{
return
wxExGetEndOfText(filename.GetFullPath(), 30) + " " +
filename.GetModificationTime().Format();
}
else
{
return _("Printed") + ": " + wxDateTime::Now().Format();
}
}
const wxString wxExQuoted(const wxString& text)
{
return "'" + text + "'";
}
const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxextension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/base.h>
const wxString wxExAlignText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out,
const wxExLexer* lexer)
{
const size_t line_length = (lexer == NULL ? 80: lexer->UsableCharactersPerLine());
// Use the header, with one space extra to separate, or no header at all.
const wxString header_with_spaces =
(header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size());
wxString in = lines, line = header;
bool at_begin = true;
wxString out;
while (!in.empty())
{
const wxString word = wxExGetWord(in, false, false);
if (line.size() + 1 + word.size() > line_length)
{
if (lexer != NULL)
{
out << lexer->MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";
}
else
{
out << line << "\n";
}
line = header_with_spaces + word;
}
else
{
line += (!line.empty() && !at_begin ? " ": wxString(wxEmptyString)) + word;
at_begin = false;
}
}
if (lexer != NULL)
{
out << lexer->MakeSingleLineComment(line, fill_out_with_space, fill_out);
}
else
{
out << line << "\n";
}
return out;
}
bool wxExClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString wxExClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void wxExComboBoxFromString(
wxComboBox* cb,
const wxString& text,
const wxChar field_separator)
{
wxASSERT(cb != NULL);
wxStringTokenizer tkz(text, field_separator);
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
if (cb->FindString(val) == wxNOT_FOUND)
{
cb->Append(val);
}
}
if (cb->GetCount() > 0) cb->SetValue(cb->GetString(0));
}
bool wxExComboBoxToString(
const wxComboBox* cb,
wxString& text,
const wxChar field_separator,
size_t max_items)
{
wxASSERT(cb != NULL);
text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case wxNOT_FOUND:
{
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < max_items; i++)
if (i < max_items - 1 && i < cb->GetCount())
text += field_separator + cb->GetString(i);
}
break;
// No change necessary, the string is already present as the first one.
case 0: return false; break;
default:
{
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += field_separator + cb_element;
}
}
}
return true;
}
#endif // wxUSE_GUI
long wxExColourToLong(const wxColour& c)
{
return c.Red() | (c.Green() << 8) | (c.Blue() << 16);
}
const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
const wxString wxExGetEndOfText(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int wxExGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\r')) + 1;
}
else if (text.Find(wxChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\n')) + 1;
}
else
{
return 1;
}
}
int wxExGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
const wxString wxExGetWord(
wxString& text,
bool use_other_field_separators,
bool use_path_separator)
{
wxString field_separators = " \t";
if (use_other_field_separators) field_separators += ":";
if (use_path_separator) field_separators = wxFILE_SEP_PATH;
wxString token;
wxStringTokenizer tkz(text, field_separators);
if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
text = tkz.GetString();
text.Trim(false);
return token;
}
bool wxExLog(const wxString& text, const wxFileName& filename)
{
return wxFile(
filename.GetFullPath(),
wxFile::write_append).Write(
wxDateTime::Now().Format() + " " + text + wxTextFile::GetEOL());
}
const wxFileName wxExLogfileName()
{
if (wxTheApp == NULL)
{
return wxFileName("app.log");
}
#ifdef EX_PORTABLE
return wxFileName(
wxPathOnly(wxStandardPaths::Get().GetExecutablePath()),
wxTheApp->GetAppName().Lower() + ".log");
#else
return wxFileName(
wxStandardPaths::Get().GetUserDataDir(),
wxTheApp->GetAppName().Lower() + ".log");
#endif
}
bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
#if wxUSE_GUI
bool wxExOpenFile(const wxFileName& filename, long open_flags)
{
wxASSERT(wxTheApp != NULL);
wxWindow* window = wxTheApp->GetTopWindow();
wxExFrame* frame = wxDynamicCast(window, wxExFrame);
if (frame != NULL)
{
return frame->OpenFile(
wxExFileName(filename.GetFullPath()), -1, wxEmptyString, open_flags);
}
else
{
return false;
}
}
#endif
const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<commit_msg><commit_after>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxextension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/base.h>
const wxString wxExAlignText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out,
const wxExLexer* lexer)
{
const size_t line_length = (lexer == NULL ? 80: lexer->UsableCharactersPerLine());
// Use the header, with one space extra to separate, or no header at all.
const wxString header_with_spaces =
(header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size());
wxString in = lines, line = header;
bool at_begin = true;
wxString out;
while (!in.empty())
{
const wxString word = wxExGetWord(in, false, false);
if (line.size() + 1 + word.size() > line_length)
{
if (lexer != NULL)
{
out << lexer->MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";
}
else
{
out << line << "\n";
}
line = header_with_spaces + word;
}
else
{
line += (!line.empty() && !at_begin ? " ": wxString(wxEmptyString)) + word;
at_begin = false;
}
}
if (lexer != NULL)
{
out << lexer->MakeSingleLineComment(line, fill_out_with_space, fill_out);
}
else
{
out << line;
}
return out;
}
bool wxExClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString wxExClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void wxExComboBoxFromString(
wxComboBox* cb,
const wxString& text,
const wxChar field_separator)
{
wxASSERT(cb != NULL);
wxStringTokenizer tkz(text, field_separator);
while (tkz.HasMoreTokens())
{
const wxString val = tkz.GetNextToken();
if (cb->FindString(val) == wxNOT_FOUND)
{
cb->Append(val);
}
}
if (cb->GetCount() > 0) cb->SetValue(cb->GetString(0));
}
bool wxExComboBoxToString(
const wxComboBox* cb,
wxString& text,
const wxChar field_separator,
size_t max_items)
{
wxASSERT(cb != NULL);
text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case wxNOT_FOUND:
{
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < max_items; i++)
if (i < max_items - 1 && i < cb->GetCount())
text += field_separator + cb->GetString(i);
}
break;
// No change necessary, the string is already present as the first one.
case 0: return false; break;
default:
{
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += field_separator + cb_element;
}
}
}
return true;
}
#endif // wxUSE_GUI
long wxExColourToLong(const wxColour& c)
{
return c.Red() | (c.Green() << 8) | (c.Blue() << 16);
}
const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
const wxString wxExGetEndOfText(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int wxExGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\r')) + 1;
}
else if (text.Find(wxChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxChar('\n')) + 1;
}
else
{
return 1;
}
}
int wxExGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
const wxString wxExGetWord(
wxString& text,
bool use_other_field_separators,
bool use_path_separator)
{
wxString field_separators = " \t";
if (use_other_field_separators) field_separators += ":";
if (use_path_separator) field_separators = wxFILE_SEP_PATH;
wxString token;
wxStringTokenizer tkz(text, field_separators);
if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
text = tkz.GetString();
text.Trim(false);
return token;
}
bool wxExLog(const wxString& text, const wxFileName& filename)
{
return wxFile(
filename.GetFullPath(),
wxFile::write_append).Write(
wxDateTime::Now().Format() + " " + text + wxTextFile::GetEOL());
}
const wxFileName wxExLogfileName()
{
if (wxTheApp == NULL)
{
return wxFileName("app.log");
}
#ifdef EX_PORTABLE
return wxFileName(
wxPathOnly(wxStandardPaths::Get().GetExecutablePath()),
wxTheApp->GetAppName().Lower() + ".log");
#else
return wxFileName(
wxStandardPaths::Get().GetUserDataDir(),
wxTheApp->GetAppName().Lower() + ".log");
#endif
}
bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
#if wxUSE_GUI
bool wxExOpenFile(const wxFileName& filename, long open_flags)
{
wxASSERT(wxTheApp != NULL);
wxWindow* window = wxTheApp->GetTopWindow();
wxExFrame* frame = wxDynamicCast(window, wxExFrame);
if (frame != NULL)
{
return frame->OpenFile(
wxExFileName(filename.GetFullPath()), -1, wxEmptyString, open_flags);
}
else
{
return false;
}
}
#endif
const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxExtension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/config.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/dir.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
const wxString wxExAlignText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out,
const wxExLexer& lexer)
{
const size_t line_length = lexer.UsableCharactersPerLine();
// Use the header, with one space extra to separate, or no header at all.
const wxString header_with_spaces =
(header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size());
wxString in = lines, line = header;
bool at_begin = true;
wxString out;
while (!in.empty())
{
const wxString word = wxExGetWord(in, false, false);
if (line.size() + 1 + word.size() > line_length)
{
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";
line = header_with_spaces + word;
}
else
{
line += (!line.empty() && !at_begin ? wxString(" "): wxString(wxEmptyString)) + word;
at_begin = false;
}
}
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out);
return out;
}
bool wxExClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString wxExClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void wxExComboBoxFromString(
wxComboBox* cb,
const wxString& text)
{
wxASSERT(cb != NULL);
cb->Clear();
wxStringTokenizer tkz(
text,
wxExFindReplaceData::Get()->GetFieldSeparator());
while (tkz.HasMoreTokens())
{
cb->Append(tkz.GetNextToken());
}
if (cb->GetCount() > 0)
{
cb->SetValue(cb->GetString(0));
}
}
const wxString wxExComboBoxToString(
const wxComboBox* cb,
size_t max_items)
{
wxASSERT(cb != NULL);
wxString text = cb->GetValue();
switch (cb->FindString(cb->GetValue()))
{
case 0:
text.clear();
// No change necessary, the string is already present as the first one.
for (size_t i = 0; i < cb->GetCount() && i < max_items; i++)
text += cb->GetString(i) + wxExFindReplaceData::Get()->GetFieldSeparator();
break;
case wxNOT_FOUND:
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < cb->GetCount() && i < max_items - 1; i++)
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb->GetString(i);
break;
default:
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb_element;
}
}
return text;
}
#endif // wxUSE_GUI
const wxString wxExConfigFirstOf(const wxString& key)
{
const wxString value = wxConfigBase::Get()->Read(key);
return value.BeforeFirst(wxExFindReplaceData::Get()->GetFieldSeparator());
}
const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
void wxExFindResult(
const wxString& find_text,
bool find_next,
bool recursive)
{
if (!recursive)
{
const wxString where = (find_next) ? _("bottom"): _("top");
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
_("Searching for") + " " + wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " +
_("hit") + " " + where);
#endif
}
else
{
wxBell();
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " + _("not found"));
#endif
}
}
const wxString wxExGetEndOfText(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int wxExGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxUniChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\r')) + 1;
}
else if (text.Find(wxUniChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\n')) + 1;
}
else
{
return 1;
}
}
int wxExGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
const wxString wxExGetWord(
wxString& text,
bool use_other_field_separators,
bool use_path_separator)
{
wxString field_separators = " \t";
if (use_other_field_separators) field_separators += ":";
if (use_path_separator) field_separators = wxFILE_SEP_PATH;
wxString token;
wxStringTokenizer tkz(text, field_separators);
if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
text = tkz.GetString();
text.Trim(false);
return token;
}
bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
#if wxUSE_GUI
void wxExOpenFiles(
wxExFrame* frame,
const wxArrayString& files,
long file_flags,
int dir_flags)
{
// std::vector gives compile error.
for (size_t i = 0; i < files.GetCount(); i++)
{
wxString file = files[i]; // cannot be const because of file = later on
if (file.Contains("*") || file.Contains("?"))
{
wxExDirOpenFile dir(frame, wxGetCwd(), file, file_flags, dir_flags);
dir.FindFiles();
}
else
{
int line = 0;
if (!wxFileName(file).FileExists() && file.Contains(":"))
{
line = atoi(file.AfterFirst(':').c_str());
file = file.BeforeFirst(':');
}
frame->OpenFile(file, line, wxEmptyString, file_flags);
}
}
}
void wxExOpenFilesDialog(
wxExFrame* frame,
long style,
const wxString& wildcards,
bool ask_for_continue,
long file_flags,
int dir_flags)
{
wxExSTC* stc = frame->GetSTC();
wxArrayString files;
const wxString caption(_("Select Files"));
if (stc != NULL)
{
wxExFileDialog dlg(frame,
stc,
caption,
wildcards,
style);
if (ask_for_continue)
{
if (dlg.ShowModalIfChanged(true) == wxID_CANCEL) return;
}
else
{
if (dlg.ShowModal() == wxID_CANCEL) return;
}
dlg.GetPaths(files);
}
else
{
wxFileDialog dlg(frame,
caption,
wxEmptyString,
wxEmptyString,
wildcards,
style);
if (dlg.ShowModal() == wxID_CANCEL) return;
dlg.GetPaths(files);
}
wxExOpenFiles(frame, files, file_flags, dir_flags);
}
#endif // wxUSE_GUI
const wxString wxExPrintCaption(const wxFileName& filename)
{
if (filename.FileExists())
{
return filename.GetFullPath();
}
else
{
return _("Printout");
}
}
const wxString wxExPrintFooter()
{
return _("Page @PAGENUM@ of @PAGESCNT@");
}
const wxString wxExPrintHeader(const wxFileName& filename)
{
if (filename.FileExists())
{
return
wxExGetEndOfText(filename.GetFullPath(), 30) + " " +
filename.GetModificationTime().Format();
}
else
{
return _("Printed") + ": " + wxDateTime::Now().Format();
}
}
const wxString wxExQuoted(const wxString& text)
{
return "'" + text + "'";
}
const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<commit_msg>added case sensitive option when finding in combobox<commit_after>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxExtension utility methods
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/clipbrd.h>
#include <wx/config.h>
#include <wx/file.h>
#include <wx/regex.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h> // for wxTextFile::GetEOL()
#include <wx/tokenzr.h>
#include <wx/extension/util.h>
#include <wx/extension/dir.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
const wxString wxExAlignText(
const wxString& lines,
const wxString& header,
bool fill_out_with_space,
bool fill_out,
const wxExLexer& lexer)
{
const size_t line_length = lexer.UsableCharactersPerLine();
// Use the header, with one space extra to separate, or no header at all.
const wxString header_with_spaces =
(header.size() == 0) ? wxString(wxEmptyString) : wxString(' ', header.size());
wxString in = lines, line = header;
bool at_begin = true;
wxString out;
while (!in.empty())
{
const wxString word = wxExGetWord(in, false, false);
if (line.size() + 1 + word.size() > line_length)
{
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out) << "\n";
line = header_with_spaces + word;
}
else
{
line += (!line.empty() && !at_begin ? wxString(" "): wxString(wxEmptyString)) + word;
at_begin = false;
}
}
out << lexer.MakeSingleLineComment(line, fill_out_with_space, fill_out);
return out;
}
bool wxExClipboardAdd(const wxString& text)
{
wxClipboardLocker locker;
if (!locker) return false;
if (!wxTheClipboard->AddData(new wxTextDataObject(text))) return false;
// Take care that clipboard data remain after exiting
// This is a boolean method as well, we don't check it, as
// clipboard data is copied.
// At least on Ubuntu 8.10 FLush returns false.
wxTheClipboard->Flush();
return true;
}
const wxString wxExClipboardGet()
{
wxBusyCursor wait;
wxClipboardLocker locker;
if (!locker)
{
wxLogError("Cannot open clipboard");
return wxEmptyString;
}
if (!wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxLogError("Clipboard format not supported");
return wxEmptyString;
}
wxTextDataObject data;
if (!wxTheClipboard->GetData(data))
{
wxLogError("Cannot get clipboard data");
return wxEmptyString;
}
return data.GetText();
}
#if wxUSE_GUI
void wxExComboBoxFromString(
wxComboBox* cb,
const wxString& text)
{
wxASSERT(cb != NULL);
cb->Clear();
wxStringTokenizer tkz(
text,
wxExFindReplaceData::Get()->GetFieldSeparator());
while (tkz.HasMoreTokens())
{
cb->Append(tkz.GetNextToken());
}
if (cb->GetCount() > 0)
{
cb->SetValue(cb->GetString(0));
}
}
const wxString wxExComboBoxToString(
const wxComboBox* cb,
size_t max_items)
{
wxASSERT(cb != NULL);
wxString text = cb->GetValue();
switch (cb->FindString(
cb->GetValue(),
true)) // case sensitive
{
case 0:
text.clear();
// No change necessary, the string is already present as the first one.
for (size_t i = 0; i < cb->GetCount() && i < max_items; i++)
text += cb->GetString(i) + wxExFindReplaceData::Get()->GetFieldSeparator();
break;
case wxNOT_FOUND:
// Add the string, as it is not in the combo box, to the text,
// simply by appending all combobox items.
for (size_t i = 0; i < cb->GetCount() && i < max_items - 1; i++)
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb->GetString(i);
break;
default:
// Reorder. The new first element already present, just add all others.
for (size_t i = 0; i < cb->GetCount(); i++)
{
const wxString cb_element = cb->GetString(i);
if (cb_element != cb->GetValue())
text += wxExFindReplaceData::Get()->GetFieldSeparator() + cb_element;
}
}
return text;
}
#endif // wxUSE_GUI
const wxString wxExConfigFirstOf(const wxString& key)
{
const wxString value = wxConfigBase::Get()->Read(key);
return value.BeforeFirst(wxExFindReplaceData::Get()->GetFieldSeparator());
}
const wxString wxExEllipsed(const wxString& text, const wxString& control)
{
return text + "..." + (!control.empty() ? "\t" + control: wxString(wxEmptyString));
}
void wxExFindResult(
const wxString& find_text,
bool find_next,
bool recursive)
{
if (!recursive)
{
const wxString where = (find_next) ? _("bottom"): _("top");
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
_("Searching for") + " " + wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " +
_("hit") + " " + where);
#endif
}
else
{
wxBell();
#if wxUSE_STATUSBAR
wxExFrame::StatusText(
wxExQuoted(wxExSkipWhiteSpace(find_text)) + " " + _("not found"));
#endif
}
}
const wxString wxExGetEndOfText(
const wxString& text,
size_t max_chars)
{
wxString text_out(text);
if (text_out.length() > max_chars)
{
text_out = "..." + text_out.substr(text_out.length() - max_chars);
}
return text_out;
}
int wxExGetNumberOfLines(const wxString& text)
{
if (text.empty())
{
return 0;
}
else if (text.Find(wxUniChar('\r')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\r')) + 1;
}
else if (text.Find(wxUniChar('\n')) != wxNOT_FOUND)
{
return text.Freq(wxUniChar('\n')) + 1;
}
else
{
return 1;
}
}
int wxExGetLineNumberFromText(const wxString& text)
{
// Get text after :.
const size_t pos_char = text.rfind(":");
if (pos_char == wxString::npos)
{
return 0;
}
const wxString linenumber = text.substr(pos_char + 1);
long line;
if (linenumber.ToLong(&line))
{
return line;
}
else
{
return 0;
}
}
const wxString wxExGetWord(
wxString& text,
bool use_other_field_separators,
bool use_path_separator)
{
wxString field_separators = " \t";
if (use_other_field_separators) field_separators += ":";
if (use_path_separator) field_separators = wxFILE_SEP_PATH;
wxString token;
wxStringTokenizer tkz(text, field_separators);
if (tkz.HasMoreTokens()) token = tkz.GetNextToken();
text = tkz.GetString();
text.Trim(false);
return token;
}
bool wxExMatchesOneOf(const wxFileName& filename, const wxString& pattern)
{
if (pattern == "*") return true; // asterix matches always.
const wxString fullname_uppercase = filename.GetFullName().Upper();
wxStringTokenizer tokenizer(pattern.Upper(), ";");
while (tokenizer.HasMoreTokens())
{
if (fullname_uppercase.Matches(tokenizer.GetNextToken())) return true;
}
return false;
}
#if wxUSE_GUI
void wxExOpenFiles(
wxExFrame* frame,
const wxArrayString& files,
long file_flags,
int dir_flags)
{
// std::vector gives compile error.
for (size_t i = 0; i < files.GetCount(); i++)
{
wxString file = files[i]; // cannot be const because of file = later on
if (file.Contains("*") || file.Contains("?"))
{
wxExDirOpenFile dir(frame, wxGetCwd(), file, file_flags, dir_flags);
dir.FindFiles();
}
else
{
int line = 0;
if (!wxFileName(file).FileExists() && file.Contains(":"))
{
line = atoi(file.AfterFirst(':').c_str());
file = file.BeforeFirst(':');
}
frame->OpenFile(file, line, wxEmptyString, file_flags);
}
}
}
void wxExOpenFilesDialog(
wxExFrame* frame,
long style,
const wxString& wildcards,
bool ask_for_continue,
long file_flags,
int dir_flags)
{
wxExSTC* stc = frame->GetSTC();
wxArrayString files;
const wxString caption(_("Select Files"));
if (stc != NULL)
{
wxExFileDialog dlg(frame,
stc,
caption,
wildcards,
style);
if (ask_for_continue)
{
if (dlg.ShowModalIfChanged(true) == wxID_CANCEL) return;
}
else
{
if (dlg.ShowModal() == wxID_CANCEL) return;
}
dlg.GetPaths(files);
}
else
{
wxFileDialog dlg(frame,
caption,
wxEmptyString,
wxEmptyString,
wildcards,
style);
if (dlg.ShowModal() == wxID_CANCEL) return;
dlg.GetPaths(files);
}
wxExOpenFiles(frame, files, file_flags, dir_flags);
}
#endif // wxUSE_GUI
const wxString wxExPrintCaption(const wxFileName& filename)
{
if (filename.FileExists())
{
return filename.GetFullPath();
}
else
{
return _("Printout");
}
}
const wxString wxExPrintFooter()
{
return _("Page @PAGENUM@ of @PAGESCNT@");
}
const wxString wxExPrintHeader(const wxFileName& filename)
{
if (filename.FileExists())
{
return
wxExGetEndOfText(filename.GetFullPath(), 30) + " " +
filename.GetModificationTime().Format();
}
else
{
return _("Printed") + ": " + wxDateTime::Now().Format();
}
}
const wxString wxExQuoted(const wxString& text)
{
return "'" + text + "'";
}
const wxString wxExSkipWhiteSpace(const wxString& text, const wxString& replace_with)
{
wxString output = text;
wxRegEx("[ \t\n]+").ReplaceAll(&output, replace_with);
return output;
}
const wxString wxExTranslate(const wxString& text, int pageNum, int numPages)
{
wxString translation = text;
wxString num;
num.Printf("%i", pageNum);
translation.Replace("@PAGENUM@", num);
num.Printf("%i", numPages);
translation.Replace("@PAGESCNT@", num);
return translation;
}
<|endoftext|>
|
<commit_before>TFile *f;
void testMergeCont()
{
// Macro to test merging of containers.
TString tutdir = gROOT->GetTutorialsDir();
cout << "----->" << tutdir << endl;
gROOT->LoadMacro(tutdir+"/hsimple.C");
TList *list = GetCollection();
TList *inputs = new TList();
for (Int_t i=0; i<10; i++) {
inputs->AddAt(GetCollection(),0);
list->Merge(inputs);
inputs->Delete();
f->Close();
}
delete inputs;
TH1F *hpx = (TH1F*)(((TList*)list->At(1))->At(0));
printf("============================================\n");
printf("Total hpx: %d entries\n", hpx->GetEntries());
hpx->Draw();
list->Delete();
delete list;
}
TSeqCollection *GetCollection()
{
TObject *obj;
f = TFile::Open("hsimple.root");
if ( !f ) f = hsimple(1);
gROOT->cd();
TList *l0 = new TList();
TList *l01 = new TList();
TH1 *hpx = (TH1*)f->Get("hpx");
printf("Adding hpx: %d entries\n", hpx->GetEntries());
l01->Add(hpx);
TH1 *hpxpy = (TH1*)f->Get("hpxpy");
l01->Add(hpxpy);
TH1 *hprof = (TH1*)f->Get("hprof");
l0->Add(hprof);
l0->Add(l01);
return l0;
}
<commit_msg>Remove debug print<commit_after>TFile *f;
void testMergeCont()
{
// Macro to test merging of containers.
TString tutdir = gROOT->GetTutorialsDir();
gROOT->LoadMacro(tutdir+"/hsimple.C");
TList *list = GetCollection();
TList *inputs = new TList();
for (Int_t i=0; i<10; i++) {
inputs->AddAt(GetCollection(),0);
list->Merge(inputs);
inputs->Delete();
f->Close();
}
delete inputs;
TH1F *hpx = (TH1F*)(((TList*)list->At(1))->At(0));
printf("============================================\n");
printf("Total hpx: %d entries\n", hpx->GetEntries());
hpx->Draw();
list->Delete();
delete list;
}
TSeqCollection *GetCollection()
{
TObject *obj;
f = TFile::Open("hsimple.root");
if ( !f ) f = hsimple(1);
gROOT->cd();
TList *l0 = new TList();
TList *l01 = new TList();
TH1 *hpx = (TH1*)f->Get("hpx");
printf("Adding hpx: %d entries\n", hpx->GetEntries());
l01->Add(hpx);
TH1 *hpxpy = (TH1*)f->Get("hpxpy");
l01->Add(hpxpy);
TH1 *hprof = (TH1*)f->Get("hprof");
l0->Add(hprof);
l0->Add(l01);
return l0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLEventImportHelper.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:19:02 $
*
* 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_XMLEVENTIMPORTHELPER_HXX
#include "XMLEventImportHelper.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLERROR_HXX
#include "xmlerror.hxx"
#endif
using ::rtl::OUString;
using ::com::sun::star::xml::sax::XAttributeList;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
XMLEventImportHelper::XMLEventImportHelper() :
aFactoryMap(),
pEventNameMap(new NameMap()),
aEventNameMapList()
{
}
XMLEventImportHelper::~XMLEventImportHelper()
{
// delete factories
FactoryMap::iterator aEnd = aFactoryMap.end();
for(FactoryMap::iterator aIter = aFactoryMap.begin();
aIter != aEnd;
aIter++ )
{
delete aIter->second;
}
aFactoryMap.clear();
// delete name map
delete pEventNameMap;
}
void XMLEventImportHelper::RegisterFactory(
const OUString& rLanguage,
XMLEventContextFactory* pFactory )
{
DBG_ASSERT(pFactory != NULL, "I need a factory.");
if (NULL != pFactory)
{
aFactoryMap[rLanguage] = pFactory;
}
}
void XMLEventImportHelper::AddTranslationTable(
const XMLEventNameTranslation* pTransTable )
{
if (NULL != pTransTable)
{
// put translation table into map
for(const XMLEventNameTranslation* pTrans = pTransTable;
pTrans->sAPIName != NULL;
pTrans++)
{
XMLEventName aName( pTrans->nPrefix, pTrans->sXMLName );
// check for conflicting entries
DBG_ASSERT(pEventNameMap->find(aName) == pEventNameMap->end(),
"conflicting event translations");
// assign new translation
(*pEventNameMap)[aName] =
OUString::createFromAscii(pTrans->sAPIName);
}
}
// else? ignore!
}
void XMLEventImportHelper::PushTranslationTable()
{
// save old map and install new one
aEventNameMapList.push_back(pEventNameMap);
pEventNameMap = new NameMap();
}
void XMLEventImportHelper::PopTranslationTable()
{
DBG_ASSERT(aEventNameMapList.size() > 0,
"no translation tables left to pop");
if (aEventNameMapList.size() > 0)
{
// delete current and install old map
delete pEventNameMap;
pEventNameMap = aEventNameMapList.back();
aEventNameMapList.pop_back();
}
}
SvXMLImportContext* XMLEventImportHelper::CreateContext(
SvXMLImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference<XAttributeList> & xAttrList,
XMLEventsImportContext* rEvents,
const OUString& rXmlEventName,
const OUString& rLanguage)
{
SvXMLImportContext* pContext = NULL;
// translate event name form xml to api
OUString sMacroName;
sal_uInt16 nMacroPrefix =
rImport.GetNamespaceMap().GetKeyByAttrName( rXmlEventName,
&sMacroName );
XMLEventName aEventName( nMacroPrefix, sMacroName );
NameMap::iterator aNameIter = pEventNameMap->find(aEventName);
if (aNameIter != pEventNameMap->end())
{
OUString aScriptLanguage;
sal_uInt16 nScriptPrefix = rImport.GetNamespaceMap().
GetKeyByAttrName( rLanguage, &aScriptLanguage );
if( XML_NAMESPACE_OOO != nScriptPrefix )
aScriptLanguage = rLanguage ;
// check for factory
FactoryMap::iterator aFactoryIterator =
aFactoryMap.find(aScriptLanguage);
if (aFactoryIterator != aFactoryMap.end())
{
// delegate to factory
pContext = aFactoryIterator->second->CreateContext(
rImport, nPrefix, rLocalName, xAttrList,
rEvents, aNameIter->second, aScriptLanguage);
}
}
// default context (if no context was created above)
if( NULL == pContext )
{
pContext = new SvXMLImportContext(rImport, nPrefix, rLocalName);
Sequence<OUString> aMsgParams(2);
aMsgParams[0] = rXmlEventName;
aMsgParams[1] = rLanguage;
rImport.SetError(XMLERROR_FLAG_ERROR | XMLERROR_ILLEGAL_EVENT,
aMsgParams);
}
return pContext;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.160); FILE MERGED 2006/09/01 17:59:43 kaib 1.8.160.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLEventImportHelper.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 10:40: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_XMLEVENTIMPORTHELPER_HXX
#include "XMLEventImportHelper.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLERROR_HXX
#include "xmlerror.hxx"
#endif
using ::rtl::OUString;
using ::com::sun::star::xml::sax::XAttributeList;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
XMLEventImportHelper::XMLEventImportHelper() :
aFactoryMap(),
pEventNameMap(new NameMap()),
aEventNameMapList()
{
}
XMLEventImportHelper::~XMLEventImportHelper()
{
// delete factories
FactoryMap::iterator aEnd = aFactoryMap.end();
for(FactoryMap::iterator aIter = aFactoryMap.begin();
aIter != aEnd;
aIter++ )
{
delete aIter->second;
}
aFactoryMap.clear();
// delete name map
delete pEventNameMap;
}
void XMLEventImportHelper::RegisterFactory(
const OUString& rLanguage,
XMLEventContextFactory* pFactory )
{
DBG_ASSERT(pFactory != NULL, "I need a factory.");
if (NULL != pFactory)
{
aFactoryMap[rLanguage] = pFactory;
}
}
void XMLEventImportHelper::AddTranslationTable(
const XMLEventNameTranslation* pTransTable )
{
if (NULL != pTransTable)
{
// put translation table into map
for(const XMLEventNameTranslation* pTrans = pTransTable;
pTrans->sAPIName != NULL;
pTrans++)
{
XMLEventName aName( pTrans->nPrefix, pTrans->sXMLName );
// check for conflicting entries
DBG_ASSERT(pEventNameMap->find(aName) == pEventNameMap->end(),
"conflicting event translations");
// assign new translation
(*pEventNameMap)[aName] =
OUString::createFromAscii(pTrans->sAPIName);
}
}
// else? ignore!
}
void XMLEventImportHelper::PushTranslationTable()
{
// save old map and install new one
aEventNameMapList.push_back(pEventNameMap);
pEventNameMap = new NameMap();
}
void XMLEventImportHelper::PopTranslationTable()
{
DBG_ASSERT(aEventNameMapList.size() > 0,
"no translation tables left to pop");
if (aEventNameMapList.size() > 0)
{
// delete current and install old map
delete pEventNameMap;
pEventNameMap = aEventNameMapList.back();
aEventNameMapList.pop_back();
}
}
SvXMLImportContext* XMLEventImportHelper::CreateContext(
SvXMLImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference<XAttributeList> & xAttrList,
XMLEventsImportContext* rEvents,
const OUString& rXmlEventName,
const OUString& rLanguage)
{
SvXMLImportContext* pContext = NULL;
// translate event name form xml to api
OUString sMacroName;
sal_uInt16 nMacroPrefix =
rImport.GetNamespaceMap().GetKeyByAttrName( rXmlEventName,
&sMacroName );
XMLEventName aEventName( nMacroPrefix, sMacroName );
NameMap::iterator aNameIter = pEventNameMap->find(aEventName);
if (aNameIter != pEventNameMap->end())
{
OUString aScriptLanguage;
sal_uInt16 nScriptPrefix = rImport.GetNamespaceMap().
GetKeyByAttrName( rLanguage, &aScriptLanguage );
if( XML_NAMESPACE_OOO != nScriptPrefix )
aScriptLanguage = rLanguage ;
// check for factory
FactoryMap::iterator aFactoryIterator =
aFactoryMap.find(aScriptLanguage);
if (aFactoryIterator != aFactoryMap.end())
{
// delegate to factory
pContext = aFactoryIterator->second->CreateContext(
rImport, nPrefix, rLocalName, xAttrList,
rEvents, aNameIter->second, aScriptLanguage);
}
}
// default context (if no context was created above)
if( NULL == pContext )
{
pContext = new SvXMLImportContext(rImport, nPrefix, rLocalName);
Sequence<OUString> aMsgParams(2);
aMsgParams[0] = rXmlEventName;
aMsgParams[1] = rLanguage;
rImport.SetError(XMLERROR_FLAG_ERROR | XMLERROR_ILLEGAL_EVENT,
aMsgParams);
}
return pContext;
}
<|endoftext|>
|
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.
#include <gtest/gtest.h>
#include <quic/server/SlidingWindowRateLimiter.h>
using namespace std::chrono_literals;
using namespace quic;
TEST(SlidingWindowRateLimiterTest, BasicExceedsCount) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
for (int i = 0; i < 10; i++) {
EXPECT_FALSE(limiter.check(now));
now += 1s;
}
EXPECT_TRUE(limiter.check(now));
}
TEST(SlidingWindowRateLimiterTest, SlidingNoExceedsCount) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
auto prevStart = now;
for (int i = 0; i < 9; i++) {
EXPECT_FALSE(limiter.check(now));
now += 1s;
}
EXPECT_FALSE(limiter.check(prevStart + 60s));
}
TEST(SlidingWindowRateLimiterTest, SlidingExceedsCount) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
auto prevStart = now;
for (int i = 0; i < 10; i++) {
limiter.check(now);
now += 1s;
}
// This makes the current window start at 60s, with one check at 7s.
// 10/60 * 53 = 8.83
// 8.83 + 1 !> 10
EXPECT_FALSE(limiter.check(prevStart + 67s));
EXPECT_FALSE(limiter.check(prevStart + 68s));
for (int i = 0; i < 8; i++) {
EXPECT_FALSE(limiter.check(prevStart + 119s));
}
}
TEST(SlidingWindowRateLimiterTest, QuiescentWindowNoExceeds) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
auto prevStart = now;
for (int i = 0; i < 10; i++) {
limiter.check(now);
now += 1s;
}
now = prevStart + 120s;
for (int i = 0; i < 10; i++) {
EXPECT_FALSE(limiter.check(now));
now += 1s;
}
}
<commit_msg>Remove dead includes in quic<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.
#include <gtest/gtest.h>
#include <quic/server/SlidingWindowRateLimiter.h>
using namespace quic;
TEST(SlidingWindowRateLimiterTest, BasicExceedsCount) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
for (int i = 0; i < 10; i++) {
EXPECT_FALSE(limiter.check(now));
now += 1s;
}
EXPECT_TRUE(limiter.check(now));
}
TEST(SlidingWindowRateLimiterTest, SlidingNoExceedsCount) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
auto prevStart = now;
for (int i = 0; i < 9; i++) {
EXPECT_FALSE(limiter.check(now));
now += 1s;
}
EXPECT_FALSE(limiter.check(prevStart + 60s));
}
TEST(SlidingWindowRateLimiterTest, SlidingExceedsCount) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
auto prevStart = now;
for (int i = 0; i < 10; i++) {
limiter.check(now);
now += 1s;
}
// This makes the current window start at 60s, with one check at 7s.
// 10/60 * 53 = 8.83
// 8.83 + 1 !> 10
EXPECT_FALSE(limiter.check(prevStart + 67s));
EXPECT_FALSE(limiter.check(prevStart + 68s));
for (int i = 0; i < 8; i++) {
EXPECT_FALSE(limiter.check(prevStart + 119s));
}
}
TEST(SlidingWindowRateLimiterTest, QuiescentWindowNoExceeds) {
SlidingWindowRateLimiter limiter(10, 60s);
auto now = Clock::now();
auto prevStart = now;
for (int i = 0; i < 10; i++) {
limiter.check(now);
now += 1s;
}
now = prevStart + 120s;
for (int i = 0; i < 10; i++) {
EXPECT_FALSE(limiter.check(now));
now += 1s;
}
}
<|endoftext|>
|
<commit_before>๏ปฟ/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include "office_annotation.h"
#include <xml/xmlchar.h>
#include <xml/attributes.h>
#include <xml/utils.h>
#include "serialize_elements.h"
#include <odf/odf_document.h>
#include "odfcontext.h"
#include "draw_common.h"
#include "calcs_styles.h"
#include "../docx/xlsx_utils.h"
namespace cpdoccore {
using namespace odf_types;
namespace odf_reader {
// dc:date
/////////////////////////////////////////////
const wchar_t * dc_date::ns = L"dc";
const wchar_t * dc_date::name = L"date";
void dc_date::add_text(const std::wstring & Text)
{
content_ = Text;
}
// dc:creator
///////////////////////////////////////////
const wchar_t * dc_creator::ns = L"dc";
const wchar_t * dc_creator::name = L"creator";
void dc_creator::add_text(const std::wstring & Text)
{
content_ = Text;
}
//-------------------------------------------------------------------------
void office_annotation_attr::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
CP_APPLY_ATTR(L"draw:style-name", draw_style_name_);
CP_APPLY_ATTR(L"draw:text-style-name", draw_text_style_name_);
CP_APPLY_ATTR(L"draw:caption-point-x", caption_point_x_);
CP_APPLY_ATTR(L"draw:caption-point-x", caption_point_y_);
CP_APPLY_ATTR(L"svg:y", svg_y_);
CP_APPLY_ATTR(L"svg:x", svg_x_);
CP_APPLY_ATTR(L"svg:width", svg_width_);
CP_APPLY_ATTR(L"svg:height", svg_height_);
CP_APPLY_ATTR(L"office:display",display_);
}
//-------------------------------------------------------------------------
const wchar_t * office_annotation_end::ns = L"office";
const wchar_t * office_annotation_end::name = L"annotation-end";
void office_annotation_end::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
CP_APPLY_ATTR(L"office:name", office_name_, std::wstring(L""));
}
void office_annotation_end::docx_convert(oox::docx_conversion_context & Context)
{
Context.get_comments_context().end_comment(office_name_);
}
//-------------------------------------------------------------------------
const wchar_t * office_annotation::ns = L"office";
const wchar_t * office_annotation::name = L"annotation";
void office_annotation::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
CP_APPLY_ATTR(L"office:name", office_name_);
attr_.add_attributes(Attributes);
}
void office_annotation::add_child_element( xml::sax * Reader, const std::wstring & Ns, const std::wstring & Name)
{
if (Ns==L"dc" && Name == L"date")
{
CP_CREATE_ELEMENT(dc_date_);
}
else if (Ns==L"dc" && Name == L"creator")
{
CP_CREATE_ELEMENT(dc_creator_);
}
else
{
CP_CREATE_ELEMENT(content_);
}
}
void office_annotation::docx_convert(oox::docx_conversion_context & Context)
{
std::wstring date;
std::wstring author;
if (dc_date_)
{
date = xml::utils::replace_text_to_xml(dynamic_cast<dc_date * >(dc_date_.get())->content_);
}
if (dc_creator_)
{
author = xml::utils::replace_text_to_xml(dynamic_cast<dc_creator * >(dc_creator_.get())->content_);
}
////////////////////////////////////////
oox::StreamsManPtr prev = Context.get_stream_man();
std::wstringstream temp_stream(Context.get_drawing_context().get_text_stream_frame());
Context.set_stream_man( boost::shared_ptr<oox::streams_man>( new oox::streams_man(temp_stream) ));
bool runState = Context.get_run_state();
Context.set_run_state(false);
bool pState = Context.get_paragraph_state();
Context.set_paragraph_state(false);
Context.start_comment_content();
for (size_t i = 0; i < content_.size(); i++)
{
content_[i]->docx_convert(Context);
}
Context.end_comment_content();
std::wstring content = temp_stream.str();
Context.set_run_state(runState);
Context.set_paragraph_state(pState);
Context.set_stream_man(prev);
Context.dump_hyperlinks(Context.get_comments_context().get_rels(), oox::comment_place);
Context.get_mediaitems()->dump_rels(Context.get_comments_context().get_rels(), oox::comment_place);
Context.get_comments_context().start_comment(content, author, date, office_name_);//content, date, author
}
void office_annotation::xlsx_convert(oox::xlsx_conversion_context & Context)
{
const _CP_OPT(length) svg_widthVal = attr_.svg_width_;
const double width_cm = svg_widthVal.get_value_or(length(0)).get_value_unit(length::cm);
const double width_pt = svg_widthVal.get_value_or(length(0)).get_value_unit(length::pt);
const _CP_OPT(length) svg_heightVal =attr_.svg_height_;
const double height_cm = svg_heightVal.get_value_or(length(0)).get_value_unit(length::cm);
const double height_pt = svg_heightVal.get_value_or(length(0)).get_value_unit(length::pt);
const double x_pt = attr_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt);
const double y_pt = attr_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt);
//-----------------------------------------------
std::wstring date;
std::wstring author;
if (dc_date_)
{
date = xml::utils::replace_text_to_xml(dynamic_cast<dc_date * >(dc_date_.get())->content_);
}
if (dc_creator_)
{
author = xml::utils::replace_text_to_xml(dynamic_cast<dc_creator * >(dc_creator_.get())->content_);
}
int col = Context.current_table_column(); if (col < 0) col = 0;
int row = Context.current_table_row(); if (row < 0) row = 0;
std::wstring ref = oox::getCellAddress(col, row);
//-----------------------------------------------
Context.get_comments_context().start_comment(ref);
if (attr_.display_)
{
}
Context.get_text_context().start_comment_content();
for (size_t i = 0; i < content_.size(); i++)//ัะตะบัั + ัะตะบััะพะฒัะน ััะธะปั
{
content_[i]->xlsx_convert(Context);
}
Context.get_comments_context().add_author(author);
Context.get_comments_context().add_content(Context.get_text_context().end_comment_content());
//----------- drawing part ---------------
Context.get_drawing_context().start_comment(col, row);
Context.get_drawing_context().start_drawing(L"");
Context.get_drawing_context().set_rect(width_pt, height_pt, x_pt, y_pt);
if (attr_.display_)
{
Context.get_drawing_context().set_property(_property(L"visibly", attr_.display_.get()));
}
if (attr_.draw_style_name_)
{
std::vector<const odf_reader::style_instance *> instances;
odf_reader::style_instance* styleInst =
Context.root()->odf_context().styleContainer().style_by_name(*attr_.draw_style_name_, odf_types::style_family::Graphic, false/*Context.process_headers_footers_*/);
if (styleInst)
{
style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic);
if (defaultStyle)instances.push_back(defaultStyle);
instances.push_back(styleInst);
}
graphic_format_properties properties = calc_graphic_properties_content(instances);
//-----------------------------------------------
properties.apply_to(Context.get_drawing_context().get_properties());
oox::_oox_fill fill;
Compute_GraphicFill(properties.common_draw_fill_attlist_, properties.style_background_image_,
Context.root()->odf_context().drawStyles(), fill);
Context.get_drawing_context().set_fill(fill);
}
//-----------------------------------------------
std::vector<const odf_reader::style_instance *> instances;
style_instance* styleInst = Context.root()->odf_context().styleContainer().style_by_name(
attr_.draw_style_name_.get_value_or(L""), odf_types::style_family::Graphic, false/*Context.process_headers_footers_*/);
if (styleInst)
{
style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic);
if (defaultStyle)instances.push_back(defaultStyle);
instances.push_back(styleInst);
}
graphic_format_properties graphicProperties = calc_graphic_properties_content(instances);
const std::wstring textStyleName = attr_.draw_text_style_name_.get_value_or(L"");
Context.get_drawing_context().end_drawing();
Context.get_drawing_context().end_comment();
Context.get_drawing_context().clear();
//-----------------------------------------------
Context.get_comments_context().end_comment();
}
// officeooo:annotation
//////////////////////////////////////////////////////////////////////////////////////////////////
const wchar_t * officeooo_annotation::ns = L"officeooo";
const wchar_t * officeooo_annotation::name = L"annotation";
void officeooo_annotation::add_child_element( xml::sax * Reader, const std::wstring & Ns, const std::wstring & Name)
{
if (Ns==L"dc" && Name == L"date")
{
CP_CREATE_ELEMENT(dc_date_);
}
else if (Ns==L"dc" && Name == L"creator")
{
CP_CREATE_ELEMENT(dc_creator_);
}
else
{
CP_CREATE_ELEMENT(content_);
}
}
void officeooo_annotation::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
attr_.add_attributes(Attributes);
}
void officeooo_annotation::pptx_convert(oox::pptx_conversion_context & Context)
{
const double x = 8 * attr_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt);
const double y = 8 * attr_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt);
/////////////////////////////////
std::wstring date;
std::wstring author;
std::pair<int,int> id_idx;
if (dc_date_)
{
date = xml::utils::replace_text_to_xml(dynamic_cast<dc_date * >(dc_date_.get())->content_);
}
if (dc_creator_)
{
author = xml::utils::replace_text_to_xml(dynamic_cast<dc_creator * >(dc_creator_.get())->content_);
}
id_idx = Context.add_author_comments(author);
Context.get_comments_context().start_comment(x, y, id_idx.first, id_idx.second);//author & idx (uniq number for author
Context.get_text_context().start_comment_content();
for (size_t i = 0; i < content_.size(); i++)//ัะตะบัั + ัะตะบััะพะฒัะน ััะธะปั
{
content_[i]->pptx_convert(Context);
}
Context.get_comments_context().add_date(date);
Context.get_comments_context().add_content(Context.get_text_context().end_comment_content());
//////////////////////////////////////////////////////////////////
/// ะะฑัะฐะฑะฐััะฒะฐะตะผ ััะธะปั draw
std::vector<const odf_reader::style_instance *> instances;
style_instance* styleInst = Context.root()->odf_context().styleContainer().style_by_name(
attr_.draw_style_name_.get_value_or(L""), odf_types::style_family::Graphic,false/*Context.process_headers_footers_*/);
if (styleInst)
{
style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic);
if (defaultStyle)instances.push_back(defaultStyle);
instances.push_back(styleInst);
}
graphic_format_properties graphicProperties = calc_graphic_properties_content(instances);
graphicProperties.apply_to(Context.get_comments_context().get_draw_properties());
const std::wstring textStyleName = attr_.draw_text_style_name_.get_value_or(L"");
Context.get_comments_context().end_comment();
}
}
}
<commit_msg>fix bug #46751<commit_after>๏ปฟ/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include "office_annotation.h"
#include <xml/xmlchar.h>
#include <xml/attributes.h>
#include <xml/utils.h>
#include "serialize_elements.h"
#include <odf/odf_document.h>
#include "odfcontext.h"
#include "draw_common.h"
#include "calcs_styles.h"
#include "../docx/xlsx_utils.h"
namespace cpdoccore {
using namespace odf_types;
namespace odf_reader {
// dc:date
/////////////////////////////////////////////
const wchar_t * dc_date::ns = L"dc";
const wchar_t * dc_date::name = L"date";
void dc_date::add_text(const std::wstring & Text)
{
content_ = Text;
}
// dc:creator
///////////////////////////////////////////
const wchar_t * dc_creator::ns = L"dc";
const wchar_t * dc_creator::name = L"creator";
void dc_creator::add_text(const std::wstring & Text)
{
content_ = Text;
}
//-------------------------------------------------------------------------
void office_annotation_attr::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
CP_APPLY_ATTR(L"draw:style-name", draw_style_name_);
CP_APPLY_ATTR(L"draw:text-style-name", draw_text_style_name_);
CP_APPLY_ATTR(L"draw:caption-point-x", caption_point_x_);
CP_APPLY_ATTR(L"draw:caption-point-x", caption_point_y_);
CP_APPLY_ATTR(L"svg:y", svg_y_);
CP_APPLY_ATTR(L"svg:x", svg_x_);
CP_APPLY_ATTR(L"svg:width", svg_width_);
CP_APPLY_ATTR(L"svg:height", svg_height_);
CP_APPLY_ATTR(L"office:display",display_);
}
//-------------------------------------------------------------------------
const wchar_t * office_annotation_end::ns = L"office";
const wchar_t * office_annotation_end::name = L"annotation-end";
void office_annotation_end::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
CP_APPLY_ATTR(L"office:name", office_name_, std::wstring(L""));
}
void office_annotation_end::docx_convert(oox::docx_conversion_context & Context)
{
Context.get_comments_context().end_comment(office_name_);
}
//-------------------------------------------------------------------------
const wchar_t * office_annotation::ns = L"office";
const wchar_t * office_annotation::name = L"annotation";
void office_annotation::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
CP_APPLY_ATTR(L"office:name", office_name_);
attr_.add_attributes(Attributes);
}
void office_annotation::add_child_element( xml::sax * Reader, const std::wstring & Ns, const std::wstring & Name)
{
if (Ns==L"dc" && Name == L"date")
{
CP_CREATE_ELEMENT(dc_date_);
}
else if (Ns==L"dc" && Name == L"creator")
{
CP_CREATE_ELEMENT(dc_creator_);
}
else
{
CP_CREATE_ELEMENT(content_);
}
}
void office_annotation::docx_convert(oox::docx_conversion_context & Context)
{
std::wstring date;
std::wstring author;
if (dc_date_)
{
date = xml::utils::replace_text_to_xml(dynamic_cast<dc_date * >(dc_date_.get())->content_);
}
if (dc_creator_)
{
author = xml::utils::replace_text_to_xml(dynamic_cast<dc_creator * >(dc_creator_.get())->content_);
}
////////////////////////////////////////
oox::StreamsManPtr prev = Context.get_stream_man();
std::wstringstream temp_stream(Context.get_drawing_context().get_text_stream_frame());
Context.set_stream_man( boost::shared_ptr<oox::streams_man>( new oox::streams_man(temp_stream) ));
bool runState = Context.get_run_state();
Context.set_run_state(false);
bool pState = Context.get_paragraph_state();
Context.set_paragraph_state(false);
Context.start_comment_content();
for (size_t i = 0; i < content_.size(); i++)
{
content_[i]->docx_convert(Context);
}
Context.end_comment_content();
std::wstring content = temp_stream.str();
Context.set_run_state(runState);
Context.set_paragraph_state(pState);
Context.set_stream_man(prev);
Context.dump_hyperlinks(Context.get_comments_context().get_rels(), oox::comment_place);
Context.get_mediaitems()->dump_rels(Context.get_comments_context().get_rels(), oox::comment_place);
Context.get_comments_context().start_comment(content, author, date, office_name_);//content, date, author
}
void office_annotation::xlsx_convert(oox::xlsx_conversion_context & Context)
{
const _CP_OPT(length) svg_widthVal = attr_.svg_width_;
const double width_cm = svg_widthVal.get_value_or(length(0)).get_value_unit(length::cm);
const double width_pt = svg_widthVal.get_value_or(length(0)).get_value_unit(length::pt);
const _CP_OPT(length) svg_heightVal =attr_.svg_height_;
const double height_cm = svg_heightVal.get_value_or(length(0)).get_value_unit(length::cm);
const double height_pt = svg_heightVal.get_value_or(length(0)).get_value_unit(length::pt);
const double x_pt = attr_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt);
const double y_pt = attr_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt);
//-----------------------------------------------
std::wstring date;
std::wstring author;
if (dc_date_)
{
date = xml::utils::replace_text_to_xml(dynamic_cast<dc_date * >(dc_date_.get())->content_);
}
if (dc_creator_)
{
author = xml::utils::replace_text_to_xml(dynamic_cast<dc_creator * >(dc_creator_.get())->content_);
}
int col = Context.current_table_column() + 1; if (col < 0) col = 0;
int row = Context.current_table_row(); if (row < 0) row = 0;
std::wstring ref = oox::getCellAddress(col, row);
//-----------------------------------------------
Context.get_comments_context().start_comment(ref);
if (attr_.display_)
{
}
Context.get_text_context().start_comment_content();
for (size_t i = 0; i < content_.size(); i++)//ัะตะบัั + ัะตะบััะพะฒัะน ััะธะปั
{
content_[i]->xlsx_convert(Context);
}
Context.get_comments_context().add_author(author);
Context.get_comments_context().add_content(Context.get_text_context().end_comment_content());
//----------- drawing part ---------------
Context.get_drawing_context().start_comment(col, row);
Context.get_drawing_context().start_drawing(L"");
Context.get_drawing_context().set_rect(width_pt, height_pt, x_pt, y_pt);
if (attr_.display_)
{
Context.get_drawing_context().set_property(_property(L"visibly", attr_.display_.get()));
}
if (attr_.draw_style_name_)
{
std::vector<const odf_reader::style_instance *> instances;
odf_reader::style_instance* styleInst =
Context.root()->odf_context().styleContainer().style_by_name(*attr_.draw_style_name_, odf_types::style_family::Graphic, false/*Context.process_headers_footers_*/);
if (styleInst)
{
style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic);
if (defaultStyle)instances.push_back(defaultStyle);
instances.push_back(styleInst);
}
graphic_format_properties properties = calc_graphic_properties_content(instances);
//-----------------------------------------------
properties.apply_to(Context.get_drawing_context().get_properties());
oox::_oox_fill fill;
Compute_GraphicFill(properties.common_draw_fill_attlist_, properties.style_background_image_,
Context.root()->odf_context().drawStyles(), fill);
Context.get_drawing_context().set_fill(fill);
}
//-----------------------------------------------
std::vector<const odf_reader::style_instance *> instances;
style_instance* styleInst = Context.root()->odf_context().styleContainer().style_by_name(
attr_.draw_style_name_.get_value_or(L""), odf_types::style_family::Graphic, false/*Context.process_headers_footers_*/);
if (styleInst)
{
style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic);
if (defaultStyle)instances.push_back(defaultStyle);
instances.push_back(styleInst);
}
graphic_format_properties graphicProperties = calc_graphic_properties_content(instances);
const std::wstring textStyleName = attr_.draw_text_style_name_.get_value_or(L"");
Context.get_drawing_context().end_drawing();
Context.get_drawing_context().end_comment();
Context.get_drawing_context().clear();
//-----------------------------------------------
Context.get_comments_context().end_comment();
}
// officeooo:annotation
//////////////////////////////////////////////////////////////////////////////////////////////////
const wchar_t * officeooo_annotation::ns = L"officeooo";
const wchar_t * officeooo_annotation::name = L"annotation";
void officeooo_annotation::add_child_element( xml::sax * Reader, const std::wstring & Ns, const std::wstring & Name)
{
if (Ns==L"dc" && Name == L"date")
{
CP_CREATE_ELEMENT(dc_date_);
}
else if (Ns==L"dc" && Name == L"creator")
{
CP_CREATE_ELEMENT(dc_creator_);
}
else
{
CP_CREATE_ELEMENT(content_);
}
}
void officeooo_annotation::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
attr_.add_attributes(Attributes);
}
void officeooo_annotation::pptx_convert(oox::pptx_conversion_context & Context)
{
const double x = 8 * attr_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt);
const double y = 8 * attr_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt);
/////////////////////////////////
std::wstring date;
std::wstring author;
std::pair<int,int> id_idx;
if (dc_date_)
{
date = xml::utils::replace_text_to_xml(dynamic_cast<dc_date * >(dc_date_.get())->content_);
}
if (dc_creator_)
{
author = xml::utils::replace_text_to_xml(dynamic_cast<dc_creator * >(dc_creator_.get())->content_);
}
id_idx = Context.add_author_comments(author);
Context.get_comments_context().start_comment(x, y, id_idx.first, id_idx.second);//author & idx (uniq number for author
Context.get_text_context().start_comment_content();
for (size_t i = 0; i < content_.size(); i++)//ัะตะบัั + ัะตะบััะพะฒัะน ััะธะปั
{
content_[i]->pptx_convert(Context);
}
Context.get_comments_context().add_date(date);
Context.get_comments_context().add_content(Context.get_text_context().end_comment_content());
//////////////////////////////////////////////////////////////////
/// ะะฑัะฐะฑะฐััะฒะฐะตะผ ััะธะปั draw
std::vector<const odf_reader::style_instance *> instances;
style_instance* styleInst = Context.root()->odf_context().styleContainer().style_by_name(
attr_.draw_style_name_.get_value_or(L""), odf_types::style_family::Graphic,false/*Context.process_headers_footers_*/);
if (styleInst)
{
style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic);
if (defaultStyle)instances.push_back(defaultStyle);
instances.push_back(styleInst);
}
graphic_format_properties graphicProperties = calc_graphic_properties_content(instances);
graphicProperties.apply_to(Context.get_comments_context().get_draw_properties());
const std::wstring textStyleName = attr_.draw_text_style_name_.get_value_or(L"");
Context.get_comments_context().end_comment();
}
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Sphere_INCLUDE_ONCE
#define Sphere_INCLUDE_ONCE
#include <vlCore/AABB.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// Sphere
//-----------------------------------------------------------------------------
/**
* The Sphere class defines a sphere using a center and a radius using vl::Real precision.
*/
class Sphere
{
public:
//! Constructor.
Sphere(): mRadius(-1) { }
//! Constructor.
Sphere(const vec3& center, Real radius): mCenter(center), mRadius(radius) {}
//! Constructor.
Sphere(const AABB& aabb) { *this = aabb; }
void setNull() { mRadius =-1.0f; mCenter = vec3(0,0,0); }
void setPoint() { mRadius = 0.0f; /*mCenter = vec3(0,0,0);*/ }
bool isNull() const { return mRadius < 0.0f; }
bool isPoint() const { return mRadius == 0.0f; }
void setCenter(const vec3& center) { mCenter = center; }
const vec3& center() const { return mCenter; }
void setRadius( Real radius ) { mRadius = radius; }
Real radius() const { return mRadius; }
bool includes(const Sphere& other) const
{
if (isNull())
return false;
else
if (other.isNull())
return true;
else
{
Real distance = (center() - other.center()).length();
return radius() >= distance + other.radius();
}
}
Sphere& operator=(const AABB& aabb)
{
// center the sphere on the aabb center
mCenter = aabb.center();
// half of the maximum diagonal
mRadius = (aabb.minCorner() - aabb.maxCorner()).length() / (Real)2.0;
return *this;
}
Sphere operator+(const Sphere& other)
{
Sphere t = *this;
return t += other;
}
const Sphere& operator+=(const Sphere& other)
{
if (this->isNull())
*this = other;
else
if (other.includes(*this))
{
*this = other;
}
else
if (!other.isNull() && !this->includes(other) )
{
vec3 v = other.center() - this->center();
if (v.isNull())
{
// the center remains the same
// sets the maximum radius
setRadius( radius() > other.radius() ? radius() : other.radius() );
}
else
{
v.normalize();
vec3 p0 = this->center() - v * this->radius();
vec3 p1 = other.center() + v * other.radius();
setCenter( (p0 + p1)*(Real)0.5 );
setRadius( (p0 - p1).length()*(Real)0.5 );
}
}
return *this;
}
void transformed(Sphere& sphere, const mat4& mat) const
{
sphere.setNull();
if ( !isNull() )
{
sphere.mCenter = mat * center();
// vec3 p = center() + vec3( (Real)0.577350269189625840, (Real)0.577350269189625840, (Real)0.577350269189625840 ) * radius();
// p = mat * p;
// p = p - sphere.center();
// sphere.setRadius(p.length());
vec3 p0 = center() + vec3(radius(),0,0);
vec3 p1 = center() + vec3(0,radius(),0);
vec3 p2 = center() + vec3(0,0,radius());
p0 = mat * p0;
p1 = mat * p1;
p2 = mat * p2;
Real d0 = (p0 - sphere.mCenter).lengthSquared();
Real d1 = (p1 - sphere.mCenter).lengthSquared();
Real d2 = (p2 - sphere.mCenter).lengthSquared();
sphere.mRadius = d0>d1 ? (d0>d2?d0:d2) : (d1>d2?d1:d2);
sphere.mRadius = ::sqrt(sphere.mRadius);
}
}
Sphere transformed(const mat4& mat) const
{
Sphere sphere;
transformed(sphere, mat);
return sphere;
}
protected:
vec3 mCenter;
Real mRadius;
};
}
#endif
<commit_msg>Sphere class: added missing operator==() and operator!=(); properly handle operator=(AABB) with null AABB.<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Sphere_INCLUDE_ONCE
#define Sphere_INCLUDE_ONCE
#include <vlCore/AABB.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// Sphere
//-----------------------------------------------------------------------------
/**
* The Sphere class defines a sphere using a center and a radius using vl::Real precision.
*/
class Sphere
{
public:
//! Constructor.
Sphere(): mRadius(-1) { }
//! Constructor.
Sphere(const vec3& center, Real radius): mCenter(center), mRadius(radius) {}
//! Constructor.
Sphere(const AABB& aabb) { *this = aabb; }
void setNull() { mRadius =-1.0f; mCenter = vec3(0,0,0); }
void setPoint() { mRadius = 0.0f; /*mCenter = vec3(0,0,0);*/ }
bool isNull() const { return mRadius < 0.0f; }
bool isPoint() const { return mRadius == 0.0f; }
void setCenter(const vec3& center) { mCenter = center; }
const vec3& center() const { return mCenter; }
void setRadius( Real radius ) { mRadius = radius; }
Real radius() const { return mRadius; }
bool includes(const Sphere& other) const
{
if (isNull())
return false;
else
if (other.isNull())
return true;
else
{
Real distance = (center() - other.center()).length();
return radius() >= distance + other.radius();
}
}
bool operator==(const Sphere& other) const
{
return mCenter == other.mCenter && mRadius == other.mRadius;
}
bool operator!=(const Sphere& other) const
{
return !operator==(other);
}
Sphere& operator=(const AABB& aabb)
{
if (aabb.isNull())
setNull();
else
{
// center the sphere on the aabb center
mCenter = aabb.center();
// half of the maximum diagonal
mRadius = (aabb.minCorner() - aabb.maxCorner()).length() / (Real)2.0;
}
return *this;
}
Sphere operator+(const Sphere& other)
{
Sphere t = *this;
return t += other;
}
const Sphere& operator+=(const Sphere& other)
{
if (this->isNull())
*this = other;
else
if (other.includes(*this))
{
*this = other;
}
else
if (!other.isNull() && !this->includes(other) )
{
vec3 v = other.center() - this->center();
if (v.isNull())
{
// the center remains the same
// sets the maximum radius
setRadius( radius() > other.radius() ? radius() : other.radius() );
}
else
{
v.normalize();
vec3 p0 = this->center() - v * this->radius();
vec3 p1 = other.center() + v * other.radius();
setCenter( (p0 + p1)*(Real)0.5 );
setRadius( (p0 - p1).length()*(Real)0.5 );
}
}
return *this;
}
void transformed(Sphere& sphere, const mat4& mat) const
{
sphere.setNull();
if ( !isNull() )
{
sphere.mCenter = mat * center();
// vec3 p = center() + vec3( (Real)0.577350269189625840, (Real)0.577350269189625840, (Real)0.577350269189625840 ) * radius();
// p = mat * p;
// p = p - sphere.center();
// sphere.setRadius(p.length());
vec3 p0 = center() + vec3(radius(),0,0);
vec3 p1 = center() + vec3(0,radius(),0);
vec3 p2 = center() + vec3(0,0,radius());
p0 = mat * p0;
p1 = mat * p1;
p2 = mat * p2;
Real d0 = (p0 - sphere.mCenter).lengthSquared();
Real d1 = (p1 - sphere.mCenter).lengthSquared();
Real d2 = (p2 - sphere.mCenter).lengthSquared();
sphere.mRadius = d0>d1 ? (d0>d2?d0:d2) : (d1>d2?d1:d2);
sphere.mRadius = ::sqrt(sphere.mRadius);
}
}
Sphere transformed(const mat4& mat) const
{
Sphere sphere;
transformed(sphere, mat);
return sphere;
}
protected:
vec3 mCenter;
Real mRadius;
};
}
#endif
<|endoftext|>
|
<commit_before>
#include "../../Flare.h"
#include "FlareCreditsMenu.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareSaveGame.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareCreditsMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCreditsMenu::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FSlateFontInfo TitleFont(FPaths::GameContentDir() / TEXT("Slate/Fonts/Lato700.ttf"), 64);
FSlateFontInfo MainFont(FPaths::GameContentDir() / TEXT("Slate/Fonts/Lato700.ttf"), 28);
FSlateFontInfo SecondaryFont(FPaths::GameContentDir() / TEXT("Slate/Fonts/Lato700.ttf"), 16);
int32 Width = 1.5 * Theme.ContentWidth;
int32 TextWidth = Width - Theme.ContentPadding.Left - Theme.ContentPadding.Right;
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Icon
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SImage).Image(FFlareStyleSet::GetImage("HeliumRain"))
]
// Title
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Title", "HELIUM RAIN"))
.Font(TitleFont)
]
]
// Main
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SBox)
.WidthOverride(Width)
.HAlign(HAlign_Fill)
[
SNew(SVerticalBox)
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
// Team 1
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
// Stranger
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger", "Gwenna\u00EBl ARBONA 'Stranger'"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger-Info", "Art \u2022 UI \u2022 Game design"))
.Font(SecondaryFont)
]
]
// Niavok
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok", "Fr\u00E9d\u00E9ric BERTOLUS 'Niavok'"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok-Info", "Gameplay \u2022 Game design"))
.Font(SecondaryFont)
]
]
]
// Team 2
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
// Daisy
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Daisy", "Daisy HERBAULT"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Daisy-Info", "Music"))
.Font(SecondaryFont)
]
]
// Grom
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Grom", "J\u00E9r\u00F4me MILLION-ROUSSEAU"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Grom-Info", "Game logo \u2022 Communication"))
.Font(SecondaryFont)
]
]
]
// Thanks
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Special Thanks", "Special thanks : Johanna and our friends at NERD and Parrot"))
.Font(SecondaryFont)
]
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info", "Helium Rain uses the Unreal\u00AE Engine. Unreal\u00AE is a trademark or registered trademark of Epic Games, Inc. in the United States of America and elsewhere."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info2", "Unreal\u00AE Engine, Copyright 1998 - 2016, Epic Games, Inc. All rights reserved."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Sound-Info", "Helium Rain uses sound from http://www.freesfx.co.uk ."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Assets-Info", "Helium Rain uses asteroids and rocks by 'Gargore', and Danny Kauer. Skybox reference sourced from work by NASA/Goddard Space Flight Center Scientific Visualization Studio."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
]
]
// Back
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
[
SNew(SFlareButton)
.Transparent(true)
.Width(3)
.Text(LOCTEXT("Back", "Back"))
.OnClicked(this, &SFlareCreditsMenu::OnMainMenu)
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareCreditsMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareCreditsMenu::Enter()
{
FLOG("SFlareCreditsMenu::Enter");
SetEnabled(true);
SetVisibility(EVisibility::Visible);
}
void SFlareCreditsMenu::Exit()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareCreditsMenu::OnMainMenu()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Main);
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Updated credits to make them relevant again<commit_after>
#include "../../Flare.h"
#include "FlareCreditsMenu.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareSaveGame.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareCreditsMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCreditsMenu::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FSlateFontInfo TitleFont(FPaths::GameContentDir() / TEXT("Slate/Fonts/Lato700.ttf"), 64);
FSlateFontInfo MainFont(FPaths::GameContentDir() / TEXT("Slate/Fonts/Lato700.ttf"), 28);
FSlateFontInfo SecondaryFont(FPaths::GameContentDir() / TEXT("Slate/Fonts/Lato700.ttf"), 16);
int32 Width = 1.5 * Theme.ContentWidth;
int32 TextWidth = Width - Theme.ContentPadding.Left - Theme.ContentPadding.Right;
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SVerticalBox)
// Title
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Icon
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SImage).Image(FFlareStyleSet::GetImage("HeliumRain"))
]
// Title
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Title", "HELIUM RAIN"))
.Font(TitleFont)
]
]
// Main
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SBox)
.WidthOverride(Width)
.HAlign(HAlign_Fill)
[
SNew(SVerticalBox)
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
// Team 1
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
// Stranger
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger", "Gwenna\u00EBl ARBONA 'Stranger'"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Stranger-Info", "Art \u2022 UI \u2022 Game design"))
.Font(SecondaryFont)
]
]
// Niavok
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok", "Fr\u00E9d\u00E9ric BERTOLUS 'Niavok'"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Niavok-Info", "Gameplay \u2022 Game design"))
.Font(SecondaryFont)
]
]
]
// Team 2
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
// Daisy
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Daisy", "Daisy HERBAULT"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Daisy-Info", "Music"))
.Font(SecondaryFont)
]
]
// Grom
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Grom", "J\u00E9r\u00F4me MILLION-ROUSSEAU"))
.Font(MainFont)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Grom-Info", "Game logo \u2022 Communication"))
.Font(SecondaryFont)
]
]
]
// Thanks
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Special Thanks", "Special thanks : Johanna and our friends at NERD and Parrot"))
.Font(SecondaryFont)
]
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(0, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info", "Helium Rain uses the Unreal\u00AE Engine. Unreal\u00AE is a trademark or registered trademark of Epic Games, Inc. in the United States of America and elsewhere."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Engine-Info2", "Unreal\u00AE Engine, Copyright 1998 - 2016, Epic Games, Inc. All rights reserved."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Sound-Info", "Helium Rain uses some sound resources from FreeSFX (http://www.freesfx.co.uk)."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.Text(LOCTEXT("DONT-TRANSLATE-Assets-Info", "Helium Rain uses some third-party assets created by CGMontreal, Poleshift Games, W3 Studios and 'Gargore'."))
.Font(SecondaryFont)
.WrapTextAt(TextWidth)
]
]
]
// Back
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
[
SNew(SFlareButton)
.Transparent(true)
.Width(3)
.Text(LOCTEXT("Back", "Back"))
.OnClicked(this, &SFlareCreditsMenu::OnMainMenu)
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareCreditsMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareCreditsMenu::Enter()
{
FLOG("SFlareCreditsMenu::Enter");
SetEnabled(true);
SetVisibility(EVisibility::Visible);
}
void SFlareCreditsMenu::Exit()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareCreditsMenu::OnMainMenu()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Main);
}
#undef LOCTEXT_NAMESPACE
<|endoftext|>
|
<commit_before>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2005, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat
// Chris Demetriou (refactoring)
//
// Profile current program by sampling stack-trace every so often
#include "config.h"
#include "getpc.h" // should be first to get the _GNU_SOURCE dfn
#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for getpid()
#endif
#if defined(HAVE_SYS_UCONTEXT_H)
#include <sys/ucontext.h>
#elif defined(HAVE_UCONTEXT_H)
#include <ucontext.h>
#elif defined(HAVE_CYGWIN_SIGNAL_H)
#include <cygwin/signal.h>
typedef ucontext ucontext_t;
#else
typedef int ucontext_t; // just to quiet the compiler, mostly
#endif
#include <sys/time.h>
#include <string>
#include <gperftools/profiler.h>
#include <gperftools/stacktrace.h>
#include "base/commandlineflags.h"
#include "base/logging.h"
#include "base/googleinit.h"
#include "base/spinlock.h"
#include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */
#include "profiledata.h"
#include "profile-handler.h"
#ifdef HAVE_CONFLICT_SIGNAL_H
#include "conflict-signal.h" /* used on msvc machines */
#endif
using std::string;
DEFINE_bool(cpu_profiler_unittest,
EnvToBool("PERFTOOLS_UNITTEST", true),
"Determines whether or not we are running under the \
control of a unit test. This allows us to include or \
exclude certain behaviours.");
// Collects up all profile data. This is a singleton, which is
// initialized by a constructor at startup. If no cpu profiler
// signal is specified then the profiler lifecycle is either
// manaully controlled via the API or attached to the scope of
// the singleton (program scope). Otherwise the cpu toggle is
// used to allow for user selectable control via signal generation.
// This is very useful for profiling a daemon process without
// having to start and stop the daemon or having to modify the
// source code to use the cpu profiler API.
class CpuProfiler {
public:
CpuProfiler();
~CpuProfiler();
// Start profiler to write profile info into fname
bool Start(const char* fname, const ProfilerOptions* options);
// Stop profiling and write the data to disk.
void Stop();
// Write the data to disk (and continue profiling).
void FlushTable();
bool Enabled();
void GetCurrentState(ProfilerState* state);
static CpuProfiler instance_;
private:
// This lock implements the locking requirements described in the ProfileData
// documentation, specifically:
//
// lock_ is held all over all collector_ method calls except for the 'Add'
// call made from the signal handler, to protect against concurrent use of
// collector_'s control routines. Code other than signal handler must
// unregister the signal handler before calling any collector_ method.
// 'Add' method in the collector is protected by a guarantee from
// ProfileHandle that only one instance of prof_handler can run at a time.
SpinLock lock_;
ProfileData collector_;
// Filter function and its argument, if any. (NULL means include all
// samples). Set at start, read-only while running. Written while holding
// lock_, read and executed in the context of SIGPROF interrupt.
int (*filter_)(void*);
void* filter_arg_;
// Opaque token returned by the profile handler. To be used when calling
// ProfileHandlerUnregisterCallback.
ProfileHandlerToken* prof_handler_token_;
// Sets up a callback to receive SIGPROF interrupt.
void EnableHandler();
// Disables receiving SIGPROF interrupt.
void DisableHandler();
// Signal handler that records the interrupted pc in the profile data.
static void prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler);
};
// Signal handler that is registered when a user selectable signal
// number is defined in the environment variable CPUPROFILESIGNAL.
static void CpuProfilerSwitch(int signal_number)
{
bool static started = false;
static unsigned profile_count = 0;
static char base_profile_name[1024] = "\0";
if (base_profile_name[0] == '\0') {
if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) {
RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined");
return;
}
}
if (!started)
{
char full_profile_name[1024];
snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u",
base_profile_name, profile_count++);
if(!ProfilerStart(full_profile_name))
{
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
full_profile_name, strerror(errno));
}
}
else
{
ProfilerStop();
}
started = !started;
}
// Profile data structure singleton: Constructor will check to see if
// profiling should be enabled. Destructor will write profile data
// out to disk.
CpuProfiler CpuProfiler::instance_;
// Initialize profiling: activated if getenv("CPUPROFILE") exists.
CpuProfiler::CpuProfiler()
: prof_handler_token_(NULL) {
// TODO(cgd) Move this code *out* of the CpuProfile constructor into a
// separate object responsible for initialization. With ProfileHandler there
// is no need to limit the number of profilers.
if (getenv("CPUPROFILE") == NULL) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
// We don't enable profiling if setuid -- it's a security risk
#ifdef HAVE_GETEUID
if (getuid() != geteuid()) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n");
}
return;
}
#endif
char *signal_number_str = getenv("CPUPROFILESIGNAL");
if (signal_number_str != NULL) {
long int signal_number = strtol(signal_number_str, NULL, 10);
if (signal_number >= 1 && signal_number <= 64) {
intptr_t old_signal_handler = reinterpret_cast<intptr_t>(signal(signal_number, CpuProfilerSwitch));
if (old_signal_handler == 0) {
RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number);
} else {
RAW_LOG(FATAL, "Signal %d already in use\n", signal_number);
}
} else {
RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str);
}
} else {
char fname[PATH_MAX];
if (!GetUniquePathFromEnv("CPUPROFILE", fname)) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
if (!Start(fname, NULL)) {
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
fname, strerror(errno));
}
}
}
bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) {
SpinLockHolder cl(&lock_);
if (collector_.enabled()) {
return false;
}
ProfileHandlerState prof_handler_state;
ProfileHandlerGetState(&prof_handler_state);
ProfileData::Options collector_options;
collector_options.set_frequency(prof_handler_state.frequency);
if (!collector_.Start(fname, collector_options)) {
return false;
}
filter_ = NULL;
if (options != NULL && options->filter_in_thread != NULL) {
filter_ = options->filter_in_thread;
filter_arg_ = options->filter_in_thread_arg;
}
// Setup handler for SIGPROF interrupts
EnableHandler();
return true;
}
CpuProfiler::~CpuProfiler() {
Stop();
}
// Stop profiling and write out any collected profile data
void CpuProfiler::Stop() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// stopping the collector.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to stop the collector.
collector_.Stop();
}
void CpuProfiler::FlushTable() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// flushing the profile data.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to flush the profile data.
collector_.FlushTable();
EnableHandler();
}
bool CpuProfiler::Enabled() {
SpinLockHolder cl(&lock_);
return collector_.enabled();
}
void CpuProfiler::GetCurrentState(ProfilerState* state) {
ProfileData::State collector_state;
{
SpinLockHolder cl(&lock_);
collector_.GetCurrentState(&collector_state);
}
state->enabled = collector_state.enabled;
state->start_time = static_cast<time_t>(collector_state.start_time);
state->samples_gathered = collector_state.samples_gathered;
int buf_size = sizeof(state->profile_name);
strncpy(state->profile_name, collector_state.profile_name, buf_size);
state->profile_name[buf_size-1] = '\0';
}
void CpuProfiler::EnableHandler() {
RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered");
prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this);
RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler");
}
void CpuProfiler::DisableHandler() {
RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered");
ProfileHandlerUnregisterCallback(prof_handler_token_);
prof_handler_token_ = NULL;
}
// Signal handler that records the pc in the profile-data structure. We do no
// synchronization here. profile-handler.cc guarantees that at most one
// instance of prof_handler() will run at a time. All other routines that
// access the data touched by prof_handler() disable this signal handler before
// accessing the data and therefore cannot execute concurrently with
// prof_handler().
void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler) {
CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler);
if (instance->filter_ == NULL ||
(*instance->filter_)(instance->filter_arg_)) {
void* stack[ProfileData::kMaxStackDepth];
// Under frame-pointer-based unwinding at least on x86, the
// top-most active routine doesn't show up as a normal frame, but
// as the "pc" value in the signal handler context.
stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext));
// We skip the top two stack trace entries (this function and one
// signal handler frame) since they are artifacts of profiling and
// should not be measured. Other profiling related frames may be
// removed by "pprof" at analysis time. Instead of skipping the top
// frames, we could skip nothing, but that would increase the
// profile size unnecessarily.
int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1,
2, signal_ucontext);
void **used_stack;
if (stack[1] == stack[0]) {
// in case of non-frame-pointer-based unwinding we will duplicate
// PC in stack[1], which we don't want
used_stack = stack + 1;
} else {
used_stack = stack;
depth++; // To account for pc value in stack[0];
}
instance->collector_.Add(depth, used_stack);
}
}
#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() {
ProfileHandlerRegisterThread();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() {
CpuProfiler::instance_.FlushTable();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() {
return CpuProfiler::instance_.Enabled();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) {
return CpuProfiler::instance_.Start(fname, NULL);
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions(
const char *fname, const ProfilerOptions *options) {
return CpuProfiler::instance_.Start(fname, options);
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() {
CpuProfiler::instance_.Stop();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState(
ProfilerState* state) {
CpuProfiler::instance_.GetCurrentState(state);
}
#else // OS_CYGWIN
// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
// work as well for profiling, and also interferes with alarm(). Because of
// these issues, unless a specific need is identified, profiler support is
// disabled under Cygwin.
extern "C" void ProfilerRegisterThread() { }
extern "C" void ProfilerFlush() { }
extern "C" int ProfilingIsEnabledForAllThreads() { return 0; }
extern "C" int ProfilerStart(const char* fname) { return 0; }
extern "C" int ProfilerStartWithOptions(const char *fname,
const ProfilerOptions *options) {
return 0;
}
extern "C" void ProfilerStop() { }
extern "C" void ProfilerGetCurrentState(ProfilerState* state) {
memset(state, 0, sizeof(*state));
}
#endif // OS_CYGWIN
// DEPRECATED routines
extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { }
extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
<commit_msg>cpuprofiler: drop correct number of signal handler frames<commit_after>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2005, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat
// Chris Demetriou (refactoring)
//
// Profile current program by sampling stack-trace every so often
#include "config.h"
#include "getpc.h" // should be first to get the _GNU_SOURCE dfn
#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for getpid()
#endif
#if defined(HAVE_SYS_UCONTEXT_H)
#include <sys/ucontext.h>
#elif defined(HAVE_UCONTEXT_H)
#include <ucontext.h>
#elif defined(HAVE_CYGWIN_SIGNAL_H)
#include <cygwin/signal.h>
typedef ucontext ucontext_t;
#else
typedef int ucontext_t; // just to quiet the compiler, mostly
#endif
#include <sys/time.h>
#include <string>
#include <gperftools/profiler.h>
#include <gperftools/stacktrace.h>
#include "base/commandlineflags.h"
#include "base/logging.h"
#include "base/googleinit.h"
#include "base/spinlock.h"
#include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */
#include "profiledata.h"
#include "profile-handler.h"
#ifdef HAVE_CONFLICT_SIGNAL_H
#include "conflict-signal.h" /* used on msvc machines */
#endif
using std::string;
DEFINE_bool(cpu_profiler_unittest,
EnvToBool("PERFTOOLS_UNITTEST", true),
"Determines whether or not we are running under the \
control of a unit test. This allows us to include or \
exclude certain behaviours.");
// Collects up all profile data. This is a singleton, which is
// initialized by a constructor at startup. If no cpu profiler
// signal is specified then the profiler lifecycle is either
// manaully controlled via the API or attached to the scope of
// the singleton (program scope). Otherwise the cpu toggle is
// used to allow for user selectable control via signal generation.
// This is very useful for profiling a daemon process without
// having to start and stop the daemon or having to modify the
// source code to use the cpu profiler API.
class CpuProfiler {
public:
CpuProfiler();
~CpuProfiler();
// Start profiler to write profile info into fname
bool Start(const char* fname, const ProfilerOptions* options);
// Stop profiling and write the data to disk.
void Stop();
// Write the data to disk (and continue profiling).
void FlushTable();
bool Enabled();
void GetCurrentState(ProfilerState* state);
static CpuProfiler instance_;
private:
// This lock implements the locking requirements described in the ProfileData
// documentation, specifically:
//
// lock_ is held all over all collector_ method calls except for the 'Add'
// call made from the signal handler, to protect against concurrent use of
// collector_'s control routines. Code other than signal handler must
// unregister the signal handler before calling any collector_ method.
// 'Add' method in the collector is protected by a guarantee from
// ProfileHandle that only one instance of prof_handler can run at a time.
SpinLock lock_;
ProfileData collector_;
// Filter function and its argument, if any. (NULL means include all
// samples). Set at start, read-only while running. Written while holding
// lock_, read and executed in the context of SIGPROF interrupt.
int (*filter_)(void*);
void* filter_arg_;
// Opaque token returned by the profile handler. To be used when calling
// ProfileHandlerUnregisterCallback.
ProfileHandlerToken* prof_handler_token_;
// Sets up a callback to receive SIGPROF interrupt.
void EnableHandler();
// Disables receiving SIGPROF interrupt.
void DisableHandler();
// Signal handler that records the interrupted pc in the profile data.
static void prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler);
};
// Signal handler that is registered when a user selectable signal
// number is defined in the environment variable CPUPROFILESIGNAL.
static void CpuProfilerSwitch(int signal_number)
{
bool static started = false;
static unsigned profile_count = 0;
static char base_profile_name[1024] = "\0";
if (base_profile_name[0] == '\0') {
if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) {
RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined");
return;
}
}
if (!started)
{
char full_profile_name[1024];
snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u",
base_profile_name, profile_count++);
if(!ProfilerStart(full_profile_name))
{
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
full_profile_name, strerror(errno));
}
}
else
{
ProfilerStop();
}
started = !started;
}
// Profile data structure singleton: Constructor will check to see if
// profiling should be enabled. Destructor will write profile data
// out to disk.
CpuProfiler CpuProfiler::instance_;
// Initialize profiling: activated if getenv("CPUPROFILE") exists.
CpuProfiler::CpuProfiler()
: prof_handler_token_(NULL) {
// TODO(cgd) Move this code *out* of the CpuProfile constructor into a
// separate object responsible for initialization. With ProfileHandler there
// is no need to limit the number of profilers.
if (getenv("CPUPROFILE") == NULL) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
// We don't enable profiling if setuid -- it's a security risk
#ifdef HAVE_GETEUID
if (getuid() != geteuid()) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n");
}
return;
}
#endif
char *signal_number_str = getenv("CPUPROFILESIGNAL");
if (signal_number_str != NULL) {
long int signal_number = strtol(signal_number_str, NULL, 10);
if (signal_number >= 1 && signal_number <= 64) {
intptr_t old_signal_handler = reinterpret_cast<intptr_t>(signal(signal_number, CpuProfilerSwitch));
if (old_signal_handler == 0) {
RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number);
} else {
RAW_LOG(FATAL, "Signal %d already in use\n", signal_number);
}
} else {
RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str);
}
} else {
char fname[PATH_MAX];
if (!GetUniquePathFromEnv("CPUPROFILE", fname)) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
if (!Start(fname, NULL)) {
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
fname, strerror(errno));
}
}
}
bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) {
SpinLockHolder cl(&lock_);
if (collector_.enabled()) {
return false;
}
ProfileHandlerState prof_handler_state;
ProfileHandlerGetState(&prof_handler_state);
ProfileData::Options collector_options;
collector_options.set_frequency(prof_handler_state.frequency);
if (!collector_.Start(fname, collector_options)) {
return false;
}
filter_ = NULL;
if (options != NULL && options->filter_in_thread != NULL) {
filter_ = options->filter_in_thread;
filter_arg_ = options->filter_in_thread_arg;
}
// Setup handler for SIGPROF interrupts
EnableHandler();
return true;
}
CpuProfiler::~CpuProfiler() {
Stop();
}
// Stop profiling and write out any collected profile data
void CpuProfiler::Stop() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// stopping the collector.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to stop the collector.
collector_.Stop();
}
void CpuProfiler::FlushTable() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// flushing the profile data.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to flush the profile data.
collector_.FlushTable();
EnableHandler();
}
bool CpuProfiler::Enabled() {
SpinLockHolder cl(&lock_);
return collector_.enabled();
}
void CpuProfiler::GetCurrentState(ProfilerState* state) {
ProfileData::State collector_state;
{
SpinLockHolder cl(&lock_);
collector_.GetCurrentState(&collector_state);
}
state->enabled = collector_state.enabled;
state->start_time = static_cast<time_t>(collector_state.start_time);
state->samples_gathered = collector_state.samples_gathered;
int buf_size = sizeof(state->profile_name);
strncpy(state->profile_name, collector_state.profile_name, buf_size);
state->profile_name[buf_size-1] = '\0';
}
void CpuProfiler::EnableHandler() {
RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered");
prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this);
RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler");
}
void CpuProfiler::DisableHandler() {
RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered");
ProfileHandlerUnregisterCallback(prof_handler_token_);
prof_handler_token_ = NULL;
}
// Signal handler that records the pc in the profile-data structure. We do no
// synchronization here. profile-handler.cc guarantees that at most one
// instance of prof_handler() will run at a time. All other routines that
// access the data touched by prof_handler() disable this signal handler before
// accessing the data and therefore cannot execute concurrently with
// prof_handler().
void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler) {
CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler);
if (instance->filter_ == NULL ||
(*instance->filter_)(instance->filter_arg_)) {
void* stack[ProfileData::kMaxStackDepth];
// Under frame-pointer-based unwinding at least on x86, the
// top-most active routine doesn't show up as a normal frame, but
// as the "pc" value in the signal handler context.
stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext));
// We skip the top three stack trace entries (this function,
// SignalHandler::SignalHandler and one signal handler frame)
// since they are artifacts of profiling and should not be
// measured. Other profiling related frames may be removed by
// "pprof" at analysis time. Instead of skipping the top frames,
// we could skip nothing, but that would increase the profile size
// unnecessarily.
int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1,
3, signal_ucontext);
void **used_stack;
if (stack[1] == stack[0]) {
// in case of non-frame-pointer-based unwinding we will get
// duplicate of PC in stack[1], which we don't want
used_stack = stack + 1;
} else {
used_stack = stack;
depth++; // To account for pc value in stack[0];
}
instance->collector_.Add(depth, used_stack);
}
}
#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() {
ProfileHandlerRegisterThread();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() {
CpuProfiler::instance_.FlushTable();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() {
return CpuProfiler::instance_.Enabled();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) {
return CpuProfiler::instance_.Start(fname, NULL);
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions(
const char *fname, const ProfilerOptions *options) {
return CpuProfiler::instance_.Start(fname, options);
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() {
CpuProfiler::instance_.Stop();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState(
ProfilerState* state) {
CpuProfiler::instance_.GetCurrentState(state);
}
#else // OS_CYGWIN
// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
// work as well for profiling, and also interferes with alarm(). Because of
// these issues, unless a specific need is identified, profiler support is
// disabled under Cygwin.
extern "C" void ProfilerRegisterThread() { }
extern "C" void ProfilerFlush() { }
extern "C" int ProfilingIsEnabledForAllThreads() { return 0; }
extern "C" int ProfilerStart(const char* fname) { return 0; }
extern "C" int ProfilerStartWithOptions(const char *fname,
const ProfilerOptions *options) {
return 0;
}
extern "C" void ProfilerStop() { }
extern "C" void ProfilerGetCurrentState(ProfilerState* state) {
memset(state, 0, sizeof(*state));
}
#endif // OS_CYGWIN
// DEPRECATED routines
extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { }
extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
<|endoftext|>
|
<commit_before>// File_ChannelGrouping - Regrouping PCM streams
// Copyright (C) 2011-2011 MediaArea.net SARL, Info@MediaArea.net
//
// 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 3 of the License, or
// 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, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AES3_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_ChannelGrouping.h"
#if defined(MEDIAINFO_AES3_YES)
#include "MediaInfo/Audio/File_Aes3.h"
#endif
#if MEDIAINFO_EVENTS
#include "MediaInfo/MediaInfo_Events.h"
#endif //MEDIAINFO_EVENTS
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
File_ChannelGrouping::File_ChannelGrouping()
{
//Configuration
#if MEDIAINFO_EVENTS
ParserIDs[0]=MediaInfo_Parser_ChannelGrouping;
#endif //MEDIAINFO_EVENTS
#if MEDIAINFO_DEMUX
Demux_Level=2; //Container
#endif //MEDIAINFO_DEMUX
#if MEDIAINFO_TRACE
Trace_Layers_Update(0); //Container1
#endif //MEDIAINFO_TRACE
//In
ByteDepth=0;
Common=NULL;
Channel_Pos=0;
Channel_Total=1;
}
File_ChannelGrouping::~File_ChannelGrouping()
{
if (Channel_Pos==0)
delete Common; //Common=NULL;
}
//***************************************************************************
// Streams management
//***************************************************************************
//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Fill()
{
Fill(Stream_General, 0, General_Format, "ChannelGrouping");
if (Common->Channel_Master!=Channel_Pos)
return;
Fill(Common->Parser);
Merge(*Common->Parser);
}
//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Finish()
{
if (Common->Channel_Master!=Channel_Pos)
return;
Finish(Common->Parser);
//Merge(*Common->Parser);
}
//***************************************************************************
// Buffer - Global
//***************************************************************************
//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Init()
{
if (Common==NULL)
{
Common=new common;
Common->Parser=new File_Aes3;
((File_Aes3*)Common->Parser)->ByteSize=ByteDepth*2;
Common->Channels.resize(Channel_Total);
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
Common->Channels[Pos]=new common::channel;
Open_Buffer_Init(Common->Parser);
}
IsAes3=false;
#if MEDIAINFO_DEMUX
Demux_UnpacketizeContainer=Config->Demux_Unpacketize_Get();
#endif //MEDIAINFO_DEMUX
}
//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Continue()
{
//Testing if it is AES3 instead of mono PCM
if (!IsAes3 && (Frame_Count || (Channel_Pos==0 && !Synchronize_AES3_0()) || (Channel_Pos==1 && !Synchronize_AES3_1())))
{
if (Frame_Count==0 && Buffer_TotalBytes+Buffer_Size<65536)
{
Buffer_Offset=0; //Reinit
return;
}
#if MEDIAINFO_DEMUX
if (Demux_UnpacketizeContainer)
{
if (StreamIDs_Size>=2)
Element_Code=StreamIDs[StreamIDs_Size-2];
StreamIDs_Size--;
Demux(Buffer, Buffer_Size, ContentType_MainStream);
StreamIDs_Size++;
}
#endif //MEDIAINFO_DEMUX
Buffer_Offset=Buffer_Size;
Frame_Count++;
return;
}
IsAes3=true;
Buffer_Offset=0;
//Copying to Channel buffer
if (Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size>Common->Channels[Channel_Pos]->Buffer_Size_Max)
Common->Channels[Channel_Pos]->resize(Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size);
memcpy(Common->Channels[Channel_Pos]->Buffer+Common->Channels[Channel_Pos]->Buffer_Size, Buffer, Buffer_Size);
Common->Channels[Channel_Pos]->Buffer_Size+=Buffer_Size;
Buffer_Offset=Buffer_Size;
Common->Channel_Current++;
if (Common->Channel_Current>=Channel_Total)
Common->Channel_Current=0;
//Copying to merged channel
size_t Minimum=(size_t)-1;
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
if (Minimum>Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset)
Minimum=Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset;
while (Minimum>=ByteDepth)
{
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
{
if (Common->MergedChannel.Buffer_Size+Minimum>Common->MergedChannel.Buffer_Size_Max)
Common->MergedChannel.resize(Common->MergedChannel.Buffer_Size+Minimum);
memcpy(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Size, Common->Channels[Pos]->Buffer+Common->Channels[Pos]->Buffer_Offset, ByteDepth);
Common->Channels[Pos]->Buffer_Offset+=ByteDepth;
Common->MergedChannel.Buffer_Size+=ByteDepth;
}
Minimum-=ByteDepth;
}
if (Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset==0)
return;
//Demux
#if MEDIAINFO_DEMUX
if (Demux_UnpacketizeContainer)
{
Common->Parser->Demux_UnpacketizeContainer=true;
Demux_Level=4; //Intermediate
if (Channel_Pos)
StreamIDs[StreamIDs_Size-2]=StreamID;
if (StreamIDs_Size>=2)
Element_Code=StreamIDs[StreamIDs_Size-2];
StreamIDs_Size--;
Demux(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset, ContentType_MainStream);
StreamIDs_Size++;
}
#endif //MEDIAINFO_EVENTS
Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset);
Common->MergedChannel.Buffer_Offset=Common->MergedChannel.Buffer_Size;
if (!Status[IsAccepted] && Common->Parser->Status[IsAccepted])
{
if (Common->Channel_Master==(size_t)-1)
Common->Channel_Master=Channel_Pos;
Accept();
}
if (!Status[IsAccepted] && Buffer_TotalBytes>=0x8000)
Reject();
if (Common->Parser->Status[IsFinished])
Finish();
//Optimize buffer
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
Common->Channels[Pos]->optimize();
Common->MergedChannel.optimize();
}
//***************************************************************************
// Buffer - Synchro
//***************************************************************************
//---------------------------------------------------------------------------
bool File_ChannelGrouping::Synchronize_AES3_0()
{
//Synchronizing
while (Buffer_Offset+8<=Buffer_Size)
{
if (CC2(Buffer+Buffer_Offset)==0xF872) //SMPTE 337M 16-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC2(Buffer+Buffer_Offset)==0x72F8) //SMPTE 337M 16-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x96F872) //SMPTE 337M 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x72F896) //SMPTE 337M 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x00F872) //16-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x0072F8) //16-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x6F8720) //20-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0xF0E154) //20-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0000F872) //16-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x000072F8) //16-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x006F872) //20-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0020876F) //20-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0096F872) //24-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0072F896) //24-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (ByteDepth!=(size_t)-1)
Buffer_Offset+=ByteDepth*2;
else
Buffer_Offset++;
}
//Parsing last bytes if needed
if (Buffer_Offset+8>Buffer_Size)
return false;
//Synched
return true;
}
//---------------------------------------------------------------------------
bool File_ChannelGrouping::Synchronize_AES3_1()
{
//Synchronizing
while (Buffer_Offset+8<=Buffer_Size)
{
if (CC2(Buffer+Buffer_Offset)==0x4E1F) //SMPTE 337M 16-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC2(Buffer+Buffer_Offset)==0x1F4E) //SMPTE 337M 16-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0xA54E1F) //SMPTE 337M 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x1F4E5A) //SMPTE 337M 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x004E1F) //16-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x001F4E) //16-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x54E1F0) //20-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0xF0E154) //20-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x00004E1F) //16-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x00001F4E) //16-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0054E1F0) //20-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x00F0E154) //20-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0A54E1F) //24-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x001F4EA5) //24-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (ByteDepth!=(size_t)-1)
Buffer_Offset+=ByteDepth*2;
else
Buffer_Offset++;
}
//Parsing last bytes if needed
if (Buffer_Offset+8>Buffer_Size)
return false;
//Synched
return true;
}
//***************************************************************************
// C++
//***************************************************************************
} //NameSpace
#endif //MEDIAINFO_AES3_YES
<commit_msg><commit_after>// File_ChannelGrouping - Regrouping PCM streams
// Copyright (C) 2011-2011 MediaArea.net SARL, Info@MediaArea.net
//
// 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 3 of the License, or
// 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, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AES3_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_ChannelGrouping.h"
#if defined(MEDIAINFO_AES3_YES)
#include "MediaInfo/Audio/File_Aes3.h"
#endif
#if MEDIAINFO_EVENTS
#include "MediaInfo/MediaInfo_Events.h"
#endif //MEDIAINFO_EVENTS
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
File_ChannelGrouping::File_ChannelGrouping()
{
//Configuration
#if MEDIAINFO_EVENTS
ParserIDs[0]=MediaInfo_Parser_ChannelGrouping;
#endif //MEDIAINFO_EVENTS
#if MEDIAINFO_DEMUX
Demux_Level=2; //Container
#endif //MEDIAINFO_DEMUX
#if MEDIAINFO_TRACE
Trace_Layers_Update(0); //Container1
#endif //MEDIAINFO_TRACE
//In
ByteDepth=0;
Common=NULL;
Channel_Pos=0;
Channel_Total=1;
}
File_ChannelGrouping::~File_ChannelGrouping()
{
if (Channel_Pos==0)
delete Common; //Common=NULL;
}
//***************************************************************************
// Streams management
//***************************************************************************
//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Fill()
{
Fill(Stream_General, 0, General_Format, "ChannelGrouping");
if (Common->Channel_Master!=Channel_Pos)
return;
Fill(Common->Parser);
Merge(*Common->Parser);
}
//---------------------------------------------------------------------------
void File_ChannelGrouping::Streams_Finish()
{
if (Common->Channel_Master!=Channel_Pos)
return;
Finish(Common->Parser);
//Merge(*Common->Parser);
}
//***************************************************************************
// Buffer - Global
//***************************************************************************
//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Init()
{
if (Common==NULL)
{
Common=new common;
Common->Parser=new File_Aes3;
((File_Aes3*)Common->Parser)->ByteSize=ByteDepth*2;
Common->Channels.resize(Channel_Total);
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
Common->Channels[Pos]=new common::channel;
Open_Buffer_Init(Common->Parser);
}
IsAes3=false;
#if MEDIAINFO_DEMUX
Demux_UnpacketizeContainer=Config->Demux_Unpacketize_Get();
#endif //MEDIAINFO_DEMUX
}
//---------------------------------------------------------------------------
void File_ChannelGrouping::Read_Buffer_Continue()
{
//Testing if it is AES3 instead of mono PCM
if (!IsAes3 && (Frame_Count || (Channel_Pos==0 && !Synchronize_AES3_0()) || (Channel_Pos==1 && !Synchronize_AES3_1())))
{
if (Frame_Count==0 && Buffer_TotalBytes+Buffer_Size<65536)
{
Buffer_Offset=0; //Reinit
return;
}
#if MEDIAINFO_DEMUX
if (Demux_UnpacketizeContainer)
{
if (StreamIDs_Size>=2)
Element_Code=StreamIDs[StreamIDs_Size-2];
StreamIDs_Size--;
Demux(Buffer, Buffer_Size, ContentType_MainStream);
StreamIDs_Size++;
}
#endif //MEDIAINFO_DEMUX
Buffer_Offset=Buffer_Size;
Frame_Count++;
Accept();
Finish();
return;
}
IsAes3=true;
Buffer_Offset=0;
//Copying to Channel buffer
if (Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size>Common->Channels[Channel_Pos]->Buffer_Size_Max)
Common->Channels[Channel_Pos]->resize(Common->Channels[Channel_Pos]->Buffer_Size+Buffer_Size);
memcpy(Common->Channels[Channel_Pos]->Buffer+Common->Channels[Channel_Pos]->Buffer_Size, Buffer, Buffer_Size);
Common->Channels[Channel_Pos]->Buffer_Size+=Buffer_Size;
Buffer_Offset=Buffer_Size;
Common->Channel_Current++;
if (Common->Channel_Current>=Channel_Total)
Common->Channel_Current=0;
//Copying to merged channel
size_t Minimum=(size_t)-1;
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
if (Minimum>Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset)
Minimum=Common->Channels[Pos]->Buffer_Size-Common->Channels[Pos]->Buffer_Offset;
while (Minimum>=ByteDepth)
{
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
{
if (Common->MergedChannel.Buffer_Size+Minimum>Common->MergedChannel.Buffer_Size_Max)
Common->MergedChannel.resize(Common->MergedChannel.Buffer_Size+Minimum);
memcpy(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Size, Common->Channels[Pos]->Buffer+Common->Channels[Pos]->Buffer_Offset, ByteDepth);
Common->Channels[Pos]->Buffer_Offset+=ByteDepth;
Common->MergedChannel.Buffer_Size+=ByteDepth;
}
Minimum-=ByteDepth;
}
if (Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset==0)
return;
//Demux
#if MEDIAINFO_DEMUX
if (Demux_UnpacketizeContainer)
{
Common->Parser->Demux_UnpacketizeContainer=true;
Demux_Level=4; //Intermediate
if (Channel_Pos)
StreamIDs[StreamIDs_Size-2]=StreamID;
if (StreamIDs_Size>=2)
Element_Code=StreamIDs[StreamIDs_Size-2];
StreamIDs_Size--;
Demux(Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset, ContentType_MainStream);
StreamIDs_Size++;
}
#endif //MEDIAINFO_EVENTS
Open_Buffer_Continue(Common->Parser, Common->MergedChannel.Buffer+Common->MergedChannel.Buffer_Offset, Common->MergedChannel.Buffer_Size-Common->MergedChannel.Buffer_Offset);
Common->MergedChannel.Buffer_Offset=Common->MergedChannel.Buffer_Size;
if (!Status[IsAccepted] && Common->Parser->Status[IsAccepted])
{
if (Common->Channel_Master==(size_t)-1)
Common->Channel_Master=Channel_Pos;
Accept();
}
if (!Status[IsAccepted] && Buffer_TotalBytes>=0x8000)
Reject();
if (Common->Parser->Status[IsFinished])
Finish();
//Optimize buffer
for (size_t Pos=0; Pos<Common->Channels.size(); Pos++)
Common->Channels[Pos]->optimize();
Common->MergedChannel.optimize();
}
//***************************************************************************
// Buffer - Synchro
//***************************************************************************
//---------------------------------------------------------------------------
bool File_ChannelGrouping::Synchronize_AES3_0()
{
//Synchronizing
while (Buffer_Offset+8<=Buffer_Size)
{
if (CC2(Buffer+Buffer_Offset)==0xF872) //SMPTE 337M 16-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC2(Buffer+Buffer_Offset)==0x72F8) //SMPTE 337M 16-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x96F872) //SMPTE 337M 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x72F896) //SMPTE 337M 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x00F872) //16-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x0072F8) //16-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x6F8720) //20-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0xF0E154) //20-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0000F872) //16-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x000072F8) //16-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x006F872) //20-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0020876F) //20-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0096F872) //24-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0072F896) //24-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (ByteDepth!=(size_t)-1)
Buffer_Offset+=ByteDepth*2;
else
Buffer_Offset++;
}
//Parsing last bytes if needed
if (Buffer_Offset+8>Buffer_Size)
return false;
//Synched
return true;
}
//---------------------------------------------------------------------------
bool File_ChannelGrouping::Synchronize_AES3_1()
{
//Synchronizing
while (Buffer_Offset+8<=Buffer_Size)
{
if (CC2(Buffer+Buffer_Offset)==0x4E1F) //SMPTE 337M 16-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC2(Buffer+Buffer_Offset)==0x1F4E) //SMPTE 337M 16-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0xA54E1F) //SMPTE 337M 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x1F4E5A) //SMPTE 337M 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x004E1F) //16-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x001F4E) //16-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0x54E1F0) //20-bit in 24-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC3(Buffer+Buffer_Offset)==0xF0E154) //20-bit in 24-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x00004E1F) //16-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x00001F4E) //16-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0054E1F0) //20-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x00F0E154) //20-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x0A54E1F) //24-bit in 32-bit, BE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (CC4(Buffer+Buffer_Offset)==0x001F4EA5) //24-bit in 32-bit, LE
{
if (Frame_Count)
break; //while()
Frame_Count++;
}
if (ByteDepth!=(size_t)-1)
Buffer_Offset+=ByteDepth*2;
else
Buffer_Offset++;
}
//Parsing last bytes if needed
if (Buffer_Offset+8>Buffer_Size)
return false;
//Synched
return true;
}
//***************************************************************************
// C++
//***************************************************************************
} //NameSpace
#endif //MEDIAINFO_AES3_YES
<|endoftext|>
|
<commit_before>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/thread/mutex.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionPlugin.hpp>
#ifdef PION_WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace pion { // begin namespace pion
// static members of PionPlugin
const std::string PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef PION_WIN32
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string> PionPlugin::m_plugin_dirs;
PionPlugin::PluginMap PionPlugin::m_plugin_map;
boost::mutex PionPlugin::m_plugin_mutex;
PionPlugin::StaticEntryPointList *PionPlugin::m_entry_points_ptr = NULL;
// PionPlugin member functions
void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
const std::string& start_path)
{
#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)
// try prepending PION_CYGWIN_DIRECTORY if not complete
if (! final_path.is_complete() && final_path.has_root_directory()) {
final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);
}
#endif
}
void PionPlugin::addPluginDirectory(const std::string& dir)
{
boost::filesystem::path plugin_path = boost::filesystem::system_complete(dir);
checkCygwinPath(plugin_path, dir);
if (! boost::filesystem::exists(plugin_path) )
throw DirectoryNotFoundException(dir);
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(plugin_path.directory_string());
}
void PionPlugin::resetPluginDirectories(void)
{
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.clear();
}
void PionPlugin::open(const std::string& plugin_name)
{
std::string plugin_file;
if (!findPluginFile(plugin_file, plugin_name))
throw PluginNotFoundException(plugin_name);
openFile(plugin_file);
}
void PionPlugin::openFile(const std::string& plugin_file)
{
releaseData(); // make sure we're not already pointing to something
// use a temporary object first since openPlugin() may throw
PionPluginData plugin_data(getPluginName(plugin_file));
// check to see if we already have a matching shared library
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
PluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);
if (itr == m_plugin_map.end()) {
// no plug-ins found with the same name
// open up the shared library using our temporary data object
openPlugin(plugin_file, plugin_data); // may throw
// all is good -> insert it into the plug-in map
m_plugin_data = new PionPluginData(plugin_data);
m_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,
m_plugin_data) );
} else {
// found an existing plug-in with the same name
m_plugin_data = itr->second;
}
// increment the number of references
++ m_plugin_data->m_references;
}
void PionPlugin::openStaticLinked(const std::string& plugin_name,
void *create_func,
void *destroy_func)
{
releaseData(); // make sure we're not already pointing to something
// check to see if we already have a matching shared library
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
PluginMap::iterator itr = m_plugin_map.find(plugin_name);
if (itr == m_plugin_map.end()) {
// no plug-ins found with the same name
// all is good -> insert it into the plug-in map
m_plugin_data = new PionPluginData(plugin_name);
m_plugin_data->m_lib_handle = NULL; // this will indicate that we are using statically linked plug-in
m_plugin_data->m_create_func = create_func;
m_plugin_data->m_destroy_func = destroy_func;
m_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,
m_plugin_data));
} else {
// found an existing plug-in with the same name
m_plugin_data = itr->second;
}
// increment the number of references
++ m_plugin_data->m_references;
}
void PionPlugin::releaseData(void)
{
if (m_plugin_data != NULL) {
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
// double-check after locking mutex
if (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {
// no more references to the plug-in library
// release the shared object
closeDynamicLibrary(m_plugin_data->m_lib_handle);
// remove it from the plug-in map
PluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);
// check itr just to be safe (it SHOULD always find a match)
if (itr != m_plugin_map.end())
m_plugin_map.erase(itr);
// release the heap object
delete m_plugin_data;
}
m_plugin_data = NULL;
}
}
void PionPlugin::grabData(const PionPlugin& p)
{
releaseData(); // make sure we're not already pointing to something
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);
if (m_plugin_data != NULL) {
++ m_plugin_data->m_references;
}
}
bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
const std::string& extension)
{
// first, try the name as-is
if (checkForFile(path_to_file, name, "", extension))
return true;
// nope, check search paths
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
i != m_plugin_dirs.end(); ++i)
{
if (checkForFile(path_to_file, *i, name, extension))
return true;
}
// no plug-in file found
return false;
}
bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
const std::string& name, const std::string& extension)
{
// check for cygwin path oddities
boost::filesystem::path cygwin_safe_path(start_path);
checkCygwinPath(cygwin_safe_path, start_path);
boost::filesystem::path test_path(cygwin_safe_path);
// if a name is specified, append it to the test path
if (! name.empty())
test_path /= name;
// check for existence of file (without extension)
if (boost::filesystem::is_regular(test_path)) {
final_path = test_path.file_string();
return true;
}
// next, try appending the extension
if (name.empty()) {
// no "name" specified -> append it directly to start_path
test_path = boost::filesystem::path(start_path + extension);
// in this case, we need to re-check for the cygwin oddities
checkCygwinPath(test_path, start_path + extension);
} else {
// name is specified, so we can just re-use cygwin_safe_path
test_path = cygwin_safe_path /
boost::filesystem::path(name + extension);
}
// re-check for existence of file (after adding extension)
if (boost::filesystem::is_regular(test_path)) {
final_path = test_path.file_string();
return true;
}
// no plug-in file found
return false;
}
void PionPlugin::openPlugin(const std::string& plugin_file,
PionPluginData& plugin_data)
{
// get the name of the plugin (for create/destroy symbol names)
plugin_data.m_plugin_name = getPluginName(plugin_file);
// attempt to open the plugin; note that this tries all search paths
// and also tries a variety of platform-specific extensions
plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
if (plugin_data.m_lib_handle == NULL) {
#ifndef PION_WIN32
char *error_msg = dlerror();
if (error_msg != NULL) {
std::string error_str(plugin_file);
error_str += " (";
error_str += error_msg;
error_str += ')';
throw OpenPluginException(error_str);
} else
#endif
throw OpenPluginException(plugin_file);
}
// find the function used to create new plugin objects
plugin_data.m_create_func =
getLibrarySymbol(plugin_data.m_lib_handle,
PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
if (plugin_data.m_create_func == NULL) {
closeDynamicLibrary(plugin_data.m_lib_handle);
throw PluginMissingCreateException(plugin_file);
}
// find the function used to destroy existing plugin objects
plugin_data.m_destroy_func =
getLibrarySymbol(plugin_data.m_lib_handle,
PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
if (plugin_data.m_destroy_func == NULL) {
closeDynamicLibrary(plugin_data.m_lib_handle);
throw PluginMissingDestroyException(plugin_file);
}
}
std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
return boost::filesystem::basename(boost::filesystem::path(plugin_file));
}
void PionPlugin::getAllPluginNames(std::vector<std::string>& plugin_names)
{
// Iterate through all the Plugin directories.
std::vector<std::string>::iterator it;
for (it = m_plugin_dirs.begin(); it != m_plugin_dirs.end(); ++it) {
// Find all shared libraries in the directory and add them to the list of Plugin names.
boost::filesystem::directory_iterator end;
for (boost::filesystem::directory_iterator it2(*it); it2 != end; ++it2) {
if (boost::filesystem::is_regular(*it2)) {
if (boost::filesystem::extension(it2->path()) == PionPlugin::PION_PLUGIN_EXTENSION) {
plugin_names.push_back(PionPlugin::getPluginName(it2->path().leaf()));
}
}
}
}
}
void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef PION_WIN32
#ifdef _MSC_VER
return LoadLibraryA(plugin_file.c_str());
#else
return LoadLibrary(plugin_file.c_str());
#endif
#else
// convert into a full/absolute/complete path since dlopen()
// does not always search the CWD on some operating systems
const boost::filesystem::path full_path = boost::filesystem::complete(plugin_file);
// NOTE: you must load shared libraries using RTLD_GLOBAL on Unix platforms
// due to a bug in GCC (or Boost::any, depending on which crowd you want to believe).
// see: http://svn.boost.org/trac/boost/ticket/754
return dlopen(full_path.file_string().c_str(), RTLD_LAZY | RTLD_GLOBAL);
#endif
}
void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef PION_WIN32
// Apparently, FreeLibrary sometimes causes crashes when running
// pion-net-unit-tests under Windows.
// It's hard to pin down, because many things can suppress the crashes,
// such as enabling logging or setting breakpoints (i.e. things that
// might help pin it down.) Also, it's very intermittent, and can be
// strongly affected by other processes that are running.
// So, please don't call FreeLibrary here unless you've been able to
// reproduce and fix the crashing of the unit tests.
//FreeLibrary((HINSTANCE) lib_handle);
#else
dlclose(lib_handle);
#endif
}
void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef PION_WIN32
return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
return dlsym(lib_handle, symbol.c_str());
#endif
}
bool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,
void **create_func,
void **destroy_func)
{
// check simple case first: no entry points exist
if (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())
return false;
// try to find the entry point for the plugin
for (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();
i != m_entry_points_ptr->end(); ++i) {
if (i->m_plugin_name==plugin_name) {
*create_func = i->m_create_func;
*destroy_func = i->m_destroy_func;
return true;
}
}
return false;
}
void PionPlugin::addStaticEntryPoint(const std::string& plugin_name,
void *create_func,
void *destroy_func)
{
// make sure that this function can only be called by one thread at a time
static boost::mutex entrypoint_mutex;
boost::mutex::scoped_lock entrypoint_lock(entrypoint_mutex);
// create the entry point list if it doesn't already exist
if (m_entry_points_ptr == NULL)
m_entry_points_ptr = new StaticEntryPointList;
// insert it into the entry point list
m_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));
}
} // end namespace pion
<commit_msg>Fix to compile on FreeBSD 7.x -- no effect on other platforms<commit_after>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/thread/mutex.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionPlugin.hpp>
#ifdef PION_WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace pion { // begin namespace pion
// static members of PionPlugin
const std::string PionPlugin::PION_PLUGIN_CREATE("pion_create_");
const std::string PionPlugin::PION_PLUGIN_DESTROY("pion_destroy_");
#ifdef PION_WIN32
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".dll");
#else
const std::string PionPlugin::PION_PLUGIN_EXTENSION(".so");
#endif
const std::string PionPlugin::PION_CONFIG_EXTENSION(".conf");
std::vector<std::string> PionPlugin::m_plugin_dirs;
PionPlugin::PluginMap PionPlugin::m_plugin_map;
boost::mutex PionPlugin::m_plugin_mutex;
PionPlugin::StaticEntryPointList *PionPlugin::m_entry_points_ptr = NULL;
// PionPlugin member functions
void PionPlugin::checkCygwinPath(boost::filesystem::path& final_path,
const std::string& start_path)
{
#if defined(PION_WIN32) && defined(PION_CYGWIN_DIRECTORY)
// try prepending PION_CYGWIN_DIRECTORY if not complete
if (! final_path.is_complete() && final_path.has_root_directory()) {
final_path = boost::filesystem::path(std::string(PION_CYGWIN_DIRECTORY) + start_path);
}
#endif
}
void PionPlugin::addPluginDirectory(const std::string& dir)
{
boost::filesystem::path plugin_path = boost::filesystem::system_complete(dir);
checkCygwinPath(plugin_path, dir);
if (! boost::filesystem::exists(plugin_path) )
throw DirectoryNotFoundException(dir);
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.push_back(plugin_path.directory_string());
}
void PionPlugin::resetPluginDirectories(void)
{
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_dirs.clear();
}
void PionPlugin::open(const std::string& plugin_name)
{
std::string plugin_file;
if (!findPluginFile(plugin_file, plugin_name))
throw PluginNotFoundException(plugin_name);
openFile(plugin_file);
}
void PionPlugin::openFile(const std::string& plugin_file)
{
releaseData(); // make sure we're not already pointing to something
// use a temporary object first since openPlugin() may throw
PionPluginData plugin_data(getPluginName(plugin_file));
// check to see if we already have a matching shared library
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
PluginMap::iterator itr = m_plugin_map.find(plugin_data.m_plugin_name);
if (itr == m_plugin_map.end()) {
// no plug-ins found with the same name
// open up the shared library using our temporary data object
openPlugin(plugin_file, plugin_data); // may throw
// all is good -> insert it into the plug-in map
m_plugin_data = new PionPluginData(plugin_data);
m_plugin_map.insert( std::make_pair(m_plugin_data->m_plugin_name,
m_plugin_data) );
} else {
// found an existing plug-in with the same name
m_plugin_data = itr->second;
}
// increment the number of references
++ m_plugin_data->m_references;
}
void PionPlugin::openStaticLinked(const std::string& plugin_name,
void *create_func,
void *destroy_func)
{
releaseData(); // make sure we're not already pointing to something
// check to see if we already have a matching shared library
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
PluginMap::iterator itr = m_plugin_map.find(plugin_name);
if (itr == m_plugin_map.end()) {
// no plug-ins found with the same name
// all is good -> insert it into the plug-in map
m_plugin_data = new PionPluginData(plugin_name);
m_plugin_data->m_lib_handle = NULL; // this will indicate that we are using statically linked plug-in
m_plugin_data->m_create_func = create_func;
m_plugin_data->m_destroy_func = destroy_func;
m_plugin_map.insert(std::make_pair(m_plugin_data->m_plugin_name,
m_plugin_data));
} else {
// found an existing plug-in with the same name
m_plugin_data = itr->second;
}
// increment the number of references
++ m_plugin_data->m_references;
}
void PionPlugin::releaseData(void)
{
if (m_plugin_data != NULL) {
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
// double-check after locking mutex
if (m_plugin_data != NULL && --m_plugin_data->m_references == 0) {
// no more references to the plug-in library
// release the shared object
closeDynamicLibrary(m_plugin_data->m_lib_handle);
// remove it from the plug-in map
PluginMap::iterator itr = m_plugin_map.find(m_plugin_data->m_plugin_name);
// check itr just to be safe (it SHOULD always find a match)
if (itr != m_plugin_map.end())
m_plugin_map.erase(itr);
// release the heap object
delete m_plugin_data;
}
m_plugin_data = NULL;
}
}
void PionPlugin::grabData(const PionPlugin& p)
{
releaseData(); // make sure we're not already pointing to something
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
m_plugin_data = const_cast<PionPluginData*>(p.m_plugin_data);
if (m_plugin_data != NULL) {
++ m_plugin_data->m_references;
}
}
bool PionPlugin::findFile(std::string& path_to_file, const std::string& name,
const std::string& extension)
{
// first, try the name as-is
if (checkForFile(path_to_file, name, "", extension))
return true;
// nope, check search paths
boost::mutex::scoped_lock plugin_lock(m_plugin_mutex);
for (std::vector<std::string>::iterator i = m_plugin_dirs.begin();
i != m_plugin_dirs.end(); ++i)
{
if (checkForFile(path_to_file, *i, name, extension))
return true;
}
// no plug-in file found
return false;
}
bool PionPlugin::checkForFile(std::string& final_path, const std::string& start_path,
const std::string& name, const std::string& extension)
{
// check for cygwin path oddities
boost::filesystem::path cygwin_safe_path(start_path);
checkCygwinPath(cygwin_safe_path, start_path);
boost::filesystem::path test_path(cygwin_safe_path);
// if a name is specified, append it to the test path
if (! name.empty())
test_path /= name;
// check for existence of file (without extension)
if (boost::filesystem::is_regular(test_path)) {
final_path = test_path.file_string();
return true;
}
// next, try appending the extension
if (name.empty()) {
// no "name" specified -> append it directly to start_path
test_path = boost::filesystem::path(start_path + extension);
// in this case, we need to re-check for the cygwin oddities
checkCygwinPath(test_path, start_path + extension);
} else {
// name is specified, so we can just re-use cygwin_safe_path
test_path = cygwin_safe_path /
boost::filesystem::path(name + extension);
}
// re-check for existence of file (after adding extension)
if (boost::filesystem::is_regular(test_path)) {
final_path = test_path.file_string();
return true;
}
// no plug-in file found
return false;
}
void PionPlugin::openPlugin(const std::string& plugin_file,
PionPluginData& plugin_data)
{
// get the name of the plugin (for create/destroy symbol names)
plugin_data.m_plugin_name = getPluginName(plugin_file);
// attempt to open the plugin; note that this tries all search paths
// and also tries a variety of platform-specific extensions
plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
if (plugin_data.m_lib_handle == NULL) {
#ifndef PION_WIN32
const char *error_msg = dlerror();
if (error_msg != NULL) {
std::string error_str(plugin_file);
error_str += " (";
error_str += error_msg;
error_str += ')';
throw OpenPluginException(error_str);
} else
#endif
throw OpenPluginException(plugin_file);
}
// find the function used to create new plugin objects
plugin_data.m_create_func =
getLibrarySymbol(plugin_data.m_lib_handle,
PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
if (plugin_data.m_create_func == NULL) {
closeDynamicLibrary(plugin_data.m_lib_handle);
throw PluginMissingCreateException(plugin_file);
}
// find the function used to destroy existing plugin objects
plugin_data.m_destroy_func =
getLibrarySymbol(plugin_data.m_lib_handle,
PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
if (plugin_data.m_destroy_func == NULL) {
closeDynamicLibrary(plugin_data.m_lib_handle);
throw PluginMissingDestroyException(plugin_file);
}
}
std::string PionPlugin::getPluginName(const std::string& plugin_file)
{
return boost::filesystem::basename(boost::filesystem::path(plugin_file));
}
void PionPlugin::getAllPluginNames(std::vector<std::string>& plugin_names)
{
// Iterate through all the Plugin directories.
std::vector<std::string>::iterator it;
for (it = m_plugin_dirs.begin(); it != m_plugin_dirs.end(); ++it) {
// Find all shared libraries in the directory and add them to the list of Plugin names.
boost::filesystem::directory_iterator end;
for (boost::filesystem::directory_iterator it2(*it); it2 != end; ++it2) {
if (boost::filesystem::is_regular(*it2)) {
if (boost::filesystem::extension(it2->path()) == PionPlugin::PION_PLUGIN_EXTENSION) {
plugin_names.push_back(PionPlugin::getPluginName(it2->path().leaf()));
}
}
}
}
}
void *PionPlugin::loadDynamicLibrary(const std::string& plugin_file)
{
#ifdef PION_WIN32
#ifdef _MSC_VER
return LoadLibraryA(plugin_file.c_str());
#else
return LoadLibrary(plugin_file.c_str());
#endif
#else
// convert into a full/absolute/complete path since dlopen()
// does not always search the CWD on some operating systems
const boost::filesystem::path full_path = boost::filesystem::complete(plugin_file);
// NOTE: you must load shared libraries using RTLD_GLOBAL on Unix platforms
// due to a bug in GCC (or Boost::any, depending on which crowd you want to believe).
// see: http://svn.boost.org/trac/boost/ticket/754
return dlopen(full_path.file_string().c_str(), RTLD_LAZY | RTLD_GLOBAL);
#endif
}
void PionPlugin::closeDynamicLibrary(void *lib_handle)
{
#ifdef PION_WIN32
// Apparently, FreeLibrary sometimes causes crashes when running
// pion-net-unit-tests under Windows.
// It's hard to pin down, because many things can suppress the crashes,
// such as enabling logging or setting breakpoints (i.e. things that
// might help pin it down.) Also, it's very intermittent, and can be
// strongly affected by other processes that are running.
// So, please don't call FreeLibrary here unless you've been able to
// reproduce and fix the crashing of the unit tests.
//FreeLibrary((HINSTANCE) lib_handle);
#else
dlclose(lib_handle);
#endif
}
void *PionPlugin::getLibrarySymbol(void *lib_handle, const std::string& symbol)
{
#ifdef PION_WIN32
return (void*)GetProcAddress((HINSTANCE) lib_handle, symbol.c_str());
#else
return dlsym(lib_handle, symbol.c_str());
#endif
}
bool PionPlugin::findStaticEntryPoint(const std::string& plugin_name,
void **create_func,
void **destroy_func)
{
// check simple case first: no entry points exist
if (m_entry_points_ptr == NULL || m_entry_points_ptr->empty())
return false;
// try to find the entry point for the plugin
for (std::list<StaticEntryPoint>::const_iterator i = m_entry_points_ptr->begin();
i != m_entry_points_ptr->end(); ++i) {
if (i->m_plugin_name==plugin_name) {
*create_func = i->m_create_func;
*destroy_func = i->m_destroy_func;
return true;
}
}
return false;
}
void PionPlugin::addStaticEntryPoint(const std::string& plugin_name,
void *create_func,
void *destroy_func)
{
// make sure that this function can only be called by one thread at a time
static boost::mutex entrypoint_mutex;
boost::mutex::scoped_lock entrypoint_lock(entrypoint_mutex);
// create the entry point list if it doesn't already exist
if (m_entry_points_ptr == NULL)
m_entry_points_ptr = new StaticEntryPointList;
// insert it into the entry point list
m_entry_points_ptr->push_back(StaticEntryPoint(plugin_name, create_func, destroy_func));
}
} // end namespace pion
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
// primary header
#include "utils.h"
// library headers
#include "common/unittest.h"
#include "common/common_def.h"
// system headers
#include <limits>
#include <sstream>
#include <va/va.h>
#define UTILS_TEST(name) \
TEST(UtilsTest, name)
using namespace YamiMediaCodec;
UTILS_TEST(guessFourcc) {
EXPECT_EQ(guessFourcc("test.i420"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test.nv12"), (uint32_t)YAMI_FOURCC_NV12);
EXPECT_EQ(guessFourcc("test.yv12"), (uint32_t)YAMI_FOURCC_YV12);
EXPECT_EQ(guessFourcc("test.yuy2"), (uint32_t)YAMI_FOURCC_YUY2);
EXPECT_EQ(guessFourcc("test.uyvy"), (uint32_t)YAMI_FOURCC_UYVY);
EXPECT_EQ(guessFourcc("test.rgbx"), (uint32_t)YAMI_FOURCC_RGBX);
EXPECT_EQ(guessFourcc("test.bgrx"), (uint32_t)YAMI_FOURCC_BGRX);
EXPECT_EQ(guessFourcc("test.xrgb"), (uint32_t)YAMI_FOURCC_XRGB);
EXPECT_EQ(guessFourcc("test.xbgr"), (uint32_t)YAMI_FOURCC_XBGR);
EXPECT_EQ(guessFourcc("test.txt"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test.I420"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test.NV12"), (uint32_t)YAMI_FOURCC_NV12);
EXPECT_EQ(guessFourcc("test.YV12"), (uint32_t)YAMI_FOURCC_YV12);
EXPECT_EQ(guessFourcc("test.YUY2"), (uint32_t)YAMI_FOURCC_YUY2);
EXPECT_EQ(guessFourcc("test.UYVY"), (uint32_t)YAMI_FOURCC_UYVY);
EXPECT_EQ(guessFourcc("test.RGBX"), (uint32_t)YAMI_FOURCC_RGBX);
EXPECT_EQ(guessFourcc("test.BGRX"), (uint32_t)YAMI_FOURCC_BGRX);
EXPECT_EQ(guessFourcc("test.XRGB"), (uint32_t)YAMI_FOURCC_XRGB);
EXPECT_EQ(guessFourcc("test.XBGR"), (uint32_t)YAMI_FOURCC_XBGR);
EXPECT_EQ(guessFourcc("test.RG16"), (uint32_t)YAMI_FOURCC_RG16);
}
UTILS_TEST(guessResolutionBasic) {
int w(-1), h(-1);
EXPECT_TRUE(guessResolution("test1920x1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("test1920X1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("test123-1920x1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("test-1920x1080-123", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test1920xx1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test", w, h));
EXPECT_EQ(w, 0);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test1080p", w, h));
EXPECT_EQ(w, 0);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test720x", w, h));
EXPECT_EQ(w, 720);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("1280x720", w, h));
EXPECT_EQ(w, 1280);
EXPECT_EQ(h, 720);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("w3840h2160", w, h));
EXPECT_EQ(w, 0);
EXPECT_EQ(h, 0);
}
UTILS_TEST(guessResolutionOverflow) {
std::stringstream sstream;
int w, h;
w = h = std::numeric_limits<int>::max();
// sanity check
ASSERT_GT(std::numeric_limits<long>::max(), w);
ASSERT_GT(std::numeric_limits<long>::max(), h);
sstream << std::numeric_limits<long>::max()
<< "x"
<< std::numeric_limits<long>::max();
EXPECT_FALSE(guessResolution(sstream.str().c_str(), w, h));
sstream.str("");
sstream << long(std::numeric_limits<int>::max()) * 2 + 3 << "x"
<< long(std::numeric_limits<int>::max()) * 3 + 2;
EXPECT_FALSE(guessResolution(sstream.str().c_str(), w, h));
}
struct BppEntry {
uint32_t fourcc;
uint32_t planes;
float bpp;
};
const static BppEntry bppEntrys[] = {
{ YAMI_FOURCC_NV12, 2, 1.5 },
{ YAMI_FOURCC_I420, 3, 1.5 },
{ YAMI_FOURCC_YV12, 3, 1.5 },
{ YAMI_FOURCC_IMC3, 3, 1.5 },
{ YAMI_FOURCC_422H, 3, 2 },
{ YAMI_FOURCC_422V, 3, 2 },
{ YAMI_FOURCC_444P, 3, 3 },
{ YAMI_FOURCC_Y800, 1, 1 },
{ YAMI_FOURCC_P010, 2, 3 },
{ YAMI_FOURCC_YUY2, 1, 2 },
{ YAMI_FOURCC_UYVY, 1, 2 },
{ YAMI_FOURCC_RGBX, 1, 4 },
{ YAMI_FOURCC_RGBA, 1, 4 },
{ YAMI_FOURCC_BGRX, 1, 4 },
{ YAMI_FOURCC_BGRA, 1, 4 },
{ YAMI_FOURCC_RG16, 1, 2 },
};
//check selected unsupported format.
//we do not want check all unsupported formats, it will introduce too many dependency on libva
const static uint32_t unsupported[] = {
0,
YAMI_FOURCC_411P,
YAMI_FOURCC_ARGB,
};
UTILS_TEST(getPlaneResolution)
{
uint32_t width = 1920;
uint32_t height = 1080;
uint32_t planes;
uint32_t w[3];
uint32_t h[3];
for (size_t i = 0; i < N_ELEMENTS(unsupported); i++) {
EXPECT_FALSE(getPlaneResolution(unsupported[i], 1920, 1080, w, h, planes));
EXPECT_EQ(0u, planes);
}
for (size_t i = 0; i < N_ELEMENTS(bppEntrys); i++) {
const BppEntry& e = bppEntrys[i];
EXPECT_TRUE(getPlaneResolution(e.fourcc, width, height, w, h, planes));
EXPECT_EQ(e.planes, planes);
float bpp;
uint32_t bytes = 0;
for (uint32_t p = 0; p < planes; p++) {
bytes += w[p] * h[p];
}
bpp = (float)bytes / (width * height);
EXPECT_FLOAT_EQ(e.bpp, bpp);
}
}
<commit_msg>unittest: common, add support for RGBA, BGRA, ARGB, ABGR<commit_after>/*
* Copyright 2016 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
// primary header
#include "utils.h"
// library headers
#include "common/unittest.h"
#include "common/common_def.h"
// system headers
#include <limits>
#include <sstream>
#include <va/va.h>
#define UTILS_TEST(name) \
TEST(UtilsTest, name)
using namespace YamiMediaCodec;
UTILS_TEST(guessFourcc) {
EXPECT_EQ(guessFourcc("test.i420"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test.nv12"), (uint32_t)YAMI_FOURCC_NV12);
EXPECT_EQ(guessFourcc("test.yv12"), (uint32_t)YAMI_FOURCC_YV12);
EXPECT_EQ(guessFourcc("test.yuy2"), (uint32_t)YAMI_FOURCC_YUY2);
EXPECT_EQ(guessFourcc("test.uyvy"), (uint32_t)YAMI_FOURCC_UYVY);
EXPECT_EQ(guessFourcc("test.rgbx"), (uint32_t)YAMI_FOURCC_RGBX);
EXPECT_EQ(guessFourcc("test.bgrx"), (uint32_t)YAMI_FOURCC_BGRX);
EXPECT_EQ(guessFourcc("test.xrgb"), (uint32_t)YAMI_FOURCC_XRGB);
EXPECT_EQ(guessFourcc("test.xbgr"), (uint32_t)YAMI_FOURCC_XBGR);
EXPECT_EQ(guessFourcc("test.txt"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test.I420"), (uint32_t)YAMI_FOURCC_I420);
EXPECT_EQ(guessFourcc("test.NV12"), (uint32_t)YAMI_FOURCC_NV12);
EXPECT_EQ(guessFourcc("test.YV12"), (uint32_t)YAMI_FOURCC_YV12);
EXPECT_EQ(guessFourcc("test.YUY2"), (uint32_t)YAMI_FOURCC_YUY2);
EXPECT_EQ(guessFourcc("test.UYVY"), (uint32_t)YAMI_FOURCC_UYVY);
EXPECT_EQ(guessFourcc("test.RGBX"), (uint32_t)YAMI_FOURCC_RGBX);
EXPECT_EQ(guessFourcc("test.BGRX"), (uint32_t)YAMI_FOURCC_BGRX);
EXPECT_EQ(guessFourcc("test.XRGB"), (uint32_t)YAMI_FOURCC_XRGB);
EXPECT_EQ(guessFourcc("test.XBGR"), (uint32_t)YAMI_FOURCC_XBGR);
EXPECT_EQ(guessFourcc("test.RGBA"), (uint32_t)YAMI_FOURCC_RGBA);
EXPECT_EQ(guessFourcc("test.BGRA"), (uint32_t)YAMI_FOURCC_BGRA);
EXPECT_EQ(guessFourcc("test.ARGB"), (uint32_t)YAMI_FOURCC_ARGB);
EXPECT_EQ(guessFourcc("test.ABGR"), (uint32_t)YAMI_FOURCC_ABGR);
EXPECT_EQ(guessFourcc("test.RG16"), (uint32_t)YAMI_FOURCC_RGB565);
}
UTILS_TEST(guessResolutionBasic) {
int w(-1), h(-1);
EXPECT_TRUE(guessResolution("test1920x1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("test1920X1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("test123-1920x1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("test-1920x1080-123", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 1080);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test1920xx1080", w, h));
EXPECT_EQ(w, 1920);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test", w, h));
EXPECT_EQ(w, 0);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test1080p", w, h));
EXPECT_EQ(w, 0);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("test720x", w, h));
EXPECT_EQ(w, 720);
EXPECT_EQ(h, 0);
w = -1, h = -1;
EXPECT_TRUE(guessResolution("1280x720", w, h));
EXPECT_EQ(w, 1280);
EXPECT_EQ(h, 720);
w = -1, h = -1;
EXPECT_FALSE(guessResolution("w3840h2160", w, h));
EXPECT_EQ(w, 0);
EXPECT_EQ(h, 0);
}
UTILS_TEST(guessResolutionOverflow) {
std::stringstream sstream;
int w, h;
w = h = std::numeric_limits<int>::max();
// sanity check
ASSERT_GT(std::numeric_limits<long>::max(), w);
ASSERT_GT(std::numeric_limits<long>::max(), h);
sstream << std::numeric_limits<long>::max()
<< "x"
<< std::numeric_limits<long>::max();
EXPECT_FALSE(guessResolution(sstream.str().c_str(), w, h));
sstream.str("");
sstream << long(std::numeric_limits<int>::max()) * 2 + 3 << "x"
<< long(std::numeric_limits<int>::max()) * 3 + 2;
EXPECT_FALSE(guessResolution(sstream.str().c_str(), w, h));
}
struct BppEntry {
uint32_t fourcc;
uint32_t planes;
float bpp;
};
const static BppEntry bppEntrys[] = {
{ YAMI_FOURCC_NV12, 2, 1.5 },
{ YAMI_FOURCC_I420, 3, 1.5 },
{ YAMI_FOURCC_YV12, 3, 1.5 },
{ YAMI_FOURCC_IMC3, 3, 1.5 },
{ YAMI_FOURCC_422H, 3, 2 },
{ YAMI_FOURCC_422V, 3, 2 },
{ YAMI_FOURCC_444P, 3, 3 },
{ YAMI_FOURCC_Y800, 1, 1 },
{ YAMI_FOURCC_P010, 2, 3 },
{ YAMI_FOURCC_YUY2, 1, 2 },
{ YAMI_FOURCC_UYVY, 1, 2 },
{ YAMI_FOURCC_RGBX, 1, 4 },
{ YAMI_FOURCC_BGRX, 1, 4 },
{ YAMI_FOURCC_XRGB, 1, 4 },
{ YAMI_FOURCC_XBGR, 1, 4 },
{ YAMI_FOURCC_RGBA, 1, 4 },
{ YAMI_FOURCC_BGRA, 1, 4 },
{ YAMI_FOURCC_ARGB, 1, 4 },
{ YAMI_FOURCC_ABGR, 1, 4 },
{ YAMI_FOURCC_RGB565, 1, 2 },
};
//check selected unsupported format.
//we do not want check all unsupported formats, it will introduce too many dependency on libva
const static uint32_t unsupported[] = {
0,
YAMI_FOURCC_411P,
};
UTILS_TEST(getPlaneResolution)
{
uint32_t width = 1920;
uint32_t height = 1080;
uint32_t planes;
uint32_t w[3];
uint32_t h[3];
for (size_t i = 0; i < N_ELEMENTS(unsupported); i++) {
EXPECT_FALSE(getPlaneResolution(unsupported[i], 1920, 1080, w, h, planes));
EXPECT_EQ(0u, planes);
}
for (size_t i = 0; i < N_ELEMENTS(bppEntrys); i++) {
const BppEntry& e = bppEntrys[i];
EXPECT_TRUE(getPlaneResolution(e.fourcc, width, height, w, h, planes));
EXPECT_EQ(e.planes, planes);
float bpp;
uint32_t bytes = 0;
for (uint32_t p = 0; p < planes; p++) {
bytes += w[p] * h[p];
}
bpp = (float)bytes / (width * height);
EXPECT_FLOAT_EQ(e.bpp, bpp);
}
}
<|endoftext|>
|
<commit_before>/**
* @file singleselect.cc
* @author Leonardo Guilherme de Freitas
* @b family menu
* @b type singleselect
* @addtogroup menu
*
* Defines a single-option menu. A single option
* menu lets you define ordered options with identifcators.
* It handles iteration, focus, selection.
*
* @b provides
* @li @c menu.options List of identificators for menu options @b string
* @li @c menu.circular Shall this menu be treated as a circular menu (last->first->last). Defaults to false. @b bool
* @li @c menu.next Touch to make focus go to the next option @b bool
* @li @c menu.prev Touch to make focus go to the previous option @b bool
* @li @c menu.focus Focused option. This will be set to the focused object. You can set it to focus an arbitrary object. @b string
* @li @c menu.last Last option that was focused. @b string
* @li @c <id>.order Order of this component for iteration @b integer
* @li @c <id>.focused Changed to true when it got focus, false when not. The option with lowest order defaults to 1, others to 0. @b boolean
*/
#include <gear2d/gear2d.h>
using namespace gear2d;
using namespace std;
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
using boost::algorithm::split;
using boost::algorithm::is_any_of;
class singleselect: public component::base {
private:
struct option;
typedef pair<int, option *> ordered;
struct option {
string id;
int order;
int oldorder;
bool focused;
bool select;
set<ordered>::iterator itr;
option()
: id("")
, order(0)
, oldorder(order)
, focused(false)
, select(false) {
}
};
map<string, option *> optionbyid;
set<ordered> optionbyorder;
option * focused;
bool circular;
bool initialized;
public:
singleselect() : focused(0) { }
virtual component::family family() { return "menu"; }
virtual component::type type() { return "singleselect"; }
virtual void handle(parameterbase::id pid, component::base * lastw, object::id owns) {
int p;
if (pid == "menu.options") {
loadoptions(raw<string>(pid));
return;
}
else if (pid == "menu.focus") {
string focusid = raw<string>("menu.focus");
cout << "the focus is changing to " << focusid << endl;
if (focusid == "") focusid = optionbyorder.begin()->second->id;
option * opt = optionbyid[focusid];
// do not touch it again...
if (opt == 0 || opt == focused) return;
if (focused != 0) {
write(focused->id + ".focused", false);
write("menu.last", focused->id);
}
focused = opt;
write(focused->id + ".focused", true);
}
else if (pid == "menu.next") {
set<ordered>::iterator itr = focused->itr;
if (itr != optionbyorder.end()) itr++;
if (itr == optionbyorder.end()) {
if (circular) itr = optionbyorder.begin();
else itr--;
}
write("menu.focus", itr->second->id);
}
else if (pid == "menu.prev") {
set<ordered>::iterator itr = focused->itr;
if (itr == optionbyorder.begin()) {
if (circular) itr = optionbyorder.end();
else itr++;
}
itr--;
write("menu.focus", itr->second->id);
}
else
if ((p = pid.find(".focused")) != parameterbase::id::npos) {
// we set this ourselves, no need to re-run.
if (lastw == this) return;
string oid = pid.substr(0, p);
option * opt = optionbyid[oid];
if (opt == 0) return;
if (opt->focused == true) {
// we got focused but game do not know yet
if (focused != opt) write("menu.focus", opt->id);
}
}
else
if ((p = pid.find(".order")) != parameterbase::id::npos) {
string oid = pid.substr(0, p);
option * opt = optionbyid[oid];
if (opt != 0) {
optionbyorder.erase(ordered(opt->oldorder, opt));
opt->oldorder = opt->order;
// insert there and update iterator
pair<set<ordered>::iterator, bool> success = optionbyorder.insert(ordered(opt->order, opt));
if (success.second) {
// update iterator
opt->itr = success.first;
cout << "success! " << optionbyorder.size() << " ";
}
}
cout << "ordering changes: " << oid << " to " << opt->order << endl;
return;
}
}
virtual void setup(object::signature & sig) {
loadoptions(sig["menu.options"]);
write<string>("menu.options", sig["menu.options"]);
hook("menu.options");
for (map<string, option *>::iterator i = optionbyid.begin(); i != optionbyid.end(); i++) {
option * opt = i->second;
string id = i->first;
write(id + ".order", eval(sig[id + ".order"], 0));
write(id + ".focused", eval(sig[id + ".focus"], false));
cout << "option " << id << " was set up with " << opt->focused << " as focused " << opt->order << " as order " << endl;
}
string focus = sig["menu.focus"];
write("menu.focus", string(""));
write("menu.last", string(""));
hook("menu.focus");
if (focus == "") {
if (optionbyorder.size() != 0) {
focus = optionbyorder.begin()->second->id;
}
}
write<string>("menu.focus", focus);
bind("menu.circular", circular);
circular = eval(sig["menu.circular"], false);
write("menu.next", false);
write("menu.prev", false);
hook("menu.next");
hook("menu.prev");
initialized = false;
}
virtual void update(float dt) {
// just to pull first selection
if (!initialized) { write("menu.focus", raw<string>("menu.focus")); initialized = true; }
}
private:
void loadoptions(const set<string> & ids) {
for (set<string>::iterator id = ids.begin(); id != ids.end(); id++) {
loadoption(*id);
}
}
void loadoptions(const string & optline) {
set<string> ids;
if (optline != "") {
split(ids, optline, is_any_of(" "));
loadoptions(ids);
}
}
void loadoption(string id) {
// do not rewrite an option.
if (optionbyid[id] != 0) return;
option * opt = new option();
opt->id = id;
bind(id + ".order", opt->order);
hook(id + ".order");
bind(id + ".focused", opt->focused);
hook(id + ".focused");
bind(id + ".select", opt->select);
hook(id + ".select");
optionbyid[id] = opt;
}
};
extern "C" {
component::base * build() { return new singleselect; }
}<commit_msg>singleselect.cc updated to include gear2d.h correctly.<commit_after>/**
* @file singleselect.cc
* @author Leonardo Guilherme de Freitas
* @b family menu
* @b type singleselect
* @addtogroup menu
*
* Defines a single-option menu. A single option
* menu lets you define ordered options with identifcators.
* It handles iteration, focus, selection.
*
* @b provides
* @li @c menu.options List of identificators for menu options @b string
* @li @c menu.circular Shall this menu be treated as a circular menu (last->first->last). Defaults to false. @b bool
* @li @c menu.next Touch to make focus go to the next option @b bool
* @li @c menu.prev Touch to make focus go to the previous option @b bool
* @li @c menu.focus Focused option. This will be set to the focused object. You can set it to focus an arbitrary object. @b string
* @li @c menu.last Last option that was focused. @b string
* @li @c <id>.order Order of this component for iteration @b integer
* @li @c <id>.focused Changed to true when it got focus, false when not. The option with lowest order defaults to 1, others to 0. @b boolean
*/
#include "gear2d.h"
using namespace gear2d;
using namespace std;
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
using boost::algorithm::split;
using boost::algorithm::is_any_of;
class singleselect: public component::base {
private:
struct option;
typedef pair<int, option *> ordered;
struct option {
string id;
int order;
int oldorder;
bool focused;
bool select;
set<ordered>::iterator itr;
option()
: id("")
, order(0)
, oldorder(order)
, focused(false)
, select(false) {
}
};
map<string, option *> optionbyid;
set<ordered> optionbyorder;
option * focused;
bool circular;
bool initialized;
public:
singleselect() : focused(0) { }
virtual component::family family() { return "menu"; }
virtual component::type type() { return "singleselect"; }
virtual void handle(parameterbase::id pid, component::base * lastw, object::id owns) {
int p;
if (pid == "menu.options") {
loadoptions(raw<string>(pid));
return;
}
else if (pid == "menu.focus") {
string focusid = raw<string>("menu.focus");
cout << "the focus is changing to " << focusid << endl;
if (focusid == "") focusid = optionbyorder.begin()->second->id;
option * opt = optionbyid[focusid];
// do not touch it again...
if (opt == 0 || opt == focused) return;
if (focused != 0) {
write(focused->id + ".focused", false);
write("menu.last", focused->id);
}
focused = opt;
write(focused->id + ".focused", true);
}
else if (pid == "menu.next") {
set<ordered>::iterator itr = focused->itr;
if (itr != optionbyorder.end()) itr++;
if (itr == optionbyorder.end()) {
if (circular) itr = optionbyorder.begin();
else itr--;
}
write("menu.focus", itr->second->id);
}
else if (pid == "menu.prev") {
set<ordered>::iterator itr = focused->itr;
if (itr == optionbyorder.begin()) {
if (circular) itr = optionbyorder.end();
else itr++;
}
itr--;
write("menu.focus", itr->second->id);
}
else
if ((p = pid.find(".focused")) != parameterbase::id::npos) {
// we set this ourselves, no need to re-run.
if (lastw == this) return;
string oid = pid.substr(0, p);
option * opt = optionbyid[oid];
if (opt == 0) return;
if (opt->focused == true) {
// we got focused but game do not know yet
if (focused != opt) write("menu.focus", opt->id);
}
}
else
if ((p = pid.find(".order")) != parameterbase::id::npos) {
string oid = pid.substr(0, p);
option * opt = optionbyid[oid];
if (opt != 0) {
optionbyorder.erase(ordered(opt->oldorder, opt));
opt->oldorder = opt->order;
// insert there and update iterator
pair<set<ordered>::iterator, bool> success = optionbyorder.insert(ordered(opt->order, opt));
if (success.second) {
// update iterator
opt->itr = success.first;
cout << "success! " << optionbyorder.size() << " ";
}
}
cout << "ordering changes: " << oid << " to " << opt->order << endl;
return;
}
}
virtual void setup(object::signature & sig) {
loadoptions(sig["menu.options"]);
write<string>("menu.options", sig["menu.options"]);
hook("menu.options");
for (map<string, option *>::iterator i = optionbyid.begin(); i != optionbyid.end(); i++) {
option * opt = i->second;
string id = i->first;
write(id + ".order", eval(sig[id + ".order"], 0));
write(id + ".focused", eval(sig[id + ".focus"], false));
cout << "option " << id << " was set up with " << opt->focused << " as focused " << opt->order << " as order " << endl;
}
string focus = sig["menu.focus"];
write("menu.focus", string(""));
write("menu.last", string(""));
hook("menu.focus");
if (focus == "") {
if (optionbyorder.size() != 0) {
focus = optionbyorder.begin()->second->id;
}
}
write<string>("menu.focus", focus);
bind("menu.circular", circular);
circular = eval(sig["menu.circular"], false);
write("menu.next", false);
write("menu.prev", false);
hook("menu.next");
hook("menu.prev");
initialized = false;
}
virtual void update(float dt) {
// just to pull first selection
if (!initialized) { write("menu.focus", raw<string>("menu.focus")); initialized = true; }
}
private:
void loadoptions(const set<string> & ids) {
for (set<string>::iterator id = ids.begin(); id != ids.end(); id++) {
loadoption(*id);
}
}
void loadoptions(const string & optline) {
set<string> ids;
if (optline != "") {
split(ids, optline, is_any_of(" "));
loadoptions(ids);
}
}
void loadoption(string id) {
// do not rewrite an option.
if (optionbyid[id] != 0) return;
option * opt = new option();
opt->id = id;
bind(id + ".order", opt->order);
hook(id + ".order");
bind(id + ".focused", opt->focused);
hook(id + ".focused");
bind(id + ".select", opt->select);
hook(id + ".select");
optionbyid[id] = opt;
}
};
extern "C" {
component::base * build() { return new singleselect; }
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLevelSetFunctionTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageRegionIterator.h"
#include "itkLevelSetFunction.h"
#include "itkDenseFiniteDifferenceImageFilter.h"
/*
* This test exercises the dense p.d.e. solver framework
* itkDenseFiniteDifferenceImageFilter and the two-dimensional level
* set surface modeling function object. It shows how to subclass
* the DenseFiniteDifferenceImageFilter and the LevelSetFunction to
* create a very simple level set surface evolution application.
*
* This application morphs a circle to a square using the level-set surface
* modeling framework. Speed function input to the level-set equation
* is the square distance transform.
*
*/
const unsigned int HEIGHT = (256);
const unsigned int WIDTH = (256);
#define RADIUS (vnl_math_min(HEIGHT, WIDTH)/4)
// Distance transform function for circle
float circle(unsigned x, unsigned y)
{
float dis;
dis = (x - (float)WIDTH/2.0)*(x - (float)WIDTH/2.0)
+ (y - (float)HEIGHT/2.0)*(y - (float)HEIGHT/2.0);
dis = RADIUS - sqrt(dis);
return(dis);
}
// Distance transform function for square
float square(unsigned x, unsigned y)
{
float X, Y;
X = ::fabs(x - (float)WIDTH/2.0);
Y = ::fabs(y - (float)HEIGHT/2.0);
float dis;
if (!((X > RADIUS)&&(Y > RADIUS)))
dis = RADIUS - vnl_math_max(X, Y);
else
dis = -sqrt((X - RADIUS)*(X - RADIUS) + (Y - RADIUS)*(Y - RADIUS));
return(dis);
}
// Evaluates a function at each pixel in the itk image
void evaluate_function(itk::Image<float, 2> *im,
float (*f)(unsigned int, unsigned int) )
{
itk::Image<float, 2>::IndexType idx;
for (unsigned int x = 0; x < WIDTH; ++x)
{
idx[0] = x;
for (unsigned int y = 0; y < HEIGHT; ++y)
{
idx[1] = y;
im->SetPixel(idx, f(x, y) );
}
}
}
namespace itk {
/**
* \class MorphFunction
* Subclasses LevelSetFunction, supplying the ``PropagationSpeed'' term.
*
* See LevelSetFunction for more information.
*/
class MorphFunction : public LevelSetFunction< Image<float, 2> >
{
public:
void SetDistanceTransform (Image<float, 2> *d)
{ m_DistanceTransform = d; }
typedef MorphFunction Self;
typedef LevelSetFunction< Image<float, 2> > Superclass;
typedef Superclass::RadiusType RadiusType;
/**
* Smart pointer support for this class.
*/
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/**
* Run-time type information (and related methods)
*/
itkTypeMacro( MorphFunction, LevelSetFunction );
/**
* Method for creation through the object factory.
*/
itkNewMacro(Self);
protected:
~MorphFunction() {}
MorphFunction()
{
RadiusType r;
r[0] = r[1] = 1;
Superclass::Initialize(r);
}
private:
Image<float, 2>::Pointer m_DistanceTransform;
virtual ScalarValueType PropagationSpeed(
const NeighborhoodType& neighborhood,
const FloatOffsetType
) const
{
Index<2> idx = neighborhood.GetIndex();
return m_DistanceTransform->GetPixel(idx);
}
virtual ScalarValueType PropagationSpeed(const BoundaryNeighborhoodType
&neighborhood, const FloatOffsetType &
) const
{
Index<2> idx = neighborhood.GetIndex();
return m_DistanceTransform->GetPixel(idx);
}
};
class MorphFilter : public
DenseFiniteDifferenceImageFilter< Image<float, 2>, Image<float, 2> >
{
public:
typedef MorphFilter Self;
/**
* Smart pointer support for this class.
*/
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/**
* Run-time type information (and related methods)
*/
itkTypeMacro( MorphFunction, LevelSetFunction );
/**
* Method for creation through the object factory.
*/
itkNewMacro(Self);
itkSetMacro(Iterations, unsigned int);
void SetDistanceTransform(Image<float, 2> *im)
{
((MorphFunction *)(this->GetDifferenceFunction().GetPointer()))
->SetDistanceTransform(im);
}
protected:
~MorphFilter() {}
MorphFilter()
{
MorphFunction::Pointer p = MorphFunction::New();
p->SetPropagationWeight(-1.0);
p->SetAdvectionWeight(0.0);
p->SetCurvatureWeight(1.0);
this->SetDifferenceFunction(p);
m_Iterations = 0;
}
MorphFilter(const Self &) {}
private:
unsigned int m_Iterations;
virtual bool Halt()
{
if (this->GetElapsedIterations() == m_Iterations) return true;
else return false;
}
};
} // end namespace itk
int itkLevelSetFunctionTest(int, char**)
{
typedef itk::Image<float, 2> ImageType;
const int n = 200; // Number of iterations
ImageType::Pointer im_init = ImageType::New();
ImageType::Pointer im_target = ImageType::New();
ImageType::RegionType r;
ImageType::SizeType sz = {{HEIGHT, WIDTH}};
ImageType::IndexType idx = {{0,0}};
r.SetSize(sz);
r.SetIndex(idx);
im_init->SetLargestPossibleRegion(r);
im_init->SetBufferedRegion(r);
im_init->SetRequestedRegion(r);
im_target->SetLargestPossibleRegion(r);
im_target->SetBufferedRegion(r);
im_target->SetRequestedRegion(r);
im_init->Allocate();
im_target->Allocate();
evaluate_function(im_init, circle);
evaluate_function(im_target, square);
itk::ImageRegionIterator<ImageType> itr(im_target,
im_target->GetRequestedRegion());
// Squash level sets everywhere but near the zero set.
for (itr = itr.Begin(); ! itr.IsAtEnd(); ++itr)
{
itr.Value() = itr.Value() /vnl_math_sqrt((5.0f +vnl_math_sqr(itr.Value())));
}
itk::MorphFilter::Pointer mf = itk::MorphFilter::New();
mf->SetDistanceTransform(im_target);
mf->SetIterations(n);
mf->SetInput(im_init);
mf->Update();
return 0;
}
<commit_msg>FIX: Warnings on IRIX<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLevelSetFunctionTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageRegionIterator.h"
#include "itkLevelSetFunction.h"
#include "itkDenseFiniteDifferenceImageFilter.h"
/*
* This test exercises the dense p.d.e. solver framework
* itkDenseFiniteDifferenceImageFilter and the two-dimensional level
* set surface modeling function object. It shows how to subclass
* the DenseFiniteDifferenceImageFilter and the LevelSetFunction to
* create a very simple level set surface evolution application.
*
* This application morphs a circle to a square using the level-set surface
* modeling framework. Speed function input to the level-set equation
* is the square distance transform.
*
*/
const unsigned int HEIGHT = (256);
const unsigned int WIDTH = (256);
#define RADIUS (vnl_math_min(HEIGHT, WIDTH)/4)
// Distance transform function for circle
float circle(unsigned x, unsigned y)
{
float dis;
dis = (x - (float)WIDTH/2.0)*(x - (float)WIDTH/2.0)
+ (y - (float)HEIGHT/2.0)*(y - (float)HEIGHT/2.0);
dis = RADIUS - sqrt(dis);
return(dis);
}
// Distance transform function for square
float square(unsigned x, unsigned y)
{
float X, Y;
X = ::fabs(x - (float)WIDTH/2.0);
Y = ::fabs(y - (float)HEIGHT/2.0);
float dis;
if (!((X > RADIUS)&&(Y > RADIUS)))
dis = RADIUS - vnl_math_max(X, Y);
else
dis = -sqrt((X - RADIUS)*(X - RADIUS) + (Y - RADIUS)*(Y - RADIUS));
return(dis);
}
// Evaluates a function at each pixel in the itk image
void evaluate_function(itk::Image<float, 2> *im,
float (*f)(unsigned int, unsigned int) )
{
itk::Image<float, 2>::IndexType idx;
for (unsigned int x = 0; x < WIDTH; ++x)
{
idx[0] = x;
for (unsigned int y = 0; y < HEIGHT; ++y)
{
idx[1] = y;
im->SetPixel(idx, f(x, y) );
}
}
}
namespace itk {
/**
* \class MorphFunction
* Subclasses LevelSetFunction, supplying the ``PropagationSpeed'' term.
*
* See LevelSetFunction for more information.
*/
class MorphFunction : public LevelSetFunction< Image<float, 2> >
{
public:
void SetDistanceTransform (Image<float, 2> *d)
{ m_DistanceTransform = d; }
typedef MorphFunction Self;
typedef LevelSetFunction< Image<float, 2> > Superclass;
typedef Superclass::RadiusType RadiusType;
/**
* Smart pointer support for this class.
*/
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/**
* Run-time type information (and related methods)
*/
itkTypeMacro( MorphFunction, LevelSetFunction );
/**
* Method for creation through the object factory.
*/
itkNewMacro(Self);
protected:
~MorphFunction() {}
MorphFunction()
{
RadiusType r;
r[0] = r[1] = 1;
Superclass::Initialize(r);
}
private:
Image<float, 2>::Pointer m_DistanceTransform;
virtual ScalarValueType PropagationSpeed(
const NeighborhoodType& neighborhood,
const FloatOffsetType &
) const
{
Index<2> idx = neighborhood.GetIndex();
return m_DistanceTransform->GetPixel(idx);
}
virtual ScalarValueType PropagationSpeed(const BoundaryNeighborhoodType
&neighborhood, const FloatOffsetType &
) const
{
Index<2> idx = neighborhood.GetIndex();
return m_DistanceTransform->GetPixel(idx);
}
};
class MorphFilter : public
DenseFiniteDifferenceImageFilter< Image<float, 2>, Image<float, 2> >
{
public:
typedef MorphFilter Self;
/**
* Smart pointer support for this class.
*/
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/**
* Run-time type information (and related methods)
*/
itkTypeMacro( MorphFunction, LevelSetFunction );
/**
* Method for creation through the object factory.
*/
itkNewMacro(Self);
itkSetMacro(Iterations, unsigned int);
void SetDistanceTransform(Image<float, 2> *im)
{
((MorphFunction *)(this->GetDifferenceFunction().GetPointer()))
->SetDistanceTransform(im);
}
protected:
~MorphFilter() {}
MorphFilter()
{
MorphFunction::Pointer p = MorphFunction::New();
p->SetPropagationWeight(-1.0);
p->SetAdvectionWeight(0.0);
p->SetCurvatureWeight(1.0);
this->SetDifferenceFunction(p);
m_Iterations = 0;
}
MorphFilter(const Self &) {}
private:
unsigned int m_Iterations;
virtual bool Halt()
{
if (this->GetElapsedIterations() == m_Iterations) return true;
else return false;
}
};
} // end namespace itk
int itkLevelSetFunctionTest(int, char**)
{
typedef itk::Image<float, 2> ImageType;
const int n = 200; // Number of iterations
ImageType::Pointer im_init = ImageType::New();
ImageType::Pointer im_target = ImageType::New();
ImageType::RegionType r;
ImageType::SizeType sz = {{HEIGHT, WIDTH}};
ImageType::IndexType idx = {{0,0}};
r.SetSize(sz);
r.SetIndex(idx);
im_init->SetLargestPossibleRegion(r);
im_init->SetBufferedRegion(r);
im_init->SetRequestedRegion(r);
im_target->SetLargestPossibleRegion(r);
im_target->SetBufferedRegion(r);
im_target->SetRequestedRegion(r);
im_init->Allocate();
im_target->Allocate();
evaluate_function(im_init, circle);
evaluate_function(im_target, square);
itk::ImageRegionIterator<ImageType> itr(im_target,
im_target->GetRequestedRegion());
// Squash level sets everywhere but near the zero set.
for (itr = itr.Begin(); ! itr.IsAtEnd(); ++itr)
{
itr.Value() = itr.Value() /vnl_math_sqrt((5.0f +vnl_math_sqr(itr.Value())));
}
itk::MorphFilter::Pointer mf = itk::MorphFilter::New();
mf->SetDistanceTransform(im_target);
mf->SetIterations(n);
mf->SetInput(im_init);
mf->Update();
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVNLRoundProfileTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "vnl/vnl_math.h"
#include "itkTimeProbesCollectorBase.h"
double itkRoundTestHelperFunction( double x )
{
if( x >= 0.0 )
{
return static_cast< int >( x + 0.5f );
}
return static_cast< int >( x - 0.5f );
}
int itkVNLRoundProfileTest1( int, char *[] )
{
itk::TimeProbesCollectorBase chronometer;
typedef std::vector< double > ArrayType;
ArrayType input;
ArrayType output1;
ArrayType output2;
const unsigned long numberOfValues = 1000000L;
const double initialValue = -10.0;
const double valueIncrement = (-initialValue-initialValue) / numberOfValues;
std::cout << "Initial Value = " << initialValue << std::endl;
std::cout << "Value Increment = " << valueIncrement << std::endl;
for( unsigned long i=0; i<numberOfValues; i++)
{
const double inputValue = initialValue + i * valueIncrement;
input.push_back( inputValue );
}
output1.resize( input.size() );
output2.resize( input.size() );
for(unsigned int tours=0; tours < 100; tours++)
{
//
// Count the time of simply assigning values in an std::vector
//
//
ArrayType::const_iterator outItr1src = output1.begin();
ArrayType::iterator outItr2dst = output2.begin();
ArrayType::const_iterator outEnd1 = output1.end();
chronometer.Start("std::vector");
while( outItr1src != outEnd1 )
{
*outItr2dst = *outItr1src;
++outItr1src;
++outItr2dst;
}
chronometer.Stop("std::vector");
ArrayType::const_iterator inpItr = input.begin();
ArrayType::const_iterator inputEnd = input.end();
ArrayType::iterator outItr1nc = output1.begin();
//
// Count the time of rounding plus storing in container
//
chronometer.Start("if-round");
while( inpItr != inputEnd )
{
*outItr1nc = itkRoundTestHelperFunction( *inpItr );
++outItr1nc;
++inpItr;
}
chronometer.Stop("if-round");
inpItr = input.begin();
inputEnd = input.end();
ArrayType::iterator outItr = output2.begin();
//
// Count the time of rounding plus storing in container
//
chronometer.Start("vnl_math_rnd");
while( inpItr != inputEnd )
{
*outItr = vnl_math_rnd( *inpItr );
++outItr;
++inpItr;
}
chronometer.Stop("vnl_math_rnd");
}
chronometer.Report( std::cout );
//
// Now test the correctness of the output
//
ArrayType::const_iterator inpItr = input.begin();
ArrayType::const_iterator inputEnd = input.end();
ArrayType::const_iterator outItr1 = output1.begin();
ArrayType::const_iterator outItr2 = output2.begin();
const double tolerance = 1e-5;
bool testFailed = false;
std::cout << std::endl;
std::cout << std::endl;
while( inpItr != inputEnd )
{
if( vnl_math_abs( *outItr1 - *outItr2 ) > tolerance )
{
std::cerr << "Error in : " << *inpItr << " : " << *outItr1 << " : " << *outItr2 << std::endl;
testFailed = true;
}
++inpItr;
++outItr1;
++outItr2;
}
std::cout << std::endl;
std::cout << "Tested " << output1.size() << " entries " << std::endl;
std::cout << std::endl;
if( testFailed )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Added Functor-based implementation.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVNLRoundProfileTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "vnl/vnl_math.h"
#include "itkTimeProbesCollectorBase.h"
double itkRoundTestHelperFunction( double x )
{
if( x >= 0.0 )
{
return static_cast< int >( x + 0.5f );
}
return static_cast< int >( x - 0.5f );
}
template <class T>
class itkMathFunctor
{
public:
static inline T Round(T x )
{
if( x >= 0.0 )
{
return static_cast< int >( x + 0.5f );
}
return static_cast< int >( x - 0.5f );
}
};
int itkVNLRoundProfileTest1( int, char *[] )
{
itk::TimeProbesCollectorBase chronometer;
typedef std::vector< double > ArrayType;
ArrayType input;
ArrayType output1;
ArrayType output2;
ArrayType output3;
const unsigned long numberOfValues = 1000000L;
const double initialValue = -10.0;
const double valueIncrement = (-initialValue-initialValue) / numberOfValues;
std::cout << "Initial Value = " << initialValue << std::endl;
std::cout << "Value Increment = " << valueIncrement << std::endl;
for( unsigned long i=0; i<numberOfValues; i++)
{
const double inputValue = initialValue + i * valueIncrement;
input.push_back( inputValue );
}
output1.resize( input.size() );
output2.resize( input.size() );
output3.resize( input.size() );
for(unsigned int tours=0; tours < 100; tours++)
{
//
// Count the time of simply assigning values in an std::vector
//
//
ArrayType::const_iterator outItr1src = output1.begin();
ArrayType::iterator outItr2dst = output2.begin();
ArrayType::const_iterator outEnd1 = output1.end();
chronometer.Start("std::vector");
while( outItr1src != outEnd1 )
{
*outItr2dst = *outItr1src;
++outItr1src;
++outItr2dst;
}
chronometer.Stop("std::vector");
ArrayType::const_iterator inpItr = input.begin();
ArrayType::const_iterator inputEnd = input.end();
ArrayType::iterator outItr1nc = output1.begin();
//
// Count the time of rounding plus storing in container
//
chronometer.Start("if-round");
while( inpItr != inputEnd )
{
*outItr1nc = itkRoundTestHelperFunction( *inpItr );
++outItr1nc;
++inpItr;
}
chronometer.Stop("if-round");
inpItr = input.begin();
inputEnd = input.end();
ArrayType::iterator outItr3nc = output3.begin();
//
// Count the time of rounding plus storing in container
//
chronometer.Start("Functor");
while( inpItr != inputEnd )
{
*outItr3nc = itkMathFunctor<double>::Round( *inpItr );
++outItr3nc;
++inpItr;
}
chronometer.Stop("Functor");
inpItr = input.begin();
inputEnd = input.end();
ArrayType::iterator outItr = output2.begin();
//
// Count the time of rounding plus storing in container
//
chronometer.Start("vnl_math_rnd");
while( inpItr != inputEnd )
{
*outItr = vnl_math_rnd( *inpItr );
++outItr;
++inpItr;
}
chronometer.Stop("vnl_math_rnd");
}
chronometer.Report( std::cout );
//
// Now test the correctness of the output
//
ArrayType::const_iterator inpItr = input.begin();
ArrayType::const_iterator inputEnd = input.end();
ArrayType::const_iterator outItr1 = output1.begin();
ArrayType::const_iterator outItr2 = output2.begin();
const double tolerance = 1e-5;
bool testFailed = false;
std::cout << std::endl;
std::cout << std::endl;
while( inpItr != inputEnd )
{
if( vnl_math_abs( *outItr1 - *outItr2 ) > tolerance )
{
std::cerr << "Error in : " << *inpItr << " : " << *outItr1 << " : " << *outItr2 << std::endl;
testFailed = true;
}
++inpItr;
++outItr1;
++outItr2;
}
std::cout << std::endl;
std::cout << "Tested " << output1.size() << " entries " << std::endl;
std::cout << std::endl;
if( testFailed )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "itkCastImageFilter.h"
/**
* This test reproduces a problem encountered with CastImageFilter and a streaming
* writer. When the image to write is already loaded in memory and InPlaceOn() is
* called, only the first stripe is repeated across the output image.
* Issue number 0000428
*/
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cout << argv[0] << " <input image> <output image>" << std::endl;
return EXIT_FAILURE;
}
typedef otb::Image<float,2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
typedef itk::CastImageFilter<ImageType,ImageType> CastFilterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
reader->Update();
CastFilterType::Pointer caster = CastFilterType::New();
caster->SetInput( reader->GetOutput() );
caster->InPlaceOn();
WriterType::Pointer writer = WriterType::New();
writer->SetInput(caster->GetOutput());
writer->SetFileName(argv[2]);
//writer->SetAutomaticTiledStreaming(1024);
writer->SetNumberOfDivisionsStrippedStreaming(10);
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>STYLE<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "itkCastImageFilter.h"
/**
* This test reproduces a problem encountered with CastImageFilter and a streaming
* writer. When the image to write is already loaded in memory and InPlaceOn() is
* called, only the first stripe is repeated across the output image.
* Issue number 0000428
*/
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cout << argv[0] << " <input image> <output image>" << std::endl;
return EXIT_FAILURE;
}
typedef otb::Image<float, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
typedef itk::CastImageFilter<ImageType, ImageType> CastFilterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
reader->Update();
CastFilterType::Pointer caster = CastFilterType::New();
caster->SetInput( reader->GetOutput() );
caster->InPlaceOn();
WriterType::Pointer writer = WriterType::New();
writer->SetInput(caster->GetOutput());
writer->SetFileName(argv[2]);
//writer->SetAutomaticTiledStreaming(1024);
writer->SetNumberOfDivisionsStrippedStreaming(10);
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2009 by Jeff Weisberg
Author: Jeff Weisberg <jaw @ tcp4me.com>
Created: 2009-Jan-23 10:02 (EST)
Function: console commands
$Id$
*/
#define CURRENT_SUBSYSTEM 'C'
#include "defs.h"
#include "misc.h"
#include "diag.h"
#include "hrtime.h"
#include "thread.h"
#include "config.h"
#include "console.h"
#include "network.h"
#include "lock.h"
#include "runmode.h"
#include "maint.h"
#include "zdb.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
static int cmd_exit(Console *, const char *, int);
static int cmd_echo(Console *, const char *, int);
static int cmd_none(Console *, const char *, int);
static int cmd_debug(Console *, const char *, int);
static int cmd_shut(Console *, const char *, int);
static int cmd_load(Console *, const char *, int);
static int cmd_reqs(Console *, const char *, int);
static int cmd_rps(Console *, const char *, int);
static int cmd_status(Console *, const char *, int);
static int cmd_help(Console *, const char *, int);
static int cmd_reload(Console *, const char *, int);
static int cmd_maint(Console *, const char *, int);
static int cmd_probe(Console *, const char *, int);
static int cmd_stats(Console *, const char *, int);
static struct {
const char *name;
int visible;
int (*func)(Console *, const char *, int);
} commands[] = {
{ "", 0, cmd_none },
{ "exit", 1, cmd_exit },
{ "echo", 1, cmd_echo },
{ "mon", 1, cmd_debug },
{ "shutdown", 1, cmd_shut },
{ "status", 1, cmd_status },
{ "load", 1, cmd_load }, // load
{ "reqs", 1, cmd_reqs }, // number of requests handled
{ "rps", 1, cmd_rps }, // requests per second
{ "reload", 1, cmd_reload },
{ "maint", 1, cmd_maint },
{ "probestatus", 0, cmd_probe }, // used by monitor process to update statuses
{ "stats", 1, cmd_stats },
{ "help", 1, cmd_help },
{ "?", 0, cmd_help },
};
extern DNS_Stats net_stats;
static struct {
const char *name;
const char fmt;
const void *data;
} statscmd[] = {
#include "stats_cmd.h"
};
static int
cmd_none(Console *con, const char *cmd, int len){
return 1;
}
static int
cmd_exit(Console *con, const char *cmd, int len){
return 0;
}
static int
cmd_echo(Console *con, const char *cmd, int len){
con->output(cmd);
return 1;
}
static int
cmd_reload(Console *con, const char *cmd, int len){
extern int force_reload;
force_reload = 1;
con->output("OK\n");
return 1;
}
static int
cmd_load(Console *con, const char *cmd, int len){
char buf[32];
snprintf(buf, sizeof(buf), "%.4f\n", net_utiliz);
con->output(buf);
return 1;
}
static int
cmd_reqs(Console *con, const char *cmd, int len){
char buf[32];
snprintf(buf, sizeof(buf), "%lld\n", net_requests);
con->output(buf);
return 1;
}
static int
cmd_rps(Console *con, const char *cmd, int len){
char buf[32];
snprintf(buf, sizeof(buf), "%.4f\n", net_req_per_sec);
con->output(buf);
return 1;
}
static void
output_stat(Console *con, int idx, bool align){
char buf[32];
const char *v;
switch(statscmd[idx].fmt){
case 's':
v = (char*) statscmd[idx].data;
break;
case 'f':
snprintf(buf, sizeof(buf), "%.6f", * (float*)statscmd[idx].data);
v = buf;
break;
case 'd':
snprintf(buf, sizeof(buf), "%d", * (int*)statscmd[idx].data);
v = buf;
break;
case 'q':
snprintf(buf, sizeof(buf), "%lld", * (int64_t*)statscmd[idx].data);
v = buf;
break;
default:
BUG("corrupt stats table");
return;
}
con->output(statscmd[idx].name);
if( align ){
int l = strlen(statscmd[idx].name);
for(int i=l; i<24; i++) con->output(" ");
}
con->output(" ");
con->output(v);
con->output("\n");
}
static int
cmd_stats(Console *con, const char *cmd, int len){
while( len && isspace(*cmd) ){ cmd++; len--; } // eat white
bool all = ! strcmp(cmd, "all");
bool ok = 0;
for(int i=0; i<ELEMENTSIN(statscmd); i++){
if( all || !strcmp(cmd, statscmd[i].name) ){
output_stat(con, i, all);
ok = 1;
}
}
if( !ok )
con->output("no such stat\n");
return 1;
}
static int
cmd_probe(Console *con, const char *cmd, int len){
// probestatus index uid status
int idx = 0;
int uid = 0;
int stat = 0;
ZDB *z = zdb;
sscanf(cmd, "%d %d %d", &idx, &uid, &stat);
if( idx < 0 || idx >= z->monitored.size() ) return 1;
RR* rr = z->monitored[idx];
if( !rr->probe || rr->probe->uid != uid ) return 1;
DEBUG("probe status %d %d => %d", idx, uid, stat);
if( !stat ){
VERBOSE("%s is DOWN", rr->name.c_str());
}
rr->probe_ok = stat;
return 1;
}
static int
cmd_maint(Console *con, const char *cmd, int len){
bool stat;
const char *dc;
// maint online|offline datacenter
while( len && isspace(*cmd) ){ cmd++; len--; } // eat white
dc = cmd;
while( *dc && !isspace(*dc) ) dc ++; // find datacenter
if( *dc ) dc ++;
if( !strncmp(cmd, "online", 6) ){
stat = 0;
}
else if( !strncmp(cmd, "offline", 7) ){
stat = 1;
}
else{
con->output("? maint online|offline datacenter\n");
return 1;
}
if( !maint_set(dc, stat) ){
con->output("invalid datacenter\n");
return 1;
}
VERBOSE("datacenter %s %s", dc, stat? "OFFLINE" : "ONLINE");
return 1;
}
// debug <number>
// debug off
static int
cmd_debug(Console *con, const char *cmd, int len){
char *ep;
int n;
// eat white
while( len && isspace(*cmd) ){ cmd++; len--; }
n = strtol(cmd, &ep, 10);
if( ep != cmd ){
con->set_loglevel(n);
}else if( !strncmp(cmd, "on", 2) ){
con->set_loglevel(8);
}else if( !strncmp(cmd, "off", 3) ){
con->set_loglevel(-1);
}else{
con->output("? mon on|off|<number>\n");
}
return 1;
}
static int
cmd_shut(Console *con, const char *cmd, int len){
time_t now = lr_now();
// eat white
while( len && isspace(*cmd) ){ cmd++; len--; }
if( !strncmp(cmd, "immediate", 9) ){
VERBOSE("immediate shutdown initiated");
con->output("shutting down\n");
runmode.shutdown();
}else if( !strncmp(cmd, "graceful", 8) ){
VERBOSE("graceful shutdown initiated");
con->output("winding down\n");
runmode.winddown();
}else if( !strncmp(cmd, "restart", 7) ){
VERBOSE("shutdown + restart initiated");
con->output("winding down\n");
runmode.winddown_and_restart();
}else if( !strncmp(cmd, "crash", 5) ){
// in case the system is hung hard (but we can somehow get to the console)
VERBOSE("crash hard + restart initiated");
con->output("crashing\n");
_exit(EXIT_ERROR_RESTART);
}else if( !strncmp(cmd, "cancel", 6) ){
VERBOSE("canceling shutdown");
con->output("canceling shutdown\n");
// NB: there is a race condition here
runmode.cancel();
}else{
con->output("? shutdown graceful|immediate|restart|crash|cancel\n");
}
return 1;
}
static int
cmd_status(Console *con, const char *cmd, int len){
switch( runmode.mode() ){
case RUN_LOLA_RUN:
con->output("running OK\n");
break;
case RUN_MODE_WINDDOWN:
if( runmode.final_exit_value() ){
con->output("graceful restart underway\n");
}else{
con->output("graceful shutdown underway\n");
}
break;
case RUN_MODE_EXITING:
if( runmode.final_exit_value() ){
con->output("restart underway\n");
}else{
con->output("shutdown underway\n");
}
break;
case RUN_MODE_ERRORED:
con->output("error recovery underway\n");
break;
default:
con->output("confused\n");
break;
}
return 1;
}
static int
cmd_help(Console *con, const char *cmd, int len){
con->output("commands:");
for(int i=0; i<ELEMENTSIN(commands); i++){
if( !commands[i].visible ) continue;
con->output(" ");
con->output(commands[i].name);
}
con->output("\n");
return 1;
}
//################################################################
static int
match(const char *c, const char *s, int l){
int p = 0;
while( 1 ){
if( !*c ){
if( p == l ) return p; // full match
if( isspace(*s) ) return p; // match plus more
return -1; // no match
}
if( p == l ) return -1; // end of input
if( *c != *s ) return -1; // no match
c++;
s++;
p++;
}
return -1;
}
int
run_command(Console *con, const char *cmd, int len){
for(int i=0; i<ELEMENTSIN(commands); i++){
int o = match(commands[i].name, cmd, len);
if( o != -1 ){
return commands[i].func(con, cmd + o, len - o);
}
}
con->output("command not found\n");
return 1;
}
<commit_msg>stats output format<commit_after>/*
Copyright (c) 2009 by Jeff Weisberg
Author: Jeff Weisberg <jaw @ tcp4me.com>
Created: 2009-Jan-23 10:02 (EST)
Function: console commands
$Id$
*/
#define CURRENT_SUBSYSTEM 'C'
#include "defs.h"
#include "misc.h"
#include "diag.h"
#include "hrtime.h"
#include "thread.h"
#include "config.h"
#include "console.h"
#include "network.h"
#include "lock.h"
#include "runmode.h"
#include "maint.h"
#include "zdb.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
static int cmd_exit(Console *, const char *, int);
static int cmd_echo(Console *, const char *, int);
static int cmd_none(Console *, const char *, int);
static int cmd_debug(Console *, const char *, int);
static int cmd_shut(Console *, const char *, int);
static int cmd_load(Console *, const char *, int);
static int cmd_reqs(Console *, const char *, int);
static int cmd_rps(Console *, const char *, int);
static int cmd_status(Console *, const char *, int);
static int cmd_help(Console *, const char *, int);
static int cmd_reload(Console *, const char *, int);
static int cmd_maint(Console *, const char *, int);
static int cmd_probe(Console *, const char *, int);
static int cmd_stats(Console *, const char *, int);
static struct {
const char *name;
int visible;
int (*func)(Console *, const char *, int);
} commands[] = {
{ "", 0, cmd_none },
{ "exit", 1, cmd_exit },
{ "echo", 1, cmd_echo },
{ "mon", 1, cmd_debug },
{ "shutdown", 1, cmd_shut },
{ "status", 1, cmd_status },
{ "load", 1, cmd_load }, // load
{ "reqs", 1, cmd_reqs }, // number of requests handled
{ "rps", 1, cmd_rps }, // requests per second
{ "reload", 1, cmd_reload },
{ "maint", 1, cmd_maint },
{ "probestatus", 0, cmd_probe }, // used by monitor process to update statuses
{ "stats", 1, cmd_stats },
{ "help", 1, cmd_help },
{ "?", 0, cmd_help },
};
extern DNS_Stats net_stats;
static struct {
const char *name;
const char fmt;
const void *data;
} statscmd[] = {
#include "stats_cmd.h"
};
static int
cmd_none(Console *con, const char *cmd, int len){
return 1;
}
static int
cmd_exit(Console *con, const char *cmd, int len){
return 0;
}
static int
cmd_echo(Console *con, const char *cmd, int len){
con->output(cmd);
return 1;
}
static int
cmd_reload(Console *con, const char *cmd, int len){
extern int force_reload;
force_reload = 1;
con->output("OK\n");
return 1;
}
static int
cmd_load(Console *con, const char *cmd, int len){
char buf[32];
snprintf(buf, sizeof(buf), "%.4f\n", net_utiliz);
con->output(buf);
return 1;
}
static int
cmd_reqs(Console *con, const char *cmd, int len){
char buf[32];
snprintf(buf, sizeof(buf), "%lld\n", net_requests);
con->output(buf);
return 1;
}
static int
cmd_rps(Console *con, const char *cmd, int len){
char buf[32];
snprintf(buf, sizeof(buf), "%.4f\n", net_req_per_sec);
con->output(buf);
return 1;
}
static void
output_stat(Console *con, int idx, bool table){
char buf[32];
const char *v;
switch(statscmd[idx].fmt){
case 's':
v = (char*) statscmd[idx].data;
break;
case 'f':
snprintf(buf, sizeof(buf), "%.6f", * (float*)statscmd[idx].data);
v = buf;
break;
case 'd':
snprintf(buf, sizeof(buf), "%d", * (int*)statscmd[idx].data);
v = buf;
break;
case 'q':
snprintf(buf, sizeof(buf), "%lld", * (int64_t*)statscmd[idx].data);
v = buf;
break;
default:
BUG("corrupt stats table");
return;
}
if( table ){
con->output(statscmd[idx].name);
int l = strlen(statscmd[idx].name);
for(int i=l; i<24; i++) con->output(" ");
con->output(" ");
}
con->output(v);
con->output("\n");
}
static int
cmd_stats(Console *con, const char *cmd, int len){
while( len && isspace(*cmd) ){ cmd++; len--; } // eat white
bool all = ! strcmp(cmd, "all");
bool ok = 0;
for(int i=0; i<ELEMENTSIN(statscmd); i++){
if( all || !strcmp(cmd, statscmd[i].name) ){
output_stat(con, i, all);
ok = 1;
}
}
if( !ok )
con->output("no such stat\n");
return 1;
}
static int
cmd_probe(Console *con, const char *cmd, int len){
// probestatus index uid status
int idx = 0;
int uid = 0;
int stat = 0;
ZDB *z = zdb;
sscanf(cmd, "%d %d %d", &idx, &uid, &stat);
if( idx < 0 || idx >= z->monitored.size() ) return 1;
RR* rr = z->monitored[idx];
if( !rr->probe || rr->probe->uid != uid ) return 1;
DEBUG("probe status %d %d => %d", idx, uid, stat);
if( !stat ){
VERBOSE("%s is DOWN", rr->name.c_str());
}
rr->probe_ok = stat;
return 1;
}
static int
cmd_maint(Console *con, const char *cmd, int len){
bool stat;
const char *dc;
// maint online|offline datacenter
while( len && isspace(*cmd) ){ cmd++; len--; } // eat white
dc = cmd;
while( *dc && !isspace(*dc) ) dc ++; // find datacenter
if( *dc ) dc ++;
if( !strncmp(cmd, "online", 6) ){
stat = 0;
}
else if( !strncmp(cmd, "offline", 7) ){
stat = 1;
}
else{
con->output("? maint online|offline datacenter\n");
return 1;
}
if( !maint_set(dc, stat) ){
con->output("invalid datacenter\n");
return 1;
}
VERBOSE("datacenter %s %s", dc, stat? "OFFLINE" : "ONLINE");
return 1;
}
// debug <number>
// debug off
static int
cmd_debug(Console *con, const char *cmd, int len){
char *ep;
int n;
// eat white
while( len && isspace(*cmd) ){ cmd++; len--; }
n = strtol(cmd, &ep, 10);
if( ep != cmd ){
con->set_loglevel(n);
}else if( !strncmp(cmd, "on", 2) ){
con->set_loglevel(8);
}else if( !strncmp(cmd, "off", 3) ){
con->set_loglevel(-1);
}else{
con->output("? mon on|off|<number>\n");
}
return 1;
}
static int
cmd_shut(Console *con, const char *cmd, int len){
time_t now = lr_now();
// eat white
while( len && isspace(*cmd) ){ cmd++; len--; }
if( !strncmp(cmd, "immediate", 9) ){
VERBOSE("immediate shutdown initiated");
con->output("shutting down\n");
runmode.shutdown();
}else if( !strncmp(cmd, "graceful", 8) ){
VERBOSE("graceful shutdown initiated");
con->output("winding down\n");
runmode.winddown();
}else if( !strncmp(cmd, "restart", 7) ){
VERBOSE("shutdown + restart initiated");
con->output("winding down\n");
runmode.winddown_and_restart();
}else if( !strncmp(cmd, "crash", 5) ){
// in case the system is hung hard (but we can somehow get to the console)
VERBOSE("crash hard + restart initiated");
con->output("crashing\n");
_exit(EXIT_ERROR_RESTART);
}else if( !strncmp(cmd, "cancel", 6) ){
VERBOSE("canceling shutdown");
con->output("canceling shutdown\n");
// NB: there is a race condition here
runmode.cancel();
}else{
con->output("? shutdown graceful|immediate|restart|crash|cancel\n");
}
return 1;
}
static int
cmd_status(Console *con, const char *cmd, int len){
switch( runmode.mode() ){
case RUN_LOLA_RUN:
con->output("running OK\n");
break;
case RUN_MODE_WINDDOWN:
if( runmode.final_exit_value() ){
con->output("graceful restart underway\n");
}else{
con->output("graceful shutdown underway\n");
}
break;
case RUN_MODE_EXITING:
if( runmode.final_exit_value() ){
con->output("restart underway\n");
}else{
con->output("shutdown underway\n");
}
break;
case RUN_MODE_ERRORED:
con->output("error recovery underway\n");
break;
default:
con->output("confused\n");
break;
}
return 1;
}
static int
cmd_help(Console *con, const char *cmd, int len){
con->output("commands:");
for(int i=0; i<ELEMENTSIN(commands); i++){
if( !commands[i].visible ) continue;
con->output(" ");
con->output(commands[i].name);
}
con->output("\n");
return 1;
}
//################################################################
static int
match(const char *c, const char *s, int l){
int p = 0;
while( 1 ){
if( !*c ){
if( p == l ) return p; // full match
if( isspace(*s) ) return p; // match plus more
return -1; // no match
}
if( p == l ) return -1; // end of input
if( *c != *s ) return -1; // no match
c++;
s++;
p++;
}
return -1;
}
int
run_command(Console *con, const char *cmd, int len){
for(int i=0; i<ELEMENTSIN(commands); i++){
int o = match(commands[i].name, cmd, len);
if( o != -1 ){
return commands[i].func(con, cmd + o, len - o);
}
}
con->output("command not found\n");
return 1;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.org
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __BOHRIUM_BRIDGE_CPP_GENERATOR
#define __BOHRIUM_BRIDGE_CPP_GENERATOR
namespace bh {
template <typename T, typename ...Dimensions>
multi_array<T>& value(T val, const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
*result = val;
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& empty(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& ones(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
*result = (T)1;
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& zeros(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
*result = (T)0;
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& random(const Dimensions&... shape)
{
bh_random_type* rinstr = (bh_random_type*)malloc(sizeof(bh_random_type));
if (rinstr == NULL) {
char err_msg[100];
sprintf(err_msg, "Failed alllocating memory for extension-call.");
throw std::runtime_error(err_msg);
}
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
rinstr->id = Runtime::instance().random_id; //Set the instruction
rinstr->nout = 1;
rinstr->nin = 0;
rinstr->struct_size = sizeof(bh_random_type);
rinstr->operand[0] = result->meta;
Runtime::instance().enqueue<T>((bh_userfunc*)rinstr);
return *result;
}
template <typename T>
multi_array<T>& random(const int64_t rank, const int64_t* shape)
{
bh_random_type* rinstr = (bh_random_type*)malloc(sizeof(bh_random_type));
if (rinstr == NULL) {
char err_msg[100];
sprintf(err_msg, "Failed alllocating memory for extension-call.");
throw std::runtime_error(err_msg);
}
multi_array<T>* result = new multi_array<T>(rank, shape);
result->setTemp(true);
result->link();
rinstr->id = Runtime::instance().random_id; //Set the instruction
rinstr->nout = 1;
rinstr->nin = 0;
rinstr->struct_size = sizeof(bh_random_type);
rinstr->operand[0] = result->meta;
Runtime::instance().enqueue<T>((bh_userfunc*)rinstr);
return *result;
}
template <typename T>
multi_array<T>& arange(const int64_t start, const int64_t end, const int64_t skip)
{
const int64_t tmp[] = { end - start };
multi_array<T>* result = new multi_array<T>((const int64_t)1, tmp);
result->setTemp(true);
result->link();
*result *= skip;
*result += start;
std::cout << "range(" << start << "," << end << "," << skip << ");" << std::endl;
return *result;
}
}
#endif
<commit_msg>Corrected implementation of arange<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.org
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __BOHRIUM_BRIDGE_CPP_GENERATOR
#define __BOHRIUM_BRIDGE_CPP_GENERATOR
namespace bh {
template <typename T, typename ...Dimensions>
multi_array<T>& value(T val, const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
*result = val;
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& empty(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& ones(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
*result = (T)1;
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& zeros(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
*result = (T)0;
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& random(const Dimensions&... shape)
{
bh_random_type* rinstr = (bh_random_type*)malloc(sizeof(bh_random_type));
if (rinstr == NULL) {
char err_msg[100];
sprintf(err_msg, "Failed alllocating memory for extension-call.");
throw std::runtime_error(err_msg);
}
multi_array<T>* result = new multi_array<T>(shape...);
result->setTemp(true);
result->link();
rinstr->id = Runtime::instance().random_id; //Set the instruction
rinstr->nout = 1;
rinstr->nin = 0;
rinstr->struct_size = sizeof(bh_random_type);
rinstr->operand[0] = result->meta;
Runtime::instance().enqueue<T>((bh_userfunc*)rinstr);
return *result;
}
template <typename T>
multi_array<T>& random(const int64_t rank, const int64_t* shape)
{
bh_random_type* rinstr = (bh_random_type*)malloc(sizeof(bh_random_type));
if (rinstr == NULL) {
char err_msg[100];
sprintf(err_msg, "Failed alllocating memory for extension-call.");
throw std::runtime_error(err_msg);
}
multi_array<T>* result = new multi_array<T>(rank, shape);
result->setTemp(true);
result->link();
rinstr->id = Runtime::instance().random_id; //Set the instruction
rinstr->nout = 1;
rinstr->nin = 0;
rinstr->struct_size = sizeof(bh_random_type);
rinstr->operand[0] = result->meta;
Runtime::instance().enqueue<T>((bh_userfunc*)rinstr);
return *result;
}
template <typename T>
multi_array<T>& arange(const int64_t start, const int64_t end, const int64_t skip)
{
const int64_t tmp[] = { end - start };
multi_array<T>* result = new multi_array<T>((const int64_t)1, tmp);
result->setTemp(true);
result->link();
for(int64_t i = 0; i < (end-start); i++) {
(*result)[i] = (T)i;
}
*result *= skip;
*result += start;
std::cout << "arange(" << start << "," << end << "," << skip << ");" << std::endl;
return *result;
}
}
#endif
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.org
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __BOHRIUM_BRIDGE_CPP_GENERATOR
#define __BOHRIUM_BRIDGE_CPP_GENERATOR
namespace bh {
template <typename T, typename ...Dimensions>
multi_array<T>& value(T val, const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
*result = val;
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& empty(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& ones(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
*result = (T)1;
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& zeros(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
*result = (T)0;
result->setTemp(true);
return *result;
}
#ifndef NO_VARIADICS
template <typename T, typename ...Dimensions>
multi_array<T>& rand(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)time(NULL), *result);
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& randu(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)time(NULL), *result);
Runtime::instance().enqueue((bh_opcode)BH_DIVIDE, *result, (T)1, *result);
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& randn(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)time(NULL), *result);
Runtime::instance().enqueue((bh_opcode)BH_DIVIDE, *result, (T)1, *result);
result->setTemp(true);
return *result;
}
#endif
template <typename T>
multi_array<T>& random(const int64_t length)
{
multi_array<T>* result = new multi_array<T>(1, &length);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)42, *result);
result->setTemp(true);
return *result;
}
template <typename T>
multi_array<T>& range(const int64_t start, const int64_t end, const int64_t skip)
{
if ((start > end) && (skip>0)) {
throw std::runtime_error("Error: Invalid range [start>end when skip>0].");
} else if((start < end) && (skip<0)) {
throw std::runtime_error("Error: Invalid range [start<end when skip<0].");
} else if (skip==0) {
throw std::runtime_error("Error: Invalid range [skip=0].");
} else if (start==end) {
throw std::runtime_error("Error: Invalid range [start=end].");
}
uint64_t nelem;
if (skip>0) {
nelem = (end-start+1)/skip;
} else {
nelem = (start-end+1)/abs(skip);
}
multi_array<T>* result = new multi_array<T>(nelem);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)skip);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)start);
result->setTemp(true);
return *result;
}
}
#endif
<commit_msg>Fixed building C++/C bridge without Variadics<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.org
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __BOHRIUM_BRIDGE_CPP_GENERATOR
#define __BOHRIUM_BRIDGE_CPP_GENERATOR
namespace bh {
template <typename T, typename ...Dimensions>
multi_array<T>& value(T val, const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
*result = val;
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& empty(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& ones(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
*result = (T)1;
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& zeros(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
*result = (T)0;
result->setTemp(true);
return *result;
}
#ifndef NO_VARIADICS
template <typename T, typename ...Dimensions>
multi_array<T>& rand(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)time(NULL), *result);
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& randu(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)time(NULL), *result);
Runtime::instance().enqueue((bh_opcode)BH_DIVIDE, *result, (T)1, *result);
result->setTemp(true);
return *result;
}
template <typename T, typename ...Dimensions>
multi_array<T>& randn(const Dimensions&... shape)
{
multi_array<T>* result = new multi_array<T>(shape...);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)time(NULL), *result);
Runtime::instance().enqueue((bh_opcode)BH_DIVIDE, *result, (T)1, *result);
result->setTemp(true);
return *result;
}
#endif
template <typename T>
multi_array<T>& random(const int64_t length)
{
multi_array<T>* result = new multi_array<T>(1, &length);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)0);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)1);
Runtime::instance().enqueue((bh_opcode)BH_RANDOM, *result, (T)42, *result);
result->setTemp(true);
return *result;
}
template <typename T>
multi_array<T>& range(const int64_t start, const int64_t end, const int64_t skip)
{
if ((start > end) && (skip>0)) {
throw std::runtime_error("Error: Invalid range [start>end when skip>0].");
} else if((start < end) && (skip<0)) {
throw std::runtime_error("Error: Invalid range [start<end when skip<0].");
} else if (skip==0) {
throw std::runtime_error("Error: Invalid range [skip=0].");
} else if (start==end) {
throw std::runtime_error("Error: Invalid range [start=end].");
}
int64_t nelem;
if (skip>0) {
nelem = (end-start+1)/skip;
} else {
nelem = (start-end+1)/abs(skip);
}
multi_array<T>* result = new multi_array<T>(1, &nelem);
result->link();
Runtime::instance().enqueue((bh_opcode)BH_RANGE, *result);
Runtime::instance().enqueue((bh_opcode)BH_MULTIPLY, *result, *result, (T)skip);
Runtime::instance().enqueue((bh_opcode)BH_ADD, *result, *result, (T)start);
result->setTemp(true);
return *result;
}
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
* Copyright (C) 2011-2013 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet 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. *
* *
* TeapotNet 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 TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "tpn/config.h"
#include "tpn/file.h"
#include "tpn/core.h"
#include "tpn/portmapping.h"
#include "tpn/httptunnel.h" // for user agent
namespace tpn
{
StringMap Config::Params;
Mutex Config::ParamsMutex;
bool Config::UpdateAvailableFlag = false;
String Config::Get(const String &key)
{
ParamsMutex.lock();
String value;
if(Params.get(key, value))
{
ParamsMutex.unlock();
return value;
}
ParamsMutex.unlock();
//throw Exception("Config: no entry for \""+key+"\"");
return "";
}
void Config::Put(const String &key, const String &value)
{
ParamsMutex.lock();
Params.insert(key, value);
ParamsMutex.unlock();
}
void Config::Default(const String &key, const String &value)
{
ParamsMutex.lock();
if(!Params.contains(key)) Params.insert(key, value);
ParamsMutex.unlock();
}
void Config::Load(const String &filename)
{
ParamsMutex.lock();
try {
File file(filename, File::Read);
file.read(Params);
file.close();
}
catch(const Exception &e)
{
LogError("Config", String("Unable to load config: ") + e.what());
}
ParamsMutex.unlock();
}
void Config::Save(const String &filename)
{
ParamsMutex.lock();
try {
File file(filename, File::Truncate);
file.write(Params);
file.close();
}
catch(...)
{
ParamsMutex.unlock();
throw;
}
ParamsMutex.unlock();
}
void Config::GetExternalAddresses(List<Address> &list)
{
list.clear();
String externalAddress = Config::Get("external_address");
if(!externalAddress.empty() && externalAddress != "auto")
{
Address addr;
if(externalAddress.contains(':')) addr.set(externalAddress);
else {
String port = Config::Get("port");
String externalPort = Config::Get("external_port");
if(!externalPort.empty() && externalPort != "auto") port = externalPort;
addr.set(externalAddress, port);
}
list.push_back(addr);
}
List<Address> tmp;
Core::Instance->getAddresses(tmp);
for(List<Address>::const_iterator it = tmp.begin();
it != tmp.end();
++it)
{
const Address &addr = *it;
if(addr.addrFamily() == AF_INET)
{
String host = PortMapping::Instance->getExternalHost();
if(!host.empty())
{
uint16_t port;
PortMapping::Instance->get(PortMapping::TCP, addr.port(), port);
list.push_back(Address(host, port));
}
}
String host = addr.host();
if(host != "127.0.0.1" && host != "::1"
&& std::find(list.begin(), list.end(), addr) == list.end())
{
list.push_back(addr);
}
}
}
bool Config::CheckUpdate(void)
{
#if defined(ANDROID)
return false;
#elif defined(WINDOWS)
String release = "win32";
#elif defined(MACOSX)
String release = "osx";
#else
String release = "src";
#endif
try {
LogInfo("Config::CheckUpdate", "Looking for updates...");
String url = String(DOWNLOADURL) + "?version&release=" + release + "¤t=" + APPVERSION;
String content;
int result = Http::Get(url, &content);
if(result != 200)
throw Exception("HTTP error code " + String::number(result));
unsigned lastVersion = content.trimmed().dottedToInt();
unsigned appVersion = String(APPVERSION).dottedToInt();
Assert(appVersion != 0);
if(lastVersion > appVersion)
{
UpdateAvailableFlag = true;
return true;
}
}
catch(const Exception &e)
{
LogWarn("Config::CheckUpdate", String("Unable to look for updates: ") + e.what());
}
return false;
}
bool Config::IsUpdateAvailable(void)
{
return UpdateAvailableFlag;
}
bool Config::GetProxyForUrl(const String &url, Address &addr)
{
String proxy = Get("http_proxy").trimmed();
if(proxy == "none")
{
return false;
}
if(!proxy.empty() && proxy != "auto")
{
addr.fromString(proxy);
return true;
}
#ifdef WINDOWS
typedef LPVOID HINTERNET;
typedef struct {
DWORD dwAccessType;
LPWSTR lpszProxy;
LPWSTR lpszProxyBypass;
} WINHTTP_PROXY_INFO;
typedef struct {
BOOL fAutoDetect;
LPWSTR lpszAutoConfigUrl;
LPWSTR lpszProxy;
LPWSTR lpszProxyBypass;
} WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
typedef struct {
DWORD dwFlags;
DWORD dwAutoDetectFlags;
LPCWSTR lpszAutoConfigUrl;
LPVOID lpvReserved;
DWORD dwReserved;
BOOL fAutoLogonIfChallenged;
} WINHTTP_AUTOPROXY_OPTIONS;
#define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY 0
#define WINHTTP_ACCESS_TYPE_NO_PROXY 1
#define WINHTTP_ACCESS_TYPE_NAMED_PROXY 3
#define WINHTTP_AUTOPROXY_AUTO_DETECT 0x00000001
#define WINHTTP_AUTOPROXY_CONFIG_URL 0x00000002
#define WINHTTP_AUTO_DETECT_TYPE_DHCP 0x00000001
#define WINHTTP_AUTO_DETECT_TYPE_DNS_A 0x00000002
#define WINHTTP_ERROR_BASE 12000
#define ERROR_WINHTTP_LOGIN_FAILURE (WINHTTP_ERROR_BASE + 15)
#define ERROR_WINHTTP_AUTODETECTION_FAILED (WINHTTP_ERROR_BASE + 180)
typedef HINTERNET (WINAPI *WINHTTPOPEN)(LPCWSTR pwszUserAgent, DWORD dwAccessType, LPCWSTR pwszProxyName, LPCWSTR pwszProxyBypass, DWORD dwFlags);
typedef BOOL (WINAPI *WINHTTPGETPROXYFORURL)(HINTERNET hSession, LPCWSTR lpcwszUrl, WINHTTP_AUTOPROXY_OPTIONS *pAutoProxyOptions, WINHTTP_PROXY_INFO *pProxyInfo);
typedef BOOL (WINAPI *WINHTTPGETDEFAULTPROXYCONFIGURATION)(WINHTTP_PROXY_INFO *pProxyInfo);
typedef BOOL (WINAPI *WINHTTPGETIEPROXYCONFIGFORCURRENTUSER)(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG *pProxyConfig);
typedef BOOL (WINAPI *WINHTTPCLOSEHANDLE)(HINTERNET hInternet);
static HMODULE hWinHttp = NULL;
static WINHTTPOPEN WinHttpOpen;
static WINHTTPGETPROXYFORURL WinHttpGetProxyForUrl;
static WINHTTPGETDEFAULTPROXYCONFIGURATION WinHttpGetDefaultProxyConfiguration;
static WINHTTPGETIEPROXYCONFIGFORCURRENTUSER WinHttpGetIEProxyConfigForCurrentUser;
static WINHTTPCLOSEHANDLE WinHttpCloseHandle;
if(!hWinHttp)
{
hWinHttp = LoadLibrary("winhttp.dll");
if(!hWinHttp) return false;
WinHttpOpen = (WINHTTPOPEN) GetProcAddress(hWinHttp, "WinHttpOpen");
WinHttpGetProxyForUrl = (WINHTTPGETPROXYFORURL) GetProcAddress(hWinHttp, "WinHttpGetProxyForUrl");
WinHttpGetDefaultProxyConfiguration = (WINHTTPGETDEFAULTPROXYCONFIGURATION) GetProcAddress(hWinHttp, "WinHttpGetDefaultProxyConfiguration");
WinHttpGetIEProxyConfigForCurrentUser = (WINHTTPGETIEPROXYCONFIGFORCURRENTUSER) GetProcAddress(hWinHttp, "WinHttpGetIEProxyConfigForCurrentUser");
WinHttpCloseHandle = (WINHTTPCLOSEHANDLE) GetProcAddress(hWinHttp, "WinHttpCloseHandle");
}
bool hasProxy = false;
std::string ua(HttpTunnel::UserAgent);
std::wstring wua(ua.begin(), ua.end());
HINTERNET hSession = WinHttpOpen(wua.c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0);
if(hSession)
{
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG userProxyConfig;
bool hasUserProxyConfig = (WinHttpGetIEProxyConfigForCurrentUser(&userProxyConfig) == TRUE);
if(hasUserProxyConfig && !userProxyConfig.fAutoDetect && userProxyConfig.lpszProxy)
{
hasProxy = parseWinHttpProxy(userProxyConfig.lpszProxy, addr);
}
else {
WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;
std::memset(&autoProxyOptions, 0, sizeof(autoProxyOptions));
autoProxyOptions.fAutoLogonIfChallenged = TRUE;
if(hasUserProxyConfig) autoProxyOptions.lpszAutoConfigUrl = userProxyConfig.lpszAutoConfigUrl;
else autoProxyOptions.lpszAutoConfigUrl = NULL;
if(autoProxyOptions.lpszAutoConfigUrl)
{
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP|WINHTTP_AUTO_DETECT_TYPE_DNS_A;
}
else {
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
autoProxyOptions.dwAutoDetectFlags = 0;
}
WINHTTP_PROXY_INFO proxyInfo;
std::wstring wurl(url.begin(), url.end());
if(WinHttpGetProxyForUrl(hSession, wurl.c_str(), &autoProxyOptions, &proxyInfo))
{
if(proxyInfo.lpszProxy && proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY)
hasProxy = parseWinHttpProxy(proxyInfo.lpszProxy, addr);
if(proxyInfo.lpszProxy) GlobalFree(proxyInfo.lpszProxy);
if(proxyInfo.lpszProxyBypass) GlobalFree(proxyInfo.lpszProxyBypass);
}
else if(WinHttpGetDefaultProxyConfiguration(&proxyInfo))
{
if(proxyInfo.lpszProxy && proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY)
hasProxy = parseWinHttpProxy(proxyInfo.lpszProxy, addr);
if(proxyInfo.lpszProxy) GlobalFree(proxyInfo.lpszProxy);
if(proxyInfo.lpszProxyBypass) GlobalFree(proxyInfo.lpszProxyBypass);
}
}
if(hasUserProxyConfig)
{
if(userProxyConfig.lpszProxy) GlobalFree(userProxyConfig.lpszProxy);
if(userProxyConfig.lpszProxyBypass) GlobalFree(userProxyConfig.lpszProxyBypass);
if(userProxyConfig.lpszAutoConfigUrl) GlobalFree(userProxyConfig.lpszAutoConfigUrl);
}
WinHttpCloseHandle(hSession);
}
return hasProxy;
#else
// TODO
return false;
#endif
}
#ifdef WINDOWS
bool Config::parseWinHttpProxy(LPWSTR lpszProxy, Address &addr)
{
Assert(lpszProxy);
String proxy(lpszProxy, lpszProxy + std::char_traits<wchar_t>::length(lpszProxy));
proxy.toLower();
size_t pos = proxy.find("http://");
if(pos != String::NotFound) proxy = proxy.substr(pos + 7);
else {
pos = proxy.find("http=");
if(pos != String::NotFound) proxy = proxy.substr(pos + 5);
}
proxy.cut('/'); proxy.cut(','); proxy.cut(' ');
if(!proxy.empty())
{
try {
addr.fromString(proxy);
return true;
}
catch(...)
{
LogDebug("Config::parseWinHtppProxy", "Got invalid proxy address: " + proxy);
}
}
return false;
}
#endif
}
<commit_msg>Fixed CheckUpdate for Android<commit_after>/*************************************************************************
* Copyright (C) 2011-2013 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet 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. *
* *
* TeapotNet 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 TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "tpn/config.h"
#include "tpn/file.h"
#include "tpn/core.h"
#include "tpn/portmapping.h"
#include "tpn/httptunnel.h" // for user agent
namespace tpn
{
StringMap Config::Params;
Mutex Config::ParamsMutex;
bool Config::UpdateAvailableFlag = false;
String Config::Get(const String &key)
{
ParamsMutex.lock();
String value;
if(Params.get(key, value))
{
ParamsMutex.unlock();
return value;
}
ParamsMutex.unlock();
//throw Exception("Config: no entry for \""+key+"\"");
return "";
}
void Config::Put(const String &key, const String &value)
{
ParamsMutex.lock();
Params.insert(key, value);
ParamsMutex.unlock();
}
void Config::Default(const String &key, const String &value)
{
ParamsMutex.lock();
if(!Params.contains(key)) Params.insert(key, value);
ParamsMutex.unlock();
}
void Config::Load(const String &filename)
{
ParamsMutex.lock();
try {
File file(filename, File::Read);
file.read(Params);
file.close();
}
catch(const Exception &e)
{
LogError("Config", String("Unable to load config: ") + e.what());
}
ParamsMutex.unlock();
}
void Config::Save(const String &filename)
{
ParamsMutex.lock();
try {
File file(filename, File::Truncate);
file.write(Params);
file.close();
}
catch(...)
{
ParamsMutex.unlock();
throw;
}
ParamsMutex.unlock();
}
void Config::GetExternalAddresses(List<Address> &list)
{
list.clear();
String externalAddress = Config::Get("external_address");
if(!externalAddress.empty() && externalAddress != "auto")
{
Address addr;
if(externalAddress.contains(':')) addr.set(externalAddress);
else {
String port = Config::Get("port");
String externalPort = Config::Get("external_port");
if(!externalPort.empty() && externalPort != "auto") port = externalPort;
addr.set(externalAddress, port);
}
list.push_back(addr);
}
List<Address> tmp;
Core::Instance->getAddresses(tmp);
for(List<Address>::const_iterator it = tmp.begin();
it != tmp.end();
++it)
{
const Address &addr = *it;
if(addr.addrFamily() == AF_INET)
{
String host = PortMapping::Instance->getExternalHost();
if(!host.empty())
{
uint16_t port;
PortMapping::Instance->get(PortMapping::TCP, addr.port(), port);
list.push_back(Address(host, port));
}
}
String host = addr.host();
if(host != "127.0.0.1" && host != "::1"
&& std::find(list.begin(), list.end(), addr) == list.end())
{
list.push_back(addr);
}
}
}
bool Config::CheckUpdate(void)
{
String release;
#if defined(WINDOWS)
release = "win32";
#elif defined(MACOSX)
release = "osx";
#else
release = "src";
#endif
try {
LogInfo("Config::CheckUpdate", "Looking for updates...");
String url = String(DOWNLOADURL) + "?version&release=" + release + "¤t=" + APPVERSION;
String content;
int result = Http::Get(url, &content);
if(result != 200)
throw Exception("HTTP error code " + String::number(result));
unsigned lastVersion = content.trimmed().dottedToInt();
unsigned appVersion = String(APPVERSION).dottedToInt();
Assert(appVersion != 0);
if(lastVersion > appVersion)
{
UpdateAvailableFlag = true;
return true;
}
}
catch(const Exception &e)
{
LogWarn("Config::CheckUpdate", String("Unable to look for updates: ") + e.what());
}
return false;
}
bool Config::IsUpdateAvailable(void)
{
return UpdateAvailableFlag;
}
bool Config::GetProxyForUrl(const String &url, Address &addr)
{
String proxy = Get("http_proxy").trimmed();
if(proxy == "none")
{
return false;
}
if(!proxy.empty() && proxy != "auto")
{
addr.fromString(proxy);
return true;
}
#ifdef WINDOWS
typedef LPVOID HINTERNET;
typedef struct {
DWORD dwAccessType;
LPWSTR lpszProxy;
LPWSTR lpszProxyBypass;
} WINHTTP_PROXY_INFO;
typedef struct {
BOOL fAutoDetect;
LPWSTR lpszAutoConfigUrl;
LPWSTR lpszProxy;
LPWSTR lpszProxyBypass;
} WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
typedef struct {
DWORD dwFlags;
DWORD dwAutoDetectFlags;
LPCWSTR lpszAutoConfigUrl;
LPVOID lpvReserved;
DWORD dwReserved;
BOOL fAutoLogonIfChallenged;
} WINHTTP_AUTOPROXY_OPTIONS;
#define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY 0
#define WINHTTP_ACCESS_TYPE_NO_PROXY 1
#define WINHTTP_ACCESS_TYPE_NAMED_PROXY 3
#define WINHTTP_AUTOPROXY_AUTO_DETECT 0x00000001
#define WINHTTP_AUTOPROXY_CONFIG_URL 0x00000002
#define WINHTTP_AUTO_DETECT_TYPE_DHCP 0x00000001
#define WINHTTP_AUTO_DETECT_TYPE_DNS_A 0x00000002
#define WINHTTP_ERROR_BASE 12000
#define ERROR_WINHTTP_LOGIN_FAILURE (WINHTTP_ERROR_BASE + 15)
#define ERROR_WINHTTP_AUTODETECTION_FAILED (WINHTTP_ERROR_BASE + 180)
typedef HINTERNET (WINAPI *WINHTTPOPEN)(LPCWSTR pwszUserAgent, DWORD dwAccessType, LPCWSTR pwszProxyName, LPCWSTR pwszProxyBypass, DWORD dwFlags);
typedef BOOL (WINAPI *WINHTTPGETPROXYFORURL)(HINTERNET hSession, LPCWSTR lpcwszUrl, WINHTTP_AUTOPROXY_OPTIONS *pAutoProxyOptions, WINHTTP_PROXY_INFO *pProxyInfo);
typedef BOOL (WINAPI *WINHTTPGETDEFAULTPROXYCONFIGURATION)(WINHTTP_PROXY_INFO *pProxyInfo);
typedef BOOL (WINAPI *WINHTTPGETIEPROXYCONFIGFORCURRENTUSER)(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG *pProxyConfig);
typedef BOOL (WINAPI *WINHTTPCLOSEHANDLE)(HINTERNET hInternet);
static HMODULE hWinHttp = NULL;
static WINHTTPOPEN WinHttpOpen;
static WINHTTPGETPROXYFORURL WinHttpGetProxyForUrl;
static WINHTTPGETDEFAULTPROXYCONFIGURATION WinHttpGetDefaultProxyConfiguration;
static WINHTTPGETIEPROXYCONFIGFORCURRENTUSER WinHttpGetIEProxyConfigForCurrentUser;
static WINHTTPCLOSEHANDLE WinHttpCloseHandle;
if(!hWinHttp)
{
hWinHttp = LoadLibrary("winhttp.dll");
if(!hWinHttp) return false;
WinHttpOpen = (WINHTTPOPEN) GetProcAddress(hWinHttp, "WinHttpOpen");
WinHttpGetProxyForUrl = (WINHTTPGETPROXYFORURL) GetProcAddress(hWinHttp, "WinHttpGetProxyForUrl");
WinHttpGetDefaultProxyConfiguration = (WINHTTPGETDEFAULTPROXYCONFIGURATION) GetProcAddress(hWinHttp, "WinHttpGetDefaultProxyConfiguration");
WinHttpGetIEProxyConfigForCurrentUser = (WINHTTPGETIEPROXYCONFIGFORCURRENTUSER) GetProcAddress(hWinHttp, "WinHttpGetIEProxyConfigForCurrentUser");
WinHttpCloseHandle = (WINHTTPCLOSEHANDLE) GetProcAddress(hWinHttp, "WinHttpCloseHandle");
}
bool hasProxy = false;
std::string ua(HttpTunnel::UserAgent);
std::wstring wua(ua.begin(), ua.end());
HINTERNET hSession = WinHttpOpen(wua.c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0);
if(hSession)
{
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG userProxyConfig;
bool hasUserProxyConfig = (WinHttpGetIEProxyConfigForCurrentUser(&userProxyConfig) == TRUE);
if(hasUserProxyConfig && !userProxyConfig.fAutoDetect && userProxyConfig.lpszProxy)
{
hasProxy = parseWinHttpProxy(userProxyConfig.lpszProxy, addr);
}
else {
WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;
std::memset(&autoProxyOptions, 0, sizeof(autoProxyOptions));
autoProxyOptions.fAutoLogonIfChallenged = TRUE;
if(hasUserProxyConfig) autoProxyOptions.lpszAutoConfigUrl = userProxyConfig.lpszAutoConfigUrl;
else autoProxyOptions.lpszAutoConfigUrl = NULL;
if(autoProxyOptions.lpszAutoConfigUrl)
{
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP|WINHTTP_AUTO_DETECT_TYPE_DNS_A;
}
else {
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
autoProxyOptions.dwAutoDetectFlags = 0;
}
WINHTTP_PROXY_INFO proxyInfo;
std::wstring wurl(url.begin(), url.end());
if(WinHttpGetProxyForUrl(hSession, wurl.c_str(), &autoProxyOptions, &proxyInfo))
{
if(proxyInfo.lpszProxy && proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY)
hasProxy = parseWinHttpProxy(proxyInfo.lpszProxy, addr);
if(proxyInfo.lpszProxy) GlobalFree(proxyInfo.lpszProxy);
if(proxyInfo.lpszProxyBypass) GlobalFree(proxyInfo.lpszProxyBypass);
}
else if(WinHttpGetDefaultProxyConfiguration(&proxyInfo))
{
if(proxyInfo.lpszProxy && proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY)
hasProxy = parseWinHttpProxy(proxyInfo.lpszProxy, addr);
if(proxyInfo.lpszProxy) GlobalFree(proxyInfo.lpszProxy);
if(proxyInfo.lpszProxyBypass) GlobalFree(proxyInfo.lpszProxyBypass);
}
}
if(hasUserProxyConfig)
{
if(userProxyConfig.lpszProxy) GlobalFree(userProxyConfig.lpszProxy);
if(userProxyConfig.lpszProxyBypass) GlobalFree(userProxyConfig.lpszProxyBypass);
if(userProxyConfig.lpszAutoConfigUrl) GlobalFree(userProxyConfig.lpszAutoConfigUrl);
}
WinHttpCloseHandle(hSession);
}
return hasProxy;
#else
// TODO
return false;
#endif
}
#ifdef WINDOWS
bool Config::parseWinHttpProxy(LPWSTR lpszProxy, Address &addr)
{
Assert(lpszProxy);
String proxy(lpszProxy, lpszProxy + std::char_traits<wchar_t>::length(lpszProxy));
proxy.toLower();
size_t pos = proxy.find("http://");
if(pos != String::NotFound) proxy = proxy.substr(pos + 7);
else {
pos = proxy.find("http=");
if(pos != String::NotFound) proxy = proxy.substr(pos + 5);
}
proxy.cut('/'); proxy.cut(','); proxy.cut(' ');
if(!proxy.empty())
{
try {
addr.fromString(proxy);
return true;
}
catch(...)
{
LogDebug("Config::parseWinHtppProxy", "Got invalid proxy address: " + proxy);
}
}
return false;
}
#endif
}
<|endoftext|>
|
<commit_before>#ifndef KMC_KLANG_EITHER_HPP
#define KMC_KLANG_EITHER_HPP
#include <cassert>
#include <type_traits>
#include <utility>
namespace klang {
namespace {
extern void* enabler;
template <typename From, typename To>
struct enable_if_convertible
: public std::enable_if<std::is_convertible<From, To>::value>
{};
}
struct LeftTag {};
struct RightTag {};
constexpr LeftTag left_tag{};
constexpr RightTag right_tag{};
template <typename L, typename R>
class Either;
template <typename L>
class Left {
public:
explicit Left(const L& src)
: left_{src}
{}
explicit Left(L&& src)
: left_{std::move(src)}
{}
template <typename... Args>
explicit Left(Args&&... args)
: left_{std::forward<Args>(args)...}
{}
Left(const Left&) = default;
Left(Left&&) = default;
Left& operator=(const Left&) = default;
Left& operator=(Left&&) = default;
void swap(Left& that) {
using std::swap;
swap(left_, that.left_);
}
const L& value() const& {
return left_;
}
L&& value() && {
return std::move(left_);
}
template <typename R>
operator Either<L, R>() const& {
return Either<L, R>{left_tag, left_};
}
template <typename R>
operator Either<L, R>() && {
return Either<L, R>{left_tag, std::move(left_)};
}
template <typename L_>
friend class Left;
friend void swap(Left& lhs, Left& rhs) {
lhs.swap(rhs);
}
friend bool operator==(const Left& lhs, const Left& rhs) {
return lhs.left_ == rhs.left_;
}
friend bool operator<(const Left& lhs, const Left& rhs) {
return lhs.left_ < rhs.left_;
}
private:
L left_;
};
template <typename R>
class Right {
public:
explicit Right(const R& src)
: right_{src}
{}
explicit Right(R&& src)
: right_{std::move(src)}
{}
template <typename... Args>
explicit Right(Args&&... args)
: right_{std::forward<Args>(args)...}
{}
Right(const Right&) = default;
Right(Right&&) = default;
Right& operator=(const Right&) = default;
Right& operator=(Right&&) = default;
void swap(Right& that) {
using std::swap;
swap(right_, that.right_);
}
const R& value() const& {
return right_;
}
R&& value() && {
return std::move(right_);
}
template <typename L, typename R_,
typename enable_if_convertible<R, R_>::type*& = enabler>
operator Either<L, R_>() const& {
return Either<L, R_>{right_tag, right_};
}
template <typename L, typename R_,
typename enable_if_convertible<R, R_>::type*& = enabler>
operator Either<L, R_>() && {
return Either<L, R_>{right_tag, std::move(right_)};
}
template <typename R_>
friend class Right;
friend void swap(Right& lhs, Right& rhs) {
lhs.swap(rhs);
}
friend bool operator==(const Right& lhs, const Right& rhs) {
return lhs.right_ == rhs.right_;
}
friend bool operator<(const Right& lhs, const Right& rhs) {
return lhs.right_ < rhs.right_;
}
private:
R right_;
};
template <typename L, typename R>
class Either {
public:
Either(LeftTag, const L& left)
: is_right_{false}, left_{left}
{}
Either(LeftTag, L&& left)
: is_right_{false}, left_{std::move(left)}
{}
Either(RightTag, const R& right)
: is_right_{true}, right_{right}
{}
Either(RightTag, R&& right)
: is_right_{true}, right_{std::move(right)}
{}
template <typename... Args>
explicit Either(LeftTag, Args&&... args)
: is_right_{false}, left_{std::forward<Args>(args)...}
{}
template <typename... Args>
explicit Either(RightTag, Args&&... args)
: is_right_{true}, right_{std::forward<Args>(args)...}
{}
Either(const Either& that)
: is_right_{that.is_right_} {
construct(that);
}
Either(Either&& that)
: is_right_{that.is_right_} {
construct(std::move(that));
}
Either& operator=(const Either& that) {
assign(that);
return *this;
}
Either& operator=(Either&& that) {
assign(std::move(that));
return *this;
}
~Either() {
destruct();
}
void swap(Either& that) {
Either tmp{std::move(*this)};
*this = std::move(that);
that = std::move(tmp);
}
bool is_left() const {
return !is_right_;
}
bool is_right() const {
return is_right_;
}
Left<L> left() const& {
assert(!is_right_);
return Left<L>{left_};
}
Left<L> left() && {
assert(!is_right_);
return Left<L>{std::move(left_)};
}
Right<R> right() const& {
assert(is_right_);
return Right<R>{right_};
}
Right<R> right() && {
assert(is_right_);
return Right<R>{std::move(right_)};
}
template <typename... Args>
void emplace(LeftTag, Args&&... args) {
destruct();
is_right_ = false;
new (&left_) L{std::forward<Args>(args)...};
}
template <typename... Args>
void emplace(RightTag, Args&&... args) {
destruct();
is_right_ = true;
new (&right_) R{std::forward<Args>(args)...};
}
explicit operator bool() const {
return is_right_;
}
const R& operator*() const& {
assert(is_right_);
return right_;
}
R& operator*() & {
assert(is_right_);
return right_;
}
R&& operator*() && {
assert(is_right_);
return std::move(right_);
}
const R* operator->() const {
assert(is_right_);
return &right_;
}
R* operator->() {
assert(is_right_);
return &right_;
}
template <typename L_, typename R_>
friend class Either;
friend void swap(Either& lhs, Either& rhs) {
lhs.swap(rhs);
}
friend bool operator==(const Either& lhs, const Either& rhs) {
if (lhs.is_right_ != rhs.is_right_) {
return false;
} else if (lhs.is_right_) {
return lhs.right_ == rhs.right_;
} else {
return lhs.left_ == rhs.left_;
}
}
friend bool operator<(const Either& lhs, const Either& rhs) {
if (lhs.is_right_ != rhs.is_right_) {
return rhs.is_right_;
} else if (lhs.is_right_) {
return lhs.right_ < rhs.right_;
} else {
return lhs.left_ < rhs.left_;
}
}
private:
void construct(const Either& src) {
if (src.is_right_) {
new (&right_) R{src.right_};
} else {
new (&left_) L{src.left_};
}
}
void construct(Either&& src) {
if (src.is_right_) {
new (&right_) R{std::move(src.right_)};
} else {
new (&left_) L{std::move(src.left_)};
}
}
void assign(const Either& src) {
if (is_right_ == src.is_right_) {
if (is_right_) {
right_ = src.right_;
} else {
left_ = src.left_;
}
} else {
destruct();
construct(src);
is_right_ = src.is_right_;
}
}
void assign(Either&& src) {
if (is_right_ == src.is_right_) {
if (is_right_) {
right_ = std::move(src.right_);
} else {
left_ = std::move(src.left_);
}
} else {
destruct();
construct(std::move(src));
is_right_ = src.is_right_;
}
}
void destruct() {
if (is_right_) {
right_.~R();
} else {
left_.~L();
}
}
private:
bool is_right_;
union {
L left_;
R right_;
};
};
template <typename T>
Left<typename std::decay<T>::type> make_left(T&& left) {
return Left<typename std::decay<T>::type>{std::forward<T>(left)};
}
template <typename T, typename... Args>
Left<T> make_left(Args&&... args) {
return Left<T>{std::forward<Args>(args)...};
}
template <typename T>
Right<typename std::decay<T>::type> make_right(T&& right) {
return Right<typename std::decay<T>::type>{std::forward<T>(right)};
}
template <typename T, typename... Args>
Right<T> make_right(Args&&... args) {
return Right<T>{std::forward<Args>(args)...};
}
} // namespace klang
#endif // KMC_KLANG_EITHER_HPP
<commit_msg>Make enabler escape from unnamed namespace<commit_after>#ifndef KMC_KLANG_EITHER_HPP
#define KMC_KLANG_EITHER_HPP
#include <cassert>
#include <type_traits>
#include <utility>
namespace klang {
extern void* enabler;
namespace /* unnamed namespace */ {
template <typename From, typename To>
struct enable_if_convertible
: public std::enable_if<std::is_convertible<From, To>::value>
{};
} // unnamed namespace
struct LeftTag {};
struct RightTag {};
constexpr LeftTag left_tag{};
constexpr RightTag right_tag{};
template <typename L, typename R>
class Either;
template <typename L>
class Left {
public:
explicit Left(const L& src)
: left_{src}
{}
explicit Left(L&& src)
: left_{std::move(src)}
{}
template <typename... Args>
explicit Left(Args&&... args)
: left_{std::forward<Args>(args)...}
{}
Left(const Left&) = default;
Left(Left&&) = default;
Left& operator=(const Left&) = default;
Left& operator=(Left&&) = default;
void swap(Left& that) {
using std::swap;
swap(left_, that.left_);
}
const L& value() const& {
return left_;
}
L&& value() && {
return std::move(left_);
}
template <typename R>
operator Either<L, R>() const& {
return Either<L, R>{left_tag, left_};
}
template <typename R>
operator Either<L, R>() && {
return Either<L, R>{left_tag, std::move(left_)};
}
template <typename L_>
friend class Left;
friend void swap(Left& lhs, Left& rhs) {
lhs.swap(rhs);
}
friend bool operator==(const Left& lhs, const Left& rhs) {
return lhs.left_ == rhs.left_;
}
friend bool operator<(const Left& lhs, const Left& rhs) {
return lhs.left_ < rhs.left_;
}
private:
L left_;
};
template <typename R>
class Right {
public:
explicit Right(const R& src)
: right_{src}
{}
explicit Right(R&& src)
: right_{std::move(src)}
{}
template <typename... Args>
explicit Right(Args&&... args)
: right_{std::forward<Args>(args)...}
{}
Right(const Right&) = default;
Right(Right&&) = default;
Right& operator=(const Right&) = default;
Right& operator=(Right&&) = default;
void swap(Right& that) {
using std::swap;
swap(right_, that.right_);
}
const R& value() const& {
return right_;
}
R&& value() && {
return std::move(right_);
}
template <typename L, typename R_,
typename enable_if_convertible<R, R_>::type*& = enabler>
operator Either<L, R_>() const& {
return Either<L, R_>{right_tag, right_};
}
template <typename L, typename R_,
typename enable_if_convertible<R, R_>::type*& = enabler>
operator Either<L, R_>() && {
return Either<L, R_>{right_tag, std::move(right_)};
}
template <typename R_>
friend class Right;
friend void swap(Right& lhs, Right& rhs) {
lhs.swap(rhs);
}
friend bool operator==(const Right& lhs, const Right& rhs) {
return lhs.right_ == rhs.right_;
}
friend bool operator<(const Right& lhs, const Right& rhs) {
return lhs.right_ < rhs.right_;
}
private:
R right_;
};
template <typename L, typename R>
class Either {
public:
Either(LeftTag, const L& left)
: is_right_{false}, left_{left}
{}
Either(LeftTag, L&& left)
: is_right_{false}, left_{std::move(left)}
{}
Either(RightTag, const R& right)
: is_right_{true}, right_{right}
{}
Either(RightTag, R&& right)
: is_right_{true}, right_{std::move(right)}
{}
template <typename... Args>
explicit Either(LeftTag, Args&&... args)
: is_right_{false}, left_{std::forward<Args>(args)...}
{}
template <typename... Args>
explicit Either(RightTag, Args&&... args)
: is_right_{true}, right_{std::forward<Args>(args)...}
{}
Either(const Either& that)
: is_right_{that.is_right_} {
construct(that);
}
Either(Either&& that)
: is_right_{that.is_right_} {
construct(std::move(that));
}
Either& operator=(const Either& that) {
assign(that);
return *this;
}
Either& operator=(Either&& that) {
assign(std::move(that));
return *this;
}
~Either() {
destruct();
}
void swap(Either& that) {
Either tmp{std::move(*this)};
*this = std::move(that);
that = std::move(tmp);
}
bool is_left() const {
return !is_right_;
}
bool is_right() const {
return is_right_;
}
Left<L> left() const& {
assert(!is_right_);
return Left<L>{left_};
}
Left<L> left() && {
assert(!is_right_);
return Left<L>{std::move(left_)};
}
Right<R> right() const& {
assert(is_right_);
return Right<R>{right_};
}
Right<R> right() && {
assert(is_right_);
return Right<R>{std::move(right_)};
}
template <typename... Args>
void emplace(LeftTag, Args&&... args) {
destruct();
is_right_ = false;
new (&left_) L{std::forward<Args>(args)...};
}
template <typename... Args>
void emplace(RightTag, Args&&... args) {
destruct();
is_right_ = true;
new (&right_) R{std::forward<Args>(args)...};
}
explicit operator bool() const {
return is_right_;
}
const R& operator*() const& {
assert(is_right_);
return right_;
}
R& operator*() & {
assert(is_right_);
return right_;
}
R&& operator*() && {
assert(is_right_);
return std::move(right_);
}
const R* operator->() const {
assert(is_right_);
return &right_;
}
R* operator->() {
assert(is_right_);
return &right_;
}
template <typename L_, typename R_>
friend class Either;
friend void swap(Either& lhs, Either& rhs) {
lhs.swap(rhs);
}
friend bool operator==(const Either& lhs, const Either& rhs) {
if (lhs.is_right_ != rhs.is_right_) {
return false;
} else if (lhs.is_right_) {
return lhs.right_ == rhs.right_;
} else {
return lhs.left_ == rhs.left_;
}
}
friend bool operator<(const Either& lhs, const Either& rhs) {
if (lhs.is_right_ != rhs.is_right_) {
return rhs.is_right_;
} else if (lhs.is_right_) {
return lhs.right_ < rhs.right_;
} else {
return lhs.left_ < rhs.left_;
}
}
private:
void construct(const Either& src) {
if (src.is_right_) {
new (&right_) R{src.right_};
} else {
new (&left_) L{src.left_};
}
}
void construct(Either&& src) {
if (src.is_right_) {
new (&right_) R{std::move(src.right_)};
} else {
new (&left_) L{std::move(src.left_)};
}
}
void assign(const Either& src) {
if (is_right_ == src.is_right_) {
if (is_right_) {
right_ = src.right_;
} else {
left_ = src.left_;
}
} else {
destruct();
construct(src);
is_right_ = src.is_right_;
}
}
void assign(Either&& src) {
if (is_right_ == src.is_right_) {
if (is_right_) {
right_ = std::move(src.right_);
} else {
left_ = std::move(src.left_);
}
} else {
destruct();
construct(std::move(src));
is_right_ = src.is_right_;
}
}
void destruct() {
if (is_right_) {
right_.~R();
} else {
left_.~L();
}
}
private:
bool is_right_;
union {
L left_;
R right_;
};
};
template <typename T>
Left<typename std::decay<T>::type> make_left(T&& left) {
return Left<typename std::decay<T>::type>{std::forward<T>(left)};
}
template <typename T, typename... Args>
Left<T> make_left(Args&&... args) {
return Left<T>{std::forward<Args>(args)...};
}
template <typename T>
Right<typename std::decay<T>::type> make_right(T&& right) {
return Right<typename std::decay<T>::type>{std::forward<T>(right)};
}
template <typename T, typename... Args>
Right<T> make_right(Args&&... args) {
return Right<T>{std::forward<Args>(args)...};
}
} // namespace klang
#endif // KMC_KLANG_EITHER_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2012-2014 Yule Fox. All rights reserved.
* http://www.yulefox.com/
*/
#include <elf/db.h>
#include <elf/log.h>
#include <elf/memory.h>
#include <elf/pc.h>
#include <elf/thread.h>
#include <deque>
#include <map>
#include <string>
using namespace google::protobuf;
namespace elf {
enum query_type {
QUERY_NO_RES, // no response
QUERY_RAW, // response with raw result
QUERY_FIELD, // response with PB field result
QUERY_PB, // response with PB result
};
struct query_t {
query_type type; // type
std::string cmd; // command
oid_t oid; // associated object id
MYSQL_RES *data; // query result
pb_t *pb; // store query data
std::string field; // pb field
db_callback proc; // callback function
time64_t stamp; // request time stamp
};
typedef struct mysql_thread_s {
int idx;
thread_t tid;
MYSQL *mysql;
xqueue<query_t *> req;
} mysql_thread_t;
typedef struct thread_list_s {
int idx;
int num;
mysql_thread_t *threads;
}thread_list_t;
typedef std::map<int, thread_list_t*> thread_list_map;
static thread_list_map s_threads;
static const int THREAD_NUM_DEFAULT = 5;
//static const int THREAD_NUM = 5;
//static const int THREAD_INDEX[THREAD_NUM] = {0, 1, 2, 3, 4};
//static MYSQL *s_mysqls[THREAD_NUM] = {NULL, NULL, NULL, NULL};
//static MYSQL_MAP s_mysqls;
//static THREAD_MAP s_threads;
//static xqueue<query_t *> s_queue_req[THREAD_NUM];
static xqueue<query_t *> s_queue_res;
static void *handle(void *args);
static void query(mysql_thread_t *th);
static void destroy(query_t *q);
static void response(query_t *q);
static void retrieve_pb(query_t *q);
static void retrieve_field(query_t *q);
volatile int _running;
static void *handle(void *args)
{
mysql_thread_t *self = (mysql_thread_t*)args;
if (self == NULL) {
LOG_ERROR("db", "Create thread failed: %s", "mysql_thread_t is NULL");
return NULL;
}
while (_running) {
query(self);
}
return NULL;
}
static void query(mysql_thread_t *th)
{
query_t *q;
MYSQL *m = th->mysql;
try {
th->req.pop(q);
assert(m && q);
// query
int status = mysql_real_query(m, q->cmd.c_str(), q->cmd.length());
if (status != 0) {
LOG_ERROR("db", "`%s` failed: %s.",
q->cmd.c_str(), mysql_error(m));
destroy(q);
return;
}
if (q->type == QUERY_NO_RES) {
destroy(q);
return;
}
q->data = NULL;
do {
MYSQL_RES *res = mysql_store_result(m);
if (res) {
if (q->data == NULL) {
q->data = res;
s_queue_res.push(q);
} else {
mysql_free_result(res);
}
}
} while (!mysql_next_result(m));
} catch(...) {
LOG_ERROR("db", "`%s` failed: %s.",
q->cmd.c_str(), mysql_error(m));
}
}
static void destroy(query_t *q)
{
assert(q);
if (q->data) {
mysql_free_result(q->data);
}
E_DELETE(q->pb);
E_DELETE(q);
}
static void retrieve_pb(query_t *q)
{
assert(q && q->data && q->pb);
const Descriptor *des = q->pb->GetDescriptor();
const int field_num = mysql_num_fields(q->data);
const MYSQL_ROW row = mysql_fetch_row(q->data);
size_t *len = mysql_fetch_lengths(q->data);
for (int c = 0; c < field_num; ++c) {
const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c);
const FieldDescriptor *ofd = des->FindFieldByName(ifd->name);
if (ofd == NULL) {
continue;
}
if (row[c] == NULL || (strlen(row[c]) == 0)) {
pb_set_field(q->pb, ofd, "");
} else {
pb_set_field(q->pb, ofd, row[c], len[c]);
}
}
}
static void retrieve_field(query_t *q)
{
assert(q && q->data && q->pb);
const Reflection *ref = q->pb->GetReflection();
const Descriptor *des = q->pb->GetDescriptor();
const FieldDescriptor *ctn = des->FindFieldByName(q->field);
const int row_num = mysql_num_rows(q->data);
const int field_num = mysql_num_fields(q->data);
assert(ctn);
for (int r = 0; r < row_num; ++r) {
pb_t *item = ref->AddMessage(q->pb, ctn);
const MYSQL_ROW row = mysql_fetch_row(q->data);
unsigned long *len = mysql_fetch_lengths(q->data);
des = item->GetDescriptor();
for (int c = 0; c < field_num; ++c) {
const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c);
const FieldDescriptor *ofd =
des->FindFieldByName(ifd->name);
if (ofd == NULL) {
continue;
}
if (row[c] == NULL || (strlen(row[c]) == 0)) {
pb_set_field(item, ofd, "");
} else {
pb_set_field(item, ofd, row[c], len[c]);
}
}
}
}
int db_init(void)
{
MODULE_IMPORT_SWITCH;
_running = 1;
return ELF_RC_DB_OK;
}
int db_fini(void)
{
MODULE_IMPORT_SWITCH;
_running = 0;
thread_list_map::iterator itr = s_threads.begin();
for (;itr != s_threads.end(); ++itr) {
thread_list_t *th_list = itr->second;
for (int i = 0;i < th_list->num; ++i) {
mysql_thread_t *th = th_list->threads + i;
thread_fini(th->tid);
if (th->mysql) {
mysql_close(th->mysql);
}
}
E_DELETE th_list->threads;
E_DELETE th_list;
}
s_threads.clear();
return ELF_RC_DB_OK;
}
int db_connect(int idx, const std::string &host, const std::string &user,
const std::string &passwd, const std::string &db, unsigned int port,
int num)
{
if (num <= 0) {
num = THREAD_NUM_DEFAULT;
}
thread_list_t *th_list = NULL;
thread_list_map::iterator itr = s_threads.find(idx);
if (itr != s_threads.end()) {
th_list = itr->second;
} else {
th_list = E_NEW thread_list_t;
th_list->idx = idx;
th_list->num = num;
th_list->threads = E_NEW mysql_thread_t[num];
s_threads[idx] = th_list;
}
for (int i = 0; i < num; ++i) {
mysql_thread_t *th = NULL;
th = th_list->threads + i;
char value = 1;
MYSQL * m = th->mysql;
try {
if (m && 0 == mysql_ping(m)) {
return ELF_RC_DB_OK;
}
m = mysql_init(NULL);
mysql_options(m, MYSQL_OPT_RECONNECT, (char *)&value);
mysql_options(m, MYSQL_SET_CHARSET_NAME, "utf8");
if (!mysql_real_connect(m, host.c_str(), user.c_str(),
passwd.c_str(), db.c_str(), port,
NULL, CLIENT_MULTI_STATEMENTS)) {
LOG_ERROR("db", "Connect DB failed: %s.",
mysql_error(m));
return ELF_RC_DB_INIT_FAILED;
}
th->mysql = m;
th->tid = thread_init(handle, (void *)th);
} catch(...) {
LOG_ERROR("db", "Connect DB failed: %s.",
mysql_error(m));
return ELF_RC_DB_INIT_FAILED;
}
}
return ELF_RC_DB_OK;
}
int db_proc(void)
{
if (s_threads.empty()) return -1;
std::deque<query_t *> list;
std::deque<query_t *>::iterator itr;
s_queue_res.swap(list);
for (itr = list.begin(); itr != list.end(); ++itr) {
query_t *q = *itr;
// object has not been destroyed
response(q);
}
return 0;
}
void db_req(int idx, const char *cmd, bool sim, db_callback proc,
oid_t oid, pb_t *out, const std::string &field)
{
thread_list_map::iterator itr = s_threads.find(idx);
if (itr == s_threads.end()) {
return;
}
thread_list_t *th_list = itr->second;
int tidx = 0;
query_t *q = E_NEW query_t;
if (proc == NULL && out == NULL) {
q->type = QUERY_NO_RES;
} else if (out == NULL) {
q->type = QUERY_RAW;
} else if (field == "") {
q->type = QUERY_PB;
} else {
q->type = QUERY_FIELD;
}
q->cmd = cmd;
q->stamp = time_ms();
q->oid = oid;
q->pb = out;
q->field = field;
q->proc = proc;
q->data = NULL;
if (sim) {
tidx = oid % (th_list->num - 1) + 1;
}
mysql_thread_t *th = th_list->threads + tidx;
th->req.push(q);
}
void response(query_t *q)
{
assert(q);
switch (q->type) {
case QUERY_RAW:
if (q->proc) {
q->proc(q->oid, q->data);
}
break;
case QUERY_PB:
retrieve_pb(q);
if (q->proc) {
q->proc(q->oid, q->pb);
}
break;
case QUERY_FIELD:
retrieve_field(q);
if (q->proc) {
q->proc(q->oid, q->pb);
}
break;
default:
assert(0);
break;
}
destroy(q);
}
size_t db_pending_size(void)
{
size_t sum = 0;
thread_list_map::iterator itr = s_threads.begin();
for (;itr != s_threads.end(); ++itr) {
thread_list_t *th_list = itr->second;
for (int i = 0;i < th_list->num; i++) {
mysql_thread_t *th = th_list->threads + i;
sum += th->req.size();
}
}
return sum;
}
} // namespace elf
<commit_msg>[MOD] mysql obj initialize<commit_after>/*
* Copyright (C) 2012-2014 Yule Fox. All rights reserved.
* http://www.yulefox.com/
*/
#include <elf/db.h>
#include <elf/log.h>
#include <elf/memory.h>
#include <elf/pc.h>
#include <elf/thread.h>
#include <deque>
#include <map>
#include <string>
using namespace google::protobuf;
namespace elf {
enum query_type {
QUERY_NO_RES, // no response
QUERY_RAW, // response with raw result
QUERY_FIELD, // response with PB field result
QUERY_PB, // response with PB result
};
struct query_t {
query_type type; // type
std::string cmd; // command
oid_t oid; // associated object id
MYSQL_RES *data; // query result
pb_t *pb; // store query data
std::string field; // pb field
db_callback proc; // callback function
time64_t stamp; // request time stamp
};
typedef struct mysql_thread_s {
int idx;
thread_t tid;
MYSQL *mysql;
xqueue<query_t *> req;
} mysql_thread_t;
typedef struct thread_list_s {
int idx;
int num;
mysql_thread_t *threads;
}thread_list_t;
typedef std::map<int, thread_list_t*> thread_list_map;
static thread_list_map s_threads;
static const int THREAD_NUM_DEFAULT = 5;
//static const int THREAD_NUM = 5;
//static const int THREAD_INDEX[THREAD_NUM] = {0, 1, 2, 3, 4};
//static MYSQL *s_mysqls[THREAD_NUM] = {NULL, NULL, NULL, NULL};
//static MYSQL_MAP s_mysqls;
//static THREAD_MAP s_threads;
//static xqueue<query_t *> s_queue_req[THREAD_NUM];
static xqueue<query_t *> s_queue_res;
static void *handle(void *args);
static void query(mysql_thread_t *th);
static void destroy(query_t *q);
static void response(query_t *q);
static void retrieve_pb(query_t *q);
static void retrieve_field(query_t *q);
volatile int _running;
static void *handle(void *args)
{
mysql_thread_t *self = (mysql_thread_t*)args;
if (self == NULL) {
LOG_ERROR("db", "Create thread failed: %s", "mysql_thread_t is NULL");
return NULL;
}
while (_running) {
query(self);
}
return NULL;
}
static void query(mysql_thread_t *th)
{
query_t *q;
MYSQL *m = th->mysql;
try {
th->req.pop(q);
assert(m && q);
// query
int status = mysql_real_query(m, q->cmd.c_str(), q->cmd.length());
if (status != 0) {
LOG_ERROR("db", "`%s` failed: %s.",
q->cmd.c_str(), mysql_error(m));
destroy(q);
return;
}
if (q->type == QUERY_NO_RES) {
destroy(q);
return;
}
q->data = NULL;
do {
MYSQL_RES *res = mysql_store_result(m);
if (res) {
if (q->data == NULL) {
q->data = res;
s_queue_res.push(q);
} else {
mysql_free_result(res);
}
}
} while (!mysql_next_result(m));
} catch(...) {
LOG_ERROR("db", "`%s` failed: %s.",
q->cmd.c_str(), mysql_error(m));
}
}
static void destroy(query_t *q)
{
assert(q);
if (q->data) {
mysql_free_result(q->data);
}
E_DELETE(q->pb);
E_DELETE(q);
}
static void retrieve_pb(query_t *q)
{
assert(q && q->data && q->pb);
const Descriptor *des = q->pb->GetDescriptor();
const int field_num = mysql_num_fields(q->data);
const MYSQL_ROW row = mysql_fetch_row(q->data);
size_t *len = mysql_fetch_lengths(q->data);
for (int c = 0; c < field_num; ++c) {
const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c);
const FieldDescriptor *ofd = des->FindFieldByName(ifd->name);
if (ofd == NULL) {
continue;
}
if (row[c] == NULL || (strlen(row[c]) == 0)) {
pb_set_field(q->pb, ofd, "");
} else {
pb_set_field(q->pb, ofd, row[c], len[c]);
}
}
}
static void retrieve_field(query_t *q)
{
assert(q && q->data && q->pb);
const Reflection *ref = q->pb->GetReflection();
const Descriptor *des = q->pb->GetDescriptor();
const FieldDescriptor *ctn = des->FindFieldByName(q->field);
const int row_num = mysql_num_rows(q->data);
const int field_num = mysql_num_fields(q->data);
assert(ctn);
for (int r = 0; r < row_num; ++r) {
pb_t *item = ref->AddMessage(q->pb, ctn);
const MYSQL_ROW row = mysql_fetch_row(q->data);
unsigned long *len = mysql_fetch_lengths(q->data);
des = item->GetDescriptor();
for (int c = 0; c < field_num; ++c) {
const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c);
const FieldDescriptor *ofd =
des->FindFieldByName(ifd->name);
if (ofd == NULL) {
continue;
}
if (row[c] == NULL || (strlen(row[c]) == 0)) {
pb_set_field(item, ofd, "");
} else {
pb_set_field(item, ofd, row[c], len[c]);
}
}
}
}
int db_init(void)
{
MODULE_IMPORT_SWITCH;
_running = 1;
return ELF_RC_DB_OK;
}
int db_fini(void)
{
MODULE_IMPORT_SWITCH;
_running = 0;
thread_list_map::iterator itr = s_threads.begin();
for (;itr != s_threads.end(); ++itr) {
thread_list_t *th_list = itr->second;
for (int i = 0;i < th_list->num; ++i) {
mysql_thread_t *th = th_list->threads + i;
thread_fini(th->tid);
if (th->mysql) {
mysql_close(th->mysql);
}
}
E_DELETE th_list->threads;
E_DELETE th_list;
}
s_threads.clear();
return ELF_RC_DB_OK;
}
int db_connect(int idx, const std::string &host, const std::string &user,
const std::string &passwd, const std::string &db, unsigned int port,
int num)
{
if (num <= 0) {
num = THREAD_NUM_DEFAULT;
}
thread_list_t *th_list = NULL;
thread_list_map::iterator itr = s_threads.find(idx);
if (itr != s_threads.end()) {
th_list = itr->second;
} else {
th_list = E_NEW thread_list_t;
th_list->idx = idx;
th_list->num = num;
th_list->threads = E_NEW mysql_thread_t[num];
for (int i = 0;i < num; i++) {
mysql_thread_t *th = th_list->threads + i;
th->mysql = NULL;
}
s_threads[idx] = th_list;
}
for (int i = 0; i < num; ++i) {
mysql_thread_t *th = NULL;
th = th_list->threads + i;
char value = 1;
MYSQL * m = th->mysql;
try {
if (m && 0 == mysql_ping(m)) {
return ELF_RC_DB_OK;
}
m = mysql_init(NULL);
mysql_options(m, MYSQL_OPT_RECONNECT, (char *)&value);
mysql_options(m, MYSQL_SET_CHARSET_NAME, "utf8");
if (!mysql_real_connect(m, host.c_str(), user.c_str(),
passwd.c_str(), db.c_str(), port,
NULL, CLIENT_MULTI_STATEMENTS)) {
LOG_ERROR("db", "Connect DB failed: %s.",
mysql_error(m));
return ELF_RC_DB_INIT_FAILED;
}
th->mysql = m;
th->tid = thread_init(handle, (void *)th);
} catch(...) {
LOG_ERROR("db", "Connect DB failed: %s.",
mysql_error(m));
return ELF_RC_DB_INIT_FAILED;
}
}
return ELF_RC_DB_OK;
}
int db_proc(void)
{
if (s_threads.empty()) return -1;
std::deque<query_t *> list;
std::deque<query_t *>::iterator itr;
s_queue_res.swap(list);
for (itr = list.begin(); itr != list.end(); ++itr) {
query_t *q = *itr;
// object has not been destroyed
response(q);
}
return 0;
}
void db_req(int idx, const char *cmd, bool sim, db_callback proc,
oid_t oid, pb_t *out, const std::string &field)
{
thread_list_map::iterator itr = s_threads.find(idx);
if (itr == s_threads.end()) {
return;
}
thread_list_t *th_list = itr->second;
int tidx = 0;
query_t *q = E_NEW query_t;
if (proc == NULL && out == NULL) {
q->type = QUERY_NO_RES;
} else if (out == NULL) {
q->type = QUERY_RAW;
} else if (field == "") {
q->type = QUERY_PB;
} else {
q->type = QUERY_FIELD;
}
q->cmd = cmd;
q->stamp = time_ms();
q->oid = oid;
q->pb = out;
q->field = field;
q->proc = proc;
q->data = NULL;
if (sim) {
tidx = oid % (th_list->num - 1) + 1;
}
mysql_thread_t *th = th_list->threads + tidx;
th->req.push(q);
}
void response(query_t *q)
{
assert(q);
switch (q->type) {
case QUERY_RAW:
if (q->proc) {
q->proc(q->oid, q->data);
}
break;
case QUERY_PB:
retrieve_pb(q);
if (q->proc) {
q->proc(q->oid, q->pb);
}
break;
case QUERY_FIELD:
retrieve_field(q);
if (q->proc) {
q->proc(q->oid, q->pb);
}
break;
default:
assert(0);
break;
}
destroy(q);
}
size_t db_pending_size(void)
{
size_t sum = 0;
thread_list_map::iterator itr = s_threads.begin();
for (;itr != s_threads.end(); ++itr) {
thread_list_t *th_list = itr->second;
for (int i = 0;i < th_list->num; i++) {
mysql_thread_t *th = th_list->threads + i;
sum += th->req.size();
}
}
return sum;
}
} // namespace elf
<|endoftext|>
|
<commit_before>/**
Copyright (c) 2015, Nsynapse Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @mainpage COSSB(Component-based Open & Simple Service Broker)
* @details
*/
/**
* @file engine.cpp
* @brief COSSB Engine
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 9
* @details COSSB Engine main starter
*/
#include <iostream>
#include <csignal>
#include <cstdlib>
#include <popt.h>
#include <memory>
#include <dirent.h>
#include "cossb.hpp"
using namespace std;
using namespace cossb;
void destroy() {
cossb::core::cossb_destroy();
_exit(EXIT_SUCCESS);
}
/**
* @brief SIGINT signal callback function
* @details Stop all services and destroy all instances
*/
void sigc_interrupt(int param) {
destroy();
}
/**
* @brief Main routine
* @param command
* @details Start with default components
*/
int main(int argc, char* argv[])
{
signal(SIGINT, sigc_interrupt);
char* manifest_file = nullptr;
char* util = nullptr;
struct poptOption optionTable[] =
{
{"run", 'r', POPT_ARG_STRING, (void*)manifest_file, 'r', "Run Engine with manifest configuration file", "XML manifest file"},
{"version", 'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
{"utility", 'u', POPT_ARG_STRING, (void*)util, 'u', "Run target utility for COSSB", "target utility"},
{"utilitylist", 'l', POPT_ARG_NONE, 0, 'l', "Show exist COSSB utility", ""},
POPT_AUTOHELP
POPT_TABLEEND
};
poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
poptSetOtherOptionHelp(optionCon, "<option>");
if(argc<2)
{
std::cout << poptStrerror(POPT_ERROR_NOARG) << endl;
_exit(EXIT_SUCCESS);
}
//only one opt
int opt = poptGetNextOpt(optionCon);
if(opt>=0)
{
switch(opt)
{
// install components
case 'v':
{
std::cout << COSSB_NAME << COSSB_VERSION << " (Released " << __DATE__ << " " <<__TIME__ << ")" << std::endl;
_exit(EXIT_SUCCESS);
} break;
//run with default configuration file(manifest.xml)
case 'r':
{
string manifest = (const char*)poptGetOptArg(optionCon);
if(!manifest.empty())
{
if(!cossb::core::cossb_init(manifest.c_str()))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
//start the cossb service
cossb::core::cossb_start();
pause();
}
}
break;
//use COSSB utility
case 'u':
{
cossb_log->log(log::loglevel::INFO, "Initializing....");
if(!cossb::core::cossb_init("manifest.xml", false))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
string target = (const char*)poptGetOptArg(optionCon);
interface::iutility* _utility = new util::utilloader(target.c_str());
if(!_utility->execute(argc, argv))
cossb_log->log(log::loglevel::ERROR, fmt::format("Cannot execute '{}' utility", target).c_str());
delete _utility;
}
break;
//show utility
case 'l':
{
cossb_log->log(log::loglevel::INFO, "Utility Listing..");
//find files in dir.
struct dirent* ent;
struct stat st;
DIR* dir;
dir = ::opendir("./");
while((ent = readdir(dir))) {
const string filename = ent->d_name;
const string fullpath = "./"+filename;
if(!stat(fullpath.c_str(), &st) && (st.st_mode&S_IFMT)==S_IFREG) {
if(filename.substr(filename.find_last_of(".") + 1) == "util") {
//interface::iutility* _utility = new util::utilloader(filename.c_str());
//cossb_log->log(log::loglevel::INFO, fmt::format("help : {}", _utility->help()).c_str());
//delete _utility;
}
}
}
closedir(dir);
/*interface::iutility* _utility = new util::utilloader(target.c_str());
if(!_utility->execute(argc, argv))
cossb_log->log(log::loglevel::ERROR, fmt::format("Cannot execute '{}' utility", target).c_str());
delete _utility;*/
}
break;
}
}
if (opt<-1)
{
cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
destroy();
}
poptFreeContext(optionCon);
destroy();
return 0;
}
<commit_msg>utility list option updated<commit_after>/**
Copyright (c) 2015, Nsynapse Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @mainpage COSSB(Component-based Open & Simple Service Broker)
* @details
*/
/**
* @file engine.cpp
* @brief COSSB Engine
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 9
* @details COSSB Engine main starter
*/
#include <iostream>
#include <csignal>
#include <cstdlib>
#include <popt.h>
#include <memory>
#include <dirent.h>
#include "cossb.hpp"
using namespace std;
using namespace cossb;
void destroy() {
cossb::core::cossb_destroy();
_exit(EXIT_SUCCESS);
}
/**
* @brief SIGINT signal callback function
* @details Stop all services and destroy all instances
*/
void sigc_interrupt(int param) {
destroy();
}
/**
* @brief Main routine
* @param command
* @details Start with default components
*/
int main(int argc, char* argv[])
{
signal(SIGINT, sigc_interrupt);
char* manifest_file = nullptr;
char* util = nullptr;
struct poptOption optionTable[] =
{
{"run", 'r', POPT_ARG_STRING, (void*)manifest_file, 'r', "Run Engine with manifest configuration file", "XML manifest file"},
{"version", 'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
{"utility", 'u', POPT_ARG_STRING, (void*)util, 'u', "Run target utility for COSSB", "target utility"},
{"utilitylist", 'l', POPT_ARG_NONE, 0, 'l', "Show exist COSSB utility", ""},
POPT_AUTOHELP
POPT_TABLEEND
};
poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
poptSetOtherOptionHelp(optionCon, "<option>");
if(argc<2)
{
std::cout << poptStrerror(POPT_ERROR_NOARG) << endl;
_exit(EXIT_SUCCESS);
}
//only one opt
int opt = poptGetNextOpt(optionCon);
if(opt>=0)
{
switch(opt)
{
// install components
case 'v':
{
std::cout << COSSB_NAME << COSSB_VERSION << " (Released " << __DATE__ << " " <<__TIME__ << ")" << std::endl;
_exit(EXIT_SUCCESS);
} break;
//run with default configuration file(manifest.xml)
case 'r':
{
string manifest = (const char*)poptGetOptArg(optionCon);
if(!manifest.empty())
{
if(!cossb::core::cossb_init(manifest.c_str()))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
//start the cossb service
cossb::core::cossb_start();
pause();
}
}
break;
//use COSSB utility
case 'u':
{
cossb_log->log(log::loglevel::INFO, "Initializing....");
if(!cossb::core::cossb_init("manifest.xml", false))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
string target = (const char*)poptGetOptArg(optionCon);
interface::iutility* _utility = new util::utilloader(target.c_str());
if(!_utility->execute(argc, argv))
cossb_log->log(log::loglevel::ERROR, fmt::format("Cannot execute '{}' utility", target).c_str());
delete _utility;
}
break;
//show list of utilities
case 'l':
{
cossb_log->log(log::loglevel::INFO, "Utility Listing..");
//find files in dir.
struct dirent* ent;
struct stat st;
DIR* dir;
dir = ::opendir("./");
while((ent = readdir(dir))) {
const string filename = ent->d_name;
const string fullpath = "./"+filename;
if(!stat(fullpath.c_str(), &st) && (st.st_mode&S_IFMT)==S_IFREG) {
if(filename.substr(filename.find_last_of(".") + 1) == "util") {
interface::iutility* _utility = new util::utilloader(filename.c_str());
//cossb_log->log(log::loglevel::INFO, fmt::format("help : {}", _utility->help()).c_str());
delete _utility;
}
}
}
closedir(dir);
/*interface::iutility* _utility = new util::utilloader(target.c_str());
if(!_utility->execute(argc, argv))
cossb_log->log(log::loglevel::ERROR, fmt::format("Cannot execute '{}' utility", target).c_str());
delete _utility;*/
}
break;
}
}
if (opt<-1)
{
cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
destroy();
}
poptFreeContext(optionCon);
destroy();
return 0;
}
<|endoftext|>
|
<commit_before>#include "engine.h"
#include "constants.h"
#include "state.h"
#include "util.h"
#include <glog/logging.h>
#include <SFML/Graphics.hpp>
namespace Engine {
std::stack<std::unique_ptr<Screen>> screens;
sf::RenderWindow window;
bool running_ = true;
bool init() {
window.create(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "Portland");
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(true);
GameState::initLuaApi();
LOG(INFO) << "Game initialized";
return true;
}
void run() {
sf::Clock clock;
sf::RenderTexture target;
target.create(SCREEN_WIDTH, SCREEN_HEIGHT);
while (window.isOpen() && running_) {
sf::Time elapsed = clock.restart();
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
return;
} else if (event.type == sf::Event::Resized) {
auto windowSize = window.getSize();
window.setView(
sf::View(sf::FloatRect(0.f, 0.f, windowSize.x, windowSize.y)));
}
screens.top()->handleEvent(event);
}
running_ = screens.top()->update(elapsed);
auto windowSize = window.getSize();
target.clear(sf::Color::Black);
screens.top()->render(target);
target.display();
sf::Sprite rendered(target.getTexture());
rendered.setOrigin(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
rendered.setPosition(windowSize.x / 2, windowSize.y / 2);
float scale;
if (windowSize.x * 9 > windowSize.y * 16) {
scale = 1.0f * windowSize.y / SCREEN_HEIGHT;
} else {
scale = 1.0f * windowSize.x / SCREEN_WIDTH;
}
rendered.setScale(scale, scale);
window.clear(sf::Color::Black);
window.draw(rendered);
window.display();
}
}
void cleanup() {
while (!screens.empty()) {
popScreen();
}
}
void pushScreen(Screen *screen) {
pushScreen(std::unique_ptr<Screen>(screen));
}
void pushScreen(std::unique_ptr<Screen> screen) {
screens.push(std::move(screen));
}
std::unique_ptr<Screen> popScreen() {
auto top = std::move(screens.top());
screens.pop();
return top;
}
std::unique_ptr<Screen> replaceScreen(Screen *screen) {
auto replaced = popScreen();
pushScreen(screen);
return replaced;
}
}
<commit_msg>Scale the window on startup<commit_after>#include "engine.h"
#include "constants.h"
#include "state.h"
#include "util.h"
#include <glog/logging.h>
#include <SFML/Graphics.hpp>
namespace Engine {
std::stack<std::unique_ptr<Screen>> screens;
sf::RenderWindow window;
bool running_ = true;
bool init() {
sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
int scale = std::min(desktop.width / SCREEN_WIDTH,
desktop.height / SCREEN_HEIGHT);
LOG(INFO) << "Desktop width: " << desktop.width;
LOG(INFO) << "Desktop height: " << desktop.height;
LOG(INFO) << "Screen scale ratio: " << scale;
window.create(sf::VideoMode(SCREEN_WIDTH * scale, SCREEN_HEIGHT * scale),
"Portland");
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(true);
GameState::initLuaApi();
LOG(INFO) << "Game initialized";
return true;
}
void run() {
sf::Clock clock;
sf::RenderTexture target;
target.create(SCREEN_WIDTH, SCREEN_HEIGHT);
while (window.isOpen() && running_) {
sf::Time elapsed = clock.restart();
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
return;
} else if (event.type == sf::Event::Resized) {
auto windowSize = window.getSize();
window.setView(
sf::View(sf::FloatRect(0.f, 0.f, windowSize.x, windowSize.y)));
}
screens.top()->handleEvent(event);
}
running_ = screens.top()->update(elapsed);
auto windowSize = window.getSize();
target.clear(sf::Color::Black);
screens.top()->render(target);
target.display();
sf::Sprite rendered(target.getTexture());
rendered.setOrigin(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
rendered.setPosition(windowSize.x / 2, windowSize.y / 2);
float scale;
if (windowSize.x * 9 > windowSize.y * 16) {
scale = 1.0f * windowSize.y / SCREEN_HEIGHT;
} else {
scale = 1.0f * windowSize.x / SCREEN_WIDTH;
}
rendered.setScale(scale, scale);
window.clear(sf::Color::Black);
window.draw(rendered);
window.display();
}
}
void cleanup() {
while (!screens.empty()) {
popScreen();
}
}
void pushScreen(Screen *screen) {
pushScreen(std::unique_ptr<Screen>(screen));
}
void pushScreen(std::unique_ptr<Screen> screen) {
screens.push(std::move(screen));
}
std::unique_ptr<Screen> popScreen() {
auto top = std::move(screens.top());
screens.pop();
return top;
}
std::unique_ptr<Screen> replaceScreen(Screen *screen) {
auto replaced = popScreen();
pushScreen(screen);
return replaced;
}
}
<|endoftext|>
|
<commit_before>#include "engine.h"
#include "random.h"
#include "Updatable.h"
#include "collisionable.h"
#include "audio/source.h"
#include "io/keybinding.h"
#include "soundManager.h"
#include "windowManager.h"
#include "scriptInterface.h"
#include "multiplayer_server.h"
#include <thread>
#include <SDL.h>
#ifdef DEBUG
#include <typeinfo>
int DEBUG_PobjCount;
PObject* DEBUG_PobjListStart;
#endif
Engine* engine;
Engine::Engine()
{
engine = this;
#ifdef WIN32
// Setup crash reporter (Dr. MinGW) if available.
exchndl = DynamicLibrary::open("exchndl.dll");
if (exchndl)
{
auto pfnExcHndlInit = exchndl->getFunction<void(*)(void)>("ExcHndlInit");
if (pfnExcHndlInit)
{
pfnExcHndlInit();
LOG(INFO) << "Crash Reporter ON";
}
else
{
exchndl.reset();
}
}
#endif // WIN32
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
#ifdef SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH
SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1");
#elif defined(SDL_HINT_MOUSE_TOUCH_EVENTS)
SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0");
SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
#endif
SDL_Init(SDL_INIT_EVERYTHING);
SDL_ShowCursor(false);
SDL_StopTextInput();
atexit(SDL_Quit);
initRandom();
CollisionManager::initialize();
gameSpeed = 1.0f;
running = true;
elapsedTime = 0.0f;
soundManager = new SoundManager();
}
Engine::~Engine()
{
Window::all_windows.clear();
updatableList.clear();
delete soundManager;
soundManager = nullptr;
}
void Engine::registerObject(string name, P<PObject> obj)
{
objectMap[name] = obj;
}
P<PObject> Engine::getObject(string name)
{
if (!objectMap[name])
return NULL;
return objectMap[name];
}
void Engine::runMainLoop()
{
if (Window::all_windows.size() == 0)
{
sp::SystemStopwatch frame_timer;
while(running)
{
float delta = frame_timer.restart();
if (delta > 0.5f)
delta = 0.5f;
if (delta < 0.001f)
delta = 0.001f;
delta *= gameSpeed;
foreach(Updatable, u, updatableList)
u->update(delta);
elapsedTime += delta;
CollisionManager::handleCollisions(delta);
ScriptObject::clearDestroyedObjects();
soundManager->updateTick();
std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta));
}
}else{
sp::audio::Source::startAudioSystem();
sp::SystemStopwatch frame_timer;
#ifdef DEBUG
sp::SystemTimer debug_output_timer;
debug_output_timer.repeat(5);
#endif
while(running)
{
// Handle events
SDL_Event event;
while (SDL_PollEvent(&event))
{
handleEvent(event);
}
#ifdef DEBUG
if (debug_output_timer.isExpired())
LOG(DEBUG) << "Object count: " << DEBUG_PobjCount << " " << updatableList.size();
#endif
float delta = frame_timer.restart();
if (delta > 0.5f)
delta = 0.5f;
if (delta < 0.001f)
delta = 0.001f;
delta *= gameSpeed;
EngineTiming engine_timing;
sp::SystemStopwatch engine_timing_stopwatch;
foreach(Updatable, u, updatableList) {
u->update(delta);
}
elapsedTime += delta;
engine_timing.update = engine_timing_stopwatch.restart();
CollisionManager::handleCollisions(delta);
engine_timing.collision = engine_timing_stopwatch.restart();
ScriptObject::clearDestroyedObjects();
soundManager->updateTick();
// Clear the window
for(auto window : Window::all_windows)
window->render();
engine_timing.render = engine_timing_stopwatch.restart();
engine_timing.server_update = 0.0f;
if (game_server)
engine_timing.server_update = game_server->getUpdateTime();
last_engine_timing = engine_timing;
sp::io::Keybinding::allPostUpdate();
}
soundManager->stopMusic();
sp::audio::Source::stopAudioSystem();
}
}
void Engine::handleEvent(SDL_Event& event)
{
if (event.type == SDL_QUIT)
running = false;
#ifdef DEBUG
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)
running = false;
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l)
{
int n = 0;
printf("------------------------\n");
std::unordered_map<string,int> totals;
for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)
{
printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());
if (!obj->isDestroyed())
{
totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1;
}
}
printf("--non-destroyed totals--\n");
int grand_total=0;
for (auto entry : totals)
{
printf("%4d %s\n", entry.second, entry.first.c_str());
grand_total+=entry.second;
}
printf("%4d %s\n",grand_total,"All PObjects");
printf("------------------------\n");
}
#endif
unsigned int window_id = 0;
switch(event.type)
{
case SDL_KEYDOWN:
#ifdef __EMSCRIPTEN__
if (!audio_started)
{
audio::AudioSource::startAudioSystem();
audio_started = true;
}
#endif
case SDL_KEYUP:
window_id = event.key.windowID;
break;
case SDL_MOUSEMOTION:
window_id = event.motion.windowID;
break;
case SDL_MOUSEBUTTONDOWN:
#ifdef __EMSCRIPTEN__
if (!audio_started)
{
audio::AudioSource::startAudioSystem();
audio_started = true;
}
#endif
case SDL_MOUSEBUTTONUP:
window_id = event.button.windowID;
break;
case SDL_MOUSEWHEEL:
window_id = event.wheel.windowID;
break;
case SDL_WINDOWEVENT:
window_id = event.window.windowID;
break;
case SDL_FINGERDOWN:
case SDL_FINGERUP:
case SDL_FINGERMOTION:
#if SDL_VERSION_ATLEAST(2, 0, 12)
window_id = event.tfinger.windowID;
#else
window_id = SDL_GetWindowID(SDL_GetMouseFocus());
#endif
break;
case SDL_TEXTEDITING:
window_id = event.edit.windowID;
break;
case SDL_TEXTINPUT:
window_id = event.text.windowID;
break;
}
if (window_id != 0)
{
foreach(Window, window, Window::all_windows)
if (window->window && SDL_GetWindowID(static_cast<SDL_Window*>(window->window)) == window_id)
window->handleEvent(event);
}
sp::io::Keybinding::handleEvent(event);
}
void Engine::setGameSpeed(float speed)
{
gameSpeed = speed;
}
float Engine::getGameSpeed()
{
return gameSpeed;
}
float Engine::getElapsedTime()
{
return elapsedTime;
}
Engine::EngineTiming Engine::getEngineTiming()
{
return last_engine_timing;
}
void Engine::shutdown()
{
running = false;
}
<commit_msg>Fix an issue with multiple windows<commit_after>#include "engine.h"
#include "random.h"
#include "Updatable.h"
#include "collisionable.h"
#include "audio/source.h"
#include "io/keybinding.h"
#include "soundManager.h"
#include "windowManager.h"
#include "scriptInterface.h"
#include "multiplayer_server.h"
#include <thread>
#include <SDL.h>
#ifdef DEBUG
#include <typeinfo>
int DEBUG_PobjCount;
PObject* DEBUG_PobjListStart;
#endif
Engine* engine;
Engine::Engine()
{
engine = this;
#ifdef WIN32
// Setup crash reporter (Dr. MinGW) if available.
exchndl = DynamicLibrary::open("exchndl.dll");
if (exchndl)
{
auto pfnExcHndlInit = exchndl->getFunction<void(*)(void)>("ExcHndlInit");
if (pfnExcHndlInit)
{
pfnExcHndlInit();
LOG(INFO) << "Crash Reporter ON";
}
else
{
exchndl.reset();
}
}
#endif // WIN32
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); // Have clicking on a window to get focus generate mouse events. For multimonitor support.
#ifdef SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH
SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1");
#elif defined(SDL_HINT_MOUSE_TOUCH_EVENTS)
SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0");
SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
#endif
SDL_Init(SDL_INIT_EVERYTHING);
SDL_ShowCursor(false);
SDL_StopTextInput();
atexit(SDL_Quit);
initRandom();
CollisionManager::initialize();
gameSpeed = 1.0f;
running = true;
elapsedTime = 0.0f;
soundManager = new SoundManager();
}
Engine::~Engine()
{
Window::all_windows.clear();
updatableList.clear();
delete soundManager;
soundManager = nullptr;
}
void Engine::registerObject(string name, P<PObject> obj)
{
objectMap[name] = obj;
}
P<PObject> Engine::getObject(string name)
{
if (!objectMap[name])
return NULL;
return objectMap[name];
}
void Engine::runMainLoop()
{
if (Window::all_windows.size() == 0)
{
sp::SystemStopwatch frame_timer;
while(running)
{
float delta = frame_timer.restart();
if (delta > 0.5f)
delta = 0.5f;
if (delta < 0.001f)
delta = 0.001f;
delta *= gameSpeed;
foreach(Updatable, u, updatableList)
u->update(delta);
elapsedTime += delta;
CollisionManager::handleCollisions(delta);
ScriptObject::clearDestroyedObjects();
soundManager->updateTick();
std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta));
}
}else{
sp::audio::Source::startAudioSystem();
sp::SystemStopwatch frame_timer;
#ifdef DEBUG
sp::SystemTimer debug_output_timer;
debug_output_timer.repeat(5);
#endif
while(running)
{
// Handle events
SDL_Event event;
while (SDL_PollEvent(&event))
{
handleEvent(event);
}
#ifdef DEBUG
if (debug_output_timer.isExpired())
LOG(DEBUG) << "Object count: " << DEBUG_PobjCount << " " << updatableList.size();
#endif
float delta = frame_timer.restart();
if (delta > 0.5f)
delta = 0.5f;
if (delta < 0.001f)
delta = 0.001f;
delta *= gameSpeed;
EngineTiming engine_timing;
sp::SystemStopwatch engine_timing_stopwatch;
foreach(Updatable, u, updatableList) {
u->update(delta);
}
elapsedTime += delta;
engine_timing.update = engine_timing_stopwatch.restart();
CollisionManager::handleCollisions(delta);
engine_timing.collision = engine_timing_stopwatch.restart();
ScriptObject::clearDestroyedObjects();
soundManager->updateTick();
// Clear the window
for(auto window : Window::all_windows)
window->render();
engine_timing.render = engine_timing_stopwatch.restart();
engine_timing.server_update = 0.0f;
if (game_server)
engine_timing.server_update = game_server->getUpdateTime();
last_engine_timing = engine_timing;
sp::io::Keybinding::allPostUpdate();
}
soundManager->stopMusic();
sp::audio::Source::stopAudioSystem();
}
}
void Engine::handleEvent(SDL_Event& event)
{
if (event.type == SDL_QUIT)
running = false;
#ifdef DEBUG
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)
running = false;
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l)
{
int n = 0;
printf("------------------------\n");
std::unordered_map<string,int> totals;
for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)
{
printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());
if (!obj->isDestroyed())
{
totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1;
}
}
printf("--non-destroyed totals--\n");
int grand_total=0;
for (auto entry : totals)
{
printf("%4d %s\n", entry.second, entry.first.c_str());
grand_total+=entry.second;
}
printf("%4d %s\n",grand_total,"All PObjects");
printf("------------------------\n");
}
#endif
unsigned int window_id = 0;
switch(event.type)
{
case SDL_KEYDOWN:
#ifdef __EMSCRIPTEN__
if (!audio_started)
{
audio::AudioSource::startAudioSystem();
audio_started = true;
}
#endif
case SDL_KEYUP:
window_id = event.key.windowID;
break;
case SDL_MOUSEMOTION:
window_id = event.motion.windowID;
break;
case SDL_MOUSEBUTTONDOWN:
#ifdef __EMSCRIPTEN__
if (!audio_started)
{
audio::AudioSource::startAudioSystem();
audio_started = true;
}
#endif
case SDL_MOUSEBUTTONUP:
window_id = event.button.windowID;
break;
case SDL_MOUSEWHEEL:
window_id = event.wheel.windowID;
break;
case SDL_WINDOWEVENT:
window_id = event.window.windowID;
break;
case SDL_FINGERDOWN:
case SDL_FINGERUP:
case SDL_FINGERMOTION:
#if SDL_VERSION_ATLEAST(2, 0, 12)
window_id = event.tfinger.windowID;
#else
window_id = SDL_GetWindowID(SDL_GetMouseFocus());
#endif
break;
case SDL_TEXTEDITING:
window_id = event.edit.windowID;
break;
case SDL_TEXTINPUT:
window_id = event.text.windowID;
break;
}
if (window_id != 0)
{
foreach(Window, window, Window::all_windows)
if (window->window && SDL_GetWindowID(static_cast<SDL_Window*>(window->window)) == window_id)
window->handleEvent(event);
}
sp::io::Keybinding::handleEvent(event);
}
void Engine::setGameSpeed(float speed)
{
gameSpeed = speed;
}
float Engine::getGameSpeed()
{
return gameSpeed;
}
float Engine::getElapsedTime()
{
return elapsedTime;
}
Engine::EngineTiming Engine::getEngineTiming()
{
return last_engine_timing;
}
void Engine::shutdown()
{
running = false;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <random>
#include <functional>
namespace dust
{
template<class State, class Observation>
class filter
{
public:
using motion_model = std::function<State(const State&, float)>;
using observation_probability = std::function<float(const Observation&,
const State&)>;
using uniform_state = std::function<State()>;
filter(motion_model motion, observation_probability obs_prob,
uniform_state uniform, unsigned int num_particles)
: motion(motion),
obs_prob(obs_prob),
uniform(uniform),
num_particles(num_particles),
resample_dist(0, 1.0f / num_particles)
{
reset();
sampled_particles.resize(num_particles);
};
void reset()
{
particles.clear();
particles.reserve(num_particles);
std::generate_n(std::back_inserter(particles), num_particles, uniform);
}
void update(const Observation& z, float dt)
{
sampled_particles.clear();
sampled_particles.reserve(num_particles);
std::transform(particles.begin(), particles.end(),
std::back_inserter(sampled_particles),
[&](const State& particle) {
auto x = motion(particle, dt);
auto w = obs_prob(z, x);
return std::make_pair(x, w);
});
particles.clear();
auto r = resample_dist(gen);
auto c = sampled_particles.front().second;
unsigned int i = 0;
for (unsigned int m = 0; m < num_particles; m++)
{
auto U = r + (m - 1.0f) / num_particles;
while (U > c)
{
i++;
c += sampled_particles[i].second;
}
particles.push_back(sampled_particles[i].first);
}
}
private:
motion_model motion;
observation_probability obs_prob;
uniform_state uniform;
unsigned int num_particles;
std::vector<State> particles;
std::vector<std::pair<State, float>> sampled_particles;
std::mt19937 gen;
std::uniform_real_distribution<float> resample_dist;
};
}<commit_msg>rolled the observation model into the motion model<commit_after>#pragma once
#include <random>
#include <functional>
namespace dust
{
template<class State, class Observation>
class filter
{
public:
using motion_model = std::function<std::pair<float, State>(const State&,
const Observation&,
float)>;
using uniform_state = std::function<State()>;
filter(motion_model motion, uniform_state uniform, unsigned int num_particles)
: motion(motion),
uniform(uniform),
num_particles(num_particles),
resample_dist(0, 1.0f / num_particles)
{
reset();
sampled_particles.resize(num_particles);
}
void reset()
{
particles.clear();
particles.reserve(num_particles);
std::generate_n(std::back_inserter(particles), num_particles, uniform);
}
void update(const Observation& z, float dt)
{
sampled_particles.clear();
sampled_particles.reserve(num_particles);
std::transform(particles.begin(), particles.end(),
std::back_inserter(sampled_particles),
[&](const State& particle) {
return motion(particle, z, dt);
});
particles.clear();
auto r = resample_dist(gen);
auto c = sampled_particles.front().second;
unsigned int i = 0;
for (unsigned int m = 0; m < num_particles; m++)
{
auto U = r + (m - 1.0f) / num_particles;
while (U > c)
{
i++;
c += sampled_particles[i].second;
}
particles.push_back(sampled_particles[i].first);
}
}
protected:
std::mt19937 gen;
private:
motion_model motion;
uniform_state uniform;
unsigned int num_particles;
std::vector<State> particles;
std::vector<std::pair<State, float>> sampled_particles;
std::uniform_real_distribution<float> resample_dist;
};
}
<|endoftext|>
|
<commit_before>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include <http_config.h>
namespace DupModule {
apr_status_t
inputFilterHandler(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)
{
apr_status_t lStatus = ap_get_brigade(pF->next, pB, pMode, pBlock, pReadbytes);
if (lStatus != APR_SUCCESS) {
return lStatus;
}
request_rec *pRequest = pF->r;
if (pRequest) {
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if (!tConf) {
return OK; // SHOULD NOT HAPPEN
}
// No context? new request
if (!pF->ctx) {
RequestInfo *info = new RequestInfo(tConf->getNextReqId());
ap_set_module_config(pRequest->request_config, &dup_module, (void *)info);
pF->ctx = info;
} else if (pF->ctx == (void *)1) {
return OK;
}
RequestInfo *pBH = static_cast<RequestInfo *>(pF->ctx);
// TODO Body is stored only if the payload flag is activated
for (apr_bucket *b = APR_BRIGADE_FIRST(pB);
b != APR_BRIGADE_SENTINEL(pB);
b = APR_BUCKET_NEXT(b) ) {
// Metadata end of stream
if ( APR_BUCKET_IS_EOS(b) ) {
// TODO Do context enrichment synchronously
gProcessor->enrichContext();
pF->ctx = (void *)1;
break;
}
const char* lReqPart = NULL;
apr_size_t lLength = 0;
apr_status_t lStatus = apr_bucket_read(b, &lReqPart, &lLength, APR_BLOCK_READ);
if ((lStatus != APR_SUCCESS) || (lReqPart == NULL)) {
continue;
}
pBH->mBody += std::string(lReqPart, lLength);
}
}
return OK;
}
/*
* Request context used during brigade run
*/
class RequestContext {
public:
apr_bucket_brigade *tmpbb;
RequestInfo *req; /** Req is pushed to requestprocessor for duplication and will be deleted later*/
RequestContext(ap_filter_t *pFilter) {
tmpbb = apr_brigade_create(pFilter->r->pool, pFilter->c->bucket_alloc);
req = reinterpret_cast<RequestInfo *>(ap_get_module_config(pFilter->r->request_config, &dup_module));
assert(req);
}
~RequestContext() {
apr_brigade_cleanup(tmpbb);
}
};
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
headers->push_back(std::pair<std::string, std::string>(key, value));
return 0;
}
static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r, bool withAnswer) {
// Basic
r.mPoison = false;
r.mConfPath = tConf->dirName;
r.mPath = pRequest->uri;
r.mArgs = pRequest->args ? pRequest->args : "";
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);
if (withAnswer) {
// Copy headers out
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersOut, pRequest->headers_out, NULL);
}
}
static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
const char *reqId = apr_table_get(pRequest->headers_in, c_UNIQUE_ID);
Log::debug("### Pushing a request with ID: %s, body size:%s", reqId, boost::lexical_cast<std::string>(pBH->mBody.size()).c_str());
Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
Log::debug("### Request args: %s", pRequest->args);
}
apr_status_t
outputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
request_rec *pRequest = pFilter->r;
if (!pRequest || !pRequest->per_dir_config)
return ap_pass_brigade(pFilter->next, pBrigade);
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
assert(tConf);
// Request answer analyse
RequestContext *ctx = static_cast<RequestContext *>(pFilter->ctx);
if (ctx == NULL) {
// Context init
ctx = new RequestContext(pFilter);
pFilter->ctx = ctx;
} else if (ctx == (void *) -1) {
return ap_pass_brigade(pFilter->next, pBrigade);
}
if (DuplicationType::value != DuplicationType::REQUEST_WITH_ANSWER) {
// Asynchronous push of request without the answer
RequestInfo *rH = ctx->req;
prepareRequestInfo(tConf, pRequest, *rH, false);
printRequest(pRequest, rH, tConf);
gThreadPool->push(rH);
delete ctx;
pFilter->ctx = (void *) -1;
return ap_pass_brigade(pFilter->next, pBrigade);
}
// Asynchronous push of request WITH the answer
apr_bucket *currentBucket;
while ((currentBucket = APR_BRIGADE_FIRST(pBrigade)) != APR_BRIGADE_SENTINEL(pBrigade)) {
const char *data;
apr_size_t len;
apr_status_t rv;
rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);
if ((rv == APR_SUCCESS) && (data != NULL)) {
ctx->req->mAnswer.append(data, len);
}
/* Remove bucket e from bb. */
APR_BUCKET_REMOVE(currentBucket);
/* Insert it into temporary brigade. */
APR_BRIGADE_INSERT_HEAD(ctx->tmpbb, currentBucket);
/* Pass brigade downstream. */
rv = ap_pass_brigade(pFilter->next, ctx->tmpbb);
// TODO if (rv) ...;
if (APR_BUCKET_IS_EOS(currentBucket)) {
apr_brigade_cleanup(ctx->tmpbb);
// Pushing the answer to the processor
// TODO dissociate body from header if possible
prepareRequestInfo(tConf, pRequest, *(ctx->req), true);
printRequest(pRequest, ctx->req, tConf);
// std::string reqId = boost::lexical_cast<std::string>(info->mId);
// apr_table_set(headersIn, c_UNIQUE_ID, reqId.c_str());
// apr_table_set(pRequest->headers_out, c_UNIQUE_ID, reqId.c_str());
gThreadPool->push(ctx->req);
delete ctx;
pFilter->ctx = (void *) -1;
}
else {
apr_brigade_cleanup(ctx->tmpbb);
}
}
return OK;
}
};
<commit_msg>Replugged the unique id<commit_after>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include <http_config.h>
namespace DupModule {
apr_status_t
inputFilterHandler(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)
{
apr_status_t lStatus = ap_get_brigade(pF->next, pB, pMode, pBlock, pReadbytes);
if (lStatus != APR_SUCCESS) {
return lStatus;
}
request_rec *pRequest = pF->r;
if (pRequest) {
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if (!tConf) {
return OK; // SHOULD NOT HAPPEN
}
// No context? new request
if (!pF->ctx) {
RequestInfo *info = new RequestInfo(tConf->getNextReqId());
ap_set_module_config(pRequest->request_config, &dup_module, (void *)info);
// Copy Request ID in both headers
std::string reqId = boost::lexical_cast<std::string>(info->mId);
apr_table_set(pRequest->headers_in, c_UNIQUE_ID, reqId.c_str());
apr_table_set(pRequest->headers_out, c_UNIQUE_ID, reqId.c_str());
// Backup of info struct in the request context
pF->ctx = info;
} else if (pF->ctx == (void *)1) {
return OK;
}
RequestInfo *pBH = static_cast<RequestInfo *>(pF->ctx);
// TODO Body is stored only if the payload flag is activated
for (apr_bucket *b = APR_BRIGADE_FIRST(pB);
b != APR_BRIGADE_SENTINEL(pB);
b = APR_BUCKET_NEXT(b) ) {
// Metadata end of stream
if ( APR_BUCKET_IS_EOS(b) ) {
// Synchronous context enrichment
gProcessor->enrichContext();
pF->ctx = (void *)1;
break;
}
const char* lReqPart = NULL;
apr_size_t lLength = 0;
apr_status_t lStatus = apr_bucket_read(b, &lReqPart, &lLength, APR_BLOCK_READ);
if ((lStatus != APR_SUCCESS) || (lReqPart == NULL)) {
continue;
}
pBH->mBody += std::string(lReqPart, lLength);
}
}
return OK;
}
/*
* Request context used during brigade run
*/
class RequestContext {
public:
apr_bucket_brigade *tmpbb;
RequestInfo *req; /** Req is pushed to requestprocessor for duplication and will be deleted later*/
RequestContext(ap_filter_t *pFilter) {
tmpbb = apr_brigade_create(pFilter->r->pool, pFilter->c->bucket_alloc);
req = reinterpret_cast<RequestInfo *>(ap_get_module_config(pFilter->r->request_config, &dup_module));
assert(req);
}
~RequestContext() {
apr_brigade_cleanup(tmpbb);
}
};
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
headers->push_back(std::pair<std::string, std::string>(key, value));
return 0;
}
static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r, bool withAnswer) {
// Basic
r.mPoison = false;
r.mConfPath = tConf->dirName;
r.mPath = pRequest->uri;
r.mArgs = pRequest->args ? pRequest->args : "";
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);
if (withAnswer) {
// Copy headers out
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersOut, pRequest->headers_out, NULL);
}
}
static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
const char *reqId = apr_table_get(pRequest->headers_in, c_UNIQUE_ID);
Log::debug("### Pushing a request with ID: %s, body size:%s", reqId, boost::lexical_cast<std::string>(pBH->mBody.size()).c_str());
Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
Log::debug("### Request args: %s", pRequest->args);
}
apr_status_t
outputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
request_rec *pRequest = pFilter->r;
if (!pRequest || !pRequest->per_dir_config)
return ap_pass_brigade(pFilter->next, pBrigade);
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
assert(tConf);
// Request answer analyse
RequestContext *ctx = static_cast<RequestContext *>(pFilter->ctx);
if (ctx == NULL) {
// Context init
ctx = new RequestContext(pFilter);
pFilter->ctx = ctx;
} else if (ctx == (void *) -1) {
return ap_pass_brigade(pFilter->next, pBrigade);
}
if (DuplicationType::value != DuplicationType::REQUEST_WITH_ANSWER) {
// Asynchronous push of request without the answer
RequestInfo *rH = ctx->req;
prepareRequestInfo(tConf, pRequest, *rH, false);
printRequest(pRequest, rH, tConf);
gThreadPool->push(rH);
delete ctx;
pFilter->ctx = (void *) -1;
return ap_pass_brigade(pFilter->next, pBrigade);
}
// Asynchronous push of request WITH the answer
apr_bucket *currentBucket;
while ((currentBucket = APR_BRIGADE_FIRST(pBrigade)) != APR_BRIGADE_SENTINEL(pBrigade)) {
const char *data;
apr_size_t len;
apr_status_t rv;
rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);
if ((rv == APR_SUCCESS) && (data != NULL)) {
ctx->req->mAnswer.append(data, len);
}
/* Remove bucket e from bb. */
APR_BUCKET_REMOVE(currentBucket);
/* Insert it into temporary brigade. */
APR_BRIGADE_INSERT_HEAD(ctx->tmpbb, currentBucket);
/* Pass brigade downstream. */
rv = ap_pass_brigade(pFilter->next, ctx->tmpbb);
// TODO if (rv) ...;
if (APR_BUCKET_IS_EOS(currentBucket)) {
apr_brigade_cleanup(ctx->tmpbb);
// Pushing the answer to the processor
// TODO dissociate body from header if possible
prepareRequestInfo(tConf, pRequest, *(ctx->req), true);
printRequest(pRequest, ctx->req, tConf);
gThreadPool->push(ctx->req);
delete ctx;
pFilter->ctx = (void *) -1;
}
else {
apr_brigade_cleanup(ctx->tmpbb);
}
}
return OK;
}
};
<|endoftext|>
|
<commit_before>// fluxbox.hh for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// blackbox.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// 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.
// $Id: fluxbox.hh,v 1.30 2002/10/15 20:49:00 fluxgen Exp $
#ifndef FLUXBOX_HH
#define FLUXBOX_HH
#include "Resource.hh"
#include "Keys.hh"
#include "BaseDisplay.hh"
#include "Image.hh"
#include "Timer.hh"
#include "Window.hh"
#include "Tab.hh"
#include "Toolbar.hh"
#include "Observer.hh"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#ifdef SLIT
#include "Slit.hh"
#endif // SLIT
#include "SignalHandler.hh"
#include "FbAtoms.hh"
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#include <cstdio>
#ifdef TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else // !TIME_WITH_SYS_TIME
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#else // !HAVE_SYS_TIME_H
#include <time.h>
#endif // HAVE_SYS_TIME_H
#endif // TIME_WITH_SYS_TIME
#include <string>
#include <vector>
#include <map>
#include <list>
class AtomHandler;
/**
main class for the window manager.
singleton type
*/
class Fluxbox : public BaseDisplay, public TimeoutHandler,
public FbTk::EventHandler<FbTk::SignalEvent>,
public FbAtoms,
public FbTk::Observer {
public:
Fluxbox(int argc, char **argv, const char * dpy_name= 0, const char *rc = 0);
virtual ~Fluxbox();
static Fluxbox *instance() { return singleton; }
inline bool useTabs() { return *m_rc_tabs; }
inline bool useIconBar() { return *m_rc_iconbar; }
inline void saveTabs(bool value) { *m_rc_tabs = value; }
inline void saveIconBar(bool value) { m_rc_iconbar = value; }
#ifdef HAVE_GETPID
inline Atom getFluxboxPidAtom() const { return fluxbox_pid; }
#ifdef KDE
//For KDE dock applets
inline Atom getKWM1DockwindowAtom() const { return kwm1_dockwindow; } //KDE v1.x
inline Atom getKWM2DockwindowAtom() const { return kwm2_dockwindow; } //KDE v2.x
#endif
#endif // HAVE_GETPID
Basemenu *searchMenu(Window);
FluxboxWindow *searchGroup(Window, FluxboxWindow *);
FluxboxWindow *searchWindow(Window);
inline FluxboxWindow *getFocusedWindow() { return focused_window; }
BScreen *searchScreen(Window w);
inline const Time &getDoubleClickInterval() const { return resource.double_click_interval; }
inline const Time &getLastTime() const { return last_time; }
Toolbar *searchToolbar(Window w);
Tab *searchTab(Window);
/// obsolete
enum Titlebar{SHADE=0, MINIMIZE, MAXIMIZE, CLOSE, STICK, MENU, EMPTY};
inline const std::vector<Fluxbox::Titlebar>& getTitlebarRight() { return *m_rc_titlebar_right; }
inline const std::vector<Fluxbox::Titlebar>& getTitlebarLeft() { return *m_rc_titlebar_left; }
inline const char *getStyleFilename() const { return m_rc_stylefile->c_str(); }
inline const char *getMenuFilename() const { return m_rc_menufile->c_str(); }
inline const std::string &getSlitlistFilename() const { return *m_rc_slitlistfile; }
inline int colorsPerChannel() const { return *m_rc_colors_per_channel; }
inline const timeval &getAutoRaiseDelay() const { return resource.auto_raise_delay; }
inline unsigned int getCacheLife() const { return *m_rc_cache_life * 60000; }
inline unsigned int getCacheMax() const { return *m_rc_cache_max; }
inline void maskWindowEvents(Window w, FluxboxWindow *bw)
{ masked = w; masked_window = bw; }
inline void setNoFocus(Bool f) { no_focus = f; }
void setFocusedWindow(FluxboxWindow *w);
void shutdown();
void load_rc(BScreen *);
void loadRootCommand(BScreen *);
void loadTitlebar();
void saveStyleFilename(const char *val) { m_rc_stylefile = (val == 0 ? "" : val); }
void saveMenuFilename(const char *);
void saveTitlebarFilename(const char *);
void saveSlitlistFilename(const char *val) { m_rc_slitlistfile = (val == 0 ? "" : val); }
void saveMenuSearch(Window, Basemenu *);
void saveWindowSearch(Window, FluxboxWindow *);
void saveToolbarSearch(Window, Toolbar *);
void saveTabSearch(Window, Tab *);
void saveGroupSearch(Window, FluxboxWindow *);
void save_rc();
void removeMenuSearch(Window);
void removeWindowSearch(Window);
void removeToolbarSearch(Window);
void removeTabSearch(Window);
void removeGroupSearch(Window);
void restart(const char * = 0);
void reconfigure();
void reconfigureTabs();
void rereadMenu();
void checkMenu();
/// handle any system signal sent to the application
void handleEvent(FbTk::SignalEvent * const signum);
void update(FbTk::Subject *changed);
void attachSignals(FluxboxWindow &win);
virtual void timeout();
inline const Cursor &getSessionCursor() const { return cursor.session; }
inline const Cursor &getMoveCursor() const { return cursor.move; }
inline const Cursor &getLowerLeftAngleCursor() const { return cursor.ll_angle; }
inline const Cursor &getLowerRightAngleCursor() const { return cursor.lr_angle; }
#ifdef SLIT
Slit *searchSlit(Window);
void saveSlitSearch(Window, Slit *);
void removeSlitSearch(Window);
#endif // SLIT
#ifndef HAVE_STRFTIME
enum { B_AMERICANDATE = 1, B_EUROPEANDATE };
#endif // HAVE_STRFTIME
typedef std::vector<Fluxbox::Titlebar> TitlebarList;
private:
struct cursor {
Cursor session, move, ll_angle, lr_angle;
} cursor;
typedef struct MenuTimestamp {
char *filename;
time_t timestamp;
} MenuTimestamp;
struct resource {
Time double_click_interval;
timeval auto_raise_delay;
} resource;
std::string getRcFilename();
void getDefaultDataFilename(char *, std::string &);
void load_rc();
void reload_rc();
void real_rereadMenu();
void real_reconfigure();
void handleEvent(XEvent *xe);
void setupConfigFiles();
void handleButtonEvent(XButtonEvent &be);
void handleUnmapNotify(XUnmapEvent &ue);
void handleClientMessage(XClientMessageEvent &ce);
void handleKeyEvent(XKeyEvent &ke);
void doWindowAction(Keys::KeyAction action, const int param);
#ifdef NEWWMSPEC
bool checkNETWMAtoms(XClientMessageEvent &ce);
#endif
ResourceManager m_resourcemanager, m_screen_rm;
//--- Resources
Resource<bool> m_rc_tabs, m_rc_iconbar;
Resource<int> m_rc_colors_per_channel;
Resource<std::string> m_rc_stylefile,
m_rc_menufile, m_rc_keyfile, m_rc_slitlistfile,
m_rc_groupfile;
Resource<TitlebarList> m_rc_titlebar_left, m_rc_titlebar_right;
Resource<unsigned int> m_rc_cache_life, m_rc_cache_max;
void setTitlebar(std::vector<Fluxbox::Titlebar>& dir, const char *arg);
std::map<Window, FluxboxWindow *> windowSearch;
std::map<Window, FluxboxWindow *> groupSearch;
std::map<Window, Basemenu *> menuSearch;
std::map<Window, Toolbar *> toolbarSearch;
typedef std::map<Window, Tab *> TabList;
TabList tabSearch;
#ifdef SLIT
std::map<Window, Slit *> slitSearch;
#ifdef KDE
//For KDE dock applets
Atom kwm1_dockwindow; //KDE v1.x
Atom kwm2_dockwindow; //KDE v2.x
#endif//KDE
#endif // SLIT
std::list<MenuTimestamp *> menuTimestamps;
typedef std::list<BScreen *> ScreenList;
ScreenList screenList;
FluxboxWindow *focused_window, *masked_window;
BTimer timer;
#ifdef HAVE_GETPID
Atom fluxbox_pid;
#endif // HAVE_GETPID
bool no_focus, reconfigure_wait, reread_menu_wait;
Time last_time;
Window masked;
std::string rc_file; ///< resource filename
char **argv;
int argc;
std::auto_ptr<Keys> key;
std::string slitlist_path;
//default arguments for titlebar left and right
static Fluxbox::Titlebar m_titlebar_left[], m_titlebar_right[];
static Fluxbox *singleton;
std::vector<AtomHandler *> m_atomhandler;
};
#endif // _FLUXBOX_HH_
<commit_msg>minor include fix<commit_after>// fluxbox.hh for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// blackbox.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// 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.
// $Id: fluxbox.hh,v 1.31 2002/10/19 14:15:07 fluxgen Exp $
#ifndef FLUXBOX_HH
#define FLUXBOX_HH
#include "Resource.hh"
#include "Keys.hh"
#include "BaseDisplay.hh"
#include "Image.hh"
#include "Timer.hh"
#include "Window.hh"
#include "Tab.hh"
#include "Toolbar.hh"
#include "Observer.hh"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#ifdef SLIT
#include "Slit.hh"
#endif // SLIT
#include "SignalHandler.hh"
#include "FbAtoms.hh"
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#include <cstdio>
#ifdef TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else // !TIME_WITH_SYS_TIME
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#else // !HAVE_SYS_TIME_H
#include <time.h>
#endif // HAVE_SYS_TIME_H
#endif // TIME_WITH_SYS_TIME
#include <list>
#include <map>
#include <memory>
#include <string>
#include <vector>
class AtomHandler;
/**
main class for the window manager.
singleton type
*/
class Fluxbox : public BaseDisplay, public TimeoutHandler,
public FbTk::EventHandler<FbTk::SignalEvent>,
public FbAtoms,
public FbTk::Observer {
public:
Fluxbox(int argc, char **argv, const char * dpy_name= 0, const char *rc = 0);
virtual ~Fluxbox();
static Fluxbox *instance() { return singleton; }
inline bool useTabs() { return *m_rc_tabs; }
inline bool useIconBar() { return *m_rc_iconbar; }
inline void saveTabs(bool value) { *m_rc_tabs = value; }
inline void saveIconBar(bool value) { m_rc_iconbar = value; }
#ifdef HAVE_GETPID
inline Atom getFluxboxPidAtom() const { return fluxbox_pid; }
#ifdef KDE
//For KDE dock applets
inline Atom getKWM1DockwindowAtom() const { return kwm1_dockwindow; } //KDE v1.x
inline Atom getKWM2DockwindowAtom() const { return kwm2_dockwindow; } //KDE v2.x
#endif
#endif // HAVE_GETPID
Basemenu *searchMenu(Window);
FluxboxWindow *searchGroup(Window, FluxboxWindow *);
FluxboxWindow *searchWindow(Window);
inline FluxboxWindow *getFocusedWindow() { return focused_window; }
BScreen *searchScreen(Window w);
inline const Time &getDoubleClickInterval() const { return resource.double_click_interval; }
inline const Time &getLastTime() const { return last_time; }
Toolbar *searchToolbar(Window w);
Tab *searchTab(Window);
/// obsolete
enum Titlebar{SHADE=0, MINIMIZE, MAXIMIZE, CLOSE, STICK, MENU, EMPTY};
inline const std::vector<Fluxbox::Titlebar>& getTitlebarRight() { return *m_rc_titlebar_right; }
inline const std::vector<Fluxbox::Titlebar>& getTitlebarLeft() { return *m_rc_titlebar_left; }
inline const char *getStyleFilename() const { return m_rc_stylefile->c_str(); }
inline const char *getMenuFilename() const { return m_rc_menufile->c_str(); }
inline const std::string &getSlitlistFilename() const { return *m_rc_slitlistfile; }
inline int colorsPerChannel() const { return *m_rc_colors_per_channel; }
inline const timeval &getAutoRaiseDelay() const { return resource.auto_raise_delay; }
inline unsigned int getCacheLife() const { return *m_rc_cache_life * 60000; }
inline unsigned int getCacheMax() const { return *m_rc_cache_max; }
inline void maskWindowEvents(Window w, FluxboxWindow *bw)
{ masked = w; masked_window = bw; }
inline void setNoFocus(Bool f) { no_focus = f; }
void setFocusedWindow(FluxboxWindow *w);
void shutdown();
void load_rc(BScreen *);
void loadRootCommand(BScreen *);
void loadTitlebar();
void saveStyleFilename(const char *val) { m_rc_stylefile = (val == 0 ? "" : val); }
void saveMenuFilename(const char *);
void saveTitlebarFilename(const char *);
void saveSlitlistFilename(const char *val) { m_rc_slitlistfile = (val == 0 ? "" : val); }
void saveMenuSearch(Window, Basemenu *);
void saveWindowSearch(Window, FluxboxWindow *);
void saveToolbarSearch(Window, Toolbar *);
void saveTabSearch(Window, Tab *);
void saveGroupSearch(Window, FluxboxWindow *);
void save_rc();
void removeMenuSearch(Window);
void removeWindowSearch(Window);
void removeToolbarSearch(Window);
void removeTabSearch(Window);
void removeGroupSearch(Window);
void restart(const char * = 0);
void reconfigure();
void reconfigureTabs();
void rereadMenu();
void checkMenu();
/// handle any system signal sent to the application
void handleEvent(FbTk::SignalEvent * const signum);
void update(FbTk::Subject *changed);
void attachSignals(FluxboxWindow &win);
virtual void timeout();
inline const Cursor &getSessionCursor() const { return cursor.session; }
inline const Cursor &getMoveCursor() const { return cursor.move; }
inline const Cursor &getLowerLeftAngleCursor() const { return cursor.ll_angle; }
inline const Cursor &getLowerRightAngleCursor() const { return cursor.lr_angle; }
#ifdef SLIT
Slit *searchSlit(Window);
void saveSlitSearch(Window, Slit *);
void removeSlitSearch(Window);
#endif // SLIT
#ifndef HAVE_STRFTIME
enum { B_AMERICANDATE = 1, B_EUROPEANDATE };
#endif // HAVE_STRFTIME
typedef std::vector<Fluxbox::Titlebar> TitlebarList;
private:
struct cursor {
Cursor session, move, ll_angle, lr_angle;
} cursor;
typedef struct MenuTimestamp {
char *filename;
time_t timestamp;
} MenuTimestamp;
struct resource {
Time double_click_interval;
timeval auto_raise_delay;
} resource;
std::string getRcFilename();
void getDefaultDataFilename(char *, std::string &);
void load_rc();
void reload_rc();
void real_rereadMenu();
void real_reconfigure();
void handleEvent(XEvent *xe);
void setupConfigFiles();
void handleButtonEvent(XButtonEvent &be);
void handleUnmapNotify(XUnmapEvent &ue);
void handleClientMessage(XClientMessageEvent &ce);
void handleKeyEvent(XKeyEvent &ke);
void doWindowAction(Keys::KeyAction action, const int param);
#ifdef NEWWMSPEC
bool checkNETWMAtoms(XClientMessageEvent &ce);
#endif
ResourceManager m_resourcemanager, m_screen_rm;
//--- Resources
Resource<bool> m_rc_tabs, m_rc_iconbar;
Resource<int> m_rc_colors_per_channel;
Resource<std::string> m_rc_stylefile,
m_rc_menufile, m_rc_keyfile, m_rc_slitlistfile,
m_rc_groupfile;
Resource<TitlebarList> m_rc_titlebar_left, m_rc_titlebar_right;
Resource<unsigned int> m_rc_cache_life, m_rc_cache_max;
void setTitlebar(std::vector<Fluxbox::Titlebar>& dir, const char *arg);
std::map<Window, FluxboxWindow *> windowSearch;
std::map<Window, FluxboxWindow *> groupSearch;
std::map<Window, Basemenu *> menuSearch;
std::map<Window, Toolbar *> toolbarSearch;
typedef std::map<Window, Tab *> TabList;
TabList tabSearch;
#ifdef SLIT
std::map<Window, Slit *> slitSearch;
#ifdef KDE
//For KDE dock applets
Atom kwm1_dockwindow; //KDE v1.x
Atom kwm2_dockwindow; //KDE v2.x
#endif//KDE
#endif // SLIT
std::list<MenuTimestamp *> menuTimestamps;
typedef std::list<BScreen *> ScreenList;
ScreenList screenList;
FluxboxWindow *focused_window, *masked_window;
BTimer timer;
#ifdef HAVE_GETPID
Atom fluxbox_pid;
#endif // HAVE_GETPID
bool no_focus, reconfigure_wait, reread_menu_wait;
Time last_time;
Window masked;
std::string rc_file; ///< resource filename
char **argv;
int argc;
std::auto_ptr<Keys> key;
std::string slitlist_path;
//default arguments for titlebar left and right
static Fluxbox::Titlebar m_titlebar_left[], m_titlebar_right[];
static Fluxbox *singleton;
std::vector<AtomHandler *> m_atomhandler;
};
#endif // _FLUXBOX_HH_
<|endoftext|>
|
<commit_before>/*
* Point.cpp
*
* Created on: Sep 15, 2013
* Author: drb
*/
#include "Point.h"
#include <cmath>
Point::Point() {
// TODO Auto-generated constructor stub
this->x = 0;
this->y = 0;
}
Point::~Point() {
// TODO Auto-generated destructor stub
}
Point::Point(double X, double Y)
{
this->x = Y;
this->y = X;
}
double Distance (Point* p1 , Point* p2)
{
return sqrt( pow(p1->x - p2->x, 2) + pow(p1->y - p2->y , 2) );
}
Point Point::operator= (const Point& p)
{
this->x = p.x;
this->y = p.y;
}
Point Point::operator+ (const Point& p)
{
Point pt;
pt.x = this->x + p.x;
pt.y = this->y + p.y;
return pt;
}
Point Point::operator- (const Point& p)
{
Point pt;
pt.x = this->x - p.x;
pt.y = this->y - p.y;
return pt;
}
SDL_Point Point::toSDLPoint()
{
SDL_Point p;
p.x = round(this->x);
p.y = round(this->y);
return p;
}
<commit_msg>Update Point.cpp<commit_after>/*
* Point.cpp
*
* Created on: Sep 15, 2013
* Author: drb
*/
#include "Point.h"
#include <cmath>
Point::Point() {
// TODO Auto-generated constructor stub
this->x = 0;
this->y = 0;
}
Point::~Point() {
// TODO Auto-generated destructor stub
}
Point::Point(double X, double Y)
{
this->x = Y;
this->y = X;
}
double Distance (Point* p1 , Point* p2)
{
return sqrt( pow(p1->x - p2->x, 2) + pow(p1->y - p2->y , 2) );
}
Point Point::operator= (const Point& p)
{
this->x = p.x;
this->y = p.y;
}
Point Point::operator+ (const Point& p)
{
this->x += p.x;
this->y += p.y;
}
Point Point::operator- (const Point& p)
{
this->x -= p.x;
this->y -= p.y;
}
SDL_Point Point::toSDLPoint()
{
SDL_Point p;
p.x = round(this->x);
p.y = round(this->y);
return p;
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <vector>
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
struct Params {
bool hasFile;
std::string fileName;
};
Params ParseArgs(int argc, char** argv) {
Params p;
std::vector<std::string> args(argv + 1, argv + argc);
return p;
}
class NullEventHandler : public YAML::EventHandler {
public:
void OnDocumentStart(const YAML::Mark&) override {}
void OnDocumentEnd() override {}
void OnNull(const YAML::Mark&, YAML::anchor_t) override {}
void OnAlias(const YAML::Mark&, YAML::anchor_t) override {}
void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t,
const std::string&) override {}
void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t,
YAML::EmitterStyle::value) override {}
void OnSequenceEnd() override {}
void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t,
YAML::EmitterStyle::value) override {}
void OnMapEnd() override {}
};
void parse(std::istream& input) {
try {
YAML::Node doc = YAML::Load(input);
std::cout << doc << "\n";
} catch (const YAML::Exception& e) {
std::cerr << e.what() << "\n";
}
}
int main(int argc, char** argv) {
Params p = ParseArgs(argc, argv);
if (argc > 1) {
std::ifstream fin;
fin.open(argv[1]);
parse(fin);
} else {
parse(std::cin);
}
return 0;
}
<commit_msg>Remove unused code from parse util (#1048)<commit_after>#include <fstream>
#include <iostream>
#include <vector>
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
class NullEventHandler : public YAML::EventHandler {
public:
void OnDocumentStart(const YAML::Mark&) override {}
void OnDocumentEnd() override {}
void OnNull(const YAML::Mark&, YAML::anchor_t) override {}
void OnAlias(const YAML::Mark&, YAML::anchor_t) override {}
void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t,
const std::string&) override {}
void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t,
YAML::EmitterStyle::value) override {}
void OnSequenceEnd() override {}
void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t,
YAML::EmitterStyle::value) override {}
void OnMapEnd() override {}
};
void parse(std::istream& input) {
try {
YAML::Node doc = YAML::Load(input);
std::cout << doc << "\n";
} catch (const YAML::Exception& e) {
std::cerr << e.what() << "\n";
}
}
int main(int argc, char** argv) {
if (argc > 1) {
std::ifstream fin;
fin.open(argv[1]);
parse(fin);
} else {
parse(std::cin);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "master.hpp"
namespace factor
{
THREADHANDLE start_thread(void *(*start_routine)(void *),void *args)
{
pthread_attr_t attr;
pthread_t thread;
if (pthread_attr_init (&attr) != 0)
fatal_error("pthread_attr_init() failed",0);
if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)
fatal_error("pthread_attr_setdetachstate() failed",0);
if (pthread_create (&thread, &attr, start_routine, args) != 0)
fatal_error("pthread_create() failed",0);
pthread_attr_destroy (&attr);
return thread;
}
pthread_key_t current_vm_tls_key = 0;
void init_platform_globals()
{
if (pthread_key_create(¤t_vm_tls_key, NULL) != 0)
fatal_error("pthread_key_create() failed",0);
}
void register_vm_with_thread(factor_vm *vm)
{
pthread_setspecific(current_vm_tls_key,vm);
}
factor_vm *current_vm()
{
factor_vm *vm = (factor_vm*)pthread_getspecific(current_vm_tls_key);
assert(vm != NULL);
return vm;
}
static void *null_dll;
u64 system_micros()
{
struct timeval t;
gettimeofday(&t,NULL);
return (u64)t.tv_sec * 1000000 + t.tv_usec;
}
void sleep_nanos(u64 nsec)
{
timespec ts;
timespec ts_rem;
int ret;
ts.tv_sec = nsec / 1000000000;
ts.tv_nsec = nsec % 1000000000;
ret = nanosleep(&ts,&ts_rem);
while(ret == -1 && errno == EINTR)
{
memcpy(&ts, &ts_rem, sizeof(ts));
ret = nanosleep(&ts, &ts_rem);
}
if(ret == -1)
fatal_error("nanosleep failed", 0);
}
void factor_vm::init_ffi()
{
/* NULL_DLL is "libfactor.dylib" for OS X and NULL for generic unix */
null_dll = dlopen(NULL_DLL,RTLD_LAZY);
}
void factor_vm::ffi_dlopen(dll *dll)
{
dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);
}
void *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)
{
void *handle = (dll == NULL ? null_dll : dll->handle);
return dlsym(handle,symbol);
}
void factor_vm::ffi_dlclose(dll *dll)
{
if(dlclose(dll->handle))
general_error(ERROR_FFI,false_object,false_object);
dll->handle = NULL;
}
void factor_vm::primitive_existsp()
{
struct stat sb;
char *path = (char *)(untag_check<byte_array>(ctx->pop()) + 1);
ctx->push(tag_boolean(stat(path,&sb) >= 0));
}
void factor_vm::move_file(const vm_char *path1, const vm_char *path2)
{
int ret = 0;
do {
ret = rename((path1),(path2));
} while(ret < 0 && errno == EINTR);
if(ret < 0)
general_error(ERROR_IO,tag_fixnum(errno),false_object);
}
segment::segment(cell size_, bool executable_p)
{
size = size_;
int pagesize = getpagesize();
int prot;
if(executable_p)
prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
else
prot = (PROT_READ | PROT_WRITE);
char *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);
if(array == (char*)-1) out_of_memory();
if(mprotect(array,pagesize,PROT_NONE) == -1)
fatal_error("Cannot protect low guard page",(cell)array);
if(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)
fatal_error("Cannot protect high guard page",(cell)array);
start = (cell)(array + pagesize);
end = start + size;
}
segment::~segment()
{
int pagesize = getpagesize();
int retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);
if(retval)
fatal_error("Segment deallocation failed",0);
}
void factor_vm::dispatch_signal(void *uap, void (handler)())
{
UAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));
UAP_PROGRAM_COUNTER(uap) = (cell)handler;
}
void memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
factor_vm *vm = current_vm();
vm->signal_fault_addr = (cell)siginfo->si_addr;
vm->dispatch_signal(uap,factor::memory_signal_handler_impl);
}
void misc_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
factor_vm *vm = current_vm();
vm->signal_number = signal;
vm->dispatch_signal(uap,factor::misc_signal_handler_impl);
}
void fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
factor_vm *vm = current_vm();
vm->signal_number = signal;
vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
uap_clear_fpu_status(uap);
vm->dispatch_signal(uap,
(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
? factor::misc_signal_handler_impl
: factor::fp_signal_handler_impl);
}
static void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)
{
int ret;
do
{
ret = sigaction(signum, act, oldact);
}
while(ret == -1 && errno == EINTR);
if(ret == -1)
fatal_error("sigaction failed", 0);
}
void unix_init_signals()
{
struct sigaction memory_sigaction;
struct sigaction misc_sigaction;
struct sigaction fpe_sigaction;
struct sigaction ignore_sigaction;
memset(&memory_sigaction,0,sizeof(struct sigaction));
sigemptyset(&memory_sigaction.sa_mask);
memory_sigaction.sa_sigaction = memory_signal_handler;
memory_sigaction.sa_flags = SA_SIGINFO;
sigaction_safe(SIGBUS,&memory_sigaction,NULL);
sigaction_safe(SIGSEGV,&memory_sigaction,NULL);
memset(&fpe_sigaction,0,sizeof(struct sigaction));
sigemptyset(&fpe_sigaction.sa_mask);
fpe_sigaction.sa_sigaction = fpe_signal_handler;
fpe_sigaction.sa_flags = SA_SIGINFO;
sigaction_safe(SIGFPE,&fpe_sigaction,NULL);
memset(&misc_sigaction,0,sizeof(struct sigaction));
sigemptyset(&misc_sigaction.sa_mask);
misc_sigaction.sa_sigaction = misc_signal_handler;
misc_sigaction.sa_flags = SA_SIGINFO;
sigaction_safe(SIGQUIT,&misc_sigaction,NULL);
sigaction_safe(SIGILL,&misc_sigaction,NULL);
memset(&ignore_sigaction,0,sizeof(struct sigaction));
sigemptyset(&ignore_sigaction.sa_mask);
ignore_sigaction.sa_handler = SIG_IGN;
sigaction_safe(SIGPIPE,&ignore_sigaction,NULL);
}
/* On Unix, shared fds such as stdin cannot be set to non-blocking mode
(http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
so we kludge around this by spawning a thread, which waits on a control pipe
for a signal, upon receiving this signal it reads one block of data from stdin
and writes it to a data pipe. Upon completion, it writes a 4-byte integer to
the size pipe, indicating how much data was written to the data pipe.
The read end of the size pipe can be set to non-blocking. */
extern "C" {
int stdin_read;
int stdin_write;
int control_read;
int control_write;
int size_read;
int size_write;
}
void safe_close(int fd)
{
if(close(fd) < 0)
fatal_error("error closing fd",errno);
}
bool check_write(int fd, void *data, ssize_t size)
{
if(write(fd,data,size) == size)
return true;
else
{
if(errno == EINTR)
return check_write(fd,data,size);
else
return false;
}
}
void safe_write(int fd, void *data, ssize_t size)
{
if(!check_write(fd,data,size))
fatal_error("error writing fd",errno);
}
bool safe_read(int fd, void *data, ssize_t size)
{
ssize_t bytes = read(fd,data,size);
if(bytes < 0)
{
if(errno == EINTR)
return safe_read(fd,data,size);
else
{
fatal_error("error reading fd",errno);
return false;
}
}
else
return (bytes == size);
}
void *stdin_loop(void *arg)
{
unsigned char buf[4096];
bool loop_running = true;
while(loop_running)
{
if(!safe_read(control_read,buf,1))
break;
if(buf[0] != 'X')
fatal_error("stdin_loop: bad data on control fd",buf[0]);
for(;;)
{
ssize_t bytes = read(0,buf,sizeof(buf));
if(bytes < 0)
{
if(errno == EINTR)
continue;
else
{
loop_running = false;
break;
}
}
else if(bytes >= 0)
{
safe_write(size_write,&bytes,sizeof(bytes));
if(!check_write(stdin_write,buf,bytes))
loop_running = false;
break;
}
}
}
safe_close(stdin_write);
safe_close(control_read);
return NULL;
}
void open_console()
{
int filedes[2];
if(pipe(filedes) < 0)
fatal_error("Error opening control pipe",errno);
control_read = filedes[0];
control_write = filedes[1];
if(pipe(filedes) < 0)
fatal_error("Error opening size pipe",errno);
size_read = filedes[0];
size_write = filedes[1];
if(pipe(filedes) < 0)
fatal_error("Error opening stdin pipe",errno);
stdin_read = filedes[0];
stdin_write = filedes[1];
start_thread(stdin_loop,NULL);
}
VM_C_API void wait_for_stdin()
{
if(write(control_write,"X",1) != 1)
{
if(errno == EINTR)
wait_for_stdin();
else
fatal_error("Error writing control fd",errno);
}
}
}
<commit_msg>vm: fix factor_vm::dispatch_signal()<commit_after>#include "master.hpp"
namespace factor
{
THREADHANDLE start_thread(void *(*start_routine)(void *),void *args)
{
pthread_attr_t attr;
pthread_t thread;
if (pthread_attr_init (&attr) != 0)
fatal_error("pthread_attr_init() failed",0);
if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)
fatal_error("pthread_attr_setdetachstate() failed",0);
if (pthread_create (&thread, &attr, start_routine, args) != 0)
fatal_error("pthread_create() failed",0);
pthread_attr_destroy (&attr);
return thread;
}
pthread_key_t current_vm_tls_key = 0;
void init_platform_globals()
{
if (pthread_key_create(¤t_vm_tls_key, NULL) != 0)
fatal_error("pthread_key_create() failed",0);
}
void register_vm_with_thread(factor_vm *vm)
{
pthread_setspecific(current_vm_tls_key,vm);
}
factor_vm *current_vm()
{
factor_vm *vm = (factor_vm*)pthread_getspecific(current_vm_tls_key);
assert(vm != NULL);
return vm;
}
static void *null_dll;
u64 system_micros()
{
struct timeval t;
gettimeofday(&t,NULL);
return (u64)t.tv_sec * 1000000 + t.tv_usec;
}
void sleep_nanos(u64 nsec)
{
timespec ts;
timespec ts_rem;
int ret;
ts.tv_sec = nsec / 1000000000;
ts.tv_nsec = nsec % 1000000000;
ret = nanosleep(&ts,&ts_rem);
while(ret == -1 && errno == EINTR)
{
memcpy(&ts, &ts_rem, sizeof(ts));
ret = nanosleep(&ts, &ts_rem);
}
if(ret == -1)
fatal_error("nanosleep failed", 0);
}
void factor_vm::init_ffi()
{
/* NULL_DLL is "libfactor.dylib" for OS X and NULL for generic Unix */
null_dll = dlopen(NULL_DLL,RTLD_LAZY);
}
void factor_vm::ffi_dlopen(dll *dll)
{
dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);
}
void *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)
{
void *handle = (dll == NULL ? null_dll : dll->handle);
return dlsym(handle,symbol);
}
void factor_vm::ffi_dlclose(dll *dll)
{
if(dlclose(dll->handle))
general_error(ERROR_FFI,false_object,false_object);
dll->handle = NULL;
}
void factor_vm::primitive_existsp()
{
struct stat sb;
char *path = (char *)(untag_check<byte_array>(ctx->pop()) + 1);
ctx->push(tag_boolean(stat(path,&sb) >= 0));
}
void factor_vm::move_file(const vm_char *path1, const vm_char *path2)
{
int ret = 0;
do {
ret = rename((path1),(path2));
} while(ret < 0 && errno == EINTR);
if(ret < 0)
general_error(ERROR_IO,tag_fixnum(errno),false_object);
}
segment::segment(cell size_, bool executable_p)
{
size = size_;
int pagesize = getpagesize();
int prot;
if(executable_p)
prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
else
prot = (PROT_READ | PROT_WRITE);
char *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);
if(array == (char*)-1) out_of_memory();
if(mprotect(array,pagesize,PROT_NONE) == -1)
fatal_error("Cannot protect low guard page",(cell)array);
if(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)
fatal_error("Cannot protect high guard page",(cell)array);
start = (cell)(array + pagesize);
end = start + size;
}
segment::~segment()
{
int pagesize = getpagesize();
int retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);
if(retval)
fatal_error("Segment deallocation failed",0);
}
void factor_vm::dispatch_signal(void *uap, void (handler)())
{
UAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));
UAP_PROGRAM_COUNTER(uap) = (cell)handler;
signal_callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);
}
void memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
factor_vm *vm = current_vm();
vm->signal_fault_addr = (cell)siginfo->si_addr;
vm->dispatch_signal(uap,factor::memory_signal_handler_impl);
}
void misc_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
factor_vm *vm = current_vm();
vm->signal_number = signal;
vm->dispatch_signal(uap,factor::misc_signal_handler_impl);
}
void fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
factor_vm *vm = current_vm();
vm->signal_number = signal;
vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
uap_clear_fpu_status(uap);
vm->dispatch_signal(uap,
(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
? factor::misc_signal_handler_impl
: factor::fp_signal_handler_impl);
}
static void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)
{
int ret;
do
{
ret = sigaction(signum, act, oldact);
}
while(ret == -1 && errno == EINTR);
if(ret == -1)
fatal_error("sigaction failed", 0);
}
void unix_init_signals()
{
struct sigaction memory_sigaction;
struct sigaction misc_sigaction;
struct sigaction fpe_sigaction;
struct sigaction ignore_sigaction;
memset(&memory_sigaction,0,sizeof(struct sigaction));
sigemptyset(&memory_sigaction.sa_mask);
memory_sigaction.sa_sigaction = memory_signal_handler;
memory_sigaction.sa_flags = SA_SIGINFO;
sigaction_safe(SIGBUS,&memory_sigaction,NULL);
sigaction_safe(SIGSEGV,&memory_sigaction,NULL);
memset(&fpe_sigaction,0,sizeof(struct sigaction));
sigemptyset(&fpe_sigaction.sa_mask);
fpe_sigaction.sa_sigaction = fpe_signal_handler;
fpe_sigaction.sa_flags = SA_SIGINFO;
sigaction_safe(SIGFPE,&fpe_sigaction,NULL);
memset(&misc_sigaction,0,sizeof(struct sigaction));
sigemptyset(&misc_sigaction.sa_mask);
misc_sigaction.sa_sigaction = misc_signal_handler;
misc_sigaction.sa_flags = SA_SIGINFO;
sigaction_safe(SIGQUIT,&misc_sigaction,NULL);
sigaction_safe(SIGILL,&misc_sigaction,NULL);
memset(&ignore_sigaction,0,sizeof(struct sigaction));
sigemptyset(&ignore_sigaction.sa_mask);
ignore_sigaction.sa_handler = SIG_IGN;
sigaction_safe(SIGPIPE,&ignore_sigaction,NULL);
}
/* On Unix, shared fds such as stdin cannot be set to non-blocking mode
(http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
so we kludge around this by spawning a thread, which waits on a control pipe
for a signal, upon receiving this signal it reads one block of data from stdin
and writes it to a data pipe. Upon completion, it writes a 4-byte integer to
the size pipe, indicating how much data was written to the data pipe.
The read end of the size pipe can be set to non-blocking. */
extern "C" {
int stdin_read;
int stdin_write;
int control_read;
int control_write;
int size_read;
int size_write;
}
void safe_close(int fd)
{
if(close(fd) < 0)
fatal_error("error closing fd",errno);
}
bool check_write(int fd, void *data, ssize_t size)
{
if(write(fd,data,size) == size)
return true;
else
{
if(errno == EINTR)
return check_write(fd,data,size);
else
return false;
}
}
void safe_write(int fd, void *data, ssize_t size)
{
if(!check_write(fd,data,size))
fatal_error("error writing fd",errno);
}
bool safe_read(int fd, void *data, ssize_t size)
{
ssize_t bytes = read(fd,data,size);
if(bytes < 0)
{
if(errno == EINTR)
return safe_read(fd,data,size);
else
{
fatal_error("error reading fd",errno);
return false;
}
}
else
return (bytes == size);
}
void *stdin_loop(void *arg)
{
unsigned char buf[4096];
bool loop_running = true;
while(loop_running)
{
if(!safe_read(control_read,buf,1))
break;
if(buf[0] != 'X')
fatal_error("stdin_loop: bad data on control fd",buf[0]);
for(;;)
{
ssize_t bytes = read(0,buf,sizeof(buf));
if(bytes < 0)
{
if(errno == EINTR)
continue;
else
{
loop_running = false;
break;
}
}
else if(bytes >= 0)
{
safe_write(size_write,&bytes,sizeof(bytes));
if(!check_write(stdin_write,buf,bytes))
loop_running = false;
break;
}
}
}
safe_close(stdin_write);
safe_close(control_read);
return NULL;
}
void open_console()
{
int filedes[2];
if(pipe(filedes) < 0)
fatal_error("Error opening control pipe",errno);
control_read = filedes[0];
control_write = filedes[1];
if(pipe(filedes) < 0)
fatal_error("Error opening size pipe",errno);
size_read = filedes[0];
size_write = filedes[1];
if(pipe(filedes) < 0)
fatal_error("Error opening stdin pipe",errno);
stdin_read = filedes[0];
stdin_write = filedes[1];
start_thread(stdin_loop,NULL);
}
VM_C_API void wait_for_stdin()
{
if(write(control_write,"X",1) != 1)
{
if(errno == EINTR)
wait_for_stdin();
else
fatal_error("Error writing control fd",errno);
}
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/msgbox.hxx>
#include <svl/solar.hrc>
#include <vcl/fltcall.hxx>
#include <vcl/FilterConfigItem.hxx>
//============================ PGMWriter ==================================
class PGMWriter {
private:
SvStream& m_rOStm; // the output PGM file
sal_uInt16 mpOStmOldModus;
bool mbStatus;
sal_uInt32 mnMode;
BitmapReadAccess* mpAcc;
sal_uLong mnWidth, mnHeight; // image size in pixeln
bool ImplWriteHeader();
void ImplWriteBody();
void ImplWriteNumber( sal_Int32 );
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;
public:
PGMWriter(SvStream &rStream);
~PGMWriter();
bool WritePGM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};
//=================== Methoden von PGMWriter ==============================
PGMWriter::PGMWriter(SvStream &rStream)
: m_rOStm(rStream)
, mbStatus(true)
, mnMode(0)
, mpAcc(NULL)
, mnWidth(0)
, mnHeight(0)
{
}
PGMWriter::~PGMWriter()
{
}
bool PGMWriter::WritePGM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem )
{
if ( pFilterConfigItem )
{
mnMode = pFilterConfigItem->ReadInt32( "FileFormat", 0 );
xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
if ( xStatusIndicator.is() )
{
OUString aMsg;
xStatusIndicator->start( aMsg, 100 );
}
}
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
Bitmap aBmp = aBmpEx.GetBitmap();
aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );
mpOStmOldModus = m_rOStm.GetNumberFormatInt();
m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
mpAcc = aBmp.AcquireReadAccess();
if( mpAcc )
{
if ( ImplWriteHeader() )
{
ImplWriteBody();
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = false;
m_rOStm.SetNumberFormatInt( mpOStmOldModus );
if ( xStatusIndicator.is() )
xStatusIndicator->end();
return mbStatus;
}
bool PGMWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnWidth && mnHeight )
{
if ( mnMode == 0 )
m_rOStm.WriteCharPtr( "P5\x0a" );
else
m_rOStm.WriteCharPtr( "P2\x0a" );
ImplWriteNumber( mnWidth );
m_rOStm.WriteUChar( (sal_uInt8)32 );
ImplWriteNumber( mnHeight );
m_rOStm.WriteUChar( (sal_uInt8)32 );
ImplWriteNumber( 255 ); // max. gray value
m_rOStm.WriteUChar( (sal_uInt8)10 );
}
else
mbStatus = false;
return mbStatus;
}
void PGMWriter::ImplWriteBody()
{
if ( mnMode == 0 )
{
for ( sal_uLong y = 0; y < mnHeight; y++ )
{
for ( sal_uLong x = 0; x < mnWidth; x++ )
{
m_rOStm.WriteUChar( mpAcc->GetPixelIndex( y, x ) );
}
}
}
else
{
for ( sal_uLong y = 0; y < mnHeight; y++ )
{
int nCount = 70;
for ( sal_uLong x = 0; x < mnWidth; x++ )
{
sal_uInt8 nDat, nNumb;
if ( nCount < 0 )
{
nCount = 69;
m_rOStm.WriteUChar( (sal_uInt8)10 );
}
nDat = mpAcc->GetPixelIndex( y, x );
nNumb = nDat / 100;
if ( nNumb )
{
m_rOStm.WriteUChar( (sal_uInt8)( nNumb + '0' ) );
nDat -= ( nNumb * 100 );
nNumb = nDat / 10;
m_rOStm.WriteUChar( (sal_uInt8)( nNumb + '0' ) );
nDat -= ( nNumb * 10 );
m_rOStm.WriteUChar( (sal_uInt8)( nDat + '0' ) );
nCount -= 4;
}
else
{
nNumb = nDat / 10;
if ( nNumb )
{
m_rOStm.WriteUChar( (sal_uInt8)( nNumb + '0' ) );
nDat -= ( nNumb * 10 );
m_rOStm.WriteUChar( (sal_uInt8)( nDat + '0' ) );
nCount -= 3;
}
else
{
m_rOStm.WriteUChar( (sal_uInt8)( nDat + '0' ) );
nCount -= 2;
}
}
m_rOStm.WriteUChar( (sal_uInt8)' ' );
}
m_rOStm.WriteUChar( (sal_uInt8)10 );
}
}
}
// write a decimal number in ascii format into the stream
void PGMWriter::ImplWriteNumber(sal_Int32 nNumber)
{
const OString aNum(OString::number(nNumber));
m_rOStm.WriteCharPtr( aNum.getStr() );
}
// - exported function -
// this needs to be kept in sync with
// ImpFilterLibCacheEntry::GetImportFunction() from
// vcl/source/filter/graphicfilter.cxx
#if defined(DISABLE_DYNLOADING)
#define GraphicExport epgGraphicExport
#endif
extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL
GraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem )
{
PGMWriter aPGMWriter(rStream);
return aPGMWriter.WritePGM( rGraphic, pFilterConfigItem );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738630 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/msgbox.hxx>
#include <svl/solar.hrc>
#include <vcl/fltcall.hxx>
#include <vcl/FilterConfigItem.hxx>
//============================ PGMWriter ==================================
class PGMWriter {
private:
SvStream& m_rOStm; // the output PGM file
sal_uInt16 mpOStmOldModus;
bool mbStatus;
sal_uInt32 mnMode;
BitmapReadAccess* mpAcc;
sal_uLong mnWidth, mnHeight; // image size in pixeln
bool ImplWriteHeader();
void ImplWriteBody();
void ImplWriteNumber( sal_Int32 );
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;
public:
PGMWriter(SvStream &rStream);
~PGMWriter();
bool WritePGM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};
//=================== Methoden von PGMWriter ==============================
PGMWriter::PGMWriter(SvStream &rStream)
: m_rOStm(rStream)
, mpOStmOldModus(0)
, mbStatus(true)
, mnMode(0)
, mpAcc(NULL)
, mnWidth(0)
, mnHeight(0)
{
}
PGMWriter::~PGMWriter()
{
}
bool PGMWriter::WritePGM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem )
{
if ( pFilterConfigItem )
{
mnMode = pFilterConfigItem->ReadInt32( "FileFormat", 0 );
xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
if ( xStatusIndicator.is() )
{
OUString aMsg;
xStatusIndicator->start( aMsg, 100 );
}
}
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
Bitmap aBmp = aBmpEx.GetBitmap();
aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );
mpOStmOldModus = m_rOStm.GetNumberFormatInt();
m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
mpAcc = aBmp.AcquireReadAccess();
if( mpAcc )
{
if ( ImplWriteHeader() )
{
ImplWriteBody();
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = false;
m_rOStm.SetNumberFormatInt( mpOStmOldModus );
if ( xStatusIndicator.is() )
xStatusIndicator->end();
return mbStatus;
}
bool PGMWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnWidth && mnHeight )
{
if ( mnMode == 0 )
m_rOStm.WriteCharPtr( "P5\x0a" );
else
m_rOStm.WriteCharPtr( "P2\x0a" );
ImplWriteNumber( mnWidth );
m_rOStm.WriteUChar( (sal_uInt8)32 );
ImplWriteNumber( mnHeight );
m_rOStm.WriteUChar( (sal_uInt8)32 );
ImplWriteNumber( 255 ); // max. gray value
m_rOStm.WriteUChar( (sal_uInt8)10 );
}
else
mbStatus = false;
return mbStatus;
}
void PGMWriter::ImplWriteBody()
{
if ( mnMode == 0 )
{
for ( sal_uLong y = 0; y < mnHeight; y++ )
{
for ( sal_uLong x = 0; x < mnWidth; x++ )
{
m_rOStm.WriteUChar( mpAcc->GetPixelIndex( y, x ) );
}
}
}
else
{
for ( sal_uLong y = 0; y < mnHeight; y++ )
{
int nCount = 70;
for ( sal_uLong x = 0; x < mnWidth; x++ )
{
sal_uInt8 nDat, nNumb;
if ( nCount < 0 )
{
nCount = 69;
m_rOStm.WriteUChar( (sal_uInt8)10 );
}
nDat = mpAcc->GetPixelIndex( y, x );
nNumb = nDat / 100;
if ( nNumb )
{
m_rOStm.WriteUChar( (sal_uInt8)( nNumb + '0' ) );
nDat -= ( nNumb * 100 );
nNumb = nDat / 10;
m_rOStm.WriteUChar( (sal_uInt8)( nNumb + '0' ) );
nDat -= ( nNumb * 10 );
m_rOStm.WriteUChar( (sal_uInt8)( nDat + '0' ) );
nCount -= 4;
}
else
{
nNumb = nDat / 10;
if ( nNumb )
{
m_rOStm.WriteUChar( (sal_uInt8)( nNumb + '0' ) );
nDat -= ( nNumb * 10 );
m_rOStm.WriteUChar( (sal_uInt8)( nDat + '0' ) );
nCount -= 3;
}
else
{
m_rOStm.WriteUChar( (sal_uInt8)( nDat + '0' ) );
nCount -= 2;
}
}
m_rOStm.WriteUChar( (sal_uInt8)' ' );
}
m_rOStm.WriteUChar( (sal_uInt8)10 );
}
}
}
// write a decimal number in ascii format into the stream
void PGMWriter::ImplWriteNumber(sal_Int32 nNumber)
{
const OString aNum(OString::number(nNumber));
m_rOStm.WriteCharPtr( aNum.getStr() );
}
// - exported function -
// this needs to be kept in sync with
// ImpFilterLibCacheEntry::GetImportFunction() from
// vcl/source/filter/graphicfilter.cxx
#if defined(DISABLE_DYNLOADING)
#define GraphicExport epgGraphicExport
#endif
extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL
GraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem )
{
PGMWriter aPGMWriter(rStream);
return aPGMWriter.WritePGM( rGraphic, pFilterConfigItem );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
class FilterConfigItem;
//============================ PCXReader ==================================
class PCXReader {
private:
SvStream& m_rPCX; // the PCX file to read
Bitmap aBmp;
BitmapWriteAccess* pAcc;
sal_uInt8 nVersion; // PCX-Version
sal_uInt8 nEncoding; // compression type
sal_uLong nBitsPerPlanePix; // bits per plane per pixel
sal_uLong nPlanes; // no of planes
sal_uLong nBytesPerPlaneLin; // bytes per plane line
sal_uInt16 nPaletteInfo;
sal_uLong nWidth, nHeight; // dimension in pixel
sal_uInt16 nResX, nResY; // resolution in pixel per inch oder 0,0
sal_uInt16 nDestBitsPerPixel; // bits per pixel in destination bitmap 1,4,8 or 24
sal_uInt8* pPalette;
sal_Bool nStatus; // from now on do not read status from stream ( SJ )
sal_Bool Callback( sal_uInt16 nPercent );
void ImplReadBody();
void ImplReadPalette( sal_uLong nCol );
void ImplReadHeader();
public:
PCXReader(SvStream &rStream);
~PCXReader();
sal_Bool ReadPCX(Graphic & rGraphic );
// Reads a PCX file from the stream and fills the GDIMetaFile
};
//=================== methods of PCXReader ==============================
PCXReader::PCXReader(SvStream &rStream)
: m_rPCX(rStream)
, pAcc(NULL)
{
pPalette = new sal_uInt8[ 768 ];
}
PCXReader::~PCXReader()
{
delete[] pPalette;
}
sal_Bool PCXReader::Callback( sal_uInt16 /*nPercent*/ )
{
return sal_False;
}
sal_Bool PCXReader::ReadPCX(Graphic & rGraphic)
{
if ( m_rPCX.GetError() )
return sal_False;
sal_uLong* pDummy = new sal_uLong; delete pDummy; // to achive that under OS/2
// the right (Tools-) new is used
// otherwise there are only Vector-news
// in this DLL
m_rPCX.SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
// read header:
nStatus = sal_True;
ImplReadHeader();
// Write BMP header and conditionally (maybe invalid for now) color palette:
if ( nStatus )
{
aBmp = Bitmap( Size( nWidth, nHeight ), nDestBitsPerPixel );
if ( ( pAcc = aBmp.AcquireWriteAccess() ) == 0 )
return sal_False;
if ( nDestBitsPerPixel <= 8 )
{
sal_uInt16 nColors = 1 << nDestBitsPerPixel;
sal_uInt8* pPal = pPalette;
pAcc->SetPaletteEntryCount( nColors );
for ( sal_uInt16 i = 0; i < nColors; i++, pPal += 3 )
{
pAcc->SetPaletteColor( i, BitmapColor ( pPal[ 0 ], pPal[ 1 ], pPal[ 2 ] ) );
}
}
// read bitmap data
ImplReadBody();
// If an extended color palette exists at the end of the file, then read it and
// and write again in palette:
if ( nDestBitsPerPixel == 8 && nStatus )
{
sal_uInt8* pPal = pPalette;
m_rPCX.SeekRel(1);
ImplReadPalette(256);
pAcc->SetPaletteEntryCount( 256 );
for ( sal_uInt16 i = 0; i < 256; i++, pPal += 3 )
{
pAcc->SetPaletteColor( i, BitmapColor ( pPal[ 0 ], pPal[ 1 ], pPal[ 2 ] ) );
}
}
/*
// set resolution:
if (nResX!=0 && nResY!=0) {
MapMode aMapMode(MAP_INCH,Point(0,0),Fraction(1,nResX),Fraction(1,nResY));
rBitmap.SetPrefMapMode(aMapMode);
rBitmap.SetPrefSize(Size(nWidth,nHeight));
}
*/ if ( nStatus && pAcc )
{
aBmp.ReleaseAccess( pAcc ), pAcc = NULL;
rGraphic = aBmp;
return sal_True;
}
}
return sal_False;
}
void PCXReader::ImplReadHeader()
{
sal_uInt8 nbyte;
sal_uInt16 nushort;
sal_uInt16 nMinX,nMinY,nMaxX,nMaxY;
m_rPCX.ReadUChar( nbyte ).ReadUChar( nVersion ).ReadUChar( nEncoding );
if ( nbyte!=0x0a || (nVersion != 0 && nVersion != 2 && nVersion != 3 && nVersion != 5) || nEncoding > 1 )
{
nStatus = sal_False;
return;
}
m_rPCX.ReadUChar( nbyte ); nBitsPerPlanePix = (sal_uLong)nbyte;
m_rPCX.ReadUInt16( nMinX ).ReadUInt16( nMinY ).ReadUInt16( nMaxX ).ReadUInt16( nMaxY );
if ((nMinX > nMaxX) || (nMinY > nMaxY))
{
nStatus = sal_False;
return;
}
nWidth = nMaxX-nMinX+1;
nHeight = nMaxY-nMinY+1;
m_rPCX.ReadUInt16( nResX );
m_rPCX.ReadUInt16( nResY );
if ( nResX >= nWidth || nResY >= nHeight || ( nResX != nResY ) )
nResX = nResY = 0;
ImplReadPalette( 16 );
m_rPCX.SeekRel( 1 );
m_rPCX.ReadUChar( nbyte ); nPlanes = (sal_uLong)nbyte;
m_rPCX.ReadUInt16( nushort ); nBytesPerPlaneLin = (sal_uLong)nushort;
m_rPCX.ReadUInt16( nPaletteInfo );
m_rPCX.SeekRel( 58 );
nDestBitsPerPixel = (sal_uInt16)( nBitsPerPlanePix * nPlanes );
if (nDestBitsPerPixel == 2 || nDestBitsPerPixel == 3) nDestBitsPerPixel = 4;
if ( ( nDestBitsPerPixel != 1 && nDestBitsPerPixel != 4 && nDestBitsPerPixel != 8 && nDestBitsPerPixel != 24 )
|| nPlanes > 4 || nBytesPerPlaneLin < ( ( nWidth * nBitsPerPlanePix+7 ) >> 3 ) )
{
nStatus = sal_False;
return;
}
// If the bitmap has only 2 colors, the palatte is most often invalid and it is always(?)
// a black and white image:
if ( nPlanes == 1 && nBitsPerPlanePix == 1 )
{
pPalette[ 0 ] = pPalette[ 1 ] = pPalette[ 2 ] = 0x00;
pPalette[ 3 ] = pPalette[ 4 ] = pPalette[ 5 ] = 0xff;
}
}
void PCXReader::ImplReadBody()
{
sal_uInt8 *pPlane[ 4 ], * pDest, * pSource1, * pSource2, * pSource3, *pSource4;
sal_uLong i, nx, ny, np, nCount, nPercent;
sal_uLong nLastPercent = 0;
sal_uInt8 nDat = 0, nCol = 0;
for( np = 0; np < nPlanes; np++ )
pPlane[ np ] = new sal_uInt8[ nBytesPerPlaneLin ];
nCount = 0;
for ( ny = 0; ny < nHeight; ny++ )
{
if (m_rPCX.GetError() || m_rPCX.IsEof())
{
nStatus = sal_False;
break;
}
nPercent = ny * 60 / nHeight + 10;
if ( ny == 0 || nLastPercent + 4 <= nPercent )
{
nLastPercent = nPercent;
if ( Callback( (sal_uInt16)nPercent ) == sal_True )
break;
}
for ( np = 0; np < nPlanes; np++)
{
if ( nEncoding == 0)
m_rPCX.Read( (void *)pPlane[ np ], nBytesPerPlaneLin );
else
{
pDest = pPlane[ np ];
nx = nBytesPerPlaneLin;
while ( nCount > 0 && nx > 0)
{
*(pDest++) = nDat;
nx--;
nCount--;
}
while ( nx > 0 )
{
m_rPCX.ReadUChar( nDat );
if ( ( nDat & 0xc0 ) == 0xc0 )
{
nCount =( (sal_uLong)nDat ) & 0x003f;
m_rPCX.ReadUChar( nDat );
if ( nCount < nx )
{
nx -= nCount;
while ( nCount > 0)
{
*(pDest++) = nDat;
nCount--;
}
}
else
{
nCount -= nx;
do
{
*(pDest++) = nDat;
nx--;
}
while ( nx > 0 );
break;
}
}
else
{
*(pDest++) = nDat;
nx--;
}
}
}
}
pSource1 = pPlane[ 0 ];
pSource2 = pPlane[ 1 ];
pSource3 = pPlane[ 2 ];
pSource4 = pPlane[ 3 ];
switch ( nBitsPerPlanePix + ( nPlanes << 8 ) )
{
// 2 colors
case 0x101 :
for ( i = 0; i < nWidth; i++ )
{
sal_uLong nShift = ( i & 7 ) ^ 7;
if ( nShift == 0 )
pAcc->SetPixelIndex( ny, i, *(pSource1++) & 1 );
else
pAcc->SetPixelIndex( ny, i, (*pSource1 >> nShift ) & 1 );
}
break;
// 4 colors
case 0x102 :
for ( i = 0; i < nWidth; i++ )
{
switch( i & 3 )
{
case 0 :
nCol = *pSource1 >> 6;
break;
case 1 :
nCol = ( *pSource1 >> 4 ) & 0x03 ;
break;
case 2 :
nCol = ( *pSource1 >> 2 ) & 0x03;
break;
case 3 :
nCol = ( *pSource1++ ) & 0x03;
break;
}
pAcc->SetPixelIndex( ny, i, nCol );
}
break;
// 256 colors
case 0x108 :
for ( i = 0; i < nWidth; i++ )
{
pAcc->SetPixelIndex( ny, i, *pSource1++ );
}
break;
// 8 colors
case 0x301 :
for ( i = 0; i < nWidth; i++ )
{
sal_uLong nShift = ( i & 7 ) ^ 7;
if ( nShift == 0 )
{
nCol = ( *pSource1++ & 1) + ( ( *pSource2++ << 1 ) & 2 ) + ( ( *pSource3++ << 2 ) & 4 );
pAcc->SetPixelIndex( ny, i, nCol );
}
else
{
nCol = sal::static_int_cast< sal_uInt8 >(
( ( *pSource1 >> nShift ) & 1) + ( ( ( *pSource2 >> nShift ) << 1 ) & 2 ) +
( ( ( *pSource3 >> nShift ) << 2 ) & 4 ));
pAcc->SetPixelIndex( ny, i, nCol );
}
}
break;
// 16 colors
case 0x401 :
for ( i = 0; i < nWidth; i++ )
{
sal_uLong nShift = ( i & 7 ) ^ 7;
if ( nShift == 0 )
{
nCol = ( *pSource1++ & 1) + ( ( *pSource2++ << 1 ) & 2 ) + ( ( *pSource3++ << 2 ) & 4 ) +
( ( *pSource4++ << 3 ) & 8 );
pAcc->SetPixelIndex( ny, i, nCol );
}
else
{
nCol = sal::static_int_cast< sal_uInt8 >(
( ( *pSource1 >> nShift ) & 1) + ( ( ( *pSource2 >> nShift ) << 1 ) & 2 ) +
( ( ( *pSource3 >> nShift ) << 2 ) & 4 ) + ( ( ( *pSource4 >> nShift ) << 3 ) & 8 ));
pAcc->SetPixelIndex( ny, i, nCol );
}
}
break;
// 16m colors
case 0x308 :
for ( i = 0; i < nWidth; i++ )
{
pAcc->SetPixel( ny, i, Color( *pSource1++, *pSource2++, *pSource3++ ) );
}
break;
default :
nStatus = sal_False;
break;
}
}
for ( np = 0; np < nPlanes; np++ )
delete[] pPlane[ np ];
}
void PCXReader::ImplReadPalette( sal_uLong nCol )
{
sal_uInt8 r, g, b;
sal_uInt8* pPtr = pPalette;
for ( sal_uLong i = 0; i < nCol; i++ )
{
m_rPCX.ReadUChar( r ).ReadUChar( g ).ReadUChar( b );
*pPtr++ = r;
*pPtr++ = g;
*pPtr++ = b;
}
}
//================== GraphicImport - the exported function ================
// this needs to be kept in sync with
// ImpFilterLibCacheEntry::GetImportFunction() from
// vcl/source/filter/graphicfilter.cxx
#if defined(DISABLE_DYNLOADING)
#define GraphicImport ipxGraphicImport
#endif
extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL
GraphicImport( SvStream & rStream, Graphic & rGraphic, FilterConfigItem* )
{
PCXReader aPCXReader(rStream);
sal_Bool nRetValue = aPCXReader.ReadPCX(rGraphic);
if ( nRetValue == sal_False )
rStream.SetError( SVSTREAM_FILEFORMAT_ERROR );
return nRetValue;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738637 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
class FilterConfigItem;
//============================ PCXReader ==================================
class PCXReader {
private:
SvStream& m_rPCX; // the PCX file to read
Bitmap aBmp;
BitmapWriteAccess* pAcc;
sal_uInt8 nVersion; // PCX-Version
sal_uInt8 nEncoding; // compression type
sal_uLong nBitsPerPlanePix; // bits per plane per pixel
sal_uLong nPlanes; // no of planes
sal_uLong nBytesPerPlaneLin; // bytes per plane line
sal_uInt16 nPaletteInfo;
sal_uLong nWidth, nHeight; // dimension in pixel
sal_uInt16 nResX, nResY; // resolution in pixel per inch oder 0,0
sal_uInt16 nDestBitsPerPixel; // bits per pixel in destination bitmap 1,4,8 or 24
sal_uInt8* pPalette;
sal_Bool nStatus; // from now on do not read status from stream ( SJ )
sal_Bool Callback( sal_uInt16 nPercent );
void ImplReadBody();
void ImplReadPalette( sal_uLong nCol );
void ImplReadHeader();
public:
PCXReader(SvStream &rStream);
~PCXReader();
sal_Bool ReadPCX(Graphic & rGraphic );
// Reads a PCX file from the stream and fills the GDIMetaFile
};
//=================== methods of PCXReader ==============================
PCXReader::PCXReader(SvStream &rStream)
: m_rPCX(rStream)
, pAcc(NULL)
, nVersion(0)
, nEncoding(0)
, nBitsPerPlanePix(0)
, nPlanes(0)
, nBytesPerPlaneLin(0)
, nPaletteInfo(0)
, nWidth(0)
, nHeight(0)
, nResX(0)
, nResY(0)
, nDestBitsPerPixel(0)
, nStatus(false)
{
pPalette = new sal_uInt8[ 768 ];
}
PCXReader::~PCXReader()
{
delete[] pPalette;
}
sal_Bool PCXReader::Callback( sal_uInt16 /*nPercent*/ )
{
return sal_False;
}
sal_Bool PCXReader::ReadPCX(Graphic & rGraphic)
{
if ( m_rPCX.GetError() )
return sal_False;
sal_uLong* pDummy = new sal_uLong; delete pDummy; // to achive that under OS/2
// the right (Tools-) new is used
// otherwise there are only Vector-news
// in this DLL
m_rPCX.SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
// read header:
nStatus = sal_True;
ImplReadHeader();
// Write BMP header and conditionally (maybe invalid for now) color palette:
if ( nStatus )
{
aBmp = Bitmap( Size( nWidth, nHeight ), nDestBitsPerPixel );
if ( ( pAcc = aBmp.AcquireWriteAccess() ) == 0 )
return sal_False;
if ( nDestBitsPerPixel <= 8 )
{
sal_uInt16 nColors = 1 << nDestBitsPerPixel;
sal_uInt8* pPal = pPalette;
pAcc->SetPaletteEntryCount( nColors );
for ( sal_uInt16 i = 0; i < nColors; i++, pPal += 3 )
{
pAcc->SetPaletteColor( i, BitmapColor ( pPal[ 0 ], pPal[ 1 ], pPal[ 2 ] ) );
}
}
// read bitmap data
ImplReadBody();
// If an extended color palette exists at the end of the file, then read it and
// and write again in palette:
if ( nDestBitsPerPixel == 8 && nStatus )
{
sal_uInt8* pPal = pPalette;
m_rPCX.SeekRel(1);
ImplReadPalette(256);
pAcc->SetPaletteEntryCount( 256 );
for ( sal_uInt16 i = 0; i < 256; i++, pPal += 3 )
{
pAcc->SetPaletteColor( i, BitmapColor ( pPal[ 0 ], pPal[ 1 ], pPal[ 2 ] ) );
}
}
/*
// set resolution:
if (nResX!=0 && nResY!=0) {
MapMode aMapMode(MAP_INCH,Point(0,0),Fraction(1,nResX),Fraction(1,nResY));
rBitmap.SetPrefMapMode(aMapMode);
rBitmap.SetPrefSize(Size(nWidth,nHeight));
}
*/ if ( nStatus && pAcc )
{
aBmp.ReleaseAccess( pAcc ), pAcc = NULL;
rGraphic = aBmp;
return sal_True;
}
}
return sal_False;
}
void PCXReader::ImplReadHeader()
{
sal_uInt8 nbyte;
sal_uInt16 nushort;
sal_uInt16 nMinX,nMinY,nMaxX,nMaxY;
m_rPCX.ReadUChar( nbyte ).ReadUChar( nVersion ).ReadUChar( nEncoding );
if ( nbyte!=0x0a || (nVersion != 0 && nVersion != 2 && nVersion != 3 && nVersion != 5) || nEncoding > 1 )
{
nStatus = sal_False;
return;
}
m_rPCX.ReadUChar( nbyte ); nBitsPerPlanePix = (sal_uLong)nbyte;
m_rPCX.ReadUInt16( nMinX ).ReadUInt16( nMinY ).ReadUInt16( nMaxX ).ReadUInt16( nMaxY );
if ((nMinX > nMaxX) || (nMinY > nMaxY))
{
nStatus = sal_False;
return;
}
nWidth = nMaxX-nMinX+1;
nHeight = nMaxY-nMinY+1;
m_rPCX.ReadUInt16( nResX );
m_rPCX.ReadUInt16( nResY );
if ( nResX >= nWidth || nResY >= nHeight || ( nResX != nResY ) )
nResX = nResY = 0;
ImplReadPalette( 16 );
m_rPCX.SeekRel( 1 );
m_rPCX.ReadUChar( nbyte ); nPlanes = (sal_uLong)nbyte;
m_rPCX.ReadUInt16( nushort ); nBytesPerPlaneLin = (sal_uLong)nushort;
m_rPCX.ReadUInt16( nPaletteInfo );
m_rPCX.SeekRel( 58 );
nDestBitsPerPixel = (sal_uInt16)( nBitsPerPlanePix * nPlanes );
if (nDestBitsPerPixel == 2 || nDestBitsPerPixel == 3) nDestBitsPerPixel = 4;
if ( ( nDestBitsPerPixel != 1 && nDestBitsPerPixel != 4 && nDestBitsPerPixel != 8 && nDestBitsPerPixel != 24 )
|| nPlanes > 4 || nBytesPerPlaneLin < ( ( nWidth * nBitsPerPlanePix+7 ) >> 3 ) )
{
nStatus = sal_False;
return;
}
// If the bitmap has only 2 colors, the palatte is most often invalid and it is always(?)
// a black and white image:
if ( nPlanes == 1 && nBitsPerPlanePix == 1 )
{
pPalette[ 0 ] = pPalette[ 1 ] = pPalette[ 2 ] = 0x00;
pPalette[ 3 ] = pPalette[ 4 ] = pPalette[ 5 ] = 0xff;
}
}
void PCXReader::ImplReadBody()
{
sal_uInt8 *pPlane[ 4 ], * pDest, * pSource1, * pSource2, * pSource3, *pSource4;
sal_uLong i, nx, ny, np, nCount, nPercent;
sal_uLong nLastPercent = 0;
sal_uInt8 nDat = 0, nCol = 0;
for( np = 0; np < nPlanes; np++ )
pPlane[ np ] = new sal_uInt8[ nBytesPerPlaneLin ];
nCount = 0;
for ( ny = 0; ny < nHeight; ny++ )
{
if (m_rPCX.GetError() || m_rPCX.IsEof())
{
nStatus = sal_False;
break;
}
nPercent = ny * 60 / nHeight + 10;
if ( ny == 0 || nLastPercent + 4 <= nPercent )
{
nLastPercent = nPercent;
if ( Callback( (sal_uInt16)nPercent ) == sal_True )
break;
}
for ( np = 0; np < nPlanes; np++)
{
if ( nEncoding == 0)
m_rPCX.Read( (void *)pPlane[ np ], nBytesPerPlaneLin );
else
{
pDest = pPlane[ np ];
nx = nBytesPerPlaneLin;
while ( nCount > 0 && nx > 0)
{
*(pDest++) = nDat;
nx--;
nCount--;
}
while ( nx > 0 )
{
m_rPCX.ReadUChar( nDat );
if ( ( nDat & 0xc0 ) == 0xc0 )
{
nCount =( (sal_uLong)nDat ) & 0x003f;
m_rPCX.ReadUChar( nDat );
if ( nCount < nx )
{
nx -= nCount;
while ( nCount > 0)
{
*(pDest++) = nDat;
nCount--;
}
}
else
{
nCount -= nx;
do
{
*(pDest++) = nDat;
nx--;
}
while ( nx > 0 );
break;
}
}
else
{
*(pDest++) = nDat;
nx--;
}
}
}
}
pSource1 = pPlane[ 0 ];
pSource2 = pPlane[ 1 ];
pSource3 = pPlane[ 2 ];
pSource4 = pPlane[ 3 ];
switch ( nBitsPerPlanePix + ( nPlanes << 8 ) )
{
// 2 colors
case 0x101 :
for ( i = 0; i < nWidth; i++ )
{
sal_uLong nShift = ( i & 7 ) ^ 7;
if ( nShift == 0 )
pAcc->SetPixelIndex( ny, i, *(pSource1++) & 1 );
else
pAcc->SetPixelIndex( ny, i, (*pSource1 >> nShift ) & 1 );
}
break;
// 4 colors
case 0x102 :
for ( i = 0; i < nWidth; i++ )
{
switch( i & 3 )
{
case 0 :
nCol = *pSource1 >> 6;
break;
case 1 :
nCol = ( *pSource1 >> 4 ) & 0x03 ;
break;
case 2 :
nCol = ( *pSource1 >> 2 ) & 0x03;
break;
case 3 :
nCol = ( *pSource1++ ) & 0x03;
break;
}
pAcc->SetPixelIndex( ny, i, nCol );
}
break;
// 256 colors
case 0x108 :
for ( i = 0; i < nWidth; i++ )
{
pAcc->SetPixelIndex( ny, i, *pSource1++ );
}
break;
// 8 colors
case 0x301 :
for ( i = 0; i < nWidth; i++ )
{
sal_uLong nShift = ( i & 7 ) ^ 7;
if ( nShift == 0 )
{
nCol = ( *pSource1++ & 1) + ( ( *pSource2++ << 1 ) & 2 ) + ( ( *pSource3++ << 2 ) & 4 );
pAcc->SetPixelIndex( ny, i, nCol );
}
else
{
nCol = sal::static_int_cast< sal_uInt8 >(
( ( *pSource1 >> nShift ) & 1) + ( ( ( *pSource2 >> nShift ) << 1 ) & 2 ) +
( ( ( *pSource3 >> nShift ) << 2 ) & 4 ));
pAcc->SetPixelIndex( ny, i, nCol );
}
}
break;
// 16 colors
case 0x401 :
for ( i = 0; i < nWidth; i++ )
{
sal_uLong nShift = ( i & 7 ) ^ 7;
if ( nShift == 0 )
{
nCol = ( *pSource1++ & 1) + ( ( *pSource2++ << 1 ) & 2 ) + ( ( *pSource3++ << 2 ) & 4 ) +
( ( *pSource4++ << 3 ) & 8 );
pAcc->SetPixelIndex( ny, i, nCol );
}
else
{
nCol = sal::static_int_cast< sal_uInt8 >(
( ( *pSource1 >> nShift ) & 1) + ( ( ( *pSource2 >> nShift ) << 1 ) & 2 ) +
( ( ( *pSource3 >> nShift ) << 2 ) & 4 ) + ( ( ( *pSource4 >> nShift ) << 3 ) & 8 ));
pAcc->SetPixelIndex( ny, i, nCol );
}
}
break;
// 16m colors
case 0x308 :
for ( i = 0; i < nWidth; i++ )
{
pAcc->SetPixel( ny, i, Color( *pSource1++, *pSource2++, *pSource3++ ) );
}
break;
default :
nStatus = sal_False;
break;
}
}
for ( np = 0; np < nPlanes; np++ )
delete[] pPlane[ np ];
}
void PCXReader::ImplReadPalette( sal_uLong nCol )
{
sal_uInt8 r, g, b;
sal_uInt8* pPtr = pPalette;
for ( sal_uLong i = 0; i < nCol; i++ )
{
m_rPCX.ReadUChar( r ).ReadUChar( g ).ReadUChar( b );
*pPtr++ = r;
*pPtr++ = g;
*pPtr++ = b;
}
}
//================== GraphicImport - the exported function ================
// this needs to be kept in sync with
// ImpFilterLibCacheEntry::GetImportFunction() from
// vcl/source/filter/graphicfilter.cxx
#if defined(DISABLE_DYNLOADING)
#define GraphicImport ipxGraphicImport
#endif
extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL
GraphicImport( SvStream & rStream, Graphic & rGraphic, FilterConfigItem* )
{
PCXReader aPCXReader(rStream);
sal_Bool nRetValue = aPCXReader.ReadPCX(rGraphic);
if ( nRetValue == sal_False )
rStream.SetError( SVSTREAM_FILEFORMAT_ERROR );
return nRetValue;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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/metrics/user_metrics.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_service.h"
void UserMetrics::RecordAction(const UserMetricsAction& action,
Profile* profile) {
Record(action.str_, profile);
}
void UserMetrics::RecordComputedAction(const std::string& action,
Profile* profile) {
Record(action.c_str(), profile);
}
void UserMetrics::Record(const char *action, Profile *profile) {
Record(action);
}
void UserMetrics::RecordAction(const UserMetricsAction& action) {
Record(action.str_);
}
void UserMetrics::RecordComputedAction(const std::string& action) {
Record(action.c_str());
}
void UserMetrics::Record(const char *action) {
NotificationService::current()->Notify(NotificationType::USER_ACTION,
NotificationService::AllSources(),
Details<const char*>(&action));
}
<commit_msg>No-op change to trigger another build.<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/metrics/user_metrics.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_service.h"
void UserMetrics::RecordAction(const UserMetricsAction& action,
Profile* profile) {
Record(action.str_, profile);
}
void UserMetrics::RecordComputedAction(const std::string& action,
Profile* profile) {
Record(action.c_str(), profile);
}
void UserMetrics::Record(const char *action, Profile *profile) {
Record(action);
}
void UserMetrics::RecordAction(const UserMetricsAction& action) {
Record(action.str_);
}
void UserMetrics::RecordComputedAction(const std::string& action) {
Record(action.c_str());
}
void UserMetrics::Record(const char *action) {
NotificationService::current()->Notify(NotificationType::USER_ACTION,
NotificationService::AllSources(),
Details<const char*>(&action));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/oom_priority_manager.h"
#include <algorithm>
#include <vector>
#include "base/process.h"
#include "base/process_util.h"
#include "base/string16.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread.h"
#include "base/timer.h"
#include "build/build_config.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/zygote_host_linux.h"
#if !defined(OS_CHROMEOS)
#error This file only meant to be compiled on ChromeOS
#endif
using base::TimeDelta;
using base::TimeTicks;
using base::ProcessHandle;
using base::ProcessMetrics;
namespace browser {
// The default interval in seconds after which to adjust the oom_score_adj
// value.
#define ADJUSTMENT_INTERVAL_SECONDS 10
// The default interval in minutes for considering activation times
// "equal".
#define BUCKET_INTERVAL_MINUTES 10
OomPriorityManager::RendererStats::RendererStats()
: is_pinned(false),
is_selected(false),
memory_used(0),
renderer_handle(0) {
}
OomPriorityManager::RendererStats::~RendererStats() {
}
// static
OomPriorityManager* OomPriorityManager::GetInstance() {
return Singleton<OomPriorityManager>::get();
}
OomPriorityManager::OomPriorityManager() {
renderer_stats_.reserve(32); // 99% of users have < 30 tabs open
}
OomPriorityManager::~OomPriorityManager() {
Stop();
}
void OomPriorityManager::Start() {
if (!timer_.IsRunning()) {
timer_.Start(FROM_HERE,
TimeDelta::FromSeconds(ADJUSTMENT_INTERVAL_SECONDS),
this,
&OomPriorityManager::AdjustOomPriorities);
}
}
void OomPriorityManager::Stop() {
timer_.Stop();
}
std::vector<string16> OomPriorityManager::GetTabTitles() {
base::AutoLock renderer_stats_autolock(renderer_stats_lock_);
std::vector<string16> titles;
titles.reserve(renderer_stats_.size());
StatsList::iterator it = renderer_stats_.begin();
for ( ; it != renderer_stats_.end(); ++it) {
titles.push_back(it->title);
}
return titles;
}
// Returns true if |first| is considered less desirable to be killed
// than |second|.
bool OomPriorityManager::CompareRendererStats(RendererStats first,
RendererStats second) {
// The size of the slop in comparing activation times. [This is
// allocated here to avoid static initialization at startup time.]
static const int64 kTimeBucketInterval =
TimeDelta::FromMinutes(BUCKET_INTERVAL_MINUTES).ToInternalValue();
// Being currently selected is most important.
if (first.is_selected != second.is_selected)
return first.is_selected == true;
// Being pinned is second most important.
if (first.is_pinned != second.is_pinned)
return first.is_pinned == true;
// We want to be a little "fuzzy" when we compare these, because
// it's not really possible for the times to be identical, but if
// the user selected two tabs at about the same time, we still want
// to take the one that uses more memory.
if (abs((first.last_selected - second.last_selected).ToInternalValue()) <
kTimeBucketInterval)
return first.last_selected < second.last_selected;
return first.memory_used < second.memory_used;
}
// Here we collect most of the information we need to sort the
// existing renderers in priority order, and hand out oom_score_adj
// scores based on that sort order.
//
// Things we need to collect on the browser thread (because
// TabStripModel isn't thread safe):
// 1) whether or not a tab is pinned
// 2) last time a tab was selected
// 3) is the tab currently selected
//
// We also need to collect:
// 4) size in memory of a tab
// But we do that in DoAdjustOomPriorities on the FILE thread so that
// we avoid jank, because it accesses /proc.
void OomPriorityManager::AdjustOomPriorities() {
if (BrowserList::size() == 0)
return;
{
base::AutoLock renderer_stats_autolock(renderer_stats_lock_);
renderer_stats_.clear();
for (BrowserList::const_iterator browser_iterator = BrowserList::begin();
browser_iterator != BrowserList::end(); ++browser_iterator) {
Browser* browser = *browser_iterator;
const TabStripModel* model = browser->tabstrip_model();
for (int i = 0; i < model->count(); i++) {
TabContents* contents = model->GetTabContentsAt(i)->tab_contents();
RendererStats stats;
stats.last_selected = contents->last_selected_time();
stats.renderer_handle = contents->GetRenderProcessHost()->GetHandle();
stats.is_pinned = model->IsTabPinned(i);
stats.memory_used = 0; // Calculated in DoAdjustOomPriorities.
stats.is_selected = model->IsTabSelected(i);
stats.title = contents->GetTitle();
renderer_stats_.push_back(stats);
}
}
}
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &OomPriorityManager::DoAdjustOomPriorities));
}
void OomPriorityManager::DoAdjustOomPriorities() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::AutoLock renderer_stats_autolock(renderer_stats_lock_);
for (StatsList::iterator stats_iter = renderer_stats_.begin();
stats_iter != renderer_stats_.end(); ++stats_iter) {
scoped_ptr<ProcessMetrics> metrics(ProcessMetrics::CreateProcessMetrics(
stats_iter->renderer_handle));
base::WorkingSetKBytes working_set_kbytes;
if (metrics->GetWorkingSetKBytes(&working_set_kbytes)) {
// We use the proportional set size (PSS) to calculate memory
// usage "badness" on Linux.
stats_iter->memory_used = working_set_kbytes.shared * 1024;
} else {
// and if for some reason we can't get PSS, we revert to using
// resident set size (RSS). This will be zero if the process
// has already gone away, but we can live with that, since the
// process is gone anyhow.
stats_iter->memory_used = metrics->GetWorkingSetSize();
}
}
// Now we sort the data we collected so that least desirable to be
// killed is first, most desirable is last.
std::sort(renderer_stats_.begin(),
renderer_stats_.end(),
OomPriorityManager::CompareRendererStats);
// Now we assign priorities based on the sorted list. We're
// assigning priorities in the range of kLowestRendererOomScore to
// kHighestRendererOomScore (defined in chrome_constants.h).
// oom_score_adj takes values from -1000 to 1000. Negative values
// are reserved for system processes, and we want to give some room
// below the range we're using to allow for things that want to be
// above the renderers in priority, so the defined range gives us
// some variation in priority without taking up the whole range. In
// the end, however, it's a pretty arbitrary range to use. Higher
// values are more likely to be killed by the OOM killer.
//
// We also remove any duplicate PIDs, leaving the most important
// (least likely to be killed) of the duplicates, so that a
// particular renderer process takes on the oom_score_adj of the
// least likely tab to be killed.
const int kPriorityRange = chrome::kHighestRendererOomScore -
chrome::kLowestRendererOomScore;
float priority_increment =
static_cast<float>(kPriorityRange) / renderer_stats_.size();
float priority = chrome::kLowestRendererOomScore;
std::set<base::ProcessHandle> already_seen;
for (StatsList::iterator iterator = renderer_stats_.begin();
iterator != renderer_stats_.end(); ++iterator) {
if (already_seen.find(iterator->renderer_handle) == already_seen.end()) {
already_seen.insert(iterator->renderer_handle);
ZygoteHost::GetInstance()->AdjustRendererOOMScore(
iterator->renderer_handle, static_cast<int>(priority + 0.5f));
priority += priority_increment;
}
}
}
} // namespace browser
<commit_msg>If a renderer is crashed, RenderProcessHost::GetHandle would return the pid of the process calling it, in this case it would be the Browser process itself. It is incorrect to change the score of the Browser process.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/oom_priority_manager.h"
#include <algorithm>
#include <vector>
#include "base/process.h"
#include "base/process_util.h"
#include "base/string16.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread.h"
#include "base/timer.h"
#include "build/build_config.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/zygote_host_linux.h"
#if !defined(OS_CHROMEOS)
#error This file only meant to be compiled on ChromeOS
#endif
using base::TimeDelta;
using base::TimeTicks;
using base::ProcessHandle;
using base::ProcessMetrics;
namespace browser {
// The default interval in seconds after which to adjust the oom_score_adj
// value.
#define ADJUSTMENT_INTERVAL_SECONDS 10
// The default interval in minutes for considering activation times
// "equal".
#define BUCKET_INTERVAL_MINUTES 10
OomPriorityManager::RendererStats::RendererStats()
: is_pinned(false),
is_selected(false),
memory_used(0),
renderer_handle(0) {
}
OomPriorityManager::RendererStats::~RendererStats() {
}
// static
OomPriorityManager* OomPriorityManager::GetInstance() {
return Singleton<OomPriorityManager>::get();
}
OomPriorityManager::OomPriorityManager() {
renderer_stats_.reserve(32); // 99% of users have < 30 tabs open
}
OomPriorityManager::~OomPriorityManager() {
Stop();
}
void OomPriorityManager::Start() {
if (!timer_.IsRunning()) {
timer_.Start(FROM_HERE,
TimeDelta::FromSeconds(ADJUSTMENT_INTERVAL_SECONDS),
this,
&OomPriorityManager::AdjustOomPriorities);
}
}
void OomPriorityManager::Stop() {
timer_.Stop();
}
std::vector<string16> OomPriorityManager::GetTabTitles() {
base::AutoLock renderer_stats_autolock(renderer_stats_lock_);
std::vector<string16> titles;
titles.reserve(renderer_stats_.size());
StatsList::iterator it = renderer_stats_.begin();
for ( ; it != renderer_stats_.end(); ++it) {
titles.push_back(it->title);
}
return titles;
}
// Returns true if |first| is considered less desirable to be killed
// than |second|.
bool OomPriorityManager::CompareRendererStats(RendererStats first,
RendererStats second) {
// The size of the slop in comparing activation times. [This is
// allocated here to avoid static initialization at startup time.]
static const int64 kTimeBucketInterval =
TimeDelta::FromMinutes(BUCKET_INTERVAL_MINUTES).ToInternalValue();
// Being currently selected is most important.
if (first.is_selected != second.is_selected)
return first.is_selected == true;
// Being pinned is second most important.
if (first.is_pinned != second.is_pinned)
return first.is_pinned == true;
// We want to be a little "fuzzy" when we compare these, because
// it's not really possible for the times to be identical, but if
// the user selected two tabs at about the same time, we still want
// to take the one that uses more memory.
if (abs((first.last_selected - second.last_selected).ToInternalValue()) <
kTimeBucketInterval)
return first.last_selected < second.last_selected;
return first.memory_used < second.memory_used;
}
// Here we collect most of the information we need to sort the
// existing renderers in priority order, and hand out oom_score_adj
// scores based on that sort order.
//
// Things we need to collect on the browser thread (because
// TabStripModel isn't thread safe):
// 1) whether or not a tab is pinned
// 2) last time a tab was selected
// 3) is the tab currently selected
//
// We also need to collect:
// 4) size in memory of a tab
// But we do that in DoAdjustOomPriorities on the FILE thread so that
// we avoid jank, because it accesses /proc.
void OomPriorityManager::AdjustOomPriorities() {
if (BrowserList::size() == 0)
return;
{
base::AutoLock renderer_stats_autolock(renderer_stats_lock_);
renderer_stats_.clear();
for (BrowserList::const_iterator browser_iterator = BrowserList::begin();
browser_iterator != BrowserList::end(); ++browser_iterator) {
Browser* browser = *browser_iterator;
const TabStripModel* model = browser->tabstrip_model();
for (int i = 0; i < model->count(); i++) {
TabContents* contents = model->GetTabContentsAt(i)->tab_contents();
if (!contents->is_crashed()) {
RendererStats stats;
stats.last_selected = contents->last_selected_time();
stats.renderer_handle = contents->GetRenderProcessHost()->GetHandle();
stats.is_pinned = model->IsTabPinned(i);
stats.memory_used = 0; // Calculated in DoAdjustOomPriorities.
stats.is_selected = model->IsTabSelected(i);
stats.title = contents->GetTitle();
renderer_stats_.push_back(stats);
}
}
}
}
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &OomPriorityManager::DoAdjustOomPriorities));
}
void OomPriorityManager::DoAdjustOomPriorities() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
base::AutoLock renderer_stats_autolock(renderer_stats_lock_);
for (StatsList::iterator stats_iter = renderer_stats_.begin();
stats_iter != renderer_stats_.end(); ++stats_iter) {
scoped_ptr<ProcessMetrics> metrics(ProcessMetrics::CreateProcessMetrics(
stats_iter->renderer_handle));
base::WorkingSetKBytes working_set_kbytes;
if (metrics->GetWorkingSetKBytes(&working_set_kbytes)) {
// We use the proportional set size (PSS) to calculate memory
// usage "badness" on Linux.
stats_iter->memory_used = working_set_kbytes.shared * 1024;
} else {
// and if for some reason we can't get PSS, we revert to using
// resident set size (RSS). This will be zero if the process
// has already gone away, but we can live with that, since the
// process is gone anyhow.
stats_iter->memory_used = metrics->GetWorkingSetSize();
}
}
// Now we sort the data we collected so that least desirable to be
// killed is first, most desirable is last.
std::sort(renderer_stats_.begin(),
renderer_stats_.end(),
OomPriorityManager::CompareRendererStats);
// Now we assign priorities based on the sorted list. We're
// assigning priorities in the range of kLowestRendererOomScore to
// kHighestRendererOomScore (defined in chrome_constants.h).
// oom_score_adj takes values from -1000 to 1000. Negative values
// are reserved for system processes, and we want to give some room
// below the range we're using to allow for things that want to be
// above the renderers in priority, so the defined range gives us
// some variation in priority without taking up the whole range. In
// the end, however, it's a pretty arbitrary range to use. Higher
// values are more likely to be killed by the OOM killer.
//
// We also remove any duplicate PIDs, leaving the most important
// (least likely to be killed) of the duplicates, so that a
// particular renderer process takes on the oom_score_adj of the
// least likely tab to be killed.
const int kPriorityRange = chrome::kHighestRendererOomScore -
chrome::kLowestRendererOomScore;
float priority_increment =
static_cast<float>(kPriorityRange) / renderer_stats_.size();
float priority = chrome::kLowestRendererOomScore;
std::set<base::ProcessHandle> already_seen;
for (StatsList::iterator iterator = renderer_stats_.begin();
iterator != renderer_stats_.end(); ++iterator) {
if (already_seen.find(iterator->renderer_handle) == already_seen.end()) {
already_seen.insert(iterator->renderer_handle);
ZygoteHost::GetInstance()->AdjustRendererOOMScore(
iterator->renderer_handle, static_cast<int>(priority + 0.5f));
priority += priority_increment;
}
}
}
} // namespace browser
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "content/renderer/p2p/p2p_transport_impl.h"
#include "jingle/glue/fake_network_manager.h"
#include "jingle/glue/fake_socket_factory.h"
#include "jingle/glue/thread_wrapper.h"
#include "net/base/completion_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/socket/socket.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::AtMost;
using testing::Exactly;
using testing::Invoke;
using webkit_glue::P2PTransport;
namespace {
const char kTestAddress1[] = "192.168.15.12";
const char kTestAddress2[] = "192.168.15.33";
const char kTransportName1[] = "tr1";
const char kTransportName2[] = "tr2";
const char kTestConfig[] = "";
// Send 10 packets 10 bytes each. Packets are sent with 10ms delay
// between packets (about 100 ms for 10 messages).
const int kMessageSize = 10;
const int kMessages = 10;
const int kUdpWriteDelayMs = 10;
class ChannelTester : public base::RefCountedThreadSafe<ChannelTester> {
public:
ChannelTester(MessageLoop* message_loop,
net::Socket* write_socket,
net::Socket* read_socket)
: message_loop_(message_loop),
write_socket_(write_socket),
read_socket_(read_socket),
done_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(
write_cb_(this, &ChannelTester::OnWritten)),
ALLOW_THIS_IN_INITIALIZER_LIST(
read_cb_(this, &ChannelTester::OnRead)),
write_errors_(0),
read_errors_(0),
packets_sent_(0),
packets_received_(0),
broken_packets_(0) {
}
virtual ~ChannelTester() { }
void Start() {
message_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &ChannelTester::DoStart));
}
void CheckResults() {
EXPECT_EQ(0, write_errors_);
EXPECT_EQ(0, read_errors_);
EXPECT_EQ(0, broken_packets_);
// Verify that we've received at least one packet.
EXPECT_GT(packets_received_, 0);
LOG(INFO) << "Received " << packets_received_ << " packets out of "
<< kMessages;
}
protected:
void Done() {
done_ = true;
message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
void DoStart() {
DoRead();
DoWrite();
}
void DoWrite() {
if (packets_sent_ >= kMessages) {
Done();
return;
}
scoped_refptr<net::IOBuffer> packet(new net::IOBuffer(kMessageSize));
memset(packet->data(), 123, kMessageSize);
sent_packets_[packets_sent_] = packet;
// Put index of this packet in the beginning of the packet body.
memcpy(packet->data(), &packets_sent_, sizeof(packets_sent_));
int result = write_socket_->Write(packet, kMessageSize, &write_cb_);
HandleWriteResult(result);
}
void OnWritten(int result) {
HandleWriteResult(result);
}
void HandleWriteResult(int result) {
if (result <= 0 && result != net::ERR_IO_PENDING) {
LOG(ERROR) << "Received error " << result << " when trying to write";
write_errors_++;
Done();
} else if (result > 0) {
EXPECT_EQ(kMessageSize, result);
packets_sent_++;
message_loop_->PostDelayedTask(
FROM_HERE, NewRunnableMethod(this, &ChannelTester::DoWrite),
kUdpWriteDelayMs);
}
}
void DoRead() {
int result = 1;
while (result > 0) {
int kReadSize = kMessageSize * 2;
read_buffer_ = new net::IOBuffer(kReadSize);
result = read_socket_->Read(read_buffer_, kReadSize, &read_cb_);
HandleReadResult(result);
};
}
void OnRead(int result) {
HandleReadResult(result);
DoRead();
}
void HandleReadResult(int result) {
if (result <= 0 && result != net::ERR_IO_PENDING) {
// Error will be received after the socket is closed.
if (!done_) {
LOG(ERROR) << "Received error " << result << " when trying to read";
read_errors_++;
Done();
}
} else if (result > 0) {
packets_received_++;
if (kMessageSize != result) {
// Invalid packet size;
broken_packets_++;
} else {
// Validate packet body.
int packet_id;
memcpy(&packet_id, read_buffer_->data(), sizeof(packet_id));
if (packet_id < 0 || packet_id >= kMessages) {
broken_packets_++;
} else {
if (memcmp(read_buffer_->data(), sent_packets_[packet_id]->data(),
kMessageSize) != 0)
broken_packets_++;
}
}
}
}
private:
MessageLoop* message_loop_;
net::Socket* write_socket_;
net::Socket* read_socket_;
bool done_;
scoped_refptr<net::IOBuffer> sent_packets_[kMessages];
scoped_refptr<net::IOBuffer> read_buffer_;
net::CompletionCallbackImpl<ChannelTester> write_cb_;
net::CompletionCallbackImpl<ChannelTester> read_cb_;
int write_errors_;
int read_errors_;
int packets_sent_;
int packets_received_;
int broken_packets_;
};
} // namespace
class MockP2PEventHandler : public P2PTransport::EventHandler {
public:
MOCK_METHOD1(OnCandidateReady, void(const std::string& address));
MOCK_METHOD1(OnStateChange, void(P2PTransport::State state));
};
class P2PTransportImplTest : public testing::Test {
public:
protected:
void SetUp() OVERRIDE {
socket_manager_ = new jingle_glue::FakeSocketManager();
net::IPAddressNumber ip;
ASSERT(net::ParseIPLiteralToNumber(kTestAddress1, &ip));
network_manager1_.reset(new jingle_glue::FakeNetworkManager(ip));
socket_factory1_.reset(
new jingle_glue::FakeSocketFactory(socket_manager_, ip));
transport1_.reset(new P2PTransportImpl(network_manager1_.get(),
socket_factory1_.get()));
ASSERT(net::ParseIPLiteralToNumber(kTestAddress2, &ip));
network_manager2_.reset(new jingle_glue::FakeNetworkManager(ip));
socket_factory2_.reset(
new jingle_glue::FakeSocketFactory(socket_manager_, ip));
transport2_.reset(new P2PTransportImpl(network_manager2_.get(),
socket_factory2_.get()));
}
MessageLoop message_loop_;
scoped_ptr<jingle_glue::FakeNetworkManager> network_manager1_;
scoped_ptr<jingle_glue::FakeNetworkManager> network_manager2_;
scoped_refptr<jingle_glue::FakeSocketManager> socket_manager_;
scoped_ptr<jingle_glue::FakeSocketFactory> socket_factory1_;
scoped_ptr<jingle_glue::FakeSocketFactory> socket_factory2_;
scoped_ptr<P2PTransportImpl> transport1_;
MockP2PEventHandler event_handler1_;
scoped_ptr<P2PTransportImpl> transport2_;
MockP2PEventHandler event_handler2_;
};
TEST_F(P2PTransportImplTest, Create) {
ASSERT_TRUE(transport1_->Init(
kTransportName1, kTestConfig, &event_handler1_));
ASSERT_TRUE(transport2_->Init(
kTransportName2, kTestConfig, &event_handler2_));
EXPECT_CALL(event_handler1_, OnCandidateReady(_));
EXPECT_CALL(event_handler2_, OnCandidateReady(_));
message_loop_.RunAllPending();
}
ACTION_P(AddRemoteCandidate, transport) {
EXPECT_TRUE(transport->AddRemoteCandidate(arg0));
}
TEST_F(P2PTransportImplTest, Connect) {
ASSERT_TRUE(transport1_->Init(
kTransportName1, kTestConfig, &event_handler1_));
ASSERT_TRUE(transport2_->Init(
kTransportName2, kTestConfig, &event_handler2_));
EXPECT_CALL(event_handler1_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport2_.get()));
EXPECT_CALL(event_handler2_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport1_.get()));
message_loop_.RunAllPending();
}
TEST_F(P2PTransportImplTest, SendData) {
ASSERT_TRUE(transport1_->Init(
kTransportName1, kTestConfig, &event_handler1_));
ASSERT_TRUE(transport2_->Init(
kTransportName2, kTestConfig, &event_handler2_));
EXPECT_CALL(event_handler1_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport2_.get()));
EXPECT_CALL(event_handler2_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport1_.get()));
// Transport may first become ether readable or writable, but
// eventually it must be readable and writable.
EXPECT_CALL(event_handler1_, OnStateChange(P2PTransport::STATE_READABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler1_, OnStateChange(P2PTransport::STATE_WRITABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler1_, OnStateChange(
static_cast<P2PTransport::State>(P2PTransport::STATE_READABLE |
P2PTransport::STATE_WRITABLE)))
.Times(Exactly(1));
EXPECT_CALL(event_handler2_, OnStateChange(P2PTransport::STATE_READABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler2_, OnStateChange(P2PTransport::STATE_WRITABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler2_, OnStateChange(
static_cast<P2PTransport::State>(P2PTransport::STATE_READABLE |
P2PTransport::STATE_WRITABLE)))
.Times(Exactly(1));
scoped_refptr<ChannelTester> channel_tester = new ChannelTester(
&message_loop_, transport1_->GetChannel(), transport2_->GetChannel());
message_loop_.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask(),
TestTimeouts::action_max_timeout_ms());
channel_tester->Start();
message_loop_.Run();
channel_tester->CheckResults();
}
<commit_msg>Disable failing P2P tests.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "content/renderer/p2p/p2p_transport_impl.h"
#include "jingle/glue/fake_network_manager.h"
#include "jingle/glue/fake_socket_factory.h"
#include "jingle/glue/thread_wrapper.h"
#include "net/base/completion_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/socket/socket.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::AtMost;
using testing::Exactly;
using testing::Invoke;
using webkit_glue::P2PTransport;
namespace {
const char kTestAddress1[] = "192.168.15.12";
const char kTestAddress2[] = "192.168.15.33";
const char kTransportName1[] = "tr1";
const char kTransportName2[] = "tr2";
const char kTestConfig[] = "";
// Send 10 packets 10 bytes each. Packets are sent with 10ms delay
// between packets (about 100 ms for 10 messages).
const int kMessageSize = 10;
const int kMessages = 10;
const int kUdpWriteDelayMs = 10;
class ChannelTester : public base::RefCountedThreadSafe<ChannelTester> {
public:
ChannelTester(MessageLoop* message_loop,
net::Socket* write_socket,
net::Socket* read_socket)
: message_loop_(message_loop),
write_socket_(write_socket),
read_socket_(read_socket),
done_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(
write_cb_(this, &ChannelTester::OnWritten)),
ALLOW_THIS_IN_INITIALIZER_LIST(
read_cb_(this, &ChannelTester::OnRead)),
write_errors_(0),
read_errors_(0),
packets_sent_(0),
packets_received_(0),
broken_packets_(0) {
}
virtual ~ChannelTester() { }
void Start() {
message_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &ChannelTester::DoStart));
}
void CheckResults() {
EXPECT_EQ(0, write_errors_);
EXPECT_EQ(0, read_errors_);
EXPECT_EQ(0, broken_packets_);
// Verify that we've received at least one packet.
EXPECT_GT(packets_received_, 0);
LOG(INFO) << "Received " << packets_received_ << " packets out of "
<< kMessages;
}
protected:
void Done() {
done_ = true;
message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
void DoStart() {
DoRead();
DoWrite();
}
void DoWrite() {
if (packets_sent_ >= kMessages) {
Done();
return;
}
scoped_refptr<net::IOBuffer> packet(new net::IOBuffer(kMessageSize));
memset(packet->data(), 123, kMessageSize);
sent_packets_[packets_sent_] = packet;
// Put index of this packet in the beginning of the packet body.
memcpy(packet->data(), &packets_sent_, sizeof(packets_sent_));
int result = write_socket_->Write(packet, kMessageSize, &write_cb_);
HandleWriteResult(result);
}
void OnWritten(int result) {
HandleWriteResult(result);
}
void HandleWriteResult(int result) {
if (result <= 0 && result != net::ERR_IO_PENDING) {
LOG(ERROR) << "Received error " << result << " when trying to write";
write_errors_++;
Done();
} else if (result > 0) {
EXPECT_EQ(kMessageSize, result);
packets_sent_++;
message_loop_->PostDelayedTask(
FROM_HERE, NewRunnableMethod(this, &ChannelTester::DoWrite),
kUdpWriteDelayMs);
}
}
void DoRead() {
int result = 1;
while (result > 0) {
int kReadSize = kMessageSize * 2;
read_buffer_ = new net::IOBuffer(kReadSize);
result = read_socket_->Read(read_buffer_, kReadSize, &read_cb_);
HandleReadResult(result);
};
}
void OnRead(int result) {
HandleReadResult(result);
DoRead();
}
void HandleReadResult(int result) {
if (result <= 0 && result != net::ERR_IO_PENDING) {
// Error will be received after the socket is closed.
if (!done_) {
LOG(ERROR) << "Received error " << result << " when trying to read";
read_errors_++;
Done();
}
} else if (result > 0) {
packets_received_++;
if (kMessageSize != result) {
// Invalid packet size;
broken_packets_++;
} else {
// Validate packet body.
int packet_id;
memcpy(&packet_id, read_buffer_->data(), sizeof(packet_id));
if (packet_id < 0 || packet_id >= kMessages) {
broken_packets_++;
} else {
if (memcmp(read_buffer_->data(), sent_packets_[packet_id]->data(),
kMessageSize) != 0)
broken_packets_++;
}
}
}
}
private:
MessageLoop* message_loop_;
net::Socket* write_socket_;
net::Socket* read_socket_;
bool done_;
scoped_refptr<net::IOBuffer> sent_packets_[kMessages];
scoped_refptr<net::IOBuffer> read_buffer_;
net::CompletionCallbackImpl<ChannelTester> write_cb_;
net::CompletionCallbackImpl<ChannelTester> read_cb_;
int write_errors_;
int read_errors_;
int packets_sent_;
int packets_received_;
int broken_packets_;
};
} // namespace
class MockP2PEventHandler : public P2PTransport::EventHandler {
public:
MOCK_METHOD1(OnCandidateReady, void(const std::string& address));
MOCK_METHOD1(OnStateChange, void(P2PTransport::State state));
};
class P2PTransportImplTest : public testing::Test {
public:
protected:
void SetUp() OVERRIDE {
socket_manager_ = new jingle_glue::FakeSocketManager();
net::IPAddressNumber ip;
ASSERT(net::ParseIPLiteralToNumber(kTestAddress1, &ip));
network_manager1_.reset(new jingle_glue::FakeNetworkManager(ip));
socket_factory1_.reset(
new jingle_glue::FakeSocketFactory(socket_manager_, ip));
transport1_.reset(new P2PTransportImpl(network_manager1_.get(),
socket_factory1_.get()));
ASSERT(net::ParseIPLiteralToNumber(kTestAddress2, &ip));
network_manager2_.reset(new jingle_glue::FakeNetworkManager(ip));
socket_factory2_.reset(
new jingle_glue::FakeSocketFactory(socket_manager_, ip));
transport2_.reset(new P2PTransportImpl(network_manager2_.get(),
socket_factory2_.get()));
}
MessageLoop message_loop_;
scoped_ptr<jingle_glue::FakeNetworkManager> network_manager1_;
scoped_ptr<jingle_glue::FakeNetworkManager> network_manager2_;
scoped_refptr<jingle_glue::FakeSocketManager> socket_manager_;
scoped_ptr<jingle_glue::FakeSocketFactory> socket_factory1_;
scoped_ptr<jingle_glue::FakeSocketFactory> socket_factory2_;
scoped_ptr<P2PTransportImpl> transport1_;
MockP2PEventHandler event_handler1_;
scoped_ptr<P2PTransportImpl> transport2_;
MockP2PEventHandler event_handler2_;
};
TEST_F(P2PTransportImplTest, DISABLED_Create) {
ASSERT_TRUE(transport1_->Init(
kTransportName1, kTestConfig, &event_handler1_));
ASSERT_TRUE(transport2_->Init(
kTransportName2, kTestConfig, &event_handler2_));
EXPECT_CALL(event_handler1_, OnCandidateReady(_));
EXPECT_CALL(event_handler2_, OnCandidateReady(_));
message_loop_.RunAllPending();
}
ACTION_P(AddRemoteCandidate, transport) {
EXPECT_TRUE(transport->AddRemoteCandidate(arg0));
}
TEST_F(P2PTransportImplTest, DISABLED_Connect) {
ASSERT_TRUE(transport1_->Init(
kTransportName1, kTestConfig, &event_handler1_));
ASSERT_TRUE(transport2_->Init(
kTransportName2, kTestConfig, &event_handler2_));
EXPECT_CALL(event_handler1_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport2_.get()));
EXPECT_CALL(event_handler2_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport1_.get()));
message_loop_.RunAllPending();
}
TEST_F(P2PTransportImplTest, DISABLED_SendData) {
ASSERT_TRUE(transport1_->Init(
kTransportName1, kTestConfig, &event_handler1_));
ASSERT_TRUE(transport2_->Init(
kTransportName2, kTestConfig, &event_handler2_));
EXPECT_CALL(event_handler1_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport2_.get()));
EXPECT_CALL(event_handler2_, OnCandidateReady(_)).WillRepeatedly(
AddRemoteCandidate(transport1_.get()));
// Transport may first become ether readable or writable, but
// eventually it must be readable and writable.
EXPECT_CALL(event_handler1_, OnStateChange(P2PTransport::STATE_READABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler1_, OnStateChange(P2PTransport::STATE_WRITABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler1_, OnStateChange(
static_cast<P2PTransport::State>(P2PTransport::STATE_READABLE |
P2PTransport::STATE_WRITABLE)))
.Times(Exactly(1));
EXPECT_CALL(event_handler2_, OnStateChange(P2PTransport::STATE_READABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler2_, OnStateChange(P2PTransport::STATE_WRITABLE))
.Times(AtMost(1));
EXPECT_CALL(event_handler2_, OnStateChange(
static_cast<P2PTransport::State>(P2PTransport::STATE_READABLE |
P2PTransport::STATE_WRITABLE)))
.Times(Exactly(1));
scoped_refptr<ChannelTester> channel_tester = new ChannelTester(
&message_loop_, transport1_->GetChannel(), transport2_->GetChannel());
message_loop_.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask(),
TestTimeouts::action_max_timeout_ms());
channel_tester->Start();
message_loop_.Run();
channel_tester->CheckResults();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-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 <string>
#include <windows.h>
#include "base/command_line.h"
#include "base/basictypes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class ChromeLoggingTest : public testing::Test {
public:
// Stores the current value of the log file name environment
// variable and sets the variable to new_value.
void SaveEnvironmentVariable(std::wstring new_value) {
unsigned status = GetEnvironmentVariable(env_vars::kLogFileName,
environment_filename_,
MAX_PATH);
if (!status) {
wcscpy_s(environment_filename_, L"");
}
SetEnvironmentVariable(env_vars::kLogFileName, new_value.c_str());
}
// Restores the value of the log file nave environment variable
// previously saved by SaveEnvironmentVariable().
void RestoreEnvironmentVariable() {
SetEnvironmentVariable(env_vars::kLogFileName, environment_filename_);
}
private:
wchar_t environment_filename_[MAX_PATH]; // Saves real environment value.
};
};
// Tests the log file name getter without an environment variable.
TEST_F(ChromeLoggingTest, LogFileName) {
SaveEnvironmentVariable(std::wstring());
FilePath filename = logging::GetLogFileName();
ASSERT_NE(FilePath::StringType::npos,
filename.value().find(FILE_PATH_LITERAL("chrome_debug.log")));
RestoreEnvironmentVariable();
}
// Tests the log file name getter with an environment variable.
TEST_F(ChromeLoggingTest, EnvironmentLogFileName) {
SaveEnvironmentVariable(std::wstring(L"test value"));
FilePath filename = logging::GetLogFileName();
ASSERT_EQ(FilePath(FILE_PATH_LITERAL("test value")).value(),
filename.value());
RestoreEnvironmentVariable();
}
#ifndef NDEBUG // We don't have assertions in release builds.
// Tests whether we correctly fail on browser assertions during tests.
class AssertionTest : public UITest {
protected:
AssertionTest() : UITest()
{
// Initial loads will never complete due to assertion.
wait_for_initial_loads_ = false;
// We're testing the renderer rather than the browser assertion here,
// because the browser assertion would flunk the test during SetUp()
// (since TAU wouldn't be able to find the browser window).
launch_arguments_.AppendSwitch(switches::kRendererAssertTest);
}
};
// Launch the app in assertion test mode, then close the app.
TEST_F(AssertionTest, Assertion) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_errors_ = 0;
expected_crashes_ = 0;
} else {
expected_errors_ = 1;
expected_crashes_ = 1;
}
}
#endif // NDEBUG
// Tests whether we correctly fail on browser crashes during UI Tests.
class RendererCrashTest : public UITest {
protected:
RendererCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kRendererCrashTest);
}
};
// Launch the app in renderer crash test mode, then close the app.
TEST_F(RendererCrashTest, Crash) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_crashes_ = 0;
} else {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
expected_crashes_ = 1;
}
}
// Tests whether we correctly fail on browser crashes during UI Tests.
class BrowserCrashTest : public UITest {
protected:
BrowserCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kBrowserCrashTest);
}
};
// Launch the app in browser crash test mode.
// This test is disabled. See bug 6910.
TEST_F(BrowserCrashTest, DISABLED_Crash) {
// Wait while the process is writing the crash dump.
PlatformThread::Sleep(5000);
expected_crashes_ = 1;
}
<commit_msg>Remove the BrowserCrashTest.Crash test from the code because it never worked. I will make bug 3910 about creating such test.<commit_after>// Copyright (c) 2006-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 <string>
#include <windows.h>
#include "base/command_line.h"
#include "base/basictypes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class ChromeLoggingTest : public testing::Test {
public:
// Stores the current value of the log file name environment
// variable and sets the variable to new_value.
void SaveEnvironmentVariable(std::wstring new_value) {
unsigned status = GetEnvironmentVariable(env_vars::kLogFileName,
environment_filename_,
MAX_PATH);
if (!status) {
wcscpy_s(environment_filename_, L"");
}
SetEnvironmentVariable(env_vars::kLogFileName, new_value.c_str());
}
// Restores the value of the log file nave environment variable
// previously saved by SaveEnvironmentVariable().
void RestoreEnvironmentVariable() {
SetEnvironmentVariable(env_vars::kLogFileName, environment_filename_);
}
private:
wchar_t environment_filename_[MAX_PATH]; // Saves real environment value.
};
};
// Tests the log file name getter without an environment variable.
TEST_F(ChromeLoggingTest, LogFileName) {
SaveEnvironmentVariable(std::wstring());
FilePath filename = logging::GetLogFileName();
ASSERT_NE(FilePath::StringType::npos,
filename.value().find(FILE_PATH_LITERAL("chrome_debug.log")));
RestoreEnvironmentVariable();
}
// Tests the log file name getter with an environment variable.
TEST_F(ChromeLoggingTest, EnvironmentLogFileName) {
SaveEnvironmentVariable(std::wstring(L"test value"));
FilePath filename = logging::GetLogFileName();
ASSERT_EQ(FilePath(FILE_PATH_LITERAL("test value")).value(),
filename.value());
RestoreEnvironmentVariable();
}
#ifndef NDEBUG // We don't have assertions in release builds.
// Tests whether we correctly fail on browser assertions during tests.
class AssertionTest : public UITest {
protected:
AssertionTest() : UITest()
{
// Initial loads will never complete due to assertion.
wait_for_initial_loads_ = false;
// We're testing the renderer rather than the browser assertion here,
// because the browser assertion would flunk the test during SetUp()
// (since TAU wouldn't be able to find the browser window).
launch_arguments_.AppendSwitch(switches::kRendererAssertTest);
}
};
// Launch the app in assertion test mode, then close the app.
TEST_F(AssertionTest, Assertion) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_errors_ = 0;
expected_crashes_ = 0;
} else {
expected_errors_ = 1;
expected_crashes_ = 1;
}
}
#endif // NDEBUG
// Tests whether we correctly fail on browser crashes during UI Tests.
class RendererCrashTest : public UITest {
protected:
RendererCrashTest() : UITest()
{
// Initial loads will never complete due to crash.
wait_for_initial_loads_ = false;
launch_arguments_.AppendSwitch(switches::kRendererCrashTest);
}
};
// Launch the app in renderer crash test mode, then close the app.
TEST_F(RendererCrashTest, Crash) {
if (UITest::in_process_renderer()) {
// in process mode doesn't do the crashing.
expected_crashes_ = 0;
} else {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));
expected_crashes_ = 1;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/threading/platform_thread.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
using base::TimeDelta;
namespace {
// This Automated UI test opens static files in different tabs in a proxy
// browser. After all the tabs have opened, it switches between tabs, and notes
// time taken for each switch. It then prints out the times on the console,
// with the aim that the page cycler parser can interpret these numbers to
// draw graphs for page cycler Tab Switching Performance.
class TabSwitchingUITest : public UIPerfTest {
public:
TabSwitchingUITest() {
PathService::Get(base::DIR_SOURCE_ROOT, &path_prefix_);
path_prefix_ = path_prefix_.AppendASCII("data");
path_prefix_ = path_prefix_.AppendASCII("tab_switching");
show_window_ = true;
}
void SetUp() {
// Set the log_file_name_ path according to the selected browser_directory_.
log_file_name_ = browser_directory_.AppendASCII("chrome_debug.log");
// Set the log file path for the browser test.
scoped_ptr<base::Environment> env(base::Environment::Create());
#if defined(OS_WIN)
env->SetVar(env_vars::kLogFileName, WideToUTF8(log_file_name_.value()));
#else
env->SetVar(env_vars::kLogFileName, log_file_name_.value());
#endif
// Add the necessary arguments to Chrome's launch command for these tests.
AddLaunchArguments();
// Run the rest of the UITest initialization.
UITest::SetUp();
}
static const int kNumCycles = 5;
void PrintTimings(const char* label, TimeDelta timings[kNumCycles],
bool important) {
std::string times;
for (int i = 0; i < kNumCycles; ++i)
base::StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList("times", "", label, times, "ms", important);
}
void RunTabSwitchingUITest(const char* label, bool important) {
// Shut down from window UITest sets up automatically.
UITest::TearDown();
TimeDelta timings[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
// Prepare for this test run.
SetUp();
// Create a browser proxy.
browser_proxy_ = automation()->GetBrowserWindow(0);
// Open all the tabs.
int initial_tab_count = 0;
ASSERT_TRUE(browser_proxy_->GetTabCount(&initial_tab_count));
int new_tab_count = OpenTabs();
int tab_count = -1;
ASSERT_TRUE(browser_proxy_->GetTabCount(&tab_count));
ASSERT_EQ(initial_tab_count + new_tab_count, tab_count);
// Switch linearly between tabs.
ASSERT_TRUE(browser_proxy_->ActivateTab(0));
int final_tab_count = 0;
ASSERT_TRUE(browser_proxy_->GetTabCount(&final_tab_count));
for (int j = initial_tab_count; j < final_tab_count; ++j) {
ASSERT_TRUE(browser_proxy_->ActivateTab(j));
ASSERT_TRUE(browser_proxy_->WaitForTabToBecomeActive(j, 10000));
}
// Close the browser to force a dump of log.
bool application_closed = false;
EXPECT_TRUE(CloseBrowser(browser_proxy_.get(), &application_closed));
// Open the corresponding log file and collect average from the
// histogram stats generated for RenderWidgetHost_TabSwitchPaintDuration.
bool log_has_been_dumped = false;
std::string contents;
int max_tries = 20;
do {
log_has_been_dumped = file_util::ReadFileToString(log_file_name_,
&contents);
if (!log_has_been_dumped)
base::PlatformThread::Sleep(100);
} while (!log_has_been_dumped && max_tries--);
ASSERT_TRUE(log_has_been_dumped) << "Failed to read the log file";
// Parse the contents to get average.
int64 average = 0;
const std::string average_str("average = ");
std::string::size_type pos = contents.find(
"Histogram: MPArch.RWH_TabSwitchPaintDuration", 0);
std::string::size_type comma_pos;
std::string::size_type number_length;
ASSERT_NE(pos, std::string::npos) <<
"Histogram: MPArch.RWH_TabSwitchPaintDuration wasn't found\n" <<
contents;
// Get the average.
pos = contents.find(average_str, pos);
comma_pos = contents.find(",", pos);
pos += average_str.length();
number_length = comma_pos - pos;
average = atoi(contents.substr(pos, number_length).c_str());
// Print the average and standard deviation.
timings[i] = TimeDelta::FromMilliseconds(average);
// Clean up from the test run.
UITest::TearDown();
}
PrintTimings(label, timings, important);
}
protected:
// Opens new tabs. Returns the number of tabs opened.
int OpenTabs() {
// Add tabs.
static const char* files[] = { "espn.go.com", "bugzilla.mozilla.org",
"news.cnet.com", "www.amazon.com",
"kannada.chakradeo.net", "allegro.pl",
"ml.wikipedia.org", "www.bbc.co.uk",
"126.com", "www.altavista.com"};
int number_of_new_tabs_opened = 0;
FilePath file_name;
for (size_t i = 0; i < arraysize(files); ++i) {
file_name = path_prefix_;
file_name = file_name.AppendASCII(files[i]);
file_name = file_name.AppendASCII("index.html");
bool success =
browser_proxy_->AppendTab(net::FilePathToFileURL(file_name));
EXPECT_TRUE(success);
if (success)
number_of_new_tabs_opened++;
}
return number_of_new_tabs_opened;
}
FilePath path_prefix_;
FilePath log_file_name_;
scoped_refptr<BrowserProxy> browser_proxy_;
private:
void AddLaunchArguments() {
launch_arguments_.AppendSwitch(switches::kEnableLogging);
launch_arguments_.AppendSwitch(switches::kDumpHistogramsOnExit);
launch_arguments_.AppendSwitchASCII(switches::kLoggingLevel, "0");
}
DISALLOW_COPY_AND_ASSIGN(TabSwitchingUITest);
};
TEST_F(TabSwitchingUITest, TabSwitch) {
RunTabSwitchingUITest("t", true);
}
TEST_F(TabSwitchingUITest, TabSwitchRef) {
UseReferenceBuild();
RunTabSwitchingUITest("t_ref", true);
}
} // namespace
<commit_msg>Mark tab_switching_tests as FAILS_ on Windows. These tests have been failing consistently on XP and Vista Interactive Perf buildbots since before ~r98000. This is a revert of http://crrev.com/55709, which re-enabled these tests.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/threading/platform_thread.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
using base::TimeDelta;
namespace {
// This Automated UI test opens static files in different tabs in a proxy
// browser. After all the tabs have opened, it switches between tabs, and notes
// time taken for each switch. It then prints out the times on the console,
// with the aim that the page cycler parser can interpret these numbers to
// draw graphs for page cycler Tab Switching Performance.
class TabSwitchingUITest : public UIPerfTest {
public:
TabSwitchingUITest() {
PathService::Get(base::DIR_SOURCE_ROOT, &path_prefix_);
path_prefix_ = path_prefix_.AppendASCII("data");
path_prefix_ = path_prefix_.AppendASCII("tab_switching");
show_window_ = true;
}
void SetUp() {
// Set the log_file_name_ path according to the selected browser_directory_.
log_file_name_ = browser_directory_.AppendASCII("chrome_debug.log");
// Set the log file path for the browser test.
scoped_ptr<base::Environment> env(base::Environment::Create());
#if defined(OS_WIN)
env->SetVar(env_vars::kLogFileName, WideToUTF8(log_file_name_.value()));
#else
env->SetVar(env_vars::kLogFileName, log_file_name_.value());
#endif
// Add the necessary arguments to Chrome's launch command for these tests.
AddLaunchArguments();
// Run the rest of the UITest initialization.
UITest::SetUp();
}
static const int kNumCycles = 5;
void PrintTimings(const char* label, TimeDelta timings[kNumCycles],
bool important) {
std::string times;
for (int i = 0; i < kNumCycles; ++i)
base::StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList("times", "", label, times, "ms", important);
}
void RunTabSwitchingUITest(const char* label, bool important) {
// Shut down from window UITest sets up automatically.
UITest::TearDown();
TimeDelta timings[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
// Prepare for this test run.
SetUp();
// Create a browser proxy.
browser_proxy_ = automation()->GetBrowserWindow(0);
// Open all the tabs.
int initial_tab_count = 0;
ASSERT_TRUE(browser_proxy_->GetTabCount(&initial_tab_count));
int new_tab_count = OpenTabs();
int tab_count = -1;
ASSERT_TRUE(browser_proxy_->GetTabCount(&tab_count));
ASSERT_EQ(initial_tab_count + new_tab_count, tab_count);
// Switch linearly between tabs.
ASSERT_TRUE(browser_proxy_->ActivateTab(0));
int final_tab_count = 0;
ASSERT_TRUE(browser_proxy_->GetTabCount(&final_tab_count));
for (int j = initial_tab_count; j < final_tab_count; ++j) {
ASSERT_TRUE(browser_proxy_->ActivateTab(j));
ASSERT_TRUE(browser_proxy_->WaitForTabToBecomeActive(j, 10000));
}
// Close the browser to force a dump of log.
bool application_closed = false;
EXPECT_TRUE(CloseBrowser(browser_proxy_.get(), &application_closed));
// Open the corresponding log file and collect average from the
// histogram stats generated for RenderWidgetHost_TabSwitchPaintDuration.
bool log_has_been_dumped = false;
std::string contents;
int max_tries = 20;
do {
log_has_been_dumped = file_util::ReadFileToString(log_file_name_,
&contents);
if (!log_has_been_dumped)
base::PlatformThread::Sleep(100);
} while (!log_has_been_dumped && max_tries--);
ASSERT_TRUE(log_has_been_dumped) << "Failed to read the log file";
// Parse the contents to get average.
int64 average = 0;
const std::string average_str("average = ");
std::string::size_type pos = contents.find(
"Histogram: MPArch.RWH_TabSwitchPaintDuration", 0);
std::string::size_type comma_pos;
std::string::size_type number_length;
ASSERT_NE(pos, std::string::npos) <<
"Histogram: MPArch.RWH_TabSwitchPaintDuration wasn't found\n" <<
contents;
// Get the average.
pos = contents.find(average_str, pos);
comma_pos = contents.find(",", pos);
pos += average_str.length();
number_length = comma_pos - pos;
average = atoi(contents.substr(pos, number_length).c_str());
// Print the average and standard deviation.
timings[i] = TimeDelta::FromMilliseconds(average);
// Clean up from the test run.
UITest::TearDown();
}
PrintTimings(label, timings, important);
}
protected:
// Opens new tabs. Returns the number of tabs opened.
int OpenTabs() {
// Add tabs.
static const char* files[] = { "espn.go.com", "bugzilla.mozilla.org",
"news.cnet.com", "www.amazon.com",
"kannada.chakradeo.net", "allegro.pl",
"ml.wikipedia.org", "www.bbc.co.uk",
"126.com", "www.altavista.com"};
int number_of_new_tabs_opened = 0;
FilePath file_name;
for (size_t i = 0; i < arraysize(files); ++i) {
file_name = path_prefix_;
file_name = file_name.AppendASCII(files[i]);
file_name = file_name.AppendASCII("index.html");
bool success =
browser_proxy_->AppendTab(net::FilePathToFileURL(file_name));
EXPECT_TRUE(success);
if (success)
number_of_new_tabs_opened++;
}
return number_of_new_tabs_opened;
}
FilePath path_prefix_;
FilePath log_file_name_;
scoped_refptr<BrowserProxy> browser_proxy_;
private:
void AddLaunchArguments() {
launch_arguments_.AppendSwitch(switches::kEnableLogging);
launch_arguments_.AppendSwitch(switches::kDumpHistogramsOnExit);
launch_arguments_.AppendSwitchASCII(switches::kLoggingLevel, "0");
}
DISALLOW_COPY_AND_ASSIGN(TabSwitchingUITest);
};
#if defined(OS_WIN)
// Started failing with a webkit roll in r49936. See http://crbug.com/46751
#define MAYBE_TabSwitch FAILS_TabSwitch
#define MAYBE_TabSwitchRef FAILS_TabSwitchRef
#else
#define MAYBE_TabSwitch TabSwitch
#define MAYBE_TabSwitchRef TabSwitchRef
#endif
TEST_F(TabSwitchingUITest, MAYBE_TabSwitch) {
RunTabSwitchingUITest("t", true);
}
TEST_F(TabSwitchingUITest, MAYBE_TabSwitchRef) {
UseReferenceBuild();
RunTabSwitchingUITest("t_ref", true);
}
} // namespace
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 Platform.
*//*--------------------------------------------------------------------*/
#include "tcuX11Platform.hpp"
#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"
#if defined (DEQP_SUPPORT_GLX)
# include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
# include "tcuX11EglPlatform.hpp"
#endif
#include <sys/utsname.h>
namespace tcu
{
namespace x11
{
class X11GLPlatform : public glu::Platform
{
public:
void registerFactory (de::MovePtr<glu::ContextFactory> factory)
{
m_contextFactoryRegistry.registerFactory(factory.release());
}
};
class VulkanLibrary : public vk::Library
{
public:
VulkanLibrary (void)
: m_library ("libvulkan.so.1")
, m_driver (m_library)
{
}
const vk::PlatformInterface& getPlatformInterface (void) const
{
return m_driver;
}
private:
const tcu::DynamicFunctionLibrary m_library;
const vk::PlatformDriver m_driver;
};
class X11VulkanPlatform : public vk::Platform
{
public:
vk::Library* createLibrary (void) const
{
return new VulkanLibrary();
}
void describePlatform (std::ostream& dst) const
{
utsname sysInfo;
deMemset(&sysInfo, 0, sizeof(sysInfo));
if (uname(&sysInfo) != 0)
throw std::runtime_error("uname() failed");
dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
dst << "CPU: " << sysInfo.machine << "\n";
}
};
class X11Platform : public tcu::Platform
{
public:
X11Platform (void);
bool processEvents (void) { return !m_eventState.getQuitFlag(); }
const glu::Platform& getGLPlatform (void) const { return m_glPlatform; }
#if defined (DEQP_SUPPORT_EGL)
const eglu::Platform& getEGLPlatform (void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL
const vk::Platform& getVulkanPlatform (void) const { return m_vkPlatform; }
private:
EventState m_eventState;
#if defined (DEQP_SUPPORT_EGL)
x11::egl::Platform m_eglPlatform;
#endif // DEQP_SPPORT_EGL
X11GLPlatform m_glPlatform;
X11VulkanPlatform m_vkPlatform;
};
X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
: m_eglPlatform (m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}
} // x11
} // tcu
tcu::Platform* createPlatform (void)
{
return new tcu::x11::X11Platform();
}
<commit_msg>Implement getMemoryLimits() in X11 vulkan platform am: 1c143ce am: 017c035 am: b208dea<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 Platform.
*//*--------------------------------------------------------------------*/
#include "tcuX11Platform.hpp"
#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"
#if defined (DEQP_SUPPORT_GLX)
# include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
# include "tcuX11EglPlatform.hpp"
#endif
#include <sys/utsname.h>
namespace tcu
{
namespace x11
{
class X11GLPlatform : public glu::Platform
{
public:
void registerFactory (de::MovePtr<glu::ContextFactory> factory)
{
m_contextFactoryRegistry.registerFactory(factory.release());
}
};
class VulkanLibrary : public vk::Library
{
public:
VulkanLibrary (void)
: m_library ("libvulkan.so.1")
, m_driver (m_library)
{
}
const vk::PlatformInterface& getPlatformInterface (void) const
{
return m_driver;
}
private:
const tcu::DynamicFunctionLibrary m_library;
const vk::PlatformDriver m_driver;
};
class X11VulkanPlatform : public vk::Platform
{
public:
vk::Library* createLibrary (void) const
{
return new VulkanLibrary();
}
void describePlatform (std::ostream& dst) const
{
utsname sysInfo;
deMemset(&sysInfo, 0, sizeof(sysInfo));
if (uname(&sysInfo) != 0)
throw std::runtime_error("uname() failed");
dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
dst << "CPU: " << sysInfo.machine << "\n";
}
void getMemoryLimits (vk::PlatformMemoryLimits& limits) const
{
limits.totalSystemMemory = 256*1024*1024;
limits.totalDeviceLocalMemory = 128*1024*1024;
limits.deviceMemoryAllocationGranularity = 64*1024;
limits.devicePageSize = 4096;
limits.devicePageTableEntrySize = 8;
limits.devicePageTableHierarchyLevels = 3;
}
};
class X11Platform : public tcu::Platform
{
public:
X11Platform (void);
bool processEvents (void) { return !m_eventState.getQuitFlag(); }
const glu::Platform& getGLPlatform (void) const { return m_glPlatform; }
#if defined (DEQP_SUPPORT_EGL)
const eglu::Platform& getEGLPlatform (void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL
const vk::Platform& getVulkanPlatform (void) const { return m_vkPlatform; }
private:
EventState m_eventState;
#if defined (DEQP_SUPPORT_EGL)
x11::egl::Platform m_eglPlatform;
#endif // DEQP_SPPORT_EGL
X11GLPlatform m_glPlatform;
X11VulkanPlatform m_vkPlatform;
};
X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
: m_eglPlatform (m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}
} // x11
} // tcu
tcu::Platform* createPlatform (void)
{
return new tcu::x11::X11Platform();
}
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 Platform.
*//*--------------------------------------------------------------------*/
#include "tcuX11Platform.hpp"
#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"
#if defined (DEQP_SUPPORT_GLX)
# include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
# include "tcuX11EglPlatform.hpp"
#endif
#include <sys/utsname.h>
namespace tcu
{
namespace x11
{
class X11GLPlatform : public glu::Platform
{
public:
void registerFactory (de::MovePtr<glu::ContextFactory> factory)
{
m_contextFactoryRegistry.registerFactory(factory.release());
}
};
class VulkanLibrary : public vk::Library
{
public:
VulkanLibrary (void)
: m_library ("libvulkan-1.so")
, m_driver (m_library)
{
}
const vk::PlatformInterface& getPlatformInterface (void) const
{
return m_driver;
}
private:
const tcu::DynamicFunctionLibrary m_library;
const vk::PlatformDriver m_driver;
};
class X11VulkanPlatform : public vk::Platform
{
public:
vk::Library* createLibrary (void) const
{
return new VulkanLibrary();
}
void describePlatform (std::ostream& dst) const
{
utsname sysInfo;
deMemset(&sysInfo, 0, sizeof(sysInfo));
if (uname(&sysInfo) != 0)
throw std::runtime_error("uname() failed");
dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
dst << "CPU: " << sysInfo.machine << "\n";
}
};
class X11Platform : public tcu::Platform
{
public:
X11Platform (void);
bool processEvents (void) { return !m_eventState.getQuitFlag(); }
const glu::Platform& getGLPlatform (void) const { return m_glPlatform; }
#if defined (DEQP_SUPPORT_EGL)
const eglu::Platform& getEGLPlatform (void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL
const vk::Platform& getVulkanPlatform (void) const { return m_vkPlatform; }
private:
EventState m_eventState;
#if defined (DEQP_SUPPORT_EGL)
x11::egl::Platform m_eglPlatform;
#endif // DEQP_SPPORT_EGL
X11GLPlatform m_glPlatform;
X11VulkanPlatform m_vkPlatform;
};
X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
: m_eglPlatform (m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}
} // x11
} // tcu
tcu::Platform* createPlatform (void)
{
return new tcu::x11::X11Platform();
}
<commit_msg>Use the correct library name on Linux<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief X11 Platform.
*//*--------------------------------------------------------------------*/
#include "tcuX11Platform.hpp"
#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"
#if defined (DEQP_SUPPORT_GLX)
# include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
# include "tcuX11EglPlatform.hpp"
#endif
#include <sys/utsname.h>
namespace tcu
{
namespace x11
{
class X11GLPlatform : public glu::Platform
{
public:
void registerFactory (de::MovePtr<glu::ContextFactory> factory)
{
m_contextFactoryRegistry.registerFactory(factory.release());
}
};
class VulkanLibrary : public vk::Library
{
public:
VulkanLibrary (void)
: m_library ("libvulkan.so.1")
, m_driver (m_library)
{
}
const vk::PlatformInterface& getPlatformInterface (void) const
{
return m_driver;
}
private:
const tcu::DynamicFunctionLibrary m_library;
const vk::PlatformDriver m_driver;
};
class X11VulkanPlatform : public vk::Platform
{
public:
vk::Library* createLibrary (void) const
{
return new VulkanLibrary();
}
void describePlatform (std::ostream& dst) const
{
utsname sysInfo;
deMemset(&sysInfo, 0, sizeof(sysInfo));
if (uname(&sysInfo) != 0)
throw std::runtime_error("uname() failed");
dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
dst << "CPU: " << sysInfo.machine << "\n";
}
};
class X11Platform : public tcu::Platform
{
public:
X11Platform (void);
bool processEvents (void) { return !m_eventState.getQuitFlag(); }
const glu::Platform& getGLPlatform (void) const { return m_glPlatform; }
#if defined (DEQP_SUPPORT_EGL)
const eglu::Platform& getEGLPlatform (void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL
const vk::Platform& getVulkanPlatform (void) const { return m_vkPlatform; }
private:
EventState m_eventState;
#if defined (DEQP_SUPPORT_EGL)
x11::egl::Platform m_eglPlatform;
#endif // DEQP_SPPORT_EGL
X11GLPlatform m_glPlatform;
X11VulkanPlatform m_vkPlatform;
};
X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
: m_eglPlatform (m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}
} // x11
} // tcu
tcu::Platform* createPlatform (void)
{
return new tcu::x11::X11Platform();
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "AddMaterialAction.h"
#include "Parser.h"
#include "MProblem.h"
template<>
InputParameters validParams<AddMaterialAction>()
{
return validParams<MooseObjectAction>();
}
AddMaterialAction::AddMaterialAction(const std::string & name, InputParameters params) :
MooseObjectAction(name, params)
{
}
void
AddMaterialAction::act()
{
_parser_handle._problem->addMaterial(_type, getShortName(), _moose_object_pars);
}
<commit_msg>Adding missing forward declaration of validParam for VolumetricModel (+ enabling volumetric tests in BISON)<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "AddMaterialAction.h"
#include "Parser.h"
#include "MProblem.h"
template<>
InputParameters validParams<AddMaterialAction>()
{
return validParams<MooseObjectAction>();
}
AddMaterialAction::AddMaterialAction(const std::string & name, InputParameters params) :
MooseObjectAction(name, params)
{
}
void
AddMaterialAction::act()
{
_parser_handle._problem->addMaterial(_type, getShortName(), _moose_object_pars);
}
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "FVBoundaryCondition.h"
#include "Problem.h"
#include "SystemBase.h"
#include "MooseVariableFV.h"
namespace
{
SystemBase &
changeSystem(const InputParameters & params_in, MooseVariableFV<Real> & fv_var)
{
SystemBase & var_sys = fv_var.sys();
auto & params = const_cast<InputParameters &>(params_in);
params.set<SystemBase *>("_sys") = &var_sys;
return var_sys;
}
}
InputParameters
FVBoundaryCondition::validParams()
{
InputParameters params = MooseObject::validParams();
params += TransientInterface::validParams();
params += BoundaryRestrictableRequired::validParams();
params += TaggingInterface::validParams();
params += FunctorInterface::validParams();
params.addRequiredParam<NonlinearVariableName>(
"variable", "The name of the variable that this boundary condition applies to");
params.addParam<bool>("use_displaced_mesh",
false,
"Whether or not this object should use the "
"displaced mesh for computation. Note that "
"in the case this is true but no "
"displacements are provided in the Mesh block "
"the undisplaced mesh will still be used.");
params.addParamNamesToGroup("use_displaced_mesh", "Advanced");
params.addCoupledVar("displacements", "The displacements");
params.declareControllable("enable");
params.registerBase("FVBoundaryCondition");
return params;
}
FVBoundaryCondition::FVBoundaryCondition(const InputParameters & parameters)
: MooseObject(parameters),
BoundaryRestrictableRequired(this, false),
SetupInterface(this),
FunctionInterface(this),
DistributionInterface(this),
UserObjectInterface(this),
TransientInterface(this),
PostprocessorInterface(this),
VectorPostprocessorInterface(this),
GeometricSearchInterface(this),
MeshChangedInterface(parameters),
TaggingInterface(this),
MooseVariableInterface<Real>(this,
false,
"variable",
Moose::VarKindType::VAR_ANY,
Moose::VarFieldType::VAR_FIELD_STANDARD),
FunctorInterface(this),
_var(*mooseVariableFV()),
_subproblem(*getCheckedPointerParam<SubProblem *>("_subproblem")),
_fv_problem(*getCheckedPointerParam<FVProblemBase *>("_fe_problem_base")),
_sys(changeSystem(parameters, _var)),
_tid(parameters.get<THREAD_ID>("_tid")),
_assembly(_subproblem.assembly(_tid)),
_mesh(_subproblem.mesh())
{
_subproblem.haveADObjects(true);
addMooseVariableDependency(&_var);
if (getParam<bool>("use_displaced_mesh"))
paramError("use_displaced_mesh", "FV boundary conditions do not yet support displaced mesh");
}
Moose::SingleSidedFaceArg
FVBoundaryCondition::singleSidedFaceArg(const FaceInfo * fi,
const Moose::FV::LimiterType limiter_type,
const bool correct_skewness) const
{
if (!fi)
fi = _face_info;
const bool use_elem = fi->faceType(_var.name()) == FaceInfo::VarFaceNeighbors::ELEM;
if (use_elem)
return {fi, limiter_type, true, correct_skewness, correct_skewness, fi->elem().subdomain_id()};
else
return {fi,
limiter_type,
true,
correct_skewness,
correct_skewness,
fi->neighborPtr()->subdomain_id()};
}
<commit_msg>Forbid FV boundary conditions on aux variables since we no longer use that, refs #15836<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "FVBoundaryCondition.h"
#include "Problem.h"
#include "SystemBase.h"
#include "MooseVariableFV.h"
namespace
{
SystemBase &
changeSystem(const InputParameters & params_in, MooseVariableFV<Real> & fv_var)
{
SystemBase & var_sys = fv_var.sys();
auto & params = const_cast<InputParameters &>(params_in);
params.set<SystemBase *>("_sys") = &var_sys;
return var_sys;
}
}
InputParameters
FVBoundaryCondition::validParams()
{
InputParameters params = MooseObject::validParams();
params += TransientInterface::validParams();
params += BoundaryRestrictableRequired::validParams();
params += TaggingInterface::validParams();
params += FunctorInterface::validParams();
params.addRequiredParam<NonlinearVariableName>(
"variable", "The name of the variable that this boundary condition applies to");
params.addParam<bool>("use_displaced_mesh",
false,
"Whether or not this object should use the "
"displaced mesh for computation. Note that "
"in the case this is true but no "
"displacements are provided in the Mesh block "
"the undisplaced mesh will still be used.");
params.addParamNamesToGroup("use_displaced_mesh", "Advanced");
params.addCoupledVar("displacements", "The displacements");
params.declareControllable("enable");
params.registerBase("FVBoundaryCondition");
return params;
}
FVBoundaryCondition::FVBoundaryCondition(const InputParameters & parameters)
: MooseObject(parameters),
BoundaryRestrictableRequired(this, false),
SetupInterface(this),
FunctionInterface(this),
DistributionInterface(this),
UserObjectInterface(this),
TransientInterface(this),
PostprocessorInterface(this),
VectorPostprocessorInterface(this),
GeometricSearchInterface(this),
MeshChangedInterface(parameters),
TaggingInterface(this),
MooseVariableInterface<Real>(this,
false,
"variable",
Moose::VarKindType::VAR_ANY,
Moose::VarFieldType::VAR_FIELD_STANDARD),
FunctorInterface(this),
_var(*mooseVariableFV()),
_subproblem(*getCheckedPointerParam<SubProblem *>("_subproblem")),
_fv_problem(*getCheckedPointerParam<FVProblemBase *>("_fe_problem_base")),
_sys(changeSystem(parameters, _var)),
_tid(parameters.get<THREAD_ID>("_tid")),
_assembly(_subproblem.assembly(_tid)),
_mesh(_subproblem.mesh())
{
_subproblem.haveADObjects(true);
addMooseVariableDependency(&_var);
if (getParam<bool>("use_displaced_mesh"))
paramError("use_displaced_mesh", "FV boundary conditions do not yet support displaced mesh");
if (_var.kind() == Moose::VarKindType::VAR_AUXILIARY)
paramError("variable",
"There should not be a need to specify boundary conditions for auxiliary variables.");
}
Moose::SingleSidedFaceArg
FVBoundaryCondition::singleSidedFaceArg(const FaceInfo * fi,
const Moose::FV::LimiterType limiter_type,
const bool correct_skewness) const
{
if (!fi)
fi = _face_info;
const bool use_elem = fi->faceType(_var.name()) == FaceInfo::VarFaceNeighbors::ELEM;
if (use_elem)
return {fi, limiter_type, true, correct_skewness, correct_skewness, fi->elem().subdomain_id()};
else
return {fi,
limiter_type,
true,
correct_skewness,
correct_skewness,
fi->neighborPtr()->subdomain_id()};
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "RestartableDataIO.h"
#include "MooseUtils.h"
#include "RestartableData.h"
#include "FEProblem.h"
#include "MooseApp.h"
#include <stdio.h>
RestartableDataIO::RestartableDataIO(FEProblem & fe_problem) :
_fe_problem(fe_problem)
{
_in_file_handles.resize(libMesh::n_threads());
}
RestartableDataIO::~RestartableDataIO()
{
unsigned int n_threads = libMesh::n_threads();
for (unsigned int tid=0; tid<n_threads; tid++)
delete _in_file_handles[tid];
}
void
RestartableDataIO::writeRestartableData(std::string base_file_name, const RestartableDatas & restartable_datas, std::set<std::string> & /*_recoverable_data*/)
{
unsigned int n_threads = libMesh::n_threads();
processor_id_type n_procs = _fe_problem.n_processors();
processor_id_type proc_id = _fe_problem.processor_id();
for (unsigned int tid=0; tid<n_threads; tid++)
{
const std::map<std::string, RestartableDataValue *> & restartable_data = restartable_datas[tid];
const unsigned int file_version = 1;
std::ofstream out;
std::ostringstream file_name_stream;
file_name_stream << base_file_name;
file_name_stream << "-" << proc_id;
if (n_threads > 1)
file_name_stream << "-" << tid;
std::string file_name = file_name_stream.str();
{ // Write out header
out.open(file_name.c_str(), std::ios::out | std::ios::binary);
char id[2];
// header
id[0] = 'R';
id[1] = 'D';
out.write(id, 2);
out.write((const char *)&file_version, sizeof(file_version));
out.write((const char *)&n_procs, sizeof(n_procs));
out.write((const char *)&n_threads, sizeof(n_threads));
// number of RestartableData
unsigned int n_data = restartable_data.size();
out.write((const char *) &n_data, sizeof(n_data));
// data names
for (std::map<std::string, RestartableDataValue *>::const_iterator it = restartable_data.begin();
it != restartable_data.end();
++it)
{
std::string name = it->first;
out.write(name.c_str(), name.length() + 1); // trailing 0!
}
}
{
std::ostringstream data_blk;
for (std::map<std::string, RestartableDataValue *>::const_iterator it = restartable_data.begin();
it != restartable_data.end();
++it)
{
// Moose::out<<"Storing "<<it->first<<std::endl;
std::ostringstream data;
it->second->store(data);
// Store the size of the data then the data
unsigned int data_size = data.tellp();
data_blk.write((const char *) &data_size, sizeof(data_size));
data_blk << data.str();
}
// Write out this proc's block size
unsigned int data_blk_size = data_blk.tellp();
out.write((const char *) &data_blk_size, sizeof(data_blk_size));
// Write out the values
out << data_blk.str();
out.close();
}
}
}
void
RestartableDataIO::readRestartableDataHeader(std::string base_file_name)
{
unsigned int n_threads = libMesh::n_threads();
processor_id_type n_procs = _fe_problem.n_processors();
processor_id_type proc_id = _fe_problem.processor_id();
for (unsigned int tid=0; tid<n_threads; tid++)
{
std::ostringstream file_name_stream;
file_name_stream << base_file_name;
file_name_stream << "-" << proc_id;
if (n_threads > 1)
file_name_stream << "-" << tid;
std::string file_name = file_name_stream.str();
MooseUtils::checkFileReadable(file_name);
const unsigned int file_version = 1;
mooseAssert(_in_file_handles[tid] == NULL, "Looks like you might be leaking in RestartableDataIO.C");
_in_file_handles[tid] = new std::ifstream(file_name.c_str(), std::ios::in | std::ios::binary);
// header
char id[2];
_in_file_handles[tid]->read(id, 2);
unsigned int this_file_version;
_in_file_handles[tid]->read((char *)&this_file_version, sizeof(this_file_version));
processor_id_type this_n_procs = 0;
unsigned int this_n_threads = 0;
_in_file_handles[tid]->read((char *)&this_n_procs, sizeof(this_n_procs));
_in_file_handles[tid]->read((char *)&this_n_threads, sizeof(this_n_threads));
// check the header
if (id[0] != 'R' || id[1] != 'D')
mooseError("Corrupted restartable data file!");
// check the file version
if (this_file_version > file_version)
mooseError("Trying to restart from a newer file version - you need to update MOOSE");
if (this_file_version < file_version)
mooseError("Trying to restart from an older file version - you need to checkout an older version of MOOSE.");
if (this_n_procs != n_procs)
mooseError("Cannot restart using a different number of processors!");
if (this_n_threads != n_threads)
mooseError("Cannot restart using a different number of threads!");
}
}
void
RestartableDataIO::readRestartableData(RestartableDatas & restartable_datas, std::set<std::string> & _recoverable_data)
{
bool recovering = _fe_problem.getMooseApp().isRecovering();
unsigned int n_threads = libMesh::n_threads();
std::vector<std::string> ignored_data;
// std::vector<unsigned int> ignored_data_is_recoverable;
for (unsigned int tid=0; tid<n_threads; tid++)
{
std::map<std::string, RestartableDataValue *> & restartable_data = restartable_datas[tid];
if (!_in_file_handles[tid]->is_open())
mooseError("In RestartableDataIO: Need to call readRestartableDataHeader() before calling readRestartableData()");
// number of data
unsigned int n_data = 0;
_in_file_handles[tid]->read((char *) &n_data, sizeof(n_data));
// data names
std::vector<std::string> data_names(n_data);
for (unsigned int i=0; i < n_data; i++)
{
std::string data_name;
char ch = 0;
do {
_in_file_handles[tid]->read(&ch, 1);
if (ch != '\0')
data_name += ch;
} while (ch != '\0');
data_names[i] = data_name;
}
// Grab this processor's block size
unsigned int data_blk_size = 0;
_in_file_handles[tid]->read((char *) &data_blk_size, sizeof(data_blk_size));
for (unsigned int i=0; i < n_data; i++)
{
std::string current_name = data_names[i];
unsigned int data_size = 0;
_in_file_handles[tid]->read((char *) &data_size, sizeof(data_size));
// Determine if the current data is recoverable
bool is_data_restartable = restartable_data.find(current_name) != restartable_data.end();
bool is_data_recoverable = _recoverable_data.find(current_name) != _recoverable_data.end();
if (is_data_restartable // Only restore values if they're currently being used
&& (recovering || !is_data_recoverable)) // Only read this value if we're either recovering or this hasn't been specified to be recovery only data
{
// Moose::out<<"Loading "<<current_name<<std::endl;
RestartableDataValue * current_data = restartable_data[current_name];
current_data->load(*_in_file_handles[tid]);
}
else
{
// Skip this piece of data and do not report if restarting and recoverable data is not used
_in_file_handles[tid]->seekg(data_size, std::ios_base::cur);
if (recovering && !is_data_recoverable)
ignored_data.push_back(current_name);
}
}
_in_file_handles[tid]->close();
}
// Procdue a warning if restarting and restart data is being skipped
// Do not produce the warning with recovery b/c in cases the parent defines a something as recoverable,
// but only certain child classes use the value in recovery (i.e., FileOutput::_num_files is needed by Exodus but not Checkpoint)
if (ignored_data.size() && !recovering)
{
std::ostringstream names;
for (unsigned int i=0; i<ignored_data.size(); i++)
names << ignored_data[i] << "\n";
mooseWarning("The following RestartableData was found in restart file but is being ignored:\n" << names.str());
}
}
<commit_msg>Fixing a typo (refs #3792)<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "RestartableDataIO.h"
#include "MooseUtils.h"
#include "RestartableData.h"
#include "FEProblem.h"
#include "MooseApp.h"
#include <stdio.h>
RestartableDataIO::RestartableDataIO(FEProblem & fe_problem) :
_fe_problem(fe_problem)
{
_in_file_handles.resize(libMesh::n_threads());
}
RestartableDataIO::~RestartableDataIO()
{
unsigned int n_threads = libMesh::n_threads();
for (unsigned int tid=0; tid<n_threads; tid++)
delete _in_file_handles[tid];
}
void
RestartableDataIO::writeRestartableData(std::string base_file_name, const RestartableDatas & restartable_datas, std::set<std::string> & /*_recoverable_data*/)
{
unsigned int n_threads = libMesh::n_threads();
processor_id_type n_procs = _fe_problem.n_processors();
processor_id_type proc_id = _fe_problem.processor_id();
for (unsigned int tid=0; tid<n_threads; tid++)
{
const std::map<std::string, RestartableDataValue *> & restartable_data = restartable_datas[tid];
const unsigned int file_version = 1;
std::ofstream out;
std::ostringstream file_name_stream;
file_name_stream << base_file_name;
file_name_stream << "-" << proc_id;
if (n_threads > 1)
file_name_stream << "-" << tid;
std::string file_name = file_name_stream.str();
{ // Write out header
out.open(file_name.c_str(), std::ios::out | std::ios::binary);
char id[2];
// header
id[0] = 'R';
id[1] = 'D';
out.write(id, 2);
out.write((const char *)&file_version, sizeof(file_version));
out.write((const char *)&n_procs, sizeof(n_procs));
out.write((const char *)&n_threads, sizeof(n_threads));
// number of RestartableData
unsigned int n_data = restartable_data.size();
out.write((const char *) &n_data, sizeof(n_data));
// data names
for (std::map<std::string, RestartableDataValue *>::const_iterator it = restartable_data.begin();
it != restartable_data.end();
++it)
{
std::string name = it->first;
out.write(name.c_str(), name.length() + 1); // trailing 0!
}
}
{
std::ostringstream data_blk;
for (std::map<std::string, RestartableDataValue *>::const_iterator it = restartable_data.begin();
it != restartable_data.end();
++it)
{
// Moose::out<<"Storing "<<it->first<<std::endl;
std::ostringstream data;
it->second->store(data);
// Store the size of the data then the data
unsigned int data_size = data.tellp();
data_blk.write((const char *) &data_size, sizeof(data_size));
data_blk << data.str();
}
// Write out this proc's block size
unsigned int data_blk_size = data_blk.tellp();
out.write((const char *) &data_blk_size, sizeof(data_blk_size));
// Write out the values
out << data_blk.str();
out.close();
}
}
}
void
RestartableDataIO::readRestartableDataHeader(std::string base_file_name)
{
unsigned int n_threads = libMesh::n_threads();
processor_id_type n_procs = _fe_problem.n_processors();
processor_id_type proc_id = _fe_problem.processor_id();
for (unsigned int tid=0; tid<n_threads; tid++)
{
std::ostringstream file_name_stream;
file_name_stream << base_file_name;
file_name_stream << "-" << proc_id;
if (n_threads > 1)
file_name_stream << "-" << tid;
std::string file_name = file_name_stream.str();
MooseUtils::checkFileReadable(file_name);
const unsigned int file_version = 1;
mooseAssert(_in_file_handles[tid] == NULL, "Looks like you might be leaking in RestartableDataIO.C");
_in_file_handles[tid] = new std::ifstream(file_name.c_str(), std::ios::in | std::ios::binary);
// header
char id[2];
_in_file_handles[tid]->read(id, 2);
unsigned int this_file_version;
_in_file_handles[tid]->read((char *)&this_file_version, sizeof(this_file_version));
processor_id_type this_n_procs = 0;
unsigned int this_n_threads = 0;
_in_file_handles[tid]->read((char *)&this_n_procs, sizeof(this_n_procs));
_in_file_handles[tid]->read((char *)&this_n_threads, sizeof(this_n_threads));
// check the header
if (id[0] != 'R' || id[1] != 'D')
mooseError("Corrupted restartable data file!");
// check the file version
if (this_file_version > file_version)
mooseError("Trying to restart from a newer file version - you need to update MOOSE");
if (this_file_version < file_version)
mooseError("Trying to restart from an older file version - you need to checkout an older version of MOOSE.");
if (this_n_procs != n_procs)
mooseError("Cannot restart using a different number of processors!");
if (this_n_threads != n_threads)
mooseError("Cannot restart using a different number of threads!");
}
}
void
RestartableDataIO::readRestartableData(RestartableDatas & restartable_datas, std::set<std::string> & _recoverable_data)
{
bool recovering = _fe_problem.getMooseApp().isRecovering();
unsigned int n_threads = libMesh::n_threads();
std::vector<std::string> ignored_data;
// std::vector<unsigned int> ignored_data_is_recoverable;
for (unsigned int tid=0; tid<n_threads; tid++)
{
std::map<std::string, RestartableDataValue *> & restartable_data = restartable_datas[tid];
if (!_in_file_handles[tid]->is_open())
mooseError("In RestartableDataIO: Need to call readRestartableDataHeader() before calling readRestartableData()");
// number of data
unsigned int n_data = 0;
_in_file_handles[tid]->read((char *) &n_data, sizeof(n_data));
// data names
std::vector<std::string> data_names(n_data);
for (unsigned int i=0; i < n_data; i++)
{
std::string data_name;
char ch = 0;
do {
_in_file_handles[tid]->read(&ch, 1);
if (ch != '\0')
data_name += ch;
} while (ch != '\0');
data_names[i] = data_name;
}
// Grab this processor's block size
unsigned int data_blk_size = 0;
_in_file_handles[tid]->read((char *) &data_blk_size, sizeof(data_blk_size));
for (unsigned int i=0; i < n_data; i++)
{
std::string current_name = data_names[i];
unsigned int data_size = 0;
_in_file_handles[tid]->read((char *) &data_size, sizeof(data_size));
// Determine if the current data is recoverable
bool is_data_restartable = restartable_data.find(current_name) != restartable_data.end();
bool is_data_recoverable = _recoverable_data.find(current_name) != _recoverable_data.end();
if (is_data_restartable // Only restore values if they're currently being used
&& (recovering || !is_data_recoverable)) // Only read this value if we're either recovering or this hasn't been specified to be recovery only data
{
// Moose::out<<"Loading "<<current_name<<std::endl;
RestartableDataValue * current_data = restartable_data[current_name];
current_data->load(*_in_file_handles[tid]);
}
else
{
// Skip this piece of data and do not report if restarting and recoverable data is not used
_in_file_handles[tid]->seekg(data_size, std::ios_base::cur);
if (recovering && !is_data_recoverable)
ignored_data.push_back(current_name);
}
}
_in_file_handles[tid]->close();
}
// Produce a warning if restarting and restart data is being skipped
// Do not produce the warning with recovery b/c in cases the parent defines a something as recoverable,
// but only certain child classes use the value in recovery (i.e., FileOutput::_num_files is needed by Exodus but not Checkpoint)
if (ignored_data.size() && !recovering)
{
std::ostringstream names;
for (unsigned int i=0; i<ignored_data.size(); i++)
names << ignored_data[i] << "\n";
mooseWarning("The following RestartableData was found in restart file but is being ignored:\n" << names.str());
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "lua_vm.h"
#include "blogger.h"
#include "luanode.h"
#include <assert.h>
#include <string>
long CLuaVM::s_nextID = 0;
//////////////////////////////////////////////////////////////////////
// Constructor
CLuaVM::CLuaVM(/*IHostVirtualMachine& vmHost*/) :
//m_vmHost(vmHost),
////Pm_ID(InterlockedIncrement(&s_nextID)),
m_ID(++s_nextID),
////Pm_timestampLastUsed(GetTickCount())
m_timestampLastUsed(0) // until no equivalent function available
{
LogDebug("CLuaVM::CLuaVM (%p)", this);
lua_atpanic(m_L, OnPanic);
}
//////////////////////////////////////////////////////////////////////
// Destructor
CLuaVM::~CLuaVM() {
LogDebug("CLuaVM::~CLuaVM (%p)", this);
}
//////////////////////////////////////////////////////////////////////////
///
long CLuaVM::GetID() const {
return m_ID;
}
//////////////////////////////////////////////////////////////////////////
///
void CLuaVM::UpdateTimestampLastUse() {
////Pm_timestampLastUsed = GetTickCount();
m_timestampLastUsed = 0;
}
unsigned int CLuaVM::GetTimestampOfLastUse() const {
return m_timestampLastUsed;
}
//////////////////////////////////////////////////////////////////////////
/// If neccesarry, add additional stuff here
bool CLuaVM::SetupEnvironment() {
//lua_State* L = m_L;
return true;
}
//////////////////////////////////////////////////////////////////////////
///
int CLuaVM::OnPanic(lua_State* L) {
LogFatal("PANIC!!!!\r\n%s", lua_tostring(L, -1));
return 0;
}
//////////////////////////////////////////////////////////////////////////
/// Logs a stack trace with the available information
int CLuaVM::OnError(bool hasStackTrace) const {
std::string errorMessage;
if(hasStackTrace) {
if(lua_isstring(m_L, -1)) {
errorMessage = lua_tostring(m_L, -1);
errorMessage += "\r\n";
}
else {
errorMessage = "(error object is not a string)";
}
}
else {
if(lua_isstring(m_L, -1)) {
errorMessage = lua_tostring(m_L, -1);
errorMessage += "\r\n";
}
errorMessage += "Stack Traceback\n===============\n\r";
// TODO: add something meaningfull here ?
//errorMessage += InternalStackTrace(m_L, 0, true);
}
if(LuaNode::FatalError(m_L, errorMessage.c_str())) {
return 1;
}
lua_getfield(m_L, LUA_GLOBALSINDEX, "console");
if(lua_istable(m_L, -1)) {
lua_getfield(m_L, -1, "error");
if(lua_type(m_L, -1) == LUA_TFUNCTION) {
lua_pushstring(m_L, "%s");
lua_pushlstring(m_L, errorMessage.c_str(), errorMessage.length());
lua_call(m_L, 2, 0);
}
else {
fprintf(stderr, "%s\n", errorMessage.c_str());
lua_pop(m_L, 1);
}
}
else {
fprintf(stderr, "%s\n", errorMessage.c_str());
}
lua_pop(m_L, 1);
//LogError("%s", errorMessage.c_str());
return 1;
}
<commit_msg>Log the error, in case we're daemonized and we miss the output of stderr<commit_after>#include "stdafx.h"
#include "lua_vm.h"
#include "blogger.h"
#include "luanode.h"
#include <assert.h>
#include <string>
long CLuaVM::s_nextID = 0;
//////////////////////////////////////////////////////////////////////
// Constructor
CLuaVM::CLuaVM(/*IHostVirtualMachine& vmHost*/) :
//m_vmHost(vmHost),
////Pm_ID(InterlockedIncrement(&s_nextID)),
m_ID(++s_nextID),
////Pm_timestampLastUsed(GetTickCount())
m_timestampLastUsed(0) // until no equivalent function available
{
LogDebug("CLuaVM::CLuaVM (%p)", this);
lua_atpanic(m_L, OnPanic);
}
//////////////////////////////////////////////////////////////////////
// Destructor
CLuaVM::~CLuaVM() {
LogDebug("CLuaVM::~CLuaVM (%p)", this);
}
//////////////////////////////////////////////////////////////////////////
///
long CLuaVM::GetID() const {
return m_ID;
}
//////////////////////////////////////////////////////////////////////////
///
void CLuaVM::UpdateTimestampLastUse() {
////Pm_timestampLastUsed = GetTickCount();
m_timestampLastUsed = 0;
}
unsigned int CLuaVM::GetTimestampOfLastUse() const {
return m_timestampLastUsed;
}
//////////////////////////////////////////////////////////////////////////
/// If neccesarry, add additional stuff here
bool CLuaVM::SetupEnvironment() {
//lua_State* L = m_L;
return true;
}
//////////////////////////////////////////////////////////////////////////
///
int CLuaVM::OnPanic(lua_State* L) {
LogFatal("PANIC!!!!\r\n%s", lua_tostring(L, -1));
return 0;
}
//////////////////////////////////////////////////////////////////////////
/// Logs a stack trace with the available information
int CLuaVM::OnError(bool hasStackTrace) const {
std::string errorMessage;
if(hasStackTrace) {
if(lua_isstring(m_L, -1)) {
errorMessage = lua_tostring(m_L, -1);
errorMessage += "\r\n";
}
else {
errorMessage = "(error object is not a string)";
}
}
else {
if(lua_isstring(m_L, -1)) {
errorMessage = lua_tostring(m_L, -1);
errorMessage += "\r\n";
}
errorMessage += "Stack Traceback\n===============\n\r";
// TODO: add something meaningfull here ?
//errorMessage += InternalStackTrace(m_L, 0, true);
}
if(LuaNode::FatalError(m_L, errorMessage.c_str())) {
return 1;
}
lua_getfield(m_L, LUA_GLOBALSINDEX, "console");
if(lua_istable(m_L, -1)) {
lua_getfield(m_L, -1, "error");
if(lua_type(m_L, -1) == LUA_TFUNCTION) {
lua_pushstring(m_L, "%s");
lua_pushlstring(m_L, errorMessage.c_str(), errorMessage.length());
lua_call(m_L, 2, 0);
}
else {
fprintf(stderr, "%s\n", errorMessage.c_str());
lua_pop(m_L, 1);
}
}
else {
fprintf(stderr, "%s\n", errorMessage.c_str());
}
lua_pop(m_L, 1);
LogError("%s", errorMessage.c_str());
return 1;
}
<|endoftext|>
|
<commit_before>// Copyright 2011 Google Inc. 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 "metrics.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <sys/time.h>
#else
#include <windows.h>
#endif
#include "util.h"
Metrics* g_metrics = NULL;
namespace {
#ifndef _WIN32
/// Compute a platform-specific high-res timer value that fits into an int64.
int64_t HighResTimer() {
timeval tv;
if (gettimeofday(&tv, NULL) < 0)
Fatal("gettimeofday: %s", strerror(errno));
return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec;
}
/// Convert a delta of HighResTimer() values to microseconds.
int64_t TimerToMicros(int64_t dt) {
// No conversion necessary.
return dt;
}
#else
int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) {
return ((int64_t)i.HighPart) << 32 | i.LowPart;
}
int64_t HighResTimer() {
LARGE_INTEGER counter;
if (!QueryPerformanceCounter(&counter))
Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str());
return LargeIntegerToInt64(counter);
}
int64_t TimerToMicros(int64_t dt) {
static int64_t ticks_per_sec = 0;
if (!ticks_per_sec) {
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq))
Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str());
ticks_per_sec = LargeIntegerToInt64(freq);
}
// dt is in ticks. We want microseconds.
return (dt * 1000000) / ticks_per_sec;
}
#endif
} // anonymous namespace
ScopedMetric::ScopedMetric(Metric* metric) {
metric_ = metric;
if (!metric_)
return;
start_ = HighResTimer();
}
ScopedMetric::~ScopedMetric() {
if (!metric_)
return;
metric_->count++;
int64_t dt = TimerToMicros(HighResTimer() - start_);
metric_->sum += dt;
}
Metric* Metrics::NewMetric(const string& name) {
Metric* metric = new Metric;
metric->name = name;
metric->count = 0;
metric->sum = 0;
metrics_.push_back(metric);
return metric;
}
void Metrics::Report() {
int width = 0;
for (vector<Metric*>::iterator i = metrics_.begin();
i != metrics_.end(); ++i) {
width = max((int)(*i)->name.size(), width);
}
printf("%-*s\t%-6s\t%9s\t%s\n", width,
"metric", "count", "total (ms)" , "avg (us)");
for (vector<Metric*>::iterator i = metrics_.begin();
i != metrics_.end(); ++i) {
Metric* metric = *i;
double total = metric->sum / (double)1000;
double avg = metric->sum / (double)metric->count;
printf("%-*s\t%-6d\t%-8.1f\t%.1f\n", width, metric->name.c_str(),
metric->count, total, avg);
}
}
<commit_msg>Switch the order of total and avg columns in -d stats output.<commit_after>// Copyright 2011 Google Inc. 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 "metrics.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <sys/time.h>
#else
#include <windows.h>
#endif
#include "util.h"
Metrics* g_metrics = NULL;
namespace {
#ifndef _WIN32
/// Compute a platform-specific high-res timer value that fits into an int64.
int64_t HighResTimer() {
timeval tv;
if (gettimeofday(&tv, NULL) < 0)
Fatal("gettimeofday: %s", strerror(errno));
return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec;
}
/// Convert a delta of HighResTimer() values to microseconds.
int64_t TimerToMicros(int64_t dt) {
// No conversion necessary.
return dt;
}
#else
int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) {
return ((int64_t)i.HighPart) << 32 | i.LowPart;
}
int64_t HighResTimer() {
LARGE_INTEGER counter;
if (!QueryPerformanceCounter(&counter))
Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str());
return LargeIntegerToInt64(counter);
}
int64_t TimerToMicros(int64_t dt) {
static int64_t ticks_per_sec = 0;
if (!ticks_per_sec) {
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq))
Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str());
ticks_per_sec = LargeIntegerToInt64(freq);
}
// dt is in ticks. We want microseconds.
return (dt * 1000000) / ticks_per_sec;
}
#endif
} // anonymous namespace
ScopedMetric::ScopedMetric(Metric* metric) {
metric_ = metric;
if (!metric_)
return;
start_ = HighResTimer();
}
ScopedMetric::~ScopedMetric() {
if (!metric_)
return;
metric_->count++;
int64_t dt = TimerToMicros(HighResTimer() - start_);
metric_->sum += dt;
}
Metric* Metrics::NewMetric(const string& name) {
Metric* metric = new Metric;
metric->name = name;
metric->count = 0;
metric->sum = 0;
metrics_.push_back(metric);
return metric;
}
void Metrics::Report() {
int width = 0;
for (vector<Metric*>::iterator i = metrics_.begin();
i != metrics_.end(); ++i) {
width = max((int)(*i)->name.size(), width);
}
printf("%-*s\t%-6s\t%-9s\t%s\n", width,
"metric", "count", "avg (us)", "total (ms)");
for (vector<Metric*>::iterator i = metrics_.begin();
i != metrics_.end(); ++i) {
Metric* metric = *i;
double total = metric->sum / (double)1000;
double avg = metric->sum / (double)metric->count;
printf("%-*s\t%-6d\t%-8.1f\t%.1f\n", width, metric->name.c_str(),
metric->count, avg, total);
}
}
<|endoftext|>
|
<commit_before>#include "command.hh"
#include "common-args.hh"
#include "shared.hh"
#include "store-api.hh"
#include "progress-bar.hh"
using namespace nix;
struct CmdLog : InstallableCommand
{
CmdLog()
{
}
std::string name() override
{
return "log";
}
std::string description() override
{
return "show the build log of the specified packages or paths, if available";
}
Examples examples() override
{
return {
Example{
"To get the build log of GNU Hello:",
"nix log nixpkgs.hello"
},
Example{
"To get the build log of a specific path:",
"nix log /nix/store/lmngj4wcm9rkv3w4dfhzhcyij3195hiq-thunderbird-52.2.1"
},
Example{
"To get a build log from a specific binary cache:",
"nix log --store https://cache.nixos.org nixpkgs.hello"
},
};
}
void run(ref<Store> store) override
{
settings.readOnlyMode = true;
auto subs = getDefaultSubstituters();
subs.push_front(store);
auto b = installable->toBuildable();
for (auto & sub : subs) {
auto log = b.drvPath != "" ? sub->getBuildLog(b.drvPath) : nullptr;
for (auto & output : b.outputs) {
if (log) break;
log = sub->getBuildLog(output.second);
}
if (!log) continue;
stopProgressBar();
printInfo("got build log for '%s' from '%s'", installable->what(), sub->getUri());
std::cout << *log;
return;
}
throw Error("build log of '%s' is not available", installable->what());
}
};
static RegisterCommand r1(make_ref<CmdLog>());
<commit_msg>nix log: use pager<commit_after>#include "command.hh"
#include "common-args.hh"
#include "shared.hh"
#include "store-api.hh"
#include "progress-bar.hh"
using namespace nix;
struct CmdLog : InstallableCommand
{
CmdLog()
{
}
std::string name() override
{
return "log";
}
std::string description() override
{
return "show the build log of the specified packages or paths, if available";
}
Examples examples() override
{
return {
Example{
"To get the build log of GNU Hello:",
"nix log nixpkgs.hello"
},
Example{
"To get the build log of a specific path:",
"nix log /nix/store/lmngj4wcm9rkv3w4dfhzhcyij3195hiq-thunderbird-52.2.1"
},
Example{
"To get a build log from a specific binary cache:",
"nix log --store https://cache.nixos.org nixpkgs.hello"
},
};
}
void run(ref<Store> store) override
{
settings.readOnlyMode = true;
auto subs = getDefaultSubstituters();
subs.push_front(store);
auto b = installable->toBuildable();
RunPager pager;
for (auto & sub : subs) {
auto log = b.drvPath != "" ? sub->getBuildLog(b.drvPath) : nullptr;
for (auto & output : b.outputs) {
if (log) break;
log = sub->getBuildLog(output.second);
}
if (!log) continue;
stopProgressBar();
printInfo("got build log for '%s' from '%s'", installable->what(), sub->getUri());
std::cout << *log;
return;
}
throw Error("build log of '%s' is not available", installable->what());
}
};
static RegisterCommand r1(make_ref<CmdLog>());
<|endoftext|>
|
<commit_before>#include "output.hpp"
#include "config.hpp"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/utility/string_ref.hpp>
#include <climits>
#include <utility>
using namespace synth;
bool Markup::empty() const
{
return beginOffset == endOffset
|| (attrs == TokenAttributes::none && !isRef());
}
fs::path HighlightedFile::dstPath() const
{
fs::path r = inOutDir->second / fname;
r += ".html";
return r;
}
static boost::string_ref htmlEscape(char const& c, bool inAttr)
{
switch (c) {
case '<':
if (!inAttr)
return "<";
break;
// Note: '>' does not need to be escaped.
case '&':
return "&";
case '"':
if (inAttr)
return """;
break;
}
return boost::string_ref(&c, 1);
}
static std::string htmlEscape(boost::string_ref s, bool inAttr)
{
std::string r;
r.reserve(s.size());
for (char c : s) {
boost::string_ref escaped = htmlEscape(c, inAttr);
r.append(escaped.data(), escaped.size());
}
return r;
}
static char const* getTokenKindCssClass(TokenAttributes attrs)
{
// These CSS classes are the ones Pygments uses.
using Tk = TokenAttributes;
SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum")
switch(attrs & Tk::maskKind) {
case Tk::attr: return "nd"; // Name.Decorator
case Tk::cmmt: return "c"; // Comment
case Tk::constant: return "no"; // Name.Constant
case Tk::func: return "nf"; // Name.Function
case Tk::kw: return "k"; // Keyword
case Tk::kwDecl: return "kd"; // Keyword.Declaration
case Tk::lbl: return "nl"; // Name.Label
case Tk::lit: return "l"; // Literal
case Tk::litChr: return "sc"; // String.Char
case Tk::litKw: return "kc"; // Keyword.Constant
case Tk::litNum: return "m"; // Number
case Tk::litNumFlt: return "mf"; // Number.Float
case Tk::litNumIntBin: return "mb"; // Number.Binary
case Tk::litNumIntDecLong: return "ml"; // Number.Integer.Long
case Tk::litNumIntHex: return "mh"; // Number.Hex
case Tk::litNumIntOct: return "mo"; // Number.Oct
case Tk::litStr: return "s"; // String
case Tk::namesp: return "nn"; // Name.Namespace
case Tk::op: return "o"; // Operator
case Tk::opWord: return "ow"; // Operator.Word
case Tk::pre: return "cp"; // Comment.Preproc
case Tk::preIncludeFile: return "cpf"; // Comment.PreprocFile
case Tk::punct: return "p"; // Punctuation
case Tk::ty: return "nc"; // Name.Class
case Tk::tyBuiltin: return "kt"; // Keyword.Type
case Tk::varGlobal: return "vg"; // Name.Variable.Global
case Tk::varLocal: return "nv"; // Name.Variable
case Tk::varNonstaticMember: return "vi"; // Name.Variable.Instance
case Tk::varStaticMember: return "vc"; // Name.Variable.Class
case Tk::none: return "";
default:
assert(false && "Unexpected token kind!");
return "";
}
SYNTH_DISCLANGWARN_END
}
static void writeCssClasses(TokenAttributes attrs, std::ostream& out)
{
if ((attrs & TokenAttributes::flagDef) != TokenAttributes::none)
out << "def ";
if ((attrs & TokenAttributes::flagDecl) != TokenAttributes::none)
out << "decl ";
out << getTokenKindCssClass(attrs);
}
// return: The written tag was a reference.
static bool writeBeginTag(
Markup const& m,
fs::path const& outPath,
MultiTuProcessor& multiTuProcessor,
std::ostream& out)
{
std::string href = m.isRef()
? m.refd(outPath, multiTuProcessor) : std::string();
if (href.empty() && m.attrs == TokenAttributes::none)
return false;
out << '<';
if (href.empty()) {
out << "span";
} else {
href = htmlEscape(std::move(href), /*inAttr:*/ true);
out << "a href=\"" << href << "\"";
}
if (m.attrs != TokenAttributes::none) {
out << " class=\"";
writeCssClasses(m.attrs, out);
out << '\"';
}
if (m.fileUniqueName && !m.fileUniqueName->empty()) {
out << " id=\""
<< htmlEscape(*m.fileUniqueName, /*inAttr:*/ true) << '\"';
}
out << '>';
return !href.empty();
}
namespace {
struct MarkupInfo {
Markup const* markup;
bool wasRef;
};
struct OutputState {
std::istream& in;
std::ostream& out;
unsigned lineno;
std::vector<MarkupInfo> const& activeTags;
fs::path const& outPath;
MultiTuProcessor& multiTuProcessor;
};
} // anonymous namespace
static void writeEndTag(MarkupInfo const& mi, std::ostream& out)
{
if (mi.wasRef)
out << "</a>";
else if (mi.markup->attrs != TokenAttributes::none)
out << "</span>";
}
static void writeAllEnds(
std::ostream& out, std::vector<MarkupInfo> const& activeTags)
{
auto rit = activeTags.rbegin();
auto rend = activeTags.rend();
for (; rit != rend; ++rit)
writeEndTag(*rit, out);
}
static bool copyWithLinenosUntil(OutputState& state, unsigned offset)
{
if (state.lineno == 0) {
++state.lineno;
state.out << "<span id=\"L1\" class=\"Ln\">";
}
while (state.in && state.in.tellg() < offset) {
int ch = state.in.get();
if (ch == std::istream::traits_type::eof()) {
state.out << "</span>\n"; // end tag for lineno.
return false;
} else {
switch (ch) {
case '\n': {
writeAllEnds(state.out, state.activeTags);
++state.lineno;
state.out
<< "</span>\n<span id=\"L"
<< state.lineno
<< "\" class=\"Ln\">";
for (auto const& mi : state.activeTags) {
writeBeginTag(
*mi.markup,
state.outPath,
state.multiTuProcessor,
state.out);
}
} break;
case '\r':
// Discard.
break;
default:
state.out << htmlEscape(static_cast<char>(ch), false);
break;
}
}
}
return true;
}
static void copyWithLinenosUntilNoEof(OutputState& state, unsigned offset)
{
bool eof = !copyWithLinenosUntil(state, offset);
if (eof) {
throw std::runtime_error(
"unexpected EOF in input source " + state.outPath.string()
+ " at line " + std::to_string(state.lineno));
}
}
void HighlightedFile::writeTo(
std::ostream& out, MultiTuProcessor& multiTuProcessor)
{
// ORDER BY beginOffset ASC, endOffset DESC
std::sort(
markups.begin(), markups.end(),
[] (Markup const& lhs, Markup const& rhs) {
return lhs.beginOffset != rhs.beginOffset
? lhs.beginOffset < rhs.beginOffset
: lhs.endOffset > rhs.endOffset;
});
fs::path outPath = dstPath();
fs::ifstream in(srcPath(), std::ios::binary);
if (!in) {
throw std::runtime_error(
"Could not reopen source " + srcPath().string());
}
std::vector<MarkupInfo> activeTags;
OutputState state {in, out, 0, activeTags, outPath, multiTuProcessor};
for (auto const& m : markups) {
while (!activeTags.empty()
&& m.beginOffset >= activeTags.back().markup->endOffset
) {
MarkupInfo const& miEnd = activeTags.back();
copyWithLinenosUntilNoEof(state, miEnd.markup->endOffset);
writeEndTag(miEnd, out);
activeTags.pop_back();
}
copyWithLinenosUntilNoEof(state, m.beginOffset);
bool wasRef = writeBeginTag(
m, state.outPath, state.multiTuProcessor, out);
activeTags.push_back({ &m, wasRef });
}
while (!activeTags.empty()) {
copyWithLinenosUntilNoEof(state, activeTags.back().markup->endOffset);
writeEndTag(activeTags.back(), out);
activeTags.pop_back();
}
BOOST_VERIFY(!copyWithLinenosUntil(state, UINT_MAX));
}
<commit_msg>output: Don't duplicate IDs when reopening tags.<commit_after>#include "output.hpp"
#include "config.hpp"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/utility/string_ref.hpp>
#include <climits>
#include <utility>
using namespace synth;
bool Markup::empty() const
{
return beginOffset == endOffset
|| (attrs == TokenAttributes::none && !isRef());
}
fs::path HighlightedFile::dstPath() const
{
fs::path r = inOutDir->second / fname;
r += ".html";
return r;
}
static boost::string_ref htmlEscape(char const& c, bool inAttr)
{
switch (c) {
case '<':
if (!inAttr)
return "<";
break;
// Note: '>' does not need to be escaped.
case '&':
return "&";
case '"':
if (inAttr)
return """;
break;
}
return boost::string_ref(&c, 1);
}
static std::string htmlEscape(boost::string_ref s, bool inAttr)
{
std::string r;
r.reserve(s.size());
for (char c : s) {
boost::string_ref escaped = htmlEscape(c, inAttr);
r.append(escaped.data(), escaped.size());
}
return r;
}
static char const* getTokenKindCssClass(TokenAttributes attrs)
{
// These CSS classes are the ones Pygments uses.
using Tk = TokenAttributes;
SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum")
switch(attrs & Tk::maskKind) {
case Tk::attr: return "nd"; // Name.Decorator
case Tk::cmmt: return "c"; // Comment
case Tk::constant: return "no"; // Name.Constant
case Tk::func: return "nf"; // Name.Function
case Tk::kw: return "k"; // Keyword
case Tk::kwDecl: return "kd"; // Keyword.Declaration
case Tk::lbl: return "nl"; // Name.Label
case Tk::lit: return "l"; // Literal
case Tk::litChr: return "sc"; // String.Char
case Tk::litKw: return "kc"; // Keyword.Constant
case Tk::litNum: return "m"; // Number
case Tk::litNumFlt: return "mf"; // Number.Float
case Tk::litNumIntBin: return "mb"; // Number.Binary
case Tk::litNumIntDecLong: return "ml"; // Number.Integer.Long
case Tk::litNumIntHex: return "mh"; // Number.Hex
case Tk::litNumIntOct: return "mo"; // Number.Oct
case Tk::litStr: return "s"; // String
case Tk::namesp: return "nn"; // Name.Namespace
case Tk::op: return "o"; // Operator
case Tk::opWord: return "ow"; // Operator.Word
case Tk::pre: return "cp"; // Comment.Preproc
case Tk::preIncludeFile: return "cpf"; // Comment.PreprocFile
case Tk::punct: return "p"; // Punctuation
case Tk::ty: return "nc"; // Name.Class
case Tk::tyBuiltin: return "kt"; // Keyword.Type
case Tk::varGlobal: return "vg"; // Name.Variable.Global
case Tk::varLocal: return "nv"; // Name.Variable
case Tk::varNonstaticMember: return "vi"; // Name.Variable.Instance
case Tk::varStaticMember: return "vc"; // Name.Variable.Class
case Tk::none: return "";
default:
assert(false && "Unexpected token kind!");
return "";
}
SYNTH_DISCLANGWARN_END
}
static void writeCssClasses(TokenAttributes attrs, std::ostream& out)
{
if ((attrs & TokenAttributes::flagDef) != TokenAttributes::none)
out << "def ";
if ((attrs & TokenAttributes::flagDecl) != TokenAttributes::none)
out << "decl ";
out << getTokenKindCssClass(attrs);
}
// return: The written tag was a reference.
static bool writeBeginTag(
Markup const& m,
fs::path const& outPath,
MultiTuProcessor& multiTuProcessor,
bool reopened,
std::ostream& out)
{
std::string href = m.isRef()
? m.refd(outPath, multiTuProcessor) : std::string();
if (href.empty() && m.attrs == TokenAttributes::none)
return false;
out << '<';
if (href.empty()) {
out << "span";
} else {
href = htmlEscape(std::move(href), /*inAttr:*/ true);
out << "a href=\"" << href << "\"";
}
if (m.attrs != TokenAttributes::none) {
out << " class=\"";
writeCssClasses(m.attrs, out);
out << '\"';
}
if (!reopened && m.fileUniqueName && !m.fileUniqueName->empty()) {
out << " id=\""
<< htmlEscape(*m.fileUniqueName, /*inAttr:*/ true) << '\"';
}
out << '>';
return !href.empty();
}
namespace {
struct MarkupInfo {
Markup const* markup;
bool wasRef;
};
struct OutputState {
std::istream& in;
std::ostream& out;
unsigned lineno;
std::vector<MarkupInfo> const& activeTags;
fs::path const& outPath;
MultiTuProcessor& multiTuProcessor;
};
} // anonymous namespace
static void writeEndTag(MarkupInfo const& mi, std::ostream& out)
{
if (mi.wasRef)
out << "</a>";
else if (mi.markup->attrs != TokenAttributes::none)
out << "</span>";
}
static void writeAllEnds(
std::ostream& out, std::vector<MarkupInfo> const& activeTags)
{
auto rit = activeTags.rbegin();
auto rend = activeTags.rend();
for (; rit != rend; ++rit)
writeEndTag(*rit, out);
}
static bool copyWithLinenosUntil(OutputState& state, unsigned offset)
{
if (state.lineno == 0) {
++state.lineno;
state.out << "<span id=\"L1\" class=\"Ln\">";
}
while (state.in && state.in.tellg() < offset) {
int ch = state.in.get();
if (ch == std::istream::traits_type::eof()) {
state.out << "</span>\n"; // end tag for lineno.
return false;
} else {
switch (ch) {
case '\n': {
writeAllEnds(state.out, state.activeTags);
++state.lineno;
state.out
<< "</span>\n<span id=\"L"
<< state.lineno
<< "\" class=\"Ln\">";
for (auto const& mi : state.activeTags) {
writeBeginTag(
*mi.markup,
state.outPath,
state.multiTuProcessor,
/*reopened:*/ true,
state.out);
}
} break;
case '\r':
// Discard.
break;
default:
state.out << htmlEscape(static_cast<char>(ch), false);
break;
}
}
}
return true;
}
static void copyWithLinenosUntilNoEof(OutputState& state, unsigned offset)
{
bool eof = !copyWithLinenosUntil(state, offset);
if (eof) {
throw std::runtime_error(
"unexpected EOF in input source " + state.outPath.string()
+ " at line " + std::to_string(state.lineno));
}
}
void HighlightedFile::writeTo(
std::ostream& out, MultiTuProcessor& multiTuProcessor)
{
// ORDER BY beginOffset ASC, endOffset DESC
std::sort(
markups.begin(), markups.end(),
[] (Markup const& lhs, Markup const& rhs) {
return lhs.beginOffset != rhs.beginOffset
? lhs.beginOffset < rhs.beginOffset
: lhs.endOffset > rhs.endOffset;
});
fs::path outPath = dstPath();
fs::ifstream in(srcPath(), std::ios::binary);
if (!in) {
throw std::runtime_error(
"Could not reopen source " + srcPath().string());
}
std::vector<MarkupInfo> activeTags;
OutputState state {in, out, 0, activeTags, outPath, multiTuProcessor};
for (auto const& m : markups) {
while (!activeTags.empty()
&& m.beginOffset >= activeTags.back().markup->endOffset
) {
MarkupInfo const& miEnd = activeTags.back();
copyWithLinenosUntilNoEof(state, miEnd.markup->endOffset);
writeEndTag(miEnd, out);
activeTags.pop_back();
}
copyWithLinenosUntilNoEof(state, m.beginOffset);
bool wasRef = writeBeginTag(
m, state.outPath, state.multiTuProcessor, /*reopened:*/ false, out);
activeTags.push_back({ &m, wasRef });
}
while (!activeTags.empty()) {
copyWithLinenosUntilNoEof(state, activeTags.back().markup->endOffset);
writeEndTag(activeTags.back(), out);
activeTags.pop_back();
}
BOOST_VERIFY(!copyWithLinenosUntil(state, UINT_MAX));
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iostream>
#include <stdexcept>
#include "config.hpp"
#include "parser.hpp"
requirements Parser::required;
void Parser::init ()
{
required.emplace("announce", std::forward_list<std::string>{"port","peer_id","info_hash","left","compact"}); // init a set of required params in a request
if (Config::get("type") == "private")
required.at("announce").push_front("passkey");
}
std::string Parser::check (const request& req)
{
try {
for (auto it : required.at(req.at("action"))) {
if (req.find(it) == req.end())
return "missing param (" + it + ")";
}
} catch (const std::exception& e) {
std::cerr << "Error in Parser::check -- action not found\n";
return "missing action";
}
return "success";
}
request Parser::parse (const std::string& input)
{
int input_length = input.length();
if (input_length < 60)
return request(); // too short
request output; // first = params, second = headers
int pos = 5; // skip 'GET /'
/*
Handles those types of request:
Case 1: GET /passkey/action?params
Case 2: GET /passkey?params
Case 3: GET /action?params
Case 4: GET /?params
*/
if ( input[pos] != '?' &&
(input.substr(pos,32).find('/') == std::string::npos) &&
(input.substr(pos,32).find('?') == std::string::npos)) { // Case 1, 2
output.emplace("passkey", input.substr(pos,32)); // Ocelot stated that substr 'exploded'. use for loop if necessary
pos += 32;
}
if (input[pos] == '/') // Case 1
++pos;
int i;
if ( input[pos] != '?' ) { // Case 1, 2, 3
for (i=0; i < 8; ++i) { // longest action possible is announce
if (input[pos+i] == '/' ||
input[pos+i] == '?' ||
input[pos+i] == '/')
break;
}
output.emplace("action", input.substr(pos,i));
pos += i;
}
if (input[pos] == '?') // Case 1,2,3,4
++pos;
else
return request(); // malformed
// ocelot-style parsing, should maybe replace with substr later
std::string key;
bool found_data = false;
for (i=pos; i < input_length; ++i) {
if (input[i] == '=') {
key = input.substr(pos,i-pos);
pos = ++i;
} else if (input[i] == '&' || input[i] == ' ') {
if (found_data) {
if (key == "info_hash") {
std::string hash = input.substr(pos, i-pos);
std::transform(hash.begin(), hash.end(), hash.begin(), ::tolower);
output.emplace("info_hash", hash);
} else {
output.emplace(key, input.substr(pos, i-pos));
}
pos = ++i;
}
found_data = false;
if (input[pos-1] == ' ')
break;
key.clear();
} else {
found_data = true;
}
}
pos += 10;
for (i=pos; i < input_length; ++i) {
if (input[i] == ':') {
key = input.substr(pos, i-pos);
i += 2;
pos = i;
} else if (input[i] == '\n' || input[i] == '\r') {
if (found_data) {
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
if (key != "host")
output.emplace(key, input.substr(pos, i-pos));
i += 2;
pos = i;
}
found_data = false;
key.clear();
} else {
found_data = true;
}
}
return output;
}
<commit_msg>optimisation de fou<commit_after>#include <algorithm>
#include <iostream>
#include <stdexcept>
#include "config.hpp"
#include "parser.hpp"
requirements Parser::required;
void Parser::init ()
{
required.emplace("announce", std::forward_list<std::string>{"port","peer_id","info_hash","left","compact"}); // init a set of required params in a request
if (Config::get("type") == "private")
required.at("announce").push_front("passkey");
}
std::string Parser::check (const request& req)
{
try {
for (auto& it : required.at(req.at("action"))) {
if (req.find(it) == req.end())
return "missing param (" + it + ")";
}
} catch (const std::exception& e) {
std::cerr << "Error in Parser::check -- action not found\n";
return "missing action";
}
return "success";
}
request Parser::parse (const std::string& input)
{
int input_length = input.length();
if (input_length < 60)
return request(); // too short
request output; // first = params, second = headers
int pos = 5; // skip 'GET /'
/*
Handles those types of request:
Case 1: GET /passkey/action?params
Case 2: GET /passkey?params
Case 3: GET /action?params
Case 4: GET /?params
*/
if ( input[pos] != '?' &&
(input.substr(pos,32).find('/') == std::string::npos) &&
(input.substr(pos,32).find('?') == std::string::npos)) { // Case 1, 2
output.emplace("passkey", input.substr(pos,32)); // Ocelot stated that substr 'exploded'. use for loop if necessary
pos += 32;
}
if (input[pos] == '/') // Case 1
++pos;
int i;
if ( input[pos] != '?' ) { // Case 1, 2, 3
for (i=0; i < 8; ++i) { // longest action possible is announce
if (input[pos+i] == '/' ||
input[pos+i] == '?' ||
input[pos+i] == '/')
break;
}
output.emplace("action", input.substr(pos,i));
pos += i;
}
if (input[pos] == '?') // Case 1,2,3,4
++pos;
else
return request(); // malformed
// ocelot-style parsing, should maybe replace with substr later
std::string key;
bool found_data = false;
for (i=pos; i < input_length; ++i) {
if (input[i] == '=') {
key = input.substr(pos,i-pos);
pos = ++i;
} else if (input[i] == '&' || input[i] == ' ') {
if (found_data) {
if (key == "info_hash") {
std::string hash = input.substr(pos, i-pos);
std::transform(hash.begin(), hash.end(), hash.begin(), ::tolower);
output.emplace("info_hash", hash);
} else {
output.emplace(key, input.substr(pos, i-pos));
}
pos = ++i;
}
found_data = false;
if (input[pos-1] == ' ')
break;
key.clear();
} else {
found_data = true;
}
}
pos += 10;
for (i=pos; i < input_length; ++i) {
if (input[i] == ':') {
key = input.substr(pos, i-pos);
i += 2;
pos = i;
} else if (input[i] == '\n' || input[i] == '\r') {
if (found_data) {
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
if (key != "host")
output.emplace(key, input.substr(pos, i-pos));
i += 2;
pos = i;
}
found_data = false;
key.clear();
} else {
found_data = true;
}
}
return output;
}
<|endoftext|>
|
<commit_before>#include "player.h"
Player::CameraNavigationMode Player::cameraNavMode = FREE_FLY;
double Player::scrollY = 0.0;
Player::Player(const glm::mat4 &matrix_, Camera *camera_, GLFWwindow *window_, const std::string &filePath)
: Geometry(matrix_, filePath)
, camera(camera_)
, window(window_)
{
// set glfw callbacks
glfwSetScrollCallback(window, onScroll);
glfwSetKeyCallback(window, keyCallback);
camera->setTransform(glm::translate(glm::mat4(1.0f), getLocation()+glm::vec3(0,0,10))); //move camera back a bit
camDirection = glm::normalize(camera->getLocation() - getLocation());
camUp = glm::vec3(0, 1, 0);
camRight = glm::normalize(glm::cross(camUp, camDirection));
}
Player::~Player()
{
delete camera; camera = nullptr;
window = nullptr;
}
void Player::update(float timeDelta)
{
// note: camera navigation mode is toggled on tab key press, look for keyCallback
if (cameraNavMode == FOLLOW_PLAYER) {
handleInput(window, timeDelta);
viewProjMat = camera->getProjectionMatrix() * glm::lookAt(camera->getLocation(), getLocation(), camUp);
}
else {
handleInputFreeCamera(window, timeDelta);
viewProjMat = camera->getProjectionMatrix() * camera->getViewMatrix();
}
//camera->update(timeDelta);
}
void Player::draw(Shader *shader)
{
// pass camera view and projection matrices to shader
GLint viewProjMatLocation = glGetUniformLocation(shader->programHandle, "viewProjMat"); // get uniform location in shader
glUniformMatrix4fv(viewProjMatLocation, 1, GL_FALSE, glm::value_ptr(viewProjMat)); // shader location, count, transpose?, value pointer
// pass camera position to shader
GLint cameraPosLocation = glGetUniformLocation(shader->programHandle, "cameraPos");
glUniform3f(cameraPosLocation, camera->getLocation().x, camera->getLocation().y, camera->getLocation().z);
Geometry::draw(shader);
}
void Player::handleInput(GLFWwindow *window, float timeDelta)
{
float moveSpeed = 5.0f;
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT)) {
moveSpeed = 20.0f;
}
// camera movement
// note: we apply rotation before translation since we dont want the distance from the origin
// to affect how we rotate
if (glfwGetKey(window, 'W')) {
translate(glm::vec3(0.0f, 0.0f, -0.1f) * timeDelta * moveSpeed, SceneObject::RIGHT);
}
else if (glfwGetKey(window, 'S')) {
translate(glm::vec3(0.0f, 0.0f, 0.1f) * timeDelta * moveSpeed, SceneObject::RIGHT);
}
if (glfwGetKey(window, 'A')) {
rotateY(timeDelta * glm::radians(90.f), SceneObject::RIGHT);
}
else if (glfwGetKey(window, 'D')) {
rotateY(timeDelta * glm::radians(-90.f), SceneObject::RIGHT);
}
if (glfwGetKey(window, 'Q')) {
translate(glm::vec3(0,1,0) * timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'E')) {
translate(glm::vec3(0,1,0) * -timeDelta * moveSpeed, SceneObject::LEFT);
}
//// rotate camera based on mouse movement
//// the mouse pointer is reset to (0, 0) every frame, and we just take the displacement of that frame
const float mouseSensitivity = 0.01f;
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
glm::vec3 camToTarget = camera->getLocation() - getLocation();
glm::vec3 rightVec = glm::normalize(glm::cross(camToTarget, glm::vec3(0, 1, 0)));
glm::mat4 rotateYaw = glm::rotate(glm::mat4(), -mouseSensitivity * (float)mouseX, glm::vec3(0, 1, 0));
glm::mat4 rotatePitch = glm::rotate(glm::mat4(), mouseSensitivity * (float)mouseY, rightVec);
camToTarget = glm::vec3(rotateYaw * glm::vec4(camToTarget, 0));
camToTarget = glm::vec3(rotatePitch * glm::vec4(camToTarget, 0));
camToTarget = camToTarget + getLocation();
camera->setLocation(camToTarget);
glfwSetCursorPos(window, 0, 0); // reset the mouse, so it doesn't leave the window
//// handle camera zoom by changing the field of view depending on mouse scroll since last frame
float zoomSensitivity = -0.1f;
float fieldOfView = camera->getFieldOfView() + zoomSensitivity * (float)scrollY;
if (fieldOfView < glm::radians(20.0f)) fieldOfView = glm::radians(20.0f);
if (fieldOfView > glm::radians(60.0f)) fieldOfView = glm::radians(60.0f);
camera->setFieldOfView(fieldOfView);
scrollY = 0.0;
}
void Player::handleInputFreeCamera(GLFWwindow *window, float timeDelta)
{
float moveSpeed = 5.0f;
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT)) {
moveSpeed = 20.0f;
}
//////////////////////////
/// CAMERA MOVEMENT
//////////////////////////
// camera movement
// note: we apply rotation before translation since we dont want the distance from the origin
// to affect how we rotate
if (glfwGetKey(window, 'W')) {
camera->translate(camera->getMatrix()[2].xyz() * -timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'S')) {
camera->translate(camera->getMatrix()[2].xyz() * timeDelta * moveSpeed, SceneObject::LEFT);
}
if (glfwGetKey(window, 'A')) {
camera->translate(camera->getMatrix()[0].xyz() * -timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'D')) {
camera->translate(camera->getMatrix()[0].xyz() * timeDelta * moveSpeed, SceneObject::LEFT);
}
if (glfwGetKey(window, 'Q')) {
camera->translate(glm::vec3(0,1,0) * timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'E')) {
camera->translate(glm::vec3(0,1,0) * -timeDelta * moveSpeed, SceneObject::LEFT);
}
// rotate camera based on mouse movement
// the mouse pointer is reset to (0, 0) every frame, and we just take the displacement of that frame
const float mouseSensitivity = 0.01f;
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
camera->rotateX(-mouseSensitivity * (float)mouseY, SceneObject::RIGHT);
camera->rotateY(-mouseSensitivity * (float)mouseX, SceneObject::RIGHT);
glfwSetCursorPos(window, 0, 0); // reset the mouse, so it doesn't leave the window
// handle camera zoom by changing the field of view depending on mouse scroll since last frame
float zoomSensitivity = -0.1f;
float fieldOfView = camera->getFieldOfView() + zoomSensitivity * (float)scrollY;
if (fieldOfView < glm::radians(20.0f)) fieldOfView = glm::radians(20.0f);
if (fieldOfView > glm::radians(60.0f)) fieldOfView = glm::radians(60.0f);
camera->setFieldOfView(fieldOfView);
scrollY = 0.0;
}
void Player::onScroll(GLFWwindow *window, double deltaX, double deltaY)
{
scrollY += deltaY;
}
void Player::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (glfwGetKey(window, GLFW_KEY_TAB) == GLFW_PRESS) {
if (cameraNavMode == FOLLOW_PLAYER) {
cameraNavMode = FREE_FLY;
}
else if (cameraNavMode == FREE_FLY) {
cameraNavMode = FOLLOW_PLAYER;
}
}
}
<commit_msg>fully implements working 3d person arcball camera<commit_after>#include "player.h"
Player::CameraNavigationMode Player::cameraNavMode = FREE_FLY;
double Player::scrollY = 0.0;
Player::Player(const glm::mat4 &matrix_, Camera *camera_, GLFWwindow *window_, const std::string &filePath)
: Geometry(matrix_, filePath)
, camera(camera_)
, window(window_)
{
// set glfw callbacks
glfwSetScrollCallback(window, onScroll);
glfwSetKeyCallback(window, keyCallback);
camera->setTransform(glm::translate(glm::mat4(1.0f), getLocation()+glm::vec3(0,0,10))); //move camera back a bit
camDirection = glm::normalize(camera->getLocation() - getLocation());
camUp = glm::vec3(0, 1, 0);
camRight = glm::normalize(glm::cross(camUp, camDirection));
}
Player::~Player()
{
delete camera; camera = nullptr;
window = nullptr;
}
void Player::update(float timeDelta)
{
// note: camera navigation mode is toggled on tab key press, look for keyCallback
if (cameraNavMode == FOLLOW_PLAYER) {
handleInput(window, timeDelta);
glm::vec3 v = glm::normalize(getLocation() - camera->getLocation()) * 15.f;
viewProjMat = camera->getProjectionMatrix() * glm::lookAt(getLocation()-v, getLocation(), camUp);
}
else {
handleInputFreeCamera(window, timeDelta);
viewProjMat = camera->getProjectionMatrix() * camera->getViewMatrix();
}
}
void Player::draw(Shader *shader)
{
// pass camera view and projection matrices to shader
GLint viewProjMatLocation = glGetUniformLocation(shader->programHandle, "viewProjMat"); // get uniform location in shader
glUniformMatrix4fv(viewProjMatLocation, 1, GL_FALSE, glm::value_ptr(viewProjMat)); // shader location, count, transpose?, value pointer
// pass camera position to shader
GLint cameraPosLocation = glGetUniformLocation(shader->programHandle, "cameraPos");
glUniform3f(cameraPosLocation, camera->getLocation().x, camera->getLocation().y, camera->getLocation().z);
Geometry::draw(shader);
}
void Player::handleInput(GLFWwindow *window, float timeDelta)
{
float moveSpeed = 10.0f;
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT)) {
moveSpeed = 40.0f;
}
// camera movement
// note: we apply rotation before translation since we dont want the distance from the origin
// to affect how we rotate
if (glfwGetKey(window, 'W')) {
translate(glm::vec3(0.0f, 0.0f, -0.1f) * timeDelta * moveSpeed, SceneObject::RIGHT);
}
else if (glfwGetKey(window, 'S')) {
translate(glm::vec3(0.0f, 0.0f, 0.1f) * timeDelta * moveSpeed, SceneObject::RIGHT);
}
if (glfwGetKey(window, 'A')) {
rotateY(timeDelta * glm::radians(90.f), SceneObject::RIGHT);
}
else if (glfwGetKey(window, 'D')) {
rotateY(timeDelta * glm::radians(-90.f), SceneObject::RIGHT);
}
if (glfwGetKey(window, 'Q')) {
translate(glm::vec3(0,1,0) * timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'E')) {
translate(glm::vec3(0,1,0) * -timeDelta * moveSpeed, SceneObject::LEFT);
}
//// rotate camera based on mouse movement
//// the mouse pointer is reset to (0, 0) every frame, and we just take the displacement of that frame
const float mouseSensitivity = 0.01f;
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
glm::vec3 camToTarget = camera->getLocation() - getLocation();
glm::vec3 rightVec = glm::normalize(glm::cross(camToTarget, glm::vec3(0, 1, 0)));
glm::mat4 rotateYaw = glm::rotate(glm::mat4(), -mouseSensitivity * (float)mouseX, glm::vec3(0, 1, 0));
glm::mat4 rotatePitch = glm::rotate(glm::mat4(), mouseSensitivity * (float)mouseY, rightVec);
camToTarget = glm::vec3(rotateYaw * glm::vec4(camToTarget, 0));
camToTarget = glm::vec3(rotatePitch * glm::vec4(camToTarget, 0));
camToTarget = camToTarget + getLocation();
camera->setLocation(camToTarget);
glfwSetCursorPos(window, 0, 0); // reset the mouse, so it doesn't leave the window
//// handle camera zoom by changing the field of view depending on mouse scroll since last frame
float zoomSensitivity = -0.1f;
float fieldOfView = camera->getFieldOfView() + zoomSensitivity * (float)scrollY;
if (fieldOfView < glm::radians(20.0f)) fieldOfView = glm::radians(20.0f);
if (fieldOfView > glm::radians(60.0f)) fieldOfView = glm::radians(60.0f);
camera->setFieldOfView(fieldOfView);
scrollY = 0.0;
}
void Player::handleInputFreeCamera(GLFWwindow *window, float timeDelta)
{
float moveSpeed = 10.0f;
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT)) {
moveSpeed = 30.0f;
}
//////////////////////////
/// CAMERA MOVEMENT
//////////////////////////
// camera movement
// note: we apply rotation before translation since we dont want the distance from the origin
// to affect how we rotate
if (glfwGetKey(window, 'W')) {
camera->translate(camera->getMatrix()[2].xyz() * -timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'S')) {
camera->translate(camera->getMatrix()[2].xyz() * timeDelta * moveSpeed, SceneObject::LEFT);
}
if (glfwGetKey(window, 'A')) {
camera->translate(camera->getMatrix()[0].xyz() * -timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'D')) {
camera->translate(camera->getMatrix()[0].xyz() * timeDelta * moveSpeed, SceneObject::LEFT);
}
if (glfwGetKey(window, 'Q')) {
camera->translate(glm::vec3(0,1,0) * timeDelta * moveSpeed, SceneObject::LEFT);
}
else if (glfwGetKey(window, 'E')) {
camera->translate(glm::vec3(0,1,0) * -timeDelta * moveSpeed, SceneObject::LEFT);
}
// rotate camera based on mouse movement
// the mouse pointer is reset to (0, 0) every frame, and we just take the displacement of that frame
const float mouseSensitivity = 0.01f;
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
camera->rotateX(-mouseSensitivity * (float)mouseY, SceneObject::RIGHT);
camera->rotateY(-mouseSensitivity * (float)mouseX, SceneObject::RIGHT);
glfwSetCursorPos(window, 0, 0); // reset the mouse, so it doesn't leave the window
// handle camera zoom by changing the field of view depending on mouse scroll since last frame
float zoomSensitivity = -0.1f;
float fieldOfView = camera->getFieldOfView() + zoomSensitivity * (float)scrollY;
if (fieldOfView < glm::radians(20.0f)) fieldOfView = glm::radians(20.0f);
if (fieldOfView > glm::radians(60.0f)) fieldOfView = glm::radians(60.0f);
camera->setFieldOfView(fieldOfView);
scrollY = 0.0;
}
void Player::onScroll(GLFWwindow *window, double deltaX, double deltaY)
{
scrollY += deltaY;
}
void Player::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (glfwGetKey(window, GLFW_KEY_TAB) == GLFW_PRESS) {
if (cameraNavMode == FOLLOW_PLAYER) {
cameraNavMode = FREE_FLY;
}
else if (cameraNavMode == FREE_FLY) {
cameraNavMode = FOLLOW_PLAYER;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "pyinterp.h"
#include "post.h"
#include "xact.h"
namespace ledger {
using namespace boost::python;
namespace {
bool py_has_tag_1s(post_t& post, const string& tag) {
return post.has_tag(tag);
}
bool py_has_tag_1m(post_t& post, const mask_t& tag_mask) {
return post.has_tag(tag_mask);
}
bool py_has_tag_2m(post_t& post, const mask_t& tag_mask,
const boost::optional<mask_t>& value_mask) {
return post.has_tag(tag_mask, value_mask);
}
boost::optional<string> py_get_tag_1s(post_t& post, const string& tag) {
return post.get_tag(tag);
}
boost::optional<string> py_get_tag_1m(post_t& post, const mask_t& tag_mask) {
return post.get_tag(tag_mask);
}
boost::optional<string> py_get_tag_2m(post_t& post, const mask_t& tag_mask,
const boost::optional<mask_t>& value_mask) {
return post.get_tag(tag_mask, value_mask);
}
post_t::xdata_t& py_xdata(post_t& post) {
return post.xdata();
}
account_t * py_reported_account(post_t& post) {
return post.reported_account();
}
} // unnamed namespace
void export_post()
{
scope().attr("POST_EXT_RECEIVED") = POST_EXT_RECEIVED;
scope().attr("POST_EXT_HANDLED") = POST_EXT_HANDLED;
scope().attr("POST_EXT_DISPLAYED") = POST_EXT_DISPLAYED;
scope().attr("POST_EXT_DIRECT_AMT") = POST_EXT_DIRECT_AMT;
scope().attr("POST_EXT_SORT_CALC") = POST_EXT_SORT_CALC;
scope().attr("POST_EXT_COMPOUND") = POST_EXT_COMPOUND;
scope().attr("POST_EXT_VISITED") = POST_EXT_VISITED;
scope().attr("POST_EXT_MATCHES") = POST_EXT_MATCHES;
scope().attr("POST_EXT_CONSIDERED") = POST_EXT_CONSIDERED;
class_< post_t::xdata_t > ("PostingXData")
#if 1
.add_property("flags",
&supports_flags<uint_least16_t>::flags,
&supports_flags<uint_least16_t>::set_flags)
.def("has_flags", &supports_flags<uint_least16_t>::has_flags)
.def("clear_flags", &supports_flags<uint_least16_t>::clear_flags)
.def("add_flags", &supports_flags<uint_least16_t>::add_flags)
.def("drop_flags", &supports_flags<uint_least16_t>::drop_flags)
#endif
.add_property("visited_value",
make_getter(&post_t::xdata_t::visited_value),
make_setter(&post_t::xdata_t::visited_value))
.add_property("compound_value",
make_getter(&post_t::xdata_t::compound_value),
make_setter(&post_t::xdata_t::compound_value))
.add_property("total",
make_getter(&post_t::xdata_t::total),
make_setter(&post_t::xdata_t::total))
.add_property("count",
make_getter(&post_t::xdata_t::count),
make_setter(&post_t::xdata_t::count))
.add_property("date",
make_getter(&post_t::xdata_t::date),
make_setter(&post_t::xdata_t::date))
.add_property("datetime",
make_getter(&post_t::xdata_t::datetime),
make_setter(&post_t::xdata_t::datetime))
.add_property("account",
make_getter(&post_t::xdata_t::account),
make_setter(&post_t::xdata_t::account))
.add_property("sort_values",
make_getter(&post_t::xdata_t::sort_values),
make_setter(&post_t::xdata_t::sort_values))
;
scope().attr("POST_VIRTUAL") = POST_VIRTUAL;
scope().attr("POST_MUST_BALANCE") = POST_MUST_BALANCE;
scope().attr("POST_CALCULATED") = POST_CALCULATED;
scope().attr("POST_COST_CALCULATED") = POST_COST_CALCULATED;
class_< post_t, bases<item_t> > ("Posting")
//.def(init<account_t *>())
.add_property("xact",
make_getter(&post_t::xact,
return_internal_reference<>()),
make_setter(&post_t::xact,
with_custodian_and_ward<1, 2>()))
.add_property("account",
make_getter(&post_t::account,
return_internal_reference<>()),
make_setter(&post_t::account,
with_custodian_and_ward<1, 2>()))
.add_property("amount",
make_getter(&post_t::amount),
make_setter(&post_t::amount))
.add_property("cost",
make_getter(&post_t::cost),
make_setter(&post_t::cost))
.add_property("assigned_amount",
make_getter(&post_t::assigned_amount),
make_setter(&post_t::assigned_amount))
.def("has_tag", py_has_tag_1s)
.def("has_tag", py_has_tag_1m)
.def("has_tag", py_has_tag_2m)
.def("get_tag", py_get_tag_1s)
.def("get_tag", py_get_tag_1m)
.def("get_tag", py_get_tag_2m)
.def("date", &post_t::date)
.def("effective_date", &post_t::effective_date)
.def("must_balance", &post_t::must_balance)
.def("lookup", &post_t::lookup)
.def("valid", &post_t::valid)
.def("has_xdata", &post_t::has_xdata)
.def("clear_xdata", &post_t::clear_xdata)
.def("xdata", py_xdata,
return_internal_reference<>())
.def("add_to_value", &post_t::add_to_value)
.def("set_reported_account", &post_t::set_reported_account)
.def("reported_account", py_reported_account,
return_internal_reference<>())
;
}
} // namespace ledger
<commit_msg>Set call policies for accessing post.xdata.account<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "pyinterp.h"
#include "post.h"
#include "xact.h"
namespace ledger {
using namespace boost::python;
namespace {
bool py_has_tag_1s(post_t& post, const string& tag) {
return post.has_tag(tag);
}
bool py_has_tag_1m(post_t& post, const mask_t& tag_mask) {
return post.has_tag(tag_mask);
}
bool py_has_tag_2m(post_t& post, const mask_t& tag_mask,
const boost::optional<mask_t>& value_mask) {
return post.has_tag(tag_mask, value_mask);
}
boost::optional<string> py_get_tag_1s(post_t& post, const string& tag) {
return post.get_tag(tag);
}
boost::optional<string> py_get_tag_1m(post_t& post, const mask_t& tag_mask) {
return post.get_tag(tag_mask);
}
boost::optional<string> py_get_tag_2m(post_t& post, const mask_t& tag_mask,
const boost::optional<mask_t>& value_mask) {
return post.get_tag(tag_mask, value_mask);
}
post_t::xdata_t& py_xdata(post_t& post) {
return post.xdata();
}
account_t * py_reported_account(post_t& post) {
return post.reported_account();
}
} // unnamed namespace
void export_post()
{
scope().attr("POST_EXT_RECEIVED") = POST_EXT_RECEIVED;
scope().attr("POST_EXT_HANDLED") = POST_EXT_HANDLED;
scope().attr("POST_EXT_DISPLAYED") = POST_EXT_DISPLAYED;
scope().attr("POST_EXT_DIRECT_AMT") = POST_EXT_DIRECT_AMT;
scope().attr("POST_EXT_SORT_CALC") = POST_EXT_SORT_CALC;
scope().attr("POST_EXT_COMPOUND") = POST_EXT_COMPOUND;
scope().attr("POST_EXT_VISITED") = POST_EXT_VISITED;
scope().attr("POST_EXT_MATCHES") = POST_EXT_MATCHES;
scope().attr("POST_EXT_CONSIDERED") = POST_EXT_CONSIDERED;
class_< post_t::xdata_t > ("PostingXData")
#if 1
.add_property("flags",
&supports_flags<uint_least16_t>::flags,
&supports_flags<uint_least16_t>::set_flags)
.def("has_flags", &supports_flags<uint_least16_t>::has_flags)
.def("clear_flags", &supports_flags<uint_least16_t>::clear_flags)
.def("add_flags", &supports_flags<uint_least16_t>::add_flags)
.def("drop_flags", &supports_flags<uint_least16_t>::drop_flags)
#endif
.add_property("visited_value",
make_getter(&post_t::xdata_t::visited_value),
make_setter(&post_t::xdata_t::visited_value))
.add_property("compound_value",
make_getter(&post_t::xdata_t::compound_value),
make_setter(&post_t::xdata_t::compound_value))
.add_property("total",
make_getter(&post_t::xdata_t::total),
make_setter(&post_t::xdata_t::total))
.add_property("count",
make_getter(&post_t::xdata_t::count),
make_setter(&post_t::xdata_t::count))
.add_property("date",
make_getter(&post_t::xdata_t::date),
make_setter(&post_t::xdata_t::date))
.add_property("datetime",
make_getter(&post_t::xdata_t::datetime),
make_setter(&post_t::xdata_t::datetime))
.add_property("account",
make_getter(&post_t::xdata_t::account,
return_internal_reference<>()),
make_setter(&post_t::xdata_t::account,
with_custodian_and_ward<1, 2>()))
.add_property("sort_values",
make_getter(&post_t::xdata_t::sort_values),
make_setter(&post_t::xdata_t::sort_values))
;
scope().attr("POST_VIRTUAL") = POST_VIRTUAL;
scope().attr("POST_MUST_BALANCE") = POST_MUST_BALANCE;
scope().attr("POST_CALCULATED") = POST_CALCULATED;
scope().attr("POST_COST_CALCULATED") = POST_COST_CALCULATED;
class_< post_t, bases<item_t> > ("Posting")
//.def(init<account_t *>())
.add_property("xact",
make_getter(&post_t::xact,
return_internal_reference<>()),
make_setter(&post_t::xact,
with_custodian_and_ward<1, 2>()))
.add_property("account",
make_getter(&post_t::account,
return_internal_reference<>()),
make_setter(&post_t::account,
with_custodian_and_ward<1, 2>()))
.add_property("amount",
make_getter(&post_t::amount),
make_setter(&post_t::amount))
.add_property("cost",
make_getter(&post_t::cost),
make_setter(&post_t::cost))
.add_property("assigned_amount",
make_getter(&post_t::assigned_amount),
make_setter(&post_t::assigned_amount))
.def("has_tag", py_has_tag_1s)
.def("has_tag", py_has_tag_1m)
.def("has_tag", py_has_tag_2m)
.def("get_tag", py_get_tag_1s)
.def("get_tag", py_get_tag_1m)
.def("get_tag", py_get_tag_2m)
.def("date", &post_t::date)
.def("effective_date", &post_t::effective_date)
.def("must_balance", &post_t::must_balance)
.def("lookup", &post_t::lookup)
.def("valid", &post_t::valid)
.def("has_xdata", &post_t::has_xdata)
.def("clear_xdata", &post_t::clear_xdata)
.def("xdata", py_xdata,
return_internal_reference<>())
.def("add_to_value", &post_t::add_to_value)
.def("set_reported_account", &post_t::set_reported_account)
.def("reported_account", py_reported_account,
return_internal_reference<>())
;
}
} // namespace ledger
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of vanillacoin.
*
* vanillacoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <cmath>
#include <coin/constants.hpp>
#include <coin/logger.hpp>
#include <coin/reward.hpp>
using namespace coin;
std::int64_t reward::get_proof_of_work(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
return get_proof_of_work_vanilla(height, fees, hash_previous);
}
std::int64_t reward::get_proof_of_stake(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
return get_proof_of_stake_vanilla(coin_age, bits, time, height);
}
std::int64_t reward::get_proof_of_stake_ppcoin(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
static std::int64_t coin_reward_year = constants::cent;
std::int64_t subsidy = coin_age * 33 / (365 * 33 + 8) * coin_reward_year;
log_debug(
"Reward (ppcoin) create = " << subsidy << ", coin age = " << coin_age <<
", bits = " << bits << "."
);
return subsidy;
}
std::int64_t reward::get_proof_of_work_ppcoin(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
// :TODO: get_proof_of_work_ppcoin
return -1;
}
std::int64_t reward::get_proof_of_work_vanilla(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
std::int64_t subsidy = 0;
/**
* The maximum coin supply is 30717658.00 over 13 years
* Year 1: 15733333.00
* Year 2: 23409756.00
* Year 3: 27154646.00
* Year 4: 28981324.00
* Year 5: 29872224.00
*/
subsidy = (1111.0 * (std::pow((height + 1.0), 2.0)));
if (subsidy > 128)
{
subsidy = 128;
}
if (subsidy < 1)
{
subsidy = 1;
}
subsidy *= 1000000;
if (height <= 50000)
{
for (auto i = 50000; i <= height; i += 50000)
{
subsidy -= subsidy / 6;
}
}
else
{
for (auto i = 40000; i <= height; i += 40000)
{
subsidy -= subsidy / 6;
}
}
/**
* If the subsidy is less than one cent the miner gets one cent
* indefinitely.
*/
if ((subsidy / 1000000.0f) <= 0.01f)
{
return 0.01f;
}
/**
* Fees are destroyed to limit inflation.
*/
return subsidy;
}
std::int64_t reward::get_proof_of_stake_vanilla(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
std::int64_t coin_reward_year = constants::max_mint_proof_of_stake;
enum { yearly_block_count = 365 * 432};
coin_reward_year = 1 * constants::max_mint_proof_of_stake;
std::int64_t subsidy = coin_age * coin_reward_year / 365;
log_debug(
"Reward (vanilla) create = " << subsidy << ", coin age = " <<
coin_age << ", bits = " << bits << "."
);
return subsidy;
}
<commit_msg>reward, use 50000 forever<commit_after>/*
* Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of vanillacoin.
*
* vanillacoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <cmath>
#include <coin/constants.hpp>
#include <coin/logger.hpp>
#include <coin/reward.hpp>
using namespace coin;
std::int64_t reward::get_proof_of_work(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
return get_proof_of_work_vanilla(height, fees, hash_previous);
}
std::int64_t reward::get_proof_of_stake(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
return get_proof_of_stake_vanilla(coin_age, bits, time, height);
}
std::int64_t reward::get_proof_of_stake_ppcoin(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
static std::int64_t coin_reward_year = constants::cent;
std::int64_t subsidy = coin_age * 33 / (365 * 33 + 8) * coin_reward_year;
log_debug(
"Reward (ppcoin) create = " << subsidy << ", coin age = " << coin_age <<
", bits = " << bits << "."
);
return subsidy;
}
std::int64_t reward::get_proof_of_work_ppcoin(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
// :TODO: get_proof_of_work_ppcoin
return -1;
}
std::int64_t reward::get_proof_of_work_vanilla(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
std::int64_t subsidy = 0;
/**
* The maximum coin supply is 30717658.00 over 13 years
* Year 1: 15733333.00
* Year 2: 23409756.00
* Year 3: 27154646.00
* Year 4: 28981324.00
* Year 5: 29872224.00
*/
subsidy = (1111.0 * (std::pow((height + 1.0), 2.0)));
if (subsidy > 128)
{
subsidy = 128;
}
if (subsidy < 1)
{
subsidy = 1;
}
subsidy *= 1000000;
for (auto i = 50000; i <= height; i += 50000)
{
subsidy -= subsidy / 6;
}
/**
* If the subsidy is less than one cent the miner gets one cent
* indefinitely.
*/
if ((subsidy / 1000000.0f) <= 0.01f)
{
return 0.01f;
}
/**
* Fees are destroyed to limit inflation.
*/
return subsidy;
}
std::int64_t reward::get_proof_of_stake_vanilla(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
std::int64_t coin_reward_year = constants::max_mint_proof_of_stake;
enum { yearly_block_count = 365 * 432};
coin_reward_year = 1 * constants::max_mint_proof_of_stake;
std::int64_t subsidy = coin_age * coin_reward_year / 365;
log_debug(
"Reward (vanilla) create = " << subsidy << ", coin age = " <<
coin_age << ", bits = " << bits << "."
);
return subsidy;
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <cassert>
#include "ring.hpp"
#include <stdint.h>
#include <QFile>
#define DEFAULTBUFFERSIZE 1024
#define DEFAULTMUTATIONINTERVAL 16
#ifdef __linux__
#define _GNU_SOURCE
#include <sched.h>
#include <sys/types.h>
#include <unistd.h>
#endif
int main(int argc, char* argv[])
{
#ifdef __linux__
//int sched_setaffinity(getpid(), size_t cpusetsize, cpu_set_t *mask);
#endif
char inputFile[256+1];
char outputFile[256+1];
char key[MAPSIZE+1];
char salt[IVSIZE];
char mutationInterval[4+1];
char buffer[6+1];
char keyFile[256+1];
bool inputSet = false;
bool outputSet = false;
bool keySet = false;
bool encode = false;
bool decode = false;
bool mutationIntervalSet = false;
bool bufferSet = false;
bool keyFileSet = false;
bool verbose = false;
bool removeSet = false;
for (int i=0; i<argc; i++)//collect arguments from cmdline
{
if (strcmp(argv[i], "-in") == 0 || strcmp(argv[i], "-i") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(inputFile, argv[i]);
inputSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-out") == 0 || strcmp(argv[i], "-o") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(outputFile, argv[i]);
outputSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-password") == 0 || strcmp(argv[i], "-p") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(key, argv[i]);
keySet = true;
}
}
continue;
}
if (strcmp(argv[i], "-key") == 0 || strcmp(argv[i], "-k") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(keyFile, argv[i]);
keyFileSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-encode") == 0 || strcmp(argv[i], "-e") == 0)
{
encode = true;
continue;
}
if (strcmp(argv[i], "-decode") == 0 || strcmp(argv[i], "-d") == 0)
{
decode = true;
continue;
}
if (strcmp(argv[i], "-verbose") == 0 || strcmp(argv[i], "-v") == 0)
{
verbose = true;
continue;
}
if (strcmp(argv[i], "-remove") == 0 || strcmp(argv[i], "-r") == 0)
{
removeSet = true;
continue;
}
if (strcmp(argv[i], "-mutation") == 0 || strcmp(argv[i], "-m") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 4)
{
strcpy(mutationInterval, argv[i]);
mutationIntervalSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-buffer") == 0 || strcmp(argv[i], "-b") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 6)
{
strcpy(buffer, argv[i]);
bufferSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0)
{
printf("%s [-e|-d] [-i <inputfile>] [-o <outputfile>] [-p <password> | -k <keyfile>] [-m <mutationInterval>] [-b <buffersize>] [-v] [-r] [-h]\n", argv[0]);
printf("\n");
printf("Encodes or decodes a single file.\n");
printf("\n");
printf("-e\n");
printf("-encode\n");
printf("\tdefault\n");
printf("\toptional\n");
printf("\tSpecifies the mode as \"encode\".\n");
printf("\n");
printf("-d\n");
printf("-decode\n");
printf("\toptional\n");
printf("\tSpecifies the mode as \"decode\".\n");
printf("\n");
printf("-i <inputfile>\n");
printf("-in <inputfile>\n");
printf("\tmust\n");
printf("\tSpecifies the inputfile.\n");
printf("\n");
printf("-o <outputfile>\n");
printf("-out <outputfile>\n");
printf("\tmust\n");
printf("\tSpecifies the outputfile.\n");
printf("\n");
printf("-p <password>\n");
printf("-password <password>\n");
printf("\tmust\n");
printf("\tSpecifies the password.\n");
printf("\n");
printf("-k <keyfile>\n");
printf("-key <keyfile>\n");
printf("\toptional (alternative for -p)\n");
printf("\tSpecifies a keyfile.\n");
printf("\n");
printf("-m <mutationInterval>\n");
printf("-mutation <mutationInterval>\n");
printf("\tdefault: %u\n", DEFAULTMUTATIONINTERVAL);
printf("\toptional\n");
printf("\tSpecifies the mutationInterval.\n");
printf("\n");
printf("-b <buffersize>\n");
printf("-buffer <buffersize>\n");
printf("\tdefault: %u\n", DEFAULTBUFFERSIZE);
printf("\toptional\n");
printf("\tSpecifies the buffersize.\n");
printf("\n");
printf("-v\n");
printf("-verbose\n");
printf("\toptional\n");
printf("\tMakes the program verbose.\n");
printf("\n");
printf("-r\n");
printf("-remove\n");
printf("\toptional\n");
printf("\tRemoves the inputfile after reading.\n");
printf("\n");
printf("-h\n");
printf("-help\n");
printf("\toptional\n");
printf("\tPrints this helpmessage and quits the program.\n");
return 0;
}
}
//evaluate arguments
if (!inputSet)
{
printf("You need to specify an inputfile!\n");
return -EINVAL;
}
if (keySet && keyFileSet)
{
printf("You shall not specify a password and a keyfile!\n");
return -EINVAL;
}
if (!keySet && !keyFileSet)
{
printf("You need to specify a password or a keyfile!\n");
return -EINVAL;
}
if (encode && decode)
{
printf("You may only specify one mode!\n");
return -EINVAL;
}
if (keyFileSet)
{
QFile in(keyFile);
if (!in.open(QIODevice::ReadOnly))
{
printf("ERROR: can not open keyfile\n");
errno = EIO;
return -errno;
}
unsigned int fileSize = in.size();
if (fileSize > MAPSIZE)
{
printf("ERROR: keyfile is to large to contain a single key -> invalid\n");
in.close();
errno = EMSGSIZE;
return -EMSGSIZE;
}
if (in.read((char*)(&key), fileSize) != fileSize)
{
in.close();
errno = EIO;
return -EIO;
}
key[fileSize] = '\0';
in.close();
printf("Password read from keyfile.\n");
}
if (!encode && !decode)
{
encode = true;
printf("No mode specified... using \"encodemode\".\n");
}
if (!outputSet)
{
strcpy(outputFile, inputFile);
if (encode)
{
strcat(outputFile, ".enc");
}
else
{
strcat(outputFile, ".dec");
}
printf("No outputfile specified... using \"%s\".\n", outputFile);
}
if (!mutationIntervalSet && encode)
{
sprintf(mutationInterval, "%u", DEFAULTMUTATIONINTERVAL);
printf("No mutationInterval specified... using \"%s\".\n", mutationInterval);
}
if (!bufferSet)
{
sprintf(buffer, "%u", DEFAULTBUFFERSIZE);
printf("No buffersize specified... using \"%s\".\n", buffer);
}
//setup
if (encode)
{
QFile in("/dev/urandom");
if (!in.open(QIODevice::ReadOnly))
{
printf("ERROR: can not open \"/dev/urandom\"\n");
errno = EIO;
return errno;
}
if (in.read((char*)(&salt), IVSIZE) != IVSIZE)
{
in.close();
errno = EIO;
return -EIO;
}
in.close();
printf("Salt generated\n");
}
unsigned int bufferInt = atoi(buffer);
unsigned int mutationIntervalInt;
QFile in(inputFile);
if (!in.open(QIODevice::ReadOnly))
{
printf("ERROR: can not open inputfile\n");
errno = EIO;
return -errno;
}
QFile out(outputFile);
if (!out.open(QIODevice::WriteOnly))
{
printf("ERROR: can not open outputfile\n");
in.close();
errno = EIO;
return errno;
}
unsigned int fileSize = in.size();
if (encode)
{
mutationIntervalInt = atoi(mutationInterval);
uint32_t mutationInterval32 = mutationIntervalInt;
if (out.write((const char*)(&mutationInterval32), sizeof(mutationInterval32)) != sizeof(mutationInterval32))
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
if (out.write((const char*)(&salt), IVSIZE) != IVSIZE)
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
printf("Salt saved\n");
}
else
{
uint32_t mutationInterval32;
if (in.read((char*)(&mutationInterval32), sizeof(mutationInterval32)) != sizeof(mutationInterval32))
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
mutationIntervalInt = mutationInterval32;
fileSize -= sizeof(mutationInterval32);
printf("Mutationinterval loaded\n");
if (in.read((char*)(&salt), IVSIZE) != IVSIZE)
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
fileSize -= IVSIZE;
printf("Salt loaded\n");
}
Ring ring((const unsigned char*)key, strlen(key), (const unsigned char*)salt, IVSIZE, mutationIntervalInt);
unsigned int readBytes = 0;
char buf[bufferInt];
char verboseMessage[1+8+1+6+1];
//encode/decode
while (readBytes < fileSize)
{
if (verbose)//print
{
float progress = (100.0*readBytes)/fileSize;
if (encode)
{
sprintf(verboseMessage, "\rencoding %.1f%%", progress);
}
else
{
sprintf(verboseMessage, "\rdecoding %.1f%%", progress);
}
printf("%s", verboseMessage);
}
//read
unsigned int bytesToRead = bufferInt;
if (readBytes+bytesToRead > fileSize)
{
bytesToRead = fileSize - readBytes;
}
unsigned int readRet = in.read((char*)(&buf), bytesToRead);
readBytes += readRet;
#ifndef NDEBUG
assert(readRet == bytesToRead);
#endif
if (encode)
{
ring.encode((unsigned char*)buf, readRet);
}
else
{
ring.decode((unsigned char*)buf, readRet);
}
//write
unsigned int writtenBytes = 0;
while (writtenBytes < readRet)
{
unsigned int writeRet = out.write((const char*)((&buf)+writtenBytes), readRet);
writtenBytes += writeRet;
}
}
//finishing
if (verbose)
{
if (encode)
{
sprintf(verboseMessage, "\rencoding %.1f%%", 100.0);
}
else
{
sprintf(verboseMessage, "\rdecoding %.1f%%", 100.0);
}
printf("%s\n", verboseMessage);
}
in.close();
out.close();
if (removeSet)
{
if (remove(inputFile))
{
perror("WARNING: could not delete inputfile");
}
else
{
printf("Inputfile deleted\n");
}
}
printf("done\n");
return 0;
}
<commit_msg>removed linux optimisation<commit_after>#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <cassert>
#include "ring.hpp"
#include <stdint.h>
#include <QFile>
#define DEFAULTBUFFERSIZE 1024
#define DEFAULTMUTATIONINTERVAL 16
int main(int argc, char* argv[])
{
char inputFile[256+1];
char outputFile[256+1];
char key[MAPSIZE+1];
char salt[IVSIZE];
char mutationInterval[4+1];
char buffer[6+1];
char keyFile[256+1];
bool inputSet = false;
bool outputSet = false;
bool keySet = false;
bool encode = false;
bool decode = false;
bool mutationIntervalSet = false;
bool bufferSet = false;
bool keyFileSet = false;
bool verbose = false;
bool removeSet = false;
for (int i=0; i<argc; i++)//collect arguments from cmdline
{
if (strcmp(argv[i], "-in") == 0 || strcmp(argv[i], "-i") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(inputFile, argv[i]);
inputSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-out") == 0 || strcmp(argv[i], "-o") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(outputFile, argv[i]);
outputSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-password") == 0 || strcmp(argv[i], "-p") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(key, argv[i]);
keySet = true;
}
}
continue;
}
if (strcmp(argv[i], "-key") == 0 || strcmp(argv[i], "-k") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 256)
{
strcpy(keyFile, argv[i]);
keyFileSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-encode") == 0 || strcmp(argv[i], "-e") == 0)
{
encode = true;
continue;
}
if (strcmp(argv[i], "-decode") == 0 || strcmp(argv[i], "-d") == 0)
{
decode = true;
continue;
}
if (strcmp(argv[i], "-verbose") == 0 || strcmp(argv[i], "-v") == 0)
{
verbose = true;
continue;
}
if (strcmp(argv[i], "-remove") == 0 || strcmp(argv[i], "-r") == 0)
{
removeSet = true;
continue;
}
if (strcmp(argv[i], "-mutation") == 0 || strcmp(argv[i], "-m") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 4)
{
strcpy(mutationInterval, argv[i]);
mutationIntervalSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-buffer") == 0 || strcmp(argv[i], "-b") == 0)
{
i++;
if (i < argc)
{
if (strlen(argv[i]) <= 6)
{
strcpy(buffer, argv[i]);
bufferSet = true;
}
}
continue;
}
if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0)
{
printf("%s [-e|-d] [-i <inputfile>] [-o <outputfile>] [-p <password> | -k <keyfile>] [-m <mutationInterval>] [-b <buffersize>] [-v] [-r] [-h]\n", argv[0]);
printf("\n");
printf("Encodes or decodes a single file.\n");
printf("\n");
printf("-e\n");
printf("-encode\n");
printf("\tdefault\n");
printf("\toptional\n");
printf("\tSpecifies the mode as \"encode\".\n");
printf("\n");
printf("-d\n");
printf("-decode\n");
printf("\toptional\n");
printf("\tSpecifies the mode as \"decode\".\n");
printf("\n");
printf("-i <inputfile>\n");
printf("-in <inputfile>\n");
printf("\tmust\n");
printf("\tSpecifies the inputfile.\n");
printf("\n");
printf("-o <outputfile>\n");
printf("-out <outputfile>\n");
printf("\tmust\n");
printf("\tSpecifies the outputfile.\n");
printf("\n");
printf("-p <password>\n");
printf("-password <password>\n");
printf("\tmust\n");
printf("\tSpecifies the password.\n");
printf("\n");
printf("-k <keyfile>\n");
printf("-key <keyfile>\n");
printf("\toptional (alternative for -p)\n");
printf("\tSpecifies a keyfile.\n");
printf("\n");
printf("-m <mutationInterval>\n");
printf("-mutation <mutationInterval>\n");
printf("\tdefault: %u\n", DEFAULTMUTATIONINTERVAL);
printf("\toptional\n");
printf("\tSpecifies the mutationInterval.\n");
printf("\n");
printf("-b <buffersize>\n");
printf("-buffer <buffersize>\n");
printf("\tdefault: %u\n", DEFAULTBUFFERSIZE);
printf("\toptional\n");
printf("\tSpecifies the buffersize.\n");
printf("\n");
printf("-v\n");
printf("-verbose\n");
printf("\toptional\n");
printf("\tMakes the program verbose.\n");
printf("\n");
printf("-r\n");
printf("-remove\n");
printf("\toptional\n");
printf("\tRemoves the inputfile after reading.\n");
printf("\n");
printf("-h\n");
printf("-help\n");
printf("\toptional\n");
printf("\tPrints this helpmessage and quits the program.\n");
return 0;
}
}
//evaluate arguments
if (!inputSet)
{
printf("You need to specify an inputfile!\n");
return -EINVAL;
}
if (keySet && keyFileSet)
{
printf("You shall not specify a password and a keyfile!\n");
return -EINVAL;
}
if (!keySet && !keyFileSet)
{
printf("You need to specify a password or a keyfile!\n");
return -EINVAL;
}
if (encode && decode)
{
printf("You may only specify one mode!\n");
return -EINVAL;
}
if (keyFileSet)
{
QFile in(keyFile);
if (!in.open(QIODevice::ReadOnly))
{
printf("ERROR: can not open keyfile\n");
errno = EIO;
return -errno;
}
unsigned int fileSize = in.size();
if (fileSize > MAPSIZE)
{
printf("ERROR: keyfile is to large to contain a single key -> invalid\n");
in.close();
errno = EMSGSIZE;
return -EMSGSIZE;
}
if (in.read((char*)(&key), fileSize) != fileSize)
{
in.close();
errno = EIO;
return -EIO;
}
key[fileSize] = '\0';
in.close();
printf("Password read from keyfile.\n");
}
if (!encode && !decode)
{
encode = true;
printf("No mode specified... using \"encodemode\".\n");
}
if (!outputSet)
{
strcpy(outputFile, inputFile);
if (encode)
{
strcat(outputFile, ".enc");
}
else
{
strcat(outputFile, ".dec");
}
printf("No outputfile specified... using \"%s\".\n", outputFile);
}
if (!mutationIntervalSet && encode)
{
sprintf(mutationInterval, "%u", DEFAULTMUTATIONINTERVAL);
printf("No mutationInterval specified... using \"%s\".\n", mutationInterval);
}
if (!bufferSet)
{
sprintf(buffer, "%u", DEFAULTBUFFERSIZE);
printf("No buffersize specified... using \"%s\".\n", buffer);
}
//setup
if (encode)
{
QFile in("/dev/urandom");
if (!in.open(QIODevice::ReadOnly))
{
printf("ERROR: can not open \"/dev/urandom\"\n");
errno = EIO;
return errno;
}
if (in.read((char*)(&salt), IVSIZE) != IVSIZE)
{
in.close();
errno = EIO;
return -EIO;
}
in.close();
printf("Salt generated\n");
}
unsigned int bufferInt = atoi(buffer);
unsigned int mutationIntervalInt;
QFile in(inputFile);
if (!in.open(QIODevice::ReadOnly))
{
printf("ERROR: can not open inputfile\n");
errno = EIO;
return -errno;
}
QFile out(outputFile);
if (!out.open(QIODevice::WriteOnly))
{
printf("ERROR: can not open outputfile\n");
in.close();
errno = EIO;
return errno;
}
unsigned int fileSize = in.size();
if (encode)
{
mutationIntervalInt = atoi(mutationInterval);
uint32_t mutationInterval32 = mutationIntervalInt;
if (out.write((const char*)(&mutationInterval32), sizeof(mutationInterval32)) != sizeof(mutationInterval32))
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
if (out.write((const char*)(&salt), IVSIZE) != IVSIZE)
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
printf("Salt saved\n");
}
else
{
uint32_t mutationInterval32;
if (in.read((char*)(&mutationInterval32), sizeof(mutationInterval32)) != sizeof(mutationInterval32))
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
mutationIntervalInt = mutationInterval32;
fileSize -= sizeof(mutationInterval32);
printf("Mutationinterval loaded\n");
if (in.read((char*)(&salt), IVSIZE) != IVSIZE)
{
in.close();
out.close();
errno = EIO;
return -EIO;
}
fileSize -= IVSIZE;
printf("Salt loaded\n");
}
Ring ring((const unsigned char*)key, strlen(key), (const unsigned char*)salt, IVSIZE, mutationIntervalInt);
unsigned int readBytes = 0;
char buf[bufferInt];
char verboseMessage[1+8+1+6+1];
//encode/decode
while (readBytes < fileSize)
{
if (verbose)//print
{
float progress = (100.0*readBytes)/fileSize;
if (encode)
{
sprintf(verboseMessage, "\rencoding %.1f%%", progress);
}
else
{
sprintf(verboseMessage, "\rdecoding %.1f%%", progress);
}
printf("%s", verboseMessage);
}
//read
unsigned int bytesToRead = bufferInt;
if (readBytes+bytesToRead > fileSize)
{
bytesToRead = fileSize - readBytes;
}
unsigned int readRet = in.read((char*)(&buf), bytesToRead);
readBytes += readRet;
#ifndef NDEBUG
assert(readRet == bytesToRead);
#endif
if (encode)
{
ring.encode((unsigned char*)buf, readRet);
}
else
{
ring.decode((unsigned char*)buf, readRet);
}
//write
unsigned int writtenBytes = 0;
while (writtenBytes < readRet)
{
unsigned int writeRet = out.write((const char*)((&buf)+writtenBytes), readRet);
writtenBytes += writeRet;
}
}
//finishing
if (verbose)
{
if (encode)
{
sprintf(verboseMessage, "\rencoding %.1f%%", 100.0);
}
else
{
sprintf(verboseMessage, "\rdecoding %.1f%%", 100.0);
}
printf("%s\n", verboseMessage);
}
in.close();
out.close();
if (removeSet)
{
if (remove(inputFile))
{
perror("WARNING: could not delete inputfile");
}
else
{
printf("Inputfile deleted\n");
}
}
printf("done\n");
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include "url.h"
#include "robots.h"
namespace Rep
{
void Robots::strip(std::string& string)
{
string.erase(string.begin(), std::find_if(string.begin(), string.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
string.erase(std::find_if(string.rbegin(), string.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), string.end());
}
bool Robots::getpair(std::istringstream& stream, std::string& key, std::string& value)
{
while (getline(stream, key))
{
size_t index = key.find('#');
if (index != std::string::npos)
{
key.resize(index);
}
// Find the colon and divide it into key and value, skipping malformed lines
index = key.find(':');
if (index == std::string::npos)
{
continue;
}
value.assign(key.begin() + index + 1, key.end());
key.resize(index);
// Strip whitespace off of each
strip(key);
strip(value);
// Lowercase the key
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
return true;
}
return false;
}
Robots::Robots(const std::string& content): agents_(), sitemaps_(), default_(agents_["*"])
{
std::string agent_name("");
std::istringstream input(content);
std::string key, value;
std::vector<std::string> group;
bool last_agent = false;
agent_map_t::iterator current = agents_.find("*");
while (Robots::getpair(input, key, value))
{
if (key.compare("user-agent") == 0)
{
// Store the user agent string as lowercased
std::transform(value.begin(), value.end(), value.begin(), ::tolower);
if (last_agent)
{
group.push_back(value);
}
else
{
if (!agent_name.empty())
{
for (auto other : group)
{
agents_[other] = current->second;
}
group.clear();
}
agent_name = value;
current = agents_.emplace(agent_name, Agent()).first;
}
last_agent = true;
continue;
}
else
{
last_agent = false;
}
if (key.compare("sitemap") == 0)
{
sitemaps_.push_back(value);
}
else if (key.compare("disallow") == 0)
{
if (agent_name.empty())
{
throw std::invalid_argument("Need User-Agent");
}
current->second.disallow(value);
}
else if (key.compare("allow") == 0)
{
if (agent_name.empty())
{
throw std::invalid_argument("Need User-Agent");
}
current->second.allow(value);
}
else if (key.compare("crawl-delay") == 0)
{
if (agent_name.empty())
{
throw std::invalid_argument("Need User-Agent");
}
try
{
current->second.delay(std::stof(value));
}
catch (const std::exception&)
{
std::cerr << "Could not parse " << value << " as float." << std::endl;
}
}
}
if (!agent_name.empty())
{
for (auto other : group)
{
agents_[other] = current->second;
}
}
}
const Agent& Robots::agent(const std::string& name) const
{
// Lowercase the agent
std::string lowered(name);
std::transform(lowered.begin(), lowered.end(), lowered.begin(), ::tolower);
auto it = agents_.find(lowered);
if (it == agents_.end())
{
return default_;
}
else
{
return it->second;
}
}
bool Robots::allowed(const std::string& path, const std::string& name) const
{
return agent(name).allowed(path);
}
std::string Robots::robotsUrl(const std::string& url)
{
return Url::Url(url)
.setUserinfo("")
.setPath("robots.txt")
.setParams("")
.setQuery("")
.setFragment("")
.remove_default_port()
.str();
}
}
<commit_msg>Distinguish between exception cases for missing User-Agent.<commit_after>#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include "url.h"
#include "robots.h"
namespace Rep
{
void Robots::strip(std::string& string)
{
string.erase(string.begin(), std::find_if(string.begin(), string.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
string.erase(std::find_if(string.rbegin(), string.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), string.end());
}
bool Robots::getpair(std::istringstream& stream, std::string& key, std::string& value)
{
while (getline(stream, key))
{
size_t index = key.find('#');
if (index != std::string::npos)
{
key.resize(index);
}
// Find the colon and divide it into key and value, skipping malformed lines
index = key.find(':');
if (index == std::string::npos)
{
continue;
}
value.assign(key.begin() + index + 1, key.end());
key.resize(index);
// Strip whitespace off of each
strip(key);
strip(value);
// Lowercase the key
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
return true;
}
return false;
}
Robots::Robots(const std::string& content): agents_(), sitemaps_(), default_(agents_["*"])
{
std::string agent_name("");
std::istringstream input(content);
std::string key, value;
std::vector<std::string> group;
bool last_agent = false;
agent_map_t::iterator current = agents_.find("*");
while (Robots::getpair(input, key, value))
{
if (key.compare("user-agent") == 0)
{
// Store the user agent string as lowercased
std::transform(value.begin(), value.end(), value.begin(), ::tolower);
if (last_agent)
{
group.push_back(value);
}
else
{
if (!agent_name.empty())
{
for (auto other : group)
{
agents_[other] = current->second;
}
group.clear();
}
agent_name = value;
current = agents_.emplace(agent_name, Agent()).first;
}
last_agent = true;
continue;
}
else
{
last_agent = false;
}
if (key.compare("sitemap") == 0)
{
sitemaps_.push_back(value);
}
else if (key.compare("disallow") == 0)
{
if (agent_name.empty())
{
throw std::invalid_argument(
"Need User-Agent before Disallow");
}
current->second.disallow(value);
}
else if (key.compare("allow") == 0)
{
if (agent_name.empty())
{
throw std::invalid_argument(
"Need User-Agent before Allow");
}
current->second.allow(value);
}
else if (key.compare("crawl-delay") == 0)
{
if (agent_name.empty())
{
throw std::invalid_argument(
"Need User-Agent before Crawl-Delay");
}
try
{
current->second.delay(std::stof(value));
}
catch (const std::exception&)
{
std::cerr << "Could not parse " << value << " as float." << std::endl;
}
}
}
if (!agent_name.empty())
{
for (auto other : group)
{
agents_[other] = current->second;
}
}
}
const Agent& Robots::agent(const std::string& name) const
{
// Lowercase the agent
std::string lowered(name);
std::transform(lowered.begin(), lowered.end(), lowered.begin(), ::tolower);
auto it = agents_.find(lowered);
if (it == agents_.end())
{
return default_;
}
else
{
return it->second;
}
}
bool Robots::allowed(const std::string& path, const std::string& name) const
{
return agent(name).allowed(path);
}
std::string Robots::robotsUrl(const std::string& url)
{
return Url::Url(url)
.setUserinfo("")
.setPath("robots.txt")
.setParams("")
.setQuery("")
.setFragment("")
.remove_default_port()
.str();
}
}
<|endoftext|>
|
<commit_before>#include "Config.hpp"
#include "Geometry.hpp"
#include "Model.hpp"
#include "Print.hpp"
#include "TriangleMesh.hpp"
#include "Format/3mf.hpp"
#include "libslic3r.h"
#include "Utils.hpp"
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <math.h>
#include <boost/filesystem.hpp>
#include <boost/nowide/args.hpp>
#include <boost/nowide/iostream.hpp>
#ifdef USE_WX
// #include "GUI/GUI.hpp"
#endif
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/GUI_App.hpp"
using namespace Slic3r;
/// utility function for displaying CLI usage
void printUsage();
using namespace Slic3r;
int main(int argc, char **argv)
{
// Convert arguments to UTF-8 (needed on Windows). argv then points to memory owned by a.
//FIXME On Windows, we want to receive the arguments as 16bit characters!
boost::nowide::args a(argc, argv);
// parse all command line options into a DynamicConfig
DynamicPrintAndCLIConfig config;
t_config_option_keys input_files;
// if any option is unsupported, print usage and abort immediately
if (! config.read_cli(argc, argv, &input_files)) {
printUsage();
return 0;
}
boost::filesystem::path path_to_binary = boost::filesystem::system_complete(argv[0]);
boost::filesystem::path path_resources = path_to_binary.parent_path();
// Path from the Slic3r binary to its resources.
path_resources /= (path_to_binary.stem().string() == "slic3r-gui") ?
// Running from the build directory:
"../../resources" :
// Running from an installation directory:
#if APPLE
// The application is packed in the .dmg archive as 'Slic3r.app/Contents/MacOS/Slic3r'
// The resources are packed to 'Slic3r.app/Contents/Resources'
"../Resources"
#else
#if WIN32
// The application is packed in the .zip archive in the root,
// The resources are packed to 'resources'
// Path from Slic3r binary to resources:
"resources"
#else
// The application is packed in the .tar.bz archive (or in AppImage) as 'bin/slic3r',
// The resources are packed to 'resources'
// Path from Slic3r binary to resources:
"../resources"
#endif
#endif
;
set_resources_dir(path_resources.string());
set_var_dir((path_resources / "icons").string());
set_local_dir((path_resources / "localization").string());
// apply command line options to a more handy CLIConfig
CLIConfig cli_config;
cli_config.apply(config, true);
set_local_dir(cli_config.datadir.value);
DynamicPrintConfig print_config;
if ((argc == 1 || cli_config.gui.value) && ! cli_config.no_gui.value && ! cli_config.help.value && cli_config.save.value.empty()) {
#if 1
GUI::GUI_App *gui = new GUI::GUI_App();
GUI::GUI_App::SetInstance(gui);
wxEntry(argc, argv);
#else
std::cout << "GUI support has not been built." << "\n";
#endif
}
// load config files supplied via --load
for (const std::string &file : cli_config.load.values) {
if (!boost::filesystem::exists(file)) {
boost::nowide::cout << "No such file: " << file << std::endl;
exit(1);
}
DynamicPrintConfig c;
try {
c.load(file);
} catch (std::exception &e) {
boost::nowide::cout << "Error while reading config file: " << e.what() << std::endl;
exit(1);
}
c.normalize();
print_config.apply(c);
}
// apply command line options to a more specific DynamicPrintConfig which provides normalize()
// (command line options override --load files)
print_config.apply(config, true);
print_config.normalize();
// write config if requested
if (! cli_config.save.value.empty())
print_config.save(cli_config.save.value);
// read input file(s) if any
std::vector<Model> models;
for (const t_config_option_key &file : input_files) {
if (! boost::filesystem::exists(file)) {
boost::nowide::cerr << "No such file: " << file << std::endl;
exit(1);
}
Model model;
try {
model = Model::read_from_file(file);
} catch (std::exception &e) {
boost::nowide::cerr << file << ": " << e.what() << std::endl;
exit(1);
}
if (model.objects.empty()) {
boost::nowide::cerr << "Error: file is empty: " << file << std::endl;
continue;
}
model.add_default_instances();
// apply command line transform options
for (ModelObject* o : model.objects) {
/*
if (cli_config.scale_to_fit.is_positive_volume())
o->scale_to_fit(cli_config.scale_to_fit.value);
*/
// TODO: honor option order?
o->scale(cli_config.scale.value);
o->rotate(Geometry::deg2rad(cli_config.rotate_x.value), X);
o->rotate(Geometry::deg2rad(cli_config.rotate_y.value), Y);
o->rotate(Geometry::deg2rad(cli_config.rotate.value), Z);
}
// TODO: handle --merge
models.push_back(model);
}
if (cli_config.help) {
printUsage();
return 0;
}
for (Model &model : models) {
if (cli_config.info) {
// --info works on unrepaired model
model.print_info();
} else if (cli_config.export_3mf) {
std::string outfile = cli_config.output.value;
if (outfile.empty()) outfile = model.objects.front()->input_file;
// Check if the file is already a 3mf.
if(outfile.substr(outfile.find_last_of('.'), outfile.length()) == ".3mf")
outfile = outfile.substr(0, outfile.find_last_of('.')) + "_2" + ".3mf";
else
// Remove the previous extension and add .3mf extention.
outfile = outfile.substr(0, outfile.find_last_of('.')) + ".3mf";
store_3mf(outfile.c_str(), &model, nullptr, false);
boost::nowide::cout << "File file exported to " << outfile << std::endl;
} else if (cli_config.cut > 0) {
model.repair();
model.translate(0, 0, - model.bounding_box().min(2));
if (! model.objects.empty()) {
Model out;
model.objects.front()->cut(cli_config.cut, &out);
ModelObject &upper = *out.objects[0];
ModelObject &lower = *out.objects[1];
// Use the input name and trim off the extension.
std::string outfile = cli_config.output.value;
if (outfile.empty())
outfile = model.objects.front()->input_file;
outfile = outfile.substr(0, outfile.find_last_of('.'));
std::cerr << outfile << "\n";
if (upper.facets_count() > 0)
upper.mesh().write_binary((outfile + "_upper.stl").c_str());
if (lower.facets_count() > 0)
lower.mesh().write_binary((outfile + "_lower.stl").c_str());
}
} else if (cli_config.slice) {
std::string outfile = cli_config.output.value;
Print print;
model.arrange_objects(print.config().min_object_distance());
model.center_instances_around_point(cli_config.center);
if (outfile.empty()) outfile = model.objects.front()->input_file + ".gcode";
print.apply_config(print_config);
for (auto* mo : model.objects) {
print.auto_assign_extruders(mo);
print.add_model_object(mo);
}
print.validate();
print.export_gcode(outfile, nullptr);
} else {
boost::nowide::cerr << "error: command not supported" << std::endl;
return 1;
}
}
return 0;
}
void printUsage()
{
std::cout << "Slic3r " << SLIC3R_VERSION << " is a STL-to-GCODE translator for RepRap 3D printers" << "\n"
<< "written by Alessandro Ranellucci <aar@cpan.org> - http://slic3r.org/ - https://github.com/slic3r/Slic3r" << "\n"
// << "Git Version " << BUILD_COMMIT << "\n\n"
<< "Usage: ./slic3r [ OPTIONS ] [ file.stl ] [ file2.stl ] ..." << "\n";
// CLI Options
std::cout << "** CLI OPTIONS **\n";
print_cli_options(boost::nowide::cout);
std::cout << "****\n";
// Print options
std::cout << "** PRINT OPTIONS **\n";
print_print_options(boost::nowide::cout);
std::cout << "****\n";
}
<commit_msg>Yet another fix of platform specific paths to resources.<commit_after>#include "Config.hpp"
#include "Geometry.hpp"
#include "Model.hpp"
#include "Print.hpp"
#include "TriangleMesh.hpp"
#include "Format/3mf.hpp"
#include "libslic3r.h"
#include "Utils.hpp"
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <math.h>
#include <boost/filesystem.hpp>
#include <boost/nowide/args.hpp>
#include <boost/nowide/iostream.hpp>
#ifdef USE_WX
// #include "GUI/GUI.hpp"
#endif
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/GUI_App.hpp"
using namespace Slic3r;
/// utility function for displaying CLI usage
void printUsage();
using namespace Slic3r;
int main(int argc, char **argv)
{
// Convert arguments to UTF-8 (needed on Windows). argv then points to memory owned by a.
//FIXME On Windows, we want to receive the arguments as 16bit characters!
boost::nowide::args a(argc, argv);
// parse all command line options into a DynamicConfig
DynamicPrintAndCLIConfig config;
t_config_option_keys input_files;
// if any option is unsupported, print usage and abort immediately
if (! config.read_cli(argc, argv, &input_files)) {
printUsage();
return 0;
}
boost::filesystem::path path_to_binary = boost::filesystem::system_complete(argv[0]);
boost::filesystem::path path_resources = path_to_binary.parent_path();
// Path from the Slic3r binary to its resources.
path_resources /= (path_to_binary.stem().string() == "slic3r-gui") ?
// Running from the build directory:
"../../resources" :
// Running from an installation directory:
#ifdef __APPLE__
// The application is packed in the .dmg archive as 'Slic3r.app/Contents/MacOS/Slic3r'
// The resources are packed to 'Slic3r.app/Contents/Resources'
"../Resources"
#else
#ifdef _WIN32
// The application is packed in the .zip archive in the root,
// The resources are packed to 'resources'
// Path from Slic3r binary to resources:
"resources"
#else
// The application is packed in the .tar.bz archive (or in AppImage) as 'bin/slic3r',
// The resources are packed to 'resources'
// Path from Slic3r binary to resources:
"../resources"
#endif
#endif
;
set_resources_dir(path_resources.string());
set_var_dir((path_resources / "icons").string());
set_local_dir((path_resources / "localization").string());
// apply command line options to a more handy CLIConfig
CLIConfig cli_config;
cli_config.apply(config, true);
set_local_dir(cli_config.datadir.value);
DynamicPrintConfig print_config;
if ((argc == 1 || cli_config.gui.value) && ! cli_config.no_gui.value && ! cli_config.help.value && cli_config.save.value.empty()) {
#if 1
GUI::GUI_App *gui = new GUI::GUI_App();
GUI::GUI_App::SetInstance(gui);
wxEntry(argc, argv);
#else
std::cout << "GUI support has not been built." << "\n";
#endif
}
// load config files supplied via --load
for (const std::string &file : cli_config.load.values) {
if (!boost::filesystem::exists(file)) {
boost::nowide::cout << "No such file: " << file << std::endl;
exit(1);
}
DynamicPrintConfig c;
try {
c.load(file);
} catch (std::exception &e) {
boost::nowide::cout << "Error while reading config file: " << e.what() << std::endl;
exit(1);
}
c.normalize();
print_config.apply(c);
}
// apply command line options to a more specific DynamicPrintConfig which provides normalize()
// (command line options override --load files)
print_config.apply(config, true);
print_config.normalize();
// write config if requested
if (! cli_config.save.value.empty())
print_config.save(cli_config.save.value);
// read input file(s) if any
std::vector<Model> models;
for (const t_config_option_key &file : input_files) {
if (! boost::filesystem::exists(file)) {
boost::nowide::cerr << "No such file: " << file << std::endl;
exit(1);
}
Model model;
try {
model = Model::read_from_file(file);
} catch (std::exception &e) {
boost::nowide::cerr << file << ": " << e.what() << std::endl;
exit(1);
}
if (model.objects.empty()) {
boost::nowide::cerr << "Error: file is empty: " << file << std::endl;
continue;
}
model.add_default_instances();
// apply command line transform options
for (ModelObject* o : model.objects) {
/*
if (cli_config.scale_to_fit.is_positive_volume())
o->scale_to_fit(cli_config.scale_to_fit.value);
*/
// TODO: honor option order?
o->scale(cli_config.scale.value);
o->rotate(Geometry::deg2rad(cli_config.rotate_x.value), X);
o->rotate(Geometry::deg2rad(cli_config.rotate_y.value), Y);
o->rotate(Geometry::deg2rad(cli_config.rotate.value), Z);
}
// TODO: handle --merge
models.push_back(model);
}
if (cli_config.help) {
printUsage();
return 0;
}
for (Model &model : models) {
if (cli_config.info) {
// --info works on unrepaired model
model.print_info();
} else if (cli_config.export_3mf) {
std::string outfile = cli_config.output.value;
if (outfile.empty()) outfile = model.objects.front()->input_file;
// Check if the file is already a 3mf.
if(outfile.substr(outfile.find_last_of('.'), outfile.length()) == ".3mf")
outfile = outfile.substr(0, outfile.find_last_of('.')) + "_2" + ".3mf";
else
// Remove the previous extension and add .3mf extention.
outfile = outfile.substr(0, outfile.find_last_of('.')) + ".3mf";
store_3mf(outfile.c_str(), &model, nullptr, false);
boost::nowide::cout << "File file exported to " << outfile << std::endl;
} else if (cli_config.cut > 0) {
model.repair();
model.translate(0, 0, - model.bounding_box().min(2));
if (! model.objects.empty()) {
Model out;
model.objects.front()->cut(cli_config.cut, &out);
ModelObject &upper = *out.objects[0];
ModelObject &lower = *out.objects[1];
// Use the input name and trim off the extension.
std::string outfile = cli_config.output.value;
if (outfile.empty())
outfile = model.objects.front()->input_file;
outfile = outfile.substr(0, outfile.find_last_of('.'));
std::cerr << outfile << "\n";
if (upper.facets_count() > 0)
upper.mesh().write_binary((outfile + "_upper.stl").c_str());
if (lower.facets_count() > 0)
lower.mesh().write_binary((outfile + "_lower.stl").c_str());
}
} else if (cli_config.slice) {
std::string outfile = cli_config.output.value;
Print print;
model.arrange_objects(print.config().min_object_distance());
model.center_instances_around_point(cli_config.center);
if (outfile.empty()) outfile = model.objects.front()->input_file + ".gcode";
print.apply_config(print_config);
for (auto* mo : model.objects) {
print.auto_assign_extruders(mo);
print.add_model_object(mo);
}
print.validate();
print.export_gcode(outfile, nullptr);
} else {
boost::nowide::cerr << "error: command not supported" << std::endl;
return 1;
}
}
return 0;
}
void printUsage()
{
std::cout << "Slic3r " << SLIC3R_VERSION << " is a STL-to-GCODE translator for RepRap 3D printers" << "\n"
<< "written by Alessandro Ranellucci <aar@cpan.org> - http://slic3r.org/ - https://github.com/slic3r/Slic3r" << "\n"
// << "Git Version " << BUILD_COMMIT << "\n\n"
<< "Usage: ./slic3r [ OPTIONS ] [ file.stl ] [ file2.stl ] ..." << "\n";
// CLI Options
std::cout << "** CLI OPTIONS **\n";
print_cli_options(boost::nowide::cout);
std::cout << "****\n";
// Print options
std::cout << "** PRINT OPTIONS **\n";
print_print_options(boost::nowide::cout);
std::cout << "****\n";
}
<|endoftext|>
|
<commit_before>/*
* =====================================================================================
*
* Filename: socket.cpp
*
* Description: Socket control
*
* Version: 1.0
* Created: 27/01/13 20:55:15
* Revision: none
* Compiler: g++
*
* Author: Daniel Bugl <Daniel.Bugl@touchlay.com>
* Organization: TouchLay
*
* =====================================================================================
*/
// Headers
#include "socket.h"
/* Socket: Constructor */
Socket::Socket(int port) {
// Create socket
if ((tdata.listener=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cout << "[ERROR] [socket ] Couldn't create socket." << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "[INFO ] [socket ] Created socket at port " << port << "." << std::endl;
// Initialise sockaddr
struct sockaddr_in sockaddr;
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_port = htons(port); // Set port
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind socket
if (bind(tdata.listener, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0) {
std::cout << "[ERROR] [socket ] Couldn't bind to socket." << std::endl;
exit(EXIT_FAILURE);
}
#ifdef DEBUG
std::cout << "[DEBUG] [socket ] Bound to socket." << std::endl;
#endif
// Listen to socket
if (listen(tdata.listener, LISTENQ) < 0) {
std::cout << "[ERROR] [socket ] Couldn't listen to socket." << std::endl;
exit(EXIT_FAILURE);
}
#ifdef DEBUG
std::cout << "[DEBUG] [socket ] Listening to socket." << std::endl;
#endif
}
void *newconn(void *ptr) {
conndata *tdata;
tdata = (conndata *)ptr;
#ifdef DEBUG
std::cout << "[DEBUG] [child ] New connection. Forked child process." << std::endl;
#endif
if ((tdata->cip = inet_ntoa(tdata->client.sin_addr)) < 0) {
std::cout << "[ERROR] [child ] Failed to get peer address." << std::endl;
pthread_exit(0);
}
#ifdef DEBUG
std::cout << "[DEBUG] [child ] Peer address: " << tdata->cip << std::endl;
#endif
if (close(tdata->listener) < 0) std::cout << "[WARN ] [child ] Couldn't close socket." << std::endl;
RequestHandler(tdata->connection, tdata->cip); // Initialise request handler
if (close(tdata->connection) < 0) std::cout << "[WARN ] [child ] Couldn't close connection." << std::endl;
#ifdef DEBUG
std::cout << "[DEBUG] [child ] Connection closed. Killing child process." << std::endl;
#endif
pthread_exit(0); // Kill child process
}
/* loop: Main loop for the socket */
int Socket::loop() {
// Initialise client struct
sockaddr_in client;
client.sin_family = AF_INET;
socklen_t clen = sizeof(client);
tdata.cip = NULL;
pthread_t thread;
while (true) {
// Accept connection if available
if ((tdata.connection=accept(tdata.listener, (struct sockaddr*)&tdata.client, &clen)) < 0) { std::cout << "[WARN ] [socket ] Couldn't accept connection." << std::endl; continue; }
// New connection, create a new thread
pthread_create(&thread, NULL, newconn, (void *)&tdata);
pthread_join(thread, NULL);
// Cleanup
if (close(tdata.connection) < 0) { std::cout << "[WARN ] [socket ] Couldn't close connection." << std::endl; continue; }
}
return EXIT_FAILURE; // Something bad happened, exit parent
}
<commit_msg>Works a lot better now. Still blocking and showing error 400 though.<commit_after>/*
* =====================================================================================
*
* Filename: socket.cpp
*
* Description: Socket control
*
* Version: 1.0
* Created: 27/01/13 20:55:15
* Revision: none
* Compiler: g++
*
* Author: Daniel Bugl <Daniel.Bugl@touchlay.com>
* Organization: TouchLay
*
* =====================================================================================
*/
// Headers
#include "socket.h"
/* Socket: Constructor */
Socket::Socket(int port) {
// Create socket
if ((tdata.listener=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cout << "[ERROR] [socket ] Couldn't create socket." << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "[INFO ] [socket ] Created socket at port " << port << "." << std::endl;
// Initialise sockaddr
struct sockaddr_in sockaddr;
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_port = htons(port); // Set port
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind socket
if (bind(tdata.listener, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0) {
std::cout << "[ERROR] [socket ] Couldn't bind to socket." << std::endl;
exit(EXIT_FAILURE);
}
#ifdef DEBUG
std::cout << "[DEBUG] [socket ] Bound to socket." << std::endl;
#endif
// Listen to socket
if (listen(tdata.listener, LISTENQ) < 0) {
std::cout << "[ERROR] [socket ] Couldn't listen to socket." << std::endl;
exit(EXIT_FAILURE);
}
#ifdef DEBUG
std::cout << "[DEBUG] [socket ] Listening to socket." << std::endl;
#endif
}
void *newconn(void *ptr) {
conndata *tdata;
tdata = (conndata *)ptr;
#ifdef DEBUG
std::cout << "[DEBUG] [child ] New connection. Forked child process." << std::endl;
#endif
if ((tdata->cip = inet_ntoa(tdata->client.sin_addr)) < 0) {
std::cout << "[ERROR] [child ] Failed to get peer address." << std::endl;
pthread_exit(0);
}
#ifdef DEBUG
std::cout << "[DEBUG] [child ] Peer address: " << tdata->cip << std::endl;
#endif
//if (close(tdata->listener) < 0) std::cout << "[WARN ] [child ] Couldn't close socket." << std::endl;
RequestHandler(tdata->connection, tdata->cip); // Initialise request handler
if (close(tdata->connection) < 0) std::cout << "[WARN ] [child ] Couldn't close connection." << std::endl;
#ifdef DEBUG
std::cout << "[DEBUG] [child ] Connection closed. Killing child process." << std::endl;
#endif
pthread_exit(0); // Kill child process
}
/* loop: Main loop for the socket */
int Socket::loop() {
// Initialise client struct
sockaddr_in client;
client.sin_family = AF_INET;
socklen_t clen = sizeof(client);
tdata.cip = NULL;
while (true) {
pthread_t thread;
// Accept connection if available
if ((tdata.connection=accept(tdata.listener, (struct sockaddr*)&tdata.client, &clen)) < 0) { std::cout << "[WARN ] [socket ] Couldn't accept connection." << std::endl; continue; }
// New connection, create a new thread
pthread_create(&thread, NULL, newconn, (void *)&tdata);
pthread_join(thread, NULL);
pthread_cancel(thread);
}
return EXIT_FAILURE; // Something bad happened, exit parent
}
<|endoftext|>
|
<commit_before>// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include "cleanup.h"
// Include GLEW
#ifdef __APPLE_CC__
#include <OpenGL/gl3.h>
#define GLFW_INCLUDE_GLCOREARB
#else
#include "GL/glew.h"
#endif
#include "SDL.h"
#undef main
// Include GLM
#include "glm/glm.hpp"
#include <iostream>
#include <common/Init.h>
#include <common/Shader.h>
using namespace glm;
int main(int argc, char *argv[]) {
//First we need to start up SDL, and make sure it went ok
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
/* Request opengl 3.3 context.
* * SDL doesn't have the ability to choose which profile at this time of writing,
* * but it should default to the core profile */
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
/* Turn on double buffering with a 24bit Z buffer.
* * You may need to change this to 16 or 32 for your system */
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_OPENGL);
//Make sure creating our window went ok
if (win == nullptr) {
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 1;
}
SDL_GLContext glcontext = SDL_GL_CreateContext(win);
SDL_GL_MakeCurrent(win, glcontext);
Init init;
init.glew();
//Initialize GLEW
// glewExperimental = GL_TRUE;
// GLenum glewError = glewInit();
// if( glewError != GLEW_OK )
// {
// printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
// }
//Load in shaders
static ShaderProgram prog("../shaders/vertShader.vert", "../shaders/fragShader.frag");
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
SDL_Event e;
bool quit = false;
while (!quit) {
// Event polling
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = true;
}
}
glClearColor(0.3f, 0.3f, 0.3f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_BACK);
prog();
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void *) 0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle
glDisableVertexAttribArray(0);
SDL_GL_SwapWindow(win);
} // Check if the ESC key was pressed or the window was closed
// Clean up
SDL_GL_DeleteContext(glcontext);
cleanup(win);
SDL_Quit();
return 0;
}
<commit_msg>clarifying shader call in loop<commit_after>// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include "cleanup.h"
// Include GLEW
#ifdef __APPLE_CC__
#include <OpenGL/gl3.h>
#define GLFW_INCLUDE_GLCOREARB
#else
#include "GL/glew.h"
#endif
#include "SDL.h"
#undef main
// Include GLM
#include "glm/glm.hpp"
#include <iostream>
#include <common/Init.h>
#include <common/Shader.h>
using namespace glm;
int main(int argc, char *argv[]) {
//First we need to start up SDL, and make sure it went ok
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
/* Request opengl 3.3 context.
* * SDL doesn't have the ability to choose which profile at this time of writing,
* * but it should default to the core profile */
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
/* Turn on double buffering with a 24bit Z buffer.
* * You may need to change this to 16 or 32 for your system */
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_OPENGL);
//Make sure creating our window went ok
if (win == nullptr) {
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 1;
}
SDL_GLContext glcontext = SDL_GL_CreateContext(win);
SDL_GL_MakeCurrent(win, glcontext);
Init init;
init.glew();
//Initialize GLEW
// glewExperimental = GL_TRUE;
// GLenum glewError = glewInit();
// if( glewError != GLEW_OK )
// {
// printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
// }
//Load in shaders
static ShaderProgram prog("../shaders/vertShader.vert", "../shaders/fragShader.frag");
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
SDL_Event e;
bool quit = false;
while (!quit) {
// Event polling
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = true;
}
}
glClearColor(0.3f, 0.3f, 0.3f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_BACK);
prog(); // calls for glUseProgram
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void *) 0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle
glDisableVertexAttribArray(0);
SDL_GL_SwapWindow(win);
} // Check if the ESC key was pressed or the window was closed
// Clean up
SDL_GL_DeleteContext(glcontext);
cleanup(win);
SDL_Quit();
return 0;
}
<|endoftext|>
|
<commit_before>#include "tester.h"
#include <vector>
#include <optional>
#include <chrono>
#include "../base/gsl.h"
namespace tester
{
Report report;
static double _presicion = default_double_presicion;
auto& cases()
{
struct CaseData
{
const char* name;
Case::Procedure proc;
};
static std::vector<CaseData> data;
return data;
}
auto& subcase_stack()
{
struct AssertData
{
std::string first_fail;
size_t fail_count = 0;
};
struct SubcaseData
{
std::string name;
std::string section;
size_t child_count = 0;
size_t child_index = 0;
size_t assert_count = 0;
double presicion = 0;
std::vector<AssertData> fails;
void reset() { child_count = 0; assert_count = 0; }
};
static std::vector<SubcaseData> data;
return data;
}
auto& subcase_depth()
{
static size_t depth;
return depth;
}
//auto& parent_subcase() { return subcase_stack()[subcase_depth() - 1]; }
auto& subcase()
{
auto& stack = subcase_stack();
auto depth = subcase_depth();
Expects(depth < stack.size());
return stack[depth];
}
decltype(presicion) presicion(
[](double value)
{
if (subcase_stack().empty())
presicion = value;
else
subcase().presicion = value;
},
[]
{
return subcase_stack().empty() ?
_presicion :
subcase().presicion;
});
decltype(section) section(
[](std::string value)
{
if (!subcase_stack().empty())
subcase().section = std::move(value);
},
[]
{
return subcase_stack().empty() ? "" : subcase().section;
});
struct SubcaseInfo
{
std::string id;
size_t assert_count = 0;
size_t fail_count = 0;
};
SubcaseInfo subcase_report()
{
SubcaseInfo result;
auto& stack = subcase_stack();
for (size_t i = 0; i < stack.size(); ++i)
{
auto& level = stack[i];
result.id += "/" + level.name;
result.assert_count += level.assert_count;
for (auto& fail : level.fails) if (fail.fail_count > 0)
{
result.fail_count += 1;
report << fail.first_fail;
if (fail.fail_count > 1)
{
report <<
" (first failure, failed " << fail.fail_count << " times)\n";
}
report << "\n";
}
level.assert_count = 0;
level.fails.clear();
}
return result;
}
void increase_subcase_index()
{
auto& stack = subcase_stack();
while (!stack.empty())
{
auto& back = stack.back();
back.child_index += 1;
if (back.child_index < back.child_count)
return;
stack.pop_back();
}
return;
}
bool shall_enter()
{
auto& stack = subcase_stack();
if (subcase_depth() + 1 == stack.size())
{
const auto p = stack.back().presicion;
stack.emplace_back();
stack.back().presicion = p;
}
auto& parent = subcase();
return parent.child_index == parent.child_count;
}
Subcase::Subcase(std::string_view name)
: _shall_enter(shall_enter())
{
if (_shall_enter)
{
subcase_depth() += 1;
subcase().name = name;
subcase().reset();
}
}
Subcase::~Subcase()
{
if (_shall_enter)
subcase_depth() -= 1;
subcase().child_count += 1;
}
Repeat::Repeat(size_t count) :
_case("repeat(" + std::to_string(count) + ")"),
_count(_case._shall_enter ? count : 0)
{
}
void Assertion::increaseCount()
{
subcase().assert_count += 1;
}
bool Repeat::iterator::operator!=(const iterator& other) const
{
if (_i != other._i)
{
subcase().reset();
return true;
}
return false;
}
void runTests()
{
using namespace std::chrono;
auto then = high_resolution_clock::now();
size_t subcase_count = 0;
size_t assert_count = 0;
size_t fail_count = 0;
for (auto& test : cases())
{
Expects(subcase_stack().empty());
subcase_stack().emplace_back();
subcase().name = test.name;
subcase().presicion = _presicion;
int i = 0;
while (!subcase_stack().empty())
{
subcase_count += 1;
subcase().reset();
test.proc();
auto info = subcase_report();
if (info.fail_count > 0)
report << "subcase " << info.id << " done\n"
<< info.assert_count << " assertions\n"
<< info.fail_count << " failures\n\n";
assert_count += info.assert_count;
fail_count += info.fail_count;
increase_subcase_index();
++i;
}
}
auto dt = duration<double>(high_resolution_clock::now() - then);
report << "tests done in " << dt.count() << "s\n"
<< cases().size() << " cases\n"
<< subcase_count << " subcases\n"
<< assert_count << " asserts\n"
<< fail_count << " failures\n";
}
Subreport::~Subreport()
{
seekp(0, std::ios::end);
auto size = size_t(tellp());
if (size != 0)
subcase().fails[subcase().assert_count - 1].first_fail = str();
}
bool report_failure()
{
auto& subc = subcase();
if (subc.fails.size() < subc.assert_count)
subc.fails.resize(subc.assert_count);
auto& fail = subc.fails[subc.assert_count - 1];
fail.fail_count += 1;
return fail.fail_count == 1;
}
std::ostream& operator<<(std::ostream& out, const Assertion& test)
{
for (auto& subcase : subcase_stack())
{
out << '/' << subcase.name;
if (!subcase.section.empty())
out << ':' << subcase.section;
}
return out << '\n' <<
test.file << '(' << test.line << ')' << '\n' <<
" " << test.expr << '\n';
}
std::ostream& operator<<(std::ostream& out, Op op)
{
switch (op)
{
case Op::E: return out << "==";
case Op::NE: return out << "!=";
case Op::L: return out << "<";
case Op::LE: return out << "<=";
case Op::GE: return out << ">=";
case Op::G: return out << ">";
default: return out << "!!";
}
}
Case Case::operator<<(Procedure proc) &&
{
cases().push_back({ _name, proc });
return *this;
}
}
<commit_msg>Changed section/presicion logic so that the presicion Parameter is reset to the default for the subcase for each new section<commit_after>#include "tester.h"
#include <vector>
#include <optional>
#include <chrono>
#include "../base/gsl.h"
namespace tester
{
Report report;
static double _presicion = default_double_presicion;
auto& cases()
{
struct CaseData
{
const char* name;
Case::Procedure proc;
};
static std::vector<CaseData> data;
return data;
}
auto& subcase_stack()
{
struct AssertData
{
std::string first_fail;
size_t fail_count = 0;
};
struct SubcaseData
{
std::string name;
std::string section;
size_t child_count = 0;
size_t child_index = 0;
size_t assert_count = 0;
double presicion = 0;
std::vector<AssertData> fails;
void reset() { child_count = 0; assert_count = 0; }
};
static std::vector<SubcaseData> data;
return data;
}
auto& subcase_depth()
{
static size_t depth;
return depth;
}
//auto& parent_subcase() { return subcase_stack()[subcase_depth() - 1]; }
auto& subcase()
{
auto& stack = subcase_stack();
auto depth = subcase_depth();
Expects(depth < stack.size());
return stack[depth];
}
decltype(presicion) presicion(
[](double value)
{
if (subcase_stack().empty())
_presicion = value;
else
subcase().presicion = value;
},
[]
{
return subcase_stack().empty() ?
_presicion :
subcase().presicion;
});
decltype(section) section(
[](std::string value)
{
auto& stack = subcase_stack();
const auto depth = subcase_depth();
if (depth < stack.size())
{
stack[depth].section = std::move(value);
stack[depth].presicion = depth > 0 ? stack[depth - 1].presicion : _presicion;
}
},
[]
{
return subcase_stack().empty() ? "" : subcase().section;
});
struct SubcaseInfo
{
std::string id;
size_t assert_count = 0;
size_t fail_count = 0;
};
SubcaseInfo subcase_report()
{
SubcaseInfo result;
auto& stack = subcase_stack();
for (size_t i = 0; i < stack.size(); ++i)
{
auto& level = stack[i];
result.id += "/" + level.name;
result.assert_count += level.assert_count;
for (auto& fail : level.fails) if (fail.fail_count > 0)
{
result.fail_count += 1;
report << fail.first_fail;
if (fail.fail_count > 1)
{
report <<
" (first failure, failed " << fail.fail_count << " times)\n";
}
report << "\n";
}
level.assert_count = 0;
level.fails.clear();
}
return result;
}
void increase_subcase_index()
{
auto& stack = subcase_stack();
while (!stack.empty())
{
auto& back = stack.back();
back.child_index += 1;
if (back.child_index < back.child_count)
return;
stack.pop_back();
}
return;
}
bool shall_enter()
{
auto& stack = subcase_stack();
if (subcase_depth() + 1 == stack.size())
{
const auto p = stack.back().presicion;
stack.emplace_back();
stack.back().presicion = p;
}
auto& parent = subcase();
return parent.child_index == parent.child_count;
}
Subcase::Subcase(std::string_view name)
: _shall_enter(shall_enter())
{
if (_shall_enter)
{
subcase_depth() += 1;
subcase().name = name;
subcase().reset();
}
}
Subcase::~Subcase()
{
if (_shall_enter)
subcase_depth() -= 1;
subcase().child_count += 1;
}
Repeat::Repeat(size_t count) :
_case("repeat(" + std::to_string(count) + ")"),
_count(_case._shall_enter ? count : 0)
{
}
void Assertion::increaseCount()
{
subcase().assert_count += 1;
}
bool Repeat::iterator::operator!=(const iterator& other) const
{
if (_i != other._i)
{
subcase().reset();
return true;
}
return false;
}
void runTests()
{
using namespace std::chrono;
auto then = high_resolution_clock::now();
size_t subcase_count = 0;
size_t assert_count = 0;
size_t fail_count = 0;
for (auto& test : cases())
{
Expects(subcase_stack().empty());
subcase_stack().emplace_back();
subcase().name = test.name;
subcase().presicion = _presicion;
int i = 0;
while (!subcase_stack().empty())
{
subcase_count += 1;
subcase().reset();
test.proc();
auto info = subcase_report();
if (info.fail_count > 0)
report << "subcase " << info.id << " done\n"
<< info.assert_count << " assertions\n"
<< info.fail_count << " failures\n\n";
assert_count += info.assert_count;
fail_count += info.fail_count;
increase_subcase_index();
++i;
}
}
auto dt = duration<double>(high_resolution_clock::now() - then);
report << "tests done in " << dt.count() << "s\n"
<< cases().size() << " cases\n"
<< subcase_count << " subcases\n"
<< assert_count << " asserts\n"
<< fail_count << " failures\n";
}
Subreport::~Subreport()
{
seekp(0, std::ios::end);
auto size = size_t(tellp());
if (size != 0)
subcase().fails[subcase().assert_count - 1].first_fail = str();
}
bool report_failure()
{
auto& subc = subcase();
if (subc.fails.size() < subc.assert_count)
subc.fails.resize(subc.assert_count);
auto& fail = subc.fails[subc.assert_count - 1];
fail.fail_count += 1;
return fail.fail_count == 1;
}
std::ostream& operator<<(std::ostream& out, const Assertion& test)
{
for (auto& subcase : subcase_stack())
{
out << '/' << subcase.name;
if (!subcase.section.empty())
out << ':' << subcase.section;
}
return out << '\n' <<
test.file << '(' << test.line << ')' << '\n' <<
" " << test.expr << '\n';
}
std::ostream& operator<<(std::ostream& out, Op op)
{
switch (op)
{
case Op::E: return out << "==";
case Op::NE: return out << "!=";
case Op::L: return out << "<";
case Op::LE: return out << "<=";
case Op::GE: return out << ">=";
case Op::G: return out << ">";
default: return out << "!!";
}
}
Case Case::operator<<(Procedure proc) &&
{
cases().push_back({ _name, proc });
return *this;
}
}
<|endoftext|>
|
<commit_before>// -*- mode: c++; coding: utf-8 -*-
/*! @file tissue.h
@brief Interface of Tissue class
*/
#pragma once
#ifndef TISSUE_HPP_
#define TISSUE_HPP_
#include <iostream>
#include <vector>
#include <valarray>
#include <unordered_set>
#include <memory>
#include <string>
#include <boost/functional/hash.hpp>
#include "cell.hpp"
#include "coord.hpp"
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace boost {
namespace program_options {
class options_description;
}
}
namespace std {
template <> struct hash<std::valarray<int>> {
size_t operator() (const std::valarray<int>& v) const {
return boost::hash_range(std::begin(v), std::end(v));
}
};
template <> struct hash<std::shared_ptr<tumopp::Cell>> {
size_t operator() (const std::shared_ptr<tumopp::Cell>& x) const {
return std::hash<std::valarray<int>>()(x->coord());
}
};
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace tumopp {
inline bool all(const std::valarray<bool>& v) {
return std::all_of(std::begin(v), std::end(v), [](bool x){return x;});
}
class equal_shptr_cell {
public:
bool operator() (const std::shared_ptr<tumopp::Cell>& lhs,
const std::shared_ptr<tumopp::Cell>& rhs) const {
return all(lhs->coord() == rhs->coord());
}
};
class Tissue {
public:
static size_t DIMENSIONS() {return DIMENSIONS_;}
//! Constructor
Tissue() = default;
//! main function
bool grow(const size_t max_size);
std::ostream& write_segsites(std::ostream&, const std::vector<std::shared_ptr<Cell>>&) const;
std::vector<std::shared_ptr<Cell>> sample_random(const size_t) const;
std::vector<std::shared_ptr<Cell>> sample_section(const size_t) const;
std::string specimens() const {return specimens_.str();}
std::string snapshots() const {return snapshots_.str();}
std::string drivers() const {return drivers_.str();}
std::string pairwise_distance(const size_t npair) const;
void write(std::ostream&) const;
friend std::ostream& operator<< (std::ostream&, const Tissue&);
size_t size() const {return tumor_.size();};
double radius() const {return coord_func_->radius(tumor_.size());}
double relative_pos(std::shared_ptr<Cell> x) const {
return coord_func_->euclidean_distance(x->coord()) / radius();
}
//! Set coordinate function object
template <class FuncObj>
void set_coord() {coord_func_ = std::make_unique<FuncObj>(DIMENSIONS_);}
const std::unique_ptr<Coord>& coord_func() const {return coord_func_;}
//! Unit test
static void unit_test();
static boost::program_options::options_description opt_description();
private:
//! Dimensions: {1, 2, 3}
static size_t DIMENSIONS_;
//! Coordinate system
static std::string COORDINATE_;
//! {const, step, linear}
static std::string LOCAL_DENSITY_EFFECT_;
//! {random, mindrag, minstraight}
static std::string DISPLACEMENT_PATH_;
//! 0: flat, +: peripheral growth
static double SIGMA_E_;
//! initial population size
static size_t INITIAL_SIZE_;
//! a flag
static size_t RECORDING_EARLY_GROWTH_;
void init();
void init_coord();
void init_insert_function();
std::function<bool(const std::shared_ptr<Cell>&)> insert;
//! Swap with a random neighbor
void migrate(const std::shared_ptr<Cell>&);
//! Emplace daughter cell and push other cells to the direction
void push(std::shared_ptr<Cell> moving, const std::valarray<int>& direction);
//! Push through the minimum drag path
void push_minimum_drag(std::shared_ptr<Cell> moving);
//! Try insert_adjacent() on every step in push()
void stroll(std::shared_ptr<Cell> moving, const std::valarray<int>& direction);
//! Insert x if any adjacent node is empty
bool insert_adjacent(const std::shared_ptr<Cell>& x);
//! Put new cell and return existing.
bool swap_existing(std::shared_ptr<Cell>* x);
//! Count steps to the nearest empty
size_t steps_to_empty(std::valarray<int> current, const std::valarray<int>& direction) const;
//! Direction to the nearest empty
std::valarray<int> to_nearest_empty(const std::valarray<int>& current, size_t search_max=26) const;
size_t num_empty_neighbors(const std::valarray<int>&) const;
double proportion_empty_neighbors(const std::valarray<int>& coord) const {
double x = static_cast<double>(num_empty_neighbors(coord));
return x /= static_cast<double>(coord_func_->directions().size());
}
void queue_push(const std::shared_ptr<Cell>&);
double positional_value(const std::valarray<int>&) const;
std::vector<size_t> generate_neutral_mutations() const;
std::string header() const;
void write(std::ostream&, const Cell&) const;
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Data member
//! cells
std::unordered_set<
std::shared_ptr<Cell>,
std::hash<std::shared_ptr<Cell>>,
equal_shptr_cell> tumor_;
//! event queue
std::multimap<double, std::shared_ptr<Cell>> queue_;
double time_ = 0.0;
size_t id_tail_ = 0;
std::unique_ptr<Coord> coord_func_;
std::ostringstream specimens_;
std::ostringstream snapshots_;
std::ostringstream drivers_;
const char* sep_ = "\t";
};
} // namespace tumopp
#endif /* TISSUE_HPP_ */
<commit_msg>Use std::valarray<bool>::min() instead of std::all_of()<commit_after>// -*- mode: c++; coding: utf-8 -*-
/*! @file tissue.h
@brief Interface of Tissue class
*/
#pragma once
#ifndef TISSUE_HPP_
#define TISSUE_HPP_
#include <iostream>
#include <vector>
#include <valarray>
#include <unordered_set>
#include <memory>
#include <string>
#include <boost/functional/hash.hpp>
#include "cell.hpp"
#include "coord.hpp"
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace boost {
namespace program_options {
class options_description;
}
}
namespace std {
template <> struct hash<std::valarray<int>> {
size_t operator() (const std::valarray<int>& v) const {
return boost::hash_range(std::begin(v), std::end(v));
}
};
template <> struct hash<std::shared_ptr<tumopp::Cell>> {
size_t operator() (const std::shared_ptr<tumopp::Cell>& x) const {
return std::hash<std::valarray<int>>()(x->coord());
}
};
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace tumopp {
class equal_shptr_cell {
public:
bool operator() (const std::shared_ptr<tumopp::Cell>& lhs,
const std::shared_ptr<tumopp::Cell>& rhs) const {
return (lhs->coord() == rhs->coord()).min();
}
};
class Tissue {
public:
static size_t DIMENSIONS() {return DIMENSIONS_;}
//! Constructor
Tissue() = default;
//! main function
bool grow(const size_t max_size);
std::ostream& write_segsites(std::ostream&, const std::vector<std::shared_ptr<Cell>>&) const;
std::vector<std::shared_ptr<Cell>> sample_random(const size_t) const;
std::vector<std::shared_ptr<Cell>> sample_section(const size_t) const;
std::string specimens() const {return specimens_.str();}
std::string snapshots() const {return snapshots_.str();}
std::string drivers() const {return drivers_.str();}
std::string pairwise_distance(const size_t npair) const;
void write(std::ostream&) const;
friend std::ostream& operator<< (std::ostream&, const Tissue&);
size_t size() const {return tumor_.size();};
double radius() const {return coord_func_->radius(tumor_.size());}
double relative_pos(std::shared_ptr<Cell> x) const {
return coord_func_->euclidean_distance(x->coord()) / radius();
}
//! Set coordinate function object
template <class FuncObj>
void set_coord() {coord_func_ = std::make_unique<FuncObj>(DIMENSIONS_);}
const std::unique_ptr<Coord>& coord_func() const {return coord_func_;}
//! Unit test
static void unit_test();
static boost::program_options::options_description opt_description();
private:
//! Dimensions: {1, 2, 3}
static size_t DIMENSIONS_;
//! Coordinate system
static std::string COORDINATE_;
//! {const, step, linear}
static std::string LOCAL_DENSITY_EFFECT_;
//! {random, mindrag, minstraight}
static std::string DISPLACEMENT_PATH_;
//! 0: flat, +: peripheral growth
static double SIGMA_E_;
//! initial population size
static size_t INITIAL_SIZE_;
//! a flag
static size_t RECORDING_EARLY_GROWTH_;
void init();
void init_coord();
void init_insert_function();
std::function<bool(const std::shared_ptr<Cell>&)> insert;
//! Swap with a random neighbor
void migrate(const std::shared_ptr<Cell>&);
//! Emplace daughter cell and push other cells to the direction
void push(std::shared_ptr<Cell> moving, const std::valarray<int>& direction);
//! Push through the minimum drag path
void push_minimum_drag(std::shared_ptr<Cell> moving);
//! Try insert_adjacent() on every step in push()
void stroll(std::shared_ptr<Cell> moving, const std::valarray<int>& direction);
//! Insert x if any adjacent node is empty
bool insert_adjacent(const std::shared_ptr<Cell>& x);
//! Put new cell and return existing.
bool swap_existing(std::shared_ptr<Cell>* x);
//! Count steps to the nearest empty
size_t steps_to_empty(std::valarray<int> current, const std::valarray<int>& direction) const;
//! Direction to the nearest empty
std::valarray<int> to_nearest_empty(const std::valarray<int>& current, size_t search_max=26) const;
size_t num_empty_neighbors(const std::valarray<int>&) const;
double proportion_empty_neighbors(const std::valarray<int>& coord) const {
double x = static_cast<double>(num_empty_neighbors(coord));
return x /= static_cast<double>(coord_func_->directions().size());
}
void queue_push(const std::shared_ptr<Cell>&);
double positional_value(const std::valarray<int>&) const;
std::vector<size_t> generate_neutral_mutations() const;
std::string header() const;
void write(std::ostream&, const Cell&) const;
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Data member
//! cells
std::unordered_set<
std::shared_ptr<Cell>,
std::hash<std::shared_ptr<Cell>>,
equal_shptr_cell> tumor_;
//! event queue
std::multimap<double, std::shared_ptr<Cell>> queue_;
double time_ = 0.0;
size_t id_tail_ = 0;
std::unique_ptr<Coord> coord_func_;
std::ostringstream specimens_;
std::ostringstream snapshots_;
std::ostringstream drivers_;
const char* sep_ = "\t";
};
} // namespace tumopp
#endif /* TISSUE_HPP_ */
<|endoftext|>
|
<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <SDL_opengl.h>
#include <list>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include "tunnel.hxx"
#include "distortion.hxx"
using namespace std;
Tunnel::Tunnel()
: offset(0), clock(0)
{
//Create initial pulses
for (unsigned off = 0; off < gridLength; off += 32) {
for (unsigned i = 0; i < gridWidth; ++i) {
pulse(off*gsqlen, i, +0.5f, +0.5f, +0.5f, +5.0f, 0);
pulse(off*gsqlen, i, -0.5f, -0.5f, -0.5f, -5.0f, 0);
}
}
}
void Tunnel::update(float et) {
clock += et;
//Dequeue pulses whose time has come
while (!pulseQueue.empty() && pulseQueue.top().when < clock) {
const QueuedPulse& qp = pulseQueue.top();
pulses[qp.column].push_back(qp.pulse);
if (pulses[qp.column].size() > maxPulses)
pulses[qp.column].pop_front();
pulseQueue.pop();
}
//Update pulses
for (unsigned col = 0; col < gridWidth; ++col) {
for (list<Pulse>::iterator it = pulses[col].begin();
it != pulses[col].end(); ++it) {
Pulse& p(*it);
p.coord += p.speed * et;
while (p.coord < 0) p.coord += gridLength;
while (p.coord >= gridLength) p.coord -= gridLength;
}
}
}
void Tunnel::draw(const Distortion& d) {
//Reset grid to neutral
for (unsigned i = 0; i < gridLength; ++i)
for (unsigned j = 0; j < gridWidth; ++j)
for (unsigned k = 0; k < 3; ++k)
grid[i][j][k] = 0.5f;
//Add in pulses
for (unsigned col = 0; col < gridWidth; ++col) {
for (list<Pulse>::const_iterator it = pulses[col].begin();
it != pulses[col].end(); ++it) {
const Pulse& p(*it);
unsigned lower = (unsigned)floor(p.coord);
unsigned upper = (unsigned)ceil(p.coord);
if (upper == gridLength)
upper = 0;
float uw = p.coord - lower;
float lw = 1.0f - uw;
grid[lower][col][0] += lw*p.dr;
grid[upper][col][0] += uw*p.dr;
grid[lower][col][1] += lw*p.dg;
grid[upper][col][1] += uw*p.dg;
grid[lower][col][2] += lw*p.db;
grid[upper][col][2] += uw*p.db;
}
}
//Translate for partial squares
float zt = (floor(offset)-offset)*gsqlen;
glBegin(GL_TRIANGLES);
//Draw the floor
signed firstFloorTile = (signed)floor(offset);
if (firstFloorTile < 0)
firstFloorTile += gridLength;
const float halfSpace = gsqsz*0.05f;
for (unsigned z = 0; z < gridLength/2; ++z) {
for (unsigned x = 0; x < gridWidth; ++x) {
glColor3fv(grid[(firstFloorTile+z) % gridLength][x]);
d.v((x+0)*gsqsz + halfSpace, 0, -((z+0)*gsqlen + halfSpace + zt));
d.v((x+1)*gsqsz - halfSpace, 0, -((z+0)*gsqlen + halfSpace + zt));
d.v((x+0)*gsqsz + halfSpace, 0, -((z+1)*gsqlen - halfSpace + zt));
d.v((x+1)*gsqsz - halfSpace, 0, -((z+0)*gsqlen + halfSpace + zt));
d.v((x+0)*gsqsz + halfSpace, 0, -((z+1)*gsqlen - halfSpace + zt));
d.v((x+1)*gsqsz - halfSpace, 0, -((z+1)*gsqlen - halfSpace + zt));
}
}
//Draw the walls
unsigned firstWallTile = firstFloorTile + gridLength / 2;
for (unsigned z = 0; z < gridLength / 2; ++z) {
for (unsigned i = 0; i < gridWidth; ++i) {
glColor3fv(grid[(firstWallTile + (gridLength/2-z-1)) % gridLength][i]);
float x = (i < gridWidth / 2? 0 : 1);
float y = 2*(i < gridWidth / 2? i*gsqsz : (gridWidth-i-1)*gsqsz);
d.v(x, y + 0.0f*2 + halfSpace, -((z+0)*gsqlen + halfSpace + zt));
d.v(x, y + gsqsz*2 - halfSpace, -((z+0)*gsqlen + halfSpace + zt));
d.v(x, y + 0.0f*2 + halfSpace, -((z+1)*gsqlen - halfSpace + zt));
d.v(x, y + gsqsz*2 - halfSpace, -((z+0)*gsqlen + halfSpace + zt));
d.v(x, y + 0.0f*2 + halfSpace, -((z+1)*gsqlen - halfSpace + zt));
d.v(x, y + gsqsz*2 - halfSpace, -((z+1)*gsqlen - halfSpace + zt));
}
}
glEnd();
}
void Tunnel::pulse(float z, unsigned col,
float r, float g, float b,
float speed, float delay) {
Pulse pulse = { -z/gsqlen + offset, speed, r, g, b };
QueuedPulse qp = { col, clock + delay, pulse };
pulseQueue.push(qp);
}
void Tunnel::translateZ(float amt) {
offset -= amt;
while (offset >= gridLength)
offset -= gridLength;
while (offset < 0)
offset += gridLength;
}
<commit_msg>Fix Tunnel translation rate.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <SDL_opengl.h>
#include <list>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include "tunnel.hxx"
#include "distortion.hxx"
using namespace std;
Tunnel::Tunnel()
: offset(0), clock(0)
{
//Create initial pulses
for (unsigned off = 0; off < gridLength; off += 32) {
for (unsigned i = 0; i < gridWidth; ++i) {
pulse(off*gsqlen, i, +0.5f, +0.5f, +0.5f, +5.0f, 0);
pulse(off*gsqlen, i, -0.5f, -0.5f, -0.5f, -5.0f, 0);
}
}
}
void Tunnel::update(float et) {
clock += et;
//Dequeue pulses whose time has come
while (!pulseQueue.empty() && pulseQueue.top().when < clock) {
const QueuedPulse& qp = pulseQueue.top();
pulses[qp.column].push_back(qp.pulse);
if (pulses[qp.column].size() > maxPulses)
pulses[qp.column].pop_front();
pulseQueue.pop();
}
//Update pulses
for (unsigned col = 0; col < gridWidth; ++col) {
for (list<Pulse>::iterator it = pulses[col].begin();
it != pulses[col].end(); ++it) {
Pulse& p(*it);
p.coord += p.speed * et;
while (p.coord < 0) p.coord += gridLength;
while (p.coord >= gridLength) p.coord -= gridLength;
}
}
}
void Tunnel::draw(const Distortion& d) {
//Reset grid to neutral
for (unsigned i = 0; i < gridLength; ++i)
for (unsigned j = 0; j < gridWidth; ++j)
for (unsigned k = 0; k < 3; ++k)
grid[i][j][k] = 0.5f;
//Add in pulses
for (unsigned col = 0; col < gridWidth; ++col) {
for (list<Pulse>::const_iterator it = pulses[col].begin();
it != pulses[col].end(); ++it) {
const Pulse& p(*it);
unsigned lower = (unsigned)floor(p.coord);
unsigned upper = (unsigned)ceil(p.coord);
if (upper == gridLength)
upper = 0;
float uw = p.coord - lower;
float lw = 1.0f - uw;
grid[lower][col][0] += lw*p.dr;
grid[upper][col][0] += uw*p.dr;
grid[lower][col][1] += lw*p.dg;
grid[upper][col][1] += uw*p.dg;
grid[lower][col][2] += lw*p.db;
grid[upper][col][2] += uw*p.db;
}
}
//Translate for partial squares
float zt = (floor(offset)-offset)*gsqlen;
glBegin(GL_TRIANGLES);
//Draw the floor
signed firstFloorTile = (signed)floor(offset);
if (firstFloorTile < 0)
firstFloorTile += gridLength;
const float halfSpace = gsqsz*0.05f;
for (unsigned z = 0; z < gridLength/2; ++z) {
for (unsigned x = 0; x < gridWidth; ++x) {
glColor3fv(grid[(firstFloorTile+z) % gridLength][x]);
d.v((x+0)*gsqsz + halfSpace, 0, -((z+0)*gsqlen + halfSpace + zt));
d.v((x+1)*gsqsz - halfSpace, 0, -((z+0)*gsqlen + halfSpace + zt));
d.v((x+0)*gsqsz + halfSpace, 0, -((z+1)*gsqlen - halfSpace + zt));
d.v((x+1)*gsqsz - halfSpace, 0, -((z+0)*gsqlen + halfSpace + zt));
d.v((x+0)*gsqsz + halfSpace, 0, -((z+1)*gsqlen - halfSpace + zt));
d.v((x+1)*gsqsz - halfSpace, 0, -((z+1)*gsqlen - halfSpace + zt));
}
}
//Draw the walls
unsigned firstWallTile = firstFloorTile + gridLength / 2;
for (unsigned z = 0; z < gridLength / 2; ++z) {
for (unsigned i = 0; i < gridWidth; ++i) {
glColor3fv(grid[(firstWallTile + (gridLength/2-z-1)) % gridLength][i]);
float x = (i < gridWidth / 2? 0 : 1);
float y = 2*(i < gridWidth / 2? i*gsqsz : (gridWidth-i-1)*gsqsz);
d.v(x, y + 0.0f*2 + halfSpace, -((z+0)*gsqlen + halfSpace + zt));
d.v(x, y + gsqsz*2 - halfSpace, -((z+0)*gsqlen + halfSpace + zt));
d.v(x, y + 0.0f*2 + halfSpace, -((z+1)*gsqlen - halfSpace + zt));
d.v(x, y + gsqsz*2 - halfSpace, -((z+0)*gsqlen + halfSpace + zt));
d.v(x, y + 0.0f*2 + halfSpace, -((z+1)*gsqlen - halfSpace + zt));
d.v(x, y + gsqsz*2 - halfSpace, -((z+1)*gsqlen - halfSpace + zt));
}
}
glEnd();
}
void Tunnel::pulse(float z, unsigned col,
float r, float g, float b,
float speed, float delay) {
Pulse pulse = { -z/gsqlen + offset, speed, r, g, b };
QueuedPulse qp = { col, clock + delay, pulse };
pulseQueue.push(qp);
}
void Tunnel::translateZ(float amt) {
offset -= amt / gsqlen;
while (offset >= gridLength)
offset -= gridLength;
while (offset < 0)
offset += gridLength;
}
<|endoftext|>
|
<commit_before>//
// George 'papanikge' Papanikolaou
// CEID Advance Algorithm Desing Course 2014
// Library of Efficient Data types and Algorithms (LEDA) testing
//
// Strong Components identifier and checker implementation
//
#include "basic.h"
using namespace leda;
/*
* My implementation of Kosaraju's algorithm for finding SCC.
* Maybe we should leave the graph reversed to save some time.
*/
int my_STRONG_COMPONENTS(graph& G, node_array<int>& compnum)
{
int i;
int scc_count = 0;
int n = G.number_of_nodes();
node v;
node* Stack = new node[n+1];
list<node> S;
node_array<int> useless(G, 0);
node_array<bool> reached(G, false);
// reinitialize to our copy
compnum.init(G, 0);
// first DFS over the graph, to get the completion times
DFS_NUM(G, useless, compnum);
// create a sorted array of the completion times. The [0] position is vacant.
forall_nodes(v,G) {
Stack[compnum[v]] = v;
}
// reverse graph
G.rev_all_edges();
// running DFS on the reversed graph starting from the top of the Stack
for (i = n; i > 0; i--) {
// we are performing DFS on the nodes in the Stack. We are using the
// reached array to perform it only once for every one.
if (!reached[Stack[i]]) {
S = DFS(G, Stack[i], reached);
// S now is the biggest strong component that contains Stack[i]
// Reporting and updating arrays and counters
forall(v, S)
compnum[v] = scc_count;
// writing the SCC nums on top of the compnums, which is kinda awkward.
scc_count++;
}
}
delete[] Stack;
G.rev_all_edges();
return scc_count;
}
/*
* Checker function for the SCC above implementation based on the fact that
* all the nodes can reach the others when they are in the same SCC
*/
bool STRONG_COMPONENTS_checker(leda::graph& G, leda::node_array<int>& check_nums)
{
int orig_counter = 0;
int rev_counter = 0;
node v, a;
list<node> LN1, LN2;
node_array<int> for_bfs(G, -1);
a = G.choose_node();
/* Performing BFS on the original and on the reverse graph.*/
LN1 = BFS(G, a, for_bfs);
forall(v, LN1)
orig_counter++;
G.rev_all_edges();
LN2 = BFS(G, a, for_bfs);
forall(v, LN2)
rev_counter++;
/* Checking the summing of the found nodes. They need to be the same. */
if (rev_counter == orig_counter) {
std::cout << "Check. Implementations match." << std::endl;
return true;
} else {
std::cout << "BEWARE: Implementations DON'T match." << std::endl;
return false;
}
}
<commit_msg>fix checker bug<commit_after>//
// George 'papanikge' Papanikolaou
// CEID Advance Algorithm Desing Course 2014
// Library of Efficient Data types and Algorithms (LEDA) testing
//
// Strong Components identifier and checker implementation
//
#include "basic.h"
using namespace leda;
/*
* My implementation of Kosaraju's algorithm for finding SCC.
* Maybe we should leave the graph reversed to save some time.
*/
int my_STRONG_COMPONENTS(graph& G, node_array<int>& compnum)
{
int i;
int scc_count = 0;
int n = G.number_of_nodes();
node v;
node* Stack = new node[n+1];
list<node> S;
node_array<int> useless(G, 0);
node_array<bool> reached(G, false);
// reinitialize to our copy
compnum.init(G, 0);
// first DFS over the graph, to get the completion times
DFS_NUM(G, useless, compnum);
// create a sorted array of the completion times. The [0] position is vacant.
forall_nodes(v,G) {
Stack[compnum[v]] = v;
}
// reverse graph
G.rev_all_edges();
// running DFS on the reversed graph starting from the top of the Stack
for (i = n; i > 0; i--) {
// we are performing DFS on the nodes in the Stack. We are using the
// reached array to perform it only once for every one.
if (!reached[Stack[i]]) {
S = DFS(G, Stack[i], reached);
// S now is the biggest strong component that contains Stack[i]
// Reporting and updating arrays and counters
forall(v, S)
compnum[v] = scc_count;
// writing the SCC nums on top of the compnums, which is kinda awkward.
scc_count++;
}
}
delete[] Stack;
G.rev_all_edges();
return scc_count;
}
/*
* Checker function for the SCC above implementation based on the fact that
* all the nodes can reach the others when they are in the same SCC
*/
bool STRONG_COMPONENTS_checker(leda::graph& G, leda::node_array<int>& check_nums)
{
int orig_counter = 0;
int rev_counter = 0;
node v, a;
list<node> LN1, LN2;
node_array<int> for_bfs(G, -1);
/* do we need to check a node from each SCC ?? */
a = G.choose_node();
/* Performing BFS on the original and on the reverse graph.*/
LN1 = BFS(G, a, for_bfs);
forall(v, LN1) {
if (check_nums[a] == check_nums[v])
orig_counter++;
}
G.rev_all_edges();
for_bfs.init(G, -1);
LN2 = BFS(G, a, for_bfs);
forall(v, LN2) {
if (check_nums[a] == check_nums[v])
rev_counter++;
}
/* Checking the summing of the found nodes. They need to be the same. */
if (rev_counter == orig_counter) {
std::cout << "Check. Implementations match." << std::endl;
return true;
} else {
std::cout << "BEWARE: Implementations DON'T match." << std::endl;
return false;
}
}
<|endoftext|>
|
<commit_before>// example.cpp : Simple logger example
//
#include "c11log/logger.h"
#include "c11log/sinks/async_sink.h"
#include "c11log/sinks/file_sinks.h"
#include "c11log/sinks/console_sinks.h"
#include "utils.h"
using std::cout;
using std::endl;
using namespace std::chrono;
using namespace c11log;
using namespace utils;
int main(int argc, char* argv[])
{
details::stack_buf<12> a;
const unsigned int howmany = argc <= 1 ? 1000000:atoi(argv[1]);
logger cout_logger ("example", sinks::stdout_sink());
cout_logger.info() << "Hello logger";
auto nullsink = sinks::null_sink::get();
//auto fsink = std::make_shared<sinks::rotating_file_sink>("log", "txt", 1024*1024*50 , 5, 0);
//auto as = std::make_shared<sinks::async_sink>(1000);
//as->add_sink(fsink);
logger my_logger ("my_logger", nullsink);
auto start = system_clock::now();
for (unsigned int i = 1; i <= howmany; ++i)
my_logger.info() << "Hello logger: msg #" << i;
//as->shutdown(std::chrono::milliseconds(15000));
auto delta = system_clock::now() - start;
auto delta_d = duration_cast<duration<double>> (delta).count();
cout_logger.info("Total:") << format(howmany);
cout_logger.info("Delta:") << format(delta_d);
cout_logger.info("Rate:") << format(howmany/delta_d) << "/sec";
return 0;
}
<commit_msg>small cleanup<commit_after>// example.cpp : Simple logger example
//
#include "c11log/logger.h"
#include "c11log/sinks/async_sink.h"
#include "c11log/sinks/file_sinks.h"
#include "c11log/sinks/console_sinks.h"
#include "utils.h"
using std::cout;
using std::endl;
using namespace std::chrono;
using namespace c11log;
using namespace utils;
int main(int argc, char* argv[])
{
const unsigned int howmany = argc <= 1 ? 1000000:atoi(argv[1]);
logger cout_logger ("example", sinks::stdout_sink());
cout_logger.info() << "Hello logger";
auto nullsink = sinks::null_sink::get();
//auto fsink = std::make_shared<sinks::rotating_file_sink>("log", "txt", 1024*1024*50 , 5, 0);
//auto as = std::make_shared<sinks::async_sink>(1000);
//as->add_sink(fsink);
logger my_logger ("my_logger", nullsink);
auto start = system_clock::now();
for (unsigned int i = 1; i <= howmany; ++i)
my_logger.info() << "Hello logger: msg #" << i;
//as->shutdown(std::chrono::milliseconds(15000));
auto delta = system_clock::now() - start;
auto delta_d = duration_cast<duration<double>> (delta).count();
cout_logger.info("Total:") << format(howmany);
cout_logger.info("Delta:") << format(delta_d);
cout_logger.info("Rate:") << format(howmany/delta_d) << "/sec";
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief PicoJPEG ใฏใฉใน
@author ๅนณๆพ้ฆไป (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdio>
#include <cstdlib>
#include "graphics/img.hpp"
#include "graphics/picojpeg.h"
#include "common/file_io.hpp"
#include "common/format.hpp"
namespace img {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief PicoJPEG ใใณใผใใปใฏใฉใน
@param[in] RENDER ๆ็ปใใกใณใฏใฟ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class RENDER>
class picojpeg_in {
RENDER& render_;
pjpeg_image_info_t image_info_;
uint8_t status_;
bool reduce_;
int16_t width_;
int16_t height_;
int16_t ofs_x_;
int16_t ofs_y_;
struct data_t {
utils::file_io& fin_;
uint32_t file_ofs_;
uint32_t file_size_;
data_t(utils::file_io& fin) : fin_(fin), file_ofs_(0), file_size_(0) { }
};
void render_rgb_(int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b)
{
auto c = RENDER::COLOR::rgb(r, g, b);
render_.plot(ofs_x_ + x, ofs_y_ + y, c);
}
static uint8_t pjpeg_callback_(uint8_t* dst, uint8_t size, uint8_t* acr, void *pdata)
{
data_t* t = static_cast<data_t*>(pdata);
auto len = std::min(t->file_size_ - t->file_ofs_, static_cast<uint32_t>(size));
auto rl = t->fin_.read(dst, len);
// utils::format("Read: %d (%d)\n") % len % rl;
*acr = rl;
t->file_ofs_ += rl;
return 0;
}
bool pixel_(utils::file_io& fin) noexcept
{
int16_t xt = 0;
int16_t yt = 0;
// utils::format("MCU: %d, %d\n") % image_info_.m_MCUWidth % image_info_.m_MCUHeight;
while((status_ = pjpeg_decode_mcu()) == 0) {
if(reduce_) {
auto row_blocks = image_info_.m_MCUWidth >> 3;
auto col_blocks = image_info_.m_MCUHeight >> 3;
int16_t xx = xt * row_blocks + ofs_x_;
int16_t yy = yt * col_blocks + ofs_y_;
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
auto gs = image_info_.m_pMCUBufR[0];
render_rgb_(xx, yy, gs, gs, gs);
} else {
for(int16_t y = 0; y < col_blocks; ++y) {
auto ofs = y * 128;
for(int16_t x = 0; x < row_blocks; ++x) {
auto r = image_info_.m_pMCUBufR[ofs];
auto g = image_info_.m_pMCUBufG[ofs];
auto b = image_info_.m_pMCUBufB[ofs];
ofs += 64;
render_rgb_(xx + x, yy + y, r, g, b);
}
}
}
} else {
auto xx = xt * image_info_.m_MCUWidth + ofs_x_;
auto yy = yt * image_info_.m_MCUHeight + ofs_y_;
for(int16_t y = 0; y < image_info_.m_MCUHeight; y += 8) {
auto by_limit = std::min(8,
image_info_.m_height - (yt * image_info_.m_MCUHeight + y));
for(int16_t x = 0; x < image_info_.m_MCUWidth; x += 8) {
auto bx_limit = std::min(8,
image_info_.m_width - (xt * image_info_.m_MCUWidth + x));
auto ofs = (x * 8) + (y * 16);
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
const uint8_t* pGS = image_info_.m_pMCUBufR + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto gs = *pGS++;
render_rgb_(x + xx + bx, y + yy + by, gs, gs, gs);
}
pGS += (8 - bx_limit);
}
} else {
const uint8_t* pR = image_info_.m_pMCUBufR + ofs;
const uint8_t* pG = image_info_.m_pMCUBufG + ofs;
const uint8_t* pB = image_info_.m_pMCUBufB + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto r = *pR++;
auto g = *pG++;
auto b = *pB++;
render_rgb_(x + xx + bx, y + yy + by, r, g, b);
}
pR += (8 - bx_limit);
pG += (8 - bx_limit);
pB += (8 - bx_limit);
}
}
}
}
}
++xt;
if(xt == image_info_.m_MCUSPerRow) {
xt = 0;
++yt;
if(yt >= image_info_.m_MCUSPerCol) {
return false;
}
}
}
if(status_ != PJPG_NO_MORE_BLOCKS) {
utils::format("pjpeg_decode_mcu() failed with status: %d\n") % status_;
return false;
}
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief ใณใณในใใฉใฏใฟใผ
*/
//-----------------------------------------------------------------//
picojpeg_in(RENDER& render) noexcept : render_(render),
image_info_(),
status_(0), reduce_(false),
width_(0), height_(0), ofs_x_(0), ofs_y_(0)
{ }
//-----------------------------------------------------------------//
/*!
@brief ในใใผใฟในใฎๅๅพ๏ผError code๏ผ
@return ในใใผใฟใน
*/
//-----------------------------------------------------------------//
uint8_t get_status() const noexcept { return status_; }
//-----------------------------------------------------------------//
/*!
@brief ๆ็ปใชใใปใใใฎ่จญๅฎ
@param[in] x X ่ปธใชใใปใใ
@param[in] y Y ่ปธใชใใปใใ
*/
//-----------------------------------------------------------------//
void set_draw_offset(int16_t x = 0, int16_t y = 0) noexcept
{
ofs_x_ = x;
ofs_y_ = y;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ใใกใคใซใ็ขบ่ชใใ
@param[in] fin file_io ใฏใฉใน
@return ใจใฉใผใชใใfalseใใ่ฟใ
*/
//-----------------------------------------------------------------//
bool probe(utils::file_io& fin) noexcept
{
uint8_t sig[2];
uint32_t pos = fin.tell();
uint32_t l = fin.read(sig, 2);
fin.seek(utils::file_io::SEEK::SET, pos);
if(l == 2) {
if(sig[0] == 0xff && sig[1] == 0xd8) { // SOI Marker, Start image
return true;
}
}
// utils::format("Not JPEG file\n");
return false;
}
//-----------------------------------------------------------------//
/*!
@brief ็ปๅใใกใคใซใฎๆ
ๅ ฑใๅๅพใใ
@param[in] fin file_io ใฏใฉใน
@param[in] fo ๆ
ๅ ฑใๅใๅใๆง้ ไฝ
@return ใจใฉใผใชใใfalseใใ่ฟใ
*/
//-----------------------------------------------------------------//
bool info(utils::file_io& fin, img::img_info& fo) noexcept
{
auto pos = fin.tell();
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, false);
if(status_) {
fin.close();
return false;
}
fin.seek(utils::file_io::SEEK::SET, pos);
fo.width = image_info_.m_width;
fo.height = image_info_.m_height;
switch(image_info_.m_comps) {
case 1:
fo.grayscale = true;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 3:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 4:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 8;
fo.clut_num = 0;
break;
default:
fo.i_depth = 0;
fo.r_depth = 0;
fo.g_depth = 0;
fo.b_depth = 0;
fo.a_depth = 0;
fo.clut_num = 0;
return false;
break;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ใใกใคใซใใญใผใ
@param[in] fin file_io ใฏใฉใน
@param[in] opt ใใฉใผใใใๅบๆใฎ่จญๅฎๆๅญๅ
@return ใจใฉใผใชใใfalseใใ่ฟใ
*/
//-----------------------------------------------------------------//
bool load(utils::file_io& fin, const char* opt = nullptr)
{
// ใจใใใใใใใใใผใฎๆคๆป
if(!probe(fin)) {
return false;
}
reduce_ = false;
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, reduce_);
if(status_) {
if(status_ == PJPG_UNSUPPORTED_MODE) {
// utils::format("Progressive JPEG files are not supported.\n");
} else {
// utils::format("pjpeg_decode_init() failed with status: %d\n") % status_;
}
return false;
}
// In reduce mode output 1 pixel per 8x8 block.
width_ = reduce_ ?
(image_info_.m_MCUSPerRow * image_info_.m_MCUWidth) / 8 : image_info_.m_width;
height_ = reduce_ ?
(image_info_.m_MCUSPerCol * image_info_.m_MCUHeight) / 8 : image_info_.m_height;
return pixel_(fin);
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ใใกใคใซใใญใผใใใ
@param[in] fin ใใกใคใซ I/O ใฏใฉใน
@param[in] opt ใใฉใผใใใๅบๆใฎ่จญๅฎๆๅญๅ
@return ใจใฉใผใใใใฐใfalseใ
*/
//-----------------------------------------------------------------//
bool load(const char* fname, const char* opt = nullptr) noexcept
{
if(fname == nullptr) return false;
utils::file_io fin;
if(!fin.open(fname, "rb")) {
return false;
}
auto ret = load(fin, opt);
fin.close();
return ret;
}
};
}
<commit_msg>update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief PicoJPEG ใฏใฉใน
@author ๅนณๆพ้ฆไป (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdio>
#include <cstdlib>
#include "graphics/img.hpp"
#include "graphics/picojpeg.h"
#include "common/file_io.hpp"
#include "common/format.hpp"
namespace img {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief PicoJPEG ใใณใผใใปใฏใฉใน
@param[in] RENDER ๆ็ปใใกใณใฏใฟ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class RENDER>
class picojpeg_in {
RENDER& render_;
pjpeg_image_info_t image_info_;
uint8_t status_;
bool reduce_;
int16_t width_;
int16_t height_;
int16_t ofs_x_;
int16_t ofs_y_;
struct data_t {
utils::file_io& fin_;
uint32_t file_ofs_;
uint32_t file_size_;
data_t(utils::file_io& fin) : fin_(fin), file_ofs_(0), file_size_(0) { }
};
void render_rgb_(int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b)
{
auto c = RENDER::COLOR::rgb(r, g, b);
render_.plot(ofs_x_ + x, ofs_y_ + y, c);
}
static uint8_t pjpeg_callback_(uint8_t* dst, uint8_t size, uint8_t* acr, void *pdata)
{
data_t* t = static_cast<data_t*>(pdata);
auto len = std::min(t->file_size_ - t->file_ofs_, static_cast<uint32_t>(size));
auto rl = t->fin_.read(dst, len);
// utils::format("Read: %d (%d)\n") % len % rl;
*acr = rl;
t->file_ofs_ += rl;
return 0;
}
bool pixel_(utils::file_io& fin) noexcept
{
int16_t xt = 0;
int16_t yt = 0;
// utils::format("MCU: %d, %d\n") % image_info_.m_MCUWidth % image_info_.m_MCUHeight;
while((status_ = pjpeg_decode_mcu()) == 0) {
if(reduce_) {
auto row_blocks = image_info_.m_MCUWidth >> 3;
auto col_blocks = image_info_.m_MCUHeight >> 3;
int16_t xx = xt * row_blocks + ofs_x_;
int16_t yy = yt * col_blocks + ofs_y_;
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
auto gs = image_info_.m_pMCUBufR[0];
render_rgb_(xx, yy, gs, gs, gs);
} else {
for(int16_t y = 0; y < col_blocks; ++y) {
auto ofs = y * 128;
for(int16_t x = 0; x < row_blocks; ++x) {
auto r = image_info_.m_pMCUBufR[ofs];
auto g = image_info_.m_pMCUBufG[ofs];
auto b = image_info_.m_pMCUBufB[ofs];
ofs += 64;
render_rgb_(xx + x, yy + y, r, g, b);
}
}
}
} else {
auto xx = xt * image_info_.m_MCUWidth + ofs_x_;
auto yy = yt * image_info_.m_MCUHeight + ofs_y_;
for(int16_t y = 0; y < image_info_.m_MCUHeight; y += 8) {
auto by_limit = std::min(8,
image_info_.m_height - (yt * image_info_.m_MCUHeight + y));
for(int16_t x = 0; x < image_info_.m_MCUWidth; x += 8) {
auto bx_limit = std::min(8,
image_info_.m_width - (xt * image_info_.m_MCUWidth + x));
auto ofs = (x * 8) + (y * 16);
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
const uint8_t* pGS = image_info_.m_pMCUBufR + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto gs = *pGS++;
render_rgb_(x + xx + bx, y + yy + by, gs, gs, gs);
}
pGS += (8 - bx_limit);
}
} else {
const uint8_t* pR = image_info_.m_pMCUBufR + ofs;
const uint8_t* pG = image_info_.m_pMCUBufG + ofs;
const uint8_t* pB = image_info_.m_pMCUBufB + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto r = *pR++;
auto g = *pG++;
auto b = *pB++;
render_rgb_(x + xx + bx, y + yy + by, r, g, b);
}
pR += (8 - bx_limit);
pG += (8 - bx_limit);
pB += (8 - bx_limit);
}
}
}
}
}
++xt;
if(xt == image_info_.m_MCUSPerRow) {
xt = 0;
++yt;
if(yt >= image_info_.m_MCUSPerCol) {
return false;
}
}
}
if(status_ != PJPG_NO_MORE_BLOCKS) {
utils::format("pjpeg_decode_mcu() failed with status: %d\n") % status_;
return false;
}
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief ใณใณในใใฉใฏใฟใผ
*/
//-----------------------------------------------------------------//
picojpeg_in(RENDER& render) noexcept : render_(render),
image_info_(),
status_(0), reduce_(false),
width_(0), height_(0), ofs_x_(0), ofs_y_(0)
{ }
//-----------------------------------------------------------------//
/*!
@brief ในใใผใฟในใฎๅๅพ๏ผError code๏ผ
@return ในใใผใฟใน
*/
//-----------------------------------------------------------------//
uint8_t get_status() const noexcept { return status_; }
//-----------------------------------------------------------------//
/*!
@brief ๆ็ปใชใใปใใใฎ่จญๅฎ
@param[in] x X ่ปธใชใใปใใ
@param[in] y Y ่ปธใชใใปใใ
*/
//-----------------------------------------------------------------//
void set_draw_offset(int16_t x = 0, int16_t y = 0) noexcept
{
ofs_x_ = x;
ofs_y_ = y;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ใใกใคใซใ็ขบ่ชใใ
@param[in] fin file_io ใฏใฉใน
@return ใจใฉใผใชใใfalseใใ่ฟใ
*/
//-----------------------------------------------------------------//
bool probe(utils::file_io& fin) noexcept
{
uint8_t sig[2];
uint32_t pos = fin.tell();
uint32_t l = fin.read(sig, 2);
fin.seek(utils::file_io::SEEK::SET, pos);
if(l == 2) {
if(sig[0] == 0xff && sig[1] == 0xd8) { // SOI Marker, Start image
return true;
}
}
// utils::format("Not JPEG file\n");
return false;
}
//-----------------------------------------------------------------//
/*!
@brief ็ปๅใใกใคใซใฎๆ
ๅ ฑใๅๅพใใ
@param[in] fin file_io ใฏใฉใน
@param[in] fo ๆ
ๅ ฑใๅใๅใๆง้ ไฝ
@return ใจใฉใผใชใใfalseใใ่ฟใ
*/
//-----------------------------------------------------------------//
bool info(utils::file_io& fin, img::img_info& fo) noexcept
{
auto pos = fin.tell();
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, false);
if(status_) {
fin.close();
return false;
}
fin.seek(utils::file_io::SEEK::SET, pos);
fo.width = image_info_.m_width;
fo.height = image_info_.m_height;
switch(image_info_.m_comps) {
case 1:
fo.grayscale = true;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 3:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 4:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 8;
fo.clut_num = 0;
break;
default:
fo.i_depth = 0;
fo.r_depth = 0;
fo.g_depth = 0;
fo.b_depth = 0;
fo.a_depth = 0;
fo.clut_num = 0;
return false;
break;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ใใกใคใซใใญใผใ
@param[in] fin file_io ใฏใฉใน
@param[in] opt ใใฉใผใใใๅบๆใฎ่จญๅฎๆๅญๅ
@return ใจใฉใผใชใใfalseใใ่ฟใ
*/
//-----------------------------------------------------------------//
bool load(utils::file_io& fin, const char* opt = nullptr)
{
// ใจใใใใใใใใใผใฎๆคๆป
if(!probe(fin)) {
return false;
}
reduce_ = false;
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, reduce_);
if(status_) {
if(status_ == PJPG_UNSUPPORTED_MODE) {
utils::format("Progressive JPEG files are not supported.\n");
} else {
// utils::format("pjpeg_decode_init() failed with status: %d\n") % status_;
}
return false;
}
// In reduce mode output 1 pixel per 8x8 block.
width_ = reduce_ ?
(image_info_.m_MCUSPerRow * image_info_.m_MCUWidth) / 8 : image_info_.m_width;
height_ = reduce_ ?
(image_info_.m_MCUSPerCol * image_info_.m_MCUHeight) / 8 : image_info_.m_height;
return pixel_(fin);
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ใใกใคใซใใญใผใใใ
@param[in] fin ใใกใคใซ I/O ใฏใฉใน
@param[in] opt ใใฉใผใใใๅบๆใฎ่จญๅฎๆๅญๅ
@return ใจใฉใผใใใใฐใfalseใ
*/
//-----------------------------------------------------------------//
bool load(const char* fname, const char* opt = nullptr) noexcept
{
if(fname == nullptr) return false;
utils::file_io fin;
if(!fin.open(fname, "rb")) {
return false;
}
auto ret = load(fin, opt);
fin.close();
return ret;
}
};
}
<|endoftext|>
|
<commit_before>#ifndef MATCHES_DHT_HPP
#define MATCHES_DHT_HPP
#include <Grappa.hpp>
#include <GlobalAllocator.hpp>
#include <GlobalCompletionEvent.hpp>
#include <ParallelLoop.hpp>
#include <BufferVector.hpp>
#include <Metrics.hpp>
#include <list>
#include <cmath>
//GRAPPA_DECLARE_METRIC(MaxMetric<uint64_t>, max_cell_length);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_tables_size);
GRAPPA_DECLARE_METRIC(SummarizingMetric<uint64_t>, hash_tables_lookup_steps);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_remote_lookups);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_remote_inserts);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_local_lookups);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_local_inserts);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_called_lookups);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_called_inserts);
// for naming the types scoped in MatchesDHT
#define MDHT_TYPE(type) typename MatchesDHT<K,V,HF>::type
// Hash table for joins
// * allows multiple copies of a Key
// * lookups return all Key matches
template <typename K, typename V, uint64_t (*HF)(K)>
class MatchesDHT {
private:
struct Entry {
K key;
std::vector<V> * vs;
//BufferVector<V> * vs;
Entry( K key ) : key(key), vs(new std::vector<V>()) {}
//Entry( K key ) : key(key), vs(new BufferVector<V>( 16 )) {}
Entry ( ) {}
};
struct Cell {
std::list<Entry> * entries;
Cell() : entries( NULL ) {}
};
struct lookup_result {
GlobalAddress<V> matches;
size_t num;
};
// private members
GlobalAddress< Cell > base;
size_t capacity;
uint64_t computeIndex( K key ) {
return HF(key) & (capacity - 1);
}
// for creating local MatchesDHT
MatchesDHT( GlobalAddress<Cell> base, uint32_t capacity_pow2 ) {
this->base = base;
this->capacity = capacity_pow2;
}
static bool lookup_local( K key, Cell * target, Entry * result ) {
std::list<MDHT_TYPE(Entry)> * entries = target->entries;
// first check if the cell has any entries;
// if not then the lookup returns nothing
if ( entries == NULL ) return false;
typename std::list<MDHT_TYPE(Entry)>::iterator i;
uint64_t steps = 1;
for (i = entries->begin(); i!=entries->end(); ++i) {
const Entry e = *i;
if ( e.key == key ) { // typename K must implement operator==
*result = e;
hash_tables_lookup_steps += steps;
return true;
}
++steps;
}
hash_tables_lookup_steps += steps;
return false;
}
public:
// for static construction
MatchesDHT( ) {}
static void init_global_DHT( MatchesDHT<K,V,HF> * globally_valid_local_pointer, size_t capacity ) {
uint32_t capacity_exp = log2(capacity);
size_t capacity_powerof2 = pow(2, capacity_exp);
GlobalAddress<Cell> base = Grappa::global_alloc<Cell>( capacity_powerof2 );
Grappa::on_all_cores( [globally_valid_local_pointer,base,capacity_powerof2] {
*globally_valid_local_pointer = MatchesDHT<K,V,HF>( base, capacity_powerof2 );
});
Grappa::forall( base, capacity_powerof2, []( int64_t i, Cell& c ) {
Cell empty;
c = empty;
});
}
struct size_aligned {
size_t s;
size_aligned operator+(const size_aligned& o) const {
size_aligned v;
v.s = this->s + o.s;
return v;
}
} GRAPPA_BLOCK_ALIGNED;
size_t size() {
auto l_size = Grappa::symmetric_global_alloc<size_aligned>();
Grappa::forall( base, capacity, [l_size](int64_t i, Cell& c) {
if (c.entries != NULL) {
for (auto eiter = c.entries->begin(); eiter != c.entries->end(); ++eiter) {
l_size->s += eiter->vs->size();
}
}
});
return Grappa::reduce<size_aligned, COLL_ADD>(l_size ).s;
//FIXME: mem leak l_size
}
static void set_RO_global( MatchesDHT<K,V,HF> * globally_valid_local_pointer ) {
Grappa::forall( globally_valid_local_pointer->base, globally_valid_local_pointer->capacity, []( int64_t i, Cell& c ) {
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = c.entries;
// if cell is not hit then no action
if ( entries == NULL ) {
return;
}
uint64_t sum_size = 0;
// for all keys, set match vector to RO
typename std::list<MDHT_TYPE(Entry)>::iterator it;
for (it = entries->begin(); it!=entries->end(); ++it) {
Entry e = *it;
//e.vs->setReadMode();
sum_size+=e.vs->size();
}
//max_cell_length.add(sum_size);
});
}
uint64_t lookup ( K key, GlobalAddress<V> * vals ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
// FIXME: remove 'this' capture when using gcc4.8, this is just a bug in 4.7
lookup_result result = Grappa::delegate::call( target.core(), [key,target,this]() {
hash_called_lookups++;
MDHT_TYPE(lookup_result) lr;
lr.num = 0;
Entry e;
if (lookup_local( key, target.pointer(), &e)) {
// lr.matches = static_cast<GlobalAddress<V>>(e.vs->getReadBuffer());
lr.num = e.vs->size();
}
return lr;
});
*vals = result.matches;
return result.num;
}
// version of lookup that takes a continuation instead of returning results back
template< typename CF, Grappa::GlobalCompletionEvent * GCE = &Grappa::impl::local_gce >
void lookup_iter ( K key, CF f ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
// FIXME: remove 'this' capture when using gcc4.8, this is just a bug in 4.7
//TODO optimization where only need to do remotePrivateTask instead of call_async
//if you are going to do more suspending ops (comms) inside the loop
if (target.core() == Grappa::mycore()) {
hash_local_lookups++;
} else {
hash_remote_lookups++;
}
Grappa::spawnRemote<GCE>( target.core(), [key, target, f, this]() {
hash_called_lookups++;
Entry e;
if (lookup_local( key, target.pointer(), &e)) {
auto resultsptr = e.vs;
Grappa::forall_here<async,GCE>(0, e.vs->size(), [f,resultsptr](int64_t start, int64_t iters) {
for (int64_t i=start; i<start+iters; i++) {
auto results = *resultsptr;
// call the continuation with the lookup result
f(results[i]);
}
});
}
});
}
template< Grappa::GlobalCompletionEvent * GCE, typename CF >
void lookup_iter ( K key, CF f ) {
lookup_iter<CF, GCE>(key, f);
}
// version of lookup that takes a continuation instead of returning results back
template< typename CF, Grappa::GlobalCompletionEvent * GCE = &Grappa::impl::local_gce >
void lookup ( K key, CF f ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
Grappa::delegate::call<async>( target.core(), [key, target, f]() {
hash_called_lookups++;
Entry e;
if (lookup_local( key, target.pointer(), &e)) {
uint64_t len = e.vs->size();
f(e.vs, len);
}
});
}
// Inserts the key if not already in the set
// Shouldn't be used with `insert`.
//
// returns true if the set already contains the key
bool insert_unique( K key ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
//FIXME: remove index capture
bool result = Grappa::delegate::call( target.core(), [index,key, target]() { // TODO: have an additional version that returns void
// to upgrade to call_async
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so no insert
return true;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key ); // TODO: cleanup since sharing insert* code here, we are just going to store an empty vector
// perhaps a different module
entries->push_back( newe );
return false;
});
return result;
}
void insert( K key, V val ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
if (target.core() == Grappa::mycore()) {
hash_local_inserts++;
} else {
hash_remote_inserts++;
}
Grappa::delegate::call( target.core(), [key, val, target]() { // TODO: upgrade to call_async; using GCE
hash_called_inserts++;
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so add to matches
e.vs->push_back( val );
hash_tables_size+=1;
return 0;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key );
newe.vs->push_back( val );
entries->push_back( newe );
return 0;
});
}
};
#endif // MATCHES_DHT_HPP
<commit_msg>insert unique returns void<commit_after>#ifndef MATCHES_DHT_HPP
#define MATCHES_DHT_HPP
#include <Grappa.hpp>
#include <GlobalAllocator.hpp>
#include <GlobalCompletionEvent.hpp>
#include <ParallelLoop.hpp>
#include <BufferVector.hpp>
#include <Metrics.hpp>
#include <list>
#include <cmath>
//GRAPPA_DECLARE_METRIC(MaxMetric<uint64_t>, max_cell_length);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_tables_size);
GRAPPA_DECLARE_METRIC(SummarizingMetric<uint64_t>, hash_tables_lookup_steps);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_remote_lookups);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_remote_inserts);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_local_lookups);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_local_inserts);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_called_lookups);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, hash_called_inserts);
// for naming the types scoped in MatchesDHT
#define MDHT_TYPE(type) typename MatchesDHT<K,V,HF>::type
// Hash table for joins
// * allows multiple copies of a Key
// * lookups return all Key matches
template <typename K, typename V, uint64_t (*HF)(K)>
class MatchesDHT {
private:
struct Entry {
K key;
std::vector<V> * vs;
//BufferVector<V> * vs;
Entry( K key ) : key(key), vs(new std::vector<V>()) {}
//Entry( K key ) : key(key), vs(new BufferVector<V>( 16 )) {}
Entry ( ) {}
};
struct Cell {
std::list<Entry> * entries;
Cell() : entries( NULL ) {}
};
struct lookup_result {
GlobalAddress<V> matches;
size_t num;
};
// private members
GlobalAddress< Cell > base;
size_t capacity;
uint64_t computeIndex( K key ) {
return HF(key) & (capacity - 1);
}
// for creating local MatchesDHT
MatchesDHT( GlobalAddress<Cell> base, uint32_t capacity_pow2 ) {
this->base = base;
this->capacity = capacity_pow2;
}
static bool lookup_local( K key, Cell * target, Entry * result ) {
std::list<MDHT_TYPE(Entry)> * entries = target->entries;
// first check if the cell has any entries;
// if not then the lookup returns nothing
if ( entries == NULL ) return false;
typename std::list<MDHT_TYPE(Entry)>::iterator i;
uint64_t steps = 1;
for (i = entries->begin(); i!=entries->end(); ++i) {
const Entry e = *i;
if ( e.key == key ) { // typename K must implement operator==
*result = e;
hash_tables_lookup_steps += steps;
return true;
}
++steps;
}
hash_tables_lookup_steps += steps;
return false;
}
public:
// for static construction
MatchesDHT( ) {}
static void init_global_DHT( MatchesDHT<K,V,HF> * globally_valid_local_pointer, size_t capacity ) {
uint32_t capacity_exp = log2(capacity);
size_t capacity_powerof2 = pow(2, capacity_exp);
GlobalAddress<Cell> base = Grappa::global_alloc<Cell>( capacity_powerof2 );
Grappa::on_all_cores( [globally_valid_local_pointer,base,capacity_powerof2] {
*globally_valid_local_pointer = MatchesDHT<K,V,HF>( base, capacity_powerof2 );
});
Grappa::forall( base, capacity_powerof2, []( int64_t i, Cell& c ) {
Cell empty;
c = empty;
});
}
struct size_aligned {
size_t s;
size_aligned operator+(const size_aligned& o) const {
size_aligned v;
v.s = this->s + o.s;
return v;
}
} GRAPPA_BLOCK_ALIGNED;
size_t size() {
auto l_size = Grappa::symmetric_global_alloc<size_aligned>();
Grappa::forall( base, capacity, [l_size](int64_t i, Cell& c) {
if (c.entries != NULL) {
for (auto eiter = c.entries->begin(); eiter != c.entries->end(); ++eiter) {
l_size->s += eiter->vs->size();
}
}
});
return Grappa::reduce<size_aligned, COLL_ADD>(l_size ).s;
//FIXME: mem leak l_size
}
static void set_RO_global( MatchesDHT<K,V,HF> * globally_valid_local_pointer ) {
Grappa::forall( globally_valid_local_pointer->base, globally_valid_local_pointer->capacity, []( int64_t i, Cell& c ) {
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = c.entries;
// if cell is not hit then no action
if ( entries == NULL ) {
return;
}
uint64_t sum_size = 0;
// for all keys, set match vector to RO
typename std::list<MDHT_TYPE(Entry)>::iterator it;
for (it = entries->begin(); it!=entries->end(); ++it) {
Entry e = *it;
//e.vs->setReadMode();
sum_size+=e.vs->size();
}
//max_cell_length.add(sum_size);
});
}
uint64_t lookup ( K key, GlobalAddress<V> * vals ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
// FIXME: remove 'this' capture when using gcc4.8, this is just a bug in 4.7
lookup_result result = Grappa::delegate::call( target.core(), [key,target,this]() {
hash_called_lookups++;
MDHT_TYPE(lookup_result) lr;
lr.num = 0;
Entry e;
if (lookup_local( key, target.pointer(), &e)) {
// lr.matches = static_cast<GlobalAddress<V>>(e.vs->getReadBuffer());
lr.num = e.vs->size();
}
return lr;
});
*vals = result.matches;
return result.num;
}
// version of lookup that takes a continuation instead of returning results back
template< typename CF, Grappa::GlobalCompletionEvent * GCE = &Grappa::impl::local_gce >
void lookup_iter ( K key, CF f ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
// FIXME: remove 'this' capture when using gcc4.8, this is just a bug in 4.7
//TODO optimization where only need to do remotePrivateTask instead of call_async
//if you are going to do more suspending ops (comms) inside the loop
if (target.core() == Grappa::mycore()) {
hash_local_lookups++;
} else {
hash_remote_lookups++;
}
Grappa::spawnRemote<GCE>( target.core(), [key, target, f, this]() {
hash_called_lookups++;
Entry e;
if (lookup_local( key, target.pointer(), &e)) {
auto resultsptr = e.vs;
Grappa::forall_here<async,GCE>(0, e.vs->size(), [f,resultsptr](int64_t start, int64_t iters) {
for (int64_t i=start; i<start+iters; i++) {
auto results = *resultsptr;
// call the continuation with the lookup result
f(results[i]);
}
});
}
});
}
template< Grappa::GlobalCompletionEvent * GCE, typename CF >
void lookup_iter ( K key, CF f ) {
lookup_iter<CF, GCE>(key, f);
}
// version of lookup that takes a continuation instead of returning results back
template< typename CF, Grappa::GlobalCompletionEvent * GCE = &Grappa::impl::local_gce >
void lookup ( K key, CF f ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
Grappa::delegate::call<async>( target.core(), [key, target, f]() {
hash_called_lookups++;
Entry e;
if (lookup_local( key, target.pointer(), &e)) {
uint64_t len = e.vs->size();
f(e.vs, len);
}
});
}
// Inserts the key if not already in the set
// Shouldn't be used with `insert`.
//
// returns true if the set already contains the key
void insert_unique( K key, V val ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
Grappa::delegate::call( target.core(), [key,val,target]() { // TODO: have an additional version that returns void
// to upgrade to call_async
hash_called_inserts++;
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so no insert
return;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key ); // TODO: cleanup since sharing insert* code here, we are just going to store an empty vector
newe.vs->push_back( val );
// perhaps a different module
entries->push_back( newe );
return;
});
}
void insert( K key, V val ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
if (target.core() == Grappa::mycore()) {
hash_local_inserts++;
} else {
hash_remote_inserts++;
}
Grappa::delegate::call( target.core(), [key, val, target]() { // TODO: upgrade to call_async; using GCE
hash_called_inserts++;
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so add to matches
e.vs->push_back( val );
hash_tables_size+=1;
return 0;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key );
newe.vs->push_back( val );
entries->push_back( newe );
return 0;
});
}
};
#endif // MATCHES_DHT_HPP
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright RTK 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.
*
*=========================================================================*/
#include "rtkramp_ggo.h"
#include "rtkMacro.h"
#include "rtkProjectionsReader.h"
#include "rtkFFTRampImageFilter.h"
#include "rtkConfiguration.h"
#if CUDA_FOUND
# include "rtkCudaFFTRampImageFilter.h"
#endif
#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkStreamingImageFilter.h>
#include <itkTimeProbe.h>
int main(int argc, char * argv[])
{
GGO(rtkramp, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
#if CUDA_FOUND
typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif
// Generate file names
itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(false);
names->SetRegularExpression(args_info.regexp_arg);
names->SetSubMatch(0);
// Projections reader
typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )
// Ramp filter
#if CUDA_FOUND
typedef rtk::CudaFFTRampImageFilter CudaRampFilterType;
CudaRampFilterType::Pointer cudaRampFilter;
#endif
typedef rtk::FFTRampImageFilter<OutputImageType, OutputImageType, double > CPURampFilterType;
CPURampFilterType::Pointer rampFilter;
if( !strcmp(args_info.hardware_arg, "cuda") )
{
#if CUDA_FOUND
cudaRampFilter = CudaRampFilterType::New();
cudaRampFilter->SetInput( reader->GetOutput() );
cudaRampFilter->SetTruncationCorrection(args_info.pad_arg);
cudaRampFilter->SetHannCutFrequency(args_info.hann_arg);
cudaRampFilter->SetHannCutFrequencyY(args_info.hannY_arg);
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
else
{
rampFilter = CPURampFilterType::New();
rampFilter->SetInput( reader->GetOutput() );
rampFilter->SetTruncationCorrection(args_info.pad_arg);
rampFilter->SetHannCutFrequency(args_info.hann_arg);
rampFilter->SetHannCutFrequencyY(args_info.hannY_arg);
}
// Streaming filter
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
StreamerType::Pointer streamer = StreamerType::New();
if( !strcmp(args_info.hardware_arg, "cuda") )
streamer->SetInput( cudaRampFilter->GetOutput() );
else
streamer->SetInput( rampFilter->GetOutput() );
streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );
itk::TimeProbe probe;
probe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( streamer->Update() )
probe.Stop();
std::cout << "The streamed ramp filter update took "
<< probe.GetMean()
<< probe.GetUnit()
<< std::endl;
// Write
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( streamer->GetOutput() );
writer->UpdateOutputInformation();
TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() )
return EXIT_SUCCESS;
}
<commit_msg>Added missing ifdef for compilation without cuda<commit_after>/*=========================================================================
*
* Copyright RTK 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.
*
*=========================================================================*/
#include "rtkramp_ggo.h"
#include "rtkMacro.h"
#include "rtkProjectionsReader.h"
#include "rtkFFTRampImageFilter.h"
#include "rtkConfiguration.h"
#if CUDA_FOUND
# include "rtkCudaFFTRampImageFilter.h"
#endif
#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkStreamingImageFilter.h>
#include <itkTimeProbe.h>
int main(int argc, char * argv[])
{
GGO(rtkramp, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
#if CUDA_FOUND
typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif
// Generate file names
itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(false);
names->SetRegularExpression(args_info.regexp_arg);
names->SetSubMatch(0);
// Projections reader
typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )
// Ramp filter
#if CUDA_FOUND
typedef rtk::CudaFFTRampImageFilter CudaRampFilterType;
CudaRampFilterType::Pointer cudaRampFilter;
#endif
typedef rtk::FFTRampImageFilter<OutputImageType, OutputImageType, double > CPURampFilterType;
CPURampFilterType::Pointer rampFilter;
if( !strcmp(args_info.hardware_arg, "cuda") )
{
#if CUDA_FOUND
cudaRampFilter = CudaRampFilterType::New();
cudaRampFilter->SetInput( reader->GetOutput() );
cudaRampFilter->SetTruncationCorrection(args_info.pad_arg);
cudaRampFilter->SetHannCutFrequency(args_info.hann_arg);
cudaRampFilter->SetHannCutFrequencyY(args_info.hannY_arg);
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
else
{
rampFilter = CPURampFilterType::New();
rampFilter->SetInput( reader->GetOutput() );
rampFilter->SetTruncationCorrection(args_info.pad_arg);
rampFilter->SetHannCutFrequency(args_info.hann_arg);
rampFilter->SetHannCutFrequencyY(args_info.hannY_arg);
}
// Streaming filter
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
StreamerType::Pointer streamer = StreamerType::New();
#if CUDA_FOUND
if( !strcmp(args_info.hardware_arg, "cuda") )
streamer->SetInput( cudaRampFilter->GetOutput() );
else
#endif
streamer->SetInput( rampFilter->GetOutput() );
streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );
itk::TimeProbe probe;
probe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( streamer->Update() )
probe.Stop();
std::cout << "The streamed ramp filter update took "
<< probe.GetMean()
<< probe.GetUnit()
<< std::endl;
// Write
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( streamer->GetOutput() );
writer->UpdateOutputInformation();
TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() )
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <string>
#include <iostream>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glut.h>
#endif
// DisplayCluster streaming
#include <dcStream.h>
std::string streamName = "SimpleStreamer";
bool parallelStreaming = false;
int segmentSize = 512;
char * hostname = NULL;
DcSocket * socket = NULL;
void syntax(char * app);
void display();
int main(int argc, char **argv)
{
// read command-line arguments
for(int i=1; i<argc; i++)
{
if(argv[i][0] == '-')
{
switch(argv[i][1])
{
case 'n':
if(i+1 < argc)
{
streamName = argv[i+1];
i++;
}
break;
case 'p':
parallelStreaming = true;
break;
case 's':
if(i+1 < argc)
{
segmentSize = atoi(argv[i+1]);
i++;
}
break;
default:
syntax(argv[0]);
}
}
else if(i == argc-1)
{
hostname = argv[i];
}
}
if(hostname == NULL)
{
syntax(argv[0]);
}
// setup GLUT / OpenGL
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(0, 0);
glutInitWindowSize(1024, 768);
glutCreateWindow("SimpleStreamer");
// the display function will be called continuously
glutDisplayFunc(display);
glutIdleFunc(display);
glClearColor(0.5, 0.5, 0.5, 1.);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// connect to DisplayCluster
socket = dcStreamConnect(hostname);
if(socket == NULL)
{
std::cerr << "could not connect to DisplayCluster host: " << hostname << std::endl;
return 1;
}
// enter the main loop
glutMainLoop();
return 0;
}
void syntax(char * app)
{
std::cerr << "syntax: " << app << " [options] <hostname>" << std::endl;
std::cerr << "options:" << std::endl;
std::cerr << " -p enable parallel streaming (default disabled)" << std::endl;
std::cerr << " -s <segment size> set parallel streaming segment size (default 512)" << std::endl;
exit(1);
}
void display()
{
// angle of camera rotation
static float angle = 0;
// clear color / depth buffers and setup view
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float size = 2.;
glOrtho(-size, size, -size, size, -size, size);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(angle, 0.0, 1.0, 1.0);
// render the teapot
glutSolidTeapot(1.);
// send to DisplayCluster
// get current window dimensions
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
// grab the image data from OpenGL
unsigned char * imageData = (unsigned char *)malloc(windowWidth * windowHeight * 4);
glReadPixels(0,0,windowWidth,windowHeight, GL_RGBA, GL_UNSIGNED_BYTE, (void *)imageData);
bool success;
if(parallelStreaming == true)
{
// use a streaming segment size of roughly <segmentSize> x <segmentSize> pixels
std::vector<DcStreamParameters> parameters = dcStreamGenerateParameters(streamName, 0, segmentSize,segmentSize, 0,0,windowWidth,windowHeight, windowWidth,windowHeight);
// finally, send it to DisplayCluster
success = dcStreamSend(socket, imageData, 0,0,windowWidth,0,windowHeight, RGBA, parameters);
}
else
{
// use a single streaming segment for the full window
DcStreamParameters parameters = dcStreamGenerateParameters(streamName, 0, 0,0,windowWidth,windowHeight, windowWidth,windowHeight);
// finally, send it to DisplayCluster
success = dcStreamSend(socket, imageData, 0,0,windowWidth,0,windowHeight, RGBA, parameters);
}
if(success == false)
{
std::cerr << "failure in dcStreamSend()" << std::endl;
exit(1);
}
// and free the allocated image data
free(imageData);
glutSwapBuffers();
// increment rotation angle
angle += 1.;
}
<commit_msg>added stream name option to syntax message.<commit_after>#include <string>
#include <iostream>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glut.h>
#endif
// DisplayCluster streaming
#include <dcStream.h>
std::string streamName = "SimpleStreamer";
bool parallelStreaming = false;
int segmentSize = 512;
char * hostname = NULL;
DcSocket * socket = NULL;
void syntax(char * app);
void display();
int main(int argc, char **argv)
{
// read command-line arguments
for(int i=1; i<argc; i++)
{
if(argv[i][0] == '-')
{
switch(argv[i][1])
{
case 'n':
if(i+1 < argc)
{
streamName = argv[i+1];
i++;
}
break;
case 'p':
parallelStreaming = true;
break;
case 's':
if(i+1 < argc)
{
segmentSize = atoi(argv[i+1]);
i++;
}
break;
default:
syntax(argv[0]);
}
}
else if(i == argc-1)
{
hostname = argv[i];
}
}
if(hostname == NULL)
{
syntax(argv[0]);
}
// setup GLUT / OpenGL
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(0, 0);
glutInitWindowSize(1024, 768);
glutCreateWindow("SimpleStreamer");
// the display function will be called continuously
glutDisplayFunc(display);
glutIdleFunc(display);
glClearColor(0.5, 0.5, 0.5, 1.);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// connect to DisplayCluster
socket = dcStreamConnect(hostname);
if(socket == NULL)
{
std::cerr << "could not connect to DisplayCluster host: " << hostname << std::endl;
return 1;
}
// enter the main loop
glutMainLoop();
return 0;
}
void syntax(char * app)
{
std::cerr << "syntax: " << app << " [options] <hostname>" << std::endl;
std::cerr << "options:" << std::endl;
std::cerr << " -n <stream name> set stream name (default SimpleStreamer)"
std::cerr << " -p enable parallel streaming (default disabled)" << std::endl;
std::cerr << " -s <segment size> set parallel streaming segment size (default 512)" << std::endl;
exit(1);
}
void display()
{
// angle of camera rotation
static float angle = 0;
// clear color / depth buffers and setup view
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float size = 2.;
glOrtho(-size, size, -size, size, -size, size);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(angle, 0.0, 1.0, 1.0);
// render the teapot
glutSolidTeapot(1.);
// send to DisplayCluster
// get current window dimensions
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
// grab the image data from OpenGL
unsigned char * imageData = (unsigned char *)malloc(windowWidth * windowHeight * 4);
glReadPixels(0,0,windowWidth,windowHeight, GL_RGBA, GL_UNSIGNED_BYTE, (void *)imageData);
bool success;
if(parallelStreaming == true)
{
// use a streaming segment size of roughly <segmentSize> x <segmentSize> pixels
std::vector<DcStreamParameters> parameters = dcStreamGenerateParameters(streamName, 0, segmentSize,segmentSize, 0,0,windowWidth,windowHeight, windowWidth,windowHeight);
// finally, send it to DisplayCluster
success = dcStreamSend(socket, imageData, 0,0,windowWidth,0,windowHeight, RGBA, parameters);
}
else
{
// use a single streaming segment for the full window
DcStreamParameters parameters = dcStreamGenerateParameters(streamName, 0, 0,0,windowWidth,windowHeight, windowWidth,windowHeight);
// finally, send it to DisplayCluster
success = dcStreamSend(socket, imageData, 0,0,windowWidth,0,windowHeight, RGBA, parameters);
}
if(success == false)
{
std::cerr << "failure in dcStreamSend()" << std::endl;
exit(1);
}
// and free the allocated image data
free(imageData);
glutSwapBuffers();
// increment rotation angle
angle += 1.;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2018 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "AgencyFeature.h"
#include "Actions/ActionFeature.h"
#include "Agency/Agent.h"
#include "Agency/Job.h"
#include "Agency/Supervision.h"
#include "ApplicationFeatures/ApplicationServer.h"
#include "ApplicationFeatures/HttpEndpointProvider.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "Basics/application-exit.h"
#include "Cluster/ClusterFeature.h"
#include "FeaturePhases/FoxxFeaturePhase.h"
#include "IResearch/IResearchAnalyzerFeature.h"
#include "IResearch/IResearchFeature.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/ScriptFeature.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;
namespace arangodb {
consensus::Agent* AgencyFeature::AGENT = nullptr;
AgencyFeature::AgencyFeature(application_features::ApplicationServer& server)
: ApplicationFeature(server, "Agency"),
_activated(false),
_size(1),
_poolSize(1),
_minElectionTimeout(1.0),
_maxElectionTimeout(5.0),
_supervision(false),
_supervisionTouched(false),
_waitForSync(true),
_supervisionFrequency(1.0),
_compactionStepSize(1000),
_compactionKeepSize(50000),
_maxAppendSize(250),
_supervisionGracePeriod(10.0),
_supervisionOkThreshold(5.0),
_cmdLineTimings(false) {
setOptional(true);
startsAfter<FoxxFeaturePhase>();
}
AgencyFeature::~AgencyFeature() = default;
void AgencyFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addSection("agency", "Configure the agency");
options->addOption("--agency.activate", "Activate agency",
new BooleanParameter(&_activated),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.size", "number of agents",
new UInt64Parameter(&_size),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.pool-size", "number of agent pool",
new UInt64Parameter(&_poolSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.election-timeout-min",
"minimum timeout before an agent calls for new election (in seconds)",
new DoubleParameter(&_minElectionTimeout),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.election-timeout-max",
"maximum timeout before an agent calls for new election (in seconds)",
new DoubleParameter(&_maxElectionTimeout),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.endpoint", "agency endpoints",
new VectorParameter<StringParameter>(&_agencyEndpoints),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.my-address",
"which address to advertise to the outside",
new StringParameter(&_agencyMyAddress),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.supervision",
"perform arangodb cluster supervision",
new BooleanParameter(&_supervision),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.supervision-frequency",
"arangodb cluster supervision frequency (in seconds)",
new DoubleParameter(&_supervisionFrequency),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.supervision-grace-period",
"supervision time, after which a server is considered to have failed (in seconds)",
new DoubleParameter(&_supervisionGracePeriod),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.supervision-ok-threshold",
"supervision time, after which a server is considered to be bad [s]",
new DoubleParameter(&_supervisionOkThreshold),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.compaction-step-size",
"step size between state machine compactions",
new UInt64Parameter(&_compactionStepSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
options->addOption("--agency.compaction-keep-size",
"keep as many indices before compaction point",
new UInt64Parameter(&_compactionKeepSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.wait-for-sync",
"wait for hard disk syncs on every persistence call "
"(required in production)",
new BooleanParameter(&_waitForSync),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
options->addOption("--agency.max-append-size",
"maximum size of appendEntries document (# log entries)",
new UInt64Parameter(&_maxAppendSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
options->addOption("--agency.disaster-recovery-id",
"allows for specification of the id for this agent; "
"dangerous option for disaster recover only!",
new StringParameter(&_recoveryId),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
}
void AgencyFeature::validateOptions(std::shared_ptr<ProgramOptions> options) {
ProgramOptions::ProcessingResult const& result = options->processingResult();
if (!result.touched("agency.activate") || !_activated) {
disable();
return;
}
if (result.touched("agency.election-timeout-min")) {
_cmdLineTimings = true;
}
ServerState::instance()->setRole(ServerState::ROLE_AGENT);
// Agency size
if (result.touched("agency.size")) {
if (_size < 1) {
LOG_TOPIC("98510", FATAL, Logger::AGENCY) << "agency must have size greater 0";
FATAL_ERROR_EXIT();
}
} else {
_size = 1;
}
// Agency pool size
if (result.touched("agency.pool-size")) {
if (_poolSize < _size) {
LOG_TOPIC("af108", FATAL, Logger::AGENCY)
<< "agency pool size must be larger than agency size.";
FATAL_ERROR_EXIT();
}
} else {
_poolSize = _size;
}
// Size needs to be odd
if (_size % 2 == 0) {
LOG_TOPIC("0eab5", FATAL, Logger::AGENCY)
<< "AGENCY: agency must have odd number of members";
FATAL_ERROR_EXIT();
}
// Timeouts sanity
if (_minElectionTimeout <= 0.) {
LOG_TOPIC("facb6", FATAL, Logger::AGENCY)
<< "agency.election-timeout-min must not be negative!";
FATAL_ERROR_EXIT();
} else if (_minElectionTimeout < 0.15) {
LOG_TOPIC("0cce9", WARN, Logger::AGENCY)
<< "very short agency.election-timeout-min!";
}
if (_maxElectionTimeout <= _minElectionTimeout) {
LOG_TOPIC("62fc3", FATAL, Logger::AGENCY)
<< "agency.election-timeout-max must not be shorter than or"
<< "equal to agency.election-timeout-min.";
FATAL_ERROR_EXIT();
}
if (_maxElectionTimeout <= 2. * _minElectionTimeout) {
LOG_TOPIC("99f84", WARN, Logger::AGENCY)
<< "agency.election-timeout-max should probably be chosen longer!";
}
if (_compactionKeepSize == 0) {
LOG_TOPIC("ca485", WARN, Logger::AGENCY)
<< "agency.compaction-keep-size must not be 0, set to 1000";
_compactionKeepSize = 50000;
}
if (!_agencyMyAddress.empty()) {
std::string const unified = Endpoint::unifiedForm(_agencyMyAddress);
if (unified.empty()) {
LOG_TOPIC("4faa0", FATAL, Logger::AGENCY) << "invalid endpoint '" << _agencyMyAddress
<< "' specified for --agency.my-address";
FATAL_ERROR_EXIT();
}
std::string fallback = unified;
// Now extract the hostname/IP:
auto pos = fallback.find("://");
if (pos != std::string::npos) {
fallback = fallback.substr(pos + 3);
}
pos = fallback.rfind(':');
if (pos != std::string::npos) {
fallback = fallback.substr(0, pos);
}
auto ss = ServerState::instance();
ss->findHost(fallback);
}
if (result.touched("agency.supervision")) {
_supervisionTouched = true;
}
// turn off the following features, as they are not needed in an agency:
// - ArangoSearch: not needed by agency
// - IResearchAnalyzer: analyzers are not needed by agency
// - Statistics: turn off statistics gathering for agency
// - Action/Script/FoxxQueues/Frontend: Foxx and JavaScript APIs
std::vector<std::type_index> disabledFeatures(
{std::type_index(typeid(iresearch::IResearchFeature)),
std::type_index(typeid(iresearch::IResearchAnalyzerFeature)),
std::type_index(typeid(ActionFeature)),
std::type_index(typeid(ScriptFeature)), std::type_index(typeid(FoxxQueuesFeature)),
std::type_index(typeid(FrontendFeature))});
if (!result.touched("console") || !*(options->get<BooleanParameter>("console")->ptr)) {
// specifying --console requires JavaScript, so we can only turn it off
// if not specified
// console mode inactive. so we can turn off V8
disabledFeatures.emplace_back(std::type_index(typeid(V8PlatformFeature)));
disabledFeatures.emplace_back(std::type_index(typeid(V8DealerFeature)));
}
server().disableFeatures(disabledFeatures);
}
void AgencyFeature::prepare() {
TRI_ASSERT(isEnabled());
// Available after validateOptions of ClusterFeature
// Find the agency prefix:
auto& feature = server().getFeature<ClusterFeature>();
if (!feature.agencyPrefix().empty()) {
arangodb::consensus::Supervision::setAgencyPrefix(std::string("/") +
feature.agencyPrefix());
arangodb::consensus::Job::agencyPrefix = feature.agencyPrefix();
}
std::string endpoint;
if (_agencyMyAddress.empty()) {
std::string port = "8529";
// Available after prepare of EndpointFeature
HttpEndpointProvider& endpointFeature = server().getFeature<HttpEndpointProvider>();
auto endpoints = endpointFeature.httpEndpoints();
if (!endpoints.empty()) {
std::string const& tmp = endpoints.front();
size_t pos = tmp.find(':', 10);
if (pos != std::string::npos) {
port = tmp.substr(pos + 1, tmp.size() - pos);
}
}
endpoint = std::string("tcp://localhost:" + port);
} else {
endpoint = _agencyMyAddress;
}
LOG_TOPIC("693a2", DEBUG, Logger::AGENCY) << "Agency endpoint " << endpoint;
if (_waitForSync) {
_maxAppendSize /= 10;
}
_agent.reset(new consensus::Agent(
server(), consensus::config_t(_recoveryId, _size, _poolSize, _minElectionTimeout,
_maxElectionTimeout, endpoint, _agencyEndpoints,
_supervision, _supervisionTouched, _waitForSync,
_supervisionFrequency, _compactionStepSize,
_compactionKeepSize, _supervisionGracePeriod,
_supervisionOkThreshold,_cmdLineTimings, _maxAppendSize)));
AGENT = _agent.get();
}
void AgencyFeature::start() {
TRI_ASSERT(isEnabled());
LOG_TOPIC("a77c8", DEBUG, Logger::AGENCY) << "Starting agency personality";
_agent->start();
LOG_TOPIC("b481d", DEBUG, Logger::AGENCY) << "Loading agency";
_agent->load();
}
void AgencyFeature::beginShutdown() {
TRI_ASSERT(isEnabled());
// pass shutdown event to _agent so it can notify all its sub-threads
_agent->beginShutdown();
}
void AgencyFeature::stop() {
TRI_ASSERT(isEnabled());
if (_agent->inception() != nullptr) { // can only exist in resilient agents
int counter = 0;
while (_agent->inception()->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// emit warning after 5 seconds
if (++counter == 10 * 5) {
LOG_TOPIC("bf6a6", WARN, Logger::AGENCY)
<< "waiting for inception thread to finish";
}
}
}
if (_agent != nullptr) {
int counter = 0;
while (_agent->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// emit warning after 5 seconds
if (++counter == 10 * 5) {
LOG_TOPIC("5d3a5", WARN, Logger::AGENCY) << "waiting for agent thread to finish";
}
}
// Wait until all agency threads have been shut down. Note that the
// actual agent object is only destroyed in the destructor to allow
// server jobs from RestAgencyHandlers to complete without incident:
_agent->waitForThreadsStop();
}
AGENT = nullptr;
}
void AgencyFeature::unprepare() {
TRI_ASSERT(isEnabled());
// delete the Agent object here ensures it shuts down all of its threads
// this is a precondition that it must fulfill before we can go on with the
// shutdown
_agent.reset();
}
} // namespace arangodb
<commit_msg>removed wrong comment<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2018 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "AgencyFeature.h"
#include "Actions/ActionFeature.h"
#include "Agency/Agent.h"
#include "Agency/Job.h"
#include "Agency/Supervision.h"
#include "ApplicationFeatures/ApplicationServer.h"
#include "ApplicationFeatures/HttpEndpointProvider.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "Basics/application-exit.h"
#include "Cluster/ClusterFeature.h"
#include "FeaturePhases/FoxxFeaturePhase.h"
#include "IResearch/IResearchAnalyzerFeature.h"
#include "IResearch/IResearchFeature.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/ScriptFeature.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;
namespace arangodb {
consensus::Agent* AgencyFeature::AGENT = nullptr;
AgencyFeature::AgencyFeature(application_features::ApplicationServer& server)
: ApplicationFeature(server, "Agency"),
_activated(false),
_size(1),
_poolSize(1),
_minElectionTimeout(1.0),
_maxElectionTimeout(5.0),
_supervision(false),
_supervisionTouched(false),
_waitForSync(true),
_supervisionFrequency(1.0),
_compactionStepSize(1000),
_compactionKeepSize(50000),
_maxAppendSize(250),
_supervisionGracePeriod(10.0),
_supervisionOkThreshold(5.0),
_cmdLineTimings(false) {
setOptional(true);
startsAfter<FoxxFeaturePhase>();
}
AgencyFeature::~AgencyFeature() = default;
void AgencyFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addSection("agency", "Configure the agency");
options->addOption("--agency.activate", "Activate agency",
new BooleanParameter(&_activated),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.size", "number of agents",
new UInt64Parameter(&_size),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.pool-size", "number of agent pool",
new UInt64Parameter(&_poolSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.election-timeout-min",
"minimum timeout before an agent calls for new election (in seconds)",
new DoubleParameter(&_minElectionTimeout),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.election-timeout-max",
"maximum timeout before an agent calls for new election (in seconds)",
new DoubleParameter(&_maxElectionTimeout),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.endpoint", "agency endpoints",
new VectorParameter<StringParameter>(&_agencyEndpoints),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.my-address",
"which address to advertise to the outside",
new StringParameter(&_agencyMyAddress),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.supervision",
"perform arangodb cluster supervision",
new BooleanParameter(&_supervision),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.supervision-frequency",
"arangodb cluster supervision frequency (in seconds)",
new DoubleParameter(&_supervisionFrequency),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.supervision-grace-period",
"supervision time, after which a server is considered to have failed (in seconds)",
new DoubleParameter(&_supervisionGracePeriod),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption(
"--agency.supervision-ok-threshold",
"supervision time, after which a server is considered to be bad [s]",
new DoubleParameter(&_supervisionOkThreshold),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.compaction-step-size",
"step size between state machine compactions",
new UInt64Parameter(&_compactionStepSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
options->addOption("--agency.compaction-keep-size",
"keep as many indices before compaction point",
new UInt64Parameter(&_compactionKeepSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::OnAgent));
options->addOption("--agency.wait-for-sync",
"wait for hard disk syncs on every persistence call "
"(required in production)",
new BooleanParameter(&_waitForSync),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
options->addOption("--agency.max-append-size",
"maximum size of appendEntries document (# log entries)",
new UInt64Parameter(&_maxAppendSize),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
options->addOption("--agency.disaster-recovery-id",
"allows for specification of the id for this agent; "
"dangerous option for disaster recover only!",
new StringParameter(&_recoveryId),
arangodb::options::makeFlags(arangodb::options::Flags::DefaultNoComponents, arangodb::options::Flags::Hidden, arangodb::options::Flags::OnAgent));
}
void AgencyFeature::validateOptions(std::shared_ptr<ProgramOptions> options) {
ProgramOptions::ProcessingResult const& result = options->processingResult();
if (!result.touched("agency.activate") || !_activated) {
disable();
return;
}
if (result.touched("agency.election-timeout-min")) {
_cmdLineTimings = true;
}
ServerState::instance()->setRole(ServerState::ROLE_AGENT);
// Agency size
if (result.touched("agency.size")) {
if (_size < 1) {
LOG_TOPIC("98510", FATAL, Logger::AGENCY) << "agency must have size greater 0";
FATAL_ERROR_EXIT();
}
} else {
_size = 1;
}
// Agency pool size
if (result.touched("agency.pool-size")) {
if (_poolSize < _size) {
LOG_TOPIC("af108", FATAL, Logger::AGENCY)
<< "agency pool size must be larger than agency size.";
FATAL_ERROR_EXIT();
}
} else {
_poolSize = _size;
}
// Size needs to be odd
if (_size % 2 == 0) {
LOG_TOPIC("0eab5", FATAL, Logger::AGENCY)
<< "AGENCY: agency must have odd number of members";
FATAL_ERROR_EXIT();
}
// Timeouts sanity
if (_minElectionTimeout <= 0.) {
LOG_TOPIC("facb6", FATAL, Logger::AGENCY)
<< "agency.election-timeout-min must not be negative!";
FATAL_ERROR_EXIT();
} else if (_minElectionTimeout < 0.15) {
LOG_TOPIC("0cce9", WARN, Logger::AGENCY)
<< "very short agency.election-timeout-min!";
}
if (_maxElectionTimeout <= _minElectionTimeout) {
LOG_TOPIC("62fc3", FATAL, Logger::AGENCY)
<< "agency.election-timeout-max must not be shorter than or"
<< "equal to agency.election-timeout-min.";
FATAL_ERROR_EXIT();
}
if (_maxElectionTimeout <= 2. * _minElectionTimeout) {
LOG_TOPIC("99f84", WARN, Logger::AGENCY)
<< "agency.election-timeout-max should probably be chosen longer!";
}
if (_compactionKeepSize == 0) {
LOG_TOPIC("ca485", WARN, Logger::AGENCY)
<< "agency.compaction-keep-size must not be 0, set to 1000";
_compactionKeepSize = 50000;
}
if (!_agencyMyAddress.empty()) {
std::string const unified = Endpoint::unifiedForm(_agencyMyAddress);
if (unified.empty()) {
LOG_TOPIC("4faa0", FATAL, Logger::AGENCY) << "invalid endpoint '" << _agencyMyAddress
<< "' specified for --agency.my-address";
FATAL_ERROR_EXIT();
}
std::string fallback = unified;
// Now extract the hostname/IP:
auto pos = fallback.find("://");
if (pos != std::string::npos) {
fallback = fallback.substr(pos + 3);
}
pos = fallback.rfind(':');
if (pos != std::string::npos) {
fallback = fallback.substr(0, pos);
}
auto ss = ServerState::instance();
ss->findHost(fallback);
}
if (result.touched("agency.supervision")) {
_supervisionTouched = true;
}
// turn off the following features, as they are not needed in an agency:
// - ArangoSearch: not needed by agency
// - IResearchAnalyzer: analyzers are not needed by agency
// - Action/Script/FoxxQueues/Frontend: Foxx and JavaScript APIs
std::vector<std::type_index> disabledFeatures(
{std::type_index(typeid(iresearch::IResearchFeature)),
std::type_index(typeid(iresearch::IResearchAnalyzerFeature)),
std::type_index(typeid(ActionFeature)),
std::type_index(typeid(ScriptFeature)), std::type_index(typeid(FoxxQueuesFeature)),
std::type_index(typeid(FrontendFeature))});
if (!result.touched("console") || !*(options->get<BooleanParameter>("console")->ptr)) {
// specifying --console requires JavaScript, so we can only turn it off
// if not specified
// console mode inactive. so we can turn off V8
disabledFeatures.emplace_back(std::type_index(typeid(V8PlatformFeature)));
disabledFeatures.emplace_back(std::type_index(typeid(V8DealerFeature)));
}
server().disableFeatures(disabledFeatures);
}
void AgencyFeature::prepare() {
TRI_ASSERT(isEnabled());
// Available after validateOptions of ClusterFeature
// Find the agency prefix:
auto& feature = server().getFeature<ClusterFeature>();
if (!feature.agencyPrefix().empty()) {
arangodb::consensus::Supervision::setAgencyPrefix(std::string("/") +
feature.agencyPrefix());
arangodb::consensus::Job::agencyPrefix = feature.agencyPrefix();
}
std::string endpoint;
if (_agencyMyAddress.empty()) {
std::string port = "8529";
// Available after prepare of EndpointFeature
HttpEndpointProvider& endpointFeature = server().getFeature<HttpEndpointProvider>();
auto endpoints = endpointFeature.httpEndpoints();
if (!endpoints.empty()) {
std::string const& tmp = endpoints.front();
size_t pos = tmp.find(':', 10);
if (pos != std::string::npos) {
port = tmp.substr(pos + 1, tmp.size() - pos);
}
}
endpoint = std::string("tcp://localhost:" + port);
} else {
endpoint = _agencyMyAddress;
}
LOG_TOPIC("693a2", DEBUG, Logger::AGENCY) << "Agency endpoint " << endpoint;
if (_waitForSync) {
_maxAppendSize /= 10;
}
_agent.reset(new consensus::Agent(
server(), consensus::config_t(_recoveryId, _size, _poolSize, _minElectionTimeout,
_maxElectionTimeout, endpoint, _agencyEndpoints,
_supervision, _supervisionTouched, _waitForSync,
_supervisionFrequency, _compactionStepSize,
_compactionKeepSize, _supervisionGracePeriod,
_supervisionOkThreshold,_cmdLineTimings, _maxAppendSize)));
AGENT = _agent.get();
}
void AgencyFeature::start() {
TRI_ASSERT(isEnabled());
LOG_TOPIC("a77c8", DEBUG, Logger::AGENCY) << "Starting agency personality";
_agent->start();
LOG_TOPIC("b481d", DEBUG, Logger::AGENCY) << "Loading agency";
_agent->load();
}
void AgencyFeature::beginShutdown() {
TRI_ASSERT(isEnabled());
// pass shutdown event to _agent so it can notify all its sub-threads
_agent->beginShutdown();
}
void AgencyFeature::stop() {
TRI_ASSERT(isEnabled());
if (_agent->inception() != nullptr) { // can only exist in resilient agents
int counter = 0;
while (_agent->inception()->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// emit warning after 5 seconds
if (++counter == 10 * 5) {
LOG_TOPIC("bf6a6", WARN, Logger::AGENCY)
<< "waiting for inception thread to finish";
}
}
}
if (_agent != nullptr) {
int counter = 0;
while (_agent->isRunning()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// emit warning after 5 seconds
if (++counter == 10 * 5) {
LOG_TOPIC("5d3a5", WARN, Logger::AGENCY) << "waiting for agent thread to finish";
}
}
// Wait until all agency threads have been shut down. Note that the
// actual agent object is only destroyed in the destructor to allow
// server jobs from RestAgencyHandlers to complete without incident:
_agent->waitForThreadsStop();
}
AGENT = nullptr;
}
void AgencyFeature::unprepare() {
TRI_ASSERT(isEnabled());
// delete the Agent object here ensures it shuts down all of its threads
// this is a precondition that it must fulfill before we can go on with the
// shutdown
_agent.reset();
}
} // namespace arangodb
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in btc/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc/kb\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getinfo", "")
+ HelpExampleRpc("getinfo", "")
);
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("mastercoreversion", (int)1010008)); // strip the initial '10' : for tagged release go to 10007, etc.
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", TestNet()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(CTransaction::nMinRelayTxFee)));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"bitcoinaddress\"\n"
"\nReturn information about the given bitcoin address.\n"
"\nArguments:\n"
"1. \"bitcoinaddress\" (string, required) The bitcoin address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"bitcoinaddress\", (string) The bitcoin address validated\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
);
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
//
// Used by addmultisigaddress / createmultisig:
//
CScript _createmultisig_redeemScript(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
throw runtime_error(
strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
return result;
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) bitcoin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
;
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"bitcoinaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"bitcoinaddress\" (string, required) The bitcoin address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")
);
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
<commit_msg>bump the ver #<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in btc/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc/kb\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getinfo", "")
+ HelpExampleRpc("getinfo", "")
);
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("mastercoreversion", (int)1020008)); // strip the initial '10' : for tagged release go to 10007, etc.
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", TestNet()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(CTransaction::nMinRelayTxFee)));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"bitcoinaddress\"\n"
"\nReturn information about the given bitcoin address.\n"
"\nArguments:\n"
"1. \"bitcoinaddress\" (string, required) The bitcoin address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"bitcoinaddress\", (string) The bitcoin address validated\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
);
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
//
// Used by addmultisigaddress / createmultisig:
//
CScript _createmultisig_redeemScript(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
throw runtime_error(
strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
return result;
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) bitcoin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
;
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"bitcoinaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"bitcoinaddress\" (string, required) The bitcoin address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")
);
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string.h>
#include <istream>
#include <cstring>
#include <unistd.h>
using namespace std;
#include <cstdio>
#include <stdio.h>
#include <string.h>
/*
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
*/
//need to figure out how to parse!!
//see boost library's TOKENIZER !!!!!
int main()
{
string input;
//taking input as a c++ string; will convert to c_str later
cout << "$ "; //command prompt
getline (cin,input);
cout << endl << "outputting input: " << endl << input << endl;
//these will be the arguments to my shell after parsing
int argc = 0; // no arguments (yet)
char* argv[99999];
argv[0] = new char[9999];
char * tmp; //cstring to not deal with memory management for now
char delims[] = " &&||;-"; // connectors we are looking out for.
//FIXME: may not be exactly what we want since may have
//to be arguments too
char input2[9999];
strcpy(input2, input.c_str() );
/*
char *argv[3];
argv[0]=new char[3];
strcpy(argv[0],"ls");
argv[1]="-a";
argv[2]="-l";
*/
cout << "about to run strtok 1st time" << endl;
tmp = strtok(input2,delims) ;
strcpy( argv[argc] , tmp ); //copying first token
argc += 1;
cout << "about to run strtok In while loop." << endl;
while (tmp != NULL)
{
argv[argc] = tmp; // copying tokens into argv one at a time
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL,delims);
}
/* cerr << "copying tmp into argv..." << endl;
strcpy(*argv,tmp );
cout << "strcpy successful!! (maybe LOL)" << endl;
*/
//checking everything was read in
cout << "argc: " << argc << " " << endl;
cout << " argv:" << endl;
for(unsigned i = 0; argv[i]!='\0'; ++i){
cout << i << ": " << argv[i] << endl;
}
//need to figure out a way to read in commands with ';' in between
//and white space in between
if (argv[1]=='\0'){
cout << "Null man. " << endl;
}
//execvp(argv);
cout << "||" << endl;
return 0;
}
<commit_msg>changed minor bug in rschell.cpp (first argument occurring twice in argv)..still need to figure out way to not parse out connectorsgit add rschell.cpp!<commit_after>#include <iostream>
#include <string.h>
#include <istream>
#include <cstring>
#include <unistd.h>
using namespace std;
#include <cstdio>
#include <stdio.h>
#include <string.h>
/*
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
*/
//need to figure out how to parse!!
//see boost library's TOKENIZER !!!!!
int main()
{
string input;
//taking input as a c++ string; will convert to c_str later
cout << "$ "; //command prompt
getline (cin,input);
cout << endl << "outputting input: " << endl << input << endl;
//these will be the arguments to my shell after parsing
int argc = 0; // no arguments (yet)
char* argv[99999];
argv[0] = new char[9999];
char * tmp; //cstring to not deal with memory management for now
char delims[] = " &&||;-"; // connectors we are looking out for.
//FIXME: may not be exactly what we want since may have
//to be arguments too
char input2[9999];
strcpy(input2, input.c_str() );
cout << "about to run strtok 1st time" << endl;
tmp = strtok(input2,delims) ;
strcpy( argv[argc] , tmp ); //copying first token
cout << "about to run strtok In while loop." << endl;
while (tmp != NULL)
{
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL,delims);
argv[argc] = tmp; // copying tokens into argv one at a time
}
/* cerr << "copying tmp into argv..." << endl;
strcpy(*argv,tmp );
cout << "strcpy successful!! (maybe LOL)" << endl;
*/
//checking everything was read in
cout << "argc: " << argc << " " << endl;
cout << " argv:" << endl;
for(unsigned i = 0; argv[i]!='\0'; ++i){
cout << i << ": " << argv[i] << endl;
}
//need to figure out a way to read in commands with ';' in between
//and white space in between
if (argv[1]=='\0'){
cout << "Null man. " << endl;
}
//execvp(argv);
cout << "||" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef SIMDIFY_UTIL_INLINE
#define SIMDIFY_UTIL_INLINE
#if defined(__GNUC__)
#define SIMDIFY_FORCE_INLINE __attribute__((always_inline)) inline
#elif defined(_MSC_VER)
#define SIMDIFY_FORCE_INLINE __forceinline
#else
#error "util_inline.h: incompatible compiler"
#endif
#endif // SIMDIFY_UTIL_INLINE
<commit_msg>Stronger inline modifiers for GCC and Clang<commit_after>#ifndef SIMDIFY_UTIL_INLINE
#define SIMDIFY_UTIL_INLINE
#if defined(__clang__)
#define SIMDIFY_FORCE_INLINE __inline__ __attribute__((always_inline, nodebug))
#elif defined(__GNUC__)
#define SIMDIFY_FORCE_INLINE __inline__ __attribute__((always_inline))
#elif defined(_MSC_VER)
#define SIMDIFY_FORCE_INLINE __forceinline
#else
#error "util_inline.h: incompatible compiler"
#endif
#endif // SIMDIFY_UTIL_INLINE
<|endoftext|>
|
<commit_before>/*==============================================================================
Copyright (c) Kapteyn Astronomical Institute
University of Groningen, Groningen, Netherlands. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute,
and was supported through the European Research Council grant nr. 291531.
==============================================================================*/
// Qt includes
#include <QDebug>
#include <QtPlugin>
// Slicer includes
#include <qSlicerCoreApplication.h>
#include <qSlicerModuleManager.h>
// Logic includes
#include <vtkSlicerAstroVolumeLogic.h>
#include <vtkSlicerAstroReprojectLogic.h>
// AstroReproject includes
#include "qSlicerAstroReprojectModule.h"
#include "qSlicerAstroReprojectModuleWidget.h"
//-----------------------------------------------------------------------------
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QtPlugin>
Q_EXPORT_PLUGIN2(qSlicerAstroReprojectModule, qSlicerAstroReprojectModule);
#endif
//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_AstroReproject
class qSlicerAstroReprojectModulePrivate
{
public:
qSlicerAstroReprojectModulePrivate();
};
//-----------------------------------------------------------------------------
// qSlicerAstroReprojectModulePrivate methods
//-----------------------------------------------------------------------------
qSlicerAstroReprojectModulePrivate::qSlicerAstroReprojectModulePrivate()
{
}
//-----------------------------------------------------------------------------
// qSlicerAstroReprojectModule methods
//-----------------------------------------------------------------------------
qSlicerAstroReprojectModule::qSlicerAstroReprojectModule(QObject* _parent)
: Superclass(_parent)
, d_ptr(new qSlicerAstroReprojectModulePrivate)
{
}
//-----------------------------------------------------------------------------
qSlicerAstroReprojectModule::~qSlicerAstroReprojectModule()
{
}
//-----------------------------------------------------------------------------
QString qSlicerAstroReprojectModule::helpText()const
{
return "AstroReproject module filters a Volume using several techniques. "
"The algorithms are optmized for Astronomical Neutral Hydrogen (HI) data.";
}
//-----------------------------------------------------------------------------
QString qSlicerAstroReprojectModule::acknowledgementText()const
{
return "The AstroReproject module implements image reprojection (resampling) methods "
"for astronomical datasets. Specifically, the methods have been designed to "
"reproject the spatial axis, (e.g., 2D images or 3D datacubes over 2D images)."
"For example in the case of datacubes, the algorithm reprojects each slice "
"(spatial celestial axis) of the datacube with the reference data (treating each slice as independent). "
"However, overlaying two 3D astronomical datasets requires also to resample the velocity axes, "
"which is not implemented in this module. "
"The AstroReproject module requires that the WCS information contained in the fits header are correct. ";
}
//-----------------------------------------------------------------------------
QStringList qSlicerAstroReprojectModule::contributors()const
{
QStringList moduleContributors;
moduleContributors << QString("Davide Punzo (Kapteyn Astronomical Institute)");
moduleContributors << QString("Thijs van der Hulst (Kapteyn Astronomical Institute)");
return moduleContributors;
}
//-----------------------------------------------------------------------------
QIcon qSlicerAstroReprojectModule::icon()const
{
return QIcon(":/Icons/AstroReproject.png");
}
//-----------------------------------------------------------------------------
QStringList qSlicerAstroReprojectModule::categories()const
{
return QStringList() << "Astronomy" << "Registration";
}
//-----------------------------------------------------------------------------
QStringList qSlicerAstroReprojectModule::dependencies()const
{
return QStringList() << "AstroVolume" ;
}
//-----------------------------------------------------------------------------
void qSlicerAstroReprojectModule::setup()
{
this->Superclass::setup();
vtkSlicerAstroReprojectLogic* AstroReprojectLogic =
vtkSlicerAstroReprojectLogic::SafeDownCast(this->logic());
qSlicerAbstractCoreModule* astroVolumeModule =
qSlicerCoreApplication::application()->moduleManager()->module("AstroVolume");
if (!astroVolumeModule)
{
qCritical() << "AstroVolume module is not found";
return;
}
vtkSlicerAstroVolumeLogic* astroVolumeLogic =
vtkSlicerAstroVolumeLogic::SafeDownCast(astroVolumeModule->logic());
AstroReprojectLogic->SetAstroVolumeLogic(astroVolumeLogic);
}
//-----------------------------------------------------------------------------
qSlicerAbstractModuleRepresentation * qSlicerAstroReprojectModule::createWidgetRepresentation()
{
return new qSlicerAstroReprojectModuleWidget;
}
//-----------------------------------------------------------------------------
vtkMRMLAbstractLogic* qSlicerAstroReprojectModule::createLogic()
{
return vtkSlicerAstroReprojectLogic::New();
}
<commit_msg>STYLE: fixed reprojection module helptext<commit_after>/*==============================================================================
Copyright (c) Kapteyn Astronomical Institute
University of Groningen, Groningen, Netherlands. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute,
and was supported through the European Research Council grant nr. 291531.
==============================================================================*/
// Qt includes
#include <QDebug>
#include <QtPlugin>
// Slicer includes
#include <qSlicerCoreApplication.h>
#include <qSlicerModuleManager.h>
// Logic includes
#include <vtkSlicerAstroVolumeLogic.h>
#include <vtkSlicerAstroReprojectLogic.h>
// AstroReproject includes
#include "qSlicerAstroReprojectModule.h"
#include "qSlicerAstroReprojectModuleWidget.h"
//-----------------------------------------------------------------------------
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QtPlugin>
Q_EXPORT_PLUGIN2(qSlicerAstroReprojectModule, qSlicerAstroReprojectModule);
#endif
//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_AstroReproject
class qSlicerAstroReprojectModulePrivate
{
public:
qSlicerAstroReprojectModulePrivate();
};
//-----------------------------------------------------------------------------
// qSlicerAstroReprojectModulePrivate methods
//-----------------------------------------------------------------------------
qSlicerAstroReprojectModulePrivate::qSlicerAstroReprojectModulePrivate()
{
}
//-----------------------------------------------------------------------------
// qSlicerAstroReprojectModule methods
//-----------------------------------------------------------------------------
qSlicerAstroReprojectModule::qSlicerAstroReprojectModule(QObject* _parent)
: Superclass(_parent)
, d_ptr(new qSlicerAstroReprojectModulePrivate)
{
}
//-----------------------------------------------------------------------------
qSlicerAstroReprojectModule::~qSlicerAstroReprojectModule()
{
}
//-----------------------------------------------------------------------------
QString qSlicerAstroReprojectModule::helpText()const
{
return "The AstroReproject module implements image reprojection (resampling) methods "
"for astronomical datasets. Specifically, the methods have been designed to "
"reproject the spatial axis, (e.g., 2D images or 3D datacubes over 2D images)."
"For example in the case of datacubes, the algorithm reprojects each slice "
"(spatial celestial axis) of the datacube with the reference data (treating each slice as independent). "
"However, overlaying two 3D astronomical datasets requires also to resample the velocity axes, "
"which is not implemented in this module. "
"The AstroReproject module requires that the WCS information contained in the fits header are correct"
"and that the two datasets ahve the same celestial system of reference (e.g., J2000/FK5). ";
}
//-----------------------------------------------------------------------------
QString qSlicerAstroReprojectModule::acknowledgementText()const
{
return "This module was developed by Davide Punzo. <br>"
"This work was supported by ERC grant nr. 291531, "
"and Slicer community. <br>";
}
//-----------------------------------------------------------------------------
QStringList qSlicerAstroReprojectModule::contributors()const
{
QStringList moduleContributors;
moduleContributors << QString("Davide Punzo (Kapteyn Astronomical Institute)");
moduleContributors << QString("Thijs van der Hulst (Kapteyn Astronomical Institute)");
return moduleContributors;
}
//-----------------------------------------------------------------------------
QIcon qSlicerAstroReprojectModule::icon()const
{
return QIcon(":/Icons/AstroReproject.png");
}
//-----------------------------------------------------------------------------
QStringList qSlicerAstroReprojectModule::categories()const
{
return QStringList() << "Astronomy" << "Registration";
}
//-----------------------------------------------------------------------------
QStringList qSlicerAstroReprojectModule::dependencies()const
{
return QStringList() << "AstroVolume" ;
}
//-----------------------------------------------------------------------------
void qSlicerAstroReprojectModule::setup()
{
this->Superclass::setup();
vtkSlicerAstroReprojectLogic* AstroReprojectLogic =
vtkSlicerAstroReprojectLogic::SafeDownCast(this->logic());
qSlicerAbstractCoreModule* astroVolumeModule =
qSlicerCoreApplication::application()->moduleManager()->module("AstroVolume");
if (!astroVolumeModule)
{
qCritical() << "AstroVolume module is not found";
return;
}
vtkSlicerAstroVolumeLogic* astroVolumeLogic =
vtkSlicerAstroVolumeLogic::SafeDownCast(astroVolumeModule->logic());
AstroReprojectLogic->SetAstroVolumeLogic(astroVolumeLogic);
}
//-----------------------------------------------------------------------------
qSlicerAbstractModuleRepresentation * qSlicerAstroReprojectModule::createWidgetRepresentation()
{
return new qSlicerAstroReprojectModuleWidget;
}
//-----------------------------------------------------------------------------
vtkMRMLAbstractLogic* qSlicerAstroReprojectModule::createLogic()
{
return vtkSlicerAstroReprojectLogic::New();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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 <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/dateformat.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/absolutetimedateformat.h>
#include <iomanip> // for setw & setfill
#include <time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
String AbsoluteTimeDateFormat::ISO8601_DATE_FORMAT = _T("ISO8601");
String AbsoluteTimeDateFormat::ABS_TIME_DATE_FORMAT = _T("ABSOLUTE");
String AbsoluteTimeDateFormat::DATE_AND_TIME_DATE_FORMAT = _T("DATE");
DateFormat::DateFormat(const String& dateFormat)
: dateFormat(dateFormat), timeZone(TimeZone::getDefault())
{
size_t pos = this->dateFormat.find(_T("%Q"));
if (pos != String::npos)
{
this->dateFormat = this->dateFormat.substr(0, pos);
this->dateFormat +=_T("%");
this->dateFormat += this->dateFormat.substr(pos);
}
}
DateFormat::DateFormat(const String& dateFormat, const TimeZonePtr& timeZone)
: dateFormat(dateFormat), timeZone(timeZone)
{
size_t pos = this->dateFormat.find(_T("%Q"));
if (pos != String::npos)
{
this->dateFormat = this->dateFormat.substr(0, pos);
this->dateFormat += _T("%");
this->dateFormat += this->dateFormat.substr(pos);
}
}
DateFormat::~DateFormat()
{
}
void DateFormat::format(ostream& os, int64_t timeMillis) const
{
TCHAR buffer[255];
if (timeZone == 0)
{
throw NullPointerException(_T("timeZone is null"));
}
int64_t localTimeMillis = timeMillis + timeZone->getOffset(timeMillis);
time_t time = (time_t)(localTimeMillis/1000);
const tm * tm = ::gmtime(&time);
#ifdef LOG4CXX_UNICODE
size_t len = ::wcsftime(buffer, 255, dateFormat.c_str(), tm);
#else
size_t len = ::strftime(buffer, 255, dateFormat.c_str(), tm);
#endif
buffer[len] = '\0';
String result(buffer);
size_t pos = result.find(_T("%Q"));
if (pos != String::npos)
{
os << result.substr(0, pos)
<< std::setw(3) << std::setfill(_T('0')) << (long)(timeMillis % 1000)
<< result.substr(pos + 2);
}
else
{
os << result;
}
}
String DateFormat::format(int64_t timeMillis) const
{
StringBuffer sbuf;
format(sbuf, timeMillis);
return sbuf.str();
}
<commit_msg>fixed regression introduced in LOG4CXX-8 fix.<commit_after>/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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 <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/dateformat.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/absolutetimedateformat.h>
#include <iomanip> // for setw & setfill
#include <time.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
String AbsoluteTimeDateFormat::ISO8601_DATE_FORMAT = _T("ISO8601");
String AbsoluteTimeDateFormat::ABS_TIME_DATE_FORMAT = _T("ABSOLUTE");
String AbsoluteTimeDateFormat::DATE_AND_TIME_DATE_FORMAT = _T("DATE");
DateFormat::DateFormat(const String& dateFormat)
: dateFormat(dateFormat), timeZone(TimeZone::getDefault())
{
size_t pos = this->dateFormat.find(_T("%Q"));
if (pos != String::npos)
{
this->dateFormat.insert(pos, _T("%"));
}
}
DateFormat::DateFormat(const String& dateFormat, const TimeZonePtr& timeZone)
: dateFormat(dateFormat), timeZone(timeZone)
{
size_t pos = this->dateFormat.find(_T("%Q"));
if (pos != String::npos)
{
this->dateFormat.insert(pos, _T("%"));
}
}
DateFormat::~DateFormat()
{
}
void DateFormat::format(ostream& os, int64_t timeMillis) const
{
TCHAR buffer[255];
if (timeZone == 0)
{
throw NullPointerException(_T("timeZone is null"));
}
int64_t localTimeMillis = timeMillis + timeZone->getOffset(timeMillis);
time_t time = (time_t)(localTimeMillis/1000);
const tm * tm = ::gmtime(&time);
#ifdef LOG4CXX_UNICODE
size_t len = ::wcsftime(buffer, 255, dateFormat.c_str(), tm);
#else
size_t len = ::strftime(buffer, 255, dateFormat.c_str(), tm);
#endif
buffer[len] = '\0';
String result(buffer);
size_t pos = result.find(_T("%Q"));
if (pos != String::npos)
{
os << result.substr(0, pos)
<< std::setw(3) << std::setfill(_T('0')) << (long)(timeMillis % 1000)
<< result.substr(pos + 2);
}
else
{
os << result;
}
}
String DateFormat::format(int64_t timeMillis) const
{
StringBuffer sbuf;
format(sbuf, timeMillis);
return sbuf.str();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "console_server.h"
#include "log.h"
#include "os.h"
#include "platform.h"
#include "string_stream.h"
#include "string_utils.h"
#include "temp_allocator.h"
#include "device.h"
namespace crown
{
namespace log_internal
{
static StringStream& sanitize(StringStream& ss, const char* msg)
{
using namespace string_stream;
const char* ch = msg;
for (; *ch; ch++)
{
if (*ch == '"')
ss << "\\";
ss << *ch;
}
return ss;
}
static void console_log(const char* msg, LogSeverity::Enum sev)
{
if (!console_server_globals::console())
return;
static const char* stt[] = { "info", "warning", "error", "debug" };
// Build json message
using namespace string_stream;
TempAllocator4096 ta;
StringStream json(ta);
json << "{\"type\":\"message\",";
json << "\"severity\":\"" << stt[sev] << "\",";
json << "\"message\":\""; sanitize(json, msg) << "\"}";
console_server_globals::console()->send(c_str(json));
}
void logx(LogSeverity::Enum sev, const char* msg, va_list args)
{
char buf[8192];
int len = vsnprintf(buf, sizeof(buf), msg, args);
buf[len] = '\0';
#if CROWN_PLATFORM_POSIX
#define ANSI_RESET "\x1b[0m"
#define ANSI_YELLOW "\x1b[33m"
#define ANSI_RED "\x1b[31m"
static const char* stt[] =
{
ANSI_RESET,
ANSI_YELLOW,
ANSI_RED,
ANSI_RESET
};
os::log(stt[sev]);
os::log(buf);
os::log(ANSI_RESET);
#else
os::log(buf);
#endif
os::log("\n");
if (device())
{
device()->log(buf);
}
console_log(buf, sev);
}
void logx(LogSeverity::Enum sev, const char* msg, ...)
{
va_list args;
va_start(args, msg);
logx(sev, msg, args);
va_end(args);
}
} // namespace log
} // namespace crown
<commit_msg>Make logging thread-safe<commit_after>/*
* Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "console_server.h"
#include "device.h"
#include "log.h"
#include "mutex.h"
#include "os.h"
#include "platform.h"
#include "string_stream.h"
#include "string_utils.h"
#include "temp_allocator.h"
namespace crown
{
namespace log_internal
{
static Mutex s_mutex;
static StringStream& sanitize(StringStream& ss, const char* msg)
{
using namespace string_stream;
const char* ch = msg;
for (; *ch; ch++)
{
if (*ch == '"')
ss << "\\";
ss << *ch;
}
return ss;
}
static void console_log(const char* msg, LogSeverity::Enum sev)
{
if (!console_server_globals::console())
return;
static const char* stt[] = { "info", "warning", "error", "debug" };
// Build json message
using namespace string_stream;
TempAllocator4096 ta;
StringStream json(ta);
json << "{\"type\":\"message\",";
json << "\"severity\":\"" << stt[sev] << "\",";
json << "\"message\":\""; sanitize(json, msg) << "\"}";
console_server_globals::console()->send(c_str(json));
}
void logx(LogSeverity::Enum sev, const char* msg, va_list args)
{
ScopedMutex sm(s_mutex);
char buf[8192];
int len = vsnprintf(buf, sizeof(buf), msg, args);
buf[len] = '\0';
#if CROWN_PLATFORM_POSIX
#define ANSI_RESET "\x1b[0m"
#define ANSI_YELLOW "\x1b[33m"
#define ANSI_RED "\x1b[31m"
static const char* stt[] =
{
ANSI_RESET,
ANSI_YELLOW,
ANSI_RED,
ANSI_RESET
};
os::log(stt[sev]);
os::log(buf);
os::log(ANSI_RESET);
#else
os::log(buf);
#endif
os::log("\n");
if (device())
{
device()->log(buf);
}
console_log(buf, sev);
}
void logx(LogSeverity::Enum sev, const char* msg, ...)
{
va_list args;
va_start(args, msg);
logx(sev, msg, args);
va_end(args);
}
} // namespace log
} // namespace crown
<|endoftext|>
|
<commit_before>//
// sdSaver.cpp
//
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "sdConst.h"
#include "sdEntity.h"
#include "sdScene.h"
#include "sdSaver.h"
#include "tinyxml2.h"
#include "JSONNode.h"
using namespace std;
string sdGlobalEvent::getKindAsString(void){
string str;
switch (kind) {
case SD_SOURCE:
str = string("source");
break;
case SD_SINK:
str = string("sink");
break;
default:
break;
}
return str;
}
string sdSaver::XMLFromScene(sdScene *scene){
using namespace tinyxml2;
XMLDocument xml;
XMLDeclaration* decl = xml.NewDeclaration();
decl->SetValue("xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");
xml.InsertEndChild(decl);
XMLElement* spatdif = xml.NewElement("spatdif");
xml.InsertEndChild(spatdif);
// meta section
XMLElement* meta = xml.NewElement("meta");
spatdif->SetAttribute("version", "0.3");
spatdif->InsertEndChild(meta);
XMLElement* info = xml.NewElement("info");
meta->InsertEndChild(info);
sdInfo information = scene->getInfo();
string infoStrings[6];
string elementNameStrings[6];
infoStrings[0] = information.getAuthor();
infoStrings[1] = information.getHost();
infoStrings[2] = information.getDateAsString();
infoStrings[3] = information.getLocation();
infoStrings[4] = information.getSession();
infoStrings[5] = information.getAnnotation();
elementNameStrings[0] = "author";
elementNameStrings[1] = "host";
elementNameStrings[2] = "date";
elementNameStrings[3] = "location";
elementNameStrings[4] = "session";
elementNameStrings[5] = "annotation";
for(int i = 0; i< 6; i++){
if(!infoStrings[i].empty()){
XMLElement* e = xml.NewElement(elementNameStrings[i].c_str());
XMLText* t = xml.NewText(infoStrings[i].c_str());
e->InsertEndChild(t);
info->InsertEndChild(e);
}
}
// check the number of extension
int num = scene->getNumberOfActivatedExtensions();
if(num > 0){
XMLElement* extensions = xml.NewElement("extensions");
string extString;
for(int i = 0; i< num; i++){
EExtension ext = scene->getActivatedExtension(i);
extString = extString + extensionToString(ext);
}
XMLText* extensionsText = xml.NewText(extString.c_str());
extensions->InsertEndChild(extensionsText);
}
XMLElement* order = xml.NewElement("ordering");
XMLText* orderingText = xml.NewText(scene->getOrderingAsString().c_str());
order->InsertEndChild(orderingText);
meta->InsertEndChild(order);
// time section
vector<sdEntityCore*> entityVector = scene->getEntityVector();
/* ordered by time */
if(scene->getOrdering() == SD_TIME){
// 1. pool all events in globalEvent Set
vector<sdEntityCore*>::iterator it = entityVector.begin();
multiset<sdGlobalEvent, sdGlobalEventCompare> allEventSet;
while(it != entityVector.end()){
sdEntityCore *entity = *it;
multiset<sdEvent*, sdEventCompare> eventSet = entity->getEventSet();
multiset<sdEvent*, sdEventCompare>::iterator iit =eventSet.begin();
while(iit != eventSet.end()){
sdEvent* event = *iit;
sdGlobalEvent globalEvent(event, entity->getName(), entity->getKind());
allEventSet.insert(globalEvent); // gather pointer to all existing instances of sdEvent
++iit;
}
++it;
}
// 2. create string
multiset<sdGlobalEvent, sdGlobalEventCompare>::iterator eit = allEventSet.begin();
while(eit != allEventSet.end()){
sdGlobalEvent event = *eit;
XMLElement* time = xml.NewElement("time");
XMLText* timeText = xml.NewText(event.getEvent()->getTimeAsString().c_str());
time->InsertEndChild(timeText);
spatdif->InsertEndChild(time);
XMLElement* kind;
kind = xml.NewElement(event.getKindAsString().c_str());
XMLElement* name = xml.NewElement("name");
XMLText* nameText = xml.NewText(event.getEntityName().c_str());
name->InsertEndChild(nameText);
kind->InsertEndChild(name);
XMLElement* element = xml.NewElement(event.getEvent()->getDescriptorAsString().c_str());
XMLText* text = xml.NewText(event.getEvent()->getValueAsString().c_str());
element->InsertEndChild(text);
kind->InsertEndChild(element);
spatdif->InsertEndChild(kind);
++eit;
}
}else if(scene->getOrdering() == SD_TRACK){
// 1. Sort vector by name alphabetically
sort(entityVector.begin(), entityVector.end(), sdEntityCore::sortAlphabetically);
vector<sdEntityCore*>::iterator it = entityVector.begin();
while(it != entityVector.end()){
sdEntityCore *entity = *it;
multiset<sdEvent*, sdEventCompare> eventSet = entity->getEventSet();
multiset<sdEvent*, sdEventCompare>::iterator iit = eventSet.begin();
while(iit != eventSet.end()){
sdEvent* event = *iit;
XMLElement* time = xml.NewElement("time");
XMLText* timeText = xml.NewText(event->getTimeAsString().c_str());
time->InsertEndChild(timeText);
spatdif->InsertEndChild(time);
XMLElement* kind;
kind = xml.NewElement(entity->getKindAsString().c_str());
XMLElement* name = xml.NewElement("name");
XMLText* nameText = xml.NewText(entity->getName().c_str());
name->InsertEndChild(nameText);
kind->InsertEndChild(name);
XMLElement* element = xml.NewElement(event->getDescriptorAsString().c_str());
XMLText* text = xml.NewText(event->getValueAsString().c_str());
element->InsertEndChild(text);
kind->InsertEndChild(element);
spatdif->InsertEndChild(kind);
++iit;
}
++it;
}
}
XMLPrinter printer;
xml.Print(&printer);
return string(printer.CStr());
}
string sdSaver::JSONFromScene( sdScene *sdScene){
return NULL;
}
string sdSaver::YAMLFromScene( sdScene *sdScene){
return NULL;
}<commit_msg>sdSaver Extension compatibility in progress<commit_after>//
// sdSaver.cpp
//
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "sdConst.h"
#include "sdEntity.h"
#include "sdEntityExtension.h"
#include "sdScene.h"
#include "sdSaver.h"
#include "tinyxml2.h"
#include "JSONNode.h"
using namespace std;
string sdGlobalEvent::getKindAsString(void){
string str;
switch (kind) {
case SD_SOURCE:
str = string("source");
break;
case SD_SINK:
str = string("sink");
break;
default:
break;
}
return str;
}
string sdSaver::XMLFromScene(sdScene *scene){
using namespace tinyxml2;
XMLDocument xml;
XMLDeclaration* decl = xml.NewDeclaration();
decl->SetValue("xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");
xml.InsertEndChild(decl);
XMLElement* spatdif = xml.NewElement("spatdif");
xml.InsertEndChild(spatdif);
// meta section
XMLElement* meta = xml.NewElement("meta");
spatdif->SetAttribute("version", "0.3");
spatdif->InsertEndChild(meta);
XMLElement* info = xml.NewElement("info");
meta->InsertEndChild(info);
sdInfo information = scene->getInfo();
string infoStrings[6];
string elementNameStrings[6];
infoStrings[0] = information.getAuthor();
infoStrings[1] = information.getHost();
infoStrings[2] = information.getDateAsString();
infoStrings[3] = information.getLocation();
infoStrings[4] = information.getSession();
infoStrings[5] = information.getAnnotation();
elementNameStrings[0] = "author";
elementNameStrings[1] = "host";
elementNameStrings[2] = "date";
elementNameStrings[3] = "location";
elementNameStrings[4] = "session";
elementNameStrings[5] = "annotation";
for(int i = 0; i< 6; i++){
if(!infoStrings[i].empty()){
XMLElement* elem = xml.NewElement(elementNameStrings[i].c_str());
XMLText* tex = xml.NewText(infoStrings[i].c_str());
elem->InsertEndChild(tex);
info->InsertEndChild(elem);
}
}
// check the number of extension
int num = scene->getNumberOfActivatedExtensions();
if(num > 0){
XMLElement* extensions = xml.NewElement("extensions");
string extString;
for(int i = 0; i< num; i++){
EExtension ext = scene->getActivatedExtension(i);
extString = extString + extensionToString(ext);
}
XMLText* extensionsText = xml.NewText(extString.c_str());
extensions->InsertEndChild(extensionsText);
meta->InsertEndChild(extensions);
}
XMLElement* order = xml.NewElement("ordering");
XMLText* orderingText = xml.NewText(scene->getOrderingAsString().c_str());
order->InsertEndChild(orderingText);
meta->InsertEndChild(order);
// time section
vector<sdEntityCore*> entityVector = scene->getEntityVector();
/* ordered by time */
if(scene->getOrdering() == SD_TIME){
// 1. pool all events in globalEvent Set
vector<sdEntityCore*>::iterator it = entityVector.begin();
multiset<sdGlobalEvent, sdGlobalEventCompare> allEventSet;
while(it != entityVector.end()){
// core event
sdEntityCore *entity = *it;
multiset<sdEvent*, sdEventCompare> eventSet = entity->getEventSet();
multiset<sdEvent*, sdEventCompare>::iterator iit =eventSet.begin();
while(iit != eventSet.end()){
sdEvent* event = *iit;
sdGlobalEvent globalEvent(event, entity->getName(), entity->getKind());
allEventSet.insert(globalEvent); // gather pointer to all existing instances of sdEvent
++iit;
}
// extension event
vector <sdEntityExtension*> extensionVector = entity->getExtensionVector();
vector <sdEntityExtension*>::iterator evit = extensionVector.begin();
while (evit != extensionVector.end()) {
sdEntityExtension* attachedExtension = *evit;
multiset<sdEvent*, sdEventCompare> extEventSet = attachedExtension->getEventSet();
multiset<sdEvent*, sdEventCompare>::iterator aeit = extEventSet.begin();
while (aeit != extEventSet.end()) {
sdEvent* extEvent = *aeit;
sdGlobalEvent globalExtEvent(extEvent, entity->getName(), entity->getKind());
allEventSet.insert(globalExtEvent);
++aeit;
}
evit++;
}
++it;
}
// 2. create string
multiset<sdGlobalEvent, sdGlobalEventCompare>::iterator eit = allEventSet.begin();
while(eit != allEventSet.end()){
sdGlobalEvent event = *eit;
XMLElement* time = xml.NewElement("time");
XMLText* timeText = xml.NewText(event.getEvent()->getTimeAsString().c_str());
time->InsertEndChild(timeText);
spatdif->InsertEndChild(time);
XMLElement* kind;
kind = xml.NewElement(event.getKindAsString().c_str());
XMLElement* name = xml.NewElement("name");
XMLText* nameText = xml.NewText(event.getEntityName().c_str());
name->InsertEndChild(nameText);
kind->InsertEndChild(name);
XMLElement* element = xml.NewElement(event.getEvent()->getDescriptorAsString().c_str());
XMLText* text = xml.NewText(event.getEvent()->getValueAsString().c_str());
element->InsertEndChild(text);
kind->InsertEndChild(element);
spatdif->InsertEndChild(kind);
++eit;
}
}else if(scene->getOrdering() == SD_TRACK){
// 1. Sort vector by name alphabetically
sort(entityVector.begin(), entityVector.end(), sdEntityCore::sortAlphabetically);
vector<sdEntityCore*>::iterator it = entityVector.begin();
while(it != entityVector.end()){
sdEntityCore *entity = *it;
multiset<sdEvent*, sdEventCompare> eventSet = entity->getEventSet();
multiset<sdEvent*, sdEventCompare>::iterator iit = eventSet.begin();
while(iit != eventSet.end()){
sdEvent* event = *iit;
XMLElement* time = xml.NewElement("time");
XMLText* timeText = xml.NewText(event->getTimeAsString().c_str());
time->InsertEndChild(timeText);
spatdif->InsertEndChild(time);
XMLElement* kind;
kind = xml.NewElement(entity->getKindAsString().c_str());
XMLElement* name = xml.NewElement("name");
XMLText* nameText = xml.NewText(entity->getName().c_str());
name->InsertEndChild(nameText);
kind->InsertEndChild(name);
XMLElement* element = xml.NewElement(event->getDescriptorAsString().c_str());
XMLText* text = xml.NewText(event->getValueAsString().c_str());
element->InsertEndChild(text);
kind->InsertEndChild(element);
spatdif->InsertEndChild(kind);
++iit;
}
++it;
}
}
XMLPrinter printer;
xml.Print(&printer);
return string(printer.CStr());
}
string sdSaver::JSONFromScene( sdScene *sdScene){
return NULL;
}
string sdSaver::YAMLFromScene( sdScene *sdScene){
return NULL;
}<|endoftext|>
|
<commit_before>// Copyright (c) 2012 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 "ash/wm/frame_painter.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/test/ash_test_base.h"
#include "base/memory/scoped_ptr.h"
#include "grit/ui_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/root_window.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/widget/widget.h"
using views::Widget;
using views::ImageButton;
namespace {
aura::Window* GetDefaultContainer() {
return ash::Shell::GetContainer(
ash::Shell::GetPrimaryRootWindow(),
ash::internal::kShellWindowId_DefaultContainer);
}
// Creates a test widget that owns its native widget.
Widget* CreateTestWidget() {
Widget* widget = new Widget;
Widget::InitParams params;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = GetDefaultContainer();
params.child = true;
widget->Init(params);
return widget;
}
Widget* CreateAlwaysOnTopWidget() {
Widget* widget = new Widget;
Widget::InitParams params;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = GetDefaultContainer();
params.child = true;
params.keep_on_top = true;
widget->Init(params);
return widget;
}
} // namespace
namespace ash {
typedef ash::test::AshTestBase FramePainterTest;
TEST_F(FramePainterTest, Basics) {
// We start with a null instances pointer, as we don't initialize until the
// first FramePainter is created.
EXPECT_FALSE(FramePainter::instances_);
// Creating a painter bumps the instance count.
{
FramePainter painter;
EXPECT_TRUE(FramePainter::instances_);
EXPECT_EQ(1u, FramePainter::instances_->size());
}
// Destroying that painter leaves a valid pointer but no instances.
EXPECT_TRUE(FramePainter::instances_);
EXPECT_EQ(0u, FramePainter::instances_->size());
}
TEST_F(FramePainterTest, UseSoloWindowHeader) {
// No windows, no solo window mode.
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Create a widget and a painter for it.
scoped_ptr<Widget> w1(CreateTestWidget());
FramePainter p1;
ImageButton size1(NULL);
ImageButton close1(NULL);
p1.Init(w1.get(), NULL, &size1, &close1, FramePainter::SIZE_BUTTON_MAXIMIZES);
w1->Show();
// We only have one window, so it should use a solo header.
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Create a second widget and painter.
scoped_ptr<Widget> w2(CreateTestWidget());
FramePainter p2;
ImageButton size2(NULL);
ImageButton close2(NULL);
p2.Init(w2.get(), NULL, &size2, &close2, FramePainter::SIZE_BUTTON_MAXIMIZES);
w2->Show();
// Now there are two windows, so we should not use solo headers.
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Hide one window. Solo should be enabled.
w2->Hide();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Show that window. Solo should be disabled.
w2->Show();
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Minimize the window. Solo should be enabled.
w2->Minimize();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Close the minimized window.
w2.reset();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Open an always-on-top widget (which lives in a different container).
scoped_ptr<Widget> w3(CreateAlwaysOnTopWidget());
FramePainter p3;
ImageButton size3(NULL);
ImageButton close3(NULL);
p3.Init(w3.get(), NULL, &size3, &close3, FramePainter::SIZE_BUTTON_MAXIMIZES);
w3->Show();
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Close the always-on-top widget.
w3.reset();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Close the first window.
w1.reset();
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
}
TEST_F(FramePainterTest, GetHeaderOpacity) {
// Create a widget and a painter for it.
scoped_ptr<Widget> w1(CreateTestWidget());
FramePainter p1;
ImageButton size1(NULL);
ImageButton close1(NULL);
p1.Init(w1.get(), NULL, &size1, &close1, FramePainter::SIZE_BUTTON_MAXIMIZES);
w1->Show();
// Solo active window has solo window opacity.
EXPECT_EQ(FramePainter::kSoloWindowOpacity,
p1.GetHeaderOpacity(FramePainter::ACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE,
NULL));
// Create a second widget and painter.
scoped_ptr<Widget> w2(CreateTestWidget());
FramePainter p2;
ImageButton size2(NULL);
ImageButton close2(NULL);
p2.Init(w2.get(), NULL, &size2, &close2, FramePainter::SIZE_BUTTON_MAXIMIZES);
w2->Show();
// Active window has active window opacity.
EXPECT_EQ(FramePainter::kActiveWindowOpacity,
p2.GetHeaderOpacity(FramePainter::ACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE,
NULL));
// Inactive window has inactive window opacity.
EXPECT_EQ(FramePainter::kInactiveWindowOpacity,
p2.GetHeaderOpacity(FramePainter::INACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_INACTIVE,
NULL));
// Custom overlay image is drawn completely opaque.
gfx::ImageSkia custom_overlay;
EXPECT_EQ(255,
p1.GetHeaderOpacity(FramePainter::ACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE,
&custom_overlay));
}
} // namespace ash
<commit_msg>cros: Fix FramePainterTest.Basics failure on VS2010<commit_after>// Copyright (c) 2012 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 "ash/wm/frame_painter.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/test/ash_test_base.h"
#include "base/memory/scoped_ptr.h"
#include "grit/ui_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/root_window.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/widget/widget.h"
using views::Widget;
using views::ImageButton;
namespace {
aura::Window* GetDefaultContainer() {
return ash::Shell::GetContainer(
ash::Shell::GetPrimaryRootWindow(),
ash::internal::kShellWindowId_DefaultContainer);
}
// Creates a test widget that owns its native widget.
Widget* CreateTestWidget() {
Widget* widget = new Widget;
Widget::InitParams params;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = GetDefaultContainer();
params.child = true;
widget->Init(params);
return widget;
}
Widget* CreateAlwaysOnTopWidget() {
Widget* widget = new Widget;
Widget::InitParams params;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = GetDefaultContainer();
params.child = true;
params.keep_on_top = true;
widget->Init(params);
return widget;
}
} // namespace
namespace ash {
typedef ash::test::AshTestBase FramePainterTest;
TEST_F(FramePainterTest, Basics) {
// Other tests might have created a FramePainter, so we cannot assert that
// FramePainter::instances_ is NULL here.
// Creating a painter bumps the instance count.
scoped_ptr<FramePainter> painter(new FramePainter);
ASSERT_TRUE(FramePainter::instances_);
EXPECT_EQ(1u, FramePainter::instances_->size());
// Destroying that painter leaves a valid pointer but no instances.
painter.reset();
ASSERT_TRUE(FramePainter::instances_);
EXPECT_EQ(0u, FramePainter::instances_->size());
}
TEST_F(FramePainterTest, UseSoloWindowHeader) {
// No windows, no solo window mode.
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Create a widget and a painter for it.
scoped_ptr<Widget> w1(CreateTestWidget());
FramePainter p1;
ImageButton size1(NULL);
ImageButton close1(NULL);
p1.Init(w1.get(), NULL, &size1, &close1, FramePainter::SIZE_BUTTON_MAXIMIZES);
w1->Show();
// We only have one window, so it should use a solo header.
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Create a second widget and painter.
scoped_ptr<Widget> w2(CreateTestWidget());
FramePainter p2;
ImageButton size2(NULL);
ImageButton close2(NULL);
p2.Init(w2.get(), NULL, &size2, &close2, FramePainter::SIZE_BUTTON_MAXIMIZES);
w2->Show();
// Now there are two windows, so we should not use solo headers.
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Hide one window. Solo should be enabled.
w2->Hide();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Show that window. Solo should be disabled.
w2->Show();
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Minimize the window. Solo should be enabled.
w2->Minimize();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Close the minimized window.
w2.reset();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Open an always-on-top widget (which lives in a different container).
scoped_ptr<Widget> w3(CreateAlwaysOnTopWidget());
FramePainter p3;
ImageButton size3(NULL);
ImageButton close3(NULL);
p3.Init(w3.get(), NULL, &size3, &close3, FramePainter::SIZE_BUTTON_MAXIMIZES);
w3->Show();
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
// Close the always-on-top widget.
w3.reset();
EXPECT_TRUE(FramePainter::UseSoloWindowHeader());
// Close the first window.
w1.reset();
EXPECT_FALSE(FramePainter::UseSoloWindowHeader());
}
TEST_F(FramePainterTest, GetHeaderOpacity) {
// Create a widget and a painter for it.
scoped_ptr<Widget> w1(CreateTestWidget());
FramePainter p1;
ImageButton size1(NULL);
ImageButton close1(NULL);
p1.Init(w1.get(), NULL, &size1, &close1, FramePainter::SIZE_BUTTON_MAXIMIZES);
w1->Show();
// Solo active window has solo window opacity.
EXPECT_EQ(FramePainter::kSoloWindowOpacity,
p1.GetHeaderOpacity(FramePainter::ACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE,
NULL));
// Create a second widget and painter.
scoped_ptr<Widget> w2(CreateTestWidget());
FramePainter p2;
ImageButton size2(NULL);
ImageButton close2(NULL);
p2.Init(w2.get(), NULL, &size2, &close2, FramePainter::SIZE_BUTTON_MAXIMIZES);
w2->Show();
// Active window has active window opacity.
EXPECT_EQ(FramePainter::kActiveWindowOpacity,
p2.GetHeaderOpacity(FramePainter::ACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE,
NULL));
// Inactive window has inactive window opacity.
EXPECT_EQ(FramePainter::kInactiveWindowOpacity,
p2.GetHeaderOpacity(FramePainter::INACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_INACTIVE,
NULL));
// Custom overlay image is drawn completely opaque.
gfx::ImageSkia custom_overlay;
EXPECT_EQ(255,
p1.GetHeaderOpacity(FramePainter::ACTIVE,
IDR_AURA_WINDOW_HEADER_BASE_ACTIVE,
&custom_overlay));
}
} // namespace ash
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 bushido
// Copyright (c) 2014 The Vertcoin developers
// Copyright (c) 2014 https://github.com/spesmilo/sx
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "stealth.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/random_device.hpp>
hash_digest bitcoin_hash(const data_chunk& chunk)
{
hash_digest first_hash;
SHA256(chunk.data(), chunk.size(), first_hash.data());
hash_digest second_hash;
SHA256(first_hash.data(), first_hash.size(), second_hash.data());
// The hash is in the reverse of the expected order.
std::reverse(second_hash.begin(), second_hash.end());
return second_hash;
}
uint32_t bitcoin_checksum(const data_chunk& chunk)
{
hash_digest hash = bitcoin_hash(chunk);
return from_little_endian<uint32_t>(hash.rbegin());
}
void append_checksum(data_chunk& data)
{
uint32_t checksum = bitcoin_checksum(data);
extend_data(data, to_little_endian(checksum));
}
std::string stealth_address::encoded() const
{
data_chunk raw_addr;
raw_addr.push_back(stealth_version_byte);
raw_addr.push_back(options);
extend_data(raw_addr, scan_pubkey);
uint8_t number_spend_pubkeys = static_cast<uint8_t>(spend_pubkeys.size());
raw_addr.push_back(number_spend_pubkeys);
for (const ec_point& pubkey: spend_pubkeys)
extend_data(raw_addr, pubkey);
raw_addr.push_back(number_signatures);
//assert_msg(prefix.number_bits == 0, "Not yet implemented!");
raw_addr.push_back(0);
append_checksum(raw_addr);
return EncodeBase58(raw_addr);
}
bool verify_checksum(const data_chunk& data)
{
data_chunk body(data.begin(), data.end() - 4);
auto checksum = from_little_endian<uint32_t>(data.end() - 4);
return bitcoin_checksum(body) == checksum;
}
bool stealth_address::set_encoded(const std::string& encoded_address)
{
data_chunk raw_addr;
DecodeBase58(encoded_address, raw_addr);
if (!verify_checksum(raw_addr))
return false;
assert(raw_addr.size() >= 4);
auto checksum_begin = raw_addr.end() - 4;
// Delete checksum bytes.
raw_addr.erase(checksum_begin, raw_addr.end());
// https://wiki.unsystem.net/index.php/DarkWallet/Stealth#Address_format
// [version] [options] [scan_key] [N] ... [Nsigs] [prefix_length] ...
size_t estimated_data_size = 1 + 1 + 33 + 1 + 1 + 1;
assert(raw_addr.size() >= estimated_data_size);
auto iter = raw_addr.begin();
uint8_t version = *iter;
if (version != stealth_version_byte)
return false;
++iter;
options = *iter;
++iter;
auto scan_key_begin = iter;
iter += 33;
scan_pubkey = data_chunk(scan_key_begin, iter);
uint8_t number_spend_pubkeys = *iter;
++iter;
estimated_data_size += number_spend_pubkeys * 33;
assert(raw_addr.size() >= estimated_data_size);
for (size_t i = 0; i < number_spend_pubkeys; ++i)
{
auto spend_key_begin = iter;
iter += 33;
spend_pubkeys.emplace_back(data_chunk(spend_key_begin, iter));
}
number_signatures = *iter;
++iter;
prefix.number_bits = *iter;
++iter;
size_t number_bitfield_bytes = 0;
if (prefix.number_bits > 0)
number_bitfield_bytes = prefix.number_bits / 8 + 1;
estimated_data_size += number_bitfield_bytes;
assert(raw_addr.size() >= estimated_data_size);
// Unimplemented currently!
assert(number_bitfield_bytes == 0);
return true;
}
ec_secret generate_random_secret()
{
using namespace boost::random;
random_device rd;
mt19937 generator(rd());
uniform_int_distribution<uint8_t> dist(0, std::numeric_limits<uint8_t>::max());
ec_secret secret;
for (uint8_t& byte: secret)
byte = dist(generator);
return secret;
}
bool ec_multiply(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_pubkey_tweak_mul(a.data(), a.size(), b.data());
}
hash_digest sha256_hash(const data_chunk& chunk)
{
hash_digest hash;
SHA256(chunk.data(), chunk.size(), hash.data());
return hash;
}
ec_secret shared_secret(const ec_secret& secret, ec_point point)
{
// diffie hellman stage
bool success = ec_multiply(point, secret);
assert(success);
// start the second stage
return sha256_hash(point);
}
bool ec_tweak_add(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_pubkey_tweak_add(a.data(), a.size(), b.data());
}
ec_point secret_to_public_key(const ec_secret& secret,
bool compressed)
{
init.init();
size_t size = ec_uncompressed_size;
if (compressed)
size = ec_compressed_size;
ec_point out(size);
int out_size;
if (!secp256k1_ec_pubkey_create(out.data(), &out_size, secret.data(),
compressed))
return ec_point();
assert(size == static_cast<size_t>(out_size));
return out;
}
ec_point initiate_stealth(
const ec_secret& ephem_secret, const ec_point& scan_pubkey,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
// Generate shared secret
ec_secret shared = shared_secret(ephem_secret, scan_pubkey);
// Now generate address
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
short_hash bitcoin_short_hash(const data_chunk& chunk)
{
hash_digest sha_hash;
SHA256(chunk.data(), chunk.size(), sha_hash.data());
short_hash ripemd_hash;
RIPEMD160(sha_hash.data(), sha_hash.size(), ripemd_hash.data());
return ripemd_hash;
}
void set_public_key(payment_address& address, const data_chunk& public_key)
{
address.set(fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS,
bitcoin_short_hash(public_key));
}
payment_address::payment_address() : version_(invalid_version), hash_(null_short_hash)
{
}
payment_address::payment_address(uint8_t version, const short_hash& hash)
{
payment_address();
set(version, hash);
}
payment_address::payment_address(const std::string& encoded_address)
{
payment_address();
set_encoded(encoded_address);
}
void payment_address::set(uint8_t version, const short_hash& hash)
{
version_ = version;
hash_ = hash;
}
bool is_base58(const char c)
{
auto last = std::end(base58_chars) - 1;
// This works because the base58 characters happen to be in sorted order
return std::binary_search(base58_chars, last, c);
}
bool is_base58(const std::string& text)
{
return std::all_of(text.begin(), text.end(),
[](const char c){ return is_base58(c); });
}
bool payment_address::set_encoded(const std::string& encoded_address)
{
if (!is_base58(encoded_address))
return false;
data_chunk decoded_address;
DecodeBase58(encoded_address, decoded_address);
// version + 20 bytes short hash + 4 bytes checksum
if (decoded_address.size() != 25)
return false;
if (!verify_checksum(decoded_address))
return false;
version_ = decoded_address[0];
std::copy_n(decoded_address.begin() + 1, hash_.size(), hash_.begin());
return true;
}
std::string payment_address::encoded() const
{
data_chunk unencoded_address;
unencoded_address.reserve(25);
// Type, Hash, Checksum doth make thy address
unencoded_address.push_back(version_);
extend_data(unencoded_address, hash_);
append_checksum(unencoded_address);
assert(unencoded_address.size() == 25);
return EncodeBase58(unencoded_address);
}
ec_point uncover_stealth(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
bool ec_add(ec_secret& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_privkey_tweak_add(a.data(), b.data());
}
ec_secret uncover_stealth_secret(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_secret& spend_secret)
{
ec_secret final = spend_secret;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_add(final, shared);
assert(success);
return final;
}
std::string secret_to_wif(const ec_secret& secret, bool compressed)
{
data_chunk data;
data.reserve(1 + hash_size + 1 + 4);
data.push_back(fTestNet ? CBitcoinSecret::PRIVKEY_ADDRESS_TEST : CBitcoinSecret::PRIVKEY_ADDRESS);
extend_data(data, secret);
if (compressed)
data.push_back(0x01);
append_checksum(data);
return EncodeBase58(data);
}
data_chunk decode_hex(std::string hex)
{
// Trim the fat.
boost::algorithm::trim(hex);
data_chunk result(hex.size() / 2);
for (size_t i = 0; i + 1 < hex.size(); i += 2)
{
assert(hex.size() - i >= 2);
auto byte_begin = hex.begin() + i;
auto byte_end = hex.begin() + i + 2;
// Perform conversion.
int val = -1;
std::stringstream converter;
converter << std::hex << std::string(byte_begin, byte_end);
converter >> val;
if (val == -1)
return data_chunk();
assert(val <= 0xff);
// Set byte.
result[i / 2] = val;
}
return result;
}
<commit_msg>Update libsecp256k1<commit_after>// Copyright (c) 2014 bushido
// Copyright (c) 2014 The Vertcoin developers
// Copyright (c) 2014 https://github.com/spesmilo/sx
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "stealth.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/random_device.hpp>
hash_digest bitcoin_hash(const data_chunk& chunk)
{
hash_digest first_hash;
SHA256(chunk.data(), chunk.size(), first_hash.data());
hash_digest second_hash;
SHA256(first_hash.data(), first_hash.size(), second_hash.data());
// The hash is in the reverse of the expected order.
std::reverse(second_hash.begin(), second_hash.end());
return second_hash;
}
uint32_t bitcoin_checksum(const data_chunk& chunk)
{
hash_digest hash = bitcoin_hash(chunk);
return from_little_endian<uint32_t>(hash.rbegin());
}
void append_checksum(data_chunk& data)
{
uint32_t checksum = bitcoin_checksum(data);
extend_data(data, to_little_endian(checksum));
}
std::string stealth_address::encoded() const
{
data_chunk raw_addr;
raw_addr.push_back(stealth_version_byte);
raw_addr.push_back(options);
extend_data(raw_addr, scan_pubkey);
uint8_t number_spend_pubkeys = static_cast<uint8_t>(spend_pubkeys.size());
raw_addr.push_back(number_spend_pubkeys);
for (const ec_point& pubkey: spend_pubkeys)
extend_data(raw_addr, pubkey);
raw_addr.push_back(number_signatures);
//assert_msg(prefix.number_bits == 0, "Not yet implemented!");
raw_addr.push_back(0);
append_checksum(raw_addr);
return EncodeBase58(raw_addr);
}
bool verify_checksum(const data_chunk& data)
{
data_chunk body(data.begin(), data.end() - 4);
auto checksum = from_little_endian<uint32_t>(data.end() - 4);
return bitcoin_checksum(body) == checksum;
}
bool stealth_address::set_encoded(const std::string& encoded_address)
{
data_chunk raw_addr;
DecodeBase58(encoded_address, raw_addr);
if (!verify_checksum(raw_addr))
return false;
assert(raw_addr.size() >= 4);
auto checksum_begin = raw_addr.end() - 4;
// Delete checksum bytes.
raw_addr.erase(checksum_begin, raw_addr.end());
// https://wiki.unsystem.net/index.php/DarkWallet/Stealth#Address_format
// [version] [options] [scan_key] [N] ... [Nsigs] [prefix_length] ...
size_t estimated_data_size = 1 + 1 + 33 + 1 + 1 + 1;
assert(raw_addr.size() >= estimated_data_size);
auto iter = raw_addr.begin();
uint8_t version = *iter;
if (version != stealth_version_byte)
return false;
++iter;
options = *iter;
++iter;
auto scan_key_begin = iter;
iter += 33;
scan_pubkey = data_chunk(scan_key_begin, iter);
uint8_t number_spend_pubkeys = *iter;
++iter;
estimated_data_size += number_spend_pubkeys * 33;
assert(raw_addr.size() >= estimated_data_size);
for (size_t i = 0; i < number_spend_pubkeys; ++i)
{
auto spend_key_begin = iter;
iter += 33;
spend_pubkeys.emplace_back(data_chunk(spend_key_begin, iter));
}
number_signatures = *iter;
++iter;
prefix.number_bits = *iter;
++iter;
size_t number_bitfield_bytes = 0;
if (prefix.number_bits > 0)
number_bitfield_bytes = prefix.number_bits / 8 + 1;
estimated_data_size += number_bitfield_bytes;
assert(raw_addr.size() >= estimated_data_size);
// Unimplemented currently!
assert(number_bitfield_bytes == 0);
return true;
}
ec_secret generate_random_secret()
{
using namespace boost::random;
random_device rd;
mt19937 generator(rd());
uniform_int_distribution<uint8_t> dist(0, std::numeric_limits<uint8_t>::max());
ec_secret secret;
for (uint8_t& byte: secret)
byte = dist(generator);
return secret;
}
bool ec_multiply(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_pubkey_tweak_mul(init.getContext(), a.data(), a.size(), b.data());
}
hash_digest sha256_hash(const data_chunk& chunk)
{
hash_digest hash;
SHA256(chunk.data(), chunk.size(), hash.data());
return hash;
}
ec_secret shared_secret(const ec_secret& secret, ec_point point)
{
// diffie hellman stage
bool success = ec_multiply(point, secret);
assert(success);
// start the second stage
return sha256_hash(point);
}
bool ec_tweak_add(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_pubkey_tweak_add(init.getContext(), a.data(), a.size(), b.data());
}
ec_point secret_to_public_key(const ec_secret& secret,
bool compressed)
{
init.init();
size_t size = ec_uncompressed_size;
if (compressed)
size = ec_compressed_size;
ec_point out(size);
int out_size;
if (!secp256k1_ec_pubkey_create(init.getContext(), out.data(), &out_size, secret.data(),
compressed))
return ec_point();
assert(size == static_cast<size_t>(out_size));
return out;
}
ec_point initiate_stealth(
const ec_secret& ephem_secret, const ec_point& scan_pubkey,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
// Generate shared secret
ec_secret shared = shared_secret(ephem_secret, scan_pubkey);
// Now generate address
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
short_hash bitcoin_short_hash(const data_chunk& chunk)
{
hash_digest sha_hash;
SHA256(chunk.data(), chunk.size(), sha_hash.data());
short_hash ripemd_hash;
RIPEMD160(sha_hash.data(), sha_hash.size(), ripemd_hash.data());
return ripemd_hash;
}
void set_public_key(payment_address& address, const data_chunk& public_key)
{
address.set(fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS,
bitcoin_short_hash(public_key));
}
payment_address::payment_address() : version_(invalid_version), hash_(null_short_hash)
{
}
payment_address::payment_address(uint8_t version, const short_hash& hash)
{
payment_address();
set(version, hash);
}
payment_address::payment_address(const std::string& encoded_address)
{
payment_address();
set_encoded(encoded_address);
}
void payment_address::set(uint8_t version, const short_hash& hash)
{
version_ = version;
hash_ = hash;
}
bool is_base58(const char c)
{
auto last = std::end(base58_chars) - 1;
// This works because the base58 characters happen to be in sorted order
return std::binary_search(base58_chars, last, c);
}
bool is_base58(const std::string& text)
{
return std::all_of(text.begin(), text.end(),
[](const char c){ return is_base58(c); });
}
bool payment_address::set_encoded(const std::string& encoded_address)
{
if (!is_base58(encoded_address))
return false;
data_chunk decoded_address;
DecodeBase58(encoded_address, decoded_address);
// version + 20 bytes short hash + 4 bytes checksum
if (decoded_address.size() != 25)
return false;
if (!verify_checksum(decoded_address))
return false;
version_ = decoded_address[0];
std::copy_n(decoded_address.begin() + 1, hash_.size(), hash_.begin());
return true;
}
std::string payment_address::encoded() const
{
data_chunk unencoded_address;
unencoded_address.reserve(25);
// Type, Hash, Checksum doth make thy address
unencoded_address.push_back(version_);
extend_data(unencoded_address, hash_);
append_checksum(unencoded_address);
assert(unencoded_address.size() == 25);
return EncodeBase58(unencoded_address);
}
ec_point uncover_stealth(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
bool ec_add(ec_secret& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_privkey_tweak_add(init.getContext(), a.data(), b.data());
}
ec_secret uncover_stealth_secret(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_secret& spend_secret)
{
ec_secret final = spend_secret;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_add(final, shared);
assert(success);
return final;
}
std::string secret_to_wif(const ec_secret& secret, bool compressed)
{
data_chunk data;
data.reserve(1 + hash_size + 1 + 4);
data.push_back(fTestNet ? CBitcoinSecret::PRIVKEY_ADDRESS_TEST : CBitcoinSecret::PRIVKEY_ADDRESS);
extend_data(data, secret);
if (compressed)
data.push_back(0x01);
append_checksum(data);
return EncodeBase58(data);
}
data_chunk decode_hex(std::string hex)
{
// Trim the fat.
boost::algorithm::trim(hex);
data_chunk result(hex.size() / 2);
for (size_t i = 0; i + 1 < hex.size(); i += 2)
{
assert(hex.size() - i >= 2);
auto byte_begin = hex.begin() + i;
auto byte_end = hex.begin() + i + 2;
// Perform conversion.
int val = -1;
std::stringstream converter;
converter << std::hex << std::string(byte_begin, byte_end);
converter >> val;
if (val == -1)
return data_chunk();
assert(val <= 0xff);
// Set byte.
result[i / 2] = val;
}
return result;
}
<|endoftext|>
|
<commit_before>#include <math.h> // sqrt
#include <stdio.h> // snprintf
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <api.h>
static void do_keyboard (GLFWwindow* window, int key, int scancode,
int action, int mods)
{
if (GLFW_KEY_ESCAPE == key) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
static void do_mouse_button (GLFWwindow* window, int button, int action,
int mods)
{
if (GLFW_MOUSE_BUTTON_2 == button) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void open_window(char const * title, bool const prefers_fullscreen)
{
if (!glfwInit()) {
printf("glfw: could not initialize\n");
return;
}
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
GLFWvidmode const * mode = glfwGetVideoMode(monitor);
int const screen_wh[] = {
mode->width,
mode->height,
};
int window_wh[] = {
screen_wh[0],
screen_wh[1],
};
if (!prefers_fullscreen) {
window_wh[0] = static_cast<int>(window_wh[0] * 1.0 / sqrt(2.0));
window_wh[1] = static_cast<int>(window_wh[1] * 1.0 / sqrt(2.0));
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 4);
GLFWwindow* window = glfwCreateWindow
(window_wh[0], window_wh[1], title,
prefers_fullscreen ? monitor : NULL,
NULL);
if (!window) {
printf("could not create window\n");
return;
}
glfwSetKeyCallback(window, do_keyboard);
glfwSetMouseButtonCallback(window, do_mouse_button);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "glew error: %s\n", glewGetErrorString(err));
return;
}
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
while(!glfwWindowShouldClose(window)) {
glfwMakeContextCurrent(window);
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
render_next_gl(now_micros());
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
}
<commit_msg>catch exception in video render method<commit_after>#include <math.h> // sqrt
#include <stdio.h> // snprintf
#include <exception>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <api.h>
static void do_keyboard (GLFWwindow* window, int key, int scancode,
int action, int mods)
{
if (GLFW_KEY_ESCAPE == key) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
static void do_mouse_button (GLFWwindow* window, int button, int action,
int mods)
{
if (GLFW_MOUSE_BUTTON_2 == button) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void open_window(char const * title, bool const prefers_fullscreen)
{
if (!glfwInit()) {
printf("glfw: could not initialize\n");
return;
}
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
GLFWvidmode const * mode = glfwGetVideoMode(monitor);
int const screen_wh[] = {
mode->width,
mode->height,
};
int window_wh[] = {
screen_wh[0],
screen_wh[1],
};
if (!prefers_fullscreen) {
window_wh[0] = static_cast<int>(window_wh[0] * 1.0 / sqrt(2.0));
window_wh[1] = static_cast<int>(window_wh[1] * 1.0 / sqrt(2.0));
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 4);
GLFWwindow* window = glfwCreateWindow
(window_wh[0], window_wh[1], title,
prefers_fullscreen ? monitor : NULL,
NULL);
if (!window) {
printf("could not create window\n");
return;
}
glfwSetKeyCallback(window, do_keyboard);
glfwSetMouseButtonCallback(window, do_mouse_button);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "glew error: %s\n", glewGetErrorString(err));
return;
}
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
while(!glfwWindowShouldClose(window)) {
glfwMakeContextCurrent(window);
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
try {
render_next_gl(now_micros());
} catch (std::exception& e) {
fprintf(stderr, "caught exception: '%s', exiting.\n", e.what());
break;
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
}
<|endoftext|>
|
<commit_before>#include "ORDocumentIterator.h"
#include "NOTDocumentIterator.h"
using namespace std;
using namespace sf1r;
ORDocumentIterator::ORDocumentIterator()
:pDocIteratorQueue_(NULL)
,hasNot_(false)
,currDocOfNOTIter_(MAX_DOC_ID)
,initNOTIterator_(false)
,pNOTDocIterator_(NULL)
{
}
ORDocumentIterator::~ORDocumentIterator()
{
for (vector<DocumentIterator*>::iterator iter = docIteratorList_.begin(); iter != docIteratorList_.end(); ++iter)
{
if(*iter)
delete *iter;
}
if (pNOTDocIterator_)
delete pNOTDocIterator_;
if (pDocIteratorQueue_)
delete pDocIteratorQueue_;
}
void ORDocumentIterator::initDocIteratorQueue()
{
if (docIteratorList_.size() < 1)
return;
pDocIteratorQueue_ = new DocumentIteratorQueue(docIteratorList_.size());
DocumentIterator* pDocIterator;
vector<DocumentIterator*>::iterator iter = docIteratorList_.begin();
while (iter != docIteratorList_.end())
{
pDocIterator = (*iter);
if (pDocIterator)
{
pDocIterator->setCurrent(false);
if(pDocIterator->next())
pDocIteratorQueue_->insert(pDocIterator);
else
{
iter = docIteratorList_.erase(iter);
delete pDocIterator;
continue;
}
}
iter ++;
}
}
void ORDocumentIterator::add(DocumentIterator* pDocIterator)
{
if (pDocIterator->isNot())
{
hasNot_ = true;
if (NULL == pNOTDocIterator_)
pNOTDocIterator_ = new NOTDocumentIterator();
pNOTDocIterator_->add(pDocIterator);
}
else
docIteratorList_.push_back(pDocIterator);
}
bool ORDocumentIterator::next()
{
if (!hasNot_)
return do_next();
else
{
if (! initNOTIterator_)
{
initNOTIterator_ = true;
if (pNOTDocIterator_->next())
currDocOfNOTIter_ = pNOTDocIterator_->doc();
else
currDocOfNOTIter_ = MAX_DOC_ID;
}
bool ret = do_next();
if (currDoc_ == currDocOfNOTIter_)
return move_together_with_not();
if (currDoc_ < currDocOfNOTIter_)
return ret;
else
{
currDocOfNOTIter_ = pNOTDocIterator_->skipTo(currDoc_);
if (currDoc_ == currDocOfNOTIter_)
return move_together_with_not();
else
return ret;
}
}
}
bool ORDocumentIterator::move_together_with_not()
{
bool ret;
do
{
ret = do_next();
if (pNOTDocIterator_->next())
currDocOfNOTIter_ = pNOTDocIterator_->doc();
else
currDocOfNOTIter_ = MAX_DOC_ID;
}
while (ret&&(currDoc_ == currDocOfNOTIter_));
return ret;
}
bool ORDocumentIterator::do_next()
{
if (pDocIteratorQueue_ == NULL)
{
initDocIteratorQueue();
if (pDocIteratorQueue_ == NULL)
return false;
DocumentIterator* top = pDocIteratorQueue_->top();
if (top == NULL)
return false;
currDoc_ = top->doc();
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
DocumentIterator* pEntry = pDocIteratorQueue_->getAt(i);
if (currDoc_ == pEntry->doc())
pEntry->setCurrent(true);
else
pEntry->setCurrent(false);
}
return true;
}
DocumentIterator* top = pDocIteratorQueue_->top();
while (top != NULL && top->isCurrent())
{
top->setCurrent(false);
if (top->next())
pDocIteratorQueue_->adjustTop();
else pDocIteratorQueue_->pop();
top = pDocIteratorQueue_->top();
}
if (top == NULL)
return false;
currDoc_ = top->doc();
//for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
///we can not use priority queue here because if some dociterator
///is removed from that queue, we should set flag for it.
for (std::vector<DocumentIterator*>::iterator iter = docIteratorList_.begin();
iter != docIteratorList_.end(); ++iter)
{
//DocumentIterator* pEntry = pDocIteratorQueue_->getAt(i);
DocumentIterator* pEntry = (*iter);
if(pEntry)
if (currDoc_ == pEntry->doc())
pEntry->setCurrent(true);
else
pEntry->setCurrent(false);
}
return true;
}
#if SKIP_ENABLED
docid_t ORDocumentIterator::skipTo(docid_t target)
{
if (!hasNot_)
return do_skipTo(target);
else
{
docid_t nFoundId, currentDoc = target;
do
{
nFoundId = do_skipTo(currentDoc);
currDocOfNOTIter_ = pNOTDocIterator_->skipTo(currentDoc);
}
while ((nFoundId != MAX_DOC_ID)&&(nFoundId == currDocOfNOTIter_));
return nFoundId;
}
}
docid_t ORDocumentIterator::do_skipTo(docid_t target)
{
if(pDocIteratorQueue_ == NULL)
{
initDocIteratorQueue();
if (pDocIteratorQueue_ == NULL)
return MAX_DOC_ID;
}
if (pDocIteratorQueue_->size() < 1)
{
return MAX_DOC_ID;
}
docid_t nFoundId = MAX_DOC_ID;
do
{
DocumentIterator* top = pDocIteratorQueue_->top();
currDoc_ = top->doc();
for (std::vector<DocumentIterator*>::iterator iter = docIteratorList_.begin(); iter != docIteratorList_.end(); ++iter)
if ((*iter)->doc() == currDoc_)
(*iter)->setCurrent(true);
if (currDoc_ >= target)
{
if(pDocIteratorQueue_->size() < 1)
{
return MAX_DOC_ID;
}
else
{
return currDoc_;
}
}
else
{
nFoundId = top->skipTo(target);
if((MAX_DOC_ID == nFoundId)||(nFoundId < target))
{
pDocIteratorQueue_->pop();
if (pDocIteratorQueue_->size() < 1)
{
return MAX_DOC_ID;
}
}
else
{
pDocIteratorQueue_->adjustTop();
}
}
} while (true);
}
#endif
void ORDocumentIterator::doc_item(RankDocumentProperty& rankDocumentProperty)
{
DocumentIterator* pEntry;
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
pEntry = pDocIteratorQueue_->getAt(i);
if (pEntry->isCurrent())
pEntry->doc_item(rankDocumentProperty);
}
}
void ORDocumentIterator::df_ctf(DocumentFrequencyInProperties& dfmap, CollectionTermFrequencyInProperties& ctfmap)
{
DocumentIterator* pEntry;
for (std::vector<DocumentIterator*>::iterator iter = docIteratorList_.begin(); iter != docIteratorList_.end(); ++iter)
{
pEntry = (*iter);
if(pEntry)
pEntry->df_ctf(dfmap, ctfmap);
}
}
count_t ORDocumentIterator::tf()
{
DocumentIterator* pEntry;
count_t maxtf = 0;
count_t tf=0;
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
pEntry = pDocIteratorQueue_->getAt(i);
if (pEntry->isCurrent())
{
tf = pEntry->tf();
if (tf > maxtf)
maxtf = tf;
}
}
return maxtf;
}
void ORDocumentIterator::queryBoosting(double& score, double& weight)
{
DocumentIterator* pEntry;
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
pEntry = pDocIteratorQueue_->getAt(i);
if (pEntry->isCurrent())
{
pEntry->queryBoosting(score, weight);
}
}
}
void ORDocumentIterator::print(int level)
{
cout << std::string(level*4, ' ') << "|--[ "<< "ORIter current: " << current_<<" "<< currDoc_ << " ]"<< endl;
DocumentIterator* pEntry;
for (size_t i = 0; i < docIteratorList_.size(); ++i)
{
pEntry = docIteratorList_[i];
if (pEntry)
pEntry->print(level+1);
}
}
<commit_msg>revise commit b4f65c97487c646d663ec85c956313138809d4ed, TermDocIterator should not be erased since it should be kept consist with RankDocumentProperties during scoring<commit_after>#include "ORDocumentIterator.h"
#include "NOTDocumentIterator.h"
using namespace std;
using namespace sf1r;
ORDocumentIterator::ORDocumentIterator()
:pDocIteratorQueue_(NULL)
,hasNot_(false)
,currDocOfNOTIter_(MAX_DOC_ID)
,initNOTIterator_(false)
,pNOTDocIterator_(NULL)
{
}
ORDocumentIterator::~ORDocumentIterator()
{
for (vector<DocumentIterator*>::iterator iter = docIteratorList_.begin(); iter != docIteratorList_.end(); ++iter)
{
if(*iter)
delete *iter;
}
if (pNOTDocIterator_)
delete pNOTDocIterator_;
if (pDocIteratorQueue_)
delete pDocIteratorQueue_;
}
void ORDocumentIterator::initDocIteratorQueue()
{
if (docIteratorList_.size() < 1)
return;
pDocIteratorQueue_ = new DocumentIteratorQueue(docIteratorList_.size());
DocumentIterator* pDocIterator;
vector<DocumentIterator*>::iterator iter = docIteratorList_.begin();
while (iter != docIteratorList_.end())
{
pDocIterator = (*iter);
if (pDocIterator)
{
pDocIterator->setCurrent(false);
if(pDocIterator->next())
pDocIteratorQueue_->insert(pDocIterator);
else
{
*iter = NULL;
delete pDocIterator;
}
}
iter ++;
}
}
void ORDocumentIterator::add(DocumentIterator* pDocIterator)
{
if (pDocIterator->isNot())
{
hasNot_ = true;
if (NULL == pNOTDocIterator_)
pNOTDocIterator_ = new NOTDocumentIterator();
pNOTDocIterator_->add(pDocIterator);
}
else
docIteratorList_.push_back(pDocIterator);
}
bool ORDocumentIterator::next()
{
if (!hasNot_)
return do_next();
else
{
if (! initNOTIterator_)
{
initNOTIterator_ = true;
if (pNOTDocIterator_->next())
currDocOfNOTIter_ = pNOTDocIterator_->doc();
else
currDocOfNOTIter_ = MAX_DOC_ID;
}
bool ret = do_next();
if (currDoc_ == currDocOfNOTIter_)
return move_together_with_not();
if (currDoc_ < currDocOfNOTIter_)
return ret;
else
{
currDocOfNOTIter_ = pNOTDocIterator_->skipTo(currDoc_);
if (currDoc_ == currDocOfNOTIter_)
return move_together_with_not();
else
return ret;
}
}
}
bool ORDocumentIterator::move_together_with_not()
{
bool ret;
do
{
ret = do_next();
if (pNOTDocIterator_->next())
currDocOfNOTIter_ = pNOTDocIterator_->doc();
else
currDocOfNOTIter_ = MAX_DOC_ID;
}
while (ret&&(currDoc_ == currDocOfNOTIter_));
return ret;
}
bool ORDocumentIterator::do_next()
{
if (pDocIteratorQueue_ == NULL)
{
initDocIteratorQueue();
if (pDocIteratorQueue_ == NULL)
return false;
DocumentIterator* top = pDocIteratorQueue_->top();
if (top == NULL)
return false;
currDoc_ = top->doc();
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
DocumentIterator* pEntry = pDocIteratorQueue_->getAt(i);
if (currDoc_ == pEntry->doc())
pEntry->setCurrent(true);
else
pEntry->setCurrent(false);
}
return true;
}
DocumentIterator* top = pDocIteratorQueue_->top();
while (top != NULL && top->isCurrent())
{
top->setCurrent(false);
if (top->next())
pDocIteratorQueue_->adjustTop();
else pDocIteratorQueue_->pop();
top = pDocIteratorQueue_->top();
}
if (top == NULL)
return false;
currDoc_ = top->doc();
//for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
///we can not use priority queue here because if some dociterator
///is removed from that queue, we should set flag for it.
for (std::vector<DocumentIterator*>::iterator iter = docIteratorList_.begin();
iter != docIteratorList_.end(); ++iter)
{
//DocumentIterator* pEntry = pDocIteratorQueue_->getAt(i);
DocumentIterator* pEntry = (*iter);
if(pEntry)
if (currDoc_ == pEntry->doc())
pEntry->setCurrent(true);
else
pEntry->setCurrent(false);
}
return true;
}
#if SKIP_ENABLED
docid_t ORDocumentIterator::skipTo(docid_t target)
{
if (!hasNot_)
return do_skipTo(target);
else
{
docid_t nFoundId, currentDoc = target;
do
{
nFoundId = do_skipTo(currentDoc);
currDocOfNOTIter_ = pNOTDocIterator_->skipTo(currentDoc);
}
while ((nFoundId != MAX_DOC_ID)&&(nFoundId == currDocOfNOTIter_));
return nFoundId;
}
}
docid_t ORDocumentIterator::do_skipTo(docid_t target)
{
if(pDocIteratorQueue_ == NULL)
{
initDocIteratorQueue();
if (pDocIteratorQueue_ == NULL)
return MAX_DOC_ID;
}
if (pDocIteratorQueue_->size() < 1)
{
return MAX_DOC_ID;
}
docid_t nFoundId = MAX_DOC_ID;
do
{
DocumentIterator* top = pDocIteratorQueue_->top();
currDoc_ = top->doc();
for (std::vector<DocumentIterator*>::iterator iter = docIteratorList_.begin(); iter != docIteratorList_.end(); ++iter)
if ((*iter)->doc() == currDoc_)
(*iter)->setCurrent(true);
if (currDoc_ >= target)
{
if(pDocIteratorQueue_->size() < 1)
{
return MAX_DOC_ID;
}
else
{
return currDoc_;
}
}
else
{
nFoundId = top->skipTo(target);
if((MAX_DOC_ID == nFoundId)||(nFoundId < target))
{
pDocIteratorQueue_->pop();
if (pDocIteratorQueue_->size() < 1)
{
return MAX_DOC_ID;
}
}
else
{
pDocIteratorQueue_->adjustTop();
}
}
} while (true);
}
#endif
void ORDocumentIterator::doc_item(RankDocumentProperty& rankDocumentProperty)
{
DocumentIterator* pEntry;
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
pEntry = pDocIteratorQueue_->getAt(i);
if (pEntry->isCurrent())
pEntry->doc_item(rankDocumentProperty);
}
}
void ORDocumentIterator::df_ctf(DocumentFrequencyInProperties& dfmap, CollectionTermFrequencyInProperties& ctfmap)
{
DocumentIterator* pEntry;
for (std::vector<DocumentIterator*>::iterator iter = docIteratorList_.begin(); iter != docIteratorList_.end(); ++iter)
{
pEntry = (*iter);
if(pEntry)
pEntry->df_ctf(dfmap, ctfmap);
}
}
count_t ORDocumentIterator::tf()
{
DocumentIterator* pEntry;
count_t maxtf = 0;
count_t tf=0;
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
pEntry = pDocIteratorQueue_->getAt(i);
if (pEntry->isCurrent())
{
tf = pEntry->tf();
if (tf > maxtf)
maxtf = tf;
}
}
return maxtf;
}
void ORDocumentIterator::queryBoosting(double& score, double& weight)
{
DocumentIterator* pEntry;
for (size_t i = 0; i < pDocIteratorQueue_->size(); ++i)
{
pEntry = pDocIteratorQueue_->getAt(i);
if (pEntry->isCurrent())
{
pEntry->queryBoosting(score, weight);
}
}
}
void ORDocumentIterator::print(int level)
{
cout << std::string(level*4, ' ') << "|--[ "<< "ORIter current: " << current_<<" "<< currDoc_ << " ]"<< endl;
DocumentIterator* pEntry;
for (size_t i = 0; i < docIteratorList_.size(); ++i)
{
pEntry = docIteratorList_[i];
if (pEntry)
pEntry->print(level+1);
}
}
<|endoftext|>
|
<commit_before>/* **********************************************************
* Copyright (c) 2015 Google, 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 Google, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. 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 "cache.h"
#include "cache_line.h"
#include "cache_stats.h"
#include "utils.h"
#include <assert.h>
cache_t::cache_t()
{
lines = 0;
}
bool
cache_t::init(int associativity_, int line_size_, int num_lines_,
cache_t *parent_, cache_stats_t *stats_)
{
if (!IS_POWER_OF_2(associativity_) ||
!IS_POWER_OF_2(line_size_) ||
!IS_POWER_OF_2(num_lines_))
return false;
associativity = associativity_;
line_size = line_size_;
num_lines = num_lines_;
parent = parent_;
stats = stats_;
lines = new cache_line_t[num_lines];
lines_per_set = num_lines / associativity;
last_tag = 0; // sentinel
return true;
}
cache_t::~cache_t()
{
delete [] lines;
}
void
cache_t::request(const memref_t &memref_in)
{
// Unfortunately we need to make a copy for our loop so we can pass
// the right data struct to the parent and stats collectors.
memref_t memref = memref_in;
// We support larger sizes to improve the IPC perf.
// This means that one memref could touch multiple lines.
// We treat each line separately for statistics purposes.
addr_t final_addr = memref.addr + memref.size - 1/*avoid overflow*/;
addr_t final_tag = final_addr / line_size;
addr_t tag = compute_tag(memref.addr);
// Optimization: remember last tag if single-line
if (final_tag == tag) {
if (tag == last_tag && tag != 0/*safety check for sentinel*/) {
int line_idx = compute_line_idx(tag);
assert(lines[line_idx * last_way].tag == tag &&
lines[line_idx * last_way].valid);
access_update(line_idx, last_way);
if (stats != NULL)
stats->access(memref, true);
return;
} else
last_tag = tag;
} else
last_tag = 0; // sentinel
for (; tag <= final_tag; ++tag) {
bool hit = false;
int final_way = 0;
int line_idx = compute_line_idx(tag);
if (tag + 1 <= final_tag)
memref.size = ((tag + 1) * line_size) - memref.addr;
for (int way = 0; way < associativity; ++way) {
if (lines[line_idx * way].tag == tag &&
lines[line_idx * way].valid) {
hit = true;
final_way = way;
break;
}
}
if (!hit) {
// If no parent we assume we get the data from main memory
if (parent != NULL)
parent->request(memref);
// FIXME i#1703: coherence policy
final_way = replace_which_way(line_idx);
lines[line_idx * final_way].tag = tag;
lines[line_idx * final_way].valid = true;
last_tag = 0; // sentinel
}
access_update(line_idx, final_way);
if (stats != NULL)
stats->access(memref, hit);
if (tag + 1 <= final_tag) {
addr_t next_addr = (tag + 1) * line_size;
memref.addr = next_addr;
memref.size = final_addr - next_addr + 1/*undo the -1*/;
} else if (last_tag == tag)
last_way = final_way;
}
}
void
cache_t::access_update(int line_idx, int way)
{
// We just inc the counter for LRU. We live with any blip on overflow.
lines[line_idx * way].counter++;
}
int
cache_t::replace_which_way(int line_idx)
{
// We only implement LRU. A subclass can override this and replace_update()
// to implement some other scheme.
int_least64_t min_counter = 0;
int min_way = 0;
for (int way = 0; way < associativity; ++way) {
if (way == 0 || lines[line_idx * way].counter < min_counter) {
min_counter = lines[line_idx * way].counter;
min_way = way;
}
// FIXME i#1703: shouldn't we clear all counters here for LRU?
// Else we have LFU. LRU results in more misses on fib: look deeper.
}
return min_way;
}
<commit_msg>i#1703 cache simulator: use compute_tag for final_tag<commit_after>/* **********************************************************
* Copyright (c) 2015 Google, 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 Google, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. 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 "cache.h"
#include "cache_line.h"
#include "cache_stats.h"
#include "utils.h"
#include <assert.h>
cache_t::cache_t()
{
lines = 0;
}
bool
cache_t::init(int associativity_, int line_size_, int num_lines_,
cache_t *parent_, cache_stats_t *stats_)
{
if (!IS_POWER_OF_2(associativity_) ||
!IS_POWER_OF_2(line_size_) ||
!IS_POWER_OF_2(num_lines_))
return false;
associativity = associativity_;
line_size = line_size_;
num_lines = num_lines_;
parent = parent_;
stats = stats_;
lines = new cache_line_t[num_lines];
lines_per_set = num_lines / associativity;
last_tag = 0; // sentinel
return true;
}
cache_t::~cache_t()
{
delete [] lines;
}
void
cache_t::request(const memref_t &memref_in)
{
// Unfortunately we need to make a copy for our loop so we can pass
// the right data struct to the parent and stats collectors.
memref_t memref = memref_in;
// We support larger sizes to improve the IPC perf.
// This means that one memref could touch multiple lines.
// We treat each line separately for statistics purposes.
addr_t final_addr = memref.addr + memref.size - 1/*avoid overflow*/;
addr_t final_tag = compute_tag(final_addr);
addr_t tag = compute_tag(memref.addr);
// Optimization: remember last tag if single-line
if (final_tag == tag) {
if (tag == last_tag && tag != 0/*safety check for sentinel*/) {
int line_idx = compute_line_idx(tag);
assert(lines[line_idx * last_way].tag == tag &&
lines[line_idx * last_way].valid);
access_update(line_idx, last_way);
if (stats != NULL)
stats->access(memref, true);
return;
} else
last_tag = tag;
} else
last_tag = 0; // sentinel
for (; tag <= final_tag; ++tag) {
bool hit = false;
int final_way = 0;
int line_idx = compute_line_idx(tag);
if (tag + 1 <= final_tag)
memref.size = ((tag + 1) * line_size) - memref.addr;
for (int way = 0; way < associativity; ++way) {
if (lines[line_idx * way].tag == tag &&
lines[line_idx * way].valid) {
hit = true;
final_way = way;
break;
}
}
if (!hit) {
// If no parent we assume we get the data from main memory
if (parent != NULL)
parent->request(memref);
// FIXME i#1703: coherence policy
final_way = replace_which_way(line_idx);
lines[line_idx * final_way].tag = tag;
lines[line_idx * final_way].valid = true;
last_tag = 0; // sentinel
}
access_update(line_idx, final_way);
if (stats != NULL)
stats->access(memref, hit);
if (tag + 1 <= final_tag) {
addr_t next_addr = (tag + 1) * line_size;
memref.addr = next_addr;
memref.size = final_addr - next_addr + 1/*undo the -1*/;
} else if (last_tag == tag)
last_way = final_way;
}
}
void
cache_t::access_update(int line_idx, int way)
{
// We just inc the counter for LRU. We live with any blip on overflow.
lines[line_idx * way].counter++;
}
int
cache_t::replace_which_way(int line_idx)
{
// We only implement LRU. A subclass can override this and replace_update()
// to implement some other scheme.
int_least64_t min_counter = 0;
int min_way = 0;
for (int way = 0; way < associativity; ++way) {
if (way == 0 || lines[line_idx * way].counter < min_counter) {
min_counter = lines[line_idx * way].counter;
min_way = way;
}
// FIXME i#1703: shouldn't we clear all counters here for LRU?
// Else we have LFU. LRU results in more misses on fib: look deeper.
}
return min_way;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkLightActor.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 "vtkLightActor.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkCameraActor.h"
#include "vtkConeSource.h"
#include "vtkCamera.h"
#include "vtkLight.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkProperty.h"
#include "vtkBoundingBox.h"
vtkStandardNewMacro(vtkLightActor);
vtkCxxSetObjectMacro(vtkLightActor, Light, vtkLight);
// ----------------------------------------------------------------------------
vtkLightActor::vtkLightActor()
{
this->Light=0;
this->ClippingRange[0]=0.5;
this->ClippingRange[1]=10.0;
this->ConeSource=0;
this->ConeMapper=0;
this->ConeActor=0;
this->CameraLight=0;
this->FrustumActor=0;
this->BoundingBox=new vtkBoundingBox;
}
// ----------------------------------------------------------------------------
vtkLightActor::~vtkLightActor()
{
this->SetLight(0);
if(this->ConeActor!=0)
{
this->ConeActor->Delete();
}
if(this->ConeMapper!=0)
{
this->ConeMapper->Delete();
}
if(this->FrustumActor!=0)
{
this->FrustumActor->Delete();
}
if(this->ConeSource!=0)
{
this->ConeSource->Delete();
}
if(this->CameraLight!=0)
{
this->CameraLight->Delete();
}
delete this->BoundingBox;
}
// ----------------------------------------------------------------------------
// Description:
// Set/Get the location of the near and far clipping planes along the
// direction of projection. Both of these values must be positive.
// Initial values are (0.5,11.0)
void vtkLightActor::SetClippingRange(double dNear,
double dFar)
{
this->ClippingRange[0]=dNear;
this->ClippingRange[1]=dFar;
}
// ----------------------------------------------------------------------------
void vtkLightActor::SetClippingRange(const double a[2])
{
this->SetClippingRange(a[0], a[1]);
}
// ----------------------------------------------------------------------------
// Description:
// Support the standard render methods.
int vtkLightActor::RenderOpaqueGeometry(vtkViewport *viewport)
{
this->UpdateViewProps();
int result=0;
if(this->ConeActor!=0 && this->ConeActor->GetMapper()!=0)
{
result=this->ConeActor->RenderOpaqueGeometry(viewport);
result+=this->FrustumActor->RenderOpaqueGeometry(viewport);
}
return result;
}
// ----------------------------------------------------------------------------
// Description:
// Does this prop have some translucent polygonal geometry? No.
int vtkLightActor::HasTranslucentPolygonalGeometry()
{
return false;
}
//-----------------------------------------------------------------------------
void vtkLightActor::ReleaseGraphicsResources(vtkWindow *window)
{
if(this->ConeActor!=0)
{
this->ConeActor->ReleaseGraphicsResources(window);
this->FrustumActor->ReleaseGraphicsResources(window);
}
}
//-------------------------------------------------------------------------
// Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
double *vtkLightActor::GetBounds()
{
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_DOUBLE_MAX;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_DOUBLE_MAX;
this->UpdateViewProps();
this->BoundingBox->Reset();
if(this->ConeActor!=0)
{
if(this->ConeActor->GetUseBounds())
{
this->BoundingBox->AddBounds(this->ConeActor->GetBounds());
}
if(this->FrustumActor->GetUseBounds())
{
this->BoundingBox->AddBounds(this->FrustumActor->GetBounds());
}
}
int i=0;
while(i<6)
{
this->Bounds[i]=this->BoundingBox->GetBound(i);
++i;
}
if(this->Bounds[0]==VTK_DOUBLE_MAX)
{
// we cannot initialize the Bounds the same way vtkBoundingBox does because
// vtkProp3D::GetLength() does not check if the Bounds are initialized or
// not and makes a call to sqrt(). This call to sqrt with invalid values
// would raise a floating-point overflow exception (notably on BCC).
// As vtkMath::UninitializeBounds initialized finite unvalid bounds, it
// passes silently and GetLength() returns 0.
vtkMath::UninitializeBounds(this->Bounds);
}
return this->Bounds;
}
//-------------------------------------------------------------------------
unsigned long int vtkLightActor::GetMTime()
{
unsigned long mTime=this->Superclass::GetMTime();
if(this->Light!=0)
{
unsigned long time;
time = this->Light->GetMTime();
if(time>mTime)
{
mTime=time;
}
}
return mTime;
}
// ----------------------------------------------------------------------------
void vtkLightActor::UpdateViewProps()
{
if(this->Light==0)
{
vtkDebugMacro(<< "no light.");
return;
}
double angle=this->Light->GetConeAngle();
if(this->Light->GetPositional() && angle<180.0)
{
if(this->ConeSource==0)
{
this->ConeSource=vtkConeSource::New();
}
this->ConeSource->SetResolution(24);
double *pos=this->Light->GetPosition();
double *f=this->Light->GetFocalPoint();
double direction[3];
int i=0;
while(i<3)
{
direction[i]=pos[i]-f[i];
++i;
}
double height=1.0;
double center[3]; //=pos
double n=vtkMath::Norm(direction);
// cone center is the middle of its axis, not the center of the base...
i=0;
while(i<3)
{
center[i]=pos[i]-0.5*height/n*direction[i];
++i;
}
this->ConeSource->SetCenter(center);
this->ConeSource->SetDirection(direction);
this->ConeSource->SetHeight(height);
this->ConeSource->SetAngle(angle);
if(this->ConeMapper==0)
{
this->ConeMapper=vtkPolyDataMapper::New();
this->ConeMapper->SetInputConnection(this->ConeSource->GetOutputPort());
this->ConeMapper->SetScalarVisibility(0);
}
if(this->ConeActor==0)
{
this->ConeActor=vtkActor::New();
this->ConeActor->SetMapper(this->ConeMapper);
}
this->ConeActor->SetVisibility(this->Light->GetSwitch());
vtkProperty *p=this->ConeActor->GetProperty();
p->SetLighting(false);
p->SetColor(this->Light->GetDiffuseColor());
p->SetRepresentationToWireframe();
if(this->CameraLight==0)
{
this->CameraLight=vtkCamera::New();
}
this->CameraLight->SetPosition(this->Light->GetPosition());
this->CameraLight->SetFocalPoint(this->Light->GetFocalPoint());
this->CameraLight->SetViewUp(0.0,1.0,0.0);
// view angle is an aperture, but cone (or light) angle is between
// the axis of the cone and a ray along the edge of the cone.
this->CameraLight->SetViewAngle(angle*2.0);
// initial clip=(0.1,1000). near>0, far>near);
this->CameraLight->SetClippingRange(this->ClippingRange);
if(this->FrustumActor==0)
{
this->FrustumActor=vtkCameraActor::New();
}
this->FrustumActor->SetCamera(this->CameraLight);
this->FrustumActor->SetWidthByHeightRatio(1.0); // camera light is square
this->FrustumActor->SetUseBounds(false);
}
else
{
this->ConeActor->SetMapper(0);
this->FrustumActor->SetCamera(0);
vtkErrorMacro(<< "not a spotlight.");
return;
}
}
//-------------------------------------------------------------------------
void vtkLightActor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Light: ";
if(this->Light==0)
{
os << "(none)" << endl;
}
else
{
this->Light->PrintSelf(os,indent);
}
os << indent << "ClippingRange: " << this->ClippingRange[0] << ","
<< this->ClippingRange[1] << endl;
}
<commit_msg>fix bug 0013676: vtkLightActor crashes if the light is not positional<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkLightActor.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 "vtkLightActor.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkCameraActor.h"
#include "vtkConeSource.h"
#include "vtkCamera.h"
#include "vtkLight.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkProperty.h"
#include "vtkBoundingBox.h"
vtkStandardNewMacro(vtkLightActor);
vtkCxxSetObjectMacro(vtkLightActor, Light, vtkLight);
// ----------------------------------------------------------------------------
vtkLightActor::vtkLightActor()
{
this->Light=0;
this->ClippingRange[0]=0.5;
this->ClippingRange[1]=10.0;
this->ConeSource=0;
this->ConeMapper=0;
this->ConeActor=0;
this->CameraLight=0;
this->FrustumActor=0;
this->BoundingBox=new vtkBoundingBox;
}
// ----------------------------------------------------------------------------
vtkLightActor::~vtkLightActor()
{
this->SetLight(0);
if(this->ConeActor!=0)
{
this->ConeActor->Delete();
}
if(this->ConeMapper!=0)
{
this->ConeMapper->Delete();
}
if(this->FrustumActor!=0)
{
this->FrustumActor->Delete();
}
if(this->ConeSource!=0)
{
this->ConeSource->Delete();
}
if(this->CameraLight!=0)
{
this->CameraLight->Delete();
}
delete this->BoundingBox;
}
// ----------------------------------------------------------------------------
// Description:
// Set/Get the location of the near and far clipping planes along the
// direction of projection. Both of these values must be positive.
// Initial values are (0.5,11.0)
void vtkLightActor::SetClippingRange(double dNear,
double dFar)
{
this->ClippingRange[0]=dNear;
this->ClippingRange[1]=dFar;
}
// ----------------------------------------------------------------------------
void vtkLightActor::SetClippingRange(const double a[2])
{
this->SetClippingRange(a[0], a[1]);
}
// ----------------------------------------------------------------------------
// Description:
// Support the standard render methods.
int vtkLightActor::RenderOpaqueGeometry(vtkViewport *viewport)
{
this->UpdateViewProps();
int result=0;
if(this->ConeActor!=0 && this->ConeActor->GetMapper()!=0)
{
result=this->ConeActor->RenderOpaqueGeometry(viewport);
result+=this->FrustumActor->RenderOpaqueGeometry(viewport);
}
return result;
}
// ----------------------------------------------------------------------------
// Description:
// Does this prop have some translucent polygonal geometry? No.
int vtkLightActor::HasTranslucentPolygonalGeometry()
{
return false;
}
//-----------------------------------------------------------------------------
void vtkLightActor::ReleaseGraphicsResources(vtkWindow *window)
{
if(this->ConeActor!=0)
{
this->ConeActor->ReleaseGraphicsResources(window);
this->FrustumActor->ReleaseGraphicsResources(window);
}
}
//-------------------------------------------------------------------------
// Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
double *vtkLightActor::GetBounds()
{
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_DOUBLE_MAX;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_DOUBLE_MAX;
this->UpdateViewProps();
this->BoundingBox->Reset();
if(this->ConeActor!=0)
{
if(this->ConeActor->GetUseBounds())
{
this->BoundingBox->AddBounds(this->ConeActor->GetBounds());
}
if(this->FrustumActor->GetUseBounds())
{
this->BoundingBox->AddBounds(this->FrustumActor->GetBounds());
}
}
int i=0;
while(i<6)
{
this->Bounds[i]=this->BoundingBox->GetBound(i);
++i;
}
if(this->Bounds[0]==VTK_DOUBLE_MAX)
{
// we cannot initialize the Bounds the same way vtkBoundingBox does because
// vtkProp3D::GetLength() does not check if the Bounds are initialized or
// not and makes a call to sqrt(). This call to sqrt with invalid values
// would raise a floating-point overflow exception (notably on BCC).
// As vtkMath::UninitializeBounds initialized finite unvalid bounds, it
// passes silently and GetLength() returns 0.
vtkMath::UninitializeBounds(this->Bounds);
}
return this->Bounds;
}
//-------------------------------------------------------------------------
unsigned long int vtkLightActor::GetMTime()
{
unsigned long mTime=this->Superclass::GetMTime();
if(this->Light!=0)
{
unsigned long time;
time = this->Light->GetMTime();
if(time>mTime)
{
mTime=time;
}
}
return mTime;
}
// ----------------------------------------------------------------------------
void vtkLightActor::UpdateViewProps()
{
if(this->Light==0)
{
vtkDebugMacro(<< "no light.");
return;
}
double angle=this->Light->GetConeAngle();
if(this->Light->GetPositional() && angle<180.0)
{
if(this->ConeSource==0)
{
this->ConeSource=vtkConeSource::New();
}
this->ConeSource->SetResolution(24);
double *pos=this->Light->GetPosition();
double *f=this->Light->GetFocalPoint();
double direction[3];
int i=0;
while(i<3)
{
direction[i]=pos[i]-f[i];
++i;
}
double height=1.0;
double center[3]; //=pos
double n=vtkMath::Norm(direction);
// cone center is the middle of its axis, not the center of the base...
i=0;
while(i<3)
{
center[i]=pos[i]-0.5*height/n*direction[i];
++i;
}
this->ConeSource->SetCenter(center);
this->ConeSource->SetDirection(direction);
this->ConeSource->SetHeight(height);
this->ConeSource->SetAngle(angle);
if(this->ConeMapper==0)
{
this->ConeMapper=vtkPolyDataMapper::New();
this->ConeMapper->SetInputConnection(this->ConeSource->GetOutputPort());
this->ConeMapper->SetScalarVisibility(0);
}
if(this->ConeActor==0)
{
this->ConeActor=vtkActor::New();
this->ConeActor->SetMapper(this->ConeMapper);
}
this->ConeActor->SetVisibility(this->Light->GetSwitch());
vtkProperty *p=this->ConeActor->GetProperty();
p->SetLighting(false);
p->SetColor(this->Light->GetDiffuseColor());
p->SetRepresentationToWireframe();
if(this->CameraLight==0)
{
this->CameraLight=vtkCamera::New();
}
this->CameraLight->SetPosition(this->Light->GetPosition());
this->CameraLight->SetFocalPoint(this->Light->GetFocalPoint());
this->CameraLight->SetViewUp(0.0,1.0,0.0);
// view angle is an aperture, but cone (or light) angle is between
// the axis of the cone and a ray along the edge of the cone.
this->CameraLight->SetViewAngle(angle*2.0);
// initial clip=(0.1,1000). near>0, far>near);
this->CameraLight->SetClippingRange(this->ClippingRange);
if(this->FrustumActor==0)
{
this->FrustumActor=vtkCameraActor::New();
}
this->FrustumActor->SetCamera(this->CameraLight);
this->FrustumActor->SetWidthByHeightRatio(1.0); // camera light is square
this->FrustumActor->SetUseBounds(false);
}
else
{
if(this->ConeActor)
{
this->ConeActor->SetMapper(0);
}
if(this->FrustumActor)
{
this->FrustumActor->SetCamera(0);
}
vtkErrorMacro(<< "not a spotlight.");
return;
}
}
//-------------------------------------------------------------------------
void vtkLightActor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Light: ";
if(this->Light==0)
{
os << "(none)" << endl;
}
else
{
this->Light->PrintSelf(os,indent);
}
os << indent << "ClippingRange: " << this->ClippingRange[0] << ","
<< this->ClippingRange[1] << endl;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include "VectorIndexer.hpp"
#include "Bookmark.hpp"
namespace Rendering
{
namespace Buffer
{
class VertexBuffer;
class IndexBuffer;
};
namespace Manager
{
template <typename BufferType>
class BufferPool final
{
public:
BufferPool() = default;
DISALLOW_ASSIGN_COPY(BufferPool);
void Add(uint hashKey, const BufferType& bufferData)
{
_buffers.Add(hashKey, bufferData);
}
auto Find(uint hashKey)
{
return _buffers.Find(hashKey);
}
bool Has(uint hashKey) const
{
return _buffers.Has(hashKey);
}
void Delete(uint hashKey)
{
auto vb = _buffers.Find(hashKey);
if (vb == nullptr) return;
_buffers.Delete(hashKey);
_idMarker.Delete(vb->GetStrKey());
}
void Destroy()
{
_buffers.DeleteAll();
_idMarker.DeleteAll();
}
private:
Core::BookHashMapmark<std::string> _marker;
Core::VectorMap<uint, BufferType> _buffers;
};
using VBPool = BufferPool<Buffer::VertexBuffer>;
using IBPool = BufferPool<Buffer::IndexBuffer>;
}
}<commit_msg>์ฌ์ฉํ์ง ์๋ ์ฝ๋ ์ ๊ฑฐ<commit_after>#pragma once
#include <memory>
#include "VectorIndexer.hpp"
#include "Bookmark.hpp"
namespace Rendering
{
namespace Buffer
{
class VertexBuffer;
class IndexBuffer;
};
namespace Manager
{
template <typename BufferType>
class BufferPool final
{
public:
BufferPool() = default;
DISALLOW_ASSIGN_COPY(BufferPool);
void Add(uint hashKey, const BufferType& bufferData)
{
_buffers.Add(hashKey, bufferData);
}
auto Find(uint hashKey)
{
return _buffers.Find(hashKey);
}
bool Has(uint hashKey) const
{
return _buffers.Has(hashKey);
}
void Delete(uint hashKey)
{
auto vb = _buffers.Find(hashKey);
if (vb == nullptr) return;
_buffers.Delete(hashKey);
_idMarker.Delete(vb->GetStrKey());
}
void Destroy()
{
_buffers.DeleteAll();
}
private:
Core::VectorMap<uint, BufferType> _buffers;
};
using VBPool = BufferPool<Buffer::VertexBuffer>;
using IBPool = BufferPool<Buffer::IndexBuffer>;
}
}<|endoftext|>
|
<commit_before>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "verilog/analysis/checkers/port_name_suffix_rule.h"
#include <set>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "common/analysis/citation.h"
#include "common/analysis/lint_rule_status.h"
#include "common/analysis/matcher/bound_symbol_manager.h"
#include "common/analysis/matcher/matcher.h"
#include "common/strings/naming_utils.h"
#include "common/text/symbol.h"
#include "common/text/syntax_tree_context.h"
#include "common/text/token_info.h"
#include "verilog/CST/identifier.h"
#include "verilog/CST/port.h"
#include "verilog/CST/verilog_matchers.h"
#include "verilog/analysis/descriptions.h"
#include "verilog/analysis/lint_rule_registry.h"
#include "verilog/parser/verilog_token_enum.h"
namespace verilog {
namespace analysis {
using verible::GetStyleGuideCitation;
using verible::LintRuleStatus;
using verible::LintViolation;
using verible::Symbol;
using verible::SyntaxTreeContext;
using verible::TokenInfo;
using verible::matcher::Matcher;
// Register PortNameSuffixRule.
VERILOG_REGISTER_LINT_RULE(PortNameSuffixRule);
absl::string_view PortNameSuffixRule::Name() { return "port-name-suffix"; }
const char PortNameSuffixRule::kTopic[] = "suffixes-for-signals-and-types";
const char PortNameSuffixRule::kMessageIn[] =
"input port names must end with _i, _ni or _pi";
const char PortNameSuffixRule::kMessageOut[] =
"output port names must end with _o, _no, or _po";
const char PortNameSuffixRule::kMessageInOut[] =
"inout port names must end with _io, _nio or _pio";
std::string PortNameSuffixRule::GetDescription(
DescriptionType description_type) {
return absl::StrCat(
"Check that port names end with _i for inputs, _o for outputs and _io "
"for inouts. "
"Alternatively, for active-low signals use _n[io], for differential "
"pairs use _n[io] and _p[io]. "
"See ",
GetStyleGuideCitation(kTopic), ".");
}
static const Matcher& PortMatcher() {
static const Matcher matcher(NodekPortDeclaration());
return matcher;
}
void PortNameSuffixRule::Violation(absl::string_view direction,
const TokenInfo& token,
const SyntaxTreeContext& context) {
if (direction == "input") {
violations_.insert(LintViolation(token, kMessageIn, context));
} else if (direction == "output") {
violations_.insert(LintViolation(token, kMessageOut, context));
} else if (direction == "inout") {
violations_.insert(LintViolation(token, kMessageInOut, context));
}
}
bool PortNameSuffixRule::IsSuffixCorrect(const absl::string_view suffix,
const absl::string_view direction) {
static const std::map<absl::string_view, std::set<absl::string_view>>
suffixes = {{"input", {"i", "ni", "pi"}},
{"output", {"o", "no", "po"}},
{"inout", {"io", "nio", "pio"}}};
return suffixes.at(direction).count(suffix) == 1;
}
void PortNameSuffixRule::HandleSymbol(const Symbol& symbol,
const SyntaxTreeContext& context) {
constexpr absl::string_view implicit_direction = "input";
verible::matcher::BoundSymbolManager manager;
if (PortMatcher().Matches(symbol, &manager)) {
const auto* identifier_leaf =
GetIdentifierFromModulePortDeclaration(symbol);
const auto* direction_leaf = GetDirectionFromModulePortDeclaration(symbol);
const auto token = identifier_leaf->get();
const auto direction =
direction_leaf ? direction_leaf->get().text() : implicit_direction;
const auto name = ABSL_DIE_IF_NULL(identifier_leaf)->get().text();
// Check if there is any suffix
std::vector<std::string> name_parts =
absl::StrSplit(name, '_', absl::SkipEmpty());
if (name_parts.size() < 2) {
// No suffix at all
Violation(direction, token, context);
}
if (!IsSuffixCorrect(name_parts.back(), direction))
Violation(direction, token, context);
}
}
LintRuleStatus PortNameSuffixRule::Report() const {
return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic));
}
} // namespace analysis
} // namespace verilog
<commit_msg>Add comments to port name suffix rule checker<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "verilog/analysis/checkers/port_name_suffix_rule.h"
#include <set>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "common/analysis/citation.h"
#include "common/analysis/lint_rule_status.h"
#include "common/analysis/matcher/bound_symbol_manager.h"
#include "common/analysis/matcher/matcher.h"
#include "common/strings/naming_utils.h"
#include "common/text/symbol.h"
#include "common/text/syntax_tree_context.h"
#include "common/text/token_info.h"
#include "verilog/CST/identifier.h"
#include "verilog/CST/port.h"
#include "verilog/CST/verilog_matchers.h"
#include "verilog/analysis/descriptions.h"
#include "verilog/analysis/lint_rule_registry.h"
#include "verilog/parser/verilog_token_enum.h"
namespace verilog {
namespace analysis {
using verible::GetStyleGuideCitation;
using verible::LintRuleStatus;
using verible::LintViolation;
using verible::Symbol;
using verible::SyntaxTreeContext;
using verible::TokenInfo;
using verible::matcher::Matcher;
// Register PortNameSuffixRule.
VERILOG_REGISTER_LINT_RULE(PortNameSuffixRule);
absl::string_view PortNameSuffixRule::Name() { return "port-name-suffix"; }
const char PortNameSuffixRule::kTopic[] = "suffixes-for-signals-and-types";
const char PortNameSuffixRule::kMessageIn[] =
"input port names must end with _i, _ni or _pi";
const char PortNameSuffixRule::kMessageOut[] =
"output port names must end with _o, _no, or _po";
const char PortNameSuffixRule::kMessageInOut[] =
"inout port names must end with _io, _nio or _pio";
std::string PortNameSuffixRule::GetDescription(
DescriptionType description_type) {
return absl::StrCat(
"Check that port names end with _i for inputs, _o for outputs and _io "
"for inouts. "
"Alternatively, for active-low signals use _n[io], for differential "
"pairs use _n[io] and _p[io]. "
"See ",
GetStyleGuideCitation(kTopic), ".");
}
static const Matcher& PortMatcher() {
static const Matcher matcher(NodekPortDeclaration());
return matcher;
}
void PortNameSuffixRule::Violation(absl::string_view direction,
const TokenInfo& token,
const SyntaxTreeContext& context) {
if (direction == "input") {
violations_.insert(LintViolation(token, kMessageIn, context));
} else if (direction == "output") {
violations_.insert(LintViolation(token, kMessageOut, context));
} else if (direction == "inout") {
violations_.insert(LintViolation(token, kMessageInOut, context));
}
}
bool PortNameSuffixRule::IsSuffixCorrect(const absl::string_view suffix,
const absl::string_view direction) {
static const std::map<absl::string_view, std::set<absl::string_view>>
suffixes = {{"input", {"i", "ni", "pi"}},
{"output", {"o", "no", "po"}},
{"inout", {"io", "nio", "pio"}}};
// At this point it is guaranteed that the direction will be set to
// one of the expected values (used as keys in the map above).
// Therefore checking the suffix like this is safe
return suffixes.at(direction).count(suffix) == 1;
}
void PortNameSuffixRule::HandleSymbol(const Symbol& symbol,
const SyntaxTreeContext& context) {
constexpr absl::string_view implicit_direction = "input";
verible::matcher::BoundSymbolManager manager;
if (PortMatcher().Matches(symbol, &manager)) {
const auto* identifier_leaf =
GetIdentifierFromModulePortDeclaration(symbol);
const auto* direction_leaf = GetDirectionFromModulePortDeclaration(symbol);
const auto token = identifier_leaf->get();
const auto direction =
direction_leaf ? direction_leaf->get().text() : implicit_direction;
const auto name = ABSL_DIE_IF_NULL(identifier_leaf)->get().text();
// Check if there is any suffix
std::vector<std::string> name_parts =
absl::StrSplit(name, '_', absl::SkipEmpty());
if (name_parts.size() < 2) {
// No suffix at all
Violation(direction, token, context);
}
if (!IsSuffixCorrect(name_parts.back(), direction))
Violation(direction, token, context);
}
}
LintRuleStatus PortNameSuffixRule::Report() const {
return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic));
}
} // namespace analysis
} // namespace verilog
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008, 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.
*/
#include <boost/version.hpp>
#include "libtorrent/error_code.hpp"
namespace libtorrent
{
#if BOOST_VERSION >= 103500
const char* libtorrent_error_category::name() const
{
return "libtorrent error";
}
std::string libtorrent_error_category::message(int ev) const
{
static char const* msgs[] =
{
"no error",
"torrent file collides with file from another torrent",
"hash check failed",
"torrent file is not a dictionary",
"missing or invalid 'info' section in torrent file",
"'info' entry is not a dictionary",
"invalid or missing 'piece length' entry in torrent file",
"missing name in torrent file",
"invalid 'name' of torrent (possible exploit attempt)",
"invalid length of torrent",
"failed to parse files from torrent file",
"invalid or missing 'pieces' entry in torrent file",
"incorrect number of piece hashes in torrent file",
"too many pieces in torrent",
"invalid metadata received from swarm",
"invalid bencoding",
"no files in torrent",
"invalid escaped string",
"session is closing",
"torrent already exists in session",
"invalid torrent handle used",
"invalid type requested from entry",
"missing info-hash from URI",
"file too short",
"unsupported URL protocol",
"failed to parse URL",
"peer sent 0 length piece",
"parse failed",
"invalid file format tag",
"missing info-hash",
"mismatching info-hash",
"invalid hostname",
"invalid port",
"port blocked by port-filter",
"expected closing ] for address",
"destructing torrent",
"timed out",
"upload to uplaod connection",
"uninteresting upload-only peer",
"invalid info-hash",
"torrent paused",
"'have'-message with higher index than the number of pieces",
"bitfield of invalid size",
"too many piece requests while choked",
"invalid piece packet",
"out of memory",
"torrent aborted",
"connected to ourselves",
"invalid piece size",
"timed out: no interest",
"timed out: inactivity",
"timed out: no handshake",
"timed out: no request",
"invalid choke message",
"invalid unchoke message",
"invalid interested message",
"invalid not-interested message",
"invalid request message",
"invalid hash list",
"invalid hash piece message",
"invalid cancel message",
"invalid dht-port message",
"invalid suggest piece message",
"invalid have-all message",
"invalid have-none message",
"invalid reject message",
"invalid allow-fast message",
"invalid extended message",
"invalid message",
"sync hash not found",
"unable to verify encryption constant",
"plaintext mode not provided",
"rc4 mode not provided",
"unsupported encryption mode",
"peer selected unsupported encryption mode",
"invalid encryption pad size",
"invalid encryption handshake",
"incoming encrypted connections disabled",
"incoming regular connections disabled",
"duplicate peer-id",
"torrent removed",
"packet too large",
"failed to parse HTTP response",
"HTTP error",
"missing location header",
"invalid redirection",
"redirecting",
"invalid HTTP range",
"missing content-length",
"banned by IP filter",
"too many connections",
"peer banned",
"stopping torrent",
"too many corrupt pieces",
"torrent is not ready to accept peers",
"peer is not properly constructed",
"session is closing",
"optimistic disconnect",
"torrent finished",
"no router found",
"metadata too large",
"invalid metadata request",
"invalid metadata size",
"invalid metadata offset",
"invalid metadata message",
"pex message too large",
"invalid pex message",
"invalid lt_tracker message",
"unsupported protocol version",
"not authorized to create port map (enable NAT-PMP on your router)",
"network failure",
"out of resources",
"unsupported opcode",
};
if (ev < 0 || ev >= sizeof(msgs)/sizeof(msgs[0]))
return "Unknown error";
return msgs[ev];
}
TORRENT_EXPORT libtorrent_error_category libtorrent_category;
#else
::asio::error::error_category libtorrent_category(20);
#endif
}
<commit_msg>fixed typo<commit_after>/*
Copyright (c) 2008, 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.
*/
#include <boost/version.hpp>
#include "libtorrent/error_code.hpp"
namespace libtorrent
{
#if BOOST_VERSION >= 103500
const char* libtorrent_error_category::name() const
{
return "libtorrent error";
}
std::string libtorrent_error_category::message(int ev) const
{
static char const* msgs[] =
{
"no error",
"torrent file collides with file from another torrent",
"hash check failed",
"torrent file is not a dictionary",
"missing or invalid 'info' section in torrent file",
"'info' entry is not a dictionary",
"invalid or missing 'piece length' entry in torrent file",
"missing name in torrent file",
"invalid 'name' of torrent (possible exploit attempt)",
"invalid length of torrent",
"failed to parse files from torrent file",
"invalid or missing 'pieces' entry in torrent file",
"incorrect number of piece hashes in torrent file",
"too many pieces in torrent",
"invalid metadata received from swarm",
"invalid bencoding",
"no files in torrent",
"invalid escaped string",
"session is closing",
"torrent already exists in session",
"invalid torrent handle used",
"invalid type requested from entry",
"missing info-hash from URI",
"file too short",
"unsupported URL protocol",
"failed to parse URL",
"peer sent 0 length piece",
"parse failed",
"invalid file format tag",
"missing info-hash",
"mismatching info-hash",
"invalid hostname",
"invalid port",
"port blocked by port-filter",
"expected closing ] for address",
"destructing torrent",
"timed out",
"upload to upload connection",
"uninteresting upload-only peer",
"invalid info-hash",
"torrent paused",
"'have'-message with higher index than the number of pieces",
"bitfield of invalid size",
"too many piece requests while choked",
"invalid piece packet",
"out of memory",
"torrent aborted",
"connected to ourselves",
"invalid piece size",
"timed out: no interest",
"timed out: inactivity",
"timed out: no handshake",
"timed out: no request",
"invalid choke message",
"invalid unchoke message",
"invalid interested message",
"invalid not-interested message",
"invalid request message",
"invalid hash list",
"invalid hash piece message",
"invalid cancel message",
"invalid dht-port message",
"invalid suggest piece message",
"invalid have-all message",
"invalid have-none message",
"invalid reject message",
"invalid allow-fast message",
"invalid extended message",
"invalid message",
"sync hash not found",
"unable to verify encryption constant",
"plaintext mode not provided",
"rc4 mode not provided",
"unsupported encryption mode",
"peer selected unsupported encryption mode",
"invalid encryption pad size",
"invalid encryption handshake",
"incoming encrypted connections disabled",
"incoming regular connections disabled",
"duplicate peer-id",
"torrent removed",
"packet too large",
"failed to parse HTTP response",
"HTTP error",
"missing location header",
"invalid redirection",
"redirecting",
"invalid HTTP range",
"missing content-length",
"banned by IP filter",
"too many connections",
"peer banned",
"stopping torrent",
"too many corrupt pieces",
"torrent is not ready to accept peers",
"peer is not properly constructed",
"session is closing",
"optimistic disconnect",
"torrent finished",
"no router found",
"metadata too large",
"invalid metadata request",
"invalid metadata size",
"invalid metadata offset",
"invalid metadata message",
"pex message too large",
"invalid pex message",
"invalid lt_tracker message",
"unsupported protocol version",
"not authorized to create port map (enable NAT-PMP on your router)",
"network failure",
"out of resources",
"unsupported opcode",
};
if (ev < 0 || ev >= sizeof(msgs)/sizeof(msgs[0]))
return "Unknown error";
return msgs[ev];
}
TORRENT_EXPORT libtorrent_error_category libtorrent_category;
#else
::asio::error::error_category libtorrent_category(20);
#endif
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWin32TextMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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 "vtkWin32TextMapper.h"
#include "vtkObjectFactory.h"
#include "vtkTextProperty.h"
#include "vtkViewport.h"
vtkCxxRevisionMacro(vtkWin32TextMapper, "1.31");
//--------------------------------------------------------------------------
vtkWin32TextMapper* vtkWin32TextMapper::New()
{
vtkGenericWarningMacro(<<"Obsolete native imaging class: "
<<"use OpenGL version instead");
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkWin32TextMapper");
if(ret)
{
return (vtkWin32TextMapper*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkWin32TextMapper;
}
vtkWin32TextMapper::vtkWin32TextMapper()
{
this->LastSize[0] = 0;
this->LastSize[1] = 0;
this->Font = 0;
}
vtkWin32TextMapper::~vtkWin32TextMapper()
{
if ( this->Font )
{
DeleteObject( this->Font );
}
}
void vtkWin32TextMapper::GetSize(vtkViewport* viewport, int *size)
{
if ( this->NumberOfLines > 1 )
{
this->GetMultiLineSize(viewport, size);
return;
}
if (this->Input == NULL || this->Input[0] == '\0')
{
size[0] = 0; size[1] = 0;
return;
}
vtkTextProperty *tprop = this->GetTextProperty();
if (!tprop)
{
vtkErrorMacro(<< "Need a text property to get size");
size[0] = 0; size[1] = 0;
return;
}
// Check to see whether we have to rebuild anything
if (this->GetMTime() < this->BuildTime &&
tprop->GetMTime() < this->BuildTime)
{
size[0] = this->LastSize[0];
size[1] = this->LastSize[1];
return;
}
// Check for input
if (this->Input == NULL)
{
vtkErrorMacro (<<"vtkWin32TextMapper::Render - No input");
return;
}
// Get the window information for display
vtkWindow* window = viewport->GetVTKWindow();
// Get the device context from the window
HDC hdc = (HDC) window->GetGenericContext();
// Create the font
LOGFONT fontStruct;
char fontname[32];
DWORD family;
switch (tprop->GetFontFamily())
{
case VTK_ARIAL:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
case VTK_TIMES:
strcpy(fontname, "Times Roman");
family = FF_ROMAN;
break;
case VTK_COURIER:
strcpy(fontname, "Courier");
family = FF_MODERN;
break;
default:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
}
#ifdef _WIN32_WCE
fontStruct.lfHeight = tprop->GetFontSize() * window->GetDPI() / 72;
#else
fontStruct.lfHeight = MulDiv(tprop->GetFontSize(),
window->GetDPI(), 72);
#endif
// height in logical units
fontStruct.lfWidth = 0; // default width
fontStruct.lfEscapement = 0;
fontStruct.lfOrientation = 0;
if (tprop->GetBold() == 1)
{
fontStruct.lfWeight = FW_BOLD;
}
else
{
fontStruct.lfWeight = FW_NORMAL;
}
fontStruct.lfItalic = tprop->GetItalic();
fontStruct.lfUnderline = 0;
fontStruct.lfStrikeOut = 0;
fontStruct.lfCharSet = ANSI_CHARSET;
fontStruct.lfOutPrecision = OUT_DEFAULT_PRECIS;
fontStruct.lfClipPrecision = CLIP_DEFAULT_PRECIS;
fontStruct.lfQuality = DEFAULT_QUALITY;
fontStruct.lfPitchAndFamily = DEFAULT_PITCH | family;
#ifdef _WIN32_WCE
mbstowcs(fontStruct.lfFaceName, fontname, strlen(fontname));
#else
strcpy(fontStruct.lfFaceName, fontname);
#endif
if (this->Font)
{
DeleteObject(this->Font);
}
this->Font = CreateFontIndirect(&fontStruct);
HFONT hOldFont = (HFONT) SelectObject(hdc, this->Font);
// Define bounding rectangle
RECT rect;
rect.left = 0;
rect.top = 0;
rect.bottom = 0;
rect.right = 0;
// Calculate the size of the bounding rectangle
#ifdef UNICODE
wchar_t *wtxt = new wchar_t [mbstowcs(NULL, this->Input, 32000)];
mbstowcs(wtxt, this->Input, 32000);
size[1] = DrawText(hdc, wtxt, -1, &rect,
DT_CALCRECT|DT_LEFT|DT_NOPREFIX);
delete [] wtxt;
#else
size[1] = static_cast<int>(DrawText(hdc, this->Input,
static_cast<int>(strlen(this->Input)),
&rect,
DT_CALCRECT|DT_LEFT|DT_NOPREFIX));
#endif
size[0] = rect.right - rect.left + 1;
this->LastSize[0] = size[0];
this->LastSize[1] = size[1];
this->BuildTime.Modified();
SelectObject(hdc, hOldFont);
}
<commit_msg>FIX: I think this one is missing (was: ENH: Added vtkInstantiatorNewMacro to provide the instantiator's wrapper around each class's New() method. The macro is automatically invoked by the vtkStandardNewMacro. It is provided for classes that don't use the vtkStandardNewMacro)<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWin32TextMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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 "vtkWin32TextMapper.h"
#include "vtkObjectFactory.h"
#include "vtkTextProperty.h"
#include "vtkViewport.h"
vtkCxxRevisionMacro(vtkWin32TextMapper, "1.32");
//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkWin32TextMapper);
//--------------------------------------------------------------------------
vtkWin32TextMapper* vtkWin32TextMapper::New()
{
vtkGenericWarningMacro(<<"Obsolete native imaging class: "
<<"use OpenGL version instead");
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkWin32TextMapper");
if(ret)
{
return (vtkWin32TextMapper*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkWin32TextMapper;
}
vtkWin32TextMapper::vtkWin32TextMapper()
{
this->LastSize[0] = 0;
this->LastSize[1] = 0;
this->Font = 0;
}
vtkWin32TextMapper::~vtkWin32TextMapper()
{
if ( this->Font )
{
DeleteObject( this->Font );
}
}
void vtkWin32TextMapper::GetSize(vtkViewport* viewport, int *size)
{
if ( this->NumberOfLines > 1 )
{
this->GetMultiLineSize(viewport, size);
return;
}
if (this->Input == NULL || this->Input[0] == '\0')
{
size[0] = 0; size[1] = 0;
return;
}
vtkTextProperty *tprop = this->GetTextProperty();
if (!tprop)
{
vtkErrorMacro(<< "Need a text property to get size");
size[0] = 0; size[1] = 0;
return;
}
// Check to see whether we have to rebuild anything
if (this->GetMTime() < this->BuildTime &&
tprop->GetMTime() < this->BuildTime)
{
size[0] = this->LastSize[0];
size[1] = this->LastSize[1];
return;
}
// Check for input
if (this->Input == NULL)
{
vtkErrorMacro (<<"vtkWin32TextMapper::Render - No input");
return;
}
// Get the window information for display
vtkWindow* window = viewport->GetVTKWindow();
// Get the device context from the window
HDC hdc = (HDC) window->GetGenericContext();
// Create the font
LOGFONT fontStruct;
char fontname[32];
DWORD family;
switch (tprop->GetFontFamily())
{
case VTK_ARIAL:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
case VTK_TIMES:
strcpy(fontname, "Times Roman");
family = FF_ROMAN;
break;
case VTK_COURIER:
strcpy(fontname, "Courier");
family = FF_MODERN;
break;
default:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
}
#ifdef _WIN32_WCE
fontStruct.lfHeight = tprop->GetFontSize() * window->GetDPI() / 72;
#else
fontStruct.lfHeight = MulDiv(tprop->GetFontSize(),
window->GetDPI(), 72);
#endif
// height in logical units
fontStruct.lfWidth = 0; // default width
fontStruct.lfEscapement = 0;
fontStruct.lfOrientation = 0;
if (tprop->GetBold() == 1)
{
fontStruct.lfWeight = FW_BOLD;
}
else
{
fontStruct.lfWeight = FW_NORMAL;
}
fontStruct.lfItalic = tprop->GetItalic();
fontStruct.lfUnderline = 0;
fontStruct.lfStrikeOut = 0;
fontStruct.lfCharSet = ANSI_CHARSET;
fontStruct.lfOutPrecision = OUT_DEFAULT_PRECIS;
fontStruct.lfClipPrecision = CLIP_DEFAULT_PRECIS;
fontStruct.lfQuality = DEFAULT_QUALITY;
fontStruct.lfPitchAndFamily = DEFAULT_PITCH | family;
#ifdef _WIN32_WCE
mbstowcs(fontStruct.lfFaceName, fontname, strlen(fontname));
#else
strcpy(fontStruct.lfFaceName, fontname);
#endif
if (this->Font)
{
DeleteObject(this->Font);
}
this->Font = CreateFontIndirect(&fontStruct);
HFONT hOldFont = (HFONT) SelectObject(hdc, this->Font);
// Define bounding rectangle
RECT rect;
rect.left = 0;
rect.top = 0;
rect.bottom = 0;
rect.right = 0;
// Calculate the size of the bounding rectangle
#ifdef UNICODE
wchar_t *wtxt = new wchar_t [mbstowcs(NULL, this->Input, 32000)];
mbstowcs(wtxt, this->Input, 32000);
size[1] = DrawText(hdc, wtxt, -1, &rect,
DT_CALCRECT|DT_LEFT|DT_NOPREFIX);
delete [] wtxt;
#else
size[1] = static_cast<int>(DrawText(hdc, this->Input,
static_cast<int>(strlen(this->Input)),
&rect,
DT_CALCRECT|DT_LEFT|DT_NOPREFIX));
#endif
size[0] = rect.right - rect.left + 1;
this->LastSize[0] = size[0];
this->LastSize[1] = size[1];
this->BuildTime.Modified();
SelectObject(hdc, hOldFont);
}
<|endoftext|>
|
<commit_before>#include "OffScreen.h"
#include "Utility.h"
using namespace Rendering::TBDR;
using namespace Rendering::PostProcessing;
using namespace Rendering::Shader;
using namespace Rendering::Texture;
using namespace GPGPU::DirectCompute;
OffScreen::OffScreen()
: FullScreen()
{
}
OffScreen::~OffScreen()
{
}
void OffScreen::Initialize(const RenderTexture* inputRenderTexture)
{
FullScreen::Initialize("DeferredMainOffScreen", "PS");
std::vector<ShaderForm::InputTexture> inputTextures;
{
ShaderForm::InputTexture input(0, inputRenderTexture, false, false, false, true);
inputTextures.push_back(input);
}
SetInputPSTextures(inputTextures);
}<commit_msg>OffScreen - ์๋ฌ ์์ #64<commit_after>#include "OffScreen.h"
#include "Utility.h"
using namespace Rendering::TBDR;
using namespace Rendering::PostProcessing;
using namespace Rendering::Shader;
using namespace Rendering::Texture;
using namespace GPGPU::DirectCompute;
OffScreen::OffScreen()
: FullScreen()
{
}
OffScreen::~OffScreen()
{
}
void OffScreen::Initialize(const RenderTexture* inputRenderTexture)
{
FullScreen::Initialize("DeferredMainOffScreen", "PS", nullptr);
std::vector<ShaderForm::InputTexture> inputTextures;
{
ShaderForm::InputTexture input(0, inputRenderTexture, false, false, false, true);
inputTextures.push_back(input);
}
SetInputPSTextures(inputTextures);
}<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.