text
stringlengths 54
60.6k
|
|---|
<commit_before>/*******************************
Copyright (c) 2016-2021 Gr�goire Angerand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/
#include "crashhandler.h"
#include <cstdlib>
#include <cstdio>
#include <csignal>
#if defined(Y_OS_WIN) && defined(__argv) && __has_include(<dbghelp.h>)
#if !defined(EDITOR_NO_CRASH_HANDLER)
#define EDITOR_WIN_CRASH_HANLDER
#endif
#endif
#ifdef EDITOR_WIN_CRASH_HANLDER
#include <windows.h>
#include <dbghelp.h>
#endif
namespace editor {
namespace crashhandler {
#ifdef EDITOR_WIN_CRASH_HANLDER
static decltype(&::SymInitialize) sym_init = nullptr;
static decltype(&::SymCleanup) sym_cleanup = nullptr;
static decltype(&::SymFunctionTableAccess64) func_table = nullptr;
static decltype(&::SymGetModuleBase64) module_base = nullptr;
static decltype(&::StackWalk64) stack_walk = nullptr;
static int print_addr(const void* ptr) {
#ifdef Y_MSVC
return 0;
#else
char buffer[512] = {};
std::sprintf(buffer, "addr2line -f -p -s -C -e %s %p", __argv[0], ptr);
return ::system(buffer);
#endif
}
// https://gist.github.com/jvranish/4441299
// http://theorangeduck.com/page/printing-stack-trace-mingw
static void print_stacktrace() {
HANDLE process = ::GetCurrentProcess();
CONTEXT context = {};
context.ContextFlags = CONTEXT_FULL;
::RtlCaptureContext(&context);
sym_init(process, nullptr, true);
STACKFRAME64 stackframe = {};
stackframe.AddrPC.Offset = context.Rip;
stackframe.AddrPC.Mode = AddrModeFlat;
stackframe.AddrFrame.Offset = context.Rsp;
stackframe.AddrFrame.Mode = AddrModeFlat;
stackframe.AddrStack.Offset = context.Rsp;
stackframe.AddrStack.Mode = AddrModeFlat;
while(stack_walk(IMAGE_FILE_MACHINE_AMD64, process, ::GetCurrentThread(), &stackframe, &context, nullptr, func_table, module_base, nullptr)) {
print_addr(reinterpret_cast<const void*>(stackframe.AddrPC.Offset));
}
sym_cleanup(process);
}
static void handler(int sig) {
// calling basically anything here is UB but we don't really care since we already crashed
y_breakpoint;
if(sig == SIGABRT) {
std::printf("Program has aborted, dumping stack:\n");
} else {
std::printf("Program has crashed, dumping stack:\n");
}
print_stacktrace();
}
bool setup_handler() {
if(HMODULE img_help = ::LoadLibrary("dbghelp.dll")) {
sym_init = reinterpret_cast<decltype(sym_init)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymInitialize")));
sym_cleanup = reinterpret_cast<decltype(sym_cleanup)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymCleanup")));
func_table = reinterpret_cast<decltype(func_table)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymFunctionTableAccess64")));
module_base = reinterpret_cast<decltype(module_base)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymGetModuleBase64")));
stack_walk = reinterpret_cast<decltype(stack_walk)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "StackWalk64")));
}
if(sym_init && sym_cleanup && func_table && module_base && stack_walk) {
std::signal(SIGSEGV, handler);
std::signal(SIGILL, handler);
std::signal(SIGABRT, handler);
return true;
}
return false;
}
#else
bool setup_handler() {
return false;
}
#endif
}
}
<commit_msg>Got crashhandler to work on MSVC<commit_after>/*******************************
Copyright (c) 2016-2021 Gr�goire Angerand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/
#include "crashhandler.h"
#include <cstdlib>
#include <cstdio>
#include <csignal>
#if defined(Y_OS_WIN) && defined(__argv) && __has_include(<dbghelp.h>)
#if !defined(EDITOR_NO_CRASH_HANDLER)
#define EDITOR_WIN_CRASH_HANLDER
#endif
#endif
#ifdef EDITOR_WIN_CRASH_HANLDER
#include <windows.h>
#include <dbghelp.h>
#endif
namespace editor {
namespace crashhandler {
#ifdef EDITOR_WIN_CRASH_HANLDER
static decltype(&::SymInitialize) sym_init = nullptr;
static decltype(&::SymCleanup) sym_cleanup = nullptr;
static decltype(&::SymFunctionTableAccess64) func_table = nullptr;
static decltype(&::SymGetModuleBase64) module_base = nullptr;
static decltype(&::StackWalk64) stack_walk = nullptr;
static decltype(&::SymGetSymFromAddr64) sym_from_addr = nullptr;
static int print_addr(STACKFRAME64 frame) {
const void* ptr = reinterpret_cast<const void*>(frame.AddrPC.Offset);
#ifdef Y_MSVC
static constexpr int max_name_len = 255;
char buffer[sizeof(IMAGEHLP_SYMBOL64) + max_name_len * sizeof(TCHAR)] = {};
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(buffer);
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = max_name_len;
if(sym_from_addr && sym_from_addr(::GetCurrentProcess(), frame.AddrPC.Offset, nullptr, symbol)) {
std::printf("%p: %s\n", ptr, symbol->Name);
} else {
std::printf("%p: ??\n", ptr);
}
return 0;
#else
// https://gist.github.com/jvranish/4441299
// http://theorangeduck.com/page/printing-stack-trace-mingw
char buffer[512] = {};
std::sprintf(buffer, "addr2line -f -p -s -C -e %s %p", __argv[0], ptr);
return ::system(buffer);
#endif
}
static void print_stacktrace() {
HANDLE process = ::GetCurrentProcess();
CONTEXT context = {};
context.ContextFlags = CONTEXT_FULL;
::RtlCaptureContext(&context);
sym_init(process, nullptr, true);
STACKFRAME64 stackframe = {};
stackframe.AddrPC.Offset = context.Rip;
stackframe.AddrPC.Mode = AddrModeFlat;
stackframe.AddrFrame.Offset = context.Rsp;
stackframe.AddrFrame.Mode = AddrModeFlat;
stackframe.AddrStack.Offset = context.Rsp;
stackframe.AddrStack.Mode = AddrModeFlat;
while(stack_walk(IMAGE_FILE_MACHINE_AMD64, process, ::GetCurrentThread(), &stackframe, &context, nullptr, func_table, module_base, nullptr)) {
print_addr(stackframe);
}
sym_cleanup(process);
}
static void handler(int sig) {
// calling basically anything here is UB but we don't really care since we already crashed
y_breakpoint;
if(sig == SIGABRT) {
std::printf("Program has aborted, dumping stack:\n");
} else {
std::printf("Program has crashed, dumping stack:\n");
}
print_stacktrace();
}
bool setup_handler() {
if(HMODULE img_help = ::LoadLibrary("dbghelp.dll")) {
sym_init = reinterpret_cast<decltype(sym_init)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymInitialize")));
sym_cleanup = reinterpret_cast<decltype(sym_cleanup)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymCleanup")));
func_table = reinterpret_cast<decltype(func_table)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymFunctionTableAccess64")));
module_base = reinterpret_cast<decltype(module_base)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymGetModuleBase64")));
stack_walk = reinterpret_cast<decltype(stack_walk)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "StackWalk64")));
sym_from_addr = reinterpret_cast<decltype(sym_from_addr)>(reinterpret_cast<void*>(::GetProcAddress(img_help, "SymGetSymFromAddr64")));
}
if(sym_init && sym_cleanup && func_table && module_base && stack_walk) {
std::signal(SIGSEGV, handler);
std::signal(SIGILL, handler);
std::signal(SIGABRT, handler);
return true;
}
return false;
}
#else
bool setup_handler() {
return false;
}
#endif
}
}
<|endoftext|>
|
<commit_before>#include "MqttClient.hpp"
#include "Timer.hpp"
#include <iostream>
#define MQTT_PROTO_MAJOR 3
#define MQTT_PROTO_MINOR 1
#define MQTT_PROTOCOL_VERSION "MQTT/3.1"
#define PROTOCOL_MAGIC "MQIsdp"
#define FLAG_CLEANSESS(F, C)(F | ((C) << 1))
#define FLAG_WILL(F, W)(F | ((W) << 2))
#define FLAG_WILLQOS(F, Q)(F | ((Q) << 3))
#define FLAG_WILLRETAIN(F, R) (F | ((R) << 5))
#define FLAG_PASSWD(F, P)(F | ((P) << 6))
#define FLAG_USERNAME(F, U)(F | ((U) << 7))
using namespace Kite;
class Frame
{
public:
enum MessageType
{
//0, //Reserved
CONNECT = 1, //Client request to connect to Server
CONNACK = 2, //Connect Acknowledgment
PUBLISH = 3, //Publish message
PUBACK = 4, //Publish Acknowledgment
PUBREC = 5, //Publish Received (assured delivery part 1)
PUBREL = 6, //Publish Release (assured delivery part 2)
PUBCOMP = 7, //Publish Complete (assured delivery part 3)
SUBSCRIBE = 8, //Client Subscribe request
SUBACK = 9, //Subscribe Acknowledgment
UNSUBSCRIBE = 10, //Client Unsubscribe request
UNSUBACK11 = 11, //Unsubscribe Acknowledgment
PINGREQ = 12, //PING Request
PINGRESP = 13, //PING Response
DISCONNECT = 14, //Client is Disconnecting
//15 // Reserved
};
Frame(MessageType type = MessageType(0), int qos = 0, bool retain = false, bool dup = false)
: expectedSize(0)
, type(type)
, qos(qos)
, retain(retain)
, dup(dup)
{ }
int expectedSize;
MessageType type;
uint8_t qos;
bool retain;
bool dup;
//TODO std::string is an inefficient buffer
std::string data;
Frame(uint8_t header, const std::string &data);
int size() const { return data.size(); }
uint16_t readInt();
uint8_t readByte();
std::string readString();
void writeInt(uint16_t i);
void writeByte(uint8_t c);
void writeString (const std::string& string);
void writeRawData(const std::string& data);
void parcel(Kite::IO *io) const;
};
///////////////////////////////////////////////////////////////////////////////
class Kite::MqttClientPrivate : public Kite::Timer
{
public:
MqttClientPrivate(std::weak_ptr<Kite::EventLoop> ev)
: Kite::Timer(ev)
{
KITE_TIMER_DEBUG_NAME(this, "MqttClientPrivate");
}
Kite::MqttClient *p;
std::string clientId;
std::string username;
std::string password;
std::string willTopic;
std::string willMessage;
int willQos;
bool willRetain;
bool cleanSess;
int keepAlive;
bool lastPongReceived;
std::vector<char> buffer;
int expectedSize;
uint8_t nextHeader;
int readPayloadSize()
{
int8_t byte;
int len = 0;
int mul = 1;
do {
//TODO we hope we got the whole header in one tcp package
//otherwise we crash
byte = buffer[0];
buffer.erase(buffer.begin());
len += (byte & 127) * mul;
mul *= 128 ;
} while ((byte & 128) != 0);
return len;
}
uint16_t nextMessageId;
void onCONNACK (Frame &frame);
void onPUBACK (Frame &frame);
void onSUBACK (Frame &frame);
void onPUBLISH (Frame &frame);
bool isConnected;
virtual bool onExpired() override {
if (!isConnected)
return true;
if (!lastPongReceived) {
std::cerr << "ping timeout" << std::endl;
p->disconnect();
}
Frame frame(Frame::PINGREQ, 0);
frame.parcel(p);
p->flush();
lastPongReceived = false;
return true;
}
};
///////////////////////////////////////////////////////////////////////////////
MqttClient::MqttClient(std::weak_ptr<Kite::EventLoop> ev)
: Kite::SecureSocket(ev)
, p(new MqttClientPrivate(ev))
{
p->p = this;
p->keepAlive = 3;
p->lastPongReceived = true;
p->clientId = "kitemqtt";
p->expectedSize = 0;
p->nextMessageId = 1;
p->isConnected = false;
p->cleanSess = false;
}
MqttClient::~MqttClient()
{
delete p;
}
void MqttClient::setCleanSession (bool clean)
{
p->cleanSess = clean;
}
void MqttClient::setClientId(const std::string &v)
{
p->clientId = v;
}
void MqttClient::setUsername(const std::string &username)
{
p->username = username;
}
void MqttClient::setPassword(const std::string &password)
{
p->password = password;
}
void MqttClient::setKeepAlive(int v)
{
p->keepAlive = v;
p->reset(p->keepAlive * 1000);
p->lastPongReceived = true;
}
void MqttClient::setWill(const std::string &topic, const std::string &message, int qos, bool retain)
{
p->willTopic = topic;
p->willMessage = message;
p->willQos = qos;
p->willRetain = retain;
}
void MqttClient::onActivated(int)
{
int osize = p->buffer.size();
p->buffer.resize(osize + 201);
int r = read(p->buffer.data() + osize, 200);
if (r < 1) {
//AGAIN
//TODO:
//this happens when the fd gets ready but ssl frames arent complete
//don't re-buffer to remove the problem.
//it's ok if the higher layer gets an EAGAIN,
//but we need an abstract concept
//at least enum or something, not ints
if (r == -1) {
std::cerr << "rebuffer" << std::endl;
p->buffer.resize(osize);
return;
}
//TODO
fprintf(stderr, "ssl read error: %d\n", r);
ev()->exit(0);
return;
}
p->buffer.resize(osize + r);
while (p->buffer.size() >= 2) {
if (p->expectedSize == 0) {
p->nextHeader = p->buffer[0];
p->buffer.erase(p->buffer.begin());
if (p->buffer[0] != 0 && p->buffer.size() < 3) {
//FIXME
//we don't have the full payload size header,
//whatever we do will be undefined behaviour.
//lets just crash
throw std::runtime_error("payload header fragementation not handled");
return;
}
p->expectedSize = p->readPayloadSize();
}
std::string data;
if (p->expectedSize != 0) {
if (p->buffer.size() < p->expectedSize)
return;
data = std::string(p->buffer.begin(), p->buffer.begin() + p->expectedSize);
p->buffer.erase(p->buffer.begin(), p->buffer.begin() + p->expectedSize);
p->expectedSize = 0;
}
Frame frame(p->nextHeader, data);
switch (frame.type) {
case Frame::CONNACK:
p->onCONNACK(frame);
break;
case Frame::PUBACK:
p->onPUBACK(frame);
break;
case Frame::SUBACK:
p->onSUBACK(frame);
break;
case Frame::PUBLISH:
p->onPUBLISH(frame);
break;
case Frame::PINGRESP:
p->lastPongReceived = true;
break;
default:
std::cerr << "unhandled message type " << frame.type << std::endl;
}
}
}
void MqttClient::onConnected() {
fprintf(stderr, "connected!\n");
Frame frame(Frame::CONNECT, 0);
frame.writeString(PROTOCOL_MAGIC);
frame.writeByte(MQTT_PROTO_MAJOR);
uint8_t flags = 0;
//flags
flags = FLAG_CLEANSESS(flags, p->cleanSess? 1 : 0 );
if (!p->willTopic.empty()) {
flags = FLAG_WILL(flags, 1);
flags = FLAG_WILLQOS(flags, p->willQos);
flags = FLAG_WILLRETAIN(flags, p->willRetain ? 1 : 0);
}
if(!p->username.empty()) {
flags = FLAG_USERNAME(flags, 1);
}
if (!p->password.empty()) {
flags = FLAG_PASSWD(flags, 1);
}
frame.writeByte(flags);
frame.writeInt(p->keepAlive * 2);
frame.writeString(p->clientId);
if (!p->willTopic.empty()) {
frame.writeString(p->willTopic);
frame.writeString(p->willMessage);
}
if (!p->username.empty()) {
frame.writeString(p->username);
}
if (!p->password.empty()) {
frame.writeString(p->password);
}
frame.parcel(this);
flush();
p->isConnected = true;
p->reset(p->keepAlive * 1000);
p->lastPongReceived = true;
}
void MqttClient::publish(const std::string &topic, const std::string &message, int qos, bool retain)
{
Frame frame(Frame::PUBLISH, qos, retain);
frame.writeString(topic);
if (qos > 0) {
if (++(p->nextMessageId) == 0) p->nextMessageId = 1;
frame.writeInt(p->nextMessageId);
}
frame.writeRawData(message);
frame.parcel(this);
flush();
}
void MqttClient::subscribe(const std::string &topic, int qos)
{
Frame frame(Frame::SUBSCRIBE, 1);
if (++(p->nextMessageId) == 0) p->nextMessageId = 1;
frame.writeInt(p->nextMessageId);
frame.writeString(topic);
frame.writeByte(qos);
frame.parcel(this);
flush();
}
void MqttClientPrivate::onCONNACK (Frame &frame)
{
frame.readByte();
int status = frame.readByte();
std::cerr << "connection status: " << status << std::endl;
if (status != 0) {
p->onProtocolError(MqttClient::ProtocolError(status));
p->disconnect();
return;
}
p->onMqttConnected();
}
void MqttClientPrivate::onPUBACK (Frame &frame) {
int id = frame.readInt();
//std::cerr<< "ackd publish " << id << std::endl;
}
void MqttClientPrivate::onSUBACK (Frame &frame) {
int id = frame.readInt();
std::cerr<< "ackd sub " << id << std::endl;
}
void MqttClientPrivate::onPUBLISH (Frame &frame) {
std::string topic = frame.readString();
uint16_t mid = 0;
if (frame.qos > 0) {
mid = frame.readInt();
}
std::string m = frame.data;
p->onPublished(topic, m);
if (frame.qos == 1) {
Frame frame(Frame::PUBACK, 0);
frame.writeInt(mid);
frame.parcel(p);
p->flush();
} else if (frame.qos == 2) {
std::cerr << "QOS2 not implemented\n";
//TODO
}
}
///////////////////////////////////////////////////////////////////////////////
#define LSB(A) (uint8_t)(A & 0x00FF)
#define MSB(A) (uint8_t)((A & 0xFF00) >> 8)
Frame::Frame(uint8_t header, const std::string &data)
: data(data)
{
type = Frame::MessageType(header >> 4);
dup = header & (1 << 3);
qos = (header >> 1) & 3;
retain = header & 1;
}
uint8_t Frame::readByte()
{
uint8_t c = data[0];
data.erase(0, 1);
return c;
}
uint16_t Frame::readInt()
{
uint8_t msb = data[0];
uint8_t lsb = data[1];
data.erase(0, 2);
//TODO: this doesnt look right. will this convert to a wider type before shift?
return (msb << 8) | lsb;
}
std::string Frame::readString()
{
int len = readInt();
std::string s = std::string(data.substr(0, len));
data.erase(0, len);
return s;
}
//TODO this is BS. just write the 16bit int in big endian
void Frame::writeInt(uint16_t i)
{
data += MSB(i);
data += LSB(i);
}
void Frame::writeString(const std::string &string)
{
writeInt(string.size());
data.append(string);
}
void Frame::writeByte(uint8_t c)
{
data += char(c);
}
void Frame::writeRawData(const std::string &d)
{
data.append(d);
}
void Frame::parcel(Kite::IO *io) const
{
uint8_t header = type << 4;
if (dup)
header |= 1 << 3;
header |= qos << 1;
if (retain)
header |= 1;
io->write((char*)&header, 1);
if (data.size() == 0) {
io->write("\0", 1);
return;
}
//length
std::vector<char> r;
int length = data.size();
uint8_t d;
do {
d = length % 128;
length /= 128;
if (length > 0) {
d |= 0x80;
}
r.push_back(d);
} while (length > 0);
io->write(r.data(), r.size());
io->write(data.c_str(), data.size());
return;
}
<commit_msg>mqtt: handle header fragmentation<commit_after>#include "MqttClient.hpp"
#include "Timer.hpp"
#include <iostream>
#define MQTT_PROTO_MAJOR 3
#define MQTT_PROTO_MINOR 1
#define MQTT_PROTOCOL_VERSION "MQTT/3.1"
#define PROTOCOL_MAGIC "MQIsdp"
#define FLAG_CLEANSESS(F, C)(F | ((C) << 1))
#define FLAG_WILL(F, W)(F | ((W) << 2))
#define FLAG_WILLQOS(F, Q)(F | ((Q) << 3))
#define FLAG_WILLRETAIN(F, R) (F | ((R) << 5))
#define FLAG_PASSWD(F, P)(F | ((P) << 6))
#define FLAG_USERNAME(F, U)(F | ((U) << 7))
using namespace Kite;
class Frame
{
public:
enum MessageType
{
//0, //Reserved
CONNECT = 1, //Client request to connect to Server
CONNACK = 2, //Connect Acknowledgment
PUBLISH = 3, //Publish message
PUBACK = 4, //Publish Acknowledgment
PUBREC = 5, //Publish Received (assured delivery part 1)
PUBREL = 6, //Publish Release (assured delivery part 2)
PUBCOMP = 7, //Publish Complete (assured delivery part 3)
SUBSCRIBE = 8, //Client Subscribe request
SUBACK = 9, //Subscribe Acknowledgment
UNSUBSCRIBE = 10, //Client Unsubscribe request
UNSUBACK11 = 11, //Unsubscribe Acknowledgment
PINGREQ = 12, //PING Request
PINGRESP = 13, //PING Response
DISCONNECT = 14, //Client is Disconnecting
//15 // Reserved
};
Frame(MessageType type = MessageType(0), int qos = 0, bool retain = false, bool dup = false)
: expectedSize(0)
, type(type)
, qos(qos)
, retain(retain)
, dup(dup)
{ }
int expectedSize;
MessageType type;
uint8_t qos;
bool retain;
bool dup;
//TODO std::string is an inefficient buffer
std::string data;
Frame(uint8_t header, const std::string &data);
int size() const { return data.size(); }
uint16_t readInt();
uint8_t readByte();
std::string readString();
void writeInt(uint16_t i);
void writeByte(uint8_t c);
void writeString (const std::string& string);
void writeRawData(const std::string& data);
void parcel(Kite::IO *io) const;
};
///////////////////////////////////////////////////////////////////////////////
class Kite::MqttClientPrivate : public Kite::Timer
{
public:
MqttClientPrivate(std::weak_ptr<Kite::EventLoop> ev)
: Kite::Timer(ev)
{
KITE_TIMER_DEBUG_NAME(this, "MqttClientPrivate");
}
Kite::MqttClient *p;
std::string clientId;
std::string username;
std::string password;
std::string willTopic;
std::string willMessage;
int willQos;
bool willRetain;
bool cleanSess;
int keepAlive;
bool lastPongReceived;
std::vector<char> buffer;
int expectedSize;
uint8_t nextHeader;
int readPayloadSize(int *offset)
{
int8_t byte;
int len = 0;
int mul = 1;
do {
if (*offset >= buffer.size())
return -1;
byte = buffer[(*offset)++];
len += (byte & 127) * mul;
mul *= 128 ;
} while ((byte & 128) != 0);
return len;
}
uint16_t nextMessageId;
void onCONNACK (Frame &frame);
void onPUBACK (Frame &frame);
void onSUBACK (Frame &frame);
void onPUBLISH (Frame &frame);
bool isConnected;
virtual bool onExpired() override {
if (!isConnected)
return true;
if (!lastPongReceived) {
std::cerr << "ping timeout" << std::endl;
p->disconnect();
}
Frame frame(Frame::PINGREQ, 0);
frame.parcel(p);
p->flush();
lastPongReceived = false;
return true;
}
};
///////////////////////////////////////////////////////////////////////////////
MqttClient::MqttClient(std::weak_ptr<Kite::EventLoop> ev)
: Kite::SecureSocket(ev)
, p(new MqttClientPrivate(ev))
{
p->p = this;
p->keepAlive = 3;
p->lastPongReceived = true;
p->clientId = "kitemqtt";
p->expectedSize = 0;
p->nextMessageId = 1;
p->isConnected = false;
p->cleanSess = false;
}
MqttClient::~MqttClient()
{
delete p;
}
void MqttClient::setCleanSession (bool clean)
{
p->cleanSess = clean;
}
void MqttClient::setClientId(const std::string &v)
{
p->clientId = v;
}
void MqttClient::setUsername(const std::string &username)
{
p->username = username;
}
void MqttClient::setPassword(const std::string &password)
{
p->password = password;
}
void MqttClient::setKeepAlive(int v)
{
p->keepAlive = v;
p->reset(p->keepAlive * 1000);
p->lastPongReceived = true;
}
void MqttClient::setWill(const std::string &topic, const std::string &message, int qos, bool retain)
{
p->willTopic = topic;
p->willMessage = message;
p->willQos = qos;
p->willRetain = retain;
}
void MqttClient::onActivated(int)
{
int osize = p->buffer.size();
p->buffer.resize(osize + 201);
int r = read(p->buffer.data() + osize, 200);
if (r < 1) {
//AGAIN
//TODO:
//this happens when the fd gets ready but ssl frames arent complete
//don't re-buffer to remove the problem.
//it's ok if the higher layer gets an EAGAIN,
//but we need an abstract concept
//at least enum or something, not ints
if (r == -1) {
std::cerr << "rebuffer" << std::endl;
p->buffer.resize(osize);
return;
}
//TODO
fprintf(stderr, "ssl read error: %d\n", r);
ev()->exit(0);
return;
}
p->buffer.resize(osize + r);
while (p->buffer.size() >= 2) {
if (p->expectedSize == 0) {
p->nextHeader = p->buffer[0];
int offset = 1;
p->expectedSize = p->readPayloadSize(&offset);
if (p->expectedSize == -1) {
p->expectedSize = 0;
std::cerr << "warning: header fragemented" << std::endl;
return;
}
p->buffer.erase(p->buffer.begin(), p->buffer.begin() + offset);
}
std::string data;
if (p->expectedSize != 0) {
if (p->buffer.size() < p->expectedSize)
return;
data = std::string(p->buffer.begin(), p->buffer.begin() + p->expectedSize);
p->buffer.erase(p->buffer.begin(), p->buffer.begin() + p->expectedSize);
p->expectedSize = 0;
}
Frame frame(p->nextHeader, data);
switch (frame.type) {
case Frame::CONNACK:
p->onCONNACK(frame);
break;
case Frame::PUBACK:
p->onPUBACK(frame);
break;
case Frame::SUBACK:
p->onSUBACK(frame);
break;
case Frame::PUBLISH:
p->onPUBLISH(frame);
break;
case Frame::PINGRESP:
p->lastPongReceived = true;
break;
default:
std::cerr << "unhandled message type " << frame.type << std::endl;
}
}
}
void MqttClient::onConnected() {
fprintf(stderr, "connected!\n");
Frame frame(Frame::CONNECT, 0);
frame.writeString(PROTOCOL_MAGIC);
frame.writeByte(MQTT_PROTO_MAJOR);
uint8_t flags = 0;
//flags
flags = FLAG_CLEANSESS(flags, p->cleanSess? 1 : 0 );
if (!p->willTopic.empty()) {
flags = FLAG_WILL(flags, 1);
flags = FLAG_WILLQOS(flags, p->willQos);
flags = FLAG_WILLRETAIN(flags, p->willRetain ? 1 : 0);
}
if(!p->username.empty()) {
flags = FLAG_USERNAME(flags, 1);
}
if (!p->password.empty()) {
flags = FLAG_PASSWD(flags, 1);
}
frame.writeByte(flags);
frame.writeInt(p->keepAlive * 2);
frame.writeString(p->clientId);
if (!p->willTopic.empty()) {
frame.writeString(p->willTopic);
frame.writeString(p->willMessage);
}
if (!p->username.empty()) {
frame.writeString(p->username);
}
if (!p->password.empty()) {
frame.writeString(p->password);
}
frame.parcel(this);
flush();
p->isConnected = true;
p->reset(p->keepAlive * 1000);
p->lastPongReceived = true;
}
void MqttClient::publish(const std::string &topic, const std::string &message, int qos, bool retain)
{
Frame frame(Frame::PUBLISH, qos, retain);
frame.writeString(topic);
if (qos > 0) {
if (++(p->nextMessageId) == 0) p->nextMessageId = 1;
frame.writeInt(p->nextMessageId);
}
frame.writeRawData(message);
frame.parcel(this);
flush();
}
void MqttClient::subscribe(const std::string &topic, int qos)
{
Frame frame(Frame::SUBSCRIBE, 1);
if (++(p->nextMessageId) == 0) p->nextMessageId = 1;
frame.writeInt(p->nextMessageId);
frame.writeString(topic);
frame.writeByte(qos);
frame.parcel(this);
flush();
}
void MqttClientPrivate::onCONNACK (Frame &frame)
{
frame.readByte();
int status = frame.readByte();
std::cerr << "connection status: " << status << std::endl;
if (status != 0) {
p->onProtocolError(MqttClient::ProtocolError(status));
p->disconnect();
return;
}
p->onMqttConnected();
}
void MqttClientPrivate::onPUBACK (Frame &frame) {
int id = frame.readInt();
//std::cerr<< "ackd publish " << id << std::endl;
}
void MqttClientPrivate::onSUBACK (Frame &frame) {
int id = frame.readInt();
std::cerr<< "ackd sub " << id << std::endl;
}
void MqttClientPrivate::onPUBLISH (Frame &frame) {
std::string topic = frame.readString();
uint16_t mid = 0;
if (frame.qos > 0) {
mid = frame.readInt();
}
std::string m = frame.data;
p->onPublished(topic, m);
if (frame.qos == 1) {
Frame frame(Frame::PUBACK, 0);
frame.writeInt(mid);
frame.parcel(p);
p->flush();
} else if (frame.qos == 2) {
std::cerr << "QOS2 not implemented\n";
//TODO
}
}
///////////////////////////////////////////////////////////////////////////////
#define LSB(A) (uint8_t)(A & 0x00FF)
#define MSB(A) (uint8_t)((A & 0xFF00) >> 8)
Frame::Frame(uint8_t header, const std::string &data)
: data(data)
{
type = Frame::MessageType(header >> 4);
dup = header & (1 << 3);
qos = (header >> 1) & 3;
retain = header & 1;
}
uint8_t Frame::readByte()
{
uint8_t c = data[0];
data.erase(0, 1);
return c;
}
uint16_t Frame::readInt()
{
uint8_t msb = data[0];
uint8_t lsb = data[1];
data.erase(0, 2);
//TODO: this doesnt look right. will this convert to a wider type before shift?
return (msb << 8) | lsb;
}
std::string Frame::readString()
{
int len = readInt();
std::string s = std::string(data.substr(0, len));
data.erase(0, len);
return s;
}
//TODO this is BS. just write the 16bit int in big endian
void Frame::writeInt(uint16_t i)
{
data += MSB(i);
data += LSB(i);
}
void Frame::writeString(const std::string &string)
{
writeInt(string.size());
data.append(string);
}
void Frame::writeByte(uint8_t c)
{
data += char(c);
}
void Frame::writeRawData(const std::string &d)
{
data.append(d);
}
void Frame::parcel(Kite::IO *io) const
{
uint8_t header = type << 4;
if (dup)
header |= 1 << 3;
header |= qos << 1;
if (retain)
header |= 1;
io->write((char*)&header, 1);
if (data.size() == 0) {
io->write("\0", 1);
return;
}
//length
std::vector<char> r;
int length = data.size();
uint8_t d;
do {
d = length % 128;
length /= 128;
if (length > 0) {
d |= 0x80;
}
r.push_back(d);
} while (length > 0);
io->write(r.data(), r.size());
io->write(data.c_str(), data.size());
return;
}
<|endoftext|>
|
<commit_before>// -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/*******************************************************************************************************************************************************.H.S.**/
/**
@file mandelbrot_period.cpp
@author Mitch Richling <https://www.mitchr.me>
@brief Produce several images related to the period/cycle structure of the Mandelbrot set.@EOL
@std C++20
@copyright
@parblock
Copyright (c) 1988-2015,2021 Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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 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.
@endparblock
@filedetails
Produce several images related to the period/cycle structure of the Mandelbrot set:
- mandelbrot_periodCYC.tiff: Period -- i.e. the length of the cycle of the orbit.
- mandelbrot_periodSTB.tiff: Number of iterations required for the cycle to be apparent.
- mandelbrot_periodESC.tiff: For divergent points, the number of iterations required for |z|>2.
- mandelbrot_period.tiff: A composite, colorized image showing period and divergent points using a nice color scheme.
********************************************************************************************************************************************************.H.E.**/
/** @cond exj */
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "ramCanvas.hpp"
typedef mjr::ramCanvas1c16b rc16;
typedef mjr::ramCanvas3c8b rc8;
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void) {
std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();
rc8::colorType aColor;
const rc16::colorChanType NUMITR = 4096;
const int CSIZE = 7680/2;
const double MAXZSQ = 4.0;
rc8 theRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4);
rc16 perRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Period -- 0 => not a periodic point
rc16 stbRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Number of iterations period structure was stable
rc16 escRamCanvas(CSIZE, CSIZE, -2.1, 0.75, 1.4, 1.4); // Iteration count for cases where |z|>2
#pragma omp parallel for schedule(static,1)
for(int y=0;y<perRamCanvas.getNumPixY();y++) {
for(int x=0;x<perRamCanvas.getNumPixX();x++) {
std::complex<double> c(perRamCanvas.int2realX(x), perRamCanvas.int2realY(y));
std::complex<double> z(0.0, 0.0);
std::vector<std::complex<double>> lastZs(NUMITR);
rc16::colorChanType count = 0;
while((std::norm(z)<MAXZSQ) && (count<NUMITR)) {
z=std::pow(z, 2) + c;
lastZs[count] = z;
count++;
}
if (count == NUMITR) { // Hit iteration limit
for(rc16::colorChanType period=1; period<(NUMITR-2); period++) {
if(std::abs(z-lastZs[NUMITR-1-period])<1e-4) {
perRamCanvas.drawPoint(x, y, period);
for(rc16::colorChanType stab=0; stab<(NUMITR-period); stab++) {
if(std::abs(lastZs[NUMITR-1-stab]-lastZs[NUMITR-1-period-stab])>1e-6) {
stbRamCanvas.drawPoint(x, y, NUMITR-stab);
break;
}
}
break;
}
}
} else { // Divergence detected because |z|>2
escRamCanvas.drawPoint(x, y, count);
}
}
std::cout << CSIZE << "/" << y << std::endl;
}
perRamCanvas.writeTIFFfile("mandelbrot_periodCYC.tiff");
stbRamCanvas.writeTIFFfile("mandelbrot_periodSTB.tiff");
escRamCanvas.writeTIFFfile("mandelbrot_periodOUT.tiff");
for(int y=0;y<theRamCanvas.getNumPixY();y++) {
for(int x=0;x<theRamCanvas.getNumPixX();x++) {
if (perRamCanvas.getPxColorNC(x, y).getC0() > 0) {
if (perRamCanvas.getPxColorNC(x, y).getC0() > (rc8::colorType::csCBDark2::maxNumC-1)) {
theRamCanvas.drawPoint(x, y, 255);
} else {
theRamCanvas.drawPoint(x, y, rc8::colorType::csCBDark2::c(perRamCanvas.getPxColorNC(x, y).getC0()));
}
} else {
rc8::csFltType c = static_cast<rc8::csFltType>(escRamCanvas.getPxColorNC(x, y).getC0()) / NUMITR;
theRamCanvas.drawPoint(x, y, rc8::colorType::csCCdiag01::c(c*30));
}
}
}
theRamCanvas.drawString("1", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.15, 0.00, "black", 3, 20);
theRamCanvas.drawString("2", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.00, 0.00, "black", 3, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.12, 0.74, "black", 3, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.12, -0.74, "black", 3, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.31, 0.00, "black", 3, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.28, 0.53, "black", 3, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.28, -0.53, "black", 3, 20);
theRamCanvas.writeTIFFfile("mandelbrot_period.tiff");
std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;
std::cout << "Total Runtime " << runTime.count() << " sec" << std::endl;
}
/** @endcond */
<commit_msg>Better cycle detection<commit_after>// -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/*******************************************************************************************************************************************************.H.S.**/
/**
@file mandelbrot_period.cpp
@author Mitch Richling <https://www.mitchr.me>
@brief Produce several images related to the period/cycle structure of the Mandelbrot set.@EOL
@std C++20
@copyright
@parblock
Copyright (c) 1988-2015,2021 Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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 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.
@endparblock
@filedetails
Produce several images related to the period/cycle structure of the Mandelbrot set:
- mandelbrot_periodPER.tiff -- Period of the point. 0 means no period known.
- mandelbrot_periodSTB.tiff -- Stability of the period. 0 means stability unknown.
- mandelbrot_periods.tiff -- Number of iterations required to escape. 0 means it didn't escape.
- mandelbrot_periodNOE.tiff -- Points that didn't escape -- the mandelbrot set. 255
- mandelbrot_period.tiff -- A composite of the above with a few notable period regions labeled.
On my 2022 vintage Intel i7, this takes about 30min to run. The runtime is directly proportional to the NUMITR, so lower that number if you want it to go
faster. Lowering NUMITR will have cause more non-escaping points to not have a known period -- the green points in
********************************************************************************************************************************************************.H.E.**/
/** @cond exj */
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "ramCanvas.hpp"
typedef mjr::ramCanvas1c16b rcM16;
typedef mjr::ramCanvas1c8b rcM8;
typedef mjr::ramCanvas3c8b rcC8;
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void) {
std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();
rcC8::colorType aColor;
const rcM16::colorChanType NUMITR = 65530;
const int CSIZE = 7680;
const double MAXZSQ = 4.1;
rcC8 theRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4);
rcM16 perRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Period -- 0 => not a periodic point
rcM16 stbRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Number of iterations period structure was stable
rcM8 noeRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // No escape: Exceeded iteration count
rcM16 escRamCanvas(CSIZE, CSIZE, -2.1, 0.75, 1.4, 1.4); // Excaped: Iteration count for cases where |z|>2
#pragma omp parallel for schedule(static,1)
for(int y=0;y<perRamCanvas.getNumPixY();y++) {
for(int x=0;x<perRamCanvas.getNumPixX();x++) {
std::complex<double> c(perRamCanvas.int2realX(x), perRamCanvas.int2realY(y));
std::complex<double> z(0.0, 0.0);
std::vector<std::complex<double>> lastZs(NUMITR);
rcM16::colorChanType count = 1;
while((std::norm(z)<MAXZSQ) && (count<NUMITR)) {
z=std::pow(z, 2) + c;
lastZs[count] = z;
count++;
}
if (count == NUMITR) { // Hit iteration limit
noeRamCanvas.drawPoint(x, y, "white");
for(rcM16::colorChanType period=1; period<(NUMITR-2); period++) {
if(std::abs(z-lastZs[NUMITR-1-period])<1e-4) { // Found an identical point 'period' away.
rcM16::colorChanType stab;
for(stab=0; stab<(NUMITR-period); stab++) {
if(std::abs(lastZs[NUMITR-1-stab]-lastZs[NUMITR-1-period-stab])>1e-6) {
break;
}
}
if (stab > period) { // Definatly found a cycle
stbRamCanvas.drawPoint(x, y, NUMITR-stab);
perRamCanvas.drawPoint(x, y, period);
break;
}
}
}
} else { // Divergence detected because |z|>2
escRamCanvas.drawPoint(x, y, count);
}
}
std::cout << CSIZE << "/" << y << std::endl;
}
perRamCanvas.writeTIFFfile("mandelbrot_periodPER.tiff");
stbRamCanvas.writeTIFFfile("mandelbrot_periodSTB.tiff");
escRamCanvas.writeTIFFfile("mandelbrot_periodESC.tiff");
noeRamCanvas.writeTIFFfile("mandelbrot_periodNOE.tiff");
int numConNoCyc = 0;
int numCyc = 0;
int numEsc = 0;
int numPts = 0;
int maxPer = 0;
for(int y=0;y<theRamCanvas.getNumPixY();y++) {
for(int x=0;x<theRamCanvas.getNumPixX();x++) {
auto period = perRamCanvas.getPxColorNC(x, y).getC0();
if (period > maxPer)
maxPer = period;
if (period > 0) {
if (period > (rcC8::colorType::csCBDark2::maxNumC-1)) {
theRamCanvas.drawPoint(x, y, "red");
} else {
theRamCanvas.drawPoint(x, y, rcC8::colorType::csCBDark2::c(period));
}
numCyc++;
} else {
if (noeRamCanvas.getPxColorNC(x, y).getC0() > 0) {
theRamCanvas.drawPoint(x, y, "green");
numConNoCyc++;
} else {
rcC8::csFltType c = static_cast<rcC8::csFltType>(escRamCanvas.getPxColorNC(x, y).getC0()) / NUMITR;
theRamCanvas.drawPoint(x, y, rcC8::colorType::csCCdiag01::c(c*30));
numEsc++;
}
}
numPts++;
}
}
theRamCanvas.drawString("1", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.1500, 0.0000, "black", 6.0, 20);
theRamCanvas.drawString("2", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.0000, 0.0000, "black", 6.0, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.1200, 0.7400, "black", 6.0, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.1200, -0.7400, "black", 6.0, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.758, 0.0000, "black", 1.0, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.3100, 0.0000, "black", 6.0, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.2800, 0.5320, "black", 6.0, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.2800, -0.5320, "black", 6.0, 20);
theRamCanvas.drawString("5", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.5060, -0.5620, "black", 4.0, 20);
theRamCanvas.drawString("5", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.3780, -0.3370, "black", 4.0, 20);
theRamCanvas.drawString("5", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.5060, 0.5620, "black", 4.0, 20);
theRamCanvas.drawString("5", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.3780, 0.3370, "black", 4.0, 20);
theRamCanvas.drawString("6", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.3890, -0.2150, "black", 2.0, 20);
theRamCanvas.drawString("6", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.1140, -0.8620, "black", 4.0, 20);
theRamCanvas.drawString("6", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.1370, -0.2390, "black", 4.0, 20);
theRamCanvas.drawString("6", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.3890, 0.2150, "black", 2.0, 20);
theRamCanvas.drawString("6", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.1140, 0.8620, "black", 4.0, 20);
theRamCanvas.drawString("6", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.1370, 0.2390, "black", 4.0, 20);
theRamCanvas.drawString("7", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.6220, -0.4240, "black", 2.0, 20);
theRamCanvas.drawString("7", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.1210, -0.6100, "black", 2.0, 20);
theRamCanvas.drawString("7", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.3760, -0.1440, "black", 1.0, 20);
theRamCanvas.drawString("7", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.6220, 0.4240, "black", 2.0, 20);
theRamCanvas.drawString("7", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.1210, 0.6100, "black", 2.0, 20);
theRamCanvas.drawString("7", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.3760, 0.1440, "black", 1.0, 20);
theRamCanvas.writeTIFFfile("mandelbrot_period.tiff");
std::cout << "numConNoCyc ... " << numConNoCyc << std::endl;
std::cout << "numCyc ........ " << numCyc << std::endl;
std::cout << "numInSet ...... " << numConNoCyc+numCyc << std::endl;
std::cout << "numEsc ........ " << numEsc << std::endl;
std::cout << "numPts ........ " << numPts << std::endl;
std::cout << "maxPer ........ " << maxPer << std::endl;
std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;
std::cout << "Total Runtime " << runTime.count() << " sec" << std::endl;
}
/** @endcond */
<|endoftext|>
|
<commit_before>#include "derivations.hh"
#include "globals.hh"
#include "shared.hh"
#include "store-api.hh"
#include <sys/utsname.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sys/mman.h>
#include <fcntl.h>
#include <mach-o/loader.h>
#include <mach-o/swap.h>
#define DO_SWAP(x, y) ((x) ? OSSwapInt32(y) : (y))
using namespace nix;
static auto cacheDir = Path{};
Path resolveCacheFile(Path lib) {
std::replace(lib.begin(), lib.end(), '/', '%');
return cacheDir + "/" + lib;
}
std::set<string> readCacheFile(const Path & file) {
return tokenizeString<set<string>>(readFile(file), "\n");
}
void writeCacheFile(const Path & file, std::set<string> & deps) {
std::ofstream fp;
fp.open(file);
for (auto & d : deps) {
fp << d << "\n";
}
fp.close();
}
std::string findDylibName(bool should_swap, ptrdiff_t dylib_command_start) {
struct dylib_command *dylc = (struct dylib_command*)dylib_command_start;
return std::string((char*)(dylib_command_start + DO_SWAP(should_swap, dylc->dylib.name.offset)));
}
std::set<std::string> runResolver(const Path & filename) {
int fd = open(filename.c_str(), O_RDONLY);
struct stat s;
fstat(fd, &s);
void *obj = mmap(NULL, s.st_size, PROT_READ, MAP_SHARED, fd, 0);
ptrdiff_t mach64_offset = 0;
uint32_t magic = ((struct mach_header_64*)obj)->magic;
if(magic == FAT_CIGAM || magic == FAT_MAGIC) {
bool should_swap = magic == FAT_CIGAM;
uint32_t narches = DO_SWAP(should_swap, ((struct fat_header*)obj)->nfat_arch);
for(uint32_t iter = 0; iter < narches; iter++) {
ptrdiff_t header_offset = (ptrdiff_t)obj + sizeof(struct fat_header);
struct fat_arch* arch = (struct fat_arch*)header_offset;
if(DO_SWAP(should_swap, arch->cputype) == CPU_TYPE_X86_64) {
mach64_offset = (ptrdiff_t)DO_SWAP(should_swap, arch->offset);
break;
}
}
if (mach64_offset == 0) {
printMsg(lvlError, format("Could not find any mach64 blobs in file ‘%1%’, continuing...") % filename);
return std::set<string>();
}
} else if (magic == MH_MAGIC_64 || magic == MH_CIGAM_64) {
mach64_offset = 0;
} else {
printMsg(lvlError, format("Object file has unknown magic number ‘%1%’, skipping it...") % magic);
return std::set<string>();
}
ptrdiff_t mach_header_offset = (ptrdiff_t)obj + mach64_offset;
struct mach_header_64 *m_header = (struct mach_header_64 *)mach_header_offset;
bool should_swap = magic == MH_CIGAM_64;
ptrdiff_t cmd_offset = mach_header_offset + sizeof(struct mach_header_64);
std::set<string> libs;
for(uint32_t i = 0; i < DO_SWAP(should_swap, m_header->ncmds); i++) {
struct load_command *cmd = (struct load_command*)cmd_offset;
switch(DO_SWAP(should_swap, cmd->cmd)) {
case LC_LOAD_UPWARD_DYLIB:
case LC_LOAD_DYLIB:
case LC_REEXPORT_DYLIB:
libs.insert(findDylibName(should_swap, cmd_offset));
break;
}
cmd_offset += DO_SWAP(should_swap, cmd->cmdsize);
}
return libs;
}
bool isSymlink(const Path & path) {
struct stat st;
if(lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path ‘%1%’") % path);
return S_ISLNK(st.st_mode);
}
Path resolveSymlink(const Path & path) {
char buf[PATH_MAX];
ssize_t len = readlink(path.c_str(), buf, sizeof(buf) - 1);
if(len != -1) {
buf[len] = 0;
return Path(buf);
} else {
throw SysError(format("readlink('%1%')") % path);
}
}
std::set<string> resolveTree(const Path & path, PathSet & deps) {
std::set<string> results;
if(deps.find(path) != deps.end()) {
return std::set<string>();
}
deps.insert(path);
for (auto & lib : runResolver(path)) {
results.insert(lib);
for (auto & p : resolveTree(lib, deps)) {
results.insert(p);
}
}
return results;
}
std::set<string> getPath(const Path & path) {
Path cacheFile = resolveCacheFile(path);
if(pathExists(cacheFile)) {
return readCacheFile(cacheFile);
}
std::set<string> deps;
std::set<string> paths;
paths.insert(path);
Path next_path = Path(path);
while(isSymlink(next_path)) {
next_path = resolveSymlink(next_path);
paths.insert(next_path);
}
for(auto & t : resolveTree(next_path, deps)) {
paths.insert(t);
}
writeCacheFile(cacheFile, paths);
return paths;
}
int main(int argc, char ** argv) {
return handleExceptions(argv[0], [&]() {
initNix();
struct utsname _uname;
uname(&_uname);
auto cacheParentDir = (format("%1%/dependency-maps") % settings.nixStateDir).str();
cacheDir = (format("%1%/%2%-%3%-%4%")
% cacheParentDir
% _uname.machine
% _uname.sysname
% _uname.release).str();
mkdir(cacheParentDir.c_str(), 0755);
mkdir(cacheDir.c_str(), 0755);
auto store = openStore();
auto drv = store->derivationFromPath(Path(argv[1]));
Strings impurePaths = tokenizeString<Strings>(get(drv.env, "__impureHostDeps"));
std::set<string> all_paths;
for (auto & path : impurePaths) {
for(auto & p : getPath(path)) {
all_paths.insert(p);
}
}
std::cout << "extra-chroot-dirs" << std::endl;
for(auto & path : all_paths) {
std::cout << path << std::endl;
}
std::cout << std::endl;
});
}
<commit_msg>iterate through fat_headers correctly<commit_after>#include "derivations.hh"
#include "globals.hh"
#include "shared.hh"
#include "store-api.hh"
#include <sys/utsname.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sys/mman.h>
#include <fcntl.h>
#include <mach-o/loader.h>
#include <mach-o/swap.h>
#define DO_SWAP(x, y) ((x) ? OSSwapInt32(y) : (y))
using namespace nix;
static auto cacheDir = Path{};
Path resolveCacheFile(Path lib) {
std::replace(lib.begin(), lib.end(), '/', '%');
return cacheDir + "/" + lib;
}
std::set<string> readCacheFile(const Path & file) {
return tokenizeString<set<string>>(readFile(file), "\n");
}
void writeCacheFile(const Path & file, std::set<string> & deps) {
std::ofstream fp;
fp.open(file);
for (auto & d : deps) {
fp << d << "\n";
}
fp.close();
}
std::string findDylibName(bool should_swap, ptrdiff_t dylib_command_start) {
struct dylib_command *dylc = (struct dylib_command*)dylib_command_start;
return std::string((char*)(dylib_command_start + DO_SWAP(should_swap, dylc->dylib.name.offset)));
}
std::set<std::string> runResolver(const Path & filename) {
int fd = open(filename.c_str(), O_RDONLY);
struct stat s;
fstat(fd, &s);
void *obj = mmap(NULL, s.st_size, PROT_READ, MAP_SHARED, fd, 0);
ptrdiff_t mach64_offset = 0;
uint32_t magic = ((struct mach_header_64*)obj)->magic;
if(magic == FAT_CIGAM || magic == FAT_MAGIC) {
bool should_swap = magic == FAT_CIGAM;
uint32_t narches = DO_SWAP(should_swap, ((struct fat_header*)obj)->nfat_arch);
for(uint32_t iter = 0; iter < narches; iter++) {
ptrdiff_t header_offset = (ptrdiff_t)obj + sizeof(struct fat_header) * (iter + 1);
struct fat_arch* arch = (struct fat_arch*)header_offset;
if(DO_SWAP(should_swap, arch->cputype) == CPU_TYPE_X86_64) {
mach64_offset = (ptrdiff_t)DO_SWAP(should_swap, arch->offset);
break;
}
}
if (mach64_offset == 0) {
printMsg(lvlError, format("Could not find any mach64 blobs in file ‘%1%’, continuing...") % filename);
return std::set<string>();
}
} else if (magic == MH_MAGIC_64 || magic == MH_CIGAM_64) {
mach64_offset = 0;
} else {
printMsg(lvlError, format("Object file has unknown magic number ‘%1%’, skipping it...") % magic);
return std::set<string>();
}
ptrdiff_t mach_header_offset = (ptrdiff_t)obj + mach64_offset;
struct mach_header_64 *m_header = (struct mach_header_64 *)mach_header_offset;
bool should_swap = magic == MH_CIGAM_64;
ptrdiff_t cmd_offset = mach_header_offset + sizeof(struct mach_header_64);
std::set<string> libs;
for(uint32_t i = 0; i < DO_SWAP(should_swap, m_header->ncmds); i++) {
struct load_command *cmd = (struct load_command*)cmd_offset;
switch(DO_SWAP(should_swap, cmd->cmd)) {
case LC_LOAD_UPWARD_DYLIB:
case LC_LOAD_DYLIB:
case LC_REEXPORT_DYLIB:
libs.insert(findDylibName(should_swap, cmd_offset));
break;
}
cmd_offset += DO_SWAP(should_swap, cmd->cmdsize);
}
return libs;
}
bool isSymlink(const Path & path) {
struct stat st;
if(lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path ‘%1%’") % path);
return S_ISLNK(st.st_mode);
}
Path resolveSymlink(const Path & path) {
char buf[PATH_MAX];
ssize_t len = readlink(path.c_str(), buf, sizeof(buf) - 1);
if(len != -1) {
buf[len] = 0;
return Path(buf);
} else {
throw SysError(format("readlink('%1%')") % path);
}
}
std::set<string> resolveTree(const Path & path, PathSet & deps) {
std::set<string> results;
if(deps.find(path) != deps.end()) {
return std::set<string>();
}
deps.insert(path);
for (auto & lib : runResolver(path)) {
results.insert(lib);
for (auto & p : resolveTree(lib, deps)) {
results.insert(p);
}
}
return results;
}
std::set<string> getPath(const Path & path) {
Path cacheFile = resolveCacheFile(path);
if(pathExists(cacheFile)) {
return readCacheFile(cacheFile);
}
std::set<string> deps;
std::set<string> paths;
paths.insert(path);
Path next_path = Path(path);
while(isSymlink(next_path)) {
next_path = resolveSymlink(next_path);
paths.insert(next_path);
}
for(auto & t : resolveTree(next_path, deps)) {
paths.insert(t);
}
writeCacheFile(cacheFile, paths);
return paths;
}
int main(int argc, char ** argv) {
return handleExceptions(argv[0], [&]() {
initNix();
struct utsname _uname;
uname(&_uname);
auto cacheParentDir = (format("%1%/dependency-maps") % settings.nixStateDir).str();
cacheDir = (format("%1%/%2%-%3%-%4%")
% cacheParentDir
% _uname.machine
% _uname.sysname
% _uname.release).str();
mkdir(cacheParentDir.c_str(), 0755);
mkdir(cacheDir.c_str(), 0755);
auto store = openStore();
auto drv = store->derivationFromPath(Path(argv[1]));
Strings impurePaths = tokenizeString<Strings>(get(drv.env, "__impureHostDeps"));
std::set<string> all_paths;
for (auto & path : impurePaths) {
for(auto & p : getPath(path)) {
all_paths.insert(p);
}
}
std::cout << "extra-chroot-dirs" << std::endl;
for(auto & path : all_paths) {
std::cout << path << std::endl;
}
std::cout << std::endl;
});
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <thread>
#include <rclcpp/rclcpp.hpp>
#include <simple_msgs/AllBuiltinTypes.h>
#include <simple_msgs/AllDynamicArrayTypes.h>
#include <simple_msgs/AllPrimitiveTypes.h>
#include <simple_msgs/AllStaticArrayTypes.h>
#include <simple_msgs/Nested.h>
#include <simple_msgs/String.h>
#include <simple_msgs/Uint32.h>
#include <userland_msgs/AddTwoInts.h>
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto node = rclcpp::Node::make_shared("add_two_ints_client");
auto client = node->create_client<userland_msgs::AddTwoInts>("add_two_ints");
auto request = std::make_shared<userland_msgs::AddTwoInts::Request>();
auto response = std::make_shared<userland_msgs::AddTwoInts::Response>();
request->a = 2;
request->b = 3;
auto rc = client->send_request(request, response);
if(rc == 0)
{
std::cout << "Sum: " << response->sum << std::endl;
return 0;
} else
{
std::cerr << "Error receiving a response" << std::endl;
}
return rc;
}
<commit_msg>Added support for asynchronous clients<commit_after>#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <thread>
#include <rclcpp/rclcpp.hpp>
#include <simple_msgs/AllBuiltinTypes.h>
#include <simple_msgs/AllDynamicArrayTypes.h>
#include <simple_msgs/AllPrimitiveTypes.h>
#include <simple_msgs/AllStaticArrayTypes.h>
#include <simple_msgs/Nested.h>
#include <simple_msgs/String.h>
#include <simple_msgs/Uint32.h>
#include <userland_msgs/AddTwoInts.h>
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto node = rclcpp::Node::make_shared("add_two_ints_client");
auto client = node->create_client<userland_msgs::AddTwoInts>("add_two_ints");
auto request = std::make_shared<userland_msgs::AddTwoInts::Request>();
auto response = std::make_shared<userland_msgs::AddTwoInts::Response>();
request->a = 2;
request->b = 3;
auto f = client->async_send_request(request, response);
std::future_status status;
do
{
rclcpp::spin_some(node);
status = f.wait_for(std::chrono::milliseconds(100));
} while(status != std::future_status::ready && rclcpp::ok());
if(std::future_status::ready == status)
{
std::cout << "FUTURE READY" << std::endl;
std::cout << f.get()->sum << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>//==============================================================================
// CellML model runtime class
//==============================================================================
#include "cellmlmodelruntime.h"
//==============================================================================
#include <QDebug>
//==============================================================================
#include "CCGSBootstrap.hpp"
//==============================================================================
namespace OpenCOR {
namespace CellMLSupport {
//==============================================================================
CellmlModelRuntime::CellmlModelRuntime()
{
// Initialise the runtime's properties
reset();
}
//==============================================================================
bool CellmlModelRuntime::isValid()
{
// The runtime is valid if no issue was found
return mIssues.isEmpty();
}
//==============================================================================
CellmlModelRuntime::ModelType CellmlModelRuntime::modelType()
{
// Return the type of model for the runtime
return mModelType;
}
//==============================================================================
QList<CellmlModelIssue> CellmlModelRuntime::issues()
{
// Return the issue(s)
return mIssues;
}
//==============================================================================
void CellmlModelRuntime::resetOdeCodeInformation()
{
/*delete mOdeCodeInformation;*/ mOdeCodeInformation = 0;
//---GRY--- WE CANNOT delete mOdeCodeInformation AT THIS STAGE. FOR THIS, WE
// WOULD NEED TO USE THE CLEANED UP C++ INTERFACE (SEE THE MAIN
// COMMENT AT THE BEGINNING OF THE cellmlmodel.cpp FILE)
}
//==============================================================================
void CellmlModelRuntime::resetDaeCodeInformation()
{
/*delete mDaeCodeInformation;*/ mDaeCodeInformation = 0;
//---GRY--- WE CANNOT delete mDaeCodeInformation AT THIS STAGE. FOR THIS, WE
// WOULD NEED TO USE THE CLEANED UP C++ INTERFACE (SEE THE MAIN
// COMMENT AT THE BEGINNING OF THE cellmlmodel.cpp FILE)
}
//==============================================================================
void CellmlModelRuntime::reset()
{
// Reset all of the runtime's properties
//---GRY--- TO BE DONE...
mModelType = Undefined;
resetOdeCodeInformation();
resetDaeCodeInformation();
mIssues.clear();
}
//==============================================================================
void CellmlModelRuntime::couldNotCompileModelIssue()
{
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model could not be compiled")));
}
//==============================================================================
void CellmlModelRuntime::unexpectedProblemDuringModelCompilationIssue()
{
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("an unexpected problem occurred while trying to compile the model")));
}
//==============================================================================
void CellmlModelRuntime::checkCodeInformation(iface::cellml_services::CodeInformation *pCodeInformation)
{
if (!pCodeInformation)
// No code information was provided, so...
return;
// Retrieve the code information's latest error message
QString codeGenerationErrorMessage = QString::fromStdWString(pCodeInformation->errorMessage());
if (codeGenerationErrorMessage.isEmpty()) {
// The code generation went fine, so check the model's constraint level
iface::cellml_services::ModelConstraintLevel constraintLevel = pCodeInformation->constraintLevel();
if (constraintLevel == iface::cellml_services::UNDERCONSTRAINED) {
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is underconstrained (i.e. some variables need to be initialised or computed)")));
} else if (constraintLevel == iface::cellml_services::UNSUITABLY_CONSTRAINED) {
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is unsuitably constrained (i.e. some variables could not be found and/or some equations could not be used)")));
} else if (constraintLevel == iface::cellml_services::OVERCONSTRAINED) {
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is overconstrained (i.e. some variables are either both initialised and computed or computed more than once)")));
}
} else {
// The code generation didn't go fine, so...
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("a problem occurred during the compilation of the model: %1").arg(codeGenerationErrorMessage.toLatin1().constData())));
}
}
//==============================================================================
void CellmlModelRuntime::getOdeCodeInformation(iface::cellml_api::Model *pModel)
{
// Get a code generator bootstrap and create an ODE code generator
ObjRef<iface::cellml_services::CodeGeneratorBootstrap> codeGeneratorBootstrap = CreateCodeGeneratorBootstrap();
ObjRef<iface::cellml_services::CodeGenerator> codeGenerator = codeGeneratorBootstrap->createCodeGenerator();
// Generate some code for the model (i.e. 'compile' the model)
try {
mOdeCodeInformation = codeGenerator->generateCode(pModel);
// Check that the code generation went fine
checkCodeInformation(mOdeCodeInformation);
} catch (iface::cellml_api::CellMLException &) {
couldNotCompileModelIssue();
} catch (...) {
unexpectedProblemDuringModelCompilationIssue();
}
// Check the outcome of the ODE code generation
if (mIssues.count())
// Something went wrong at some point, so...
resetOdeCodeInformation();
}
//==============================================================================
void CellmlModelRuntime::getDaeCodeInformation(iface::cellml_api::Model *pModel)
{
// Get a code generator bootstrap and create a DAE code generator
ObjRef<iface::cellml_services::CodeGeneratorBootstrap> codeGeneratorBootstrap = CreateCodeGeneratorBootstrap();
ObjRef<iface::cellml_services::IDACodeGenerator> codeGenerator = codeGeneratorBootstrap->createIDACodeGenerator();
// Generate some code for the model (i.e. 'compile' the model)
try {
mDaeCodeInformation = codeGenerator->generateIDACode(pModel);
// Check that the code generation went fine
checkCodeInformation(mDaeCodeInformation);
} catch (iface::cellml_api::CellMLException &) {
couldNotCompileModelIssue();
} catch (...) {
unexpectedProblemDuringModelCompilationIssue();
}
// Check the outcome of the DAE code generation
if (mIssues.count())
// Something went wrong at some point, so...
resetDaeCodeInformation();
}
//==============================================================================
CellmlModelRuntime * CellmlModelRuntime::update(iface::cellml_api::Model *pModel,
const bool &pValidModel)
{
// Reset the runtime's properties
reset();
// Check that the model is valid
if (pValidModel) {
// The model is valid, so make sure that it's either a 'simple' ODE
// model or a DAE model
// Note #1: in order to do so, we need to get a 'normal' code generator
// (as opposed to an IDA, i.e. DAE, code generator) since if
// the model is correctly constrained, then we can check
// whether some of its equations were flagged as needing a
// Newton-Raphson evaluation, in which case we would be dealing
// with a DAE model...
// Note #2: ideally, there would be a more convenient way to determine
// the type of a model, but well... there isn't, so...
getOdeCodeInformation(pModel);
// Retrieve the model's type
// Note: this can be done by checking whether some equations were
// flagged as needing a Newton-Raphson evaluation...
if (mOdeCodeInformation) {
// An ODE code information could be retrieved, so we can determine
// the model's type
mModelType = mOdeCodeInformation->flaggedEquations()->length()?Dae:Ode;
// If the model is of DAE type, then we must get the 'right' code
// information
if (mModelType == Dae)
getDaeCodeInformation(pModel);
} else {
// No ODE code information could be retrieved, so...
mModelType = Undefined;
}
// qDebug("---------------------------------------");
// qDebug("\nRequired functions:");
// qDebug(QString::fromStdWString(codeInformation->functionsString()).toLatin1().constData());
// qDebug("---------------------------------------");
// qDebug("\nInitialisations:");
// qDebug(QString::fromStdWString(codeInformation->initConstsString()).toLatin1().constData());
// qDebug("---------------------------------------");
// qDebug("\nVariable evaluations:");
// qDebug(QString::fromStdWString(codeInformation->variablesString()).toLatin1().constData());
// qDebug("---------------------------------------");
// Just testing the generation of 'C code'...
//qDebug() << QString::fromStdWString(getModelAsCCode(pModel));
} else {
// The model is not valid, so...
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is not valid")));
}
// We are done, so return ourselves
return this;
}
//==============================================================================
} // namespace CellMLSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Further work on our CellMLModelRuntime class.<commit_after>//==============================================================================
// CellML model runtime class
//==============================================================================
#include "cellmlmodelruntime.h"
//==============================================================================
#include <QDebug>
//==============================================================================
#include "CCGSBootstrap.hpp"
//==============================================================================
namespace OpenCOR {
namespace CellMLSupport {
//==============================================================================
CellmlModelRuntime::CellmlModelRuntime()
{
// Initialise the runtime's properties
reset();
}
//==============================================================================
bool CellmlModelRuntime::isValid()
{
// The runtime is valid if no issue was found
return mIssues.isEmpty();
}
//==============================================================================
CellmlModelRuntime::ModelType CellmlModelRuntime::modelType()
{
// Return the type of model for the runtime
return mModelType;
}
//==============================================================================
QList<CellmlModelIssue> CellmlModelRuntime::issues()
{
// Return the issue(s)
return mIssues;
}
//==============================================================================
void CellmlModelRuntime::resetOdeCodeInformation()
{
/*delete mOdeCodeInformation;*/ mOdeCodeInformation = 0;
//---GRY--- WE CANNOT delete mOdeCodeInformation AT THIS STAGE. FOR THIS, WE
// WOULD NEED TO USE THE CLEANED UP C++ INTERFACE (SEE THE MAIN
// COMMENT AT THE BEGINNING OF THE cellmlmodel.cpp FILE)
}
//==============================================================================
void CellmlModelRuntime::resetDaeCodeInformation()
{
/*delete mDaeCodeInformation;*/ mDaeCodeInformation = 0;
//---GRY--- WE CANNOT delete mDaeCodeInformation AT THIS STAGE. FOR THIS, WE
// WOULD NEED TO USE THE CLEANED UP C++ INTERFACE (SEE THE MAIN
// COMMENT AT THE BEGINNING OF THE cellmlmodel.cpp FILE)
}
//==============================================================================
void CellmlModelRuntime::reset()
{
// Reset all of the runtime's properties
//---GRY--- TO BE DONE...
mModelType = Undefined;
resetOdeCodeInformation();
resetDaeCodeInformation();
mIssues.clear();
}
//==============================================================================
void CellmlModelRuntime::couldNotCompileModelIssue()
{
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model could not be compiled")));
}
//==============================================================================
void CellmlModelRuntime::unexpectedProblemDuringModelCompilationIssue()
{
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("an unexpected problem occurred while trying to compile the model")));
}
//==============================================================================
void CellmlModelRuntime::checkCodeInformation(iface::cellml_services::CodeInformation *pCodeInformation)
{
if (!pCodeInformation)
// No code information was provided, so...
return;
// Retrieve the code information's latest error message
QString codeGenerationErrorMessage = QString::fromStdWString(pCodeInformation->errorMessage());
if (codeGenerationErrorMessage.isEmpty()) {
// The code generation went fine, so check the model's constraint level
iface::cellml_services::ModelConstraintLevel constraintLevel = pCodeInformation->constraintLevel();
if (constraintLevel == iface::cellml_services::UNDERCONSTRAINED) {
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is underconstrained (i.e. some variables need to be initialised or computed)")));
} else if (constraintLevel == iface::cellml_services::UNSUITABLY_CONSTRAINED) {
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is unsuitably constrained (i.e. some variables could not be found and/or some equations could not be used)")));
} else if (constraintLevel == iface::cellml_services::OVERCONSTRAINED) {
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is overconstrained (i.e. some variables are either both initialised and computed or computed more than once)")));
}
} else {
// The code generation didn't go fine, so...
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("a problem occurred during the compilation of the model: %1").arg(codeGenerationErrorMessage.toLatin1().constData())));
}
}
//==============================================================================
void CellmlModelRuntime::getOdeCodeInformation(iface::cellml_api::Model *pModel)
{
// Get a code generator bootstrap and create an ODE code generator
ObjRef<iface::cellml_services::CodeGeneratorBootstrap> codeGeneratorBootstrap = CreateCodeGeneratorBootstrap();
ObjRef<iface::cellml_services::CodeGenerator> codeGenerator = codeGeneratorBootstrap->createCodeGenerator();
// Generate some code for the model (i.e. 'compile' the model)
try {
mOdeCodeInformation = codeGenerator->generateCode(pModel);
// Check that the code generation went fine
checkCodeInformation(mOdeCodeInformation);
} catch (iface::cellml_api::CellMLException &) {
couldNotCompileModelIssue();
} catch (...) {
unexpectedProblemDuringModelCompilationIssue();
}
// Check the outcome of the ODE code generation
if (mIssues.count())
// Something went wrong at some point, so...
resetOdeCodeInformation();
}
//==============================================================================
void CellmlModelRuntime::getDaeCodeInformation(iface::cellml_api::Model *pModel)
{
// Get a code generator bootstrap and create a DAE code generator
ObjRef<iface::cellml_services::CodeGeneratorBootstrap> codeGeneratorBootstrap = CreateCodeGeneratorBootstrap();
ObjRef<iface::cellml_services::IDACodeGenerator> codeGenerator = codeGeneratorBootstrap->createIDACodeGenerator();
// Generate some code for the model (i.e. 'compile' the model)
try {
mDaeCodeInformation = codeGenerator->generateIDACode(pModel);
// Check that the code generation went fine
checkCodeInformation(mDaeCodeInformation);
} catch (iface::cellml_api::CellMLException &) {
couldNotCompileModelIssue();
} catch (...) {
unexpectedProblemDuringModelCompilationIssue();
}
// Check the outcome of the DAE code generation
if (mIssues.count())
// Something went wrong at some point, so...
resetDaeCodeInformation();
}
//==============================================================================
CellmlModelRuntime * CellmlModelRuntime::update(iface::cellml_api::Model *pModel,
const bool &pValidModel)
{
// Reset the runtime's properties
reset();
// Check that the model is valid
if (pValidModel) {
// The model is valid, so make sure that it's either a 'simple' ODE
// model or a DAE model
// Note #1: in order to do so, we need to get a 'normal' code generator
// (as opposed to an IDA, i.e. DAE, code generator) since if
// the model is correctly constrained, then we can check
// whether some of its equations were flagged as needing a
// Newton-Raphson evaluation, in which case we would be dealing
// with a DAE model...
// Note #2: ideally, there would be a more convenient way to determine
// the type of a model, but well... there isn't, so...
getOdeCodeInformation(pModel);
// Retrieve the model's type
// Note: this can be done by checking whether some equations were
// flagged as needing a Newton-Raphson evaluation...
if (mOdeCodeInformation) {
// An ODE code information could be retrieved, so we can determine
// the model's type
mModelType = mOdeCodeInformation->flaggedEquations()->length()?Dae:Ode;
// If the model is of DAE type, then we must get the 'right' code
// information
if (mModelType == Dae)
getDaeCodeInformation(pModel);
// Retrieve some code
if (mModelType ==Ode) {
qDebug("---------------------------------------");
qDebug("\ninitConstsString():");
qDebug(QString::fromStdWString(mOdeCodeInformation->initConstsString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nratesString():");
qDebug(QString::fromStdWString(mOdeCodeInformation->ratesString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nvariablesString():");
qDebug(QString::fromStdWString(mOdeCodeInformation->variablesString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nfunctionsString():");
qDebug(QString::fromStdWString(mOdeCodeInformation->functionsString()).toLatin1().constData());
qDebug("---------------------------------------");
} else {
qDebug("---------------------------------------");
qDebug("\ninitConstsString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->initConstsString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nratesString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->ratesString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nvariablesString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->variablesString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nfunctionsString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->functionsString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nessentialVariablesString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->essentialVariablesString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nstateInformationString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->stateInformationString()).toLatin1().constData());
qDebug("---------------------------------------");
qDebug("\nrootInformationString():");
qDebug(QString::fromStdWString(mDaeCodeInformation->rootInformationString()).toLatin1().constData());
qDebug("---------------------------------------");
}
} else {
// No ODE code information could be retrieved, so...
mModelType = Undefined;
}
} else {
// The model is not valid, so...
mIssues.append(CellmlModelIssue(CellmlModelIssue::Error,
tr("the model is not valid")));
}
// We are done, so return ourselves
return this;
}
//==============================================================================
} // namespace CellMLSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/* Copyright (c) 2013 Quanta Research Cambridge, Inc
*
* 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.
*/
/*
* Implementation of:
* MP algorithm on pages 7-11 from "Pattern Matching Algorithms" by
* Alberto Apostolico, Zvi Galil, 1997
*
* procedure MP(x, t: string; m, n: integer);
* begin
* i := 1; j := 1;
* while j <= n do begin
* while (i = m + 1) or (i > 0 and x[i] != t[j]) do j := MP_next[i];
* i := i + 1; j := j + 1;
* if i = m + 1 then writeln('x occurs in t at position ', j - i + 1);
* end;
* end;
*
* procedure Compute_borders(x: string; m: integer);
* begin
* Border[0] := -1;
* for i := 1 to m do begin
* j := Border[i - 1];
* while j >= 0 and x[i] != x[j + 1] do j := Border[j];
* Border[i] := j + 1;
* end;
* end;
*
* procedure Compute_MP_next(x: string; m: integer);
* begin
* MP_next[i] := 0; j := 0;
* for i := 1 to m do begin
* { at this point, we have j = MP_next[i] }
* while j > 0 and x[i] != x[j] do j := MP_next[j];
* j := j + 1;
* MP_next[i + 1] := j;
* end;
* end;
*
*/
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <ctime>
#include "StdDmaIndication.h"
#include "StrstrIndicationWrapper.h"
#include "StrstrRequestProxy.h"
#include "GeneratedTypes.h"
#include "DmaConfigProxy.h"
sem_t test_sem;
sem_t setup_sem;
unsigned int sw_match_cnt = 0;
unsigned int hw_match_cnt = 0;
class StrstrIndication : public StrstrIndicationWrapper
{
public:
StrstrIndication(unsigned int id) : StrstrIndicationWrapper(id){};
virtual void setupComplete() {
sem_post(&setup_sem);
}
virtual void searchResult (int v){
fprintf(stderr, "searchResult = %d\n", v);
if (v == -1)
sem_post(&test_sem);
else
hw_match_cnt++;
}
};
void compute_borders(const char *x, int *border, int m)
{
border[0] = -1;
for(int i = 1; i <=m; i++){
int j = border[i-1];
while ((j>=0) && (x[i] != x[j+1]))
j = border[j];
border[i] = j+1;
}
}
void compute_MP_next(const char *x, int *MP_next, int m)
{
MP_next[1] = 0;
int j = 0;
for(int i = 1; i <= m; i++){
while ((j>0) && (x[i] != x[j]))
j = MP_next[j];
j = j+1;
MP_next[i+1] = j;
}
}
void MP(const char *x, const char *t, int *MP_next, int m, int n, int iter_cnt)
{
while(iter_cnt--){
int i = 1;
int j = 1;
fprintf(stderr, "MP starting\n");
while (j <= n) {
while ((i==m+1) || ((i>0) && (x[i-1] != t[j-1]))){
//fprintf(stderr, "char mismatch %d %d MP_next[i]=%d\n", i,j,MP_next[i]);
i = MP_next[i];
}
//fprintf(stderr, " char match %d %d\n", i, j);
i = i+1;
j = j+1;
if (i==m+1){
fprintf(stderr, "%s occurs in t at position %d\n", x, j-i);
i = 1;
sw_match_cnt++;
}
}
}
fprintf(stderr, "MP exiting\n");
}
int main(int argc, const char **argv)
{
StrstrRequestProxy *device = 0;
DmaConfigProxy *dma = 0;
StrstrIndication *deviceIndication = 0;
DmaIndication *dmaIndication = 0;
fprintf(stderr, "%s %s\n", __DATE__, __TIME__);
device = new StrstrRequestProxy(IfcNames_StrstrRequest);
dma = new DmaConfigProxy(IfcNames_DmaConfig);
deviceIndication = new StrstrIndication(IfcNames_StrstrIndication);
dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);
if(sem_init(&test_sem, 1, 0)){
fprintf(stderr, "failed to init test_sem\n");
return -1;
}
if(sem_init(&setup_sem, 1, 0)){
fprintf(stderr, "failed to init setup_sem\n");
return -1;
}
pthread_t tid;
fprintf(stderr, "creating exec thread\n");
if(pthread_create(&tid, NULL, portalExec, NULL)){
fprintf(stderr, "error creating exec thread\n");
exit(1);
}
#ifndef MMAP_HW
if(1){
fprintf(stderr, "simple tests\n");
PortalAlloc *needleAlloc;
PortalAlloc *haystackAlloc;
PortalAlloc *mpNextAlloc;
unsigned int alloc_len = 16 << 2;
dma->alloc(alloc_len, &needleAlloc);
dma->alloc(alloc_len, &mpNextAlloc);
dma->alloc(alloc_len, &haystackAlloc);
char *needle = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, needleAlloc->header.fd, 0);
char *haystack = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, haystackAlloc->header.fd, 0);
int *mpNext = (int *)mmap(0, alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, mpNextAlloc->header.fd, 0);
const char *needle_text = "ababab";
const char *haystack_text = "acabcabacababacababababababcacabcabacababacabababc";
assert(strlen(haystack_text) < alloc_len);
assert(strlen(needle_text)*4 < alloc_len);
strncpy(needle, needle_text, alloc_len);
strncpy(haystack, haystack_text, alloc_len);
int needle_len = strlen(needle);
int haystack_len = strlen(haystack);
int border[needle_len+1];
compute_borders(needle, border, needle_len);
compute_MP_next(needle, mpNext, needle_len);
assert(mpNext[1] == 0);
assert(border[1] == 0);
for(int i = 2; i < needle_len+1; i++)
assert(mpNext[i] == border[i-1]+1);
for(int i = 0; i < needle_len; i++)
fprintf(stderr, "%d %d\n", needle[i], mpNext[i]);
int iter_cnt = 2;
start_timer(0);
MP(needle, haystack, mpNext, needle_len, haystack_len, iter_cnt);
fprintf(stderr, "elapsed time (hw cycles): %lld\n", lap_timer(0));
dma->dCacheFlushInval(needleAlloc, needle);
dma->dCacheFlushInval(mpNextAlloc, mpNext);
unsigned int ref_needleAlloc = dma->reference(needleAlloc);
unsigned int ref_mpNextAlloc = dma->reference(mpNextAlloc);
unsigned int ref_haystackAlloc = dma->reference(haystackAlloc);
device->setup(ref_needleAlloc, ref_mpNextAlloc, needle_len);
sem_wait(&setup_sem);
start_timer(0);
device->search(ref_haystackAlloc, haystack_len, iter_cnt);
sem_wait(&test_sem);
uint64_t cycles = lap_timer(0);
uint64_t beats = dma->show_mem_stats(ChannelType_Read);
fprintf(stderr, "memory read utilization (beats/cycle): %f\n", ((float)beats)/((float)cycles));
close(needleAlloc->header.fd);
close(haystackAlloc->header.fd);
close(mpNextAlloc->header.fd);
}
#endif
#ifdef MMAP_HW
if(1){
fprintf(stderr, "benchmarks\n");
PortalAlloc *needleAlloc;
PortalAlloc *haystackAlloc;
PortalAlloc *mpNextAlloc;
const char *needle_text = "I have control\n";
unsigned int BENCHMARK_INPUT_SIZE = 16 << 18;
unsigned int haystack_alloc_len = BENCHMARK_INPUT_SIZE;
unsigned int needle_alloc_len = strlen(needle_text);
unsigned int mpNext_alloc_len = needle_alloc_len*4;
dma->alloc(needle_alloc_len, &needleAlloc);
dma->alloc(haystack_alloc_len, &haystackAlloc);
dma->alloc(mpNext_alloc_len, &mpNextAlloc);
char *needle = (char *)mmap(0, needle_alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, needleAlloc->header.fd, 0);
char *haystack = (char *)mmap(0, haystack_alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, haystackAlloc->header.fd, 0);
int *mpNext = (int *)mmap(0, mpNext_alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, mpNextAlloc->header.fd, 0);
unsigned int ref_needleAlloc = dma->reference(needleAlloc);
unsigned int ref_haystackAlloc = dma->reference(haystackAlloc);
unsigned int ref_mpNextAlloc = dma->reference(mpNextAlloc);
FILE* fp = fopen("/dev/urandom", "r");
size_t rv = fread(haystack, 1, BENCHMARK_INPUT_SIZE, fp);
strncpy(needle, needle_text, needle_alloc_len);
int needle_len = strlen(needle);
int haystack_len = haystack_alloc_len;
int border[needle_len+1];
compute_borders(needle, border, needle_len);
compute_MP_next(needle, mpNext, needle_len);
assert(mpNext[1] == 0);
assert(border[1] == 0);
for(int i = 2; i < needle_len+1; i++)
assert(mpNext[i] == border[i-1]+1);
int iter_cnt = 32;
start_timer(0);
MP(needle, haystack, mpNext, needle_len, haystack_len, iter_cnt);
uint64_t sw_cycles = lap_timer(0);
fprintf(stderr, "sw_cycles:%zx\n", sw_cycles);
dma->dCacheFlushInval(needleAlloc, needle);
dma->dCacheFlushInval(mpNextAlloc, mpNext);
device->setup(ref_needleAlloc, ref_mpNextAlloc, needle_len);
sem_wait(&setup_sem);
start_timer(0);
device->search(ref_haystackAlloc, haystack_len, iter_cnt);
sem_wait(&test_sem);
uint64_t hw_cycles = lap_timer(0);
uint64_t beats = dma->show_mem_stats(ChannelType_Read);
fprintf(stderr, "memory read utilization (beats/cycle): %f\n", ((float)beats)/((float)hw_cycles));
close(needleAlloc->header.fd);
close(haystackAlloc->header.fd);
close(mpNextAlloc->header.fd);
}
#endif
fprintf(stderr, "sw_match_cnt=%d, hw_match_cnt=%d\n", sw_match_cnt, hw_match_cnt);
return (sw_match_cnt != hw_match_cnt);
}
<commit_msg>updating strstr test<commit_after>/* Copyright (c) 2013 Quanta Research Cambridge, Inc
*
* 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.
*/
/*
* Implementation of:
* MP algorithm on pages 7-11 from "Pattern Matching Algorithms" by
* Alberto Apostolico, Zvi Galil, 1997
*
* procedure MP(x, t: string; m, n: integer);
* begin
* i := 1; j := 1;
* while j <= n do begin
* while (i = m + 1) or (i > 0 and x[i] != t[j]) do j := MP_next[i];
* i := i + 1; j := j + 1;
* if i = m + 1 then writeln('x occurs in t at position ', j - i + 1);
* end;
* end;
*
* procedure Compute_borders(x: string; m: integer);
* begin
* Border[0] := -1;
* for i := 1 to m do begin
* j := Border[i - 1];
* while j >= 0 and x[i] != x[j + 1] do j := Border[j];
* Border[i] := j + 1;
* end;
* end;
*
* procedure Compute_MP_next(x: string; m: integer);
* begin
* MP_next[i] := 0; j := 0;
* for i := 1 to m do begin
* { at this point, we have j = MP_next[i] }
* while j > 0 and x[i] != x[j] do j := MP_next[j];
* j := j + 1;
* MP_next[i + 1] := j;
* end;
* end;
*
*/
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <ctime>
#include "StdDmaIndication.h"
#include "StrstrIndicationWrapper.h"
#include "StrstrRequestProxy.h"
#include "GeneratedTypes.h"
#include "DmaConfigProxy.h"
sem_t test_sem;
sem_t setup_sem;
unsigned int sw_match_cnt = 0;
unsigned int hw_match_cnt = 0;
class StrstrIndication : public StrstrIndicationWrapper
{
public:
StrstrIndication(unsigned int id) : StrstrIndicationWrapper(id){};
virtual void setupComplete() {
sem_post(&setup_sem);
}
virtual void searchResult (int v){
fprintf(stderr, "searchResult = %d\n", v);
if (v == -1)
sem_post(&test_sem);
else
hw_match_cnt++;
}
};
void compute_borders(const char *x, int *border, int m)
{
border[0] = -1;
for(int i = 1; i <=m; i++){
int j = border[i-1];
while ((j>=0) && (x[i] != x[j+1]))
j = border[j];
border[i] = j+1;
}
}
void compute_MP_next(const char *x, int *MP_next, int m)
{
MP_next[1] = 0;
int j = 0;
for(int i = 1; i <= m; i++){
while ((j>0) && (x[i] != x[j]))
j = MP_next[j];
j = j+1;
MP_next[i+1] = j;
}
}
void MP(const char *x, const char *t, int *MP_next, int m, int n, int iter_cnt)
{
while(iter_cnt--){
int i = 1;
int j = 1;
fprintf(stderr, "MP starting\n");
while (j <= n) {
while ((i==m+1) || ((i>0) && (x[i-1] != t[j-1]))){
//fprintf(stderr, "char mismatch %d %d MP_next[i]=%d\n", i,j,MP_next[i]);
i = MP_next[i];
}
//fprintf(stderr, " char match %d %d\n", i, j);
i = i+1;
j = j+1;
if (i==m+1){
fprintf(stderr, "%s occurs in t at position %d\n", x, j-i);
i = 1;
sw_match_cnt++;
}
}
}
fprintf(stderr, "MP exiting\n");
}
int main(int argc, const char **argv)
{
StrstrRequestProxy *device = 0;
DmaConfigProxy *dma = 0;
StrstrIndication *deviceIndication = 0;
DmaIndication *dmaIndication = 0;
fprintf(stderr, "%s %s\n", __DATE__, __TIME__);
device = new StrstrRequestProxy(IfcNames_StrstrRequest);
dma = new DmaConfigProxy(IfcNames_DmaConfig);
deviceIndication = new StrstrIndication(IfcNames_StrstrIndication);
dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);
if(sem_init(&test_sem, 1, 0)){
fprintf(stderr, "failed to init test_sem\n");
return -1;
}
if(sem_init(&setup_sem, 1, 0)){
fprintf(stderr, "failed to init setup_sem\n");
return -1;
}
pthread_t tid;
fprintf(stderr, "creating exec thread\n");
if(pthread_create(&tid, NULL, portalExec, NULL)){
fprintf(stderr, "error creating exec thread\n");
exit(1);
}
if(1){
fprintf(stderr, "simple tests\n");
PortalAlloc *needleAlloc;
PortalAlloc *haystackAlloc;
PortalAlloc *mpNextAlloc;
unsigned int alloc_len = 16 << 2;
dma->alloc(alloc_len, &needleAlloc);
dma->alloc(alloc_len, &mpNextAlloc);
dma->alloc(alloc_len, &haystackAlloc);
char *needle = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, needleAlloc->header.fd, 0);
char *haystack = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, haystackAlloc->header.fd, 0);
int *mpNext = (int *)mmap(0, alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, mpNextAlloc->header.fd, 0);
const char *needle_text = "ababab";
const char *haystack_text = "acabcabacababacababababababcacabcabacababacabababc";
assert(strlen(haystack_text) < alloc_len);
assert(strlen(needle_text)*4 < alloc_len);
strncpy(needle, needle_text, alloc_len);
strncpy(haystack, haystack_text, alloc_len);
int needle_len = strlen(needle);
int haystack_len = strlen(haystack);
int border[needle_len+1];
compute_borders(needle, border, needle_len);
compute_MP_next(needle, mpNext, needle_len);
assert(mpNext[1] == 0);
assert(border[1] == 0);
for(int i = 2; i < needle_len+1; i++)
assert(mpNext[i] == border[i-1]+1);
for(int i = 0; i < needle_len; i++)
fprintf(stderr, "%d %d\n", needle[i], mpNext[i]);
int iter_cnt = 2;
start_timer(0);
MP(needle, haystack, mpNext, needle_len, haystack_len, iter_cnt);
fprintf(stderr, "elapsed time (hw cycles): %lld\n", lap_timer(0));
dma->dCacheFlushInval(needleAlloc, needle);
dma->dCacheFlushInval(mpNextAlloc, mpNext);
unsigned int ref_needleAlloc = dma->reference(needleAlloc);
unsigned int ref_mpNextAlloc = dma->reference(mpNextAlloc);
unsigned int ref_haystackAlloc = dma->reference(haystackAlloc);
device->setup(ref_needleAlloc, ref_mpNextAlloc, needle_len);
sem_wait(&setup_sem);
start_timer(0);
device->search(ref_haystackAlloc, haystack_len, iter_cnt);
sem_wait(&test_sem);
uint64_t cycles = lap_timer(0);
uint64_t beats = dma->show_mem_stats(ChannelType_Read);
fprintf(stderr, "memory read utilization (beats/cycle): %f\n", ((float)beats)/((float)cycles));
close(needleAlloc->header.fd);
close(haystackAlloc->header.fd);
close(mpNextAlloc->header.fd);
}
#ifdef MMAP_HW
if(1){
fprintf(stderr, "benchmarks\n");
PortalAlloc *needleAlloc;
PortalAlloc *haystackAlloc;
PortalAlloc *mpNextAlloc;
const char *needle_text = "I have control\n";
unsigned int BENCHMARK_INPUT_SIZE = 16 << 18;
unsigned int haystack_alloc_len = BENCHMARK_INPUT_SIZE;
unsigned int needle_alloc_len = strlen(needle_text);
unsigned int mpNext_alloc_len = needle_alloc_len*4;
dma->alloc(needle_alloc_len, &needleAlloc);
dma->alloc(haystack_alloc_len, &haystackAlloc);
dma->alloc(mpNext_alloc_len, &mpNextAlloc);
char *needle = (char *)mmap(0, needle_alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, needleAlloc->header.fd, 0);
char *haystack = (char *)mmap(0, haystack_alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, haystackAlloc->header.fd, 0);
int *mpNext = (int *)mmap(0, mpNext_alloc_len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, mpNextAlloc->header.fd, 0);
unsigned int ref_needleAlloc = dma->reference(needleAlloc);
unsigned int ref_haystackAlloc = dma->reference(haystackAlloc);
unsigned int ref_mpNextAlloc = dma->reference(mpNextAlloc);
FILE* fp = fopen("/dev/urandom", "r");
size_t rv = fread(haystack, 1, BENCHMARK_INPUT_SIZE, fp);
strncpy(needle, needle_text, needle_alloc_len);
int needle_len = strlen(needle);
int haystack_len = haystack_alloc_len;
int border[needle_len+1];
compute_borders(needle, border, needle_len);
compute_MP_next(needle, mpNext, needle_len);
assert(mpNext[1] == 0);
assert(border[1] == 0);
for(int i = 2; i < needle_len+1; i++)
assert(mpNext[i] == border[i-1]+1);
int iter_cnt = 8;
start_timer(0);
MP(needle, haystack, mpNext, needle_len, haystack_len, iter_cnt);
uint64_t sw_cycles = lap_timer(0);
fprintf(stderr, "sw_cycles:%zx\n", sw_cycles);
dma->dCacheFlushInval(needleAlloc, needle);
dma->dCacheFlushInval(mpNextAlloc, mpNext);
device->setup(ref_needleAlloc, ref_mpNextAlloc, needle_len);
sem_wait(&setup_sem);
start_timer(0);
device->search(ref_haystackAlloc, haystack_len, iter_cnt);
sem_wait(&test_sem);
uint64_t hw_cycles = lap_timer(0);
uint64_t beats = dma->show_mem_stats(ChannelType_Read);
fprintf(stderr, "memory read utilization (beats/cycle): %f\n", ((float)beats)/((float)hw_cycles));
close(needleAlloc->header.fd);
close(haystackAlloc->header.fd);
close(mpNextAlloc->header.fd);
}
#endif
fprintf(stderr, "sw_match_cnt=%d, hw_match_cnt=%d\n", sw_match_cnt, hw_match_cnt);
return (sw_match_cnt != hw_match_cnt);
}
<|endoftext|>
|
<commit_before>#include "UniformRand.h"
UniformRand::UniformRand(double minValue, double maxValue)
{
setBoundaries(minValue, maxValue);
}
std::string UniformRand::name()
{
return "Uniform(" + toStringWithPrecision(getMinValue()) + ", " + toStringWithPrecision(getMaxValue()) + ")";
}
void UniformRand::setBoundaries(double minValue, double maxValue)
{
a = minValue;
b = maxValue;
/// Sanity check
if (b < a)
SWAP(a, b);
if (a == b)
b = a + 1.0;
c = 1.0 / (b - a);
}
double UniformRand::f(double x) const
{
return (x >= a && x <= b) ? c : 0;
}
double UniformRand::F(double x) const
{
if (x < a)
return 0;
if (x > b)
return 1;
return c * (x - a);
}
double UniformRand::variate() const
{
return a + standardVariate() * (b - a);
}
double UniformRand::variate(double minValue, double maxValue)
{
return minValue + standardVariate() * (maxValue - minValue);
}
double UniformRand::standardVariate()
{
double x;
unsigned long long a = RandGenerator::variate();
a = (a >> 12) | 0x3FF0000000000000ULL; /// Take upper 52 bits
*((unsigned long long *)&x) = a; /// Make a double from bits
return x - 1.0;
}
double UniformRand::Mean() const
{
return .5 * (b + a);
}
double UniformRand::Variance() const
{
return (b - a) * (b - a) / 12;
}
std::complex<double> UniformRand::CF(double t) const
{
std::complex<double> x(0, -t * a), y(0, -t * b);
std::complex<double> numerator = std::exp(x) - std::exp(y);
std::complex<double> denominator(0, t * (b - a));
return numerator / denominator;
}
double UniformRand::Quantile(double p) const
{
if (p < 0 || p > 1)
return NAN;
if (p == 0)
return -INFINITY;
return a + (b - a) * p;
}
double UniformRand::Median() const
{
return .5 * (b + a);
}
double UniformRand::Mode() const
{
/// this can be any value in [a, b]
return variate();
}
double UniformRand::Skewness() const
{
return 0.0;
}
double UniformRand::ExcessKurtosis() const
{
return -1.2;
}
double UniformRand::Entropy() const
{
return (b == a) ? -INFINITY : std::log(b - a);
}
bool UniformRand::fitMax_MLE(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double maxVar = sample.at(0);
for (double var : sample) {
if (var < a)
return false;
maxVar = std::max(var, maxVar);
}
setBoundaries(a, maxVar);
return true;
}
bool UniformRand::fitMin_MLE(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double minVar = sample.at(0);
for (double var : sample) {
if (var > b)
return false;
minVar = std::min(var, minVar);
}
setBoundaries(minVar, b);
return true;
}
bool UniformRand::fit_MLE(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double maxVar = sample.at(0), minVar = maxVar;
for (double var : sample) {
maxVar = std::max(var, maxVar);
minVar = std::min(var, minVar);
}
setBoundaries(minVar, maxVar);
return true;
}
bool UniformRand::fitToData(const QVector<double> &sample)
{
int n = sample.size();
if (n == 0)
return false;
double maxVar = sample.at(0), minVar = maxVar;
for (double var : sample) {
maxVar = std::max(var, maxVar);
minVar = std::min(var, minVar);
}
/// E[min] = b - n / (n + 1) * (b - a)
/// E[max] = (b - a) * n / (n + 1) + a
minVar = (minVar * n - maxVar) / (n - 1.0);
maxVar = (maxVar * (n + 1) - minVar) / n;
setBoundaries(minVar, maxVar);
return true;
}
<commit_msg>Update UniformRand.cpp<commit_after>#include "UniformRand.h"
UniformRand::UniformRand(double minValue, double maxValue)
{
setBoundaries(minValue, maxValue);
}
std::string UniformRand::name()
{
return "Uniform(" + toStringWithPrecision(getMinValue()) + ", " + toStringWithPrecision(getMaxValue()) + ")";
}
void UniformRand::setBoundaries(double minValue, double maxValue)
{
a = minValue;
b = maxValue;
/// Sanity check
if (b < a)
SWAP(a, b);
if (a == b)
b = a + 1.0;
c = 1.0 / (b - a);
}
double UniformRand::f(double x) const
{
return (x >= a && x <= b) ? c : 0;
}
double UniformRand::F(double x) const
{
if (x < a)
return 0;
if (x > b)
return 1;
return c * (x - a);
}
double UniformRand::variate() const
{
return a + standardVariate() * (b - a);
}
double UniformRand::variate(double minValue, double maxValue)
{
return minValue + standardVariate() * (maxValue - minValue);
}
double UniformRand::standardVariate()
{
double x;
unsigned long long a = RandGenerator::variate();
a = (a >> 12) | 0x3FF0000000000000ULL; /// Take upper 52 bits
*((unsigned long long *)&x) = a; /// Make a double from bits
return x - 1.0;
}
double UniformRand::Mean() const
{
return .5 * (b + a);
}
double UniformRand::Variance() const
{
return (b - a) * (b - a) / 12;
}
std::complex<double> UniformRand::CF(double t) const
{
std::complex<double> x(0, -t * a), y(0, -t * b);
std::complex<double> numerator = std::exp(x) - std::exp(y);
std::complex<double> denominator(0, t * (b - a));
return numerator / denominator;
}
double UniformRand::Quantile(double p) const
{
if (p < 0 || p > 1)
return NAN;
if (p == 0)
return -INFINITY;
return a + (b - a) * p;
}
double UniformRand::Median() const
{
return .5 * (b + a);
}
double UniformRand::Mode() const
{
/// this can be any value in [a, b]
return variate();
}
double UniformRand::Skewness() const
{
return 0.0;
}
double UniformRand::ExcessKurtosis() const
{
return -1.2;
}
double UniformRand::Entropy() const
{
return (b == a) ? -INFINITY : std::log(b - a);
}
bool UniformRand::fitMax_MLE(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double maxVar = sample.at(0);
for (double var : sample) {
if (var < a)
return false;
maxVar = std::max(var, maxVar);
}
setBoundaries(a, maxVar);
return true;
}
bool UniformRand::fitMin_MLE(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double minVar = sample.at(0);
for (double var : sample) {
if (var > b)
return false;
minVar = std::min(var, minVar);
}
setBoundaries(minVar, b);
return true;
}
bool UniformRand::fit_MLE(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double maxVar = sample.at(0), minVar = maxVar;
for (double var : sample) {
maxVar = std::max(var, maxVar);
minVar = std::min(var, minVar);
}
setBoundaries(minVar, maxVar);
return true;
}
bool UniformRand::fitMin_UMVU(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double minVar = sample.at(0);
for (double var : sample) {
if (var < a)
return false;
minVar = std::min(var, minVar);
}
/// E[min] = b - n / (n + 1) * (b - a)
minVar = (minVar * (n + 1) - b) / n;
setBoundaries(minVar, b);
return true;
}
bool UniformRand::fitMax_UMVU(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double maxVar = sample.at(0);
for (double var : sample) {
if (var < a)
return false;
maxVar = std::max(var, maxVar);
}
/// E[max] = (b - a) * n / (n + 1) + a
maxVar = (maxVar * (n + 1) - a) / n;
setBoundaries(a, maxVar);
return true;
}
bool UniformRand::fit_UMVU(const QVector<double> &sample)
{
int n = sample.size();
if (n <= 0)
return false;
double maxVar = sample.at(0), minVar = maxVar;
for (double var : sample) {
maxVar = std::max(var, maxVar);
minVar = std::min(var, minVar);
}
/// E[min] = b - n / (n + 1) * (b - a)
/// E[max] = (b - a) * n / (n + 1) + a
minVar = (minVar * n - maxVar) / (n - 1);
maxVar = (maxVar * (n + 1) - minVar) / n;
setBoundaries(minVar, maxVar);
return true;
}
<|endoftext|>
|
<commit_before>#include "cexio.h"
#include "parameters.h"
#include "utils/restapi.h"
#include "utils/base64.h"
#include "unique_json.hpp"
#include "hex_str.hpp"
#include "openssl/sha.h"
#include "openssl/hmac.h"
#include <vector>
#include <iomanip>
#include <array>
#include <chrono>
#include <cmath>
#include <algorithm>
namespace Cexio {
static json_t* authRequest(Parameters &, std::string, std::string);
static RestApi& queryHandle(Parameters ¶ms)
{
static RestApi query ("https://cex.io/api",
params.cacert.c_str(), *params.logFile);
return query;
}
static json_t* checkResponse(std::ostream &logFile, json_t *root)
{
auto errstatus = json_object_get(root, "error");
if (errstatus)
{
auto errmsg = json_dumps(errstatus, JSON_ENCODE_ANY);
logFile << "<Cexio> Error with response: "
<< errmsg << '\n';
free(errmsg);
}
return root;
}
quote_t getQuote(Parameters ¶ms)
{
auto &exchange = queryHandle(params);
unique_json root { exchange.getRequest("/ticker/BTC/USD") };
double bidValue = json_number_value(json_object_get(root.get(), "bid"));
double askValue = json_number_value(json_object_get(root.get(), "ask"));
return std::make_pair(bidValue, askValue);
}
double getAvail(Parameters& params, std::string currency)
{
double available = 0.0;
std::transform(currency.begin(), currency.end(), currency.begin(), ::toupper);
const char * curr_ = currency.c_str();
unique_json root { authRequest(params, "/balance/","") };
const char * avail_str = json_string_value(json_object_get(json_object_get(root.get(), curr_), "available"));
available = avail_str ? atof(avail_str) : 0.0;
return available;
}
std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price)
{
return sendOrder(params, direction, quantity, price);
}
std::string sendShortOrder(Parameters& params, std::string direction, double quantity, double price)
{
return sendOrder(params, direction, quantity, price);
}
std::string sendOrder(Parameters& params, std::string direction, double quantity, double price)
{
using namespace std;
string pair = "btc_usd";
string orderId = "";
*params.logFile << "<Cexio> Trying to send a " << pair << " " << direction << " limit order: " << quantity << "@" << price << endl;
ostringstream oss;
oss << "type=" << direction << "&amount=" << quantity << "&price=" << fixed << setprecision(2) << price;
string options = oss.str();
unique_json root { authRequest(params, "/place_order/BTC/USD/", options) };
auto error = json_string_value(json_object_get(root.get(), "error"));
if (error){
// auto dump = json_dumps(root.get(), 0);
// *params.logFile << "<Cexio> Error placing order: " << dump << ")\n" << endl;
// free(dump);
orderId = "0";
} else {
orderId = json_string_value(json_object_get(root.get(), "id"));
*params.logFile << "<Cexio> Done (order ID): " << orderId << ")\n" << endl;
}
return orderId;
}
bool isOrderComplete(Parameters& params, std::string orderId)
{
using namespace std;
bool tmp = true;
unique_json root { authRequest(params, "/open_orders/","") };
size_t arraySize = json_array_size(root.get());
for (size_t i = 0; i < arraySize; ++i){
string tmpid = json_string_value(json_object_get(json_array_get(root.get(),i),"id"));
if (tmpid.compare(orderId.c_str())==0){
*params.logFile << "<Cexio> Order Still open (ID: " << orderId << " )" << " Remaining: "
<< json_string_value(json_object_get(json_array_get(root.get(),i),"pending"))
<< endl;
return tmp = false;
}
}
if (tmp == true){ *params.logFile << "<Cexio> Order Complete (ID: " << orderId << " )" << endl;}
return tmp;
}
double getActivePos(Parameters& params) { return getAvail(params, "btc"); }
double getLimitPrice(Parameters ¶ms, double volume, bool isBid)
{
auto &exchange = queryHandle(params);
auto root = unique_json(exchange.getRequest("/order_book/BTC/USD/"));
auto branch = json_object_get(root.get(), isBid ? "bids" : "asks");
// loop on volume
double totVol = 0.0;
double currPrice = 0.0;
double currVol = 0.0;
unsigned int i = 0;
// // [[<price>, <volume>], [<price>, <volume>], ...]
for(i = 0; i < (json_array_size(branch)); i++)
{
// volumes are added up until the requested volume is reached
currVol = json_number_value(json_array_get(json_array_get(branch, i), 1));
currPrice = json_number_value(json_array_get(json_array_get(branch, i), 0));
totVol += currVol;
if(totVol >= volume * params.orderBookFactor){
break;
}
}
return currPrice;
}
json_t* authRequest(Parameters ¶ms, std::string request, std::string options)
{
using namespace std;
static uint64_t nonce = time(nullptr) * 4;
auto msg = to_string(++nonce) + params.cexioClientId + params.cexioApi;
uint8_t *digest = HMAC (EVP_sha256(),
params.cexioSecret.c_str(), params.cexioSecret.size(),
reinterpret_cast<const uint8_t *>(msg.data()), msg.size(),
nullptr, nullptr);
string postParams = "key=" + params.cexioApi +
"&signature=" + hex_str<upperhex>(digest, digest + SHA256_DIGEST_LENGTH) +
"&nonce=" + to_string(nonce);
if (!options.empty())
{
postParams += "&";
postParams += options;
}
auto &exchange = queryHandle(params);
return checkResponse(*params.logFile, exchange.postRequest(request, postParams));
}
void testCexio() {
using namespace std;
Parameters params("blackbird.conf");
params.logFile = new ofstream("./test.log" , ofstream::trunc);
string orderId;
cout << "Current value BTC_USD bid: " << getQuote(params).bid() << endl;
cout << "Current value BTC_USD ask: " << getQuote(params).ask() << endl;
cout << "Current balance BTC: " << getAvail(params, "BTC") << endl;
cout << "Current balance BCH: " << getAvail(params, "BCH") << endl;
cout << "Current balance ETH: " << getAvail(params, "ETH") << endl;
cout << "Current balance LTC: " << getAvail(params, "LTC") << endl;
cout << "Current balance DASH: " << getAvail(params, "DASH") << endl;
cout << "Current balance ZEC: " << getAvail(params, "ZEC") << endl;
cout << "Current balance USD: " << getAvail(params, "USD") << endl;
cout << "Current balance EUR: " << getAvail(params, "EUR")<< endl;
cout << "Current balance GBP: " << getAvail(params, "GBP") << endl;
cout << "Current balance RUB: " << getAvail(params, "RUB") << endl;
cout << "Current balance GHS: " << getAvail(params, "GHS") << endl;
cout << "Current bid limit price for 10 units: " << getLimitPrice(params, 10.0, true) << endl;
cout << "Current ask limit price for 10 units: " << getLimitPrice(params, 10.0, false) << endl;
// cout << "Sending buy order - TXID: " ;
// orderId = sendLongOrder(params, "buy", 0.002, 9510);
// cout << orderId << endl;
// cout << "Buy order is complete: " << isOrderComplete(params, orderId) << endl;
// cout << "Active positions (BTC): " << getActivePos(params) << endl;
// cout << "Sending sell order - TXID: " ;
// orderId = sendLongOrder(params, "sell", 0.002, 8800);
// cout << orderId << endl;
// cout << "Sell order is complete: " << isOrderComplete(params, orderId) << endl;
// cout << "Active positions (BTC): " << getActivePos(params) << endl;
// cout << "Sending short order - TXID: " ;
// orderId = sendShortOrder(params, "sell", 0.002, 8800);
// cout << orderId << endl;
// cout << "Sell order is complete: " << isOrderComplete(params, orderId) << endl;
// cout << "Active positions: " << getActivePos(params) << endl;
/******* Cancel order functionality - for testing *******/
// long oId = 0; //Add orderId here
// ostringstream oss;
// oss << "id=" << oId;
// string options = oss.str();
// unique_json root { authRequest(params, "/cancel_order/", options) };
// auto dump = json_dumps(root.get(), 0);
// *params.logFile << "<Cexio> Error canceling order: " << dump << ")\n" << endl;
// free(dump);
/*********************************************************/
}
}
<commit_msg>cex.io<commit_after>#include "cexio.h"
#include "parameters.h"
#include "utils/restapi.h"
#include "utils/base64.h"
#include "unique_json.hpp"
#include "hex_str.hpp"
#include "openssl/sha.h"
#include "openssl/hmac.h"
#include <vector>
#include <iomanip>
#include <array>
#include <chrono>
#include <cmath>
#include <algorithm>
namespace Cexio {
static json_t* authRequest(Parameters &, std::string, std::string);
static bool g_bShort= false;
static RestApi& queryHandle(Parameters ¶ms)
{
static RestApi query ("https://cex.io/api",
params.cacert.c_str(), *params.logFile);
return query;
}
static json_t* checkResponse(std::ostream &logFile, json_t *root)
{
auto errstatus = json_object_get(root, "error");
if (errstatus)
{
auto errmsg = json_dumps(errstatus, JSON_ENCODE_ANY);
logFile << "<Cexio> Error with response: "
<< errmsg << '\n';
free(errmsg);
}
return root;
}
quote_t getQuote(Parameters ¶ms)
{
auto &exchange = queryHandle(params);
unique_json root { exchange.getRequest("/ticker/BTC/USD") };
double bidValue = json_number_value(json_object_get(root.get(), "bid"));
double askValue = json_number_value(json_object_get(root.get(), "ask"));
return std::make_pair(bidValue, askValue);
}
double getAvail(Parameters& params, std::string currency)
{
double available = 0.0;
std::transform(currency.begin(), currency.end(), currency.begin(), ::toupper);
const char * curr_ = currency.c_str();
unique_json root { authRequest(params, "/balance/","") };
const char * avail_str = json_string_value(json_object_get(json_object_get(root.get(), curr_), "available"));
available = avail_str ? atof(avail_str) : 0.0;
return available;
}
std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price)
{
g_bShort = false;
return sendOrder(params, direction, quantity, price);
}
std::string sendShortOrder(Parameters& params, std::string direction, double quantity, double price)
{
//return sendOrder(params, direction, quantity, price);
g_bShort = true;
if(direction.compare("sell") == 0)
{
return openPosition(params, direction, quantity, price);
}else if(direction.compare("buy")== 0){
return closePosition(params);
}
return "0";
}
std::string openPosition(Parameters& params, std::string direction, double quantity, double price)
{
using namespace std;
string pair = "btc_usd";
string orderId = "";
*params.logFile << "<Cexio> Trying to open a " << pair << " " << direction << " position: " << quantity << "@" << price << endl;
ostringstream oss;
string ptype = "";
if(direction.compare("sell") == 0)
{
ptype = "short";
}else if(direction.compare("buy")== 0){
ptype = "long";
}
oss << "symbol=" << "BTC" << "&amount=" << setprecision(8) << quantity << "&msymbol=" << "USD" << "&leverage="
<< "3" << "&ptype=" << ptype << "&anySlipppage=" << "true" << "&eoprice=" << setprecision(8) << price << "&stopLossPrice=" << "35000";
string options = oss.str();
unique_json root {authRequest(params,"open_position/BTC/USD/",options)};
auto error = json_string_value(json_object_get(root.get(),"error"));
if(error){
orderId = "0";
}else{
orderId = json_string_value(json_object_get(root.get(),"id"));
*params.logFile << "<Cexio>Open Position Done (positon ID): " << orderId << ")\n" << endl;
}
return orderId;
}
std::string closePosition(Parameters& params)
{
using namespace std;
string orderId = "";
unique_json root {authRequest(params,"/open_positions/BTC/USD/","")};
size_t arraySize = json_array_size(json_object_get(root.get(),"data"));
auto data = json_object_get(root.get(),"data");
for(size_t i=0; i< arraySize;i++){
std::string tmpId = json_string_value(json_object_get(json_array_get(data,i),"id"));
ostringstream oss;
oss << "id=" << tmpId;
string options = oss.str();
unique_json root1 {authRequest(params,"close_position/BTC/USD/",options)};
auto error = json_string_value(json_object_get(root1.get(),"error"));
if(error){
orderId ="0";
}else{
orderId = json_string_value(json_object_get(root1.get(),"id"));
}
}
return orderId;
}
std::string sendOrder(Parameters& params, std::string direction, double quantity, double price)
{
using namespace std;
string pair = "btc_usd";
string orderId = "";
*params.logFile << "<Cexio> Trying to send a " << pair << " " << direction << " limit order: " << quantity << "@" << price << endl;
ostringstream oss;
oss << "type=" << direction << "&amount=" << quantity << "&price=" << fixed << setprecision(2) << price;
string options = oss.str();
unique_json root { authRequest(params, "/place_order/BTC/USD/", options) };
auto error = json_string_value(json_object_get(root.get(), "error"));
if (error){
// auto dump = json_dumps(root.get(), 0);
// *params.logFile << "<Cexio> Error placing order: " << dump << ")\n" << endl;
// free(dump);
orderId = "0";
} else {
orderId = json_string_value(json_object_get(root.get(), "id"));
*params.logFile << "<Cexio> Done (order ID): " << orderId << ")\n" << endl;
}
return orderId;
}
bool isOrderComplete(Parameters& params, std::string orderId)
{
using namespace std;
if (orderId == "0") return false;
auto oId = stol(orderId);
ostringstream oss;
oss << "id=" << oId;
string options = oss.str();
if(g_bShort)
{
unique_json root { authRequest(params, "/get_position/", options) };
auto slremains = atof(json_string_value(json_object_get(root.get(), "slremains")));
if (slremains==0){
return true;
} else {
auto dump = json_dumps(root.get(), 0);
*params.logFile << "<Cexio> Position Order Not Complete: " << dump << ")\n" << endl;
free(dump);
// cout << "REMAINS:" << remains << endl;
return false;
}
}else{
unique_json root { authRequest(params, "/get_order/", options) };
auto remains = atof(json_string_value(json_object_get(root.get(), "remains")));
if (remains==0){
return true;
} else {
auto dump = json_dumps(root.get(), 0);
*params.logFile << "<Cexio> Order Not Complete: " << dump << ")\n" << endl;
free(dump);
// cout << "REMAINS:" << remains << endl;
return false;
}
}
}
double getActivePos(Parameters& params) { return getAvail(params, "btc"); }
double getLimitPrice(Parameters ¶ms, double volume, bool isBid)
{
auto &exchange = queryHandle(params);
auto root = unique_json(exchange.getRequest("/order_book/BTC/USD/"));
auto branch = json_object_get(root.get(), isBid ? "bids" : "asks");
// loop on volume
double totVol = 0.0;
double currPrice = 0.0;
double currVol = 0.0;
unsigned int i = 0;
// // [[<price>, <volume>], [<price>, <volume>], ...]
for(i = 0; i < (json_array_size(branch)); i++)
{
// volumes are added up until the requested volume is reached
currVol = json_number_value(json_array_get(json_array_get(branch, i), 1));
currPrice = json_number_value(json_array_get(json_array_get(branch, i), 0));
totVol += currVol;
if(totVol >= volume * params.orderBookFactor){
break;
}
}
return currPrice;
}
json_t* authRequest(Parameters ¶ms, std::string request, std::string options)
{
using namespace std;
static uint64_t nonce = time(nullptr) * 4;
auto msg = to_string(++nonce) + params.cexioClientId + params.cexioApi;
uint8_t *digest = HMAC (EVP_sha256(),
params.cexioSecret.c_str(), params.cexioSecret.size(),
reinterpret_cast<const uint8_t *>(msg.data()), msg.size(),
nullptr, nullptr);
string postParams = "key=" + params.cexioApi +
"&signature=" + hex_str<upperhex>(digest, digest + SHA256_DIGEST_LENGTH) +
"&nonce=" + to_string(nonce);
if (!options.empty())
{
postParams += "&";
postParams += options;
}
auto &exchange = queryHandle(params);
return checkResponse(*params.logFile, exchange.postRequest(request, postParams));
}
void testCexio() {
using namespace std;
Parameters params("blackbird.conf");
params.logFile = new ofstream("./test.log" , ofstream::trunc);
string orderId;
cout << "Current value BTC_USD bid: " << getQuote(params).bid() << endl;
cout << "Current value BTC_USD ask: " << getQuote(params).ask() << endl;
cout << "Current balance BTC: " << getAvail(params, "BTC") << endl;
cout << "Current balance BCH: " << getAvail(params, "BCH") << endl;
cout << "Current balance ETH: " << getAvail(params, "ETH") << endl;
cout << "Current balance LTC: " << getAvail(params, "LTC") << endl;
cout << "Current balance DASH: " << getAvail(params, "DASH") << endl;
cout << "Current balance ZEC: " << getAvail(params, "ZEC") << endl;
cout << "Current balance USD: " << getAvail(params, "USD") << endl;
cout << "Current balance EUR: " << getAvail(params, "EUR")<< endl;
cout << "Current balance GBP: " << getAvail(params, "GBP") << endl;
cout << "Current balance RUB: " << getAvail(params, "RUB") << endl;
cout << "Current balance GHS: " << getAvail(params, "GHS") << endl;
cout << "Current bid limit price for 10 units: " << getLimitPrice(params, 10.0, true) << endl;
cout << "Current ask limit price for 10 units: " << getLimitPrice(params, 10.0, false) << endl;
// cout << "Sending buy order - TXID: " ;
// orderId = sendLongOrder(params, "buy", 0.002, 9510);
// cout << orderId << endl;
// cout << "Buy order is complete: " << isOrderComplete(params, orderId) << endl;
// cout << "Active positions (BTC): " << getActivePos(params) << endl;
// cout << "Sending sell order - TXID: " ;
// orderId = sendLongOrder(params, "sell", 0.002, 8800);
// cout << orderId << endl;
// cout << "Sell order is complete: " << isOrderComplete(params, orderId) << endl;
// cout << "Active positions (BTC): " << getActivePos(params) << endl;
// cout << "Sending short order - TXID: " ;
// orderId = sendShortOrder(params, "sell", 0.002, 8800);
// cout << orderId << endl;
// cout << "Sell order is complete: " << isOrderComplete(params, orderId) << endl;
// cout << "Active positions: " << getActivePos(params) << endl;
/******* Cancel order functionality - for testing *******/
// long oId = 0; //Add orderId here
// ostringstream oss;
// oss << "id=" << oId;
// string options = oss.str();
// unique_json root { authRequest(params, "/cancel_order/", options) };
// auto dump = json_dumps(root.get(), 0);
// *params.logFile << "<Cexio> Error canceling order: " << dump << ")\n" << endl;
// free(dump);
/*********************************************************/
}
}
<|endoftext|>
|
<commit_before>/**
* Run SDC for the van der Pol oscillator.
*
*/
#include<pfasst.hpp>
#include<pfasst/sdc.hpp>
#include<pfasst/encap/vector.hpp>
#include "vdp_sweeper.hpp"
double run_vdp_sdc(const size_t nsteps, const double dt, const size_t nnodes,
const size_t niters, const double nu, const double x0,
const double y0, const pfasst::quadrature::QuadratureType nodetype)
{
pfasst::SDC<> sdc;
auto quad = pfasst::quadrature::quadrature_factory(nnodes, nodetype);
// van der Pol oscillator (as first order system) has two components
auto factory = make_shared<pfasst::encap::VectorFactory<double>>(2);
// input is parameter nu and initial values for position and velocity
auto sweeper = make_shared<VdpSweeper<>>(nu, x0, y0);
sweeper->set_quadrature(quad);
sweeper->set_factory(factory);
sdc.add_level(sweeper);
// Final time Tend = dt*nsteps
sdc.set_duration(0.0, dt*nsteps, dt, niters);
sdc.setup();
auto q0 = sweeper->get_state(0);
sweeper->exact(q0, 0.0);
sdc.run();
return sweeper->get_errors();
}
#ifndef PFASST_UNIT_TESTING
/**
* Main routine running the scalar example with a preset parameters
*/
int main(int /*argc*/, char** /*argv*/)
{
const double x0 = 2.0,
y0 = 0.0;
const size_t nsteps = 1000;
const double dt = 50.0/( (double) nsteps);
const size_t nnodes = 3;
const size_t niters = 1;
const double nu = 5.0;
const pfasst::quadrature::QuadratureType nodetype = pfasst::quadrature::QuadratureType::GaussLegendre;
std::cout << "Used timestep: " << dt << std::endl;
run_vdp_sdc(nsteps, dt, nnodes, niters, nu, x0, y0, nodetype);
}
#endif
<commit_msg>vdp: Fix initial condition.<commit_after>/**
* Run SDC for the van der Pol oscillator.
*
*/
#include<pfasst.hpp>
#include<pfasst/sdc.hpp>
#include<pfasst/encap/vector.hpp>
#include "vdp_sweeper.hpp"
double run_vdp_sdc(const size_t nsteps, const double dt, const size_t nnodes,
const size_t niters, const double nu, const double x0,
const double y0, const pfasst::quadrature::QuadratureType nodetype)
{
pfasst::SDC<> sdc;
auto quad = pfasst::quadrature::quadrature_factory(nnodes, nodetype);
// van der Pol oscillator (as first order system) has two components
auto factory = make_shared<pfasst::encap::VectorFactory<double>>(2);
// input is parameter nu and initial values for position and velocity
auto sweeper = make_shared<VdpSweeper<>>(nu, x0, y0);
sweeper->set_quadrature(quad);
sweeper->set_factory(factory);
sdc.add_level(sweeper);
// Final time Tend = dt*nsteps
sdc.set_duration(0.0, dt*nsteps, dt, niters);
sdc.setup();
auto q0 = sweeper->get_start_state();
sweeper->exact(q0, 0.0);
sdc.run();
return sweeper->get_errors();
}
#ifndef PFASST_UNIT_TESTING
/**
* Main routine running the scalar example with a preset parameters
*/
int main(int /*argc*/, char** /*argv*/)
{
const double x0 = 2.0,
y0 = 0.0;
const size_t nsteps = 1000;
const double dt = 50.0/( (double) nsteps);
const size_t nnodes = 3;
const size_t niters = 1;
const double nu = 5.0;
const pfasst::quadrature::QuadratureType nodetype = pfasst::quadrature::QuadratureType::GaussLegendre;
std::cout << "Used timestep: " << dt << std::endl;
run_vdp_sdc(nsteps, dt, nnodes, niters, nu, x0, y0, nodetype);
}
#endif
<|endoftext|>
|
<commit_before>// File: gaussian.hh
// Date: Sat May 04 01:33:12 2013 +0800
// Author: Yuxin Wu <ppwwyyxxc@gmail.com>
#pragma once
#include <memory>
#include <vector>
#include "lib/mat.h"
#include "lib/utils.hh"
#include "lib/timer.hh"
#include "common/common.hh"
namespace pano {
class GaussCache {
public:
std::unique_ptr<float, std::default_delete<float[]>> kernel_buf;
float* kernel;
int kw;
GaussCache(float sigma);
};
class GaussianBlur {
float sigma;
GaussCache gcache;
public:
GaussianBlur(float sigma): sigma(sigma), gcache(sigma) {}
// TODO faster convolution
template <typename T>
Mat<T> blur(const Mat<T>& img) const {
m_assert(img.channels() == 1);
TotalTimer tm("gaussianblur");
const int w = img.width(), h = img.height();
Mat<T> ret(h, w, img.channels());
const int kw = gcache.kw;
const int center = kw / 2;
float * kernel = gcache.kernel;
std::vector<T> cur_line_mem(center * 2 + std::max(w, h), 0);
T *cur_line = cur_line_mem.data() + center;
// apply to columns
REP(j, w){
const T* src = img.ptr(0, j);
// copy a column of src
REP(i, h) {
cur_line[i] = *src;
src += w;
}
// pad the border with border value
T v0 = cur_line[0];
for (int i = 1; i <= center; i ++)
cur_line[-i] = v0;
v0 = cur_line[h - 1];
for (int i = 0; i < center; i ++)
cur_line[h + i] = v0;
T *dest = ret.ptr(0, j);
REP(i, h) {
T tmp{0};
for (int k = -center; k <= center; k ++)
tmp += cur_line[i + k] * kernel[k];
*dest = tmp;
dest += w;
}
}
// apply to rows
REP(i, h) {
T *dest = ret.ptr(i);
memcpy(cur_line, dest, sizeof(T) * w);
{ // pad the border
T v0 = cur_line[0];
for (int j = 1; j <= center; j ++)
cur_line[-j] = v0;
v0 = cur_line[w - 1];
for (int j = 0; j < center; j ++)
cur_line[center + j] = v0;
}
REP(j, w) {
T tmp{0};
for (int k = -center; k <= center; k ++)
tmp += cur_line[j + k] * kernel[k];
*(dest ++) = tmp;
}
}
return ret;
}
};
class MultiScaleGaussianBlur {
std::vector<GaussianBlur> gauss; // size = nscale - 1
public:
MultiScaleGaussianBlur(
int nscale, float gauss_sigma,
float scale_factor) {
REP(k, nscale - 1) {
gauss.emplace_back(gauss_sigma);
gauss_sigma *= scale_factor;
}
}
Mat32f blur(const Mat32f& img, int n) const
{ return gauss[n - 1].blur(img); }
};
}
<commit_msg>fix padding in gaussian blur (fix #52)<commit_after>// File: gaussian.hh
// Date: Wed Nov 22 14:38:30 2017 +0800
// Author: Yuxin Wu <ppwwyyxxc@gmail.com>
#pragma once
#include <memory>
#include <vector>
#include "lib/mat.h"
#include "lib/utils.hh"
#include "lib/timer.hh"
#include "common/common.hh"
namespace pano {
class GaussCache {
public:
std::unique_ptr<float, std::default_delete<float[]>> kernel_buf;
float* kernel;
int kw;
GaussCache(float sigma);
};
class GaussianBlur {
float sigma;
GaussCache gcache;
public:
GaussianBlur(float sigma): sigma(sigma), gcache(sigma) {}
// TODO faster convolution
template <typename T>
Mat<T> blur(const Mat<T>& img) const {
m_assert(img.channels() == 1);
TotalTimer tm("gaussianblur");
const int w = img.width(), h = img.height();
Mat<T> ret(h, w, img.channels());
const int kw = gcache.kw;
const int center = kw / 2;
float * kernel = gcache.kernel;
std::vector<T> cur_line_mem(center * 2 + std::max(w, h), 0);
T *cur_line = cur_line_mem.data() + center;
// apply to columns
REP(j, w){
const T* src = img.ptr(0, j);
// copy a column of src
REP(i, h) {
cur_line[i] = *src;
src += w;
}
// pad the border with border value
T v0 = cur_line[0];
for (int i = 1; i <= center; i ++)
cur_line[-i] = v0;
v0 = cur_line[h - 1];
for (int i = 0; i < center; i ++)
cur_line[h + i] = v0;
T *dest = ret.ptr(0, j);
REP(i, h) {
T tmp{0};
for (int k = -center; k <= center; k ++)
tmp += cur_line[i + k] * kernel[k];
*dest = tmp;
dest += w;
}
}
// apply to rows
REP(i, h) {
T *dest = ret.ptr(i);
memcpy(cur_line, dest, sizeof(T) * w);
{ // pad the border
T v0 = cur_line[0];
for (int j = 1; j <= center; j ++)
cur_line[-j] = v0;
v0 = cur_line[w - 1];
for (int j = 0; j < center; j ++)
cur_line[w + j] = v0;
}
REP(j, w) {
T tmp{0};
for (int k = -center; k <= center; k ++)
tmp += cur_line[j + k] * kernel[k];
*(dest ++) = tmp;
}
}
return ret;
}
};
class MultiScaleGaussianBlur {
std::vector<GaussianBlur> gauss; // size = nscale - 1
public:
MultiScaleGaussianBlur(
int nscale, float gauss_sigma,
float scale_factor) {
REP(k, nscale - 1) {
gauss.emplace_back(gauss_sigma);
gauss_sigma *= scale_factor;
}
}
Mat32f blur(const Mat32f& img, int n) const
{ return gauss[n - 1].blur(img); }
};
}
<|endoftext|>
|
<commit_before>#include "shape/solid.h"
VALUE sr_cSolid;
SR_SHAPE_GET(Solid, solid)
SR_SHAPE_CHECK(Solid, solid)
bool siren_solid_install()
{
SR_SHAPE_INIT(Solid)
rb_define_method(sr_cSolid, "initialize", RUBY_METHOD_FUNC(siren_solid_init), -1);
rb_define_singleton_method(sr_cSolid, "box", RUBY_METHOD_FUNC(siren_solid_box), -1);
rb_define_singleton_method(sr_cSolid, "box2p", RUBY_METHOD_FUNC(siren_solid_box2p), -1);
rb_define_singleton_method(sr_cSolid, "boxax", RUBY_METHOD_FUNC(siren_solid_boxax), -1);
rb_define_singleton_method(sr_cSolid, "sphere", RUBY_METHOD_FUNC(siren_solid_sphere), -1);
rb_define_singleton_method(sr_cSolid, "cylinder", RUBY_METHOD_FUNC(siren_solid_cylinder), -1);
rb_define_singleton_method(sr_cSolid, "cone", RUBY_METHOD_FUNC(siren_solid_cone), -1);
rb_define_singleton_method(sr_cSolid, "torus", RUBY_METHOD_FUNC(siren_solid_torus), -1);
rb_define_singleton_method(sr_cSolid, "halfspace", RUBY_METHOD_FUNC(siren_solid_halfspace), -1);
rb_define_singleton_method(sr_cSolid, "prism", RUBY_METHOD_FUNC(siren_solid_prism), -1);
rb_define_singleton_method(sr_cSolid, "revol", RUBY_METHOD_FUNC(siren_solid_revol), -1);
rb_define_singleton_method(sr_cSolid, "revolution", RUBY_METHOD_FUNC(siren_solid_revolution), -1);
rb_define_singleton_method(sr_cSolid, "wedge", RUBY_METHOD_FUNC(siren_solid_wedge), -1);
return true;
}
VALUE siren_solid_init(int argc, VALUE* argv, VALUE self)
{
VALUE* a;
rb_scan_args(argc, argv, "1", &a);
int len = RARRAY_LEN(a);
if (argc == 0 || len == 0) {
rb_raise(Qnil, "No shapes specified.");
}
BRepBuilderAPI_MakeSolid solid_maker;
for (int i = 0; i < len; i++) {
TopoDS_Shell shell = siren_shell_get(a[i]);
solid_maker.Add(shell);
}
if (!solid_maker.IsDone()) {
rb_raise(Qnil, "Failed to make a Solid.");
}
TopoDS_Shape shape = solid_maker.Shape();
if (shape.IsNull()) {
rb_raise(Qnil, "Failed to make a Solid.");
}
auto p = siren_shape_get(self);
*p = shape;
return self;
}
VALUE siren_solid_box(int argc, VALUE* argv, VALUE self)
{
VALUE size, pos;
rb_scan_args(argc, argv, "02", &size, &pos);
Standard_Real sx, sy, sz;
if (argc >= 1) {
siren_ary_to_xyz(size, sx, sy, sz);
}
else {
sx = 1.0; sy = 1.0; sz = 1.0;
}
gp_Pnt op;
if (argc >= 2) {
Standard_Real px, py, pz;
siren_ary_to_xyz(pos, px, py, pz);
op = gp_Pnt(px, py, pz);
}
else {
op = gp_Pnt(0., 0., 0.);
}
if (std::fabs(sx * sy * sz) == 0.0) {
rb_raise(Qnil,
"Failed to make solid. Incorrect size specified.");
}
BRepPrimAPI_MakeBox api(op, sx, sy, sz);
return siren_shape_new(api.Shape());
}
VALUE siren_solid_box2p(int argc, VALUE* argv, VALUE self)
{
VALUE p1, p2;
rb_scan_args(argc, argv, "02", &p1, &p2);
Standard_Real x1 = 0.0, y1 = 0.0, z1 = 0.0;
Standard_Real x2 = 1.0, y2 = 1.0, z2 = 1.0;
if (argc >= 1) {
siren_ary_to_xyz(p1, x1, y1, z1);
}
if (argc >= 2) {
siren_ary_to_xyz(p2, x2, y2, z2);
}
gp_Pnt point1(x1, x1, x1);
gp_Pnt point2(x2, x2, x2);
BRepPrimAPI_MakeBox api(point1, point2);
return siren_shape_new(api.Shape());
}
VALUE siren_solid_boxax(int argc, VALUE* argv, VALUE self)
{
VALUE size, pos, dir;
rb_scan_args(argc, argv, "3", &size, &pos, &dir);
Standard_Real sx, sy, sz;
siren_ary_to_xyz(size, sx, sy, sz);
Standard_Real px, py, pz;
siren_ary_to_xyz(pos, px, py, pz);
Standard_Real dx, dy, dz;
siren_ary_to_xyz(dir, dx, dy, dz);
gp_Ax2 ax(gp_Pnt(px, py, pz), gp_Dir(dx, dy, dz));
BRepPrimAPI_MakeBox api(ax, sx, sy, sz);
return siren_shape_new(api.Shape());
}
VALUE siren_solid_sphere(int argc, VALUE* argv, VALUE self)
{
VALUE r = 1.0;
VALUE pos;
rb_scan_args(argc, argv, "02", &r, &pos);
siren_numeric_check(r);
gp_Pnt op;
if (argc == 2) {
Standard_Real px, py, pz;
siren_ary_to_xyz(pos, px, py, pz);
op = gp_Pnt(px, py, pz);
}
else {
op = gp_Pnt(0., 0., 0.);
}
if (NUM2DBL(r) < 0) {
rb_raise(Qnil, "Failed to make solid."
" Specified radius value below 0.");
}
BRepPrimAPI_MakeSphere api(op, NUM2DBL(r));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_cylinder(int argc, VALUE* argv, VALUE self)
{
VALUE pos, norm;
VALUE r, h, a;
rb_scan_args(argc, argv, "5", &pos, &norm, &r, &h, &a);
siren_numeric_check(r);
siren_numeric_check(h);
siren_numeric_check(a);
gp_Ax2 ax = siren_ary_to_ax2(pos, norm);
BRepPrimAPI_MakeCylinder api(ax, NUM2DBL(r), NUM2DBL(h), NUM2DBL(a));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_cone(int argc, VALUE* argv, VALUE self)
{
VALUE pos, norm;
VALUE r1, r2, h, ang;
rb_scan_args(argc, argv, "6", &pos, &norm, &r1, &r2, &h, &ang);
siren_numeric_check(r1);
siren_numeric_check(r2);
siren_numeric_check(h);
siren_numeric_check(ang);
gp_Ax2 ax = siren_ary_to_ax2(pos, norm);
BRepPrimAPI_MakeCone api(ax, NUM2DBL(r1), NUM2DBL(r2), NUM2DBL(h), NUM2DBL(ang));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_torus(int argc, VALUE* argv, VALUE self)
{
VALUE r1, r2, ang;
VALUE pos, norm;
rb_scan_args(argc, argv, "5", &pos, &norm, &r1, &r2, &ang);
siren_numeric_check(r1);
siren_numeric_check(r2);
siren_numeric_check(ang);
gp_Ax2 ax = siren_ary_to_ax2(pos, norm);
BRepPrimAPI_MakeTorus api(ax, NUM2DBL(r1), NUM2DBL(r2), NUM2DBL(ang));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_halfspace(int argc, VALUE* argv, VALUE self)
{
VALUE surf, refpnt;
rb_scan_args(argc, argv, "2", &surf, &refpnt);
siren_shape_check(surf);
TopoDS_Shape* shape = siren_shape_get(surf);
TopoDS_Solid solid;
gp_Pnt pnt = siren_ary_to_pnt(refpnt);
if (shape->ShapeType() == TopAbs_FACE) {
solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Face(*shape), pnt);
}
else if (shape->ShapeType() == TopAbs_SHELL) {
solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Shell(*shape), pnt);
}
else {
rb_raise(Qnil, "Specified shape type is not FACE or SHELL.");
}
return siren_shape_new(solid);
}
VALUE siren_solid_prism(int argc, VALUE* argv, VALUE self)
{
rb_raise(Qnil, "Not implemented.");
return Qnil;
}
VALUE siren_solid_revol(int argc, VALUE* argv, VALUE self)
{
rb_raise(Qnil, "Not implemented.");
return Qnil;
}
VALUE siren_solid_revolution(int argc, VALUE* argv, VALUE self)
{
rb_raise(Qnil, "Not implemented.");
return Qnil;
}
VALUE siren_solid_wedge(int argc, VALUE* argv, VALUE self)
{
VALUE dx = DBL2NUM(1.0), dy = DBL2NUM(1.0), dz = DBL2NUM(1.0),
x = DBL2NUM(0.5), z = DBL2NUM(0.5), X = DBL2NUM(0.5), Z = DBL2NUM(0.5);
rb_scan_args(argc, argv, "07", &dx, &dy, &dz, &x, &z, &X, &Z);
try {
BRepPrimAPI_MakeWedge api(NUM2DBL(dx), NUM2DBL(dy), NUM2DBL(dz),
NUM2DBL(x), NUM2DBL(z), NUM2DBL(X), NUM2DBL(Z));
TopoDS_Shape s = api.Shape();
return siren_shape_new(s);
}
catch (...) {
rb_raise(Qnil, "Failed to make a wedge.");
}
return Qnil;
}
<commit_msg>Update Siren::Solid.initialize method.<commit_after>#include "shape/solid.h"
VALUE sr_cSolid;
SR_SHAPE_GET(Solid, solid)
SR_SHAPE_CHECK(Solid, solid)
bool siren_solid_install()
{
SR_SHAPE_INIT(Solid)
rb_define_method(sr_cSolid, "initialize", RUBY_METHOD_FUNC(siren_solid_init), -1);
rb_define_singleton_method(sr_cSolid, "box", RUBY_METHOD_FUNC(siren_solid_box), -1);
rb_define_singleton_method(sr_cSolid, "box2p", RUBY_METHOD_FUNC(siren_solid_box2p), -1);
rb_define_singleton_method(sr_cSolid, "boxax", RUBY_METHOD_FUNC(siren_solid_boxax), -1);
rb_define_singleton_method(sr_cSolid, "sphere", RUBY_METHOD_FUNC(siren_solid_sphere), -1);
rb_define_singleton_method(sr_cSolid, "cylinder", RUBY_METHOD_FUNC(siren_solid_cylinder), -1);
rb_define_singleton_method(sr_cSolid, "cone", RUBY_METHOD_FUNC(siren_solid_cone), -1);
rb_define_singleton_method(sr_cSolid, "torus", RUBY_METHOD_FUNC(siren_solid_torus), -1);
rb_define_singleton_method(sr_cSolid, "halfspace", RUBY_METHOD_FUNC(siren_solid_halfspace), -1);
rb_define_singleton_method(sr_cSolid, "prism", RUBY_METHOD_FUNC(siren_solid_prism), -1);
rb_define_singleton_method(sr_cSolid, "revol", RUBY_METHOD_FUNC(siren_solid_revol), -1);
rb_define_singleton_method(sr_cSolid, "revolution", RUBY_METHOD_FUNC(siren_solid_revolution), -1);
rb_define_singleton_method(sr_cSolid, "wedge", RUBY_METHOD_FUNC(siren_solid_wedge), -1);
return true;
}
VALUE siren_solid_init(int argc, VALUE* argv, VALUE self)
{
VALUE a;
rb_scan_args(argc, argv, "*", &a);
auto b = rb_funcall(a, rb_intern("flatten"), 0);
BRepBuilderAPI_MakeSolid solid_maker;
for (int i = 0; i < RARRAY_LEN(b); i++) {
auto item = RARRAY_AREF(b, i);
if (siren_shell_p(item)) {
TopoDS_Shell shell = siren_shell_get(item);
solid_maker.Add(shell);
}
}
if (!solid_maker.IsDone()) {
rb_raise(Qnil, "Failed to make a Solid.");
}
TopoDS_Shape shape = solid_maker.Shape();
if (shape.IsNull()) {
rb_raise(Qnil, "Failed to make a Solid.");
}
auto p = siren_shape_get(self);
*p = shape;
return self;
}
VALUE siren_solid_box(int argc, VALUE* argv, VALUE self)
{
VALUE size, pos;
rb_scan_args(argc, argv, "02", &size, &pos);
Standard_Real sx, sy, sz;
if (argc >= 1) {
siren_ary_to_xyz(size, sx, sy, sz);
}
else {
sx = 1.0; sy = 1.0; sz = 1.0;
}
gp_Pnt op;
if (argc >= 2) {
Standard_Real px, py, pz;
siren_ary_to_xyz(pos, px, py, pz);
op = gp_Pnt(px, py, pz);
}
else {
op = gp_Pnt(0., 0., 0.);
}
if (std::fabs(sx * sy * sz) == 0.0) {
rb_raise(Qnil,
"Failed to make solid. Incorrect size specified.");
}
BRepPrimAPI_MakeBox api(op, sx, sy, sz);
return siren_shape_new(api.Shape());
}
VALUE siren_solid_box2p(int argc, VALUE* argv, VALUE self)
{
VALUE p1, p2;
rb_scan_args(argc, argv, "02", &p1, &p2);
Standard_Real x1 = 0.0, y1 = 0.0, z1 = 0.0;
Standard_Real x2 = 1.0, y2 = 1.0, z2 = 1.0;
if (argc >= 1) {
siren_ary_to_xyz(p1, x1, y1, z1);
}
if (argc >= 2) {
siren_ary_to_xyz(p2, x2, y2, z2);
}
gp_Pnt point1(x1, x1, x1);
gp_Pnt point2(x2, x2, x2);
BRepPrimAPI_MakeBox api(point1, point2);
return siren_shape_new(api.Shape());
}
VALUE siren_solid_boxax(int argc, VALUE* argv, VALUE self)
{
VALUE size, pos, dir;
rb_scan_args(argc, argv, "3", &size, &pos, &dir);
Standard_Real sx, sy, sz;
siren_ary_to_xyz(size, sx, sy, sz);
Standard_Real px, py, pz;
siren_ary_to_xyz(pos, px, py, pz);
Standard_Real dx, dy, dz;
siren_ary_to_xyz(dir, dx, dy, dz);
gp_Ax2 ax(gp_Pnt(px, py, pz), gp_Dir(dx, dy, dz));
BRepPrimAPI_MakeBox api(ax, sx, sy, sz);
return siren_shape_new(api.Shape());
}
VALUE siren_solid_sphere(int argc, VALUE* argv, VALUE self)
{
VALUE r = 1.0;
VALUE pos;
rb_scan_args(argc, argv, "02", &r, &pos);
siren_numeric_check(r);
gp_Pnt op;
if (argc == 2) {
Standard_Real px, py, pz;
siren_ary_to_xyz(pos, px, py, pz);
op = gp_Pnt(px, py, pz);
}
else {
op = gp_Pnt(0., 0., 0.);
}
if (NUM2DBL(r) < 0) {
rb_raise(Qnil, "Failed to make solid."
" Specified radius value below 0.");
}
BRepPrimAPI_MakeSphere api(op, NUM2DBL(r));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_cylinder(int argc, VALUE* argv, VALUE self)
{
VALUE pos, norm;
VALUE r, h, a;
rb_scan_args(argc, argv, "5", &pos, &norm, &r, &h, &a);
siren_numeric_check(r);
siren_numeric_check(h);
siren_numeric_check(a);
gp_Ax2 ax = siren_ary_to_ax2(pos, norm);
BRepPrimAPI_MakeCylinder api(ax, NUM2DBL(r), NUM2DBL(h), NUM2DBL(a));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_cone(int argc, VALUE* argv, VALUE self)
{
VALUE pos, norm;
VALUE r1, r2, h, ang;
rb_scan_args(argc, argv, "6", &pos, &norm, &r1, &r2, &h, &ang);
siren_numeric_check(r1);
siren_numeric_check(r2);
siren_numeric_check(h);
siren_numeric_check(ang);
gp_Ax2 ax = siren_ary_to_ax2(pos, norm);
BRepPrimAPI_MakeCone api(ax, NUM2DBL(r1), NUM2DBL(r2), NUM2DBL(h), NUM2DBL(ang));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_torus(int argc, VALUE* argv, VALUE self)
{
VALUE r1, r2, ang;
VALUE pos, norm;
rb_scan_args(argc, argv, "5", &pos, &norm, &r1, &r2, &ang);
siren_numeric_check(r1);
siren_numeric_check(r2);
siren_numeric_check(ang);
gp_Ax2 ax = siren_ary_to_ax2(pos, norm);
BRepPrimAPI_MakeTorus api(ax, NUM2DBL(r1), NUM2DBL(r2), NUM2DBL(ang));
return siren_shape_new(api.Shape());
}
VALUE siren_solid_halfspace(int argc, VALUE* argv, VALUE self)
{
VALUE surf, refpnt;
rb_scan_args(argc, argv, "2", &surf, &refpnt);
siren_shape_check(surf);
TopoDS_Shape* shape = siren_shape_get(surf);
TopoDS_Solid solid;
gp_Pnt pnt = siren_ary_to_pnt(refpnt);
if (shape->ShapeType() == TopAbs_FACE) {
solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Face(*shape), pnt);
}
else if (shape->ShapeType() == TopAbs_SHELL) {
solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Shell(*shape), pnt);
}
else {
rb_raise(Qnil, "Specified shape type is not FACE or SHELL.");
}
return siren_shape_new(solid);
}
VALUE siren_solid_prism(int argc, VALUE* argv, VALUE self)
{
rb_raise(Qnil, "Not implemented.");
return Qnil;
}
VALUE siren_solid_revol(int argc, VALUE* argv, VALUE self)
{
rb_raise(Qnil, "Not implemented.");
return Qnil;
}
VALUE siren_solid_revolution(int argc, VALUE* argv, VALUE self)
{
rb_raise(Qnil, "Not implemented.");
return Qnil;
}
VALUE siren_solid_wedge(int argc, VALUE* argv, VALUE self)
{
VALUE dx = DBL2NUM(1.0), dy = DBL2NUM(1.0), dz = DBL2NUM(1.0),
x = DBL2NUM(0.5), z = DBL2NUM(0.5), X = DBL2NUM(0.5), Z = DBL2NUM(0.5);
rb_scan_args(argc, argv, "07", &dx, &dy, &dz, &x, &z, &X, &Z);
try {
BRepPrimAPI_MakeWedge api(NUM2DBL(dx), NUM2DBL(dy), NUM2DBL(dz),
NUM2DBL(x), NUM2DBL(z), NUM2DBL(X), NUM2DBL(Z));
TopoDS_Shape s = api.Shape();
return siren_shape_new(s);
}
catch (...) {
rb_raise(Qnil, "Failed to make a wedge.");
}
return Qnil;
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <comedilib.h>
#include <getopt.h>
int subdev = 0;
int range = 0;
int aref = AREF_GROUND;
int chan[50];
int blink_msec = 300;
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "read", required_argument, 0, 'r' },
{ "write", required_argument, 0, 'w' },
{ "aread", required_argument, 0, 'i' },
{ "awrite", required_argument, 0, 'o' },
{ "subdev", required_argument, 0, 's' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "aref", required_argument, 0, 'z' },
{ "range", required_argument, 0, 'x' },
{ "config", required_argument, 0, 'c' },
{ "autoconf", no_argument, 0, 'a' },
{ "plus", required_argument, 0, 'p' },
{ "blink", no_argument, 0, 'b' },
{ "blink-msec", required_argument, 0, 'm' },
{ "subdev-config", required_argument, 0, 'q' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
enum Command
{
cmdNOP,
cmdDRead,
cmdDWrite,
cmdARead,
cmdAWrite,
cmdConfig,
cmdSubConfig
} cmd;
// --------------------------------------------------------------------------
static void insn_config( comedi_t* card, int subdev, int channel, lsampl_t iotype, int range, int aref );
static void insn_subdev_config( comedi_t* card, int subdev, lsampl_t type );
// --------------------------------------------------------------------------
int main(int argc, char* argv[])
{
comedi_t* card;
lsampl_t data = 0;
int optindex = 0;
int opt = 0;
const char* dev = "/dev/comedi0";
int val = -1;
cmd = cmdNOP;
int verb = 0;
int autoconf = 0;
int cnum = 0;
int blink = 0;
int exret = EXIT_SUCCESS;
memset(chan,-1,sizeof(chan));
while( (opt = getopt_long(argc, argv, "habr:w:i:o:s:d:c:p:m:q:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
printf("-h|--help - this message\n");
printf("[-w|--write] chan val - write to digital channel\n");
printf("[-r|--read] chan - read from digital channel\n");
printf("[-o|--awrite] chan val - write to analog channel\n");
printf("[-i|--aread] chan - read from analog channel\n");
printf("[-s|--subdev] sub - use subdev number sub. (Default: 0)\n");
printf("[-d|--device] dev - use device dev. (Default: /dev/comedi0)\n");
printf("[--aref] val - AREF (Default: %d)\n",aref);
printf("[--range] val - RANGE (Default: %d)\n",range);
printf("[-p|--plus] chan - Add channel for command.\n");
printf("[-a|--autoconf] - autoconf channel type\n");
printf("[-q|--subdev-config] - subdev type configure\n");
printf(" 1 - TBI 24/0\n");
printf(" 2 - TBI 0/24\n");
printf(" 3 - TBI 16/8\n");
printf("aref:\n");
printf(" 0 - analog ref = analog ground\n");
printf(" 1 - analog ref = analog common\n");
printf(" 2 - analog ref = differential\n");
printf(" 3 - analog ref = other (undefined)\n");
printf("range:\n");
printf(" 0 - -10В - 10В\n");
printf(" 1 - -5В - 5В\n");
printf(" 2 - -2.5В - 2.5В\n");
printf(" 3 - -1.25В - 1.25В\n");
printf("[--blink] - (blink output): ONLY FOR 'write': 0-1-0-1-0-...\n");
printf("[--blink-msec] val - Blink pause [msec]. Default: 300 msec\n");
return 0;
case 'r':
chan[0] = atoi(optarg);
cmd = cmdDRead;
break;
case 'w':
chan[0] = atoi(optarg);
cmd = cmdDWrite;
if( optind<argc && (argv[optind])[0]!='-' )
val = atoi(argv[optind]);
break;
case 'i':
chan[0] = atoi(optarg);
cmd = cmdARead;
break;
case 'o':
chan[0] = atoi(optarg);
cmd = cmdAWrite;
if( optind<argc && (argv[optind])[0]!='-' )
val = atoi(argv[optind]);
break;
case 'd':
dev = optarg;
break;
case 's':
subdev = atoi(optarg);
break;
case 'v':
verb = 1;
break;
case 'x':
range = atoi(optarg);
break;
case 'z':
aref = atoi(optarg);
break;
case 'c':
cmd = cmdConfig;
val = atoi(optarg);
break;
case 'q':
cmd = cmdSubConfig;
val = atoi(optarg);
break;
case 'a':
autoconf = 1;
break;
case 'p':
chan[++cnum] = atoi(optarg);
break;
case 'm':
blink_msec = atoi(optarg);
break;
case 'b':
blink = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
card = comedi_open(dev);
if( card == NULL )
{
comedi_perror("comedi_open error");
exit(EXIT_FAILURE);
}
if( verb )
{
fprintf(stdout, "init comedi:\n");
fprintf(stdout, "dev: %s\n",dev);
fprintf(stdout, "subdev: %d\n",subdev);
fprintf(stdout, "channel: %d\n",chan[0]);
}
switch( cmd )
{
case cmdDRead:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( comedi_dio_config(card, subdev, chan[k],INSN_CONFIG_DIO_INPUT) < 0)
{
comedi_perror("can't configure DI channels");
exret = EXIT_FAILURE;
}
if( comedi_dio_read(card, subdev, chan[k],&data) < 0)
{
fprintf(stderr, "can't read from channel %d\n",chan[k]);
exret = EXIT_FAILURE;
}
printf("Digital input %d: %d\n",chan[k], data);
}
}
break;
case cmdDWrite:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( comedi_dio_config(card, subdev, chan[k],INSN_CONFIG_DIO_OUTPUT) < 0 )
{
comedi_perror("can't configure DO channels");
exret = EXIT_FAILURE;
}
}
// реализация мигания
while(1)
{
for( int k=0; chan[k]!=-1; k++ )
{
if( verb )
printf( "write: ch=%d val=%d\n",chan[k],val);
if( comedi_dio_write(card, subdev, chan[k], val) < 0)
{
comedi_perror("can't write 1 to channel\n");
exret = EXIT_FAILURE;
}
}
if( !blink )
break;
val = val ? 0 : 1;
usleep(1000*blink_msec);
}
}
break;
case cmdARead:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( autoconf )
insn_config(card, subdev,chan[k],100,range,aref);
int ret = comedi_data_read(card, subdev, chan[k], range, aref, &data);
if( ret < 0)
{
fprintf(stderr, "can't read from channel %d: (%d) %s\n",chan[k],ret,strerror(ret));
exret = EXIT_FAILURE;
}
printf("Readed from channel %d value is %d\n", chan[k], data);
}
}
break;
case cmdAWrite:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( autoconf )
insn_config(card,subdev,chan[k],101,range,aref);
int ret = comedi_data_write(card, subdev, chan[k], range, aref, val);
if( ret < 0)
{
fprintf(stderr, "can't write to channel %d: (%d) %s\n",chan[k],ret,strerror(ret));
exret = EXIT_FAILURE;
}
}
}
break;
case cmdConfig:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( val != INSN_CONFIG_DIO_INPUT
&& val != INSN_CONFIG_DIO_OUTPUT
&& val != 100 /* INSN_CONFIG_AIO_INPUT */
&& val != 101 /* INSN_CONFIG_AIO_OUTPUT */
)
{
fprintf(stderr, "can't config channel %d for type = %d (val=[%d,%d,%d,%d])\n"
,chan[k],val,INSN_CONFIG_DIO_INPUT,INSN_CONFIG_DIO_OUTPUT,100,101);
exret = EXIT_FAILURE;
}
}
}
case cmdSubConfig:
insn_subdev_config(card, subdev, val);
break;
default:
comedi_perror("\n...No command... Use -h for help\n");
exit(EXIT_FAILURE);
break;
}
exit(exret);
}
void insn_config( comedi_t* card, int subdev, int channel, lsampl_t iotype, int range, int aref )
{
comedi_insn insn;
memset(&insn,0,sizeof(insn));
insn.insn = INSN_CONFIG;
insn.n = 1;
insn.data = &iotype;
insn.subdev = subdev;
insn.chanspec = CR_PACK(channel,range,aref);
if( comedi_do_insn(card,&insn) < 0 )
{
fprintf(stderr, "can`t configure (AIO) subdev=%d channel=%d type=%d",subdev,channel,iotype);
exit(EXIT_FAILURE);
}
}
void insn_subdev_config( comedi_t* card, int subdev, lsampl_t type )
{
lsampl_t cmd = 102;
comedi_insn insn;
memset(&insn,0,sizeof(insn));
insn.insn = INSN_CONFIG;
insn.n = 1;
insn.data = &cmd;
insn.unused[0] = type;
insn.subdev = subdev;
insn.chanspec = 0;
switch(type)
{
case 1:
printf("set subdev %d type: 'TBI 24/0'\n",subdev);
break;
case 2:
printf("set subdev %d type: 'TBI 0/24'\n",subdev);
break;
case 3:
printf("set subdev %d type: 'TBI 16/8'\n",subdev);
break;
default:
printf("set subdev %d type: UNKNOWN\n",subdev);
break;
}
if( comedi_do_insn(card,&insn) < 0 )
{
fprintf(stderr, "can`t configure subdev subdev=%d type=%d",subdev,type);
exit(EXIT_FAILURE);
}
}
<commit_msg>(iotest): 1. Убрал автоконфигурирование при чтении DO,DI 2. Подправил вывод ошибок<commit_after>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <errno.h>
#include <comedilib.h>
#include <getopt.h>
int subdev = 0;
int range = 0;
int aref = AREF_GROUND;
int chan[50];
int blink_msec = 300;
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "read", required_argument, 0, 'r' },
{ "write", required_argument, 0, 'w' },
{ "aread", required_argument, 0, 'i' },
{ "awrite", required_argument, 0, 'o' },
{ "subdev", required_argument, 0, 's' },
{ "device", required_argument, 0, 'd' },
{ "verbose", no_argument, 0, 'v' },
{ "aref", required_argument, 0, 'z' },
{ "range", required_argument, 0, 'x' },
{ "config", required_argument, 0, 'c' },
{ "autoconf", no_argument, 0, 'a' },
{ "plus", required_argument, 0, 'p' },
{ "blink", no_argument, 0, 'b' },
{ "blink-msec", required_argument, 0, 'm' },
{ "subdev-config", required_argument, 0, 'q' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
enum Command
{
cmdNOP,
cmdDRead,
cmdDWrite,
cmdARead,
cmdAWrite,
cmdConfig,
cmdSubConfig
} cmd;
// --------------------------------------------------------------------------
static void insn_config( comedi_t* card, int subdev, int channel, lsampl_t iotype, int range, int aref );
static void insn_subdev_config( comedi_t* card, int subdev, lsampl_t type );
// --------------------------------------------------------------------------
int main(int argc, char* argv[])
{
comedi_t* card;
lsampl_t data = 0;
int optindex = 0;
int opt = 0;
const char* dev = "/dev/comedi0";
int val = -1;
cmd = cmdNOP;
int verb = 0;
int autoconf = 0;
int cnum = 0;
int blink = 0;
int exret = EXIT_SUCCESS;
memset(chan,-1,sizeof(chan));
while( (opt = getopt_long(argc, argv, "habr:w:i:o:s:d:c:p:m:q:",longopts,&optindex)) != -1 )
{
switch (opt)
{
case 'h':
printf("-h|--help - this message\n");
printf("[-w|--write] chan val - write to digital channel\n");
printf("[-r|--read] chan - read from digital channel\n");
printf("[-o|--awrite] chan val - write to analog channel\n");
printf("[-i|--aread] chan - read from analog channel\n");
printf("[-s|--subdev] sub - use subdev number sub. (Default: 0)\n");
printf("[-d|--device] dev - use device dev. (Default: /dev/comedi0)\n");
printf("[--aref] val - AREF (Default: %d)\n",aref);
printf("[--range] val - RANGE (Default: %d)\n",range);
printf("[-p|--plus] chan - Add channel for command.\n");
printf("[-a|--autoconf] - autoconf channel type\n");
printf("[-q|--subdev-config] - subdev type configure\n");
printf(" 1 - TBI 24/0\n");
printf(" 2 - TBI 0/24\n");
printf(" 3 - TBI 16/8\n");
printf("aref:\n");
printf(" 0 - analog ref = analog ground\n");
printf(" 1 - analog ref = analog common\n");
printf(" 2 - analog ref = differential\n");
printf(" 3 - analog ref = other (undefined)\n");
printf("range:\n");
printf(" 0 - -10В - 10В\n");
printf(" 1 - -5В - 5В\n");
printf(" 2 - -2.5В - 2.5В\n");
printf(" 3 - -1.25В - 1.25В\n");
printf("[--blink] - (blink output): ONLY FOR 'write': 0-1-0-1-0-...\n");
printf("[--blink-msec] val - Blink pause [msec]. Default: 300 msec\n");
return 0;
case 'r':
chan[0] = atoi(optarg);
cmd = cmdDRead;
break;
case 'w':
chan[0] = atoi(optarg);
cmd = cmdDWrite;
if( optind<argc && (argv[optind])[0]!='-' )
val = atoi(argv[optind]);
break;
case 'i':
chan[0] = atoi(optarg);
cmd = cmdARead;
break;
case 'o':
chan[0] = atoi(optarg);
cmd = cmdAWrite;
if( optind<argc && (argv[optind])[0]!='-' )
val = atoi(argv[optind]);
break;
case 'd':
dev = optarg;
break;
case 's':
subdev = atoi(optarg);
break;
case 'v':
verb = 1;
break;
case 'x':
range = atoi(optarg);
break;
case 'z':
aref = atoi(optarg);
break;
case 'c':
cmd = cmdConfig;
val = atoi(optarg);
break;
case 'q':
cmd = cmdSubConfig;
val = atoi(optarg);
break;
case 'a':
autoconf = 1;
break;
case 'p':
chan[++cnum] = atoi(optarg);
break;
case 'm':
blink_msec = atoi(optarg);
break;
case 'b':
blink = 1;
break;
case '?':
default:
printf("? argumnet\n");
return 0;
}
}
card = comedi_open(dev);
if( card == NULL )
{
comedi_perror("comedi_open error");
exit(EXIT_FAILURE);
}
if( verb )
{
fprintf(stdout, "init comedi:\n");
fprintf(stdout, "dev: %s\n",dev);
fprintf(stdout, "subdev: %d\n",subdev);
fprintf(stdout, "channel: %d\n",chan[0]);
}
switch( cmd )
{
case cmdDRead:
{
if( autoconf )
{
for( int k=0; chan[k]!=-1; k++ )
{
if( comedi_dio_config(card, subdev, chan[k],INSN_CONFIG_DIO_INPUT) < 0)
{
comedi_perror("can't configure DI channels");
exret = EXIT_FAILURE;
}
}
}
for( int k=0; chan[k]!=-1; k++ )
{
if( comedi_dio_read(card, subdev, chan[k],&data) < 0)
{
fprintf(stderr, "can't read from channel %d (err(%d): %s)\n",chan[k],errno,strerror(errno));
exret = EXIT_FAILURE;
}
printf("Digital input %d: %d\n",chan[k], data);
}
}
break;
case cmdDWrite:
{
if( autoconf )
{
for( int k=0; chan[k]!=-1; k++ )
{
if( comedi_dio_config(card, subdev, chan[k],INSN_CONFIG_DIO_OUTPUT) < 0 )
{
fprintf(stderr,"can't configure DO channels. (%d) %s", errno,strerror(errno));
exret = EXIT_FAILURE;
}
}
}
// реализация мигания
while(1)
{
for( int k=0; chan[k]!=-1; k++ )
{
if( verb )
printf( "write: ch=%d val=%d\n",chan[k],val);
if( comedi_dio_write(card, subdev, chan[k], val) < 0)
{
fprintf(stderr,"can't write 1 to channel %d. (%d) %s\n",k,errno,strerror(errno));
exret = EXIT_FAILURE;
}
}
if( !blink )
break;
val = val ? 0 : 1;
usleep(1000*blink_msec);
}
}
break;
case cmdARead:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( autoconf )
insn_config(card, subdev,chan[k],100,range,aref);
int ret = comedi_data_read(card, subdev, chan[k], range, aref, &data);
if( ret < 0)
{
fprintf(stderr, "can't read from channel %d: (%d) %s\n",chan[k],errno,strerror(errno));
exret = EXIT_FAILURE;
}
printf("Readed from channel %d value is %d\n", chan[k], data);
}
}
break;
case cmdAWrite:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( autoconf )
insn_config(card,subdev,chan[k],101,range,aref);
int ret = comedi_data_write(card, subdev, chan[k], range, aref, val);
if( ret < 0)
{
fprintf(stderr, "can't write to channel %d: (%d) %s\n",chan[k],errno,strerror(errno));
exret = EXIT_FAILURE;
}
}
}
break;
case cmdConfig:
{
for( int k=0; chan[k]!=-1; k++ )
{
if( val != INSN_CONFIG_DIO_INPUT
&& val != INSN_CONFIG_DIO_OUTPUT
&& val != 100 /* INSN_CONFIG_AIO_INPUT */
&& val != 101 /* INSN_CONFIG_AIO_OUTPUT */
)
{
fprintf(stderr, "can't config channel %d for type = %d (val=[%d,%d,%d,%d])\n"
,chan[k],val,INSN_CONFIG_DIO_INPUT,INSN_CONFIG_DIO_OUTPUT,100,101);
exret = EXIT_FAILURE;
}
}
}
case cmdSubConfig:
insn_subdev_config(card, subdev, val);
break;
default:
comedi_perror("\n...No command... Use -h for help\n");
exit(EXIT_FAILURE);
break;
}
exit(exret);
}
void insn_config( comedi_t* card, int subdev, int channel, lsampl_t iotype, int range, int aref )
{
comedi_insn insn;
memset(&insn,0,sizeof(insn));
insn.insn = INSN_CONFIG;
insn.n = 1;
insn.data = &iotype;
insn.subdev = subdev;
insn.chanspec = CR_PACK(channel,range,aref);
if( comedi_do_insn(card,&insn) < 0 )
{
fprintf(stderr, "can`t configure (AIO) subdev=%d channel=%d type=%d",subdev,channel,iotype);
exit(EXIT_FAILURE);
}
}
void insn_subdev_config( comedi_t* card, int subdev, lsampl_t type )
{
lsampl_t cmd = 102;
comedi_insn insn;
memset(&insn,0,sizeof(insn));
insn.insn = INSN_CONFIG;
insn.n = 1;
insn.data = &cmd;
insn.unused[0] = type;
insn.subdev = subdev;
insn.chanspec = 0;
switch(type)
{
case 1:
printf("set subdev %d type: 'TBI 24/0'\n",subdev);
break;
case 2:
printf("set subdev %d type: 'TBI 0/24'\n",subdev);
break;
case 3:
printf("set subdev %d type: 'TBI 16/8'\n",subdev);
break;
default:
printf("set subdev %d type: UNKNOWN\n",subdev);
break;
}
if( comedi_do_insn(card,&insn) < 0 )
{
fprintf(stderr, "can`t configure subdev subdev=%d type=%d. Err(%d): %s",subdev,type,errno,strerror(errno));
exit(EXIT_FAILURE);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "error.h"
#include "bpmf.h"
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
#ifdef BPMF_REDUCE
if (it.row() >= other.to() || it.row() < other.from())
continue;
#endif
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
#ifdef BPMF_REDUCE
precMu = MatrixNXd::Zero(num_latent, num());
precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
#endif
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_larger_bp1 = 0;
int count_larger_bp2 = 0;
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
if (count > breakpoint1) count_larger_bp1++;
if (count > breakpoint2) count_larger_bp2++;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM) const
{
const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix
// (how many movies watched idx-th user?).
if (count < breakpoint2)
{
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = other.items().col(it.row());
MM.triangularView<Eigen::Upper>() += col * col.transpose();
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
}
else
{
const int task_size = int(count / 100) + 1;
unsigned from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix
unsigned to = M.outerIndexPtr()[idx + 1]; // "to" belongs to [1..m], m - number of movies in M matrix
thread_vector<VectorNd> rrs(VectorNd::Zero());
thread_vector<MatrixNNd> MMs(MatrixNNd::Zero());
#pragma omp taskloop shared(rrs, MMs, other) grainsize(task_size)
for (unsigned j = from; j < to; j++)
{
// for each nonzeros elemen in the i-th row of M matrix
auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix
auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix
auto col = other.items().col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:]
MMs.local().triangularView<Eigen::Upper>() += col * col.transpose(); // outer product
rrs.local().noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1
}
// accumulate
MM += MMs.combine();
rr += rrs.combine();
}
}
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, Sys &other)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
MatrixNNd MM(MatrixNNd::Zero());
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
#ifdef BPMF_REDUCE
rr += precMu.col(idx);
MM += precLambdaMatrix(idx);
#else
computeMuLambda(idx, other, rr, MM);
#endif
// copy upper -> lower part, matrix is symmetric.
MM.triangularView<Eigen::Lower>() = MM.transpose();
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(num_latent); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
#ifdef BPMF_REDUCE
#pragma omp critical
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
other.precLambdaMatrix(it.row()).triangularView<Eigen::Upper>() += rr * rr.transpose();
other.precMu.col(it.row()).noalias() += rr * (it.value() - mean_rating) * alpha;
}
#endif
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &other)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#ifdef BPMF_REDUCE
other.precMu.setZero();
other.precLambda.setZero();
#endif
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, other);
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}<commit_msg>ENH: add perf counters<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "error.h"
#include "bpmf.h"
#include "io.h"
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
int Sys::update_freq;
double Sys::alpha = 2.0;
std::string Sys::odirname = "";
bool Sys::permute = true;
bool Sys::verbose = false;
// verifies that A has the same non-zero structure as B
void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B)
{
assert(A.cols() == B.cols());
assert(A.rows() == B.rows());
for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
#ifdef BPMF_REDUCE
if (it.row() >= other.to() || it.row() < other.from())
continue;
#endif
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
col_permutation.setIdentity(num());
#ifdef BPMF_REDUCE
precMu = MatrixNXd::Zero(num_latent, num());
precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
#endif
if (Sys::odirname.size())
{
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
}
int count_larger_bp1 = 0;
int count_larger_bp2 = 0;
int count_sum = 0;
for(int k = 0; k<M.cols(); k++) {
int count = M.col(k).nonZeros();
count_sum += count;
if (count > breakpoint1) count_larger_bp1++;
if (count > breakpoint2) count_larger_bp2++;
}
Sys::cout() << "mean rating: " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl;
Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl;
Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM) const
{
BPMF_COUNTER("computeMuLambda");
const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix
// (how many movies watched idx-th user?).
if (count < breakpoint2)
{
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
auto col = other.items().col(it.row());
MM.triangularView<Eigen::Upper>() += col * col.transpose();
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
}
else
{
const int task_size = int(count / 100) + 1;
unsigned from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix
unsigned to = M.outerIndexPtr()[idx + 1]; // "to" belongs to [1..m], m - number of movies in M matrix
thread_vector<VectorNd> rrs(VectorNd::Zero());
thread_vector<MatrixNNd> MMs(MatrixNNd::Zero());
#pragma omp taskloop shared(rrs, MMs, other) grainsize(task_size)
for (unsigned j = from; j < to; j++)
{
// for each nonzeros elemen in the i-th row of M matrix
auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix
auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix
auto col = other.items().col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:]
MMs.local().triangularView<Eigen::Upper>() += col * col.transpose(); // outer product
rrs.local().noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1
}
// accumulate
MM += MMs.combine();
rr += rrs.combine();
}
}
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, Sys &other)
{
auto start = tick();
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
MatrixNNd MM(MatrixNNd::Zero());
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
#ifdef BPMF_REDUCE
rr += precMu.col(idx);
MM += precLambdaMatrix(idx);
#else
computeMuLambda(idx, other, rr, MM);
#endif
// copy upper -> lower part, matrix is symmetric.
MM.triangularView<Eigen::Lower>() = MM.transpose();
chol.compute(hp_LambdaF + alpha * MM);
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(num_latent); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
#ifdef BPMF_REDUCE
{
BPMF_COUNTER("update_Lambda");
MatrixNNd Lambda_update;
Lambda_update.triangularView<Eigen::Upper>() = rr * rr.transpose();
for (SparseMatrixD::InnerIterator it(M, idx); it; ++it)
{
other.precLambdaMatrix(it.row()).triangularView<Eigen::Upper>() += Lambda_update;
VectorNd mu_update = rr * (it.value() - mean_rating) * alpha;
other.precMu.col(it.row()).noalias() += mu_update;
}
}
#endif
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &other)
{
iter++;
thread_vector<VectorNd> sums(VectorNd::Zero()); // sum
thread_vector<double> norms(0.0); // squared norm
thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod
#ifdef BPMF_REDUCE
other.precMu.setZero();
other.precLambda.setZero();
#endif
#pragma omp parallel for schedule(guided)
for (int i = from(); i < to(); ++i)
{
#pragma omp task
{
auto r = sample(i, other);
MatrixNNd cov = (r * r.transpose());
prods.local() += cov;
sums.local() += r;
norms.local() += r.squaredNorm();
if (iter >= burnin && Sys::odirname.size())
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_item(i);
}
}
#pragma omp taskwait
VectorNd sum = sums.combine();
MatrixNNd prod = prods.combine();
double norm = norms.combine();
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "io.h"
#if defined(_OPENMP)
#include "omp.h"
#pragma omp declare reduction (VectorPlus : VectorNd : omp_out += omp_in) initializer(omp_priv = VectorNd::Zero())
#pragma omp declare reduction (MatrixPlus : MatrixNNd : omp_out += omp_in) initializer(omp_priv = MatrixNNd::Zero())
#endif
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
bool Sys::permute = true;
bool Sys::verbose = false;
unsigned Sys::grain_size;
void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose();
void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part
// verifies that A is transpose of B
void assert_transpose(SparseMatrixD &A, SparseMatrixD &B)
{
SparseMatrixD At = A.transpose();
SparseMatrixD Bt = B.transpose();
assert(At.cols() == B.cols());
assert(A.cols() == Bt.cols());
for(int i=0; i<B.cols(); ++i) assert(At.col(i).nonZeros() == B.col(i).nonZeros());
for(int i=0; i<A.cols(); ++i) assert(Bt.col(i).nonZeros() == A.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.2f\tavg RMSE: %3.2f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
Sys::cout() << "mean rating = " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train = " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test = " << T.nonZeros() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, const MapNXd in)
{
auto start = tick();
const double alpha = 2; // Gaussian noice
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
int breakpoint1 = 24;
int breakpoint2 = 10500;
const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix
// (how many movies watched idx-th user?).
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
// if this user movie has less than 1K ratings,
// we do a serial rank update
if( count < breakpoint1 ) {
chol = hp_LambdaL;
for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) {
auto col = in.col(it.row());
chol.rankUpdate(col, alpha);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// else we do a serial full cholesky decomposition
// (not used if breakpoint1 == breakpoint2)
} else if (count < breakpoint2) {
MatrixNNd MM(MatrixNNd::Zero());
for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) {
auto col = in.col(it.row());
//MM.noalias() += col * col.transpose();
calc_upper_part(MM, col);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM);
// for > 1K ratings, we have additional thread-level parallellism
} else {
auto from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix
auto to = M.outerIndexPtr()[idx+1]; // "to" belongs to [1..m], m - number of movies in M matrix
MatrixNNd MM(MatrixNNd::Zero()); // matrix num_latent x num_latent
// #pragma omp parallel for reduction(VectorPlus:rr) reduction(MatrixPlus:MM)
#pragma omp parallel for reduction(VectorPlus:rr) reduction(MatrixPlus:MM) schedule(dynamic,200)
for(int j = from; j<to; ++j) { // for each nonzeros elemen in the i-th row of M matrix
auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix
auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix
auto col = in.col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:]
//MM.noalias() += col * col.transpose(); // outer product
calc_upper_part(MM, col);
rr.noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1
}
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM); // matrix num_latent x num_latent
// chol="lambda_i with *" from formula (14)
// lambda_i with * = LambdaU + alpha * MM
}
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &in)
{
iter++;
VectorNd sum(VectorNd::Zero()); // sum
double norm(0.0); // squared norm
MatrixNNd prod(MatrixNNd::Zero()); // outer prod
//#pragma omp parallel for reduction(VectorPlus:sum) reduction(MatrixPlus:prod) reduction(+:norm) schedule(dynamic, 1)
#pragma omp parallel for reduction(VectorPlus:sum) reduction(MatrixPlus:prod) reduction(+:norm) schedule(dynamic,1)
for(int i = from(); i<to(); ++i) {
auto r = sample(i,in.items());
MatrixNNd cov = (r * r.transpose());
prod += cov;
sum += r;
norm += r.squaredNorm();
if (iter >= burnin)
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_items(i, i + 1);
}
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}
void calc_upper_part(MatrixNNd &m, VectorNd v)
{
// we use the formula: m = m + v * v.transpose(), but we calculate only an upper part of m matrix
for (int j=0; j<num_latent; j++) // columns
{
for(int i=0; i<=j; i++) // rows
{
m(i,j) = m(i,j) + v[j] * v[i];
}
}
}
void copy_lower_part(MatrixNNd &m)
{
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
for (int j=1; j<num_latent; j++) // columns
{
for(int i=0; i<=j-1; i++) // rows
{
m(j,i) = m(i,j);
}
}
}
<commit_msg>ENH: print 4 digits after decimal point<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include "error.h"
#include "bpmf.h"
#include <random>
#include <memory>
#include <cstdio>
#include <iostream>
#include <climits>
#include <stdexcept>
#include "io.h"
#if defined(_OPENMP)
#include "omp.h"
#pragma omp declare reduction (VectorPlus : VectorNd : omp_out += omp_in) initializer(omp_priv = VectorNd::Zero())
#pragma omp declare reduction (MatrixPlus : MatrixNNd : omp_out += omp_in) initializer(omp_priv = MatrixNNd::Zero())
#endif
static const bool measure_perf = false;
std::ostream *Sys::os;
int Sys::procid = -1;
int Sys::nprocs = -1;
int Sys::nsims;
int Sys::burnin;
bool Sys::permute = true;
bool Sys::verbose = false;
unsigned Sys::grain_size;
void calc_upper_part(MatrixNNd &m, VectorNd v); // function for calcutation of an upper part of a symmetric matrix: m = v * v.transpose();
void copy_lower_part(MatrixNNd &m); // function to copy an upper part of a symmetric matrix to a lower part
// verifies that A is transpose of B
void assert_transpose(SparseMatrixD &A, SparseMatrixD &B)
{
SparseMatrixD At = A.transpose();
SparseMatrixD Bt = B.transpose();
assert(At.cols() == B.cols());
assert(A.cols() == Bt.cols());
for(int i=0; i<B.cols(); ++i) assert(At.col(i).nonZeros() == B.col(i).nonZeros());
for(int i=0; i<A.cols(); ++i) assert(Bt.col(i).nonZeros() == A.col(i).nonZeros());
}
//
// Does predictions for prediction matrix T
// Computes RMSE (Root Means Square Error)
//
void Sys::predict(Sys& other, bool all)
{
int n = (iter < burnin) ? 0 : (iter - burnin);
double se(0.0); // squared err
double se_avg(0.0); // squared avg err
unsigned nump(0); // number of predictions
int lo = all ? 0 : from();
int hi = all ? num() : to();
#pragma omp parallel for reduction(+:se,se_avg,nump)
for(int k = lo; k<hi; k++) {
for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it)
{
auto m = items().col(it.col());
auto u = other.items().col(it.row());
assert(m.norm() > 0.0);
assert(u.norm() > 0.0);
const double pred = m.dot(u) + mean_rating;
se += sqr(it.value() - pred);
// update average prediction
double &avg = Pavg.coeffRef(it.row(), it.col());
double delta = pred - avg;
avg = (n == 0) ? pred : (avg + delta/n);
double &m2 = Pm2.coeffRef(it.row(), it.col());
m2 = (n == 0) ? 0 : m2 + delta * (pred - avg);
se_avg += sqr(it.value() - avg);
nump++;
}
}
rmse = sqrt( se / nump );
rmse_avg = sqrt( se_avg / nump );
}
//
// Prints sampling progress
//
void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) {
char buf[1024];
std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling";
sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n",
Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6);
Sys::cout() << buf;
}
//
// Constructor with that reads MTX files
//
Sys::Sys(std::string name, std::string fname, std::string probename)
: name(name), iter(-1), assigned(false), dom(nprocs+1)
{
read_matrix(fname, M);
read_matrix(probename, T);
auto rows = std::max(M.rows(), T.rows());
auto cols = std::max(M.cols(), T.cols());
M.conservativeResize(rows,cols);
T.conservativeResize(rows,cols);
Pm2 = Pavg = T; // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
assert(Sys::nprocs <= (int)Sys::max_procs);
}
//
// Constructs Sys as transpose of existing Sys
//
Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) {
M = Mt.transpose();
Pm2 = Pavg = T = Pt.transpose(); // reference ratings and predicted ratings
assert(M.rows() == Pavg.rows());
assert(M.cols() == Pavg.cols());
}
Sys::~Sys()
{
if (measure_perf) {
Sys::cout() << " --------------------\n";
Sys::cout() << name << ": sampling times on " << procid << "\n";
for(int i = from(); i<to(); ++i)
{
Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n";
}
Sys::cout() << " --------------------\n\n";
}
}
bool Sys::has_prop_posterior() const
{
return propMu.nonZeros() > 0;
}
void Sys::add_prop_posterior(std::string fnames)
{
if (fnames.empty()) return;
std::size_t pos = fnames.find_first_of(",");
std::string mu_name = fnames.substr(0, pos);
std::string lambda_name = fnames.substr(pos+1);
read_matrix(mu_name, propMu);
read_matrix(lambda_name, propLambda);
assert(propMu.cols() == num());
assert(propLambda.cols() == num());
assert(propMu.rows() == num_latent);
assert(propLambda.rows() == num_latent * num_latent);
}
//
// Intializes internal Matrices and Vectors
//
void Sys::init()
{
//-- M
assert(M.rows() > 0 && M.cols() > 0);
mean_rating = M.sum() / M.nonZeros();
items().setZero();
sum_map().setZero();
cov_map().setZero();
norm_map().setZero();
aggrMu = Eigen::MatrixXd::Zero(num_latent, num());
aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num());
Sys::cout() << "mean rating = " << mean_rating << std::endl;
Sys::cout() << "total number of ratings in train = " << M.nonZeros() << std::endl;
Sys::cout() << "total number of ratings in test = " << T.nonZeros() << std::endl;
Sys::cout() << "num " << name << ": " << num() << std::endl;
if (has_prop_posterior())
{
Sys::cout() << "with propagated posterior" << std::endl;
}
if (measure_perf) sample_time.resize(num(), .0);
}
class PrecomputedLLT : public Eigen::LLT<MatrixNNd>
{
public:
void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; }
};
//
// Update ONE movie or one user
//
VectorNd Sys::sample(long idx, const MapNXd in)
{
auto start = tick();
const double alpha = 2; // Gaussian noice
VectorNd hp_mu;
MatrixNNd hp_LambdaF;
MatrixNNd hp_LambdaL;
if (has_prop_posterior())
{
hp_mu = propMu.col(idx);
hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data());
hp_LambdaL = hp_LambdaF.llt().matrixL();
}
else
{
hp_mu = hp.mu;
hp_LambdaF = hp.LambdaF;
hp_LambdaL = hp.LambdaL;
}
int breakpoint1 = 24;
int breakpoint2 = 10500;
const int count = M.innerVector(idx).nonZeros(); // count of nonzeros elements in idx-th row of M matrix
// (how many movies watched idx-th user?).
VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper
PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14)
// if this user movie has less than 1K ratings,
// we do a serial rank update
if( count < breakpoint1 ) {
chol = hp_LambdaL;
for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) {
auto col = in.col(it.row());
chol.rankUpdate(col, alpha);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// else we do a serial full cholesky decomposition
// (not used if breakpoint1 == breakpoint2)
} else if (count < breakpoint2) {
MatrixNNd MM(MatrixNNd::Zero());
for (SparseMatrixD::InnerIterator it(M,idx); it; ++it) {
auto col = in.col(it.row());
//MM.noalias() += col * col.transpose();
calc_upper_part(MM, col);
rr.noalias() += col * ((it.value() - mean_rating) * alpha);
}
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM);
// for > 1K ratings, we have additional thread-level parallellism
} else {
auto from = M.outerIndexPtr()[idx]; // "from" belongs to [1..m], m - number of movies in M matrix
auto to = M.outerIndexPtr()[idx+1]; // "to" belongs to [1..m], m - number of movies in M matrix
MatrixNNd MM(MatrixNNd::Zero()); // matrix num_latent x num_latent
// #pragma omp parallel for reduction(VectorPlus:rr) reduction(MatrixPlus:MM)
#pragma omp parallel for reduction(VectorPlus:rr) reduction(MatrixPlus:MM) schedule(dynamic,200)
for(int j = from; j<to; ++j) { // for each nonzeros elemen in the i-th row of M matrix
auto val = M.valuePtr()[j]; // value of the j-th nonzeros element from idx-th row of M matrix
auto idx = M.innerIndexPtr()[j]; // index "j" of the element [i,j] from M matrix in compressed M matrix
auto col = in.col(idx); // vector num_latent x 1 from V matrix: M[i,j] = U[i,:] x V[idx,:]
//MM.noalias() += col * col.transpose(); // outer product
calc_upper_part(MM, col);
rr.noalias() += col * ((val - mean_rating) * alpha); // vector num_latent x 1
}
copy_lower_part(MM);
chol.compute(hp_LambdaF + alpha * MM); // matrix num_latent x num_latent
// chol="lambda_i with *" from formula (14)
// lambda_i with * = LambdaU + alpha * MM
}
if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed");
// now we should calculate formula (14) from the paper
// u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) =
// = mu_i with * + s * [U]^-1,
// where
// s is a random vector with N(0, I),
// mu_i with * is a vector num_latent x 1,
// mu_i with * = [lambda_i with *]^-1 * rr,
// lambda_i with * = L * U
// Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like:
chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector
rr += nrandn(); // rr=s+(L\rr), we store result again in rr vector
chol.matrixU().solveInPlace(rr); // u_i=U\rr
items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix)
auto stop = tick();
register_time(idx, 1e6 * (stop - start));
//Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl;
assert(rr.norm() > .0);
return rr;
}
//
// update ALL movies / users in parallel
//
void Sys::sample(Sys &in)
{
iter++;
VectorNd sum(VectorNd::Zero()); // sum
double norm(0.0); // squared norm
MatrixNNd prod(MatrixNNd::Zero()); // outer prod
//#pragma omp parallel for reduction(VectorPlus:sum) reduction(MatrixPlus:prod) reduction(+:norm) schedule(dynamic, 1)
#pragma omp parallel for reduction(VectorPlus:sum) reduction(MatrixPlus:prod) reduction(+:norm) schedule(dynamic,1)
for(int i = from(); i<to(); ++i) {
auto r = sample(i,in.items());
MatrixNNd cov = (r * r.transpose());
prod += cov;
sum += r;
norm += r.squaredNorm();
if (iter >= burnin)
{
aggrMu.col(i) += r;
aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent);
}
send_items(i, i + 1);
}
const int N = num();
local_sum() = sum;
local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1);
local_norm() = norm;
}
void Sys::register_time(int i, double t)
{
if (measure_perf) sample_time.at(i) += t;
}
void calc_upper_part(MatrixNNd &m, VectorNd v)
{
// we use the formula: m = m + v * v.transpose(), but we calculate only an upper part of m matrix
for (int j=0; j<num_latent; j++) // columns
{
for(int i=0; i<=j; i++) // rows
{
m(i,j) = m(i,j) + v[j] * v[i];
}
}
}
void copy_lower_part(MatrixNNd &m)
{
// Here, we copy a triangular upper part to a triangular lower part, because the matrix is symmetric.
for (int j=1; j<num_latent; j++) // columns
{
for(int i=0; i<=j-1; i++) // rows
{
m(j,i) = m(i,j);
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/program_options.hpp>
#include "float-semiring.h"
#include "semilinSetExp.h"
#include "matrix.h"
#include "polynomial.h"
#include "newton.h"
#include "commutativeRExp.h"
#include "parser.h"
template <typename SR>
struct VertexProp {
std::string name; // used for graphviz output
VarPtr var; // var and rex combines the equations in the vertex
Polynomial<SR> rex;
};
// group the equations to SCCs
template <typename SR>
std::vector<std::vector<std::pair<VarPtr, Polynomial<SR>>>> group_by_scc(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool graphviz_output)
{
// create map of variables to [0..n]. this is used to enumerate important variables in a clean way from 0 to n during graph construction
std::map<VarPtr, int> var_key;
// build the graph
boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProp<SR>> graph(equations.size());
for(auto e_it = equations.begin(); e_it != equations.end(); ++e_it)
{
// if the variable is not yet in the map insert it together with the size of
// the map. this way we get a unique identifier for the variable counting from 0 to n
if(var_key.find(e_it->first) == var_key.end())
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(e_it->first,var_key.size()));
int a = var_key.find(e_it->first)->second; // variable key
graph[a].var = e_it->first; // store VarPtr to the vertex
graph[a].name = e_it->first->string(); // store the name to the vertex
graph[a].rex = e_it->second; // store the regular expression to the vertex
auto v = e_it->second.get_variables(); // all variables of this rule;
for(auto v_it = v.begin(); v_it != v.end(); ++v_it)
{
if(var_key.find(*v_it) == var_key.end()) // variable is not yet in the map
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(*v_it,var_key.size()));
int b = var_key.find(*v_it)->second; // variable key
boost::add_edge(a, b, graph);
}
} // graph is complete
if(graphviz_output)
{
// output the created graph to graph.dot
boost::dynamic_properties dp;
dp.property("label", boost::get(&VertexProp<SR>::name, graph)); // vertex name is the name of the equation
dp.property("node_id", get(boost::vertex_index, graph)); // this is needed
std::ofstream outf("graph.dot");
boost::write_graphviz_dp(outf, graph, dp);
}
// calculate strong connected components and store them in 'component'
std::vector<int> component(boost::num_vertices(graph));
boost::strong_components(graph,&component[0]);
// group neccessary equations together
int num_comp = *std::max_element(component.begin(), component.end()) + 1; // find the number of components
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> grouped_equations;
grouped_equations.resize(num_comp);
// iterate over all vertices (0 to n)
// collect the necessary variables + equations for every component
for (unsigned int j = 0; j != component.size(); ++j)
{
//std::cout << j << ", " << graph[j].var << " is in component " << component[j] << std::endl;
grouped_equations[component[j]].push_back(std::pair<VarPtr,Polynomial<SR>>(graph[j].var, graph[j].rex));
}
return grouped_equations;
}
// apply the newton method to the given input
template <typename SR>
std::map<VarPtr, SR> apply_newton(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool scc, bool iteration_flag, int iterations, bool graphviz_output)
{
// TODO: sanity checks on the input!
// generate an instance of the newton solver
Newton<SR> newton;
// if we use the scc method, group the equations
// the outer vector contains SCCs starting with a bottom SCC at 0
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> equations2;
if(scc)
{
auto tmp = group_by_scc(equations, graphviz_output);
equations2.insert(equations2.begin(), tmp.begin(), tmp.end());
}
else if (!scc)
{
equations2.push_back(equations);
}
// this holds the solution
std::map<VarPtr, SR> solution;
// the same loop is used for both the scc and the non-scc variant
// in the non-scc variant, we just run once through the loop
//for(auto it1 = equations2.begin(); it != equations2.end(); ++it)
for(unsigned int j = 0; j != equations2.size(); ++j)
{
// use the solutions to get rid of variables in the remaining equations
// does nothing in the first round
std::vector<std::pair<VarPtr, Polynomial<SR>>> tmp1;
for(auto it = equations2[j].begin(); it != equations2[j].end(); ++it)
{ // it = (VarPtr, Polynomial[SR])
auto tmp2 = it->second.partial_eval(solution);
tmp1.push_back(std::pair<VarPtr, Polynomial<SR>>(it->first, tmp2));
}
// replace old equations with simplified ones
equations2[j] = tmp1;
// dynamic iterations
if(!iteration_flag)
// for commutative SRs newton has converged after n+1 iterations, so use this number as default
iterations = equations2[j].size() + 1;
// do some real work here
std::map<VarPtr, SR> result = newton.solve_fixpoint(equations2[j], iterations);
// copy the results into the solution map
solution.insert(result.begin(), result.end());
}
return solution;
}
template <typename SR>
std::string result_string(std::map<VarPtr,SR> result)
{
std::stringstream ss;
for(auto r_it = result.begin(); r_it != result.end(); ++r_it)
ss << r_it->first << " == " << r_it->second << std::endl;
return ss.str();
}
int main(int argc, char* argv[])
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
( "scc", "apply newton method iteratively to strongly connected components of the equation graph" )
( "help,h", "print this help message" )
( "iterations,i", po::value<int>(), "specify the number of newton iterations. default is optimal number" )
//( "verbose", "enable verbose output" )
//( "debug", "enable debug output" )
( "test", "just for testing purposes ... explicit test defined in main()" )
( "file,f", po::value<std::string>(), "input file" )
( "float", "float semiring" )
( "rexp", "commutative regular expression semiring" )
( "slset", "explicit semilinear sets semiring (as vectors)" )
( "graphviz", "create the file graph.dot with the equation graph" )
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("test")) {
Newton<SemilinSetExp> newton;
std::vector<VarPtr> variables;
variables.push_back(Var::getVar("x"));
std::cout << "- newton (cnt-SR):" << std::endl;
std::vector<Polynomial<SemilinSetExp> > polynomials;
Polynomial<SemilinSetExp> f1 = Polynomial<SemilinSetExp>({
Monomial<SemilinSetExp>(SemilinSetExp(Var::getVar("a")), {Var::getVar("x"),Var::getVar("x")}),
Monomial<SemilinSetExp>(SemilinSetExp(Var::getVar("c")), {}) });
polynomials.push_back(f1);
Matrix<SemilinSetExp> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
/* auto s1 = CommutativeRExp(Var::getVar("a"));
auto s2 = CommutativeRExp(Var::getVar("b"));
auto m1 = Matrix<CommutativeRExp>(1,1,{s1});
auto m2 = Matrix<CommutativeRExp>(1,1,{s2});
*/
// this actually led to a strange bug with the ublas-matrix implementation!!
/* auto s1 = SemilinSetExp(Var::getVar("a"));
auto s2 = SemilinSetExp(Var::getVar("b"));
auto m1 = Matrix<SemilinSetExp>(1,1,{s1});
auto m2 = Matrix<SemilinSetExp>(1,1,{s2});
auto m3 = m1*m2;
std::cout << m3;
*/
return 0;
}
if(vm.count("help"))
{
std::cout << desc << std::endl;
return 0;
}
int iterations=0;
if(vm.count("iterations"))
iterations = vm["iterations"].as<int>();
// check if we can do something useful
if(!vm.count("float") && !vm.count("rexp") && !vm.count("slset")) // check for all compatible parameters
{
std::cout << "Please supply a supported semiring :)" << std::endl;
return 0;
}
std::vector<std::string> input;
std::string line;
if(vm.count("file"))
{
// we are reading the input from the given file
std::ifstream file;
file.open(vm["file"].as<std::string>(), std::ifstream::in);
if(file.fail())
std::cerr << "Could not open input file: " << vm["file"].as<std::string>() << std::endl;
while(std::getline(file, line))
input.push_back(line);
}
else
{
// we are reading from stdin
while(std::getline(std::cin, line))
input.push_back(line);
}
// join the input into one string
std::string input_all = std::accumulate(input.begin(), input.end(), std::string(""));
Parser p;
if(vm.count("slset")) {
std::vector<std::pair<VarPtr, Polynomial<SemilinSetExp>>> equations(p.slset_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
auto result = apply_newton<SemilinSetExp>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
else if(vm.count("rexp")) {
// parse the input into a list of (Var → Polynomial[SR])
std::vector<std::pair<VarPtr, Polynomial<CommutativeRExp>>> equations(p.rexp_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
// apply the newton method to the equations
auto result = apply_newton<CommutativeRExp>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
else if(vm.count("float")) {
std::vector<std::pair<VarPtr, Polynomial<FloatSemiring>>> equations(p.float_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
auto result = apply_newton<FloatSemiring>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
return 0;
}
<commit_msg>main: update for new {Mo,Poly}nomial implementation<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/program_options.hpp>
#include "float-semiring.h"
#include "semilinSetExp.h"
#include "matrix.h"
#include "polynomial.h"
#include "newton.h"
#include "commutativeRExp.h"
#include "parser.h"
template <typename SR>
struct VertexProp {
std::string name; // used for graphviz output
VarPtr var; // var and rex combines the equations in the vertex
Polynomial<SR> rex;
};
// group the equations to SCCs
template <typename SR>
std::vector<std::vector<std::pair<VarPtr, Polynomial<SR>>>> group_by_scc(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool graphviz_output)
{
// create map of variables to [0..n]. this is used to enumerate important variables in a clean way from 0 to n during graph construction
std::map<VarPtr, int> var_key;
// build the graph
boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProp<SR>> graph(equations.size());
for(auto e_it = equations.begin(); e_it != equations.end(); ++e_it)
{
// if the variable is not yet in the map insert it together with the size of
// the map. this way we get a unique identifier for the variable counting from 0 to n
if(var_key.find(e_it->first) == var_key.end())
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(e_it->first,var_key.size()));
int a = var_key.find(e_it->first)->second; // variable key
graph[a].var = e_it->first; // store VarPtr to the vertex
graph[a].name = e_it->first->string(); // store the name to the vertex
graph[a].rex = e_it->second; // store the regular expression to the vertex
auto v = e_it->second.get_variables(); // all variables of this rule;
for(auto v_it = v.begin(); v_it != v.end(); ++v_it)
{
if(var_key.find(*v_it) == var_key.end()) // variable is not yet in the map
var_key.insert(var_key.begin(), std::pair<VarPtr,int>(*v_it,var_key.size()));
int b = var_key.find(*v_it)->second; // variable key
boost::add_edge(a, b, graph);
}
} // graph is complete
if(graphviz_output)
{
// output the created graph to graph.dot
boost::dynamic_properties dp;
dp.property("label", boost::get(&VertexProp<SR>::name, graph)); // vertex name is the name of the equation
dp.property("node_id", get(boost::vertex_index, graph)); // this is needed
std::ofstream outf("graph.dot");
boost::write_graphviz_dp(outf, graph, dp);
}
// calculate strong connected components and store them in 'component'
std::vector<int> component(boost::num_vertices(graph));
boost::strong_components(graph,&component[0]);
// group neccessary equations together
int num_comp = *std::max_element(component.begin(), component.end()) + 1; // find the number of components
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> grouped_equations;
grouped_equations.resize(num_comp);
// iterate over all vertices (0 to n)
// collect the necessary variables + equations for every component
for (unsigned int j = 0; j != component.size(); ++j)
{
//std::cout << j << ", " << graph[j].var << " is in component " << component[j] << std::endl;
grouped_equations[component[j]].push_back(std::pair<VarPtr,Polynomial<SR>>(graph[j].var, graph[j].rex));
}
return grouped_equations;
}
// apply the newton method to the given input
template <typename SR>
std::map<VarPtr, SR> apply_newton(std::vector<std::pair<VarPtr, Polynomial<SR>>> equations, bool scc, bool iteration_flag, int iterations, bool graphviz_output)
{
// TODO: sanity checks on the input!
// generate an instance of the newton solver
Newton<SR> newton;
// if we use the scc method, group the equations
// the outer vector contains SCCs starting with a bottom SCC at 0
std::vector<std::vector<std::pair<VarPtr,Polynomial<SR>>>> equations2;
if(scc)
{
auto tmp = group_by_scc(equations, graphviz_output);
equations2.insert(equations2.begin(), tmp.begin(), tmp.end());
}
else if (!scc)
{
equations2.push_back(equations);
}
// this holds the solution
std::map<VarPtr, SR> solution;
// the same loop is used for both the scc and the non-scc variant
// in the non-scc variant, we just run once through the loop
//for(auto it1 = equations2.begin(); it != equations2.end(); ++it)
for(unsigned int j = 0; j != equations2.size(); ++j)
{
// use the solutions to get rid of variables in the remaining equations
// does nothing in the first round
std::vector<std::pair<VarPtr, Polynomial<SR>>> tmp1;
for(auto it = equations2[j].begin(); it != equations2[j].end(); ++it)
{ // it = (VarPtr, Polynomial[SR])
auto tmp2 = it->second.partial_eval(solution);
tmp1.push_back(std::pair<VarPtr, Polynomial<SR>>(it->first, tmp2));
}
// replace old equations with simplified ones
equations2[j] = tmp1;
// dynamic iterations
if(!iteration_flag)
// for commutative SRs newton has converged after n+1 iterations, so use this number as default
iterations = equations2[j].size() + 1;
// do some real work here
std::map<VarPtr, SR> result = newton.solve_fixpoint(equations2[j], iterations);
// copy the results into the solution map
solution.insert(result.begin(), result.end());
}
return solution;
}
template <typename SR>
std::string result_string(std::map<VarPtr,SR> result)
{
std::stringstream ss;
for(auto r_it = result.begin(); r_it != result.end(); ++r_it)
ss << r_it->first << " == " << r_it->second << std::endl;
return ss.str();
}
int main(int argc, char* argv[])
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
( "scc", "apply newton method iteratively to strongly connected components of the equation graph" )
( "help,h", "print this help message" )
( "iterations,i", po::value<int>(), "specify the number of newton iterations. default is optimal number" )
//( "verbose", "enable verbose output" )
//( "debug", "enable debug output" )
( "test", "just for testing purposes ... explicit test defined in main()" )
( "file,f", po::value<std::string>(), "input file" )
( "float", "float semiring" )
( "rexp", "commutative regular expression semiring" )
( "slset", "explicit semilinear sets semiring (as vectors)" )
( "graphviz", "create the file graph.dot with the equation graph" )
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("test")) {
Newton<SemilinSetExp> newton;
std::vector<VarPtr> variables;
variables.push_back(Var::getVar("x"));
std::cout << "- newton (cnt-SR):" << std::endl;
std::vector<Polynomial<SemilinSetExp> > polynomials;
Polynomial<SemilinSetExp> f1 = Polynomial<SemilinSetExp>({
{ SemilinSetExp(Var::getVar("a")), Monomial{ {Var::getVar("x"),Var::getVar("x")} } },
{ SemilinSetExp(Var::getVar("c")), Monomial{} } });
polynomials.push_back(f1);
Matrix<SemilinSetExp> result = newton.solve_fixpoint(polynomials, variables, 2);
std::cout << result << std::endl;
/* auto s1 = CommutativeRExp(Var::getVar("a"));
auto s2 = CommutativeRExp(Var::getVar("b"));
auto m1 = Matrix<CommutativeRExp>(1,1,{s1});
auto m2 = Matrix<CommutativeRExp>(1,1,{s2});
*/
// this actually led to a strange bug with the ublas-matrix implementation!!
/* auto s1 = SemilinSetExp(Var::getVar("a"));
auto s2 = SemilinSetExp(Var::getVar("b"));
auto m1 = Matrix<SemilinSetExp>(1,1,{s1});
auto m2 = Matrix<SemilinSetExp>(1,1,{s2});
auto m3 = m1*m2;
std::cout << m3;
*/
return 0;
}
if(vm.count("help"))
{
std::cout << desc << std::endl;
return 0;
}
int iterations=0;
if(vm.count("iterations"))
iterations = vm["iterations"].as<int>();
// check if we can do something useful
if(!vm.count("float") && !vm.count("rexp") && !vm.count("slset")) // check for all compatible parameters
{
std::cout << "Please supply a supported semiring :)" << std::endl;
return 0;
}
std::vector<std::string> input;
std::string line;
if(vm.count("file"))
{
// we are reading the input from the given file
std::ifstream file;
file.open(vm["file"].as<std::string>(), std::ifstream::in);
if(file.fail())
std::cerr << "Could not open input file: " << vm["file"].as<std::string>() << std::endl;
while(std::getline(file, line))
input.push_back(line);
}
else
{
// we are reading from stdin
while(std::getline(std::cin, line))
input.push_back(line);
}
// join the input into one string
std::string input_all = std::accumulate(input.begin(), input.end(), std::string(""));
Parser p;
if(vm.count("slset")) {
std::vector<std::pair<VarPtr, Polynomial<SemilinSetExp>>> equations(p.slset_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
auto result = apply_newton<SemilinSetExp>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
else if(vm.count("rexp")) {
// parse the input into a list of (Var → Polynomial[SR])
std::vector<std::pair<VarPtr, Polynomial<CommutativeRExp>>> equations(p.rexp_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
// apply the newton method to the equations
auto result = apply_newton<CommutativeRExp>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
else if(vm.count("float")) {
std::vector<std::pair<VarPtr, Polynomial<FloatSemiring>>> equations(p.float_parser(input_all));
if(equations.empty()) return -1;
for(auto eq_it = equations.begin(); eq_it != equations.end(); ++eq_it)
{
std::cout << "* " << eq_it->first << " → " << eq_it->second << std::endl;
}
auto result = apply_newton<FloatSemiring>(equations, vm.count("scc"), vm.count("iterations"), iterations, vm.count("graphviz"));
std::cout << result_string(result) << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>// From vmdconio.h
#define VMDCON_WARN 2
#define VMDCON_ERROR 3
extern "C" {
#include <vmdplugin.h>
#include <molfile_plugin.h>
}
#include <cassert>
#include <array>
#include <string>
#include <vector>
#include <unordered_map>
#include "chemfiles/File.hpp"
#include "chemfiles/Format.hpp"
#include "chemfiles/Atom.hpp"
#include "chemfiles/Frame.hpp"
#include "chemfiles/Residue.hpp"
#include "chemfiles/Topology.hpp"
#include "chemfiles/types.hpp"
#include "chemfiles/warnings.hpp"
#include "chemfiles/error_fmt.hpp"
#include "chemfiles/external/span.hpp"
#include "chemfiles/external/optional.hpp"
#include "chemfiles/formats/Molfile.hpp"
using namespace chemfiles;
/******************************************************************************/
#define PLUGINS_DATA(FORMAT, PLUGIN, READER, VELOCITIES) \
extern "C" int PLUGIN##_register(void*, vmdplugin_register_cb); /*NOLINT*/ \
extern "C" int PLUGIN##_fini(void); /*NOLINT*/ \
extern "C" int PLUGIN##_init(void); /*NOLINT*/ \
template <> struct MolfilePluginData<FORMAT> { \
int init() { return PLUGIN##_init(); } \
int registration(void* data, vmdplugin_register_cb callback) { \
return PLUGIN##_register(data, callback); \
} \
int fini() { return PLUGIN##_fini(); } \
std::string format() const {return #FORMAT;} \
std::string plugin_name() const {return #PLUGIN;} \
std::string reader() const {return #READER;} \
bool have_velocities() const {return VELOCITIES;} \
}
namespace chemfiles {
PLUGINS_DATA(DCD, dcdplugin, dcd, false);
PLUGINS_DATA(TRJ, gromacsplugin, trj, false);
PLUGINS_DATA(LAMMPS, lammpsplugin, lammpstrj, true);
PLUGINS_DATA(MOLDEN, moldenplugin, molden, false);
}
#undef PLUGINS_FUNCTIONS
/******************************************************************************/
template <MolfileFormat F> static int register_plugin(void* user_data, vmdplugin_t* vmd_plugin) {
auto user_plugin = static_cast<molfile_plugin_t**>(user_data);
assert(std::string(MOLFILE_PLUGIN_TYPE) == std::string(vmd_plugin->type));
auto plugin = reinterpret_cast<molfile_plugin_t*>(vmd_plugin);
// When this callback is called multiple times with more than one plugin,
// only register the one whe want
if (MolfilePluginData<F>().reader() == plugin->name) {
*user_plugin = plugin;
}
return VMDPLUGIN_SUCCESS;
}
static int molfiles_to_chemfiles_warning(int level, const char* message) {
if (level == VMDCON_ERROR || level == VMDCON_WARN) {
send_warning(message);
}
return 0;
}
/******************************************************************************/
template <MolfileFormat F>
Molfile<F>::Molfile(std::string path, File::Mode mode, File::Compression compression)
: path_(std::move(path)), plugin_handle_(nullptr), data_(nullptr), natoms_(0) {
if (mode != File::READ) {
throw format_error(
"molfiles based format {} is only available in read mode", plugin_data_.format()
);
}
if (compression != File::DEFAULT) {
throw format_error(
"molfiles based format {} do not support compression", plugin_data_.format()
);
}
if (plugin_data_.init()) {
throw format_error(
"could not initialize the {} plugin", plugin_data_.format()
);
}
if (plugin_data_.registration(&plugin_handle_, register_plugin<F>)) {
throw format_error(
"could not register the {} plugin", plugin_data_.format()
);
}
// Check the ABI version of the plugin
assert(plugin_handle_->abiversion == vmdplugin_ABIVERSION);
// Redirect console output to chemfiles warnings
plugin_handle_->cons_fputs = molfiles_to_chemfiles_warning;
// Check that needed functions are here
if (plugin_handle_->open_file_read == nullptr ||
(plugin_handle_->read_next_timestep == nullptr && plugin_handle_->read_timestep == nullptr ) ||
(plugin_handle_->close_file_read == nullptr )) {
throw format_error(
"the {} plugin does not have read capacities", plugin_data_.format()
);
}
data_ = plugin_handle_->open_file_read(
path_.c_str(), plugin_handle_->name, &natoms_
);
if (data_ == nullptr) {
throw format_error(
"could not open the file at '{}' with {} plugin", path_, plugin_data_.format()
);
}
read_topology();
}
template <MolfileFormat F> Molfile<F>::~Molfile() {
if (data_) {
plugin_handle_->close_file_read(data_);
}
plugin_data_.fini();
}
template <MolfileFormat F> int Molfile<F>::read_next_timestep(molfile_timestep_t* timestep) {
if (plugin_handle_->read_next_timestep != nullptr) {
// This function is provided by classical molecular simulation format.
return plugin_handle_->read_next_timestep(data_, natoms_, timestep);
} else if (plugin_handle_->read_timestep != nullptr) {
// This function is provided by quantum molecular simulation format.
return plugin_handle_->read_timestep(
data_, natoms_, timestep, nullptr, nullptr
);
} else {
throw format_error(
"both read_next_timestep and read_timestep are missing in this "
"plugin. This is a bug"
);
}
}
template <MolfileFormat F> void Molfile<F>::read(Frame& frame) {
std::vector<float> coords(3 * static_cast<size_t>(natoms_));
std::vector<float> velocities(0);
molfile_timestep_t timestep{nullptr, nullptr, 0, 0, 0, 0, 0, 0, 0};
timestep.coords = coords.data();
if (plugin_data_.have_velocities()) {
velocities.resize(3 * static_cast<size_t>(natoms_));
timestep.velocities = velocities.data();
}
int status = read_next_timestep(×tep);
if (status != MOLFILE_SUCCESS) {
throw format_error(
"error while reading the file at '{}' with {} plugin",
path_, plugin_data_.format()
);
}
if (topology_) {
frame.resize(topology_->size());
frame.set_topology(*topology_);
}
molfile_to_frame(timestep, frame);
frames_.emplace_back(std::move(frame.clone()));
}
template <MolfileFormat F> void Molfile<F>::read_step(size_t step, Frame& frame) {
while (step >= frames_.size()) {
Frame new_frame;
this->read(new_frame);
}
frame = frames_.at(step).clone();
}
template <MolfileFormat F> size_t Molfile<F>::nsteps() {
if (plugin_handle_->read_next_timestep == nullptr) {
// FIXME: this is hacky, but the molden plugin does not respect a NULL
// argument for molfile_timestep_t, so for now we are only able to read
// a sinle step from all the QM format plugins.
return 1;
}
size_t n = 0;
int status = MOLFILE_SUCCESS;
while (true) {
status = read_next_timestep(nullptr);
if (status == MOLFILE_SUCCESS) {
n++;
} else {
break;
}
}
// We need to close and re-open the file
plugin_handle_->close_file_read(data_);
int unused = 0;
data_ = plugin_handle_->open_file_read(path_.c_str(), plugin_handle_->name, &unused);
read_topology();
return n;
}
template <MolfileFormat F>
void Molfile<F>::molfile_to_frame(const molfile_timestep_t& timestep,
Frame& frame) {
frame.set_cell({
static_cast<double>(timestep.A),
static_cast<double>(timestep.B),
static_cast<double>(timestep.C),
static_cast<double>(timestep.alpha),
static_cast<double>(timestep.beta),
static_cast<double>(timestep.gamma)
});
frame.resize(static_cast<size_t>(natoms_));
auto positions = frame.positions();
for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
positions[i][0] = static_cast<double>(timestep.coords[3 * i + 0]);
positions[i][1] = static_cast<double>(timestep.coords[3 * i + 1]);
positions[i][2] = static_cast<double>(timestep.coords[3 * i + 2]);
}
if (plugin_data_.have_velocities()) {
frame.add_velocities();
auto velocities = frame.velocities();
for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
(*velocities)[i][0] = static_cast<double>(timestep.velocities[3 * i + 0]);
(*velocities)[i][1] = static_cast<double>(timestep.velocities[3 * i + 1]);
(*velocities)[i][2] = static_cast<double>(timestep.velocities[3 * i + 2]);
}
}
}
template <MolfileFormat F> void Molfile<F>::read_topology() {
if (plugin_handle_->read_structure == nullptr) {
return;
}
std::vector<molfile_atom_t> atoms(static_cast<size_t>(natoms_));
int optflags = 0;
int status = plugin_handle_->read_structure(data_, &optflags, atoms.data());
if (status != MOLFILE_SUCCESS) {
throw format_error(
"could not read the molecule structure with {} plugin",
plugin_data_.format()
);
}
topology_ = Topology();
auto residues = std::unordered_map<int64_t, Residue>();
size_t atom_id = 0;
for (auto& molfile_atom : atoms) {
Atom atom(molfile_atom.name, molfile_atom.type);
if ((optflags & MOLFILE_MASS) != 0) {
atom.set_mass(static_cast<double>(molfile_atom.mass));
}
if ((optflags & MOLFILE_CHARGE) != 0) {
atom.set_charge(static_cast<double>(molfile_atom.charge));
}
topology_->add_atom(std::move(atom));
if (molfile_atom.resname != std::string("")) {
auto resid = static_cast<int64_t>(molfile_atom.resid);
auto residue = Residue(molfile_atom.resname, resid);
auto inserted = residues.insert({resid, std::move(residue)});
inserted.first->second.add_atom(atom_id);
}
atom_id++;
}
if (plugin_handle_->read_bonds == nullptr) {
return;
}
int nbonds = 0;
int* from = nullptr;
int* to = nullptr;
int dummy = 0;
float* _float = nullptr;
int* _int = nullptr;
char** _char = nullptr;
status = plugin_handle_->read_bonds(
data_, &nbonds, &from, &to, &_float, &_int, &dummy, &_char
);
if (status != MOLFILE_SUCCESS) {
throw format_error(
"could not read bonds with {} plugin", plugin_data_.format()
);
}
for (size_t i = 0; i < static_cast<size_t>(nbonds); i++) {
// Indexes are 1-based in Molfile
topology_->add_bond(static_cast<size_t>(from[i] - 1),
static_cast<size_t>(to[i]) - 1);
}
}
// Instanciate all the templates
template class chemfiles::Molfile<DCD>;
template class chemfiles::Molfile<TRJ>;
template class chemfiles::Molfile<LAMMPS>;
template class chemfiles::Molfile<MOLDEN>;
template<> FormatInfo chemfiles::format_information<Molfile<DCD>>() {
return FormatInfo("DCD").with_extension(".dcd").description(
"DCD binary format"
);
}
template<> FormatInfo chemfiles::format_information<Molfile<TRJ>>() {
return FormatInfo("TRJ").with_extension(".trj").description(
"GROMACS .trj binary format"
);
}
template<> FormatInfo chemfiles::format_information<Molfile<LAMMPS>>() {
return FormatInfo("LAMMPS").with_extension(".lammpstrj").description(
"LAMMPS text trajectory format"
);
}
template<> FormatInfo chemfiles::format_information<Molfile<MOLDEN>>() {
return FormatInfo("Molden").with_extension(".molden").description(
"Molden text format"
);
}
<commit_msg>Do not std::move temporary object<commit_after>// From vmdconio.h
#define VMDCON_WARN 2
#define VMDCON_ERROR 3
extern "C" {
#include <vmdplugin.h>
#include <molfile_plugin.h>
}
#include <cassert>
#include <array>
#include <string>
#include <vector>
#include <unordered_map>
#include "chemfiles/File.hpp"
#include "chemfiles/Format.hpp"
#include "chemfiles/Atom.hpp"
#include "chemfiles/Frame.hpp"
#include "chemfiles/Residue.hpp"
#include "chemfiles/Topology.hpp"
#include "chemfiles/types.hpp"
#include "chemfiles/warnings.hpp"
#include "chemfiles/error_fmt.hpp"
#include "chemfiles/external/span.hpp"
#include "chemfiles/external/optional.hpp"
#include "chemfiles/formats/Molfile.hpp"
using namespace chemfiles;
/******************************************************************************/
#define PLUGINS_DATA(FORMAT, PLUGIN, READER, VELOCITIES) \
extern "C" int PLUGIN##_register(void*, vmdplugin_register_cb); /*NOLINT*/ \
extern "C" int PLUGIN##_fini(void); /*NOLINT*/ \
extern "C" int PLUGIN##_init(void); /*NOLINT*/ \
template <> struct MolfilePluginData<FORMAT> { \
int init() { return PLUGIN##_init(); } \
int registration(void* data, vmdplugin_register_cb callback) { \
return PLUGIN##_register(data, callback); \
} \
int fini() { return PLUGIN##_fini(); } \
std::string format() const {return #FORMAT;} \
std::string plugin_name() const {return #PLUGIN;} \
std::string reader() const {return #READER;} \
bool have_velocities() const {return VELOCITIES;} \
}
namespace chemfiles {
PLUGINS_DATA(DCD, dcdplugin, dcd, false);
PLUGINS_DATA(TRJ, gromacsplugin, trj, false);
PLUGINS_DATA(LAMMPS, lammpsplugin, lammpstrj, true);
PLUGINS_DATA(MOLDEN, moldenplugin, molden, false);
}
#undef PLUGINS_FUNCTIONS
/******************************************************************************/
template <MolfileFormat F> static int register_plugin(void* user_data, vmdplugin_t* vmd_plugin) {
auto user_plugin = static_cast<molfile_plugin_t**>(user_data);
assert(std::string(MOLFILE_PLUGIN_TYPE) == std::string(vmd_plugin->type));
auto plugin = reinterpret_cast<molfile_plugin_t*>(vmd_plugin);
// When this callback is called multiple times with more than one plugin,
// only register the one whe want
if (MolfilePluginData<F>().reader() == plugin->name) {
*user_plugin = plugin;
}
return VMDPLUGIN_SUCCESS;
}
static int molfiles_to_chemfiles_warning(int level, const char* message) {
if (level == VMDCON_ERROR || level == VMDCON_WARN) {
send_warning(message);
}
return 0;
}
/******************************************************************************/
template <MolfileFormat F>
Molfile<F>::Molfile(std::string path, File::Mode mode, File::Compression compression)
: path_(std::move(path)), plugin_handle_(nullptr), data_(nullptr), natoms_(0) {
if (mode != File::READ) {
throw format_error(
"molfiles based format {} is only available in read mode", plugin_data_.format()
);
}
if (compression != File::DEFAULT) {
throw format_error(
"molfiles based format {} do not support compression", plugin_data_.format()
);
}
if (plugin_data_.init()) {
throw format_error(
"could not initialize the {} plugin", plugin_data_.format()
);
}
if (plugin_data_.registration(&plugin_handle_, register_plugin<F>)) {
throw format_error(
"could not register the {} plugin", plugin_data_.format()
);
}
// Check the ABI version of the plugin
assert(plugin_handle_->abiversion == vmdplugin_ABIVERSION);
// Redirect console output to chemfiles warnings
plugin_handle_->cons_fputs = molfiles_to_chemfiles_warning;
// Check that needed functions are here
if (plugin_handle_->open_file_read == nullptr ||
(plugin_handle_->read_next_timestep == nullptr && plugin_handle_->read_timestep == nullptr ) ||
(plugin_handle_->close_file_read == nullptr )) {
throw format_error(
"the {} plugin does not have read capacities", plugin_data_.format()
);
}
data_ = plugin_handle_->open_file_read(
path_.c_str(), plugin_handle_->name, &natoms_
);
if (data_ == nullptr) {
throw format_error(
"could not open the file at '{}' with {} plugin", path_, plugin_data_.format()
);
}
read_topology();
}
template <MolfileFormat F> Molfile<F>::~Molfile() {
if (data_) {
plugin_handle_->close_file_read(data_);
}
plugin_data_.fini();
}
template <MolfileFormat F> int Molfile<F>::read_next_timestep(molfile_timestep_t* timestep) {
if (plugin_handle_->read_next_timestep != nullptr) {
// This function is provided by classical molecular simulation format.
return plugin_handle_->read_next_timestep(data_, natoms_, timestep);
} else if (plugin_handle_->read_timestep != nullptr) {
// This function is provided by quantum molecular simulation format.
return plugin_handle_->read_timestep(
data_, natoms_, timestep, nullptr, nullptr
);
} else {
throw format_error(
"both read_next_timestep and read_timestep are missing in this "
"plugin. This is a bug"
);
}
}
template <MolfileFormat F> void Molfile<F>::read(Frame& frame) {
std::vector<float> coords(3 * static_cast<size_t>(natoms_));
std::vector<float> velocities(0);
molfile_timestep_t timestep{nullptr, nullptr, 0, 0, 0, 0, 0, 0, 0};
timestep.coords = coords.data();
if (plugin_data_.have_velocities()) {
velocities.resize(3 * static_cast<size_t>(natoms_));
timestep.velocities = velocities.data();
}
int status = read_next_timestep(×tep);
if (status != MOLFILE_SUCCESS) {
throw format_error(
"error while reading the file at '{}' with {} plugin",
path_, plugin_data_.format()
);
}
if (topology_) {
frame.resize(topology_->size());
frame.set_topology(*topology_);
}
molfile_to_frame(timestep, frame);
frames_.emplace_back(frame.clone());
}
template <MolfileFormat F> void Molfile<F>::read_step(size_t step, Frame& frame) {
while (step >= frames_.size()) {
Frame new_frame;
this->read(new_frame);
}
frame = frames_.at(step).clone();
}
template <MolfileFormat F> size_t Molfile<F>::nsteps() {
if (plugin_handle_->read_next_timestep == nullptr) {
// FIXME: this is hacky, but the molden plugin does not respect a NULL
// argument for molfile_timestep_t, so for now we are only able to read
// a sinle step from all the QM format plugins.
return 1;
}
size_t n = 0;
int status = MOLFILE_SUCCESS;
while (true) {
status = read_next_timestep(nullptr);
if (status == MOLFILE_SUCCESS) {
n++;
} else {
break;
}
}
// We need to close and re-open the file
plugin_handle_->close_file_read(data_);
int unused = 0;
data_ = plugin_handle_->open_file_read(path_.c_str(), plugin_handle_->name, &unused);
read_topology();
return n;
}
template <MolfileFormat F>
void Molfile<F>::molfile_to_frame(const molfile_timestep_t& timestep,
Frame& frame) {
frame.set_cell({
static_cast<double>(timestep.A),
static_cast<double>(timestep.B),
static_cast<double>(timestep.C),
static_cast<double>(timestep.alpha),
static_cast<double>(timestep.beta),
static_cast<double>(timestep.gamma)
});
frame.resize(static_cast<size_t>(natoms_));
auto positions = frame.positions();
for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
positions[i][0] = static_cast<double>(timestep.coords[3 * i + 0]);
positions[i][1] = static_cast<double>(timestep.coords[3 * i + 1]);
positions[i][2] = static_cast<double>(timestep.coords[3 * i + 2]);
}
if (plugin_data_.have_velocities()) {
frame.add_velocities();
auto velocities = frame.velocities();
for (size_t i = 0; i < static_cast<size_t>(natoms_); i++) {
(*velocities)[i][0] = static_cast<double>(timestep.velocities[3 * i + 0]);
(*velocities)[i][1] = static_cast<double>(timestep.velocities[3 * i + 1]);
(*velocities)[i][2] = static_cast<double>(timestep.velocities[3 * i + 2]);
}
}
}
template <MolfileFormat F> void Molfile<F>::read_topology() {
if (plugin_handle_->read_structure == nullptr) {
return;
}
std::vector<molfile_atom_t> atoms(static_cast<size_t>(natoms_));
int optflags = 0;
int status = plugin_handle_->read_structure(data_, &optflags, atoms.data());
if (status != MOLFILE_SUCCESS) {
throw format_error(
"could not read the molecule structure with {} plugin",
plugin_data_.format()
);
}
topology_ = Topology();
auto residues = std::unordered_map<int64_t, Residue>();
size_t atom_id = 0;
for (auto& molfile_atom : atoms) {
Atom atom(molfile_atom.name, molfile_atom.type);
if ((optflags & MOLFILE_MASS) != 0) {
atom.set_mass(static_cast<double>(molfile_atom.mass));
}
if ((optflags & MOLFILE_CHARGE) != 0) {
atom.set_charge(static_cast<double>(molfile_atom.charge));
}
topology_->add_atom(std::move(atom));
if (molfile_atom.resname != std::string("")) {
auto resid = static_cast<int64_t>(molfile_atom.resid);
auto residue = Residue(molfile_atom.resname, resid);
auto inserted = residues.insert({resid, std::move(residue)});
inserted.first->second.add_atom(atom_id);
}
atom_id++;
}
if (plugin_handle_->read_bonds == nullptr) {
return;
}
int nbonds = 0;
int* from = nullptr;
int* to = nullptr;
int dummy = 0;
float* _float = nullptr;
int* _int = nullptr;
char** _char = nullptr;
status = plugin_handle_->read_bonds(
data_, &nbonds, &from, &to, &_float, &_int, &dummy, &_char
);
if (status != MOLFILE_SUCCESS) {
throw format_error(
"could not read bonds with {} plugin", plugin_data_.format()
);
}
for (size_t i = 0; i < static_cast<size_t>(nbonds); i++) {
// Indexes are 1-based in Molfile
topology_->add_bond(static_cast<size_t>(from[i] - 1),
static_cast<size_t>(to[i]) - 1);
}
}
// Instanciate all the templates
template class chemfiles::Molfile<DCD>;
template class chemfiles::Molfile<TRJ>;
template class chemfiles::Molfile<LAMMPS>;
template class chemfiles::Molfile<MOLDEN>;
template<> FormatInfo chemfiles::format_information<Molfile<DCD>>() {
return FormatInfo("DCD").with_extension(".dcd").description(
"DCD binary format"
);
}
template<> FormatInfo chemfiles::format_information<Molfile<TRJ>>() {
return FormatInfo("TRJ").with_extension(".trj").description(
"GROMACS .trj binary format"
);
}
template<> FormatInfo chemfiles::format_information<Molfile<LAMMPS>>() {
return FormatInfo("LAMMPS").with_extension(".lammpstrj").description(
"LAMMPS text trajectory format"
);
}
template<> FormatInfo chemfiles::format_information<Molfile<MOLDEN>>() {
return FormatInfo("Molden").with_extension(".molden").description(
"Molden text format"
);
}
<|endoftext|>
|
<commit_before>/******************************************************************
*
* uHTTP for C++
*
* Copyright (C) Satoshi Konno 2002
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <stdlib.h>
#include <uhttp/http/HTTP.h>
#include <uhttp/http/HTTPStatus.h>
#include <uhttp/util/StringTokenizer.h>
#include <uhttp/util/StringUtil.h>
using namespace uHTTP;
using namespace uHTTP;
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
HTTPStatus::HTTPStatus() {
setVersion("");
setStatusCode(0);
setReasonPhrase("");
}
HTTPStatus::HTTPStatus(const std::string &ver, int code, const std::string &reason) {
setVersion(ver);
setStatusCode(code);
setReasonPhrase(reason);
}
HTTPStatus::HTTPStatus(const std::string &lineStr) {
set(lineStr);
}
////////////////////////////////////////////////
// set
////////////////////////////////////////////////
void HTTPStatus::set(const std::string &lineStr) {
if (lineStr.length() <= 0) {
setVersion(HTTP::VER);
setStatusCode(HTTP::INTERNAL_SERVER_ERROR);
setReasonPhrase(HTTP::StatusCode2String(HTTP::INTERNAL_SERVER_ERROR));
return;
}
StringTokenizer st(lineStr, HTTP::STATUS_LINE_DELIM);
std::string trimBuf;
if (st.hasMoreTokens() == false)
return;
std::string ver = st.nextToken();
setVersion(StringTrim(ver.c_str(), trimBuf));
if (st.hasMoreTokens() == false)
return;
std::string codeStr = st.nextToken();
int code = atoi(codeStr.c_str());
setStatusCode(code);
std::string reason = "";
while (st.hasMoreTokens() == true) {
if (0 < reason.length())
reason.append(" ");
reason.append(st.nextToken());
}
setReasonPhrase(StringTrim(reason.c_str(), trimBuf));
}
////////////////////////////////////////////////
// IsStatusCodeSuccess
////////////////////////////////////////////////
bool uHTTP::HTTP::IsStatusCodeSuccess(int statCode) {
if (200 <= statCode && statCode < 300)
return true;
return false;
}
////////////////////////////////////////////////
// StatusCode2String
////////////////////////////////////////////////
const std::string &uHTTP::HTTP::StatusCode2String(int code) {
int errType = code - (code % 100);
if (errType == 100) {
switch (code) {
case PROCESSING: return PROCESSING_STRING;
}
return CONTINUE_STRING;
}
if (errType == 200) {
switch (code) {
case ACCEPTED: return ACCEPTED_STRING;
case NO_CONTENT: return NO_CONTENT_STRING;
case PARTIAL_CONTENT: return PARTIAL_CONTENT_STRING;
}
return OK_REQUEST_STRING;
}
if (errType == 400) {
switch (code) {
case NOT_FOUND: return NOT_FOUND_STING;
case PRECONDITION_FAILED: return PRECONDITION_FAILED_STING;
case INVALID_RANGE: return INVALID_RANGE_STING;
}
return BAD_REQUEST_STRING;
}
if (errType == 500) {
return INTERNAL_SERVER_ERROR_STRING;
}
if (errType == 600) {
return INTERNAL_CLIENT_ERROR_STRING;
}
return UNKOWN_ERROR_STRING;
}
<commit_msg>* Removed extra namespace.<commit_after>/******************************************************************
*
* uHTTP for C++
*
* Copyright (C) Satoshi Konno 2002
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <stdlib.h>
#include <uhttp/http/HTTP.h>
#include <uhttp/http/HTTPStatus.h>
#include <uhttp/util/StringTokenizer.h>
#include <uhttp/util/StringUtil.h>
using namespace uHTTP;
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
HTTPStatus::HTTPStatus() {
setVersion("");
setStatusCode(0);
setReasonPhrase("");
}
HTTPStatus::HTTPStatus(const std::string &ver, int code, const std::string &reason) {
setVersion(ver);
setStatusCode(code);
setReasonPhrase(reason);
}
HTTPStatus::HTTPStatus(const std::string &lineStr) {
set(lineStr);
}
////////////////////////////////////////////////
// set
////////////////////////////////////////////////
void HTTPStatus::set(const std::string &lineStr) {
if (lineStr.length() <= 0) {
setVersion(HTTP::VER);
setStatusCode(HTTP::INTERNAL_SERVER_ERROR);
setReasonPhrase(HTTP::StatusCode2String(HTTP::INTERNAL_SERVER_ERROR));
return;
}
StringTokenizer st(lineStr, HTTP::STATUS_LINE_DELIM);
std::string trimBuf;
if (st.hasMoreTokens() == false)
return;
std::string ver = st.nextToken();
setVersion(StringTrim(ver.c_str(), trimBuf));
if (st.hasMoreTokens() == false)
return;
std::string codeStr = st.nextToken();
int code = atoi(codeStr.c_str());
setStatusCode(code);
std::string reason = "";
while (st.hasMoreTokens() == true) {
if (0 < reason.length())
reason.append(" ");
reason.append(st.nextToken());
}
setReasonPhrase(StringTrim(reason.c_str(), trimBuf));
}
////////////////////////////////////////////////
// IsStatusCodeSuccess
////////////////////////////////////////////////
bool uHTTP::HTTP::IsStatusCodeSuccess(int statCode) {
if (200 <= statCode && statCode < 300)
return true;
return false;
}
////////////////////////////////////////////////
// StatusCode2String
////////////////////////////////////////////////
const std::string &uHTTP::HTTP::StatusCode2String(int code) {
int errType = code - (code % 100);
if (errType == 100) {
switch (code) {
case PROCESSING: return PROCESSING_STRING;
}
return CONTINUE_STRING;
}
if (errType == 200) {
switch (code) {
case ACCEPTED: return ACCEPTED_STRING;
case NO_CONTENT: return NO_CONTENT_STRING;
case PARTIAL_CONTENT: return PARTIAL_CONTENT_STRING;
}
return OK_REQUEST_STRING;
}
if (errType == 400) {
switch (code) {
case NOT_FOUND: return NOT_FOUND_STING;
case PRECONDITION_FAILED: return PRECONDITION_FAILED_STING;
case INVALID_RANGE: return INVALID_RANGE_STING;
}
return BAD_REQUEST_STRING;
}
if (errType == 500) {
return INTERNAL_SERVER_ERROR_STRING;
}
if (errType == 600) {
return INTERNAL_CLIENT_ERROR_STRING;
}
return UNKOWN_ERROR_STRING;
}
<|endoftext|>
|
<commit_before>#include <stan/services/util/experimental_message.hpp>
#include <gtest/gtest.h>
#include <stan/callbacks/stream_writer.hpp>
#include <sstream>
TEST(ServicesUtil, experimental_message) {
std::stringstream ss;
stan::callbacks::stream_writer writer(ss);
stan::services::util::experimental_message(writer);
EXPECT_TRUE(ss.str().find("EXPERIMENTAL ALGORITHM") != std::string::npos);
}
<commit_msg>updating experimental message test<commit_after>#include <stan/services/util/experimental_message.hpp>
#include <gtest/gtest.h>
#include <test/unit/services/instrumented_callbacks.hpp>
#include <sstream>
TEST(ServicesUtil, experimental_message) {
stan::test::unit::instrumented_logger logger;
stan::services::util::experimental_message(logger);
EXPECT_EQ(1, logger.find_info("EXPERIMENTAL ALGORITHM"));
}
<|endoftext|>
|
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <string>
#include <getopt.h>
#include "server.h"
#include "logger.h"
#include "libconfig.h++"
#include "initConfig.h"
#include "singletonConfig.h"
#include "watcherd.h"
using namespace std;
using namespace watcher;
using namespace libconfig;
option Options[] = {
{ "help", 0, NULL, 'h' },
{ "config", 1, NULL, 'c' },
{ "database", 1, NULL, 'd' },
{ "read-only", 1, NULL, 'r' },
{ 0, 0, NULL, 0 }
};
void usage(const char *progName, bool exitp)
{
cout << "Usage: " << basename(progName) << " [-c config filename]" << endl;
cout << "Args: " << endl;
cout << " -h, show this messsage and exit." << endl;
cout << " -d database, use this event database when running watcherd" << endl;
cout << " -c configfile - If not given a filename of the form \""<< basename(progName) << ".cfg\" is assumed." << endl;
cout << " -r, --read-only - do not write events to the database." << endl;
cout << "If a configuration file is not found on startup, a default one will be created, used, and saved on program exit." << endl;
if (exitp)
exit(EXIT_FAILURE);
}
DECLARE_GLOBAL_LOGGER("watcherdMain");
int main(int argc, char* argv[])
{
TRACE_ENTER();
int i;
bool readOnly = false;
std::string dbPath;
while ((i = getopt_long(argc, argv, "hc:d:r", Options, NULL)) != -1) {
switch (i) {
case 'c':
//handled below
break;
case 'r':
readOnly = true;
break;
case 'd':
dbPath=string(optarg);
break;
default:
usage(argv[0], true);
}
}
string configFilename;
Config &config=SingletonConfig::instance();
SingletonConfig::lock();
if (false==initConfig(config, argc, argv, configFilename))
{
cerr << "Error reading configuration file, unable to continue." << endl;
cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl;
return 1;
}
SingletonConfig::unlock();
string logConf("log.properties");
if (!config.lookupValue("logPropertiesFile", logConf))
{
cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf
<< " and adding it to the configuration file." << endl;
config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf;
}
LOAD_LOG_PROPS(logConf);
LOG_INFO("Logger initialized from file \"" << logConf << "\"");
string address("glory");
string port("8095");
size_t numThreads=8;
if (!config.lookupValue("server", address))
{
LOG_INFO("'server' not found in the configuration file, using default: " << address
<< " and adding this to the configuration file.");
config.getRoot().add("server", libconfig::Setting::TypeString) = address;
}
if (!config.lookupValue("port", port))
{
LOG_INFO("'port' not found in the configuration file, using default: " << port
<< " and adding this to the configuration file.");
config.getRoot().add("port", libconfig::Setting::TypeString)=port;
}
if (!config.lookupValue("serverThreadNum", numThreads))
{
LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads
<< " and adding this to the configuration file.");
config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads);
}
std::string tmpDBPath("event.db");
if (!config.lookupValue("databasePath", tmpDBPath))
{
LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath
<< " and adding this to the configuration file.");
config.getRoot().add("databasePath", libconfig::Setting::TypeString)=tmpDBPath;
}
if (dbPath.size())
config.getRoot()["databasePath"]=dbPath;
WatcherdPtr theWatcherDaemon(new Watcherd(readOnly));
try
{
theWatcherDaemon->run(address, port, (int)numThreads);
}
catch (std::exception &e)
{
LOG_FATAL("Caught exception in main(): " << e.what());
std::cerr << "exception: " << e.what() << "\n";
}
// Save any configuration changes made during the run.
LOG_INFO("Saving last known configuration to " << configFilename);
SingletonConfig::lock();
config.writeFile(configFilename.c_str());
return 0;
}
<commit_msg>default hostname is now "localhost" so everyone but me can actually run watcherd by just typing "watcherd".<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <string>
#include <getopt.h>
#include "server.h"
#include "logger.h"
#include "libconfig.h++"
#include "initConfig.h"
#include "singletonConfig.h"
#include "watcherd.h"
using namespace std;
using namespace watcher;
using namespace libconfig;
option Options[] = {
{ "help", 0, NULL, 'h' },
{ "config", 1, NULL, 'c' },
{ "database", 1, NULL, 'd' },
{ "read-only", 1, NULL, 'r' },
{ 0, 0, NULL, 0 }
};
void usage(const char *progName, bool exitp)
{
cout << "Usage: " << basename(progName) << " [-c config filename]" << endl;
cout << "Args: " << endl;
cout << " -h, show this messsage and exit." << endl;
cout << " -d database, use this event database when running watcherd" << endl;
cout << " -c configfile - If not given a filename of the form \""<< basename(progName) << ".cfg\" is assumed." << endl;
cout << " -r, --read-only - do not write events to the database." << endl;
cout << "If a configuration file is not found on startup, a default one will be created, used, and saved on program exit." << endl;
if (exitp)
exit(EXIT_FAILURE);
}
DECLARE_GLOBAL_LOGGER("watcherdMain");
int main(int argc, char* argv[])
{
TRACE_ENTER();
int i;
bool readOnly = false;
std::string dbPath;
while ((i = getopt_long(argc, argv, "hc:d:r", Options, NULL)) != -1) {
switch (i) {
case 'c':
//handled below
break;
case 'r':
readOnly = true;
break;
case 'd':
dbPath=string(optarg);
break;
default:
usage(argv[0], true);
}
}
string configFilename;
Config &config=SingletonConfig::instance();
SingletonConfig::lock();
if (false==initConfig(config, argc, argv, configFilename))
{
cerr << "Error reading configuration file, unable to continue." << endl;
cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl;
return 1;
}
SingletonConfig::unlock();
string logConf("log.properties");
if (!config.lookupValue("logPropertiesFile", logConf))
{
cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf
<< " and adding it to the configuration file." << endl;
config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf;
}
LOAD_LOG_PROPS(logConf);
LOG_INFO("Logger initialized from file \"" << logConf << "\"");
string address("localhost");
string port("8095");
size_t numThreads=8;
if (!config.lookupValue("server", address))
{
LOG_INFO("'server' not found in the configuration file, using default: " << address
<< " and adding this to the configuration file.");
config.getRoot().add("server", libconfig::Setting::TypeString) = address;
}
if (!config.lookupValue("port", port))
{
LOG_INFO("'port' not found in the configuration file, using default: " << port
<< " and adding this to the configuration file.");
config.getRoot().add("port", libconfig::Setting::TypeString)=port;
}
if (!config.lookupValue("serverThreadNum", numThreads))
{
LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads
<< " and adding this to the configuration file.");
config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads);
}
std::string tmpDBPath("event.db");
if (!config.lookupValue("databasePath", tmpDBPath))
{
LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath
<< " and adding this to the configuration file.");
config.getRoot().add("databasePath", libconfig::Setting::TypeString)=tmpDBPath;
}
if (dbPath.size())
config.getRoot()["databasePath"]=dbPath;
WatcherdPtr theWatcherDaemon(new Watcherd(readOnly));
try
{
theWatcherDaemon->run(address, port, (int)numThreads);
}
catch (std::exception &e)
{
LOG_FATAL("Caught exception in main(): " << e.what());
std::cerr << "exception: " << e.what() << "\n";
}
// Save any configuration changes made during the run.
LOG_INFO("Saving last known configuration to " << configFilename);
SingletonConfig::lock();
config.writeFile(configFilename.c_str());
return 0;
}
<|endoftext|>
|
<commit_before>#include "apt_source_manager_page.h"
#include "ui_apt_source_manager_page.h"
#include <QDebug>
#include "utilities.h"
#include "Managers/tool_manager.h"
APTSourceManagerPage::~APTSourceManagerPage()
{
delete ui;
}
APTSourcePtr APTSourceManagerPage::selectedAptSource = nullptr;
APTSourceManagerPage::APTSourceManagerPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::APTSourceManagerPage)
{
ui->setupUi(this);
init();
}
void APTSourceManagerPage::init()
{
ui->txtAptSource->setPlaceholderText(tr("example %1")
.arg("'deb http://archive.ubuntu.com/ubuntu xenial main'"));
loadAptSources();
on_btnCancel_clicked();
Utilities::addDropShadow(ui->txtSearchAptSource, 40);
}
void APTSourceManagerPage::loadAptSources()
{
ui->listWidgetAptSources->clear();
QList<APTSourcePtr> aptSourceList = ToolManager::ins()->getSourceList();
for (APTSourcePtr &aptSource: aptSourceList) {
QListWidgetItem *listItem = new QListWidgetItem(ui->listWidgetAptSources);
listItem->setData(5, aptSource->source); // for search
APTSourceRepositoryItem *aptSourceItem = new APTSourceRepositoryItem(aptSource, ui->listWidgetAptSources);
listItem->setSizeHint(aptSourceItem->sizeHint() + QSize(0, 1));
ui->listWidgetAptSources->setItemWidget(listItem, aptSourceItem);
}
ui->notFoundWidget->setVisible(aptSourceList.isEmpty());
ui->lblAptSourceTitle->setText(tr("APT Repositories (%1)")
.arg(aptSourceList.count()));
}
void APTSourceManagerPage::on_btnAddAPTSourceRepository_clicked(bool checked)
{
if (checked) {
ui->btnAddAPTSourceRepository->setText(tr("Save"));
changeElementsVisible(checked);
} else {
QString aptSourceRepository = ui->txtAptSource->text().trimmed();
if (! aptSourceRepository.isEmpty()) {
ToolManager::ins()->addAPTRepository(aptSourceRepository, ui->checkEnableSource->isChecked());
ui->txtAptSource->clear();
ui->checkEnableSource->setChecked(false);
on_btnCancel_clicked();
loadAptSources();
}
}
}
void APTSourceManagerPage::on_btnCancel_clicked()
{
ui->btnAddAPTSourceRepository->setChecked(false);
changeElementsVisible(false);
ui->btnAddAPTSourceRepository->setText(tr("Add Repository"));
}
void APTSourceManagerPage::changeElementsVisible(const bool checked)
{
ui->txtAptSource->setVisible(checked);
ui->checkEnableSource->setVisible(checked);
ui->btnCancel->setVisible(checked);
ui->btnEditAptSource->setVisible(!checked);
ui->btnDeleteAptSource->setVisible(!checked);
ui->bottomSectionHorizontalSpacer->changeSize(0, 0, checked ? QSizePolicy::Minimum : QSizePolicy::Expanding);
}
void APTSourceManagerPage::on_listWidgetAptSources_itemClicked(QListWidgetItem *item)
{
QWidget *widget = ui->listWidgetAptSources->itemWidget(item);
if (widget) {
APTSourceRepositoryItem *aptSourceItem = dynamic_cast<APTSourceRepositoryItem*>(widget);
if (aptSourceItem) {
selectedAptSource = aptSourceItem->aptSource();
}
} else {
selectedAptSource.clear();
}
}
void APTSourceManagerPage::on_listWidgetAptSources_itemDoubleClicked(QListWidgetItem *item)
{
on_listWidgetAptSources_itemClicked(item);
on_btnEditAptSource_clicked();
}
void APTSourceManagerPage::on_btnDeleteAptSource_clicked()
{
if (! selectedAptSource.isNull()) {
ToolManager::ins()->removeAPTSource(selectedAptSource);
loadAptSources();
}
}
void APTSourceManagerPage::on_txtSearchAptSource_textChanged(const QString &val)
{
for (int i = 0; i < ui->listWidgetAptSources->count(); ++i) {
QListWidgetItem *item = ui->listWidgetAptSources->item(i);
if (item) {
bool isContain = item->data(5).toString().contains(val, Qt::CaseInsensitive);
ui->listWidgetAptSources->setItemHidden(item, ! isContain);
}
}
}
void APTSourceManagerPage::on_btnEditAptSource_clicked()
{
if (! selectedAptSource.isNull()) {
if (mAptSourceEditDialog.isNull()) {
mAptSourceEditDialog = QSharedPointer<APTSourceEdit>(new APTSourceEdit(this));
connect(mAptSourceEditDialog.data(), &APTSourceEdit::saved, this, &APTSourceManagerPage::loadAptSources);
}
APTSourceEdit::selectedAptSource = selectedAptSource;
mAptSourceEditDialog->show();
}
}
<commit_msg>added shadow to buttons<commit_after>#include "apt_source_manager_page.h"
#include "ui_apt_source_manager_page.h"
#include <QDebug>
#include "utilities.h"
#include "Managers/tool_manager.h"
APTSourceManagerPage::~APTSourceManagerPage()
{
delete ui;
}
APTSourcePtr APTSourceManagerPage::selectedAptSource = nullptr;
APTSourceManagerPage::APTSourceManagerPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::APTSourceManagerPage)
{
ui->setupUi(this);
init();
}
void APTSourceManagerPage::init()
{
ui->txtAptSource->setPlaceholderText(tr("example %1")
.arg("'deb http://archive.ubuntu.com/ubuntu xenial main'"));
loadAptSources();
on_btnCancel_clicked();
QList<QWidget*> widgets = {
ui->btnAddAPTSourceRepository, ui->btnCancel, ui->btnDeleteAptSource, ui->btnEditAptSource,
ui->txtSearchAptSource, ui->txtSearchAptSource
};
Utilities::addDropShadow(widgets, 40);
}
void APTSourceManagerPage::loadAptSources()
{
ui->listWidgetAptSources->clear();
QList<APTSourcePtr> aptSourceList = ToolManager::ins()->getSourceList();
for (APTSourcePtr &aptSource: aptSourceList) {
QListWidgetItem *listItem = new QListWidgetItem(ui->listWidgetAptSources);
listItem->setData(5, aptSource->source); // for search
APTSourceRepositoryItem *aptSourceItem = new APTSourceRepositoryItem(aptSource, ui->listWidgetAptSources);
listItem->setSizeHint(aptSourceItem->sizeHint() + QSize(0, 1));
ui->listWidgetAptSources->setItemWidget(listItem, aptSourceItem);
}
ui->notFoundWidget->setVisible(aptSourceList.isEmpty());
ui->lblAptSourceTitle->setText(tr("APT Repositories (%1)")
.arg(aptSourceList.count()));
}
void APTSourceManagerPage::on_btnAddAPTSourceRepository_clicked(bool checked)
{
if (checked) {
ui->btnAddAPTSourceRepository->setText(tr("Save"));
changeElementsVisible(checked);
} else {
QString aptSourceRepository = ui->txtAptSource->text().trimmed();
if (! aptSourceRepository.isEmpty()) {
ToolManager::ins()->addAPTRepository(aptSourceRepository, ui->checkEnableSource->isChecked());
ui->txtAptSource->clear();
ui->checkEnableSource->setChecked(false);
on_btnCancel_clicked();
loadAptSources();
}
}
}
void APTSourceManagerPage::on_btnCancel_clicked()
{
ui->btnAddAPTSourceRepository->setChecked(false);
changeElementsVisible(false);
ui->btnAddAPTSourceRepository->setText(tr("Add Repository"));
}
void APTSourceManagerPage::changeElementsVisible(const bool checked)
{
ui->txtAptSource->setVisible(checked);
ui->checkEnableSource->setVisible(checked);
ui->btnCancel->setVisible(checked);
ui->btnEditAptSource->setVisible(!checked);
ui->btnDeleteAptSource->setVisible(!checked);
ui->bottomSectionHorizontalSpacer->changeSize(0, 0, checked ? QSizePolicy::Minimum : QSizePolicy::Expanding);
}
void APTSourceManagerPage::on_listWidgetAptSources_itemClicked(QListWidgetItem *item)
{
QWidget *widget = ui->listWidgetAptSources->itemWidget(item);
if (widget) {
APTSourceRepositoryItem *aptSourceItem = dynamic_cast<APTSourceRepositoryItem*>(widget);
if (aptSourceItem) {
selectedAptSource = aptSourceItem->aptSource();
}
} else {
selectedAptSource.clear();
}
}
void APTSourceManagerPage::on_listWidgetAptSources_itemDoubleClicked(QListWidgetItem *item)
{
on_listWidgetAptSources_itemClicked(item);
on_btnEditAptSource_clicked();
}
void APTSourceManagerPage::on_btnDeleteAptSource_clicked()
{
if (! selectedAptSource.isNull()) {
ToolManager::ins()->removeAPTSource(selectedAptSource);
loadAptSources();
}
}
void APTSourceManagerPage::on_txtSearchAptSource_textChanged(const QString &val)
{
for (int i = 0; i < ui->listWidgetAptSources->count(); ++i) {
QListWidgetItem *item = ui->listWidgetAptSources->item(i);
if (item) {
bool isContain = item->data(5).toString().contains(val, Qt::CaseInsensitive);
ui->listWidgetAptSources->setItemHidden(item, ! isContain);
}
}
}
void APTSourceManagerPage::on_btnEditAptSource_clicked()
{
if (! selectedAptSource.isNull()) {
if (mAptSourceEditDialog.isNull()) {
mAptSourceEditDialog = QSharedPointer<APTSourceEdit>(new APTSourceEdit(this));
connect(mAptSourceEditDialog.data(), &APTSourceEdit::saved, this, &APTSourceManagerPage::loadAptSources);
}
APTSourceEdit::selectedAptSource = selectedAptSource;
mAptSourceEditDialog->show();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuline.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-12-14 16:59:36 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "fuline.hxx"
#include <svx/svxids.hrc>
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _XDEF_HXX //autogen
#include <svx/xdef.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuLine, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuLine::FuLine (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuLine::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuLine( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuLine::DoExecute( SfxRequest& rReq )
{
BOOL bHasMarked = pView->AreObjectsMarked();
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
// erst einmal alle eingabeparameter fuer den dialog retten
SfxItemSet aInputAttr( pDoc->GetPool() );
pView->GetAttributes( aInputAttr );
const XLineStyleItem &rILineStyleItem = (const XLineStyleItem &) aInputAttr.Get (XATTR_LINESTYLE);
XLineStyle eILineStyle = rILineStyleItem.GetValue ();
const XLineDashItem &rILineDashItem = (const XLineDashItem &) aInputAttr.Get (XATTR_LINEDASH);
const XDash &rIDash = rILineDashItem.GetValue ();
const XLineWidthItem &rILineWidthItem = (const XLineWidthItem &) aInputAttr.Get (XATTR_LINEWIDTH);
long nILineWidth = rILineWidthItem.GetValue ();
const XLineColorItem &rILineColorItem = (const XLineColorItem &) aInputAttr.Get (XATTR_LINECOLOR);
const Color &rIColor = rILineColorItem.GetValue ();
const SdrObject* pObj = NULL;
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
pObj = rMarkList.GetMark(0)->GetObj();
SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
pView->GetAttributes( *pNewAttr );
//CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog( NULL, pNewAttr, pDoc, pObj, bHasMarked );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog(NULL,
pNewAttr,
pDoc,
ResId(RID_SVXDLG_LINE),
pObj,
bHasMarked);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
if ( pDlg->Execute() == RET_OK )
{
// die ausgabeparameter des dialogs bestimmen
SfxItemSet *pOutputAttr = (SfxItemSet *) pDlg->GetOutputItemSet();
const XLineStyleItem &rOLineStyleItem = (const XLineStyleItem &) pOutputAttr->Get (XATTR_LINESTYLE);
XLineStyle eOLineStyle = rOLineStyleItem.GetValue ();
const XLineDashItem &rOLineDashItem = (const XLineDashItem &) pOutputAttr->Get (XATTR_LINEDASH);
const XDash &rODash = rOLineDashItem.GetValue ();
const XLineWidthItem &rOLineWidthItem = (const XLineWidthItem &) pOutputAttr->Get (XATTR_LINEWIDTH);
long nOLineWidth = rOLineWidthItem.GetValue ();
const XLineColorItem &rOLineColorItem = (const XLineColorItem &) pOutputAttr->Get (XATTR_LINECOLOR);
const Color &rOColor = rOLineColorItem.GetValue ();
pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
}
// Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
static USHORT SidArray[] = {
SID_ATTR_LINE_STYLE,
SID_ATTR_LINE_DASH,
SID_ATTR_LINE_WIDTH,
SID_ATTR_LINE_COLOR,
0 };
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
delete pDlg;
delete pNewAttr;
}
rReq.Ignore ();
}
void FuLine::Activate()
{
}
void FuLine::Deactivate()
{
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS warnings01 (1.7.150); FILE MERGED 2006/05/12 16:40:35 sb 1.7.150.1: #i53898# Made code warning-free and/or compile at all after resync to SRC680m162.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuline.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-19 12:32:32 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "fuline.hxx"
#include <svx/svxids.hrc>
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _XDEF_HXX //autogen
#include <svx/xdef.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuLine, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuLine::FuLine (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuLine::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuLine( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuLine::DoExecute( SfxRequest& rReq )
{
BOOL bHasMarked = pView->AreObjectsMarked();
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
// erst einmal alle eingabeparameter fuer den dialog retten
SfxItemSet aInputAttr( pDoc->GetPool() );
pView->GetAttributes( aInputAttr );
const XLineStyleItem &rILineStyleItem = (const XLineStyleItem &) aInputAttr.Get (XATTR_LINESTYLE);
XLineStyle eILineStyle = rILineStyleItem.GetValue ();
const XLineDashItem &rILineDashItem = (const XLineDashItem &) aInputAttr.Get (XATTR_LINEDASH);
const XDash &rIDash = rILineDashItem.GetDashValue ();
const XLineWidthItem &rILineWidthItem = (const XLineWidthItem &) aInputAttr.Get (XATTR_LINEWIDTH);
long nILineWidth = rILineWidthItem.GetValue ();
const XLineColorItem &rILineColorItem = (const XLineColorItem &) aInputAttr.Get (XATTR_LINECOLOR);
const Color &rIColor = rILineColorItem.GetColorValue ();
const SdrObject* pObj = NULL;
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
pObj = rMarkList.GetMark(0)->GetObj();
SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
pView->GetAttributes( *pNewAttr );
//CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog( NULL, pNewAttr, pDoc, pObj, bHasMarked );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog(NULL,
pNewAttr,
pDoc,
ResId(RID_SVXDLG_LINE),
pObj,
bHasMarked);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
if ( pDlg->Execute() == RET_OK )
{
// die ausgabeparameter des dialogs bestimmen
SfxItemSet *pOutputAttr = (SfxItemSet *) pDlg->GetOutputItemSet();
const XLineStyleItem &rOLineStyleItem = (const XLineStyleItem &) pOutputAttr->Get (XATTR_LINESTYLE);
XLineStyle eOLineStyle = rOLineStyleItem.GetValue ();
const XLineDashItem &rOLineDashItem = (const XLineDashItem &) pOutputAttr->Get (XATTR_LINEDASH);
const XDash &rODash = rOLineDashItem.GetDashValue ();
const XLineWidthItem &rOLineWidthItem = (const XLineWidthItem &) pOutputAttr->Get (XATTR_LINEWIDTH);
long nOLineWidth = rOLineWidthItem.GetValue ();
const XLineColorItem &rOLineColorItem = (const XLineColorItem &) pOutputAttr->Get (XATTR_LINECOLOR);
const Color &rOColor = rOLineColorItem.GetColorValue ();
pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
}
// Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
static USHORT SidArray[] = {
SID_ATTR_LINE_STYLE,
SID_ATTR_LINE_DASH,
SID_ATTR_LINE_WIDTH,
SID_ATTR_LINE_COLOR,
0 };
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
delete pDlg;
delete pNewAttr;
}
rReq.Ignore ();
}
void FuLine::Activate()
{
}
void FuLine::Deactivate()
{
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuslhide.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:39:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_FU_SLIDE_HIDE_HXX
#define SD_FU_SLIDE_HIDE_HXX
#ifndef SD_FU_SLIDE_HXX
#include "fuslid.hxx"
#endif
namespace sd {
/*************************************************************************
|*
|* selektierte Dias in der Show zeigen / nicht zeigen
|*
\************************************************************************/
class FuSlideHide
: public FuSlide
{
public:
TYPEINFO();
FuSlideHide (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuSlideHide (void);
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impressfunctions (1.4.40); FILE MERGED 2005/10/28 10:56:54 cl 1.4.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuslhide.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-12-14 17:16:41 $
*
* 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 SD_FU_SLIDE_HIDE_HXX
#define SD_FU_SLIDE_HIDE_HXX
#ifndef SD_FU_SLIDE_HXX
#include "fuslid.hxx"
#endif
namespace sd {
/*************************************************************************
|*
|* selektierte Dias in der Show zeigen / nicht zeigen
|*
\************************************************************************/
class FuSlideHide
: public FuSlide
{
public:
TYPEINFO();
static FunctionReference Create( SlideViewShell* pViewSh, ::sd::Window* pWin, SlideView* pView, SdDrawDocument* pDoc, SfxRequest& rReq );
virtual void DoExecute( SfxRequest& rReq );
protected:
FuSlideHide (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuSlideHide (void);
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>/* smoothmove.cpp
* Smooth motion source file
*/
#include "smoothmove.h"
// Constructor
SmoothMove::SmoothMove(boost::shared_ptr<AL::ALBroker> broker,
const std::string &name)
: AL::ALModule(broker, name)
{
// Set description, and bind each function
setModuleDescription("Smooth movement testing module");
functionName("harryDance", getName(), "Do a little dance");
BIND_METHOD(SmoothMove::harryDance);
functionName("moveTest", getName(), "Testing movement");
BIND_METHOD(SmoothMove::moveTest);
// Set broker parent IP and port
pip = broker->getParentIP();
pport = broker->getParentPort();
}
// Destructor
SmoothMove::~SmoothMove()
{
}
// init() - called as soon as the module is constructed
void SmoothMove::init()
{
}
void SmoothMove::moveTest()
{
// Get brokers, and go to initial posture
AL::ALMotionProxy motion(pip, pport);
AL::ALRobotPostureProxy posture(pip, pport);
posture.goToPosture("StandInit", 0.5f);
int space = 2; // FRAME_ROBOT
int axisMask = 63; // control all the effector's axes
bool isAbsolute = false;
// Lower the Torso and move to the side
std::string torso = "Torso";
std::string lArm = "LArm";
std::string rArm = "RArm";
std::vector<float> position(6, 0.0f);
position[0] = 0.0f;
position[1] = 0.0f;
position[2] = 0.3f;
position[3] = 0.0f;
position[4] = 0.0f;
position[5] = 0.0f;
// Amplitude of oscillation
float amplitude = 0.05f;
// Oscillation time in seconds
float freq = 8.0f;
// Update time in milliseconds
unsigned int update = 50;
// Max speed of robot movement
float speed = 1.0f;
for (float t = 0; t < freq * 2.0; t += 0.001 * update)
{
position[0] = amplitude * sin (2.0 * M_PI * t / freq);
motion.setPosition(torso, space, position, speed, axisMask);
qi::os::msleep(update);
}
}
void SmoothMove::harryDance()
{
/** The name of the joint to be moved. */
const AL::ALValue jointName = "HeadYaw";
try {
/** Create a ALMotionProxy to call the methods to move NAO's head.
* Arguments for the constructor are:
* - IP adress of the robot
* - port on which NAOqi is listening, by default 9559
*/
AL::ALMotionProxy motion(pip, pport);
/** Make sure the head is stiff to be able to move it.
* To do so, make the stiffness go to the maximum in one second.
*/
/** Target stiffness. */
AL::ALValue stiffness = 1.0f;
/** Time (in seconds) to reach the target. */
AL::ALValue time = 1.0f;
/** Call the stiffness interpolation method. */
motion.stiffnessInterpolation(jointName, stiffness, time);
/** Remove the stiffness on the head. */
stiffness = 0.0f;
time = 1.0f;
motion.stiffnessInterpolation(jointName, stiffness, time);
AL::ALValue result = motion.getWalkArmsEnabled();
/*---------Harry's Edits-------*/
AL::ALValue names = "RShoulderPitch"; //String is the limb name
AL::ALValue names2 = "LShoulderPitch";
AL::ALValue angles = 1.0f; //Angle is in robot unit, f
AL::ALValue angles2 = 0.0f;
AL::ALValue times = 1.0f;
bool isAbsolute = true; // Tells robot the angle values are absolute
std::cout << "\nShoulder Pitch:\n";
for (int i = 0; i < 3; i++)
{
//Function calls robot to move
motion.angleInterpolation(names, angles, times, isAbsolute);
motion.angleInterpolation(names2, angles2, times, isAbsolute);
//angles = 0.0f;
motion.angleInterpolation(names, angles2, times, isAbsolute);
motion.angleInterpolation(names2, angles, times, isAbsolute);
}
std::cout << "Shoulder Roll";
//Creates arrays of values to send to robot.
AL::ALValue angle_list, time_list;
angle_list = AL::ALValue::array(1.0f);
time_list = AL::ALValue::array(1.0f);
angle_list.clear();
time_list.clear();
angle_list.arraySetSize(2);
//Array lists angles to move through
angle_list[0] = AL::ALValue::array(-0.5f, 0.5f); //From -0.5 to 0.5
angle_list[1] = AL::ALValue::array(0.5f, -0.5f);
time_list.arraySetSize(2);
//Time arrays - unsure of what this does...
time_list[0] = AL::ALValue::array(1.0f, 2.0f);
time_list[1] = AL::ALValue::array(1.0f, 2.0f);
motion.angleInterpolation(names, angles, times, isAbsolute);
//Array tells robot what limbs to move
//All array[0] (angle, time) are assigned to the first limb
names = AL::ALValue::array("RShoulderRoll", "LShoulderRoll");
motion.angleInterpolation(names, angle_list, time_list, isAbsolute);
/*-------------------*/
}
catch (const AL::ALError& e)
{
std::cerr << "Caught exception: " << e.what() << std::endl;
}
}
<commit_msg>Small smoothmove update<commit_after>/* smoothmove.cpp
* Smooth motion source file
*/
#include "smoothmove.h"
// Constructor
SmoothMove::SmoothMove(boost::shared_ptr<AL::ALBroker> broker,
const std::string &name)
: AL::ALModule(broker, name)
{
// Set description, and bind each function
setModuleDescription("Smooth movement testing module");
functionName("harryDance", getName(), "Do a little dance");
BIND_METHOD(SmoothMove::harryDance);
functionName("moveTest", getName(), "Testing movement");
BIND_METHOD(SmoothMove::moveTest);
// Set broker parent IP and port
pip = broker->getParentIP();
pport = broker->getParentPort();
}
// Destructor
SmoothMove::~SmoothMove()
{
}
// init() - called as soon as the module is constructed
void SmoothMove::init()
{
}
void SmoothMove::moveTest()
{
// Get brokers, and go to initial posture
AL::ALMotionProxy motion(pip, pport);
AL::ALRobotPostureProxy posture(pip, pport);
posture.goToPosture("StandInit", 0.5f);
int space = 2; // FRAME_ROBOT
int axisMask = 63; // control all the effector's axes
bool isAbsolute = false;
// Lower the Torso and move to the side
std::string torso = "Torso";
std::string lArm = "LArm";
std::string rArm = "RArm";
std::vector<float> position(6, 0.0f);
position[0] = 0.0f;
position[1] = 0.0f;
position[2] = 0.3f;
position[3] = 0.0f;
position[4] = 0.0f;
position[5] = 0.0f;
// Amplitude of oscillation
float amplitude = 0.05f;
// Oscillation time in seconds
float freq = 4.0f;
// Update time in milliseconds
unsigned int update = 50;
// Max speed of robot movement
float speed = 1.0f;
// Go to initial position
motion.setPosition(torso, space, position, speed, axisMask);
qi::os::sleep(1.0f);
for (float t = 0; t < freq * 2.0; t += 0.001 * update)
{
position[0] = amplitude * sin (2.0 * M_PI * t / freq);
motion.setPosition(torso, space, position, speed, axisMask);
qi::os::msleep(update);
}
}
void SmoothMove::harryDance()
{
/** The name of the joint to be moved. */
const AL::ALValue jointName = "HeadYaw";
try {
/** Create a ALMotionProxy to call the methods to move NAO's head.
* Arguments for the constructor are:
* - IP adress of the robot
* - port on which NAOqi is listening, by default 9559
*/
AL::ALMotionProxy motion(pip, pport);
/** Make sure the head is stiff to be able to move it.
* To do so, make the stiffness go to the maximum in one second.
*/
/** Target stiffness. */
AL::ALValue stiffness = 1.0f;
/** Time (in seconds) to reach the target. */
AL::ALValue time = 1.0f;
/** Call the stiffness interpolation method. */
motion.stiffnessInterpolation(jointName, stiffness, time);
/** Remove the stiffness on the head. */
stiffness = 0.0f;
time = 1.0f;
motion.stiffnessInterpolation(jointName, stiffness, time);
AL::ALValue result = motion.getWalkArmsEnabled();
/*---------Harry's Edits-------*/
AL::ALValue names = "RShoulderPitch"; //String is the limb name
AL::ALValue names2 = "LShoulderPitch";
AL::ALValue angles = 1.0f; //Angle is in robot unit, f
AL::ALValue angles2 = 0.0f;
AL::ALValue times = 1.0f;
bool isAbsolute = true; // Tells robot the angle values are absolute
std::cout << "\nShoulder Pitch:\n";
for (int i = 0; i < 3; i++)
{
//Function calls robot to move
motion.angleInterpolation(names, angles, times, isAbsolute);
motion.angleInterpolation(names2, angles2, times, isAbsolute);
//angles = 0.0f;
motion.angleInterpolation(names, angles2, times, isAbsolute);
motion.angleInterpolation(names2, angles, times, isAbsolute);
}
std::cout << "Shoulder Roll";
//Creates arrays of values to send to robot.
AL::ALValue angle_list, time_list;
angle_list = AL::ALValue::array(1.0f);
time_list = AL::ALValue::array(1.0f);
angle_list.clear();
time_list.clear();
angle_list.arraySetSize(2);
//Array lists angles to move through
angle_list[0] = AL::ALValue::array(-0.5f, 0.5f); //From -0.5 to 0.5
angle_list[1] = AL::ALValue::array(0.5f, -0.5f);
time_list.arraySetSize(2);
//Time arrays - unsure of what this does...
time_list[0] = AL::ALValue::array(1.0f, 2.0f);
time_list[1] = AL::ALValue::array(1.0f, 2.0f);
motion.angleInterpolation(names, angles, times, isAbsolute);
//Array tells robot what limbs to move
//All array[0] (angle, time) are assigned to the first limb
names = AL::ALValue::array("RShoulderRoll", "LShoulderRoll");
motion.angleInterpolation(names, angle_list, time_list, isAbsolute);
/*-------------------*/
}
catch (const AL::ALError& e)
{
std::cerr << "Caught exception: " << e.what() << std::endl;
}
}
<|endoftext|>
|
<commit_before>#include "gui/boardwidget.hpp"
#include <cmath>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/Color.hpp>
#include <iostream>
#include <stdio.h>
#include "engine/engine.hpp"
#include "engine/player.hpp"
#include "engine/pathfinding/path.hpp"
#include "gui/guihandler.hpp"
#include "gui/cursor.hpp"
#include "gui/damagenumber.hpp"
namespace qrw
{
BoardWidget::BoardWidget(GuiHandler* guihandler, Engine* engine, float width, float height)
: Widget(guihandler->getRenderWindow(), width, height),
board(0),
engine(engine),
spritedimensions(0.0),
singlespritescale(0.0),
path(0),
deploywindow(guihandler->getDeployWindow())
{
printf("boardrenderer position: x=%f / y=%f\n", getGlobalBounds().left, getGlobalBounds().top);
printf("boardrenderer size: w=%f / h=%f\n", getSize().x, getSize().y);
// Create required sprites.
TextureManager* texturemanager = TextureManager::getInstance();
plainsquare = new sf::Sprite(*texturemanager->getTexture("plainsquare"));
footstep = new sf::Sprite(*texturemanager->getTexture("footstep"));
terrainsprites[ET_WOOD] = new sf::Sprite(*texturemanager->getTexture("wood"));
terrainsprites[ET_HILL] = new sf::Sprite(*texturemanager->getTexture("hill"));
terrainsprites[ET_WALL] = new sf::Sprite(*texturemanager->getTexture("wall"));
p1unitsprites[EUT_SWORDMAN] = new sf::Sprite(*texturemanager->getTexture("p1swordman"));
p1unitsprites[EUT_ARCHER] = new sf::Sprite(*texturemanager->getTexture("p1archer"));
p1unitsprites[EUT_SPEARMAN] = new sf::Sprite(*texturemanager->getTexture("p1spearman"));
p2unitsprites[EUT_SWORDMAN] = new sf::Sprite(*texturemanager->getTexture("p2swordman"));
p2unitsprites[EUT_ARCHER] = new sf::Sprite(*texturemanager->getTexture("p2archer"));
p2unitsprites[EUT_SPEARMAN] = new sf::Sprite(*texturemanager->getTexture("p2spearman"));
signalmousemoved.connect(std::bind(&BoardWidget::updateCursor, this));
signalmouseentered.connect(std::bind(&BoardWidget::updateCursor, this));
signalclicked.connect(std::bind(&BoardWidget::leftClicked, this));
signalrightclicked.connect(std::bind(&BoardWidget::rightClicked, this));
signalkeypressed.connect(std::bind(&BoardWidget::keyPressed, this, std::placeholders::_1));
}
BoardWidget::~BoardWidget()
{
delete plainsquare;
delete footstep;
}
void BoardWidget::setBoard(Board* board)
{
this->board = board;
calcSpriteDimensions(board->getWidth(), board->getHeight());
}
void BoardWidget::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
sf::Vector2f targetsize = target.getView().getSize();
targetsize.x -= 180.0;
int width = board->getWidth();
int height = board->getHeight();
sf::Vector2f spritescale(singlespritescale, singlespritescale);
sf::VertexArray vertices(sf::Lines, 0);
Square *square = 0;
Unit *unit = 0;
Terrain *terrain = 0;
sf::Vector2f currpos;
sf::Vector2i cursorpos = Cursor::getCursor()->getPosition();
sf::Vector2i childcursorpos(-1, -1);
if(Cursor::getCursor()->getChild() != 0)
{
childcursorpos.x = Cursor::getCursor()->getChild()->getPosition().x;
childcursorpos.y = Cursor::getCursor()->getChild()->getPosition().y;
}
for(int i = 0; i < width; ++i)
{
for(int j = 0; j < height; ++j)
{
currpos.x = i * spritedimensions;
currpos.y = j * spritedimensions;
plainsquare->setPosition(currpos);
plainsquare->setScale(spritescale);
target.draw(*plainsquare);
square = board->getSquare(i, j);
terrain = square->getTerrain();
unit = square->getUnit();
// Render cursor
if(cursorpos.x == i && cursorpos.y == j)
Cursor::getCursor()->draw(target, currpos, spritedimensions);
if(childcursorpos.x == i && childcursorpos.y == j)
Cursor::getCursor()->drawChild(target, currpos, spritedimensions);
// Render Terrain
if(terrain != 0)
{
drawTerrain(target, terrain->getType(), currpos, spritescale);
}
// Render Units
if(unit != 0)
{
drawUnit(target, unit->getPlayer()->getId(), unit->getType(),
currpos, spritescale);
}
}
}
drawPath(target, spritescale);
}
void BoardWidget::calcSpriteDimensions(int boardwidth, int boardheight)
{
if(boardwidth > boardheight)
{
spritedimensions = getSize().x / boardwidth;
singlespritescale = getSize().x / (boardwidth * 32.0);
}
else
{
spritedimensions = getSize().y / boardheight;
singlespritescale = getSize().y / (boardheight * 32.0);
}
}
void BoardWidget::drawTerrain(sf::RenderTarget& target,
TERRAINTYPES terraintype, sf::Vector2f position, sf::Vector2f scale) const
{
terrainsprites[terraintype]->setPosition(position);
terrainsprites[terraintype]->setScale(scale);
target.draw(*terrainsprites[terraintype]);
}
void BoardWidget::drawUnit(sf::RenderTarget& target, int playerid,
UNITTYPES unittype, sf::Vector2f position, sf::Vector2f scale) const
{
sf::Sprite* unitsprite = 0;
if(playerid == 0)
unitsprite = p1unitsprites[unittype];
else
unitsprite = p2unitsprites[unittype];
unitsprite->setPosition(position);
unitsprite->setScale(scale);
target.draw(*unitsprite);
}
void BoardWidget::drawPath(sf::RenderTarget& target, sf::Vector2f scale) const
{
if(!path)
return;
int pathlength = path->getLength();
Square* previous = 0;
Square* current = path->getStep(0);
Square* next = path->getStep(1);
// Do not render first step.
for(int i = 1; i < pathlength; ++i)
{
previous = current;
current = next;
// Reset the previously applied transformations.
footstep->setOrigin(16, 16);
footstep->setScale(scale);
footstep->setRotation(0);
// Transformations relative to the previous step
Coordinates prevdelta(previous->getCoordinates() - current->getCoordinates());
if(prevdelta.getX() != 0)
footstep->rotate(-90 * prevdelta.getX());
if(prevdelta.getY() != 0)
footstep->scale(1, prevdelta.getY());
// Transformations relative to the next step (if possible)
if(i < pathlength - 1)
{
next = path->getStep(i+1);
}
footstep->setPosition(
spritedimensions * (0.5f + current->getXPosition()),
spritedimensions * (0.5f + current->getYPosition())
);
target.draw(*footstep);
}
}
void BoardWidget::moveUnitIngame()
{
Cursor* cursor = Cursor::getCursor();
Cursor* childcursor = cursor->getChild();
if(childcursor)
{
Unit* unit1 = board->getSquare(cursor->getPosition().x, cursor->getPosition().y)->getUnit();
int unit1hp = unit1->getHP();
Unit* unit2 = board->getSquare(childcursor->getPosition().x, childcursor->getPosition().y)->getUnit();
int unit2hp;
if(unit2)
unit2hp = unit2->getHP();
int moveresult = engine->moveUnitIngame(cursor->getPosition().x, cursor->getPosition().y,
childcursor->getPosition().x, childcursor->getPosition().y);
printf("moveresult: %i\n", moveresult);
if(moveresult == 0 || moveresult == -9 || moveresult == -8 || moveresult == -11)
{
// Display damage numbers
if(moveresult == -9 || moveresult == -8 || moveresult == -11)
{
DamageNumber* dm;
sf::Vector2f pos;
// First DMG number
pos.x = cursor->getPosition().x * spritedimensions;
pos.y = cursor->getPosition().y * spritedimensions + spritedimensions * 0.2;
dm = new DamageNumber(unit1->getHP() - unit1hp, pos);
// Second DMG number
pos.x = childcursor->getPosition().x * spritedimensions;
pos.y = childcursor->getPosition().y * spritedimensions + spritedimensions * 0.2;
dm = new DamageNumber(unit2->getHP() - unit2hp, pos);
}
// Resetting cursors
cursor->setPosition(childcursor->getPosition());
cursor->despawnChild();
// Reset path
if(path)
{
delete path;
path = 0;
}
}
}
}
void BoardWidget::updateCursor()
{
// Calculate on which field the mouse cursor is placed.
sf::Vector2i mousePosition = sf::Mouse::getPosition(*window);
sf::Vector2i newCursorPos;
newCursorPos.x = floor( ((float)mousePosition.x) / spritedimensions );
newCursorPos.y = floor( ((float)mousePosition.y) / spritedimensions );
// Boarder checks
if(newCursorPos.x < 0)
newCursorPos.x = 0;
else if(newCursorPos.x > board->getWidth())
newCursorPos.x = board->getWidth();
if(newCursorPos.y < 0)
newCursorPos.y = 0;
else if(newCursorPos.y > board->getHeight())
newCursorPos.y = board->getHeight();
if(!Cursor::getCursor()->getChild())
Cursor::getCursor()->setPosition(newCursorPos);
else
{
Cursor::getCursor()->getChild()->setPosition(newCursorPos);
if(engine->getStatus() == EES_RUNNING)
{
// Update path
if(path)
delete path;
path = engine->findPath(
Coordinates(Cursor::getCursor()->getPosition().x, Cursor::getCursor()->getPosition().y),
Coordinates(newCursorPos.x, newCursorPos.y)
);
}
}
}
void BoardWidget::leftClicked()
{
Cursor* cursor = Cursor::getCursor();
Cursor* childcursor = cursor->getChild();
Square* cursorsquare = board->getSquare(cursor->getPosition().x, cursor->getPosition().y);
// Depploy unit / terrain by calling deploywindow methods.
if(engine->getStatus() == EES_PREPARE)
{
if(childcursor)
{
deploywindow->moveUnit();
}
else if(cursorsquare->getUnit())
{
cursor->spawnChild();
}
else
{
printf("boardwidget leftclicked pre placeEntity (deploywindow=%p)\n", deploywindow);
deploywindow->placeEntity();
}
}
// Ingame actions.
// TODO: Following code is just a copy&paste of GuiHandler::HandleEvent() code. Find a better solution
// for this code duplication...
else
{
if(cursorsquare->getUnit() && !childcursor)
{
cursor->spawnChild();
}
// Move a unit
else if(childcursor)
{
this->moveUnitIngame();
}
}
} // BoardWidget::leftClicked();
void BoardWidget::rightClicked()
{
Cursor* cursor = Cursor::getCursor();
Cursor* childcursor = cursor->getChild();
if(childcursor)
{
cursor->setPosition(childcursor->getPosition());
cursor->despawnChild();
}
if(path)
{
delete path;
path = 0;
}
}
void BoardWidget::keyPressed(const sf::Event& event)
{
qrw::Cursor* cursor = qrw::Cursor::getCursor();
qrw::Cursor* childcursor = cursor->getChild();
if(event.key.code == sf::Keyboard::Up)
cursor->move(0, -1);
else if(event.key.code == sf::Keyboard::Down)
cursor->move(0, 1);
else if(event.key.code == sf::Keyboard::Right)
cursor->move(1, 0);
else if(event.key.code == sf::Keyboard::Left)
cursor->move(-1, 0);
else if(event.key.code == sf::Keyboard::Escape)
cursor->despawnChild();
else if(event.key.code == sf::Keyboard::Return)
{
if(engine->getStatus() == EES_PREPARE)
{
// Check if a new unit is placed or a unit is moved.
// A unit is moved if cursor has a child (to point to destination)
// or there is a unit under cursor.
Square* cursorsquare = engine->getBoard()->getSquare(cursor->getPosition().x,
cursor->getPosition().y);
if (cursor->getChild() != NULL)
{
deploywindow->moveUnit();
}
else if(cursorsquare->getUnit() != NULL)
{
cursor->spawnChild();
}
else
{
deploywindow->placeEntity();
}
}
else if(childcursor == 0)
{
cursor->spawnChild();
}
else if(childcursor != 0)
{
this->moveUnitIngame();
}
}
}
}
<commit_msg>Added 45° rotations of footsteps.<commit_after>#include "gui/boardwidget.hpp"
#include <cmath>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/Color.hpp>
#include <iostream>
#include <stdio.h>
#include "engine/engine.hpp"
#include "engine/player.hpp"
#include "engine/pathfinding/path.hpp"
#include "gui/guihandler.hpp"
#include "gui/cursor.hpp"
#include "gui/damagenumber.hpp"
namespace qrw
{
BoardWidget::BoardWidget(GuiHandler* guihandler, Engine* engine, float width, float height)
: Widget(guihandler->getRenderWindow(), width, height),
board(0),
engine(engine),
spritedimensions(0.0),
singlespritescale(0.0),
path(0),
deploywindow(guihandler->getDeployWindow())
{
printf("boardrenderer position: x=%f / y=%f\n", getGlobalBounds().left, getGlobalBounds().top);
printf("boardrenderer size: w=%f / h=%f\n", getSize().x, getSize().y);
// Create required sprites.
TextureManager* texturemanager = TextureManager::getInstance();
plainsquare = new sf::Sprite(*texturemanager->getTexture("plainsquare"));
footstep = new sf::Sprite(*texturemanager->getTexture("footstep"));
terrainsprites[ET_WOOD] = new sf::Sprite(*texturemanager->getTexture("wood"));
terrainsprites[ET_HILL] = new sf::Sprite(*texturemanager->getTexture("hill"));
terrainsprites[ET_WALL] = new sf::Sprite(*texturemanager->getTexture("wall"));
p1unitsprites[EUT_SWORDMAN] = new sf::Sprite(*texturemanager->getTexture("p1swordman"));
p1unitsprites[EUT_ARCHER] = new sf::Sprite(*texturemanager->getTexture("p1archer"));
p1unitsprites[EUT_SPEARMAN] = new sf::Sprite(*texturemanager->getTexture("p1spearman"));
p2unitsprites[EUT_SWORDMAN] = new sf::Sprite(*texturemanager->getTexture("p2swordman"));
p2unitsprites[EUT_ARCHER] = new sf::Sprite(*texturemanager->getTexture("p2archer"));
p2unitsprites[EUT_SPEARMAN] = new sf::Sprite(*texturemanager->getTexture("p2spearman"));
signalmousemoved.connect(std::bind(&BoardWidget::updateCursor, this));
signalmouseentered.connect(std::bind(&BoardWidget::updateCursor, this));
signalclicked.connect(std::bind(&BoardWidget::leftClicked, this));
signalrightclicked.connect(std::bind(&BoardWidget::rightClicked, this));
signalkeypressed.connect(std::bind(&BoardWidget::keyPressed, this, std::placeholders::_1));
}
BoardWidget::~BoardWidget()
{
delete plainsquare;
delete footstep;
}
void BoardWidget::setBoard(Board* board)
{
this->board = board;
calcSpriteDimensions(board->getWidth(), board->getHeight());
}
void BoardWidget::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
sf::Vector2f targetsize = target.getView().getSize();
targetsize.x -= 180.0;
int width = board->getWidth();
int height = board->getHeight();
sf::Vector2f spritescale(singlespritescale, singlespritescale);
sf::VertexArray vertices(sf::Lines, 0);
Square *square = 0;
Unit *unit = 0;
Terrain *terrain = 0;
sf::Vector2f currpos;
sf::Vector2i cursorpos = Cursor::getCursor()->getPosition();
sf::Vector2i childcursorpos(-1, -1);
if(Cursor::getCursor()->getChild() != 0)
{
childcursorpos.x = Cursor::getCursor()->getChild()->getPosition().x;
childcursorpos.y = Cursor::getCursor()->getChild()->getPosition().y;
}
for(int i = 0; i < width; ++i)
{
for(int j = 0; j < height; ++j)
{
currpos.x = i * spritedimensions;
currpos.y = j * spritedimensions;
plainsquare->setPosition(currpos);
plainsquare->setScale(spritescale);
target.draw(*plainsquare);
square = board->getSquare(i, j);
terrain = square->getTerrain();
unit = square->getUnit();
// Render cursor
if(cursorpos.x == i && cursorpos.y == j)
Cursor::getCursor()->draw(target, currpos, spritedimensions);
if(childcursorpos.x == i && childcursorpos.y == j)
Cursor::getCursor()->drawChild(target, currpos, spritedimensions);
// Render Terrain
if(terrain != 0)
{
drawTerrain(target, terrain->getType(), currpos, spritescale);
}
// Render Units
if(unit != 0)
{
drawUnit(target, unit->getPlayer()->getId(), unit->getType(),
currpos, spritescale);
}
}
}
drawPath(target, spritescale);
}
void BoardWidget::calcSpriteDimensions(int boardwidth, int boardheight)
{
if(boardwidth > boardheight)
{
spritedimensions = getSize().x / boardwidth;
singlespritescale = getSize().x / (boardwidth * 32.0);
}
else
{
spritedimensions = getSize().y / boardheight;
singlespritescale = getSize().y / (boardheight * 32.0);
}
}
void BoardWidget::drawTerrain(sf::RenderTarget& target,
TERRAINTYPES terraintype, sf::Vector2f position, sf::Vector2f scale) const
{
terrainsprites[terraintype]->setPosition(position);
terrainsprites[terraintype]->setScale(scale);
target.draw(*terrainsprites[terraintype]);
}
void BoardWidget::drawUnit(sf::RenderTarget& target, int playerid,
UNITTYPES unittype, sf::Vector2f position, sf::Vector2f scale) const
{
sf::Sprite* unitsprite = 0;
if(playerid == 0)
unitsprite = p1unitsprites[unittype];
else
unitsprite = p2unitsprites[unittype];
unitsprite->setPosition(position);
unitsprite->setScale(scale);
target.draw(*unitsprite);
}
void BoardWidget::drawPath(sf::RenderTarget& target, sf::Vector2f scale) const
{
if(!path)
return;
int pathlength = path->getLength();
Square* previous = 0;
Square* current = path->getStep(0);
Square* next = path->getStep(1);
// Do not render first step.
for(int i = 1; i < pathlength; ++i)
{
previous = current;
current = next;
// Reset the previously applied transformations.
footstep->setOrigin(16, 16);
footstep->setScale(scale);
footstep->setRotation(0);
// Transformations relative to the previous step
Coordinates prevdelta(previous->getCoordinates() - current->getCoordinates());
if(prevdelta.getX() != 0)
footstep->rotate(-90 * prevdelta.getX());
if(prevdelta.getY() != 0)
footstep->scale(1, prevdelta.getY());
// Transformations relative to the next step (if possible)
if(i < pathlength - 1)
{
next = path->getStep(i+1);
Coordinates prevnextdelta(previous->getCoordinates() - next->getCoordinates());
// If the path has a corner at this position
if(prevnextdelta.getX() != 0 && prevnextdelta.getY() != 0)
{
int rotationdirection = 0;
// horizontal
if(prevdelta.getX() == 0)
{
rotationdirection = -1;
}
// vertical
else if(prevdelta.getY() == 0)
{
rotationdirection = +1;
}
footstep->rotate(rotationdirection * 45 * (prevnextdelta.getX() * prevnextdelta.getY()));
}
}
footstep->setPosition(
spritedimensions * (0.5f + current->getXPosition()),
spritedimensions * (0.5f + current->getYPosition())
);
target.draw(*footstep);
}
}
void BoardWidget::moveUnitIngame()
{
Cursor* cursor = Cursor::getCursor();
Cursor* childcursor = cursor->getChild();
if(childcursor)
{
Unit* unit1 = board->getSquare(cursor->getPosition().x, cursor->getPosition().y)->getUnit();
int unit1hp = unit1->getHP();
Unit* unit2 = board->getSquare(childcursor->getPosition().x, childcursor->getPosition().y)->getUnit();
int unit2hp;
if(unit2)
unit2hp = unit2->getHP();
int moveresult = engine->moveUnitIngame(cursor->getPosition().x, cursor->getPosition().y,
childcursor->getPosition().x, childcursor->getPosition().y);
printf("moveresult: %i\n", moveresult);
if(moveresult == 0 || moveresult == -9 || moveresult == -8 || moveresult == -11)
{
// Display damage numbers
if(moveresult == -9 || moveresult == -8 || moveresult == -11)
{
DamageNumber* dm;
sf::Vector2f pos;
// First DMG number
pos.x = cursor->getPosition().x * spritedimensions;
pos.y = cursor->getPosition().y * spritedimensions + spritedimensions * 0.2;
dm = new DamageNumber(unit1->getHP() - unit1hp, pos);
// Second DMG number
pos.x = childcursor->getPosition().x * spritedimensions;
pos.y = childcursor->getPosition().y * spritedimensions + spritedimensions * 0.2;
dm = new DamageNumber(unit2->getHP() - unit2hp, pos);
}
// Resetting cursors
cursor->setPosition(childcursor->getPosition());
cursor->despawnChild();
// Reset path
if(path)
{
delete path;
path = 0;
}
}
}
}
void BoardWidget::updateCursor()
{
// Calculate on which field the mouse cursor is placed.
sf::Vector2i mousePosition = sf::Mouse::getPosition(*window);
sf::Vector2i newCursorPos;
newCursorPos.x = floor( ((float)mousePosition.x) / spritedimensions );
newCursorPos.y = floor( ((float)mousePosition.y) / spritedimensions );
// Boarder checks
if(newCursorPos.x < 0)
newCursorPos.x = 0;
else if(newCursorPos.x > board->getWidth())
newCursorPos.x = board->getWidth();
if(newCursorPos.y < 0)
newCursorPos.y = 0;
else if(newCursorPos.y > board->getHeight())
newCursorPos.y = board->getHeight();
if(!Cursor::getCursor()->getChild())
Cursor::getCursor()->setPosition(newCursorPos);
else
{
Cursor::getCursor()->getChild()->setPosition(newCursorPos);
if(engine->getStatus() == EES_RUNNING)
{
// Update path
if(path)
delete path;
path = engine->findPath(
Coordinates(Cursor::getCursor()->getPosition().x, Cursor::getCursor()->getPosition().y),
Coordinates(newCursorPos.x, newCursorPos.y)
);
}
}
}
void BoardWidget::leftClicked()
{
Cursor* cursor = Cursor::getCursor();
Cursor* childcursor = cursor->getChild();
Square* cursorsquare = board->getSquare(cursor->getPosition().x, cursor->getPosition().y);
// Depploy unit / terrain by calling deploywindow methods.
if(engine->getStatus() == EES_PREPARE)
{
if(childcursor)
{
deploywindow->moveUnit();
}
else if(cursorsquare->getUnit())
{
cursor->spawnChild();
}
else
{
printf("boardwidget leftclicked pre placeEntity (deploywindow=%p)\n", deploywindow);
deploywindow->placeEntity();
}
}
// Ingame actions.
// TODO: Following code is just a copy&paste of GuiHandler::HandleEvent() code. Find a better solution
// for this code duplication...
else
{
if(cursorsquare->getUnit() && !childcursor)
{
cursor->spawnChild();
}
// Move a unit
else if(childcursor)
{
this->moveUnitIngame();
}
}
} // BoardWidget::leftClicked();
void BoardWidget::rightClicked()
{
Cursor* cursor = Cursor::getCursor();
Cursor* childcursor = cursor->getChild();
if(childcursor)
{
cursor->setPosition(childcursor->getPosition());
cursor->despawnChild();
}
if(path)
{
delete path;
path = 0;
}
}
void BoardWidget::keyPressed(const sf::Event& event)
{
qrw::Cursor* cursor = qrw::Cursor::getCursor();
qrw::Cursor* childcursor = cursor->getChild();
if(event.key.code == sf::Keyboard::Up)
cursor->move(0, -1);
else if(event.key.code == sf::Keyboard::Down)
cursor->move(0, 1);
else if(event.key.code == sf::Keyboard::Right)
cursor->move(1, 0);
else if(event.key.code == sf::Keyboard::Left)
cursor->move(-1, 0);
else if(event.key.code == sf::Keyboard::Escape)
cursor->despawnChild();
else if(event.key.code == sf::Keyboard::Return)
{
if(engine->getStatus() == EES_PREPARE)
{
// Check if a new unit is placed or a unit is moved.
// A unit is moved if cursor has a child (to point to destination)
// or there is a unit under cursor.
Square* cursorsquare = engine->getBoard()->getSquare(cursor->getPosition().x,
cursor->getPosition().y);
if (cursor->getChild() != NULL)
{
deploywindow->moveUnit();
}
else if(cursorsquare->getUnit() != NULL)
{
cursor->spawnChild();
}
else
{
deploywindow->placeEntity();
}
}
else if(childcursor == 0)
{
cursor->spawnChild();
}
else if(childcursor != 0)
{
this->moveUnitIngame();
}
}
}
}
<|endoftext|>
|
<commit_before>#include "gusanos/allegro.h"
#include "gconsole.h"
#include "resource_list.h"
#include "sprite.h"
#include "level.h"
#include "gusgame.h"
#include "part_type.h"
#include "particle.h"
#include "CWormHuman.h"
#include "util/macros.h"
#ifndef DEDICATED_ONLY
#include "CViewport.h"
#include "font.h"
#include "gfx.h"
#include "sound/sfx.h"
#include "menu.h"
#include "distortion.h"
#endif
#include "sprite_set.h"
#include "network.h"
#include "CMap.h"
#include "script.h"
#include "glua.h"
#include "luaapi/context.h"
#include "util/log.h"
#include "game/Game.h"
#include <memory>
#include <string>
#include <vector>
#ifdef POSIX
#include <unistd.h>
#endif
using namespace std;
bool quit = false;
static Uint32 logicLast = 0;
bool gusInitBase() {
if(!gusGame.init())
return false;
#ifndef DEDICATED_ONLY
OmfgGUI::menu.clear();
#endif
//gusGame.loadMod();
gusGame.reloadModWithoutMap();
//gusGame.runInitScripts();
// TODO: check bDedicated instead
#ifndef DEDICATED_ONLY
console.executeConfig("autoexec.cfg");
#else
console.executeConfig("autoexec-ded.cfg");
#endif
return true;
}
bool gusInit(const std::string& mod) {
notes << "Gusanos: set mod " << mod << endl;
gusGame.setMod(mod);
quit = false;
logicLast = SDL_GetTicks() / 10;
return true;
}
bool gusCanRunFrame() {
return !quit || !network.isDisconnected();
}
void gusLogicFrame() {
Uint32 timer = SDL_GetTicks() / 10;
size_t logicFrameCount = 0;
while ( logicLast + 1 <= timer )
{
for ( Grid::iterator iter = game.objects.beginAll(); iter;)
{
if(iter->deleteMe)
iter.erase();
else
++iter;
}
if ( game.shouldDoPhysicsFrame() && gusGame.isLoaded() && gusGame.isLevelLoaded() )
{
for ( Grid::iterator iter = game.objects.beginAll(); iter; ++iter)
{
iter->think();
game.objects.relocateIfNecessary(iter);
}
game.objects.flush(); // Insert all new objects
for ( vector<CWormInputHandler*>::iterator iter = game.players.begin(); iter != game.players.end(); iter++)
{
if(!(*iter)->deleteMe)
(*iter)->think();
}
}
gusGame.think();
#ifndef DEDICATED_ONLY
sfx.think(); // WARNING: THIS MUST! BE PLACED BEFORE THE OBJECT DELETE LOOP
#endif
#ifndef DEDICATED_ONLY
console.checkInput();
#endif
console.think();
spriteList.think();
EACH_CALLBACK(i, afterUpdate)
{
(lua.call(*i))();
}
++logicLast;
++logicFrameCount;
if(logicFrameCount > 10) { // don't be too slow
logicLast = timer; // skip left frames
break;
}
}
network.update();
}
void gusQuit() {
//network.disconnect(); // If we haven't already, it's too late
network.shutDown();
gusGame.unload();
#ifndef DEDICATED_ONLY
OmfgGUI::menu.destroy();
#endif
console.shutDown();
#ifndef DEDICATED_ONLY
sfx.shutDown();
#endif
gfx.shutDown();
lua.close();
allegro_exit();
}
<commit_msg>cleanup<commit_after>#include "gusanos/allegro.h"
#include "gconsole.h"
#include "resource_list.h"
#include "sprite.h"
#include "level.h"
#include "gusgame.h"
#include "part_type.h"
#include "particle.h"
#include "CWormHuman.h"
#include "util/macros.h"
#ifndef DEDICATED_ONLY
#include "CViewport.h"
#include "font.h"
#include "gfx.h"
#include "sound/sfx.h"
#include "menu.h"
#include "distortion.h"
#endif
#include "sprite_set.h"
#include "network.h"
#include "CMap.h"
#include "script.h"
#include "glua.h"
#include "luaapi/context.h"
#include "util/log.h"
#include "game/Game.h"
#include <memory>
#include <string>
#include <vector>
#ifdef POSIX
#include <unistd.h>
#endif
using namespace std;
bool quit = false;
static Uint32 logicLast = 0;
bool gusInitBase() {
if(!gusGame.init())
return false;
#ifndef DEDICATED_ONLY
OmfgGUI::menu.clear();
#endif
gusGame.reloadModWithoutMap();
if(!bDedicated)
console.executeConfig("autoexec.cfg");
else
console.executeConfig("autoexec-ded.cfg");
return true;
}
bool gusInit(const std::string& mod) {
notes << "Gusanos: set mod " << mod << endl;
gusGame.setMod(mod);
quit = false;
logicLast = SDL_GetTicks() / 10;
return true;
}
bool gusCanRunFrame() {
return !quit || !network.isDisconnected();
}
void gusLogicFrame() {
Uint32 timer = SDL_GetTicks() / 10;
size_t logicFrameCount = 0;
while ( logicLast + 1 <= timer )
{
for ( Grid::iterator iter = game.objects.beginAll(); iter;)
{
if(iter->deleteMe)
iter.erase();
else
++iter;
}
if ( game.shouldDoPhysicsFrame() && gusGame.isLoaded() && gusGame.isLevelLoaded() )
{
for ( Grid::iterator iter = game.objects.beginAll(); iter; ++iter)
{
iter->think();
game.objects.relocateIfNecessary(iter);
}
game.objects.flush(); // Insert all new objects
for ( vector<CWormInputHandler*>::iterator iter = game.players.begin(); iter != game.players.end(); iter++)
{
if(!(*iter)->deleteMe)
(*iter)->think();
}
}
gusGame.think();
#ifndef DEDICATED_ONLY
sfx.think(); // WARNING: THIS MUST! BE PLACED BEFORE THE OBJECT DELETE LOOP
#endif
#ifndef DEDICATED_ONLY
console.checkInput();
#endif
console.think();
spriteList.think();
EACH_CALLBACK(i, afterUpdate)
{
(lua.call(*i))();
}
++logicLast;
++logicFrameCount;
if(logicFrameCount > 10) { // don't be too slow
logicLast = timer; // skip left frames
break;
}
}
network.update();
}
void gusQuit() {
//network.disconnect(); // If we haven't already, it's too late
network.shutDown();
gusGame.unload();
#ifndef DEDICATED_ONLY
OmfgGUI::menu.destroy();
#endif
console.shutDown();
#ifndef DEDICATED_ONLY
sfx.shutDown();
#endif
gfx.shutDown();
lua.close();
allegro_exit();
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout
, bool handle_redirect)
{
m_redirect = handle_redirect;
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout, bool handle_redirect)
{
m_redirect = handle_redirect;
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
// having a nonempty path means we should handle redirects
if (m_redirect && m_parser.header_finished())
{
int code = m_parser.status_code();
if (code >= 300 && code < 400)
{
// attempt a redirect
std::string url = m_parser.header<std::string>("location");
if (url.empty())
{
// missing location header
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
get(url, m_timeout);
return;
}
m_redirect = false;
}
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if ((e == asio::error::operation_aborted
&& m_limiter_timer_active)
|| !m_sock.is_open())
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<commit_msg>fixes for the GET request and passes that data through the data pointer in bottled mode too<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout
, bool handle_redirect)
{
m_redirect = handle_redirect;
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"\r\nConnection: close\r\n"
"\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout, bool handle_redirect)
{
m_redirect = handle_redirect;
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
char const* data = 0;
std::size_t size = 0;
if (m_bottled)
{
data = m_parser.get_body().begin;
size = m_parser.get_body().left();
}
m_handler(asio::error_code(), m_parser, data, size);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
// having a nonempty path means we should handle redirects
if (m_redirect && m_parser.header_finished())
{
int code = m_parser.status_code();
if (code >= 300 && code < 400)
{
// attempt a redirect
std::string url = m_parser.header<std::string>("location");
if (url.empty())
{
// missing location header
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
get(url, m_timeout);
return;
}
m_redirect = false;
}
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, m_parser.get_body().begin, m_parser.get_body().left());
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if ((e == asio::error::operation_aborted
&& m_limiter_timer_active)
|| !m_sock.is_open())
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout
, bool handle_redirect)
{
m_redirect = handle_redirect;
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
m_path = path;
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout, bool handle_redirect = true)
{
m_redirect = handle_redirect;
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
// having a nonempty path means we should handle redirects
if (m_redirect && m_parser.header_finished())
{
int code = m_parser.status_code();
if (code >= 300 && code < 400)
{
// attempt a redirect
std::string url = m_parser.header<std::string>("location");
if (url.empty())
{
// missing location header
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
get(url, m_timeout);
return;
}
m_redirect = false;
}
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if ((e == asio::error::operation_aborted
&& m_limiter_timer_active)
|| !m_sock.is_open())
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<commit_msg>fix to previous check-in<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout
, bool handle_redirect)
{
m_redirect = handle_redirect;
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout, bool handle_redirect)
{
m_redirect = handle_redirect;
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
// having a nonempty path means we should handle redirects
if (m_redirect && m_parser.header_finished())
{
int code = m_parser.status_code();
if (code >= 300 && code < 400)
{
// attempt a redirect
std::string url = m_parser.header<std::string>("location");
if (url.empty())
{
// missing location header
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
get(url, m_timeout);
return;
}
m_redirect = false;
}
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if ((e == asio::error::operation_aborted
&& m_limiter_timer_active)
|| !m_sock.is_open())
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
return;
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/c/task/vision/image_classifier.h"
#include <memory>
#include "tensorflow_lite_support/c/task/vision/utils/frame_buffer_cpp_c_utils.h"
#include "tensorflow_lite_support/cc/task/vision/image_classifier.h"
#include "tensorflow_lite_support/cc/task/vision/proto/classifications_proto_inc.h"
#include "tensorflow_lite_support/cc/task/vision/proto/image_classifier_options_proto_inc.h"
namespace {
using ::tflite::support::StatusOr;
using ClassificationResultCpp = ::tflite::task::vision::ClassificationResult;
using ClassificationsCpp = ::tflite::task::vision::Classifications;
using ClassCpp = ::tflite::task::vision::Class;
using BoundingBoxCpp = ::tflite::task::vision::BoundingBox;
using ImageClassifierCpp = ::tflite::task::vision::ImageClassifier;
using ImageClassifierOptionsCpp =
::tflite::task::vision::ImageClassifierOptions;
using FrameBufferCpp = ::tflite::task::vision::FrameBuffer;
} // namespace
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
struct TfLiteImageClassifier {
std::unique_ptr<ImageClassifierCpp> impl;
};
TfLiteImageClassifierOptions TfLiteImageClassifierOptionsCreate() {
TfLiteImageClassifierOptions options = {
.classification_options.max_results = -1,
.base_options.compute_settings.cpu_settings.num_threads = -1};
return options;
}
std::unique_ptr<ImageClassifierOptionsCpp>
CreateImageClassifierCppOptionsFromCOptions(
const TfLiteImageClassifierOptions* c_options) {
std::unique_ptr<ImageClassifierOptionsCpp> cpp_options(
new ImageClassifierOptionsCpp);
// More file sources can be added in else ifs
if (c_options->base_options.model_file.file_path)
cpp_options->mutable_base_options()->mutable_model_file()->set_file_name(
c_options->base_options.model_file.file_path);
else
return nullptr;
// c_options->base_options.compute_settings.num_threads iis expected to be
// set to value > 0 or -1. Otherwise invoking
// ImageClassifierCpp::CreateFromOptions() results in a not ok status.
cpp_options->mutable_base_options()
->mutable_compute_settings()
->mutable_tflite_settings()
->mutable_cpu_settings()
->set_num_threads(
c_options->base_options.compute_settings.cpu_settings.num_threads);
for (int i = 0; i < c_options->classification_options.label_denylist.length;
i++)
cpp_options->add_class_name_blacklist(
c_options->classification_options.label_denylist.list[i]);
for (int i = 0; i < c_options->classification_options.label_allowlist.length;
i++)
cpp_options->add_class_name_whitelist(
c_options->classification_options.label_allowlist.list[i]);
// Check needed since setting a nullptr for this field results in a segfault
// on invocation of ImageClassifierCpp::CreateFromOptions().
if (c_options->classification_options.display_names_local) {
cpp_options->set_display_names_locale(
c_options->classification_options.display_names_local);
}
// c_options->classification_options.max_results is expected to be set to -1
// or any value > 0. Otherwise invoking
// ImageClassifierCpp::CreateFromOptions() results in a not ok status.
cpp_options->set_max_results(c_options->classification_options.max_results);
cpp_options->set_score_threshold(
c_options->classification_options.score_threshold);
return cpp_options;
}
TfLiteImageClassifier* TfLiteImageClassifierFromOptions(
const TfLiteImageClassifierOptions* options) {
std::unique_ptr<ImageClassifierOptionsCpp> cpp_options =
CreateImageClassifierCppOptionsFromCOptions(options);
if (cpp_options == nullptr) {
return nullptr;
}
auto classifier_status = ImageClassifierCpp::CreateFromOptions(*cpp_options);
if (classifier_status.ok()) {
return new TfLiteImageClassifier{.impl =
std::move(classifier_status.value())};
} else {
return nullptr;
}
}
TfLiteClassificationResult* GetClassificationResultCStruct(
const ClassificationResultCpp& classification_result_cpp) {
TfLiteClassifications* c_classifications =
new TfLiteClassifications[classification_result_cpp
.classifications_size()];
for (int head = 0; head < classification_result_cpp.classifications_size();
++head) {
const ClassificationsCpp& classifications =
classification_result_cpp.classifications(head);
c_classifications[head].head_index = head;
TfLiteCategory* c_categories =
new TfLiteCategory[classifications.classes_size()];
c_classifications->size = classifications.classes_size();
for (int rank = 0; rank < classifications.classes_size(); ++rank) {
const ClassCpp& classification = classifications.classes(rank);
c_categories[rank].index = classification.index();
c_categories[rank].score = classification.score();
if (classification.has_class_name())
c_categories[rank].label = strdup(classification.class_name().c_str());
else
c_categories[rank].label = nullptr;
if (classification.has_display_name())
c_categories[rank].display_name =
strdup(classification.display_name().c_str());
else
c_categories[rank].display_name = nullptr;
}
c_classifications[head].categories = c_categories;
}
TfLiteClassificationResult* c_classification_result =
new TfLiteClassificationResult;
c_classification_result->classifications = c_classifications;
c_classification_result->size =
classification_result_cpp.classifications_size();
return c_classification_result;
}
TfLiteClassificationResult* TfLiteImageClassifierClassifyWithRoi(
const TfLiteImageClassifier* classifier,
const TfLiteFrameBuffer* frame_buffer, const TfLiteBoundingBox* roi) {
if (classifier == nullptr || frame_buffer == nullptr) {
return nullptr;
}
BoundingBoxCpp cc_roi;
if (roi == nullptr) {
cc_roi.set_width(frame_buffer->dimension.width);
cc_roi.set_height(frame_buffer->dimension.height);
} else {
cc_roi.set_origin_x(roi->origin_x);
cc_roi.set_origin_y(roi->origin_y);
cc_roi.set_width(roi->width);
cc_roi.set_height(roi->height);
}
StatusOr<std::unique_ptr<FrameBufferCpp>> cpp_frame_buffer_status =
::tflite::task::vision::CreateCppFrameBuffer(*frame_buffer);
if (!cpp_frame_buffer_status.ok()) return nullptr;
// fnc_sample(cpp_frame_buffer_status);
StatusOr<ClassificationResultCpp> classification_result_cpp =
classifier->impl->Classify(*std::move(cpp_frame_buffer_status.value()),
cc_roi);
if (!classification_result_cpp.ok()) return nullptr;
return GetClassificationResultCStruct(classification_result_cpp.value());
}
TfLiteClassificationResult* TfLiteImageClassifierClassify(
const TfLiteImageClassifier* classifier,
const TfLiteFrameBuffer* frame_buffer) {
return TfLiteImageClassifierClassifyWithRoi(classifier, frame_buffer,
nullptr);
}
void TfLiteImageClassifierDelete(TfLiteImageClassifier* classifier) {
delete classifier;
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
<commit_msg>Formatting fixes<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/c/task/vision/image_classifier.h"
#include <memory>
#include "tensorflow_lite_support/c/task/vision/utils/frame_buffer_cpp_c_utils.h"
#include "tensorflow_lite_support/cc/task/vision/image_classifier.h"
#include "tensorflow_lite_support/cc/task/vision/proto/classifications_proto_inc.h"
#include "tensorflow_lite_support/cc/task/vision/proto/image_classifier_options_proto_inc.h"
namespace {
using ::tflite::support::StatusOr;
using ClassificationResultCpp = ::tflite::task::vision::ClassificationResult;
using ClassificationsCpp = ::tflite::task::vision::Classifications;
using ClassCpp = ::tflite::task::vision::Class;
using BoundingBoxCpp = ::tflite::task::vision::BoundingBox;
using ImageClassifierCpp = ::tflite::task::vision::ImageClassifier;
using ImageClassifierOptionsCpp =
::tflite::task::vision::ImageClassifierOptions;
using FrameBufferCpp = ::tflite::task::vision::FrameBuffer;
} // namespace
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
struct TfLiteImageClassifier {
std::unique_ptr<ImageClassifierCpp> impl;
};
TfLiteImageClassifierOptions TfLiteImageClassifierOptionsCreate() {
return {
.classification_options.max_results = -1,
.base_options.compute_settings.cpu_settings.num_threads = -1};
}
std::unique_ptr<ImageClassifierOptionsCpp>
CreateImageClassifierCppOptionsFromCOptions(
const TfLiteImageClassifierOptions* c_options) {
std::unique_ptr<ImageClassifierOptionsCpp> cpp_options(
new ImageClassifierOptionsCpp);
// More file sources can be added in else ifs
if (c_options->base_options.model_file.file_path)
cpp_options->mutable_base_options()->mutable_model_file()->set_file_name(
c_options->base_options.model_file.file_path);
else
return nullptr;
// c_options->base_options.compute_settings.num_threads iis expected to be
// set to value > 0 or -1. Otherwise invoking
// ImageClassifierCpp::CreateFromOptions() results in a not ok status.
cpp_options->mutable_base_options()
->mutable_compute_settings()
->mutable_tflite_settings()
->mutable_cpu_settings()
->set_num_threads(
c_options->base_options.compute_settings.cpu_settings.num_threads);
for (int i = 0; i < c_options->classification_options.label_denylist.length;
i++)
cpp_options->add_class_name_blacklist(
c_options->classification_options.label_denylist.list[i]);
for (int i = 0; i < c_options->classification_options.label_allowlist.length;
i++)
cpp_options->add_class_name_whitelist(
c_options->classification_options.label_allowlist.list[i]);
// Check needed since setting a nullptr for this field results in a segfault
// on invocation of ImageClassifierCpp::CreateFromOptions().
if (c_options->classification_options.display_names_local) {
cpp_options->set_display_names_locale(
c_options->classification_options.display_names_local);
}
// c_options->classification_options.max_results is expected to be set to -1
// or any value > 0. Otherwise invoking
// ImageClassifierCpp::CreateFromOptions() results in a not ok status.
cpp_options->set_max_results(c_options->classification_options.max_results);
cpp_options->set_score_threshold(
c_options->classification_options.score_threshold);
return cpp_options;
}
TfLiteImageClassifier* TfLiteImageClassifierFromOptions(
const TfLiteImageClassifierOptions* options) {
std::unique_ptr<ImageClassifierOptionsCpp> cpp_options =
CreateImageClassifierCppOptionsFromCOptions(options);
if (cpp_options == nullptr) {
return nullptr;
}
auto classifier_status = ImageClassifierCpp::CreateFromOptions(*cpp_options);
if (classifier_status.ok()) {
return new TfLiteImageClassifier{.impl =
std::move(classifier_status.value())};
} else {
return nullptr;
}
}
TfLiteClassificationResult* GetClassificationResultCStruct(
const ClassificationResultCpp& classification_result_cpp) {
TfLiteClassifications* c_classifications =
new TfLiteClassifications[classification_result_cpp
.classifications_size()];
for (int head = 0; head < classification_result_cpp.classifications_size();
++head) {
const ClassificationsCpp& classifications =
classification_result_cpp.classifications(head);
c_classifications[head].head_index = head;
TfLiteCategory* c_categories =
new TfLiteCategory[classifications.classes_size()];
c_classifications->size = classifications.classes_size();
for (int rank = 0; rank < classifications.classes_size(); ++rank) {
const ClassCpp& classification = classifications.classes(rank);
c_categories[rank].index = classification.index();
c_categories[rank].score = classification.score();
if (classification.has_class_name())
c_categories[rank].label = strdup(classification.class_name().c_str());
else
c_categories[rank].label = nullptr;
if (classification.has_display_name())
c_categories[rank].display_name =
strdup(classification.display_name().c_str());
else
c_categories[rank].display_name = nullptr;
}
c_classifications[head].categories = c_categories;
}
TfLiteClassificationResult* c_classification_result =
new TfLiteClassificationResult;
c_classification_result->classifications = c_classifications;
c_classification_result->size =
classification_result_cpp.classifications_size();
return c_classification_result;
}
TfLiteClassificationResult* TfLiteImageClassifierClassifyWithRoi(
const TfLiteImageClassifier* classifier,
const TfLiteFrameBuffer* frame_buffer, const TfLiteBoundingBox* roi) {
if (classifier == nullptr || frame_buffer == nullptr) {
return nullptr;
}
BoundingBoxCpp cc_roi;
if (roi == nullptr) {
cc_roi.set_width(frame_buffer->dimension.width);
cc_roi.set_height(frame_buffer->dimension.height);
} else {
cc_roi.set_origin_x(roi->origin_x);
cc_roi.set_origin_y(roi->origin_y);
cc_roi.set_width(roi->width);
cc_roi.set_height(roi->height);
}
StatusOr<std::unique_ptr<FrameBufferCpp>> cpp_frame_buffer_status =
::tflite::task::vision::CreateCppFrameBuffer(*frame_buffer);
if (!cpp_frame_buffer_status.ok()) return nullptr;
// fnc_sample(cpp_frame_buffer_status);
StatusOr<ClassificationResultCpp> classification_result_cpp =
classifier->impl->Classify(*std::move(cpp_frame_buffer_status.value()),
cc_roi);
if (!classification_result_cpp.ok()) return nullptr;
return GetClassificationResultCStruct(classification_result_cpp.value());
}
TfLiteClassificationResult* TfLiteImageClassifierClassify(
const TfLiteImageClassifier* classifier,
const TfLiteFrameBuffer* frame_buffer) {
return TfLiteImageClassifierClassifyWithRoi(classifier, frame_buffer,
nullptr);
}
void TfLiteImageClassifierDelete(TfLiteImageClassifier* classifier) {
delete classifier;
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, 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 <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.id[0] = id[1];
ret.id[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.id[0] = id[0];
ret.id[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
if (!std::isprint(id[0])
|| !std::isalnum(id[1])
|| id[2] != '-'
|| !std::isalnum(id[3])
|| id[4] != '-'
|| !std::isalnum(id[5])
|| !std::equal(id.begin() + 6, id.begin() + 8, "--"))
return boost::optional<fingerprint>();
fingerprint ret("..", 0, 0, 0, 0);
ret.id[0] = id[0];
ret.id[1] = 0;
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[3]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CT", "CTorrent")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
};
bool compare_first_string(map_entry const& e, char const* str)
{
return e.first[0] < str[0]
|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, f.id, &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i].first));
}
#endif
if (i < name_map + size && std::equal(f.id, f.id + 2, i->first))
identity << i->second;
else
identity << std::string(f.id, f.id + 2);
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version
<< "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
std::string identify_client(const peer_id& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>updated client identification<commit_after>/*
Copyright (c) 2003, 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 <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.id[0] = id[1];
ret.id[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.id[0] = id[0];
ret.id[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
if (!std::isprint(id[0])
|| !std::isalnum(id[1])
|| id[2] != '-'
|| !std::isalnum(id[3])
|| id[4] != '-'
|| !std::isalnum(id[5])
|| !std::equal(id.begin() + 6, id.begin() + 8, "--"))
return boost::optional<fingerprint>();
fingerprint ret("..", 0, 0, 0, 0);
ret.id[0] = id[0];
ret.id[1] = 0;
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[3]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CT", "CTorrent")
, map_entry("KT", "KTorrent")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
};
bool compare_first_string(map_entry const& e, char const* str)
{
return e.first[0] < str[0]
|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, f.id, &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i].first));
}
#endif
if (i < name_map + size && std::equal(f.id, f.id + 2, i->first))
identity << i->second;
else
identity << std::string(f.id, f.id + 2);
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version
<< "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
std::string identify_client(const peer_id& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, 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 "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "uTorrent"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "Pando-")) return "Pando";
if (find_string(PID, "LIME")) return "LimeWire";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "DNA")) return "BitTorrent DNA";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>refactored identify_client<commit_after>/*
Copyright (c) 2003, 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 "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"ST", "SymTorrent"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "uTorrent"}
, {"XL", "Xunlei"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
, {"st", "SharkTorrent"}
};
struct generic_map_entry
{
int offset;
char const* id;
char const* name;
};
// non-standard names
generic_map_entry generic_mappings[] =
{
{0, "Deadman Walking-", "Deadman"}
, {5, "Azureus", "Azureus 2.0.3.2"}
, {0, "DansClient", "XanTorrent"}
, {4, "btfans", "SimpleBT"}
, {0, "PRC.P---", "Bittorrent Plus! II"}
, {0, "P87.P---", "Bittorrent Plus!"}
, {0, "S587Plus", "Bittorrent Plus!"}
, {0, "martini", "Martini Man"}
, {0, "Plus---", "Bittorrent Plus"}
, {0, "turbobt", "TurboBT"}
, {0, "a00---0", "Swarmy"}
, {0, "a02---0", "Swarmy"}
, {0, "T00---0", "Teeweety"}
, {0, "BTDWV-", "Deadman Walking"}
, {2, "BS", "BitSpirit"}
, {0, "Pando-", "Pando"}
, {0, "LIME", "LimeWire"}
, {0, "btuga", "BTugaXP"}
, {0, "oernu", "BTugaXP"}
, {0, "Mbrst", "Burst!"}
, {0, "PEERAPP", "PeerApp"}
, {0, "Plus", "Plus!"}
, {0, "-Qt-", "Qt"}
, {0, "exbc", "BitComet"}
, {0, "DNA", "BitTorrent DNA"}
, {0, "-G3", "G3 Torrent"}
, {0, "-FG", "FlashGet"}
, {0, "-ML", "MLdonkey"}
, {0, "XBT", "XBT"}
, {0, "OP", "Opera"}
, {2, "RS", "Rufus"}
, {0, "AZ2500BT", "BitTyrant"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]);
for (int i = 0; i < num_generic_mappings; ++i)
{
generic_map_entry const& e = generic_mappings[i];
if (find_string(PID + e.offset, e.id)) return e.name;
}
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, 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 "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MR", "Miro"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"ST", "SymTorrent"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "uTorrent"}
, {"XL", "Xunlei"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
, {"st", "SharkTorrent"}
};
struct generic_map_entry
{
int offset;
char const* id;
char const* name;
};
// non-standard names
generic_map_entry generic_mappings[] =
{
{0, "Deadman Walking-", "Deadman"}
, {5, "Azureus", "Azureus 2.0.3.2"}
, {0, "DansClient", "XanTorrent"}
, {4, "btfans", "SimpleBT"}
, {0, "PRC.P---", "Bittorrent Plus! II"}
, {0, "P87.P---", "Bittorrent Plus!"}
, {0, "S587Plus", "Bittorrent Plus!"}
, {0, "martini", "Martini Man"}
, {0, "Plus---", "Bittorrent Plus"}
, {0, "turbobt", "TurboBT"}
, {0, "a00---0", "Swarmy"}
, {0, "a02---0", "Swarmy"}
, {0, "T00---0", "Teeweety"}
, {0, "BTDWV-", "Deadman Walking"}
, {2, "BS", "BitSpirit"}
, {0, "Pando-", "Pando"}
, {0, "LIME", "LimeWire"}
, {0, "btuga", "BTugaXP"}
, {0, "oernu", "BTugaXP"}
, {0, "Mbrst", "Burst!"}
, {0, "PEERAPP", "PeerApp"}
, {0, "Plus", "Plus!"}
, {0, "-Qt-", "Qt"}
, {0, "exbc", "BitComet"}
, {0, "DNA", "BitTorrent DNA"}
, {0, "-G3", "G3 Torrent"}
, {0, "-FG", "FlashGet"}
, {0, "-ML", "MLdonkey"}
, {0, "XBT", "XBT"}
, {0, "OP", "Opera"}
, {2, "RS", "Rufus"}
, {0, "AZ2500BT", "BitTyrant"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
TORRENT_ASSERT(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]);
for (int i = 0; i < num_generic_mappings; ++i)
{
generic_map_entry const& e = generic_mappings[i];
if (find_string(PID + e.offset, e.id)) return e.name;
}
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>added LeechCraft to identify client<commit_after>/*
Copyright (c) 2003, 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 "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LC", "LeechCraft"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MR", "Miro"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"ST", "SymTorrent"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "uTorrent"}
, {"XL", "Xunlei"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
, {"st", "SharkTorrent"}
};
struct generic_map_entry
{
int offset;
char const* id;
char const* name;
};
// non-standard names
generic_map_entry generic_mappings[] =
{
{0, "Deadman Walking-", "Deadman"}
, {5, "Azureus", "Azureus 2.0.3.2"}
, {0, "DansClient", "XanTorrent"}
, {4, "btfans", "SimpleBT"}
, {0, "PRC.P---", "Bittorrent Plus! II"}
, {0, "P87.P---", "Bittorrent Plus!"}
, {0, "S587Plus", "Bittorrent Plus!"}
, {0, "martini", "Martini Man"}
, {0, "Plus---", "Bittorrent Plus"}
, {0, "turbobt", "TurboBT"}
, {0, "a00---0", "Swarmy"}
, {0, "a02---0", "Swarmy"}
, {0, "T00---0", "Teeweety"}
, {0, "BTDWV-", "Deadman Walking"}
, {2, "BS", "BitSpirit"}
, {0, "Pando-", "Pando"}
, {0, "LIME", "LimeWire"}
, {0, "btuga", "BTugaXP"}
, {0, "oernu", "BTugaXP"}
, {0, "Mbrst", "Burst!"}
, {0, "PEERAPP", "PeerApp"}
, {0, "Plus", "Plus!"}
, {0, "-Qt-", "Qt"}
, {0, "exbc", "BitComet"}
, {0, "DNA", "BitTorrent DNA"}
, {0, "-G3", "G3 Torrent"}
, {0, "-FG", "FlashGet"}
, {0, "-ML", "MLdonkey"}
, {0, "XBT", "XBT"}
, {0, "OP", "Opera"}
, {2, "RS", "Rufus"}
, {0, "AZ2500BT", "BitTyrant"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
TORRENT_ASSERT(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]);
for (int i = 0; i < num_generic_mappings; ++i)
{
generic_map_entry const& e = generic_mappings[i];
if (find_string(PID + e.offset, e.id)) return e.name;
}
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ISTREAM_HXX
#define ISTREAM_HXX
#include "pool/Holder.hxx"
#include "pool/Notify.hxx"
#include "io/FdType.hxx"
#include "util/LeakDetector.hxx"
#include <algorithm>
#include <assert.h>
class IstreamHandler;
class IstreamBucketList;
/**
* An asynchronous input stream.
*
* The lifetime of an #istream begins when it is created, and ends
* with one of the following events:
*
* - it is closed manually using istream_close()
* - it is invalidated by a successful istream_as_fd() call
* - it has reached end-of-file
* - an error has occurred
*/
class Istream : PoolHolder, LeakDetector {
/** data sink */
IstreamHandler *handler = nullptr;
/** which types of file descriptors are accepted by the handler? */
FdTypeMask handler_direct = 0;
#ifndef NDEBUG
bool reading = false, destroyed = false;
bool closing = false, eof = false;
bool in_data = false, available_full_set = false;
/** how much data was available in the previous invocation? */
size_t data_available = 0;
off_t available_partial = 0, available_full = 0;
#endif
protected:
explicit Istream(struct pool &_pool) noexcept
:PoolHolder(_pool) {}
Istream(const Istream &) = delete;
Istream &operator=(const Istream &) = delete;
virtual ~Istream() noexcept;
using PoolHolder::GetPool;
public:
FdTypeMask GetHandlerDirect() const {
return handler_direct;
}
protected:
bool CheckDirect(FdType type) const {
return (handler_direct & FdTypeMask(type)) != 0;
}
void Consumed(size_t nbytes) {
#ifdef NDEBUG
(void)nbytes;
#else
if ((off_t)nbytes >= available_partial)
available_partial = 0;
else
available_partial -= nbytes;
if (available_full_set) {
assert((off_t)nbytes <= available_full);
available_full -= (off_t)nbytes;
}
data_available -= std::min(nbytes, data_available);
#endif
}
size_t InvokeData(const void *data, size_t length) noexcept;
ssize_t InvokeDirect(FdType type, int fd, size_t max_length) noexcept;
void InvokeEof() noexcept;
void InvokeError(std::exception_ptr ep) noexcept;
void Destroy() noexcept {
this->~Istream();
/* no need to free memory from the pool */
}
void DestroyEof() noexcept {
InvokeEof();
Destroy();
}
void DestroyError(std::exception_ptr ep) noexcept {
InvokeError(ep);
Destroy();
}
/**
* @return the number of bytes still in the buffer
*/
template<typename Buffer>
size_t ConsumeFromBuffer(Buffer &buffer) noexcept {
auto r = buffer.Read().ToVoid();
if (r.empty())
return 0;
size_t consumed = InvokeData(r.data, r.size);
if (consumed > 0)
buffer.Consume(consumed);
return r.size - consumed;
}
/**
* @return the number of bytes consumed
*/
template<typename Buffer>
size_t SendFromBuffer(Buffer &buffer) noexcept {
auto r = buffer.Read().ToVoid();
if (r.empty())
return 0;
size_t consumed = InvokeData(r.data, r.size);
if (consumed > 0)
buffer.Consume(consumed);
return consumed;
}
public:
bool HasHandler() const noexcept {
assert(!destroyed);
return handler != nullptr;
}
void SetHandler(IstreamHandler &_handler,
FdTypeMask _handler_direct=0) noexcept {
assert(!destroyed);
handler = &_handler;
handler_direct = _handler_direct;
}
void SetDirect(FdTypeMask _handler_direct) noexcept {
assert(!destroyed);
handler_direct = _handler_direct;
}
/**
* How much data is available?
*
* @param partial if false, the stream must provide the data size
* until the end of the stream; for partial, a minimum estimate is
* ok
* @return the number of bytes available or -1 if the object does
* not know
*/
gcc_pure
off_t GetAvailable(bool partial) noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
PoolNotify notify(pool);
reading = true;
#endif
off_t available = _GetAvailable(partial);
#ifndef NDEBUG
assert(available >= -1);
assert(!notify.IsDestroyed());
assert(!destroyed);
assert(reading);
reading = false;
if (partial) {
assert(available_partial == 0 ||
available >= available_partial);
if (available > available_partial)
available_partial = available;
} else {
assert(!available_full_set ||
available_full == available);
if (!available_full_set && available != (off_t)-1) {
available_full = available;
available_full_set = true;
}
}
#endif
return available;
}
/**
* Skip data without processing it. By skipping 0 bytes, you can
* test whether the stream is able to skip at all.
*
* @return the number of bytes skipped or -1 if skipping is not supported
*/
off_t Skip(off_t length) noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
PoolNotify notify(pool);
reading = true;
#endif
off_t nbytes = _Skip(length);
assert(nbytes <= length);
#ifndef NDEBUG
if (notify.IsDestroyed() || destroyed)
return nbytes;
reading = false;
if (nbytes > 0) {
if (nbytes > available_partial)
available_partial = 0;
else
available_partial -= nbytes;
assert(!available_full_set ||
nbytes < available_full);
if (available_full_set)
available_full -= nbytes;
}
#endif
return nbytes;
}
/**
* Try to read from the stream. If the stream can read data
* without blocking, it must provide data. It may invoke the
* callbacks any number of times, supposed that the handler itself
* doesn't block.
*
* If the stream does not provide data immediately (and it is not
* at EOF yet), it must install an event and invoke the handler
* later, whenever data becomes available.
*
* Whenever the handler reports it is blocking, the responsibility
* for calling back (and calling this function) is handed back to
* the istream handler.
*/
void Read() noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
PoolNotify notify(pool);
reading = true;
#endif
_Read();
#ifndef NDEBUG
if (notify.IsDestroyed() || destroyed)
return;
reading = false;
#endif
}
/**
* Append #IstreamBucket instances with consecutive data from this
* #Istream to the end of the given #IstreamBucketList. Unless
* the returned data marks the end of the stream,
* IstreamBucketList::SetMore() must be called.
*
* On error, this method destroys the #Istream instance and throws
* std::runtime_error.
*/
void FillBucketList(IstreamBucketList &list) {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
PoolNotify notify(pool);
reading = true;
try {
#endif
_FillBucketList(list);
#ifndef NDEBUG
} catch (...) {
if (!notify.IsDestroyed()) {
assert(destroyed);
}
throw;
}
assert(!notify.IsDestroyed());
assert(!destroyed);
assert(reading);
reading = false;
#if 0
// TODO: not possible currently due to include dependencies
size_t total_size = list.GetTotalBufferSize();
if ((off_t)total_size > available_partial)
available_partial = total_size;
if (!list.HasMore() && !list.HasNonBuffer()) {
if (available_full_set)
assert((off_t)total_size == available_full);
else
available_full = total_size;
}
#endif
#endif
}
/**
* Consume data from the #IstreamBucketList filled by
* FillBucketList().
*
* @param nbytes the number of bytes to be consumed; may be more
* than returned by FillBucketList(), because some of the data may
* be returned by this Istream's successive siblings
*
* @return the number of bytes really consumed by this instance
* (the rest will be consumed by its siblings)
*/
size_t ConsumeBucketList(size_t nbytes) noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
#endif
auto result = _ConsumeBucketList(nbytes);
#ifndef NDEBUG
assert(!destroyed);
assert(result <= nbytes);
#endif
return result;
}
/**
* Close the istream object, and return the remaining data as a
* file descriptor. This fd can be read until end-of-stream.
* Returns -1 if this is not possible (the stream object is still
* usable).
*/
int AsFd() noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
PoolNotify notify(pool);
reading = true;
#endif
int fd = _AsFd();
#ifndef NDEBUG
assert(!notify.IsDestroyed() || fd < 0);
if (fd < 0)
reading = false;
#endif
return fd;
}
/**
* Close the stream and free resources. This must not be called
* after the handler's eof() / abort() callbacks were invoked.
*/
void Close() noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
closing = true;
#endif
_Close();
}
/**
* Close an istream which was never used, i.e. it does not have a
* handler yet.
*/
void CloseUnused() noexcept {
assert(!HasHandler());
Close();
}
protected:
virtual off_t _GetAvailable(gcc_unused bool partial) noexcept {
return -1;
}
virtual off_t _Skip(gcc_unused off_t length) noexcept {
return -1;
}
virtual void _Read() noexcept = 0;
virtual void _FillBucketList(IstreamBucketList &list);
virtual size_t _ConsumeBucketList(size_t nbytes) noexcept;
virtual int _AsFd() noexcept {
return -1;
}
virtual void _Close() noexcept {
Destroy();
}
};
#endif
<commit_msg>istream/Istream: add method ClearHandler()<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ISTREAM_HXX
#define ISTREAM_HXX
#include "pool/Holder.hxx"
#include "pool/Notify.hxx"
#include "io/FdType.hxx"
#include "util/LeakDetector.hxx"
#include <algorithm>
#include <assert.h>
class IstreamHandler;
class IstreamBucketList;
/**
* An asynchronous input stream.
*
* The lifetime of an #istream begins when it is created, and ends
* with one of the following events:
*
* - it is closed manually using istream_close()
* - it is invalidated by a successful istream_as_fd() call
* - it has reached end-of-file
* - an error has occurred
*/
class Istream : PoolHolder, LeakDetector {
/** data sink */
IstreamHandler *handler = nullptr;
/** which types of file descriptors are accepted by the handler? */
FdTypeMask handler_direct = 0;
#ifndef NDEBUG
bool reading = false, destroyed = false;
bool closing = false, eof = false;
bool in_data = false, available_full_set = false;
/** how much data was available in the previous invocation? */
size_t data_available = 0;
off_t available_partial = 0, available_full = 0;
#endif
protected:
explicit Istream(struct pool &_pool) noexcept
:PoolHolder(_pool) {}
Istream(const Istream &) = delete;
Istream &operator=(const Istream &) = delete;
virtual ~Istream() noexcept;
using PoolHolder::GetPool;
public:
FdTypeMask GetHandlerDirect() const {
return handler_direct;
}
protected:
bool CheckDirect(FdType type) const {
return (handler_direct & FdTypeMask(type)) != 0;
}
void Consumed(size_t nbytes) {
#ifdef NDEBUG
(void)nbytes;
#else
if ((off_t)nbytes >= available_partial)
available_partial = 0;
else
available_partial -= nbytes;
if (available_full_set) {
assert((off_t)nbytes <= available_full);
available_full -= (off_t)nbytes;
}
data_available -= std::min(nbytes, data_available);
#endif
}
size_t InvokeData(const void *data, size_t length) noexcept;
ssize_t InvokeDirect(FdType type, int fd, size_t max_length) noexcept;
void InvokeEof() noexcept;
void InvokeError(std::exception_ptr ep) noexcept;
void Destroy() noexcept {
this->~Istream();
/* no need to free memory from the pool */
}
void DestroyEof() noexcept {
InvokeEof();
Destroy();
}
void DestroyError(std::exception_ptr ep) noexcept {
InvokeError(ep);
Destroy();
}
/**
* @return the number of bytes still in the buffer
*/
template<typename Buffer>
size_t ConsumeFromBuffer(Buffer &buffer) noexcept {
auto r = buffer.Read().ToVoid();
if (r.empty())
return 0;
size_t consumed = InvokeData(r.data, r.size);
if (consumed > 0)
buffer.Consume(consumed);
return r.size - consumed;
}
/**
* @return the number of bytes consumed
*/
template<typename Buffer>
size_t SendFromBuffer(Buffer &buffer) noexcept {
auto r = buffer.Read().ToVoid();
if (r.empty())
return 0;
size_t consumed = InvokeData(r.data, r.size);
if (consumed > 0)
buffer.Consume(consumed);
return consumed;
}
public:
bool HasHandler() const noexcept {
assert(!destroyed);
return handler != nullptr;
}
void SetHandler(IstreamHandler &_handler,
FdTypeMask _handler_direct=0) noexcept {
assert(!destroyed);
handler = &_handler;
handler_direct = _handler_direct;
}
/**
* Detach the handler from this object. This should only be done
* if it is going to be reattached to a new handler right after
* this call.
*/
void ClearHandler() noexcept {
handler = nullptr;
handler_direct = 0;
}
void SetDirect(FdTypeMask _handler_direct) noexcept {
assert(!destroyed);
handler_direct = _handler_direct;
}
/**
* How much data is available?
*
* @param partial if false, the stream must provide the data size
* until the end of the stream; for partial, a minimum estimate is
* ok
* @return the number of bytes available or -1 if the object does
* not know
*/
gcc_pure
off_t GetAvailable(bool partial) noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
PoolNotify notify(pool);
reading = true;
#endif
off_t available = _GetAvailable(partial);
#ifndef NDEBUG
assert(available >= -1);
assert(!notify.IsDestroyed());
assert(!destroyed);
assert(reading);
reading = false;
if (partial) {
assert(available_partial == 0 ||
available >= available_partial);
if (available > available_partial)
available_partial = available;
} else {
assert(!available_full_set ||
available_full == available);
if (!available_full_set && available != (off_t)-1) {
available_full = available;
available_full_set = true;
}
}
#endif
return available;
}
/**
* Skip data without processing it. By skipping 0 bytes, you can
* test whether the stream is able to skip at all.
*
* @return the number of bytes skipped or -1 if skipping is not supported
*/
off_t Skip(off_t length) noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
PoolNotify notify(pool);
reading = true;
#endif
off_t nbytes = _Skip(length);
assert(nbytes <= length);
#ifndef NDEBUG
if (notify.IsDestroyed() || destroyed)
return nbytes;
reading = false;
if (nbytes > 0) {
if (nbytes > available_partial)
available_partial = 0;
else
available_partial -= nbytes;
assert(!available_full_set ||
nbytes < available_full);
if (available_full_set)
available_full -= nbytes;
}
#endif
return nbytes;
}
/**
* Try to read from the stream. If the stream can read data
* without blocking, it must provide data. It may invoke the
* callbacks any number of times, supposed that the handler itself
* doesn't block.
*
* If the stream does not provide data immediately (and it is not
* at EOF yet), it must install an event and invoke the handler
* later, whenever data becomes available.
*
* Whenever the handler reports it is blocking, the responsibility
* for calling back (and calling this function) is handed back to
* the istream handler.
*/
void Read() noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
PoolNotify notify(pool);
reading = true;
#endif
_Read();
#ifndef NDEBUG
if (notify.IsDestroyed() || destroyed)
return;
reading = false;
#endif
}
/**
* Append #IstreamBucket instances with consecutive data from this
* #Istream to the end of the given #IstreamBucketList. Unless
* the returned data marks the end of the stream,
* IstreamBucketList::SetMore() must be called.
*
* On error, this method destroys the #Istream instance and throws
* std::runtime_error.
*/
void FillBucketList(IstreamBucketList &list) {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
PoolNotify notify(pool);
reading = true;
try {
#endif
_FillBucketList(list);
#ifndef NDEBUG
} catch (...) {
if (!notify.IsDestroyed()) {
assert(destroyed);
}
throw;
}
assert(!notify.IsDestroyed());
assert(!destroyed);
assert(reading);
reading = false;
#if 0
// TODO: not possible currently due to include dependencies
size_t total_size = list.GetTotalBufferSize();
if ((off_t)total_size > available_partial)
available_partial = total_size;
if (!list.HasMore() && !list.HasNonBuffer()) {
if (available_full_set)
assert((off_t)total_size == available_full);
else
available_full = total_size;
}
#endif
#endif
}
/**
* Consume data from the #IstreamBucketList filled by
* FillBucketList().
*
* @param nbytes the number of bytes to be consumed; may be more
* than returned by FillBucketList(), because some of the data may
* be returned by this Istream's successive siblings
*
* @return the number of bytes really consumed by this instance
* (the rest will be consumed by its siblings)
*/
size_t ConsumeBucketList(size_t nbytes) noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
#endif
auto result = _ConsumeBucketList(nbytes);
#ifndef NDEBUG
assert(!destroyed);
assert(result <= nbytes);
#endif
return result;
}
/**
* Close the istream object, and return the remaining data as a
* file descriptor. This fd can be read until end-of-stream.
* Returns -1 if this is not possible (the stream object is still
* usable).
*/
int AsFd() noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
assert(!reading);
assert(!in_data);
PoolNotify notify(pool);
reading = true;
#endif
int fd = _AsFd();
#ifndef NDEBUG
assert(!notify.IsDestroyed() || fd < 0);
if (fd < 0)
reading = false;
#endif
return fd;
}
/**
* Close the stream and free resources. This must not be called
* after the handler's eof() / abort() callbacks were invoked.
*/
void Close() noexcept {
#ifndef NDEBUG
assert(!destroyed);
assert(!closing);
assert(!eof);
closing = true;
#endif
_Close();
}
/**
* Close an istream which was never used, i.e. it does not have a
* handler yet.
*/
void CloseUnused() noexcept {
assert(!HasHandler());
Close();
}
protected:
virtual off_t _GetAvailable(gcc_unused bool partial) noexcept {
return -1;
}
virtual off_t _Skip(gcc_unused off_t length) noexcept {
return -1;
}
virtual void _Read() noexcept = 0;
virtual void _FillBucketList(IstreamBucketList &list);
virtual size_t _ConsumeBucketList(size_t nbytes) noexcept;
virtual int _AsFd() noexcept {
return -1;
}
virtual void _Close() noexcept {
Destroy();
}
};
#endif
<|endoftext|>
|
<commit_before>#include "mystring.hpp"
<commit_msg>Implemented my string type.<commit_after>#include "mystring.hpp"
/////////////
// Imports //
#include <iostream>
#include <string.h>
#include "array.hpp"
//////////
// Code //
// Constructing a string from a c string.
String::String(char* word) : Array<char>() {
int l = strlen(word);
for (int i = 0; i < l; i++)
this->append(word[i]);
}
// Constructing a string with a given capacity.
String::String(int size) : Array<char>(size) { }
// Constructing a string with a default capacity.
String::String() : Array<char>() { }
// Printing out the strng.
void String::print() {
for (int i = 0; i < this->get_length(); i++)
std::cout << this->get(i);
}
// Printing out the string with a newline after.
void String::println() {
this->print();
std::cout << "\n";
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "MetaCallMapping.h"
#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(OOModel::MetaCallMapping)
namespace OOModel {
COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(MetaCallMapping)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(MetaCallMapping)
REGISTER_ATTRIBUTE(MetaCallMapping, value, ReferenceExpression, false, false, true)
MetaCallMapping::MetaCallMapping(const QString& name) : Super(nullptr, MetaCallMapping::getMetaData())
{
setName(name);
}
MetaCallMapping::SymbolTypes MetaCallMapping::symbolType() const
{
return UNSPECIFIED;
}
}
<commit_msg>Change symbolType of MetaCallMapping<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "MetaCallMapping.h"
#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(OOModel::MetaCallMapping)
namespace OOModel {
COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(MetaCallMapping)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(MetaCallMapping)
REGISTER_ATTRIBUTE(MetaCallMapping, value, ReferenceExpression, false, false, true)
MetaCallMapping::MetaCallMapping(const QString& name) : Super(nullptr, MetaCallMapping::getMetaData())
{
setName(name);
}
MetaCallMapping::SymbolTypes MetaCallMapping::symbolType() const
{
return VARIABLE;
}
}
<|endoftext|>
|
<commit_before>void runPluginProof
(
const char *runMode = "full",
Int_t nmix = 50,
//const char *clusterName = "alice-caf.cern.ch",
//const char *dataSet = "/alice/sim/LHC10d1_000117112",
//const char *options = "esd_mc",
//const char *dataSet = "/alice/sim/LHC11a10b_000139507",
//const char *options = "esd_mc_pbpb",
//const char *dataSet = "/PWG3/rbala/LHC11a10b_000137748_AOD048",
//const char *options = "aod_mc_pbpb",
const char *clusterName = "skaf.saske.sk",
const char *dataSet = "/alice/sim/LHC10d2_117099",
const char *options = "esd_mc",
//const char *dataSet = "/alice/sim/LHC11a10b_000139314_AOD048",
//const char *options = "aod_mc_pbpb",
const char *outName = "proof.root",
const char *macroPath = "..",
const char *testFile = "",
const char *addLibs = "libEventMixing.so PWG2resonances.par",
const char *addPars = ""
)
{
//
// === PREPARATION ==============================================================================
//
// this option is not needed when using plugin
// gEnv->SetValue("XSec.GSI.DelegProxy","2");
// execute the general setup from the apposite macro
// it returns also a TString value with the input tree name
gROOT->LoadMacro("../AnalysisSetupRsnMini.C");
TString out = Setup(nmix, options, outName, macroPath);
if (out.Length() < 1) return;
//
// === PLUGIN CONFIGURATION =====================================================================
//
// load macro for plugin setup
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gROOT->LoadMacro("SetupPlugin.C++g");
// set run modalities
PluginSetup::runMode = runMode;
PluginSetup::targetAlien = kFALSE;
// define inputs
PluginSetup::dataSet = dataSet;
PluginSetup::proofTest = testFile;
PluginSetup::proofCluster = clusterName;
// define additional libraries
PluginSetup::addLibs = addLibs;
PluginSetup::addPar = addPars;
// additional modalities
PluginSetup::aliVersion = "v4-21-26-AN";
// create the plugin (need to know if we want tender)
if (!PluginSetup::CreatePlugin()) return;
PluginSetup::plugin->SetRunMode(runMode);
PluginSetup::plugin->SetOverwriteMode();
PluginSetup::plugin->SetProofParameter("PROOF_UseMergers", "-1");
if (nmix > 0) {::Info("run", "Forcing local"); PluginSetup::plugin->SetProofParameter("PROOF_ForceLocal", "1");}
PluginSetup::plugin->SetRootVersionForProof("current");
PluginSetup::plugin->SetAliRootMode("default");
PluginSetup::plugin->SetClearPackages(kFALSE);
//
// === ANALYSIS EXECUTION =======================================================================
//
// add plugin to analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
mgr->SetGridHandler(PluginSetup::plugin);
// initialize and start analysis
if (!mgr->InitAnalysis()) {
::Error("runPlugin.C", "Failed to init analysis");
return;
}
mgr->PrintStatus();
mgr->StartAnalysis("proof");
}
<commit_msg>Bugfix<commit_after>void runPluginProof
(
const char *runMode = "full",
Int_t nmix = 50,
//const char *clusterName = "alice-caf.cern.ch",
//const char *dataSet = "/alice/sim/LHC10d1_000117112",
//const char *options = "esd_mc",
//const char *dataSet = "/alice/sim/LHC11a10b_000139507",
//const char *options = "esd_mc_pbpb",
//const char *dataSet = "/PWG3/rbala/LHC11a10b_000137748_AOD048",
//const char *options = "aod_mc_pbpb",
const char *clusterName = "skaf.saske.sk",
const char *dataSet = "/alice/sim/LHC10d2_117099",
const char *options = "esd_mc",
//const char *dataSet = "/alice/sim/LHC11a10b_000139314_AOD048",
//const char *options = "aod_mc_pbpb",
const char *outName = "proof.root",
const char *macroPath = ".",
const char *testFile = "",
const char *addLibs = "libEventMixing.so PWG2resonances.par",
const char *addPars = ""
)
{
//
// === PREPARATION ==============================================================================
//
// this option is not needed when using plugin
// gEnv->SetValue("XSec.GSI.DelegProxy","2");
// execute the general setup from the apposite macro
// it returns also a TString value with the input tree name
gROOT->LoadMacro("AnalysisSetupRsnMini.C");
TString out = Setup(nmix, options, outName, macroPath);
if (out.Length() < 1) return;
//
// === PLUGIN CONFIGURATION =====================================================================
//
// load macro for plugin setup
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gROOT->LoadMacro("SetupPlugin.C++g");
// set run modalities
PluginSetup::runMode = runMode;
PluginSetup::targetAlien = kFALSE;
// define inputs
PluginSetup::dataSet = dataSet;
PluginSetup::proofTest = testFile;
PluginSetup::proofCluster = clusterName;
// define additional libraries
PluginSetup::addLibs = addLibs;
PluginSetup::addPar = addPars;
// additional modalities
PluginSetup::aliVersion = "v4-21-26-AN";
// create the plugin (need to know if we want tender)
if (!PluginSetup::CreatePlugin()) return;
PluginSetup::plugin->SetRunMode(runMode);
PluginSetup::plugin->SetOverwriteMode();
PluginSetup::plugin->SetProofParameter("PROOF_UseMergers", "-1");
if (nmix > 0) {::Info("run", "Forcing local"); PluginSetup::plugin->SetProofParameter("PROOF_ForceLocal", "1");}
PluginSetup::plugin->SetRootVersionForProof("current");
PluginSetup::plugin->SetAliRootMode("default");
PluginSetup::plugin->SetClearPackages(kFALSE);
//
// === ANALYSIS EXECUTION =======================================================================
//
// add plugin to analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
mgr->SetGridHandler(PluginSetup::plugin);
// initialize and start analysis
if (!mgr->InitAnalysis()) {
::Error("runPlugin.C", "Failed to init analysis");
return;
}
mgr->PrintStatus();
mgr->StartAnalysis("proof");
}
<|endoftext|>
|
<commit_before>/*
* FrameAverage.cpp
*
* Created on: Apr 22, 2010
* Author: Nathan Clack <clackn@janelia.hhmi.org>
*/
/*
* Notes for change to resizable queue
* -----------------------------------
* - need current buffer size for push/pop...just need to keep track
* - what happens if the source buffer changes in the middle of an average
*/
#include "stdafx.h"
#include "FrameAverage.h"
using namespace fetch::worker;
namespace fetch
{
namespace task
{
unsigned int
FrameAverage::run(Agent *a)
{ FrameAverageAgent *agent = dynamic_cast<FrameAverageAgent*>(a);
int every = agent->config;
asynq *qsrc = agent->in->contents[ 0 ],
*qdst = agent->out->contents[ 0 ];
Frame *fsrc = (Frame*) Asynq_Token_Buffer_Alloc(qsrc),
*fdst = (Frame*) Asynq_Token_Buffer_Alloc(qdst);
f32 *buf, *acc = NULL;
size_t dst_bytes = qdst->q->buffer_size_bytes;
{ unsigned int i,count=0;
do
{
size_t src_bytes = qsrc->q->buffer_size_bytes,
nbytes = src_bytes - sizeof(Frame), //bytes in acc
nelem = nbytes / sizeof(f32);
// First one
if(!agent->is_stopping() && Asynq_Pop(qsrc,(void**)&fsrc,src_bytes))
{
if(fsrc->size_bytes()>dst_bytes)
Guarded_Assert(fdst = (Frame*) realloc(fdst,dst_bytes = fsrc->size_bytes()));
fsrc->format(fdst);
acc = (f32*) fdst->data;
memcpy(acc,fsrc->data,nbytes);
} else
continue;
// The rest
while(!agent->is_stopping() && Asynq_Pop(qsrc, (void**)&fsrc, fsrc->size_bytes()) )
{ buf = (f32*) fsrc->data;
++count;
if( count % every == 0 ) // emit and reset every so often
{ float norm = (float)every; // average
for(i=0;i<nelem;++i)
acc[i]/=norm;
goto_if_fail( // push - wait till successful
Asynq_Push_Timed( qdst, (void**)&fdst, fdst->size_bytes(), WORKER_DEFAULT_TIMEOUT ),
OutputQueueTimeoutError);
if(fsrc->size_bytes()>dst_bytes)
Guarded_Assert(fdst = (Frame*)realloc(fdst,dst_bytes = fsrc->size_bytes()));
fsrc->format(fdst); // Initialize the accumulator
acc = (f32*)fdst->data;
memcpy(acc,fsrc->data,nbytes);
} else
{ for (i = 0; i < nelem; ++i) // accumulate
acc[i] += buf[i];
}
}
} while (!agent->is_stopping());
}
Asynq_Token_Buffer_Free(fsrc);
Asynq_Token_Buffer_Free(fdst);
return 0;
OutputQueueTimeoutError:
warning("Pushing to output queue timeout\r\n.");
Asynq_Token_Buffer_Free(fsrc);
Asynq_Token_Buffer_Free(fdst);
return 1; // failure
}
}
}<commit_msg>FrameAverage properly interprets averaging <2 frames<commit_after>/*
* FrameAverage.cpp
*
* Created on: Apr 22, 2010
* Author: Nathan Clack <clackn@janelia.hhmi.org>
*/
/*
* Notes for change to resizable queue
* -----------------------------------
* - need current buffer size for push/pop...just need to keep track
* - what happens if the source buffer changes in the middle of an average
*/
#include "stdafx.h"
#include "FrameAverage.h"
using namespace fetch::worker;
namespace fetch
{
namespace task
{
unsigned int
FrameAverage::run(Agent *a)
{ FrameAverageAgent *agent = dynamic_cast<FrameAverageAgent*>(a);
int every = agent->config;
asynq *qsrc = agent->in->contents[ 0 ],
*qdst = agent->out->contents[ 0 ];
Frame *fsrc = (Frame*) Asynq_Token_Buffer_Alloc(qsrc),
*fdst = (Frame*) Asynq_Token_Buffer_Alloc(qdst);
f32 *buf, *acc = NULL;
size_t dst_bytes = qdst->q->buffer_size_bytes;
if(every<=1)
// Do nothing, just pass through
{ while(!agent->is_stopping() && Asynq_Pop(qsrc, (void**)&fsrc, qsrc->q->buffer_size_bytes) )
goto_if_fail( // push - wait till successful
Asynq_Push_Timed( qdst, (void**)&fsrc, fsrc->size_bytes(), WORKER_DEFAULT_TIMEOUT ),
OutputQueueTimeoutError);
} else
{ unsigned int i,count=0;
do
{
size_t src_bytes = qsrc->q->buffer_size_bytes,
nbytes = src_bytes - sizeof(Frame), //bytes in acc
nelem = nbytes / sizeof(f32);
// First one
if(!agent->is_stopping() && Asynq_Pop(qsrc,(void**)&fsrc,src_bytes))
{
if(fsrc->size_bytes()>dst_bytes)
Guarded_Assert(fdst = (Frame*) realloc(fdst,dst_bytes = fsrc->size_bytes()));
fsrc->format(fdst);
acc = (f32*) fdst->data;
memcpy(acc,fsrc->data,nbytes);
} else
continue;
// The rest
while(!agent->is_stopping() && Asynq_Pop(qsrc, (void**)&fsrc, fsrc->size_bytes()) )
{ buf = (f32*) fsrc->data;
++count;
if( count % every == 0 ) // emit and reset every so often
{ float norm = (float)every; // average
for(i=0;i<nelem;++i)
acc[i]/=norm;
goto_if_fail( // push - wait till successful
Asynq_Push_Timed( qdst, (void**)&fdst, fdst->size_bytes(), WORKER_DEFAULT_TIMEOUT ),
OutputQueueTimeoutError);
if(fsrc->size_bytes()>dst_bytes)
Guarded_Assert(fdst = (Frame*)realloc(fdst,dst_bytes = fsrc->size_bytes()));
fsrc->format(fdst); // Initialize the accumulator
acc = (f32*)fdst->data;
memcpy(acc,fsrc->data,nbytes);
} else
{ for (i = 0; i < nelem; ++i) // accumulate
acc[i] += buf[i];
}
}
} while (!agent->is_stopping());
}
Asynq_Token_Buffer_Free(fsrc);
Asynq_Token_Buffer_Free(fdst);
return 0;
OutputQueueTimeoutError:
warning("Pushing to output queue timeout\r\n.");
Asynq_Token_Buffer_Free(fsrc);
Asynq_Token_Buffer_Free(fdst);
return 1; // failure
}
}
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version: $Revision: 7837 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
//Poco headers
#include "Poco/Path.h"
#include <mitkNavigationToolStorageSerializer.h>
#include <mitkNavigationToolStorageDeserializer.h>
#include <mitkCommon.h>
#include <mitkTestingMacros.h>
#include <mitkStandaloneDataStorage.h>
#include <mitkStandardFileLocations.h>
#include <mitkSTLFileReader.h>
#include "mitkNavigationToolStorage.h"
class NavigationToolStorageSerializerAndDeserializerTestClass
{
public:
static void TestInstantiationSerializer()
{
// let's create objects of our classes
mitk::NavigationToolStorageSerializer::Pointer testSerializer = mitk::NavigationToolStorageSerializer::New();
MITK_TEST_CONDITION_REQUIRED(testSerializer.IsNotNull(),"Testing instantiation of NavigationToolStorageSerializer");
}
static void TestInstantiationDeserializer()
{
mitk::DataStorage::Pointer tempStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); //needed for deserializer!
mitk::NavigationToolStorageDeserializer::Pointer testDeserializer = mitk::NavigationToolStorageDeserializer::New(tempStorage);
MITK_TEST_CONDITION_REQUIRED(testDeserializer.IsNotNull(),"Testing instantiation of NavigationToolStorageDeserializer")
}
static void TestWriteSimpleToolStorage()
{
//create Tool Storage
mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
//first tool
mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
myTool1->SetIdentifier("001");
myStorage->AddTool(myTool1);
//second tool
mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
myTool2->SetIdentifier("002");
myStorage->AddTool(myTool2);
//third tool
mitk::NavigationTool::Pointer myTool3 = mitk::NavigationTool::New();
myTool3->SetIdentifier("003");
myStorage->AddTool(myTool3);
//create Serializer
mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New();
//create filename
std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage.storage";
//test serialization
bool success = mySerializer->Serialize(filename,myStorage);
MITK_TEST_CONDITION_REQUIRED(success,"Testing serialization of simple tool storage");
}
static void TestReadSimpleToolStorage()
{
mitk::DataStorage::Pointer tempStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); //needed for deserializer!
mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(tempStorage);
mitk::NavigationToolStorage::Pointer readStorage = myDeserializer->Deserialize(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage.storage");
MITK_TEST_CONDITION_REQUIRED(readStorage.IsNotNull(),"Testing deserialization of simple tool storage");
MITK_TEST_CONDITION_REQUIRED(readStorage->GetToolCount()==3," ..Testing number of tools in storage");
//TODO: why is the order of tools changed is save/load process??
bool foundtool1 = false;
bool foundtool2 = false;
bool foundtool3 = false;
for(int i=0; i<3; i++)
{
if ((readStorage->GetTool(i)->GetIdentifier()=="001")) foundtool1 = true;
else if ((readStorage->GetTool(i)->GetIdentifier()=="002")) foundtool2 = true;
else if ((readStorage->GetTool(i)->GetIdentifier()=="003")) foundtool3 = true;
}
MITK_TEST_CONDITION_REQUIRED(foundtool1&&foundtool2&&foundtool3," ..Testing if identifiers of tools where saved / loaded successfully");
}
static void CleanUp()
{
std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage.storage").c_str());
std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage2.storage").c_str());
}
static void TestWriteComplexToolStorage()
{
//create first tool
mitk::Surface::Pointer testSurface;
std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data");
MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration of claron tool file exists");
mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();
myNavigationTool->SetCalibrationFile(toolFileName);
mitk::DataNode::Pointer myNode = mitk::DataNode::New();
myNode->SetName("ClaronTool");
//load an stl File
mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();
try
{
stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool.stl", "Testing/Data/").c_str() );
stlReader->Update();
}
catch (...)
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
if ( stlReader->GetOutput() == NULL )
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
else
{
testSurface = stlReader->GetOutput();
myNode->SetData(testSurface);
}
myNavigationTool->SetDataNode(myNode);
myNavigationTool->SetIdentifier("ClaronTool#1");
myNavigationTool->SetSerialNumber("0815");
myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron);
myNavigationTool->SetType(mitk::NavigationTool::Fiducial);
//create second tool
mitk::NavigationTool::Pointer myNavigationTool2 = mitk::NavigationTool::New();
mitk::Surface::Pointer testSurface2;
mitk::DataNode::Pointer myNode2 = mitk::DataNode::New();
myNode2->SetName("AuroraTool");
//load an stl File
try
{
stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("EMTool.stl", "Testing/Data/").c_str() );
stlReader->Update();
}
catch (...)
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
if ( stlReader->GetOutput() == NULL )
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
else
{
testSurface2 = stlReader->GetOutput();
myNode2->SetData(testSurface2);
}
myNavigationTool2->SetDataNode(myNode2);
myNavigationTool2->SetIdentifier("AuroraTool#1");
myNavigationTool2->SetSerialNumber("0816");
myNavigationTool2->SetTrackingDeviceType(mitk::NDIAurora);
myNavigationTool2->SetType(mitk::NavigationTool::Instrument);
//create navigation tool storage
mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
myStorage->AddTool(myNavigationTool);
myStorage->AddTool(myNavigationTool2);
//create Serializer
mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New();
//create filename
std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage2.storage";
//test serialization
bool success = mySerializer->Serialize(filename,myStorage);
MITK_TEST_CONDITION_REQUIRED(success,"Testing serialization of complex tool storage");
}
static void TestReadComplexToolStorage()
{
mitk::DataStorage::Pointer tempStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); //needed for deserializer!
mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(tempStorage);
mitk::NavigationToolStorage::Pointer readStorage = myDeserializer->Deserialize(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage2.storage");
MITK_TEST_CONDITION_REQUIRED(readStorage.IsNotNull(),"Testing deserialization of complex tool storage");
MITK_TEST_CONDITION_REQUIRED(readStorage->GetToolCount()==2," ..Testing number of tools in storage");
}
};
/** This function is testing the TrackingVolume class. */
int mitkNavigationToolStorageSerializerAndDeserializerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("NavigationToolStorageSerializerAndDeserializer");
NavigationToolStorageSerializerAndDeserializerTestClass::TestInstantiationSerializer();
NavigationToolStorageSerializerAndDeserializerTestClass::TestInstantiationDeserializer();
NavigationToolStorageSerializerAndDeserializerTestClass::TestWriteSimpleToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::TestReadSimpleToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::TestWriteComplexToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::TestReadComplexToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::CleanUp();
MITK_TEST_END();
}
<commit_msg>COMP (#7928): Deactivated instantiation tests because of strange behavior<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version: $Revision: 7837 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
//Poco headers
#include "Poco/Path.h"
#include <mitkNavigationToolStorageSerializer.h>
#include <mitkNavigationToolStorageDeserializer.h>
#include <mitkCommon.h>
#include <mitkTestingMacros.h>
#include <mitkStandaloneDataStorage.h>
#include <mitkStandardFileLocations.h>
#include <mitkSTLFileReader.h>
#include "mitkNavigationToolStorage.h"
class NavigationToolStorageSerializerAndDeserializerTestClass
{
public:
static void TestInstantiationSerializer()
{
// let's create objects of our classes
mitk::NavigationToolStorageSerializer::Pointer testSerializer = mitk::NavigationToolStorageSerializer::New();
MITK_TEST_CONDITION_REQUIRED(testSerializer.IsNotNull(),"Testing instantiation of NavigationToolStorageSerializer");
}
static void TestInstantiationDeserializer()
{
mitk::DataStorage::Pointer tempStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); //needed for deserializer!
mitk::NavigationToolStorageDeserializer::Pointer testDeserializer = mitk::NavigationToolStorageDeserializer::New(tempStorage);
MITK_TEST_CONDITION_REQUIRED(testDeserializer.IsNotNull(),"Testing instantiation of NavigationToolStorageDeserializer")
}
static void TestWriteSimpleToolStorage()
{
//create Tool Storage
mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
//first tool
mitk::NavigationTool::Pointer myTool1 = mitk::NavigationTool::New();
myTool1->SetIdentifier("001");
myStorage->AddTool(myTool1);
//second tool
mitk::NavigationTool::Pointer myTool2 = mitk::NavigationTool::New();
myTool2->SetIdentifier("002");
myStorage->AddTool(myTool2);
//third tool
mitk::NavigationTool::Pointer myTool3 = mitk::NavigationTool::New();
myTool3->SetIdentifier("003");
myStorage->AddTool(myTool3);
//create Serializer
mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New();
//create filename
std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage.storage";
//test serialization
bool success = mySerializer->Serialize(filename,myStorage);
MITK_TEST_CONDITION_REQUIRED(success,"Testing serialization of simple tool storage");
}
static void TestReadSimpleToolStorage()
{
mitk::DataStorage::Pointer tempStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); //needed for deserializer!
mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(tempStorage);
mitk::NavigationToolStorage::Pointer readStorage = myDeserializer->Deserialize(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage.storage");
MITK_TEST_CONDITION_REQUIRED(readStorage.IsNotNull(),"Testing deserialization of simple tool storage");
MITK_TEST_CONDITION_REQUIRED(readStorage->GetToolCount()==3," ..Testing number of tools in storage");
//TODO: why is the order of tools changed is save/load process??
bool foundtool1 = false;
bool foundtool2 = false;
bool foundtool3 = false;
for(int i=0; i<3; i++)
{
if ((readStorage->GetTool(i)->GetIdentifier()=="001")) foundtool1 = true;
else if ((readStorage->GetTool(i)->GetIdentifier()=="002")) foundtool2 = true;
else if ((readStorage->GetTool(i)->GetIdentifier()=="003")) foundtool3 = true;
}
MITK_TEST_CONDITION_REQUIRED(foundtool1&&foundtool2&&foundtool3," ..Testing if identifiers of tools where saved / loaded successfully");
}
static void CleanUp()
{
std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage.storage").c_str());
std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage2.storage").c_str());
}
static void TestWriteComplexToolStorage()
{
//create first tool
mitk::Surface::Pointer testSurface;
std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data");
MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration of claron tool file exists");
mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();
myNavigationTool->SetCalibrationFile(toolFileName);
mitk::DataNode::Pointer myNode = mitk::DataNode::New();
myNode->SetName("ClaronTool");
//load an stl File
mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();
try
{
stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool.stl", "Testing/Data/").c_str() );
stlReader->Update();
}
catch (...)
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
if ( stlReader->GetOutput() == NULL )
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
else
{
testSurface = stlReader->GetOutput();
myNode->SetData(testSurface);
}
myNavigationTool->SetDataNode(myNode);
myNavigationTool->SetIdentifier("ClaronTool#1");
myNavigationTool->SetSerialNumber("0815");
myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron);
myNavigationTool->SetType(mitk::NavigationTool::Fiducial);
//create second tool
mitk::NavigationTool::Pointer myNavigationTool2 = mitk::NavigationTool::New();
mitk::Surface::Pointer testSurface2;
mitk::DataNode::Pointer myNode2 = mitk::DataNode::New();
myNode2->SetName("AuroraTool");
//load an stl File
try
{
stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("EMTool.stl", "Testing/Data/").c_str() );
stlReader->Update();
}
catch (...)
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
if ( stlReader->GetOutput() == NULL )
{
MITK_TEST_FAILED_MSG(<<"Cannot read stl file.");
}
else
{
testSurface2 = stlReader->GetOutput();
myNode2->SetData(testSurface2);
}
myNavigationTool2->SetDataNode(myNode2);
myNavigationTool2->SetIdentifier("AuroraTool#1");
myNavigationTool2->SetSerialNumber("0816");
myNavigationTool2->SetTrackingDeviceType(mitk::NDIAurora);
myNavigationTool2->SetType(mitk::NavigationTool::Instrument);
//create navigation tool storage
mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New();
myStorage->AddTool(myNavigationTool);
myStorage->AddTool(myNavigationTool2);
//create Serializer
mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New();
//create filename
std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage2.storage";
//test serialization
bool success = mySerializer->Serialize(filename,myStorage);
MITK_TEST_CONDITION_REQUIRED(success,"Testing serialization of complex tool storage");
}
static void TestReadComplexToolStorage()
{
mitk::DataStorage::Pointer tempStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); //needed for deserializer!
mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(tempStorage);
mitk::NavigationToolStorage::Pointer readStorage = myDeserializer->Deserialize(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestStorage2.storage");
MITK_TEST_CONDITION_REQUIRED(readStorage.IsNotNull(),"Testing deserialization of complex tool storage");
MITK_TEST_CONDITION_REQUIRED(readStorage->GetToolCount()==2," ..Testing number of tools in storage");
}
};
/** This function is testing the TrackingVolume class. */
int mitkNavigationToolStorageSerializerAndDeserializerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("NavigationToolStorageSerializerAndDeserializer");
//NavigationToolStorageSerializerAndDeserializerTestClass::TestInstantiationSerializer();
//NavigationToolStorageSerializerAndDeserializerTestClass::TestInstantiationDeserializer();
NavigationToolStorageSerializerAndDeserializerTestClass::TestWriteSimpleToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::TestReadSimpleToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::TestWriteComplexToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::TestReadComplexToolStorage();
NavigationToolStorageSerializerAndDeserializerTestClass::CleanUp();
MITK_TEST_END();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperQtWidgetInputFilenameListParameter.h"
namespace otb
{
namespace Wrapper
{
QtWidgetInputFilenameListParameter
::QtWidgetInputFilenameListParameter( InputFilenameListParameter * param,
QtWidgetModel * m ) :
QtWidgetParameterList( param, m )
{
connect(
this, SIGNAL( Change() ),
// to:
GetModel(), SLOT( NotifyUpdate() )
);
}
QtWidgetInputFilenameListParameter
::~QtWidgetInputFilenameListParameter()
{
}
}
}
<commit_msg>ENH: Removed obsolete signal/slot connection.<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperQtWidgetInputFilenameListParameter.h"
namespace otb
{
namespace Wrapper
{
/*****************************************************************************/
QtWidgetInputFilenameListParameter
::QtWidgetInputFilenameListParameter( InputFilenameListParameter * param,
QtWidgetModel * m ) :
QtWidgetParameterList( param, m )
{
}
/*****************************************************************************/
QtWidgetInputFilenameListParameter
::~QtWidgetInputFilenameListParameter()
{
}
}
}
<|endoftext|>
|
<commit_before>#include <FancyMeshComponent.hpp>
#include <iostream>
#include <Core/String/StringUtils.hpp>
#include <Core/Mesh/MeshUtils.hpp>
#include <Core/Containers/MakeShared.hpp>
#include <Core/Geometry/Normal/Normal.hpp>
#include <Core/File/FileData.hpp>
#include <Core/File/GeometryData.hpp>
#include <Engine/Renderer/RenderObject/RenderObjectManager.hpp>
#include <Engine/Managers/ComponentMessenger/ComponentMessenger.hpp>
#include <Engine/Renderer/Mesh/Mesh.hpp>
#include <Engine/Renderer/RenderTechnique/Material.hpp>
#include <Engine/Renderer/RenderObject/RenderObject.hpp>
#include <Engine/Renderer/RenderObject/RenderObjectTypes.hpp>
#include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgram.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgramManager.hpp>
#include <Engine/Renderer/RenderObject/Primitives/DrawPrimitives.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp>
using Ra::Core::TriangleMesh;
using Ra::Engine::ComponentMessenger;
typedef Ra::Core::VectorArray<Ra::Core::Triangle> TriangleArray;
namespace FancyMeshPlugin
{
FancyMeshComponent::FancyMeshComponent(const std::string& name , bool deformable)
: Ra::Engine::Component( name ) , m_deformable(deformable)
{
}
FancyMeshComponent::~FancyMeshComponent()
{
}
void FancyMeshComponent::initialize()
{
}
void FancyMeshComponent::addMeshRenderObject( const Ra::Core::TriangleMesh& mesh, const std::string& name )
{
setupIO(name);
std::shared_ptr<Ra::Engine::Mesh> displayMesh( new Ra::Engine::Mesh( name ) );
displayMesh->loadGeometry( mesh );
auto renderObject = Ra::Engine::RenderObject::createRenderObject(name, this, Ra::Engine::RenderObjectType::Fancy, displayMesh);
addRenderObject(renderObject);
}
void FancyMeshComponent::handleMeshLoading( const Ra::Asset::GeometryData* data )
{
std::string name( m_name );
name.append( "_" + data->getName() );
std::string roName = name;
roName.append( "_RO" );
std::string meshName = name;
meshName.append( "_Mesh" );
std::string matName = name;
matName.append( "_Mat" );
m_contentName = data->getName();
auto displayMesh = Ra::Core::make_shared<Ra::Engine::Mesh>(meshName/*, Ra::Engine::Mesh::RM_POINTS*/);
Ra::Core::TriangleMesh mesh;
Ra::Core::Transform T = data->getFrame();
Ra::Core::Transform N;
N.matrix() = (T.matrix()).inverse().transpose();
mesh.m_vertices.resize(data->getVerticesSize());
std::transform(data->getVertices().begin(), data->getVertices().end(),
mesh.m_vertices.begin(),
[T](const Ra::Core::Vector3& v){return T * v; });
if(data->hasNormals())
{
mesh.m_normals.resize(data->getVerticesSize());
std::transform(data->getNormals().begin(), data->getNormals().end(),
mesh.m_normals.begin(),
[N](const Ra::Core::Vector3& v){return (N * v).normalized(); });
}
if(data->hasFaces())
{
mesh.m_triangles.resize(data->getFaces().size());
std::transform(data->getFaces().begin(), data->getFaces().end(),
mesh.m_triangles.begin(),
[](const Ra::Core::VectorNui& face){return face.head<3>(); });
}
displayMesh->loadGeometry(mesh);
if (data->hasTangents())
{
Ra::Core::Vector3Array tangents; tangents.resize(data->getTangents().size());
std::copy(data->getTangents().begin(), data->getTangents().end(), tangents.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_TANGENT, tangents );
}
if (data->hasBiTangents())
{
Ra::Core::Vector3Array bitangents; bitangents.resize(data->getBiTangents().size());
std::copy(data->getBiTangents().begin(), data->getBiTangents().end(), bitangents.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_BITANGENT, bitangents );
}
if (data->hasTextureCoordinates())
{
Ra::Core::Vector3Array texcoords; texcoords.resize(data->getTexCoords().size());
std::copy(data->getTexCoords().begin(), data->getTexCoords().end(), texcoords.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_TEXCOORD, texcoords );
}
if (data->hasColors())
{
Ra::Core::Vector4Array colors; colors.resize(data->getColors().size());
std::copy(data->getColors().begin(), data->getColors().end(), colors.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_COLOR, colors );
}
// FIXME(Charly): Should not weights be part of the geometry ?
// mesh->addData( Ra::Engine::Mesh::VERTEX_WEIGHTS, meshData.weights );
std::shared_ptr<Ra::Engine::Material> mat (new Ra::Engine::Material( matName ));
auto m = data->getMaterial();
if ( m.hasDiffuse() ) mat->m_kd = m.m_diffuse;
if ( m.hasSpecular() ) mat->m_ks = m.m_specular;
if ( m.hasShininess() ) mat->m_ns = m.m_shininess;
if ( m.hasOpacity() ) mat->m_alpha = m.m_opacity;
#ifdef LOAD_TEXTURES
if ( m.hasDiffuseTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_DIFFUSE, m.m_texDiffuse );
if ( m.hasSpecularTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SPECULAR, m.m_texSpecular );
if ( m.hasShininessTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SHININESS, m.m_texShininess );
if ( m.hasOpacityTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_ALPHA, m.m_texOpacity );
if ( m.hasNormalTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_NORMAL, m.m_texNormal );
#endif
auto config = Ra::Engine::ShaderConfigurationFactory::getConfiguration("BlinnPhong");
auto ro = Ra::Engine::RenderObject::createRenderObject(roName, this, Ra::Engine::RenderObjectType::Fancy, displayMesh, config, mat);
if ( mat->m_alpha < 1.0 ) ro->setTransparent(true);
setupIO( data->getName());
m_meshIndex = addRenderObject(ro);
}
Ra::Core::Index FancyMeshComponent::getRenderObjectIndex() const
{
return m_meshIndex;
}
const Ra::Core::TriangleMesh& FancyMeshComponent::getMesh() const
{
return getDisplayMesh().getGeometry();
}
void FancyMeshComponent::setDeformable (const bool b)
{
this->m_deformable=b;
}
void FancyMeshComponent::setContentName (const std::string name)
{
this->m_contentName=name;
}
void FancyMeshComponent::setupIO(const std::string& id)
{
auto msg = ComponentMessenger::getInstance();
ComponentMessenger::CallbackTypes<TriangleMesh>::Getter cbOut = std::bind( &FancyMeshComponent::getMeshOutput, this );
msg->registerOutput<TriangleMesh>( getEntity(), this, id, cbOut);
ComponentMessenger::CallbackTypes<TriangleMesh>::ReadWrite cbRw = std::bind( &FancyMeshComponent::getMeshRw, this );
msg->registerReadWrite<TriangleMesh>( getEntity(), this, id, cbRw);
ComponentMessenger::CallbackTypes<Ra::Core::Index>::Getter roOut = std::bind(&FancyMeshComponent::roIndexRead, this);
msg->registerOutput<Ra::Core::Index>(getEntity(), this, id, roOut);
if( m_deformable)
{
ComponentMessenger::CallbackTypes<TriangleMesh>::Setter cbIn = std::bind( &FancyMeshComponent::setMeshInput, this, std::placeholders::_1 );
msg->registerInput<TriangleMesh>( getEntity(), this, id, cbIn);
ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite vRW = std::bind( &FancyMeshComponent::getVerticesRw, this);
msg->registerReadWrite<Ra::Core::Vector3Array>( getEntity(), this, id+"v", vRW);
ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite nRW = std::bind( &FancyMeshComponent::getNormalsRw, this);
msg->registerReadWrite<Ra::Core::Vector3Array>( getEntity(), this, id+"n", nRW);
ComponentMessenger::CallbackTypes<TriangleArray>::ReadWrite tRW = std::bind( &FancyMeshComponent::getTrianglesRw, this);
msg->registerReadWrite<TriangleArray>( getEntity(), this, id+"t", tRW);
}
}
const Ra::Engine::Mesh& FancyMeshComponent::getDisplayMesh() const
{
return *(getRoMgr()->getRenderObject(getRenderObjectIndex())->getMesh());
}
Ra::Engine::Mesh& FancyMeshComponent::getDisplayMesh()
{
return *(getRoMgr()->getRenderObject(getRenderObjectIndex())->getMesh());
}
const Ra::Core::TriangleMesh* FancyMeshComponent::getMeshOutput() const
{
return &(getMesh());
}
Ra::Core::TriangleMesh *FancyMeshComponent::getMeshRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_POSITION );
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_NORMAL );
getDisplayMesh().setDirty( Ra::Engine::Mesh::INDEX);
return &(getDisplayMesh().getGeometry());
}
void FancyMeshComponent::setMeshInput(const TriangleMesh *meshptr)
{
CORE_ASSERT( meshptr, " Input is null");
CORE_ASSERT( m_deformable, "Mesh is not deformable");
Ra::Engine::Mesh& displayMesh = getDisplayMesh();
displayMesh.loadGeometry( *meshptr );
}
Ra::Core::Vector3Array* FancyMeshComponent::getVerticesRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_POSITION);
return &(getDisplayMesh().getGeometry().m_vertices);
}
Ra::Core::Vector3Array* FancyMeshComponent::getNormalsRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_NORMAL);
return &(getDisplayMesh().getGeometry().m_normals);
}
Ra::Core::VectorArray<Ra::Core::Triangle>* FancyMeshComponent::getTrianglesRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::INDEX);
return &(getDisplayMesh().getGeometry().m_triangles);
}
const Ra::Core::Index* FancyMeshComponent::roIndexRead() const
{
return &m_meshIndex;
}
} // namespace FancyMeshPlugin
<commit_msg>Remove faulty code<commit_after>#include <FancyMeshComponent.hpp>
#include <iostream>
#include <Core/String/StringUtils.hpp>
#include <Core/Mesh/MeshUtils.hpp>
#include <Core/Containers/MakeShared.hpp>
#include <Core/Geometry/Normal/Normal.hpp>
#include <Core/File/FileData.hpp>
#include <Core/File/GeometryData.hpp>
#include <Engine/Renderer/RenderObject/RenderObjectManager.hpp>
#include <Engine/Managers/ComponentMessenger/ComponentMessenger.hpp>
#include <Engine/Renderer/Mesh/Mesh.hpp>
#include <Engine/Renderer/RenderTechnique/Material.hpp>
#include <Engine/Renderer/RenderObject/RenderObject.hpp>
#include <Engine/Renderer/RenderObject/RenderObjectTypes.hpp>
#include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgram.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderProgramManager.hpp>
#include <Engine/Renderer/RenderObject/Primitives/DrawPrimitives.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp>
using Ra::Core::TriangleMesh;
using Ra::Engine::ComponentMessenger;
typedef Ra::Core::VectorArray<Ra::Core::Triangle> TriangleArray;
namespace FancyMeshPlugin
{
FancyMeshComponent::FancyMeshComponent(const std::string& name , bool deformable)
: Ra::Engine::Component( name ) , m_deformable(deformable)
{
}
FancyMeshComponent::~FancyMeshComponent()
{
}
void FancyMeshComponent::initialize()
{
}
void FancyMeshComponent::addMeshRenderObject( const Ra::Core::TriangleMesh& mesh, const std::string& name )
{
setupIO(name);
std::shared_ptr<Ra::Engine::Mesh> displayMesh( new Ra::Engine::Mesh( name ) );
displayMesh->loadGeometry( mesh );
auto renderObject = Ra::Engine::RenderObject::createRenderObject(name, this, Ra::Engine::RenderObjectType::Fancy, displayMesh);
addRenderObject(renderObject);
}
void FancyMeshComponent::handleMeshLoading( const Ra::Asset::GeometryData* data )
{
std::string name( m_name );
name.append( "_" + data->getName() );
std::string roName = name;
roName.append( "_RO" );
std::string meshName = name;
meshName.append( "_Mesh" );
std::string matName = name;
matName.append( "_Mat" );
m_contentName = data->getName();
auto displayMesh = Ra::Core::make_shared<Ra::Engine::Mesh>(meshName/*, Ra::Engine::Mesh::RM_POINTS*/);
Ra::Core::TriangleMesh mesh;
Ra::Core::Transform T = data->getFrame();
Ra::Core::Transform N;
N.matrix() = (T.matrix()).inverse().transpose();
for (size_t i = 0; i < data->getVerticesSize(); ++i)
{
mesh.m_vertices.push_back(T * data->getVertices()[i]);
mesh.m_normals.push_back((N * data->getNormals()[i]).normalized());
}
for (const auto& face : data->getFaces())
{
mesh.m_triangles.push_back(face.head<3>());
}
displayMesh->loadGeometry(mesh);
if (data->hasTangents())
{
Ra::Core::Vector3Array tangents; tangents.resize(data->getTangents().size());
std::copy(data->getTangents().begin(), data->getTangents().end(), tangents.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_TANGENT, tangents );
}
if (data->hasBiTangents())
{
Ra::Core::Vector3Array bitangents; bitangents.resize(data->getBiTangents().size());
std::copy(data->getBiTangents().begin(), data->getBiTangents().end(), bitangents.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_BITANGENT, bitangents );
}
if (data->hasTextureCoordinates())
{
Ra::Core::Vector3Array texcoords; texcoords.resize(data->getTexCoords().size());
std::copy(data->getTexCoords().begin(), data->getTexCoords().end(), texcoords.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_TEXCOORD, texcoords );
}
if (data->hasColors())
{
Ra::Core::Vector4Array colors; colors.resize(data->getColors().size());
std::copy(data->getColors().begin(), data->getColors().end(), colors.begin());
displayMesh->addData( Ra::Engine::Mesh::VERTEX_COLOR, colors );
}
// FIXME(Charly): Should not weights be part of the geometry ?
// mesh->addData( Ra::Engine::Mesh::VERTEX_WEIGHTS, meshData.weights );
std::shared_ptr<Ra::Engine::Material> mat (new Ra::Engine::Material( matName ));
auto m = data->getMaterial();
if ( m.hasDiffuse() ) mat->m_kd = m.m_diffuse;
if ( m.hasSpecular() ) mat->m_ks = m.m_specular;
if ( m.hasShininess() ) mat->m_ns = m.m_shininess;
if ( m.hasOpacity() ) mat->m_alpha = m.m_opacity;
#ifdef LOAD_TEXTURES
if ( m.hasDiffuseTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_DIFFUSE, m.m_texDiffuse );
if ( m.hasSpecularTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SPECULAR, m.m_texSpecular );
if ( m.hasShininessTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SHININESS, m.m_texShininess );
if ( m.hasOpacityTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_ALPHA, m.m_texOpacity );
if ( m.hasNormalTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_NORMAL, m.m_texNormal );
#endif
auto config = Ra::Engine::ShaderConfigurationFactory::getConfiguration("BlinnPhong");
auto ro = Ra::Engine::RenderObject::createRenderObject(roName, this, Ra::Engine::RenderObjectType::Fancy, displayMesh, config, mat);
if ( mat->m_alpha < 1.0 ) ro->setTransparent(true);
setupIO( data->getName());
m_meshIndex = addRenderObject(ro);
}
Ra::Core::Index FancyMeshComponent::getRenderObjectIndex() const
{
return m_meshIndex;
}
const Ra::Core::TriangleMesh& FancyMeshComponent::getMesh() const
{
return getDisplayMesh().getGeometry();
}
void FancyMeshComponent::setDeformable (const bool b)
{
this->m_deformable=b;
}
void FancyMeshComponent::setContentName (const std::string name)
{
this->m_contentName=name;
}
void FancyMeshComponent::setupIO(const std::string& id)
{
auto msg = ComponentMessenger::getInstance();
ComponentMessenger::CallbackTypes<TriangleMesh>::Getter cbOut = std::bind( &FancyMeshComponent::getMeshOutput, this );
msg->registerOutput<TriangleMesh>( getEntity(), this, id, cbOut);
ComponentMessenger::CallbackTypes<TriangleMesh>::ReadWrite cbRw = std::bind( &FancyMeshComponent::getMeshRw, this );
msg->registerReadWrite<TriangleMesh>( getEntity(), this, id, cbRw);
ComponentMessenger::CallbackTypes<Ra::Core::Index>::Getter roOut = std::bind(&FancyMeshComponent::roIndexRead, this);
msg->registerOutput<Ra::Core::Index>(getEntity(), this, id, roOut);
if( m_deformable)
{
ComponentMessenger::CallbackTypes<TriangleMesh>::Setter cbIn = std::bind( &FancyMeshComponent::setMeshInput, this, std::placeholders::_1 );
msg->registerInput<TriangleMesh>( getEntity(), this, id, cbIn);
ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite vRW = std::bind( &FancyMeshComponent::getVerticesRw, this);
msg->registerReadWrite<Ra::Core::Vector3Array>( getEntity(), this, id+"v", vRW);
ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite nRW = std::bind( &FancyMeshComponent::getNormalsRw, this);
msg->registerReadWrite<Ra::Core::Vector3Array>( getEntity(), this, id+"n", nRW);
ComponentMessenger::CallbackTypes<TriangleArray>::ReadWrite tRW = std::bind( &FancyMeshComponent::getTrianglesRw, this);
msg->registerReadWrite<TriangleArray>( getEntity(), this, id+"t", tRW);
}
}
const Ra::Engine::Mesh& FancyMeshComponent::getDisplayMesh() const
{
return *(getRoMgr()->getRenderObject(getRenderObjectIndex())->getMesh());
}
Ra::Engine::Mesh& FancyMeshComponent::getDisplayMesh()
{
return *(getRoMgr()->getRenderObject(getRenderObjectIndex())->getMesh());
}
const Ra::Core::TriangleMesh* FancyMeshComponent::getMeshOutput() const
{
return &(getMesh());
}
Ra::Core::TriangleMesh *FancyMeshComponent::getMeshRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_POSITION );
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_NORMAL );
getDisplayMesh().setDirty( Ra::Engine::Mesh::INDEX);
return &(getDisplayMesh().getGeometry());
}
void FancyMeshComponent::setMeshInput(const TriangleMesh *meshptr)
{
CORE_ASSERT( meshptr, " Input is null");
CORE_ASSERT( m_deformable, "Mesh is not deformable");
Ra::Engine::Mesh& displayMesh = getDisplayMesh();
displayMesh.loadGeometry( *meshptr );
}
Ra::Core::Vector3Array* FancyMeshComponent::getVerticesRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_POSITION);
return &(getDisplayMesh().getGeometry().m_vertices);
}
Ra::Core::Vector3Array* FancyMeshComponent::getNormalsRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::VERTEX_NORMAL);
return &(getDisplayMesh().getGeometry().m_normals);
}
Ra::Core::VectorArray<Ra::Core::Triangle>* FancyMeshComponent::getTrianglesRw()
{
getDisplayMesh().setDirty( Ra::Engine::Mesh::INDEX);
return &(getDisplayMesh().getGeometry().m_triangles);
}
const Ra::Core::Index* FancyMeshComponent::roIndexRead() const
{
return &m_meshIndex;
}
} // namespace FancyMeshPlugin
<|endoftext|>
|
<commit_before>#include <cmath>
#include <Eigen/Dense>
#include <gtest/gtest.h>
class ReferenceFilter
{
public:
ReferenceFilter( unsigned inputCount, unsigned outputCount )
: mW( Eigen::MatrixXf::Random( outputCount, inputCount ) )
{}
Eigen::VectorXf operator()( Eigen::VectorXf inputs )
{
return mW * inputs;
}
Eigen::MatrixXf mW;
};
TEST( AdaptiveFilter, LMS )
{
const unsigned kInputCount = 10;
const unsigned kOutputCount = 3;
const unsigned kSampleCount = 100;
const float kMaxAmplitude = 1.0f;
const float kMaxFrequency = 10.0f;
const float kStep = 0.1f * 1.0f / kMaxFrequency;
ReferenceFilter referenceFilter( kInputCount, kOutputCount );
Eigen::VectorXf input( kInputCount );
Eigen::VectorXf A = kMaxAmplitude / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f );
Eigen::VectorXf W = kMaxFrequency / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f );
for ( int i = 0; i < kSampleCount; ++ i )
{
float t = kStep * i;
input = A.array() * ( W.array() * t ).unaryExpr(
std::ptr_fun( std::sinf ) );
}
}
<commit_msg>esn : tests : AdaptiveFilter : LMS : rename variable W -> omega<commit_after>#include <cmath>
#include <Eigen/Dense>
#include <gtest/gtest.h>
class ReferenceFilter
{
public:
ReferenceFilter( unsigned inputCount, unsigned outputCount )
: mW( Eigen::MatrixXf::Random( outputCount, inputCount ) )
{}
Eigen::VectorXf operator()( Eigen::VectorXf inputs )
{
return mW * inputs;
}
Eigen::MatrixXf mW;
};
TEST( AdaptiveFilter, LMS )
{
const unsigned kInputCount = 10;
const unsigned kOutputCount = 3;
const unsigned kSampleCount = 100;
const float kMaxAmplitude = 1.0f;
const float kMaxFrequency = 10.0f;
const float kStep = 0.1f * 1.0f / kMaxFrequency;
ReferenceFilter referenceFilter( kInputCount, kOutputCount );
Eigen::VectorXf input( kInputCount );
Eigen::VectorXf A = kMaxAmplitude / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f );
Eigen::VectorXf omega = kMaxFrequency / 2.0f *
( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f );
for ( int i = 0; i < kSampleCount; ++ i )
{
float t = kStep * i;
input = A.array() * ( omega.array() * t ).unaryExpr(
std::ptr_fun( std::sinf ) );
}
}
<|endoftext|>
|
<commit_before>#include "GameStateHandler.h"
GameStateHandler::GameStateHandler()
{
}
GameStateHandler::~GameStateHandler()
{
}
int GameStateHandler::ShutDown()
{
//Delete the states
while (this->m_stateStack.size())
{
GameState* temp;
temp = this->m_stateStack.back();
delete temp;
temp = nullptr;
this->m_stateStack.pop_back();
}
//Delete the states that should have been popped
while (this->m_statesToRemove.size())
{
GameState* temp;
temp = this->m_statesToRemove.back();
delete temp;
temp = nullptr;
this->m_statesToRemove.pop_back();
}
//Shutdown the NetworkModule that is shared with all GameStates
if (GameState::m_networkModule) //If it is active
{
GameState::m_networkModule->Shutdown();
delete GameState::m_networkModule;
GameState::m_networkModule = nullptr;
}
return 1;
}
int GameStateHandler::Initialize(ComponentHandler * cHandler, Camera * cameraRef, std::string levelPath)
{
int result = 0;
#ifndef START_WITHOUT_MENU
StartState* startState = new StartState();
result = startState->Initialize(this, cHandler, cameraRef);
if (result > 0)
{
//Push it to the gamestate stack/vector
this->m_stateStack.push_back(startState);
}
else
{
//Delete it
delete startState;
startState = nullptr;
}
#else
//Create, Initialize and push a LevelSelectState
LevelSelectState* levelSelect = new LevelSelectState();
result = levelSelect->Initialize(this, cHandler, cameraRef);
//If the initialization was successful
if (result > 0)
{
//Push it to the gamestate stack/vector
//this->PushStateToStack(levelSelect);
if (levelPath.length() < 2)
levelSelect->LoadLevel(std::string("../ResourceLib/AssetFiles/Vertical_level_2.level"));
else
levelSelect->LoadLevel(levelPath);
//Delete it. If it was successful it would have pushed a LevelState to the stack
delete levelSelect;
levelSelect = nullptr;
}
else
{
delete levelSelect;
levelSelect = nullptr;
}
#endif
return result;
////Create, Initialize and push a LevelSelectState
//LevelSelectState* levelSelect = new LevelSelectState();
//result = levelSelect->Initialize(this, cHandler);
////If the initialization was successful
//if (result > 0)
//{
// //Push it to the gamestate stack/vector
// this->m_stateStack.push_back(levelSelect);
//
// levelSelect->LoadLevel(std::string("../ResourceLib/AssetFiles/TestingLevel.level"));
//}
//else
//{
// //Delete it
// delete levelSelect;
// levelSelect = nullptr;
//}
//return result;
////Create, Initialize and push a LevelState
//LevelState* tempState = new LevelState();
//result = tempState->Initialize(this, cHandler);
////If the initialization was successful
//if (result > 0)
//{
// //Push it to the gamestate stack/vector
// this->m_stateStack.push_back(tempState);
//}
//else
//{
// //Delete it
// delete tempState;
// tempState = nullptr;
//}
//return result;
}
int GameStateHandler::Update(float dt, InputHandler * inputHandler)
{
int result = 1;
//Update the active state
if (this->m_stateStack.size())
{
result = this->m_stateStack.back()->Update(dt, inputHandler);
}
//Delete the states
while (this->m_statesToRemove.size())
{
GameState* temp;
temp = this->m_statesToRemove.back();
temp->ShutDown();
delete temp;
temp = nullptr;
this->m_statesToRemove.pop_back();
}
return result;
}
int GameStateHandler::PushStateToStack(GameState * state)
{
int result = 1;
this->m_stateStack.back()->LeaveState();
this->m_stateStack.push_back(state);
this->m_stateStack.back()->EnterState();
return 1;
}
GameState * GameStateHandler::PopStateFromStack()
{
GameState* result = nullptr;
this->m_stateStack.back()->LeaveState();
result = this->m_stateStack.back();
this->m_stateStack.pop_back();
//Check if it wants to be manually managed after popping
if (!result->GetManualRemoval())
{
this->m_statesToRemove.push_back(result);
}
this->m_stateStack.back()->EnterState();
return result;
}
<commit_msg>UPDATE Changed back to tutorial level when hosting<commit_after>#include "GameStateHandler.h"
GameStateHandler::GameStateHandler()
{
}
GameStateHandler::~GameStateHandler()
{
}
int GameStateHandler::ShutDown()
{
//Delete the states
while (this->m_stateStack.size())
{
GameState* temp;
temp = this->m_stateStack.back();
delete temp;
temp = nullptr;
this->m_stateStack.pop_back();
}
//Delete the states that should have been popped
while (this->m_statesToRemove.size())
{
GameState* temp;
temp = this->m_statesToRemove.back();
delete temp;
temp = nullptr;
this->m_statesToRemove.pop_back();
}
//Shutdown the NetworkModule that is shared with all GameStates
if (GameState::m_networkModule) //If it is active
{
GameState::m_networkModule->Shutdown();
delete GameState::m_networkModule;
GameState::m_networkModule = nullptr;
}
return 1;
}
int GameStateHandler::Initialize(ComponentHandler * cHandler, Camera * cameraRef, std::string levelPath)
{
int result = 0;
#ifndef START_WITHOUT_MENU
StartState* startState = new StartState();
result = startState->Initialize(this, cHandler, cameraRef);
if (result > 0)
{
//Push it to the gamestate stack/vector
this->m_stateStack.push_back(startState);
}
else
{
//Delete it
delete startState;
startState = nullptr;
}
#else
//Create, Initialize and push a LevelSelectState
LevelSelectState* levelSelect = new LevelSelectState();
result = levelSelect->Initialize(this, cHandler, cameraRef);
//If the initialization was successful
if (result > 0)
{
//Push it to the gamestate stack/vector
//this->PushStateToStack(levelSelect);
if (levelPath.length() < 2)
levelSelect->LoadLevel(std::string("../ResourceLib/AssetFiles/TutorialLevel.level"));
else
levelSelect->LoadLevel(levelPath);
//Delete it. If it was successful it would have pushed a LevelState to the stack
delete levelSelect;
levelSelect = nullptr;
}
else
{
delete levelSelect;
levelSelect = nullptr;
}
#endif
return result;
////Create, Initialize and push a LevelSelectState
//LevelSelectState* levelSelect = new LevelSelectState();
//result = levelSelect->Initialize(this, cHandler);
////If the initialization was successful
//if (result > 0)
//{
// //Push it to the gamestate stack/vector
// this->m_stateStack.push_back(levelSelect);
//
// levelSelect->LoadLevel(std::string("../ResourceLib/AssetFiles/TestingLevel.level"));
//}
//else
//{
// //Delete it
// delete levelSelect;
// levelSelect = nullptr;
//}
//return result;
////Create, Initialize and push a LevelState
//LevelState* tempState = new LevelState();
//result = tempState->Initialize(this, cHandler);
////If the initialization was successful
//if (result > 0)
//{
// //Push it to the gamestate stack/vector
// this->m_stateStack.push_back(tempState);
//}
//else
//{
// //Delete it
// delete tempState;
// tempState = nullptr;
//}
//return result;
}
int GameStateHandler::Update(float dt, InputHandler * inputHandler)
{
int result = 1;
//Update the active state
if (this->m_stateStack.size())
{
result = this->m_stateStack.back()->Update(dt, inputHandler);
}
//Delete the states
while (this->m_statesToRemove.size())
{
GameState* temp;
temp = this->m_statesToRemove.back();
temp->ShutDown();
delete temp;
temp = nullptr;
this->m_statesToRemove.pop_back();
}
return result;
}
int GameStateHandler::PushStateToStack(GameState * state)
{
int result = 1;
this->m_stateStack.back()->LeaveState();
this->m_stateStack.push_back(state);
this->m_stateStack.back()->EnterState();
return 1;
}
GameState * GameStateHandler::PopStateFromStack()
{
GameState* result = nullptr;
this->m_stateStack.back()->LeaveState();
result = this->m_stateStack.back();
this->m_stateStack.pop_back();
//Check if it wants to be manually managed after popping
if (!result->GetManualRemoval())
{
this->m_statesToRemove.push_back(result);
}
this->m_stateStack.back()->EnterState();
return result;
}
<|endoftext|>
|
<commit_before>// -*- mode:C++; tab-width:3; c-basic-offset:4; indent-tabs-mode:nil -*-
//Copyright: Universidad Carlos III de Madrid (C) 2016
//Authors: jgvictores, raulfdzbis, smorante
#include "CgdaPaintFitnessFunction.hpp"
namespace teo
{
/************************************************************************/
//double target[10]={0, 10, 20, 30, 40, 50, 60, 70, 80, 100};
double Const_target[17]={0, 6.25, 12.5, 18.75, 25, 31.25, 37.5
, 43.75, 50, 56.25, 62.5, 68.75, 75, 81.25, 87.5, 93.75, 100};
void CgdaPaintFitnessFunction::trajectoryExecution(int NumberPoints, vector<double> result_trajectory){
//std::cout<<"I have entered Execution"<<std::endl;
const int rows=4; //setting wall parameters
const int cols=4;
int sqPainted [rows*cols] = { }; //setting number of changed square as cero
// // reset square color
for(int i=0; i<(rows*cols); i++){
stringstream rr;
rr << "square" << i;
_wall->GetLink(rr.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.5, 0.5, 0.5));
rr.str("");
}
//Move robot
for(int t=0;t<=NumberPoints;t++) {
std::cout<<"Time interval"<<t<<std::endl;
std::vector<dReal> dEncRaw(probot->GetDOF()); // NUM_MOTORS
dEncRaw[0+4] = result_trajectory[t*3+0]*M_PI/180.0; // simple
dEncRaw[1+4] = -result_trajectory[t*3+1]*M_PI/180.0; // simple
dEncRaw[3+4] = result_trajectory[t*3+2]*M_PI/180.0; // simple
dEncRaw[4+4] = 45*M_PI/180.0;
probot->SetJointValues(dEncRaw);
pcontrol->SetDesired(dEncRaw); // This function "resets" physics
while(!pcontrol->IsDone()) {
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
penv->StepSimulation(0.0001); // StepSimulation must be given in seconds
//std::cout<<"W8ing"<<std::endl;
T_base_object = _objPtr->GetTransform();
double T_base_object_x = T_base_object.trans.x;
double T_base_object_y = T_base_object.trans.y;
double T_base_object_z = T_base_object.trans.z;
//change square color in function of dist (end-effector,square)
for(int i=0; i<(rows*cols); i++){
stringstream ss;
ss << "square" << i;
Transform pos_square = _wall->GetLink(ss.str())->GetGeometry(0)->GetTransform();
double pos_square_x = pos_square.trans.x;
double pos_square_y = pos_square.trans.y;
double pos_square_z = pos_square.trans.z;
double dist = sqrt(pow(T_base_object_x-pos_square_x,2)
+ pow(T_base_object_y-pos_square_y,2)
+ pow(T_base_object_z-pos_square_z,2) );
if (dist < 0.13){
_wall->GetLink(ss.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.0, 0.0, 1.0));
sqPainted[i]=1;
//std::cout<<"I have painted a happy little tree "<<std::endl;
}
ss.str("");
}
sleep(1);
}
}
double CgdaPaintFitnessFunction::getCustomFitness(vector <double> genPoints){
const int rows=4; //setting wall parameters
const int cols=4;
std::vector<double> percentage;
int sqPainted [rows*cols] = { }; //setting number of changed square as cero
// // reset square color
for(int i=0; i<(rows*cols); i++){
stringstream rr;
rr << "square" << i;
_wall->GetLink(rr.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.5, 0.5, 0.5));
rr.str("");
}
genPoints[0]=47.546;
genPoints[1]=81.3215;
genPoints[2]=42.7629;
for(int t=0;t<=*pIter;t++) {
std::vector<dReal> dEncRaw(probot->GetDOF()); // NUM_MOTORS
if (t<*pIter){
// cout << "< t: " << t << " *pIter: " << *pIter << std::endl;
// cout << "pF0: " << pFresults->operator [](t*3+0) << std::endl;
// cout << "pF1: " << pFresults->operator [](t*3+1) << std::endl;
// cout << "pF2: " << pFresults->operator [](t*3+2) << std::endl;
dEncRaw[0+4] = 1*(pFresults->operator [](t*3+0))*M_PI/180.0; // simple
dEncRaw[1+4] = -1*(pFresults->operator [](t*3+1))*M_PI/180.0; // simple
dEncRaw[3+4] = 1*(pFresults->operator [](t*3+2))*M_PI/180.0; // simple
}
else if (t==*pIter){
// cout << "== t: " << t << " *pIter: " << *pIter << std::endl;
// cout << "gp0: " << genPoints[0] << std::endl;
// cout << "gp1: " << genPoints[1] << std::endl;
// cout << "gp2: " << genPoints[2] << std::endl;
dEncRaw[0+4] = genPoints[0]*M_PI/180.0; // simple
dEncRaw[1+4] = -genPoints[1]*M_PI/180.0; // simple
dEncRaw[3+4] = genPoints[2]*M_PI/180.0; // simple
}
else{cerr << "ERROR IN pIter or t" << std::endl;}
dEncRaw[4+4] = 45*M_PI/180.0;
probot->SetJointValues(dEncRaw);
pcontrol->SetDesired(dEncRaw); // This function "resets" physics
while(!pcontrol->IsDone()) {
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
penv->StepSimulation(0.0001); // StepSimulation must be given in seconds
T_base_object = _objPtr->GetTransform();
double T_base_object_x = T_base_object.trans.x;
double T_base_object_y = T_base_object.trans.y;
double T_base_object_z = T_base_object.trans.z;
//change square color in function of dist (end-effector,square)
for(int i=0; i<(rows*cols); i++){
stringstream ss;
ss << "square" << i;
Transform pos_square = _wall->GetLink(ss.str())->GetGeometry(0)->GetTransform();
double pos_square_x = pos_square.trans.x;
double pos_square_y = pos_square.trans.y;
double pos_square_z = pos_square.trans.z;
double dist = sqrt(pow(T_base_object_x-pos_square_x,2)
+ pow(T_base_object_y-pos_square_y,2)
+ pow(T_base_object_z-pos_square_z,2) );
if (dist < 0.13){
_wall->GetLink(ss.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.0, 0.0, 1.0));
sqPainted[i]=1;
//std::cout<<"I have painted a happy little tree "<<std::endl;
}
ss.str("");
}
//Fitness = percentage of wall painted
std::valarray<int> myvalarray (sqPainted,rows*cols);
percentage.push_back(( (float)myvalarray.sum()/(rows*cols))*100);
} //cierre bucle trayectoria completa
//Output to file
std::ofstream myfile2;
myfile2.open("PercentageWall.txt", std::ios_base::app);
if (myfile2.is_open()){
myfile2<<percentage[*pIter]<<" ";
}
// calculate fit /percentage of painted wall
//double fit = abs(percentage-target[*pIter]);
//The fit is obtained using the DTW algorithm.
//The feature is the percentage of wall painted
CgdaRecognition* featureTrajectories;
featureTrajectories = new DtwCgdaRecognition;
//Current Generalized trajectory
std::vector < std::vector < double > > current_target;
for(int i=0; i<=*pIter;i++){
current_target.push_back({Const_target[i]});
}
featureTrajectories->setGeneralized(current_target);
//Get the discrepancy value between what we have and what we want
//Init feature attemp vector
std::vector< std::vector< double > > attempVectforSimpleDiscrepancy;
for(int t=0;t<percentage.size();t++)
{
attempVectforSimpleDiscrepancy.push_back({percentage[t]});
//std::cout<<std::endl<<"ATTEMP TRAJECTORY ::::"<<t<<" : "<<percentage[t]<<std::endl;
}
//Console output.
for(int i=0; i<attempVectforSimpleDiscrepancy[0].size(); i++){ //For each vector of characteristics(each column). In this case should be 1.
std::cout<<std::endl<<std::endl;
for(int j=0; j<attempVectforSimpleDiscrepancy.size(); j++){ //For each trajectory step
std::cout<<"trajectory step "<<j<<" ==> " <<attempVectforSimpleDiscrepancy[j][i]<<std::endl;
}
}
double fit;
featureTrajectories->compare(attempVectforSimpleDiscrepancy,fit);
// cout << std::endl << " percentage: "<< percentage[0] << ","<< percentage[1] << ","<< percentage[2] << ","<< percentage[3] << ","<< percentage[4];
cout << std::endl << " fit: " << fit << " ";
return fit;
}
/************************************************************************/
void CgdaPaintFitnessFunction::registerParameters(StateP state) {
state->getRegistry()->registerEntry("function", (voidP) (new uint(1)), ECF::UINT);
}
/************************************************************************/
bool CgdaPaintFitnessFunction::initialize(StateP state) {
voidP sptr = state->getRegistry()->getEntry("function"); // get parameter value
stringstream msg;
_objPtr = penv->GetKinBody("object");
_wall = penv->GetKinBody("wall");
if(!_objPtr) {
fprintf(stderr,"error: object \"object\" does not exist.\n");
} else printf("sucess: object \"object\" exists.\n");
if(!_wall) {
fprintf(stderr,"error: object \"wall\" does not exist.\n");
} else printf("sucess: object \"wall\" exists.\n");
usleep(1.0 * 1000000.0);
return true;
}
/************************************************************************/
FitnessP CgdaPaintFitnessFunction::evaluate(IndividualP individual) {
// evaluation creates a new fitness object using a smart pointer
// in our case, we try to minimize the function value, so we use FitnessMin fitness (for minimization problems)
FitnessP fitness (new FitnessMin);
// we define FloatingPoint as the only genotype (in the configuration file)
FloatingPoint::FloatingPoint* gen = (FloatingPoint::FloatingPoint*) individual->getGenotype().get();
// we implement the fitness function 'as is', without any translation
// the number of variables is read from the genotype itself (size of 'realValue' vactor)
double value =0;
value= getCustomFitness(gen->realValue);
fitness->setValue(value);
return fitness;
}
/************************************************************************/
} // namespace teo
<commit_msg>Starting with IET to YarpOpenrave<commit_after>// -*- mode:C++; tab-width:3; c-basic-offset:4; indent-tabs-mode:nil -*-
//Copyright: Universidad Carlos III de Madrid (C) 2016
//Authors: jgvictores, raulfdzbis, smorante
#include "CgdaPaintFitnessFunction.hpp"
namespace teo
{
/************************************************************************/
//double target[10]={0, 10, 20, 30, 40, 50, 60, 70, 80, 100};
double Const_target[17]={0, 6.25, 12.5, 18.75, 25, 31.25, 37.5
, 43.75, 50, 56.25, 62.5, 68.75, 75, 81.25, 87.5, 93.75, 100};
void CgdaPaintFitnessFunction::trajectoryExecution(int NumberPoints, vector<double> result_trajectory){
//std::cout<<"I have entered Execution"<<std::endl;
const int rows=4; //setting wall parameters
const int cols=4;
int sqPainted [rows*cols] = { }; //setting number of changed square as cero
// // reset square color
for(int i=0; i<(rows*cols); i++){
stringstream rr;
rr << "square" << i;
_wall->GetLink(rr.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.5, 0.5, 0.5));
rr.str("");
}
//Move robot
for(int t=0;t<=NumberPoints;t++) {
std::cout<<"Time interval"<<t<<std::endl;
std::vector<dReal> dEncRaw(probot->GetDOF()); // NUM_MOTORS
dEncRaw[0+4] = result_trajectory[t*3+0]*M_PI/180.0; // simple
dEncRaw[1+4] = -result_trajectory[t*3+1]*M_PI/180.0; // simple
dEncRaw[3+4] = result_trajectory[t*3+2]*M_PI/180.0; // simple
dEncRaw[4+4] = 45*M_PI/180.0;
probot->SetJointValues(dEncRaw);
pcontrol->SetDesired(dEncRaw); // This function "resets" physics
while(!pcontrol->IsDone()) {
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
penv->StepSimulation(0.0001); // StepSimulation must be given in seconds
//std::cout<<"W8ing"<<std::endl;
T_base_object = _objPtr->GetTransform();
double T_base_object_x = T_base_object.trans.x;
double T_base_object_y = T_base_object.trans.y;
double T_base_object_z = T_base_object.trans.z;
//change square color in function of dist (end-effector,square)
for(int i=0; i<(rows*cols); i++){
stringstream ss;
ss << "square" << i;
Transform pos_square = _wall->GetLink(ss.str())->GetGeometry(0)->GetTransform();
double pos_square_x = pos_square.trans.x;
double pos_square_y = pos_square.trans.y;
double pos_square_z = pos_square.trans.z;
double dist = sqrt(pow(T_base_object_x-pos_square_x,2)
+ pow(T_base_object_y-pos_square_y,2)
+ pow(T_base_object_z-pos_square_z,2) );
if (dist < 0.13){
_wall->GetLink(ss.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.0, 0.0, 1.0));
sqPainted[i]=1;
//std::cout<<"I have painted a happy little tree "<<std::endl;
}
ss.str("");
}
sleep(1);
}
}
double CgdaPaintFitnessFunction::getCustomFitness(vector <double> genPoints){
const int rows=4; //setting wall parameters
const int cols=4;
std::vector<double> percentage;
int sqPainted [rows*cols] = { }; //setting number of changed square as cero
// // reset square color
for(int i=0; i<(rows*cols); i++){
stringstream rr;
rr << "square" << i;
_wall->GetLink(rr.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.5, 0.5, 0.5));
rr.str("");
}
for(int t=0;t<=*pIter;t++) {
std::vector<dReal> dEncRaw(probot->GetDOF()); // NUM_MOTORS
if (t<*pIter){
// cout << "< t: " << t << " *pIter: " << *pIter << std::endl;
// cout << "pF0: " << pFresults->operator [](t*3+0) << std::endl;
// cout << "pF1: " << pFresults->operator [](t*3+1) << std::endl;
// cout << "pF2: " << pFresults->operator [](t*3+2) << std::endl;
dEncRaw[0+4] = 1*(pFresults->operator [](t*3+0)); // simple
dEncRaw[1+4] = -1*(pFresults->operator [](t*3+1)); // simple
dEncRaw[3+4] = 1*(pFresults->operator [](t*3+2)); // simple
}
else if (t==*pIter){
// cout << "== t: " << t << " *pIter: " << *pIter << std::endl;
// cout << "gp0: " << genPoints[0] << std::endl;
// cout << "gp1: " << genPoints[1] << std::endl;
// cout << "gp2: " << genPoints[2] << std::endl;
dEncRaw[0+4] = genPoints[0]; // simple
dEncRaw[1+4] = -genPoints[1]; // simple
dEncRaw[3+4] = genPoints[2]; // simple
}
else{cerr << "ERROR IN pIter or t" << std::endl;}
dEncRaw[4+4] = 45;
probot->SetJointValues(dEncRaw);
pcontrol->SetDesired(dEncRaw); // This function "resets" physics
while(!pcontrol->IsDone()) {
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
penv->StepSimulation(0.0001); // StepSimulation must be given in seconds
T_base_object = _objPtr->GetTransform();
double T_base_object_x = T_base_object.trans.x;
double T_base_object_y = T_base_object.trans.y;
double T_base_object_z = T_base_object.trans.z;
//change square color in function of dist (end-effector,square)
for(int i=0; i<(rows*cols); i++){
stringstream ss;
ss << "square" << i;
Transform pos_square = _wall->GetLink(ss.str())->GetGeometry(0)->GetTransform();
double pos_square_x = pos_square.trans.x;
double pos_square_y = pos_square.trans.y;
double pos_square_z = pos_square.trans.z;
double dist = sqrt(pow(T_base_object_x-pos_square_x,2)
+ pow(T_base_object_y-pos_square_y,2)
+ pow(T_base_object_z-pos_square_z,2) );
if (dist < 0.13){
_wall->GetLink(ss.str())->GetGeometry(0)->SetDiffuseColor(RaveVector<float>(0.0, 0.0, 1.0));
sqPainted[i]=1;
//std::cout<<"I have painted a happy little tree "<<std::endl;
}
ss.str("");
}
//Fitness = percentage of wall painted
std::valarray<int> myvalarray (sqPainted,rows*cols);
percentage.push_back(( (float)myvalarray.sum()/(rows*cols))*100);
} //cierre bucle trayectoria completa
//Output to file
std::ofstream myfile2;
myfile2.open("PercentageWall.txt", std::ios_base::app);
if (myfile2.is_open()){
myfile2<<percentage[*pIter]<<" ";
}
// calculate fit /percentage of painted wall
//double fit = abs(percentage-target[*pIter]);
//The fit is obtained using the DTW algorithm.
//The feature is the percentage of wall painted
CgdaRecognition* featureTrajectories;
featureTrajectories = new DtwCgdaRecognition;
//Current Generalized trajectory
std::vector < std::vector < double > > current_target;
for(int i=0; i<=*pIter;i++){
current_target.push_back({Const_target[i]});
}
featureTrajectories->setGeneralized(current_target);
//Get the discrepancy value between what we have and what we want
//Init feature attemp vector
std::vector< std::vector< double > > attempVectforSimpleDiscrepancy;
for(int t=0;t<percentage.size();t++)
{
attempVectforSimpleDiscrepancy.push_back({percentage[t]});
//std::cout<<std::endl<<"ATTEMP TRAJECTORY ::::"<<t<<" : "<<percentage[t]<<std::endl;
}
//Console output.
for(int i=0; i<attempVectforSimpleDiscrepancy[0].size(); i++){ //For each vector of characteristics(each column). In this case should be 1.
std::cout<<std::endl<<std::endl;
for(int j=0; j<attempVectforSimpleDiscrepancy.size(); j++){ //For each trajectory step
std::cout<<"trajectory step "<<j<<" ==> " <<attempVectforSimpleDiscrepancy[j][i]<<std::endl;
}
}
double fit;
featureTrajectories->compare(attempVectforSimpleDiscrepancy,fit);
// cout << std::endl << " percentage: "<< percentage[0] << ","<< percentage[1] << ","<< percentage[2] << ","<< percentage[3] << ","<< percentage[4];
cout << std::endl << " fit: " << fit << " ";
return fit;
}
/************************************************************************/
void CgdaPaintFitnessFunction::registerParameters(StateP state) {
state->getRegistry()->registerEntry("function", (voidP) (new uint(1)), ECF::UINT);
}
/************************************************************************/
bool CgdaPaintFitnessFunction::initialize(StateP state) {
voidP sptr = state->getRegistry()->getEntry("function"); // get parameter value
stringstream msg;
_objPtr = penv->GetKinBody("object");
_wall = penv->GetKinBody("wall");
if(!_objPtr) {
fprintf(stderr,"error: object \"object\" does not exist.\n");
} else printf("sucess: object \"object\" exists.\n");
if(!_wall) {
fprintf(stderr,"error: object \"wall\" does not exist.\n");
} else printf("sucess: object \"wall\" exists.\n");
usleep(1.0 * 1000000.0);
return true;
}
/************************************************************************/
FitnessP CgdaPaintFitnessFunction::evaluate(IndividualP individual) {
// evaluation creates a new fitness object using a smart pointer
// in our case, we try to minimize the function value, so we use FitnessMin fitness (for minimization problems)
FitnessP fitness (new FitnessMin);
// we define FloatingPoint as the only genotype (in the configuration file)
FloatingPoint::FloatingPoint* gen = (FloatingPoint::FloatingPoint*) individual->getGenotype().get();
// we implement the fitness function 'as is', without any translation
// the number of variables is read from the genotype itself (size of 'realValue' vactor)
double value =0;
value= getCustomFitness(gen->realValue);
fitness->setValue(value);
return fitness;
}
/************************************************************************/
} // namespace teo
<|endoftext|>
|
<commit_before>/**
* @file uart.cpp
*
* @brief Contains uart access functionality
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
#include "utils/ringbuffer.h"
/**
* @brief Used to access uart0
*
* On atmega2561:<b>
* Pin2: RXD0 <b>
* Pin3: TXD0
*/
Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
/**
* @brief Used to access uart1
*
* On atmega2561:<b>
* Pin27: RXD0 <b>
* Pin28: TXD0
*/
Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
/**
* @brief Calculates the clock scale needed to run uart at the specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*/
uint16_t Uart::BaudScale(uint16_t baudrate) { (((F_CPU / (baudrate * 16UL))) - 1); }
/**
* @brief Initializes uart with specified baud rate.
*
* @param ubrr
* @param ucsra
* @param ucsrb
* @param ucsrc
* @param udr
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
*
* @endcode
*/
Uart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr)
{
_ubrr = ubrr;
_ucsra = ucsra;
_ucsrb = ucsrb;
_ucsrc = ucsrc;
_udr = udr;
}
/**
* @brief Initializes uart with specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
void Uart::Init(uint16_t baudrate)
{
// initializing uart to baud rate of 9600
*_ubrr = BaudScale(baudrate);
// setting 8 data bits, 1 stop bit, no parity
*_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01));
// enabling receiver and transmitter
*_ucsrb = ((1 << RXEN0) | (1 << TXEN0));
// enabling uart interrupts
*_ucsrb |= ((1 << RXCIE0) | (1 << TXCIE0));
}
/**
* @brief Pushes byte to rx buffer. If buffer is full, nothing happens.
*
* @param byte Byte to push to buffer.
*/
void _PushRx(Uart *uart, char byte) { uart->_rx_buffer.Push(byte); }
ISR(USART0_RX_vect)
{
char rxbyte;
// echo rx to tx
rxbyte = UDR0;
UDR0 = rxbyte;
// pushing byte to rxbuff
_PushRx(&uart0, rxbyte);
}
<commit_msg>Fixed uart bug caused by baudscale missing return<commit_after>/**
* @file uart.cpp
*
* @brief Contains uart access functionality
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
#include "utils/ringbuffer.h"
/**
* @brief Used to access uart0
*
* On atmega2561:<b>
* Pin2: RXD0 <b>
* Pin3: TXD0
*/
Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
/**
* @brief Used to access uart1
*
* On atmega2561:<b>
* Pin27: RXD0 <b>
* Pin28: TXD0
*/
Uart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
/**
* @brief Calculates the clock scale needed to run uart at the specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*/
uint16_t Uart::BaudScale(uint16_t baudrate) { return (((F_CPU / (baudrate * 16UL))) - 1); }
/**
* @brief Initializes uart with specified baud rate.
*
* @param ubrr
* @param ucsra
* @param ucsrb
* @param ucsrc
* @param udr
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
*
* @endcode
*/
Uart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr)
{
_ubrr = ubrr;
_ucsra = ucsra;
_ucsrb = ucsrb;
_ucsrc = ucsrc;
_udr = udr;
}
/**
* @brief Initializes uart with specified baud rate.
*
* @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.
* If not specified 9600 is used.
*
* Example usage:
* @code
*
* Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
* uart0.Init(9600);
*
* @endcode
*/
void Uart::Init(uint16_t baudrate)
{
// initializing uart to specified baud rate
*_ubrr = BaudScale(baudrate);
// setting 8 data bits, 1 stop bit, no parity
*_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01));
// enabling receiver and transmitter
*_ucsrb = ((1 << RXEN0) | (1 << TXEN0));
// enabling uart interrupts
*_ucsrb |= ((1 << RXCIE0) | (1 << TXCIE0));
}
/**
* @brief Pushes byte to rx buffer. If buffer is full, nothing happens.
*
* @param byte Byte to push to buffer.
*/
void _PushRx(Uart *uart, char byte) { uart->_rx_buffer.Push(byte); }
ISR(USART0_RX_vect)
{
char rxbyte;
// echo rx to tx
rxbyte = UDR0;
UDR0 = rxbyte;
// pushing byte to rxbuff
_PushRx(&uart0, rxbyte);
}
<|endoftext|>
|
<commit_before>
#include <string.h>
#include <math.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#include <windows.h>
#include "GUI.h"
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace Microsoft::Win32;
using namespace ExtIO_RedPitaya_TRX;
//---------------------------------------------------------------------------
#define EXTIO_API __declspec(dllexport) __stdcall
#define TCP_PORT 1001
#define TCP_ADDR "192.168.1.100"
SOCKET gSock[2] = {-1, -1};
char gBuffer[8192];
UInt32 gRate = 100000;
Int32 gCorr = 0;
UInt32 gFreq = 600000;
UInt32 gFreqMin = 100000;
UInt32 gFreqMax = 60000000;
bool gInitHW = false;
bool gExitThread = false;
bool gThreadRunning = false;
//---------------------------------------------------------------------------
ref class ManagedGlobals
{
public:
static GUI ^gGUI = nullptr;
static RegistryKey ^gKey = nullptr;
};
//---------------------------------------------------------------------------
void (*ExtIOCallback)(int, int, float, void *) = 0;
static void SetRate(UInt32);
static void UpdateRate(UInt32);
static void SetCorr(Int32);
//---------------------------------------------------------------------------
DWORD WINAPI GeneratorThreadProc(__in LPVOID lpParameter)
{
unsigned long size = 0;
while(!gExitThread)
{
SleepEx(1, FALSE);
if(gExitThread) break;
ioctlsocket(gSock[1], FIONREAD, &size);
while(size >= 8192)
{
recv(gSock[1], gBuffer, 8192, 0);
if(ExtIOCallback) (*ExtIOCallback)(1024, 0, 0.0, gBuffer);
ioctlsocket(gSock[1], FIONREAD, &size);
}
}
gExitThread = false;
gThreadRunning = false;
return 0;
}
//---------------------------------------------------------------------------
static void StopThread()
{
if(gThreadRunning)
{
gExitThread = true;
while(gThreadRunning)
{
SleepEx(10, FALSE);
}
}
}
//---------------------------------------------------------------------------
static void StartThread()
{
gExitThread = false;
gThreadRunning = true;
CreateThread(NULL, (SIZE_T)(64 * 1024), GeneratorThreadProc, NULL, 0, NULL);
}
//---------------------------------------------------------------------------
extern "C" int EXTIO_API SetHWLO(long LOfreq);
//---------------------------------------------------------------------------
extern "C"
bool EXTIO_API InitHW(char *name, char *model, int &type)
{
String ^addrString;
UInt32 rateIndex = 2;
Int32 corr = 0;
type = 7;
strcpy(name, "Red Pitaya SDR TRX");
strcpy(model, "");
if(!gInitHW)
{
ManagedGlobals::gKey = Registry::CurrentUser->OpenSubKey("Software\\ExtIO_RedPitaya_TRX", true);
if(!ManagedGlobals::gKey)
{
ManagedGlobals::gKey = Registry::CurrentUser->CreateSubKey("Software\\ExtIO_RedPitaya_TRX");
ManagedGlobals::gKey->SetValue("IP Address", TCP_ADDR);
ManagedGlobals::gKey->SetValue("Sample Rate", rateIndex);
ManagedGlobals::gKey->SetValue("Freq. Corr.", corr);
}
ManagedGlobals::gGUI = gcnew GUI;
addrString = ManagedGlobals::gKey->GetValue("IP Address")->ToString();
ManagedGlobals::gGUI->addrValue->Text = addrString;
rateIndex = Convert::ToUInt32(ManagedGlobals::gKey->GetValue("Sample Rate", 1));
if(rateIndex < 0 || rateIndex > 5) rateIndex = 2;
ManagedGlobals::gGUI->rateValue->SelectedIndex = rateIndex;
ManagedGlobals::gGUI->rateCallback = UpdateRate;
corr = Convert::ToInt32(ManagedGlobals::gKey->GetValue("Freq. Corr.", 0));
if(corr < -100 || corr > 100) corr = 0;
ManagedGlobals::gGUI->corrValue->Value = corr;
ManagedGlobals::gGUI->corrCallback = SetCorr;
SetRate(rateIndex);
SetCorr(corr);
gInitHW = true;
}
return gInitHW;
}
//---------------------------------------------------------------------------
extern "C"
bool EXTIO_API OpenHW()
{
return gInitHW;
}
//---------------------------------------------------------------------------
extern "C"
int EXTIO_API StartHW(long LOfreq)
{
WSADATA wsaData;
struct sockaddr_in addr;
String ^addrString;
char *buffer;
UInt32 command;
int i;
if(!gInitHW) return 0;
WSAStartup(MAKEWORD(2, 2), &wsaData);
addrString = ManagedGlobals::gGUI->addrValue->Text;
ManagedGlobals::gKey->SetValue("IP Address", addrString);
buffer = (char*)Marshal::StringToHGlobalAnsi(addrString).ToPointer();
for(i = 0; i < 2; ++i)
{
gSock[i] = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(buffer);
addr.sin_port = htons(TCP_PORT);
connect(gSock[i], (struct sockaddr *)&addr, sizeof(addr));
command = i;
send(gSock[i], (char *)&command, 4, 0);
}
Marshal::FreeHGlobal(IntPtr(buffer));
StopThread();
gFreq = LOfreq;
SetRate(ManagedGlobals::gGUI->rateValue->SelectedIndex);
StartThread();
return 1024;
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API StopHW()
{
StopThread();
closesocket(gSock[1]);
closesocket(gSock[0]);
gSock[1] = -1;
gSock[0] = -1;
WSACleanup();
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API CloseHW()
{
gInitHW = false;
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API SetCallback(void (*callback)(int, int, float, void *))
{
ExtIOCallback = callback;
}
//---------------------------------------------------------------------------
extern "C"
int EXTIO_API SetHWLO(long LOfreq)
{
int rc = 0;
UInt32 buffer = 0;
gFreq = LOfreq;
// check limits
if(gFreq < gFreqMin)
{
gFreq = gFreqMin;
rc = -gFreqMin;
}
else if(gFreq > gFreqMax)
{
gFreq = gFreqMax;
rc = gFreqMax;
}
if(gFreq != LOfreq && ExtIOCallback) (*ExtIOCallback)(-1, 101, 0.0, 0);
buffer = (long)floor(gFreq*(1.0 + gCorr*1.0e-6) + 0.5);
if(gSock[0] > 0) send(gSock[0], (char *)&buffer, 4, 0);
return rc;
}
//---------------------------------------------------------------------------
static void SetRate(UInt32 rateIndex)
{
switch(rateIndex)
{
case 0: gRate = 20000; gFreqMin = 10000; break;
case 1: gRate = 50000; gFreqMin = 25000; break;
case 2: gRate = 100000; gFreqMin = 50000; break;
case 3: gRate = 250000; gFreqMin = 125000; break;
case 4: gRate = 500000; gFreqMin = 250000; break;
case 5: gRate = 1250000; gFreqMin = 625000; break;
}
if(ManagedGlobals::gKey) ManagedGlobals::gKey->SetValue("Sample Rate", rateIndex);
rateIndex |= 1<<28;
if(gSock[0] > 0) send(gSock[0], (char *)&rateIndex, 4, 0);
SetHWLO(gFreq);
}
//---------------------------------------------------------------------------
static void UpdateRate(UInt32 rateIndex)
{
SetRate(rateIndex);
if(ExtIOCallback) (*ExtIOCallback)(-1, 100, 0.0, 0);
}
//---------------------------------------------------------------------------
static void SetCorr(Int32 corr)
{
gCorr = corr;
if(ManagedGlobals::gKey) ManagedGlobals::gKey->SetValue("Freq. Corr.", corr);
SetHWLO(gFreq);
}
//---------------------------------------------------------------------------
extern "C"
long EXTIO_API GetHWLO()
{
return gFreq;
}
//---------------------------------------------------------------------------
extern "C"
long EXTIO_API GetHWSR()
{
return gRate;
}
//---------------------------------------------------------------------------
extern "C"
int EXTIO_API GetStatus()
{
return 0;
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API ShowGUI()
{
if(ManagedGlobals::gGUI) ManagedGlobals::gGUI->ShowDialog();
}
<commit_msg>fix initial gFreqMin value in ExtIO_RedPitaya_TRX.cpp<commit_after>
#include <string.h>
#include <math.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#include <windows.h>
#include "GUI.h"
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace Microsoft::Win32;
using namespace ExtIO_RedPitaya_TRX;
//---------------------------------------------------------------------------
#define EXTIO_API __declspec(dllexport) __stdcall
#define TCP_PORT 1001
#define TCP_ADDR "192.168.1.100"
SOCKET gSock[2] = {-1, -1};
char gBuffer[8192];
UInt32 gRate = 100000;
Int32 gCorr = 0;
UInt32 gFreq = 600000;
UInt32 gFreqMin = 50000;
UInt32 gFreqMax = 60000000;
bool gInitHW = false;
bool gExitThread = false;
bool gThreadRunning = false;
//---------------------------------------------------------------------------
ref class ManagedGlobals
{
public:
static GUI ^gGUI = nullptr;
static RegistryKey ^gKey = nullptr;
};
//---------------------------------------------------------------------------
void (*ExtIOCallback)(int, int, float, void *) = 0;
static void SetRate(UInt32);
static void UpdateRate(UInt32);
static void SetCorr(Int32);
//---------------------------------------------------------------------------
DWORD WINAPI GeneratorThreadProc(__in LPVOID lpParameter)
{
unsigned long size = 0;
while(!gExitThread)
{
SleepEx(1, FALSE);
if(gExitThread) break;
ioctlsocket(gSock[1], FIONREAD, &size);
while(size >= 8192)
{
recv(gSock[1], gBuffer, 8192, 0);
if(ExtIOCallback) (*ExtIOCallback)(1024, 0, 0.0, gBuffer);
ioctlsocket(gSock[1], FIONREAD, &size);
}
}
gExitThread = false;
gThreadRunning = false;
return 0;
}
//---------------------------------------------------------------------------
static void StopThread()
{
if(gThreadRunning)
{
gExitThread = true;
while(gThreadRunning)
{
SleepEx(10, FALSE);
}
}
}
//---------------------------------------------------------------------------
static void StartThread()
{
gExitThread = false;
gThreadRunning = true;
CreateThread(NULL, (SIZE_T)(64 * 1024), GeneratorThreadProc, NULL, 0, NULL);
}
//---------------------------------------------------------------------------
extern "C" int EXTIO_API SetHWLO(long LOfreq);
//---------------------------------------------------------------------------
extern "C"
bool EXTIO_API InitHW(char *name, char *model, int &type)
{
String ^addrString;
UInt32 rateIndex = 2;
Int32 corr = 0;
type = 7;
strcpy(name, "Red Pitaya SDR TRX");
strcpy(model, "");
if(!gInitHW)
{
ManagedGlobals::gKey = Registry::CurrentUser->OpenSubKey("Software\\ExtIO_RedPitaya_TRX", true);
if(!ManagedGlobals::gKey)
{
ManagedGlobals::gKey = Registry::CurrentUser->CreateSubKey("Software\\ExtIO_RedPitaya_TRX");
ManagedGlobals::gKey->SetValue("IP Address", TCP_ADDR);
ManagedGlobals::gKey->SetValue("Sample Rate", rateIndex);
ManagedGlobals::gKey->SetValue("Freq. Corr.", corr);
}
ManagedGlobals::gGUI = gcnew GUI;
addrString = ManagedGlobals::gKey->GetValue("IP Address")->ToString();
ManagedGlobals::gGUI->addrValue->Text = addrString;
rateIndex = Convert::ToUInt32(ManagedGlobals::gKey->GetValue("Sample Rate", 1));
if(rateIndex < 0 || rateIndex > 5) rateIndex = 2;
ManagedGlobals::gGUI->rateValue->SelectedIndex = rateIndex;
ManagedGlobals::gGUI->rateCallback = UpdateRate;
corr = Convert::ToInt32(ManagedGlobals::gKey->GetValue("Freq. Corr.", 0));
if(corr < -100 || corr > 100) corr = 0;
ManagedGlobals::gGUI->corrValue->Value = corr;
ManagedGlobals::gGUI->corrCallback = SetCorr;
SetRate(rateIndex);
SetCorr(corr);
gInitHW = true;
}
return gInitHW;
}
//---------------------------------------------------------------------------
extern "C"
bool EXTIO_API OpenHW()
{
return gInitHW;
}
//---------------------------------------------------------------------------
extern "C"
int EXTIO_API StartHW(long LOfreq)
{
WSADATA wsaData;
struct sockaddr_in addr;
String ^addrString;
char *buffer;
UInt32 command;
int i;
if(!gInitHW) return 0;
WSAStartup(MAKEWORD(2, 2), &wsaData);
addrString = ManagedGlobals::gGUI->addrValue->Text;
ManagedGlobals::gKey->SetValue("IP Address", addrString);
buffer = (char*)Marshal::StringToHGlobalAnsi(addrString).ToPointer();
for(i = 0; i < 2; ++i)
{
gSock[i] = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(buffer);
addr.sin_port = htons(TCP_PORT);
connect(gSock[i], (struct sockaddr *)&addr, sizeof(addr));
command = i;
send(gSock[i], (char *)&command, 4, 0);
}
Marshal::FreeHGlobal(IntPtr(buffer));
StopThread();
gFreq = LOfreq;
SetRate(ManagedGlobals::gGUI->rateValue->SelectedIndex);
StartThread();
return 1024;
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API StopHW()
{
StopThread();
closesocket(gSock[1]);
closesocket(gSock[0]);
gSock[1] = -1;
gSock[0] = -1;
WSACleanup();
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API CloseHW()
{
gInitHW = false;
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API SetCallback(void (*callback)(int, int, float, void *))
{
ExtIOCallback = callback;
}
//---------------------------------------------------------------------------
extern "C"
int EXTIO_API SetHWLO(long LOfreq)
{
int rc = 0;
UInt32 buffer = 0;
gFreq = LOfreq;
// check limits
if(gFreq < gFreqMin)
{
gFreq = gFreqMin;
rc = -gFreqMin;
}
else if(gFreq > gFreqMax)
{
gFreq = gFreqMax;
rc = gFreqMax;
}
if(gFreq != LOfreq && ExtIOCallback) (*ExtIOCallback)(-1, 101, 0.0, 0);
buffer = (long)floor(gFreq*(1.0 + gCorr*1.0e-6) + 0.5);
if(gSock[0] > 0) send(gSock[0], (char *)&buffer, 4, 0);
return rc;
}
//---------------------------------------------------------------------------
static void SetRate(UInt32 rateIndex)
{
switch(rateIndex)
{
case 0: gRate = 20000; gFreqMin = 10000; break;
case 1: gRate = 50000; gFreqMin = 25000; break;
case 2: gRate = 100000; gFreqMin = 50000; break;
case 3: gRate = 250000; gFreqMin = 125000; break;
case 4: gRate = 500000; gFreqMin = 250000; break;
case 5: gRate = 1250000; gFreqMin = 625000; break;
}
if(ManagedGlobals::gKey) ManagedGlobals::gKey->SetValue("Sample Rate", rateIndex);
rateIndex |= 1<<28;
if(gSock[0] > 0) send(gSock[0], (char *)&rateIndex, 4, 0);
SetHWLO(gFreq);
}
//---------------------------------------------------------------------------
static void UpdateRate(UInt32 rateIndex)
{
SetRate(rateIndex);
if(ExtIOCallback) (*ExtIOCallback)(-1, 100, 0.0, 0);
}
//---------------------------------------------------------------------------
static void SetCorr(Int32 corr)
{
gCorr = corr;
if(ManagedGlobals::gKey) ManagedGlobals::gKey->SetValue("Freq. Corr.", corr);
SetHWLO(gFreq);
}
//---------------------------------------------------------------------------
extern "C"
long EXTIO_API GetHWLO()
{
return gFreq;
}
//---------------------------------------------------------------------------
extern "C"
long EXTIO_API GetHWSR()
{
return gRate;
}
//---------------------------------------------------------------------------
extern "C"
int EXTIO_API GetStatus()
{
return 0;
}
//---------------------------------------------------------------------------
extern "C"
void EXTIO_API ShowGUI()
{
if(ManagedGlobals::gGUI) ManagedGlobals::gGUI->ShowDialog();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2014 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "vld.h"
#include <stdlib.h>
#include "SessionMgr.h"
#include "Server.h"
#include "stringtools.h"
CSessionMgr::CSessionMgr(void)
{
sess_mutex=Server->createMutex();
wait_cond=Server->createCondition();
wait_mutex=Server->createMutex();
stop_mutex=Server->createMutex();
stop_cond=Server->createCondition();
SESSIONID_LEN=30;//Server->Settings->getValue("SESSIONID_LEN",15);
SESSION_TIMEOUT_S=1800;//Server->Settings->getValue("SESSION_TIMEOUT_S",600);
for(unsigned char i=48;i<58;++i)
Pool.push_back(i);
for(unsigned char i=65;i<91;++i)
Pool.push_back(i);
for(unsigned char i=97;i<122;++i)
Pool.push_back(i);
run=false;
}
CSessionMgr::~CSessionMgr()
{
{
IScopedLock lock( sess_mutex );
Server->Log("removing sessions...");
if(!mSessions.empty() )
{
std::vector<std::wstring> sesids;
for(std::map<std::wstring, SUser*>::iterator i=mSessions.begin();i!=mSessions.end();++i)
{
sesids.push_back(i->first);
}
lock.relock(NULL);
for(size_t i=0;i<sesids.size();++i)
{
RemoveSession(sesids[i]);
}
}
Server->Log("done.");
}
if(run)
{
IScopedLock slock(stop_mutex);
Server->Log("waiting for sessionmgr...");
run=false;
wait_cond->notify_all();
stop_cond->wait(&slock);
Server->Log("done.");
}
Server->destroy(sess_mutex);
Server->destroy(wait_mutex);
Server->destroy(stop_mutex);
Server->destroy(wait_cond);
Server->destroy(stop_cond);
}
void CSessionMgr::startTimeoutSessionThread()
{
run=true;
Server->createThread(this);
}
std::wstring CSessionMgr::GenerateSessionIDWithUser(const std::wstring &pUsername, const std::wstring &pIdentData, bool update_user)
{
std::wstring ret;
ret.resize(SESSIONID_LEN);
std::vector<unsigned int> rnd_n=Server->getSecureRandomNumbers(SESSIONID_LEN);
for(int i=0;i<SESSIONID_LEN;++i)
ret[i]+=Pool[rnd_n[i]%Pool.size()];
IScopedLock lock( sess_mutex );
if(update_user)
{
std::vector<std::wstring> to_remove;
for(std::map<std::wstring, SUser*>::iterator i=mSessions.begin();i!=mSessions.end();++i)
{
if( i->second->username==pUsername )
{
to_remove.push_back(i->first);
}
}
lock.relock(NULL);
for(size_t i=0;i<to_remove.size();++i)
{
RemoveSession(to_remove[i]);
}
lock.relock(sess_mutex);
}
SUser *user=new SUser;
user->username=pUsername;
user->session=ret;
user->mutex=Server->createMutex();
user->lock=NULL;
user->ident_data=pIdentData;
user->id=-1;
user->lastused=Server->getTimeMS();
mSessions.insert(std::pair<std::wstring, SUser*>(ret, user) );
return ret;
}
SUser *CSessionMgr::getUser(const std::wstring &pSID, const std::wstring &pIdentData, bool update)
{
IScopedLock lock( sess_mutex );
std::map<std::wstring, SUser*>::iterator i=mSessions.find(pSID);
if( i!=mSessions.end() )
{
if( i->second->ident_data!=pIdentData )
return NULL;
lock.relock(NULL);
ILock *lock=((IMutex*)i->second->mutex)->Lock2();
i->second->lock=lock;
if( update==true )
i->second->lastused=Server->getTimeMS();
return i->second;
}
else
return NULL;
}
void CSessionMgr::releaseUser(SUser *user)
{
if( user!=NULL )
{
((ILock*)user->lock)->Remove();
}
}
void CSessionMgr::lockUser(SUser *user)
{
if( user!=NULL )
{
ILock *lock=((IMutex*)user->mutex)->Lock2();
user->lock=lock;
}
}
bool CSessionMgr::RemoveSession(const std::wstring &pSID)
{
IScopedLock lock( sess_mutex );
std::map<std::wstring, SUser*>::iterator i=mSessions.find(pSID);
if( i!=mSessions.end() )
{
SUser* user=i->second;
mSessions.erase(i);
lock.relock(NULL);
IScopedLock *lock=new IScopedLock(((IMutex*)user->mutex));
delete lock;
Server->destroy((IMutex*)user->mutex);
for(std::map<std::string, IObject* >::iterator iter=user->mCustom.begin();
iter!=user->mCustom.end();++iter)
{
iter->second->Remove();
}
delete user;
return true;
}
else
return false;
}
unsigned int CSessionMgr::TimeoutSessions(void)
{
if(Server!=NULL)
Server->Log("Looking for old Sessions... "+nconvert(mSessions.size())+" sessions", LL_INFO);
unsigned int ret=0;
IScopedLock lock( sess_mutex );
int64 ttime=Server->getTimeMS();
std::vector<std::wstring> to_timeout;
for(std::map<std::wstring, SUser*>::iterator i=mSessions.begin();i!=mSessions.end();++i)
{
int64 diff=ttime-i->second->lastused;
if( diff > (unsigned int)(SESSION_TIMEOUT_S)*1000 )
{
Server->Log(L"Session timeout: Session "+i->first, LL_INFO);
to_timeout.push_back(i->first);
return 0;
}
else
{
ret=static_cast<unsigned int>((std::max)(diff, static_cast<int64>(ret)));
}
}
lock.relock(NULL);
for(size_t i=0;i<to_timeout.size();++i)
{
RemoveSession(to_timeout[i]);
}
return (unsigned int)((SESSION_TIMEOUT_S)*1000)-ret+1000;
}
void CSessionMgr::operator()(void)
{
{
IScopedLock lock( wait_mutex );
while(run)
{
unsigned int wtime=TimeoutSessions();
wait_cond->wait(&lock, wtime);
}
}
IScopedLock slock(stop_mutex);
stop_cond->notify_one();
}
<commit_msg>Properly timeout sessions<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2014 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "vld.h"
#include <stdlib.h>
#include "SessionMgr.h"
#include "Server.h"
#include "stringtools.h"
CSessionMgr::CSessionMgr(void)
{
sess_mutex=Server->createMutex();
wait_cond=Server->createCondition();
wait_mutex=Server->createMutex();
stop_mutex=Server->createMutex();
stop_cond=Server->createCondition();
SESSIONID_LEN=30;//Server->Settings->getValue("SESSIONID_LEN",15);
SESSION_TIMEOUT_S=1800;//Server->Settings->getValue("SESSION_TIMEOUT_S",600);
for(unsigned char i=48;i<58;++i)
Pool.push_back(i);
for(unsigned char i=65;i<91;++i)
Pool.push_back(i);
for(unsigned char i=97;i<122;++i)
Pool.push_back(i);
run=false;
}
CSessionMgr::~CSessionMgr()
{
{
IScopedLock lock( sess_mutex );
Server->Log("removing sessions...");
if(!mSessions.empty() )
{
std::vector<std::wstring> sesids;
for(std::map<std::wstring, SUser*>::iterator i=mSessions.begin();i!=mSessions.end();++i)
{
sesids.push_back(i->first);
}
lock.relock(NULL);
for(size_t i=0;i<sesids.size();++i)
{
RemoveSession(sesids[i]);
}
}
Server->Log("done.");
}
if(run)
{
IScopedLock slock(stop_mutex);
Server->Log("waiting for sessionmgr...");
run=false;
wait_cond->notify_all();
stop_cond->wait(&slock);
Server->Log("done.");
}
Server->destroy(sess_mutex);
Server->destroy(wait_mutex);
Server->destroy(stop_mutex);
Server->destroy(wait_cond);
Server->destroy(stop_cond);
}
void CSessionMgr::startTimeoutSessionThread()
{
run=true;
Server->createThread(this);
}
std::wstring CSessionMgr::GenerateSessionIDWithUser(const std::wstring &pUsername, const std::wstring &pIdentData, bool update_user)
{
std::wstring ret;
ret.resize(SESSIONID_LEN);
std::vector<unsigned int> rnd_n=Server->getSecureRandomNumbers(SESSIONID_LEN);
for(int i=0;i<SESSIONID_LEN;++i)
ret[i]+=Pool[rnd_n[i]%Pool.size()];
IScopedLock lock( sess_mutex );
if(update_user)
{
std::vector<std::wstring> to_remove;
for(std::map<std::wstring, SUser*>::iterator i=mSessions.begin();i!=mSessions.end();++i)
{
if( i->second->username==pUsername )
{
to_remove.push_back(i->first);
}
}
lock.relock(NULL);
for(size_t i=0;i<to_remove.size();++i)
{
RemoveSession(to_remove[i]);
}
lock.relock(sess_mutex);
}
SUser *user=new SUser;
user->username=pUsername;
user->session=ret;
user->mutex=Server->createMutex();
user->lock=NULL;
user->ident_data=pIdentData;
user->id=-1;
user->lastused=Server->getTimeMS();
mSessions.insert(std::pair<std::wstring, SUser*>(ret, user) );
return ret;
}
SUser *CSessionMgr::getUser(const std::wstring &pSID, const std::wstring &pIdentData, bool update)
{
IScopedLock lock( sess_mutex );
std::map<std::wstring, SUser*>::iterator i=mSessions.find(pSID);
if( i!=mSessions.end() )
{
if( i->second->ident_data!=pIdentData )
return NULL;
lock.relock(NULL);
ILock *lock=((IMutex*)i->second->mutex)->Lock2();
i->second->lock=lock;
if( update==true )
i->second->lastused=Server->getTimeMS();
return i->second;
}
else
return NULL;
}
void CSessionMgr::releaseUser(SUser *user)
{
if( user!=NULL )
{
((ILock*)user->lock)->Remove();
}
}
void CSessionMgr::lockUser(SUser *user)
{
if( user!=NULL )
{
ILock *lock=((IMutex*)user->mutex)->Lock2();
user->lock=lock;
}
}
bool CSessionMgr::RemoveSession(const std::wstring &pSID)
{
IScopedLock lock( sess_mutex );
std::map<std::wstring, SUser*>::iterator i=mSessions.find(pSID);
if( i!=mSessions.end() )
{
SUser* user=i->second;
mSessions.erase(i);
lock.relock(NULL);
IScopedLock *lock=new IScopedLock(((IMutex*)user->mutex));
delete lock;
Server->destroy((IMutex*)user->mutex);
for(std::map<std::string, IObject* >::iterator iter=user->mCustom.begin();
iter!=user->mCustom.end();++iter)
{
iter->second->Remove();
}
delete user;
return true;
}
else
return false;
}
unsigned int CSessionMgr::TimeoutSessions(void)
{
if(Server!=NULL)
Server->Log("Looking for old Sessions... "+nconvert(mSessions.size())+" sessions", LL_INFO);
unsigned int ret=0;
IScopedLock lock( sess_mutex );
int64 ttime=Server->getTimeMS();
std::vector<std::wstring> to_timeout;
for(std::map<std::wstring, SUser*>::iterator i=mSessions.begin();i!=mSessions.end();++i)
{
int64 diff=ttime-i->second->lastused;
if( diff > (unsigned int)(SESSION_TIMEOUT_S)*1000 )
{
Server->Log(L"Session timeout: Session "+i->first, LL_INFO);
to_timeout.push_back(i->first);
}
else
{
ret=static_cast<unsigned int>((std::max)(diff, static_cast<int64>(ret)));
}
}
lock.relock(NULL);
for(size_t i=0;i<to_timeout.size();++i)
{
RemoveSession(to_timeout[i]);
}
return (unsigned int)((SESSION_TIMEOUT_S)*1000)-ret+1000;
}
void CSessionMgr::operator()(void)
{
{
IScopedLock lock( wait_mutex );
while(run)
{
unsigned int wtime=TimeoutSessions();
wait_cond->wait(&lock, wtime);
}
}
IScopedLock slock(stop_mutex);
stop_cond->notify_one();
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Core/WindowsApplication.h"
#include "Sources/External/IMGUI/imgui_impl_win32.h"
#include <functional>
#include <Strsafe.h>
#include "Core/CoreTypes.h"
#include "Core/Input/Input.h"
#include "Render/RenderSettings.h"
namespace Kioto
{
namespace KiotoCore
{
void Init();
void Update();
void Shutdown();
void ChangeFullscreenMode(bool fullScreen);
void Resize(uint16 width, uint16 height, bool minimized);
Kioto::RenderSettings& GetRenderSettings();
}
namespace WindowsApplication
{
namespace
{
const UINT WindowStyle = WS_OVERLAPPEDWINDOW;
RECT WindowRect = {};
std::wstring WindowCaption;
bool IsFullscreen = false;
HWND Hwnd;
}
void MessageError(LPTSTR lpszFunction);
LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
bool Init(HINSTANCE hInstance, int32 nCmdShow, std::wstring caption)
{
// TODO: create mutex to check if another instance exist.
IsFullscreen = false;
WindowCaption = caption;
WNDCLASSEX windowClass = {};
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
windowClass.lpszClassName = caption.c_str();
RegisterClassEx(&windowClass);
Vector2i resolution = KiotoCore::GetRenderSettings().Resolution;
RECT windowRect = { 0, 0, resolution.x, resolution.y };
if (!AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE))
return false;
Hwnd = CreateWindow(windowClass.lpszClassName,
WindowCaption.c_str(),
WindowStyle,
CW_USEDEFAULT,
CW_USEDEFAULT,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
nullptr,
nullptr,
hInstance,
nullptr);
if (Hwnd == nullptr)
{
MessageError(TEXT("Create window"));
return false;
}
ShowWindow(Hwnd, nCmdShow);
return true;
}
int64 Run()
{
MSG msg = {};
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
KiotoCore::Update(); // [a_vorontcov] TODO: If app minimized go to sleep.
}
}
Shutdown();
return static_cast<int64>(msg.wParam);
}
void Shutdown()
{
KiotoCore::Shutdown();
}
void ChangeFullscreenMode(bool fullScreen)
{
if (fullScreen == IsFullscreen)
return;
IsFullscreen = fullScreen;
if (!IsFullscreen)
{
SetWindowLong(Hwnd, GWL_STYLE, WindowStyle);
SetWindowPos(
Hwnd,
HWND_NOTOPMOST,
WindowRect.left,
WindowRect.top,
WindowRect.right - WindowRect.left,
WindowRect.bottom - WindowRect.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(Hwnd, SW_NORMAL);
return;
}
GetWindowRect(Hwnd, &WindowRect);
UINT fullScreenWindowStyle = WindowStyle & ~(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU | WS_THICKFRAME);
SetWindowLong(Hwnd, GWL_STYLE, fullScreenWindowStyle);
DEVMODE devMode = {};
devMode.dmSize = sizeof(DEVMODE);
EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &devMode);
SetWindowPos(
Hwnd,
HWND_TOPMOST,
devMode.dmPosition.x,
devMode.dmPosition.y,
devMode.dmPosition.x + devMode.dmPelsWidth,
devMode.dmPosition.y + devMode.dmPelsHeight,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(Hwnd, SW_MAXIMIZE);
}
HWND GetHWND()
{
return Hwnd;
}
LRESULT WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
ImGui::ImplWinWndProcHandler(hwnd, message, wParam, lParam);
switch (message)
{
case WM_CREATE:
{
LPCREATESTRUCT pCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pCreateStruct->lpCreateParams));
// [a_vorontcov] For now only keyboard, joystick and mouse.
RAWINPUTDEVICE rid[3];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x02; // [a_vorontcov] Mouse.
rid[0].dwFlags = 0;
rid[0].hwndTarget = hwnd;
rid[1].usUsagePage = 0x01;
rid[1].usUsage = 0x06; // [a_vorontcov] Keyboard.
rid[1].dwFlags = 0;
rid[1].hwndTarget = hwnd;
rid[2].usUsagePage = 0x01;
rid[2].usUsage = 0x04; // [a_vorontcov] Joystic.
rid[2].dwFlags = 0;
rid[2].hwndTarget = hwnd;
if (!RegisterRawInputDevices(rid, 3, sizeof(rid[0])))
assert(false && "Couldn't register input devices");
return 0;
}
case WM_INPUT:
{
if (ImGui::IsAnyWindowFocused())
return 0;
// [a_vorontcov] Explanation of what's going on here - https://docs.microsoft.com/en-us/windows/desktop/inputdev/using-raw-input
UINT dwSize;
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
LPBYTE lpb = new BYTE[dwSize]; // [a_vorontcov] TODO: Remove every frame reallocation here.
if (lpb == NULL)
return 0;
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
OutputDebugString(TEXT("GetRawInputData doesn't return correct size! \n"));
RAWINPUT* raw = (RAWINPUT*)lpb;
if (raw->header.dwType == RIM_TYPEKEYBOARD)
{
if ((raw->data.keyboard.Flags & RI_KEY_BREAK) != 0)
Input::SetButtonUp(static_cast<uint32>(raw->data.keyboard.VKey));
else if (raw->data.keyboard.Flags == RI_KEY_MAKE)
Input::SetButtonDown(static_cast<uint32>(raw->data.keyboard.VKey));
}
else if (raw->header.dwType == RIM_TYPEMOUSE)
{
Input::SetMouseMoveRelated(raw->data.mouse.lLastX, raw->data.mouse.lLastY);
if (raw->data.mouse.usButtonFlags & RI_MOUSE_WHEEL)
Input::SetMouseWheel(raw->data.mouse.usButtonData);
if (static_cast<uint32>(raw->data.mouse.usButtonFlags) != 0)
Input::SetMouseFlags(static_cast<uint32>(raw->data.mouse.usButtonFlags));
}
SafeDeleteArray(lpb);
return 0;
}
case WM_KEYDOWN:
return 0;
case WM_KEYUP:
return 0;
case WM_SYSKEYDOWN:
if ((wParam == VK_RETURN) && (lParam & (1 << 29))) // [a_vorontcov] Handle Alt+Enter.
{
KiotoCore::ChangeFullscreenMode(!IsFullscreen);
}
return 0;
case WM_EXITSIZEMOVE:
{
RECT clientRect = {};
GetClientRect(Hwnd, &clientRect);
KiotoCore::Resize(static_cast<uint16>(clientRect.right - clientRect.left), static_cast<uint16>(clientRect.bottom - clientRect.top), wParam == SIZE_MINIMIZED);
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
void MessageError(LPTSTR lpszFunction)
{
LPVOID messageBuffer;
LPVOID displayBuffer;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&messageBuffer,
0, nullptr);
displayBuffer = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)messageBuffer) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)displayBuffer,
LocalSize(displayBuffer) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, messageBuffer);
MessageBox(nullptr, (LPCTSTR)displayBuffer, TEXT("Error"), MB_OK);
LocalFree(messageBuffer);
LocalFree(displayBuffer);
}
}
}<commit_msg>Fixed lptstr conversion<commit_after>#include "stdafx.h"
#include "Core/WindowsApplication.h"
#include "Sources/External/IMGUI/imgui_impl_win32.h"
#include <functional>
#include <Strsafe.h>
#include "Core/CoreTypes.h"
#include "Core/Input/Input.h"
#include "Render/RenderSettings.h"
namespace Kioto
{
namespace KiotoCore
{
void Init();
void Update();
void Shutdown();
void ChangeFullscreenMode(bool fullScreen);
void Resize(uint16 width, uint16 height, bool minimized);
Kioto::RenderSettings& GetRenderSettings();
}
namespace WindowsApplication
{
namespace
{
const UINT WindowStyle = WS_OVERLAPPEDWINDOW;
RECT WindowRect = {};
std::wstring WindowCaption;
bool IsFullscreen = false;
HWND Hwnd;
}
void MessageError(LPTSTR lpszFunction);
LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
bool Init(HINSTANCE hInstance, int32 nCmdShow, std::wstring caption)
{
// TODO: create mutex to check if another instance exist.
IsFullscreen = false;
WindowCaption = caption;
WNDCLASSEX windowClass = {};
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
windowClass.lpszClassName = caption.c_str();
RegisterClassEx(&windowClass);
Vector2i resolution = KiotoCore::GetRenderSettings().Resolution;
RECT windowRect = { 0, 0, resolution.x, resolution.y };
if (!AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE))
return false;
Hwnd = CreateWindow(windowClass.lpszClassName,
WindowCaption.c_str(),
WindowStyle,
CW_USEDEFAULT,
CW_USEDEFAULT,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
nullptr,
nullptr,
hInstance,
nullptr);
if (Hwnd == nullptr)
{
MessageError(const_cast<wchar_t*>(TEXT("Create window")));
return false;
}
ShowWindow(Hwnd, nCmdShow);
return true;
}
int64 Run()
{
MSG msg = {};
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
KiotoCore::Update(); // [a_vorontcov] TODO: If app minimized go to sleep.
}
}
Shutdown();
return static_cast<int64>(msg.wParam);
}
void Shutdown()
{
KiotoCore::Shutdown();
}
void ChangeFullscreenMode(bool fullScreen)
{
if (fullScreen == IsFullscreen)
return;
IsFullscreen = fullScreen;
if (!IsFullscreen)
{
SetWindowLong(Hwnd, GWL_STYLE, WindowStyle);
SetWindowPos(
Hwnd,
HWND_NOTOPMOST,
WindowRect.left,
WindowRect.top,
WindowRect.right - WindowRect.left,
WindowRect.bottom - WindowRect.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(Hwnd, SW_NORMAL);
return;
}
GetWindowRect(Hwnd, &WindowRect);
UINT fullScreenWindowStyle = WindowStyle & ~(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU | WS_THICKFRAME);
SetWindowLong(Hwnd, GWL_STYLE, fullScreenWindowStyle);
DEVMODE devMode = {};
devMode.dmSize = sizeof(DEVMODE);
EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &devMode);
SetWindowPos(
Hwnd,
HWND_TOPMOST,
devMode.dmPosition.x,
devMode.dmPosition.y,
devMode.dmPosition.x + devMode.dmPelsWidth,
devMode.dmPosition.y + devMode.dmPelsHeight,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(Hwnd, SW_MAXIMIZE);
}
HWND GetHWND()
{
return Hwnd;
}
LRESULT WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
ImGui::ImplWinWndProcHandler(hwnd, message, wParam, lParam);
switch (message)
{
case WM_CREATE:
{
LPCREATESTRUCT pCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pCreateStruct->lpCreateParams));
// [a_vorontcov] For now only keyboard, joystick and mouse.
RAWINPUTDEVICE rid[3];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x02; // [a_vorontcov] Mouse.
rid[0].dwFlags = 0;
rid[0].hwndTarget = hwnd;
rid[1].usUsagePage = 0x01;
rid[1].usUsage = 0x06; // [a_vorontcov] Keyboard.
rid[1].dwFlags = 0;
rid[1].hwndTarget = hwnd;
rid[2].usUsagePage = 0x01;
rid[2].usUsage = 0x04; // [a_vorontcov] Joystic.
rid[2].dwFlags = 0;
rid[2].hwndTarget = hwnd;
if (!RegisterRawInputDevices(rid, 3, sizeof(rid[0])))
assert(false && "Couldn't register input devices");
return 0;
}
case WM_INPUT:
{
if (ImGui::IsAnyWindowFocused())
return 0;
// [a_vorontcov] Explanation of what's going on here - https://docs.microsoft.com/en-us/windows/desktop/inputdev/using-raw-input
UINT dwSize;
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
LPBYTE lpb = new BYTE[dwSize]; // [a_vorontcov] TODO: Remove every frame reallocation here.
if (lpb == NULL)
return 0;
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
OutputDebugString(TEXT("GetRawInputData doesn't return correct size! \n"));
RAWINPUT* raw = (RAWINPUT*)lpb;
if (raw->header.dwType == RIM_TYPEKEYBOARD)
{
if ((raw->data.keyboard.Flags & RI_KEY_BREAK) != 0)
Input::SetButtonUp(static_cast<uint32>(raw->data.keyboard.VKey));
else if (raw->data.keyboard.Flags == RI_KEY_MAKE)
Input::SetButtonDown(static_cast<uint32>(raw->data.keyboard.VKey));
}
else if (raw->header.dwType == RIM_TYPEMOUSE)
{
Input::SetMouseMoveRelated(raw->data.mouse.lLastX, raw->data.mouse.lLastY);
if (raw->data.mouse.usButtonFlags & RI_MOUSE_WHEEL)
Input::SetMouseWheel(raw->data.mouse.usButtonData);
if (static_cast<uint32>(raw->data.mouse.usButtonFlags) != 0)
Input::SetMouseFlags(static_cast<uint32>(raw->data.mouse.usButtonFlags));
}
SafeDeleteArray(lpb);
return 0;
}
case WM_KEYDOWN:
return 0;
case WM_KEYUP:
return 0;
case WM_SYSKEYDOWN:
if ((wParam == VK_RETURN) && (lParam & (1 << 29))) // [a_vorontcov] Handle Alt+Enter.
{
KiotoCore::ChangeFullscreenMode(!IsFullscreen);
}
return 0;
case WM_EXITSIZEMOVE:
{
RECT clientRect = {};
GetClientRect(Hwnd, &clientRect);
KiotoCore::Resize(static_cast<uint16>(clientRect.right - clientRect.left), static_cast<uint16>(clientRect.bottom - clientRect.top), wParam == SIZE_MINIMIZED);
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
void MessageError(LPTSTR lpszFunction)
{
LPVOID messageBuffer;
LPVOID displayBuffer;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&messageBuffer,
0, nullptr);
displayBuffer = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)messageBuffer) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)displayBuffer,
LocalSize(displayBuffer) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, messageBuffer);
MessageBox(nullptr, (LPCTSTR)displayBuffer, TEXT("Error"), MB_OK);
LocalFree(messageBuffer);
LocalFree(displayBuffer);
}
}
}<|endoftext|>
|
<commit_before>#include <iomanip>
#include <Castro.H>
#include <Castro_F.H>
#include <Geometry.H>
void
Castro::sum_integrated_quantities ()
{
int finest_level = parent->finestLevel();
Real time = state[State_Type].curTime();
Real mass = 0.0;
Real momentum[3] = { 0.0 };
Real rho_E = 0.0;
Real rho_e = 0.0;
Real rho_phi = 0.0;
Real gravitational_energy = 0.0;
Real kinetic_energy = 0.0;
Real internal_energy = 0.0;
Real total_energy = 0.0;
Real angular_momentum[3] = { 0.0 };
Real moment_of_inertia[3][3] = { 0.0 };
Real m_r_squared[3] = { 0.0 };
Real omega[3] = { 0.0, 0.0, 2.0*3.14159265358979*rotational_frequency };
Real L_grid[3] = { 0.0 };
Real mass_left = 0.0;
Real mass_right = 0.0;
Real com[3] = { 0.0 };
Real com_l[3] = { 0.0 };
Real com_r[3] = { 0.0 };
Real delta_com[3] = { 0.0 };
Real com_vel[3] = { 0.0 };
Real com_vel_l[3] = { 0.0 };
Real com_vel_r[3] = { 0.0 };
std::string name1;
std::string name2;
int index1;
int index2;
int datawidth = 14;
int dataprecision = 6;
for (int lev = 0; lev <= finest_level; lev++)
{
// Get the current level from Castro
Castro& ca_lev = getLevel(lev);
// Calculate center of mass quantities.
mass_left += ca_lev.volWgtSumOneSide("density", time, 0, 0);
mass_right += ca_lev.volWgtSumOneSide("density", time, 1, 0);
for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) {
switch ( i ) {
case 0 :
name1 = "xmom"; break;
case 1 :
name1 = "ymom"; break;
case 2 :
name1 = "zmom"; break;
}
delta_com[i] = ca_lev.locWgtSum("density", time, i);
com[i] += delta_com[i];
com_l[i] += ca_lev.locWgtSumOneSide("density", time, i, 0, 0);
com_r[i] += ca_lev.locWgtSumOneSide("density", time, i, 1, 0);
com_vel_l[i] += ca_lev.volWgtSumOneSide(name1, time, 0, 0);
com_vel_r[i] += ca_lev.volWgtSumOneSide(name1, time, 1, 0);
}
// Calculate total mass, momentum and energy of system.
mass += ca_lev.volWgtSum("density", time);
momentum[0] += ca_lev.volWgtSum("xmom", time);
momentum[1] += ca_lev.volWgtSum("ymom", time);
#if (BL_SPACEDIM == 3)
momentum[2] += ca_lev.volWgtSum("zmom", time);
#endif
rho_E += ca_lev.volWgtSum("rho_E", time);
rho_e += ca_lev.volWgtSum("rho_e", time);
#ifdef GRAVITY
if ( do_grav ) {
rho_phi += ca_lev.volProductSum("density", "phi", time);
}
#endif
// Calculate total angular momentum on the grid using L = r x p
#if (BL_SPACEDIM == 3)
for ( int i = 0; i <= 2; i++ ) {
index1 = (i+1) % 3;
index2 = (i+2) % 3;
switch (i) {
case 0 :
name1 = "ymom"; name2 = "zmom"; break;
case 1 :
name1 = "zmom"; name2 = "xmom"; break;
case 2 :
name1 = "xmom"; name2 = "ymom"; break;
}
L_grid[i] = ca_lev.locWgtSum(name2, time, index1) - ca_lev.locWgtSum(name1, time, index2);
angular_momentum[i] += L_grid[i];
}
#elif (BL_SPACEDIM == 2)
L_grid[2] = ca_lev.locWgtSum("ymom", time, 0) - ca_lev.locWgtSum("xmom", time, 1);
#endif
// Add rotation source terms
if ( do_rotation ) {
// Construct (symmetric) moment of inertia tensor
for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) {
m_r_squared[i] = ca_lev.locWgtSum2D("density", time, i, i);
}
for ( int i = 0; i <= 2; i++ ) {
for ( int j = 0; j <= 2; j++ ) {
if ( i <= j ) {
if ( i != j ) {
if ( ( i < BL_SPACEDIM ) && ( j < BL_SPACEDIM ) ) // Protect against computing z direction sum in 2D
moment_of_inertia[i][j] = -ca_lev.locWgtSum2D("density", time, i, j);
}
else
moment_of_inertia[i][j] = m_r_squared[(i+1)%3] + m_r_squared[(i+2)%3];
}
else
moment_of_inertia[i][j] = moment_of_inertia[j][i];
}
}
for ( int i = 0; i <= 2; i++ ) {
// Momentum source from motion IN rotating frame == omega x (rho * r)
momentum[i] += omega[(i+1)%3]*delta_com[(i+2)%3] - omega[(i+2)%3]*delta_com[(i+1)%3];
// Rotational energy from motion IN rotating frame == omega dot L_grid
kinetic_energy += omega[i] * L_grid[i];
// Now add quantities due to motion OF rotating frame
for ( int j = 0; j <=2; j++ ) {
angular_momentum[i] += moment_of_inertia[i][j] * omega[j];
kinetic_energy += (1.0/2.0) * omega[i] * moment_of_inertia[i][j] * omega[j];
}
}
}
}
// Complete calculations for COM quantities
Real center = 0.0;
for ( int i = 0; i <= 2; i++ ) {
center = 0.5*(Geometry::ProbLo(i) + Geometry::ProbHi(i));
com[i] = com[i] / mass + center;
com_l[i] = com_l[i] / mass_left + center;
com_r[i] = com_r[i] / mass_right + center;
com_vel_l[i] = com_vel_l[i] / mass_left;
com_vel_r[i] = com_vel_r[i] / mass_right;
com_vel[i] = momentum[i] / mass;
}
const Real* ml = &mass_left;
const Real* mr = &mass_right;
const Real* cxl = &com_l[0];
const Real* cxr = &com_r[0];
const Real* cyl = &com_l[1];
const Real* cyr = &com_r[1];
const Real* czl = &com_l[2];
const Real* czr = &com_r[2];
BL_FORT_PROC_CALL(COM_SAVE,com_save)
(ml, mr, cxl, cxr, cyl, cyr, czl, czr);
// Complete calculations for energy
gravitational_energy = (-1.0/2.0) * rho_phi; // avoids double counting; CASTRO uses positive phi
internal_energy = rho_e;
kinetic_energy += rho_E - rho_e;
total_energy = gravitational_energy + internal_energy + kinetic_energy;
// Write data out to the log.
if ( ParallelDescriptor::IOProcessor() )
{
std::ostream& data_log1 = parent->DataLog(0);
if ( data_log1.good() ) {
// Write header row
if (time == 0.0) {
data_log1 << std::setw(datawidth) << "# TIME ";
data_log1 << std::setw(datawidth) << " MASS ";
data_log1 << std::setw(datawidth) << " XMOM ";
data_log1 << std::setw(datawidth) << " YMOM ";
data_log1 << std::setw(datawidth) << " ZMOM ";
data_log1 << std::setw(datawidth) << " KIN. ENERGY ";
data_log1 << std::setw(datawidth) << " GRAV. ENERGY";
data_log1 << std::setw(datawidth) << " INT. ENERGY ";
data_log1 << std::setw(datawidth) << " TOTAL ENERGY";
data_log1 << std::setw(datawidth) << " ANG. MOM. X ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Y ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Z ";
data_log1 << std::setw(datawidth) << " X COM ";
data_log1 << std::setw(datawidth) << " Y COM ";
data_log1 << std::setw(datawidth) << " Z COM ";
data_log1 << std::setw(datawidth) << " LEFT MASS ";
data_log1 << std::setw(datawidth) << " RIGHT MASS ";
data_log1 << std::setw(datawidth) << " LEFT X COM ";
data_log1 << std::setw(datawidth) << " RIGHT X COM ";
data_log1 << std::setw(datawidth) << " LEFT Y COM ";
data_log1 << std::setw(datawidth) << " RIGHT Y COM ";
data_log1 << std::setw(datawidth) << " LEFT Z COM ";
data_log1 << std::setw(datawidth) << " RIGHT Z COM ";
data_log1 << std::setw(datawidth) << " X VEL ";
data_log1 << std::setw(datawidth) << " Y VEL ";
data_log1 << std::setw(datawidth) << " Z VEL ";
data_log1 << std::setw(datawidth) << " LEFT X VEL ";
data_log1 << std::setw(datawidth) << " RIGHT X VEL ";
data_log1 << std::setw(datawidth) << " LEFT Y VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Y VEL ";
data_log1 << std::setw(datawidth) << " LEFT Z VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Z VEL ";
data_log1 << std::endl;
}
// Write data for the present time
data_log1 << std::fixed;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << time;
data_log1 << std::scientific;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << kinetic_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << gravitational_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << internal_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << total_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_left;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_right;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[2];
data_log1 << std::endl;
}
}
}
<commit_msg>Added explanatory comment regarding previous parallel output fix.<commit_after>#include <iomanip>
#include <Castro.H>
#include <Castro_F.H>
#include <Geometry.H>
void
Castro::sum_integrated_quantities ()
{
int finest_level = parent->finestLevel();
Real time = state[State_Type].curTime();
Real mass = 0.0;
Real momentum[3] = { 0.0 };
Real rho_E = 0.0;
Real rho_e = 0.0;
Real rho_phi = 0.0;
Real gravitational_energy = 0.0;
Real kinetic_energy = 0.0;
Real internal_energy = 0.0;
Real total_energy = 0.0;
Real angular_momentum[3] = { 0.0 };
Real moment_of_inertia[3][3] = { 0.0 };
Real m_r_squared[3] = { 0.0 };
Real omega[3] = { 0.0, 0.0, 2.0*3.14159265358979*rotational_frequency };
Real L_grid[3] = { 0.0 };
Real mass_left = 0.0;
Real mass_right = 0.0;
Real com[3] = { 0.0 };
Real com_l[3] = { 0.0 };
Real com_r[3] = { 0.0 };
Real delta_com[3] = { 0.0 };
Real com_vel[3] = { 0.0 };
Real com_vel_l[3] = { 0.0 };
Real com_vel_r[3] = { 0.0 };
std::string name1;
std::string name2;
int index1;
int index2;
int datawidth = 14;
int dataprecision = 6;
for (int lev = 0; lev <= finest_level; lev++)
{
// Get the current level from Castro
Castro& ca_lev = getLevel(lev);
// Calculate center of mass quantities.
mass_left += ca_lev.volWgtSumOneSide("density", time, 0, 0);
mass_right += ca_lev.volWgtSumOneSide("density", time, 1, 0);
for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) {
switch ( i ) {
case 0 :
name1 = "xmom"; break;
case 1 :
name1 = "ymom"; break;
case 2 :
name1 = "zmom"; break;
}
delta_com[i] = ca_lev.locWgtSum("density", time, i);
com[i] += delta_com[i];
com_l[i] += ca_lev.locWgtSumOneSide("density", time, i, 0, 0);
com_r[i] += ca_lev.locWgtSumOneSide("density", time, i, 1, 0);
com_vel_l[i] += ca_lev.volWgtSumOneSide(name1, time, 0, 0);
com_vel_r[i] += ca_lev.volWgtSumOneSide(name1, time, 1, 0);
}
// Calculate total mass, momentum and energy of system.
mass += ca_lev.volWgtSum("density", time);
momentum[0] += ca_lev.volWgtSum("xmom", time);
momentum[1] += ca_lev.volWgtSum("ymom", time);
#if (BL_SPACEDIM == 3)
momentum[2] += ca_lev.volWgtSum("zmom", time);
#endif
rho_E += ca_lev.volWgtSum("rho_E", time);
rho_e += ca_lev.volWgtSum("rho_e", time);
#ifdef GRAVITY
if ( do_grav ) {
rho_phi += ca_lev.volProductSum("density", "phi", time);
}
#endif
// Calculate total angular momentum on the grid using L = r x p
#if (BL_SPACEDIM == 3)
for ( int i = 0; i <= 2; i++ ) {
index1 = (i+1) % 3;
index2 = (i+2) % 3;
switch (i) {
case 0 :
name1 = "ymom"; name2 = "zmom"; break;
case 1 :
name1 = "zmom"; name2 = "xmom"; break;
case 2 :
name1 = "xmom"; name2 = "ymom"; break;
}
L_grid[i] = ca_lev.locWgtSum(name2, time, index1) - ca_lev.locWgtSum(name1, time, index2);
angular_momentum[i] += L_grid[i];
}
#elif (BL_SPACEDIM == 2)
L_grid[2] = ca_lev.locWgtSum("ymom", time, 0) - ca_lev.locWgtSum("xmom", time, 1);
#endif
// Add rotation source terms
if ( do_rotation ) {
// Construct (symmetric) moment of inertia tensor
for ( int i = 0; i <= BL_SPACEDIM-1; i++ ) {
m_r_squared[i] = ca_lev.locWgtSum2D("density", time, i, i);
}
for ( int i = 0; i <= 2; i++ ) {
for ( int j = 0; j <= 2; j++ ) {
if ( i <= j ) {
if ( i != j ) {
if ( ( i < BL_SPACEDIM ) && ( j < BL_SPACEDIM ) ) // Protect against computing z direction sum in 2D
moment_of_inertia[i][j] = -ca_lev.locWgtSum2D("density", time, i, j);
}
else
moment_of_inertia[i][j] = m_r_squared[(i+1)%3] + m_r_squared[(i+2)%3];
}
else
moment_of_inertia[i][j] = moment_of_inertia[j][i];
}
}
for ( int i = 0; i <= 2; i++ ) {
// Momentum source from motion IN rotating frame == omega x (rho * r)
momentum[i] += omega[(i+1)%3]*delta_com[(i+2)%3] - omega[(i+2)%3]*delta_com[(i+1)%3];
// Rotational energy from motion IN rotating frame == omega dot L_grid
kinetic_energy += omega[i] * L_grid[i];
// Now add quantities due to motion OF rotating frame
for ( int j = 0; j <=2; j++ ) {
angular_momentum[i] += moment_of_inertia[i][j] * omega[j];
kinetic_energy += (1.0/2.0) * omega[i] * moment_of_inertia[i][j] * omega[j];
}
}
}
}
// Complete calculations for COM quantities
Real center = 0.0;
for ( int i = 0; i <= 2; i++ ) {
center = 0.5*(Geometry::ProbLo(i) + Geometry::ProbHi(i));
com[i] = com[i] / mass + center;
com_l[i] = com_l[i] / mass_left + center;
com_r[i] = com_r[i] / mass_right + center;
com_vel_l[i] = com_vel_l[i] / mass_left;
com_vel_r[i] = com_vel_r[i] / mass_right;
com_vel[i] = momentum[i] / mass;
}
const Real* ml = &mass_left;
const Real* mr = &mass_right;
const Real* cxl = &com_l[0];
const Real* cxr = &com_r[0];
const Real* cyl = &com_l[1];
const Real* cyr = &com_r[1];
const Real* czl = &com_l[2];
const Real* czr = &com_r[2];
BL_FORT_PROC_CALL(COM_SAVE,com_save)
(ml, mr, cxl, cxr, cyl, cyr, czl, czr);
// Complete calculations for energy
gravitational_energy = (-1.0/2.0) * rho_phi; // avoids double counting; CASTRO uses positive phi
internal_energy = rho_e;
kinetic_energy += rho_E - rho_e;
total_energy = gravitational_energy + internal_energy + kinetic_energy;
// Write data out to the log.
if ( ParallelDescriptor::IOProcessor() )
{
// The data log is only defined on the IO processor
// for parallel runs, so the stream should only be opened inside.
std::ostream& data_log1 = parent->DataLog(0);
if ( data_log1.good() ) {
// Write header row
if (time == 0.0) {
data_log1 << std::setw(datawidth) << "# TIME ";
data_log1 << std::setw(datawidth) << " MASS ";
data_log1 << std::setw(datawidth) << " XMOM ";
data_log1 << std::setw(datawidth) << " YMOM ";
data_log1 << std::setw(datawidth) << " ZMOM ";
data_log1 << std::setw(datawidth) << " KIN. ENERGY ";
data_log1 << std::setw(datawidth) << " GRAV. ENERGY";
data_log1 << std::setw(datawidth) << " INT. ENERGY ";
data_log1 << std::setw(datawidth) << " TOTAL ENERGY";
data_log1 << std::setw(datawidth) << " ANG. MOM. X ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Y ";
data_log1 << std::setw(datawidth) << " ANG. MOM. Z ";
data_log1 << std::setw(datawidth) << " X COM ";
data_log1 << std::setw(datawidth) << " Y COM ";
data_log1 << std::setw(datawidth) << " Z COM ";
data_log1 << std::setw(datawidth) << " LEFT MASS ";
data_log1 << std::setw(datawidth) << " RIGHT MASS ";
data_log1 << std::setw(datawidth) << " LEFT X COM ";
data_log1 << std::setw(datawidth) << " RIGHT X COM ";
data_log1 << std::setw(datawidth) << " LEFT Y COM ";
data_log1 << std::setw(datawidth) << " RIGHT Y COM ";
data_log1 << std::setw(datawidth) << " LEFT Z COM ";
data_log1 << std::setw(datawidth) << " RIGHT Z COM ";
data_log1 << std::setw(datawidth) << " X VEL ";
data_log1 << std::setw(datawidth) << " Y VEL ";
data_log1 << std::setw(datawidth) << " Z VEL ";
data_log1 << std::setw(datawidth) << " LEFT X VEL ";
data_log1 << std::setw(datawidth) << " RIGHT X VEL ";
data_log1 << std::setw(datawidth) << " LEFT Y VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Y VEL ";
data_log1 << std::setw(datawidth) << " LEFT Z VEL ";
data_log1 << std::setw(datawidth) << " RIGHT Z VEL ";
data_log1 << std::endl;
}
// Write data for the present time
data_log1 << std::fixed;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << time;
data_log1 << std::scientific;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << kinetic_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << gravitational_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << internal_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << total_energy;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << angular_momentum[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_left;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << mass_right;
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_r[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[0];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[1];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_l[2];
data_log1 << std::setw(datawidth) << std::setprecision(dataprecision) << com_vel_r[2];
data_log1 << std::endl;
}
}
}
<|endoftext|>
|
<commit_before>#include "fetchers.hh"
#include "store-api.hh"
#include <filesystem>
#include "archive.hh"
namespace nix::fetchers {
struct PathInputScheme : InputScheme
{
std::optional<Input> inputFromURL(const ParsedURL & url) override
{
if (url.scheme != "path") return {};
if (url.authority && *url.authority != "")
throw Error("path URL '%s' should not have an authority ('%s')", url.url, *url.authority);
Input input;
input.attrs.insert_or_assign("type", "path");
input.attrs.insert_or_assign("path", url.path);
for (auto & [name, value] : url.query)
if (name == "rev" || name == "narHash")
input.attrs.insert_or_assign(name, value);
else if (name == "revCount" || name == "lastModified") {
if (auto n = string2Int<uint64_t>(value))
input.attrs.insert_or_assign(name, *n);
else
throw Error("path URL '%s' has invalid parameter '%s'", url.to_string(), name);
}
else
throw Error("path URL '%s' has unsupported parameter '%s'", url.to_string(), name);
return input;
}
std::optional<Input> inputFromAttrs(const Attrs & attrs) override
{
if (maybeGetStrAttr(attrs, "type") != "path") return {};
getStrAttr(attrs, "path");
for (auto & [name, value] : attrs)
/* Allow the user to pass in "fake" tree info
attributes. This is useful for making a pinned tree
work the same as the repository from which is exported
(e.g. path:/nix/store/...-source?lastModified=1585388205&rev=b0c285...). */
if (name == "type" || name == "rev" || name == "revCount" || name == "lastModified" || name == "narHash" || name == "path")
// checked in Input::fromAttrs
;
else
throw Error("unsupported path input attribute '%s'", name);
Input input;
input.attrs = attrs;
return input;
}
ParsedURL toURL(const Input & input) override
{
auto query = attrsToQuery(input.attrs);
query.erase("path");
query.erase("type");
return ParsedURL {
.scheme = "path",
.path = getStrAttr(input.attrs, "path"),
.query = query,
};
}
bool hasAllInfo(const Input & input) override
{
return true;
}
std::optional<Path> getSourcePath(const Input & input) override
{
return getStrAttr(input.attrs, "path");
}
void markChangedFile(const Input & input, std::string_view file, std::optional<std::string> commitMsg) override
{
// nothing to do
}
std::pair<StorePath, Input> fetch(ref<Store> store, const Input & _input) override
{
Input input(_input);
std::string absPath;
auto path = getStrAttr(input.attrs, "path");
if (path[0] != '/') {
if (!input.parent)
throw Error("cannot fetch input '%s' because it uses a relative path", input.to_string());
auto parent = canonPath(*input.parent);
// the path isn't relative, prefix it
absPath = nix::absPath(path, parent);
// for security, ensure that if the parent is a store path, it's inside it
if (store->isInStore(parent)) {
auto storePath = store->printStorePath(store->toStorePath(parent).first);
if (!isDirOrInDir(absPath, storePath))
throw BadStorePath("relative path '%s' points outside of its parent's store path '%s'", path, storePath);
}
} else
absPath = path;
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying '%s'", absPath));
// FIXME: check whether access to 'path' is allowed.
auto storePath = store->maybeParseStorePath(absPath);
if (storePath)
store->addTempRoot(*storePath);
time_t mtime = 0;
if (!storePath || storePath->name() != "source" || !store->isValidPath(*storePath)) {
// FIXME: try to substitute storePath.
auto src = sinkToSource([&](Sink & sink) {
mtime = dumpPathAndGetMtime(absPath, sink, defaultPathFilter);
});
storePath = store->addToStoreFromDump(*src, "source");
}
input.attrs.insert_or_assign("lastModified", uint64_t(mtime));
return {std::move(*storePath), input};
}
};
static auto rPathInputScheme = OnStartup([] { registerInputScheme(std::make_unique<PathInputScheme>()); });
}
<commit_msg>libfetchers: remove obsolete filesystem #include<commit_after>#include "fetchers.hh"
#include "store-api.hh"
#include "archive.hh"
namespace nix::fetchers {
struct PathInputScheme : InputScheme
{
std::optional<Input> inputFromURL(const ParsedURL & url) override
{
if (url.scheme != "path") return {};
if (url.authority && *url.authority != "")
throw Error("path URL '%s' should not have an authority ('%s')", url.url, *url.authority);
Input input;
input.attrs.insert_or_assign("type", "path");
input.attrs.insert_or_assign("path", url.path);
for (auto & [name, value] : url.query)
if (name == "rev" || name == "narHash")
input.attrs.insert_or_assign(name, value);
else if (name == "revCount" || name == "lastModified") {
if (auto n = string2Int<uint64_t>(value))
input.attrs.insert_or_assign(name, *n);
else
throw Error("path URL '%s' has invalid parameter '%s'", url.to_string(), name);
}
else
throw Error("path URL '%s' has unsupported parameter '%s'", url.to_string(), name);
return input;
}
std::optional<Input> inputFromAttrs(const Attrs & attrs) override
{
if (maybeGetStrAttr(attrs, "type") != "path") return {};
getStrAttr(attrs, "path");
for (auto & [name, value] : attrs)
/* Allow the user to pass in "fake" tree info
attributes. This is useful for making a pinned tree
work the same as the repository from which is exported
(e.g. path:/nix/store/...-source?lastModified=1585388205&rev=b0c285...). */
if (name == "type" || name == "rev" || name == "revCount" || name == "lastModified" || name == "narHash" || name == "path")
// checked in Input::fromAttrs
;
else
throw Error("unsupported path input attribute '%s'", name);
Input input;
input.attrs = attrs;
return input;
}
ParsedURL toURL(const Input & input) override
{
auto query = attrsToQuery(input.attrs);
query.erase("path");
query.erase("type");
return ParsedURL {
.scheme = "path",
.path = getStrAttr(input.attrs, "path"),
.query = query,
};
}
bool hasAllInfo(const Input & input) override
{
return true;
}
std::optional<Path> getSourcePath(const Input & input) override
{
return getStrAttr(input.attrs, "path");
}
void markChangedFile(const Input & input, std::string_view file, std::optional<std::string> commitMsg) override
{
// nothing to do
}
std::pair<StorePath, Input> fetch(ref<Store> store, const Input & _input) override
{
Input input(_input);
std::string absPath;
auto path = getStrAttr(input.attrs, "path");
if (path[0] != '/') {
if (!input.parent)
throw Error("cannot fetch input '%s' because it uses a relative path", input.to_string());
auto parent = canonPath(*input.parent);
// the path isn't relative, prefix it
absPath = nix::absPath(path, parent);
// for security, ensure that if the parent is a store path, it's inside it
if (store->isInStore(parent)) {
auto storePath = store->printStorePath(store->toStorePath(parent).first);
if (!isDirOrInDir(absPath, storePath))
throw BadStorePath("relative path '%s' points outside of its parent's store path '%s'", path, storePath);
}
} else
absPath = path;
Activity act(*logger, lvlTalkative, actUnknown, fmt("copying '%s'", absPath));
// FIXME: check whether access to 'path' is allowed.
auto storePath = store->maybeParseStorePath(absPath);
if (storePath)
store->addTempRoot(*storePath);
time_t mtime = 0;
if (!storePath || storePath->name() != "source" || !store->isValidPath(*storePath)) {
// FIXME: try to substitute storePath.
auto src = sinkToSource([&](Sink & sink) {
mtime = dumpPathAndGetMtime(absPath, sink, defaultPathFilter);
});
storePath = store->addToStoreFromDump(*src, "source");
}
input.attrs.insert_or_assign("lastModified", uint64_t(mtime));
return {std::move(*storePath), input};
}
};
static auto rPathInputScheme = OnStartup([] { registerInputScheme(std::make_unique<PathInputScheme>()); });
}
<|endoftext|>
|
<commit_before>//
// src/macho/container.cc
// tbd
//
// Created by inoahdev on 4/24/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include "header/symbol_table.h"
#include "container.h"
namespace macho {
container::container(FILE *file, long base)
: file_(file), base_(base) {
const auto position = ftell(file);
fseek(file, 0, SEEK_END);
this->size_ = ftell(file);
fseek(file, position, SEEK_SET);
this->validate();
}
container::container(FILE *file, long base, size_t size)
: file_(file), base_(base), size_(size) {
this->validate();
}
container::~container() {
auto &cached = cached_;
if (cached) {
delete[] cached;
}
auto &string_table = string_table_;
if (string_table) {
delete[] string_table;
}
}
void container::validate() {
auto &base = base_;
auto &file = file_;
auto &header = header_;
auto &magic = header.magic;
const auto is_big_endian = this->is_big_endian();
const auto position = ftell(file);
fseek(file, base, SEEK_SET);
fread(&magic, sizeof(uint32_t), 1, file);
const auto macho_file_is_regular = magic_is_thin(magic);
if (macho_file_is_regular) {
fread(&header.cputype, sizeof(header) - sizeof(uint32_t), 1, file);
if (is_big_endian) {
swap_mach_header(&header);
}
} else {
const auto macho_file_is_fat = magic_is_fat(magic);
if (macho_file_is_fat) {
fprintf(stderr, "Architecture at location (0x%.8lX) cannot be a fat mach-o file itself\n", base);
exit(1);
} else {
fprintf(stderr, "Architecture at location (0x%.8lX) is not a valid mach-o base\n", base);
exit(1);
}
}
fseek(file, position, SEEK_SET);
}
void container::iterate_load_commands(const std::function<bool (const struct load_command *)> &callback) {
const auto &base = base_;
const auto &file = file_;
const auto &header = header_;
const auto is_big_endian = this->is_big_endian();
const auto &ncmds = header.ncmds;
const auto &sizeofcmds = header.sizeofcmds;
auto &cached = cached_;
auto created_cache = false;
if (!cached) {
cached = new char[sizeofcmds];
created_cache = true;
auto load_command_base = base + sizeof(header);
if (this->is_64_bit()) {
load_command_base += sizeof(uint32_t);
}
const auto position = ftell(file);
fseek(file, load_command_base, SEEK_SET);
fread(cached, sizeofcmds, 1, file);
fseek(file, position, SEEK_SET);
}
auto size_used = 0;
auto cached_index = 0;
auto should_callback = true;
for (auto i = 0; i < ncmds; i++) {
auto load_cmd = (struct load_command *)&cached[cached_index];
const auto &cmdsize = load_cmd->cmdsize;
if (created_cache) {
if (is_big_endian) {
swap_load_command(load_cmd);
}
if (cmdsize < sizeof(struct load_command)) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) is too small to be valid\n", i, base);
exit(1);
}
if (cmdsize >= sizeofcmds) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) is larger than/or equal to entire area allocated for load-commands\n", i, base);
exit(1);
}
size_used += cmdsize;
if (size_used > sizeofcmds) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) goes past end of area allocated for load-commands\n", i, base);
exit(1);
} else if (size_used == sizeofcmds && i != ncmds - 1) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) takes up all of the remaining space allocated for load-commands\n", i, base);
exit(1);
}
}
if (should_callback) {
auto result = callback(load_cmd);
if (!result) {
should_callback = false;
}
}
if (!should_callback && !created_cache) {
break;
}
cached_index += cmdsize;
}
}
void container::iterate_symbols(const std::function<bool (const struct nlist_64 &, const char *)> &callback) {
auto &base = base_;
auto &file = file_;
const auto is_big_endian = this->is_big_endian();
const auto position = ftell(file);
struct symtab_command *symtab_command = nullptr;
iterate_load_commands([&](const struct load_command *load_cmd) {
if (load_cmd->cmd != load_commands::symbol_table) {
return true;
}
symtab_command = (struct symtab_command *)load_cmd;
if (is_big_endian) {
swap_symtab_command(symtab_command);
}
return false;
});
if (!symtab_command) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) does not have a symbol-table\n", base);
exit(1);
}
const auto &string_table_location = symtab_command->stroff;
if (string_table_location > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a string-table outside of its container\n", base);
exit(1);
}
const auto &string_table_size = symtab_command->strsize;
if (string_table_size > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a string-table with a size larger than that of itself\n", base);
exit(1);
}
const auto string_table_end = string_table_location + string_table_size;
if (string_table_end > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a string-table that goes outside of its container\n", base);
exit(1);
}
const auto &symbol_table_location = symtab_command->symoff;
if (symbol_table_location > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table that is outside of its container\n", base);
exit(1);
}
auto &string_table = string_table_;
if (!string_table) {
string_table = new char[string_table_size];
fseek(file, base + string_table_location, SEEK_SET);
fread(string_table, string_table_size, 1, file);
}
const auto &symbol_table_count = symtab_command->nsyms;
const auto string_table_max_index = string_table_size - 1;
fseek(file, base + symbol_table_location, SEEK_SET);
const auto is_64_bit = this->is_64_bit();
if (is_64_bit) {
const auto symbol_table_size = sizeof(struct nlist_64) * symbol_table_count;
if (symbol_table_size > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table with a size larger than itself\n", base);
exit(1);
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table that goes outside of its boundaries\n", base);
exit(1);
}
const auto symbol_table = new struct nlist_64[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (is_big_endian) {
swap_nlist_64(symbol_table, symbol_table_count);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (symbol_table_entry_string_table_index > string_table_max_index) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table of mach-o container (at base 0x%.8lX)\n", i, base);
exit(1);
}
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
} else {
const auto symbol_table_size = sizeof(struct nlist) * symbol_table_count;
if (symbol_table_size > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table with a size larger than itself\n", base);
exit(1);
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table that goes outside of its boundaries\n", base);
exit(1);
}
const auto symbol_table = new struct nlist[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (is_big_endian) {
swap_nlist(symbol_table, symbol_table_count);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (i == 10956) {
printf("");
}
if (symbol_table_entry_string_table_index > string_table_max_index) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table of mach-o container (at base 0x%.8lX)\n", i, base);
exit(1);
}
const struct nlist_64 symbol_table_entry_64 = { { symbol_table_entry.n_un.n_strx }, symbol_table_entry.n_type, symbol_table_entry.n_sect, (uint16_t)symbol_table_entry.n_desc, symbol_table_entry.n_value };
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry_64, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
}
fseek(file, position, SEEK_SET);
}
}
<commit_msg>Fix spaces/tabs in container.cc<commit_after>//
// src/macho/container.cc
// tbd
//
// Created by inoahdev on 4/24/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include "header/symbol_table.h"
#include "container.h"
namespace macho {
container::container(FILE *file, long base)
: file_(file), base_(base) {
const auto position = ftell(file);
fseek(file, 0, SEEK_END);
this->size_ = ftell(file);
fseek(file, position, SEEK_SET);
this->validate();
}
container::container(FILE *file, long base, size_t size)
: file_(file), base_(base), size_(size) {
this->validate();
}
container::~container() {
auto &cached = cached_;
if (cached) {
delete[] cached;
}
auto &string_table = string_table_;
if (string_table) {
delete[] string_table;
}
}
void container::validate() {
auto &base = base_;
auto &file = file_;
auto &header = header_;
auto &magic = header.magic;
const auto is_big_endian = this->is_big_endian();
const auto position = ftell(file);
fseek(file, base, SEEK_SET);
fread(&magic, sizeof(uint32_t), 1, file);
const auto macho_file_is_regular = magic_is_thin(magic);
if (macho_file_is_regular) {
fread(&header.cputype, sizeof(header) - sizeof(uint32_t), 1, file);
if (is_big_endian) {
swap_mach_header(&header);
}
} else {
const auto macho_file_is_fat = magic_is_fat(magic);
if (macho_file_is_fat) {
fprintf(stderr, "Architecture at location (0x%.8lX) cannot be a fat mach-o file itself\n", base);
exit(1);
} else {
fprintf(stderr, "Architecture at location (0x%.8lX) is not a valid mach-o base\n", base);
exit(1);
}
}
fseek(file, position, SEEK_SET);
}
void container::iterate_load_commands(const std::function<bool (const struct load_command *)> &callback) {
const auto &base = base_;
const auto &file = file_;
const auto &header = header_;
const auto is_big_endian = this->is_big_endian();
const auto &ncmds = header.ncmds;
const auto &sizeofcmds = header.sizeofcmds;
auto &cached = cached_;
auto created_cache = false;
if (!cached) {
cached = new char[sizeofcmds];
created_cache = true;
auto load_command_base = base + sizeof(header);
if (this->is_64_bit()) {
load_command_base += sizeof(uint32_t);
}
const auto position = ftell(file);
fseek(file, load_command_base, SEEK_SET);
fread(cached, sizeofcmds, 1, file);
fseek(file, position, SEEK_SET);
}
auto size_used = 0;
auto cached_index = 0;
auto should_callback = true;
for (auto i = 0; i < ncmds; i++) {
auto load_cmd = (struct load_command *)&cached[cached_index];
const auto &cmdsize = load_cmd->cmdsize;
if (created_cache) {
if (is_big_endian) {
swap_load_command(load_cmd);
}
if (cmdsize < sizeof(struct load_command)) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) is too small to be valid\n", i, base);
exit(1);
}
if (cmdsize >= sizeofcmds) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) is larger than/or equal to entire area allocated for load-commands\n", i, base);
exit(1);
}
size_used += cmdsize;
if (size_used > sizeofcmds) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) goes past end of area allocated for load-commands\n", i, base);
exit(1);
} else if (size_used == sizeofcmds && i != ncmds - 1) {
fprintf(stderr, "Load-command (at index %d) of mach-o container (at base 0x%.8lX) takes up all of the remaining space allocated for load-commands\n", i, base);
exit(1);
}
}
if (should_callback) {
auto result = callback(load_cmd);
if (!result) {
should_callback = false;
}
}
if (!should_callback && !created_cache) {
break;
}
cached_index += cmdsize;
}
}
void container::iterate_symbols(const std::function<bool (const struct nlist_64 &, const char *)> &callback) {
auto &base = base_;
auto &file = file_;
const auto is_big_endian = this->is_big_endian();
const auto position = ftell(file);
struct symtab_command *symtab_command = nullptr;
iterate_load_commands([&](const struct load_command *load_cmd) {
if (load_cmd->cmd != load_commands::symbol_table) {
return true;
}
symtab_command = (struct symtab_command *)load_cmd;
if (is_big_endian) {
swap_symtab_command(symtab_command);
}
return false;
});
if (!symtab_command) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) does not have a symbol-table\n", base);
exit(1);
}
const auto &string_table_location = symtab_command->stroff;
if (string_table_location > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a string-table outside of its container\n", base);
exit(1);
}
const auto &string_table_size = symtab_command->strsize;
if (string_table_size > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a string-table with a size larger than that of itself\n", base);
exit(1);
}
const auto string_table_end = string_table_location + string_table_size;
if (string_table_end > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a string-table that goes outside of its container\n", base);
exit(1);
}
const auto &symbol_table_location = symtab_command->symoff;
if (symbol_table_location > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table that is outside of its container\n", base);
exit(1);
}
auto &string_table = string_table_;
if (!string_table) {
string_table = new char[string_table_size];
fseek(file, base + string_table_location, SEEK_SET);
fread(string_table, string_table_size, 1, file);
}
const auto &symbol_table_count = symtab_command->nsyms;
const auto string_table_max_index = string_table_size - 1;
fseek(file, base + symbol_table_location, SEEK_SET);
const auto is_64_bit = this->is_64_bit();
if (is_64_bit) {
const auto symbol_table_size = sizeof(struct nlist_64) * symbol_table_count;
if (symbol_table_size > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table with a size larger than itself\n", base);
exit(1);
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table that goes outside of its boundaries\n", base);
exit(1);
}
const auto symbol_table = new struct nlist_64[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (is_big_endian) {
swap_nlist_64(symbol_table, symbol_table_count);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (symbol_table_entry_string_table_index > string_table_max_index) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table of mach-o container (at base 0x%.8lX)\n", i, base);
exit(1);
}
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
} else {
const auto symbol_table_size = sizeof(struct nlist) * symbol_table_count;
if (symbol_table_size > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table with a size larger than itself\n", base);
exit(1);
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size_) {
fprintf(stderr, "Mach-o container (at base 0x%.8lX) has a symbol-table that goes outside of its boundaries\n", base);
exit(1);
}
const auto symbol_table = new struct nlist[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (is_big_endian) {
swap_nlist(symbol_table, symbol_table_count);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (i == 10956) {
printf("");
}
if (symbol_table_entry_string_table_index > string_table_max_index) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table of mach-o container (at base 0x%.8lX)\n", i, base);
exit(1);
}
const struct nlist_64 symbol_table_entry_64 = { { symbol_table_entry.n_un.n_strx }, symbol_table_entry.n_type, symbol_table_entry.n_sect, (uint16_t)symbol_table_entry.n_desc, symbol_table_entry.n_value };
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry_64, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
}
fseek(file, position, SEEK_SET);
}
}
<|endoftext|>
|
<commit_before>#include "machine/machine.hpp"
#include <pthread.h>
#include <semaphore.h>
#include <cpu/intel8080.hpp>
#include <SDL2/SDL.h>
void *doCpuWork(void *arg) {
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
struct timespec sleeptime;
sleeptime.tv_sec = 0;
sleeptime.tv_nsec = 10;
if (arg != NULL) {
Intel8080 *cpu = (Intel8080 *) arg;
// Update the CPU
while (1) {
cpu->emulateCycle();
nanosleep(&sleeptime, NULL);
}
}
}
void Machine::start() {
pthread_t cpuThread;
pthread_create(&cpuThread, NULL, doCpuWork, (void *) &cpu);
screen.initSDL();
SDL_Event e;
keys.insert(std::pair<std::string, bool>("w", false));
keys.insert(std::pair<std::string, bool>("g", false));
keys.insert(std::pair<std::string, bool>("h", false));
keys.insert(std::pair<std::string, bool>("a", false));
keys.insert(std::pair<std::string, bool>("s", false));
keys.insert(std::pair<std::string, bool>("d", false));
keys.insert(std::pair<std::string, bool>("up", false));
keys.insert(std::pair<std::string, bool>("left", false));
keys.insert(std::pair<std::string, bool>("down", false));
keys.insert(std::pair<std::string, bool>("right", false));
// SDL happens on a separate thread from the CPU
while(!quit) {
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) {
switch (e.key.keysym.sym) {
case SDLK_w:
keys["w"] = e.type == SDL_KEYDOWN;
break;
case SDLK_a:
keys["a"] = e.type == SDL_KEYDOWN;
break;
case SDLK_s:
keys["s"] = e.type == SDL_KEYDOWN;
break;
case SDLK_d:
keys["d"] = e.type == SDL_KEYDOWN;
break;
case SDLK_UP:
keys["up"] = e.type == SDL_KEYDOWN;
break;
case SDLK_LEFT:
keys["left"] = e.type == SDL_KEYDOWN;
break;
case SDLK_DOWN:
keys["down"] = e.type == SDL_KEYDOWN;
break;
case SDLK_RIGHT:
keys["right"] = e.type == SDL_KEYDOWN;
break;
}
} else if (e.type == SDL_QUIT) {
quit = e.type == SDL_QUIT;
}
}
cycle();
}
}
void Machine::cycle() {
screen.update(cpu);
screen.render();
}
<commit_msg>Fixed h and g not being tracked by SDL<commit_after>#include "machine/machine.hpp"
#include <pthread.h>
#include <semaphore.h>
#include <cpu/intel8080.hpp>
#include <SDL2/SDL.h>
void *doCpuWork(void *arg) {
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
struct timespec sleeptime;
sleeptime.tv_sec = 0;
sleeptime.tv_nsec = 10;
if (arg != NULL) {
Intel8080 *cpu = (Intel8080 *) arg;
// Update the CPU
while (1) {
cpu->emulateCycle();
nanosleep(&sleeptime, NULL);
}
}
}
void Machine::start() {
pthread_t cpuThread;
pthread_create(&cpuThread, NULL, doCpuWork, (void *) &cpu);
screen.initSDL();
SDL_Event e;
keys.insert(std::pair<std::string, bool>("w", false));
keys.insert(std::pair<std::string, bool>("g", false));
keys.insert(std::pair<std::string, bool>("h", false));
keys.insert(std::pair<std::string, bool>("a", false));
keys.insert(std::pair<std::string, bool>("s", false));
keys.insert(std::pair<std::string, bool>("d", false));
keys.insert(std::pair<std::string, bool>("up", false));
keys.insert(std::pair<std::string, bool>("left", false));
keys.insert(std::pair<std::string, bool>("down", false));
keys.insert(std::pair<std::string, bool>("right", false));
// SDL happens on a separate thread from the CPU
while(!quit) {
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) {
switch (e.key.keysym.sym) {
case SDLK_w:
keys["w"] = e.type == SDL_KEYDOWN;
break;
case SDLK_a:
keys["a"] = e.type == SDL_KEYDOWN;
break;
case SDLK_s:
keys["s"] = e.type == SDL_KEYDOWN;
break;
case SDLK_d:
keys["d"] = e.type == SDL_KEYDOWN;
break;
case SDLK_h:
keys["g"] = e.type == SDL_KEYDOWN;
break;
case SDLK_g:
keys["h"] = e.type == SDL_KEYDOWN;
break;
case SDLK_UP:
keys["up"] = e.type == SDL_KEYDOWN;
break;
case SDLK_LEFT:
keys["left"] = e.type == SDL_KEYDOWN;
break;
case SDLK_DOWN:
keys["down"] = e.type == SDL_KEYDOWN;
break;
case SDLK_RIGHT:
keys["right"] = e.type == SDL_KEYDOWN;
break;
}
} else if (e.type == SDL_QUIT) {
quit = e.type == SDL_QUIT;
}
}
cycle();
}
}
void Machine::cycle() {
screen.update(cpu);
screen.render();
}
<|endoftext|>
|
<commit_before>#include <imp/bridge/opencv/image_cv.hpp>
#include <iostream>
#include <imp/core/exception.hpp>
#include <imp/bridge/opencv/cv_connector_pixel_types.hpp>
namespace imp {
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(std::uint32_t width, std::uint32_t height)
: Base(width, height)
, mat_(height, width, imp::pixelTypeToCv(pixel_type))
{
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(const imp::Size2u& size)
: Base(size)
, mat_(size[1], size[0], imp::pixelTypeToCv(pixel_type))
{
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(const ImageCv<Pixel, pixel_type>& from)
: Base(from)
, mat_(from.cvMat())
{
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(const Image<Pixel, pixel_type>& from)
: Base(from)
, mat_(from.height(), from.width(), imp::pixelTypeToCv(pixel_type))
{
from.copyTo(*this);
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>
::ImageCv(cv::Mat mat, imp::PixelOrder pixel_order)
: Base(mat.cols, mat.rows, pixel_order)
, mat_(mat)
{
if (this->pixelType() != imp::pixelTypeFromCv(mat_.type()))
{
throw imp::Exception("OpenCV pixel type does not match to the internally used one.",
__FILE__, __FUNCTION__, __LINE__);
}
if (this->pixelOrder() == imp::PixelOrder::undefined)
{
switch (this->pixelType())
{
case imp::PixelType::i8uC1:
case imp::PixelType::i16uC1:
case imp::PixelType::i32fC1:
case imp::PixelType::i32sC1:
this->pixel_order_ = imp::PixelOrder::gray;
break;
case imp::PixelType::i8uC3:
case imp::PixelType::i16uC3:
case imp::PixelType::i32fC3:
case imp::PixelType::i32sC3:
this->pixel_order_ = imp::PixelOrder::bgr;
break;
case imp::PixelType::i8uC4:
case imp::PixelType::i16uC4:
case imp::PixelType::i32fC4:
case imp::PixelType::i32sC4:
this->pixel_order_ = imp::PixelOrder::bgra;
break;
default:
// if we have something else than 1,3 or 4-channel images, we do not set the
// pixel order automatically.
break;
}
}
}
////-----------------------------------------------------------------------------
//template<typename Pixel, imp::PixelType pixel_type>
//ImageCv<Pixel, pixel_type>
//::ImageCv(Pixel* data, std::uint32_t width, std::uint32_t height,
// size_type pitch, bool use_ext_data_pointer)
// : Base(width, height)
//{
// if (data == nullptr)
// {
// throw imp::Exception("input data not valid", __FILE__, __FUNCTION__, __LINE__);
// }
// if(use_ext_data_pointer)
// {
// // This uses the external data pointer as internal data pointer.
// auto dealloc_nop = [](Pixel* p) { ; };
// data_ = std::unique_ptr<pixel_storage_t, Deallocator>(
// data, Deallocator(dealloc_nop));
// pitch_ = pitch;
// }
// else
// {
// data_.reset(Memory::alignedAlloc(this->width(), this->height(), &pitch_));
// size_type stride = pitch / sizeof(pixel_storage_t);
// if (this->bytes() == pitch*height)
// {
// std::copy(data, data+stride*height, data_.get());
// }
// else
// {
// for (std::uint32_t y=0; y<height; ++y)
// {
// for (std::uint32_t x=0; x<width; ++x)
// {
// data_.get()[y*this->stride()+x] = data[y*stride + x];
// }
// }
// }
// }
//}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
cv::Mat& ImageCv<Pixel, pixel_type>::cvMat()
{
return mat_;
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
const cv::Mat& ImageCv<Pixel, pixel_type>::cvMat() const
{
return mat_;
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
Pixel* ImageCv<Pixel, pixel_type>::data(
std::uint32_t ox, std::uint32_t oy)
{
if (ox > this->width() || oy > this->height())
{
throw imp::Exception("Request starting offset is outside of the image.", __FILE__, __FUNCTION__, __LINE__);
}
Pixel* buffer = (Pixel*)mat_.data;
return &buffer[oy*this->stride() + ox];
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
const Pixel* ImageCv<Pixel, pixel_type>::data(
std::uint32_t ox, std::uint32_t oy) const
{
if (ox > this->width() || oy > this->height())
{
throw imp::Exception("Request starting offset is outside of the image.", __FILE__, __FUNCTION__, __LINE__);
}
Pixel* buffer = (Pixel*)mat_.data;
return reinterpret_cast<const Pixel*>(&buffer[oy*this->stride() + ox]);
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
void ImageCv<Pixel,pixel_type>::setValue(const Pixel& value)
{
mat_ = cv::Scalar::all(value);
}
//=============================================================================
// Explicitely instantiate the desired classes
// (sync with typedefs at the end of the hpp file)
template class ImageCv<imp::Pixel8uC1, imp::PixelType::i8uC1>;
template class ImageCv<imp::Pixel8uC2, imp::PixelType::i8uC2>;
template class ImageCv<imp::Pixel8uC3, imp::PixelType::i8uC3>;
template class ImageCv<imp::Pixel8uC4, imp::PixelType::i8uC4>;
template class ImageCv<imp::Pixel16uC1, imp::PixelType::i16uC1>;
template class ImageCv<imp::Pixel16uC2, imp::PixelType::i16uC2>;
template class ImageCv<imp::Pixel16uC3, imp::PixelType::i16uC3>;
template class ImageCv<imp::Pixel16uC4, imp::PixelType::i16uC4>;
template class ImageCv<imp::Pixel32sC1, imp::PixelType::i32sC1>;
template class ImageCv<imp::Pixel32sC2, imp::PixelType::i32sC2>;
template class ImageCv<imp::Pixel32sC3, imp::PixelType::i32sC3>;
template class ImageCv<imp::Pixel32sC4, imp::PixelType::i32sC4>;
template class ImageCv<imp::Pixel32fC1, imp::PixelType::i32fC1>;
template class ImageCv<imp::Pixel32fC2, imp::PixelType::i32fC2>;
template class ImageCv<imp::Pixel32fC3, imp::PixelType::i32fC3>;
template class ImageCv<imp::Pixel32fC4, imp::PixelType::i32fC4>;
} // namespace imp
<commit_msg>code style<commit_after>#include <imp/bridge/opencv/image_cv.hpp>
#include <iostream>
#include <imp/core/exception.hpp>
#include <imp/bridge/opencv/cv_connector_pixel_types.hpp>
namespace imp {
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(std::uint32_t width, std::uint32_t height)
: Base(width, height)
, mat_(height, width, imp::pixelTypeToCv(pixel_type))
{
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(const imp::Size2u& size)
: Base(size)
, mat_(size[1], size[0], imp::pixelTypeToCv(pixel_type))
{
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(const ImageCv<Pixel, pixel_type>& from)
: Base(from)
, mat_(from.cvMat())
{
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(const Image<Pixel, pixel_type>& from)
: Base(from)
, mat_(from.height(), from.width(), imp::pixelTypeToCv(pixel_type))
{
from.copyTo(*this);
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
ImageCv<Pixel, pixel_type>::ImageCv(cv::Mat mat, imp::PixelOrder pixel_order)
: Base(mat.cols, mat.rows, pixel_order)
, mat_(mat)
{
if (this->pixelType() != imp::pixelTypeFromCv(mat_.type()))
{
throw imp::Exception("OpenCV pixel type does not match to the internally used one.",
__FILE__, __FUNCTION__, __LINE__);
}
if (this->pixelOrder() == imp::PixelOrder::undefined)
{
switch (this->pixelType())
{
case imp::PixelType::i8uC1:
case imp::PixelType::i16uC1:
case imp::PixelType::i32fC1:
case imp::PixelType::i32sC1:
this->pixel_order_ = imp::PixelOrder::gray;
break;
case imp::PixelType::i8uC3:
case imp::PixelType::i16uC3:
case imp::PixelType::i32fC3:
case imp::PixelType::i32sC3:
this->pixel_order_ = imp::PixelOrder::bgr;
break;
case imp::PixelType::i8uC4:
case imp::PixelType::i16uC4:
case imp::PixelType::i32fC4:
case imp::PixelType::i32sC4:
this->pixel_order_ = imp::PixelOrder::bgra;
break;
default:
// if we have something else than 1,3 or 4-channel images, we do not set the
// pixel order automatically.
break;
}
}
}
////-----------------------------------------------------------------------------
//template<typename Pixel, imp::PixelType pixel_type>
//ImageCv<Pixel, pixel_type>
//::ImageCv(Pixel* data, std::uint32_t width, std::uint32_t height,
// size_type pitch, bool use_ext_data_pointer)
// : Base(width, height)
//{
// if (data == nullptr)
// {
// throw imp::Exception("input data not valid", __FILE__, __FUNCTION__, __LINE__);
// }
// if(use_ext_data_pointer)
// {
// // This uses the external data pointer as internal data pointer.
// auto dealloc_nop = [](Pixel* p) { ; };
// data_ = std::unique_ptr<pixel_storage_t, Deallocator>(
// data, Deallocator(dealloc_nop));
// pitch_ = pitch;
// }
// else
// {
// data_.reset(Memory::alignedAlloc(this->width(), this->height(), &pitch_));
// size_type stride = pitch / sizeof(pixel_storage_t);
// if (this->bytes() == pitch*height)
// {
// std::copy(data, data+stride*height, data_.get());
// }
// else
// {
// for (std::uint32_t y=0; y<height; ++y)
// {
// for (std::uint32_t x=0; x<width; ++x)
// {
// data_.get()[y*this->stride()+x] = data[y*stride + x];
// }
// }
// }
// }
//}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
cv::Mat& ImageCv<Pixel, pixel_type>::cvMat()
{
return mat_;
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
const cv::Mat& ImageCv<Pixel, pixel_type>::cvMat() const
{
return mat_;
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
Pixel* ImageCv<Pixel, pixel_type>::data(
std::uint32_t ox, std::uint32_t oy)
{
if (ox > this->width() || oy > this->height())
{
throw imp::Exception("Request starting offset is outside of the image.", __FILE__, __FUNCTION__, __LINE__);
}
Pixel* buffer = (Pixel*)mat_.data;
return &buffer[oy*this->stride() + ox];
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
const Pixel* ImageCv<Pixel, pixel_type>::data(
std::uint32_t ox, std::uint32_t oy) const
{
if (ox > this->width() || oy > this->height())
{
throw imp::Exception("Request starting offset is outside of the image.", __FILE__, __FUNCTION__, __LINE__);
}
Pixel* buffer = (Pixel*)mat_.data;
return reinterpret_cast<const Pixel*>(&buffer[oy*this->stride() + ox]);
}
//-----------------------------------------------------------------------------
template<typename Pixel, imp::PixelType pixel_type>
void ImageCv<Pixel,pixel_type>::setValue(const Pixel& value)
{
mat_ = cv::Scalar::all(value);
}
//=============================================================================
// Explicitely instantiate the desired classes
// (sync with typedefs at the end of the hpp file)
template class ImageCv<imp::Pixel8uC1, imp::PixelType::i8uC1>;
template class ImageCv<imp::Pixel8uC2, imp::PixelType::i8uC2>;
template class ImageCv<imp::Pixel8uC3, imp::PixelType::i8uC3>;
template class ImageCv<imp::Pixel8uC4, imp::PixelType::i8uC4>;
template class ImageCv<imp::Pixel16uC1, imp::PixelType::i16uC1>;
template class ImageCv<imp::Pixel16uC2, imp::PixelType::i16uC2>;
template class ImageCv<imp::Pixel16uC3, imp::PixelType::i16uC3>;
template class ImageCv<imp::Pixel16uC4, imp::PixelType::i16uC4>;
template class ImageCv<imp::Pixel32sC1, imp::PixelType::i32sC1>;
template class ImageCv<imp::Pixel32sC2, imp::PixelType::i32sC2>;
template class ImageCv<imp::Pixel32sC3, imp::PixelType::i32sC3>;
template class ImageCv<imp::Pixel32sC4, imp::PixelType::i32sC4>;
template class ImageCv<imp::Pixel32fC1, imp::PixelType::i32fC1>;
template class ImageCv<imp::Pixel32fC2, imp::PixelType::i32fC2>;
template class ImageCv<imp::Pixel32fC3, imp::PixelType::i32fC3>;
template class ImageCv<imp::Pixel32fC4, imp::PixelType::i32fC4>;
} // namespace imp
<|endoftext|>
|
<commit_before>#include "camera.h"
#include <math.h>
#include <glew.h>
using namespace GluonGraphics;
Camera::Camera()
{
mFoV = 45.0f;
mAspect = 1.0f;
mDepthNear = 1.0f;
mDepthFar = 100.0f;
mPosition = Eigen::Vector3f(-10, 0, 10);
mLookAt = Eigen::Vector3f(0, 0, 0);
mUp = Eigen::Vector3f(0, 1, 0);
mModelviewMatrixDirty = true;
mProjectionMatrixDirty = true;
}
Camera::~Camera()
{
}
void Camera::setFoV(float fov)
{
mFoV = fov;
mProjectionMatrixDirty = true;
}
void Camera::setAspect(float aspect)
{
mAspect = aspect;
mProjectionMatrixDirty = true;
}
void Camera::setDepthRange(float near, float far)
{
mDepthNear = near;
mDepthFar = far;
mProjectionMatrixDirty = true;
}
void Camera::setPosition(const Eigen::Vector3f& pos)
{
mPosition = pos;
mModelviewMatrixDirty = true;
}
void Camera::setLookAt(const Eigen::Vector3f& lookat)
{
mLookAt = lookat;
mModelviewMatrixDirty = true;
}
void Camera::setUp(const Eigen::Vector3f& up)
{
mUp = up;
mModelviewMatrixDirty = true;
}
void Camera::setDirection(const Eigen::Vector3f& dir)
{
setLookAt(mPosition + dir);
}
void Camera::setViewport(int x, int y, int width, int height)
{
mViewport[0] = x;
mViewport[1] = y;
mViewport[2] = width;
mViewport[3] = height;
}
void Camera::applyPerspective()
{
if (mProjectionMatrixDirty) {
recalculateProjectionMatrix();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMultMatrixf(mProjectionMatrix.data());
glMatrixMode(GL_MODELVIEW);
}
void Camera::applyView(bool reset)
{
if (mModelviewMatrixDirty) {
recalculateModelviewMatrix();
}
if (reset) {
glLoadIdentity();
}
glMultMatrixf(mModelviewMatrix.data());
}
void Camera::applyViewport()
{
glViewport(mViewport[0], mViewport[1], mViewport[2], mViewport[3]);
}
void Camera::recalculateModelviewMatrix()
{
// Code from Mesa project, src/glu/sgi/libutil/project.c
mModelviewMatrixDirty = false;
// Our looking direction
Eigen::Vector3f forward = (mLookAt - mPosition).normalized();
Eigen::Vector3f side = forward.cross(mUp).normalized();
// Recompute up vector, using cross product
Eigen::Vector3f up = side.cross(forward);
mModelviewMatrix.setIdentity();
mModelviewMatrix.linear() << side.transpose(), up.transpose(), -forward.transpose();
mModelviewMatrix.translate(-mPosition);
}
void Camera::recalculateProjectionMatrix()
{
// Code from Mesa project, src/glu/sgi/libutil/project.c
mProjectionMatrixDirty = false;
mProjectionMatrix.setIdentity();
float radians = mFoV / 2 * M_PI / 180;
float deltaZ = mDepthFar - mDepthNear;
float sine = Eigen::ei_sin(radians);
if ((deltaZ == 0) || (sine == 0) || (mAspect == 0)) {
return;
}
float cotangent = Eigen::ei_cos(radians) / sine;
mProjectionMatrix(0, 0) = cotangent / mAspect;
mProjectionMatrix(1, 1) = cotangent;
mProjectionMatrix(2, 2) = -(mDepthFar + mDepthNear) / deltaZ;
mProjectionMatrix(3, 2) = -1;
mProjectionMatrix(2, 3) = -2 * mDepthNear * mDepthFar / deltaZ;
mProjectionMatrix(3, 3) = 0;
}
void Camera::setModelviewMatrix(const Eigen::Transform3f& modelview)
{
mModelviewMatrix = modelview;
mModelviewMatrixDirty = false;
}
void Camera::setProjectionMatrix(const Eigen::Transform3f& projection)
{
mProjectionMatrix = projection;
mProjectionMatrixDirty = false;
}
Eigen::Transform3f Camera::modelviewMatrix() const
{
if (mModelviewMatrixDirty) {
const_cast<Camera*>(this)->recalculateModelviewMatrix();
}
return mModelviewMatrix;
}
Eigen::Transform3f Camera::projectionMatrix() const
{
if (mProjectionMatrixDirty) {
const_cast<Camera*>(this)->recalculateProjectionMatrix();
}
return mProjectionMatrix;
}
Eigen::Vector3f Camera::project(const Eigen::Vector3f& v, bool* ok) const
{
// TODO add unit test
Eigen::Vector3f res;
Eigen::Vector4f p4 = projectionMatrix() * (modelviewMatrix() * Eigen::Vector4f(v[0],v[1],v[2],1));
if (p4.w()!=0)
{
res = p4.start<3>() / p4.w();
res = (res * 0.5).cwise() + 0.5;
res.start<2>() = Eigen::Vector2f(mViewport[0],mViewport[1])
+ Eigen::Vector2f(mViewport[2],mViewport[3]).cwise() * res.start<2>();
if (ok)
*ok = true;
}
else if (ok)
*ok = false;
return res;
}
Eigen::Vector3f Camera::unProject(const Eigen::Vector3f& v, bool* ok) const
{
// TODO add unit test
if (ok) *ok = true;
Eigen::Vector4f a;
a << (v.start<2>() - Eigen::Vector2f(mViewport[0],mViewport[1]))
.cwise() / Eigen::Vector2f(mViewport[2],mViewport[3]),
v.z(),
1;
a.start<3>() = a.start<3>() * 2 - Eigen::Vector3f::Constant(1);
// FIXME if we assume the projection matrix always has the structure defined in
// recalculateProjectionMatrix, then the following matrix product could be
// significantly improved !!
a = (projectionMatrix() * modelviewMatrix()).inverse() * a;
if (a.w()==0)
{
if (ok) *ok = false;
return a.start<3>();
}
return a.start<3>() / a.w();
}
<commit_msg>Fix an undfeined reference due to failing to include an Eigen include<commit_after>#include "camera.h"
#include <math.h>
#include <glew.h>
#include <Eigen/LU>
using namespace GluonGraphics;
Camera::Camera()
{
mFoV = 45.0f;
mAspect = 1.0f;
mDepthNear = 1.0f;
mDepthFar = 100.0f;
mPosition = Eigen::Vector3f(-10, 0, 10);
mLookAt = Eigen::Vector3f(0, 0, 0);
mUp = Eigen::Vector3f(0, 1, 0);
mModelviewMatrixDirty = true;
mProjectionMatrixDirty = true;
}
Camera::~Camera()
{
}
void Camera::setFoV(float fov)
{
mFoV = fov;
mProjectionMatrixDirty = true;
}
void Camera::setAspect(float aspect)
{
mAspect = aspect;
mProjectionMatrixDirty = true;
}
void Camera::setDepthRange(float near, float far)
{
mDepthNear = near;
mDepthFar = far;
mProjectionMatrixDirty = true;
}
void Camera::setPosition(const Eigen::Vector3f& pos)
{
mPosition = pos;
mModelviewMatrixDirty = true;
}
void Camera::setLookAt(const Eigen::Vector3f& lookat)
{
mLookAt = lookat;
mModelviewMatrixDirty = true;
}
void Camera::setUp(const Eigen::Vector3f& up)
{
mUp = up;
mModelviewMatrixDirty = true;
}
void Camera::setDirection(const Eigen::Vector3f& dir)
{
setLookAt(mPosition + dir);
}
void Camera::setViewport(int x, int y, int width, int height)
{
mViewport[0] = x;
mViewport[1] = y;
mViewport[2] = width;
mViewport[3] = height;
}
void Camera::applyPerspective()
{
if (mProjectionMatrixDirty) {
recalculateProjectionMatrix();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMultMatrixf(mProjectionMatrix.data());
glMatrixMode(GL_MODELVIEW);
}
void Camera::applyView(bool reset)
{
if (mModelviewMatrixDirty) {
recalculateModelviewMatrix();
}
if (reset) {
glLoadIdentity();
}
glMultMatrixf(mModelviewMatrix.data());
}
void Camera::applyViewport()
{
glViewport(mViewport[0], mViewport[1], mViewport[2], mViewport[3]);
}
void Camera::recalculateModelviewMatrix()
{
// Code from Mesa project, src/glu/sgi/libutil/project.c
mModelviewMatrixDirty = false;
// Our looking direction
Eigen::Vector3f forward = (mLookAt - mPosition).normalized();
Eigen::Vector3f side = forward.cross(mUp).normalized();
// Recompute up vector, using cross product
Eigen::Vector3f up = side.cross(forward);
mModelviewMatrix.setIdentity();
mModelviewMatrix.linear() << side.transpose(), up.transpose(), -forward.transpose();
mModelviewMatrix.translate(-mPosition);
}
void Camera::recalculateProjectionMatrix()
{
// Code from Mesa project, src/glu/sgi/libutil/project.c
mProjectionMatrixDirty = false;
mProjectionMatrix.setIdentity();
float radians = mFoV / 2 * M_PI / 180;
float deltaZ = mDepthFar - mDepthNear;
float sine = Eigen::ei_sin(radians);
if ((deltaZ == 0) || (sine == 0) || (mAspect == 0)) {
return;
}
float cotangent = Eigen::ei_cos(radians) / sine;
mProjectionMatrix(0, 0) = cotangent / mAspect;
mProjectionMatrix(1, 1) = cotangent;
mProjectionMatrix(2, 2) = -(mDepthFar + mDepthNear) / deltaZ;
mProjectionMatrix(3, 2) = -1;
mProjectionMatrix(2, 3) = -2 * mDepthNear * mDepthFar / deltaZ;
mProjectionMatrix(3, 3) = 0;
}
void Camera::setModelviewMatrix(const Eigen::Transform3f& modelview)
{
mModelviewMatrix = modelview;
mModelviewMatrixDirty = false;
}
void Camera::setProjectionMatrix(const Eigen::Transform3f& projection)
{
mProjectionMatrix = projection;
mProjectionMatrixDirty = false;
}
Eigen::Transform3f Camera::modelviewMatrix() const
{
if (mModelviewMatrixDirty) {
const_cast<Camera*>(this)->recalculateModelviewMatrix();
}
return mModelviewMatrix;
}
Eigen::Transform3f Camera::projectionMatrix() const
{
if (mProjectionMatrixDirty) {
const_cast<Camera*>(this)->recalculateProjectionMatrix();
}
return mProjectionMatrix;
}
Eigen::Vector3f Camera::project(const Eigen::Vector3f& v, bool* ok) const
{
// TODO add unit test
Eigen::Vector3f res;
Eigen::Vector4f p4 = projectionMatrix() * (modelviewMatrix() * Eigen::Vector4f(v[0],v[1],v[2],1));
if (p4.w()!=0)
{
res = p4.start<3>() / p4.w();
res = (res * 0.5).cwise() + 0.5;
res.start<2>() = Eigen::Vector2f(mViewport[0],mViewport[1])
+ Eigen::Vector2f(mViewport[2],mViewport[3]).cwise() * res.start<2>();
if (ok)
*ok = true;
}
else if (ok)
*ok = false;
return res;
}
Eigen::Vector3f Camera::unProject(const Eigen::Vector3f& v, bool* ok) const
{
// TODO add unit test
if (ok) *ok = true;
Eigen::Vector4f a;
a << (v.start<2>() - Eigen::Vector2f(mViewport[0],mViewport[1]))
.cwise() / Eigen::Vector2f(mViewport[2],mViewport[3]),
v.z(),
1;
a.start<3>() = a.start<3>() * 2 - Eigen::Vector3f::Constant(1);
// FIXME if we assume the projection matrix always has the structure defined in
// recalculateProjectionMatrix, then the following matrix product could be
// significantly improved !!
a = (projectionMatrix() * modelviewMatrix()).inverse() * a;
if (a.w()==0)
{
if (ok) *ok = false;
return a.start<3>();
}
return a.start<3>() / a.w();
}
#include "camera.moc"
<|endoftext|>
|
<commit_before>#ifndef ___INANITY_GRAPHICS_OPENGL_HPP___
#define ___INANITY_GRAPHICS_OPENGL_HPP___
#include "../Object.hpp"
#ifdef ___INANITY_WINDOWS
#define GLEW_STATIC
#include "../deps/glew/include/GL/glew.h"
#include "../windows.hpp"
#include "../deps/glew/include/GL/wglew.h"
#endif
#ifdef ___INANITY_LINUX
#include <GL/glew.h>
//#include "../deps/glew/include/GL/glxew.h"
#include <GL/glxew.h>
#endif
#include <GL/gl.h>
#endif
<commit_msg>always use static GLEW<commit_after>#ifndef ___INANITY_GRAPHICS_OPENGL_HPP___
#define ___INANITY_GRAPHICS_OPENGL_HPP___
#include "../Object.hpp"
#define GLEW_STATIC
#include "../deps/glew/include/GL/glew.h"
#ifdef ___INANITY_WINDOWS
#include "../windows.hpp"
#include "../deps/glew/include/GL/wglew.h"
#endif
#ifdef ___INANITY_LINUX
#include "../deps/glew/include/GL/glxew.h"
#endif
#include <GL/gl.h>
#endif
<|endoftext|>
|
<commit_before>/**
* \file
* \brief MessageQueue class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-01-14
*/
#ifndef INCLUDE_DISTORTOS_MESSAGEQUEUE_HPP_
#define INCLUDE_DISTORTOS_MESSAGEQUEUE_HPP_
#include "distortos/synchronization/MessageQueueBase.hpp"
#include "distortos/synchronization/SemaphoreWaitFunctor.hpp"
namespace distortos
{
/// GCC 4.9 is needed for all MessageQueue::*emplace*() functions - earlier versions don't support parameter pack
/// expansion in lambdas
#define DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED __GNUC_PREREQ(4, 9)
/**
* \brief MessageQueue class is a message queue for thread-thread, thread-interrupt or interrupt-interrupt
* communication. It supports multiple readers and multiple writers. It is implemented as a wrapper for
* synchronization::MessageQueueBase.
*
* Similar to POSIX mqd_t - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/mqueue.h.html
*
* \param T is the type of data in queue
*/
template<typename T>
class MessageQueue
{
public:
/// type of uninitialized storage for data
using Storage = synchronization::MessageQueueBase::Storage<T>;
/**
* \brief MessageQueue's constructor
*
* \param [in] storage is an array of Storage elements
* \param [in] maxElements is the number of elements in storage array
*/
MessageQueue(Storage* const storage, const size_t maxElements) :
messageQueueBase_{storage, maxElements}
{
}
#if DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Emplaces the element in the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \note This function requires GCC 4.9.
*
* \param Args are types of arguments for constructor of T
*
* \param [in] priority is the priority of new element
* \param [in] args are arguments for constructor of T
*
* \return zero if element was emplaced successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
template<typename... Args>
int emplace(const uint8_t priority, Args&&... args)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return emplaceInternal(semaphoreWaitFunctor, priority, std::forward<Args>(args)...);
}
#endif // DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Pops oldest element with highest priority from the queue.
*
* Similar to mq_receive() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_receive.html#
*
* \param [out] priority is a reference to variable that will be used to return priority of popped value
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int pop(uint8_t& priority, T& value)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return popInternal(semaphoreWaitFunctor, priority, value);
}
/**
* \brief Pushes the element to the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \param [in] priority is the priority of new element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const uint8_t priority, const T& value)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return pushInternal(semaphoreWaitFunctor, priority, value);
}
/**
* \brief Pushes the element to the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \param [in] priority is the priority of new element
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const uint8_t priority, T&& value)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return pushInternal(semaphoreWaitFunctor, priority, std::move(value));
}
private:
/**
* \brief BoundedFunctor is a type-erased synchronization::MessageQueueBase::Functor which calls its bounded functor
* to execute actions on queue's storage
*
* \param F is the type of bounded functor, it will be called with <em>void*</em> as only argument
*/
template<typename F>
class BoundedFunctor : public synchronization::MessageQueueBase::Functor
{
public:
/**
* \brief BoundedFunctor's constructor
*
* \param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct
* internal bounded functor
*/
constexpr explicit BoundedFunctor(F&& boundedFunctor) :
boundedFunctor_{std::move(boundedFunctor)}
{
}
/**
* \brief Calls the bounded functor which will execute some action on queue's storage (like copy-constructing,
* swapping, destroying, emplacing, ...)
*
* \param [in,out] storage is a pointer to storage with/for element
*/
virtual void operator()(void* storage) const override
{
boundedFunctor_(storage);
}
private:
/// bounded functor
F boundedFunctor_;
};
/**
* \brief Helper factory function to make BoundedFunctor object with partially deduced template arguments
*
* \param F is the type of bounded functor, it will be called with <em>void*</em> as only argument
*
* \param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct internal
* bounded functor
*
* \return BoundedFunctor object with partially deduced template arguments
*/
template<typename F>
constexpr static BoundedFunctor<F> makeBoundedFunctor(F&& boundedFunctor)
{
return BoundedFunctor<F>{std::move(boundedFunctor)};
}
#if DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Emplaces the element in the queue.
*
* Internal version - builds the Functor object.
*
* \note This function requires GCC 4.9.
*
* \param Args are types of arguments for constructor of T
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] priority is the priority of new element
* \param [in] args are arguments for constructor of T
*
* \return zero if element was emplaced successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
template<typename... Args>
int emplaceInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority,
Args&&... args);
#endif // DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Pops oldest element with highest priority from the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
* \param [out] priority is a reference to variable that will be used to return priority of popped value
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int popInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, T& value);
/**
* \brief Pushes the element to the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] priority is the priority of new element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const T& value);
/**
* \brief Pushes the element to the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] priority is the priority of new element
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, T&& value);
/// contained synchronization::MessageQueueBase object which implements whole functionality
synchronization::MessageQueueBase messageQueueBase_;
};
#if DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
template<typename T>
template<typename... Args>
int MessageQueue<T>::emplaceInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor,
const uint8_t priority, Args&&... args)
{
const auto emplaceFunctor = makeBoundedFunctor(
[&args...](void* const storage)
{
new (storage) T{std::forward<Args>(args)...};
});
return messageQueueBase_.push(waitSemaphoreFunctor, priority, emplaceFunctor);
}
#endif // DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
template<typename T>
int MessageQueue<T>::popInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority,
T& value)
{
const auto swapFunctor = makeBoundedFunctor(
[&value](void* const storage)
{
auto& swappedValue = *reinterpret_cast<T*>(storage);
using std::swap;
swap(value, swappedValue);
swappedValue.~T();
});
return messageQueueBase_.pop(waitSemaphoreFunctor, priority, swapFunctor);
}
template<typename T>
int MessageQueue<T>::pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, const uint8_t priority,
const T& value)
{
const auto copyFunctor = makeBoundedFunctor(
[&value](void* const storage)
{
new (storage) T{value};
});
return messageQueueBase_.push(waitSemaphoreFunctor, priority, copyFunctor);
}
template<typename T>
int MessageQueue<T>::pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, const uint8_t priority,
T&& value)
{
const auto moveFunctor = makeBoundedFunctor(
[&value](void* const storage)
{
new (storage) T{std::move(value)};
});
return messageQueueBase_.push(waitSemaphoreFunctor, priority, moveFunctor);
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_MESSAGEQUEUE_HPP_
<commit_msg>MessageQueue: add MessageQueue::tryPush(..., const T&)<commit_after>/**
* \file
* \brief MessageQueue class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-01-14
*/
#ifndef INCLUDE_DISTORTOS_MESSAGEQUEUE_HPP_
#define INCLUDE_DISTORTOS_MESSAGEQUEUE_HPP_
#include "distortos/synchronization/MessageQueueBase.hpp"
#include "distortos/synchronization/SemaphoreWaitFunctor.hpp"
#include "distortos/synchronization/SemaphoreTryWaitFunctor.hpp"
namespace distortos
{
/// GCC 4.9 is needed for all MessageQueue::*emplace*() functions - earlier versions don't support parameter pack
/// expansion in lambdas
#define DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED __GNUC_PREREQ(4, 9)
/**
* \brief MessageQueue class is a message queue for thread-thread, thread-interrupt or interrupt-interrupt
* communication. It supports multiple readers and multiple writers. It is implemented as a wrapper for
* synchronization::MessageQueueBase.
*
* Similar to POSIX mqd_t - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/mqueue.h.html
*
* \param T is the type of data in queue
*/
template<typename T>
class MessageQueue
{
public:
/// type of uninitialized storage for data
using Storage = synchronization::MessageQueueBase::Storage<T>;
/**
* \brief MessageQueue's constructor
*
* \param [in] storage is an array of Storage elements
* \param [in] maxElements is the number of elements in storage array
*/
MessageQueue(Storage* const storage, const size_t maxElements) :
messageQueueBase_{storage, maxElements}
{
}
#if DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Emplaces the element in the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \note This function requires GCC 4.9.
*
* \param Args are types of arguments for constructor of T
*
* \param [in] priority is the priority of new element
* \param [in] args are arguments for constructor of T
*
* \return zero if element was emplaced successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
template<typename... Args>
int emplace(const uint8_t priority, Args&&... args)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return emplaceInternal(semaphoreWaitFunctor, priority, std::forward<Args>(args)...);
}
#endif // DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Pops oldest element with highest priority from the queue.
*
* Similar to mq_receive() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_receive.html#
*
* \param [out] priority is a reference to variable that will be used to return priority of popped value
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int pop(uint8_t& priority, T& value)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return popInternal(semaphoreWaitFunctor, priority, value);
}
/**
* \brief Pushes the element to the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \param [in] priority is the priority of new element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const uint8_t priority, const T& value)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return pushInternal(semaphoreWaitFunctor, priority, value);
}
/**
* \brief Pushes the element to the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \param [in] priority is the priority of new element
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const uint8_t priority, T&& value)
{
const synchronization::SemaphoreWaitFunctor semaphoreWaitFunctor;
return pushInternal(semaphoreWaitFunctor, priority, std::move(value));
}
/**
* \brief Tries to push the element to the queue.
*
* Similar to mq_send() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html#
*
* \param [in] priority is the priority of new element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(const uint8_t priority, const T& value)
{
const synchronization::SemaphoreTryWaitFunctor semaphoreTryWaitFunctor;
return pushInternal(semaphoreTryWaitFunctor, priority, value);
}
private:
/**
* \brief BoundedFunctor is a type-erased synchronization::MessageQueueBase::Functor which calls its bounded functor
* to execute actions on queue's storage
*
* \param F is the type of bounded functor, it will be called with <em>void*</em> as only argument
*/
template<typename F>
class BoundedFunctor : public synchronization::MessageQueueBase::Functor
{
public:
/**
* \brief BoundedFunctor's constructor
*
* \param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct
* internal bounded functor
*/
constexpr explicit BoundedFunctor(F&& boundedFunctor) :
boundedFunctor_{std::move(boundedFunctor)}
{
}
/**
* \brief Calls the bounded functor which will execute some action on queue's storage (like copy-constructing,
* swapping, destroying, emplacing, ...)
*
* \param [in,out] storage is a pointer to storage with/for element
*/
virtual void operator()(void* storage) const override
{
boundedFunctor_(storage);
}
private:
/// bounded functor
F boundedFunctor_;
};
/**
* \brief Helper factory function to make BoundedFunctor object with partially deduced template arguments
*
* \param F is the type of bounded functor, it will be called with <em>void*</em> as only argument
*
* \param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct internal
* bounded functor
*
* \return BoundedFunctor object with partially deduced template arguments
*/
template<typename F>
constexpr static BoundedFunctor<F> makeBoundedFunctor(F&& boundedFunctor)
{
return BoundedFunctor<F>{std::move(boundedFunctor)};
}
#if DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Emplaces the element in the queue.
*
* Internal version - builds the Functor object.
*
* \note This function requires GCC 4.9.
*
* \param Args are types of arguments for constructor of T
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] priority is the priority of new element
* \param [in] args are arguments for constructor of T
*
* \return zero if element was emplaced successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
template<typename... Args>
int emplaceInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority,
Args&&... args);
#endif // DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
/**
* \brief Pops oldest element with highest priority from the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
* \param [out] priority is a reference to variable that will be used to return priority of popped value
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int popInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, T& value);
/**
* \brief Pushes the element to the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] priority is the priority of new element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const T& value);
/**
* \brief Pushes the element to the queue.
*
* Internal version - builds the Functor object.
*
* \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
* \param [in] priority is the priority of new element
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by \a waitSemaphoreFunctor's operator() call;
* - error codes returned by Semaphore::post();
*/
int pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, T&& value);
/// contained synchronization::MessageQueueBase object which implements whole functionality
synchronization::MessageQueueBase messageQueueBase_;
};
#if DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
template<typename T>
template<typename... Args>
int MessageQueue<T>::emplaceInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor,
const uint8_t priority, Args&&... args)
{
const auto emplaceFunctor = makeBoundedFunctor(
[&args...](void* const storage)
{
new (storage) T{std::forward<Args>(args)...};
});
return messageQueueBase_.push(waitSemaphoreFunctor, priority, emplaceFunctor);
}
#endif // DISTORTOS_MESSAGEQUEUE_EMPLACE_SUPPORTED == 1 || DOXYGEN == 1
template<typename T>
int MessageQueue<T>::popInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority,
T& value)
{
const auto swapFunctor = makeBoundedFunctor(
[&value](void* const storage)
{
auto& swappedValue = *reinterpret_cast<T*>(storage);
using std::swap;
swap(value, swappedValue);
swappedValue.~T();
});
return messageQueueBase_.pop(waitSemaphoreFunctor, priority, swapFunctor);
}
template<typename T>
int MessageQueue<T>::pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, const uint8_t priority,
const T& value)
{
const auto copyFunctor = makeBoundedFunctor(
[&value](void* const storage)
{
new (storage) T{value};
});
return messageQueueBase_.push(waitSemaphoreFunctor, priority, copyFunctor);
}
template<typename T>
int MessageQueue<T>::pushInternal(const synchronization::SemaphoreFunctor& waitSemaphoreFunctor, const uint8_t priority,
T&& value)
{
const auto moveFunctor = makeBoundedFunctor(
[&value](void* const storage)
{
new (storage) T{std::move(value)};
});
return messageQueueBase_.push(waitSemaphoreFunctor, priority, moveFunctor);
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_MESSAGEQUEUE_HPP_
<|endoftext|>
|
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen 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 details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SocketListener.hpp"
#include "Engine.hpp"
#include "SocketServer.hpp"
#include "ingen/Configuration.hpp"
#include "ingen/Log.hpp"
#include "ingen/World.hpp"
#include "raul/Socket.hpp"
#include <poll.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <string>
#include <thread>
namespace ingen {
namespace server {
static constexpr const char* const unix_scheme = "unix://";
static std::string
get_link_target(const char* link_path)
{
// Stat the link to get the required size for the target path
struct stat link_stat{};
if (lstat(link_path, &link_stat)) {
return std::string();
}
// Allocate buffer and read link target
char* target = (char*)calloc(1, link_stat.st_size + 1);
if (readlink(link_path, target, link_stat.st_size) != -1) {
const std::string result(target);
free(target);
return result;
}
return std::string();
}
static void ingen_listen(Engine* engine,
Raul::Socket* unix_sock,
Raul::Socket* net_sock);
SocketListener::SocketListener(Engine& engine)
: unix_sock(Raul::Socket::Type::UNIX)
, net_sock(Raul::Socket::Type::TCP)
, thread(new std::thread(ingen_listen, &engine, &unix_sock, &net_sock))
{}
SocketListener::~SocketListener() {
unix_sock.shutdown();
net_sock.shutdown();
thread->join();
unlink(unix_sock.uri().substr(strlen(unix_scheme)).c_str());
}
static void
ingen_listen(Engine* engine, Raul::Socket* unix_sock, Raul::Socket* net_sock)
{
ingen::World& world = engine->world();
const std::string link_path(world.conf().option("socket").ptr<char>());
const std::string unix_path(link_path + "." + std::to_string(getpid()));
// Bind UNIX socket and create PID-less symbolic link
const URI unix_uri(unix_scheme + unix_path);
bool make_link = true;
if (!unix_sock->bind(unix_uri) || !unix_sock->listen()) {
world.log().error("Failed to create UNIX socket\n");
unix_sock->close();
make_link = false;
} else {
const std::string old_path = get_link_target(link_path.c_str());
if (!old_path.empty()) {
const std::string suffix = old_path.substr(old_path.find_last_of('.') + 1);
const pid_t pid = std::stoi(suffix);
if (!kill(pid, 0)) {
make_link = false;
world.log().warn(
"Another Ingen instance is running at %1% => %2%\n",
link_path, old_path);
} else {
world.log().warn("Replacing old link %1% => %2%\n",
link_path, old_path);
unlink(link_path.c_str());
}
}
if (make_link) {
if (!symlink(unix_path.c_str(), link_path.c_str())) {
world.log().info("Listening on %1%\n",
(unix_scheme + link_path));
} else {
world.log().error("Failed to link %1% => %2% (%3%)\n",
link_path, unix_path, strerror(errno));
}
} else {
world.log().info("Listening on %1%\n", unix_uri);
}
}
// Bind TCP socket
const int port = world.conf().option("engine-port").get<int32_t>();
std::ostringstream ss;
ss << "tcp://*:" << port;
if (!net_sock->bind(URI(ss.str())) || !net_sock->listen()) {
world.log().error("Failed to create TCP socket\n");
net_sock->close();
} else {
world.log().info("Listening on TCP port %1%\n", port);
}
if (unix_sock->fd() == -1 && net_sock->fd() == -1) {
return; // No sockets to listen to, exit thread
}
struct pollfd pfds[2];
int nfds = 0;
if (unix_sock->fd() != -1) {
pfds[nfds].fd = unix_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
if (net_sock->fd() != -1) {
pfds[nfds].fd = net_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
while (true) {
// Wait for input to arrive at a socket
const int ret = poll(pfds, nfds, -1);
if (ret == -1) {
world.log().error("Poll error: %1%\n", strerror(errno));
break;
} else if (ret == 0) {
world.log().warn("Poll returned with no data\n");
continue;
} else if ((pfds[0].revents & POLLHUP) || pfds[1].revents & POLLHUP) {
break;
}
if (pfds[0].revents & POLLIN) {
SPtr<Raul::Socket> conn = unix_sock->accept();
if (conn) {
new SocketServer(world, *engine, conn);
}
}
if (pfds[1].revents & POLLIN) {
SPtr<Raul::Socket> conn = net_sock->accept();
if (conn) {
new SocketServer(world, *engine, conn);
}
}
}
if (make_link) {
unlink(link_path.c_str());
}
}
} // namespace server
} // namespace ingen
<commit_msg>Cleanup: Fix potential memory leak<commit_after>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen 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 details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SocketListener.hpp"
#include "Engine.hpp"
#include "SocketServer.hpp"
#include "ingen/Configuration.hpp"
#include "ingen/Log.hpp"
#include "ingen/World.hpp"
#include "raul/Socket.hpp"
#include <poll.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <string>
#include <thread>
namespace ingen {
namespace server {
static constexpr const char* const unix_scheme = "unix://";
static std::string
get_link_target(const char* link_path)
{
// Stat the link to get the required size for the target path
struct stat link_stat{};
if (lstat(link_path, &link_stat)) {
return std::string();
}
// Allocate buffer and read link target
char* target = (char*)calloc(1, link_stat.st_size + 1);
if (readlink(link_path, target, link_stat.st_size) != -1) {
const std::string result(target);
free(target);
return result;
}
free(target);
return std::string();
}
static void ingen_listen(Engine* engine,
Raul::Socket* unix_sock,
Raul::Socket* net_sock);
SocketListener::SocketListener(Engine& engine)
: unix_sock(Raul::Socket::Type::UNIX)
, net_sock(Raul::Socket::Type::TCP)
, thread(new std::thread(ingen_listen, &engine, &unix_sock, &net_sock))
{}
SocketListener::~SocketListener() {
unix_sock.shutdown();
net_sock.shutdown();
thread->join();
unlink(unix_sock.uri().substr(strlen(unix_scheme)).c_str());
}
static void
ingen_listen(Engine* engine, Raul::Socket* unix_sock, Raul::Socket* net_sock)
{
ingen::World& world = engine->world();
const std::string link_path(world.conf().option("socket").ptr<char>());
const std::string unix_path(link_path + "." + std::to_string(getpid()));
// Bind UNIX socket and create PID-less symbolic link
const URI unix_uri(unix_scheme + unix_path);
bool make_link = true;
if (!unix_sock->bind(unix_uri) || !unix_sock->listen()) {
world.log().error("Failed to create UNIX socket\n");
unix_sock->close();
make_link = false;
} else {
const std::string old_path = get_link_target(link_path.c_str());
if (!old_path.empty()) {
const std::string suffix = old_path.substr(old_path.find_last_of('.') + 1);
const pid_t pid = std::stoi(suffix);
if (!kill(pid, 0)) {
make_link = false;
world.log().warn(
"Another Ingen instance is running at %1% => %2%\n",
link_path, old_path);
} else {
world.log().warn("Replacing old link %1% => %2%\n",
link_path, old_path);
unlink(link_path.c_str());
}
}
if (make_link) {
if (!symlink(unix_path.c_str(), link_path.c_str())) {
world.log().info("Listening on %1%\n",
(unix_scheme + link_path));
} else {
world.log().error("Failed to link %1% => %2% (%3%)\n",
link_path, unix_path, strerror(errno));
}
} else {
world.log().info("Listening on %1%\n", unix_uri);
}
}
// Bind TCP socket
const int port = world.conf().option("engine-port").get<int32_t>();
std::ostringstream ss;
ss << "tcp://*:" << port;
if (!net_sock->bind(URI(ss.str())) || !net_sock->listen()) {
world.log().error("Failed to create TCP socket\n");
net_sock->close();
} else {
world.log().info("Listening on TCP port %1%\n", port);
}
if (unix_sock->fd() == -1 && net_sock->fd() == -1) {
return; // No sockets to listen to, exit thread
}
struct pollfd pfds[2];
int nfds = 0;
if (unix_sock->fd() != -1) {
pfds[nfds].fd = unix_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
if (net_sock->fd() != -1) {
pfds[nfds].fd = net_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
while (true) {
// Wait for input to arrive at a socket
const int ret = poll(pfds, nfds, -1);
if (ret == -1) {
world.log().error("Poll error: %1%\n", strerror(errno));
break;
} else if (ret == 0) {
world.log().warn("Poll returned with no data\n");
continue;
} else if ((pfds[0].revents & POLLHUP) || pfds[1].revents & POLLHUP) {
break;
}
if (pfds[0].revents & POLLIN) {
SPtr<Raul::Socket> conn = unix_sock->accept();
if (conn) {
new SocketServer(world, *engine, conn);
}
}
if (pfds[1].revents & POLLIN) {
SPtr<Raul::Socket> conn = net_sock->accept();
if (conn) {
new SocketServer(world, *engine, conn);
}
}
}
if (make_link) {
unlink(link_path.c_str());
}
}
} // namespace server
} // namespace ingen
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file expression_helpers.hpp
* \brief Contains internal helpers to build expressions.
*/
#pragma once
namespace etl {
namespace detail {
template<typename T>
using build_type = std::conditional_t<
is_etl_value<T>::value,
const std::decay_t<T>&,
std::decay_t<T>>;
template<typename T>
using build_identity_type = std::conditional_t<
is_etl_value<T>::value,
std::conditional_t<
std::is_const<std::remove_reference_t<T>>::value,
const std::decay_t<T>&,
std::decay_t<T>&>,
std::decay_t<T>>;
template<typename LE, typename RE, template<typename> class OP>
using left_binary_helper = binary_expr<value_t<LE>, build_type<LE>, OP<value_t<LE>>, build_type<RE>>;
template<typename LE, typename RE, typename OP>
using left_binary_helper_op = binary_expr<value_t<LE>, build_type<LE>, OP, build_type<RE>>;
template<typename LE, typename RE, template<typename> class OP>
using right_binary_helper = binary_expr<value_t<RE>, build_type<LE>, OP<value_t<RE>>, build_type<RE>>;
template<typename E, template<typename> class OP>
using unary_helper = unary_expr<value_t<E>, build_type<E>, OP<value_t<E>>>;
template<typename E, typename OP>
using identity_helper = unary_expr<value_t<E>, OP, identity_op>;
template<typename E, typename OP>
using virtual_helper = unary_expr<E, OP, transform_op>;
template<typename E, template<typename> class OP>
using stable_transform_helper = unary_expr<value_t<E>, OP<build_type<E>>, transform_op>;
template<typename LE, typename RE, template<typename,typename> class OP>
using stable_transform_binary_helper = unary_expr<value_t<LE>, OP<build_type<LE>, build_type<RE>>, transform_op>;
template<typename E, template<typename> class OP, typename... Args>
auto make_transform_expr(Args&&... args){
return detail::stable_transform_helper<E, OP>{OP<detail::build_type<E>>(std::forward<Args>(args)...)};
}
template<typename E, typename OP, typename... Args>
auto make_stateful_unary_expr(Args&&... args){
return unary_expr<value_t<E>, build_type<E>, stateful_op<OP>>(std::forward<Args>(args)...);
}
template<typename A, typename B, template<typename> class OP>
using temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>>, void>;
template<typename A, template<typename> class OP>
using temporary_unary_helper = temporary_unary_expr<value_t<A>, build_type<A>, OP<value_t<A>>, void>;
template<typename T, typename A, template<typename> class OP>
using temporary_unary_helper_type = temporary_unary_expr<T, build_type<A>, OP<T>, void>;
template<typename A, typename B, typename C, template<typename> class OP>
using forced_temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>>, build_identity_type<C>>;
template<typename A, typename C, template<typename> class OP>
using forced_temporary_unary_helper = temporary_unary_expr<value_t<A>, build_type<A>, OP<value_t<A>>, build_identity_type<C>>;
template<typename T, typename A, typename C, template<typename> class OP>
using forced_temporary_unary_helper_type = temporary_unary_expr<T, build_type<A>, OP<T>, build_identity_type<C>>;
template<typename A, typename B, template<typename, std::size_t> class OP, std::size_t D>
using dim_temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>, D>, void>;
template<typename A, typename B, typename C, template<typename, std::size_t> class OP, std::size_t D>
using dim_forced_temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>, D>, build_identity_type<C>>;
} //end of namespace detail
} //end of namespace etl
<commit_msg>New helper<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file expression_helpers.hpp
* \brief Contains internal helpers to build expressions.
*/
#pragma once
namespace etl {
namespace detail {
template<typename T>
using build_type = std::conditional_t<
is_etl_value<T>::value,
const std::decay_t<T>&,
std::decay_t<T>>;
template<typename T>
using build_identity_type = std::conditional_t<
is_etl_value<T>::value,
std::conditional_t<
std::is_const<std::remove_reference_t<T>>::value,
const std::decay_t<T>&,
std::decay_t<T>&>,
std::decay_t<T>>;
template<typename LE, typename RE, template<typename> class OP>
using left_binary_helper = binary_expr<value_t<LE>, build_type<LE>, OP<value_t<LE>>, build_type<RE>>;
template<typename LE, typename RE, typename OP>
using left_binary_helper_op = binary_expr<value_t<LE>, build_type<LE>, OP, build_type<RE>>;
template<typename LE, typename RE, template<typename> class OP>
using right_binary_helper = binary_expr<value_t<RE>, build_type<LE>, OP<value_t<RE>>, build_type<RE>>;
template<typename LE, typename RE, typename OP>
using right_binary_helper_op = binary_expr<value_t<RE>, build_type<LE>, OP, build_type<RE>>;
template<typename E, template<typename> class OP>
using unary_helper = unary_expr<value_t<E>, build_type<E>, OP<value_t<E>>>;
template<typename E, typename OP>
using identity_helper = unary_expr<value_t<E>, OP, identity_op>;
template<typename E, typename OP>
using virtual_helper = unary_expr<E, OP, transform_op>;
template<typename E, template<typename> class OP>
using stable_transform_helper = unary_expr<value_t<E>, OP<build_type<E>>, transform_op>;
template<typename LE, typename RE, template<typename,typename> class OP>
using stable_transform_binary_helper = unary_expr<value_t<LE>, OP<build_type<LE>, build_type<RE>>, transform_op>;
template<typename E, template<typename> class OP, typename... Args>
auto make_transform_expr(Args&&... args){
return detail::stable_transform_helper<E, OP>{OP<detail::build_type<E>>(std::forward<Args>(args)...)};
}
template<typename E, typename OP, typename... Args>
auto make_stateful_unary_expr(Args&&... args){
return unary_expr<value_t<E>, build_type<E>, stateful_op<OP>>(std::forward<Args>(args)...);
}
template<typename A, typename B, template<typename> class OP>
using temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>>, void>;
template<typename A, template<typename> class OP>
using temporary_unary_helper = temporary_unary_expr<value_t<A>, build_type<A>, OP<value_t<A>>, void>;
template<typename T, typename A, template<typename> class OP>
using temporary_unary_helper_type = temporary_unary_expr<T, build_type<A>, OP<T>, void>;
template<typename A, typename B, typename C, template<typename> class OP>
using forced_temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>>, build_identity_type<C>>;
template<typename A, typename C, template<typename> class OP>
using forced_temporary_unary_helper = temporary_unary_expr<value_t<A>, build_type<A>, OP<value_t<A>>, build_identity_type<C>>;
template<typename T, typename A, typename C, template<typename> class OP>
using forced_temporary_unary_helper_type = temporary_unary_expr<T, build_type<A>, OP<T>, build_identity_type<C>>;
template<typename A, typename B, template<typename, std::size_t> class OP, std::size_t D>
using dim_temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>, D>, void>;
template<typename A, typename B, typename C, template<typename, std::size_t> class OP, std::size_t D>
using dim_forced_temporary_binary_helper = temporary_binary_expr<value_t<A>, build_type<A>, build_type<B>, OP<value_t<A>, D>, build_identity_type<C>>;
} //end of namespace detail
} //end of namespace etl
<|endoftext|>
|
<commit_before>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* 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.
*/
#ifndef FMICPP_FMU_HPP
#define FMICPP_FMU_HPP
#include <memory>
#include <vector>
#include <boost/filesystem.hpp>
#include "../xml/ModelDescription.hpp"
namespace fs = boost::filesystem;
using std::string;
using std::unique_ptr;
using fmicpp::fmi2::xml::ModelDescription;
namespace fmicpp::fmi2::import {
class CoSimulationSlaveBuilder;
class ModelExchangeInstanceBuilder;
class Fmu {
friend class CoSimulationSlaveBuilder;
friend class ModelExchangeInstanceBuilder;
public:
explicit Fmu(const string &fmu_file);
const string getGuid() const;
const string getModelName() const;
const string getModelDescriptionXml() const;
const ModelDescription &getModelDescription() const;
const bool supportsModelExchange() const;
const bool supportsCoSimulation() const;
CoSimulationSlaveBuilder &asCoSimulationFmu();
ModelExchangeInstanceBuilder &asModelExchangeFmu();
~Fmu();
private:
fs::path tmp_path_;
const string fmu_file_;
unique_ptr<ModelDescription> modelDescription_;
unique_ptr<CoSimulationSlaveBuilder> csBuilder_;
unique_ptr<ModelExchangeInstanceBuilder> meBuilder_;
const string getModelDescriptionPath() const;
const string getResourcePath() const;
const string getAbsoluteLibraryPath(string modelIdentifier) const;
};
}
#endif //FMICPP_FMU_HPP
<commit_msg>refactor<commit_after>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* 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.
*/
#ifndef FMICPP_FMU_HPP
#define FMICPP_FMU_HPP
#include <memory>
#include <vector>
#include <boost/filesystem.hpp>
#include "../xml/ModelDescription.hpp"
namespace fs = boost::filesystem;
using std::string;
using std::unique_ptr;
using fmicpp::fmi2::xml::ModelDescription;
namespace fmicpp::fmi2::import {
class Fmu {
friend class CoSimulationSlaveBuilder;
friend class ModelExchangeInstanceBuilder;
public:
explicit Fmu(const string &fmu_file);
const string getGuid() const;
const string getModelName() const;
const string getModelDescriptionXml() const;
const ModelDescription &getModelDescription() const;
const bool supportsModelExchange() const;
const bool supportsCoSimulation() const;
CoSimulationSlaveBuilder &asCoSimulationFmu();
ModelExchangeInstanceBuilder &asModelExchangeFmu();
~Fmu();
private:
fs::path tmp_path_;
const string fmu_file_;
unique_ptr<ModelDescription> modelDescription_;
unique_ptr<CoSimulationSlaveBuilder> csBuilder_;
unique_ptr<ModelExchangeInstanceBuilder> meBuilder_;
const string getModelDescriptionPath() const;
const string getResourcePath() const;
const string getAbsoluteLibraryPath(string modelIdentifier) const;
};
}
#endif //FMICPP_FMU_HPP
<|endoftext|>
|
<commit_before>/**
* @file mmio.hxx
* @author Muhammad Osama (mosama@ucdavis.edu)
* @brief Matrix-Market file format header file, see mmio.cpp for implementation
* details.
* @version 0.1
* @date 2020-10-12
*
* @copyright Copyright (c) 2020
*
*/
#if defined(__cplusplus)
extern "C" {
#endif
/*
* Matrix Market I/O library for ANSI C
*
* See http://math.nist.gov/MatrixMarket for details.
*
*
*/
#ifndef MM_IO_H
#define MM_IO_H
#define MM_MAX_LINE_LENGTH 1025
#define MatrixMarketBanner "%%MatrixMarket"
#define MM_MAX_TOKEN_LENGTH 64
typedef char MM_typecode[4];
char* mm_typecode_to_str(MM_typecode matcode);
int mm_read_banner(FILE* f, MM_typecode* matcode);
int mm_read_mtx_crd_size(FILE* f, int* M, int* N, int* nz);
int mm_read_mtx_array_size(FILE* f, int* M, int* N);
int mm_write_banner(FILE* f, MM_typecode matcode);
int mm_write_mtx_crd_size(FILE* f, int M, int N, int nz);
int mm_write_mtx_array_size(FILE* f, int M, int N);
/********************* MM_typecode query fucntions ***************************/
#define mm_is_matrix(typecode) ((typecode)[0] == 'M')
#define mm_is_sparse(typecode) ((typecode)[1] == 'C')
#define mm_is_coordinate(typecode) ((typecode)[1] == 'C')
#define mm_is_dense(typecode) ((typecode)[1] == 'A')
#define mm_is_array(typecode) ((typecode)[1] == 'A')
#define mm_is_complex(typecode) ((typecode)[2] == 'C')
#define mm_is_real(typecode) ((typecode)[2] == 'R')
#define mm_is_pattern(typecode) ((typecode)[2] == 'P')
#define mm_is_integer(typecode) ((typecode)[2] == 'I')
#define mm_is_symmetric(typecode) ((typecode)[3] == 'S')
#define mm_is_general(typecode) ((typecode)[3] == 'G')
#define mm_is_skew(typecode) ((typecode)[3] == 'K')
#define mm_is_hermitian(typecode) ((typecode)[3] == 'H')
int mm_is_valid(MM_typecode matcode); /* too complex for a macro */
/********************* MM_typecode modify fucntions ***************************/
#define mm_set_matrix(typecode) ((*typecode)[0] = 'M')
#define mm_set_coordinate(typecode) ((*typecode)[1] = 'C')
#define mm_set_array(typecode) ((*typecode)[1] = 'A')
#define mm_set_dense(typecode) mm_set_array(typecode)
#define mm_set_sparse(typecode) mm_set_coordinate(typecode)
#define mm_set_complex(typecode) ((*typecode)[2] = 'C')
#define mm_set_real(typecode) ((*typecode)[2] = 'R')
#define mm_set_pattern(typecode) ((*typecode)[2] = 'P')
#define mm_set_integer(typecode) ((*typecode)[2] = 'I')
#define mm_set_symmetric(typecode) ((*typecode)[3] = 'S')
#define mm_set_general(typecode) ((*typecode)[3] = 'G')
#define mm_set_skew(typecode) ((*typecode)[3] = 'K')
#define mm_set_hermitian(typecode) ((*typecode)[3] = 'H')
#define mm_clear_typecode(typecode) \
((*typecode)[0] = (*typecode)[1] = (*typecode)[2] = ' ', (*typecode)[3] = 'G')
#define mm_initialize_typecode(typecode) mm_clear_typecode(typecode)
/********************* Matrix Market error codes ***************************/
#define MM_COULD_NOT_READ_FILE 11
#define MM_PREMATURE_EOF 12
#define MM_NOT_MTX 13
#define MM_NO_HEADER 14
#define MM_UNSUPPORTED_TYPE 15
#define MM_LINE_TOO_LONG 16
#define MM_COULD_NOT_WRITE_FILE 17
/**
* @brief Matrix Market internal definitions.
*
* MM_matrix_typecode: 4-character sequence
*
* | | ojbect | sparse/dense | data type | storage scheme |
* |-----------------|----------|--------------|-----------|----------------|
* | string position | [0] | [1] | [2] | [3] |
* | Matrix typecode | M(atrix) | C(oord) | R(eal) | G(eneral) |
* | | | A(rray) | C(omplex) | H(ermitian) |
* | | | | P(attern) | S(ymmetric) |
* | | | | I(nteger) | K(kew) |
*
*/
#define MM_MTX_STR "matrix"
#define MM_ARRAY_STR "array"
#define MM_DENSE_STR "array"
#define MM_COORDINATE_STR "coordinate"
#define MM_SPARSE_STR "coordinate"
#define MM_COMPLEX_STR "complex"
#define MM_REAL_STR "real"
#define MM_INT_STR "integer"
#define MM_GENERAL_STR "general"
#define MM_SYMM_STR "symmetric"
#define MM_HERM_STR "hermitian"
#define MM_SKEW_STR "skew-symmetric"
#define MM_PATTERN_STR "pattern"
/* high level routines */
int mm_write_mtx_crd(char fname[],
int M,
int N,
int nz,
int I[],
int J[],
double val[],
MM_typecode matcode);
int mm_read_mtx_crd_data(FILE* f,
int M,
int N,
int nz,
int I[],
int J[],
double val[],
MM_typecode matcode);
int mm_read_mtx_crd_entry(FILE* f,
int* I,
int* J,
double* real,
double* img,
MM_typecode matcode);
int mm_read_unsymmetric_sparse(const char* fname,
int* M_,
int* N_,
int* nz_,
double** val_,
int** I_,
int** J_);
#endif
#if defined(__cplusplus)
}
#endif<commit_msg>Update helper header<commit_after>/**
* @file mmio.hxx
* @author Muhammad Osama (mosama@ucdavis.edu)
* @brief Matrix-Market file format header file, see mmio.cpp for implementation
* details.
* @version 0.1
* @date 2020-10-12
*
* @copyright Copyright (c) 2020
*
*/
#if defined(__cplusplus)
extern "C" {
#endif
/*
* Matrix Market I/O library for ANSI C
*
* See http://math.nist.gov/MatrixMarket for details.
*
*
*/
#ifndef MM_IO_H
#define MM_IO_H
#define MM_MAX_LINE_LENGTH 1025
#define MatrixMarketBanner "%%MatrixMarket"
#define MM_MAX_TOKEN_LENGTH 64
typedef char MM_typecode[4];
char* mm_typecode_to_str(MM_typecode matcode);
int mm_read_banner(FILE* f, MM_typecode* matcode);
int mm_read_mtx_crd_size(FILE* f,
std::size_t* M,
std::size_t* N,
std::size_t* nz);
int mm_read_mtx_array_size(FILE* f, std::size_t* M, std::size_t* N);
int mm_write_banner(FILE* f, MM_typecode matcode);
int mm_write_mtx_crd_size(FILE* f,
std::size_t M,
std::size_t N,
std::size_t nz);
int mm_write_mtx_array_size(FILE* f, std::size_t M, std::size_t N);
/********************* MM_typecode query fucntions ***************************/
#define mm_is_matrix(typecode) ((typecode)[0] == 'M')
#define mm_is_sparse(typecode) ((typecode)[1] == 'C')
#define mm_is_coordinate(typecode) ((typecode)[1] == 'C')
#define mm_is_dense(typecode) ((typecode)[1] == 'A')
#define mm_is_array(typecode) ((typecode)[1] == 'A')
#define mm_is_complex(typecode) ((typecode)[2] == 'C')
#define mm_is_real(typecode) ((typecode)[2] == 'R')
#define mm_is_pattern(typecode) ((typecode)[2] == 'P')
#define mm_is_integer(typecode) ((typecode)[2] == 'I')
#define mm_is_symmetric(typecode) ((typecode)[3] == 'S')
#define mm_is_general(typecode) ((typecode)[3] == 'G')
#define mm_is_skew(typecode) ((typecode)[3] == 'K')
#define mm_is_hermitian(typecode) ((typecode)[3] == 'H')
int mm_is_valid(MM_typecode matcode); /* too complex for a macro */
/********************* MM_typecode modify fucntions ***************************/
#define mm_set_matrix(typecode) ((*typecode)[0] = 'M')
#define mm_set_coordinate(typecode) ((*typecode)[1] = 'C')
#define mm_set_array(typecode) ((*typecode)[1] = 'A')
#define mm_set_dense(typecode) mm_set_array(typecode)
#define mm_set_sparse(typecode) mm_set_coordinate(typecode)
#define mm_set_complex(typecode) ((*typecode)[2] = 'C')
#define mm_set_real(typecode) ((*typecode)[2] = 'R')
#define mm_set_pattern(typecode) ((*typecode)[2] = 'P')
#define mm_set_integer(typecode) ((*typecode)[2] = 'I')
#define mm_set_symmetric(typecode) ((*typecode)[3] = 'S')
#define mm_set_general(typecode) ((*typecode)[3] = 'G')
#define mm_set_skew(typecode) ((*typecode)[3] = 'K')
#define mm_set_hermitian(typecode) ((*typecode)[3] = 'H')
#define mm_clear_typecode(typecode) \
((*typecode)[0] = (*typecode)[1] = (*typecode)[2] = ' ', (*typecode)[3] = 'G')
#define mm_initialize_typecode(typecode) mm_clear_typecode(typecode)
/********************* Matrix Market error codes ***************************/
#define MM_COULD_NOT_READ_FILE 11
#define MM_PREMATURE_EOF 12
#define MM_NOT_MTX 13
#define MM_NO_HEADER 14
#define MM_UNSUPPORTED_TYPE 15
#define MM_LINE_TOO_LONG 16
#define MM_COULD_NOT_WRITE_FILE 17
/**
* @brief Matrix Market internal definitions.
*
* MM_matrix_typecode: 4-character sequence
*
* | | ojbect | sparse/dense | data type | storage scheme |
* |-----------------|----------|--------------|-----------|----------------|
* | string position | [0] | [1] | [2] | [3] |
* | Matrix typecode | M(atrix) | C(oord) | R(eal) | G(eneral) |
* | | | A(rray) | C(omplex) | H(ermitian) |
* | | | | P(attern) | S(ymmetric) |
* | | | | I(nteger) | K(kew) |
*
*/
#define MM_MTX_STR "matrix"
#define MM_ARRAY_STR "array"
#define MM_DENSE_STR "array"
#define MM_COORDINATE_STR "coordinate"
#define MM_SPARSE_STR "coordinate"
#define MM_COMPLEX_STR "complex"
#define MM_REAL_STR "real"
#define MM_INT_STR "integer"
#define MM_GENERAL_STR "general"
#define MM_SYMM_STR "symmetric"
#define MM_HERM_STR "hermitian"
#define MM_SKEW_STR "skew-symmetric"
#define MM_PATTERN_STR "pattern"
/* high level routines */
int mm_write_mtx_crd(char fname[],
std::size_t M,
std::size_t N,
std::size_t nz,
std::size_t I[],
std::size_t J[],
double val[],
MM_typecode matcode);
int mm_read_mtx_crd_data(FILE* f,
std::size_t M,
std::size_t N,
std::size_t nz,
std::size_t I[],
std::size_t J[],
double val[],
MM_typecode matcode);
int mm_read_mtx_crd_entry(FILE* f,
std::size_t* I,
std::size_t* J,
double* real,
double* img,
MM_typecode matcode);
int mm_read_unsymmetric_sparse(const char* fname,
std::size_t* M_,
std::size_t* N_,
std::size_t* nz_,
double** val_,
std::size_t** I_,
std::size_t** J_);
#endif
#if defined(__cplusplus)
}
#endif<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_HTTP_STREAM_HPP_INCLUDED
#define TORRENT_HTTP_STREAM_HPP_INCLUDED
#include <boost/function/function1.hpp>
#include "libtorrent/proxy_base.hpp"
#include <boost/bind.hpp>
namespace libtorrent {
class http_stream : public proxy_base
{
public:
explicit http_stream(io_service& io_service)
: proxy_base(io_service)
, m_no_connect(false)
{}
void set_no_connect(bool c) { m_no_connect = c; }
void set_username(std::string const& user
, std::string const& password)
{
m_user = user;
m_password = password;
}
typedef boost::function<void(error_code const&)> handler_type;
template <class Handler>
void async_connect(endpoint_type const& endpoint, Handler const& handler)
{
m_remote_endpoint = endpoint;
// the connect is split up in the following steps:
// 1. resolve name of proxy server
// 2. connect to proxy server
// 3. send HTTP CONNECT method and possibly username+password
// 4. read CONNECT response
// to avoid unnecessary copying of the handler,
// store it in a shaed_ptr
boost::shared_ptr<handler_type> h(new handler_type(handler));
tcp::resolver::query q(m_hostname, to_string(m_port).elems);
m_resolver.async_resolve(q, boost::bind(
&http_stream::name_lookup, this, _1, _2, h));
}
private:
void name_lookup(error_code const& e, tcp::resolver::iterator i
, boost::shared_ptr<handler_type> h);
void connected(error_code const& e, boost::shared_ptr<handler_type> h);
void handshake1(error_code const& e, boost::shared_ptr<handler_type> h);
void handshake2(error_code const& e, boost::shared_ptr<handler_type> h);
// send and receive buffer
std::vector<char> m_buffer;
// proxy authentication
std::string m_user;
std::string m_password;
// this is true if the connection is HTTP based and
// want to talk directly to the proxy
bool m_no_connect;
};
}
#endif
<commit_msg>fixed typo in comment<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_HTTP_STREAM_HPP_INCLUDED
#define TORRENT_HTTP_STREAM_HPP_INCLUDED
#include <boost/function/function1.hpp>
#include "libtorrent/proxy_base.hpp"
#include <boost/bind.hpp>
namespace libtorrent {
class http_stream : public proxy_base
{
public:
explicit http_stream(io_service& io_service)
: proxy_base(io_service)
, m_no_connect(false)
{}
void set_no_connect(bool c) { m_no_connect = c; }
void set_username(std::string const& user
, std::string const& password)
{
m_user = user;
m_password = password;
}
typedef boost::function<void(error_code const&)> handler_type;
template <class Handler>
void async_connect(endpoint_type const& endpoint, Handler const& handler)
{
m_remote_endpoint = endpoint;
// the connect is split up in the following steps:
// 1. resolve name of proxy server
// 2. connect to proxy server
// 3. send HTTP CONNECT method and possibly username+password
// 4. read CONNECT response
// to avoid unnecessary copying of the handler,
// store it in a shared_ptr
boost::shared_ptr<handler_type> h(new handler_type(handler));
tcp::resolver::query q(m_hostname, to_string(m_port).elems);
m_resolver.async_resolve(q, boost::bind(
&http_stream::name_lookup, this, _1, _2, h));
}
private:
void name_lookup(error_code const& e, tcp::resolver::iterator i
, boost::shared_ptr<handler_type> h);
void connected(error_code const& e, boost::shared_ptr<handler_type> h);
void handshake1(error_code const& e, boost::shared_ptr<handler_type> h);
void handshake2(error_code const& e, boost::shared_ptr<handler_type> h);
// send and receive buffer
std::vector<char> m_buffer;
// proxy authentication
std::string m_user;
std::string m_password;
// this is true if the connection is HTTP based and
// want to talk directly to the proxy
bool m_no_connect;
};
}
#endif
<|endoftext|>
|
<commit_before>#include "main_window.h"
#include "ui_main_window.h"
#include <QtGlobal>
#include <scene_detector.h>
main_window::main_window(QWidget* parent, CutDetector* detector)
: QMainWindow(parent),
ui(new Ui::main_window),
comparator_options_dialog_(new ComparatorOptionsDialog(
this,
static_cast<HistogramBasedFrameComparator*>(
detector->frame_comparator()))),
scene_list_preview_dialog_(new SceneListPreviewDialog(this)) {
detector_.reset(detector);
detector_->scene_detector()->RegisterObserver(&interface_);
detector_->video_reader()->RegisterObserver(&interface_);
scene_list_preview_dialog_->setVideoReader(detector_->video_reader());
worker_thread_.start();
interface_.set_detector(detector_.get());
interface_.moveToThread(&worker_thread_);
ui->setupUi(this);
setupSignals();
}
void main_window::setupSignals() {
qRegisterMetaType<cv::Mat>("cv::Mat");
qRegisterMetaType<QVector<int> >("QVector<int>");
// Detector settings signals
QObject::connect(ui->detectorSettingsButton, &QAbstractButton::clicked, this,
&main_window::openComparatorSettingsDialog);
QObject::connect(ui->saveDetectorSettingsButton, &QAbstractButton::clicked,
[=]() { interface_.saveSettingsJsonFile(this); });
QObject::connect(ui->loadDetectorSettingsButton, &QAbstractButton::clicked,
[=]() { interface_.openSettingsJsonFile(this); });
// OpenCVWidget signals
QObject::connect(&interface_, &CutDetectorQtInterface::showCurrentFrame,
ui->bottomOpenCVWidget, &OpenCVImageWidget::showImage);
QObject::connect(&interface_, &CutDetectorQtInterface::showNewSceneFirstFrame,
ui->bottomOpenCVWidget, &OpenCVImageWidget::showImage);
QObject::connect(&interface_,
&CutDetectorQtInterface::showPreviousSceneLastFrame,
ui->topOpenCVWidget, &OpenCVImageWidget::showImage);
// Scene detection signals
QObject::connect(ui->startButton, &QToolButton::clicked, &interface_,
&CutDetectorQtInterface::detectScenes);
QObject::connect(&interface_, &CutDetectorQtInterface::sceneListGenerated,
[=](sceneList list) {
for (auto scene : list) {
QTableWidgetItem* item1 =
new QTableWidgetItem(QString::number(scene.first));
QTableWidgetItem* item2 =
new QTableWidgetItem(QString::number(scene.second));
int row = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(
ui->sceneTableWidget->rowCount() + 1);
ui->sceneTableWidget->setItem(row, 0, item1);
ui->sceneTableWidget->setItem(row, 1, item2);
}
});
QObject::connect(&interface_, &CutDetectorQtInterface::sceneDetectionStarted,
this, &main_window::clearScenesList);
// Video Reader controls
QObject::connect(
&interface_, &CutDetectorQtInterface::changeCurrentFrameIndex,
[=](int current, int total) {
ui->playbackSlider->setValue(((double)current / total) * 100);
});
QObject::connect(ui->actionOpen_file, &QAction::triggered, [=]() {
interface_.openVideoFile(this);
clearScenesList();
});
QObject::connect(ui->stepForwardButton, &QAbstractButton::clicked,
&interface_, &CutDetectorQtInterface::stepVideoForward);
QObject::connect(ui->stepBackButton, &QAbstractButton::clicked, &interface_,
&CutDetectorQtInterface::stepVideoBackward);
QObject::connect(ui->rewindButton, &QAbstractButton::clicked, &interface_,
&CutDetectorQtInterface::rewindVideo);
QObject::connect(ui->endButton, &QAbstractButton::clicked, &interface_,
&CutDetectorQtInterface::fastforwardVideo);
// Scene list controls
QObject::connect(ui->actionClear_cuts_list, &QAction::triggered, this,
&main_window::clearScenesList);
QObject::connect(ui->clearListButton, &QAbstractButton::clicked, this,
&main_window::clearScenesList);
QObject::connect(ui->loadListButton, &QAbstractButton::clicked,
[=]() { loadSceneList(interface_.openCutsFile(this)); });
QObject::connect(ui->saveListButton, &QAbstractButton::clicked, [=]() {
interface_.saveCutsFile(this, generateSceneList());
});
QObject::connect(ui->addRowButton, &QAbstractButton::clicked, [=]() {
int rowCount = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(++rowCount);
ui->sceneTableWidget->setCurrentCell(rowCount - 1, 0);
});
QObject::connect(ui->deleteRowButton, &QAbstractButton::clicked, [=]() {
int rowCount = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(--rowCount);
ui->sceneTableWidget->setCurrentCell(rowCount - 1, 0);
});
// Scene list table widget
QObject::connect(ui->sceneTableWidget, &QTableWidget::cellChanged,
[=](int row, int collumn) {
auto item = ui->sceneTableWidget->item(row, collumn);
if (item->text().isEmpty())
return;
int rowCount = ui->sceneTableWidget->rowCount();
if (rowCount <= (row + 1)) {
ui->sceneTableWidget->setRowCount(++rowCount);
}
int currentVal = item->text().toInt();
auto newItem = new QTableWidgetItem();
int nextRow = collumn ? row + 1 : row;
int nextCol = (collumn + 1) % 2;
int newValue = currentVal + 1;
if (collumn == 0) {
auto nextItem =
ui->sceneTableWidget->item(nextRow, nextCol);
if (!nextItem || nextItem->text().isEmpty() ||
nextItem->text().toInt() > newValue) {
ui->sceneTableWidget->setCurrentCell(nextRow, collumn);
return;
}
}
newItem->setText(QString::number(newValue));
ui->sceneTableWidget->setItem(nextRow, nextCol, newItem);
ui->sceneTableWidget->setCurrentCell(nextRow, nextCol);
});
// Scene list preview dialog
QObject::connect(ui->openSceneListPreviewButton, &QAbstractButton::clicked,
[=]() {
QList<QString> list = generateSceneList();
if (!list.empty()) {
this->scene_list_preview_dialog_->loadScenesList(list);
this->scene_list_preview_dialog_->show();
}
});
}
QList<QString> main_window::generateSceneList() {
ui->sceneTableWidget->blockSignals(true);
QList<QString> result;
for (int i = 0; i < ui->sceneTableWidget->rowCount(); ++i) {
QString temp = "[";
for (int j = 0; j < ui->sceneTableWidget->columnCount(); ++j) {
if (j != 0)
temp += ";";
temp += ui->sceneTableWidget->item(i, j)->text();
}
result.push_back(temp + "]");
}
ui->sceneTableWidget->blockSignals(false);
return result;
}
void main_window::loadSceneList(QList<QString> list) {
ui->sceneTableWidget->setRowCount(0);
for (QString scene : list) {
scene.remove(QChar('['));
scene.remove(QChar(']'));
auto cells = scene.split(";");
int row = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(row + 1);
int col = 0;
for (QString cell : cells) {
auto item = new QTableWidgetItem(cell);
ui->sceneTableWidget->setItem(row, col, item);
++col;
}
}
}
void main_window::clearScenesList() {
ui->sceneTableWidget->setRowCount(0);
}
void main_window::openComparatorSettingsDialog() {
comparator_options_dialog_->show();
}
main_window::~main_window() {
worker_thread_.exit();
worker_thread_.wait();
delete ui;
}
<commit_msg>Fix crash on opening scene preview<commit_after>#include "main_window.h"
#include "ui_main_window.h"
#include <QtGlobal>
#include <scene_detector.h>
main_window::main_window(QWidget* parent, CutDetector* detector)
: QMainWindow(parent),
ui(new Ui::main_window),
comparator_options_dialog_(new ComparatorOptionsDialog(
this,
static_cast<HistogramBasedFrameComparator*>(
detector->frame_comparator()))),
scene_list_preview_dialog_(new SceneListPreviewDialog(this)) {
detector_.reset(detector);
detector_->scene_detector()->RegisterObserver(&interface_);
detector_->video_reader()->RegisterObserver(&interface_);
scene_list_preview_dialog_->setVideoReader(detector_->video_reader());
worker_thread_.start();
interface_.set_detector(detector_.get());
interface_.moveToThread(&worker_thread_);
ui->setupUi(this);
setupSignals();
}
void main_window::setupSignals() {
qRegisterMetaType<cv::Mat>("cv::Mat");
qRegisterMetaType<QVector<int> >("QVector<int>");
// Detector settings signals
QObject::connect(ui->detectorSettingsButton, &QAbstractButton::clicked, this,
&main_window::openComparatorSettingsDialog);
QObject::connect(ui->saveDetectorSettingsButton, &QAbstractButton::clicked,
[=]() { interface_.saveSettingsJsonFile(this); });
QObject::connect(ui->loadDetectorSettingsButton, &QAbstractButton::clicked,
[=]() { interface_.openSettingsJsonFile(this); });
// OpenCVWidget signals
QObject::connect(&interface_, &CutDetectorQtInterface::showCurrentFrame,
ui->bottomOpenCVWidget, &OpenCVImageWidget::showImage);
QObject::connect(&interface_, &CutDetectorQtInterface::showNewSceneFirstFrame,
ui->bottomOpenCVWidget, &OpenCVImageWidget::showImage);
QObject::connect(&interface_,
&CutDetectorQtInterface::showPreviousSceneLastFrame,
ui->topOpenCVWidget, &OpenCVImageWidget::showImage);
// Scene detection signals
QObject::connect(ui->startButton, &QToolButton::clicked, &interface_,
&CutDetectorQtInterface::detectScenes);
QObject::connect(&interface_, &CutDetectorQtInterface::sceneListGenerated,
[=](sceneList list) {
for (auto scene : list) {
QTableWidgetItem* item1 =
new QTableWidgetItem(QString::number(scene.first));
QTableWidgetItem* item2 =
new QTableWidgetItem(QString::number(scene.second));
int row = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(
ui->sceneTableWidget->rowCount() + 1);
ui->sceneTableWidget->setItem(row, 0, item1);
ui->sceneTableWidget->setItem(row, 1, item2);
}
});
QObject::connect(&interface_, &CutDetectorQtInterface::sceneDetectionStarted,
this, &main_window::clearScenesList);
// Video Reader controls
QObject::connect(
&interface_, &CutDetectorQtInterface::changeCurrentFrameIndex,
[=](int current, int total) {
ui->playbackSlider->setValue(((double)current / total) * 100);
});
QObject::connect(ui->actionOpen_file, &QAction::triggered, [=]() {
interface_.openVideoFile(this);
clearScenesList();
});
QObject::connect(ui->stepForwardButton, &QAbstractButton::clicked,
&interface_, &CutDetectorQtInterface::stepVideoForward);
QObject::connect(ui->stepBackButton, &QAbstractButton::clicked, &interface_,
&CutDetectorQtInterface::stepVideoBackward);
QObject::connect(ui->rewindButton, &QAbstractButton::clicked, &interface_,
&CutDetectorQtInterface::rewindVideo);
QObject::connect(ui->endButton, &QAbstractButton::clicked, &interface_,
&CutDetectorQtInterface::fastforwardVideo);
// Scene list controls
QObject::connect(ui->actionClear_cuts_list, &QAction::triggered, this,
&main_window::clearScenesList);
QObject::connect(ui->clearListButton, &QAbstractButton::clicked, this,
&main_window::clearScenesList);
QObject::connect(ui->loadListButton, &QAbstractButton::clicked,
[=]() { loadSceneList(interface_.openCutsFile(this)); });
QObject::connect(ui->saveListButton, &QAbstractButton::clicked, [=]() {
interface_.saveCutsFile(this, generateSceneList());
});
QObject::connect(ui->addRowButton, &QAbstractButton::clicked, [=]() {
int rowCount = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(++rowCount);
ui->sceneTableWidget->setCurrentCell(rowCount - 1, 0);
});
QObject::connect(ui->deleteRowButton, &QAbstractButton::clicked, [=]() {
int rowCount = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(--rowCount);
ui->sceneTableWidget->setCurrentCell(rowCount - 1, 0);
});
// Scene list table widget
QObject::connect(ui->sceneTableWidget, &QTableWidget::cellChanged,
[=](int row, int collumn) {
auto item = ui->sceneTableWidget->item(row, collumn);
if (item->text().isEmpty())
return;
int rowCount = ui->sceneTableWidget->rowCount();
if (rowCount <= (row + 1)) {
ui->sceneTableWidget->setRowCount(++rowCount);
}
int currentVal = item->text().toInt();
auto newItem = new QTableWidgetItem();
int nextRow = collumn ? row + 1 : row;
int nextCol = (collumn + 1) % 2;
int newValue = currentVal + 1;
if (collumn == 0) {
auto nextItem =
ui->sceneTableWidget->item(nextRow, nextCol);
if (!nextItem || nextItem->text().isEmpty() ||
nextItem->text().toInt() > newValue) {
ui->sceneTableWidget->setCurrentCell(nextRow, collumn);
return;
}
}
newItem->setText(QString::number(newValue));
ui->sceneTableWidget->setItem(nextRow, nextCol, newItem);
ui->sceneTableWidget->setCurrentCell(nextRow, nextCol);
});
// Scene list preview dialog
QObject::connect(ui->openSceneListPreviewButton, &QAbstractButton::clicked,
[=]() {
QList<QString> list = generateSceneList();
if (!list.empty()) {
this->scene_list_preview_dialog_->loadScenesList(list);
this->scene_list_preview_dialog_->show();
}
});
}
QList<QString> main_window::generateSceneList() {
ui->sceneTableWidget->blockSignals(true);
QList<QString> result;
for (int i = 0; i < ui->sceneTableWidget->rowCount(); ++i) {
QString temp = "[";
for (int j = 0; j < ui->sceneTableWidget->columnCount(); ++j) {
if (j != 0)
temp += ";";
if (ui->sceneTableWidget->item(i, j))
temp += ui->sceneTableWidget->item(i, j)->text();
else
temp.clear();
}
if (!temp.isEmpty())
result.push_back(temp + "]");
}
ui->sceneTableWidget->blockSignals(false);
return result;
}
void main_window::loadSceneList(QList<QString> list) {
ui->sceneTableWidget->setRowCount(0);
for (QString scene : list) {
scene.remove(QChar('['));
scene.remove(QChar(']'));
auto cells = scene.split(";");
int row = ui->sceneTableWidget->rowCount();
ui->sceneTableWidget->setRowCount(row + 1);
int col = 0;
for (QString cell : cells) {
auto item = new QTableWidgetItem(cell);
ui->sceneTableWidget->setItem(row, col, item);
++col;
}
}
}
void main_window::clearScenesList() {
ui->sceneTableWidget->setRowCount(0);
}
void main_window::openComparatorSettingsDialog() {
comparator_options_dialog_->show();
}
main_window::~main_window() {
worker_thread_.exit();
worker_thread_.wait();
delete ui;
}
<|endoftext|>
|
<commit_before>///
/// @file StorePrimes.hpp
/// @brief Store primes in a vector.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef STOREPRIMES_HPP
#define STOREPRIMES_HPP
#include "iterator.hpp"
#include "primesieve_error.hpp"
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <string>
namespace primesieve {
/// primeCountApprox(x) >= pi(x)
inline std::size_t prime_count_approx(uint64_t start, uint64_t stop)
{
if (start > stop)
return 0;
// pi(x) <= x / (log(x) - 1.1) + 5, for x >= 4.
// Pierre Dusart, https://arxiv.org/abs/1002.0442 eq. 6.6.
double x = (double) stop;
x = std::max<double>(100.0, x);
double pix = (stop - start) / (std::log(x) - 1.1) + 5;
return (std::size_t) pix;
}
/// Used to print type name in error messages
template <typename T> inline std::string getTypeName() { return "Type"; }
template <> inline std::string getTypeName<int8_t>() { return "int8_t"; }
template <> inline std::string getTypeName<uint8_t>() { return "uint8_t"; }
template <> inline std::string getTypeName<int16_t>() { return "int16_t"; }
template <> inline std::string getTypeName<uint16_t>() { return "uint16_t"; }
template <> inline std::string getTypeName<int32_t>() { return "int32_t"; }
template <> inline std::string getTypeName<uint32_t>() { return "uint32_t"; }
template <> inline std::string getTypeName<int64_t>() { return "int64_t"; }
template <> inline std::string getTypeName<uint64_t>() { return "uint64_t"; }
template <typename T>
inline void store_primes(uint64_t start,
uint64_t stop,
T& primes)
{
#if defined(_MSC_VER)
#pragma warning(push)
// Disable warning: conversion from X to Y, possible loss of data
#pragma warning(disable : 4244)
// Disable warning C4018: '>': signed/unsigned mismatch
#pragma warning(disable : 4018)
#endif
if (start > stop)
return;
using V = typename T::value_type;
if (stop > std::numeric_limits<V>::max())
throw primesieve_error("store_primes(): " + getTypeName<V>() + " is too narrow for generating primes up to " + std::to_string(stop));
std::size_t size = primes.size() + prime_count_approx(start, stop);
primes.reserve(size);
primesieve::iterator it(start, stop);
it.generate_next_primes();
uint64_t maxPrime64bits = 18446744073709551557ull;
uint64_t limit = std::min(stop, maxPrime64bits - 1);
for (; it.primes_[it.size_ - 1] <= limit; it.generate_next_primes())
primes.insert(primes.end(), it.primes_, it.primes_ + it.size_);
for (std::size_t i = 0; it.primes_[i] <= limit; i++)
primes.push_back((V) it.primes_[i]);
if (stop >= maxPrime64bits)
primes.push_back((V) maxPrime64bits);
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}
template <typename T>
inline void store_n_primes(uint64_t n,
uint64_t start,
T& primes)
{
#if defined(_MSC_VER)
#pragma warning(push)
// Disable warning: conversion from X to Y, possible loss of data
#pragma warning(disable : 4244)
// Disable warning C4018: '>': signed/unsigned mismatch
#pragma warning(disable : 4018)
#endif
if (n == 0)
return;
using V = typename T::value_type;
std::size_t size = primes.size() + (std::size_t) n;
primes.reserve(size);
// nthPrime < n(log n + log log n), for n >= 6.
// https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
double x = std::max<double>({6.0, (double) n, (double) start});
double logn = std::log(x);
double loglogn = std::log(logn);
uint64_t nthPrime = (uint64_t)(n * (logn + loglogn));
uint64_t stop = start + nthPrime;
primesieve::iterator it(start, stop);
it.generate_next_primes();
while (n >= it.size_)
{
if (it.primes_[it.size_ - 1] > std::numeric_limits<V>::max())
throw primesieve_error("store_n_primes(): " + getTypeName<V>() + " is too narrow for generating primes up to " + std::to_string(stop));
primes.insert(primes.end(), it.primes_, it.primes_ + it.size_);
n -= it.size_;
if (n == 0)
return;
it.generate_next_primes();
}
if (it.primes_[n - 1] > std::numeric_limits<V>::max())
throw primesieve_error("store_n_primes(): " + getTypeName<V>() + " is too narrow for generating primes up to " + std::to_string(stop));
for (std::size_t i = 0; i < (std::size_t) n; i++)
primes.push_back((V) it.primes_[i]);
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}
} // namespace
#endif
<commit_msg>Add comment<commit_after>///
/// @file StorePrimes.hpp
/// @brief Store primes in a vector.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef STOREPRIMES_HPP
#define STOREPRIMES_HPP
#include "iterator.hpp"
#include "primesieve_error.hpp"
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <string>
namespace primesieve {
/// primeCountApprox(x) >= pi(x)
inline std::size_t prime_count_approx(uint64_t start, uint64_t stop)
{
if (start > stop)
return 0;
// pi(x) <= x / (log(x) - 1.1) + 5, for x >= 4.
// Pierre Dusart, https://arxiv.org/abs/1002.0442 eq. 6.6.
double x = (double) stop;
x = std::max<double>(100.0, x);
double pix = (stop - start) / (std::log(x) - 1.1) + 5;
return (std::size_t) pix;
}
/// Used to print type name in error messages
template <typename T> inline std::string getTypeName() { return "Type"; }
template <> inline std::string getTypeName<int8_t>() { return "int8_t"; }
template <> inline std::string getTypeName<uint8_t>() { return "uint8_t"; }
template <> inline std::string getTypeName<int16_t>() { return "int16_t"; }
template <> inline std::string getTypeName<uint16_t>() { return "uint16_t"; }
template <> inline std::string getTypeName<int32_t>() { return "int32_t"; }
template <> inline std::string getTypeName<uint32_t>() { return "uint32_t"; }
template <> inline std::string getTypeName<int64_t>() { return "int64_t"; }
template <> inline std::string getTypeName<uint64_t>() { return "uint64_t"; }
template <typename T>
inline void store_primes(uint64_t start,
uint64_t stop,
T& primes)
{
#if defined(_MSC_VER)
#pragma warning(push)
// Disable warning: conversion from X to Y, possible loss of data
#pragma warning(disable : 4244)
// Disable warning C4018: '>': signed/unsigned mismatch
#pragma warning(disable : 4018)
#endif
if (start > stop)
return;
using V = typename T::value_type;
if (stop > std::numeric_limits<V>::max())
throw primesieve_error("store_primes(): " + getTypeName<V>() + " is too narrow for generating primes up to " + std::to_string(stop));
std::size_t size = primes.size() + prime_count_approx(start, stop);
primes.reserve(size);
primesieve::iterator it(start, stop);
it.generate_next_primes();
// primesieve::iterator throws an exception if one tries to
// generate primes > 2^64. Hence we must avoid calling
// generate_next_primes() after the largest 64-bit prime.
uint64_t maxPrime64bits = 18446744073709551557ull;
uint64_t limit = std::min(stop, maxPrime64bits - 1);
for (; it.primes_[it.size_ - 1] <= limit; it.generate_next_primes())
primes.insert(primes.end(), it.primes_, it.primes_ + it.size_);
for (std::size_t i = 0; it.primes_[i] <= limit; i++)
primes.push_back((V) it.primes_[i]);
if (stop >= maxPrime64bits)
primes.push_back((V) maxPrime64bits);
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}
template <typename T>
inline void store_n_primes(uint64_t n,
uint64_t start,
T& primes)
{
#if defined(_MSC_VER)
#pragma warning(push)
// Disable warning: conversion from X to Y, possible loss of data
#pragma warning(disable : 4244)
// Disable warning C4018: '>': signed/unsigned mismatch
#pragma warning(disable : 4018)
#endif
if (n == 0)
return;
using V = typename T::value_type;
std::size_t size = primes.size() + (std::size_t) n;
primes.reserve(size);
// nthPrime < n(log n + log log n), for n >= 6.
// https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
double x = std::max<double>({6.0, (double) n, (double) start});
double logn = std::log(x);
double loglogn = std::log(logn);
uint64_t nthPrime = (uint64_t)(n * (logn + loglogn));
uint64_t stop = start + nthPrime;
primesieve::iterator it(start, stop);
it.generate_next_primes();
while (n >= it.size_)
{
if (it.primes_[it.size_ - 1] > std::numeric_limits<V>::max())
throw primesieve_error("store_n_primes(): " + getTypeName<V>() + " is too narrow for generating primes up to " + std::to_string(stop));
primes.insert(primes.end(), it.primes_, it.primes_ + it.size_);
n -= it.size_;
if (n == 0)
return;
it.generate_next_primes();
}
if (it.primes_[n - 1] > std::numeric_limits<V>::max())
throw primesieve_error("store_n_primes(): " + getTypeName<V>() + " is too narrow for generating primes up to " + std::to_string(stop));
for (std::size_t i = 0; i < (std::size_t) n; i++)
primes.push_back((V) it.primes_[i]);
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}
} // namespace
#endif
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Radu Bogdan rusu, Suat Gedikli
*
*/
// PCL
#include <Eigen/Geometry>
#include <pcl/common/common.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/pcd_grabber.h>
#include <cfloat>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/terminal_tools/print.h>
#include <pcl/terminal_tools/parse.h>
#include <pcl/terminal_tools/time.h>
using terminal_tools::print_color;
using terminal_tools::print_error;
using terminal_tools::print_error;
using terminal_tools::print_warn;
using terminal_tools::print_info;
using terminal_tools::print_debug;
using terminal_tools::print_value;
using terminal_tools::print_highlight;
using terminal_tools::TT_BRIGHT;
using terminal_tools::TT_RED;
using terminal_tools::TT_GREEN;
using terminal_tools::TT_BLUE;
typedef pcl_visualization::PointCloudColorHandler<pcl::PointCloud<pcl::PointXYZ> > ColorHandler;
typedef ColorHandler::Ptr ColorHandlerPtr;
typedef ColorHandler::ConstPtr ColorHandlerConstPtr;
typedef pcl_visualization::PointCloudGeometryHandler<pcl::PointCloud<pcl::PointXYZ> > GeometryHandler;
typedef GeometryHandler::Ptr GeometryHandlerPtr;
typedef GeometryHandler::ConstPtr GeometryHandlerConstPtr;
boost::mutex mutex_;
#define NORMALS_SCALE 0.01
#define PC_SCALE 0.001
void
printHelp (int argc, char **argv)
{
//print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
print_error ("Syntax is: %s <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -dev device_id = device to be used\n");
print_info (" maybe \"#n\", with n being the number of the device in device list.\n");
print_info (" maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n");
print_info (" maybe \"serial\", with serial being the serial number of the device.\n");
print_info (" -bc r,g,b = background color\n");
print_info (" -fc r,g,b = foreground color\n");
print_info (" -ps X = point size ("); print_value ("1..64"); print_info (") \n");
print_info (" -opaque X = rendered point cloud opacity ("); print_value ("0..1"); print_info (")\n");
print_info (" -ax "); print_value ("n"); print_info (" = enable on-screen display of ");
print_color (stdout, TT_BRIGHT, TT_RED, "X"); print_color (stdout, TT_BRIGHT, TT_GREEN, "Y"); print_color (stdout, TT_BRIGHT, TT_BLUE, "Z");
print_info (" axes and scale them to "); print_value ("n\n");
print_info (" -ax_pos X,Y,Z = if axes are enabled, set their X,Y,Z position in space (default "); print_value ("0,0,0"); print_info (")\n");
print_info ("\n");
print_info (" -cam (*) = use given camera settings as initial view\n");
print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n");
print_info ("\n");
print_info (" -multiview 0/1 = enable/disable auto-multi viewport rendering (default "); print_value ("disabled"); print_info (")\n");
print_info ("\n");
print_info ("\n");
print_info (" -normals 0/X = disable/enable the display of every Xth point's surface normal as lines (default "); print_value ("disabled"); print_info (")\n");
print_info (" -normals_scale X = resize the normal unit vector size to X (default "); print_value ("0.02"); print_info (")\n");
print_info ("\n");
print_info (" -pc 0/X = disable/enable the display of every Xth point's principal curvatures as lines (default "); print_value ("disabled"); print_info (")\n");
print_info (" -pc_scale X = resize the principal curvatures vectors size to X (default "); print_value ("0.02"); print_info (")\n");
print_info ("\n");
print_info ("\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\n");
}
// Create the PCLVisualizer object
boost::shared_ptr<pcl_visualization::PCLVisualizer> p;
ColorHandlerPtr color_handler;
GeometryHandlerPtr geometry_handler;
std::vector<double> fcolor_r, fcolor_b, fcolor_g;
bool fcolorparam = false;
struct EventHelper
{
void cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
//std::cout << __PRETTY_FUNCTION__ << " " << cloud->width << std::endl;
// Add the dataset with a XYZ and a random handler
// geometry_handler.reset (new pcl_visualization::PointCloudGeometryHandlerXYZ<pcl::PointCloud<pcl::PointXYZRGB> > (*cloud));
//// If color was given, ues that
//if (fcolorparam)
// color_handler.reset (new pcl_visualization::PointCloudColorHandlerCustom<pcl::PointCloud<pcl::PointXYZRGB> > (cloud, fcolor_r, fcolor_g, fcolor_b));
//else
// color_handler.reset (new pcl_visualization::PointCloudColorHandlerRandom<pcl::PointCloud<pcl::PointXYZRGB> > (cloud));
// Add the cloud to the renderer
boost::mutex::scoped_lock lock(mutex_);
if (!cloud)
return;
p->removePointCloud ("PCDCloud");
p->addPointCloud (*cloud, "PCDCloud");
}
};
/* ---[ */
int
main (int argc, char** argv)
{
srand (time (0));
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (std::string(argv[i]) == "-h")
{
printHelp (argc, argv);
return (-1);
}
}
}
// Command line parsing
double bcolor[3] = {0, 0, 0};
terminal_tools::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]);
fcolorparam = terminal_tools::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b);
int psize = 0;
terminal_tools::parse_argument (argc, argv, "-ps", psize);
double opaque;
terminal_tools::parse_argument (argc, argv, "-opaque", opaque);
p.reset (new pcl_visualization::PCLVisualizer (argc, argv, "PCD viewer"));
// // Change the cloud rendered point size
// if (psize > 0)
// p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_POINT_SIZE, psize, "KinectCloud");
//
// // Change the cloud rendered opacity
// if (opaque >= 0)
// p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_OPACITY, opaque, "KinectCloud");
p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);
//boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1));
//boost::function<void (boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1);
//boost::signals2::connection c =
// interface->registerCallback <void(boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).);
// Read axes settings
double axes = 0.0;
terminal_tools::parse_argument (argc, argv, "-ax", axes);
if (axes != 0.0 && p)
{
double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;
terminal_tools::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false);
// Draw XYZ axes if command-line enabled
p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);
}
std::string pcd_file = "";
terminal_tools::parse_argument (argc, argv, "-file", pcd_file);
pcl::Grabber* interface = new pcl::PCDGrabber<pcl::PointXYZRGB>(pcd_file);
EventHelper h;
boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind(&EventHelper::cloud_cb, &h, _1);
boost::signals2::connection c1 = interface->registerCallback (f);
interface->start ();
while (true)
{
usleep (10000);
{
boost::mutex::scoped_lock lock(mutex_);
p->spinOnce ();
if (p->wasStopped ())
break;
}
}
interface->stop ();
}
/* ]--- */
<commit_msg>added -dir, -fps and -repeat options<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Radu Bogdan rusu, Suat Gedikli
*
*/
// PCL
#include <Eigen/Geometry>
#include <pcl/common/common.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/pcd_grabber.h>
#include <cfloat>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/terminal_tools/print.h>
#include <pcl/terminal_tools/parse.h>
#include <pcl/terminal_tools/time.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
using terminal_tools::print_color;
using terminal_tools::print_error;
using terminal_tools::print_error;
using terminal_tools::print_warn;
using terminal_tools::print_info;
using terminal_tools::print_debug;
using terminal_tools::print_value;
using terminal_tools::print_highlight;
using terminal_tools::TT_BRIGHT;
using terminal_tools::TT_RED;
using terminal_tools::TT_GREEN;
using terminal_tools::TT_BLUE;
using namespace boost::filesystem;
typedef pcl_visualization::PointCloudColorHandler<pcl::PointCloud<pcl::PointXYZ> > ColorHandler;
typedef ColorHandler::Ptr ColorHandlerPtr;
typedef ColorHandler::ConstPtr ColorHandlerConstPtr;
typedef pcl_visualization::PointCloudGeometryHandler<pcl::PointCloud<pcl::PointXYZ> > GeometryHandler;
typedef GeometryHandler::Ptr GeometryHandlerPtr;
typedef GeometryHandler::ConstPtr GeometryHandlerConstPtr;
boost::mutex mutex_;
#define NORMALS_SCALE 0.01
#define PC_SCALE 0.001
void
printHelp (int argc, char **argv)
{
//print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
print_error ("Syntax is: %s <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -file file_name = PCD file to be read from\n");
print_info (" -dir directory_path = directory path to PCD file(s) to be read from\n");
print_info (" -fps frequency = frames per second\n");
print_info (" -repeat = optional parameter that tells wheter the PCD file(s) should be \"grabbed\" in a endless loop.\n");
print_info (" -bc r,g,b = background color\n");
print_info (" -fc r,g,b = foreground color\n");
print_info (" -ps X = point size (");
print_value ("1..64");
print_info (") \n");
print_info (" -opaque X = rendered point cloud opacity (");
print_value ("0..1");
print_info (")\n");
print_info (" -ax ");
print_value ("n");
print_info (" = enable on-screen display of ");
print_color (stdout, TT_BRIGHT, TT_RED, "X");
print_color (stdout, TT_BRIGHT, TT_GREEN, "Y");
print_color (stdout, TT_BRIGHT, TT_BLUE, "Z");
print_info (" axes and scale them to ");
print_value ("n\n");
print_info (" -ax_pos X,Y,Z = if axes are enabled, set their X,Y,Z position in space (default ");
print_value ("0,0,0");
print_info (")\n");
print_info ("\n");
print_info (" -cam (*) = use given camera settings as initial view\n");
print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n");
print_info ("\n");
print_info (" -multiview 0/1 = enable/disable auto-multi viewport rendering (default ");
print_value ("disabled");
print_info (")\n");
print_info ("\n");
print_info ("\n");
print_info (" -normals 0/X = disable/enable the display of every Xth point's surface normal as lines (default ");
print_value ("disabled");
print_info (")\n");
print_info (" -normals_scale X = resize the normal unit vector size to X (default ");
print_value ("0.02");
print_info (")\n");
print_info ("\n");
print_info (" -pc 0/X = disable/enable the display of every Xth point's principal curvatures as lines (default ");
print_value ("disabled");
print_info (")\n");
print_info (" -pc_scale X = resize the principal curvatures vectors size to X (default ");
print_value ("0.02");
print_info (")\n");
print_info ("\n");
print_info ("\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\n");
}
// Create the PCLVisualizer object
boost::shared_ptr<pcl_visualization::PCLVisualizer> p;
ColorHandlerPtr color_handler;
GeometryHandlerPtr geometry_handler;
std::vector<double> fcolor_r, fcolor_b, fcolor_g;
bool fcolorparam = false;
struct EventHelper
{
void cloud_cb (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud)
{
//std::cout << __PRETTY_FUNCTION__ << " " << cloud->width << std::endl;
// Add the dataset with a XYZ and a random handler
// geometry_handler.reset (new pcl_visualization::PointCloudGeometryHandlerXYZ<pcl::PointCloud<pcl::PointXYZRGB> > (*cloud));
//// If color was given, ues that
//if (fcolorparam)
// color_handler.reset (new pcl_visualization::PointCloudColorHandlerCustom<pcl::PointCloud<pcl::PointXYZRGB> > (cloud, fcolor_r, fcolor_g, fcolor_b));
//else
// color_handler.reset (new pcl_visualization::PointCloudColorHandlerRandom<pcl::PointCloud<pcl::PointXYZRGB> > (cloud));
// Add the cloud to the renderer
boost::mutex::scoped_lock lock (mutex_);
if (!cloud)
return;
p->removePointCloud ("PCDCloud");
p->addPointCloud (*cloud, "PCDCloud");
}
};
/* ---[ */
int
main (int argc, char** argv)
{
srand (time (0));
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (std::string (argv[i]) == "-h")
{
printHelp (argc, argv);
return (-1);
}
}
}
// Command line parsing
double bcolor[3] = {0, 0, 0};
terminal_tools::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]);
fcolorparam = terminal_tools::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b);
int psize = 0;
terminal_tools::parse_argument (argc, argv, "-ps", psize);
double opaque;
terminal_tools::parse_argument (argc, argv, "-opaque", opaque);
p.reset (new pcl_visualization::PCLVisualizer (argc, argv, "PCD viewer"));
// // Change the cloud rendered point size
// if (psize > 0)
// p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_POINT_SIZE, psize, "KinectCloud");
//
// // Change the cloud rendered opacity
// if (opaque >= 0)
// p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_OPACITY, opaque, "KinectCloud");
p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);
//boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1));
//boost::function<void (boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1);
//boost::signals2::connection c =
// interface->registerCallback <void(boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).);
// Read axes settings
double axes = 0.0;
terminal_tools::parse_argument (argc, argv, "-ax", axes);
if (axes != 0.0 && p)
{
double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;
terminal_tools::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false);
// Draw XYZ axes if command-line enabled
p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);
}
pcl::Grabber* interface = 0;
float frames_per_second = 0; // 0 means only if triggered!
terminal_tools::parse (argc, argv, "-fps", frames_per_second);
if (frames_per_second < 0)
frames_per_second = 0.0;
std::cout << terminal_tools::find_argument (argc, argv, "-repeat") << " : repaet" << std::endl;
bool repeat = (terminal_tools::find_argument (argc, argv, "-repeat") != -1);
std::cout << "fps: " << frames_per_second << " , repeat: " << repeat << std::endl;
std::string path = "";
terminal_tools::parse_argument (argc, argv, "-file", path);
std::cout << "path: " << path << std::endl;
if (path != "" && exists (path))
{
interface = new pcl::PCDGrabber<pcl::PointXYZ > (path, frames_per_second, repeat);
}
else
{
std::vector<std::string> pcd_files;
terminal_tools::parse_argument (argc, argv, "-dir", path);
std::cout << "path: " << path << std::endl;
if (path != "" && exists (path))
{
directory_iterator end_itr;
for (directory_iterator itr (path); itr != end_itr; ++itr)
{
if (!is_directory (itr->status()) && boost::algorithm::to_upper_copy(extension (itr->leaf())) == ".PCD" )
{
pcd_files.push_back (itr->path ().string());
std::cout << "added: " << itr->path ().string() << std::endl;
}
}
}
else
{
std::cout << "Neither a pcd file given using the \"-file\" option, nor given a directory containing pcd files using the \"-dir\" option." << std::endl;
}
interface = new pcl::PCDGrabber<pcl::PointXYZ > (pcd_files, frames_per_second, repeat);
}
EventHelper h;
boost::function<void(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
boost::signals2::connection c1 = interface->registerCallback (f);
interface->start ();
while (true)
{
usleep (10000);
{
boost::mutex::scoped_lock lock (mutex_);
p->spinOnce ();
if (p->wasStopped ())
break;
}
}
interface->stop ();
}
/* ]--- */
<|endoftext|>
|
<commit_before>
#include <boost/asio.hpp>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>
#include "vtrc-bind.h"
#include "vtrc-function.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-random-device.h"
#include "vtrc-protocol-layer-c.h"
#include "vtrc-transport-iface.h"
#include "vtrc-client.h"
#include "vtrc-chrono.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
namespace vtrc { namespace client {
namespace gpb = google::protobuf;
namespace {
typedef vtrc::shared_ptr <
vtrc_rpc_lowlevel::lowlevel_unit
> lowlevel_unit_sptr;
typedef vtrc::shared_ptr<gpb::Service> service_str;
enum protocol_stage {
STAGE_HELLO = 1
,STAGE_SETUP = 2
,STAGE_READY = 3
,STAGE_RPC = 4
};
}
struct protocol_layer_c::impl {
typedef impl this_type;
typedef protocol_layer_c parent_type;
typedef vtrc::function<void (void)> stage_funcion_type;
common::transport_iface *connection_;
protocol_layer_c *parent_;
stage_funcion_type stage_call_;
vtrc_client *client_;
protocol_stage stage_;
impl( common::transport_iface *c, vtrc_client *client )
:connection_(c)
,client_(client)
,stage_(STAGE_HELLO)
{
stage_call_ = vtrc::bind( &this_type::on_hello_call, this );
}
void change_stage( protocol_stage stage )
{
stage_ = stage;
switch ( stage_ ) {
case STAGE_HELLO:
stage_call_ = vtrc::bind( &this_type::on_hello_call, this );
break;
case STAGE_SETUP:
stage_call_ = vtrc::bind( &this_type::on_trans_setup, this );
break;
case STAGE_READY:
stage_call_ = vtrc::bind( &this_type::on_server_ready, this );
break;
case STAGE_RPC:
stage_call_ = vtrc::bind( &this_type::on_rpc_process, this );
break;
}
}
void init( )
{
}
void check_disconnect_stage( )
{
switch ( stage_ ) {
case STAGE_HELLO:
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server in not ready");
break;
case STAGE_SETUP:
parent_->on_init_error(
create_error( vtrc_errors::ERR_INVALID_VALUE, "" ),
"Bad setup info.");
break;
case STAGE_READY:
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Bad session key.");
break;
case STAGE_RPC:
default:
break;
}
}
vtrc_errors::container create_error( unsigned code,
const std::string &add )
{
vtrc_errors::container cont;
cont.set_code( code );
cont.set_category( vtrc_errors::CATEGORY_INTERNAL );
cont.set_additional( add );
}
const std::string &client_id( ) const
{
return client_->get_session_id( );
}
common::rpc_service_wrapper_sptr get_service_by_name(
const std::string &name )
{
return common::rpc_service_wrapper_sptr
(new common::rpc_service_wrapper(
client_->get_rpc_handler( name )));
}
void pop_message( )
{
parent_->pop_message( );
}
void send_proto_message( const gpb::Message &mess ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ) );
}
void send_proto_message( const gpb::Message &mess,
common::closure_type closure,
bool on_send ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ), closure, on_send );
}
void process_event_impl( vtrc_client_wptr client,
lowlevel_unit_sptr llu)
{
vtrc_client_sptr c(client.lock( ));
if( !c ) return;
parent_->make_call( llu );
}
void process_event( lowlevel_unit_sptr &llu )
{
client_->get_rpc_service( ).post(
vtrc::bind( &this_type::process_event_impl, this,
client_->weak_from_this( ), llu));
}
void process_service( lowlevel_unit_sptr &llu )
{
}
void process_internal( lowlevel_unit_sptr &llu )
{
}
void process_call( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_callback( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_invalid( lowlevel_unit_sptr &llu )
{
// llu->Clear( );
// parent_->send_message( *llu );
}
void on_ready( bool ready )
{
parent_->set_ready( ready );
client_->on_ready_( );
}
void on_rpc_process( )
{
while( !parent_->message_queue( ).empty( ) ) {
std::string &mess (parent_->message_queue( ).front( ));
bool check = parent_->check_message( mess );
lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());
if( !check ) {
vtrc_errors::container *err = llu->mutable_error( );
err->set_code(vtrc_errors::ERR_PROTOCOL);
err->set_additional("Bad message was received");
err->set_fatal( true );
parent_->push_rpc_message_all( llu );
connection_->close( );
return;
}
parent_->parse_message( mess, *llu );
switch( llu->info( ).message_type( ) ) {
case vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT:
process_event( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK:
process_callback( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_SERVICE:
process_service( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_INTERNAL:
process_internal( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_CALL:
case vtrc_rpc_lowlevel::message_info::MESSAGE_INSERTION_CALL:
process_call( llu );
break;
default:
process_invalid( llu );
}
pop_message( );
}
}
void on_server_ready( )
{
std::string &mess = parent_->message_queue( ).front( );
bool check = parent_->check_message( mess );
vtrc_auth::init_capsule capsule;
if( check ) {
parent_->parse_message( mess, capsule );
} else {
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server's 'Ready' has bad hash. Bad session key." );
connection_->close( );
return;
}
if( !capsule.ready( ) ) {
parent_->on_init_error(capsule.error( ),
"Server is not ready; stage: 'Ready'");
}
pop_message( );
change_stage( STAGE_RPC );
on_ready( true );
}
void on_trans_setup( )
{
using namespace common::transformers;
std::string &mess = parent_->message_queue( ).front( );
bool check = parent_->check_message( mess );
if( !check ) {
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server's 'Setup' has bad hash." );
connection_->close( );
return;
}
vtrc_auth::init_capsule capsule;
parent_->parse_message( mess, capsule );
parent_->pop_message( );
if( !capsule.ready( ) ) {
parent_->on_init_error( capsule.error( ),
"Server is not ready; stage: 'Setup'" );
connection_->close( );
return;
}
vtrc_auth::transformer_setup tsetup;
tsetup.ParseFromString( capsule.body( ) );
std::string key(client_->get_session_key( ));
std::string s1(tsetup.salt1( ));
std::string s2(tsetup.salt2( ));
create_key( key, s1, s2, key );
common::transformer_iface *new_transformer =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_transformer( new_transformer );
key.assign( client_->get_session_key( ) );
generate_key_infos( key, s1, s2, key );
tsetup.set_salt1( s1 );
tsetup.set_salt2( s2 );
common::transformer_iface *new_reverter =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_revertor( new_reverter );
capsule.set_ready( true );
capsule.set_body( tsetup.SerializeAsString( ) );
change_stage( STAGE_READY );
send_proto_message( capsule );
}
void set_options( const boost::system::error_code &err )
{
if( !err ) {
std::cout << "set opts\n";
parent_->change_hash_maker(
common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));
}
}
void on_hello_call( )
{
std::string &mess = parent_->message_queue( ).front( );
bool check = parent_->check_message( mess );
if( !check ) {
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server's 'Hello' has bad hash." );
connection_->close( );
return;
}
vtrc_auth::init_capsule capsule;
parent_->parse_message( mess, capsule );
if( !capsule.ready( ) ) {
parent_->on_init_error(capsule.error( ),
"Server is not ready; stage: 'Hello'");
connection_->close( );
return;
}
pop_message( );
vtrc_auth::client_selection init;
capsule.set_ready( true );
capsule.set_text( "Miten menee?" );
bool key_set = client_->is_key_set( );
if( !key_set ) {
init.set_transform( vtrc_auth::TRANSFORM_NONE );
} else {
init.set_transform( vtrc_auth::TRANSFORM_ERSEEFOR );
init.set_id( client_->get_session_id( ) );
}
init.set_hash( vtrc_auth::HASH_CRC_32 );
capsule.set_body( init.SerializeAsString( ) );
parent_->change_hash_checker(
common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));
change_stage( key_set ? STAGE_SETUP : STAGE_READY );
send_proto_message( capsule,
vtrc::bind( &this_type::set_options, this, _1 ),
false );
}
void data_ready( )
{
stage_call_( );
}
};
protocol_layer_c::protocol_layer_c( common::transport_iface *connection,
vtrc::client::vtrc_client *client )
:common::protocol_layer(connection, true)
,impl_(new impl(connection, client))
{
impl_->parent_ = this;
}
protocol_layer_c::~protocol_layer_c( )
{
delete impl_;
}
void protocol_layer_c::init( )
{
impl_->init( );
}
void protocol_layer_c::close( )
{
impl_->check_disconnect_stage( );
impl_->client_->on_disconnect_( );
}
const std::string &protocol_layer_c::client_id( ) const
{
return impl_->client_id( );
}
void protocol_layer_c::on_data_ready( )
{
impl_->data_ready( );
}
void protocol_layer_c::on_init_error(const vtrc_errors::container &error,
const char *message)
{
impl_->client_->on_init_error_( error, message );
}
common::rpc_service_wrapper_sptr protocol_layer_c::get_service_by_name(
const std::string &name)
{
return impl_->get_service_by_name( name );
}
}}
<commit_msg>return<commit_after>
#include <boost/asio.hpp>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>
#include "vtrc-bind.h"
#include "vtrc-function.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-random-device.h"
#include "vtrc-protocol-layer-c.h"
#include "vtrc-transport-iface.h"
#include "vtrc-client.h"
#include "vtrc-chrono.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
namespace vtrc { namespace client {
namespace gpb = google::protobuf;
namespace {
typedef vtrc::shared_ptr <
vtrc_rpc_lowlevel::lowlevel_unit
> lowlevel_unit_sptr;
typedef vtrc::shared_ptr<gpb::Service> service_str;
enum protocol_stage {
STAGE_HELLO = 1
,STAGE_SETUP = 2
,STAGE_READY = 3
,STAGE_RPC = 4
};
}
struct protocol_layer_c::impl {
typedef impl this_type;
typedef protocol_layer_c parent_type;
typedef vtrc::function<void (void)> stage_funcion_type;
common::transport_iface *connection_;
protocol_layer_c *parent_;
stage_funcion_type stage_call_;
vtrc_client *client_;
protocol_stage stage_;
impl( common::transport_iface *c, vtrc_client *client )
:connection_(c)
,client_(client)
,stage_(STAGE_HELLO)
{
stage_call_ = vtrc::bind( &this_type::on_hello_call, this );
}
void change_stage( protocol_stage stage )
{
stage_ = stage;
switch ( stage_ ) {
case STAGE_HELLO:
stage_call_ = vtrc::bind( &this_type::on_hello_call, this );
break;
case STAGE_SETUP:
stage_call_ = vtrc::bind( &this_type::on_trans_setup, this );
break;
case STAGE_READY:
stage_call_ = vtrc::bind( &this_type::on_server_ready, this );
break;
case STAGE_RPC:
stage_call_ = vtrc::bind( &this_type::on_rpc_process, this );
break;
}
}
void init( )
{
}
void check_disconnect_stage( )
{
switch ( stage_ ) {
case STAGE_HELLO:
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server in not ready");
break;
case STAGE_SETUP:
parent_->on_init_error(
create_error( vtrc_errors::ERR_INVALID_VALUE, "" ),
"Bad setup info.");
break;
case STAGE_READY:
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Bad session key.");
break;
case STAGE_RPC:
default:
break;
}
}
vtrc_errors::container create_error( unsigned code,
const std::string &add )
{
vtrc_errors::container cont;
cont.set_code( code );
cont.set_category( vtrc_errors::CATEGORY_INTERNAL );
cont.set_additional( add );
return cont;
}
const std::string &client_id( ) const
{
return client_->get_session_id( );
}
common::rpc_service_wrapper_sptr get_service_by_name(
const std::string &name )
{
return common::rpc_service_wrapper_sptr
(new common::rpc_service_wrapper(
client_->get_rpc_handler( name )));
}
void pop_message( )
{
parent_->pop_message( );
}
void send_proto_message( const gpb::Message &mess ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ) );
}
void send_proto_message( const gpb::Message &mess,
common::closure_type closure,
bool on_send ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ), closure, on_send );
}
void process_event_impl( vtrc_client_wptr client,
lowlevel_unit_sptr llu)
{
vtrc_client_sptr c(client.lock( ));
if( !c ) return;
parent_->make_call( llu );
}
void process_event( lowlevel_unit_sptr &llu )
{
client_->get_rpc_service( ).post(
vtrc::bind( &this_type::process_event_impl, this,
client_->weak_from_this( ), llu));
}
void process_service( lowlevel_unit_sptr &llu )
{
}
void process_internal( lowlevel_unit_sptr &llu )
{
}
void process_call( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_callback( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_invalid( lowlevel_unit_sptr &llu )
{
// llu->Clear( );
// parent_->send_message( *llu );
}
void on_ready( bool ready )
{
parent_->set_ready( ready );
client_->on_ready_( );
}
void on_rpc_process( )
{
while( !parent_->message_queue( ).empty( ) ) {
std::string &mess (parent_->message_queue( ).front( ));
bool check = parent_->check_message( mess );
lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());
if( !check ) {
vtrc_errors::container *err = llu->mutable_error( );
err->set_code(vtrc_errors::ERR_PROTOCOL);
err->set_additional("Bad message was received");
err->set_fatal( true );
parent_->push_rpc_message_all( llu );
connection_->close( );
return;
}
parent_->parse_message( mess, *llu );
switch( llu->info( ).message_type( ) ) {
case vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT:
process_event( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK:
process_callback( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_SERVICE:
process_service( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_INTERNAL:
process_internal( llu );
break;
case vtrc_rpc_lowlevel::message_info::MESSAGE_CALL:
case vtrc_rpc_lowlevel::message_info::MESSAGE_INSERTION_CALL:
process_call( llu );
break;
default:
process_invalid( llu );
}
pop_message( );
}
}
void on_server_ready( )
{
std::string &mess = parent_->message_queue( ).front( );
bool check = parent_->check_message( mess );
vtrc_auth::init_capsule capsule;
if( check ) {
parent_->parse_message( mess, capsule );
} else {
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server's 'Ready' has bad hash. Bad session key." );
connection_->close( );
return;
}
if( !capsule.ready( ) ) {
parent_->on_init_error(capsule.error( ),
"Server is not ready; stage: 'Ready'");
}
pop_message( );
change_stage( STAGE_RPC );
on_ready( true );
}
void on_trans_setup( )
{
using namespace common::transformers;
std::string &mess = parent_->message_queue( ).front( );
bool check = parent_->check_message( mess );
if( !check ) {
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server's 'Setup' has bad hash." );
connection_->close( );
return;
}
vtrc_auth::init_capsule capsule;
parent_->parse_message( mess, capsule );
parent_->pop_message( );
if( !capsule.ready( ) ) {
parent_->on_init_error( capsule.error( ),
"Server is not ready; stage: 'Setup'" );
connection_->close( );
return;
}
vtrc_auth::transformer_setup tsetup;
tsetup.ParseFromString( capsule.body( ) );
std::string key(client_->get_session_key( ));
std::string s1(tsetup.salt1( ));
std::string s2(tsetup.salt2( ));
create_key( key, s1, s2, key );
common::transformer_iface *new_transformer =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_transformer( new_transformer );
key.assign( client_->get_session_key( ) );
generate_key_infos( key, s1, s2, key );
tsetup.set_salt1( s1 );
tsetup.set_salt2( s2 );
common::transformer_iface *new_reverter =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_revertor( new_reverter );
capsule.set_ready( true );
capsule.set_body( tsetup.SerializeAsString( ) );
change_stage( STAGE_READY );
send_proto_message( capsule );
}
void set_options( const boost::system::error_code &err )
{
if( !err ) {
std::cout << "set opts\n";
parent_->change_hash_maker(
common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));
}
}
void on_hello_call( )
{
std::string &mess = parent_->message_queue( ).front( );
bool check = parent_->check_message( mess );
if( !check ) {
parent_->on_init_error(
create_error( vtrc_errors::ERR_INTERNAL, "" ),
"Server's 'Hello' has bad hash." );
connection_->close( );
return;
}
vtrc_auth::init_capsule capsule;
parent_->parse_message( mess, capsule );
if( !capsule.ready( ) ) {
parent_->on_init_error(capsule.error( ),
"Server is not ready; stage: 'Hello'");
connection_->close( );
return;
}
pop_message( );
vtrc_auth::client_selection init;
capsule.set_ready( true );
capsule.set_text( "Miten menee?" );
bool key_set = client_->is_key_set( );
if( !key_set ) {
init.set_transform( vtrc_auth::TRANSFORM_NONE );
} else {
init.set_transform( vtrc_auth::TRANSFORM_ERSEEFOR );
init.set_id( client_->get_session_id( ) );
}
init.set_hash( vtrc_auth::HASH_CRC_32 );
capsule.set_body( init.SerializeAsString( ) );
parent_->change_hash_checker(
common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));
change_stage( key_set ? STAGE_SETUP : STAGE_READY );
send_proto_message( capsule,
vtrc::bind( &this_type::set_options, this, _1 ),
false );
}
void data_ready( )
{
stage_call_( );
}
};
protocol_layer_c::protocol_layer_c( common::transport_iface *connection,
vtrc::client::vtrc_client *client )
:common::protocol_layer(connection, true)
,impl_(new impl(connection, client))
{
impl_->parent_ = this;
}
protocol_layer_c::~protocol_layer_c( )
{
delete impl_;
}
void protocol_layer_c::init( )
{
impl_->init( );
}
void protocol_layer_c::close( )
{
impl_->check_disconnect_stage( );
impl_->client_->on_disconnect_( );
}
const std::string &protocol_layer_c::client_id( ) const
{
return impl_->client_id( );
}
void protocol_layer_c::on_data_ready( )
{
impl_->data_ready( );
}
void protocol_layer_c::on_init_error(const vtrc_errors::container &error,
const char *message)
{
impl_->client_->on_init_error_( error, message );
}
common::rpc_service_wrapper_sptr protocol_layer_c::get_service_by_name(
const std::string &name)
{
return impl_->get_service_by_name( name );
}
}}
<|endoftext|>
|
<commit_before>#include "MazeFileUtilities.h"
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#elif __linux
#include <limits.h>
#include <unistd.h>
#endif
namespace sim {
std::string getProjectDirectory(){
// This approach is claimed to be more reliable than argv[0] on windows
// and linux. On Windows GetModuleFileName is the directory to the executable
// which is located in /mms/src/Debug/. On linux /proc/self/exe is a path to exe.
// This aproach does not work for all flavors to Linux, should on the common.
// executable on Linux is located at /mms/bin/
std::string path;
#ifdef _WIN32
char result[MAX_PATH];
path = std::string(result, GetModuleFileName(NULL, result, MAX_PATH));
path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path
path += "\\..\\..\\"; // Point to /mms/
// Windows uses \ in directory
#elif __linux
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
path = std::string(result, (count > 0) ? count : 0);
path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path
path += "/../"; // Point to /mms/
#endif
return path;
}
std::string getMazeFileDirPath(){
std::string path;
path = getProjectDirectory();
// Append mazeFile directory path from the root of the project
path += "src/maze_files/";
return path;
}
/*int mazeFileWidth(std::string mazeFilePath){
}
int mazeFileHeight(std::string mazeFilePath){
}
*/
bool checkValidMazeFile(std::string mazeFilePath){
// TODO: Ensure that you have unique y values for all x values
// TODO: Ensure that the walls line up
// TODO: Make a mazeFileValidator - gets height, width, valid, etc
// This function validates following:
// 1.) There are an equal number of y values for each x value
// 2.) All the x and y values are unique
// 3.) The walls are valid
// Create the file object
std::ifstream file(mazeFilePath.c_str());
// Initialize a string variable
std::string line("");
if (file.is_open()){
// Vector that counts the number of y values colums for each x value // TODO
std::vector<int> counts;
counts.push_back(0);
int xValue = 0;
while (getline(file, line)){
std::istringstream iss(line);
std::vector<std::string> tokens;
copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(tokens));
// Counting logic // TODO
/*if (tokens.at(0) == xValue){
counts.at(xValue) += 1;
}
else{
xValue = tokens.at(0);
counts.push_back(1);
}*/
}
file.close();
/*int numberOfYValues = counts.at(0);
for (int i = 1; i < counts.size(); i += 1){
if (counts.at(i) != numberOfYValues){
return 0;
}
}*/
}
// false indicates invalid file
return false;
}
bool checkValidMazeFileTom(std::string mazeFilePath, int height, int width){
// Create the file object
std::ifstream file(mazeFilePath.c_str());
if (!file.is_open())
return false; // Error opening file
// Initialize a string variable
std::string line("");
int x_pos = 0;
int y_pos = 0;
int expected_x_pos = 0;
int expected_y_pos = 0;
int current_int = 0;
while (std::getline(file, line)){
for (int i = 0; i < 6; i += 1){
try { // When did this happen << ?
current_int = std::stoi(line, nullptr, 10); //Attempt to get an integer which is followed by a space
}
catch (const std::invalid_argument& ia) {
return false; // If not then something in the maze file is not valid
}
if (i == 0){ // X Pos
if (current_int != expected_x_pos){
return false;
}
x_pos = current_int;
if (x_pos == width)
return false; // Too many lines, RUN
}
if (i == 1){ // Y Pos
if (current_int != expected_y_pos){
return false;
}
if (current_int == height - 1) { // Wrap Around
expected_y_pos = 0;
expected_x_pos += 1; // X-Pos will increase
} else{
expected_y_pos += 1;
}
x_pos = current_int;
}
if (i > 1){ // Wall Values - check if 1 or 0
if (current_int != 0 && current_int != 1){
return false;
}
}
std::size_t found = line.find_first_of(" ");
if (found != std::string::npos) { // extra space exists in the string
line = line.substr(line.find_first_of(" ") + 1, line.length());
if (i == 5){
return false; // return false if more spaces after last digit remain
}
}
else{
if (i != 5)
return false; // If no more spaces before the last digit that means the line
// does not have enough digits
}
}
if (expected_x_pos == width)
break;
}
if (x_pos != width && y_pos != 0)
return false; //Not all lines present in the last group
return true; //should be fine
}
} // namespace sim
<commit_msg>Changed the Maze Validator exception<commit_after>#include "MazeFileUtilities.h"
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#elif __linux
#include <limits.h>
#include <unistd.h>
#endif
namespace sim {
std::string getProjectDirectory(){
// This approach is claimed to be more reliable than argv[0] on windows
// and linux. On Windows GetModuleFileName is the directory to the executable
// which is located in /mms/src/Debug/. On linux /proc/self/exe is a path to exe.
// This aproach does not work for all flavors to Linux, should on the common.
// executable on Linux is located at /mms/bin/
std::string path;
#ifdef _WIN32
char result[MAX_PATH];
path = std::string(result, GetModuleFileName(NULL, result, MAX_PATH));
path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path
path += "\\..\\..\\"; // Point to /mms/
// Windows uses \ in directory
#elif __linux
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
path = std::string(result, (count > 0) ? count : 0);
path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path
path += "/../"; // Point to /mms/
#endif
return path;
}
std::string getMazeFileDirPath(){
std::string path;
path = getProjectDirectory();
// Append mazeFile directory path from the root of the project
path += "src/maze_files/";
return path;
}
/*int mazeFileWidth(std::string mazeFilePath){
}
int mazeFileHeight(std::string mazeFilePath){
}
*/
bool checkValidMazeFile(std::string mazeFilePath){
// TODO: Ensure that you have unique y values for all x values
// TODO: Ensure that the walls line up
// TODO: Make a mazeFileValidator - gets height, width, valid, etc
// This function validates following:
// 1.) There are an equal number of y values for each x value
// 2.) All the x and y values are unique
// 3.) The walls are valid
// Create the file object
std::ifstream file(mazeFilePath.c_str());
// Initialize a string variable
std::string line("");
if (file.is_open()){
// Vector that counts the number of y values colums for each x value // TODO
std::vector<int> counts;
counts.push_back(0);
int xValue = 0;
while (getline(file, line)){
std::istringstream iss(line);
std::vector<std::string> tokens;
copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(tokens));
// Counting logic // TODO
/*if (tokens.at(0) == xValue){
counts.at(xValue) += 1;
}
else{
xValue = tokens.at(0);
counts.push_back(1);
}*/
}
file.close();
/*int numberOfYValues = counts.at(0);
for (int i = 1; i < counts.size(); i += 1){
if (counts.at(i) != numberOfYValues){
return 0;
}
}*/
}
// false indicates invalid file
return false;
}
bool checkValidMazeFileTom(std::string mazeFilePath, int height, int width){
// Create the file object
std::ifstream file(mazeFilePath.c_str());
if (!file.is_open())
return false; // Error opening file
// Initialize a string variable
std::string line("");
int x_pos = 0;
int y_pos = 0;
int expected_x_pos = 0;
int expected_y_pos = 0;
int current_int = 0;
while (std::getline(file, line)){
for (int i = 0; i < 6; i += 1){
try { // When did this happen << ?
current_int = std::stoi(line, nullptr, 10); //Attempt to get an integer which is followed by a space
}
//catch (const std::invalid_argument& ia) { // TODO: Tomasz
catch (...) {
return false; // If not then something in the maze file is not valid
}
if (i == 0){ // X Pos
if (current_int != expected_x_pos){
return false;
}
x_pos = current_int;
if (x_pos == width)
return false; // Too many lines, RUN
}
if (i == 1){ // Y Pos
if (current_int != expected_y_pos){
return false;
}
if (current_int == height - 1) { // Wrap Around
expected_y_pos = 0;
expected_x_pos += 1; // X-Pos will increase
} else{
expected_y_pos += 1;
}
x_pos = current_int;
}
if (i > 1){ // Wall Values - check if 1 or 0
if (current_int != 0 && current_int != 1){
return false;
}
}
std::size_t found = line.find_first_of(" ");
if (found != std::string::npos) { // extra space exists in the string
line = line.substr(line.find_first_of(" ") + 1, line.length());
if (i == 5){
return false; // return false if more spaces after last digit remain
}
}
else{
if (i != 5)
return false; // If no more spaces before the last digit that means the line
// does not have enough digits
}
}
if (expected_x_pos == width)
break;
}
if (x_pos != width && y_pos != 0)
return false; //Not all lines present in the last group
return true; //should be fine
}
} // namespace sim
<|endoftext|>
|
<commit_before>// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_BUFFER_INPUT_HPP
#define TAO_PEGTL_BUFFER_INPUT_HPP
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include "config.hpp"
#include "eol.hpp"
#include "memory_input.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/bump.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
namespace TAO_PEGTL_NAMESPACE
{
template< typename Reader, typename Eol = eol::lf_crlf, typename Source = std::string, std::size_t Chunk = 64 >
class buffer_input
{
public:
using reader_t = Reader;
using eol_t = Eol;
using source_t = Source;
using iterator_t = internal::iterator;
using action_t = internal::action_input< buffer_input >;
static constexpr std::size_t chunk_size = Chunk;
static constexpr tracking_mode tracking_mode_v = tracking_mode::eager;
template< typename T, typename... As >
buffer_input( T&& in_source, const std::size_t maximum, As&&... as )
: m_reader( std::forward< As >( as )... ),
m_maximum( maximum + Chunk ),
m_buffer( new char[ maximum + Chunk ] ),
m_current( m_buffer.get() ),
m_end( m_buffer.get() ),
m_source( std::forward< T >( in_source ) )
{
static_assert( Chunk, "zero chunk size not implemented" );
assert( m_maximum > maximum ); // Catches overflow; change to >= when zero chunk size is implemented.
}
buffer_input( const buffer_input& ) = delete;
buffer_input( buffer_input&& ) = delete;
~buffer_input() = default;
void operator=( const buffer_input& ) = delete;
void operator=( buffer_input&& ) = delete;
[[nodiscard]] bool empty()
{
require( 1 );
return m_current.data == m_end;
}
[[nodiscard]] std::size_t size( const std::size_t amount )
{
require( amount );
return buffer_occupied();
}
[[nodiscard]] const char* current() const noexcept
{
return m_current.data;
}
[[nodiscard]] const char* end( const std::size_t amount )
{
require( amount );
return m_end;
}
[[nodiscard]] std::size_t byte() const noexcept
{
return m_current.byte;
}
[[nodiscard]] std::size_t line() const noexcept
{
return m_current.line;
}
[[nodiscard]] std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
[[nodiscard]] const Source& source() const noexcept
{
return m_source;
}
[[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept
{
return m_current.data[ offset ];
}
[[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept
{
return static_cast< std::uint8_t >( peek_char( offset ) );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
void discard() noexcept
{
if( m_current.data > m_buffer.get() + Chunk ) {
const auto s = m_end - m_current.data;
std::memmove( m_buffer.get(), m_current.data, s );
m_current.data = m_buffer.get();
m_end = m_buffer.get() + s;
}
}
void require( const std::size_t amount )
{
if( m_current.data + amount <= m_end ) {
return;
}
if( m_current.data + amount > m_buffer.get() + m_maximum ) {
throw std::runtime_error( "require beyond end of buffer" );
}
if( const auto r = m_reader( m_end, ( std::min )( buffer_free_after_end(), ( std::max )( amount, Chunk ) ) ) ) {
m_end += r;
}
}
template< rewind_mode M >
[[nodiscard]] internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( m_current );
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const
{
return position( m_current );
}
[[nodiscard]] const iterator_t& iterator() const noexcept
{
return m_current;
}
[[nodiscard]] std::size_t buffer_capacity() const noexcept
{
return m_maximum;
}
[[nodiscard]] std::size_t buffer_occupied() const noexcept
{
assert( m_end >= m_current.data );
return std::size_t( m_end - m_current.data );
}
[[nodiscard]] std::size_t buffer_free_before_current() const noexcept
{
assert( m_current.data >= m_buffer.get() );
return std::size_t( m_current.data - m_buffer.get() );
}
[[nodiscard]] std::size_t buffer_free_after_end() const noexcept
{
assert( m_buffer.get() + m_maximum >= m_end );
return std::size_t( m_buffer.get() + m_maximum - m_end );
}
private:
Reader m_reader;
std::size_t m_maximum;
std::unique_ptr< char[] > m_buffer; // NOLINT
iterator_t m_current;
char* m_end;
const Source m_source;
};
} // namespace TAO_PEGTL_NAMESPACE
#endif
<commit_msg>Fix exception.<commit_after>// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_BUFFER_INPUT_HPP
#define TAO_PEGTL_BUFFER_INPUT_HPP
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include "config.hpp"
#include "eol.hpp"
#include "memory_input.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/bump.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
namespace TAO_PEGTL_NAMESPACE
{
template< typename Reader, typename Eol = eol::lf_crlf, typename Source = std::string, std::size_t Chunk = 64 >
class buffer_input
{
public:
using reader_t = Reader;
using eol_t = Eol;
using source_t = Source;
using iterator_t = internal::iterator;
using action_t = internal::action_input< buffer_input >;
static constexpr std::size_t chunk_size = Chunk;
static constexpr tracking_mode tracking_mode_v = tracking_mode::eager;
template< typename T, typename... As >
buffer_input( T&& in_source, const std::size_t maximum, As&&... as )
: m_reader( std::forward< As >( as )... ),
m_maximum( maximum + Chunk ),
m_buffer( new char[ maximum + Chunk ] ),
m_current( m_buffer.get() ),
m_end( m_buffer.get() ),
m_source( std::forward< T >( in_source ) )
{
static_assert( Chunk, "zero chunk size not implemented" );
assert( m_maximum > maximum ); // Catches overflow; change to >= when zero chunk size is implemented.
}
buffer_input( const buffer_input& ) = delete;
buffer_input( buffer_input&& ) = delete;
~buffer_input() = default;
void operator=( const buffer_input& ) = delete;
void operator=( buffer_input&& ) = delete;
[[nodiscard]] bool empty()
{
require( 1 );
return m_current.data == m_end;
}
[[nodiscard]] std::size_t size( const std::size_t amount )
{
require( amount );
return buffer_occupied();
}
[[nodiscard]] const char* current() const noexcept
{
return m_current.data;
}
[[nodiscard]] const char* end( const std::size_t amount )
{
require( amount );
return m_end;
}
[[nodiscard]] std::size_t byte() const noexcept
{
return m_current.byte;
}
[[nodiscard]] std::size_t line() const noexcept
{
return m_current.line;
}
[[nodiscard]] std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
[[nodiscard]] const Source& source() const noexcept
{
return m_source;
}
[[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept
{
return m_current.data[ offset ];
}
[[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept
{
return static_cast< std::uint8_t >( peek_char( offset ) );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
void discard() noexcept
{
if( m_current.data > m_buffer.get() + Chunk ) {
const auto s = m_end - m_current.data;
std::memmove( m_buffer.get(), m_current.data, s );
m_current.data = m_buffer.get();
m_end = m_buffer.get() + s;
}
}
void require( const std::size_t amount )
{
if( m_current.data + amount <= m_end ) {
return;
}
if( m_current.data + amount > m_buffer.get() + m_maximum ) {
throw std::overflow_error( "require beyond end of buffer" );
}
if( const auto r = m_reader( m_end, ( std::min )( buffer_free_after_end(), ( std::max )( amount, Chunk ) ) ) ) {
m_end += r;
}
}
template< rewind_mode M >
[[nodiscard]] internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( m_current );
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
[[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const
{
return position( m_current );
}
[[nodiscard]] const iterator_t& iterator() const noexcept
{
return m_current;
}
[[nodiscard]] std::size_t buffer_capacity() const noexcept
{
return m_maximum;
}
[[nodiscard]] std::size_t buffer_occupied() const noexcept
{
assert( m_end >= m_current.data );
return std::size_t( m_end - m_current.data );
}
[[nodiscard]] std::size_t buffer_free_before_current() const noexcept
{
assert( m_current.data >= m_buffer.get() );
return std::size_t( m_current.data - m_buffer.get() );
}
[[nodiscard]] std::size_t buffer_free_after_end() const noexcept
{
assert( m_buffer.get() + m_maximum >= m_end );
return std::size_t( m_buffer.get() + m_maximum - m_end );
}
private:
Reader m_reader;
std::size_t m_maximum;
std::unique_ptr< char[] > m_buffer; // NOLINT
iterator_t m_current;
char* m_end;
const Source m_source;
};
} // namespace TAO_PEGTL_NAMESPACE
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <array>
#include <string>
class GLFWwindow;
/**
* This class defines GLFW based OpenGL Context.
* There are two use cases of such a context :
* - headless rendering application.
* - simple window with limited interaction
*/
class OpenGLContext
{
public:
/** @defgroup context OpenGL context management
* These methods allow to create and manipulate an openGLContext.
* Using this function, the openGL context created is an offscreen context with no exposed
* window.
* @{
*/
/**
* Create an offscreen openGl context.
* The created context has the following properties
* - OpenGL version requested : >= 4.1
* - OpenGL consstext profile : Core Profile
* @param size
*/
explicit OpenGLContext( const std::array<int, 2>& size = {1, 1} );
/// destructor
~OpenGLContext();
/// make the context active
void makeCurrent() const;
/// make the context inactive
void doneCurrent() const;
/// Check for validity of the context
bool isValid() const;
[[nodiscard]] std::string getInfo() const;
/** @} */
/** @defgroup window Window management from an openGL context
* These methods allow to display and control a simple window associated with the created
* OpenGL Context
* @{
*/
/// Show the window
void show();
/// Hide the window
void hide();
/// Resize the window
void resize( const std::array<int, 2>& size );
/// Swap back/front buffers
void swapbuffers();
/// Wait for the user to close the window
void waitForClose();
/** @} */
private:
GLFWwindow* m_offscreenContext {nullptr};
};
<commit_msg>[testes] GLFWwindow forward decl as struct.<commit_after>#pragma once
#include <array>
#include <string>
struct GLFWwindow;
/**
* This class defines GLFW based OpenGL Context.
* There are two use cases of such a context :
* - headless rendering application.
* - simple window with limited interaction
*/
class OpenGLContext
{
public:
/** @defgroup context OpenGL context management
* These methods allow to create and manipulate an openGLContext.
* Using this function, the openGL context created is an offscreen context with no exposed
* window.
* @{
*/
/**
* Create an offscreen openGl context.
* The created context has the following properties
* - OpenGL version requested : >= 4.1
* - OpenGL consstext profile : Core Profile
* @param size
*/
explicit OpenGLContext( const std::array<int, 2>& size = {1, 1} );
/// destructor
~OpenGLContext();
/// make the context active
void makeCurrent() const;
/// make the context inactive
void doneCurrent() const;
/// Check for validity of the context
bool isValid() const;
[[nodiscard]] std::string getInfo() const;
/** @} */
/** @defgroup window Window management from an openGL context
* These methods allow to display and control a simple window associated with the created
* OpenGL Context
* @{
*/
/// Show the window
void show();
/// Hide the window
void hide();
/// Resize the window
void resize( const std::array<int, 2>& size );
/// Swap back/front buffers
void swapbuffers();
/// Wait for the user to close the window
void waitForClose();
/** @} */
private:
GLFWwindow* m_offscreenContext {nullptr};
};
<|endoftext|>
|
<commit_before>#ifndef TWISTEDCPP_MIXED_RECEIVER
#define TWISTEDCPP_MIXED_RECEIVER
#include "protocol_core.hpp"
#include "detail/line_receiver_parser.hpp"
#include "detail/byte_receiver_parser.hpp"
#include <boost/container/vector.hpp>
namespace twisted {
template <typename ChildProtocol>
class mixed_receiver
: public twisted::protocol_core<
ChildProtocol,
boost::iterator_range<boost::container::vector<char>::iterator>> {
public:
typedef boost::container::vector<char> internal_buffer_type;
typedef internal_buffer_type::size_type size_type;
typedef boost::iterator_range<internal_buffer_type::iterator> buffer_type;
typedef boost::iterator_range<internal_buffer_type::const_iterator>
const_buffer_type;
mixed_receiver(std::string delimiter = std::string("\r\n"))
: is_byte_mode(false), _current_begin(0), _current_count(0),
_delimiter(std::move(delimiter)), _next_bytes_size(0),
_read_buffer(32) {}
template <typename Iter>
void on_message(Iter begin, Iter end) {
_current_count += std::distance(begin, end);
bool process = false;
Iter line_start;
Iter search_iter;
process = loop_condition(search_iter, end, line_start, _current_begin,
_read_buffer, _delimiter);
while (process) {
if (is_byte_mode) {
byte::core_loop(_current_count, _current_begin, _read_buffer,
_next_bytes_size, this->this_protocol());
} else {
line::core_loop(line_start, search_iter, _delimiter,
_current_count, _current_begin,
this->this_protocol());
}
process = loop_condition(search_iter, end, line_start,
_current_begin, _read_buffer, _delimiter);
}
if (is_byte_mode) {
byte::prepare_buffers(_current_count, _current_begin, _read_buffer);
} else {
line::prepare_buffers(_current_count, _current_begin, _read_buffer);
}
}
template <typename Iter>
void send_line(Iter begin, Iter end) {
std::array<boost::asio::const_buffer, 2> buffers{
{ boost::asio::buffer(&*begin, std::distance(begin, end)),
boost::asio::buffer(&*_delimiter.begin(), _delimiter.size()) }
};
this->send_buffers(buffers);
}
buffer_type read_buffer() {
return boost::make_iterator_range(
std::next(_read_buffer.begin(), _current_begin + _current_count),
_read_buffer.end());
}
const const_buffer_type& read_buffer() const {
return boost::make_iterator_range(
std::next(_read_buffer.begin(), _current_begin + _current_count),
_read_buffer.end());
}
void set_byte_mode() { is_byte_mode = true; }
void set_line_mode() { is_byte_mode = false; }
void set_package_size(size_type package_size) {
byte::set_package_size(package_size, _next_bytes_size, _read_buffer);
}
private:
template <typename Iter>
bool loop_condition(Iter& search_iter, Iter end, Iter& line_start,
std::size_t _current_begin,
boost::container::vector<char>& _read_buffer,
const std::string& _delimiter) const {
if (is_byte_mode) {
return byte::loop_condition(_current_count, _next_bytes_size);
} else {
return line::loop_condition(search_iter, end, line_start,
_current_begin, _read_buffer,
_delimiter);
}
}
// TODO evaluate whether copying each time is faster than tracking
// _current_begin
bool is_byte_mode;
size_type _current_begin; // start-position of not processed data in buffer
size_type _current_count; // current amount of not processed data
const std::string _delimiter;
size_type _next_bytes_size;
internal_buffer_type _read_buffer;
};
}
#endif
<commit_msg>added mixed receiver docs<commit_after>#ifndef TWISTEDCPP_MIXED_RECEIVER
#define TWISTEDCPP_MIXED_RECEIVER
#include "protocol_core.hpp"
#include "detail/line_receiver_parser.hpp"
#include "detail/byte_receiver_parser.hpp"
#include <boost/container/vector.hpp>
namespace twisted {
/**
* @brief Protocol that combines the line_receiver and the byte_receiver
*
* You can switch between the two modes by calling
*
* void set_byte_mode() and void set_line_mode();
*
* Provided callbacks:
*
* void bytes_received(const_buffer_iterator begin, const_buffer_iterator end);
*
* Will be called whenever N bytes have been received. [begin, end) is the data
* range. (In byte mode)
*
* void line_received(const_buffer_iterator begin, const_buffer_iterator end);
*
* Will be called whenever a line delimited by the delimiter has been received.
* [begin, end) is the data
* range. The range does not include the delimiter. (In line mode)
*/
template <typename ChildProtocol>
class mixed_receiver
: public twisted::protocol_core<
ChildProtocol,
boost::iterator_range<boost::container::vector<char>::iterator>> {
public:
typedef boost::container::vector<char> internal_buffer_type;
typedef internal_buffer_type::size_type size_type;
typedef boost::iterator_range<internal_buffer_type::iterator> buffer_type;
typedef boost::iterator_range<internal_buffer_type::const_iterator>
const_buffer_type;
/**
* @brief constructor
* @param delimiter delimiter for the string mode
*/
mixed_receiver(std::string delimiter = std::string("\r\n"))
: is_byte_mode(false), _current_begin(0), _current_count(0),
_delimiter(std::move(delimiter)), _next_bytes_size(0),
_read_buffer(32) {}
template <typename Iter>
void on_message(Iter begin, Iter end) {
_current_count += std::distance(begin, end);
bool process = false;
Iter line_start;
Iter search_iter;
process = loop_condition(search_iter, end, line_start, _current_begin,
_read_buffer, _delimiter);
while (process) {
if (is_byte_mode) {
byte::core_loop(_current_count, _current_begin, _read_buffer,
_next_bytes_size, this->this_protocol());
} else {
line::core_loop(line_start, search_iter, _delimiter,
_current_count, _current_begin,
this->this_protocol());
}
process = loop_condition(search_iter, end, line_start,
_current_begin, _read_buffer, _delimiter);
}
if (is_byte_mode) {
byte::prepare_buffers(_current_count, _current_begin, _read_buffer);
} else {
line::prepare_buffers(_current_count, _current_begin, _read_buffer);
}
}
/**
* @brief Sends a line. Automatically adds the current delimiter
* @param begin range begin
* @param end range end
*/
template <typename Iter>
void send_line(Iter begin, Iter end) {
std::array<boost::asio::const_buffer, 2> buffers{
{ boost::asio::buffer(&*begin, std::distance(begin, end)),
boost::asio::buffer(&*_delimiter.begin(), _delimiter.size()) }
};
this->send_buffers(buffers);
}
buffer_type read_buffer() {
return boost::make_iterator_range(
std::next(_read_buffer.begin(), _current_begin + _current_count),
_read_buffer.end());
}
const const_buffer_type& read_buffer() const {
return boost::make_iterator_range(
std::next(_read_buffer.begin(), _current_begin + _current_count),
_read_buffer.end());
}
/**
* @brief puts the mixed receiver into byte mode
*/
void set_byte_mode() { is_byte_mode = true; }
/**
* @brief puts the mixed receiver into line mode
*/
void set_line_mode() { is_byte_mode = false; }
/**
* @brief sets the size in bytes of the next packet to read (byte mode)
*/
void set_package_size(size_type package_size) {
byte::set_package_size(package_size, _next_bytes_size, _read_buffer);
}
private:
template <typename Iter>
bool loop_condition(Iter& search_iter, Iter end, Iter& line_start,
std::size_t _current_begin,
boost::container::vector<char>& _read_buffer,
const std::string& _delimiter) const {
if (is_byte_mode) {
return byte::loop_condition(_current_count, _next_bytes_size);
} else {
return line::loop_condition(search_iter, end, line_start,
_current_begin, _read_buffer,
_delimiter);
}
}
// TODO evaluate whether copying each time is faster than tracking
// _current_begin
bool is_byte_mode;
size_type _current_begin; // start-position of not processed data in buffer
size_type _current_count; // current amount of not processed data
const std::string _delimiter;
size_type _next_bytes_size;
internal_buffer_type _read_buffer;
};
}
#endif
<|endoftext|>
|
<commit_before>#ifndef V_SMC_HELPER_SEQUENTIAL_HPP
#define V_SMC_HELPER_SEQUENTIAL_HPP
namespace vSMC {
/// \brief Type of weight returned by MoveSeq::move_state
///
/// \li No_ACTION The weight is discarded without further action
/// \li SET_WEIGHT The weight is set directly as the new weight
/// \li SET_LOG_WEIGHT The weight is set direclty as the new log weight
/// \li MUL_WEIGHT The weight is the incremental weight
/// \li ADD_LOG_WEIGHT The weight is the log of the incremental weight
enum WeightAction {
NO_ACTION, SET_WEIGHT, SET_LOG_WEIGHT, MUL_WEIGHT, ADD_LOG_WEIGHT};
/// \brief Particle type for helping implementing SMC sequentially
///
/// StateSeq or its derived class can be used as the template argument of
/// Particle. It targets the particular problems where the parameters to be
/// sampled can be viewed as a vector of dimension Dim and type T.
template <int Dim, typename T = double>
class StateSeq
{
public :
/// The type of parameters
typedef T value_type;
/// \brief Construct a StateSeq object with given number of particles
///
/// \param N The number of particles
StateSeq (std::size_t N) : size_(N), state_(N * Dim) {}
/// \brief The dimension of the problem
///
/// \return The dimension of the parameter vector
static int dim ()
{
return Dim;
}
/// \brief The number of particles
///
/// \return The number of particles in the current particle set
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to the array of a single particle states
///
/// \return A pointer to the states of a single particle
T *state (std::size_t n)
{
return state_.get() + n * dim();
}
/// \brief Read only access to the array of a single particle states
///
/// \return A const pointer to the states of a single array particle
const T *state (std::size_t n) const
{
return state_.get() + n * dim();
}
/// \brief Read and write access to the array of all particle states
///
/// \return A pointer to the states of all particles
///
/// \note The array is of row major order. In other words, it is ordered
/// as the first Dim elements are the states of first particle, the next
/// Dim elements are the states of the second particle, and so on.
T *state ()
{
return state_.get();
}
/// \brief Read only access to the array of all particle states
///
/// \return A const pointer to the states of all particles
const T *state () const
{
return state_.get();
}
/// \brief Read only access to the states of a particular paramter
///
/// \param id The index, starting from 0, of the paramter
/// \param first An iterator point to where writing starts
template<typename OIter>
void state (int id, OIter first) const
{
const T *src = state_.get() + id;
for (std::size_t i = 0; i != size_; ++i, src += Dim)
*first++ = *src;
}
/// \brief The copy method used by the Sampler
///
/// \param from The index of particle whose state to be copied
/// \param to The index of particle to which new state to be written
void copy (std::size_t from, std::size_t to)
{
const T *state_from = state(from);
T *state_to = state(to);
for (int i = 0; i != Dim; ++i, ++state_from, ++state_to)
*state_to = *state_from;
}
private :
std::size_t size_;
vDist::tool::Buffer<T> state_;
}; // class StateSeq
/// \brief Sampler::init_type class for helping implementing SMC sequentially
///
/// This is a abstract factory class. Object of its derived type can used as
/// the argument \b init of Sampler constructor. The derived class need to at
/// least define method initialize_state. Optionally, it can also overload the
/// method initialize_param, which will be called before initialization and
/// accept the last argument of Sampler::init_type functor as its parameter.
///
/// \note The template parameter has to be type StateSeq or its derived
/// class.
template <typename T>
class InitializeSeq
{
public :
InitializeSeq () {}
InitializeSeq (const InitializeSeq<T> &init) {}
InitializeSeq<T> & operator= (const InitializeSeq<T> &init) {return *this;}
/// \brief Operator called by Sampler for initialize the particle set
///
/// \param particle The Particle set passed by Sampler
/// \param param Additional parameters
///
/// \return Accept count
virtual std::size_t operator() (Particle<T> &particle, void *param)
{
initialize_param(particle, param);
weight_.resize(particle.size());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i) {
accept += initialize_state(particle,
particle.value().state(i), weight_[i]);
}
particle.set_log_weight(weight_);
return accept;
}
/// \brief Initialize a single particle
///
/// \param particle The Particle set passed by Sampler
/// \param state The array contains the states of a single particle
/// \param weight The log weight of the particle
///
/// \return Accept count, normally should be zero or one
virtual int initialize_state (const Particle<T> &particle,
typename T::value_type *state, double &weight) = 0;
/// \brief Initialize the Particle set
///
/// \param particle The Particle set passed by Sampler
/// \param param Additional parameter passed by Sampler
virtual void initialize_param (Particle<T> &particle, void *param) {};
private :
vDist::tool::Buffer<double> weight_;
}; // class InitializeSeq
/// \brief Sampler::move_type class for helping implementing SMC sequentially
///
/// This is a abstract factory class. Object of its derived type can be used as
/// the argument \b move or \b mcmc of Sampler constructor. The derived class
/// need to at least define method move_state. Optionally, it can also overload
/// the weight_action method to change how the returned weighted should be
/// treated.
///
/// \note The template parameter has to be type StateSeq or its derived
/// class.
template <typename T>
class MoveSeq
{
public :
MoveSeq () {}
MoveSeq (const MoveSeq<T> &move) {}
MoveSeq<T> & operator= (const MoveSeq<T> &move) {return *this;}
/// \brief Operator called by Sampler for move the particle set
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
///
/// \return Accept count
virtual std::size_t operator () (std::size_t iter, Particle<T> &particle)
{
weight_.resize(particle.size());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i) {
accept += move_state(iter, particle,
particle.value().state(i), weight_[i]);
}
set_weight(particle);
return accept;
}
/// \brief Move a single particle
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param state The array contains the states of a single particle
/// \param weight The weight of the particle. This may not be the actual
/// weight. How the returned weight is treated depend on the return from
/// another method, weight_action. The default behavior is that it is
/// treated as the log of the incremental weight. It can also be treated
/// as multiplier to the original weight, or the acutal value of the (log
/// of) weight. It can even be meaningless, namely no action is taken with
/// this weight. See WeightAction and weight_action.
virtual int move_state (std::size_t iter, const Particle<T> &particle,
typename T::value_type *state, double &weight) = 0;
/// \brief Determine how weight returned by move_state shall be treated
///
/// \return One of the enumerators of WeightAction
virtual WeightAction weight_action ()
{
return ADD_LOG_WEIGHT;
}
private :
vDist::tool::Buffer<double> weight_;
void set_weight (Particle<T> &particle)
{
switch (weight_action()) {
case NO_ACTION :
break;
case SET_WEIGHT :
vdLn(particle.size(), weight_, weight_);
case SET_LOG_WEIGHT :
particle.set_log_weight(weight_);
break;
case MUL_WEIGHT :
vdLn(particle.size(), weight_, weight_);
case ADD_LOG_WEIGHT :
particle.add_log_weight(weight_);
break;
default :
particle.add_log_weight(weight_);
break;
}
}
}; // class MoveSeq
/// \brief Monitor::integral_type class for helping implementing SMC
/// sequentially
///
/// This is a abstract factory class. Object of its derived type can be used
/// as the argument integral of Sampler::monitor(std::string,
/// Monitor<T>::integral_type integral). The derived class need to at least
/// define method monitor_state.
template <typename T>
class MonitorSeq
{
public :
/// \brief Operator called by Monitor to record Monte Carlo integration
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the Monte Carlo
/// integration result.
virtual void operator () (std::size_t iter, Particle<T> &particle,
double *res)
{
for (std::size_t i = 0; i != particle.size(); ++i)
res[i] = monitor_state(iter, particle, particle.value().state(i));
}
/// \brief Record the integrand from a single particle
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param state The array contains the states of a single particle
///
/// \return The value to be estimated
virtual double monitor_state (std::size_t iter,
const Particle<T> &particle, typename T::value_type *state) = 0;
}; // class MonitorSeq
/// \brief Path::integral_type class for helping implementing SMC sequentially
///
/// This is a abstract factory class. Object of its derived type can be used
/// as the argument integral of Sampler::path_sampling(Path<T>::integral_type
/// integral). The derived class need to at least define method path_state and
/// width_state.
template <typename T>
class PathSeq
{
public :
/// \brief Operator called by Path to record path sampling integrands and
/// widths
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the path
///
/// \return The width
/// sampling integrand.
virtual double operator () (std::size_t iter, Particle<T> &particle,
double *res)
{
for (std::size_t i = 0; i != particle.size(); ++i)
res[i] = path_state(iter, particle, particle.value().state(i));
return width_state(iter, particle);
}
/// \brief Evaluate the path sampling integrand for a single particle
///
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
/// \param state The array contains the states of a single particle
///
/// \return The value of the integrand
virtual double path_state (std::size_t iter, const Particle<T> &particle,
typename T::value_type *state) = 0;
/// \brief Evaluate the path sampling width
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
///
/// \return The value of the width
virtual double width_state (std::size_t iter,
const Particle<T> &particle) = 0;
};
} // namespace vSMC
#endif // V_SMC_HELPER_SEQUENTIAL_HPP
<commit_msg>set_weight no long use private data<commit_after>#ifndef V_SMC_HELPER_SEQUENTIAL_HPP
#define V_SMC_HELPER_SEQUENTIAL_HPP
namespace vSMC {
/// \brief Type of weight returned by MoveSeq::move_state
///
/// \li No_ACTION The weight is discarded without further action
/// \li SET_WEIGHT The weight is set directly as the new weight
/// \li SET_LOG_WEIGHT The weight is set direclty as the new log weight
/// \li MUL_WEIGHT The weight is the incremental weight
/// \li ADD_LOG_WEIGHT The weight is the log of the incremental weight
enum WeightAction {
NO_ACTION, SET_WEIGHT, SET_LOG_WEIGHT, MUL_WEIGHT, ADD_LOG_WEIGHT};
/// \brief Particle type for helping implementing SMC sequentially
///
/// StateSeq or its derived class can be used as the template argument of
/// Particle. It targets the particular problems where the parameters to be
/// sampled can be viewed as a vector of dimension Dim and type T.
template <int Dim, typename T = double>
class StateSeq
{
public :
/// The type of parameters
typedef T value_type;
/// \brief Construct a StateSeq object with given number of particles
///
/// \param N The number of particles
StateSeq (std::size_t N) : size_(N), state_(N * Dim) {}
/// \brief The dimension of the problem
///
/// \return The dimension of the parameter vector
static int dim ()
{
return Dim;
}
/// \brief The number of particles
///
/// \return The number of particles in the current particle set
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to the array of a single particle states
///
/// \return A pointer to the states of a single particle
T *state (std::size_t n)
{
return state_.get() + n * dim();
}
/// \brief Read only access to the array of a single particle states
///
/// \return A const pointer to the states of a single array particle
const T *state (std::size_t n) const
{
return state_.get() + n * dim();
}
/// \brief Read and write access to the array of all particle states
///
/// \return A pointer to the states of all particles
///
/// \note The array is of row major order. In other words, it is ordered
/// as the first Dim elements are the states of first particle, the next
/// Dim elements are the states of the second particle, and so on.
T *state ()
{
return state_.get();
}
/// \brief Read only access to the array of all particle states
///
/// \return A const pointer to the states of all particles
const T *state () const
{
return state_.get();
}
/// \brief Read only access to the states of a particular paramter
///
/// \param id The index, starting from 0, of the paramter
/// \param first An iterator point to where writing starts
template<typename OIter>
void state (int id, OIter first) const
{
const T *src = state_.get() + id;
for (std::size_t i = 0; i != size_; ++i, src += Dim)
*first++ = *src;
}
/// \brief The copy method used by the Sampler
///
/// \param from The index of particle whose state to be copied
/// \param to The index of particle to which new state to be written
void copy (std::size_t from, std::size_t to)
{
const T *state_from = state(from);
T *state_to = state(to);
for (int i = 0; i != Dim; ++i, ++state_from, ++state_to)
*state_to = *state_from;
}
private :
std::size_t size_;
vDist::tool::Buffer<T> state_;
}; // class StateSeq
/// \brief Sampler::init_type class for helping implementing SMC sequentially
///
/// This is a abstract factory class. Object of its derived type can used as
/// the argument \b init of Sampler constructor. The derived class need to at
/// least define method initialize_state. Optionally, it can also overload the
/// method initialize_param, which will be called before initialization and
/// accept the last argument of Sampler::init_type functor as its parameter.
///
/// \note The template parameter has to be type StateSeq or its derived
/// class.
template <typename T>
class InitializeSeq
{
public :
InitializeSeq () {}
InitializeSeq (const InitializeSeq<T> &init) {}
InitializeSeq<T> & operator= (const InitializeSeq<T> &init) {return *this;}
/// \brief Operator called by Sampler for initialize the particle set
///
/// \param particle The Particle set passed by Sampler
/// \param param Additional parameters
///
/// \return Accept count
virtual std::size_t operator() (Particle<T> &particle, void *param)
{
initialize_param(particle, param);
weight_.resize(particle.size());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i) {
accept += initialize_state(particle,
particle.value().state(i), weight_[i]);
}
particle.set_log_weight(weight_);
return accept;
}
/// \brief Initialize a single particle
///
/// \param particle The Particle set passed by Sampler
/// \param state The array contains the states of a single particle
/// \param weight The log weight of the particle
///
/// \return Accept count, normally should be zero or one
virtual int initialize_state (const Particle<T> &particle,
typename T::value_type *state, double &weight) = 0;
/// \brief Initialize the Particle set
///
/// \param particle The Particle set passed by Sampler
/// \param param Additional parameter passed by Sampler
virtual void initialize_param (Particle<T> &particle, void *param) {};
private :
vDist::tool::Buffer<double> weight_;
}; // class InitializeSeq
/// \brief Sampler::move_type class for helping implementing SMC sequentially
///
/// This is a abstract factory class. Object of its derived type can be used as
/// the argument \b move or \b mcmc of Sampler constructor. The derived class
/// need to at least define method move_state. Optionally, it can also overload
/// the weight_action method to change how the returned weighted should be
/// treated.
///
/// \note The template parameter has to be type StateSeq or its derived
/// class.
template <typename T>
class MoveSeq
{
public :
MoveSeq () {}
MoveSeq (const MoveSeq<T> &move) {}
MoveSeq<T> & operator= (const MoveSeq<T> &move) {return *this;}
/// \brief Operator called by Sampler for move the particle set
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
///
/// \return Accept count
virtual std::size_t operator () (std::size_t iter, Particle<T> &particle)
{
weight_.resize(particle.size());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i) {
accept += move_state(iter, particle,
particle.value().state(i), weight_[i]);
}
set_weight(weight_action(), particle, weight_.get());
return accept;
}
/// \brief Move a single particle
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param state The array contains the states of a single particle
/// \param weight The weight of the particle. This may not be the actual
/// weight. How the returned weight is treated depend on the return from
/// another method, weight_action. The default behavior is that it is
/// treated as the log of the incremental weight. It can also be treated
/// as multiplier to the original weight, or the acutal value of the (log
/// of) weight. It can even be meaningless, namely no action is taken with
/// this weight. See WeightAction and weight_action.
virtual int move_state (std::size_t iter, const Particle<T> &particle,
typename T::value_type *state, double &weight) = 0;
/// \brief Determine how weight returned by move_state shall be treated
///
/// \return One of the enumerators of WeightAction
virtual WeightAction weight_action ()
{
return ADD_LOG_WEIGHT;
}
void set_weight (WeightAction action,
Particle<T> &particle, double *weight)
{
switch (action) {
case NO_ACTION :
break;
case SET_WEIGHT :
vdLn(particle.size(), weight, weight);
case SET_LOG_WEIGHT :
particle.set_log_weight(weight);
break;
case MUL_WEIGHT :
vdLn(particle.size(), weight, weight);
case ADD_LOG_WEIGHT :
particle.add_log_weight(weight);
break;
default :
particle.add_log_weight(weight);
break;
}
}
private :
vDist::tool::Buffer<double> weight_;
}; // class MoveSeq
/// \brief Monitor::integral_type class for helping implementing SMC
/// sequentially
///
/// This is a abstract factory class. Object of its derived type can be used
/// as the argument integral of Sampler::monitor(std::string,
/// Monitor<T>::integral_type integral). The derived class need to at least
/// define method monitor_state.
template <typename T>
class MonitorSeq
{
public :
/// \brief Operator called by Monitor to record Monte Carlo integration
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the Monte Carlo
/// integration result.
virtual void operator () (std::size_t iter, Particle<T> &particle,
double *res)
{
for (std::size_t i = 0; i != particle.size(); ++i)
res[i] = monitor_state(iter, particle, particle.value().state(i));
}
/// \brief Record the integrand from a single particle
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param state The array contains the states of a single particle
///
/// \return The value to be estimated
virtual double monitor_state (std::size_t iter,
const Particle<T> &particle, typename T::value_type *state) = 0;
}; // class MonitorSeq
/// \brief Path::integral_type class for helping implementing SMC sequentially
///
/// This is a abstract factory class. Object of its derived type can be used
/// as the argument integral of Sampler::path_sampling(Path<T>::integral_type
/// integral). The derived class need to at least define method path_state and
/// width_state.
template <typename T>
class PathSeq
{
public :
/// \brief Operator called by Path to record path sampling integrands and
/// widths
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the path
///
/// \return The width
/// sampling integrand.
virtual double operator () (std::size_t iter, Particle<T> &particle,
double *res)
{
for (std::size_t i = 0; i != particle.size(); ++i)
res[i] = path_state(iter, particle, particle.value().state(i));
return width_state(iter, particle);
}
/// \brief Evaluate the path sampling integrand for a single particle
///
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
/// \param state The array contains the states of a single particle
///
/// \return The value of the integrand
virtual double path_state (std::size_t iter, const Particle<T> &particle,
typename T::value_type *state) = 0;
/// \brief Evaluate the path sampling width
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
///
/// \return The value of the width
virtual double width_state (std::size_t iter,
const Particle<T> &particle) = 0;
};
} // namespace vSMC
#endif // V_SMC_HELPER_SEQUENTIAL_HPP
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include <QDebug>
#include "akonadi.h"
#include "akonadiconnection.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "status.h"
#include "response.h"
using namespace Akonadi;
Status::Status(): Handler()
{
}
Status::~Status()
{
}
bool Status::handleLine( const QByteArray& line )
{
// Arguments: mailbox name
// status data item names
// Syntax:
// status = "STATUS" SP mailbox SP "(" status-att *(SP status-att) ")"
// status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" / "UNSEEN"
const int startOfCommand = line.indexOf( ' ' ) + 1;
const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
const int endOfMailbox = line.indexOf( ' ', startOfMailbox );
const QByteArray mailbox = stripQuotes( line.mid( startOfMailbox, endOfMailbox - startOfMailbox ) );
const QByteArray statusAttributes = line.mid( endOfMailbox + 2, line.size() - ( endOfMailbox + 2 ) - 1 );
const QList<QByteArray> attributeList = statusAttributes.split( ' ' );
Response response;
DataStore *db = connection()->storageBackend();
Location l = db->locationByRawMailbox( mailbox );
if ( !l.isValid() )
return failureResponse( "No status for this folder" );
// Responses:
// REQUIRED untagged responses: STATUS
// build STATUS response
QString statusResponse;
// MESSAGES - The number of messages in the mailbox
if ( attributeList.contains( "MESSAGES" ) ) {
statusResponse += "MESSAGES ";
statusResponse += QString::number( l.exists() );
}
// RECENT - The number of messages with the \Recent flag set
if ( attributeList.contains( "RECENT" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " RECENT ";
else
statusResponse += "RECENT ";
statusResponse += QString::number( l.recent() );
}
// UIDNEXT - The next unique identifier value of the mailbox
if ( attributeList.contains( "UIDNEXT" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " UIDNEXT ";
else
statusResponse += "UIDNEXT ";
statusResponse += QString::number( db->uidNext() );
}
// UIDVALIDITY - The unique identifier validity value of the mailbox
if ( attributeList.contains( "UIDVALIDITY" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " UIDVALIDITY ";
else
statusResponse += "UIDVALIDITY ";
statusResponse += QString::number( l.uidValidity() );
}
if ( attributeList.contains( "UNSEEN" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " UNSEEN ";
else
statusResponse += "UNSEEN ";
statusResponse += QString::number( l.unseen() );
}
response.setUntagged();
response.setString( "STATUS " + mailbox + " (" + statusResponse + ')' );
emit responseAvailable( response );
response.setSuccess();
response.setTag( tag() );
response.setString( "STATUS completed" );
emit responseAvailable( response );
deleteLater();
return true;
}
<commit_msg>Handle collection names with spaces.<commit_after>/***************************************************************************
* Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include <QDebug>
#include "akonadi.h"
#include "akonadiconnection.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "status.h"
#include "response.h"
#include "handlerhelper.h"
using namespace Akonadi;
Status::Status(): Handler()
{
}
Status::~Status()
{
}
bool Status::handleLine( const QByteArray& line )
{
// Arguments: mailbox name
// status data item names
// Syntax:
// status = "STATUS" SP mailbox SP "(" status-att *(SP status-att) ")"
// status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" / "UNSEEN"
const int startOfCommand = line.indexOf( ' ' ) + 1;
const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
QByteArray mailbox;
const int endOfMailbox = HandlerHelper::parseQuotedString( line, mailbox, startOfMailbox );
const QByteArray statusAttributes = line.mid( endOfMailbox + 2, line.size() - ( endOfMailbox + 2 ) - 1 );
const QList<QByteArray> attributeList = statusAttributes.split( ' ' );
Response response;
DataStore *db = connection()->storageBackend();
Location l = db->locationByRawMailbox( mailbox );
if ( !l.isValid() )
return failureResponse( "No status for this folder" );
// Responses:
// REQUIRED untagged responses: STATUS
// build STATUS response
QString statusResponse;
// MESSAGES - The number of messages in the mailbox
if ( attributeList.contains( "MESSAGES" ) ) {
statusResponse += "MESSAGES ";
statusResponse += QString::number( l.exists() );
}
// RECENT - The number of messages with the \Recent flag set
if ( attributeList.contains( "RECENT" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " RECENT ";
else
statusResponse += "RECENT ";
statusResponse += QString::number( l.recent() );
}
// UIDNEXT - The next unique identifier value of the mailbox
if ( attributeList.contains( "UIDNEXT" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " UIDNEXT ";
else
statusResponse += "UIDNEXT ";
statusResponse += QString::number( db->uidNext() );
}
// UIDVALIDITY - The unique identifier validity value of the mailbox
if ( attributeList.contains( "UIDVALIDITY" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " UIDVALIDITY ";
else
statusResponse += "UIDVALIDITY ";
statusResponse += QString::number( l.uidValidity() );
}
if ( attributeList.contains( "UNSEEN" ) ) {
if ( !statusResponse.isEmpty() )
statusResponse += " UNSEEN ";
else
statusResponse += "UNSEEN ";
statusResponse += QString::number( l.unseen() );
}
response.setUntagged();
response.setString( "STATUS " + mailbox + " (" + statusResponse + ')' );
emit responseAvailable( response );
response.setSuccess();
response.setTag( tag() );
response.setString( "STATUS completed" );
emit responseAvailable( response );
deleteLater();
return true;
}
<|endoftext|>
|
<commit_before>#include <float.h>
#include <functional>
#include <iostream> // NOLINT(readability/streams)
#include "geometry/grassmann.hpp"
#include "geometry/r3_element.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/dimensionless.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/explicit_operators.hpp"
using principia::astronomy::JulianYear;
using principia::astronomy::Parsec;
using principia::constants::SpeedOfLight;
using principia::quantities::Dimensionless;
using principia::quantities::Length;
using principia::quantities::Product;
using principia::quantities::Speed;
using principia::quantities::Sqrt;
using principia::quantities::Time;
using principia::si::Day;
using principia::si::Metre;
using principia::si::Second;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::Times;
using principia::uk::admiralty::Fathom;
using principia::uk::Foot;
using principia::uk::Furlong;
using principia::uk::Inch;
using principia::uk::Rod;
using testing::Eq;
namespace principia {
namespace geometry {
class GrassmannTest : public testing::Test {
protected:
struct World;
template<typename LScalar, typename RScalar, typename Frame, int Rank>
static Product<LScalar, RScalar> MultivectorInnerProduct(
Multivector<LScalar, Frame, Rank> const& left,
Multivector<RScalar, Frame, Rank> const& right) {
return InnerProduct(left, right);
}
template<typename LScalar, typename RScalar, typename Frame, int LRank,
int RRank>
static Multivector<Product<LScalar, RScalar>, Frame, LRank + RRank>
Multivectorwedge(Multivector<LScalar, Frame, LRank> const& left,
Multivector<RScalar, Frame, RRank> const& right) {
return Wedge(left, right);
}
R3Element<Length> const null_displacement_ = {0 * Metre,
0 * Metre,
0 * Metre};
R3Element<Length> const u_ = {3 * Metre, -42 * Metre, 0 * Metre};
R3Element<Length> const v_ = {-π * Metre, -e * Metre, -1 * Metre};
R3Element<Length> const w_ = {2 * Metre, 2 * Metre, 2 * Metre};
R3Element<Length> const a_ = {1 * Inch, 2 * Foot, 3 * Fathom};
};
TEST_F(GrassmannTest, Operators) {
testing_utilities::TestEquality(Bivector<Length, World>(u_),
Bivector<Length, World>(v_));
testing_utilities::TestEquality(Vector<Length, World>(u_),
Vector<Length, World>(v_));
testing_utilities::TestEquality(Trivector<Length, World>(u_.x),
Trivector<Length, World>(v_.x));
std::cout << "vector: " << Vector<Length, World>(u_) << "\n";
std::cout << "bivector: " << Bivector<Length, World>(u_) << "\n";
std::cout << "trivector: " << Trivector<Length, World>(u_.x) << "\n";
}
TEST_F(GrassmannTest, SpecialOrthogonalLieAlgebra) {
testing_utilities::TestLieBracket(
Commutator<Dimensionless, Dimensionless, World>,
Bivector<Dimensionless, World>(u_ / Foot),
Bivector<Dimensionless, World>(v_ / Metre),
Bivector<Dimensionless, World>(w_ / Rod),
Bivector<Dimensionless, World>(a_ / Furlong),
Dimensionless(0.42), 1000 / DBL_EPSILON);
}
TEST_F(GrassmannTest, MixedScalarMultiplication) {
testing_utilities::TestBilinearMap(
Times<Vector<Speed, World>, Time::Inverse, Vector<Length, World>>,
1 / Second,
1 / JulianYear,
Vector<Length, World>(u_),
Vector<Length, World>(v_),
Dimensionless(42),
2);
testing_utilities::TestBilinearMap(
Times<Vector<Speed, World>, Vector<Length, World>, Time::Inverse>,
Vector<Length, World>(w_),
Vector<Length, World>(a_),
-1 / Day,
SpeedOfLight / Parsec,
Dimensionless(-π),
1);
Time::Inverse t = -3 / Second;
EXPECT_EQ((t * Vector<Length, World>(u_)), (Vector<Length, World>(u_) * t));
EXPECT_EQ((Vector<Length, World>(v_) * t) / t, (Vector<Length, World>(v_)));
}
TEST_F(GrassmannTest, VectorSpaces) {
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Length, Length, World, 1>,
Vector<Length, World>(null_displacement_),
Vector<Length, World>(u_),
Vector<Length, World>(v_),
Vector<Length, World>(w_),
Vector<Length, World>(a_),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Length, Length, World, 2>,
Bivector<Length, World>(null_displacement_),
Bivector<Length, World>(u_),
Bivector<Length, World>(v_),
Bivector<Length, World>(w_),
Bivector<Length, World>(a_),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Length, Length, World, 3>,
Trivector<Length, World>(null_displacement_.x),
Trivector<Length, World>(u_.y),
Trivector<Length, World>(v_.z),
Trivector<Length, World>(w_.x),
Trivector<Length, World>(a_.y),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2));
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Dimensionless, Dimensionless, World, 1>,
Vector<Dimensionless, World>(null_displacement_ / Metre),
Vector<Dimensionless, World>(u_ / Metre),
Vector<Dimensionless, World>(v_ / Metre),
Vector<Dimensionless, World>(w_ / Metre),
Vector<Dimensionless, World>(a_ / Metre),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Dimensionless, Dimensionless, World, 2>,
Bivector<Dimensionless, World>(null_displacement_ / Metre),
Bivector<Dimensionless, World>(u_ / Metre),
Bivector<Dimensionless, World>(v_ / Metre),
Bivector<Dimensionless, World>(w_ / Metre),
Bivector<Dimensionless, World>(a_ / Metre),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Dimensionless, Dimensionless, World, 3>,
Trivector<Dimensionless, World>(null_displacement_.x / Metre),
Trivector<Dimensionless, World>(u_.y / Metre),
Trivector<Dimensionless, World>(v_.z / Metre),
Trivector<Dimensionless, World>(w_.x / Metre),
Trivector<Dimensionless, World>(a_.y / Metre),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2));
}
TEST_F(GrassmannTest, GrassmannAlgebra) {
testing_utilities::TestAlternatingBilinearMap(
Multivectorwedge<Dimensionless, Dimensionless, World, 1, 1>,
Vector<Dimensionless, World>(u_ / Metre),
Vector<Dimensionless, World>(v_ / Metre),
Vector<Dimensionless, World>(w_ / Metre),
Vector<Dimensionless, World>(a_ / Metre),
Dimensionless(6 * 9),
2);
testing_utilities::TestBilinearMap(
Multivectorwedge<Length, Speed, World, 1, 2>,
Vector<Length, World>(u_),
Vector<Length, World>(v_),
Bivector<Speed, World>(w_ / Second),
Bivector<Speed, World>(a_ / Second),
Dimensionless(6 * 9),
2);
testing_utilities::TestBilinearMap(
Multivectorwedge<Length, Speed, World, 2, 1>,
Bivector<Length, World>(u_),
Bivector<Length, World>(v_),
Vector<Speed, World>(w_ / Second),
Vector<Speed, World>(a_ / Second),
Dimensionless(6 * 9),
2);
EXPECT_EQ(
Wedge(Vector<Speed, World>(v_ / Second), Bivector<Length, World>(u_)),
Wedge(Bivector<Length, World>(u_), Vector<Speed, World>(v_ / Second)));
}
TEST_F(GrassmannTest, Actions) {
Vector<Length, World> const a(u_);
Vector<Length, World> const b(v_);
Bivector<Length, World> const β(v_);
Bivector<Length, World> const γ(w_);
// A strongly typed version of the Lagrange formula
// a × (b × c) = b (a · c) - c (a · b).
EXPECT_THAT(a * Commutator(β, γ),
AlmostEquals(β * Wedge(a, γ) - γ * Wedge(a, β), 26));
EXPECT_THAT(Commutator(β, γ) * a,
AlmostEquals(Wedge(a, β) * γ - β * Wedge(a, γ), 26));
EXPECT_THAT(a * Wedge(b, γ), AlmostEquals(Wedge(γ, b) * a, 21));
}
} // namespace geometry
} // namespace principia
<commit_msg>Readying<commit_after>#include <float.h>
#include <functional>
#include <iostream> // NOLINT(readability/streams)
#include "geometry/grassmann.hpp"
#include "geometry/r3_element.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/dimensionless.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/explicit_operators.hpp"
using principia::astronomy::JulianYear;
using principia::astronomy::Parsec;
using principia::constants::SpeedOfLight;
using principia::quantities::Dimensionless;
using principia::quantities::Length;
using principia::quantities::Product;
using principia::quantities::Speed;
using principia::quantities::Sqrt;
using principia::quantities::Time;
using principia::si::Day;
using principia::si::Metre;
using principia::si::Second;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::Times;
using principia::uk::admiralty::Fathom;
using principia::uk::Foot;
using principia::uk::Furlong;
using principia::uk::Inch;
using principia::uk::Rod;
using testing::Eq;
namespace principia {
namespace geometry {
class GrassmannTest : public testing::Test {
protected:
struct World;
template<typename LScalar, typename RScalar, typename Frame, int Rank>
static Product<LScalar, RScalar> MultivectorInnerProduct(
Multivector<LScalar, Frame, Rank> const& left,
Multivector<RScalar, Frame, Rank> const& right) {
return InnerProduct(left, right);
}
template<typename LScalar, typename RScalar, typename Frame, int LRank,
int RRank>
static Multivector<Product<LScalar, RScalar>, Frame, LRank + RRank>
Multivectorwedge(Multivector<LScalar, Frame, LRank> const& left,
Multivector<RScalar, Frame, RRank> const& right) {
return Wedge(left, right);
}
R3Element<Length> const null_displacement_ = {0 * Metre,
0 * Metre,
0 * Metre};
R3Element<Length> const u_ = {3 * Metre, -42 * Metre, 0 * Metre};
R3Element<Length> const v_ = {-π * Metre, -e * Metre, -1 * Metre};
R3Element<Length> const w_ = {2 * Metre, 2 * Metre, 2 * Metre};
R3Element<Length> const a_ = {1 * Inch, 2 * Foot, 3 * Fathom};
};
TEST_F(GrassmannTest, Operators) {
testing_utilities::TestEquality(Bivector<Length, World>(u_),
Bivector<Length, World>(v_));
testing_utilities::TestEquality(Vector<Length, World>(u_),
Vector<Length, World>(v_));
testing_utilities::TestEquality(Trivector<Length, World>(u_.x),
Trivector<Length, World>(v_.x));
std::cout << "vector: " << Vector<Length, World>(u_) << "\n";
std::cout << "bivector: " << Bivector<Length, World>(u_) << "\n";
std::cout << "trivector: " << Trivector<Length, World>(u_.x) << "\n";
}
TEST_F(GrassmannTest, SpecialOrthogonalLieAlgebra) {
testing_utilities::TestLieBracket(
Commutator<Dimensionless, Dimensionless, World>,
Bivector<Dimensionless, World>(u_ / Foot),
Bivector<Dimensionless, World>(v_ / Metre),
Bivector<Dimensionless, World>(w_ / Rod),
Bivector<Dimensionless, World>(a_ / Furlong),
Dimensionless(0.42), static_cast<int64_t>(1000 / DBL_EPSILON));
}
TEST_F(GrassmannTest, MixedScalarMultiplication) {
testing_utilities::TestBilinearMap(
Times<Vector<Speed, World>, Time::Inverse, Vector<Length, World>>,
1 / Second,
1 / JulianYear,
Vector<Length, World>(u_),
Vector<Length, World>(v_),
Dimensionless(42),
2);
testing_utilities::TestBilinearMap(
Times<Vector<Speed, World>, Vector<Length, World>, Time::Inverse>,
Vector<Length, World>(w_),
Vector<Length, World>(a_),
-1 / Day,
SpeedOfLight / Parsec,
Dimensionless(-π),
1);
Time::Inverse t = -3 / Second;
EXPECT_EQ((t * Vector<Length, World>(u_)), (Vector<Length, World>(u_) * t));
EXPECT_EQ((Vector<Length, World>(v_) * t) / t, (Vector<Length, World>(v_)));
}
TEST_F(GrassmannTest, VectorSpaces) {
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Length, Length, World, 1>,
Vector<Length, World>(null_displacement_),
Vector<Length, World>(u_),
Vector<Length, World>(v_),
Vector<Length, World>(w_),
Vector<Length, World>(a_),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Length, Length, World, 2>,
Bivector<Length, World>(null_displacement_),
Bivector<Length, World>(u_),
Bivector<Length, World>(v_),
Bivector<Length, World>(w_),
Bivector<Length, World>(a_),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Length, Length, World, 3>,
Trivector<Length, World>(null_displacement_.x),
Trivector<Length, World>(u_.y),
Trivector<Length, World>(v_.z),
Trivector<Length, World>(w_.x),
Trivector<Length, World>(a_.y),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2));
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Dimensionless, Dimensionless, World, 1>,
Vector<Dimensionless, World>(null_displacement_ / Metre),
Vector<Dimensionless, World>(u_ / Metre),
Vector<Dimensionless, World>(v_ / Metre),
Vector<Dimensionless, World>(w_ / Metre),
Vector<Dimensionless, World>(a_ / Metre),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Dimensionless, Dimensionless, World, 2>,
Bivector<Dimensionless, World>(null_displacement_ / Metre),
Bivector<Dimensionless, World>(u_ / Metre),
Bivector<Dimensionless, World>(v_ / Metre),
Bivector<Dimensionless, World>(w_ / Metre),
Bivector<Dimensionless, World>(a_ / Metre),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2), 18);
testing_utilities::TestInnerProductSpace(
MultivectorInnerProduct<Dimensionless, Dimensionless, World, 3>,
Trivector<Dimensionless, World>(null_displacement_.x / Metre),
Trivector<Dimensionless, World>(u_.y / Metre),
Trivector<Dimensionless, World>(v_.z / Metre),
Trivector<Dimensionless, World>(w_.x / Metre),
Trivector<Dimensionless, World>(a_.y / Metre),
Dimensionless(0), Dimensionless(1), Sqrt(163),
-Sqrt(2));
}
TEST_F(GrassmannTest, GrassmannAlgebra) {
testing_utilities::TestAlternatingBilinearMap(
Multivectorwedge<Dimensionless, Dimensionless, World, 1, 1>,
Vector<Dimensionless, World>(u_ / Metre),
Vector<Dimensionless, World>(v_ / Metre),
Vector<Dimensionless, World>(w_ / Metre),
Vector<Dimensionless, World>(a_ / Metre),
Dimensionless(6 * 9),
2);
testing_utilities::TestBilinearMap(
Multivectorwedge<Length, Speed, World, 1, 2>,
Vector<Length, World>(u_),
Vector<Length, World>(v_),
Bivector<Speed, World>(w_ / Second),
Bivector<Speed, World>(a_ / Second),
Dimensionless(6 * 9),
2);
testing_utilities::TestBilinearMap(
Multivectorwedge<Length, Speed, World, 2, 1>,
Bivector<Length, World>(u_),
Bivector<Length, World>(v_),
Vector<Speed, World>(w_ / Second),
Vector<Speed, World>(a_ / Second),
Dimensionless(6 * 9),
2);
EXPECT_EQ(
Wedge(Vector<Speed, World>(v_ / Second), Bivector<Length, World>(u_)),
Wedge(Bivector<Length, World>(u_), Vector<Speed, World>(v_ / Second)));
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(GrassmannTest, Actions) {
Vector<Length, World> const a(u_);
Vector<Length, World> const b(v_);
Bivector<Length, World> const β(v_);
Bivector<Length, World> const γ(w_);
// A strongly typed version of the Lagrange formula
// a × (b × c) = b (a · c) - c (a · b).
EXPECT_THAT(a * Commutator(β, γ),
AlmostEquals(β * Wedge(a, γ) - γ * Wedge(a, β), 26));
EXPECT_THAT(Commutator(β, γ) * a,
AlmostEquals(Wedge(a, β) * γ - β * Wedge(a, γ), 26));
EXPECT_THAT(a * Wedge(b, γ), AlmostEquals(Wedge(γ, b) * a, 21));
}
#pragma warning(default: 4566)
} // namespace geometry
} // namespace principia
<|endoftext|>
|
<commit_before>/**
* @file llpacketbuffer.cpp
* @brief implementation of LLPacketBuffer class for a packet.
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llpacketbuffer.h"
#include "net.h"
#include "timing.h"
#include "llhost.h"
///////////////////////////////////////////////////////////
LLPacketBuffer::LLPacketBuffer(const LLHost &host, const char *datap, const S32 size) : mHost(host)
{
if (size > NET_BUFFER_SIZE)
{
llerrs << "Sending packet > " << NET_BUFFER_SIZE << " of size " << size << llendl;
}
else // we previously relied on llerrs being fatal to not get here...
{
if (datap != NULL)
{
memcpy(mData, datap, size);
mSize = size;
}
}
}
LLPacketBuffer::LLPacketBuffer (S32 hSocket)
{
init(hSocket);
}
///////////////////////////////////////////////////////////
LLPacketBuffer::~LLPacketBuffer ()
{
}
///////////////////////////////////////////////////////////
void LLPacketBuffer::init (S32 hSocket)
{
mSize = receive_packet(hSocket, mData);
mHost = ::get_sender();
mReceivingIF = ::get_receiving_interface();
}
<commit_msg>CID-277<commit_after>/**
* @file llpacketbuffer.cpp
* @brief implementation of LLPacketBuffer class for a packet.
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llpacketbuffer.h"
#include "net.h"
#include "timing.h"
#include "llhost.h"
///////////////////////////////////////////////////////////
LLPacketBuffer::LLPacketBuffer(const LLHost &host, const char *datap, const S32 size) : mHost(host)
{
if (size > NET_BUFFER_SIZE)
{
mSize = 0;
mData[0] = 0;
llerrs << "Sending packet > " << NET_BUFFER_SIZE << " of size " << size << llendl;
}
else // we previously relied on llerrs being fatal to not get here...
{
if (datap != NULL)
{
memcpy(mData, datap, size);
mSize = size;
}
}
}
LLPacketBuffer::LLPacketBuffer (S32 hSocket)
{
init(hSocket);
}
///////////////////////////////////////////////////////////
LLPacketBuffer::~LLPacketBuffer ()
{
}
///////////////////////////////////////////////////////////
void LLPacketBuffer::init (S32 hSocket)
{
mSize = receive_packet(hSocket, mData);
mHost = ::get_sender();
mReceivingIF = ::get_receiving_interface();
}
<|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/net/url_request_slow_download_job.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_filter.h"
const int kFirstDownloadSize = 1024 * 35;
const int kSecondDownloadSize = 1024 * 10;
const char URLRequestSlowDownloadJob::kUnknownSizeUrl[] =
"http://url.handled.by.slow.download/download-unknown-size";
const char URLRequestSlowDownloadJob::kKnownSizeUrl[] =
"http://url.handled.by.slow.download/download-known-size";
const char URLRequestSlowDownloadJob::kFinishDownloadUrl[] =
"http://url.handled.by.slow.download/download-finish";
std::vector<URLRequestSlowDownloadJob*>
URLRequestSlowDownloadJob::kPendingRequests;
void URLRequestSlowDownloadJob::Start() {
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&URLRequestSlowDownloadJob::StartAsync));
}
/* static */
void URLRequestSlowDownloadJob::AddUrlHandler() {
URLRequestFilter* filter = URLRequestFilter::GetInstance();
filter->AddUrlHandler(GURL(kUnknownSizeUrl),
&URLRequestSlowDownloadJob::Factory);
filter->AddUrlHandler(GURL(kKnownSizeUrl),
&URLRequestSlowDownloadJob::Factory);
filter->AddUrlHandler(GURL(kFinishDownloadUrl),
&URLRequestSlowDownloadJob::Factory);
}
/*static */
URLRequestJob* URLRequestSlowDownloadJob::Factory(URLRequest* request,
const std::string& scheme) {
URLRequestSlowDownloadJob* job = new URLRequestSlowDownloadJob(request);
if (request->url().spec() != kFinishDownloadUrl)
URLRequestSlowDownloadJob::kPendingRequests.push_back(job);
return job;
}
/* static */
void URLRequestSlowDownloadJob::FinishPendingRequests() {
typedef std::vector<URLRequestSlowDownloadJob*> JobList;
for (JobList::iterator it = kPendingRequests.begin(); it !=
kPendingRequests.end(); ++it) {
(*it)->set_should_finish_download();
}
kPendingRequests.clear();
}
URLRequestSlowDownloadJob::URLRequestSlowDownloadJob(URLRequest* request)
: URLRequestJob(request),
first_download_size_remaining_(kFirstDownloadSize),
should_finish_download_(false),
should_send_second_chunk_(false) {
}
void URLRequestSlowDownloadJob::StartAsync() {
if (LowerCaseEqualsASCII(kFinishDownloadUrl, request_->url().spec().c_str()))
URLRequestSlowDownloadJob::FinishPendingRequests();
NotifyHeadersComplete();
}
bool URLRequestSlowDownloadJob::ReadRawData(net::IOBuffer* buf, int buf_size,
int *bytes_read) {
if (LowerCaseEqualsASCII(kFinishDownloadUrl,
request_->url().spec().c_str())) {
*bytes_read = 0;
return true;
}
if (should_send_second_chunk_) {
DCHECK(buf_size > kSecondDownloadSize);
for (int i = 0; i < kSecondDownloadSize; ++i) {
buf->data()[i] = '*';
}
*bytes_read = kSecondDownloadSize;
should_send_second_chunk_ = false;
return true;
}
if (first_download_size_remaining_ > 0) {
int send_size = std::min(first_download_size_remaining_, buf_size);
for (int i = 0; i < send_size; ++i) {
buf->data()[i] = '*';
}
*bytes_read = send_size;
first_download_size_remaining_ -= send_size;
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
DCHECK(!is_done());
return true;
}
if (should_finish_download_) {
*bytes_read = 0;
return true;
}
// If we make it here, the first chunk has been sent and we need to wait
// until a request is made for kFinishDownloadUrl.
MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestSlowDownloadJob::CheckDoneStatus), 100);
AddRef();
// Return false to signal there is pending data.
return false;
}
void URLRequestSlowDownloadJob::CheckDoneStatus() {
if (should_finish_download_) {
should_send_second_chunk_ = true;
SetStatus(URLRequestStatus());
NotifyReadComplete(kSecondDownloadSize);
Release();
} else {
MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestSlowDownloadJob::CheckDoneStatus), 100);
}
}
// Public virtual version.
void URLRequestSlowDownloadJob::GetResponseInfo(net::HttpResponseInfo* info) {
// Forward to private const version.
GetResponseInfoConst(info);
}
// Private const version.
void URLRequestSlowDownloadJob::GetResponseInfoConst(
net::HttpResponseInfo* info) const {
// Send back mock headers.
std::string raw_headers;
if (LowerCaseEqualsASCII(kFinishDownloadUrl,
request_->url().spec().c_str())) {
raw_headers.append(
"HTTP/1.1 200 OK\n"
"Content-type: text/plain\n");
} else {
raw_headers.append(
"HTTP/1.1 200 OK\n"
"Content-type: application/octet-stream\n"
"Cache-Control: max-age=0\n");
if (LowerCaseEqualsASCII(kKnownSizeUrl, request_->url().spec().c_str())) {
raw_headers.append(StringPrintf("Content-Length: %d\n",
kFirstDownloadSize + kSecondDownloadSize));
}
}
// ParseRawHeaders expects \0 to end each header line.
ReplaceSubstringsAfterOffset(&raw_headers, 0, "\n", std::string("\0", 1));
info->headers = new net::HttpResponseHeaders(raw_headers);
}
bool URLRequestSlowDownloadJob::GetMimeType(std::string* mime_type) const {
net::HttpResponseInfo info;
GetResponseInfoConst(&info);
return info.headers && info.headers->GetMimeType(mime_type);
}
<commit_msg>Fix ReadRawData to make the job state match the return value.<commit_after>// 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/net/url_request_slow_download_job.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_filter.h"
const int kFirstDownloadSize = 1024 * 35;
const int kSecondDownloadSize = 1024 * 10;
const char URLRequestSlowDownloadJob::kUnknownSizeUrl[] =
"http://url.handled.by.slow.download/download-unknown-size";
const char URLRequestSlowDownloadJob::kKnownSizeUrl[] =
"http://url.handled.by.slow.download/download-known-size";
const char URLRequestSlowDownloadJob::kFinishDownloadUrl[] =
"http://url.handled.by.slow.download/download-finish";
std::vector<URLRequestSlowDownloadJob*>
URLRequestSlowDownloadJob::kPendingRequests;
void URLRequestSlowDownloadJob::Start() {
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&URLRequestSlowDownloadJob::StartAsync));
}
/* static */
void URLRequestSlowDownloadJob::AddUrlHandler() {
URLRequestFilter* filter = URLRequestFilter::GetInstance();
filter->AddUrlHandler(GURL(kUnknownSizeUrl),
&URLRequestSlowDownloadJob::Factory);
filter->AddUrlHandler(GURL(kKnownSizeUrl),
&URLRequestSlowDownloadJob::Factory);
filter->AddUrlHandler(GURL(kFinishDownloadUrl),
&URLRequestSlowDownloadJob::Factory);
}
/*static */
URLRequestJob* URLRequestSlowDownloadJob::Factory(URLRequest* request,
const std::string& scheme) {
URLRequestSlowDownloadJob* job = new URLRequestSlowDownloadJob(request);
if (request->url().spec() != kFinishDownloadUrl)
URLRequestSlowDownloadJob::kPendingRequests.push_back(job);
return job;
}
/* static */
void URLRequestSlowDownloadJob::FinishPendingRequests() {
typedef std::vector<URLRequestSlowDownloadJob*> JobList;
for (JobList::iterator it = kPendingRequests.begin(); it !=
kPendingRequests.end(); ++it) {
(*it)->set_should_finish_download();
}
kPendingRequests.clear();
}
URLRequestSlowDownloadJob::URLRequestSlowDownloadJob(URLRequest* request)
: URLRequestJob(request),
first_download_size_remaining_(kFirstDownloadSize),
should_finish_download_(false),
should_send_second_chunk_(false) {
}
void URLRequestSlowDownloadJob::StartAsync() {
if (LowerCaseEqualsASCII(kFinishDownloadUrl, request_->url().spec().c_str()))
URLRequestSlowDownloadJob::FinishPendingRequests();
NotifyHeadersComplete();
}
bool URLRequestSlowDownloadJob::ReadRawData(net::IOBuffer* buf, int buf_size,
int *bytes_read) {
if (LowerCaseEqualsASCII(kFinishDownloadUrl,
request_->url().spec().c_str())) {
*bytes_read = 0;
return true;
}
if (should_send_second_chunk_) {
DCHECK(buf_size > kSecondDownloadSize);
for (int i = 0; i < kSecondDownloadSize; ++i) {
buf->data()[i] = '*';
}
*bytes_read = kSecondDownloadSize;
should_send_second_chunk_ = false;
return true;
}
if (first_download_size_remaining_ > 0) {
int send_size = std::min(first_download_size_remaining_, buf_size);
for (int i = 0; i < send_size; ++i) {
buf->data()[i] = '*';
}
*bytes_read = send_size;
first_download_size_remaining_ -= send_size;
DCHECK(!is_done());
return true;
}
if (should_finish_download_) {
*bytes_read = 0;
return true;
}
// If we make it here, the first chunk has been sent and we need to wait
// until a request is made for kFinishDownloadUrl.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestSlowDownloadJob::CheckDoneStatus), 100);
AddRef();
// Return false to signal there is pending data.
return false;
}
void URLRequestSlowDownloadJob::CheckDoneStatus() {
if (should_finish_download_) {
should_send_second_chunk_ = true;
SetStatus(URLRequestStatus());
NotifyReadComplete(kSecondDownloadSize);
Release();
} else {
MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestSlowDownloadJob::CheckDoneStatus), 100);
}
}
// Public virtual version.
void URLRequestSlowDownloadJob::GetResponseInfo(net::HttpResponseInfo* info) {
// Forward to private const version.
GetResponseInfoConst(info);
}
// Private const version.
void URLRequestSlowDownloadJob::GetResponseInfoConst(
net::HttpResponseInfo* info) const {
// Send back mock headers.
std::string raw_headers;
if (LowerCaseEqualsASCII(kFinishDownloadUrl,
request_->url().spec().c_str())) {
raw_headers.append(
"HTTP/1.1 200 OK\n"
"Content-type: text/plain\n");
} else {
raw_headers.append(
"HTTP/1.1 200 OK\n"
"Content-type: application/octet-stream\n"
"Cache-Control: max-age=0\n");
if (LowerCaseEqualsASCII(kKnownSizeUrl, request_->url().spec().c_str())) {
raw_headers.append(StringPrintf("Content-Length: %d\n",
kFirstDownloadSize + kSecondDownloadSize));
}
}
// ParseRawHeaders expects \0 to end each header line.
ReplaceSubstringsAfterOffset(&raw_headers, 0, "\n", std::string("\0", 1));
info->headers = new net::HttpResponseHeaders(raw_headers);
}
bool URLRequestSlowDownloadJob::GetMimeType(std::string* mime_type) const {
net::HttpResponseInfo info;
GetResponseInfoConst(&info);
return info.headers && info.headers->GetMimeType(mime_type);
}
<|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/password_manager/password_store_x.h"
#include <algorithm>
#include <map>
#include <vector>
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/password_manager/password_store_change.h"
#include "content/browser/browser_thread.h"
#include "content/common/notification_service.h"
using std::vector;
using webkit_glue::PasswordForm;
PasswordStoreX::PasswordStoreX(LoginDatabase* login_db,
Profile* profile,
WebDataService* web_data_service,
NativeBackend* backend)
: PasswordStoreDefault(login_db, profile, web_data_service),
backend_(backend), migration_checked_(!backend), allow_fallback_(false) {
}
PasswordStoreX::~PasswordStoreX() {
}
void PasswordStoreX::AddLoginImpl(const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->AddLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::AddLoginImpl(form);
}
}
void PasswordStoreX::UpdateLoginImpl(const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->UpdateLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::UPDATE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::UpdateLoginImpl(form);
}
}
void PasswordStoreX::RemoveLoginImpl(const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->RemoveLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::RemoveLoginImpl(form);
}
}
void PasswordStoreX::RemoveLoginsCreatedBetweenImpl(
const base::Time& delete_begin,
const base::Time& delete_end) {
CheckMigration();
vector<PasswordForm*> forms;
if (use_native_backend() &&
backend_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms) &&
backend_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) {
PasswordStoreChangeList changes;
for (vector<PasswordForm*>::const_iterator it = forms.begin();
it != forms.end(); ++it) {
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE,
**it));
}
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl(delete_begin,
delete_end);
}
STLDeleteElements(&forms);
}
namespace {
struct LoginLessThan {
bool operator()(const PasswordForm* a, const PasswordForm* b) {
return a->origin < b->origin;
}
};
} // anonymous namespace
void PasswordStoreX::SortLoginsByOrigin(NativeBackend::PasswordFormList* list) {
// In login_database.cc, the query has ORDER BY origin_url. Simulate that.
std::sort(list->begin(), list->end(), LoginLessThan());
}
void PasswordStoreX::GetLoginsImpl(GetLoginsRequest* request,
const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->GetLogins(form, &request->value)) {
SortLoginsByOrigin(&request->value);
ForwardLoginsResult(request);
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::GetLoginsImpl(request, form);
} else {
// The consumer will be left hanging unless we reply.
ForwardLoginsResult(request);
}
}
void PasswordStoreX::GetAutofillableLoginsImpl(GetLoginsRequest* request) {
CheckMigration();
if (use_native_backend() &&
backend_->GetAutofillableLogins(&request->value)) {
SortLoginsByOrigin(&request->value);
ForwardLoginsResult(request);
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::GetAutofillableLoginsImpl(request);
} else {
// The consumer will be left hanging unless we reply.
ForwardLoginsResult(request);
}
}
void PasswordStoreX::GetBlacklistLoginsImpl(GetLoginsRequest* request) {
CheckMigration();
if (use_native_backend() &&
backend_->GetBlacklistLogins(&request->value)) {
SortLoginsByOrigin(&request->value);
ForwardLoginsResult(request);
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::GetBlacklistLoginsImpl(request);
} else {
// The consumer will be left hanging unless we reply.
ForwardLoginsResult(request);
}
}
bool PasswordStoreX::FillAutofillableLogins(vector<PasswordForm*>* forms) {
CheckMigration();
if (use_native_backend() && backend_->GetAutofillableLogins(forms)) {
allow_fallback_ = false;
return true;
}
if (allow_default_store())
return PasswordStoreDefault::FillAutofillableLogins(forms);
return false;
}
bool PasswordStoreX::FillBlacklistLogins(vector<PasswordForm*>* forms) {
CheckMigration();
if (use_native_backend() && backend_->GetBlacklistLogins(forms)) {
allow_fallback_ = false;
return true;
}
if (allow_default_store())
return PasswordStoreDefault::FillBlacklistLogins(forms);
return false;
}
void PasswordStoreX::CheckMigration() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
if (migration_checked_ || !backend_.get())
return;
migration_checked_ = true;
ssize_t migrated = MigrateLogins();
if (migrated > 0) {
VLOG(1) << "Migrated " << migrated << " passwords to native store.";
} else if (migrated == 0) {
// As long as we are able to migrate some passwords, we know the native
// store is working. But if there is nothing to migrate, the "migration"
// can succeed even when the native store would fail. In this case we
// allow a later fallback to the default store. Once any later operation
// succeeds on the native store, we will no longer allow it.
allow_fallback_ = true;
} else {
LOG(WARNING) << "Native password store migration failed! " <<
"Falling back on default (unencrypted) store.";
backend_.reset(NULL);
}
}
bool PasswordStoreX::allow_default_store() {
if (allow_fallback_) {
LOG(WARNING) << "Native password store failed! " <<
"Falling back on default (unencrypted) store.";
backend_.reset(NULL);
// Don't warn again. We'll use the default store because backend_ is NULL.
allow_fallback_ = false;
}
return !backend_.get();
}
ssize_t PasswordStoreX::MigrateLogins() {
DCHECK(backend_.get());
vector<PasswordForm*> forms;
bool ok = PasswordStoreDefault::FillAutofillableLogins(&forms) &&
PasswordStoreDefault::FillBlacklistLogins(&forms);
if (ok) {
// We add all the passwords (and blacklist entries) to the native backend
// before attempting to remove any from the login database, to make sure we
// don't somehow end up with some of the passwords in one store and some in
// another. We'll always have at least one intact store this way.
for (size_t i = 0; i < forms.size(); ++i) {
if (!backend_->AddLogin(*forms[i])) {
ok = false;
break;
}
}
if (forms.empty()) {
// If there's nothing to migrate, then we try to insert a dummy login form
// just to force the native store to unlock if it was locked. We delete it
// right away if we are successful. If the first operation we try to do is
// a read, then in some cases this is just an error rather than an action
// that causes the native store to prompt the user to unlock.
// TODO(mdm): this means we no longer need the allow_fallback mechanism.
// Remove it once this preemptive unlock by write is baked for a while.
PasswordForm dummy;
dummy.origin = GURL("http://www.example.com/force-keyring-unlock");
dummy.signon_realm = "www.example.com";
if (backend_->AddLogin(dummy))
backend_->RemoveLogin(dummy);
else
ok = false;
}
if (ok) {
for (size_t i = 0; i < forms.size(); ++i) {
// If even one of these calls to RemoveLoginImpl() succeeds, then we
// should prefer the native backend to the now-incomplete login
// database. Thus we want to return a success status even in the case
// where some fail. The only real problem with this is that we might
// leave passwords in the login database and never come back to clean
// them out if any of these calls do fail.
PasswordStoreDefault::RemoveLoginImpl(*forms[i]);
}
// Finally, delete the database file itself. We remove the passwords from
// it before deleting the file just in case there is some problem deleting
// the file (e.g. directory is not writable, but file is), which would
// otherwise cause passwords to re-migrate next (or maybe every) time.
DeleteAndRecreateDatabaseFile();
}
}
ssize_t result = ok ? forms.size() : -1;
STLDeleteElements(&forms);
return result;
}
<commit_msg>Linux: remove the forced keyring unlock on password store initialization. It is no longer required for our gnome keyring integration to work correctly.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/password_manager/password_store_x.h"
#include <algorithm>
#include <map>
#include <vector>
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/password_manager/password_store_change.h"
#include "content/browser/browser_thread.h"
#include "content/common/notification_service.h"
using std::vector;
using webkit_glue::PasswordForm;
PasswordStoreX::PasswordStoreX(LoginDatabase* login_db,
Profile* profile,
WebDataService* web_data_service,
NativeBackend* backend)
: PasswordStoreDefault(login_db, profile, web_data_service),
backend_(backend), migration_checked_(!backend), allow_fallback_(false) {
}
PasswordStoreX::~PasswordStoreX() {
}
void PasswordStoreX::AddLoginImpl(const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->AddLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::AddLoginImpl(form);
}
}
void PasswordStoreX::UpdateLoginImpl(const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->UpdateLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::UPDATE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::UpdateLoginImpl(form);
}
}
void PasswordStoreX::RemoveLoginImpl(const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->RemoveLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::RemoveLoginImpl(form);
}
}
void PasswordStoreX::RemoveLoginsCreatedBetweenImpl(
const base::Time& delete_begin,
const base::Time& delete_end) {
CheckMigration();
vector<PasswordForm*> forms;
if (use_native_backend() &&
backend_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms) &&
backend_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) {
PasswordStoreChangeList changes;
for (vector<PasswordForm*>::const_iterator it = forms.begin();
it != forms.end(); ++it) {
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE,
**it));
}
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(this),
Details<PasswordStoreChangeList>(&changes));
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl(delete_begin,
delete_end);
}
STLDeleteElements(&forms);
}
namespace {
struct LoginLessThan {
bool operator()(const PasswordForm* a, const PasswordForm* b) {
return a->origin < b->origin;
}
};
} // anonymous namespace
void PasswordStoreX::SortLoginsByOrigin(NativeBackend::PasswordFormList* list) {
// In login_database.cc, the query has ORDER BY origin_url. Simulate that.
std::sort(list->begin(), list->end(), LoginLessThan());
}
void PasswordStoreX::GetLoginsImpl(GetLoginsRequest* request,
const PasswordForm& form) {
CheckMigration();
if (use_native_backend() && backend_->GetLogins(form, &request->value)) {
SortLoginsByOrigin(&request->value);
ForwardLoginsResult(request);
// The native backend may succeed and return no data even while locked, if
// the query did not match anything stored. So we continue to allow fallback
// until we perform a write operation, or until a read returns actual data.
if (request->value.size() > 0)
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::GetLoginsImpl(request, form);
} else {
// The consumer will be left hanging unless we reply.
ForwardLoginsResult(request);
}
}
void PasswordStoreX::GetAutofillableLoginsImpl(GetLoginsRequest* request) {
CheckMigration();
if (use_native_backend() &&
backend_->GetAutofillableLogins(&request->value)) {
SortLoginsByOrigin(&request->value);
ForwardLoginsResult(request);
// See GetLoginsImpl() for why we disallow fallback conditionally here.
if (request->value.size() > 0)
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::GetAutofillableLoginsImpl(request);
} else {
// The consumer will be left hanging unless we reply.
ForwardLoginsResult(request);
}
}
void PasswordStoreX::GetBlacklistLoginsImpl(GetLoginsRequest* request) {
CheckMigration();
if (use_native_backend() &&
backend_->GetBlacklistLogins(&request->value)) {
SortLoginsByOrigin(&request->value);
ForwardLoginsResult(request);
// See GetLoginsImpl() for why we disallow fallback conditionally here.
if (request->value.size() > 0)
allow_fallback_ = false;
} else if (allow_default_store()) {
PasswordStoreDefault::GetBlacklistLoginsImpl(request);
} else {
// The consumer will be left hanging unless we reply.
ForwardLoginsResult(request);
}
}
bool PasswordStoreX::FillAutofillableLogins(vector<PasswordForm*>* forms) {
CheckMigration();
if (use_native_backend() && backend_->GetAutofillableLogins(forms)) {
// See GetLoginsImpl() for why we disallow fallback conditionally here.
if (forms->size() > 0)
allow_fallback_ = false;
return true;
}
if (allow_default_store())
return PasswordStoreDefault::FillAutofillableLogins(forms);
return false;
}
bool PasswordStoreX::FillBlacklistLogins(vector<PasswordForm*>* forms) {
CheckMigration();
if (use_native_backend() && backend_->GetBlacklistLogins(forms)) {
// See GetLoginsImpl() for why we disallow fallback conditionally here.
if (forms->size() > 0)
allow_fallback_ = false;
return true;
}
if (allow_default_store())
return PasswordStoreDefault::FillBlacklistLogins(forms);
return false;
}
void PasswordStoreX::CheckMigration() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
if (migration_checked_ || !backend_.get())
return;
migration_checked_ = true;
ssize_t migrated = MigrateLogins();
if (migrated > 0) {
VLOG(1) << "Migrated " << migrated << " passwords to native store.";
} else if (migrated == 0) {
// As long as we are able to migrate some passwords, we know the native
// store is working. But if there is nothing to migrate, the "migration"
// can succeed even when the native store would fail. In this case we
// allow a later fallback to the default store. Once any later operation
// succeeds on the native store, we will no longer allow fallback.
allow_fallback_ = true;
} else {
LOG(WARNING) << "Native password store migration failed! " <<
"Falling back on default (unencrypted) store.";
backend_.reset(NULL);
}
}
bool PasswordStoreX::allow_default_store() {
if (allow_fallback_) {
LOG(WARNING) << "Native password store failed! " <<
"Falling back on default (unencrypted) store.";
backend_.reset(NULL);
// Don't warn again. We'll use the default store because backend_ is NULL.
allow_fallback_ = false;
}
return !backend_.get();
}
ssize_t PasswordStoreX::MigrateLogins() {
DCHECK(backend_.get());
vector<PasswordForm*> forms;
bool ok = PasswordStoreDefault::FillAutofillableLogins(&forms) &&
PasswordStoreDefault::FillBlacklistLogins(&forms);
if (ok) {
// We add all the passwords (and blacklist entries) to the native backend
// before attempting to remove any from the login database, to make sure we
// don't somehow end up with some of the passwords in one store and some in
// another. We'll always have at least one intact store this way.
for (size_t i = 0; i < forms.size(); ++i) {
if (!backend_->AddLogin(*forms[i])) {
ok = false;
break;
}
}
if (ok) {
for (size_t i = 0; i < forms.size(); ++i) {
// If even one of these calls to RemoveLoginImpl() succeeds, then we
// should prefer the native backend to the now-incomplete login
// database. Thus we want to return a success status even in the case
// where some fail. The only real problem with this is that we might
// leave passwords in the login database and never come back to clean
// them out if any of these calls do fail.
PasswordStoreDefault::RemoveLoginImpl(*forms[i]);
}
// Finally, delete the database file itself. We remove the passwords from
// it before deleting the file just in case there is some problem deleting
// the file (e.g. directory is not writable, but file is), which would
// otherwise cause passwords to re-migrate next (or maybe every) time.
DeleteAndRecreateDatabaseFile();
}
}
ssize_t result = ok ? forms.size() : -1;
STLDeleteElements(&forms);
return result;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin 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 <bitcoin/bitcoin/message/network_address.hpp>
#include <boost/iostreams/stream.hpp>
#include <bitcoin/bitcoin/utility/container_sink.hpp>
#include <bitcoin/bitcoin/utility/container_source.hpp>
#include <bitcoin/bitcoin/utility/istream.hpp>
#include <bitcoin/bitcoin/utility/ostream.hpp>
namespace libbitcoin {
namespace message {
ip_address null_address = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
network_address network_address::factory_from_data(const data_chunk& data,
bool with_timestamp /*= false*/)
{
network_address instance;
instance.from_data(data, with_timestamp);
return instance;
}
network_address network_address::factory_from_data(std::istream& stream,
bool with_timestamp /*= false*/)
{
network_address instance;
instance.from_data(stream, with_timestamp);
return instance;
}
bool network_address::is_valid() const
{
return (timestamp != 0) ||
(services != 0) ||
(port != 0) ||
(ip != null_address);
}
void network_address::reset()
{
timestamp = 0;
services = 0;
ip.fill(0);
port = 0;
}
bool network_address::from_data(const data_chunk& data, bool with_timestamp)
{
boost::iostreams::stream<byte_source<data_chunk>> istream(data);
return from_data(istream, with_timestamp);
}
bool network_address::from_data(std::istream& stream, bool with_timestamp)
{
reset();
if (with_timestamp)
timestamp = read_4_bytes(stream);
services = read_8_bytes(stream);
ip= read_bytes<16>(stream);
port = read_big_endian<uint16_t>(stream);
if (!stream)
reset();
return stream;
}
data_chunk network_address::to_data(bool with_timestamp) const
{
data_chunk data;
boost::iostreams::stream<byte_sink<data_chunk>> ostream(data);
to_data(ostream, with_timestamp);
BOOST_ASSERT(data.size() == satoshi_size());
return data;
}
void network_address::to_data(std::ostream& stream, bool with_timestamp) const
{
if (with_timestamp)
write_4_bytes(stream, timestamp);
write_8_bytes(stream, services);
write_data(stream, ip);
write_big_endian<uint16_t>(stream, port);
}
uint64_t network_address::satoshi_size(bool with_timestamp) const
{
return network_address::satoshi_fixed_size(with_timestamp);
}
uint64_t network_address::satoshi_fixed_size(bool with_timestamp)
{
uint64_t result = 26;
if (with_timestamp)
result += 4;
return result;
}
} // end message
} // end libbitcoin
<commit_msg>Correct error in assert.<commit_after>/*
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin 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 <bitcoin/bitcoin/message/network_address.hpp>
#include <boost/iostreams/stream.hpp>
#include <bitcoin/bitcoin/utility/container_sink.hpp>
#include <bitcoin/bitcoin/utility/container_source.hpp>
#include <bitcoin/bitcoin/utility/istream.hpp>
#include <bitcoin/bitcoin/utility/ostream.hpp>
namespace libbitcoin {
namespace message {
ip_address null_address = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
network_address network_address::factory_from_data(const data_chunk& data,
bool with_timestamp /*= false*/)
{
network_address instance;
instance.from_data(data, with_timestamp);
return instance;
}
network_address network_address::factory_from_data(std::istream& stream,
bool with_timestamp /*= false*/)
{
network_address instance;
instance.from_data(stream, with_timestamp);
return instance;
}
bool network_address::is_valid() const
{
return (timestamp != 0) ||
(services != 0) ||
(port != 0) ||
(ip != null_address);
}
void network_address::reset()
{
timestamp = 0;
services = 0;
ip.fill(0);
port = 0;
}
bool network_address::from_data(const data_chunk& data, bool with_timestamp)
{
boost::iostreams::stream<byte_source<data_chunk>> istream(data);
return from_data(istream, with_timestamp);
}
bool network_address::from_data(std::istream& stream, bool with_timestamp)
{
reset();
if (with_timestamp)
timestamp = read_4_bytes(stream);
services = read_8_bytes(stream);
ip= read_bytes<16>(stream);
port = read_big_endian<uint16_t>(stream);
if (!stream)
reset();
return stream;
}
data_chunk network_address::to_data(bool with_timestamp) const
{
data_chunk data;
boost::iostreams::stream<byte_sink<data_chunk>> ostream(data);
to_data(ostream, with_timestamp);
BOOST_ASSERT(data.size() == satoshi_size(with_timestamp));
return data;
}
void network_address::to_data(std::ostream& stream, bool with_timestamp) const
{
if (with_timestamp)
write_4_bytes(stream, timestamp);
write_8_bytes(stream, services);
write_data(stream, ip);
write_big_endian<uint16_t>(stream, port);
}
uint64_t network_address::satoshi_size(bool with_timestamp) const
{
return network_address::satoshi_fixed_size(with_timestamp);
}
uint64_t network_address::satoshi_fixed_size(bool with_timestamp)
{
uint64_t result = 26;
if (with_timestamp)
result += 4;
return result;
}
} // end message
} // end libbitcoin
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_loader.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2007-10-11 15:52:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <pyuno/pyuno.hxx>
#include <osl/module.hxx>
#include <osl/process.h>
#include <osl/file.h>
#include <osl/thread.h>
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>
using rtl::OUString;
using rtl::OUStringBuffer;
using rtl::OString;
using pyuno::PyRef;
using pyuno::Runtime;
using pyuno::PyThreadAttach;
using com::sun::star::registry::XRegistryKey;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::XComponentContext;
using com::sun::star::uno::RuntimeException;
namespace pyuno_loader
{
static void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )
{
if( PyErr_Occurred() )
{
PyRef excType, excValue, excTraceback;
PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);
Runtime runtime;
com::sun::star::uno::Any a = runtime.extractUnoException( excType, excValue, excTraceback );
OUStringBuffer buf;
buf.appendAscii( "python-loader:" );
if( a.hasValue() )
buf.append( ((com::sun::star::uno::Exception *)a.getValue())->Message );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface> () );
}
}
static PyRef getLoaderModule() throw( RuntimeException )
{
PyRef module(
PyImport_ImportModule( const_cast< char * >("pythonloader") ),
SAL_NO_ACQUIRE );
raiseRuntimeExceptionWhenNeeded();
if( !module.is() )
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "pythonloader: Couldn't load pythonloader module" ) ),
Reference< XInterface > () );
}
return PyRef( PyModule_GetDict( module.get() ));
}
static PyRef getObjectFromLoaderModule( const char * func )
throw ( RuntimeException )
{
PyRef object( PyDict_GetItemString(getLoaderModule().get(), (char*)func ) );
if( !object.is() )
{
OUStringBuffer buf;
buf.appendAscii( "pythonloader: couldn't find core element pythonloader." );
buf.appendAscii( func );
throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
}
return object;
}
OUString getImplementationName()
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.pyuno.Loader" ) );
}
Sequence< OUString > getSupportedServiceNames()
{
OUString serviceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.loader.Python" ) );
return Sequence< OUString > ( &serviceName, 1 );
}
static OUString getLibDir()
{
static OUString *pLibDir;
if( !pLibDir )
{
osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );
if( ! pLibDir )
{
static OUString libDir;
if( osl::Module::getUrlFromAddress(
reinterpret_cast< oslGenericFunction >(getLibDir) , libDir ) )
{
libDir = OUString( libDir.getStr(), libDir.lastIndexOf('/' ) );
}
pLibDir = &libDir;
}
}
return *pLibDir;
}
static void setPythonHome ( const OUString & pythonHome )
{
OUString systemPythonHome;
osl_getSystemPathFromFileURL( pythonHome.pData, &(systemPythonHome.pData) );
OString o = rtl::OUStringToOString( systemPythonHome, osl_getThreadTextEncoding() );
rtl_string_acquire(o.pData); // leak this string (thats the api!)
Py_SetPythonHome( o.pData->buffer);
}
static void prependPythonPath( const OUString & pythonPathBootstrap )
{
rtl::OStringBuffer bufPYTHONPATH( 256 );
bufPYTHONPATH.append( "PYTHONPATH=");
sal_Int32 nIndex = 0;
while( 1 )
{
sal_Int32 nNew = pythonPathBootstrap.indexOf( ' ', nIndex );
OUString fileUrl;
if( nNew == -1 )
{
fileUrl = OUString( &( pythonPathBootstrap[nIndex] ) );
}
else
{
fileUrl = OUString( &(pythonPathBootstrap[nIndex]) , nNew - nIndex );
}
OUString systemPath;
osl_getSystemPathFromFileURL( fileUrl.pData, &(systemPath.pData) );
bufPYTHONPATH.append( rtl::OUStringToOString( systemPath.pData, osl_getThreadTextEncoding() ));
bufPYTHONPATH.append( SAL_PATHSEPARATOR );
if( nNew == -1 )
break;
nIndex = nNew + 1;
}
const char * oldEnv = getenv( "PYTHONPATH");
if( oldEnv )
bufPYTHONPATH.append( oldEnv );
OString result = bufPYTHONPATH.makeStringAndClear();
rtl_string_acquire( result.pData );
// printf( "Setting %s\n" , result.pData->buffer );
putenv( result.pData->buffer );
}
Reference< XInterface > CreateInstance( const Reference< XComponentContext > & ctx )
{
Reference< XInterface > ret;
if( ! Py_IsInitialized() )
{
OUString pythonPath;
OUString pythonHome;
OUString path = getLibDir();
if( path.getLength() )
{
path += OUString( RTL_CONSTASCII_USTRINGPARAM( "/" SAL_CONFIGFILE("pythonloader.uno" )));
rtl::Bootstrap bootstrap(path);
// look for pythonhome
bootstrap.getFrom( OUString( RTL_CONSTASCII_USTRINGPARAM( "PYUNO_LOADER_PYTHONHOME") ), pythonHome );
bootstrap.getFrom( OUString( RTL_CONSTASCII_USTRINGPARAM( "PYUNO_LOADER_PYTHONPATH" ) ) , pythonPath );
}
// pythonhome+pythonpath must be set before Py_Initialize(), otherwise there appear warning on the console
// sadly, there is no api for setting the pythonpath, we have to use the environment variable
if( pythonHome.getLength() )
setPythonHome( pythonHome );
if( pythonPath.getLength() )
prependPythonPath( pythonPath );
// initialize python
Py_Initialize();
PyEval_InitThreads();
PyThreadState *tstate = PyThreadState_Get();
PyEval_ReleaseThread( tstate );
}
PyThreadAttach attach( PyInterpreterState_Head() );
{
if( ! Runtime::isInitialized() )
{
Runtime::initialize( ctx );
}
Runtime runtime;
PyRef pyCtx = runtime.any2PyObject(
com::sun::star::uno::makeAny( ctx ) );
PyRef clazz = getObjectFromLoaderModule( "Loader" );
PyRef args ( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
PyTuple_SetItem( args.get(), 0 , pyCtx.getAcquired() );
PyRef pyInstance( PyObject_CallObject( clazz.get() , args.get() ), SAL_NO_ACQUIRE );
runtime.pyObject2Any( pyInstance ) >>= ret;
}
return ret;
}
}
static struct cppu::ImplementationEntry g_entries[] =
{
{
pyuno_loader::CreateInstance, pyuno_loader::getImplementationName,
pyuno_loader::getSupportedServiceNames, cppu::createSingleComponentFactory,
0 , 0
},
{ 0, 0, 0, 0, 0, 0 }
};
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
void * pServiceManager, void * pRegistryKey )
{
return cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.12); FILE MERGED 2008/03/31 07:24:58 rt 1.10.12.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_loader.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <pyuno/pyuno.hxx>
#include <osl/module.hxx>
#include <osl/process.h>
#include <osl/file.h>
#include <osl/thread.h>
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>
using rtl::OUString;
using rtl::OUStringBuffer;
using rtl::OString;
using pyuno::PyRef;
using pyuno::Runtime;
using pyuno::PyThreadAttach;
using com::sun::star::registry::XRegistryKey;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::XComponentContext;
using com::sun::star::uno::RuntimeException;
namespace pyuno_loader
{
static void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )
{
if( PyErr_Occurred() )
{
PyRef excType, excValue, excTraceback;
PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);
Runtime runtime;
com::sun::star::uno::Any a = runtime.extractUnoException( excType, excValue, excTraceback );
OUStringBuffer buf;
buf.appendAscii( "python-loader:" );
if( a.hasValue() )
buf.append( ((com::sun::star::uno::Exception *)a.getValue())->Message );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface> () );
}
}
static PyRef getLoaderModule() throw( RuntimeException )
{
PyRef module(
PyImport_ImportModule( const_cast< char * >("pythonloader") ),
SAL_NO_ACQUIRE );
raiseRuntimeExceptionWhenNeeded();
if( !module.is() )
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "pythonloader: Couldn't load pythonloader module" ) ),
Reference< XInterface > () );
}
return PyRef( PyModule_GetDict( module.get() ));
}
static PyRef getObjectFromLoaderModule( const char * func )
throw ( RuntimeException )
{
PyRef object( PyDict_GetItemString(getLoaderModule().get(), (char*)func ) );
if( !object.is() )
{
OUStringBuffer buf;
buf.appendAscii( "pythonloader: couldn't find core element pythonloader." );
buf.appendAscii( func );
throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
}
return object;
}
OUString getImplementationName()
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.pyuno.Loader" ) );
}
Sequence< OUString > getSupportedServiceNames()
{
OUString serviceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.loader.Python" ) );
return Sequence< OUString > ( &serviceName, 1 );
}
static OUString getLibDir()
{
static OUString *pLibDir;
if( !pLibDir )
{
osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );
if( ! pLibDir )
{
static OUString libDir;
if( osl::Module::getUrlFromAddress(
reinterpret_cast< oslGenericFunction >(getLibDir) , libDir ) )
{
libDir = OUString( libDir.getStr(), libDir.lastIndexOf('/' ) );
}
pLibDir = &libDir;
}
}
return *pLibDir;
}
static void setPythonHome ( const OUString & pythonHome )
{
OUString systemPythonHome;
osl_getSystemPathFromFileURL( pythonHome.pData, &(systemPythonHome.pData) );
OString o = rtl::OUStringToOString( systemPythonHome, osl_getThreadTextEncoding() );
rtl_string_acquire(o.pData); // leak this string (thats the api!)
Py_SetPythonHome( o.pData->buffer);
}
static void prependPythonPath( const OUString & pythonPathBootstrap )
{
rtl::OStringBuffer bufPYTHONPATH( 256 );
bufPYTHONPATH.append( "PYTHONPATH=");
sal_Int32 nIndex = 0;
while( 1 )
{
sal_Int32 nNew = pythonPathBootstrap.indexOf( ' ', nIndex );
OUString fileUrl;
if( nNew == -1 )
{
fileUrl = OUString( &( pythonPathBootstrap[nIndex] ) );
}
else
{
fileUrl = OUString( &(pythonPathBootstrap[nIndex]) , nNew - nIndex );
}
OUString systemPath;
osl_getSystemPathFromFileURL( fileUrl.pData, &(systemPath.pData) );
bufPYTHONPATH.append( rtl::OUStringToOString( systemPath.pData, osl_getThreadTextEncoding() ));
bufPYTHONPATH.append( SAL_PATHSEPARATOR );
if( nNew == -1 )
break;
nIndex = nNew + 1;
}
const char * oldEnv = getenv( "PYTHONPATH");
if( oldEnv )
bufPYTHONPATH.append( oldEnv );
OString result = bufPYTHONPATH.makeStringAndClear();
rtl_string_acquire( result.pData );
// printf( "Setting %s\n" , result.pData->buffer );
putenv( result.pData->buffer );
}
Reference< XInterface > CreateInstance( const Reference< XComponentContext > & ctx )
{
Reference< XInterface > ret;
if( ! Py_IsInitialized() )
{
OUString pythonPath;
OUString pythonHome;
OUString path = getLibDir();
if( path.getLength() )
{
path += OUString( RTL_CONSTASCII_USTRINGPARAM( "/" SAL_CONFIGFILE("pythonloader.uno" )));
rtl::Bootstrap bootstrap(path);
// look for pythonhome
bootstrap.getFrom( OUString( RTL_CONSTASCII_USTRINGPARAM( "PYUNO_LOADER_PYTHONHOME") ), pythonHome );
bootstrap.getFrom( OUString( RTL_CONSTASCII_USTRINGPARAM( "PYUNO_LOADER_PYTHONPATH" ) ) , pythonPath );
}
// pythonhome+pythonpath must be set before Py_Initialize(), otherwise there appear warning on the console
// sadly, there is no api for setting the pythonpath, we have to use the environment variable
if( pythonHome.getLength() )
setPythonHome( pythonHome );
if( pythonPath.getLength() )
prependPythonPath( pythonPath );
// initialize python
Py_Initialize();
PyEval_InitThreads();
PyThreadState *tstate = PyThreadState_Get();
PyEval_ReleaseThread( tstate );
}
PyThreadAttach attach( PyInterpreterState_Head() );
{
if( ! Runtime::isInitialized() )
{
Runtime::initialize( ctx );
}
Runtime runtime;
PyRef pyCtx = runtime.any2PyObject(
com::sun::star::uno::makeAny( ctx ) );
PyRef clazz = getObjectFromLoaderModule( "Loader" );
PyRef args ( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
PyTuple_SetItem( args.get(), 0 , pyCtx.getAcquired() );
PyRef pyInstance( PyObject_CallObject( clazz.get() , args.get() ), SAL_NO_ACQUIRE );
runtime.pyObject2Any( pyInstance ) >>= ret;
}
return ret;
}
}
static struct cppu::ImplementationEntry g_entries[] =
{
{
pyuno_loader::CreateInstance, pyuno_loader::getImplementationName,
pyuno_loader::getSupportedServiceNames, cppu::createSingleComponentFactory,
0 , 0
},
{ 0, 0, 0, 0, 0, 0 }
};
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
void * pServiceManager, void * pRegistryKey )
{
return cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_loader.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:50:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <osl/module.hxx>
#include <osl/process.h>
#include <osl/file.h>
#include <osl/thread.h>
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>
#include <pyuno/pyuno.hxx>
using rtl::OUString;
using rtl::OUStringBuffer;
using rtl::OString;
using pyuno::PyRef;
using pyuno::Runtime;
using pyuno::PyThreadAttach;
using com::sun::star::registry::XRegistryKey;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::XComponentContext;
using com::sun::star::uno::RuntimeException;
namespace pyuno_loader
{
static void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )
{
if( PyErr_Occurred() )
{
PyRef excType, excValue, excTraceback;
PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);
Runtime runtime;
com::sun::star::uno::Any a = runtime.extractUnoException( excType, excValue, excTraceback );
OUStringBuffer buf;
buf.appendAscii( "python-loader:" );
if( a.hasValue() )
buf.append( ((com::sun::star::uno::Exception *)a.getValue())->Message );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface> () );
}
}
static PyRef getLoaderModule() throw( RuntimeException )
{
PyRef module( PyImport_ImportModule( "pythonloader" ), SAL_NO_ACQUIRE );
raiseRuntimeExceptionWhenNeeded();
if( !module.is() )
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "pythonloader: Couldn't load pythonloader module" ) ),
Reference< XInterface > () );
}
return PyRef( PyModule_GetDict( module.get() ));
}
static PyRef getObjectFromLoaderModule( const char * func )
throw ( RuntimeException )
{
PyRef object( PyDict_GetItemString(getLoaderModule().get(), (char*)func ) );
if( !object.is() )
{
OUStringBuffer buf;
buf.appendAscii( "pythonloader: couldn't find core element pythonloader." );
buf.appendAscii( func );
throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
}
return object;
}
OUString getImplementationName()
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.pyuno.Loader" ) );
}
Sequence< OUString > getSupportedServiceNames()
{
OUString serviceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.loader.Python" ) );
return Sequence< OUString > ( &serviceName, 1 );
}
static OUString getLibDir()
{
static OUString *pLibDir;
if( !pLibDir )
{
osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );
if( ! pLibDir )
{
static OUString libDir;
// changed from reinterpret_cast<void*> this is not allowed
// in gcc 3.3 without permissive. Us simple C cast.
if( osl::Module::getUrlFromAddress( (void*)(getLibDir) , libDir ) )
{
libDir = OUString( libDir.getStr(), libDir.lastIndexOf('/' ) );
}
pLibDir = &libDir;
}
}
return *pLibDir;
}
Reference< XInterface > CreateInstance( const Reference< XComponentContext > & ctx )
{
Reference< XInterface > ret;
if( ! Py_IsInitialized() )
{
// in case python path is already set, nothing is done ...
const OUString pythonPath ( RTL_CONSTASCII_USTRINGPARAM( "PYTHONPATH" ) );
// otherwise, try to get the PYTHONPATH bootstrap variable
OUStringBuffer bufPYTHONPATH( 256 );
OUString path = getLibDir();
if( path.getLength() )
{
path += OUString( RTL_CONSTASCII_USTRINGPARAM( "/" SAL_CONFIGFILE("pythonloader.uno" )));
rtl::Bootstrap bootstrap(path);
// look for pythonhome
OUString pythonHome;
if( bootstrap.getFrom( OUString ( RTL_CONSTASCII_USTRINGPARAM( "PYTHONHOME") ),
pythonHome ) )
{
osl_getFileURLFromSystemPath( pythonHome.pData, &(pythonHome.pData) );
rtl::OStringBuffer stringBuffer( pythonHome.getLength() +20);
stringBuffer.append( "PYTHONHOME=" );
stringBuffer.append(
rtl::OUStringToOString( pythonHome, osl_getThreadTextEncoding() ) );
OString env2= stringBuffer.makeStringAndClear();
rtl_string_acquire(env2.pData );
putenv( env2.pData->buffer );
}
// check for pythonpath
OUString pythonPathBootstrap;
bootstrap.getFrom( pythonPath , pythonPathBootstrap );
sal_Int32 nIndex = 0;
while( 1 )
{
sal_Int32 nNew = pythonPathBootstrap.indexOf( ' ', nIndex );
OUString fileUrl;
if( nNew == -1 )
{
fileUrl = OUString( &( pythonPathBootstrap[nIndex] ) );
}
else
{
fileUrl = OUString( &(pythonPathBootstrap[nIndex]) , nNew - nIndex );
}
OUString systemPath;
osl_getSystemPathFromFileURL( fileUrl.pData, &(systemPath.pData) );
bufPYTHONPATH.append( systemPath );
if( nNew == -1 )
break;
bufPYTHONPATH.append( (sal_Unicode) SAL_PATHSEPARATOR );
nIndex = nNew + 1;
}
}
OUString value;
osl_getEnvironment( pythonPath.pData, &value.pData );
bufPYTHONPATH.append( value );
rtl::OStringBuffer stringBuffer;
stringBuffer.append( "PYTHONPATH=" );
stringBuffer.append(
rtl::OUStringToOString( bufPYTHONPATH.makeStringAndClear(), osl_getThreadTextEncoding()));
OString env = stringBuffer.makeStringAndClear();
// leak this string (putenv does not make a copy)
rtl_string_acquire( env.pData );
putenv( env.pData->buffer );
// initialize python
Py_Initialize();
PyEval_InitThreads();
PyThreadState *tstate = PyThreadState_Get();
PyEval_ReleaseThread( tstate );
}
PyThreadAttach attach( PyInterpreterState_Head() );
{
if( ! Runtime::isInitialized() )
{
Runtime::initialize( ctx );
}
Runtime runtime;
PyRef pyCtx = runtime.any2PyObject(
com::sun::star::uno::makeAny( ctx ) );
PyRef clazz = getObjectFromLoaderModule( "Loader" );
PyRef args ( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
PyTuple_SetItem( args.get(), 0 , pyCtx.getAcquired() );
PyRef pyInstance( PyObject_CallObject( clazz.get() , args.get() ), SAL_NO_ACQUIRE );
runtime.pyObject2Any( pyInstance ) >>= ret;
}
return ret;
}
}
static struct cppu::ImplementationEntry g_entries[] =
{
{
pyuno_loader::CreateInstance, pyuno_loader::getImplementationName,
pyuno_loader::getSupportedServiceNames, cppu::createSingleComponentFactory,
0 , 0
},
{ 0, 0, 0, 0, 0, 0 }
};
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
void * pServiceManager, void * pRegistryKey )
{
return cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.6.14); FILE MERGED 2005/09/23 02:07:33 sb 1.6.14.2: RESYNC: (1.6-1.7); FILE MERGED 2005/09/09 15:31:16 sb 1.6.14.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_loader.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:02:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <pyuno/pyuno.hxx>
#include <osl/module.hxx>
#include <osl/process.h>
#include <osl/file.h>
#include <osl/thread.h>
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>
using rtl::OUString;
using rtl::OUStringBuffer;
using rtl::OString;
using pyuno::PyRef;
using pyuno::Runtime;
using pyuno::PyThreadAttach;
using com::sun::star::registry::XRegistryKey;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::XComponentContext;
using com::sun::star::uno::RuntimeException;
namespace pyuno_loader
{
static void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )
{
if( PyErr_Occurred() )
{
PyRef excType, excValue, excTraceback;
PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);
Runtime runtime;
com::sun::star::uno::Any a = runtime.extractUnoException( excType, excValue, excTraceback );
OUStringBuffer buf;
buf.appendAscii( "python-loader:" );
if( a.hasValue() )
buf.append( ((com::sun::star::uno::Exception *)a.getValue())->Message );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface> () );
}
}
static PyRef getLoaderModule() throw( RuntimeException )
{
PyRef module(
PyImport_ImportModule( const_cast< char * >("pythonloader") ),
SAL_NO_ACQUIRE );
raiseRuntimeExceptionWhenNeeded();
if( !module.is() )
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "pythonloader: Couldn't load pythonloader module" ) ),
Reference< XInterface > () );
}
return PyRef( PyModule_GetDict( module.get() ));
}
static PyRef getObjectFromLoaderModule( const char * func )
throw ( RuntimeException )
{
PyRef object( PyDict_GetItemString(getLoaderModule().get(), (char*)func ) );
if( !object.is() )
{
OUStringBuffer buf;
buf.appendAscii( "pythonloader: couldn't find core element pythonloader." );
buf.appendAscii( func );
throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());
}
return object;
}
OUString getImplementationName()
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.pyuno.Loader" ) );
}
Sequence< OUString > getSupportedServiceNames()
{
OUString serviceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.loader.Python" ) );
return Sequence< OUString > ( &serviceName, 1 );
}
static OUString getLibDir()
{
static OUString *pLibDir;
if( !pLibDir )
{
osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );
if( ! pLibDir )
{
static OUString libDir;
if( osl::Module::getUrlFromAddress(
reinterpret_cast< oslGenericFunction >(getLibDir) , libDir ) )
{
libDir = OUString( libDir.getStr(), libDir.lastIndexOf('/' ) );
}
pLibDir = &libDir;
}
}
return *pLibDir;
}
Reference< XInterface > CreateInstance( const Reference< XComponentContext > & ctx )
{
Reference< XInterface > ret;
if( ! Py_IsInitialized() )
{
// in case python path is already set, nothing is done ...
const OUString pythonPath ( RTL_CONSTASCII_USTRINGPARAM( "PYTHONPATH" ) );
// otherwise, try to get the PYTHONPATH bootstrap variable
OUStringBuffer bufPYTHONPATH( 256 );
OUString path = getLibDir();
if( path.getLength() )
{
path += OUString( RTL_CONSTASCII_USTRINGPARAM( "/" SAL_CONFIGFILE("pythonloader.uno" )));
rtl::Bootstrap bootstrap(path);
// look for pythonhome
OUString pythonHome;
if( bootstrap.getFrom( OUString ( RTL_CONSTASCII_USTRINGPARAM( "PYTHONHOME") ),
pythonHome ) )
{
osl_getFileURLFromSystemPath( pythonHome.pData, &(pythonHome.pData) );
rtl::OStringBuffer stringBuffer( pythonHome.getLength() +20);
stringBuffer.append( "PYTHONHOME=" );
stringBuffer.append(
rtl::OUStringToOString( pythonHome, osl_getThreadTextEncoding() ) );
OString env2= stringBuffer.makeStringAndClear();
rtl_string_acquire(env2.pData );
putenv( env2.pData->buffer );
}
// check for pythonpath
OUString pythonPathBootstrap;
bootstrap.getFrom( pythonPath , pythonPathBootstrap );
sal_Int32 nIndex = 0;
while( 1 )
{
sal_Int32 nNew = pythonPathBootstrap.indexOf( ' ', nIndex );
OUString fileUrl;
if( nNew == -1 )
{
fileUrl = OUString( &( pythonPathBootstrap[nIndex] ) );
}
else
{
fileUrl = OUString( &(pythonPathBootstrap[nIndex]) , nNew - nIndex );
}
OUString systemPath;
osl_getSystemPathFromFileURL( fileUrl.pData, &(systemPath.pData) );
bufPYTHONPATH.append( systemPath );
if( nNew == -1 )
break;
bufPYTHONPATH.append( (sal_Unicode) SAL_PATHSEPARATOR );
nIndex = nNew + 1;
}
}
OUString value;
osl_getEnvironment( pythonPath.pData, &value.pData );
bufPYTHONPATH.append( value );
rtl::OStringBuffer stringBuffer;
stringBuffer.append( "PYTHONPATH=" );
stringBuffer.append(
rtl::OUStringToOString( bufPYTHONPATH.makeStringAndClear(), osl_getThreadTextEncoding()));
OString env = stringBuffer.makeStringAndClear();
// leak this string (putenv does not make a copy)
rtl_string_acquire( env.pData );
putenv( env.pData->buffer );
// initialize python
Py_Initialize();
PyEval_InitThreads();
PyThreadState *tstate = PyThreadState_Get();
PyEval_ReleaseThread( tstate );
}
PyThreadAttach attach( PyInterpreterState_Head() );
{
if( ! Runtime::isInitialized() )
{
Runtime::initialize( ctx );
}
Runtime runtime;
PyRef pyCtx = runtime.any2PyObject(
com::sun::star::uno::makeAny( ctx ) );
PyRef clazz = getObjectFromLoaderModule( "Loader" );
PyRef args ( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
PyTuple_SetItem( args.get(), 0 , pyCtx.getAcquired() );
PyRef pyInstance( PyObject_CallObject( clazz.get() , args.get() ), SAL_NO_ACQUIRE );
runtime.pyObject2Any( pyInstance ) >>= ret;
}
return ret;
}
}
static struct cppu::ImplementationEntry g_entries[] =
{
{
pyuno_loader::CreateInstance, pyuno_loader::getImplementationName,
pyuno_loader::getSupportedServiceNames, cppu::createSingleComponentFactory,
0 , 0
},
{ 0, 0, 0, 0, 0, 0 }
};
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
void * pServiceManager, void * pRegistryKey )
{
return cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}
<|endoftext|>
|
<commit_before>/**
* @file llmessageconfig_tut.cpp
* @date March 2007
* @brief LLMessageConfig unit tests
*
* $LicenseInfo:firstyear=2006&license=viewergpl$
*
* Copyright (c) 2006-2007, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlife.com/developers/opensource/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at http://secondlife.com/developers/opensource/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmessageconfig.h"
#include "lltut.h"
#include "llsdserialize.h"
#include "llfile.h"
#include "lltimer.h"
#include "llframetimer.h"
#include "llsdutil.h"
namespace tut
{
struct LLMessageConfigTestData {
std::string mTestConfigDir;
LLMessageConfigTestData()
{
LLUUID random;
random.generate();
// generate temp dir
std::ostringstream oStr;
oStr << "/tmp/llmessage-config-test-" << random;
mTestConfigDir = oStr.str();
LLFile::mkdir(mTestConfigDir.c_str());
writeConfigFile(LLSD());
LLMessageConfig::initClass("simulator", mTestConfigDir);
}
~LLMessageConfigTestData()
{
// rm contents of temp dir
int rmfile = LLFile::remove((mTestConfigDir + "/message.xml").c_str());
ensure_equals("rmfile value", rmfile, 0);
// rm temp dir
int rmdir = LLFile::rmdir(mTestConfigDir.c_str());
ensure_equals("rmdir value", rmdir, 0);
}
void writeConfigFile(const LLSD& config)
{
llofstream file((mTestConfigDir + "/message.xml").c_str());
if (file.is_open())
{
LLSDSerialize::toPrettyXML(config, file);
}
file.close();
}
};
typedef test_group<LLMessageConfigTestData> LLMessageConfigTestGroup;
typedef LLMessageConfigTestGroup::object LLMessageConfigTestObject;
LLMessageConfigTestGroup llMessageConfigTestGroup("LLMessageConfig");
template<> template<>
void LLMessageConfigTestObject::test<1>()
// tests server defaults
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
LLMessageConfig::useConfig(config);
ensure_equals("Ensure server default is not template",
LLMessageConfig::getServerDefaultFlavor(),
LLMessageConfig::TEMPLATE_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<2>()
// tests message flavors
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "template";
config["messages"]["msg2"]["flavor"] = "llsd";
LLMessageConfig::useConfig(config);
ensure_equals("Ensure msg template flavor",
LLMessageConfig::getMessageFlavor("msg1"),
LLMessageConfig::TEMPLATE_FLAVOR);
ensure_equals("Ensure msg llsd flavor",
LLMessageConfig::getMessageFlavor("msg2"),
LLMessageConfig::LLSD_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<4>()
// tests message flavor defaults
{
LLSD config;
config["serverDefaults"]["simulator"] = "llsd";
config["messages"]["msg1"]["trusted-sender"] = true;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure missing message gives no flavor",
LLMessageConfig::getMessageFlavor("Test"),
LLMessageConfig::NO_FLAVOR);
ensure_equals("Ensure missing flavor is NO_FLAVOR even with sender trustedness set",
LLMessageConfig::getMessageFlavor("msg1"),
LLMessageConfig::NO_FLAVOR);
ensure_equals("Ensure server default is llsd",
LLMessageConfig::getServerDefaultFlavor(),
LLMessageConfig::LLSD_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<3>()
// tests trusted/untrusted senders
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "llsd";
config["messages"]["msg1"]["trusted-sender"] = false;
config["messages"]["msg2"]["flavor"] = "llsd";
config["messages"]["msg2"]["trusted-sender"] = true;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure untrusted is untrusted",
LLMessageConfig::getSenderTrustedness("msg1"),
LLMessageConfig::UNTRUSTED);
ensure_equals("Ensure trusted is trusted",
LLMessageConfig::getSenderTrustedness("msg2"),
LLMessageConfig::TRUSTED);
ensure_equals("Ensure missing trustedness is NOT_SET",
LLMessageConfig::getSenderTrustedness("msg3"),
LLMessageConfig::NOT_SET);
}
template<> template<>
void LLMessageConfigTestObject::test<5>()
// tests trusted/untrusted without flag, only flavor
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "llsd";
LLMessageConfig::useConfig(config);
ensure_equals("Ensure msg1 exists, has llsd flavor",
LLMessageConfig::getMessageFlavor("msg1"),
LLMessageConfig::LLSD_FLAVOR);
ensure_equals("Ensure missing trusted is not set",
LLMessageConfig::getSenderTrustedness("msg1"),
LLMessageConfig::NOT_SET);
}
template<> template<>
void LLMessageConfigTestObject::test<6>()
{
LLSD config;
config["capBans"]["MapLayer"] = true;
config["capBans"]["MapLayerGod"] = false;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure cap ban true MapLayer",
LLMessageConfig::isCapBanned("MapLayer"),
true);
ensure_equals("Ensure cap ban false",
LLMessageConfig::isCapBanned("MapLayerGod"),
false);
}
template<> template<>
void LLMessageConfigTestObject::test<7>()
// tests that config changes are picked up/refreshed periodically
{
LLSD config;
config["serverDefaults"]["simulator"] = "llsd";
writeConfigFile(config);
// wait for it to reload after N seconds
ms_sleep(6*1000);
LLFrameTimer::updateFrameTime();
ensure_equals("Ensure reload after 6 seconds",
LLMessageConfig::getServerDefaultFlavor(),
LLMessageConfig::LLSD_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<8>()
// tests that config changes are picked up/refreshed periodically
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "llsd";
config["messages"]["msg1"]["only-send-latest"] = true;
config["messages"]["msg2"]["flavor"] = "llsd";
config["messages"]["msg2"]["only-send-latest"] = false;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure msg1 exists, sent latest-only",
LLMessageConfig::onlySendLatest("msg1"),
true);
ensure_equals("Ensure msg2 exists, sent latest-only",
LLMessageConfig::onlySendLatest("msg2"),
false);
}
}
<commit_msg>Fixed unit test failure on Windows, "/tmp" doesn't exist on Win32. Ported from Havok4 branch, reviewed with Kelly, OK with Josh.<commit_after>/**
* @file llmessageconfig_tut.cpp
* @date March 2007
* @brief LLMessageConfig unit tests
*
* $LicenseInfo:firstyear=2006&license=viewergpl$
*
* Copyright (c) 2006-2007, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlife.com/developers/opensource/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at http://secondlife.com/developers/opensource/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmessageconfig.h"
#include "lltut.h"
#include "llsdserialize.h"
#include "llfile.h"
#include "lltimer.h"
#include "llframetimer.h"
#include "llsdutil.h"
namespace tut
{
struct LLMessageConfigTestData {
std::string mTestConfigDir;
LLMessageConfigTestData()
{
LLUUID random;
random.generate();
// generate temp dir
std::ostringstream oStr;
#if LL_WINDOWS
oStr << "llmessage-config-test-" << random;
#else
oStr << "/tmp/llmessage-config-test-" << random;
#endif
mTestConfigDir = oStr.str();
LLFile::mkdir(mTestConfigDir.c_str());
writeConfigFile(LLSD());
LLMessageConfig::initClass("simulator", mTestConfigDir);
}
~LLMessageConfigTestData()
{
// rm contents of temp dir
int rmfile = LLFile::remove((mTestConfigDir + "/message.xml").c_str());
ensure_equals("rmfile value", rmfile, 0);
// rm temp dir
int rmdir = LLFile::rmdir(mTestConfigDir.c_str());
ensure_equals("rmdir value", rmdir, 0);
}
void writeConfigFile(const LLSD& config)
{
llofstream file((mTestConfigDir + "/message.xml").c_str());
if (file.is_open())
{
LLSDSerialize::toPrettyXML(config, file);
}
file.close();
}
};
typedef test_group<LLMessageConfigTestData> LLMessageConfigTestGroup;
typedef LLMessageConfigTestGroup::object LLMessageConfigTestObject;
LLMessageConfigTestGroup llMessageConfigTestGroup("LLMessageConfig");
template<> template<>
void LLMessageConfigTestObject::test<1>()
// tests server defaults
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
LLMessageConfig::useConfig(config);
ensure_equals("Ensure server default is not template",
LLMessageConfig::getServerDefaultFlavor(),
LLMessageConfig::TEMPLATE_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<2>()
// tests message flavors
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "template";
config["messages"]["msg2"]["flavor"] = "llsd";
LLMessageConfig::useConfig(config);
ensure_equals("Ensure msg template flavor",
LLMessageConfig::getMessageFlavor("msg1"),
LLMessageConfig::TEMPLATE_FLAVOR);
ensure_equals("Ensure msg llsd flavor",
LLMessageConfig::getMessageFlavor("msg2"),
LLMessageConfig::LLSD_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<4>()
// tests message flavor defaults
{
LLSD config;
config["serverDefaults"]["simulator"] = "llsd";
config["messages"]["msg1"]["trusted-sender"] = true;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure missing message gives no flavor",
LLMessageConfig::getMessageFlavor("Test"),
LLMessageConfig::NO_FLAVOR);
ensure_equals("Ensure missing flavor is NO_FLAVOR even with sender trustedness set",
LLMessageConfig::getMessageFlavor("msg1"),
LLMessageConfig::NO_FLAVOR);
ensure_equals("Ensure server default is llsd",
LLMessageConfig::getServerDefaultFlavor(),
LLMessageConfig::LLSD_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<3>()
// tests trusted/untrusted senders
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "llsd";
config["messages"]["msg1"]["trusted-sender"] = false;
config["messages"]["msg2"]["flavor"] = "llsd";
config["messages"]["msg2"]["trusted-sender"] = true;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure untrusted is untrusted",
LLMessageConfig::getSenderTrustedness("msg1"),
LLMessageConfig::UNTRUSTED);
ensure_equals("Ensure trusted is trusted",
LLMessageConfig::getSenderTrustedness("msg2"),
LLMessageConfig::TRUSTED);
ensure_equals("Ensure missing trustedness is NOT_SET",
LLMessageConfig::getSenderTrustedness("msg3"),
LLMessageConfig::NOT_SET);
}
template<> template<>
void LLMessageConfigTestObject::test<5>()
// tests trusted/untrusted without flag, only flavor
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "llsd";
LLMessageConfig::useConfig(config);
ensure_equals("Ensure msg1 exists, has llsd flavor",
LLMessageConfig::getMessageFlavor("msg1"),
LLMessageConfig::LLSD_FLAVOR);
ensure_equals("Ensure missing trusted is not set",
LLMessageConfig::getSenderTrustedness("msg1"),
LLMessageConfig::NOT_SET);
}
template<> template<>
void LLMessageConfigTestObject::test<6>()
{
LLSD config;
config["capBans"]["MapLayer"] = true;
config["capBans"]["MapLayerGod"] = false;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure cap ban true MapLayer",
LLMessageConfig::isCapBanned("MapLayer"),
true);
ensure_equals("Ensure cap ban false",
LLMessageConfig::isCapBanned("MapLayerGod"),
false);
}
template<> template<>
void LLMessageConfigTestObject::test<7>()
// tests that config changes are picked up/refreshed periodically
{
LLSD config;
config["serverDefaults"]["simulator"] = "llsd";
writeConfigFile(config);
// wait for it to reload after N seconds
ms_sleep(6*1000);
LLFrameTimer::updateFrameTime();
ensure_equals("Ensure reload after 6 seconds",
LLMessageConfig::getServerDefaultFlavor(),
LLMessageConfig::LLSD_FLAVOR);
}
template<> template<>
void LLMessageConfigTestObject::test<8>()
// tests that config changes are picked up/refreshed periodically
{
LLSD config;
config["serverDefaults"]["simulator"] = "template";
config["messages"]["msg1"]["flavor"] = "llsd";
config["messages"]["msg1"]["only-send-latest"] = true;
config["messages"]["msg2"]["flavor"] = "llsd";
config["messages"]["msg2"]["only-send-latest"] = false;
LLMessageConfig::useConfig(config);
ensure_equals("Ensure msg1 exists, sent latest-only",
LLMessageConfig::onlySendLatest("msg1"),
true);
ensure_equals("Ensure msg2 exists, sent latest-only",
LLMessageConfig::onlySendLatest("msg2"),
false);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: pyuno_except.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hjs $ $Date: 2003-08-18 15:01:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Ralph Thomas
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Ralph Thomas, Joerg Budischewski
*
*
************************************************************************/
#include "pyuno_impl.hxx"
#include <rtl/ustrbuf.hxx>
#include <typelib/typedescription.hxx>
using rtl::OUString;
using rtl::OUStringBuffer;
using rtl::OUStringToOString;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Type;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::TypeDescription;
namespace pyuno
{
void raisePyExceptionWithAny( const com::sun::star::uno::Any &anyExc )
{
try
{
Runtime runtime;
PyRef exc = runtime.any2PyObject( anyExc );
if( exc.is() )
{
PyRef type( getClass( anyExc.getValueType().getTypeName(),runtime ) );
PyErr_SetObject( type.get(), exc.get());
}
else
{
com::sun::star::uno::Exception e;
anyExc >>= e;
OUStringBuffer buf;
buf.appendAscii( "Couldn't convert uno exception to a python exception (" );
buf.append(anyExc.getValueType().getTypeName());
buf.appendAscii( ": " );
buf.append(e.Message );
buf.appendAscii( ")" );
PyErr_SetString(
PyExc_SystemError,
OUStringToOString(buf.makeStringAndClear(),RTL_TEXTENCODING_ASCII_US) );
}
}
catch( com::sun::star::lang::IllegalArgumentException & e)
{
PyErr_SetString( PyExc_SystemError,
OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US) );
}
catch( com::sun::star::script::CannotConvertException & e)
{
PyErr_SetString( PyExc_SystemError,
OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US) );
}
catch( RuntimeException & e)
{
PyErr_SetString( PyExc_SystemError,
OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US) );
}
}
static PyRef createClass( const OUString & name, const Runtime &runtime )
throw ( RuntimeException )
{
// assuming that this is never deleted !
// note I don't have the knowledge how to initialize these type objects correctly !
TypeDescription desc( name );
if( ! desc.is() )
{
OUStringBuffer buf;
buf.appendAscii( "pyuno.getClass: uno exception " );
buf.append(name).appendAscii( " is unknown" );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface > () );
}
sal_Bool isStruct = desc.get()->eTypeClass == typelib_TypeClass_STRUCT;
sal_Bool isExc = desc.get()->eTypeClass == typelib_TypeClass_EXCEPTION;
sal_Bool isInterface = desc.get()->eTypeClass == typelib_TypeClass_INTERFACE;
if( !isStruct && !isExc && ! isInterface )
{
OUStringBuffer buf;
buf.appendAscii( "pyuno.getClass: " ).append(name).appendAscii( "is a " );
buf.appendAscii(
typeClassToString( (com::sun::star::uno::TypeClass) desc.get()->eTypeClass));
buf.appendAscii( ", expected EXCEPTION, STRUCT or INTERFACE" );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface>() );
}
// retrieve base class
PyRef base;
if( isInterface )
{
typelib_InterfaceTypeDescription *pDesc = (typelib_InterfaceTypeDescription * )desc.get();
if( pDesc->pBaseTypeDescription )
{
base = getClass( pDesc->pBaseTypeDescription->aBase.pTypeName, runtime );
}
else
{
// must be XInterface !
}
}
else
{
typelib_CompoundTypeDescription *pDesc = (typelib_CompoundTypeDescription*)desc.get();
if( pDesc->pBaseTypeDescription )
{
base = getClass( pDesc->pBaseTypeDescription->aBase.pTypeName, runtime );
}
else
{
if( isExc )
// we are currently creating the root UNO exception
base = PyRef(PyExc_Exception);
}
}
PyRef args( PyTuple_New( 3 ), SAL_NO_ACQUIRE );
PyRef pyTypeName = ustring2PyString( name /*.replace( '.', '_' )*/ );
PyRef bases;
if( base.is() )
{
{ // for CC, keeping ref-count being 1
bases = PyRef( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
}
PyTuple_SetItem( bases.get(), 0 , base.getAcquired() );
}
else
{
bases = PyRef( PyTuple_New( 0 ), SAL_NO_ACQUIRE );
}
PyTuple_SetItem( args.get(), 0, pyTypeName.getAcquired());
PyTuple_SetItem( args.get(), 1, bases.getAcquired() );
PyTuple_SetItem( args.get(), 2, PyDict_New() );
PyRef ret(
PyObject_CallObject(reinterpret_cast<PyObject *>(&PyClass_Type) , args.get()),
SAL_NO_ACQUIRE );
// now overwrite ctor and attrib functions
if( isInterface )
{
PyObject_SetAttrString( ret.get(), "__pyunointerface__" , ustring2PyString(name).get() );
}
else
{
PyRef ctor = getObjectFromUnoModule( runtime,"_uno_struct__init__" );
PyRef setter = getObjectFromUnoModule( runtime,"_uno_struct__setattr__" );
PyRef getter = getObjectFromUnoModule( runtime,"_uno_struct__getattr__" );
PyRef repr = getObjectFromUnoModule( runtime,"_uno_struct__repr__" );
PyRef eq = getObjectFromUnoModule( runtime,"_uno_struct__eq__" );
PyObject_SetAttrString( ret.get(), "__pyunostruct__" , ustring2PyString(name).get() );
PyObject_SetAttrString( ret.get(), "typeName", ustring2PyString(name).get() );
PyObject_SetAttrString( ret.get(), "__init__" , ctor.get() );
PyObject_SetAttrString( ret.get(), "__getattr__", getter.get() );
PyObject_SetAttrString( ret.get(), "__setattr__", setter.get() );
PyObject_SetAttrString( ret.get(), "__repr__", repr.get() );
PyObject_SetAttrString( ret.get(), "__str__", repr.get() );
PyObject_SetAttrString( ret.get(), "__eq__", eq.get() );
}
return ret;
}
sal_Bool isInstanceOfStructOrException( const Runtime & runtime, PyObject *obj)
{
PyRef attr(PyObject_GetAttrString(obj,"__class__"), SAL_NO_ACQUIRE );
return PyObject_HasAttrString(attr.get(),"__pyunostruct__");
}
sal_Bool isInterfaceClass( const Runtime &runtime, PyObject * obj )
{
const ClassSet & set = runtime.getImpl()->cargo->interfaceSet;
return set.find( obj ) != set.end();
}
PyRef getClass( const OUString & name , const Runtime &runtime)
{
PyRef ret;
RuntimeCargo *cargo =runtime.getImpl()->cargo;
ExceptionClassMap::iterator ii = cargo->exceptionMap.find( name );
if( ii == cargo->exceptionMap.end() )
{
ret = createClass( name, runtime );
cargo->exceptionMap[name] = ret;
if( PyObject_HasAttrString( ret.get() , "__pyunointerface__" ) )
cargo->interfaceSet.insert( ret );
PyObject_SetAttrString( ret.get(), "__pyunointerface__" , ustring2PyString(name).get() );
}
else
{
ret = ii->second;
}
return ret;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.54); FILE MERGED 2005/09/05 18:39:21 rt 1.2.54.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_except.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:52:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "pyuno_impl.hxx"
#include <rtl/ustrbuf.hxx>
#include <typelib/typedescription.hxx>
using rtl::OUString;
using rtl::OUStringBuffer;
using rtl::OUStringToOString;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Type;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::TypeDescription;
namespace pyuno
{
void raisePyExceptionWithAny( const com::sun::star::uno::Any &anyExc )
{
try
{
Runtime runtime;
PyRef exc = runtime.any2PyObject( anyExc );
if( exc.is() )
{
PyRef type( getClass( anyExc.getValueType().getTypeName(),runtime ) );
PyErr_SetObject( type.get(), exc.get());
}
else
{
com::sun::star::uno::Exception e;
anyExc >>= e;
OUStringBuffer buf;
buf.appendAscii( "Couldn't convert uno exception to a python exception (" );
buf.append(anyExc.getValueType().getTypeName());
buf.appendAscii( ": " );
buf.append(e.Message );
buf.appendAscii( ")" );
PyErr_SetString(
PyExc_SystemError,
OUStringToOString(buf.makeStringAndClear(),RTL_TEXTENCODING_ASCII_US) );
}
}
catch( com::sun::star::lang::IllegalArgumentException & e)
{
PyErr_SetString( PyExc_SystemError,
OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US) );
}
catch( com::sun::star::script::CannotConvertException & e)
{
PyErr_SetString( PyExc_SystemError,
OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US) );
}
catch( RuntimeException & e)
{
PyErr_SetString( PyExc_SystemError,
OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US) );
}
}
static PyRef createClass( const OUString & name, const Runtime &runtime )
throw ( RuntimeException )
{
// assuming that this is never deleted !
// note I don't have the knowledge how to initialize these type objects correctly !
TypeDescription desc( name );
if( ! desc.is() )
{
OUStringBuffer buf;
buf.appendAscii( "pyuno.getClass: uno exception " );
buf.append(name).appendAscii( " is unknown" );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface > () );
}
sal_Bool isStruct = desc.get()->eTypeClass == typelib_TypeClass_STRUCT;
sal_Bool isExc = desc.get()->eTypeClass == typelib_TypeClass_EXCEPTION;
sal_Bool isInterface = desc.get()->eTypeClass == typelib_TypeClass_INTERFACE;
if( !isStruct && !isExc && ! isInterface )
{
OUStringBuffer buf;
buf.appendAscii( "pyuno.getClass: " ).append(name).appendAscii( "is a " );
buf.appendAscii(
typeClassToString( (com::sun::star::uno::TypeClass) desc.get()->eTypeClass));
buf.appendAscii( ", expected EXCEPTION, STRUCT or INTERFACE" );
throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface>() );
}
// retrieve base class
PyRef base;
if( isInterface )
{
typelib_InterfaceTypeDescription *pDesc = (typelib_InterfaceTypeDescription * )desc.get();
if( pDesc->pBaseTypeDescription )
{
base = getClass( pDesc->pBaseTypeDescription->aBase.pTypeName, runtime );
}
else
{
// must be XInterface !
}
}
else
{
typelib_CompoundTypeDescription *pDesc = (typelib_CompoundTypeDescription*)desc.get();
if( pDesc->pBaseTypeDescription )
{
base = getClass( pDesc->pBaseTypeDescription->aBase.pTypeName, runtime );
}
else
{
if( isExc )
// we are currently creating the root UNO exception
base = PyRef(PyExc_Exception);
}
}
PyRef args( PyTuple_New( 3 ), SAL_NO_ACQUIRE );
PyRef pyTypeName = ustring2PyString( name /*.replace( '.', '_' )*/ );
PyRef bases;
if( base.is() )
{
{ // for CC, keeping ref-count being 1
bases = PyRef( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
}
PyTuple_SetItem( bases.get(), 0 , base.getAcquired() );
}
else
{
bases = PyRef( PyTuple_New( 0 ), SAL_NO_ACQUIRE );
}
PyTuple_SetItem( args.get(), 0, pyTypeName.getAcquired());
PyTuple_SetItem( args.get(), 1, bases.getAcquired() );
PyTuple_SetItem( args.get(), 2, PyDict_New() );
PyRef ret(
PyObject_CallObject(reinterpret_cast<PyObject *>(&PyClass_Type) , args.get()),
SAL_NO_ACQUIRE );
// now overwrite ctor and attrib functions
if( isInterface )
{
PyObject_SetAttrString( ret.get(), "__pyunointerface__" , ustring2PyString(name).get() );
}
else
{
PyRef ctor = getObjectFromUnoModule( runtime,"_uno_struct__init__" );
PyRef setter = getObjectFromUnoModule( runtime,"_uno_struct__setattr__" );
PyRef getter = getObjectFromUnoModule( runtime,"_uno_struct__getattr__" );
PyRef repr = getObjectFromUnoModule( runtime,"_uno_struct__repr__" );
PyRef eq = getObjectFromUnoModule( runtime,"_uno_struct__eq__" );
PyObject_SetAttrString( ret.get(), "__pyunostruct__" , ustring2PyString(name).get() );
PyObject_SetAttrString( ret.get(), "typeName", ustring2PyString(name).get() );
PyObject_SetAttrString( ret.get(), "__init__" , ctor.get() );
PyObject_SetAttrString( ret.get(), "__getattr__", getter.get() );
PyObject_SetAttrString( ret.get(), "__setattr__", setter.get() );
PyObject_SetAttrString( ret.get(), "__repr__", repr.get() );
PyObject_SetAttrString( ret.get(), "__str__", repr.get() );
PyObject_SetAttrString( ret.get(), "__eq__", eq.get() );
}
return ret;
}
sal_Bool isInstanceOfStructOrException( const Runtime & runtime, PyObject *obj)
{
PyRef attr(PyObject_GetAttrString(obj,"__class__"), SAL_NO_ACQUIRE );
return PyObject_HasAttrString(attr.get(),"__pyunostruct__");
}
sal_Bool isInterfaceClass( const Runtime &runtime, PyObject * obj )
{
const ClassSet & set = runtime.getImpl()->cargo->interfaceSet;
return set.find( obj ) != set.end();
}
PyRef getClass( const OUString & name , const Runtime &runtime)
{
PyRef ret;
RuntimeCargo *cargo =runtime.getImpl()->cargo;
ExceptionClassMap::iterator ii = cargo->exceptionMap.find( name );
if( ii == cargo->exceptionMap.end() )
{
ret = createClass( name, runtime );
cargo->exceptionMap[name] = ret;
if( PyObject_HasAttrString( ret.get() , "__pyunointerface__" ) )
cargo->interfaceSet.insert( ret );
PyObject_SetAttrString( ret.get(), "__pyunointerface__" , ustring2PyString(name).get() );
}
else
{
ret = ii->second;
}
return ret;
}
}
<|endoftext|>
|
<commit_before>#pragma once
#ifndef _QI_SOCK_CONNECTEDSTATE_HPP
#define _QI_SOCK_CONNECTEDSTATE_HPP
#include <memory>
#include <utility>
#include <boost/optional.hpp>
#include <qi/atomic.hpp>
#include <qi/functional.hpp>
#include <qi/future.hpp>
#include <qi/messaging/sock/common.hpp>
#include <qi/messaging/sock/receive.hpp>
#include <qi/messaging/sock/send.hpp>
#include <qi/messaging/sock/traits.hpp>
#include "src/messaging/message.hpp"
#include <qi/url.hpp>
namespace qi
{
namespace sock
{
/// The URL of the endpoint of the given socket.
/// Precondition: The socket must be connected.
///
/// NetSslSocket S
template<typename S>
Url remoteEndpoint(S& socket, bool ssl)
{
const auto endpoint = socket.lowest_layer().remote_endpoint();
return url(endpoint, SslEnabled{ssl});
}
/// Ouput of the connected state.
///
/// It contains the socket, error information, and a promise to be set to
/// indicate the end of the disconnection. This promise will typically be
/// passed to the disconnecting state and finally set by the disconnected state.
///
/// The only valid operation on the socket is to close it.
///
/// The error message is valid only if there was an error.
///
/// Example:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// // res is a ConnectedResult<N>
/// if (res.hasError)
/// {
/// qiLogWarning() << "socket exited connected state with an error: "
/// << res.errorMessage;
/// }
/// close<N>(res.socket);
/// res.disconnectedPromise.setValue(nullptr);
/// // ...
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Network N,
/// With NetSslSocket S:
/// S is compatible with N
template<typename N, typename S>
struct ConnectedResult
{
SocketPtr<S> socket;
/// If a disconnection was requested, this promise is related to the future
/// returned to the caller. Setting it will inform the caller that the
/// disconnection is complete (that is, the socket is in a disconnected state).
Promise<void> disconnectedPromise;
bool hasError;
std::string errorMessage;
ConnectedResult(SocketPtr<S> s = SocketPtr<S>{})
: socket(s)
, hasError(false)
{
}
};
/// Network N
/// With NetSslSocket S:
/// S is compatible with N
template<typename N, typename S>
using SyncConnectedResult = boost::synchronized_value<ConnectedResult<N, S>>;
/// Network N
/// With NetSslSocket S:
/// S is compatible with N
template<typename N, typename S>
using SyncConnectedResultPtr = boost::shared_ptr<SyncConnectedResult<N, S>>;
boost::optional<qi::int64_t> getSocketTimeWarnThresholdFromEnv();
/// Connected state of the socket.
/// Allow to send and receive messages.
///
/// Received messages are exposed via a callback specified at construction.
///
/// You can send messages continuously : they will be enqueued if needed.
/// By default, enqueued messages are sent as soon as possible, but
/// you can explicitly ask to stop the queue processing.
///
/// You can request this state to stop, by optionally passing it a Promise
/// to be set on disconnection.
///
/// A `complete` future is set when the connected state is over.
/// It contains the socket and a Promise to be set when disconnection is over.
///
/// If an error occurs while sending or receiving, the `complete` future is
/// set in error.
///
/// Warning: You must call `stop()` before closing the socket, because
/// closing the socket cause the send and receive handlers to be called with
/// an 'abort' error, and we don't want to take it into account.
///
/// Usage:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// auto onReceive = [](ErrorCode e, const Message* msg) {
/// // `msg` is valid only if there is no error.
/// // Do something with `msg`.
/// return true; // Or return false to stop listening to message.
/// };
/// Connected<N> c{socketPtr, SslEnabled{true}, maxPayload, onReceive};
/// // Get a Message msg;
/// c.send(msg); // Move the message if you can, to avoid a copy.
/// // Send more messages.
/// Future<std::pair<SocketPtr<S>, Promise<void>>> futureComplete = c.complete();
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Network N
/// NetSslSocket N
template<typename N, typename S>
struct Connected
{
private:
struct Impl : std::enable_shared_from_this<Impl>
{
using std::enable_shared_from_this<Impl>::shared_from_this;
using ReadableMessage = typename SendMessageEnqueue<N, SocketPtr<S>>::ReadableMessage;
boost::synchronized_value<Promise<SyncConnectedResultPtr<N, S>>> _completePromise;
SyncConnectedResultPtr<N, S> _result;
std::atomic<bool> _stopRequested;
std::atomic<bool> _shuttingdown;
ReceiveMessageContinuous<N> _receiveMsg;
SendMessageEnqueue<N, SocketPtr<S>> _sendMsg;
Impl(const SocketPtr<S>& socket);
~Impl();
template<typename Proc>
void start(SslEnabled, size_t maxPayload, Proc onReceive, qi::int64_t messageHandlingTimeoutInMus);
template<typename Msg, typename Proc>
void send(Msg&& msg, SslEnabled, Proc onSent);
void stop(Promise<void> disconnectedPromise)
{
if (tryRaiseAtomicFlag(_stopRequested))
{
(*_result)->disconnectedPromise = disconnectedPromise;
// The shutdown will cause any pending operation on the socket to fail.
auto self = shared_from_this();
ioServiceStranded([=] {
self->_shuttingdown = true;
auto socket = (*self->_result)->socket;
socket->lowest_layer().cancel();
socket->lowest_layer().shutdown(ShutdownMode<Lowest<S>>::shutdown_both);
})();
}
else
{
// The disconnected promise has already been set.
// Forward the result when we have it.
adaptFuture((*_result)->disconnectedPromise.future(), disconnectedPromise);
}
}
void setPromise(const sock::ErrorCode<N>&, const Message*);
SocketPtr<S>& socket()
{
return (*_result)->socket;
}
template<typename Proc>
auto ioServiceStranded(Proc&& p)
-> decltype(StrandTransfo<N>{std::declval<IoService<N>*>()}(std::forward<Proc>(p)))
{
return StrandTransfo<N>{&socket()->get_io_service()}(std::forward<Proc>(p));
}
DataBoundTransfo<std::shared_ptr<Impl>> lifetimeTransfo()
{
return dataBoundTransfo(shared_from_this());
}
StrandTransfo<N> syncTransfo()
{
return {&(*socket()).get_io_service()};
}
};
std::shared_ptr<Impl> _impl;
public:
/// If `onReceive` returns `false`, this stops the message receiving.
///
/// Procedure<bool (ErrorCode<N>, const Message*)> Proc
template<typename Proc>
Connected(const SocketPtr<S>&, SslEnabled ssl, size_t maxPayload, const Proc& onReceive,
qi::int64_t messageHandlingTimeoutInMus = getSocketTimeWarnThresholdFromEnv().value_or(0));
/// If `onSent` returns false, the processing of enqueued messages stops.
///
/// Procedure<bool (ErrorCode<N>, std::list<Message>::const_iterator)>
template<typename Msg, typename Proc = NoOpProcedure<bool (ErrorCode<N>, std::list<Message>::const_iterator)>>
void send(Msg&& msg, SslEnabled ssl, const Proc& onSent = {true})
{
return _impl->send(std::forward<Msg>(msg), ssl, onSent);
}
Future<SyncConnectedResultPtr<N, S>> complete() const
{
return _impl->_completePromise->future();
}
Url remoteEndpoint(SslEnabled ssl) const
{
return sock::remoteEndpoint(*_impl->socket(), *ssl);
}
void stop(Promise<void> disconnectedPromise = Promise<void>{})
{
_impl->stop(disconnectedPromise);
}
template<typename Proc>
auto ioServiceStranded(Proc&& p)
-> decltype(_impl->ioServiceStranded(std::forward<Proc>(p)))
{
return _impl->ioServiceStranded(std::forward<Proc>(p));
}
};
template<typename N, typename S>
template<typename Proc>
Connected<N, S>::Connected(const SocketPtr<S>& socket, SslEnabled ssl, size_t maxPayload,
const Proc& onReceive, qi::int64_t messageHandlingTimeoutInMus)
: _impl(std::make_shared<Impl>(socket))
{
_impl->start(ssl, maxPayload, onReceive, messageHandlingTimeoutInMus);
}
template<typename N, typename S>
Connected<N, S>::Impl::Impl(const SocketPtr<S>& s)
: _result{ boost::make_shared<SyncConnectedResult<N, S>>(ConnectedResult<N, S>{ s }) }
, _stopRequested(false)
, _shuttingdown(false)
, _sendMsg{s}
{
}
template<typename N, typename S>
void Connected<N, S>::Impl::setPromise(const sock::ErrorCode<N>& error, const Message* msg)
{
auto prom = _completePromise.synchronize();
if (!prom->future().isRunning()) // promise already set
return;
const bool stopAsked = _stopRequested.load() && _shuttingdown.load();
const bool hasError = error || !msg;
if (!stopAsked && hasError)
{
auto syncRes = _result->synchronize();
syncRes->hasError = true;
syncRes->errorMessage = error.message();
}
prom->setValue(_result);
}
template<typename N, typename S>
template<typename Proc>
void Connected<N, S>::Impl::start(SslEnabled ssl, size_t maxPayload, Proc onReceive,
qi::int64_t messageHandlingTimeoutInMus)
{
auto self = shared_from_this();
auto life = lifetimeTransfo();
auto sync = syncTransfo();
// We preventively strand the first call.
sync(life([=]() mutable {
_receiveMsg(socket(), ssl, maxPayload,
[=](sock::ErrorCode<N> e, const Message* msg) mutable { // onReceived
const bool mustContinue = !_shuttingdown.load() && onReceive(e, msg);
if (!mustContinue)
{
self->setPromise(e, msg);
return false; // We must not continue to receive messages.
}
return true; // Otherwise, we continue to receive messages.
},
life,
sync
);
}))();
}
template<typename N, typename S>
Connected<N, S>::Impl::~Impl()
{
}
template<typename N, typename S>
template<typename Msg, typename Proc>
void Connected<N, S>::Impl::send(Msg&& msg, SslEnabled ssl, Proc onSent)
{
using SendMessage = decltype(_sendMsg);
using ReadableMessage = typename SendMessage::ReadableMessage;
auto self = shared_from_this();
auto life = lifetimeTransfo();
auto sync = syncTransfo();
// We preventively strand the first call.
sync(life([=]() mutable {
_sendMsg(std::forward<Msg>(msg), ssl,
[=](const ErrorCode<N>& e, const ReadableMessage& ptrMsg) mutable { // onSent
const bool mustContinue = !_shuttingdown.load() && onSent(e, ptrMsg);
if (!mustContinue)
{
self->setPromise(e, &msg);
return false; // We must not continue to send messages.
}
return true; // Otherwise, we continue to send messages.
},
life,
sync
);
}))();
}
}} // namespace qi::sock
#endif // _QI_SOCK_CONNECTEDSTATE_HPP
<commit_msg>messaging: Removes unnecessary message copies.<commit_after>#pragma once
#ifndef _QI_SOCK_CONNECTEDSTATE_HPP
#define _QI_SOCK_CONNECTEDSTATE_HPP
#include <memory>
#include <utility>
#include <boost/optional.hpp>
#include <qi/atomic.hpp>
#include <qi/functional.hpp>
#include <qi/future.hpp>
#include <qi/messaging/sock/common.hpp>
#include <qi/messaging/sock/receive.hpp>
#include <qi/messaging/sock/send.hpp>
#include <qi/messaging/sock/traits.hpp>
#include "src/messaging/message.hpp"
#include <qi/url.hpp>
namespace qi
{
namespace sock
{
/// The URL of the endpoint of the given socket.
/// Precondition: The socket must be connected.
///
/// NetSslSocket S
template<typename S>
Url remoteEndpoint(S& socket, bool ssl)
{
const auto endpoint = socket.lowest_layer().remote_endpoint();
return url(endpoint, SslEnabled{ssl});
}
/// Ouput of the connected state.
///
/// It contains the socket, error information, and a promise to be set to
/// indicate the end of the disconnection. This promise will typically be
/// passed to the disconnecting state and finally set by the disconnected state.
///
/// The only valid operation on the socket is to close it.
///
/// The error message is valid only if there was an error.
///
/// Example:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// // res is a ConnectedResult<N>
/// if (res.hasError)
/// {
/// qiLogWarning() << "socket exited connected state with an error: "
/// << res.errorMessage;
/// }
/// close<N>(res.socket);
/// res.disconnectedPromise.setValue(nullptr);
/// // ...
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Network N,
/// With NetSslSocket S:
/// S is compatible with N
template<typename N, typename S>
struct ConnectedResult
{
SocketPtr<S> socket;
/// If a disconnection was requested, this promise is related to the future
/// returned to the caller. Setting it will inform the caller that the
/// disconnection is complete (that is, the socket is in a disconnected state).
Promise<void> disconnectedPromise;
bool hasError;
std::string errorMessage;
ConnectedResult(SocketPtr<S> s = SocketPtr<S>{})
: socket(s)
, hasError(false)
{
}
};
/// Network N
/// With NetSslSocket S:
/// S is compatible with N
template<typename N, typename S>
using SyncConnectedResult = boost::synchronized_value<ConnectedResult<N, S>>;
/// Network N
/// With NetSslSocket S:
/// S is compatible with N
template<typename N, typename S>
using SyncConnectedResultPtr = boost::shared_ptr<SyncConnectedResult<N, S>>;
boost::optional<qi::int64_t> getSocketTimeWarnThresholdFromEnv();
/// Connected state of the socket.
/// Allow to send and receive messages.
///
/// Received messages are exposed via a callback specified at construction.
///
/// You can send messages continuously : they will be enqueued if needed.
/// By default, enqueued messages are sent as soon as possible, but
/// you can explicitly ask to stop the queue processing.
///
/// You can request this state to stop, by optionally passing it a Promise
/// to be set on disconnection.
///
/// A `complete` future is set when the connected state is over.
/// It contains the socket and a Promise to be set when disconnection is over.
///
/// If an error occurs while sending or receiving, the `complete` future is
/// set in error.
///
/// Warning: You must call `stop()` before closing the socket, because
/// closing the socket cause the send and receive handlers to be called with
/// an 'abort' error, and we don't want to take it into account.
///
/// Usage:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// auto onReceive = [](ErrorCode e, const Message* msg) {
/// // `msg` is valid only if there is no error.
/// // Do something with `msg`.
/// return true; // Or return false to stop listening to message.
/// };
/// Connected<N> c{socketPtr, SslEnabled{true}, maxPayload, onReceive};
/// // Get a Message msg;
/// c.send(msg); // Move the message if you can, to avoid a copy.
/// // Send more messages.
/// Future<std::pair<SocketPtr<S>, Promise<void>>> futureComplete = c.complete();
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Network N
/// NetSslSocket N
template<typename N, typename S>
struct Connected
{
private:
struct Impl : std::enable_shared_from_this<Impl>
{
using std::enable_shared_from_this<Impl>::shared_from_this;
using ReadableMessage = typename SendMessageEnqueue<N, SocketPtr<S>>::ReadableMessage;
boost::synchronized_value<Promise<SyncConnectedResultPtr<N, S>>> _completePromise;
SyncConnectedResultPtr<N, S> _result;
std::atomic<bool> _stopRequested;
std::atomic<bool> _shuttingdown;
ReceiveMessageContinuous<N> _receiveMsg;
SendMessageEnqueue<N, SocketPtr<S>> _sendMsg;
Impl(const SocketPtr<S>& socket);
~Impl();
template<typename Proc>
void start(SslEnabled, size_t maxPayload, Proc onReceive, qi::int64_t messageHandlingTimeoutInMus);
template<typename Msg, typename Proc>
void send(Msg&& msg, SslEnabled, Proc onSent);
void stop(Promise<void> disconnectedPromise)
{
if (tryRaiseAtomicFlag(_stopRequested))
{
(*_result)->disconnectedPromise = disconnectedPromise;
// The shutdown will cause any pending operation on the socket to fail.
auto self = shared_from_this();
ioServiceStranded([=] {
self->_shuttingdown = true;
auto socket = (*self->_result)->socket;
socket->lowest_layer().cancel();
socket->lowest_layer().shutdown(ShutdownMode<Lowest<S>>::shutdown_both);
})();
}
else
{
// The disconnected promise has already been set.
// Forward the result when we have it.
adaptFuture((*_result)->disconnectedPromise.future(), disconnectedPromise);
}
}
void setPromise(const sock::ErrorCode<N>&);
SocketPtr<S>& socket()
{
return (*_result)->socket;
}
template<typename Proc>
auto ioServiceStranded(Proc&& p)
-> decltype(StrandTransfo<N>{std::declval<IoService<N>*>()}(std::forward<Proc>(p)))
{
return StrandTransfo<N>{&socket()->get_io_service()}(std::forward<Proc>(p));
}
DataBoundTransfo<std::shared_ptr<Impl>> lifetimeTransfo()
{
return dataBoundTransfo(shared_from_this());
}
StrandTransfo<N> syncTransfo()
{
return {&(*socket()).get_io_service()};
}
};
std::shared_ptr<Impl> _impl;
public:
/// If `onReceive` returns `false`, this stops the message receiving.
///
/// Procedure<bool (ErrorCode<N>, const Message*)> Proc
template<typename Proc>
Connected(const SocketPtr<S>&, SslEnabled ssl, size_t maxPayload, const Proc& onReceive,
qi::int64_t messageHandlingTimeoutInMus = getSocketTimeWarnThresholdFromEnv().value_or(0));
/// If `onSent` returns false, the processing of enqueued messages stops.
///
/// Procedure<bool (ErrorCode<N>, std::list<Message>::const_iterator)>
template<typename Msg, typename Proc = NoOpProcedure<bool (ErrorCode<N>, std::list<Message>::const_iterator)>>
void send(Msg&& msg, SslEnabled ssl, const Proc& onSent = {true})
{
return _impl->send(std::forward<Msg>(msg), ssl, onSent);
}
Future<SyncConnectedResultPtr<N, S>> complete() const
{
return _impl->_completePromise->future();
}
Url remoteEndpoint(SslEnabled ssl) const
{
return sock::remoteEndpoint(*_impl->socket(), *ssl);
}
void stop(Promise<void> disconnectedPromise = Promise<void>{})
{
_impl->stop(disconnectedPromise);
}
template<typename Proc>
auto ioServiceStranded(Proc&& p)
-> decltype(_impl->ioServiceStranded(std::forward<Proc>(p)))
{
return _impl->ioServiceStranded(std::forward<Proc>(p));
}
};
template<typename N, typename S>
template<typename Proc>
Connected<N, S>::Connected(const SocketPtr<S>& socket, SslEnabled ssl, size_t maxPayload,
const Proc& onReceive, qi::int64_t messageHandlingTimeoutInMus)
: _impl(std::make_shared<Impl>(socket))
{
_impl->start(ssl, maxPayload, onReceive, messageHandlingTimeoutInMus);
}
template<typename N, typename S>
Connected<N, S>::Impl::Impl(const SocketPtr<S>& s)
: _result{ boost::make_shared<SyncConnectedResult<N, S>>(ConnectedResult<N, S>{ s }) }
, _stopRequested(false)
, _shuttingdown(false)
, _sendMsg{s}
{
}
template<typename N, typename S>
void Connected<N, S>::Impl::setPromise(const sock::ErrorCode<N>& error)
{
auto prom = _completePromise.synchronize();
if (!prom->future().isRunning()) // promise already set
return;
const bool stopAsked = _stopRequested.load() && _shuttingdown.load();
if (!stopAsked && error)
{
auto syncRes = _result->synchronize();
syncRes->hasError = true;
syncRes->errorMessage = error.message();
}
prom->setValue(_result);
}
template<typename N, typename S>
template<typename Proc>
void Connected<N, S>::Impl::start(SslEnabled ssl, size_t maxPayload, Proc onReceive,
qi::int64_t messageHandlingTimeoutInMus)
{
auto self = shared_from_this();
auto life = lifetimeTransfo();
auto sync = syncTransfo();
// We preventively strand the first call.
sync(life([=]() mutable {
_receiveMsg(socket(), ssl, maxPayload,
[=](sock::ErrorCode<N> e, const Message* msg) mutable { // onReceived
const bool mustContinue = !_shuttingdown.load() && onReceive(e, msg);
if (!mustContinue)
{
self->setPromise(e);
return false; // We must not continue to receive messages.
}
return true; // Otherwise, we continue to receive messages.
},
life,
sync
);
}))();
}
template<typename N, typename S>
Connected<N, S>::Impl::~Impl()
{
}
template<typename N, typename S>
template<typename Msg, typename Proc>
void Connected<N, S>::Impl::send(Msg&& msg, SslEnabled ssl, Proc onSent)
{
using SendMessage = decltype(_sendMsg);
using ReadableMessage = typename SendMessage::ReadableMessage;
auto self = shared_from_this();
auto life = lifetimeTransfo();
auto sync = syncTransfo();
// We preventively strand the first call.
sync(life([=]() mutable {
_sendMsg(std::move(msg), ssl,
[=](const ErrorCode<N>& e, const ReadableMessage& ptrMsg) mutable { // onSent
const bool mustContinue = !_shuttingdown.load() && onSent(e, ptrMsg);
if (!mustContinue)
{
self->setPromise(e);
return false; // We must not continue to send messages.
}
return true; // Otherwise, we continue to send messages.
},
life,
sync
);
}))();
}
}} // namespace qi::sock
#endif // _QI_SOCK_CONNECTEDSTATE_HPP
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <string>
#include "LinkerEngine.h"
#include "ModuleEngine.h"
#include "ObjectCode.h"
using std::cout;
using std::cin;
using std::advance;
using std::string;
int main(int argc, char *argv[]) {
int pause;
string fileA = "arquivoTesteA.o";
string fileB = "arquivoTesteB.o";
auto linker = new LinkerEngine;
auto mod_A_teste = new ModuleEngine(fileA);
linker->AddModule(*mod_A_teste);
auto mod_B_teste = new ModuleEngine(fileB);
linker->AddModule(*mod_B_teste);
linker->Merge();
cin >> pause;
return 0;
}
<commit_msg>Main para ser a copia do preprocrssador do Pedro<commit_after>#include <stdio.h>
#include <fstream>
#include "MacroAssemblerLibraries.h"
#include <stdlib.h>
#include <string>
#include "LinkerEngine.h"
#include "ModuleEngine.h"
#include "ObjectCode.h"
using std::cout;
using std::cin;
using std::advance;
using std::string;
using std::ifstream;
ifstream VerifyFile(const char* fileName);
int main(int argc, char *argv[]) {
#ifdef _DEBUG
//seta programaticamente os argumentos em modo debug
argv[0] = "arquivoTesteA.o";
argv[1] = "arquivoTesteB.o";
argv[2] = "arquivoTeste.exe";
#else
//pega os argumentos da linha de comando em modo release
if (argc < 4) {
printf("Selecione ate 3 arquivos objetos para o ligador,juntamente com o arquivo .e ligador:\n");
printf("cmd>Montador <Arquivo de Entrada1> <Arquivo de Entrada2> <Arquivo de Saida>\n");
return 0;
}
if (argc > 3) {
printf("Selecione ate 3 arquivos objetos para o ligador,juntamente com o arquivo .e ligador:\n");
printf("cmd>Montador <Arquivo de Entrada1> <Arquivo de Entrada2><Arquivo de Entrada3> <Arquivo de Saida>\n");
return 0;
}
#endif // DEBUG
for (int i = 0; i < 2; i++) {
ifstream& fileStream = VerifyFile(argv[i]);
}
auto linker = new LinkerEngine;
for (int i = 0; i < 2; i++) {
auto File = new ModuleEngine(argv[i]);
linker->AddModule(*File);
}
linker->Merge();
getchar();
return 0;
}
/// <summary>
/// Verifica a extenso do arquivo passado e se ele foi encontrado
/// </summary>
/// <param name="fileName">nome do arquivo</param>
/// <returns>Uma stream para o arquivo o caso a verificao seja bem sucedida. Sai do programa caso contrario</returns>
ifstream VerifyFile(const char* fileName) {
string fileNameS(fileName);
size_t extensionIndex = fileNameS.find_last_of(".");
string extension = StringLibrary::ToLower(fileNameS.substr(extensionIndex + 1));
if (extension != "o") {
printf("O ligador aceita somente arquivos .o para a leitura \nExtensao do arquivo passado: .%s\n", extension.c_str());
exit(0);
}
ifstream file(fileName);
if (!file.is_open()) {
printf("O arquivo especificado %s nao existe\n", fileName);
exit(0);
}
return file;
}
/*
int pause;
string fileA = "arquivoTesteA.o";
string fileB = "arquivoTesteB.o";
auto linker = new LinkerEngine;
auto mod_A_teste = new ModuleEngine(fileA);
linker->AddModule(*mod_A_teste);
auto mod_B_teste = new ModuleEngine(fileB);
linker->AddModule(*mod_B_teste);
linker->Merge();
cin >> pause;
return 0;
}*/
<|endoftext|>
|
<commit_before>// [WriteFile Name=ConfigureSubnetworkTrace, Category=Analysis]
// [Legal]
// Copyright 2020 Esri.
// 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.
// [Legal]
#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD
#include "ConfigureSubnetworkTrace.h"
#include "CodedValueDomain.h"
#include "TaskWatcher.h"
#include "UtilityAssetGroup.h"
#include "UtilityAssetType.h"
#include "UtilityCategory.h"
#include "UtilityCategoryComparison.h"
#include "UtilityDomainNetwork.h"
#include "UtilityElement.h"
#include "UtilityElementTraceResult.h"
#include "UtilityNetwork.h"
#include "UtilityNetworkDefinition.h"
#include "UtilityNetworkSource.h"
#include "UtilityNetworkTypes.h"
#include "UtilityTerminal.h"
#include "UtilityTerminalConfiguration.h"
#include "UtilityTier.h"
#include "UtilityTraceAndCondition.h"
#include "UtilityTraceConfiguration.h"
#include "UtilityTraceOrCondition.h"
#include "UtilityTraceParameters.h"
#include "UtilityTraceResultListModel.h"
#include "UtilityTraversability.h"
#include <QQmlEngine>
using namespace Esri::ArcGISRuntime;
QString expressionToString(UtilityTraceConditionalExpression* expression);
QString comparisonOperatorToString(const UtilityAttributeComparisonOperator& comparisonOperator);
QVariant convertToDataType(const QVariant& value, const Esri::ArcGISRuntime::UtilityNetworkAttributeDataType& dataType);
ConfigureSubnetworkTrace::ConfigureSubnetworkTrace(QObject* parent /* = nullptr */):
QObject(parent)
{
m_utilityNetwork = new UtilityNetwork(m_featureLayerUrl, this);
connect(m_utilityNetwork, &UtilityNetwork::doneLoading, this, &ConfigureSubnetworkTrace::onUtilityNetworkLoaded);
connect(m_utilityNetwork, &UtilityNetwork::traceCompleted, this, &ConfigureSubnetworkTrace::onTraceCompleted);
m_utilityNetwork->load();
}
QString expressionToString(UtilityTraceConditionalExpression* expression)
{
switch (expression->traceConditionType())
{
case UtilityTraceConditionType::UtilityNetworkAttributeComparison:
{
const UtilityNetworkAttributeComparison* attributeExpression = static_cast<UtilityNetworkAttributeComparison*>(expression);
const UtilityNetworkAttribute* networkAttribute = attributeExpression->networkAttribute();
const UtilityNetworkAttribute* otherNetworkAttribute = attributeExpression->otherNetworkAttribute();
const Domain networkDomain = networkAttribute->domain();
const QString operatorAsString = comparisonOperatorToString(attributeExpression->comparisonOperator());
// check if attribute domain is a coded value domain.
if (!networkDomain.isEmpty() && (networkDomain.domainType() == DomainType::CodedValueDomain))
{
const CodedValueDomain codedValueDomain = static_cast<CodedValueDomain>(networkDomain);
const QList<CodedValue> codedValues = codedValueDomain.codedValues();
// get the coded value using the value as the index for the list of coded values
const QString codedValueName = codedValues[attributeExpression->value().toInt()].name();
return QString("`%1` %2 `%3`").arg(networkAttribute->name(), operatorAsString, codedValueName);
}
else
{
if (otherNetworkAttribute)
{
return QString("`%1` %2 `%3`").arg(networkAttribute->name(), operatorAsString, otherNetworkAttribute->name());
}
return QString("`%1` %2 `%3`").arg(networkAttribute->name(), operatorAsString, attributeExpression->value().toString());
}
}
case UtilityTraceConditionType::UtilityCategoryComparison:
{
const UtilityCategoryComparison* comparisonExpression = static_cast<UtilityCategoryComparison*>(expression);
return QString("`%1` %2").arg(comparisonExpression->category()->name(), (comparisonExpression->comparisonOperator() == UtilityCategoryComparisonOperator::Exists) ? "Exists" : "DoesNotExist");
}
case UtilityTraceConditionType::UtilityTraceAndCondition:
{
const UtilityTraceAndCondition* andExpression = static_cast<UtilityTraceAndCondition*>(expression);
return QString("(%1) AND\n (%2)").arg(expressionToString(andExpression->leftExpression()), expressionToString(andExpression->rightExpression()));
}
case UtilityTraceConditionType::UtilityTraceOrCondition:
{
const UtilityTraceOrCondition* orExpression = static_cast<UtilityTraceOrCondition*>(expression);
return QString("(%1) OR\n (%2)").arg(expressionToString(orExpression->leftExpression()), expressionToString(orExpression->rightExpression()));
}
default:
return QString("Unknown trace conditional expression");
}
}
QString comparisonOperatorToString(const UtilityAttributeComparisonOperator& comparisonOperator)
{
switch (comparisonOperator)
{
case UtilityAttributeComparisonOperator::Equal:
return QString("Equal");
case UtilityAttributeComparisonOperator::NotEqual:
return QString("NotEqual");
case UtilityAttributeComparisonOperator::GreaterThan:
return QString("GreaterThan");
case UtilityAttributeComparisonOperator::GreaterThanEqual:
return QString("GreaterThanEqual");
case UtilityAttributeComparisonOperator::LessThan:
return QString("LessThan");
case UtilityAttributeComparisonOperator::LessThanEqual:
return QString("LessThanEqual");
case UtilityAttributeComparisonOperator::IncludesTheValues:
return QString("IncludesTheValues");
case UtilityAttributeComparisonOperator::DoesNotIncludeTheValues:
return QString("DoesNotIncludeTheValues");
case UtilityAttributeComparisonOperator::IncludesAny:
return QString("IncludesAny");
case UtilityAttributeComparisonOperator::DoesNotIncludeAny:
return QString("DoesNotIncludeAny");
default:
return QString("Unknown comparison operator");
}
}
QVariant convertToDataType(const QVariant& value, const Esri::ArcGISRuntime::UtilityNetworkAttributeDataType& dataType)
{
switch (dataType)
{
case UtilityNetworkAttributeDataType::Integer:
{
return static_cast<int>(value.toDouble());
}
case UtilityNetworkAttributeDataType::Float:
{
return value.toFloat();
}
case UtilityNetworkAttributeDataType::Double:
{
return value.toDouble();
}
case UtilityNetworkAttributeDataType::Boolean:
{
return value.toBool();
}
default:
return QVariant();
}
}
void ConfigureSubnetworkTrace::codedValueOrInputText(const QString& currentText)
{
// Update the UI to show the correct value entry for the attribute.
if (m_networkDefinition)
{
const Domain domain = m_networkDefinition->networkAttribute(currentText)->domain();
if (!domain.isEmpty() && (domain.domainType() == DomainType::CodedValueDomain))
{
m_valueSelectionListModel.clear();
const CodedValueDomain codedValueDomain = static_cast<CodedValueDomain>(domain);
for (CodedValue codedValue: codedValueDomain.codedValues())
m_valueSelectionListModel.append(codedValue.name());
m_textFieldVisible = false;
}
else
{
m_textFieldVisible = true;
}
emit valueSelectionListModelChanged();
emit textFieldVisibleChanged();
}
}
void ConfigureSubnetworkTrace::addCondition(const QString& selectedAttribute, int selectedOperator, const QVariant& selectedValue)
{
// NOTE: You may also create a UtilityCategoryComparison with UtilityNetworkDefinition.Categories and UtilityCategoryComparisonOperator.
UtilityNetworkAttribute* selectedNetworkAttribute = m_networkDefinition->networkAttribute(selectedAttribute);
const QVariant convertedSelectedValue = convertToDataType(selectedValue, selectedNetworkAttribute->dataType());
if (convertedSelectedValue.isNull())
{
m_dialogText = "Unknow network attribute data type";
emit dialogTextChanged();
emit showDialog();
return;
}
const UtilityAttributeComparisonOperator selectedOperatorEnum = static_cast<UtilityAttributeComparisonOperator>(selectedOperator);
// NOTE: You may also create a UtilityNetworkAttributeComparison with another NetworkAttribute.
UtilityTraceConditionalExpression* expression = new UtilityNetworkAttributeComparison(selectedNetworkAttribute, selectedOperatorEnum, convertedSelectedValue, this);
UtilityTraceConditionalExpression* otherExpression = static_cast<UtilityTraceConditionalExpression*>(m_traceConfiguration->traversability()->barriers());
// NOTE: You may also combine expressions with UtilityTraceAndCondition
UtilityTraceConditionalExpression* combineExpressions = new UtilityTraceOrCondition(otherExpression, expression, this);
m_expressionBuilder = expressionToString(combineExpressions);
emit expressionBuilderChanged();
m_traceConfiguration->traversability()->setBarriers(combineExpressions);
}
void ConfigureSubnetworkTrace::changeIncludeBarriersState(bool includeBarriers)
{
m_traceConfiguration->setIncludeBarriers(includeBarriers);
}
void ConfigureSubnetworkTrace::changeIncludeContainersState(bool includeContainers)
{
m_traceConfiguration->setIncludeContainers(includeContainers);
}
void ConfigureSubnetworkTrace::reset()
{
// Reset the barrier condition to the initial value.
m_traceConfiguration->traversability()->setBarriers(m_initialExpression);
m_expressionBuilder.clear();
m_expressionBuilder = expressionToString(static_cast<UtilityTraceConditionalExpression*>(m_initialExpression));
emit expressionBuilderChanged();
}
void ConfigureSubnetworkTrace::trace()
{
if (!m_utilityNetwork || !m_utilityElementStartingLocation)
{
return;
}
m_busy = true;
emit busyChanged();
const QList<UtilityElement*> startingLocations {m_utilityElementStartingLocation};
// Create utility trace parameters for the starting location.
m_traceParams = new UtilityTraceParameters(UtilityTraceType::Subnetwork, startingLocations, this);
m_traceParams->setTraceConfiguration(m_traceConfiguration);
// trace the network
m_utilityNetwork->trace(m_traceParams);
}
void ConfigureSubnetworkTrace::onTraceCompleted()
{
if (m_utilityNetwork->traceResult()->isEmpty())
{
m_dialogText = "No results returned";
emit dialogTextChanged();
emit showDialog();
}
// Get the first result.
UtilityTraceResult* result = m_utilityNetwork->traceResult()->at(0);
const QList<UtilityElement*> elements = static_cast<UtilityElementTraceResult*>(result)->elements(this);
// Display the number of elements found by the trace.
m_dialogText = QString("%1 elements found.").arg(elements.length());
m_busy = false;
emit dialogTextChanged();
emit showDialog();
emit busyChanged();
}
void ConfigureSubnetworkTrace::onUtilityNetworkLoaded(const Error& e)
{
if (!e.isEmpty())
{
m_dialogText = QString("%1 - %2").arg(e.message(), e.additionalMessage());
m_busy = false;
emit dialogTextChanged();
emit showDialog();
emit busyChanged();
return;
}
m_busy = false;
emit busyChanged();
m_networkDefinition = m_utilityNetwork->definition();
// Build the choice lists for network attribute comparison.
for (UtilityNetworkAttribute* networkAttribute : m_networkDefinition->networkAttributes())
{
if (!networkAttribute->isSystemDefined())
m_attributeListModel.append(networkAttribute->name());
}
emit attributeListModelChanged();
// Create a default starting location.
const UtilityNetworkSource* networkSource = m_networkDefinition->networkSource(m_deviceTableName);
const UtilityAssetGroup* assetGroup = networkSource->assetGroup(m_assetGroupName);
UtilityAssetType* assetType = assetGroup->assetType(m_assetTypeName);
m_utilityElementStartingLocation = m_utilityNetwork->createElementWithAssetType(assetType, m_gloabId);
QList<UtilityTerminal*> terminals = m_utilityElementStartingLocation->assetType()->terminalConfiguration()->terminals();
// Set the terminal for this location. (For our case, we use the 'Load' terminal.)
auto terminal = std::find_if(terminals.begin(), terminals.end(), [](UtilityTerminal* terminal)
{
return terminal->name() == "Load";
});
m_utilityElementStartingLocation->setTerminal(static_cast<UtilityTerminal*>(*terminal));
// Get a default trace configuration from a tier to update the UI.
const UtilityDomainNetwork* domainNetwork = m_networkDefinition->domainNetwork(m_domainNetworkName);
const UtilityTier* utilityTierSource = domainNetwork->tier(m_tierName);
// Set the trace configuration.
m_traceConfiguration = utilityTierSource->traceConfiguration();
m_initialExpression = m_traceConfiguration->traversability()->barriers();
if (m_initialExpression)
{
m_expressionBuilder = expressionToString(static_cast<UtilityTraceConditionalExpression*>(m_initialExpression));
emit expressionBuilderChanged();
}
// Set the traversability scope.
utilityTierSource->traceConfiguration()->traversability()->setScope(UtilityTraversabilityScope::Junctions);
}
ConfigureSubnetworkTrace::~ConfigureSubnetworkTrace() = default;
void ConfigureSubnetworkTrace::init()
{
qmlRegisterType<ConfigureSubnetworkTrace>("Esri.Samples", 1, 0, "ConfigureSubnetworkTraceSample");
}
<commit_msg>adding algorithm library.<commit_after>// [WriteFile Name=ConfigureSubnetworkTrace, Category=Analysis]
// [Legal]
// Copyright 2020 Esri.
// 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.
// [Legal]
#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD
#include "ConfigureSubnetworkTrace.h"
#include "CodedValueDomain.h"
#include "TaskWatcher.h"
#include "UtilityAssetGroup.h"
#include "UtilityAssetType.h"
#include "UtilityCategory.h"
#include "UtilityCategoryComparison.h"
#include "UtilityDomainNetwork.h"
#include "UtilityElement.h"
#include "UtilityElementTraceResult.h"
#include "UtilityNetwork.h"
#include "UtilityNetworkDefinition.h"
#include "UtilityNetworkSource.h"
#include "UtilityNetworkTypes.h"
#include "UtilityTerminal.h"
#include "UtilityTerminalConfiguration.h"
#include "UtilityTier.h"
#include "UtilityTraceAndCondition.h"
#include "UtilityTraceConfiguration.h"
#include "UtilityTraceOrCondition.h"
#include "UtilityTraceParameters.h"
#include "UtilityTraceResultListModel.h"
#include "UtilityTraversability.h"
#include <QQmlEngine>
#include <algorithm>
using namespace Esri::ArcGISRuntime;
QString expressionToString(UtilityTraceConditionalExpression* expression);
QString comparisonOperatorToString(const UtilityAttributeComparisonOperator& comparisonOperator);
QVariant convertToDataType(const QVariant& value, const Esri::ArcGISRuntime::UtilityNetworkAttributeDataType& dataType);
ConfigureSubnetworkTrace::ConfigureSubnetworkTrace(QObject* parent /* = nullptr */):
QObject(parent)
{
m_utilityNetwork = new UtilityNetwork(m_featureLayerUrl, this);
connect(m_utilityNetwork, &UtilityNetwork::doneLoading, this, &ConfigureSubnetworkTrace::onUtilityNetworkLoaded);
connect(m_utilityNetwork, &UtilityNetwork::traceCompleted, this, &ConfigureSubnetworkTrace::onTraceCompleted);
m_utilityNetwork->load();
}
QString expressionToString(UtilityTraceConditionalExpression* expression)
{
switch (expression->traceConditionType())
{
case UtilityTraceConditionType::UtilityNetworkAttributeComparison:
{
const UtilityNetworkAttributeComparison* attributeExpression = static_cast<UtilityNetworkAttributeComparison*>(expression);
const UtilityNetworkAttribute* networkAttribute = attributeExpression->networkAttribute();
const UtilityNetworkAttribute* otherNetworkAttribute = attributeExpression->otherNetworkAttribute();
const Domain networkDomain = networkAttribute->domain();
const QString operatorAsString = comparisonOperatorToString(attributeExpression->comparisonOperator());
// check if attribute domain is a coded value domain.
if (!networkDomain.isEmpty() && (networkDomain.domainType() == DomainType::CodedValueDomain))
{
const CodedValueDomain codedValueDomain = static_cast<CodedValueDomain>(networkDomain);
const QList<CodedValue> codedValues = codedValueDomain.codedValues();
// get the coded value using the value as the index for the list of coded values
const QString codedValueName = codedValues[attributeExpression->value().toInt()].name();
return QString("`%1` %2 `%3`").arg(networkAttribute->name(), operatorAsString, codedValueName);
}
else
{
if (otherNetworkAttribute)
{
return QString("`%1` %2 `%3`").arg(networkAttribute->name(), operatorAsString, otherNetworkAttribute->name());
}
return QString("`%1` %2 `%3`").arg(networkAttribute->name(), operatorAsString, attributeExpression->value().toString());
}
}
case UtilityTraceConditionType::UtilityCategoryComparison:
{
const UtilityCategoryComparison* comparisonExpression = static_cast<UtilityCategoryComparison*>(expression);
return QString("`%1` %2").arg(comparisonExpression->category()->name(), (comparisonExpression->comparisonOperator() == UtilityCategoryComparisonOperator::Exists) ? "Exists" : "DoesNotExist");
}
case UtilityTraceConditionType::UtilityTraceAndCondition:
{
const UtilityTraceAndCondition* andExpression = static_cast<UtilityTraceAndCondition*>(expression);
return QString("(%1) AND\n (%2)").arg(expressionToString(andExpression->leftExpression()), expressionToString(andExpression->rightExpression()));
}
case UtilityTraceConditionType::UtilityTraceOrCondition:
{
const UtilityTraceOrCondition* orExpression = static_cast<UtilityTraceOrCondition*>(expression);
return QString("(%1) OR\n (%2)").arg(expressionToString(orExpression->leftExpression()), expressionToString(orExpression->rightExpression()));
}
default:
return QString("Unknown trace conditional expression");
}
}
QString comparisonOperatorToString(const UtilityAttributeComparisonOperator& comparisonOperator)
{
switch (comparisonOperator)
{
case UtilityAttributeComparisonOperator::Equal:
return QString("Equal");
case UtilityAttributeComparisonOperator::NotEqual:
return QString("NotEqual");
case UtilityAttributeComparisonOperator::GreaterThan:
return QString("GreaterThan");
case UtilityAttributeComparisonOperator::GreaterThanEqual:
return QString("GreaterThanEqual");
case UtilityAttributeComparisonOperator::LessThan:
return QString("LessThan");
case UtilityAttributeComparisonOperator::LessThanEqual:
return QString("LessThanEqual");
case UtilityAttributeComparisonOperator::IncludesTheValues:
return QString("IncludesTheValues");
case UtilityAttributeComparisonOperator::DoesNotIncludeTheValues:
return QString("DoesNotIncludeTheValues");
case UtilityAttributeComparisonOperator::IncludesAny:
return QString("IncludesAny");
case UtilityAttributeComparisonOperator::DoesNotIncludeAny:
return QString("DoesNotIncludeAny");
default:
return QString("Unknown comparison operator");
}
}
QVariant convertToDataType(const QVariant& value, const Esri::ArcGISRuntime::UtilityNetworkAttributeDataType& dataType)
{
switch (dataType)
{
case UtilityNetworkAttributeDataType::Integer:
{
return static_cast<int>(value.toDouble());
}
case UtilityNetworkAttributeDataType::Float:
{
return value.toFloat();
}
case UtilityNetworkAttributeDataType::Double:
{
return value.toDouble();
}
case UtilityNetworkAttributeDataType::Boolean:
{
return value.toBool();
}
default:
return QVariant();
}
}
void ConfigureSubnetworkTrace::codedValueOrInputText(const QString& currentText)
{
// Update the UI to show the correct value entry for the attribute.
if (m_networkDefinition)
{
const Domain domain = m_networkDefinition->networkAttribute(currentText)->domain();
if (!domain.isEmpty() && (domain.domainType() == DomainType::CodedValueDomain))
{
m_valueSelectionListModel.clear();
const CodedValueDomain codedValueDomain = static_cast<CodedValueDomain>(domain);
for (CodedValue codedValue: codedValueDomain.codedValues())
m_valueSelectionListModel.append(codedValue.name());
m_textFieldVisible = false;
}
else
{
m_textFieldVisible = true;
}
emit valueSelectionListModelChanged();
emit textFieldVisibleChanged();
}
}
void ConfigureSubnetworkTrace::addCondition(const QString& selectedAttribute, int selectedOperator, const QVariant& selectedValue)
{
// NOTE: You may also create a UtilityCategoryComparison with UtilityNetworkDefinition.Categories and UtilityCategoryComparisonOperator.
UtilityNetworkAttribute* selectedNetworkAttribute = m_networkDefinition->networkAttribute(selectedAttribute);
const QVariant convertedSelectedValue = convertToDataType(selectedValue, selectedNetworkAttribute->dataType());
if (convertedSelectedValue.isNull())
{
m_dialogText = "Unknow network attribute data type";
emit dialogTextChanged();
emit showDialog();
return;
}
const UtilityAttributeComparisonOperator selectedOperatorEnum = static_cast<UtilityAttributeComparisonOperator>(selectedOperator);
// NOTE: You may also create a UtilityNetworkAttributeComparison with another NetworkAttribute.
UtilityTraceConditionalExpression* expression = new UtilityNetworkAttributeComparison(selectedNetworkAttribute, selectedOperatorEnum, convertedSelectedValue, this);
UtilityTraceConditionalExpression* otherExpression = static_cast<UtilityTraceConditionalExpression*>(m_traceConfiguration->traversability()->barriers());
// NOTE: You may also combine expressions with UtilityTraceAndCondition
UtilityTraceConditionalExpression* combineExpressions = new UtilityTraceOrCondition(otherExpression, expression, this);
m_expressionBuilder = expressionToString(combineExpressions);
emit expressionBuilderChanged();
m_traceConfiguration->traversability()->setBarriers(combineExpressions);
}
void ConfigureSubnetworkTrace::changeIncludeBarriersState(bool includeBarriers)
{
m_traceConfiguration->setIncludeBarriers(includeBarriers);
}
void ConfigureSubnetworkTrace::changeIncludeContainersState(bool includeContainers)
{
m_traceConfiguration->setIncludeContainers(includeContainers);
}
void ConfigureSubnetworkTrace::reset()
{
// Reset the barrier condition to the initial value.
m_traceConfiguration->traversability()->setBarriers(m_initialExpression);
m_expressionBuilder.clear();
m_expressionBuilder = expressionToString(static_cast<UtilityTraceConditionalExpression*>(m_initialExpression));
emit expressionBuilderChanged();
}
void ConfigureSubnetworkTrace::trace()
{
if (!m_utilityNetwork || !m_utilityElementStartingLocation)
{
return;
}
m_busy = true;
emit busyChanged();
const QList<UtilityElement*> startingLocations {m_utilityElementStartingLocation};
// Create utility trace parameters for the starting location.
m_traceParams = new UtilityTraceParameters(UtilityTraceType::Subnetwork, startingLocations, this);
m_traceParams->setTraceConfiguration(m_traceConfiguration);
// trace the network
m_utilityNetwork->trace(m_traceParams);
}
void ConfigureSubnetworkTrace::onTraceCompleted()
{
if (m_utilityNetwork->traceResult()->isEmpty())
{
m_dialogText = "No results returned";
emit dialogTextChanged();
emit showDialog();
}
// Get the first result.
UtilityTraceResult* result = m_utilityNetwork->traceResult()->at(0);
const QList<UtilityElement*> elements = static_cast<UtilityElementTraceResult*>(result)->elements(this);
// Display the number of elements found by the trace.
m_dialogText = QString("%1 elements found.").arg(elements.length());
m_busy = false;
emit dialogTextChanged();
emit showDialog();
emit busyChanged();
}
void ConfigureSubnetworkTrace::onUtilityNetworkLoaded(const Error& e)
{
if (!e.isEmpty())
{
m_dialogText = QString("%1 - %2").arg(e.message(), e.additionalMessage());
m_busy = false;
emit dialogTextChanged();
emit showDialog();
emit busyChanged();
return;
}
m_busy = false;
emit busyChanged();
m_networkDefinition = m_utilityNetwork->definition();
// Build the choice lists for network attribute comparison.
for (UtilityNetworkAttribute* networkAttribute : m_networkDefinition->networkAttributes())
{
if (!networkAttribute->isSystemDefined())
m_attributeListModel.append(networkAttribute->name());
}
emit attributeListModelChanged();
// Create a default starting location.
const UtilityNetworkSource* networkSource = m_networkDefinition->networkSource(m_deviceTableName);
const UtilityAssetGroup* assetGroup = networkSource->assetGroup(m_assetGroupName);
UtilityAssetType* assetType = assetGroup->assetType(m_assetTypeName);
m_utilityElementStartingLocation = m_utilityNetwork->createElementWithAssetType(assetType, m_gloabId);
QList<UtilityTerminal*> terminals = m_utilityElementStartingLocation->assetType()->terminalConfiguration()->terminals();
// Set the terminal for this location. (For our case, we use the 'Load' terminal.)
auto terminal = std::find_if(terminals.begin(), terminals.end(), [](UtilityTerminal* terminal)
{
return terminal->name() == "Load";
});
m_utilityElementStartingLocation->setTerminal(static_cast<UtilityTerminal*>(*terminal));
// Get a default trace configuration from a tier to update the UI.
const UtilityDomainNetwork* domainNetwork = m_networkDefinition->domainNetwork(m_domainNetworkName);
const UtilityTier* utilityTierSource = domainNetwork->tier(m_tierName);
// Set the trace configuration.
m_traceConfiguration = utilityTierSource->traceConfiguration();
m_initialExpression = m_traceConfiguration->traversability()->barriers();
if (m_initialExpression)
{
m_expressionBuilder = expressionToString(static_cast<UtilityTraceConditionalExpression*>(m_initialExpression));
emit expressionBuilderChanged();
}
// Set the traversability scope.
utilityTierSource->traceConfiguration()->traversability()->setScope(UtilityTraversabilityScope::Junctions);
}
ConfigureSubnetworkTrace::~ConfigureSubnetworkTrace() = default;
void ConfigureSubnetworkTrace::init()
{
qmlRegisterType<ConfigureSubnetworkTrace>("Esri.Samples", 1, 0, "ConfigureSubnetworkTraceSample");
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 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 "quic/test_tools/quic_test_backend.h"
#include <cstring>
#include <memory>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "quic/core/quic_buffer_allocator.h"
#include "quic/core/quic_simple_buffer_allocator.h"
#include "quic/core/web_transport_interface.h"
#include "quic/platform/api/quic_mem_slice.h"
#include "quic/tools/web_transport_test_visitors.h"
namespace quic {
namespace test {
QuicSimpleServerBackend::WebTransportResponse
QuicTestBackend::ProcessWebTransportRequest(
const spdy::Http2HeaderBlock& request_headers,
WebTransportSession* session) {
if (!SupportsWebTransport()) {
return QuicSimpleServerBackend::ProcessWebTransportRequest(request_headers,
session);
}
auto path_it = request_headers.find(":path");
if (path_it == request_headers.end()) {
WebTransportResponse response;
response.response_headers[":status"] = "400";
return response;
}
absl::string_view path = path_it->second;
// Match any "/echo.*" pass, e.g. "/echo_foobar"
if (absl::StartsWith(path, "/echo")) {
WebTransportResponse response;
response.response_headers[":status"] = "200";
// Add response headers if the paramer has "set-header=XXX:YYY" query.
GURL url = GURL(absl::StrCat("https://localhost", path));
const std::vector<std::string>& params = absl::StrSplit(url.query(), '&');
for (const auto& param : params) {
absl::string_view param_view = param;
if (absl::ConsumePrefix(¶m_view, "set-header=")) {
const std::vector<std::string_view> header_value =
absl::StrSplit(param_view, ':');
if (header_value.size() == 2 &&
!absl::StartsWith(header_value[0], ":")) {
response.response_headers[header_value[0]] = header_value[1];
}
}
}
response.visitor =
std::make_unique<EchoWebTransportSessionVisitor>(session);
return response;
}
WebTransportResponse response;
response.response_headers[":status"] = "404";
return response;
}
} // namespace test
} // namespace quic
<commit_msg>Disallow std::string_view in QUIC<commit_after>// Copyright (c) 2021 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 "quic/test_tools/quic_test_backend.h"
#include <cstring>
#include <memory>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "quic/core/quic_buffer_allocator.h"
#include "quic/core/quic_simple_buffer_allocator.h"
#include "quic/core/web_transport_interface.h"
#include "quic/platform/api/quic_mem_slice.h"
#include "quic/tools/web_transport_test_visitors.h"
namespace quic {
namespace test {
QuicSimpleServerBackend::WebTransportResponse
QuicTestBackend::ProcessWebTransportRequest(
const spdy::Http2HeaderBlock& request_headers,
WebTransportSession* session) {
if (!SupportsWebTransport()) {
return QuicSimpleServerBackend::ProcessWebTransportRequest(request_headers,
session);
}
auto path_it = request_headers.find(":path");
if (path_it == request_headers.end()) {
WebTransportResponse response;
response.response_headers[":status"] = "400";
return response;
}
absl::string_view path = path_it->second;
// Match any "/echo.*" pass, e.g. "/echo_foobar"
if (absl::StartsWith(path, "/echo")) {
WebTransportResponse response;
response.response_headers[":status"] = "200";
// Add response headers if the paramer has "set-header=XXX:YYY" query.
GURL url = GURL(absl::StrCat("https://localhost", path));
const std::vector<std::string>& params = absl::StrSplit(url.query(), '&');
for (const auto& param : params) {
absl::string_view param_view = param;
if (absl::ConsumePrefix(¶m_view, "set-header=")) {
const std::vector<absl::string_view> header_value =
absl::StrSplit(param_view, ':');
if (header_value.size() == 2 &&
!absl::StartsWith(header_value[0], ":")) {
response.response_headers[header_value[0]] = header_value[1];
}
}
}
response.visitor =
std::make_unique<EchoWebTransportSessionVisitor>(session);
return response;
}
WebTransportResponse response;
response.response_headers[":status"] = "404";
return response;
}
} // namespace test
} // namespace quic
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: global.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: vg $ $Date: 2007-09-20 15:03:42 $
*
* 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 _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include <stdlib.h>
#include <stdio.h>
#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif
#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif
#ifndef _CODEMAKER_GLOBAL_HXX_
#include <codemaker/global.hxx>
#endif
#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif
using namespace ::rtl;
using namespace ::osl;
OString createFileNameFromType( const OString& destination,
const OString typeName,
const OString postfix,
sal_Bool bLowerCase,
const OString prefix )
{
OString type(typeName);
if (bLowerCase)
{
type = typeName.toAsciiLowerCase();
}
sal_uInt32 length = destination.getLength();
sal_Bool withPoint = sal_False;
if (length == 0)
{
length++;
withPoint = sal_True;
}
length += prefix.getLength() + type.getLength() + postfix.getLength();
sal_Bool withSeperator = sal_False;
if (destination.getStr()[destination.getLength()] != '\\' &&
destination.getStr()[destination.getLength()] != '/' &&
type.getStr()[0] != '\\' &&
type.getStr()[0] != '/')
{
length++;
withSeperator = sal_True;
}
OStringBuffer nameBuffer(length);
if (withPoint)
nameBuffer.append('.');
else
nameBuffer.append(destination.getStr(), destination.getLength());
if (withSeperator)
nameBuffer.append("/", 1);
OString tmpStr(type);
if (prefix.getLength() > 0)
{
tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
}
nameBuffer.append(tmpStr.getStr(), tmpStr.getLength());
nameBuffer.append(postfix.getStr(), postfix.getLength());
OString fileName(nameBuffer);
sal_Char token;
#ifdef SAL_UNX
fileName = fileName.replace('\\', '/');
token = '/';
#else
fileName = fileName.replace('/', '\\');
token = '\\';
#endif
nameBuffer = OStringBuffer(length);
sal_Int32 nIndex = 0;
do
{
nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());
if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
{
nameBuffer.append(token);
continue;
}
#if defined(SAL_UNX) || defined(SAL_OS2)
if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
{
if ( errno == ENOENT )
return OString();
}
nameBuffer.append(token);
}
while ( nIndex >= 0 );
return fileName;
}
sal_Bool fileExists(const OString& fileName)
{
FILE *f= fopen(fileName.getStr(), "r");
if (f != NULL)
{
fclose(f);
return sal_True;
}
return sal_False;
}
sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
FILE *target = fopen(targetFileName.getStr(), "r");
FILE *tmp = fopen(tmpFileName.getStr(), "r");
sal_Bool ret = sal_False;
if (target != NULL && tmp != NULL)
{
sal_Bool bFindChanges = sal_False;
sal_Char buffer1[1024+1];
sal_Char buffer2[1024+1];
sal_Int32 n1 = 0;
sal_Int32 n2 = 0;
while ( !bFindChanges && !feof(target) && !feof(tmp))
{
n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);
if ( n1 != n2 )
{
bFindChanges = sal_True;
}
else
{
if ( rtl_compareMemory(buffer1, buffer2, n2) != 0 )
bFindChanges = sal_True;
}
}
fclose(target);
fclose(tmp);
if ( bFindChanges )
{
if ( !unlink(targetFileName.getStr()) )
if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
ret = sal_True;
}
else
{
if ( !unlink(tmpFileName.getStr()) )
ret = sal_True;
}
}
return ret;
}
const OString inGlobalSet(const OUString & rValue)
{
OString sValue( OUStringToOString(rValue, RTL_TEXTENCODING_UTF8) );
static StringSet aGlobalMap;
StringSet::iterator iter = aGlobalMap.find( sValue );
if( iter != aGlobalMap.end() )
return *iter;
return *(aGlobalMap.insert( sValue ).first);
}
static sal_Bool isFileUrl(const OString& fileName)
{
if (fileName.indexOf("file://") == 0 )
return sal_True;
return sal_False;
}
OUString convertToFileUrl(const OString& fileName)
{
if ( isFileUrl(fileName) )
{
return OStringToOUString(fileName, osl_getThreadTextEncoding());
}
OUString uUrlFileName;
OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
{
OUString uWorkingDir;
if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None) {
OSL_ASSERT(false);
}
if (FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
} else
{
if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
}
return uUrlFileName;
}
//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
{
}
FileStream::FileStream(const OString& name, FileAccessMode mode)
: m_pFile(NULL)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
FileStream::~FileStream()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
}
}
sal_Bool FileStream::isValid()
{
if ( m_pFile )
return sal_True;
return sal_False;
}
void FileStream::open(const OString& name, FileAccessMode mode)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
void FileStream::close()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
m_pFile = NULL;
m_name = OString();
}
}
sal_Int32 FileStream::getSize()
{
sal_Int32 pos = 0;
sal_Int32 size = 0;
if ( isValid() )
{
fflush(m_pFile);
pos = ftell(m_pFile);
if (!fseek(m_pFile, 0, SEEK_END))
size = ftell(m_pFile);
fseek(m_pFile, pos, SEEK_SET);
}
return size;
}
const sal_Char* FileStream::checkAccessMode(FileAccessMode mode)
{
switch( mode )
{
case FAM_READ:
return "r";
case FAM_WRITE:
return "w";
case FAM_APPEND:
return "a";
case FAM_READWRITE_EXIST:
return "r+";
case FAM_READWRITE:
return "w+";
case FAM_READAPPEND:
return "a+";
}
return "w+";
}
<commit_msg>INTEGRATION: CWS changefileheader (1.13.12); FILE MERGED 2008/04/01 15:22:57 thb 1.13.12.3: #i85898# Stripping all external header guards 2008/04/01 12:32:32 thb 1.13.12.2: #i85898# Stripping all external header guards 2008/03/31 07:25:06 rt 1.13.12.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: global.cxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <osl/process.h>
#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif
#include <rtl/ustring.hxx>
#include <osl/thread.h>
#include <osl/file.hxx>
#include <stdlib.h>
#include <stdio.h>
#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif
#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif
#include <codemaker/global.hxx>
#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif
using namespace ::rtl;
using namespace ::osl;
OString createFileNameFromType( const OString& destination,
const OString typeName,
const OString postfix,
sal_Bool bLowerCase,
const OString prefix )
{
OString type(typeName);
if (bLowerCase)
{
type = typeName.toAsciiLowerCase();
}
sal_uInt32 length = destination.getLength();
sal_Bool withPoint = sal_False;
if (length == 0)
{
length++;
withPoint = sal_True;
}
length += prefix.getLength() + type.getLength() + postfix.getLength();
sal_Bool withSeperator = sal_False;
if (destination.getStr()[destination.getLength()] != '\\' &&
destination.getStr()[destination.getLength()] != '/' &&
type.getStr()[0] != '\\' &&
type.getStr()[0] != '/')
{
length++;
withSeperator = sal_True;
}
OStringBuffer nameBuffer(length);
if (withPoint)
nameBuffer.append('.');
else
nameBuffer.append(destination.getStr(), destination.getLength());
if (withSeperator)
nameBuffer.append("/", 1);
OString tmpStr(type);
if (prefix.getLength() > 0)
{
tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
}
nameBuffer.append(tmpStr.getStr(), tmpStr.getLength());
nameBuffer.append(postfix.getStr(), postfix.getLength());
OString fileName(nameBuffer);
sal_Char token;
#ifdef SAL_UNX
fileName = fileName.replace('\\', '/');
token = '/';
#else
fileName = fileName.replace('/', '\\');
token = '\\';
#endif
nameBuffer = OStringBuffer(length);
sal_Int32 nIndex = 0;
do
{
nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());
if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
{
nameBuffer.append(token);
continue;
}
#if defined(SAL_UNX) || defined(SAL_OS2)
if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
{
if ( errno == ENOENT )
return OString();
}
nameBuffer.append(token);
}
while ( nIndex >= 0 );
return fileName;
}
sal_Bool fileExists(const OString& fileName)
{
FILE *f= fopen(fileName.getStr(), "r");
if (f != NULL)
{
fclose(f);
return sal_True;
}
return sal_False;
}
sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
FILE *target = fopen(targetFileName.getStr(), "r");
FILE *tmp = fopen(tmpFileName.getStr(), "r");
sal_Bool ret = sal_False;
if (target != NULL && tmp != NULL)
{
sal_Bool bFindChanges = sal_False;
sal_Char buffer1[1024+1];
sal_Char buffer2[1024+1];
sal_Int32 n1 = 0;
sal_Int32 n2 = 0;
while ( !bFindChanges && !feof(target) && !feof(tmp))
{
n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);
if ( n1 != n2 )
{
bFindChanges = sal_True;
}
else
{
if ( rtl_compareMemory(buffer1, buffer2, n2) != 0 )
bFindChanges = sal_True;
}
}
fclose(target);
fclose(tmp);
if ( bFindChanges )
{
if ( !unlink(targetFileName.getStr()) )
if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
ret = sal_True;
}
else
{
if ( !unlink(tmpFileName.getStr()) )
ret = sal_True;
}
}
return ret;
}
const OString inGlobalSet(const OUString & rValue)
{
OString sValue( OUStringToOString(rValue, RTL_TEXTENCODING_UTF8) );
static StringSet aGlobalMap;
StringSet::iterator iter = aGlobalMap.find( sValue );
if( iter != aGlobalMap.end() )
return *iter;
return *(aGlobalMap.insert( sValue ).first);
}
static sal_Bool isFileUrl(const OString& fileName)
{
if (fileName.indexOf("file://") == 0 )
return sal_True;
return sal_False;
}
OUString convertToFileUrl(const OString& fileName)
{
if ( isFileUrl(fileName) )
{
return OStringToOUString(fileName, osl_getThreadTextEncoding());
}
OUString uUrlFileName;
OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
{
OUString uWorkingDir;
if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None) {
OSL_ASSERT(false);
}
if (FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
} else
{
if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
}
return uUrlFileName;
}
//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
{
}
FileStream::FileStream(const OString& name, FileAccessMode mode)
: m_pFile(NULL)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
FileStream::~FileStream()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
}
}
sal_Bool FileStream::isValid()
{
if ( m_pFile )
return sal_True;
return sal_False;
}
void FileStream::open(const OString& name, FileAccessMode mode)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
void FileStream::close()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
m_pFile = NULL;
m_name = OString();
}
}
sal_Int32 FileStream::getSize()
{
sal_Int32 pos = 0;
sal_Int32 size = 0;
if ( isValid() )
{
fflush(m_pFile);
pos = ftell(m_pFile);
if (!fseek(m_pFile, 0, SEEK_END))
size = ftell(m_pFile);
fseek(m_pFile, pos, SEEK_SET);
}
return size;
}
const sal_Char* FileStream::checkAccessMode(FileAccessMode mode)
{
switch( mode )
{
case FAM_READ:
return "r";
case FAM_WRITE:
return "w";
case FAM_APPEND:
return "a";
case FAM_READWRITE_EXIST:
return "r+";
case FAM_READWRITE:
return "w+";
case FAM_READAPPEND:
return "a+";
}
return "w+";
}
<|endoftext|>
|
<commit_before>#include "Global.h"
#include <vector>
#include <iostream>
#include <thread>
#include <unordered_map>
#include <cmath>
#include <chrono>
#include "Controller.h"
#include "Job.h"
#include "JobHandler.h"
#include "Sensor.h"
#include "Controller/UDPClientController.h"
#include "Controller/FakeMotorController.h"
#include "Controller/MotorController.h"
#include "JobHandler/ManualInputsHandler.h"
#include "JobHandler/ForwardHandler.h"
#include "JobHandler/R2Server.h"
#include "JobHandler/SafetyHandler.h"
#include "Sensor/UDPServerSensor.h"
#include "Sensor/UltrasoundSensor.h"
/** Initializes sensors */
smap<ptr<Sensor>> initializeSensors(smap<string>& args) {
printf("Initialize sensors\n");
smap<ptr<Sensor>> sensors;
if (args.find("udp-server-ip") != args.end() && args.find("udp-server-port") != args.end()) {
sensors["UDP SERVER"] = std::make_shared<UDPServerSensor>(args["udp-server-ip"], atoi(args["udp-server-port"].c_str()));
}
else {
sensors["UDP SERVER"] = std::make_shared<UDPServerSensor>("0.0.0.0", 9000);
}
if (args.find("ultrasound-com-port") != args.end()) {
sensors["ULTRASOUND"] = std::make_shared<UltrasoundSensor>(args["ultrasound-com-port"], B9600);
}
else {
std::cout << "No ultrasound port specified." << std::endl;
}
return sensors;
}
/** Initializes controllers */
smap<ptr<Controller>> initializeControllers(smap<string>& args) {
printf("Initialize controllers\n");
smap<ptr<Controller>> controllers;
if (args.find("udp-nuc-ip") != args.end() && args.find("udp-nuc-port") != args.end()) {
controllers["UDP NUC"] = std::make_shared<UDPClientController>(args["udp-nuc-ip"], atoi(args["udp-nuc-port"].c_str()));
}
else {
std::cout << "No UDP NUC ip or port specified." << std::endl;
}
if (args.find("motor-com-port") != args.end()) {
controllers["MOTOR"] = std::make_shared<MotorController>(args["motor-com-port"], B9600);
}
else if (args.find("use-fake-motor") != args.end()) {
controllers["MOTOR"] = std::make_shared<FakeMotorController>();
}
else {
std::cout << "No motor port specified." << std::endl;
}
return controllers;
}
/** Initialize a list of jobs */
deque<Job> initializeJobs(smap<string>& args) {
printf("Initialize jobs\n");
deque<Job> jobs;
jobs.push_back(Job("manual-inputs"));
return jobs;
}
/** Initialize background jobs */
deque<JobHandler> initializeBackgroundJobs(smap<string>& args, smap<ptr<Sensor>>& sensors, smap<ptr<Controller>>& controllers) {
printf("Initializing background jobs\n");
deque<JobHandler> jobs;
if (args.find("disable-safety") != args.end()) {
printf("WARNING: DISABLING MOTOR SAFETY\n");
}
else {
jobs.push_back(SafetyHandler());
}
smap<ptr<Controller>> routes;
if (controllers.find("UDP NUC") != controllers.end()) {
routes["PICAMERA"] = controllers["UDP NUC"];
}
jobs.push_back(ForwardHandler(routes));
return jobs;
}
int main(int argc, char *argv[]) {
smap<string> args = parseArguments(argc, argv);
/** Initialization */
smap<ptr<Sensor>> sensors = initializeSensors(args);
smap<ptr<Controller>> controllers = initializeControllers(args);
deque<Job> jobQueue = initializeJobs(args);
ptr<JobHandler> currentJob;
deque<JobHandler> bgJobs = initializeBackgroundJobs(args, sensors, controllers);
//TODO: method arg should be sql command stored in a char
/** Main execution loop */
while (1) {
// Collect data from sensors
printf("Collecting data from sensors\n");
SensorData data;
for (auto itr : sensors) {
ptr<Sensor> sensor = itr.second;
sensor->fillData(data);
}
// Get the next job in the queue
if (!currentJob) {
if (jobQueue.size() > 0) {
Job nextJob = jobQueue.front();
jobQueue.pop_front();
currentJob = JobHandler::GetJobHandler(nextJob.getHandler());
}
}
// Run the current job
printf("Executing the current job\n");
ControllerData outputs;
if (currentJob) {
currentJob->execute(jobQueue, data, outputs);
}
// Run background jobs
printf("Executing background jobs\n");
for (auto itr : bgJobs) {
itr.execute(jobQueue, data, outputs);
}
// Send output data to controllers
printf("Sending outputs to controllers\n");
for (auto itr : controllers) {
ptr<Controller> controller = itr.second;
std::cout << controller->getName() << std::endl;
controller->sendData(outputs);
}
// Sleep
Sleep(20);
}
}
<commit_msg>Make outputs more clear<commit_after>#include "Global.h"
#include <vector>
#include <iostream>
#include <thread>
#include <unordered_map>
#include <cmath>
#include <chrono>
#include "Controller.h"
#include "Job.h"
#include "JobHandler.h"
#include "Sensor.h"
#include "Controller/UDPClientController.h"
#include "Controller/FakeMotorController.h"
#include "Controller/MotorController.h"
#include "JobHandler/ManualInputsHandler.h"
#include "JobHandler/ForwardHandler.h"
#include "JobHandler/R2Server.h"
#include "JobHandler/SafetyHandler.h"
#include "Sensor/UDPServerSensor.h"
#include "Sensor/UltrasoundSensor.h"
/** Initializes sensors */
smap<ptr<Sensor>> initializeSensors(smap<string>& args) {
printf("*** Initialize sensors\n");
smap<ptr<Sensor>> sensors;
if (args.find("udp-server-ip") != args.end() && args.find("udp-server-port") != args.end()) {
sensors["UDP SERVER"] = std::make_shared<UDPServerSensor>(args["udp-server-ip"], atoi(args["udp-server-port"].c_str()));
}
else {
sensors["UDP SERVER"] = std::make_shared<UDPServerSensor>("0.0.0.0", 9000);
}
if (args.find("ultrasound-com-port") != args.end()) {
sensors["ULTRASOUND"] = std::make_shared<UltrasoundSensor>(args["ultrasound-com-port"], B9600);
}
else {
std::cout << "No ultrasound port specified." << std::endl;
}
return sensors;
}
/** Initializes controllers */
smap<ptr<Controller>> initializeControllers(smap<string>& args) {
printf("*** Initialize controllers\n");
smap<ptr<Controller>> controllers;
if (args.find("udp-nuc-ip") != args.end() && args.find("udp-nuc-port") != args.end()) {
controllers["UDP NUC"] = std::make_shared<UDPClientController>(args["udp-nuc-ip"], atoi(args["udp-nuc-port"].c_str()));
}
else {
std::cout << "No UDP NUC ip or port specified." << std::endl;
}
if (args.find("motor-com-port") != args.end()) {
controllers["MOTOR"] = std::make_shared<MotorController>(args["motor-com-port"], B9600);
}
else if (args.find("use-fake-motor") != args.end()) {
controllers["MOTOR"] = std::make_shared<FakeMotorController>();
}
else {
std::cout << "No motor port specified." << std::endl;
}
return controllers;
}
/** Initialize a list of jobs */
deque<Job> initializeJobs(smap<string>& args) {
printf("*** Initialize jobs\n");
deque<Job> jobs;
jobs.push_back(Job("manual-inputs"));
return jobs;
}
/** Initialize background jobs */
deque<JobHandler> initializeBackgroundJobs(smap<string>& args, smap<ptr<Sensor>>& sensors, smap<ptr<Controller>>& controllers) {
printf("*** Initializing background jobs\n");
deque<JobHandler> jobs;
if (args.find("disable-safety") != args.end()) {
printf("WARNING: DISABLING MOTOR SAFETY\n");
}
else {
jobs.push_back(SafetyHandler());
}
smap<ptr<Controller>> routes;
if (controllers.find("UDP NUC") != controllers.end()) {
routes["PICAMERA"] = controllers["UDP NUC"];
}
jobs.push_back(ForwardHandler(routes));
return jobs;
}
int main(int argc, char *argv[]) {
smap<string> args = parseArguments(argc, argv);
/** Initialization */
smap<ptr<Sensor>> sensors = initializeSensors(args);
smap<ptr<Controller>> controllers = initializeControllers(args);
deque<Job> jobQueue = initializeJobs(args);
ptr<JobHandler> currentJob;
deque<JobHandler> bgJobs = initializeBackgroundJobs(args, sensors, controllers);
//TODO: method arg should be sql command stored in a char
/** Main execution loop */
while (1) {
// Collect data from sensors
printf("** Collecting data from sensors\n");
SensorData data;
for (auto itr : sensors) {
ptr<Sensor> sensor = itr.second;
sensor->fillData(data);
}
// Get the next job in the queue
if (!currentJob) {
if (jobQueue.size() > 0) {
Job nextJob = jobQueue.front();
jobQueue.pop_front();
currentJob = JobHandler::GetJobHandler(nextJob.getHandler());
}
}
// Run the current job
ControllerData outputs;
if (currentJob) {
printf("** Executing the current job\n");
currentJob->execute(jobQueue, data, outputs);
}
else {
printf("** No current job to execute\n");
}
// Run background jobs
printf("** Executing background jobs\n");
for (auto itr : bgJobs) {
itr.execute(jobQueue, data, outputs);
}
// Send output data to controllers
printf("** Sending outputs to controllers\n");
for (auto itr : controllers) {
ptr<Controller> controller = itr.second;
std::cout << controller->getName() << std::endl;
controller->sendData(outputs);
}
// Sleep
Sleep(20);
}
}
<|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.
// TODO : Support NP_ASFILEONLY mode
// TODO : Support NP_SEEK mode
// TODO : Support SEEKABLE=true in NewStream
#include "webkit/glue/plugins/plugin_stream.h"
#include "base/string_util.h"
#include "base/message_loop.h"
#include "net/base/mime_util.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "googleurl/src/gurl.h"
namespace NPAPI {
PluginStream::~PluginStream() {
// always close our temporary files.
CloseTempFile();
free(const_cast<char*>(stream_.url));
}
bool PluginStream::Open(const std::string &mime_type,
const std::string &headers,
uint32 length,
uint32 last_modified,
bool request_is_seekable) {
headers_ = headers;
NPP id = instance_->npp();
stream_.end = length;
stream_.lastmodified = last_modified;
stream_.pdata = 0;
stream_.ndata = id->ndata;
stream_.notifyData = notify_data_;
bool seekable_stream = false;
if (request_is_seekable && !headers_.empty()) {
stream_.headers = headers_.c_str();
if (headers_.find("Accept-Ranges: bytes") != std::string::npos) {
seekable_stream = true;
}
}
const char *char_mime_type = "application/x-unknown-content-type";
std::string temp_mime_type;
if (!mime_type.empty()) {
char_mime_type = mime_type.c_str();
} else {
GURL gurl(stream_.url);
#if defined(OS_WIN)
FilePath path(UTF8ToWide(gurl.path()));
#elif defined(OS_POSIX)
FilePath path(gurl.path());
#endif
if (net::GetMimeTypeFromFile(path, &temp_mime_type))
char_mime_type = temp_mime_type.c_str();
}
// Silverlight expects a valid mime type
DCHECK(strlen(char_mime_type) != 0);
NPError err = instance_->NPP_NewStream((NPMIMEType)char_mime_type,
&stream_, seekable_stream,
&requested_plugin_mode_);
if (err != NPERR_NO_ERROR) {
Notify(err);
return false;
}
opened_ = true;
if (requested_plugin_mode_ == NP_SEEK) {
seekable_stream_ = true;
}
// If the plugin has requested certain modes, then we need a copy
// of this file on disk. Open it and save it as we go.
if (requested_plugin_mode_ == NP_ASFILEONLY ||
requested_plugin_mode_ == NP_ASFILE) {
if (OpenTempFile() == false)
return false;
}
mime_type_ = char_mime_type;
return true;
}
int PluginStream::Write(const char *buffer, const int length,
int data_offset) {
// There may be two streams to write to - the plugin and the file.
// It is unclear what to do if we cannot write to both. The rules of
// this function are that the plugin must consume at least as many
// bytes as returned by the WriteReady call. So, we will attempt to
// write that many to both streams. If we can't write that many bytes
// to each stream, we'll return failure.
DCHECK(opened_);
if (WriteToFile(buffer, length) &&
WriteToPlugin(buffer, length, data_offset))
return length;
return -1;
}
bool PluginStream::WriteToFile(const char *buf, size_t length) {
// For ASFILEONLY, ASFILE, and SEEK modes, we need to write
// to the disk
if (TempFileIsValid() &&
(requested_plugin_mode_ == NP_ASFILE ||
requested_plugin_mode_ == NP_ASFILEONLY) ) {
size_t totalBytesWritten = 0, bytes;
do {
bytes = WriteBytes(buf, length);
totalBytesWritten += bytes;
} while (bytes > 0U && totalBytesWritten < length);
if (totalBytesWritten != length)
return false;
}
return true;
}
bool PluginStream::WriteToPlugin(const char *buf, const int length,
const int data_offset) {
// For NORMAL and ASFILE modes, we send the data to the plugin now
if (requested_plugin_mode_ != NP_NORMAL &&
requested_plugin_mode_ != NP_ASFILE &&
requested_plugin_mode_ != NP_SEEK)
return true;
int written = TryWriteToPlugin(buf, length, data_offset);
if (written == -1)
return false;
if (written < length) {
// Buffer the remaining data.
size_t remaining = length - written;
size_t previous_size = delivery_data_.size();
delivery_data_.resize(previous_size + remaining);
data_offset_ = data_offset;
memcpy(&delivery_data_[previous_size], buf + written, remaining);
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &PluginStream::OnDelayDelivery));
}
return true;
}
void PluginStream::OnDelayDelivery() {
// It is possible that the plugin stream may have closed before the task
// was hit.
if (!opened_) {
return;
}
int size = static_cast<int>(delivery_data_.size());
int written = TryWriteToPlugin(&delivery_data_.front(), size,
data_offset_);
if (written > 0) {
// Remove the data that we already wrote.
delivery_data_.erase(delivery_data_.begin(),
delivery_data_.begin() + written);
}
}
int PluginStream::TryWriteToPlugin(const char *buf, const int length,
const int data_offset) {
int byte_offset = 0;
if (data_offset > 0)
data_offset_ = data_offset;
while (byte_offset < length) {
int bytes_remaining = length - byte_offset;
int bytes_to_write = instance_->NPP_WriteReady(&stream_);
if (bytes_to_write > bytes_remaining)
bytes_to_write = bytes_remaining;
if (bytes_to_write == 0)
return byte_offset;
int bytes_consumed = instance_->NPP_Write(
&stream_, data_offset_, bytes_to_write,
const_cast<char*>(buf + byte_offset));
if (bytes_consumed < 0) {
// The plugin failed, which means that we need to close the stream.
Close(NPRES_NETWORK_ERR);
return -1;
}
if (bytes_consumed == 0) {
// The plugin couldn't take all of the data now.
return byte_offset;
}
// The plugin might report more that we gave it.
bytes_consumed = std::min(bytes_consumed, bytes_to_write);
data_offset_ += bytes_consumed;
byte_offset += bytes_consumed;
}
if (close_on_write_data_)
Close(NPRES_DONE);
return length;
}
bool PluginStream::Close(NPReason reason) {
if (opened_ == true) {
opened_ = false;
if (delivery_data_.size()) {
if (reason == NPRES_DONE) {
// There is more data to be streamed, don't destroy the stream now.
close_on_write_data_ = true;
return true;
} else {
// Stop any pending data from being streamed
delivery_data_.resize(0);
}
}
// If we have a temp file, be sure to close it.
// Also, allow the plugin to access it now.
if (TempFileIsValid()) {
CloseTempFile();
if (reason == NPRES_DONE)
WriteAsFile();
}
if (stream_.ndata != NULL) {
// Stream hasn't been closed yet.
NPError err = instance_->NPP_DestroyStream(&stream_, reason);
DCHECK(err == NPERR_NO_ERROR);
}
}
Notify(reason);
return true;
}
void PluginStream::Notify(NPReason reason) {
if (notify_needed_) {
instance_->NPP_URLNotify(stream_.url, reason, notify_data_);
notify_needed_ = false;
}
}
} // namespace NPAPI
<commit_msg>Always send the stream headers to the plugin, not just for seekable ones.<commit_after>// 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.
// TODO : Support NP_ASFILEONLY mode
// TODO : Support NP_SEEK mode
// TODO : Support SEEKABLE=true in NewStream
#include "webkit/glue/plugins/plugin_stream.h"
#include "base/string_util.h"
#include "base/message_loop.h"
#include "net/base/mime_util.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "googleurl/src/gurl.h"
namespace NPAPI {
PluginStream::~PluginStream() {
// always close our temporary files.
CloseTempFile();
free(const_cast<char*>(stream_.url));
}
bool PluginStream::Open(const std::string &mime_type,
const std::string &headers,
uint32 length,
uint32 last_modified,
bool request_is_seekable) {
headers_ = headers;
NPP id = instance_->npp();
stream_.end = length;
stream_.lastmodified = last_modified;
stream_.pdata = 0;
stream_.ndata = id->ndata;
stream_.notifyData = notify_data_;
if (!headers_.empty())
stream_.headers = headers_.c_str();
bool seekable_stream = false;
if (request_is_seekable) {
std::string headers_lc = StringToLowerASCII(headers);
if (headers_lc.find("accept-ranges: bytes") != std::string::npos) {
seekable_stream = true;
}
}
const char *char_mime_type = "application/x-unknown-content-type";
std::string temp_mime_type;
if (!mime_type.empty()) {
char_mime_type = mime_type.c_str();
} else {
GURL gurl(stream_.url);
#if defined(OS_WIN)
FilePath path(UTF8ToWide(gurl.path()));
#elif defined(OS_POSIX)
FilePath path(gurl.path());
#endif
if (net::GetMimeTypeFromFile(path, &temp_mime_type))
char_mime_type = temp_mime_type.c_str();
}
// Silverlight expects a valid mime type
DCHECK(strlen(char_mime_type) != 0);
NPError err = instance_->NPP_NewStream((NPMIMEType)char_mime_type,
&stream_, seekable_stream,
&requested_plugin_mode_);
if (err != NPERR_NO_ERROR) {
Notify(err);
return false;
}
opened_ = true;
if (requested_plugin_mode_ == NP_SEEK) {
seekable_stream_ = true;
}
// If the plugin has requested certain modes, then we need a copy
// of this file on disk. Open it and save it as we go.
if (requested_plugin_mode_ == NP_ASFILEONLY ||
requested_plugin_mode_ == NP_ASFILE) {
if (OpenTempFile() == false)
return false;
}
mime_type_ = char_mime_type;
return true;
}
int PluginStream::Write(const char *buffer, const int length,
int data_offset) {
// There may be two streams to write to - the plugin and the file.
// It is unclear what to do if we cannot write to both. The rules of
// this function are that the plugin must consume at least as many
// bytes as returned by the WriteReady call. So, we will attempt to
// write that many to both streams. If we can't write that many bytes
// to each stream, we'll return failure.
DCHECK(opened_);
if (WriteToFile(buffer, length) &&
WriteToPlugin(buffer, length, data_offset))
return length;
return -1;
}
bool PluginStream::WriteToFile(const char *buf, size_t length) {
// For ASFILEONLY, ASFILE, and SEEK modes, we need to write
// to the disk
if (TempFileIsValid() &&
(requested_plugin_mode_ == NP_ASFILE ||
requested_plugin_mode_ == NP_ASFILEONLY) ) {
size_t totalBytesWritten = 0, bytes;
do {
bytes = WriteBytes(buf, length);
totalBytesWritten += bytes;
} while (bytes > 0U && totalBytesWritten < length);
if (totalBytesWritten != length)
return false;
}
return true;
}
bool PluginStream::WriteToPlugin(const char *buf, const int length,
const int data_offset) {
// For NORMAL and ASFILE modes, we send the data to the plugin now
if (requested_plugin_mode_ != NP_NORMAL &&
requested_plugin_mode_ != NP_ASFILE &&
requested_plugin_mode_ != NP_SEEK)
return true;
int written = TryWriteToPlugin(buf, length, data_offset);
if (written == -1)
return false;
if (written < length) {
// Buffer the remaining data.
size_t remaining = length - written;
size_t previous_size = delivery_data_.size();
delivery_data_.resize(previous_size + remaining);
data_offset_ = data_offset;
memcpy(&delivery_data_[previous_size], buf + written, remaining);
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &PluginStream::OnDelayDelivery));
}
return true;
}
void PluginStream::OnDelayDelivery() {
// It is possible that the plugin stream may have closed before the task
// was hit.
if (!opened_) {
return;
}
int size = static_cast<int>(delivery_data_.size());
int written = TryWriteToPlugin(&delivery_data_.front(), size,
data_offset_);
if (written > 0) {
// Remove the data that we already wrote.
delivery_data_.erase(delivery_data_.begin(),
delivery_data_.begin() + written);
}
}
int PluginStream::TryWriteToPlugin(const char *buf, const int length,
const int data_offset) {
int byte_offset = 0;
if (data_offset > 0)
data_offset_ = data_offset;
while (byte_offset < length) {
int bytes_remaining = length - byte_offset;
int bytes_to_write = instance_->NPP_WriteReady(&stream_);
if (bytes_to_write > bytes_remaining)
bytes_to_write = bytes_remaining;
if (bytes_to_write == 0)
return byte_offset;
int bytes_consumed = instance_->NPP_Write(
&stream_, data_offset_, bytes_to_write,
const_cast<char*>(buf + byte_offset));
if (bytes_consumed < 0) {
// The plugin failed, which means that we need to close the stream.
Close(NPRES_NETWORK_ERR);
return -1;
}
if (bytes_consumed == 0) {
// The plugin couldn't take all of the data now.
return byte_offset;
}
// The plugin might report more that we gave it.
bytes_consumed = std::min(bytes_consumed, bytes_to_write);
data_offset_ += bytes_consumed;
byte_offset += bytes_consumed;
}
if (close_on_write_data_)
Close(NPRES_DONE);
return length;
}
bool PluginStream::Close(NPReason reason) {
if (opened_ == true) {
opened_ = false;
if (delivery_data_.size()) {
if (reason == NPRES_DONE) {
// There is more data to be streamed, don't destroy the stream now.
close_on_write_data_ = true;
return true;
} else {
// Stop any pending data from being streamed
delivery_data_.resize(0);
}
}
// If we have a temp file, be sure to close it.
// Also, allow the plugin to access it now.
if (TempFileIsValid()) {
CloseTempFile();
if (reason == NPRES_DONE)
WriteAsFile();
}
if (stream_.ndata != NULL) {
// Stream hasn't been closed yet.
NPError err = instance_->NPP_DestroyStream(&stream_, reason);
DCHECK(err == NPERR_NO_ERROR);
}
}
Notify(reason);
return true;
}
void PluginStream::Notify(NPReason reason) {
if (notify_needed_) {
instance_->NPP_URLNotify(stream_.url, reason, notify_data_);
notify_needed_ = false;
}
}
} // namespace NPAPI
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/ppb_pdf_impl.h"
#include "app/resource_bundle.h"
#include "base/metrics/histogram.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "grit/webkit_resources.h"
#include "grit/webkit_strings.h"
#include "skia/ext/platform_canvas.h"
#include "ppapi/c/pp_resource.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/icu/public/i18n/unicode/usearch.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_image_data_impl.h"
#include "webkit/plugins/ppapi/ppb_pdf.h"
#include "webkit/plugins/ppapi/var.h"
namespace webkit {
namespace ppapi {
#if defined(OS_LINUX)
class PrivateFontFile : public Resource {
public:
PrivateFontFile(PluginModule* module, int fd)
: Resource(module),
fd_(fd) {
}
virtual ~PrivateFontFile() {
}
// Resource overrides.
PrivateFontFile* AsPrivateFontFile() { return this; }
bool GetFontTable(uint32_t table,
void* output,
uint32_t* output_length);
private:
int fd_;
};
#endif
namespace {
struct ResourceImageInfo {
PP_ResourceImage pp_id;
int res_id;
};
static const ResourceImageInfo kResourceImageMap[] = {
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH, IDR_PDF_BUTTON_FTH },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_HOVER, IDR_PDF_BUTTON_FTH_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_PRESSED, IDR_PDF_BUTTON_FTH_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW, IDR_PDF_BUTTON_FTW },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, IDR_PDF_BUTTON_FTW_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED, IDR_PDF_BUTTON_FTW_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, IDR_PDF_BUTTON_ZOOMIN },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, IDR_PDF_BUTTON_ZOOMIN_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED, IDR_PDF_BUTTON_ZOOMIN_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, IDR_PDF_BUTTON_ZOOMOUT },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, IDR_PDF_BUTTON_ZOOMOUT_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED,
IDR_PDF_BUTTON_ZOOMOUT_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0, IDR_PDF_THUMBNAIL_0 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1, IDR_PDF_THUMBNAIL_1 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2, IDR_PDF_THUMBNAIL_2 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3, IDR_PDF_THUMBNAIL_3 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4, IDR_PDF_THUMBNAIL_4 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5, IDR_PDF_THUMBNAIL_5 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6, IDR_PDF_THUMBNAIL_6 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7, IDR_PDF_THUMBNAIL_7 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8, IDR_PDF_THUMBNAIL_8 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9, IDR_PDF_THUMBNAIL_9 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND,
IDR_PDF_THUMBNAIL_NUM_BACKGROUND },
};
PP_Var GetLocalizedString(PP_Module module_id, PP_ResourceString string_id) {
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return PP_MakeUndefined();
std::string rv;
if (string_id == PP_RESOURCESTRING_PDFGETPASSWORD) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_NEED_PASSWORD));
} else if (string_id == PP_RESOURCESTRING_PDFLOADING) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOADING));
} else if (string_id == PP_RESOURCESTRING_PDFLOAD_FAILED) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOAD_FAILED));
} else {
NOTREACHED();
}
return StringVar::StringToPPVar(module, rv);
}
PP_Resource GetResourceImage(PP_Module module_id, PP_ResourceImage image_id) {
int res_id = 0;
for (size_t i = 0; i < arraysize(kResourceImageMap); ++i) {
if (kResourceImageMap[i].pp_id == image_id) {
res_id = kResourceImageMap[i].res_id;
break;
}
}
if (res_id == 0)
return 0;
SkBitmap* res_bitmap =
ResourceBundle::GetSharedInstance().GetBitmapNamed(res_id);
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<PPB_ImageData_Impl> image_data(new PPB_ImageData_Impl(module));
if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
res_bitmap->width(), res_bitmap->height(), false)) {
return 0;
}
ImageDataAutoMapper mapper(image_data);
if (!mapper.is_valid())
return 0;
skia::PlatformCanvas* canvas = image_data->mapped_canvas();
SkBitmap& ret_bitmap =
const_cast<SkBitmap&>(canvas->getTopPlatformDevice().accessBitmap(true));
if (!res_bitmap->copyTo(&ret_bitmap, SkBitmap::kARGB_8888_Config, NULL)) {
return 0;
}
return image_data->GetReference();
}
PP_Resource GetFontFileWithFallback(
PP_Module module_id,
const PP_FontDescription_Dev* description,
PP_PrivateFontCharset charset) {
#if defined(OS_LINUX)
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<StringVar> face_name(StringVar::FromPPVar(description->face));
if (!face_name)
return 0;
int fd = webkit_glue::MatchFontWithFallback(
face_name->value().c_str(),
description->weight >= PP_FONTWEIGHT_BOLD,
description->italic,
charset);
if (fd == -1)
return 0;
scoped_refptr<PrivateFontFile> font(new PrivateFontFile(module, fd));
return font->GetReference();
#else
// For trusted PPAPI plugins, this is only needed in Linux since font loading
// on Windows and Mac works through the renderer sandbox.
return 0;
#endif
}
bool GetFontTableForPrivateFontFile(PP_Resource font_file,
uint32_t table,
void* output,
uint32_t* output_length) {
#if defined(OS_LINUX)
scoped_refptr<PrivateFontFile> font(
Resource::GetAs<PrivateFontFile>(font_file));
if (!font.get())
return false;
return font->GetFontTable(table, output, output_length);
#else
return false;
#endif
}
void SearchString(PP_Module module,
const unsigned short* input_string,
const unsigned short* input_term,
bool case_sensitive,
PP_PrivateFindResult** results,
int* count) {
const char16* string = reinterpret_cast<const char16*>(input_string);
const char16* term = reinterpret_cast<const char16*>(input_term);
UErrorCode status = U_ZERO_ERROR;
UStringSearch* searcher = usearch_open(
term, -1, string, -1, webkit_glue::GetWebKitLocale().c_str(), 0,
&status);
DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING ||
status == U_USING_DEFAULT_WARNING);
UCollationStrength strength = case_sensitive ? UCOL_TERTIARY : UCOL_PRIMARY;
UCollator* collator = usearch_getCollator(searcher);
if (ucol_getStrength(collator) != strength) {
ucol_setStrength(collator, strength);
usearch_reset(searcher);
}
status = U_ZERO_ERROR;
int match_start = usearch_first(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
std::vector<PP_PrivateFindResult> pp_results;
while (match_start != USEARCH_DONE) {
size_t matched_length = usearch_getMatchedLength(searcher);
PP_PrivateFindResult result;
result.start_index = match_start;
result.length = matched_length;
pp_results.push_back(result);
match_start = usearch_next(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
}
*count = pp_results.size();
if (*count) {
*results = reinterpret_cast<PP_PrivateFindResult*>(
malloc(*count * sizeof(PP_PrivateFindResult)));
memcpy(*results, &pp_results[0], *count * sizeof(PP_PrivateFindResult));
} else {
*results = NULL;
}
usearch_close(searcher);
}
void DidStartLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStartLoading();
}
void DidStopLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStopLoading();
}
void SetContentRestriction(PP_Instance instance_id, int restrictions) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->SetContentRestriction(restrictions);
}
void HistogramPDFPageCount(int count) {
UMA_HISTOGRAM_COUNTS_10000("PDF.PageCount", count);
}
void UserMetricsRecordAction(PP_Var action) {
scoped_refptr<StringVar> action_str(StringVar::FromPPVar(action));
if (action_str)
webkit_glue::UserMetricsRecordAction(action_str->value());
}
const PPB_PDF ppb_pdf = {
&GetLocalizedString,
&GetResourceImage,
&GetFontFileWithFallback,
&GetFontTableForPrivateFontFile,
&SearchString,
&DidStartLoading,
&DidStopLoading,
&SetContentRestriction,
&HistogramPDFPageCount,
&UserMetricsRecordAction
};
} // namespace
// static
const PPB_PDF* PPB_PDF_Impl::GetInterface() {
return &ppb_pdf;
}
#if defined(OS_LINUX)
bool PrivateFontFile::GetFontTable(uint32_t table,
void* output,
uint32_t* output_length) {
size_t temp_size = static_cast<size_t>(*output_length);
bool rv = webkit_glue::GetFontTable(
fd_, table, static_cast<uint8_t*>(output), &temp_size);
*output_length = static_cast<uint32_t>(temp_size);
return rv;
}
#endif
} // namespace ppapi
} // namespace webkit
<commit_msg>Modify inclusion to use system icu headers when -Duse_system_icu=1<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/ppb_pdf_impl.h"
#include "app/resource_bundle.h"
#include "base/metrics/histogram.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "grit/webkit_resources.h"
#include "grit/webkit_strings.h"
#include "skia/ext/platform_canvas.h"
#include "ppapi/c/pp_resource.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "unicode/usearch.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_image_data_impl.h"
#include "webkit/plugins/ppapi/ppb_pdf.h"
#include "webkit/plugins/ppapi/var.h"
namespace webkit {
namespace ppapi {
#if defined(OS_LINUX)
class PrivateFontFile : public Resource {
public:
PrivateFontFile(PluginModule* module, int fd)
: Resource(module),
fd_(fd) {
}
virtual ~PrivateFontFile() {
}
// Resource overrides.
PrivateFontFile* AsPrivateFontFile() { return this; }
bool GetFontTable(uint32_t table,
void* output,
uint32_t* output_length);
private:
int fd_;
};
#endif
namespace {
struct ResourceImageInfo {
PP_ResourceImage pp_id;
int res_id;
};
static const ResourceImageInfo kResourceImageMap[] = {
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH, IDR_PDF_BUTTON_FTH },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_HOVER, IDR_PDF_BUTTON_FTH_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_PRESSED, IDR_PDF_BUTTON_FTH_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW, IDR_PDF_BUTTON_FTW },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, IDR_PDF_BUTTON_FTW_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED, IDR_PDF_BUTTON_FTW_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, IDR_PDF_BUTTON_ZOOMIN },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, IDR_PDF_BUTTON_ZOOMIN_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED, IDR_PDF_BUTTON_ZOOMIN_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, IDR_PDF_BUTTON_ZOOMOUT },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, IDR_PDF_BUTTON_ZOOMOUT_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED,
IDR_PDF_BUTTON_ZOOMOUT_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0, IDR_PDF_THUMBNAIL_0 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1, IDR_PDF_THUMBNAIL_1 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2, IDR_PDF_THUMBNAIL_2 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3, IDR_PDF_THUMBNAIL_3 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4, IDR_PDF_THUMBNAIL_4 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5, IDR_PDF_THUMBNAIL_5 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6, IDR_PDF_THUMBNAIL_6 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7, IDR_PDF_THUMBNAIL_7 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8, IDR_PDF_THUMBNAIL_8 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9, IDR_PDF_THUMBNAIL_9 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND,
IDR_PDF_THUMBNAIL_NUM_BACKGROUND },
};
PP_Var GetLocalizedString(PP_Module module_id, PP_ResourceString string_id) {
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return PP_MakeUndefined();
std::string rv;
if (string_id == PP_RESOURCESTRING_PDFGETPASSWORD) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_NEED_PASSWORD));
} else if (string_id == PP_RESOURCESTRING_PDFLOADING) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOADING));
} else if (string_id == PP_RESOURCESTRING_PDFLOAD_FAILED) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOAD_FAILED));
} else {
NOTREACHED();
}
return StringVar::StringToPPVar(module, rv);
}
PP_Resource GetResourceImage(PP_Module module_id, PP_ResourceImage image_id) {
int res_id = 0;
for (size_t i = 0; i < arraysize(kResourceImageMap); ++i) {
if (kResourceImageMap[i].pp_id == image_id) {
res_id = kResourceImageMap[i].res_id;
break;
}
}
if (res_id == 0)
return 0;
SkBitmap* res_bitmap =
ResourceBundle::GetSharedInstance().GetBitmapNamed(res_id);
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<PPB_ImageData_Impl> image_data(new PPB_ImageData_Impl(module));
if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
res_bitmap->width(), res_bitmap->height(), false)) {
return 0;
}
ImageDataAutoMapper mapper(image_data);
if (!mapper.is_valid())
return 0;
skia::PlatformCanvas* canvas = image_data->mapped_canvas();
SkBitmap& ret_bitmap =
const_cast<SkBitmap&>(canvas->getTopPlatformDevice().accessBitmap(true));
if (!res_bitmap->copyTo(&ret_bitmap, SkBitmap::kARGB_8888_Config, NULL)) {
return 0;
}
return image_data->GetReference();
}
PP_Resource GetFontFileWithFallback(
PP_Module module_id,
const PP_FontDescription_Dev* description,
PP_PrivateFontCharset charset) {
#if defined(OS_LINUX)
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<StringVar> face_name(StringVar::FromPPVar(description->face));
if (!face_name)
return 0;
int fd = webkit_glue::MatchFontWithFallback(
face_name->value().c_str(),
description->weight >= PP_FONTWEIGHT_BOLD,
description->italic,
charset);
if (fd == -1)
return 0;
scoped_refptr<PrivateFontFile> font(new PrivateFontFile(module, fd));
return font->GetReference();
#else
// For trusted PPAPI plugins, this is only needed in Linux since font loading
// on Windows and Mac works through the renderer sandbox.
return 0;
#endif
}
bool GetFontTableForPrivateFontFile(PP_Resource font_file,
uint32_t table,
void* output,
uint32_t* output_length) {
#if defined(OS_LINUX)
scoped_refptr<PrivateFontFile> font(
Resource::GetAs<PrivateFontFile>(font_file));
if (!font.get())
return false;
return font->GetFontTable(table, output, output_length);
#else
return false;
#endif
}
void SearchString(PP_Module module,
const unsigned short* input_string,
const unsigned short* input_term,
bool case_sensitive,
PP_PrivateFindResult** results,
int* count) {
const char16* string = reinterpret_cast<const char16*>(input_string);
const char16* term = reinterpret_cast<const char16*>(input_term);
UErrorCode status = U_ZERO_ERROR;
UStringSearch* searcher = usearch_open(
term, -1, string, -1, webkit_glue::GetWebKitLocale().c_str(), 0,
&status);
DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING ||
status == U_USING_DEFAULT_WARNING);
UCollationStrength strength = case_sensitive ? UCOL_TERTIARY : UCOL_PRIMARY;
UCollator* collator = usearch_getCollator(searcher);
if (ucol_getStrength(collator) != strength) {
ucol_setStrength(collator, strength);
usearch_reset(searcher);
}
status = U_ZERO_ERROR;
int match_start = usearch_first(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
std::vector<PP_PrivateFindResult> pp_results;
while (match_start != USEARCH_DONE) {
size_t matched_length = usearch_getMatchedLength(searcher);
PP_PrivateFindResult result;
result.start_index = match_start;
result.length = matched_length;
pp_results.push_back(result);
match_start = usearch_next(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
}
*count = pp_results.size();
if (*count) {
*results = reinterpret_cast<PP_PrivateFindResult*>(
malloc(*count * sizeof(PP_PrivateFindResult)));
memcpy(*results, &pp_results[0], *count * sizeof(PP_PrivateFindResult));
} else {
*results = NULL;
}
usearch_close(searcher);
}
void DidStartLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStartLoading();
}
void DidStopLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStopLoading();
}
void SetContentRestriction(PP_Instance instance_id, int restrictions) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->SetContentRestriction(restrictions);
}
void HistogramPDFPageCount(int count) {
UMA_HISTOGRAM_COUNTS_10000("PDF.PageCount", count);
}
void UserMetricsRecordAction(PP_Var action) {
scoped_refptr<StringVar> action_str(StringVar::FromPPVar(action));
if (action_str)
webkit_glue::UserMetricsRecordAction(action_str->value());
}
const PPB_PDF ppb_pdf = {
&GetLocalizedString,
&GetResourceImage,
&GetFontFileWithFallback,
&GetFontTableForPrivateFontFile,
&SearchString,
&DidStartLoading,
&DidStopLoading,
&SetContentRestriction,
&HistogramPDFPageCount,
&UserMetricsRecordAction
};
} // namespace
// static
const PPB_PDF* PPB_PDF_Impl::GetInterface() {
return &ppb_pdf;
}
#if defined(OS_LINUX)
bool PrivateFontFile::GetFontTable(uint32_t table,
void* output,
uint32_t* output_length) {
size_t temp_size = static_cast<size_t>(*output_length);
bool rv = webkit_glue::GetFontTable(
fd_, table, static_cast<uint8_t*>(output), &temp_size);
*output_length = static_cast<uint32_t>(temp_size);
return rv;
}
#endif
} // namespace ppapi
} // namespace webkit
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ツールス・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <string>
#include "utils/input.hpp"
#include "utils/format.hpp"
#include "utils/preference.hpp"
#include "widgets/widget_chip.hpp"
#include "interlock.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ツールス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct tools {
static std::string limitf(const std::string& str, float min, float max, const char* form)
{
std::string newtext;
float v;
if((utils::input("%f", str.c_str()) % v).status()) {
if(v < min) v = min;
else if(v > max) v = max;
char tmp[256];
utils::format(form, tmp, sizeof(tmp)) % v;
newtext = tmp;
}
return newtext;
}
static std::string limiti(const std::string& str, int min, int max, const char* form)
{
std::string newtext;
int v;
if((utils::input("%d", str.c_str()) % v).status()) {
if(v < min) v = min;
else if(v > max) v = max;
char tmp[256];
utils::format(form, tmp, sizeof(tmp)) % v;
newtext = tmp;
}
return newtext;
}
static void set_help(gui::widget_chip* chip, gui::widget* src, const std::string& text)
{
chip->set_offset(src);
chip->set_text(text);
}
static interlock::module get_module(int swn)
{
interlock::module md = interlock::module::N;
switch(swn) {
case 1:
md = interlock::module::CRM;
break;
case 15:
md = interlock::module::DC2;
break;
case 29:
md = interlock::module::WDM;
break;
case 34:
md = interlock::module::ICM;
break;
case 40:
md = interlock::module::DC1;
break;
case 44:
md = interlock::module::WGM;
break;
default:
break;
}
return md;
}
static void init_sw(gui::widget_director& wd, gui::widget* root, interlock& ilc,
int ofsx, int ofsy, gui::widget_check* out[], int num, int swn)
{
auto md = get_module(swn);
for(int i = 0; i < num; ++i) {
gui::widget::param wp(vtx::irect(ofsx, ofsy, 60, 40), root);
gui::widget_check::param wp_((boost::format("%d") % swn).str());
out[i] = wd.add_widget<gui::widget_check>(wp, wp_);
ofsx += 60;
ilc.install(md, static_cast<interlock::swtype>(swn), out[i]);
++swn;
}
}
static void load_sw(sys::preference& pre, gui::widget_check* sw[], uint32_t n)
{
for(uint32_t i = 0; i < n; ++i) {
sw[i]->load(pre);
}
}
static void save_sw(sys::preference& pre, gui::widget_check* sw[], uint32_t n)
{
for(uint32_t i = 0; i < n; ++i) {
sw[i]->save(pre);
}
}
static std::string double_to_str(double a)
{
std::string str;
if(a >= 0.001) {
str = (boost::format("%4.3f") % a).str();
} else {
str = (boost::format("%e") % a).str();
}
return str;
}
};
}
<commit_msg>update: chip location<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ツールス・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <string>
#include "utils/input.hpp"
#include "utils/format.hpp"
#include "utils/preference.hpp"
#include "widgets/widget_chip.hpp"
#include "interlock.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ツールス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct tools {
static std::string limitf(const std::string& str, float min, float max, const char* form)
{
std::string newtext;
float v;
if((utils::input("%f", str.c_str()) % v).status()) {
if(v < min) v = min;
else if(v > max) v = max;
char tmp[256];
utils::format(form, tmp, sizeof(tmp)) % v;
newtext = tmp;
}
return newtext;
}
static std::string limiti(const std::string& str, int min, int max, const char* form)
{
std::string newtext;
int v;
if((utils::input("%d", str.c_str()) % v).status()) {
if(v < min) v = min;
else if(v > max) v = max;
char tmp[256];
utils::format(form, tmp, sizeof(tmp)) % v;
newtext = tmp;
}
return newtext;
}
static void set_help(gui::widget_chip* chip, gui::widget* src, const std::string& text)
{
chip->set_offset(src, gui::widget_chip::offset_type::CENTER_UP);
chip->set_text(text);
}
static interlock::module get_module(int swn)
{
interlock::module md = interlock::module::N;
switch(swn) {
case 1:
md = interlock::module::CRM;
break;
case 15:
md = interlock::module::DC2;
break;
case 29:
md = interlock::module::WDM;
break;
case 34:
md = interlock::module::ICM;
break;
case 40:
md = interlock::module::DC1;
break;
case 44:
md = interlock::module::WGM;
break;
default:
break;
}
return md;
}
static void init_sw(gui::widget_director& wd, gui::widget* root, interlock& ilc,
int ofsx, int ofsy, gui::widget_check* out[], int num, int swn)
{
auto md = get_module(swn);
for(int i = 0; i < num; ++i) {
gui::widget::param wp(vtx::irect(ofsx, ofsy, 60, 40), root);
gui::widget_check::param wp_((boost::format("%d") % swn).str());
out[i] = wd.add_widget<gui::widget_check>(wp, wp_);
ofsx += 60;
ilc.install(md, static_cast<interlock::swtype>(swn), out[i]);
++swn;
}
}
static void load_sw(sys::preference& pre, gui::widget_check* sw[], uint32_t n)
{
for(uint32_t i = 0; i < n; ++i) {
sw[i]->load(pre);
}
}
static void save_sw(sys::preference& pre, gui::widget_check* sw[], uint32_t n)
{
for(uint32_t i = 0; i < n; ++i) {
sw[i]->save(pre);
}
}
static std::string double_to_str(double a)
{
std::string str;
if(a >= 0.001) {
str = (boost::format("%4.3f") % a).str();
} else {
str = (boost::format("%e") % a).str();
}
return str;
}
};
}
<|endoftext|>
|
<commit_before>#include "whitted_integrator.h"
#include "diff_geom.h"
#include "light.h"
#include "brdf.h"
namespace pt {
WhittedIntegrator::WhittedIntegrator(const glm::vec3 &background, Scene scene)
: background(background), scene(std::move(scene))
{}
IntersectionResult WhittedIntegrator::integrate(ActiveRay &ray) const {
IntersectionResult result;
const float dummy_samples[2] = {0};
DifferentialGeometry dg;
if (scene.intersect(ray.ray, dg)) {
result.any_hit = true;
glm::vec3 lighting(0);
dg.orthonormalize();
const glm::vec3 w_o = dg.to_shading(-ray.ray.dir);
if (!(dg.brdf->bxdf_type() & BRDFType::Specular)) {
for (const auto &l : scene.lights) {
const LightSample light_sample = l->incident(dg.point);
const glm::vec3 w_i = dg.to_shading(light_sample.dir);
const glm::vec3 color = dg.brdf->eval(w_i, w_o) * light_sample.illum
* std::max(glm::dot(light_sample.dir, dg.normal), 0.f);
if (color != glm::vec3(0.f)) {
result.shadow = std::unique_ptr<ActiveRay>(ActiveRay::shadow(light_sample.occlusion_ray, ray));
for (size_t i = 0; i < 3; ++ i) {
result.shadow->color[i] = color[i];
}
}
}
} else if (ray.ray.depth < 6) {
// TODO: We actually need to create and ship off an ActiveRay as a secondary ray.
if (dg.brdf->bxdf_type() & BRDFType::Reflection) {
const BxDFSample f = dg.brdf->sample(w_o, dummy_samples);
if (f.pdf != 0.f && f.color != glm::vec3(0.f)) {
Ray refl_ray(dg.point, dg.from_shading(f.w_i), 0.001);
refl_ray.depth = ray.ray.depth + 1;
result.secondary = std::unique_ptr<ActiveRay>(ActiveRay::secondary(refl_ray, ray));
for (size_t i = 0; i < 3; ++ i) {
result.secondary->color[i] = f.color[i];
}
}
}
if (dg.brdf->bxdf_type() & BRDFType::Transmission) {
// TODO
}
}
}
return result;
}
bool WhittedIntegrator::occluded(ActiveRay &ray) const {
DifferentialGeometry dg;
return scene.intersect(ray.ray, dg);
}
}
<commit_msg>Update the compositing depth value when we find a hit as well<commit_after>#include "whitted_integrator.h"
#include "diff_geom.h"
#include "light.h"
#include "brdf.h"
namespace pt {
WhittedIntegrator::WhittedIntegrator(const glm::vec3 &background, Scene scene)
: background(background), scene(std::move(scene))
{}
IntersectionResult WhittedIntegrator::integrate(ActiveRay &ray) const {
IntersectionResult result;
const float dummy_samples[2] = {0};
DifferentialGeometry dg;
if (scene.intersect(ray.ray, dg)) {
result.any_hit = true;
ray.color.w = ray.ray.t_max;
glm::vec3 lighting(0);
dg.orthonormalize();
const glm::vec3 w_o = dg.to_shading(-ray.ray.dir);
if (!(dg.brdf->bxdf_type() & BRDFType::Specular)) {
for (const auto &l : scene.lights) {
const LightSample light_sample = l->incident(dg.point);
const glm::vec3 w_i = dg.to_shading(light_sample.dir);
const glm::vec3 color = dg.brdf->eval(w_i, w_o) * light_sample.illum
* std::max(glm::dot(light_sample.dir, dg.normal), 0.f);
if (color != glm::vec3(0.f)) {
result.shadow = std::unique_ptr<ActiveRay>(ActiveRay::shadow(light_sample.occlusion_ray, ray));
for (size_t i = 0; i < 3; ++ i) {
result.shadow->color[i] = color[i];
}
}
}
} else if (ray.ray.depth < 6) {
// TODO: We actually need to create and ship off an ActiveRay as a secondary ray.
if (dg.brdf->bxdf_type() & BRDFType::Reflection) {
const BxDFSample f = dg.brdf->sample(w_o, dummy_samples);
if (f.pdf != 0.f && f.color != glm::vec3(0.f)) {
Ray refl_ray(dg.point, dg.from_shading(f.w_i), 0.001);
refl_ray.depth = ray.ray.depth + 1;
result.secondary = std::unique_ptr<ActiveRay>(ActiveRay::secondary(refl_ray, ray));
for (size_t i = 0; i < 3; ++ i) {
result.secondary->color[i] = f.color[i];
}
}
}
if (dg.brdf->bxdf_type() & BRDFType::Transmission) {
// TODO
}
}
}
return result;
}
bool WhittedIntegrator::occluded(ActiveRay &ray) const {
DifferentialGeometry dg;
return scene.intersect(ray.ray, dg);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: recoveryui.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:25:54 $
*
* 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 _RECOVERYUI_HXX
#define _RECOVERYUI_HXX
//===============================================
// includes
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSYNCHRONOUSDISPATCH_HPP_
#include <com/sun/star/frame/XSynchronousDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SVX_DOCRECOVERY_HXX
#include "docrecovery.hxx"
#endif
//===============================================
// namespace
namespace svx
{
// Dont export this header ... Otherwise you have to remove this namespace alias!
namespace css = ::com::sun::star;
namespace svxdr = ::svx::DocRecovery;
//===============================================
// declarations
class RecoveryUI : public ::cppu::WeakImplHelper2< css::lang::XServiceInfo ,
css::frame::XSynchronousDispatch > // => XDispatch!
{
//-------------------------------------------
// const, types, etcpp.
private:
/** @short TODO */
enum EJob
{
E_JOB_UNKNOWN,
E_DO_EMERGENCY_SAVE,
E_DO_RECOVERY,
E_DO_CRASHREPORT
};
//-------------------------------------------
// member
private:
/** @short TODO */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** @short TODO */
Window* m_pParentWindow;
/** @short TODO */
RecoveryUI::EJob m_eJob;
/** @short TODO */
css::uno::Reference< css::task::XStatusIndicatorFactory > m_xProgressFactory;
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short TODO */
RecoveryUI(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
/** @short TODO */
virtual ~RecoveryUI();
//---------------------------------------
// css.lang.XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const ::rtl::OUString& sServiceName)
throw(css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(css::uno::RuntimeException);
//---------------------------------------
virtual com::sun::star::uno::Any SAL_CALL dispatchWithReturnValue(const css::util::URL& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments )
throw(css::uno::RuntimeException);
//---------------------------------------
// css.frame.XDispatch
virtual void SAL_CALL dispatch(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments)
throw(css::uno::RuntimeException);
virtual void SAL_CALL addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException);
virtual void SAL_CALL removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException);
//---------------------------------------
// XServiceInfo helper
static ::rtl::OUString st_getImplementationName();
static css::uno::Sequence< ::rtl::OUString > st_getSupportedServiceNames();
static css::uno::Reference< css::uno::XInterface > SAL_CALL st_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//-------------------------------------------
// helper
private:
EJob impl_classifyJob(const css::util::URL& aURL);
sal_Bool impl_doEmergencySave();
void impl_doRecovery();
void impl_showAllRecoveredDocs();
void impl_doCrashReport();
};
} // namespace svx
#endif // _RECOVERYUI_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.1254); FILE MERGED 2008/04/01 15:51:11 thb 1.3.1254.3: #i85898# Stripping all external header guards 2008/04/01 12:49:07 thb 1.3.1254.2: #i85898# Stripping all external header guards 2008/03/31 14:22:21 rt 1.3.1254.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: recoveryui.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _RECOVERYUI_HXX
#define _RECOVERYUI_HXX
//===============================================
// includes
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/frame/XSynchronousDispatch.hpp>
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#include <cppuhelper/implbase2.hxx>
#include <vcl/window.hxx>
#include "docrecovery.hxx"
//===============================================
// namespace
namespace svx
{
// Dont export this header ... Otherwise you have to remove this namespace alias!
namespace css = ::com::sun::star;
namespace svxdr = ::svx::DocRecovery;
//===============================================
// declarations
class RecoveryUI : public ::cppu::WeakImplHelper2< css::lang::XServiceInfo ,
css::frame::XSynchronousDispatch > // => XDispatch!
{
//-------------------------------------------
// const, types, etcpp.
private:
/** @short TODO */
enum EJob
{
E_JOB_UNKNOWN,
E_DO_EMERGENCY_SAVE,
E_DO_RECOVERY,
E_DO_CRASHREPORT
};
//-------------------------------------------
// member
private:
/** @short TODO */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** @short TODO */
Window* m_pParentWindow;
/** @short TODO */
RecoveryUI::EJob m_eJob;
/** @short TODO */
css::uno::Reference< css::task::XStatusIndicatorFactory > m_xProgressFactory;
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short TODO */
RecoveryUI(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
/** @short TODO */
virtual ~RecoveryUI();
//---------------------------------------
// css.lang.XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const ::rtl::OUString& sServiceName)
throw(css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(css::uno::RuntimeException);
//---------------------------------------
virtual com::sun::star::uno::Any SAL_CALL dispatchWithReturnValue(const css::util::URL& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments )
throw(css::uno::RuntimeException);
//---------------------------------------
// css.frame.XDispatch
virtual void SAL_CALL dispatch(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments)
throw(css::uno::RuntimeException);
virtual void SAL_CALL addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException);
virtual void SAL_CALL removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException);
//---------------------------------------
// XServiceInfo helper
static ::rtl::OUString st_getImplementationName();
static css::uno::Sequence< ::rtl::OUString > st_getSupportedServiceNames();
static css::uno::Reference< css::uno::XInterface > SAL_CALL st_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//-------------------------------------------
// helper
private:
EJob impl_classifyJob(const css::util::URL& aURL);
sal_Bool impl_doEmergencySave();
void impl_doRecovery();
void impl_showAllRecoveredDocs();
void impl_doCrashReport();
};
} // namespace svx
#endif // _RECOVERYUI_HXX
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "base/misc.hh"
#include "dev/etherpkt.hh"
#include "sim/serialize.hh"
using namespace std;
void
PacketData::serialize(const string &base, ostream &os)
{
paramOut(os, base + ".length", length);
arrayParamOut(os, base + ".data", data, length);
}
void
PacketData::unserialize(const string &base, Checkpoint *cp,
const string §ion)
{
paramIn(cp, section, base + ".length", length);
arrayParamIn(cp, section, base + ".data", data, length);
}
<commit_msg>Improve checkpointing of ethernet packets a bit.<commit_after>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "base/misc.hh"
#include "dev/etherpkt.hh"
#include "sim/serialize.hh"
using namespace std;
void
PacketData::serialize(const string &base, ostream &os)
{
paramOut(os, base + ".length", length);
arrayParamOut(os, base + ".data", data, length);
}
void
PacketData::unserialize(const string &base, Checkpoint *cp,
const string §ion)
{
paramIn(cp, section, base + ".length", length);
if (length)
arrayParamIn(cp, section, base + ".data", data, length);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DEV_SINICREG_HH__
#define __DEV_SINICREG_HH__
#define __SINIC_REG32(NAME, VAL) static const uint32_t NAME = (VAL)
#define __SINIC_REG64(NAME, VAL) static const uint64_t NAME = (VAL)
#define __SINIC_VAL32(NAME, OFFSET, WIDTH) \
static const uint32_t NAME##_width = WIDTH; \
static const uint32_t NAME##_offset = OFFSET; \
static const uint32_t NAME##_mask = (1 << WIDTH) - 1; \
static const uint32_t NAME = ((1 << WIDTH) - 1) << OFFSET; \
static inline uint32_t get_##NAME(uint32_t reg) \
{ return (reg & NAME) >> OFFSET; } \
static inline uint32_t set_##NAME(uint32_t reg, uint32_t val) \
{ return (reg & ~NAME) | ((val << OFFSET) & NAME); }
#define __SINIC_VAL64(NAME, OFFSET, WIDTH) \
static const uint64_t NAME##_width = WIDTH; \
static const uint64_t NAME##_offset = OFFSET; \
static const uint64_t NAME##_mask = (ULL(1) << WIDTH) - 1; \
static const uint64_t NAME = ((ULL(1) << WIDTH) - 1) << OFFSET; \
static inline uint64_t get_##NAME(uint64_t reg) \
{ return (reg & NAME) >> OFFSET; } \
static inline uint64_t set_##NAME(uint64_t reg, uint64_t val) \
{ return (reg & ~NAME) | ((val << OFFSET) & NAME); }
namespace Sinic {
namespace Regs {
static const int VirtualMask = 0xff;
static const int VirtualShift = 8;
// Registers
__SINIC_REG32(Config, 0x00); // 32: configuration register
__SINIC_REG32(Command, 0x04); // 32: command register
__SINIC_REG32(IntrStatus, 0x08); // 32: interrupt status
__SINIC_REG32(IntrMask, 0x0c); // 32: interrupt mask
__SINIC_REG32(RxMaxCopy, 0x10); // 32: max bytes per rx copy
__SINIC_REG32(TxMaxCopy, 0x14); // 32: max bytes per tx copy
__SINIC_REG32(RxMaxIntr, 0x18); // 32: max receives per interrupt
__SINIC_REG32(Reserved0, 0x1c); // 32: reserved
__SINIC_REG32(RxFifoSize, 0x20); // 32: rx fifo capacity in bytes
__SINIC_REG32(TxFifoSize, 0x24); // 32: tx fifo capacity in bytes
__SINIC_REG32(RxFifoMark, 0x28); // 32: rx fifo high watermark
__SINIC_REG32(TxFifoMark, 0x2c); // 32: tx fifo low watermark
__SINIC_REG32(RxData, 0x30); // 64: receive data
__SINIC_REG32(RxDone, 0x38); // 64: receive done
__SINIC_REG32(RxWait, 0x40); // 64: receive done (busy wait)
__SINIC_REG32(TxData, 0x48); // 64: transmit data
__SINIC_REG32(TxDone, 0x50); // 64: transmit done
__SINIC_REG32(TxWait, 0x58); // 64: transmit done (busy wait)
__SINIC_REG32(HwAddr, 0x60); // 64: mac address
__SINIC_REG32(Size, 0x68); // register addres space size
// Config register bits
__SINIC_VAL32(Config_RSS, 10, 1); // enable receive side scaling
__SINIC_VAL32(Config_RxThread, 9, 1); // enable receive threads
__SINIC_VAL32(Config_TxThread, 8, 1); // enable transmit thread
__SINIC_VAL32(Config_Filter, 7, 1); // enable receive filter
__SINIC_VAL32(Config_Vlan, 6, 1); // enable vlan tagging
__SINIC_VAL32(Config_Virtual, 5, 1); // enable virtual addressing
__SINIC_VAL32(Config_Desc, 4, 1); // enable tx/rx descriptors
__SINIC_VAL32(Config_Poll, 3, 1); // enable polling
__SINIC_VAL32(Config_IntEn, 2, 1); // enable interrupts
__SINIC_VAL32(Config_TxEn, 1, 1); // enable transmit
__SINIC_VAL32(Config_RxEn, 0, 1); // enable receive
// Command register bits
__SINIC_VAL32(Command_Intr, 1, 1); // software interrupt
__SINIC_VAL32(Command_Reset, 0, 1); // reset chip
// Interrupt register bits
__SINIC_VAL32(Intr_Soft, 8, 1); // software interrupt
__SINIC_VAL32(Intr_TxLow, 7, 1); // tx fifo dropped below watermark
__SINIC_VAL32(Intr_TxFull, 6, 1); // tx fifo full
__SINIC_VAL32(Intr_TxDMA, 5, 1); // tx dma completed w/ interrupt
__SINIC_VAL32(Intr_TxPacket, 4, 1); // packet transmitted
__SINIC_VAL32(Intr_RxHigh, 3, 1); // rx fifo above high watermark
__SINIC_VAL32(Intr_RxEmpty, 2, 1); // rx fifo empty
__SINIC_VAL32(Intr_RxDMA, 1, 1); // rx dma completed w/ interrupt
__SINIC_VAL32(Intr_RxPacket, 0, 1); // packet received
__SINIC_REG32(Intr_All, 0x01ff); // all valid interrupts
__SINIC_REG32(Intr_NoDelay, 0x01cc); // interrupts that aren't coalesced
__SINIC_REG32(Intr_Res, ~0x01ff); // reserved interrupt bits
// RX Data Description
__SINIC_VAL64(RxData_Len, 40, 20); // 0 - 1M
__SINIC_VAL64(RxData_Addr, 0, 40); // Address 1TB
// TX Data Description
__SINIC_VAL64(TxData_More, 63, 1); // Packet not complete (will dma more)
__SINIC_VAL64(TxData_Checksum, 62, 1); // do checksum
__SINIC_VAL64(TxData_Len, 40, 20); // 0 - 1M
__SINIC_VAL64(TxData_Addr, 0, 40); // Address 1TB
// RX Done/Busy Information
__SINIC_VAL64(RxDone_Packets, 32, 16); // number of packets in rx fifo
__SINIC_VAL64(RxDone_Busy, 31, 1); // receive dma busy copying
__SINIC_VAL64(RxDone_Complete, 30, 1); // valid data (packet complete)
__SINIC_VAL64(RxDone_More, 29, 1); // Packet has more data (dma again)
__SINIC_VAL64(RxDone_Res0, 28, 1); // reserved
__SINIC_VAL64(RxDone_Res1, 27, 1); // reserved
__SINIC_VAL64(RxDone_Res2, 26, 1); // reserved
__SINIC_VAL64(RxDone_TcpError, 25, 1); // TCP packet error (bad checksum)
__SINIC_VAL64(RxDone_UdpError, 24, 1); // UDP packet error (bad checksum)
__SINIC_VAL64(RxDone_IpError, 23, 1); // IP packet error (bad checksum)
__SINIC_VAL64(RxDone_TcpPacket, 22, 1); // this is a TCP packet
__SINIC_VAL64(RxDone_UdpPacket, 21, 1); // this is a UDP packet
__SINIC_VAL64(RxDone_IpPacket, 20, 1); // this is an IP packet
__SINIC_VAL64(RxDone_CopyLen, 0, 20); // up to 256k
// TX Done/Busy Information
__SINIC_VAL64(TxDone_Packets, 32, 16); // number of packets in tx fifo
__SINIC_VAL64(TxDone_Busy, 31, 1); // transmit dma busy copying
__SINIC_VAL64(TxDone_Complete, 30, 1); // valid data (packet complete)
__SINIC_VAL64(TxDone_Full, 29, 1); // tx fifo is full
__SINIC_VAL64(TxDone_Low, 28, 1); // tx fifo is below the watermark
__SINIC_VAL64(TxDone_Res0, 27, 1); // reserved
__SINIC_VAL64(TxDone_Res1, 26, 1); // reserved
__SINIC_VAL64(TxDone_Res2, 25, 1); // reserved
__SINIC_VAL64(TxDone_Res3, 24, 1); // reserved
__SINIC_VAL64(TxDone_Res4, 23, 1); // reserved
__SINIC_VAL64(TxDone_Res5, 22, 1); // reserved
__SINIC_VAL64(TxDone_Res6, 21, 1); // reserved
__SINIC_VAL64(TxDone_Res7, 20, 1); // reserved
__SINIC_VAL64(TxDone_CopyLen, 0, 20); // up to 256k
struct Info
{
uint8_t size;
bool read;
bool write;
const char *name;
};
/* namespace Regs */ }
inline const Regs::Info&
regInfo(Addr daddr)
{
static Regs::Info invalid = { 0, false, false, "invalid" };
static Regs::Info info [] = {
{ 4, true, true, "Config" },
{ 4, false, true, "Command" },
{ 4, true, true, "IntrStatus" },
{ 4, true, true, "IntrMask" },
{ 4, true, false, "RxMaxCopy" },
{ 4, true, false, "TxMaxCopy" },
{ 4, true, false, "RxMaxIntr" },
invalid,
{ 4, true, false, "RxFifoSize" },
{ 4, true, false, "TxFifoSize" },
{ 4, true, false, "RxFifoMark" },
{ 4, true, false, "TxFifoMark" },
{ 8, true, true, "RxData" },
invalid,
{ 8, true, false, "RxDone" },
invalid,
{ 8, true, false, "RxWait" },
invalid,
{ 8, true, true, "TxData" },
invalid,
{ 8, true, false, "TxDone" },
invalid,
{ 8, true, false, "TxWait" },
invalid,
{ 8, true, false, "HwAddr" },
invalid,
};
return info[daddr / 4];
}
inline bool
regValid(Addr daddr)
{
if (daddr > Regs::Size)
return false;
if (regInfo(daddr).size == 0)
return false;
return true;
}
/* namespace Sinic */ }
#endif // __DEV_SINICREG_HH__
<commit_msg>Bit of formatting for sinicreg.hh<commit_after>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DEV_SINICREG_HH__
#define __DEV_SINICREG_HH__
#define __SINIC_REG32(NAME, VAL) static const uint32_t NAME = (VAL)
#define __SINIC_REG64(NAME, VAL) static const uint64_t NAME = (VAL)
#define __SINIC_VAL32(NAME, OFFSET, WIDTH) \
static const uint32_t NAME##_width = WIDTH; \
static const uint32_t NAME##_offset = OFFSET; \
static const uint32_t NAME##_mask = (1 << WIDTH) - 1; \
static const uint32_t NAME = ((1 << WIDTH) - 1) << OFFSET; \
static inline uint32_t get_##NAME(uint32_t reg) \
{ return (reg & NAME) >> OFFSET; } \
static inline uint32_t set_##NAME(uint32_t reg, uint32_t val) \
{ return (reg & ~NAME) | ((val << OFFSET) & NAME); }
#define __SINIC_VAL64(NAME, OFFSET, WIDTH) \
static const uint64_t NAME##_width = WIDTH; \
static const uint64_t NAME##_offset = OFFSET; \
static const uint64_t NAME##_mask = (ULL(1) << WIDTH) - 1; \
static const uint64_t NAME = ((ULL(1) << WIDTH) - 1) << OFFSET; \
static inline uint64_t get_##NAME(uint64_t reg) \
{ return (reg & NAME) >> OFFSET; } \
static inline uint64_t set_##NAME(uint64_t reg, uint64_t val) \
{ return (reg & ~NAME) | ((val << OFFSET) & NAME); }
namespace Sinic {
namespace Regs {
static const int VirtualMask = 0xff;
static const int VirtualShift = 8;
// Registers
__SINIC_REG32(Config, 0x00); // 32: configuration register
__SINIC_REG32(Command, 0x04); // 32: command register
__SINIC_REG32(IntrStatus, 0x08); // 32: interrupt status
__SINIC_REG32(IntrMask, 0x0c); // 32: interrupt mask
__SINIC_REG32(RxMaxCopy, 0x10); // 32: max bytes per rx copy
__SINIC_REG32(TxMaxCopy, 0x14); // 32: max bytes per tx copy
__SINIC_REG32(RxMaxIntr, 0x18); // 32: max receives per interrupt
__SINIC_REG32(Reserved0, 0x1c); // 32: reserved
__SINIC_REG32(RxFifoSize, 0x20); // 32: rx fifo capacity in bytes
__SINIC_REG32(TxFifoSize, 0x24); // 32: tx fifo capacity in bytes
__SINIC_REG32(RxFifoMark, 0x28); // 32: rx fifo high watermark
__SINIC_REG32(TxFifoMark, 0x2c); // 32: tx fifo low watermark
__SINIC_REG32(RxData, 0x30); // 64: receive data
__SINIC_REG32(RxDone, 0x38); // 64: receive done
__SINIC_REG32(RxWait, 0x40); // 64: receive done (busy wait)
__SINIC_REG32(TxData, 0x48); // 64: transmit data
__SINIC_REG32(TxDone, 0x50); // 64: transmit done
__SINIC_REG32(TxWait, 0x58); // 64: transmit done (busy wait)
__SINIC_REG32(HwAddr, 0x60); // 64: mac address
__SINIC_REG32(Size, 0x68); // register addres space size
// Config register bits
__SINIC_VAL32(Config_RSS, 10, 1); // enable receive side scaling
__SINIC_VAL32(Config_RxThread, 9, 1); // enable receive threads
__SINIC_VAL32(Config_TxThread, 8, 1); // enable transmit thread
__SINIC_VAL32(Config_Filter, 7, 1); // enable receive filter
__SINIC_VAL32(Config_Vlan, 6, 1); // enable vlan tagging
__SINIC_VAL32(Config_Virtual, 5, 1); // enable virtual addressing
__SINIC_VAL32(Config_Desc, 4, 1); // enable tx/rx descriptors
__SINIC_VAL32(Config_Poll, 3, 1); // enable polling
__SINIC_VAL32(Config_IntEn, 2, 1); // enable interrupts
__SINIC_VAL32(Config_TxEn, 1, 1); // enable transmit
__SINIC_VAL32(Config_RxEn, 0, 1); // enable receive
// Command register bits
__SINIC_VAL32(Command_Intr, 1, 1); // software interrupt
__SINIC_VAL32(Command_Reset, 0, 1); // reset chip
// Interrupt register bits
__SINIC_VAL32(Intr_Soft, 8, 1); // software interrupt
__SINIC_VAL32(Intr_TxLow, 7, 1); // tx fifo dropped below watermark
__SINIC_VAL32(Intr_TxFull, 6, 1); // tx fifo full
__SINIC_VAL32(Intr_TxDMA, 5, 1); // tx dma completed w/ interrupt
__SINIC_VAL32(Intr_TxPacket, 4, 1); // packet transmitted
__SINIC_VAL32(Intr_RxHigh, 3, 1); // rx fifo above high watermark
__SINIC_VAL32(Intr_RxEmpty, 2, 1); // rx fifo empty
__SINIC_VAL32(Intr_RxDMA, 1, 1); // rx dma completed w/ interrupt
__SINIC_VAL32(Intr_RxPacket, 0, 1); // packet received
__SINIC_REG32(Intr_All, 0x01ff); // all valid interrupts
__SINIC_REG32(Intr_NoDelay, 0x01cc); // interrupts that aren't coalesced
__SINIC_REG32(Intr_Res, ~0x01ff); // reserved interrupt bits
// RX Data Description
__SINIC_VAL64(RxData_Len, 40, 20); // 0 - 1M
__SINIC_VAL64(RxData_Addr, 0, 40); // Address 1TB
// TX Data Description
__SINIC_VAL64(TxData_More, 63, 1); // Packet not complete (will dma more)
__SINIC_VAL64(TxData_Checksum, 62, 1); // do checksum
__SINIC_VAL64(TxData_Len, 40, 20); // 0 - 1M
__SINIC_VAL64(TxData_Addr, 0, 40); // Address 1TB
// RX Done/Busy Information
__SINIC_VAL64(RxDone_Packets, 32, 16); // number of packets in rx fifo
__SINIC_VAL64(RxDone_Busy, 31, 1); // receive dma busy copying
__SINIC_VAL64(RxDone_Complete, 30, 1); // valid data (packet complete)
__SINIC_VAL64(RxDone_More, 29, 1); // Packet has more data (dma again)
__SINIC_VAL64(RxDone_Res0, 28, 1); // reserved
__SINIC_VAL64(RxDone_Res1, 27, 1); // reserved
__SINIC_VAL64(RxDone_Res2, 26, 1); // reserved
__SINIC_VAL64(RxDone_TcpError, 25, 1); // TCP packet error (bad checksum)
__SINIC_VAL64(RxDone_UdpError, 24, 1); // UDP packet error (bad checksum)
__SINIC_VAL64(RxDone_IpError, 23, 1); // IP packet error (bad checksum)
__SINIC_VAL64(RxDone_TcpPacket, 22, 1); // this is a TCP packet
__SINIC_VAL64(RxDone_UdpPacket, 21, 1); // this is a UDP packet
__SINIC_VAL64(RxDone_IpPacket, 20, 1); // this is an IP packet
__SINIC_VAL64(RxDone_CopyLen, 0, 20); // up to 256k
// TX Done/Busy Information
__SINIC_VAL64(TxDone_Packets, 32, 16); // number of packets in tx fifo
__SINIC_VAL64(TxDone_Busy, 31, 1); // transmit dma busy copying
__SINIC_VAL64(TxDone_Complete, 30, 1); // valid data (packet complete)
__SINIC_VAL64(TxDone_Full, 29, 1); // tx fifo is full
__SINIC_VAL64(TxDone_Low, 28, 1); // tx fifo is below the watermark
__SINIC_VAL64(TxDone_Res0, 27, 1); // reserved
__SINIC_VAL64(TxDone_Res1, 26, 1); // reserved
__SINIC_VAL64(TxDone_Res2, 25, 1); // reserved
__SINIC_VAL64(TxDone_Res3, 24, 1); // reserved
__SINIC_VAL64(TxDone_Res4, 23, 1); // reserved
__SINIC_VAL64(TxDone_Res5, 22, 1); // reserved
__SINIC_VAL64(TxDone_Res6, 21, 1); // reserved
__SINIC_VAL64(TxDone_Res7, 20, 1); // reserved
__SINIC_VAL64(TxDone_CopyLen, 0, 20); // up to 256k
struct Info
{
uint8_t size;
bool read;
bool write;
const char *name;
};
/* namespace Regs */ }
inline const Regs::Info&
regInfo(Addr daddr)
{
static Regs::Info invalid = { 0, false, false, "invalid" };
static Regs::Info info [] = {
{ 4, true, true, "Config" },
{ 4, false, true, "Command" },
{ 4, true, true, "IntrStatus" },
{ 4, true, true, "IntrMask" },
{ 4, true, false, "RxMaxCopy" },
{ 4, true, false, "TxMaxCopy" },
{ 4, true, false, "RxMaxIntr" },
invalid,
{ 4, true, false, "RxFifoSize" },
{ 4, true, false, "TxFifoSize" },
{ 4, true, false, "RxFifoMark" },
{ 4, true, false, "TxFifoMark" },
{ 8, true, true, "RxData" },
invalid,
{ 8, true, false, "RxDone" },
invalid,
{ 8, true, false, "RxWait" },
invalid,
{ 8, true, true, "TxData" },
invalid,
{ 8, true, false, "TxDone" },
invalid,
{ 8, true, false, "TxWait" },
invalid,
{ 8, true, false, "HwAddr" },
invalid,
};
return info[daddr / 4];
}
inline bool
regValid(Addr daddr)
{
if (daddr > Regs::Size)
return false;
if (regInfo(daddr).size == 0)
return false;
return true;
}
/* namespace Sinic */ }
#endif // __DEV_SINICREG_HH__
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: linkmgr2.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-10-04 20:45:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "linkmgr.hxx"
#include <vcl/msgbox.hxx>
#include "lnkbase.hxx"
//#include "linksrc.hxx"
#include "impldde.hxx"
//#include "svuidlg.hrc"
//#include "iface.hxx"
#include "app.hrc"
#include "sfxresid.hxx"
#pragma hdrstop
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
namespace sfx2
{
SV_IMPL_PTRARR( SvBaseLinks, SvBaseLinkRefPtr )
SvLinkManager::SvLinkManager()
: pPersist( 0 )
{
}
SvLinkManager::~SvLinkManager()
{
SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
{
if( (*ppRef)->Is() )
{
(*(*ppRef))->Disconnect();
(*(*ppRef))->pLinkMgr = 0;
}
delete *ppRef;
}
}
/************************************************************************
|* SvLinkManager::Remove()
|*
|* Beschreibung
*************************************************************************/
void SvLinkManager::Remove( SvBaseLink *pLink )
{
// keine Links doppelt einfuegen
int bFound = FALSE;
SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
{
if( pLink == *(*ppRef) )
{
(*(*ppRef))->Disconnect();
(*(*ppRef))->pLinkMgr = 0;
(*(*ppRef)).Clear();
bFound = TRUE;
}
// falls noch leere rum stehen sollten, weg damit
if( !(*ppRef)->Is() )
{
delete *ppRef;
aLinkTbl.Remove( aLinkTbl.Count() - n, 1 );
if( bFound )
return ;
--ppRef;
}
}
}
void SvLinkManager::Remove( USHORT nPos, USHORT nCnt )
{
if( nCnt && nPos < aLinkTbl.Count() )
{
if( nPos + nCnt > aLinkTbl.Count() )
nCnt = aLinkTbl.Count() - nPos;
SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData() + nPos;
for( USHORT n = nCnt; n; --n, ++ppRef )
{
if( (*ppRef)->Is() )
{
(*(*ppRef))->Disconnect();
(*(*ppRef))->pLinkMgr = 0;
}
delete *ppRef;
}
aLinkTbl.Remove( nPos, nCnt );
}
}
BOOL SvLinkManager::Insert( SvBaseLink* pLink )
{
// keine Links doppelt einfuegen
for( USHORT n = 0; n < aLinkTbl.Count(); ++n )
{
SvBaseLinkRef* pTmp = aLinkTbl[ n ];
if( !pTmp->Is() )
aLinkTbl.DeleteAndDestroy( n-- );
if( pLink == *pTmp )
return FALSE;
}
SvBaseLinkRef* pTmp = new SvBaseLinkRef( pLink );
pLink->pLinkMgr = this;
aLinkTbl.Insert( pTmp, aLinkTbl.Count() );
return TRUE;
}
BOOL SvLinkManager::InsertLink( SvBaseLink * pLink,
USHORT nObjType,
USHORT nUpdateMode,
const String* pName )
{
// unbedingt zuerst
pLink->SetObjType( nObjType );
if( pName )
pLink->SetName( *pName );
pLink->SetUpdateMode( nUpdateMode );
return Insert( pLink );
}
BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink,
const String& rServer,
const String& rTopic,
const String& rItem )
{
if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
return FALSE;
String sCmd;
::sfx2::MakeLnkName( sCmd, &rServer, rTopic, rItem );
pLink->SetObjType( OBJECT_CLIENT_DDE );
pLink->SetName( sCmd );
return Insert( pLink );
}
BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink )
{
DBG_ASSERT( OBJECT_CLIENT_SO & pLink->GetObjType(), "no OBJECT_CLIENT_SO" )
if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
return FALSE;
if( pLink->GetObjType() == OBJECT_CLIENT_SO )
pLink->SetObjType( OBJECT_CLIENT_DDE );
return Insert( pLink );
}
// erfrage die Strings fuer den Dialog
BOOL SvLinkManager::GetDisplayNames( const SvBaseLink * pLink,
String* pType,
String* pFile,
String* pLinkStr,
String* pFilter ) const
{
BOOL bRet = FALSE;
String aLN = pLink->GetLinkSourceName();
if( aLN.Len() != 0 && pLink->GetObjType() == OBJECT_CLIENT_DDE )
{
USHORT nTmp = 0;
String sCmd( aLN );
String sServer( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
String sTopic( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
if( pType )
*pType = sServer;
if( pFile )
*pFile = sTopic;
if( pLinkStr )
*pLinkStr = sCmd.Copy( nTmp );
bRet = TRUE;
}
return bRet;
}
void SvLinkManager::UpdateAllLinks( BOOL bAskUpdate, BOOL bCallErrHdl,
BOOL bUpdateGrfLinks, Window* pParentWin )
{
SvStringsDtor aApps, aTopics, aItems;
String sApp, sTopic, sItem;
// erstmal eine Kopie vom Array machen, damit sich updatende Links in
// Links in ... nicht dazwischen funken!!
SvPtrarr aTmpArr( 255, 50 );
USHORT n;
for( n = 0; n < aLinkTbl.Count(); ++n )
{
SvBaseLink* pLink = *aLinkTbl[ n ];
if( !pLink )
{
Remove( n-- );
continue;
}
aTmpArr.Insert( pLink, aTmpArr.Count() );
}
for( n = 0; n < aTmpArr.Count(); ++n )
{
SvBaseLink* pLink = (SvBaseLink*)aTmpArr[ n ];
// suche erstmal im Array nach dem Eintrag
USHORT nFndPos = USHRT_MAX;
for( USHORT i = 0; i < aLinkTbl.Count(); ++i )
if( pLink == *aLinkTbl[ i ] )
{
nFndPos = i;
break;
}
if( USHRT_MAX == nFndPos )
continue; // war noch nicht vorhanden!
// Graphic-Links noch nicht updaten
if( !pLink->IsVisible() ||
( !bUpdateGrfLinks && OBJECT_CLIENT_GRF == pLink->GetObjType() ))
continue;
if( bAskUpdate )
{
int nRet = QueryBox( pParentWin, WB_YES_NO | WB_DEF_YES, SfxResId( STR_QUERY_UPDATE_LINKS ) ).Execute();
if( RET_YES != nRet )
return ; // es soll nichts geupdatet werden
bAskUpdate = FALSE; // einmal reicht
}
pLink->Update();
}
}
/************************************************************************
|* SvBaseLink::CreateObject()
|*
|* Beschreibung
*************************************************************************/
SvLinkSourceRef SvLinkManager::CreateObj( SvBaseLink * pLink )
{
if( OBJECT_CLIENT_DDE == pLink->GetObjType() )
return new SvDDEObject();
return SvLinkSourceRef();
}
BOOL SvLinkManager::InsertServer( SvLinkSource* pObj )
{
// keine doppelt einfuegen
if( !pObj || USHRT_MAX != aServerTbl.GetPos( pObj ) )
return FALSE;
aServerTbl.Insert( pObj, aServerTbl.Count() );
return TRUE;
}
void SvLinkManager::RemoveServer( SvLinkSource* pObj )
{
USHORT nPos = aServerTbl.GetPos( pObj );
if( USHRT_MAX != nPos )
aServerTbl.Remove( nPos, 1 );
}
void MakeLnkName( String& rName, const String* pType, const String& rFile,
const String& rLink, const String* pFilter )
{
if( pType )
(rName = *pType).EraseLeadingChars().EraseTrailingChars() += cTokenSeperator;
else if( rName.Len() )
rName.Erase();
((rName += rFile).EraseLeadingChars().EraseTrailingChars() +=
cTokenSeperator ).EraseLeadingChars().EraseTrailingChars() += rLink;
if( pFilter )
((rName += cTokenSeperator ) += *pFilter).EraseLeadingChars().EraseTrailingChars();
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.434); FILE MERGED 2005/09/05 15:22:09 rt 1.2.434.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: linkmgr2.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:42:04 $
*
* 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 _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "linkmgr.hxx"
#include <vcl/msgbox.hxx>
#include "lnkbase.hxx"
//#include "linksrc.hxx"
#include "impldde.hxx"
//#include "svuidlg.hrc"
//#include "iface.hxx"
#include "app.hrc"
#include "sfxresid.hxx"
#pragma hdrstop
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
namespace sfx2
{
SV_IMPL_PTRARR( SvBaseLinks, SvBaseLinkRefPtr )
SvLinkManager::SvLinkManager()
: pPersist( 0 )
{
}
SvLinkManager::~SvLinkManager()
{
SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
{
if( (*ppRef)->Is() )
{
(*(*ppRef))->Disconnect();
(*(*ppRef))->pLinkMgr = 0;
}
delete *ppRef;
}
}
/************************************************************************
|* SvLinkManager::Remove()
|*
|* Beschreibung
*************************************************************************/
void SvLinkManager::Remove( SvBaseLink *pLink )
{
// keine Links doppelt einfuegen
int bFound = FALSE;
SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
{
if( pLink == *(*ppRef) )
{
(*(*ppRef))->Disconnect();
(*(*ppRef))->pLinkMgr = 0;
(*(*ppRef)).Clear();
bFound = TRUE;
}
// falls noch leere rum stehen sollten, weg damit
if( !(*ppRef)->Is() )
{
delete *ppRef;
aLinkTbl.Remove( aLinkTbl.Count() - n, 1 );
if( bFound )
return ;
--ppRef;
}
}
}
void SvLinkManager::Remove( USHORT nPos, USHORT nCnt )
{
if( nCnt && nPos < aLinkTbl.Count() )
{
if( nPos + nCnt > aLinkTbl.Count() )
nCnt = aLinkTbl.Count() - nPos;
SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData() + nPos;
for( USHORT n = nCnt; n; --n, ++ppRef )
{
if( (*ppRef)->Is() )
{
(*(*ppRef))->Disconnect();
(*(*ppRef))->pLinkMgr = 0;
}
delete *ppRef;
}
aLinkTbl.Remove( nPos, nCnt );
}
}
BOOL SvLinkManager::Insert( SvBaseLink* pLink )
{
// keine Links doppelt einfuegen
for( USHORT n = 0; n < aLinkTbl.Count(); ++n )
{
SvBaseLinkRef* pTmp = aLinkTbl[ n ];
if( !pTmp->Is() )
aLinkTbl.DeleteAndDestroy( n-- );
if( pLink == *pTmp )
return FALSE;
}
SvBaseLinkRef* pTmp = new SvBaseLinkRef( pLink );
pLink->pLinkMgr = this;
aLinkTbl.Insert( pTmp, aLinkTbl.Count() );
return TRUE;
}
BOOL SvLinkManager::InsertLink( SvBaseLink * pLink,
USHORT nObjType,
USHORT nUpdateMode,
const String* pName )
{
// unbedingt zuerst
pLink->SetObjType( nObjType );
if( pName )
pLink->SetName( *pName );
pLink->SetUpdateMode( nUpdateMode );
return Insert( pLink );
}
BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink,
const String& rServer,
const String& rTopic,
const String& rItem )
{
if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
return FALSE;
String sCmd;
::sfx2::MakeLnkName( sCmd, &rServer, rTopic, rItem );
pLink->SetObjType( OBJECT_CLIENT_DDE );
pLink->SetName( sCmd );
return Insert( pLink );
}
BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink )
{
DBG_ASSERT( OBJECT_CLIENT_SO & pLink->GetObjType(), "no OBJECT_CLIENT_SO" )
if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
return FALSE;
if( pLink->GetObjType() == OBJECT_CLIENT_SO )
pLink->SetObjType( OBJECT_CLIENT_DDE );
return Insert( pLink );
}
// erfrage die Strings fuer den Dialog
BOOL SvLinkManager::GetDisplayNames( const SvBaseLink * pLink,
String* pType,
String* pFile,
String* pLinkStr,
String* pFilter ) const
{
BOOL bRet = FALSE;
String aLN = pLink->GetLinkSourceName();
if( aLN.Len() != 0 && pLink->GetObjType() == OBJECT_CLIENT_DDE )
{
USHORT nTmp = 0;
String sCmd( aLN );
String sServer( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
String sTopic( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
if( pType )
*pType = sServer;
if( pFile )
*pFile = sTopic;
if( pLinkStr )
*pLinkStr = sCmd.Copy( nTmp );
bRet = TRUE;
}
return bRet;
}
void SvLinkManager::UpdateAllLinks( BOOL bAskUpdate, BOOL bCallErrHdl,
BOOL bUpdateGrfLinks, Window* pParentWin )
{
SvStringsDtor aApps, aTopics, aItems;
String sApp, sTopic, sItem;
// erstmal eine Kopie vom Array machen, damit sich updatende Links in
// Links in ... nicht dazwischen funken!!
SvPtrarr aTmpArr( 255, 50 );
USHORT n;
for( n = 0; n < aLinkTbl.Count(); ++n )
{
SvBaseLink* pLink = *aLinkTbl[ n ];
if( !pLink )
{
Remove( n-- );
continue;
}
aTmpArr.Insert( pLink, aTmpArr.Count() );
}
for( n = 0; n < aTmpArr.Count(); ++n )
{
SvBaseLink* pLink = (SvBaseLink*)aTmpArr[ n ];
// suche erstmal im Array nach dem Eintrag
USHORT nFndPos = USHRT_MAX;
for( USHORT i = 0; i < aLinkTbl.Count(); ++i )
if( pLink == *aLinkTbl[ i ] )
{
nFndPos = i;
break;
}
if( USHRT_MAX == nFndPos )
continue; // war noch nicht vorhanden!
// Graphic-Links noch nicht updaten
if( !pLink->IsVisible() ||
( !bUpdateGrfLinks && OBJECT_CLIENT_GRF == pLink->GetObjType() ))
continue;
if( bAskUpdate )
{
int nRet = QueryBox( pParentWin, WB_YES_NO | WB_DEF_YES, SfxResId( STR_QUERY_UPDATE_LINKS ) ).Execute();
if( RET_YES != nRet )
return ; // es soll nichts geupdatet werden
bAskUpdate = FALSE; // einmal reicht
}
pLink->Update();
}
}
/************************************************************************
|* SvBaseLink::CreateObject()
|*
|* Beschreibung
*************************************************************************/
SvLinkSourceRef SvLinkManager::CreateObj( SvBaseLink * pLink )
{
if( OBJECT_CLIENT_DDE == pLink->GetObjType() )
return new SvDDEObject();
return SvLinkSourceRef();
}
BOOL SvLinkManager::InsertServer( SvLinkSource* pObj )
{
// keine doppelt einfuegen
if( !pObj || USHRT_MAX != aServerTbl.GetPos( pObj ) )
return FALSE;
aServerTbl.Insert( pObj, aServerTbl.Count() );
return TRUE;
}
void SvLinkManager::RemoveServer( SvLinkSource* pObj )
{
USHORT nPos = aServerTbl.GetPos( pObj );
if( USHRT_MAX != nPos )
aServerTbl.Remove( nPos, 1 );
}
void MakeLnkName( String& rName, const String* pType, const String& rFile,
const String& rLink, const String* pFilter )
{
if( pType )
(rName = *pType).EraseLeadingChars().EraseTrailingChars() += cTokenSeperator;
else if( rName.Len() )
rName.Erase();
((rName += rFile).EraseLeadingChars().EraseTrailingChars() +=
cTokenSeperator ).EraseLeadingChars().EraseTrailingChars() += rLink;
if( pFilter )
((rName += cTokenSeperator ) += *pFilter).EraseLeadingChars().EraseTrailingChars();
}
}
<|endoftext|>
|
<commit_before>#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "floatMul.h"
#include "featureSupport.h"
#include <string>
#include <iostream>
#include <iomanip>
#ifdef HAVE_CUDA
// CUDA includes
#include <cuda_runtime.h>
#endif // HAVE_CUDA
cv::VideoCapture capture;
const char windowName[] = "demo";
const char header[] = "precision: ";
const char* imagePath[][2] = {
{ "defaultMaskHalf.png", "defaultMaskFloat.png"},
{ "lenaMaskHalf.png", "lenaMaskFloat.png"},
};
short *gainCuda = NULL;
float *gainFloatCuda = NULL;
unsigned char *imageCuda = NULL;
unsigned char *imageResult = NULL;
enum precision
{
precisionHalf,
precisionFloat,
};
enum device
{
useCpuSimd,
useGpu,
};
void computeStatistics(double time, char key)
{
const int cHistoryMax = 16;
static double history[cHistoryMax];
static double square [cHistoryMax];
static int iHistory = 0;
switch (key)
{
case 'h':
case 'H':
case 'f':
case 'F':
case 'c':
case 'C':
case 'g':
case 'G':
for (int i = 0; i < cHistoryMax; i++)
{
history[i] = 0.0f;
square[i] = 0.0f;
iHistory = 0;
}
break;
}
history[iHistory] = time;
square[iHistory] = time * time;
double sum = 0.0f;
double squareSum = 0.0f;
for (int i = 0; i < cHistoryMax; i++)
{
sum += history[i];
squareSum += square[i];
}
double average = sum / (double)cHistoryMax;
squareSum /= cHistoryMax;
double variance = squareSum - (average * average);
std::cout << "average: " << std::fixed << std::setprecision(3) << average * 1000.0f << "[ms] ";
std::cout << "stddev: " << std::fixed << std::setprecision(3) << sqrt(variance) * 1000.0f << "[ms] \r";
std::cout << std::flush;
iHistory++;
iHistory = iHistory & (cHistoryMax-1);
}
#ifdef HAVE_CUDA
extern "C" void
launchCudaProcessHalf(dim3 grid, dim3 block, int sbytes,
short *gain,
unsigned char *imageInput,
unsigned char *imageOutput,
int imgw);
extern "C" void
launchCudaProcessFloat(dim3 grid, dim3 block, int sbytes,
float *gain,
unsigned char *imageInput,
unsigned char *imageOutput,
int imgw);
double multiplyImageCuda(cv::Mat &image, cv::Mat gain)
{
unsigned int image_width = image.cols;
unsigned int image_height = image.rows;
cudaMemcpy(imageCuda, image.data, image_height*image_width*sizeof(char)*3, cudaMemcpyHostToDevice);
// calculate grid size
dim3 block(16, 16, 1);
dim3 grid(image_width / block.x, image_height / block.y, 1);
int64 begin, end;
switch (gain.elemSize())
{
case 2:
begin = cv::getTickCount();
cudaMemcpy(gainCuda, gain.data, image_height*image_width*sizeof(short), cudaMemcpyHostToDevice);
end = cv::getTickCount();
launchCudaProcessHalf(grid, block, 0, gainCuda, imageCuda, imageResult, image_width);
break;
case 4:
begin = cv::getTickCount();
cudaMemcpy(gainFloatCuda, gain.data, image_height*image_width*sizeof(float), cudaMemcpyHostToDevice);
end = cv::getTickCount();
launchCudaProcessFloat(grid, block, 0, gainFloatCuda, imageCuda, imageResult, image_width);
break;
}
cudaMemcpy(image.data, imageResult, image_height*image_width*sizeof(char)*3, cudaMemcpyDeviceToHost);
double tickCountElapsed = double(end - begin);
return tickCountElapsed/(double)cv::getTickFrequency();
}
#endif // HAVE_CUDA
double multiplyImage(cv::Mat &image, cv::Mat gain)
{
cv::Mat stub, b, g, r;
std::vector<cv::Mat> arrayColor;
arrayColor.push_back(b);
arrayColor.push_back(g);
arrayColor.push_back(r);
cv::split(image, arrayColor);
int64 begin, end;
begin = cv::getTickCount();
switch (gain.elemSize())
{
case 2:
for (unsigned int i = 0; i < arrayColor.size(); i++)
{
multiply(arrayColor[i].data, (short*)gain.data, arrayColor[i].data, arrayColor[i].rows*arrayColor[i].cols);
}
break;
case 4:
default:
for (unsigned int i = 0; i < arrayColor.size(); i++)
{
arrayColor[i].convertTo(stub, CV_32FC1);
multiply(stub, gain, arrayColor[i], 1.0, CV_8UC1);
}
break;
}
end = cv::getTickCount();
cv::merge(arrayColor, image);
double tickCountElapsed = double(end - begin);
return tickCountElapsed/(double)cv::getTickFrequency();
}
bool isFinish(char key)
{
bool finishKey = false;
switch (key)
{
case 'q':
case 'Q':
case 27: // ESC key
finishKey = true;
default:
break;
}
return finishKey;
}
#ifdef HAVE_CUDA
void initArray(cv::Mat &image)
{
unsigned int w = image.cols;
unsigned int h = image.rows;
unsigned int s = w * h;
cudaMalloc((short**)&gainCuda, (s*sizeof(short)));
cudaMalloc((float**)&gainFloatCuda, (s*sizeof(float)));
cudaMalloc((unsigned char**)&imageCuda, (s*sizeof(unsigned char)*3));
cudaMalloc((unsigned char**)&imageResult, (s*sizeof(unsigned char)*3));
}
void releaseArray()
{
cudaFree((void*)gainCuda);
cudaFree((void*)gainFloatCuda);
cudaFree((void*)imageCuda);
cudaFree((void*)imageResult);
}
bool initCuda()
{
int devID = 0;
int device_count= 0;
cudaGetDeviceCount(&device_count);
if (device_count < 1)
{
return false;
}
cudaSetDevice(devID);
return true;
}
#else
void initArray(cv::Mat &image){}
void releaseArray(){}
bool initCuda(){ return false; }
#endif // HAVE_CUDA
int main(int argc, char**argv)
{
capture.open(0);
cv::Mat image;
capture >> image;
cv::namedWindow(windowName);
cv::imshow(windowName, image);
initCuda();
initArray(image);
char key = -1;
enum device statusDevice = useCpuSimd;
enum precision statusPrecision = precisionFloat;
int index = 1;
cv::Mat stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
cv::Mat gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
double elapsedTime;
while (isFinish(key) == false)
{
capture >> image;
switch (key)
{
case 'h':
case 'H':
// switch to half precision
statusPrecision = precisionHalf;
std::cout << std::endl << header << "half " << std::endl;
stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
break;
case 'f':
case 'F':
// switch to single precision
statusPrecision = precisionFloat;
std::cout << std::endl << header << "single" << std::endl;
stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
break;
case '0':
case '1':
index = key - '0';
if (statusPrecision == precisionHalf)
{
// precision half
stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
}
else
{
// precision single
stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
}
break;
case 'c':
case 'C':
std::cout << std::endl << "Using CPU SIMD " << std::endl;
statusDevice = useCpuSimd;
break;
case 'g':
case 'G':
std::cout << std::endl << "Using GPU " << std::endl;
statusDevice = useGpu;
break;
default:
break;
}
if (statusDevice == useCpuSimd)
{
elapsedTime = multiplyImage(image, gain);
}
else
{
#ifdef HAVE_CUDA
// CUDA
elapsedTime = multiplyImageCuda(image, gain);
#endif // HAVE_CUDA
}
computeStatistics(elapsedTime, key);
cv::imshow(windowName, image);
key = cv::waitKey(1);
}
std::cout << std::endl;
cv::destroyAllWindows();
releaseArray();
return 0;
}
<commit_msg>save image when 's' key pressed<commit_after>#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "floatMul.h"
#include "featureSupport.h"
#include <string>
#include <iostream>
#include <iomanip>
#ifdef HAVE_CUDA
// CUDA includes
#include <cuda_runtime.h>
#endif // HAVE_CUDA
cv::VideoCapture capture;
const char dumpFilename[] = "dump.png";
const char windowName[] = "demo";
const char header[] = "precision: ";
const char* imagePath[][2] = {
{ "defaultMaskHalf.png", "defaultMaskFloat.png"},
{ "lenaMaskHalf.png", "lenaMaskFloat.png"},
};
short *gainCuda = NULL;
float *gainFloatCuda = NULL;
unsigned char *imageCuda = NULL;
unsigned char *imageResult = NULL;
enum precision
{
precisionHalf,
precisionFloat,
};
enum device
{
useCpuSimd,
useGpu,
};
void computeStatistics(double time, char key)
{
const int cHistoryMax = 16;
static double history[cHistoryMax];
static double square [cHistoryMax];
static int iHistory = 0;
switch (key)
{
case 'h':
case 'H':
case 'f':
case 'F':
case 'c':
case 'C':
case 'g':
case 'G':
for (int i = 0; i < cHistoryMax; i++)
{
history[i] = 0.0f;
square[i] = 0.0f;
iHistory = 0;
}
break;
}
history[iHistory] = time;
square[iHistory] = time * time;
double sum = 0.0f;
double squareSum = 0.0f;
for (int i = 0; i < cHistoryMax; i++)
{
sum += history[i];
squareSum += square[i];
}
double average = sum / (double)cHistoryMax;
squareSum /= cHistoryMax;
double variance = squareSum - (average * average);
std::cout << "average: " << std::fixed << std::setprecision(3) << average * 1000.0f << "[ms] ";
std::cout << "stddev: " << std::fixed << std::setprecision(3) << sqrt(variance) * 1000.0f << "[ms] \r";
std::cout << std::flush;
iHistory++;
iHistory = iHistory & (cHistoryMax-1);
}
#ifdef HAVE_CUDA
extern "C" void
launchCudaProcessHalf(dim3 grid, dim3 block, int sbytes,
short *gain,
unsigned char *imageInput,
unsigned char *imageOutput,
int imgw);
extern "C" void
launchCudaProcessFloat(dim3 grid, dim3 block, int sbytes,
float *gain,
unsigned char *imageInput,
unsigned char *imageOutput,
int imgw);
double multiplyImageCuda(cv::Mat &image, cv::Mat gain)
{
unsigned int image_width = image.cols;
unsigned int image_height = image.rows;
cudaMemcpy(imageCuda, image.data, image_height*image_width*sizeof(char)*3, cudaMemcpyHostToDevice);
// calculate grid size
dim3 block(16, 16, 1);
dim3 grid(image_width / block.x, image_height / block.y, 1);
int64 begin, end;
switch (gain.elemSize())
{
case 2:
begin = cv::getTickCount();
cudaMemcpy(gainCuda, gain.data, image_height*image_width*sizeof(short), cudaMemcpyHostToDevice);
end = cv::getTickCount();
launchCudaProcessHalf(grid, block, 0, gainCuda, imageCuda, imageResult, image_width);
break;
case 4:
begin = cv::getTickCount();
cudaMemcpy(gainFloatCuda, gain.data, image_height*image_width*sizeof(float), cudaMemcpyHostToDevice);
end = cv::getTickCount();
launchCudaProcessFloat(grid, block, 0, gainFloatCuda, imageCuda, imageResult, image_width);
break;
}
cudaMemcpy(image.data, imageResult, image_height*image_width*sizeof(char)*3, cudaMemcpyDeviceToHost);
double tickCountElapsed = double(end - begin);
return tickCountElapsed/(double)cv::getTickFrequency();
}
#endif // HAVE_CUDA
double multiplyImage(cv::Mat &image, cv::Mat gain)
{
cv::Mat stub, b, g, r;
std::vector<cv::Mat> arrayColor;
arrayColor.push_back(b);
arrayColor.push_back(g);
arrayColor.push_back(r);
cv::split(image, arrayColor);
int64 begin, end;
begin = cv::getTickCount();
switch (gain.elemSize())
{
case 2:
for (unsigned int i = 0; i < arrayColor.size(); i++)
{
multiply(arrayColor[i].data, (short*)gain.data, arrayColor[i].data, arrayColor[i].rows*arrayColor[i].cols);
}
break;
case 4:
default:
for (unsigned int i = 0; i < arrayColor.size(); i++)
{
arrayColor[i].convertTo(stub, CV_32FC1);
multiply(stub, gain, arrayColor[i], 1.0, CV_8UC1);
}
break;
}
end = cv::getTickCount();
cv::merge(arrayColor, image);
double tickCountElapsed = double(end - begin);
return tickCountElapsed/(double)cv::getTickFrequency();
}
bool isFinish(char key)
{
bool finishKey = false;
switch (key)
{
case 'q':
case 'Q':
case 27: // ESC key
finishKey = true;
default:
break;
}
return finishKey;
}
#ifdef HAVE_CUDA
void initArray(cv::Mat &image)
{
unsigned int w = image.cols;
unsigned int h = image.rows;
unsigned int s = w * h;
cudaMalloc((short**)&gainCuda, (s*sizeof(short)));
cudaMalloc((float**)&gainFloatCuda, (s*sizeof(float)));
cudaMalloc((unsigned char**)&imageCuda, (s*sizeof(unsigned char)*3));
cudaMalloc((unsigned char**)&imageResult, (s*sizeof(unsigned char)*3));
}
void releaseArray()
{
cudaFree((void*)gainCuda);
cudaFree((void*)gainFloatCuda);
cudaFree((void*)imageCuda);
cudaFree((void*)imageResult);
}
bool initCuda()
{
int devID = 0;
int device_count= 0;
cudaGetDeviceCount(&device_count);
if (device_count < 1)
{
return false;
}
cudaSetDevice(devID);
return true;
}
#else
void initArray(cv::Mat &image){}
void releaseArray(){}
bool initCuda(){ return false; }
#endif // HAVE_CUDA
int main(int argc, char**argv)
{
capture.open(0);
cv::Mat image;
capture >> image;
cv::namedWindow(windowName);
cv::imshow(windowName, image);
initCuda();
initArray(image);
char key = -1;
enum device statusDevice = useCpuSimd;
enum precision statusPrecision = precisionFloat;
int index = 1;
cv::Mat stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
cv::Mat gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
double elapsedTime;
while (isFinish(key) == false)
{
capture >> image;
switch (key)
{
case 'h':
case 'H':
// switch to half precision
statusPrecision = precisionHalf;
std::cout << std::endl << header << "half " << std::endl;
stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
break;
case 'f':
case 'F':
// switch to single precision
statusPrecision = precisionFloat;
std::cout << std::endl << header << "single" << std::endl;
stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
break;
case '0':
case '1':
index = key - '0';
if (statusPrecision == precisionHalf)
{
// precision half
stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
}
else
{
// precision single
stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
}
break;
case 'c':
case 'C':
std::cout << std::endl << "Using CPU SIMD " << std::endl;
statusDevice = useCpuSimd;
break;
case 'g':
case 'G':
std::cout << std::endl << "Using GPU " << std::endl;
statusDevice = useGpu;
break;
default:
break;
}
if (statusDevice == useCpuSimd)
{
elapsedTime = multiplyImage(image, gain);
}
else
{
#ifdef HAVE_CUDA
// CUDA
elapsedTime = multiplyImageCuda(image, gain);
#endif // HAVE_CUDA
}
computeStatistics(elapsedTime, key);
if (key == 's' || key == 'S')
{
cv::imwrite(dumpFilename, image);
}
cv::imshow(windowName, image);
key = cv::waitKey(1);
}
std::cout << std::endl;
cv::destroyAllWindows();
releaseArray();
return 0;
}
<|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/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/site_instance.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_type.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class RenderViewHostManagerTest : public InProcessBrowserTest {
public:
RenderViewHostManagerTest() {
EnableDOMAutomation();
}
static bool GetFilePathWithHostAndPortReplacement(
const std::string& original_file_path,
const net::HostPortPair& host_port_pair,
std::string* replacement_path) {
std::vector<net::TestServer::StringPair> replacement_text;
replacement_text.push_back(
make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
return net::TestServer::GetFilePathWithReplacements(
original_file_path, replacement_text, replacement_path);
}
};
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
SwapProcessWithRelNoreferrerAndTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer + target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the tab to open.
if (browser()->tab_count() < 2)
ui_test_utils::WaitForNewTab(browser());
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Wait for the cross-site transition in the new tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()->
pending_render_view_host());
// Should have a new SiteInstance.
scoped_refptr<SiteInstance> noref_blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the tab to open.
if (browser()->tab_count() < 2)
ui_test_utils::WaitForNewTab(browser());
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
// Wait for the cross-site transition in the new tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyRelNoreferrer) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition in the current tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
// Started failing on Linux and Mac too, http://crbug.com/77762.
#define MAYBE_ChromeURLAfterDownload FLAKY_ChromeURLAfterDownload
#endif // defined(OS_WIN)
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
MAYBE_ChromeURLAfterDownload) {
GURL downloads_url("chrome://downloads");
GURL extensions_url("chrome://extensions");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool webui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.webui_responded_);",
&webui_responded));
EXPECT_TRUE(webui_responded);
}
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
private:
NotificationRegistrar registrar_;
};
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url("chrome://downloads");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
ASSERT_TRUE(file_util::PathExists(zip_download));
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
browser()->CloseWindow();
BrowserClosedObserver wait_for_close(browser());
}
// Test for crbug.com/76666. A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
// The links will point to the HTTPS server.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Load a cross-site page that fails with a 204 error.
ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent"));
// We should still be looking at the normal page.
scoped_refptr<SiteInstance> post_nav_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, post_nav_site_instance);
EXPECT_EQ("/files/click-noreferrer-links.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Renderer-initiated navigations should work.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition in the current tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
<commit_msg>Revert 79680 - Mark ChromeURLAfterDownload as flaky.<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/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/site_instance.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_type.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class RenderViewHostManagerTest : public InProcessBrowserTest {
public:
RenderViewHostManagerTest() {
EnableDOMAutomation();
}
static bool GetFilePathWithHostAndPortReplacement(
const std::string& original_file_path,
const net::HostPortPair& host_port_pair,
std::string* replacement_path) {
std::vector<net::TestServer::StringPair> replacement_text;
replacement_text.push_back(
make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
return net::TestServer::GetFilePathWithReplacements(
original_file_path, replacement_text, replacement_path);
}
};
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
SwapProcessWithRelNoreferrerAndTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer + target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the tab to open.
if (browser()->tab_count() < 2)
ui_test_utils::WaitForNewTab(browser());
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Wait for the cross-site transition in the new tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()->
pending_render_view_host());
// Should have a new SiteInstance.
scoped_refptr<SiteInstance> noref_blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the tab to open.
if (browser()->tab_count() < 2)
ui_test_utils::WaitForNewTab(browser());
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
// Wait for the cross-site transition in the new tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyRelNoreferrer) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition in the current tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#define MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif // defined(OS_WIN)
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
MAYBE_ChromeURLAfterDownload) {
GURL downloads_url("chrome://downloads");
GURL extensions_url("chrome://extensions");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool webui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.webui_responded_);",
&webui_responded));
EXPECT_TRUE(webui_responded);
}
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
private:
NotificationRegistrar registrar_;
};
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url("chrome://downloads");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
ASSERT_TRUE(file_util::PathExists(zip_download));
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
browser()->CloseWindow();
BrowserClosedObserver wait_for_close(browser());
}
// Test for crbug.com/76666. A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server.Start());
// Load a page with links that open in a new window.
// The links will point to the HTTPS server.
std::string replacement_path;
ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
"files/click-noreferrer-links.html",
https_server.host_port_pair(),
&replacement_path));
ui_test_utils::NavigateToURL(browser(),
test_server()->GetURL(replacement_path));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Load a cross-site page that fails with a 204 error.
ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent"));
// We should still be looking at the normal page.
scoped_refptr<SiteInstance> post_nav_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, post_nav_site_instance);
EXPECT_EQ("/files/click-noreferrer-links.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Renderer-initiated navigations should work.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition in the current tab to finish.
ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ("/files/title2.html",
browser()->GetSelectedTabContents()->GetURL().path());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
<|endoftext|>
|
<commit_before><commit_msg>SetFmtItemByAutoFmt/SetTxtFmtCollByAutoFmt called with SwTxtNode<commit_after><|endoftext|>
|
<commit_before>#include "lrate.h"
#include "tensor/momentum.h"
#include "text/json_writer.h"
#include "solver_stoch_adam.h"
using namespace nano;
solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0) const
{
const auto beta1s = make_finite_space(scalar_t(0.900));
const auto beta2s = make_finite_space(scalar_t(0.999));
return tune(this, param, function, x0, make_alpha0s(), make_decays(), make_epsilons(), beta1s, beta2s);
}
solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0,
const scalar_t alpha0, const scalar_t decay, const scalar_t epsilon, const scalar_t beta1, const scalar_t beta2)
{
// learning rate schedule
lrate_t lrate(alpha0, decay);
// first-order momentum of the gradient
momentum_t<vector_t> m(beta1, x0.size());
// second-order momentum of the gradient
momentum_t<vector_t> v(beta2, x0.size());
// assembly the solver
const auto solver = [&] (solver_state_t& cstate, const solver_state_t&)
{
// learning rate
const scalar_t alpha = lrate.get();
// descent direction
m.update(cstate.g);
v.update(cstate.g.array().square());
cstate.d = -m.value().array() / (epsilon + v.value().array().sqrt());
// update solution
function.stoch_next();
cstate.stoch_update(function, alpha);
};
const auto snapshot = [&] (const solver_state_t& cstate, solver_state_t& sstate)
{
sstate.update(function, cstate.x);
};
return loop(param, function, x0, solver, snapshot,
json_writer_t().object("alpha0", alpha0, "decay", decay, "epsilon", epsilon, "beta1", beta1, "beta2", beta2).str());
}
<commit_msg>use decay=0.50 for adam (like in the paper)<commit_after>#include "lrate.h"
#include "tensor/momentum.h"
#include "text/json_writer.h"
#include "solver_stoch_adam.h"
using namespace nano;
solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0) const
{
const auto decays = make_finite_space(scalar_t(0.500));
const auto beta1s = make_finite_space(scalar_t(0.900));
const auto beta2s = make_finite_space(scalar_t(0.999));
return tune(this, param, function, x0, make_alpha0s(), decays, make_epsilons(), beta1s, beta2s);
}
solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0,
const scalar_t alpha0, const scalar_t decay, const scalar_t epsilon, const scalar_t beta1, const scalar_t beta2)
{
// learning rate schedule
lrate_t lrate(alpha0, decay);
// first-order momentum of the gradient
momentum_t<vector_t> m(beta1, x0.size());
// second-order momentum of the gradient
momentum_t<vector_t> v(beta2, x0.size());
// assembly the solver
const auto solver = [&] (solver_state_t& cstate, const solver_state_t&)
{
// learning rate
const scalar_t alpha = lrate.get();
// descent direction
m.update(cstate.g);
v.update(cstate.g.array().square());
cstate.d = -m.value().array() / (epsilon + v.value().array().sqrt());
// update solution
function.stoch_next();
cstate.stoch_update(function, alpha);
};
const auto snapshot = [&] (const solver_state_t& cstate, solver_state_t& sstate)
{
sstate.update(function, cstate.x);
};
return loop(param, function, x0, solver, snapshot,
json_writer_t().object("alpha0", alpha0, "decay", decay, "epsilon", epsilon, "beta1", beta1, "beta2", beta2).str());
}
<|endoftext|>
|
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "websearch_api_compat.h"
#include "cgi.h"
#include "urlmatch.h"
#include "mrf.h"
using namespace sp;
using lsh::mrf;
namespace seeks_plugins
{
websearch_api_compat::websearch_api_compat()
: plugin()
{
_name = "websearch-api-compat";
_version_major = "0";
_version_minor = "3";
// cgi_dispatchers.
cgi_dispatcher *cgid_wb_search
= new cgi_dispatcher("search", &websearch_api_compat::cgi_search_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_search);
cgi_dispatcher *cgid_wb_search_cache
= new cgi_dispatcher("search_cache", &websearch_api_compat::cgi_search_cache_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_search_cache);
cgi_dispatcher *cgid_wb_qc_redir
= new cgi_dispatcher("qc_redir",&websearch_api_compat::cgi_qc_redir_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_qc_redir);
cgi_dispatcher *cgid_wb_tbd
= new cgi_dispatcher("tbd",&websearch_api_compat::cgi_tbd_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_tbd);
}
websearch_api_compat::~websearch_api_compat()
{
}
sp_err websearch_api_compat::cgi_search_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
// check for action.
const char *action = miscutil::lookup(parameters,"action");
if (!action || strcasecmp(action,"expand")==0
|| strcasecmp(action,"page")==0)
{
// route to /search/txt
free(csp->_http._path);
std::string path = "/search/txt/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_search(csp,rsp,parameters);
}
else if (strcasecmp(action,"types")==0)
{
// route to /cluster/types
free(csp->_http._path);
std::string path = "/cluster/types/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_clustered_types(csp,rsp,parameters);
}
else if (strcasecmp(action,"clusterize")==0)
{
// route to /cluster/auto
free(csp->_http._path);
std::string path = "/cluster/auto/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_clusterize(csp,rsp,parameters);
}
else if (strcasecmp(action,"similarity")==0)
{
// route to /similar/txt
free(csp->_http._path);
std::string path = "/similar/txt/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_similarity(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
else return SP_ERR_CGI_PARAMS;
}
sp_err websearch_api_compat::cgi_search_cache_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
// check for url.
const char *url_str = miscutil::lookup(parameters,"url");
if (!url_str)
return SP_ERR_CGI_PARAMS;
std::string url = url_str;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string surl = urlmatch::strip_url(url);
uint32_t id = mrf::mrf_single_feature(surl);
std::string sid = miscutil::to_string(id);
// route to /cache
free(csp->_http._path);
std::string path = "/cache/txt/" + query + "/" + sid;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_search_cache(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
sp_err websearch_api_compat::cgi_qc_redir_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
// redirection.
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>\
(parameters),"redirect",1,"1",1);
// check for url.
const char *url_str = miscutil::lookup(parameters,"url");
if (!url_str)
return SP_ERR_CGI_PARAMS;
std::string url = url_str;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string surl = urlmatch::strip_url(url);
uint32_t id = mrf::mrf_single_feature(surl);
std::string sid = miscutil::to_string(id);
// route to POST /search/txt
free(csp->_http._path);
std::string path = "/search/txt/" + query + "/" + sid;
csp->_http._path = strdup(path.c_str());
free(csp->_http._gpc);
csp->_http._gpc = strdup("post");
return websearch::cgi_websearch_search(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
sp_err websearch_api_compat::cgi_tbd_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
// check for url.
const char *url_str = miscutil::lookup(parameters,"url");
if (!url_str)
return SP_ERR_CGI_PARAMS;
std::string url = url_str;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string surl = urlmatch::strip_url(url);
uint32_t id = mrf::mrf_single_feature(surl);
std::string sid = miscutil::to_string(id);
// route to DELETE /search/txt
free(csp->_http._path);
std::string path = "/search/txt/" + query + "/" + sid;
csp->_http._path = strdup(path.c_str());
free(csp->_http._gpc);
csp->_http._gpc = strdup("delete");
sp_err err = websearch::cgi_websearch_search(csp,rsp,parameters);
if (err != SP_ERR_OK)
return err;
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"action",1,"expand",1);
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"output",1,"html",1);
//return websearch_api_compat::cgi_search_compat(csp,rsp,parameters);
free(csp->_http._gpc);
csp->_http._gpc = strdup("get");
free(csp->_http._path);
path = "/search/txt/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_search(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
/* plugin registration */
extern "C"
{
plugin* maker()
{
return new websearch_api_compat;
}
}
} /* end of namespace. */
<commit_msg>fixed leak in websearch API compatibility plugin<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "websearch_api_compat.h"
#include "cgi.h"
#include "urlmatch.h"
#include "mrf.h"
using namespace sp;
using lsh::mrf;
namespace seeks_plugins
{
websearch_api_compat::websearch_api_compat()
: plugin()
{
_name = "websearch-api-compat";
_version_major = "0";
_version_minor = "3";
// cgi_dispatchers.
cgi_dispatcher *cgid_wb_search
= new cgi_dispatcher("search", &websearch_api_compat::cgi_search_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_search);
cgi_dispatcher *cgid_wb_search_cache
= new cgi_dispatcher("search_cache", &websearch_api_compat::cgi_search_cache_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_search_cache);
cgi_dispatcher *cgid_wb_qc_redir
= new cgi_dispatcher("qc_redir",&websearch_api_compat::cgi_qc_redir_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_qc_redir);
cgi_dispatcher *cgid_wb_tbd
= new cgi_dispatcher("tbd",&websearch_api_compat::cgi_tbd_compat, NULL, TRUE);
_cgi_dispatchers.push_back(cgid_wb_tbd);
}
websearch_api_compat::~websearch_api_compat()
{
}
sp_err websearch_api_compat::cgi_search_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");
// check for action.
const char *action = miscutil::lookup(parameters,"action");
if (!action || strcasecmp(action,"expand")==0
|| strcasecmp(action,"page")==0)
{
// route to /search/txt
free(csp->_http._path);
std::string path = "/search/txt/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_search(csp,rsp,parameters);
}
else if (strcasecmp(action,"types")==0)
{
// route to /cluster/types
free(csp->_http._path);
std::string path = "/cluster/types/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_clustered_types(csp,rsp,parameters);
}
else if (strcasecmp(action,"clusterize")==0)
{
// route to /cluster/auto
free(csp->_http._path);
std::string path = "/cluster/auto/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_clusterize(csp,rsp,parameters);
}
else if (strcasecmp(action,"similarity")==0)
{
// route to /similar/txt
free(csp->_http._path);
std::string path = "/similar/txt/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_similarity(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
else return SP_ERR_CGI_PARAMS;
}
sp_err websearch_api_compat::cgi_search_cache_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");
// check for url.
const char *url_str = miscutil::lookup(parameters,"url");
if (!url_str)
return SP_ERR_CGI_PARAMS;
std::string url = url_str;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string surl = urlmatch::strip_url(url);
uint32_t id = mrf::mrf_single_feature(surl);
std::string sid = miscutil::to_string(id);
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
// route to /cache
free(csp->_http._path);
std::string path = "/cache/txt/" + query + "/" + sid;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_search_cache(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
sp_err websearch_api_compat::cgi_qc_redir_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");
// redirection.
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>\
(parameters),"redirect",1,"1",1);
// check for url.
const char *url_str = miscutil::lookup(parameters,"url");
if (!url_str)
return SP_ERR_CGI_PARAMS;
std::string url = url_str;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string surl = urlmatch::strip_url(url);
uint32_t id = mrf::mrf_single_feature(surl);
std::string sid = miscutil::to_string(id);
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
// route to POST /search/txt
free(csp->_http._path);
std::string path = "/search/txt/" + query + "/" + sid;
csp->_http._path = strdup(path.c_str());
free(csp->_http._gpc);
csp->_http._gpc = strdup("post");
return websearch::cgi_websearch_search(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
sp_err websearch_api_compat::cgi_tbd_compat(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
if (!parameters->empty())
{
// check for query.
const char *query_str = miscutil::lookup(parameters,"q");
if (!query_str || strlen(query_str) == 0)
return SP_ERR_CGI_PARAMS;
std::string query = query_str;
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");
// check for url.
const char *url_str = miscutil::lookup(parameters,"url");
if (!url_str)
return SP_ERR_CGI_PARAMS;
std::string url = url_str;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string surl = urlmatch::strip_url(url);
uint32_t id = mrf::mrf_single_feature(surl);
std::string sid = miscutil::to_string(id);
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
// route to DELETE /search/txt
free(csp->_http._path);
std::string path = "/search/txt/" + query + "/" + sid;
csp->_http._path = strdup(path.c_str());
free(csp->_http._gpc);
csp->_http._gpc = strdup("delete");
sp_err err = websearch::cgi_websearch_search(csp,rsp,parameters);
if (err != SP_ERR_OK)
return err;
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"action",1,"expand",1);
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"output",1,"html",1);
//return websearch_api_compat::cgi_search_compat(csp,rsp,parameters);
free(csp->_http._gpc);
csp->_http._gpc = strdup("get");
free(csp->_http._path);
path = "/search/txt/" + query;
csp->_http._path = strdup(path.c_str());
return websearch::cgi_websearch_search(csp,rsp,parameters);
}
else return SP_ERR_CGI_PARAMS;
}
/* plugin registration */
extern "C"
{
plugin* maker()
{
return new websearch_api_compat;
}
}
} /* end of namespace. */
<|endoftext|>
|
<commit_before>#include "Bullet.h"
#include <math.h>
using namespace tdr;
void tdr::Bullet::update() {
if (useRadial) {
int32_t nxs, nxy;
sincos(angle, nxs, nxy);
xs = multiply1616By230(speed, nxs);
ys = multiply1616By230(speed, nxs);
} else {
rectp(xs, ys, speed, angle);
}
hitbox.c.x += xs;
hitbox.c.y += ys;
xs += xa;
ys += ya;
if (delay != 0) --delay;
if (!detachVisualAndMovementAngles) visualAngle = angle;
refreshGraze();
}
bool tdr::Bullet::graze() {
if (timeToNextGraze != 0 || grazeFrequency == -1) return false;
timeToNextGraze = grazeFrequency == 0 ? -1 : grazeFrequency - 1;
return true;
}
void tdr::Bullet::refreshGraze() {
if (timeToNextGraze != 0 && grazeFrequency != -1) --timeToNextGraze;
}
const char* tdr::BL_VERTEX_SOURCE = "\
#version 330 core \n\
layout (location = 0) in vec2 bounds; \n\
layout (location = 1) in vec2 position; \n\
layout (location = 2) in vec3 awl; \n\
layout (location = 3) in vec4 shottc; \n\
out vec2 texCoord; \n\
uniform vec2 texDimensions; \n\
uniform vec2 screenDimensions; \n\
\n\
void main() { \n\
texCoord = vec2(mix(shottc.x, shottc.z, bounds.x), mix(shottc.y, shottc.w, bounds.y)) / texDimensions; \n\
float angle = awl.x * 2 * 3.14159265358979323; \n\
mat2 rm = mat2(cos(angle), -sin(angle), sin(angle), cos(angle)); \n\
vec2 pos = position / screenDimensions + rm * ((bounds * vec2(2.0f, 2.0f) - vec2(1.0f, 1.0f)) * awl.zy); \n\
gl_Position = vec4(position * vec2(2.0f, -2.0f) + vec2(-1.0f, 1.0f), 1.0f, 1.0f); \n\
} \
";
const char* tdr::BL_FRAGMENT_SOURCE = "\
#version 330 core \n\
in vec2 texCoord; \n\
out vec4 color; \n\
uniform sampler2D tex; \n\
\n\
void main() { \n\
color = texture(tex, texCoord); \n\
} \
";
void tdr::BulletList::setUp() {
if (p == nullptr)
throw "What, are you crazy?!";
agl::Shader vertex(BL_VERTEX_SOURCE, GL_VERTEX_SHADER);
agl::Shader fragment(BL_FRAGMENT_SOURCE, GL_FRAGMENT_SHADER);
program.attach(vertex);
program.attach(fragment);
program.link();
hasInitializedProgram = true;
vao.setActive();
// Vertex data
vbo.feedData(sizeof(agl::rectangleVertices), (void*) agl::rectangleVertices, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*) 0);
// InstanceData
instanceVBO.setActive();
instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
// The shader needs to know about the following fields:
// hitbox.c.x hitbox.c.y
// visualAngle visualWidth visualLength
// texcoords
// So, without further ado:
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FIXED, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, hitbox.c.x));
glVertexAttribDivisor(1, 1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_UNSIGNED_INT, true, sizeof(Bullet), (GLvoid*) offsetof(Bullet, visualAngle));
glVertexAttribDivisor(2, 1);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_SHORT, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, texcoords));
glVertexAttribDivisor(3, 1);
agl::resetVBO();
agl::resetVAO();
}
void tdr::BulletList::setUniforms() {
if (hasSetUniforms) return;
vao.setActive();
program.use();
shotsheet.bindTo(0);
SETUNSP(program, 1i, "tex", 0);
SETUNSP2(program, 2f, "texDimensions", (GLfloat) shotsheet.getWidth(), (GLfloat) shotsheet.getHeight());
SETUNSP2(program, 2f, "screenDimensions", (GLfloat) p->width(), (GLfloat) p->height());
hasSetUniforms = true;
}
void tdr::BulletList::tick() {
p->getFBO().setActive();
glEnable(GL_BLEND);
agl::BM_ALPHA.use();
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
setUniforms();
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, bullets.size());
agl::resetVAO();
}
void tdr::BulletList::update() {
instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
}
void tdr::BulletList::_tearDown() {
}
bool tdr::BulletList::check(const Circle& h) {
for (Bullet& b : bullets) {
if (!b.collides) continue;
if (b.isLaser ?
doCirclesIntersect(b.hitbox.c, h) :
doCircleAndLineIntersect(h, b.hitbox.l))
return true;
}
return false;
}
bool tdr::BulletList::check(const Line& h) {
for (Bullet& b : bullets) {
if (!b.collides) continue;
if (b.isLaser ?
doCircleAndLineIntersect(b.hitbox.c, h) :
doLinesIntersect(h, b.hitbox.l))
return true;
}
return false;
}
void tdr::BulletList::updatePositions(const agl::IRect16& bounds) {
for (Bullet& b : bullets) {
b.update();
if (b.deleteWhenOutOfBounds && (
b.hitbox.c.x < bounds.left ||
b.hitbox.c.x > bounds.right ||
b.hitbox.c.y < bounds.top ||
b.hitbox.c.y > bounds.bottom))
b.markedForDeletion = 1;
}
// Remove marked bullets from list
unsigned int ahead = 0;
unsigned int behind = 0;
for (ahead = 0; ahead < bullets.size(); ++ahead) {
if (!bullets[ahead].markedForDeletion) {
if (ahead != behind) bullets[behind] = bullets[ahead];
++behind;
}
}
bullets.resize(behind);
}
void tdr::BulletList::insert(Bullet& b) {
b.id = highestID++;
bullets.push_back(b);
}
Bullet* tdr::BulletList::query(uint64_t id) {
unsigned int lower = 0, upper = bullets.size();
while (upper > lower + 1) { // v this avoids overflow
unsigned int middle = lower + ((upper - lower) >> 1);
uint64_t mid = bullets[middle].id;
if (mid == id) return bullets.data() + middle;
if (id < mid) upper = middle;
else lower = middle;
}
return bullets[lower].id == id ? bullets.data() + lower : nullptr;
}
void tdr::BulletList::graze(const Circle& h) {
for (Bullet& b : bullets) {
if (!b.collides) continue;
if (b.isLaser ?
doCirclesIntersect(b.hitbox.c, h) :
doCircleAndLineIntersect(h, b.hitbox.l))
b.graze();
}
}
<commit_msg>Correct shader code<commit_after>#include "Bullet.h"
#include <math.h>
using namespace tdr;
void tdr::Bullet::update() {
if (useRadial) {
int32_t nxs, nxy;
sincos(angle, nxs, nxy);
xs = multiply1616By230(speed, nxs);
ys = multiply1616By230(speed, nxs);
} else {
rectp(xs, ys, speed, angle);
}
hitbox.c.x += xs;
hitbox.c.y += ys;
xs += xa;
ys += ya;
if (delay != 0) --delay;
if (!detachVisualAndMovementAngles) visualAngle = angle;
refreshGraze();
}
bool tdr::Bullet::graze() {
if (timeToNextGraze != 0 || grazeFrequency == -1) return false;
timeToNextGraze = grazeFrequency == 0 ? -1 : grazeFrequency - 1;
return true;
}
void tdr::Bullet::refreshGraze() {
if (timeToNextGraze != 0 && grazeFrequency != -1) --timeToNextGraze;
}
const char* tdr::BL_VERTEX_SOURCE = "\
#version 330 core \n\
layout (location = 0) in vec2 bounds; \n\
layout (location = 1) in vec2 position; \n\
layout (location = 2) in vec3 awl; \n\
layout (location = 3) in vec4 shottc; \n\
out vec2 texCoord; \n\
uniform vec2 texDimensions; \n\
uniform vec2 screenDimensions; \n\
\n\
void main() { \n\
texCoord = vec2(mix(shottc.x, shottc.z, bounds.x), mix(shottc.y, shottc.w, bounds.y)) / texDimensions; \n\
float angle = awl.x * 2 * 3.14159265358979323 / 16384; \n\
mat2 rm = mat2(cos(angle), -sin(angle), sin(angle), cos(angle)); \n\
vec2 pos = position / screenDimensions + rm * ((bounds * vec2(2.0f, 2.0f) - vec2(1.0f, 1.0f)) * awl.zy); \n\
gl_Position = vec4(position * vec2(2.0f, -2.0f) + vec2(-1.0f, 1.0f), 1.0f, 1.0f); \n\
} \
";
const char* tdr::BL_FRAGMENT_SOURCE = "\
#version 330 core \n\
in vec2 texCoord; \n\
out vec4 color; \n\
uniform sampler2D tex; \n\
\n\
void main() { \n\
color = texture(tex, texCoord); \n\
} \
";
void tdr::BulletList::setUp() {
if (p == nullptr)
throw "What, are you crazy?!";
agl::Shader vertex(BL_VERTEX_SOURCE, GL_VERTEX_SHADER);
agl::Shader fragment(BL_FRAGMENT_SOURCE, GL_FRAGMENT_SHADER);
program.attach(vertex);
program.attach(fragment);
program.link();
hasInitializedProgram = true;
vao.setActive();
// Vertex data
vbo.feedData(sizeof(agl::rectangleVertices), (void*) agl::rectangleVertices, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*) 0);
// InstanceData
instanceVBO.setActive();
instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
// The shader needs to know about the following fields:
// hitbox.c.x hitbox.c.y
// visualAngle visualWidth visualLength
// texcoords
// So, without further ado:
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FIXED, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, hitbox.c.x));
glVertexAttribDivisor(1, 1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FIXED, true, sizeof(Bullet), (GLvoid*) offsetof(Bullet, visualAngle));
glVertexAttribDivisor(2, 1);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_SHORT, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, texcoords));
glVertexAttribDivisor(3, 1);
agl::resetVBO();
agl::resetVAO();
}
void tdr::BulletList::setUniforms() {
if (hasSetUniforms) return;
vao.setActive();
program.use();
shotsheet.bindTo(0);
SETUNSP(program, 1i, "tex", 0);
SETUNSP2(program, 2f, "texDimensions", (GLfloat) shotsheet.getWidth(), (GLfloat) shotsheet.getHeight());
SETUNSP2(program, 2f, "screenDimensions", (GLfloat) p->width(), (GLfloat) p->height());
hasSetUniforms = true;
}
void tdr::BulletList::tick() {
p->getFBO().setActive();
glEnable(GL_BLEND);
agl::BM_ALPHA.use();
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
setUniforms();
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, bullets.size());
agl::resetVAO();
}
void tdr::BulletList::update() {
instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
}
void tdr::BulletList::_tearDown() {
}
bool tdr::BulletList::check(const Circle& h) {
for (Bullet& b : bullets) {
if (!b.collides) continue;
if (b.isLaser ?
doCirclesIntersect(b.hitbox.c, h) :
doCircleAndLineIntersect(h, b.hitbox.l))
return true;
}
return false;
}
bool tdr::BulletList::check(const Line& h) {
for (Bullet& b : bullets) {
if (!b.collides) continue;
if (b.isLaser ?
doCircleAndLineIntersect(b.hitbox.c, h) :
doLinesIntersect(h, b.hitbox.l))
return true;
}
return false;
}
void tdr::BulletList::updatePositions(const agl::IRect16& bounds) {
for (Bullet& b : bullets) {
b.update();
if (b.deleteWhenOutOfBounds && (
b.hitbox.c.x < bounds.left ||
b.hitbox.c.x > bounds.right ||
b.hitbox.c.y < bounds.top ||
b.hitbox.c.y > bounds.bottom))
b.markedForDeletion = 1;
}
// Remove marked bullets from list
unsigned int ahead = 0;
unsigned int behind = 0;
for (ahead = 0; ahead < bullets.size(); ++ahead) {
if (!bullets[ahead].markedForDeletion) {
if (ahead != behind) bullets[behind] = bullets[ahead];
++behind;
}
}
bullets.resize(behind);
}
void tdr::BulletList::insert(Bullet& b) {
b.id = highestID++;
bullets.push_back(b);
}
Bullet* tdr::BulletList::query(uint64_t id) {
unsigned int lower = 0, upper = bullets.size();
while (upper > lower + 1) { // v this avoids overflow
unsigned int middle = lower + ((upper - lower) >> 1);
uint64_t mid = bullets[middle].id;
if (mid == id) return bullets.data() + middle;
if (id < mid) upper = middle;
else lower = middle;
}
return bullets[lower].id == id ? bullets.data() + lower : nullptr;
}
void tdr::BulletList::graze(const Circle& h) {
for (Bullet& b : bullets) {
if (!b.collides) continue;
if (b.isLaser ?
doCirclesIntersect(b.hitbox.c, h) :
doCircleAndLineIntersect(h, b.hitbox.l))
b.graze();
}
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#984422 unused pointer value<commit_after><|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.