text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for the Command Buffer Helper.
#include "base/at_exit.h"
#include "base/callback.h"
#include "base/message_loop.h"
#include "base/scoped_nsautorelease_pool.h"
#include "gpu/command_buffer/client/cmd_buffer_helper.h"
#include "gpu/command_buffer/service/mocks.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
using testing::Return;
using testing::Mock;
using testing::Truly;
using testing::Sequence;
using testing::DoAll;
using testing::Invoke;
using testing::_;
const int32 kNumCommandEntries = 10;
const int32 kCommandBufferSizeBytes =
kNumCommandEntries * sizeof(CommandBufferEntry);
// Test fixture for CommandBufferHelper test - Creates a CommandBufferHelper,
// using a CommandBufferEngine with a mock AsyncAPIInterface for its interface
// (calling it directly, not through the RPC mechanism).
class CommandBufferHelperTest : public testing::Test {
protected:
virtual void SetUp() {
api_mock_.reset(new AsyncAPIMock);
// ignore noops in the mock - we don't want to inspect the internals of the
// helper.
EXPECT_CALL(*api_mock_, DoCommand(0, _, _))
.WillRepeatedly(Return(error::kNoError));
command_buffer_.reset(new CommandBufferService);
command_buffer_->Initialize(kNumCommandEntries);
Buffer ring_buffer = command_buffer_->GetRingBuffer();
parser_ = new CommandParser(ring_buffer.ptr,
ring_buffer.size,
0,
ring_buffer.size,
0,
api_mock_.get());
scoped_refptr<GPUProcessor> gpu_processor(new GPUProcessor(
command_buffer_.get(), NULL, parser_, 1));
command_buffer_->SetPutOffsetChangeCallback(NewCallback(
gpu_processor.get(), &GPUProcessor::ProcessCommands));
api_mock_->set_engine(gpu_processor.get());
helper_.reset(new CommandBufferHelper(command_buffer_.get()));
helper_->Initialize();
}
virtual void TearDown() {
// If the GPUProcessor posts any tasks, this forces them to run.
MessageLoop::current()->RunAllPending();
helper_.release();
}
// Adds a command to the buffer through the helper, while adding it as an
// expected call on the API mock.
void AddCommandWithExpect(error::Error _return,
unsigned int command,
int arg_count,
CommandBufferEntry *args) {
CommandHeader header;
header.size = arg_count + 1;
header.command = command;
CommandBufferEntry* cmds = helper_->GetSpace(arg_count + 1);
CommandBufferOffset put = 0;
cmds[put++].value_header = header;
for (int ii = 0; ii < arg_count; ++ii) {
cmds[put++] = args[ii];
}
EXPECT_CALL(*api_mock_, DoCommand(command, arg_count,
Truly(AsyncAPIMock::IsArgs(arg_count, args))))
.InSequence(sequence_)
.WillOnce(Return(_return));
}
// Checks that the buffer from put to put+size is free in the parser.
void CheckFreeSpace(CommandBufferOffset put, unsigned int size) {
CommandBufferOffset parser_put = parser_->put();
CommandBufferOffset parser_get = parser_->get();
CommandBufferOffset limit = put + size;
if (parser_get > parser_put) {
// "busy" buffer wraps, so "free" buffer is between put (inclusive) and
// get (exclusive).
EXPECT_LE(parser_put, put);
EXPECT_GT(parser_get, limit);
} else {
// "busy" buffer does not wrap, so the "free" buffer is the top side (from
// put to the limit) and the bottom side (from 0 to get).
if (put >= parser_put) {
// we're on the top side, check we are below the limit.
EXPECT_GE(kNumCommandEntries, limit);
} else {
// we're on the bottom side, check we are below get.
EXPECT_GT(parser_get, limit);
}
}
}
int32 GetGetOffset() {
return command_buffer_->GetState().get_offset;
}
int32 GetPutOffset() {
return command_buffer_->GetState().put_offset;
}
error::Error GetError() {
return command_buffer_->GetState().error;
}
CommandBufferOffset get_helper_put() { return helper_->put_; }
base::ScopedNSAutoreleasePool autorelease_pool_;
base::AtExitManager at_exit_manager_;
MessageLoop message_loop_;
scoped_ptr<AsyncAPIMock> api_mock_;
scoped_ptr<CommandBufferService> command_buffer_;
CommandParser* parser_;
scoped_ptr<CommandBufferHelper> helper_;
Sequence sequence_;
};
// Checks that commands in the buffer are properly executed, and that the
// status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandProcessing) {
// Check initial state of the engine - it should have been configured by the
// helper.
EXPECT_TRUE(parser_ != NULL);
EXPECT_EQ(error::kNoError, GetError());
EXPECT_EQ(0, GetGetOffset());
// Add 3 commands through the helper
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
CommandBufferEntry args1[2];
args1[0].value_uint32 = 3;
args1[1].value_float = 4.f;
AddCommandWithExpect(error::kNoError, 2, 2, args1);
CommandBufferEntry args2[2];
args2[0].value_uint32 = 5;
args2[1].value_float = 6.f;
AddCommandWithExpect(error::kNoError, 3, 2, args2);
helper_->Flush();
// Check that the engine has work to do now.
EXPECT_FALSE(parser_->IsEmpty());
// Wait until it's done.
helper_->Finish();
// Check that the engine has no more work to do.
EXPECT_TRUE(parser_->IsEmpty());
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that commands in the buffer are properly executed when wrapping the
// buffer, and that the status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandWrapping) {
// Add 5 commands of size 3 through the helper to make sure we do wrap.
CommandBufferEntry args1[2];
args1[0].value_uint32 = 3;
args1[1].value_float = 4.f;
for (unsigned int i = 0; i < 5; ++i) {
AddCommandWithExpect(error::kNoError, i + 1, 2, args1);
}
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that asking for available entries work, and that the parser
// effectively won't use that space.
TEST_F(CommandBufferHelperTest, TestAvailableEntries) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add 2 commands through the helper - 8 entries
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
AddCommandWithExpect(error::kNoError, 2, 0, NULL);
AddCommandWithExpect(error::kNoError, 3, 2, args);
AddCommandWithExpect(error::kNoError, 4, 2, args);
// Ask for 5 entries.
helper_->WaitForAvailableEntries(5);
CommandBufferOffset put = get_helper_put();
CheckFreeSpace(put, 5);
// Add more commands.
AddCommandWithExpect(error::kNoError, 5, 2, args);
// Wait until everything is done done.
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that the InsertToken/WaitForToken work.
TEST_F(CommandBufferHelperTest, TestToken) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add a first command.
AddCommandWithExpect(error::kNoError, 3, 2, args);
// keep track of the buffer position.
CommandBufferOffset command1_put = get_helper_put();
int32 token = helper_->InsertToken();
EXPECT_CALL(*api_mock_.get(), DoCommand(cmd::kSetToken, 1, _))
.WillOnce(DoAll(Invoke(api_mock_.get(), &AsyncAPIMock::SetToken),
Return(error::kNoError)));
// Add another command.
AddCommandWithExpect(error::kNoError, 4, 2, args);
helper_->WaitForToken(token);
// check that the get pointer is beyond the first command.
EXPECT_LE(command1_put, GetGetOffset());
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
} // namespace gpu
<commit_msg>Add command buffer test for case where command inserted exactly matches the space left in the command buffer.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests for the Command Buffer Helper.
#include "base/at_exit.h"
#include "base/callback.h"
#include "base/message_loop.h"
#include "base/scoped_nsautorelease_pool.h"
#include "gpu/command_buffer/client/cmd_buffer_helper.h"
#include "gpu/command_buffer/service/mocks.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
using testing::Return;
using testing::Mock;
using testing::Truly;
using testing::Sequence;
using testing::DoAll;
using testing::Invoke;
using testing::_;
const int32 kNumCommandEntries = 10;
const int32 kCommandBufferSizeBytes =
kNumCommandEntries * sizeof(CommandBufferEntry);
// Test fixture for CommandBufferHelper test - Creates a CommandBufferHelper,
// using a CommandBufferEngine with a mock AsyncAPIInterface for its interface
// (calling it directly, not through the RPC mechanism).
class CommandBufferHelperTest : public testing::Test {
protected:
virtual void SetUp() {
api_mock_.reset(new AsyncAPIMock);
// ignore noops in the mock - we don't want to inspect the internals of the
// helper.
EXPECT_CALL(*api_mock_, DoCommand(0, _, _))
.WillRepeatedly(Return(error::kNoError));
command_buffer_.reset(new CommandBufferService);
command_buffer_->Initialize(kNumCommandEntries);
Buffer ring_buffer = command_buffer_->GetRingBuffer();
parser_ = new CommandParser(ring_buffer.ptr,
ring_buffer.size,
0,
ring_buffer.size,
0,
api_mock_.get());
scoped_refptr<GPUProcessor> gpu_processor(new GPUProcessor(
command_buffer_.get(), NULL, parser_, 1));
command_buffer_->SetPutOffsetChangeCallback(NewCallback(
gpu_processor.get(), &GPUProcessor::ProcessCommands));
api_mock_->set_engine(gpu_processor.get());
helper_.reset(new CommandBufferHelper(command_buffer_.get()));
helper_->Initialize();
}
virtual void TearDown() {
// If the GPUProcessor posts any tasks, this forces them to run.
MessageLoop::current()->RunAllPending();
helper_.release();
}
// Adds a command to the buffer through the helper, while adding it as an
// expected call on the API mock.
void AddCommandWithExpect(error::Error _return,
unsigned int command,
int arg_count,
CommandBufferEntry *args) {
CommandHeader header;
header.size = arg_count + 1;
header.command = command;
CommandBufferEntry* cmds = helper_->GetSpace(arg_count + 1);
CommandBufferOffset put = 0;
cmds[put++].value_header = header;
for (int ii = 0; ii < arg_count; ++ii) {
cmds[put++] = args[ii];
}
EXPECT_CALL(*api_mock_, DoCommand(command, arg_count,
Truly(AsyncAPIMock::IsArgs(arg_count, args))))
.InSequence(sequence_)
.WillOnce(Return(_return));
}
// Checks that the buffer from put to put+size is free in the parser.
void CheckFreeSpace(CommandBufferOffset put, unsigned int size) {
CommandBufferOffset parser_put = parser_->put();
CommandBufferOffset parser_get = parser_->get();
CommandBufferOffset limit = put + size;
if (parser_get > parser_put) {
// "busy" buffer wraps, so "free" buffer is between put (inclusive) and
// get (exclusive).
EXPECT_LE(parser_put, put);
EXPECT_GT(parser_get, limit);
} else {
// "busy" buffer does not wrap, so the "free" buffer is the top side (from
// put to the limit) and the bottom side (from 0 to get).
if (put >= parser_put) {
// we're on the top side, check we are below the limit.
EXPECT_GE(kNumCommandEntries, limit);
} else {
// we're on the bottom side, check we are below get.
EXPECT_GT(parser_get, limit);
}
}
}
int32 GetGetOffset() {
return command_buffer_->GetState().get_offset;
}
int32 GetPutOffset() {
return command_buffer_->GetState().put_offset;
}
error::Error GetError() {
return command_buffer_->GetState().error;
}
CommandBufferOffset get_helper_put() { return helper_->put_; }
base::ScopedNSAutoreleasePool autorelease_pool_;
base::AtExitManager at_exit_manager_;
MessageLoop message_loop_;
scoped_ptr<AsyncAPIMock> api_mock_;
scoped_ptr<CommandBufferService> command_buffer_;
CommandParser* parser_;
scoped_ptr<CommandBufferHelper> helper_;
Sequence sequence_;
};
// Checks that commands in the buffer are properly executed, and that the
// status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandProcessing) {
// Check initial state of the engine - it should have been configured by the
// helper.
EXPECT_TRUE(parser_ != NULL);
EXPECT_EQ(error::kNoError, GetError());
EXPECT_EQ(0, GetGetOffset());
// Add 3 commands through the helper
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
CommandBufferEntry args1[2];
args1[0].value_uint32 = 3;
args1[1].value_float = 4.f;
AddCommandWithExpect(error::kNoError, 2, 2, args1);
CommandBufferEntry args2[2];
args2[0].value_uint32 = 5;
args2[1].value_float = 6.f;
AddCommandWithExpect(error::kNoError, 3, 2, args2);
helper_->Flush();
// Check that the engine has work to do now.
EXPECT_FALSE(parser_->IsEmpty());
// Wait until it's done.
helper_->Finish();
// Check that the engine has no more work to do.
EXPECT_TRUE(parser_->IsEmpty());
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that commands in the buffer are properly executed when wrapping the
// buffer, and that the status/error stay valid.
TEST_F(CommandBufferHelperTest, TestCommandWrapping) {
// Add 5 commands of size 3 through the helper to make sure we do wrap.
CommandBufferEntry args1[2];
args1[0].value_uint32 = 5;
args1[1].value_float = 4.f;
for (unsigned int i = 0; i < 5; ++i) {
AddCommandWithExpect(error::kNoError, i + 1, 2, args1);
}
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks the case where the command inserted exactly matches the space left in
// the command buffer.
TEST_F(CommandBufferHelperTest, TestCommandWrappingExactMultiple) {
const int32 kCommandSize = 5;
const int32 kNumArgs = kCommandSize - 1;
COMPILE_ASSERT(kNumCommandEntries % kCommandSize == 0,
Not_multiple_of_num_command_entries);
CommandBufferEntry args1[kNumArgs];
for (size_t ii = 0; ii < kNumArgs; ++ii) {
args1[0].value_uint32 = ii + 1;
}
for (unsigned int i = 0; i < 5; ++i) {
AddCommandWithExpect(error::kNoError, i + 1, kNumArgs, args1);
}
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that asking for available entries work, and that the parser
// effectively won't use that space.
TEST_F(CommandBufferHelperTest, TestAvailableEntries) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add 2 commands through the helper - 8 entries
AddCommandWithExpect(error::kNoError, 1, 0, NULL);
AddCommandWithExpect(error::kNoError, 2, 0, NULL);
AddCommandWithExpect(error::kNoError, 3, 2, args);
AddCommandWithExpect(error::kNoError, 4, 2, args);
// Ask for 5 entries.
helper_->WaitForAvailableEntries(5);
CommandBufferOffset put = get_helper_put();
CheckFreeSpace(put, 5);
// Add more commands.
AddCommandWithExpect(error::kNoError, 5, 2, args);
// Wait until everything is done done.
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
// Checks that the InsertToken/WaitForToken work.
TEST_F(CommandBufferHelperTest, TestToken) {
CommandBufferEntry args[2];
args[0].value_uint32 = 3;
args[1].value_float = 4.f;
// Add a first command.
AddCommandWithExpect(error::kNoError, 3, 2, args);
// keep track of the buffer position.
CommandBufferOffset command1_put = get_helper_put();
int32 token = helper_->InsertToken();
EXPECT_CALL(*api_mock_.get(), DoCommand(cmd::kSetToken, 1, _))
.WillOnce(DoAll(Invoke(api_mock_.get(), &AsyncAPIMock::SetToken),
Return(error::kNoError)));
// Add another command.
AddCommandWithExpect(error::kNoError, 4, 2, args);
helper_->WaitForToken(token);
// check that the get pointer is beyond the first command.
EXPECT_LE(command1_put, GetGetOffset());
helper_->Finish();
// Check that the commands did happen.
Mock::VerifyAndClearExpectations(api_mock_.get());
// Check the error status.
EXPECT_EQ(error::kNoError, GetError());
}
} // namespace gpu
<|endoftext|> |
<commit_before>#include <dlfcn.h>
#include <cassert>
#include <fstream>
#include <zmq.hpp>
#include <quidpp.h>
#include <package.h>
#include <Python.h>
#include "common/util.h"
#include "ace/interface.h"
#include "protoc/processjob.pb.h"
#include "dirent.h"
#include "wal.h"
#include "exec.h"
#include "ace/config.h"
#include "ace/ipc.h"
void Execute::init(ControlClient *control, const std::string& _master) {
DIR *dir = nullptr;
struct dirent *ent = nullptr;
Execute& exec = Execute::getInstance();
exec.jobcontrol = control;
exec.master = _master;
return;
if ((dir = opendir(WALDIR)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
Wal::rollback(ent->d_name, [](const std::string & name, Execute::Parameter & param) {
/* Run procedure */
Execute::run(name, param);
/* Setup subjobs if any */
Execute::prospect(name);
});
}
closedir(dir);
}
}
void Execute::run(const std::string& name, Parameter& param) {
Wal *executionLog = new Wal(name, param);
Execute& exec = Execute::getInstance();
std::cout << "Running package " << name << std::endl;
/* Move worker in accept mode */
exec.jobcontrol->setStateAccepted();
/* Set members of shared object via callback */
exec.workerid = exec.jobcontrol->workerId();
exec.clusterjobs = exec.jobcontrol->clusterJobs();
exec.module = name;
exec.jobid = param.jobid;
exec.jobname = param.jobname;
exec.jobquid = param.jobquid;
exec.jobpartition = param.jobpartition;
exec.jobpartition_count = param.jobpartition_count;
exec.jobstate = param.jobstate;
exec.jobparent = param.jobparent;
/* Ensure package exist */
if (!file_exist(PKGDIR "/" + name)) {
exec.jobcontrol->setStateIdle();
std::cerr << "Package does not exist" << std::endl;
return;
}
//TODO: check if module directory already exist
/* Extract package in job directory */
if (package_extract((PKGDIR "/" + name).c_str(), ("cache/local/" + name).c_str())) {
exec.jobcontrol->setStateIdle();
std::cerr << "Cannot open package " << std::endl;
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::INIT);
wchar_t *program = Py_DecodeLocale("Chella Worker", NULL);
if (!program) {
std::cerr << "Cannot decode name" << std::endl;
return;
}
chdir((LOCALDIR "/" + name).c_str());
setenv("PYTHONPATH", ".", 1);
Py_SetProgramName(program);
Py_Initialize();
PyObject *pModuleJob = PyImport_ImportModule("job_example");
if (!pModuleJob) {
PyErr_Print();
return;
}
/* Initialize Ace modules */
PyObject *pMethodConfig = Ace::Config::PyAce_ModuleClass();
PyObject *pMethodCallback = Ace::IPC::PyAce_ModuleClass();
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::LOAD);
/* Create Ace config instance */
PyObject *pInstanceConfig = PyObject_CallObject(pMethodConfig, NULL);
if (!pInstanceConfig) {
PyErr_Print();
return;
}
/* Locate job init and call routine */
PyObject *pFuncJobInit = PyObject_GetAttrString(pModuleJob, "job_init");
if (!pFuncJobInit || !PyCallable_Check(pFuncJobInit)) {
PyErr_Print();
return;
}
PyObject *pArgsJobInit = Py_BuildValue("(O)", pInstanceConfig);
PyObject *pInstanceJobInit = PyObject_CallObject(pFuncJobInit, pArgsJobInit);
if (!pInstanceJobInit) {
PyErr_Print();
return;
}
PyObject *pFuncJobInvoke = PyObject_GetAttrString(pInstanceJobInit, "invoke");
if (!pFuncJobInvoke || !PyCallable_Check(pFuncJobInvoke)) {
PyErr_Print();
return;
}
/* Instantiate job class */
PyObject *pInstanceJob = PyObject_CallObject(pFuncJobInvoke, NULL);
if (!pInstanceJob) {
PyErr_Print();
return;
}
PyObject *pResult = NULL;
pResult = PyObject_CallMethod(pInstanceJob, "inject", "(Oisssii)", pMethodCallback,
exec.jobid,
exec.jobname.c_str(),
name.c_str(),
exec.jobquid.c_str(),
exec.jobpartition,
exec.jobpartition_count);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::INJECT);
pResult = PyObject_CallMethod(pInstanceJob, "setup_once", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::SETUP_ONCE);
pResult = PyObject_CallMethod(pInstanceJob, "setup", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::SETUP);
pResult = PyObject_CallMethod(pInstanceJob, "run", "(y#)", param.jobdata.data(), param.jobdata.size());
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::RUN);
pResult = PyObject_CallMethod(pInstanceJob, "teardown", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::TEARDOWN);
pResult = PyObject_CallMethod(pInstanceJob, "teardown_once", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::TEARDOWN_ONCE);
PyObject *pMemberChains = PyObject_GetAttrString(pInstanceJob, "chains");
if (!pMemberChains) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::PULLCHAIN);
Py_DECREF(pResult);
Py_DECREF(pMemberChains);
Py_DECREF(pInstanceJob);
Py_DECREF(pMethodCallback);
Py_DECREF(pMethodConfig);
Py_DECREF(pModuleJob);
/* Release resources allocated for this job */
Py_Finalize();
exec.sessionCleanup();
/* Mark WAL done */
executionLog->markDone();
std::cout << "Job routine reached end" << std::endl;
/* Move worker in idle mode */
exec.jobcontrol->setStateIdle();
delete executionLog;
}
void Execute::prospect(const std::string& name) {
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REQ);
Execute& exec = Execute::getInstance();
if (!exec.chain) {
return;
}
if (!file_exist(PKGDIR "/" + name)) {
std::cerr << "Cannot access library" << std::endl;
return;
}
std::ifstream ifs(PKGDIR "/" + name);
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
socket.connect(("tcp://" + exec.master).c_str());
std::cout << "Connect to master " << exec.master << std::endl;
for (unsigned int i = 0; i < exec.chain->size(); ++i) {
auto subjob = exec.chain->at(i);
ProcessJob job;
job.set_name(subjob->name);
job.set_id(i);
job.set_quid(quidpp::Quid().toString(true));
job.set_content(content);
job.set_partition(i);
job.set_partition_count(exec.chain->size());
job.set_state(ProcessJob::PARTITION);
job.set_quid_parent(exec.chain->parentQuid());
job.set_data(subjob->data);
std::cout << "Submit subjob " << i << " linked to parent " << exec.chain->parentQuid() + "(" + exec.chain->parentName() + ")" << std::endl;
std::string serialized;
job.SerializeToString(&serialized);
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
/* Get the reply */
zmq::message_t reply;
socket.recv(&reply);
}
delete exec.chain;
exec.chain = nullptr;
}
void Execute::dispose() {
DIR *dir = nullptr;
struct dirent *ent = nullptr;
if ((dir = opendir(PKGDIR)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
remove((PKGDIR "/" + std::string(ent->d_name)).c_str());
}
closedir(dir);
}
if ((dir = opendir(WALDIR)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
remove((WALDIR "/" + std::string(ent->d_name)).c_str());
}
closedir(dir);
}
}
<commit_msg>Measure job runtime<commit_after>#include <dlfcn.h>
#include <cassert>
#include <fstream>
#include <zmq.hpp>
#include <quidpp.h>
#include <package.h>
#include <Python.h>
#include "common/util.h"
#include "ace/interface.h"
#include "protoc/processjob.pb.h"
#include "dirent.h"
#include "wal.h"
#include "exec.h"
#include "ace/config.h"
#include "ace/ipc.h"
void Execute::init(ControlClient *control, const std::string& _master) {
DIR *dir = nullptr;
struct dirent *ent = nullptr;
Execute& exec = Execute::getInstance();
exec.jobcontrol = control;
exec.master = _master;
return;
if ((dir = opendir(WALDIR)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
Wal::rollback(ent->d_name, [](const std::string & name, Execute::Parameter & param) {
/* Run procedure */
Execute::run(name, param);
/* Setup subjobs if any */
Execute::prospect(name);
});
}
closedir(dir);
}
}
void Execute::run(const std::string& name, Parameter& param) {
Wal *executionLog = new Wal(name, param);
struct timeval t1, t2;
Execute& exec = Execute::getInstance();
std::cout << "Running package " << name << std::endl;
/* Move worker in accept mode */
exec.jobcontrol->setStateAccepted();
/* Set members of shared object via callback */
exec.workerid = exec.jobcontrol->workerId();
exec.clusterjobs = exec.jobcontrol->clusterJobs();
exec.module = name;
exec.jobid = param.jobid;
exec.jobname = param.jobname;
exec.jobquid = param.jobquid;
exec.jobpartition = param.jobpartition;
exec.jobpartition_count = param.jobpartition_count;
exec.jobstate = param.jobstate;
exec.jobparent = param.jobparent;
/* Ensure package exist */
if (!file_exist(PKGDIR "/" + name)) {
exec.jobcontrol->setStateIdle();
std::cerr << "Package does not exist" << std::endl;
return;
}
//TODO: check if module directory already exist
/* Extract package in job directory */
if (package_extract((PKGDIR "/" + name).c_str(), ("cache/local/" + name).c_str())) {
exec.jobcontrol->setStateIdle();
std::cerr << "Cannot open package " << std::endl;
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::INIT);
wchar_t *program = Py_DecodeLocale("Chella Worker", NULL);
if (!program) {
std::cerr << "Cannot decode name" << std::endl;
return;
}
chdir((LOCALDIR "/" + name).c_str());
setenv("PYTHONPATH", ".", 1);
Py_SetProgramName(program);
Py_Initialize();
PyObject *pModuleJob = PyImport_ImportModule("job_example");
if (!pModuleJob) {
PyErr_Print();
return;
}
/* Initialize Ace modules */
PyObject *pMethodConfig = Ace::Config::PyAce_ModuleClass();
PyObject *pMethodCallback = Ace::IPC::PyAce_ModuleClass();
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::LOAD);
gettimeofday(&t1, NULL);
/* Create Ace config instance */
PyObject *pInstanceConfig = PyObject_CallObject(pMethodConfig, NULL);
if (!pInstanceConfig) {
PyErr_Print();
return;
}
/* Locate job init and call routine */
PyObject *pFuncJobInit = PyObject_GetAttrString(pModuleJob, "job_init");
if (!pFuncJobInit || !PyCallable_Check(pFuncJobInit)) {
PyErr_Print();
return;
}
PyObject *pArgsJobInit = Py_BuildValue("(O)", pInstanceConfig);
PyObject *pInstanceJobInit = PyObject_CallObject(pFuncJobInit, pArgsJobInit);
if (!pInstanceJobInit) {
PyErr_Print();
return;
}
PyObject *pFuncJobInvoke = PyObject_GetAttrString(pInstanceJobInit, "invoke");
if (!pFuncJobInvoke || !PyCallable_Check(pFuncJobInvoke)) {
PyErr_Print();
return;
}
/* Instantiate job class */
PyObject *pInstanceJob = PyObject_CallObject(pFuncJobInvoke, NULL);
if (!pInstanceJob) {
PyErr_Print();
return;
}
PyObject *pResult = NULL;
pResult = PyObject_CallMethod(pInstanceJob, "inject", "(Oisssii)", pMethodCallback,
exec.jobid,
exec.jobname.c_str(),
name.c_str(),
exec.jobquid.c_str(),
exec.jobpartition,
exec.jobpartition_count);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::INJECT);
pResult = PyObject_CallMethod(pInstanceJob, "setup_once", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::SETUP_ONCE);
pResult = PyObject_CallMethod(pInstanceJob, "setup", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::SETUP);
pResult = PyObject_CallMethod(pInstanceJob, "run", "(y#)", param.jobdata.data(), param.jobdata.size());
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::RUN);
pResult = PyObject_CallMethod(pInstanceJob, "teardown", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::TEARDOWN);
pResult = PyObject_CallMethod(pInstanceJob, "teardown_once", NULL);
if (!pResult) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::TEARDOWN_ONCE);
PyObject *pMemberChains = PyObject_GetAttrString(pInstanceJob, "chains");
if (!pMemberChains) {
PyErr_Print();
return;
}
/* Move WAL forward */
executionLog->setCheckpoint(Wal::Checkpoint::PULLCHAIN);
gettimeofday(&t2, NULL);
Py_DECREF(pResult);
Py_DECREF(pMemberChains);
Py_DECREF(pInstanceJob);
Py_DECREF(pMethodCallback);
Py_DECREF(pMethodConfig);
Py_DECREF(pModuleJob);
/* Release resources allocated for this job */
Py_Finalize();
exec.sessionCleanup();
/* Mark WAL done */
executionLog->markDone();
double runtime = (t2.tv_sec - t1.tv_sec) * 1000.0;
runtime += (t2.tv_usec - t1.tv_usec) / 1000.0;
std::cout << "Job routine reached end" << std::endl;
std::cout << "Total runtime: " << runtime << std::endl;
/* Move worker in idle mode */
exec.jobcontrol->setStateIdle();
delete executionLog;
}
void Execute::prospect(const std::string& name) {
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REQ);
Execute& exec = Execute::getInstance();
if (!exec.chain) {
return;
}
if (!file_exist(PKGDIR "/" + name)) {
std::cerr << "Cannot access library" << std::endl;
return;
}
std::ifstream ifs(PKGDIR "/" + name);
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
socket.connect(("tcp://" + exec.master).c_str());
std::cout << "Connect to master " << exec.master << std::endl;
for (unsigned int i = 0; i < exec.chain->size(); ++i) {
auto subjob = exec.chain->at(i);
ProcessJob job;
job.set_name(subjob->name);
job.set_id(i);
job.set_quid(quidpp::Quid().toString(true));
job.set_content(content);
job.set_partition(i);
job.set_partition_count(exec.chain->size());
job.set_state(ProcessJob::PARTITION);
job.set_quid_parent(exec.chain->parentQuid());
job.set_data(subjob->data);
std::cout << "Submit subjob " << i << " linked to parent " << exec.chain->parentQuid() + "(" + exec.chain->parentName() + ")" << std::endl;
std::string serialized;
job.SerializeToString(&serialized);
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
/* Get the reply */
zmq::message_t reply;
socket.recv(&reply);
}
delete exec.chain;
exec.chain = nullptr;
}
void Execute::dispose() {
DIR *dir = nullptr;
struct dirent *ent = nullptr;
if ((dir = opendir(PKGDIR)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
remove((PKGDIR "/" + std::string(ent->d_name)).c_str());
}
closedir(dir);
}
if ((dir = opendir(WALDIR)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
remove((WALDIR "/" + std::string(ent->d_name)).c_str());
}
closedir(dir);
}
}
<|endoftext|> |
<commit_before>/* Description: A simple command shell */
/* Created by: David / 13513019
Gerry Kastogi / 13513011
Jessica Andjani / 13513086
*/
/*** Compile instruction: g++ shell.cpp -o shell -lreadline ***/
#include "shellfunc.h" //Self-made
using namespace std;
string NextToken(string temp, int &i){
string arg;
//Ignore blank
while(i<temp.length() && temp[i]==' '){
i++;
}
//If first character encounter special delimiter
if((temp[i]=='>' || temp[i]=='<' || temp[i]=='|') && i<temp.length()){
arg=temp[i];
i++;
}
else{ //Read command until found delimiter
while(i<temp.length()){
if (temp[i]=='>' || temp[i]=='<' || temp[i]==' ' || temp[i]=='|'){
break;
}
else{
arg+=temp[i];
i++;
}
}
}
return arg;
}
int ReadCommand(string temp, int& i, char ** argv, int (&stats)[3], string& filein, string& fileout){
string arg;
char *cstr;
int argc=0;
do{
arg=NextToken(temp, i);
if(!arg.compare("<")){
filein=NextToken(temp,i);
stats[0]=1;
}
else if(!arg.compare(">")){
fileout=NextToken(temp,i);
stats[1]=1;
}
else if(!arg.compare("|")){ //Pipeline
stats[2]=1;
break;
}
else{
cstr = new char[arg.size()];
strcpy(cstr, arg.c_str());
argv[argc] = cstr;
argc++;
}
}
while (i<temp.length());
argv[argc] = NULL;
return argc;
}
int ParseCommand(string temp, char ** argv, char ** argv2, int (&stats)[3], int (&stats2)[3], string& filein, string& fileout){
int argc=0; //Argumen ke berapa
int i=0;
argc+=ReadCommand(temp, i,argv, stats, filein, fileout);
if(stats[2]==1){ //Pipeline occured
argc+=ReadCommand(temp, i, argv2, stats2, filein, fileout);
}
return argc;
}
void RunCommand(char ** argv, char ** argv2, int stats[], int stats2[], string filein, string fileout){
//Change Directory
if(argv[0]==NULL){
//Do Nothing
}
else if(strcmp(argv[0], "cd")==0)
changeDir(argv[1]);
//Exit Program
else if(strcmp(argv[0], "quit")==0)
exit(0);
else{
pid_t pid=fork();
if(pid==0){ //Child Process
if(stats[2]==1) //Pipeline
Pipe(argv, argv2, stats, stats2, filein, fileout);
else //Run Program Normally
RunProgram1(argv, stats, filein, fileout);
}
else if (pid>0){
waitpid(pid,NULL,0);
}
}
}
int main(){
int argc; //Jumlah argv yang terpakai
char* argv[100]; //Menampung parameter
char* argv2[100]; //Dipakai jika menggunakan pipeline
string filein, fileout; //Digunakan jika menggunakan redirect
//Program terminalnya
while (true){
/* stats[0]==1 jika menyimpan redirect in */
/* stats[1]==1 jika menyimpan redirect out */
/* stats[2]==1 jika terjadi pipeline */
int stats[] = {0, 0, 0};
int stats2[] = {0, 0, 0}; //Digunakan jika memakai pipeline
rl_bind_key('\t', rl_complete); //Auto complete on
char* buf;
char* dir;
strcpy(dir,"~"); strcat(dir, Directory()); strcat(dir,"> "); //Concat gak jelas
buf = readline(dir); //Baca input
if(buf[0]!=0){
add_history(buf);
string temp = buf;
//Parse
argc= ParseCommand(temp, argv, argv2, stats, stats2, filein, fileout);
//Jalanin command yang sudah di parse
RunCommand(argv, argv2, stats, stats2, filein, fileout);
}
free(buf);
}
return 0;
}<commit_msg>Translating comment into english<commit_after>/* Description: A simple command shell */
/* Created by: David / 13513019
Gerry Kastogi / 13513011
Jessica Andjani / 13513086
*/
/*** Compile instruction: g++ shell.cpp -o shell -lreadline ***/
#include "shellfunc.h" //Self-made
using namespace std;
string NextToken(string temp, int &i){
string arg;
//Ignore blank
while(i<temp.length() && temp[i]==' '){
i++;
}
//If first character encounter special delimiter
if((temp[i]=='>' || temp[i]=='<' || temp[i]=='|') && i<temp.length()){
arg=temp[i];
i++;
}
else{ //Read command until found delimiter
while(i<temp.length()){
if (temp[i]=='>' || temp[i]=='<' || temp[i]==' ' || temp[i]=='|'){
break;
}
else{
arg+=temp[i];
i++;
}
}
}
return arg;
}
int ReadCommand(string temp, int& i, char ** argv, int (&stats)[3], string& filein, string& fileout){
string arg;
char *cstr;
int argc=0;
do{
arg=NextToken(temp, i);
if(!arg.compare("<")){
filein=NextToken(temp,i);
stats[0]=1;
}
else if(!arg.compare(">")){
fileout=NextToken(temp,i);
stats[1]=1;
}
else if(!arg.compare("|")){ //Pipeline
stats[2]=1;
break;
}
else{
cstr = new char[arg.size()];
strcpy(cstr, arg.c_str());
argv[argc] = cstr;
argc++;
}
}
while (i<temp.length());
argv[argc] = NULL;
return argc;
}
int ParseCommand(string temp, char ** argv, char ** argv2, int (&stats)[3], int (&stats2)[3], string& filein, string& fileout){
int argc=0; //Argument count
int i=0;
argc+=ReadCommand(temp, i,argv, stats, filein, fileout);
if(stats[2]==1){ //Pipeline occured
argc+=ReadCommand(temp, i, argv2, stats2, filein, fileout);
}
return argc;
}
void RunCommand(char ** argv, char ** argv2, int stats[], int stats2[], string filein, string fileout){
//Change Directory
if(argv[0]==NULL){
//Do Nothing
}
else if(strcmp(argv[0], "cd")==0)
changeDir(argv[1]);
//Exit Program
else if(strcmp(argv[0], "quit")==0)
exit(0);
else{
pid_t pid=fork();
if(pid==0){ //Child Process
if(stats[2]==1) //Pipeline
Pipe(argv, argv2, stats, stats2, filein, fileout);
else //Run Program Normally
RunProgram1(argv, stats, filein, fileout);
}
else if (pid>0){
waitpid(pid,NULL,0);
}
}
}
int main(){
int argc; //Number of argv used
char* argv[100]; //Contains parameter
char* argv2[100]; //Used if pipeline exists
string filein, fileout; //Used if I/O redirection exists
//Program
while (true){
/* stats[0]==1 if redirect in */
/* stats[1]==1 if redirect out */
/* stats[2]==1 if pipeline occured */
int stats[] = {0, 0, 0};
int stats2[] = {0, 0, 0}; //Used if pipeline exists
rl_bind_key('\t', rl_complete); //Auto complete on
char* buf;
char* dir;
strcpy(dir,"~"); strcat(dir, Directory()); strcat(dir,"> "); //Concat
buf = readline(dir); //Baca input
if(buf[0]!=0){
add_history(buf);
string temp = buf;
//Parse
argc= ParseCommand(temp, argv, argv2, stats, stats2, filein, fileout);
//Run command that has been parsed
RunCommand(argv, argv2, stats, stats2, filein, fileout);
}
free(buf);
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief VS1063 VLSI Audio Codec ドライバー
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "G13/port.hpp"
#include "common/csi_io.hpp"
#include "common/delay.hpp"
#include "common/format.hpp"
#include "ff12a/src/ff.h"
extern "C" {
char sci_getch(void);
uint16_t sci_length();
}
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief VS1063 テンプレートクラス
@param[in] CSI CSI(SPI) 制御クラス
@param[in] SEL /xCS 制御クラス
@param[in] DCS /xDCS 制御クラス
@param[in] REQ DREQ 入力クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CSI, class SEL, class DCS, class REQ>
class VS1063 {
CSI& csi_;
FIL fp_;
uint8_t frame_;
bool open_;
/// VS1063a コマンド表
enum class CMD {
MODE, ///< モード制御
STATUS, ///< ステータス
BASS, ///< 内臓の低音/高音強調
CLOCKF, ///< クロック周波数+逓倍器
DECODE_TIME, ///< 再生時間[秒]
AUDATA, ///< 各種オーディオ・データ
WRAM, ///< RAM リード/ライト
WRAMADDR, ///< RAM リード/ライト・アドレス
HDAT0, ///< ストリーム・ヘッダ・データ0
HDAT1, ///< ストリーム・ヘッダ・データ1
AIADDR, ///< アプリケーション開始アドレス
VOL, ///< ボリューム制御
AICTRL0, ///< アプリケーション制御レジスタ0
AICTRL1, ///< アプリケーション制御レジスタ1
AICTRL2, ///< アプリケーション制御レジスタ2
AICTRL3 ///< アプリケーション制御レジスタ3
};
inline void sleep_() { asm("nop"); }
inline bool get_status_()
{
return REQ::P();
}
inline void wait_ready_()
{
while(REQ::P() == 0) sleep_();
}
void write_(CMD cmd, uint16_t data)
{
wait_ready_();
SEL::P = 0;
csi_.xchg(0x02); // Write command (0x02)
csi_.xchg(static_cast<uint8_t>(cmd));
csi_.xchg(data >> 8);
csi_.xchg(data & 0xff);
SEL::P = 1;
}
uint16_t read_(CMD cmd)
{
wait_ready_();
uint16_t data;
SEL::P = 0;
csi_.xchg(0x03); // Read command (0x03)
csi_.xchg(static_cast<uint8_t>(cmd));
data = static_cast<uint16_t>(CSI::xchg()) << 8;
data |= csi_.xchg();
SEL::P = 1;
return data;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
VS1063(CSI& csi) : csi_(csi), frame_(0), open_(false) { }
//-----------------------------------------------------------------//
/*!
@brief 開始(初期化)
*/
//-----------------------------------------------------------------//
void start()
{
SEL::PM = 0;
SEL::PU = 0;
DCS::PM = 0;
DCS::PU = 0;
REQ::PM = 1;
REQ::PU = 0;
SEL::P = 1; // /xCS = H
DCS::P = 1; // /xDCS = H
open_ = false;
uint8_t intr_level = 0;
if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) {
utils::format("CSI1 Start fail ! (Clock spped over range)\n");
return;
}
write_(CMD::MODE, 0x4800);
write_(CMD::VOL, 0x4040); // volume
// write_(CMD::CLOCKF, 0x9800);
write_(CMD::CLOCKF, 0x8BE8); // 12MHz OSC 補正
utils::delay::milli_second(10);
if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) {
utils::format("CSI1 Start fail ! (Clock spped over range)\n");
return;
}
utils::delay::milli_second(10);
}
//----------------------------------------------------------------//
/*!
@brief サービス
*/
//----------------------------------------------------------------//
bool service()
{
while(get_status_() != 0) {
uint8_t buff[32];
UINT len;
if(f_read(&fp_, buff, sizeof(buff), &len) != FR_OK) {
return false;
}
if(len > 0) {
csi_.write(buff, len);
}
if(len < 32) {
f_close(&fp_);
open_ = false;
return false;
}
++frame_;
if(frame_ >= 40) {
device::P4.B3 = !device::P4.B3();
frame_ = 0;
}
if(sci_length()) {
auto ch = sci_getch();
if(ch == '>') {
f_close(&fp_);
open_ = false;
return false;
}
}
}
return true;
}
//----------------------------------------------------------------//
/*!
@brief 再生
@param[in] fname ファイル名
@return エラーなら「false」
*/
//----------------------------------------------------------------//
bool play(const char* fname)
{
set_volume(255);
if(f_open(&fp_, fname, FA_READ) != FR_OK) {
utils::format("Can't open input file: '%s'\n") % fname;
return false;
}
open_ = true;
frame_ = 0;
DCS::P = 0;
while(service()) {
sleep_();
}
DCS::P = 1;
return true;
}
//----------------------------------------------------------------//
/*!
@brief ボリュームを設定
@param[in] ボリューム(255が最大、0が最小)
*/
//----------------------------------------------------------------//
void set_volume(uint8_t vol)
{
vol ^= 0xff;
write_(CMD::VOL, (vol << 8) | vol);
}
//----------------------------------------------------------------//
/*!
@brief ボリュームを取得
@return ボリューム(255が最大、0が最小)
*/
//----------------------------------------------------------------//
uint8_t get_volume()
{
return (read_(CMD::VOL) & 255) ^ 0xff;
}
};
}
<commit_msg>fix ID3 tag skip<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief VS1063 VLSI Audio Codec ドライバー
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "G13/port.hpp"
#include "common/csi_io.hpp"
#include "common/delay.hpp"
#include "common/format.hpp"
#include "ff12a/src/ff.h"
extern "C" {
char sci_getch(void);
uint16_t sci_length();
}
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief VS1063 テンプレートクラス
@param[in] CSI CSI(SPI) 制御クラス
@param[in] SEL /xCS 制御クラス
@param[in] DCS /xDCS 制御クラス
@param[in] REQ DREQ 入力クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CSI, class SEL, class DCS, class REQ>
class VS1063 {
CSI& csi_;
FIL fp_;
uint8_t frame_;
bool open_;
uint8_t buff_[256];
/// VS1063a コマンド表
enum class CMD {
MODE, ///< モード制御
STATUS, ///< ステータス
BASS, ///< 内臓の低音/高音強調
CLOCKF, ///< クロック周波数+逓倍器
DECODE_TIME, ///< 再生時間[秒]
AUDATA, ///< 各種オーディオ・データ
WRAM, ///< RAM リード/ライト
WRAMADDR, ///< RAM リード/ライト・アドレス
HDAT0, ///< ストリーム・ヘッダ・データ0
HDAT1, ///< ストリーム・ヘッダ・データ1
AIADDR, ///< アプリケーション開始アドレス
VOL, ///< ボリューム制御
AICTRL0, ///< アプリケーション制御レジスタ0
AICTRL1, ///< アプリケーション制御レジスタ1
AICTRL2, ///< アプリケーション制御レジスタ2
AICTRL3 ///< アプリケーション制御レジスタ3
};
inline void sleep_() { asm("nop"); }
inline bool get_status_()
{
return REQ::P();
}
inline void wait_ready_()
{
while(REQ::P() == 0) sleep_();
}
void write_(CMD cmd, uint16_t data)
{
wait_ready_();
SEL::P = 0;
csi_.xchg(0x02); // Write command (0x02)
csi_.xchg(static_cast<uint8_t>(cmd));
csi_.xchg(data >> 8);
csi_.xchg(data & 0xff);
SEL::P = 1;
}
uint16_t read_(CMD cmd)
{
wait_ready_();
uint16_t data;
SEL::P = 0;
csi_.xchg(0x03); // Read command (0x03)
csi_.xchg(static_cast<uint8_t>(cmd));
data = static_cast<uint16_t>(CSI::xchg()) << 8;
data |= csi_.xchg();
SEL::P = 1;
return data;
}
bool probe_mp3_()
{
UINT len;
if(f_read(&fp_, buff_, 10, &len) != FR_OK) {
return false;
}
if(len != 10) {
f_close(&fp_);
return false;
}
if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ;
else {
return false;
}
// skip TAG
uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21;
ofs |= static_cast<uint32_t>(buff_[7]) << 14;
ofs |= static_cast<uint32_t>(buff_[8]) << 7;
ofs |= static_cast<uint32_t>(buff_[9]);
f_lseek(&fp_, ofs);
utils::format("Find ID3 tag skip: %d\n") % ofs;
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
VS1063(CSI& csi) : csi_(csi), frame_(0), open_(false) { }
//-----------------------------------------------------------------//
/*!
@brief 開始(初期化)
*/
//-----------------------------------------------------------------//
void start()
{
SEL::PM = 0;
SEL::PU = 0;
DCS::PM = 0;
DCS::PU = 0;
REQ::PM = 1;
REQ::PU = 0;
SEL::P = 1; // /xCS = H
DCS::P = 1; // /xDCS = H
open_ = false;
uint8_t intr_level = 0;
if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) {
utils::format("CSI1 Start fail ! (Clock spped over range)\n");
return;
}
/// write_(CMD::MODE, 0x4840);
write_(CMD::MODE, 0x4800);
write_(CMD::VOL, 0x4040); // volume
// write_(CMD::CLOCKF, 0x9800);
write_(CMD::CLOCKF, 0x8BE8); // 12MHz OSC 補正
utils::delay::milli_second(10);
if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) {
utils::format("CSI1 Start fail ! (Clock spped over range)\n");
return;
}
utils::delay::milli_second(10);
set_volume(255);
}
//----------------------------------------------------------------//
/*!
@brief サービス
*/
//----------------------------------------------------------------//
bool service()
{
UINT len;
if(f_read(&fp_, buff_, sizeof(buff_), &len) != FR_OK) {
return false;
}
if(len == 0) return false;
const uint8_t* p = buff_;
while(len > 0) {
while(get_status_() == 0) ;
uint16_t l = 32;
if(l > len) l = len;
csi_.write(p, l);
p += l;
len -= l;
}
++frame_;
if(frame_ >= 40) {
device::P4.B3 = !device::P4.B3();
frame_ = 0;
}
if(sci_length()) {
auto ch = sci_getch();
if(ch == '>') {
return false;
}
}
return true;
}
//----------------------------------------------------------------//
/*!
@brief 再生
@param[in] fname ファイル名
@return エラーなら「false」
*/
//----------------------------------------------------------------//
bool play(const char* fname)
{
utils::format("Play: '%s'\n") % fname;
if(f_open(&fp_, fname, FA_READ) != FR_OK) {
utils::format("Can't open input file: '%s'\n") % fname;
return false;
}
// ファイル・フォーマットを確認
probe_mp3_();
{
open_ = true;
frame_ = 0;
DCS::P = 0;
while(service()) {
sleep_();
}
DCS::P = 1;
}
f_close(&fp_);
open_ = false;
return true;
}
//----------------------------------------------------------------//
/*!
@brief ボリュームを設定
@param[in] ボリューム(255が最大、0が最小)
*/
//----------------------------------------------------------------//
void set_volume(uint8_t vol)
{
vol ^= 0xff;
write_(CMD::VOL, (vol << 8) | vol);
}
//----------------------------------------------------------------//
/*!
@brief ボリュームを取得
@return ボリューム(255が最大、0が最小)
*/
//----------------------------------------------------------------//
uint8_t get_volume()
{
return (read_(CMD::VOL) & 255) ^ 0xff;
}
};
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name 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.
******************************************************************************/
/*******************************************************************************
* \file serial_udp.cpp
*
* \author MAV'RIC Team
*
* \brief Linux implementation of serial peripherals using UDP
*
******************************************************************************/
#include "serial_udp.hpp"
extern "C"
{
#include <unistd.h>
// #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include <time.h>
#include <arpa/inet.h>
// #include "print_util.h"
}
//------------------------------------------------------------------------------
// PUBLIC FUNCTIONS IMPLEMENTATION
//------------------------------------------------------------------------------
Serial_udp::Serial_udp(serial_udp_conf_t config):
tx_udp_(udp_client(config.ip, config.tx_port)),
rx_udp_(udp_server(config.ip, config.rx_port))
{
config = config;
// Init buffers
buffer_init(&tx_buffer_);
buffer_init(&rx_buffer_);
// Set rx as non blocking
int sock = rx_udp_.get_socket();
int flags = fcntl (sock, F_GETFL, 0 );
fcntl( sock, F_SETFL, flags | O_NONBLOCK );
}
bool Serial_udp::init(void)
{
return true;
}
uint32_t Serial_udp::readable(void)
{
int32_t recsize;
char buf[BUFFER_SIZE];
recsize = rx_udp_.recv(buf, BUFFER_SIZE);
for( int32_t i=0; i<recsize; i++ )
{
buffer_put( &rx_buffer_, buf[i] );
}
return buffer_bytes_available(&rx_buffer_);
}
uint32_t Serial_udp::writeable(void)
{
return buffer_bytes_free( &tx_buffer_ );
}
void Serial_udp::flush(void)
{
int32_t bytes_sent;
bytes_sent = tx_udp_.send((const char*)tx_buffer_.Buffer, buffer_bytes_available(&tx_buffer_));
if( bytes_sent == (int32_t)buffer_bytes_available( &tx_buffer_ ) )
{
buffer_clear( &tx_buffer_ );
}
else
{
for(int32_t i=0; i<bytes_sent; i++ )
{
buffer_get( &tx_buffer_ );
}
}
}
bool Serial_udp::write(const uint8_t* bytes, const uint32_t size)
{
bool ret = true;
// Queue byte
for (uint32_t i = 0; i < size; ++i)
{
ret &= buffer_put( &tx_buffer_, bytes[i] );
}
// Start transmission
if( buffer_bytes_available( &tx_buffer_ ) >= 1 )
{
flush();
}
return ret;
}
bool Serial_udp::read(uint8_t bytes[], const uint32_t size)
{
bool ret = false;
if( readable() >= size )
{
for (uint32_t i = 0; i < size; ++i)
{
bytes[i] = buffer_get( &rx_buffer_ );
}
ret = true;
}
return ret;
}
//------------------------------------------------------------------------------
// PRIVATE FUNCTIONS IMPLEMENTATION
//------------------------------------------------------------------------------<commit_msg>Cosmetics<commit_after>/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name 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.
******************************************************************************/
/*******************************************************************************
* \file serial_udp.cpp
*
* \author MAV'RIC Team
*
* \brief Linux implementation of serial peripherals using UDP
*
******************************************************************************/
#include "serial_udp.hpp"
extern "C"
{
#include <fcntl.h>
}
//------------------------------------------------------------------------------
// PUBLIC FUNCTIONS IMPLEMENTATION
//------------------------------------------------------------------------------
Serial_udp::Serial_udp(serial_udp_conf_t config):
tx_udp_(udp_client(config.ip, config.tx_port)),
rx_udp_(udp_server(config.ip, config.rx_port))
{
config = config;
// Init buffers
buffer_init(&tx_buffer_);
buffer_init(&rx_buffer_);
// Set rx as non blocking
int sock = rx_udp_.get_socket();
int flags = fcntl (sock, F_GETFL, 0 );
fcntl( sock, F_SETFL, flags | O_NONBLOCK );
}
bool Serial_udp::init(void)
{
return true;
}
uint32_t Serial_udp::readable(void)
{
int32_t recsize;
char buf[BUFFER_SIZE];
recsize = rx_udp_.recv(buf, BUFFER_SIZE);
for( int32_t i=0; i<recsize; i++ )
{
buffer_put( &rx_buffer_, buf[i] );
}
return buffer_bytes_available(&rx_buffer_);
}
uint32_t Serial_udp::writeable(void)
{
return buffer_bytes_free( &tx_buffer_ );
}
void Serial_udp::flush(void)
{
int32_t bytes_sent;
bytes_sent = tx_udp_.send((const char*)tx_buffer_.Buffer, buffer_bytes_available(&tx_buffer_));
if( bytes_sent == (int32_t)buffer_bytes_available( &tx_buffer_ ) )
{
buffer_clear( &tx_buffer_ );
}
else
{
for(int32_t i=0; i<bytes_sent; i++ )
{
buffer_get( &tx_buffer_ );
}
}
}
bool Serial_udp::write(const uint8_t* bytes, const uint32_t size)
{
bool ret = true;
// Queue byte
for (uint32_t i = 0; i < size; ++i)
{
ret &= buffer_put( &tx_buffer_, bytes[i] );
}
// Start transmission
if( buffer_bytes_available( &tx_buffer_ ) >= 1 )
{
flush();
}
return ret;
}
bool Serial_udp::read(uint8_t bytes[], const uint32_t size)
{
bool ret = false;
if( readable() >= size )
{
for (uint32_t i = 0; i < size; ++i)
{
bytes[i] = buffer_get( &rx_buffer_ );
}
ret = true;
}
return ret;
}
//------------------------------------------------------------------------------
// PRIVATE FUNCTIONS IMPLEMENTATION
//------------------------------------------------------------------------------<|endoftext|> |
<commit_before>/********************************************************************
* Copyright © 2017 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* This file is part of ReaDDy. *
* *
* ReaDDy is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General *
* Public License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
********************************************************************/
/**
* @file Timer.cpp
* @brief Implementation of timer classes
* @author chrisfroe
* @date 01.09.17
* @copyright GNU Lesser General Public License v3.0
*/
#include <readdy/common/Timer.h>
#include <readdy/common/string.h>
namespace readdy {
namespace util {
constexpr const char PerformanceNode::slash[];
PerformanceNode::PerformanceNode(const std::string &name, bool measure) : _name(validateName(name)), _measure(measure), _data(0., 0) { }
PerformanceNode &PerformanceNode::subnode(const std::string &name) {
auto validatedName = validateName(name);
const auto &it = std::find_if(children.begin(), children.end(),
[&validatedName](const performance_node_ref &node) { return node->_name == validatedName; });
if (it == children.end()) {
children.push_back(std::make_unique<PerformanceNode>(validatedName, _measure));
return *children.back();
}
return **it;
}
void PerformanceNode::clear() {
_data.cumulativeTime = 0.;
_data.count = 0;
for (auto &c : children) {
c->clear();
}
}
Timer PerformanceNode::timeit() {
return Timer(_data, _measure);
}
const PerformanceData &PerformanceNode::data() const {
return _data;
}
const PerformanceNode &PerformanceNode::direct_child(const std::string &name) const {
const auto &it = std::find_if(children.begin(), children.end(), [&name](const performance_node_ref &node) { return node->_name == name; });
if (it == children.end()) {
throw std::runtime_error(fmt::format("Child with name {} does not exist", name));
}
return **it;
}
const std::size_t PerformanceNode::n_children() const {
return children.size();
}
std::string PerformanceNode::describe(const size_t level) const {
std::string s;
for (auto i = 0; i < level; ++i) {
s += "\t";
}
s += fmt::format("{}: time {} s, count {}\n", _name, _data.cumulativeTime, _data.count);
for (const auto &c : children) {
s += c->describe(level + 1);
}
return s;
}
std::vector<std::string> PerformanceNode::parse(const std::string &path) const {
std::vector<std::string> labels;
std::string residualPath(path);
auto slashPos = residualPath.find(slash);
while (slashPos != residualPath.npos) {
auto lhs = residualPath.substr(0, slashPos);
auto rhs = residualPath.substr(slashPos + std::strlen(slash), residualPath.npos);
util::str::trim(lhs);
util::str::trim(rhs);
residualPath = rhs;
labels.push_back(lhs);
slashPos = residualPath.find(slash);
}
labels.push_back(residualPath);
return labels;
}
const PerformanceNode &PerformanceNode::child(const std::vector<std::string> &labels) const {
if (labels.empty()) {
throw std::invalid_argument("labels must not be empty");
}
std::vector<std::reference_wrapper<const PerformanceNode>> nodes;
nodes.push_back(std::cref(direct_child(labels[0])));
for (auto i = 1; i< labels.size(); ++i) {
auto previousNode = nodes.back();
auto nextNode = std::cref(previousNode.get().direct_child(labels[i]));
nodes.push_back(nextNode);
}
return nodes.back();
}
const PerformanceNode &PerformanceNode::child(const std::string &path) const {
if (path.find(slash)) {
const auto &labels = parse(path);
return child(labels);
} else {
return direct_child(path);
}
}
const std::string &PerformanceNode::name() const {
return _name;
}
std::string PerformanceNode::validateName(const std::string &name) const {
if (name.find(slash) != name.npos) {
throw std::invalid_argument(fmt::format("name {} contains forbidden char {}", name, slash));
}
return util::str::trim_copy(name);
}
Timer::Timer(PerformanceData &target, bool measure) : target(target), measure(measure) {
if (measure) {
begin = std::chrono::high_resolution_clock::now();
}
}
Timer::~Timer() {
if (measure) {
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
long elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();
const auto elapsedSeconds = static_cast<PerformanceData::time>(1e-6) * static_cast<PerformanceData::time>(elapsed);
std::unique_lock<std::mutex> lock(target.mutex);
target.cumulativeTime += elapsedSeconds;
target.count++;
}
}
}
}<commit_msg>simplify tree descending<commit_after>/********************************************************************
* Copyright © 2017 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* This file is part of ReaDDy. *
* *
* ReaDDy is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General *
* Public License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
********************************************************************/
/**
* @file Timer.cpp
* @brief Implementation of timer classes
* @author chrisfroe
* @date 01.09.17
* @copyright GNU Lesser General Public License v3.0
*/
#include <readdy/common/Timer.h>
#include <readdy/common/string.h>
namespace readdy {
namespace util {
constexpr const char PerformanceNode::slash[];
PerformanceNode::PerformanceNode(const std::string &name, bool measure) : _name(validateName(name)), _measure(measure), _data(0., 0) { }
PerformanceNode &PerformanceNode::subnode(const std::string &name) {
auto validatedName = validateName(name);
const auto &it = std::find_if(children.begin(), children.end(),
[&validatedName](const performance_node_ref &node) { return node->_name == validatedName; });
if (it == children.end()) {
children.push_back(std::make_unique<PerformanceNode>(validatedName, _measure));
return *children.back();
}
return **it;
}
void PerformanceNode::clear() {
_data.cumulativeTime = 0.;
_data.count = 0;
for (auto &c : children) {
c->clear();
}
}
Timer PerformanceNode::timeit() {
return Timer(_data, _measure);
}
const PerformanceData &PerformanceNode::data() const {
return _data;
}
const PerformanceNode &PerformanceNode::direct_child(const std::string &name) const {
const auto &it = std::find_if(children.begin(), children.end(), [&name](const performance_node_ref &node) { return node->_name == name; });
if (it == children.end()) {
throw std::runtime_error(fmt::format("Child with name {} does not exist", name));
}
return **it;
}
const std::size_t PerformanceNode::n_children() const {
return children.size();
}
std::string PerformanceNode::describe(const size_t level) const {
std::string s;
for (auto i = 0; i < level; ++i) {
s += "\t";
}
s += fmt::format("{}: time {} s, count {}\n", _name, _data.cumulativeTime, _data.count);
for (const auto &c : children) {
s += c->describe(level + 1);
}
return s;
}
std::vector<std::string> PerformanceNode::parse(const std::string &path) const {
std::vector<std::string> labels;
std::string residualPath(path);
auto slashPos = residualPath.find(slash);
while (slashPos != residualPath.npos) {
auto lhs = residualPath.substr(0, slashPos);
auto rhs = residualPath.substr(slashPos + std::strlen(slash), residualPath.npos);
util::str::trim(lhs);
util::str::trim(rhs);
residualPath = rhs;
labels.push_back(lhs);
slashPos = residualPath.find(slash);
}
labels.push_back(residualPath);
return labels;
}
const PerformanceNode &PerformanceNode::child(const std::vector<std::string> &labels) const {
if (labels.empty()) {
throw std::invalid_argument("labels must not be empty");
}
std::reference_wrapper<const PerformanceNode> currentNode {direct_child(labels[0])};
for (auto i = 1; i< labels.size(); ++i) {
currentNode = std::cref(currentNode.get().direct_child(labels[i]));
}
return currentNode.get();
}
const PerformanceNode &PerformanceNode::child(const std::string &path) const {
if (path.find(slash)) {
const auto &labels = parse(path);
return child(labels);
} else {
return direct_child(path);
}
}
const std::string &PerformanceNode::name() const {
return _name;
}
std::string PerformanceNode::validateName(const std::string &name) const {
if (name.find(slash) != name.npos) {
throw std::invalid_argument(fmt::format("name {} contains forbidden char {}", name, slash));
}
return util::str::trim_copy(name);
}
Timer::Timer(PerformanceData &target, bool measure) : target(target), measure(measure) {
if (measure) {
begin = std::chrono::high_resolution_clock::now();
}
}
Timer::~Timer() {
if (measure) {
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
long elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();
const auto elapsedSeconds = static_cast<PerformanceData::time>(1e-6) * static_cast<PerformanceData::time>(elapsed);
std::unique_lock<std::mutex> lock(target.mutex);
target.cumulativeTime += elapsedSeconds;
target.count++;
}
}
}
}<|endoftext|> |
<commit_before>#ifndef SLICE_HPP
#define SLICE_HPP
#include "iterbase.hpp"
#include <iterator>
#include <type_traits>
#include <initializer_list>
namespace iter {
//Forward declarations of Slice and slice
//template <typename Container, typename DifferenceType>
//class Slice;
//template <typename T>
//Slice<std::initializer_list<T>> slice( std::initializer_list<T>);
//template <typename Container, typename DifferenceType>
//Slice<Container> slice(Container &&);
template <typename T>
class has_size
{
typedef char one;
typedef long two;
template <typename C> static one test( decltype(&C::size) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
template <typename Container>
typename std::enable_if<has_size<Container>::value, std::size_t>::type
size(const Container& container) {
return container.size();
}
template <typename Container>
typename std::enable_if<!has_size<Container>::value, std::size_t>::type
size(const Container& container) {
return std::distance(std::begin(container), std::end(container));
}
template <typename T, std::size_t N>
std::size_t size(const T (&)[N]) {
return N;
}
template <typename Container, typename DifferenceType>
class Slice {
private:
Container container;
DifferenceType start;
DifferenceType stop;
DifferenceType step;
// The only thing allowed to directly instantiate an Slice is
// the slice function
//friend Slice slice<Container, DifferenceType>(Container &&);
//template <typename T>
//friend Slice<std::initializer_list<T>> slice(std::initializer_list<T>);
public:
Slice(Container in_container, DifferenceType start,
DifferenceType stop, DifferenceType step)
: container(std::forward<Container>(in_container)),
start{start},
stop{stop},
step{step}
{
// sets stop = start if the range is empty
if ((start < stop && step <=0) ||
(start > stop && step >=0)){
this->stop = start;
}
if (this->stop > static_cast<DifferenceType>(
size(this->container))) {
this->stop = static_cast<DifferenceType>(size(
this->container));
}
if (this->start < 0) {
this->start = 0;
}
}
Slice() = delete;
Slice& operator=(const Slice&) = delete;
Slice(const Slice &) = default;
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
iterator_type<Container> sub_iter;
DifferenceType current;
DifferenceType stop;
DifferenceType step;
public:
Iterator (iterator_type<Container> si, DifferenceType start,
DifferenceType stop, DifferenceType step)
: sub_iter{si},
current{start},
stop{stop},
step{step}
{ }
iterator_deref<Container> operator*() const {
return *this->sub_iter;
}
Iterator& operator++() {
std::advance(this->sub_iter, this->step);
this->current += this->step;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator &) const {
return (this->step > 0 && this->current < this->stop)
|| (this->step < 0 && this->current > this->stop);
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::next(std::begin(this->container), this->start),
this->start, this->stop, this->step};
}
Iterator end() {
return {std::next(std::begin(this->container), this->stop),
this->stop, this->stop, this->step};
}
};
// Helper function to instantiate a Slice
template <typename Container, typename DifferenceType>
Slice<Container, DifferenceType> slice(
Container&& container,
DifferenceType start, DifferenceType stop, DifferenceType step=1) {
return {std::forward<Container>(container), start, stop, step};
}
//only give the end as an arg and assume step is 1 and begin is 0
template <typename Container, typename DifferenceType>
Slice<Container, DifferenceType> slice(
Container&& container, DifferenceType stop) {
return {std::forward<Container>(container), 0, stop, 1};
}
template <typename T, typename DifferenceType>
Slice<std::initializer_list<T>, DifferenceType> slice(
std::initializer_list<T> il, DifferenceType start,
DifferenceType stop, DifferenceType step=1) {
return {il, start, stop, step};
}
template <typename T, typename DifferenceType>
Slice<std::initializer_list<T>, DifferenceType> slice(
std::initializer_list<T> il, DifferenceType stop) {
return {il, 0, stop, 1};
}
}
#endif //SLICE_HPP
<commit_msg>adjusts include guards<commit_after>#ifndef ITER_SLICE_HPP
#define ITER_SLICE_HPP
#include "iterbase.hpp"
#include <iterator>
#include <type_traits>
#include <initializer_list>
namespace iter {
//Forward declarations of Slice and slice
//template <typename Container, typename DifferenceType>
//class Slice;
//template <typename T>
//Slice<std::initializer_list<T>> slice( std::initializer_list<T>);
//template <typename Container, typename DifferenceType>
//Slice<Container> slice(Container &&);
template <typename T>
class has_size
{
typedef char one;
typedef long two;
template <typename C> static one test( decltype(&C::size) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
template <typename Container>
typename std::enable_if<has_size<Container>::value, std::size_t>::type
size(const Container& container) {
return container.size();
}
template <typename Container>
typename std::enable_if<!has_size<Container>::value, std::size_t>::type
size(const Container& container) {
return std::distance(std::begin(container), std::end(container));
}
template <typename T, std::size_t N>
std::size_t size(const T (&)[N]) {
return N;
}
template <typename Container, typename DifferenceType>
class Slice {
private:
Container container;
DifferenceType start;
DifferenceType stop;
DifferenceType step;
// The only thing allowed to directly instantiate an Slice is
// the slice function
//friend Slice slice<Container, DifferenceType>(Container &&);
//template <typename T>
//friend Slice<std::initializer_list<T>> slice(std::initializer_list<T>);
public:
Slice(Container in_container, DifferenceType start,
DifferenceType stop, DifferenceType step)
: container(std::forward<Container>(in_container)),
start{start},
stop{stop},
step{step}
{
// sets stop = start if the range is empty
if ((start < stop && step <=0) ||
(start > stop && step >=0)){
this->stop = start;
}
if (this->stop > static_cast<DifferenceType>(
size(this->container))) {
this->stop = static_cast<DifferenceType>(size(
this->container));
}
if (this->start < 0) {
this->start = 0;
}
}
Slice() = delete;
Slice& operator=(const Slice&) = delete;
Slice(const Slice &) = default;
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
iterator_type<Container> sub_iter;
DifferenceType current;
DifferenceType stop;
DifferenceType step;
public:
Iterator (iterator_type<Container> si, DifferenceType start,
DifferenceType stop, DifferenceType step)
: sub_iter{si},
current{start},
stop{stop},
step{step}
{ }
iterator_deref<Container> operator*() const {
return *this->sub_iter;
}
Iterator& operator++() {
std::advance(this->sub_iter, this->step);
this->current += this->step;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator &) const {
return (this->step > 0 && this->current < this->stop)
|| (this->step < 0 && this->current > this->stop);
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::next(std::begin(this->container), this->start),
this->start, this->stop, this->step};
}
Iterator end() {
return {std::next(std::begin(this->container), this->stop),
this->stop, this->stop, this->step};
}
};
// Helper function to instantiate a Slice
template <typename Container, typename DifferenceType>
Slice<Container, DifferenceType> slice(
Container&& container,
DifferenceType start, DifferenceType stop, DifferenceType step=1) {
return {std::forward<Container>(container), start, stop, step};
}
//only give the end as an arg and assume step is 1 and begin is 0
template <typename Container, typename DifferenceType>
Slice<Container, DifferenceType> slice(
Container&& container, DifferenceType stop) {
return {std::forward<Container>(container), 0, stop, 1};
}
template <typename T, typename DifferenceType>
Slice<std::initializer_list<T>, DifferenceType> slice(
std::initializer_list<T> il, DifferenceType start,
DifferenceType stop, DifferenceType step=1) {
return {il, start, stop, step};
}
template <typename T, typename DifferenceType>
Slice<std::initializer_list<T>, DifferenceType> slice(
std::initializer_list<T> il, DifferenceType stop) {
return {il, 0, stop, 1};
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011,2015, Robert Escriva
// 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 po6 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.
// po6
#include "po6/net/socket.h"
using po6::net::socket;
socket :: socket()
: fd(-1)
{
}
socket :: ~socket() throw ()
{
}
bool
socket :: reset(int domain, int type, int protocol)
{
*this = ::socket(domain, type, protocol);
return get() >= 0;
}
// On all platforms I checked, a sockaddr_in6 is larger than a
// sockaddr, which in turn is larger than a sockaddr_in. As a
// result, we allocate the largest of the three and call it a
// sockaddr.
bool
socket :: bind(const ipaddr& addr, in_port_t port)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
addr.pack(sa, &salen, port);
return ::bind(get(), sa, salen) == 0;
}
bool
socket :: bind(const ipaddr& addr)
{
return bind(addr, 0);
}
bool
socket :: bind(const location& loc)
{
return bind(loc.address, loc.port);
}
bool
socket :: connect(const ipaddr& addr, in_port_t port)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
addr.pack(sa, &salen, port);
return ::connect(get(), sa, salen) == 0;
}
bool
socket :: connect(const location& loc)
{
return connect(loc.address, loc.port);
}
bool
socket :: listen(int backlog)
{
return ::listen(get(), backlog) == 0;
}
bool
socket :: accept(socket* newsock)
{
newsock->close();
int ret;
if ((ret = ::accept(get(), NULL, NULL)) < 0)
{
return false;
}
*newsock = ret;
return true;
}
bool
socket :: shutdown(int how)
{
return ::shutdown(get(), how) == 0;
}
bool
socket :: getpeername(location* loc)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
if (::getpeername(get(), sa, &salen) < 0)
{
return false;
}
return loc->set(sa, salen);
}
bool
socket :: getsockname(location* loc)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
if (::getsockname(get(), sa, &salen) < 0)
{
return false;
}
return loc->set(sa, salen);
}
bool
socket :: set_sockopt(int level, int optname,
const void *optval, socklen_t optlen)
{
return setsockopt(get(), level, optname, optval, optlen) == 0;
}
bool
socket :: set_reuseaddr()
{
int yes = 1;
return set_sockopt(SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
}
bool
socket :: set_tcp_nodelay()
{
int yes = 1;
return set_sockopt(IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
}
bool
socket :: sndbuf(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
}
bool
socket :: rcvbuf(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
}
bool
socket :: sndlowat(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_SNDLOWAT, &size, sizeof(size));
}
bool
socket :: rcvlowat(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_RCVLOWAT, &size, sizeof(size));
}
ssize_t
socket :: recv(void *buf, size_t len, int flags)
{
return ::recv(get(), buf, len, flags);
}
ssize_t
socket :: xrecv(void *buf, size_t len, int flags)
{
size_t rem = len;
ssize_t amt = 0;
while (rem > 0)
{
if ((amt = recv(buf, rem, flags)) < 0)
{
if (rem == len)
{
return -1;
}
else
{
break;
}
}
else if (amt == 0)
{
break;
}
rem -= amt;
buf = static_cast<char*>(buf) + amt;
}
return len - rem;
}
ssize_t
socket :: send(const void *buf, size_t len, int flags)
{
return ::send(get(), buf, len, flags);
}
ssize_t
socket :: xsend(const void *buf, size_t len, int flags)
{
size_t rem = len;
ssize_t amt = 0;
while (rem > 0)
{
if ((amt = send(buf, rem, flags)) < 0)
{
if (rem == len)
{
return -1;
}
else
{
break;
}
}
else if (amt == 0)
{
break;
}
rem -= amt;
buf = static_cast<const char*>(buf) + amt;
}
return len - rem;
}
po6::net::socket&
socket :: operator = (int f)
{
*dynamic_cast<fd*>(this) = f;
return *this;
}
<commit_msg>Discard "using po6::net::socket"<commit_after>// Copyright (c) 2011,2015, Robert Escriva
// 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 po6 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.
// po6
#include "po6/net/socket.h"
po6 :: net :: socket :: socket()
: fd(-1)
{
}
po6 :: net :: socket :: ~socket() throw ()
{
}
bool
po6 :: net :: socket :: reset(int domain, int type, int protocol)
{
*this = ::socket(domain, type, protocol);
return get() >= 0;
}
// On all platforms I checked, a sockaddr_in6 is larger than a
// sockaddr, which in turn is larger than a sockaddr_in. As a
// result, we allocate the largest of the three and call it a
// sockaddr.
bool
po6 :: net :: socket :: bind(const ipaddr& addr, in_port_t port)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
addr.pack(sa, &salen, port);
return ::bind(get(), sa, salen) == 0;
}
bool
po6 :: net :: socket :: bind(const ipaddr& addr)
{
return bind(addr, 0);
}
bool
po6 :: net :: socket :: bind(const location& loc)
{
return bind(loc.address, loc.port);
}
bool
po6 :: net :: socket :: connect(const ipaddr& addr, in_port_t port)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
addr.pack(sa, &salen, port);
return ::connect(get(), sa, salen) == 0;
}
bool
po6 :: net :: socket :: connect(const location& loc)
{
return connect(loc.address, loc.port);
}
bool
po6 :: net :: socket :: listen(int backlog)
{
return ::listen(get(), backlog) == 0;
}
bool
po6 :: net :: socket :: accept(socket* newsock)
{
newsock->close();
int ret;
if ((ret = ::accept(get(), NULL, NULL)) < 0)
{
return false;
}
*newsock = ret;
return true;
}
bool
po6 :: net :: socket :: shutdown(int how)
{
return ::shutdown(get(), how) == 0;
}
bool
po6 :: net :: socket :: getpeername(location* loc)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
if (::getpeername(get(), sa, &salen) < 0)
{
return false;
}
return loc->set(sa, salen);
}
bool
po6 :: net :: socket :: getsockname(location* loc)
{
sockaddr_in6 sa6;
socklen_t salen = sizeof(sa6);
sockaddr* sa = reinterpret_cast<sockaddr*>(&sa6);
if (::getsockname(get(), sa, &salen) < 0)
{
return false;
}
return loc->set(sa, salen);
}
bool
po6 :: net :: socket :: set_sockopt(int level, int optname,
const void *optval, socklen_t optlen)
{
return setsockopt(get(), level, optname, optval, optlen) == 0;
}
bool
po6 :: net :: socket :: set_reuseaddr()
{
int yes = 1;
return set_sockopt(SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
}
bool
po6 :: net :: socket :: set_tcp_nodelay()
{
int yes = 1;
return set_sockopt(IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
}
bool
po6 :: net :: socket :: sndbuf(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
}
bool
po6 :: net :: socket :: rcvbuf(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
}
bool
po6 :: net :: socket :: sndlowat(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_SNDLOWAT, &size, sizeof(size));
}
bool
po6 :: net :: socket :: rcvlowat(size_t size)
{
return set_sockopt(SOL_SOCKET, SO_RCVLOWAT, &size, sizeof(size));
}
ssize_t
po6 :: net :: socket :: recv(void *buf, size_t len, int flags)
{
return ::recv(get(), buf, len, flags);
}
ssize_t
po6 :: net :: socket :: xrecv(void *buf, size_t len, int flags)
{
size_t rem = len;
ssize_t amt = 0;
while (rem > 0)
{
if ((amt = recv(buf, rem, flags)) < 0)
{
if (rem == len)
{
return -1;
}
else
{
break;
}
}
else if (amt == 0)
{
break;
}
rem -= amt;
buf = static_cast<char*>(buf) + amt;
}
return len - rem;
}
ssize_t
po6 :: net :: socket :: send(const void *buf, size_t len, int flags)
{
return ::send(get(), buf, len, flags);
}
ssize_t
po6 :: net :: socket :: xsend(const void *buf, size_t len, int flags)
{
size_t rem = len;
ssize_t amt = 0;
while (rem > 0)
{
if ((amt = send(buf, rem, flags)) < 0)
{
if (rem == len)
{
return -1;
}
else
{
break;
}
}
else if (amt == 0)
{
break;
}
rem -= amt;
buf = static_cast<const char*>(buf) + amt;
}
return len - rem;
}
po6::net::socket&
po6 :: net :: socket :: operator = (int f)
{
*dynamic_cast<fd*>(this) = f;
return *this;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <memory>
#ifdef WITH_RUNTIME_STATS
# include "runtime_stats.cpp" // must be included before anything else
#endif
#include "input_data.cpp"
#include "quicksort-all.cpp"
#include "avx2-altquicksort.h"
#define USE_RDTSC // undef to get measurments in seconds
#ifdef USE_RDTSC
# include "rdtsc.cpp"
#else
# include "gettime.cpp"
#endif
class PerformanceTest final {
int iterations;
InputData& input;
uint32_t* tmp;
public:
PerformanceTest(int n, InputData& input)
: iterations(n)
, input(input) {
assert(iterations > 0);
tmp = new uint32_t[input.count()];
}
~PerformanceTest() {
delete[] tmp;
}
public:
template <typename SORT_FUNCTION>
uint64_t run(SORT_FUNCTION sort) {
uint64_t time = 0;
int k = iterations;
while (k--) {
memcpy(tmp, input.pointer(), input.size());
uint64_t t1, t2;
#ifdef USE_RDTSC
RDTSC_START(t1);
#else
t1 = get_time();
#endif
sort(input.pointer(), 0, input.count() - 1);
#ifdef USE_RDTSC
RDTSC_START(t2);
#else
t1 = get_time();
#endif
const uint64_t dt = t2 - t1;
if (time == 0) {
time = dt;
} else if (dt < time) {
time = dt;
}
}
return time;
}
};
enum class InputType {
randomfew,
randomuniq,
random,
ascending,
descending,
};
const char* as_string(InputType type) {
switch (type) {
case InputType::randomfew:
return "randomfew";
case InputType::randomuniq:
return "randomuniq";
case InputType::random:
return "random";
case InputType::ascending:
return "ascending";
case InputType::descending:
return "descending";
default:
return "<unknown>";
}
}
void std_qsort_wrapper(uint32_t* array, int left, int right) {
std::qsort(array + left, right - left + 1, sizeof(uint32_t), [](const void* a, const void* b)
{
uint32_t a1 = *static_cast<const uint32_t*>(a);
uint32_t a2 = *static_cast<const uint32_t*>(b);
if(a1 < a2) return -1;
if(a1 > a2) return 1;
return 0;
});
}
void std_stable_sort_wrapper(uint32_t* array, int left, int right) {
std::stable_sort(array + left, array + right + 1);
}
void std_sort_wrapper(uint32_t* array, int left, int right) {
std::sort(array + left, array + right + 1);
}
class Test {
std::unique_ptr<InputData> data;
InputType type;
size_t count;
int iterations;
public:
Test(InputType type, size_t count, int iterations)
: type(type)
, count(count)
, iterations(iterations) {
switch (type) {
case InputType::randomfew:
data.reset(new InputRandomFew(count));
break;
case InputType::randomuniq:
data.reset(new InputRandomUnique(count));
break;
case InputType::random:
data.reset(new InputRandom(count));
break;
case InputType::ascending:
data.reset(new InputAscending(count));
break;
case InputType::descending:
data.reset(new InputDescending(count));
break;
}
}
void run() {
printf("items count: %lu (%lu bytes), input %s\n", data->count(), data->size(), as_string(type));
uint64_t ref = 0;
ref = measure("std::sort", std_sort_wrapper, ref);
measure("std::qsort", std_qsort_wrapper, ref);
measure("std::stable_sort", std_stable_sort_wrapper, ref);
measure("quick sort", quicksort, ref);
#ifdef HAVE_AVX2_INSTRUCTIONS
measure("AVX2 quick sort", qs::avx2::quicksort, ref);
measure("AVX2 alt quicksort", wrapped_avx2_pivotonlast_sort,ref);
#endif
#ifdef HAVE_AVX512F_INSTRUCTIONS
measure("AVX512 quick sort", qs::avx512::quicksort, ref);
measure("AVX512 quick sort - aux buf", qs::avx512::auxbuffer_quicksort, ref);
measure("AVX512 + popcnt quick sort", qs::avx512::popcnt_quicksort, ref);
measure("AVX512 + BMI2 quick sort", qs::avx512::bmi2_quicksort, ref);
#endif
}
private:
template <typename SORT_FUNCTION>
uint64_t measure(const char* name, SORT_FUNCTION sort, uint64_t ref) {
PerformanceTest test(iterations, *data);
printf("%30s ... ", name); fflush(stdout);
#ifdef WITH_RUNTIME_STATS
statistics.reset();
#endif
uint64_t time = test.run(sort);
#ifdef USE_RDTSC
printf("%10lu cycles", time);
if (ref > 0) {
printf(" (%0.2f)", ref/double(time));
}
# ifdef WITH_RUNTIME_STATS
if (statistics.anything_collected()) {
printf("\n");
printf("\t\tpartition calls: %lu (+%lu scalar)\n", statistics.partition_calls, statistics.scalar__partition_calls);
printf("\t\titems processed: %lu (+%lu by scalar partition)\n", statistics.items_processed, statistics.scalar__items_processed);
const size_t total_items = statistics.items_processed + statistics.scalar__items_processed;
if (total_items != 0) {
const double cpi = double(time)/total_items;
printf("\t\t : %0.4f cycles/item\n", cpi * iterations);
}
}
# endif // WITH_RUNTIME_STATS
#else
printf("%0.4f s", time/1000000.0);
if (ref > 0) {
printf(" (%0.2f)\n", ref/double(time));
}
#endif
putchar('\n');
return time;
}
};
// ------------------------------------------------------------
void usage() {
puts("usage:");
puts("speed SIZE ITERATIONS INPUT");
puts("");
puts("where");
puts("* SIZE - number of 32-bit elements");
puts("* ITERATIONS - number of iterations");
puts("* INPUT - one of:");
puts(" ascending (or asc)");
puts(" descending (or dsc, desc)");
puts(" random (or rnd, rand)");
puts(" randomfew");
puts(" randomuniq");
}
int main(int argc, char* argv[]) {
if (argc < 4) {
usage();
return EXIT_FAILURE;
}
int count = atoi(argv[1]);
int iterations = atoi(argv[2]);
InputType type;
#define is_keyword(key) (strcmp(argv[3], key) == 0)
if (is_keyword("descending") || is_keyword("desc") || is_keyword("dsc")) {
type = InputType::descending;
} else if (is_keyword("ascending") || is_keyword("asc")) {
type = InputType::ascending;
} else if (is_keyword("random") || is_keyword("rnd") || is_keyword("rand")) {
type = InputType::random;
} else if (is_keyword("randomfew")) {
type = InputType::randomfew;
} else if (is_keyword("randomuniq")) {
type = InputType::randomuniq;
} else {
usage();
return EXIT_FAILURE;
}
#undef is_keyword
#ifdef USE_RDTSC
RDTSC_SET_OVERHEAD(rdtsc_overhead_func(1), iterations);
#endif
Test test(type, count, iterations);
test.run();
return EXIT_SUCCESS;
}
<commit_msg>speed util: parse command line<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <memory>
#include "cmdline.cpp"
#ifdef WITH_RUNTIME_STATS
# include "runtime_stats.cpp" // must be included before anything else
#endif
#include "input_data.cpp"
#include "quicksort-all.cpp"
#include "avx2-altquicksort.h"
#define USE_RDTSC // undef to get measurments in seconds
#ifdef USE_RDTSC
# include "rdtsc.cpp"
#else
# include "gettime.cpp"
#endif
class PerformanceTest final {
int iterations;
InputData& input;
uint32_t* tmp;
public:
PerformanceTest(int n, InputData& input)
: iterations(n)
, input(input) {
assert(iterations > 0);
tmp = new uint32_t[input.count()];
}
~PerformanceTest() {
delete[] tmp;
}
public:
template <typename SORT_FUNCTION>
uint64_t run(SORT_FUNCTION sort) {
uint64_t time = 0;
int k = iterations;
while (k--) {
memcpy(tmp, input.pointer(), input.size());
uint64_t t1, t2;
#ifdef USE_RDTSC
RDTSC_START(t1);
#else
t1 = get_time();
#endif
sort(input.pointer(), 0, input.count() - 1);
#ifdef USE_RDTSC
RDTSC_START(t2);
#else
t1 = get_time();
#endif
const uint64_t dt = t2 - t1;
if (time == 0) {
time = dt;
} else if (dt < time) {
time = dt;
}
}
return time;
}
};
enum class InputType {
randomfew,
randomuniq,
random,
ascending,
descending,
};
const char* as_string(InputType type) {
switch (type) {
case InputType::randomfew:
return "randomfew";
case InputType::randomuniq:
return "randomuniq";
case InputType::random:
return "random";
case InputType::ascending:
return "ascending";
case InputType::descending:
return "descending";
default:
return "<unknown>";
}
}
void std_qsort_wrapper(uint32_t* array, int left, int right) {
std::qsort(array + left, right - left + 1, sizeof(uint32_t), [](const void* a, const void* b)
{
uint32_t a1 = *static_cast<const uint32_t*>(a);
uint32_t a2 = *static_cast<const uint32_t*>(b);
if(a1 < a2) return -1;
if(a1 > a2) return 1;
return 0;
});
}
void std_stable_sort_wrapper(uint32_t* array, int left, int right) {
std::stable_sort(array + left, array + right + 1);
}
void std_sort_wrapper(uint32_t* array, int left, int right) {
std::sort(array + left, array + right + 1);
}
class Flags {
public:
bool std_sort;
bool std_qsort;
bool std_stable_sort;
bool quicksort;
bool avx2;
bool avx2_alt;
bool avx512;
bool avx512_buf;
bool avx512_popcnt;
bool avx512_bmi;
public:
Flags(const CommandLine& cmd) {
enable_all(false);
bool any_set = false;
if (cmd.has("-std-sort")) {
std_sort = true;
any_set = true;
}
if (cmd.has("-std-qsort")) {
std_qsort = true;
any_set = true;
}
if (cmd.has("-std-stable-sort") || cmd.has("-std-stable")) {
std_stable_sort = true;
any_set = true;
}
if (cmd.has("-quicksort")) {
quicksort = true;
any_set = true;
}
if (cmd.has("-avx2")) {
avx2 = true;
any_set = true;
}
if (cmd.has("-avx2-alt")) {
avx2_alt = true;
any_set = true;
}
if (cmd.has("-avx512")) {
avx512 = true;
any_set = true;
}
if (cmd.has("-avx512-buf")) {
avx512_buf = true;
any_set = true;
}
if (cmd.has("-avx512-popcnt")) {
avx512_popcnt = true;
any_set = true;
}
if (cmd.has("-avx512-bmi")) {
avx512_bmi = true;
any_set = true;
}
if (!any_set) {
enable_all(true);
}
}
void enable_all(bool val) {
std_sort = val;
std_qsort = val;
std_stable_sort = val;
quicksort = val;
avx2 = val;
avx2_alt = val;
avx512 = val;
avx512_buf = val;
avx512_popcnt = val;
avx512_bmi = val;
}
};
class Test {
std::unique_ptr<InputData> data;
InputType type;
size_t count;
int iterations;
Flags flags;
uint64_t ref;
public:
Test(InputType type, size_t count, int iterations, Flags&& flags)
: type(type)
, count(count)
, iterations(iterations)
, flags(std::move(flags)) {
switch (type) {
case InputType::randomfew:
data.reset(new InputRandomFew(count));
break;
case InputType::randomuniq:
data.reset(new InputRandomUnique(count));
break;
case InputType::random:
data.reset(new InputRandom(count));
break;
case InputType::ascending:
data.reset(new InputAscending(count));
break;
case InputType::descending:
data.reset(new InputDescending(count));
break;
}
}
void run() {
printf("items count: %lu (%lu bytes), input %s\n", data->count(), data->size(), as_string(type));
ref = 0;
if (flags.std_sort) {
measure("std::sort", std_sort_wrapper);
}
if (flags.std_qsort) {
measure("std::qsort", std_qsort_wrapper);
}
if (flags.std_stable_sort) {
measure("std::stable_sort", std_stable_sort_wrapper);
}
if (flags.std_qsort) {
measure("quick sort", quicksort);
}
#ifdef HAVE_AVX2_INSTRUCTIONS
if (flags.avx2) {
measure("AVX2 quick sort", qs::avx2::quicksort);
}
if (flags.avx2_alt) {
measure("AVX2 alt quicksort", wrapped_avx2_pivotonlast_sort);
}
#endif
#ifdef HAVE_AVX512F_INSTRUCTIONS
if (flags.avx512) {
measure("AVX512 quick sort", qs::avx512::quicksort);
}
if (flags.avx512_buf) {
measure("AVX512 quick sort - aux buf", qs::avx512::auxbuffer_quicksort);
}
if (flags.avx512_popcnt) {
measure("AVX512 + popcnt quick sort", qs::avx512::popcnt_quicksort);
}
if (flags.avx512_bmi) {
measure("AVX512 + BMI2 quick sort", qs::avx512::bmi2_quicksort);
}
#endif
}
private:
template <typename SORT_FUNCTION>
void measure(const char* name, SORT_FUNCTION sort) {
PerformanceTest test(iterations, *data);
printf("%30s ... ", name); fflush(stdout);
#ifdef WITH_RUNTIME_STATS
statistics.reset();
#endif
uint64_t time = test.run(sort);
#ifdef USE_RDTSC
printf("%10lu cycles", time);
if (ref > 0) {
printf(" (%0.2f)", ref/double(time));
}
# ifdef WITH_RUNTIME_STATS
if (statistics.anything_collected()) {
printf("\n");
printf("\t\tpartition calls: %lu (+%lu scalar)\n", statistics.partition_calls, statistics.scalar__partition_calls);
printf("\t\titems processed: %lu (+%lu by scalar partition)\n", statistics.items_processed, statistics.scalar__items_processed);
const size_t total_items = statistics.items_processed + statistics.scalar__items_processed;
if (total_items != 0) {
const double cpi = double(time)/total_items;
printf("\t\t : %0.4f cycles/item\n", cpi * iterations);
}
}
# endif // WITH_RUNTIME_STATS
#else
printf("%0.4f s", time/1000000.0);
if (ref > 0) {
printf(" (%0.2f)\n", ref/double(time));
}
#endif
putchar('\n');
if (ref == 0) {
ref = time;
}
}
};
// ------------------------------------------------------------
void usage() {
puts("usage:");
puts("speed SIZE ITERATIONS INPUT [options]");
puts("");
puts("where");
puts("* SIZE - number of 32-bit elements");
puts("* ITERATIONS - number of iterations");
puts("* INPUT - one of:");
puts(" ascending (or asc)");
puts(" descending (or dsc, desc)");
puts(" random (or rnd, rand)");
puts(" randomfew");
puts(" randomuniq");
puts("options - optional name of procedure(s) to run");
}
int main(int argc, char* argv[]) {
if (argc < 4) {
usage();
return EXIT_FAILURE;
}
int count = atoi(argv[1]);
int iterations = atoi(argv[2]);
InputType type;
#define is_keyword(key) (strcmp(argv[3], key) == 0)
if (is_keyword("descending") || is_keyword("desc") || is_keyword("dsc")) {
type = InputType::descending;
} else if (is_keyword("ascending") || is_keyword("asc")) {
type = InputType::ascending;
} else if (is_keyword("random") || is_keyword("rnd") || is_keyword("rand")) {
type = InputType::random;
} else if (is_keyword("randomfew")) {
type = InputType::randomfew;
} else if (is_keyword("randomuniq")) {
type = InputType::randomuniq;
} else {
usage();
return EXIT_FAILURE;
}
#undef is_keyword
#ifdef USE_RDTSC
RDTSC_SET_OVERHEAD(rdtsc_overhead_func(1), iterations);
#endif
CommandLine cmd(argc, argv);
Flags flags(cmd);
Test test(type, count, iterations, std::move(flags));
test.run();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2002 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "mysql_priv.h"
#include "sp.h"
#include "sp_head.h"
#include "sp_cache.h"
/*
*
* DB storage of Stored PROCEDUREs and FUNCTIONs
*
*/
// *opened=true means we opened ourselves
static int
db_find_routine_aux(THD *thd, int type, char *name, uint namelen,
enum thr_lock_type ltype, TABLE **tablep, bool *opened)
{
DBUG_ENTER("db_find_routine_aux");
DBUG_PRINT("enter", ("type: %d name: %*s", type, namelen, name));
TABLE *table;
byte key[65]; // We know name is 64 and the enum is 1 byte
uint keylen;
int ret;
// Put the key together
keylen= namelen;
if (keylen > sizeof(key)-1)
keylen= sizeof(key)-1;
memcpy(key, name, keylen);
memset(key+keylen, (int)' ', sizeof(key)-1 - keylen); // Pad with space
key[sizeof(key)-1]= type;
keylen= sizeof(key);
for (table= thd->open_tables ; table ; table= table->next)
if (strcmp(table->table_cache_key, "mysql") == 0 &&
strcmp(table->real_name, "proc") == 0)
break;
if (table)
*opened= FALSE;
else
{
TABLE_LIST tables;
memset(&tables, 0, sizeof(tables));
tables.db= (char*)"mysql";
tables.real_name= tables.alias= (char*)"proc";
if (! (table= open_ltable(thd, &tables, ltype)))
{
*tablep= NULL;
DBUG_RETURN(SP_OPEN_TABLE_FAILED);
}
*opened= TRUE;
}
if (table->file->index_read_idx(table->record[0], 0,
key, keylen,
HA_READ_KEY_EXACT))
{
*tablep= NULL;
DBUG_RETURN(SP_KEY_NOT_FOUND);
}
*tablep= table;
DBUG_RETURN(SP_OK);
}
static int
db_find_routine(THD *thd, int type, char *name, uint namelen, sp_head **sphp)
{
DBUG_ENTER("db_find_routine");
DBUG_PRINT("enter", ("type: %d name: %*s", type, namelen, name));
extern int yyparse(void *thd);
TABLE *table;
const char *defstr;
int ret;
bool opened;
const char *creator;
longlong created;
longlong modified;
bool suid= 1;
char *ptr;
uint length;
char buff[65];
String str(buff, sizeof(buff), &my_charset_bin);
ret= db_find_routine_aux(thd, type, name, namelen, TL_READ, &table, &opened);
if (ret != SP_OK)
goto done;
if ((defstr= get_field(&thd->mem_root, table->field[2])) == NULL)
{
ret= SP_GET_FIELD_FAILED;
goto done;
}
// Get additional information
if ((creator= get_field(&thd->mem_root, table->field[3])) == NULL)
{
ret= SP_GET_FIELD_FAILED;
goto done;
}
modified= table->field[4]->val_int();
created= table->field[5]->val_int();
if ((ptr= get_field(&thd->mem_root, table->field[6])) == NULL)
{
ret= SP_GET_FIELD_FAILED;
goto done;
}
if (ptr[0] == 'N')
suid= 0;
table->field[7]->val_str(&str, &str);
ptr= 0;
if ((length= str.length()))
ptr= strmake_root(&thd->mem_root, str.ptr(), length);
if (opened)
{
close_thread_tables(thd, 0, 1);
table= NULL;
}
{
LEX *oldlex= thd->lex;
enum enum_sql_command oldcmd= thd->lex->sql_command;
lex_start(thd, (uchar*)defstr, strlen(defstr));
if (yyparse(thd) || thd->is_fatal_error || thd->lex->sphead == NULL)
{
LEX *newlex= thd->lex;
sp_head *sp= newlex->sphead;
if (sp)
{
if (oldlex != newlex)
sp->restore_lex(thd);
delete sp;
newlex->sphead= NULL;
}
ret= SP_PARSE_ERROR;
}
else
{
*sphp= thd->lex->sphead;
(*sphp)->sp_set_info((char *) creator, (uint) strlen(creator),
created, modified, suid,
ptr, length);
}
thd->lex->sql_command= oldcmd;
}
done:
if (table && opened)
close_thread_tables(thd);
DBUG_RETURN(ret);
}
static int
db_create_routine(THD *thd, int type,
char *name, uint namelen, char *def, uint deflen,
char *comment, uint commentlen, bool suid)
{
DBUG_ENTER("db_create_routine");
DBUG_PRINT("enter", ("type: %d name: %*s def: %*s", type, namelen, name, deflen, def));
int ret;
TABLE *table;
TABLE_LIST tables;
char creator[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
memset(&tables, 0, sizeof(tables));
tables.db= (char*)"mysql";
tables.real_name= tables.alias= (char*)"proc";
if (! (table= open_ltable(thd, &tables, TL_WRITE)))
ret= SP_OPEN_TABLE_FAILED;
else
{
restore_record(table, default_values); // Get default values for fields
strxmov(creator, thd->user, "@", thd->host_or_ip, NullS);
table->field[0]->store(name, namelen, system_charset_info);
table->field[1]->store((longlong)type);
table->field[2]->store(def, deflen, system_charset_info);
table->field[3]->store(creator, (uint)strlen(creator), system_charset_info);
((Field_timestamp *)table->field[5])->set_time();
if (suid)
table->field[6]->store((longlong)suid);
if (comment)
table->field[7]->store(comment, commentlen, system_charset_info);
if (table->file->write_row(table->record[0]))
ret= SP_WRITE_ROW_FAILED;
else
ret= SP_OK;
}
close_thread_tables(thd);
DBUG_RETURN(ret);
}
static int
db_drop_routine(THD *thd, int type, char *name, uint namelen)
{
DBUG_ENTER("db_drop_routine");
DBUG_PRINT("enter", ("type: %d name: %*s", type, namelen, name));
TABLE *table;
int ret;
bool opened;
ret= db_find_routine_aux(thd, type, name, namelen, TL_WRITE, &table, &opened);
if (ret == SP_OK)
{
if (table->file->delete_row(table->record[0]))
ret= SP_DELETE_ROW_FAILED;
}
if (opened)
close_thread_tables(thd);
DBUG_RETURN(ret);
}
/*
*
* PROCEDURE
*
*/
sp_head *
sp_find_procedure(THD *thd, LEX_STRING *name)
{
DBUG_ENTER("sp_find_procedure");
sp_head *sp;
DBUG_PRINT("enter", ("name: %*s", name->length, name->str));
sp= thd->sp_proc_cache->lookup(name->str, name->length);
if (! sp)
{
if (db_find_routine(thd, TYPE_ENUM_PROCEDURE,
name->str, name->length, &sp) == SP_OK)
{
thd->sp_proc_cache->insert(sp);
}
}
DBUG_RETURN(sp);
}
int
sp_create_procedure(THD *thd, char *name, uint namelen, char *def, uint deflen,
char *comment, uint commentlen, bool suid)
{
DBUG_ENTER("sp_create_procedure");
DBUG_PRINT("enter", ("name: %*s def: %*s", namelen, name, deflen, def));
int ret;
ret= db_create_routine(thd, TYPE_ENUM_PROCEDURE, name, namelen, def, deflen,
comment, commentlen, suid);
DBUG_RETURN(ret);
}
int
sp_drop_procedure(THD *thd, char *name, uint namelen)
{
DBUG_ENTER("sp_drop_procedure");
DBUG_PRINT("enter", ("name: %*s", namelen, name));
sp_head *sp;
int ret;
sp= thd->sp_proc_cache->lookup(name, namelen);
if (sp)
{
thd->sp_proc_cache->remove(sp);
delete sp;
}
ret= db_drop_routine(thd, TYPE_ENUM_PROCEDURE, name, namelen);
DBUG_RETURN(ret);
}
/*
*
* FUNCTION
*
*/
sp_head *
sp_find_function(THD *thd, LEX_STRING *name)
{
DBUG_ENTER("sp_find_function");
sp_head *sp;
DBUG_PRINT("enter", ("name: %*s", name->length, name->str));
sp= thd->sp_func_cache->lookup(name->str, name->length);
if (! sp)
{
if (db_find_routine(thd, TYPE_ENUM_FUNCTION,
name->str, name->length, &sp) != SP_OK)
sp= NULL;
}
DBUG_RETURN(sp);
}
int
sp_create_function(THD *thd, char *name, uint namelen, char *def, uint deflen,
char *comment, uint commentlen, bool suid)
{
DBUG_ENTER("sp_create_function");
DBUG_PRINT("enter", ("name: %*s def: %*s", namelen, name, deflen, def));
int ret;
ret= db_create_routine(thd, TYPE_ENUM_FUNCTION, name, namelen, def, deflen,
comment, commentlen, suid);
DBUG_RETURN(ret);
}
int
sp_drop_function(THD *thd, char *name, uint namelen)
{
DBUG_ENTER("sp_drop_function");
DBUG_PRINT("enter", ("name: %*s", namelen, name));
sp_head *sp;
int ret;
sp= thd->sp_func_cache->lookup(name, namelen);
if (sp)
{
thd->sp_func_cache->remove(sp);
delete sp;
}
ret= db_drop_routine(thd, TYPE_ENUM_FUNCTION, name, namelen);
DBUG_RETURN(ret);
}
// QQ Temporary until the function call detection in sql_lex has been reworked.
bool
sp_function_exists(THD *thd, LEX_STRING *name)
{
TABLE *table;
bool ret= FALSE;
bool opened= FALSE;
if (thd->sp_func_cache->lookup(name->str, name->length) ||
db_find_routine_aux(thd, TYPE_ENUM_FUNCTION,
name->str, name->length, TL_READ,
&table, &opened) == SP_OK)
{
ret= TRUE;
}
if (opened)
close_thread_tables(thd, 0, 1);
return ret;
}
byte *
sp_lex_spfuns_key(const byte *ptr, uint *plen, my_bool first)
{
LEX_STRING *lsp= (LEX_STRING *)ptr;
*plen= lsp->length;
return (byte *)lsp->str;
}
void
sp_add_fun_to_lex(LEX *lex, LEX_STRING fun)
{
if (! hash_search(&lex->spfuns, (byte *)fun.str, fun.length))
{
LEX_STRING *ls= (LEX_STRING *)sql_alloc(sizeof(LEX_STRING));
ls->str= sql_strmake(fun.str, fun.length);
ls->length= fun.length;
hash_insert(&lex->spfuns, (byte *)ls);
}
}
void
sp_merge_funs(LEX *dst, LEX *src)
{
for (uint i=0 ; i < src->spfuns.records ; i++)
{
LEX_STRING *ls= (LEX_STRING *)hash_element(&src->spfuns, i);
if (! hash_search(&dst->spfuns, (byte *)ls->str, ls->length))
hash_insert(&dst->spfuns, (byte *)ls);
}
}
int
sp_cache_functions(THD *thd, LEX *lex)
{
HASH *h= &lex->spfuns;
int ret= 0;
for (uint i=0 ; i < h->records ; i++)
{
LEX_STRING *ls= (LEX_STRING *)hash_element(h, i);
if (! thd->sp_func_cache->lookup(ls->str, ls->length))
{
sp_head *sp;
LEX *oldlex= thd->lex;
LEX *newlex= new st_lex;
thd->lex= newlex;
if (db_find_routine(thd, TYPE_ENUM_FUNCTION, ls->str, ls->length, &sp)
== SP_OK)
{
ret= sp_cache_functions(thd, newlex);
delete newlex;
thd->lex= oldlex;
if (ret)
break;
thd->sp_func_cache->insert(sp);
}
else
{
delete newlex;
thd->lex= oldlex;
net_printf(thd, ER_SP_DOES_NOT_EXIST, "FUNCTION", ls->str);
ret= 1;
break;
}
}
}
return ret;
}
<commit_msg>Fix bug in sp.cc:db_find_routine() which made tables remain open in some cases.<commit_after>/* Copyright (C) 2002 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "mysql_priv.h"
#include "sp.h"
#include "sp_head.h"
#include "sp_cache.h"
/*
*
* DB storage of Stored PROCEDUREs and FUNCTIONs
*
*/
// *opened=true means we opened ourselves
static int
db_find_routine_aux(THD *thd, int type, char *name, uint namelen,
enum thr_lock_type ltype, TABLE **tablep, bool *opened)
{
DBUG_ENTER("db_find_routine_aux");
DBUG_PRINT("enter", ("type: %d name: %*s", type, namelen, name));
TABLE *table;
byte key[65]; // We know name is 64 and the enum is 1 byte
uint keylen;
int ret;
// Put the key together
keylen= namelen;
if (keylen > sizeof(key)-1)
keylen= sizeof(key)-1;
memcpy(key, name, keylen);
memset(key+keylen, (int)' ', sizeof(key)-1 - keylen); // Pad with space
key[sizeof(key)-1]= type;
keylen= sizeof(key);
for (table= thd->open_tables ; table ; table= table->next)
if (strcmp(table->table_cache_key, "mysql") == 0 &&
strcmp(table->real_name, "proc") == 0)
break;
if (table)
*opened= FALSE;
else
{
TABLE_LIST tables;
memset(&tables, 0, sizeof(tables));
tables.db= (char*)"mysql";
tables.real_name= tables.alias= (char*)"proc";
if (! (table= open_ltable(thd, &tables, ltype)))
{
*tablep= NULL;
DBUG_RETURN(SP_OPEN_TABLE_FAILED);
}
*opened= TRUE;
}
if (table->file->index_read_idx(table->record[0], 0,
key, keylen,
HA_READ_KEY_EXACT))
{
*tablep= NULL;
DBUG_RETURN(SP_KEY_NOT_FOUND);
}
*tablep= table;
DBUG_RETURN(SP_OK);
}
static int
db_find_routine(THD *thd, int type, char *name, uint namelen, sp_head **sphp)
{
DBUG_ENTER("db_find_routine");
DBUG_PRINT("enter", ("type: %d name: %*s", type, namelen, name));
extern int yyparse(void *thd);
TABLE *table;
const char *defstr;
int ret;
bool opened;
const char *creator;
longlong created;
longlong modified;
bool suid= 1;
char *ptr;
uint length;
char buff[65];
String str(buff, sizeof(buff), &my_charset_bin);
ret= db_find_routine_aux(thd, type, name, namelen, TL_READ, &table, &opened);
if (ret != SP_OK)
goto done;
if ((defstr= get_field(&thd->mem_root, table->field[2])) == NULL)
{
ret= SP_GET_FIELD_FAILED;
goto done;
}
// Get additional information
if ((creator= get_field(&thd->mem_root, table->field[3])) == NULL)
{
ret= SP_GET_FIELD_FAILED;
goto done;
}
modified= table->field[4]->val_int();
created= table->field[5]->val_int();
if ((ptr= get_field(&thd->mem_root, table->field[6])) == NULL)
{
ret= SP_GET_FIELD_FAILED;
goto done;
}
if (ptr[0] == 'N')
suid= 0;
table->field[7]->val_str(&str, &str);
ptr= 0;
if ((length= str.length()))
ptr= strmake_root(&thd->mem_root, str.ptr(), length);
if (opened)
{
close_thread_tables(thd, 0, 1);
opened= FALSE;
}
{
LEX *oldlex= thd->lex;
enum enum_sql_command oldcmd= thd->lex->sql_command;
lex_start(thd, (uchar*)defstr, strlen(defstr));
if (yyparse(thd) || thd->is_fatal_error || thd->lex->sphead == NULL)
{
LEX *newlex= thd->lex;
sp_head *sp= newlex->sphead;
if (sp)
{
if (oldlex != newlex)
sp->restore_lex(thd);
delete sp;
newlex->sphead= NULL;
}
ret= SP_PARSE_ERROR;
}
else
{
*sphp= thd->lex->sphead;
(*sphp)->sp_set_info((char *) creator, (uint) strlen(creator),
created, modified, suid,
ptr, length);
}
thd->lex->sql_command= oldcmd;
}
done:
if (opened)
close_thread_tables(thd);
DBUG_RETURN(ret);
}
static int
db_create_routine(THD *thd, int type,
char *name, uint namelen, char *def, uint deflen,
char *comment, uint commentlen, bool suid)
{
DBUG_ENTER("db_create_routine");
DBUG_PRINT("enter", ("type: %d name: %*s def: %*s", type, namelen, name, deflen, def));
int ret;
TABLE *table;
TABLE_LIST tables;
char creator[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
memset(&tables, 0, sizeof(tables));
tables.db= (char*)"mysql";
tables.real_name= tables.alias= (char*)"proc";
if (! (table= open_ltable(thd, &tables, TL_WRITE)))
ret= SP_OPEN_TABLE_FAILED;
else
{
restore_record(table, default_values); // Get default values for fields
strxmov(creator, thd->user, "@", thd->host_or_ip, NullS);
table->field[0]->store(name, namelen, system_charset_info);
table->field[1]->store((longlong)type);
table->field[2]->store(def, deflen, system_charset_info);
table->field[3]->store(creator, (uint)strlen(creator), system_charset_info);
((Field_timestamp *)table->field[5])->set_time();
if (suid)
table->field[6]->store((longlong)suid);
if (comment)
table->field[7]->store(comment, commentlen, system_charset_info);
if (table->file->write_row(table->record[0]))
ret= SP_WRITE_ROW_FAILED;
else
ret= SP_OK;
}
close_thread_tables(thd);
DBUG_RETURN(ret);
}
static int
db_drop_routine(THD *thd, int type, char *name, uint namelen)
{
DBUG_ENTER("db_drop_routine");
DBUG_PRINT("enter", ("type: %d name: %*s", type, namelen, name));
TABLE *table;
int ret;
bool opened;
ret= db_find_routine_aux(thd, type, name, namelen, TL_WRITE, &table, &opened);
if (ret == SP_OK)
{
if (table->file->delete_row(table->record[0]))
ret= SP_DELETE_ROW_FAILED;
}
if (opened)
close_thread_tables(thd);
DBUG_RETURN(ret);
}
/*
*
* PROCEDURE
*
*/
sp_head *
sp_find_procedure(THD *thd, LEX_STRING *name)
{
DBUG_ENTER("sp_find_procedure");
sp_head *sp;
DBUG_PRINT("enter", ("name: %*s", name->length, name->str));
sp= thd->sp_proc_cache->lookup(name->str, name->length);
if (! sp)
{
if (db_find_routine(thd, TYPE_ENUM_PROCEDURE,
name->str, name->length, &sp) == SP_OK)
{
thd->sp_proc_cache->insert(sp);
}
}
DBUG_RETURN(sp);
}
int
sp_create_procedure(THD *thd, char *name, uint namelen, char *def, uint deflen,
char *comment, uint commentlen, bool suid)
{
DBUG_ENTER("sp_create_procedure");
DBUG_PRINT("enter", ("name: %*s def: %*s", namelen, name, deflen, def));
int ret;
ret= db_create_routine(thd, TYPE_ENUM_PROCEDURE, name, namelen, def, deflen,
comment, commentlen, suid);
DBUG_RETURN(ret);
}
int
sp_drop_procedure(THD *thd, char *name, uint namelen)
{
DBUG_ENTER("sp_drop_procedure");
DBUG_PRINT("enter", ("name: %*s", namelen, name));
sp_head *sp;
int ret;
sp= thd->sp_proc_cache->lookup(name, namelen);
if (sp)
{
thd->sp_proc_cache->remove(sp);
delete sp;
}
ret= db_drop_routine(thd, TYPE_ENUM_PROCEDURE, name, namelen);
DBUG_RETURN(ret);
}
/*
*
* FUNCTION
*
*/
sp_head *
sp_find_function(THD *thd, LEX_STRING *name)
{
DBUG_ENTER("sp_find_function");
sp_head *sp;
DBUG_PRINT("enter", ("name: %*s", name->length, name->str));
sp= thd->sp_func_cache->lookup(name->str, name->length);
if (! sp)
{
if (db_find_routine(thd, TYPE_ENUM_FUNCTION,
name->str, name->length, &sp) != SP_OK)
sp= NULL;
}
DBUG_RETURN(sp);
}
int
sp_create_function(THD *thd, char *name, uint namelen, char *def, uint deflen,
char *comment, uint commentlen, bool suid)
{
DBUG_ENTER("sp_create_function");
DBUG_PRINT("enter", ("name: %*s def: %*s", namelen, name, deflen, def));
int ret;
ret= db_create_routine(thd, TYPE_ENUM_FUNCTION, name, namelen, def, deflen,
comment, commentlen, suid);
DBUG_RETURN(ret);
}
int
sp_drop_function(THD *thd, char *name, uint namelen)
{
DBUG_ENTER("sp_drop_function");
DBUG_PRINT("enter", ("name: %*s", namelen, name));
sp_head *sp;
int ret;
sp= thd->sp_func_cache->lookup(name, namelen);
if (sp)
{
thd->sp_func_cache->remove(sp);
delete sp;
}
ret= db_drop_routine(thd, TYPE_ENUM_FUNCTION, name, namelen);
DBUG_RETURN(ret);
}
// QQ Temporary until the function call detection in sql_lex has been reworked.
bool
sp_function_exists(THD *thd, LEX_STRING *name)
{
TABLE *table;
bool ret= FALSE;
bool opened= FALSE;
if (thd->sp_func_cache->lookup(name->str, name->length) ||
db_find_routine_aux(thd, TYPE_ENUM_FUNCTION,
name->str, name->length, TL_READ,
&table, &opened) == SP_OK)
{
ret= TRUE;
}
if (opened)
close_thread_tables(thd, 0, 1);
return ret;
}
byte *
sp_lex_spfuns_key(const byte *ptr, uint *plen, my_bool first)
{
LEX_STRING *lsp= (LEX_STRING *)ptr;
*plen= lsp->length;
return (byte *)lsp->str;
}
void
sp_add_fun_to_lex(LEX *lex, LEX_STRING fun)
{
if (! hash_search(&lex->spfuns, (byte *)fun.str, fun.length))
{
LEX_STRING *ls= (LEX_STRING *)sql_alloc(sizeof(LEX_STRING));
ls->str= sql_strmake(fun.str, fun.length);
ls->length= fun.length;
hash_insert(&lex->spfuns, (byte *)ls);
}
}
void
sp_merge_funs(LEX *dst, LEX *src)
{
for (uint i=0 ; i < src->spfuns.records ; i++)
{
LEX_STRING *ls= (LEX_STRING *)hash_element(&src->spfuns, i);
if (! hash_search(&dst->spfuns, (byte *)ls->str, ls->length))
hash_insert(&dst->spfuns, (byte *)ls);
}
}
int
sp_cache_functions(THD *thd, LEX *lex)
{
HASH *h= &lex->spfuns;
int ret= 0;
for (uint i=0 ; i < h->records ; i++)
{
LEX_STRING *ls= (LEX_STRING *)hash_element(h, i);
if (! thd->sp_func_cache->lookup(ls->str, ls->length))
{
sp_head *sp;
LEX *oldlex= thd->lex;
LEX *newlex= new st_lex;
thd->lex= newlex;
if (db_find_routine(thd, TYPE_ENUM_FUNCTION, ls->str, ls->length, &sp)
== SP_OK)
{
ret= sp_cache_functions(thd, newlex);
delete newlex;
thd->lex= oldlex;
if (ret)
break;
thd->sp_func_cache->insert(sp);
}
else
{
delete newlex;
thd->lex= oldlex;
net_printf(thd, ER_SP_DOES_NOT_EXIST, "FUNCTION", ls->str);
ret= 1;
break;
}
}
}
return ret;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v{};
cout << "Initial Capacity: " << v.capacity() << endl;
for(int i = 0;i < 100;i++) {
v.push_back(i);
cout << "Capacity: " << v.capacity() << endl;
}
return 0;
}
<commit_msg>Adding reserve() to vector capacity test<commit_after>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v{};
v.reserve(17);
cout << "Initial Capacity: " << v.capacity() << endl;
for(int i = 0;i < 100;i++) {
v.push_back(i);
cout << "Capacity: " << v.capacity() << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* For more details, see http://www.mrtrix.org/
*/
#include "command.h"
#include "image.h"
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#define DEFAULT_SIZE 5
using namespace MR;
using namespace App;
const char* const dtypes[] = { "float32", "float64", NULL };
void usage ()
{
SYNOPSIS = "Denoise DWI data and estimate the noise level based on the optimal threshold for PCA";
DESCRIPTION
+ "DWI data denoising and noise map estimation by exploiting data redundancy in the PCA domain "
"using the prior knowledge that the eigenspectrum of random covariance matrices is described by "
"the universal Marchenko Pastur distribution."
+ "Important note: image denoising must be performed as the first step of the image processing pipeline. "
"The routine will fail if interpolation or smoothing has been applied to the data prior to denoising."
+ "Note that this function does not correct for non-Gaussian noise biases.";
AUTHOR = "Daan Christiaens ([email protected]) & Jelle Veraart ([email protected]) & J-Donald Tournier ([email protected])";
REFERENCES
+ "Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-aron, B.; Sijbers, J. & Fieremans, E. " // Internal
"Denoising of diffusion MRI using random matrix theory. "
"NeuroImage, 2016, 142, 394-406, doi: 10.1016/j.neuroimage.2016.08.016"
+ "Veraart, J.; Fieremans, E. & Novikov, D.S. " // Internal
"Diffusion MRI noise mapping using random matrix theory. "
"Magn. Res. Med., 2016, 76(5), 1582-1593, doi: 10.1002/mrm.26059";
ARGUMENTS
+ Argument ("dwi", "the input diffusion-weighted image.").type_image_in ()
+ Argument ("out", "the output denoised DWI image.").type_image_out ();
OPTIONS
+ Option ("mask", "only perform computation within the specified binary brain mask image.")
+ Argument ("image").type_image_in()
+ Option ("extent", "set the window size of the denoising filter. (default = " + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + ")")
+ Argument ("window").type_sequence_int ()
+ Option ("noise", "the output noise map.")
+ Argument ("level").type_image_out()
+ Option ("datatype", "datatype for SVD (float32 or float64).")
+ Argument ("spec").type_choice(dtypes);
COPYRIGHT = "Copyright (c) 2016 New York University, University of Antwerp, and the MRtrix3 contributors \n \n"
"Permission is hereby granted, free of charge, to any non-commercial entity ('Recipient') obtaining a copy of this software and "
"associated documentation files (the 'Software'), to the Software solely for non-commercial research, including the rights to "
"use, copy and modify the Software, subject to the following conditions: \n \n"
"\t 1. The above copyright notice and this permission notice shall be included by Recipient in all copies or substantial portions of "
"the Software. \n \n"
"\t 2. 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. \n \n"
"\t 3. In no event shall NYU be liable for direct, indirect, special, incidental or consequential damages in connection with the Software. "
"Recipient will defend, indemnify and hold NYU harmless from any claims or liability resulting from the use of the Software by recipient. \n \n"
"\t 4. Neither anything contained herein nor the delivery of the Software to recipient shall be deemed to grant the Recipient any right or "
"licenses under any patents or patent application owned by NYU. \n \n"
"\t 5. The Software may only be used for non-commercial research and may not be used for clinical care. \n \n"
"\t 6. Any publication by Recipient of research involving the Software shall cite the references listed below.";
}
using value_type = float;
template <class ImageType, typename F = float>
class DenoisingFunctor {
MEMALIGN(DenoisingFunctor)
public:
typedef Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic> MatrixX;
typedef Eigen::Matrix<F, Eigen::Dynamic, 1> VectorX;
DenoisingFunctor (ImageType& dwi, vector<int> extent, Image<bool>& mask, ImageType& noise)
: extent {{extent[0]/2, extent[1]/2, extent[2]/2}},
m (dwi.size(3)),
n (extent[0]*extent[1]*extent[2]),
r ((m<n) ? m : n),
X (m,n),
Xm (r),
pos {{0, 0, 0}},
mask (mask),
noise (noise)
{ }
void operator () (ImageType& dwi, ImageType& out)
{
// Process voxels in mask only
if (mask.valid()) {
assign_pos_of (dwi).to (mask);
if (!mask.value())
return;
}
// Load data in local window
load_data (dwi);
// Compute Eigendecomposition:
MatrixX XtX (r,r);
if (m <= n)
XtX.template triangularView<Eigen::Lower>() = X * X.adjoint();
else
XtX.template triangularView<Eigen::Lower>() = X.adjoint() * X;
Eigen::SelfAdjointEigenSolver<MatrixX> eig (XtX);
// eigenvalues provide squared singular values, sorted in increasing order:
VectorX s = eig.eigenvalues();
// Marchenko-Pastur optimal threshold
const double lam_r = std::max(double(s[0]), 0.0) / std::max(m,n);
double clam = 0.0;
sigma2 = 0.0;
ssize_t cutoff_p = 0;
for (ssize_t p = 0; p < r; ++p) // p+1 is the number of noise components
{ // (as opposed to the paper where p is defined as the number of signal components)
double lam = std::max(double(s[p]), 0.0) / std::max(m,n);
clam += lam;
double gam = double(p+1) / (std::max(m,n) - (r-p-1));
double sigsq1 = clam / double(p+1);
double sigsq2 = (lam - lam_r) / (4.0 * std::sqrt(gam));
// sigsq2 > sigsq1 if signal else noise
if (sigsq2 < sigsq1) {
sigma2 = sigsq1;
cutoff_p = p+1;
}
}
if (cutoff_p > 0) {
// recombine data using only eigenvectors above threshold:
s.head (cutoff_p).setZero();
s.tail (r-cutoff_p).setOnes();
if (m <= n)
X.col (n/2) = eig.eigenvectors() * ( s.asDiagonal() * ( eig.eigenvectors().adjoint() * X.col(n/2) ));
else
X.col (n/2) = X * ( eig.eigenvectors() * ( s.asDiagonal() * eig.eigenvectors().adjoint().col(n/2) ));
}
// Store output
assign_pos_of(dwi).to(out);
if (m <= n) {
for (auto l = Loop (3) (out); l; ++l)
out.value() = value_type (X(out.index(3), n/2));
}
else {
for (auto l = Loop (3) (out); l; ++l)
out.value() = value_type (X(out.index(3), n/2));
}
// store noise map if requested:
if (noise.valid()) {
assign_pos_of(dwi).to(noise);
noise.value() = value_type (std::sqrt(sigma2));
}
}
void load_data (ImageType& dwi)
{
pos[0] = dwi.index(0); pos[1] = dwi.index(1); pos[2] = dwi.index(2);
X.setZero();
size_t k = 0;
for (int z = -extent[2]; z <= extent[2]; z++) {
dwi.index(2) = wrapindex(z, 2, dwi.size(2));
for (int y = -extent[1]; y <= extent[1]; y++) {
dwi.index(1) = wrapindex(y, 1, dwi.size(1));
for (int x = -extent[0]; x <= extent[0]; x++, k++) {
dwi.index(0) = wrapindex(x, 0, dwi.size(0));
X.col(k) = dwi.row(3);
}
}
}
// reset image position
dwi.index(0) = pos[0];
dwi.index(1) = pos[1];
dwi.index(2) = pos[2];
}
private:
const std::array<ssize_t, 3> extent;
const ssize_t m, n, r;
MatrixX X;
VectorX Xm;
std::array<ssize_t, 3> pos;
double sigma2;
Image<bool> mask;
ImageType noise;
inline size_t wrapindex(int r, int axis, int max) const {
int rr = pos[axis] + r;
if (rr < 0)
rr = extent[axis] - r;
if (rr >= max)
rr = (max-1) - extent[axis] - r;
return rr;
}
};
void run ()
{
auto dwi_in = Image<value_type>::open (argument[0]).with_direct_io(3);
if (dwi_in.ndim() != 4 || dwi_in.size(3) <= 1)
throw Exception ("input image must be 4-dimensional");
Image<bool> mask;
auto opt = get_options ("mask");
if (opt.size()) {
mask = Image<bool>::open (opt[0][0]);
check_dimensions (mask, dwi_in, 0, 3);
}
auto header = Header (dwi_in);
header.datatype() = DataType::Float32;
auto dwi_out = Image<value_type>::create (argument[1], header);
opt = get_options("extent");
vector<int> extent = { DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE };
if (opt.size()) {
extent = parse_ints(opt[0][0]);
if (extent.size() == 1)
extent = {extent[0], extent[0], extent[0]};
if (extent.size() != 3)
throw Exception ("-extent must be either a scalar or a list of length 3");
for (auto &e : extent)
if (!(e & 1))
throw Exception ("-extent must be a (list of) odd numbers");
}
Image<value_type> noise;
opt = get_options("noise");
if (opt.size()) {
header.ndim() = 3;
noise = Image<value_type>::create (opt[0][0], header);
}
opt = get_options("datatype");
if (!opt.size() || (int(opt[0][0]) == 0)) {
DEBUG("Computing SVD with single precision.");
DenoisingFunctor< Image<value_type> , float > func (dwi_in, extent, mask, noise);
ThreadedLoop ("running MP-PCA denoising", dwi_in, 0, 3)
.run (func, dwi_in, dwi_out);
}
else if (int(opt[0][0]) == 1) {
DEBUG("Computing SVD with double precision.");
DenoisingFunctor< Image<value_type> , double > func (dwi_in, extent, mask, noise);
ThreadedLoop ("running MP-PCA denoising", dwi_in, 0, 3)
.run (func, dwi_in, dwi_out);
}
else {
assert(0);
}
}
<commit_msg>dwidenoise: code cleanup.<commit_after>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* For more details, see http://www.mrtrix.org/
*/
#include "command.h"
#include "image.h"
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#define DEFAULT_SIZE 5
using namespace MR;
using namespace App;
const char* const dtypes[] = { "float32", "float64", NULL };
void usage ()
{
SYNOPSIS = "Denoise DWI data and estimate the noise level based on the optimal threshold for PCA";
DESCRIPTION
+ "DWI data denoising and noise map estimation by exploiting data redundancy in the PCA domain "
"using the prior knowledge that the eigenspectrum of random covariance matrices is described by "
"the universal Marchenko Pastur distribution."
+ "Important note: image denoising must be performed as the first step of the image processing pipeline. "
"The routine will fail if interpolation or smoothing has been applied to the data prior to denoising."
+ "Note that this function does not correct for non-Gaussian noise biases.";
AUTHOR = "Daan Christiaens ([email protected]) & "
"Jelle Veraart ([email protected]) & "
"J-Donald Tournier ([email protected])";
REFERENCES
+ "Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-aron, B.; Sijbers, J. & Fieremans, E. " // Internal
"Denoising of diffusion MRI using random matrix theory. "
"NeuroImage, 2016, 142, 394-406, doi: 10.1016/j.neuroimage.2016.08.016"
+ "Veraart, J.; Fieremans, E. & Novikov, D.S. " // Internal
"Diffusion MRI noise mapping using random matrix theory. "
"Magn. Res. Med., 2016, 76(5), 1582-1593, doi: 10.1002/mrm.26059";
ARGUMENTS
+ Argument ("dwi", "the input diffusion-weighted image.").type_image_in ()
+ Argument ("out", "the output denoised DWI image.").type_image_out ();
OPTIONS
+ Option ("mask", "only perform computation within the specified binary brain mask image.")
+ Argument ("image").type_image_in()
+ Option ("extent", "set the window size of the denoising filter. (default = " + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + ")")
+ Argument ("window").type_sequence_int ()
+ Option ("noise", "the output noise map.")
+ Argument ("level").type_image_out()
+ Option ("datatype", "datatype for SVD (float32 or float64).")
+ Argument ("spec").type_choice(dtypes);
COPYRIGHT = "Copyright (c) 2016 New York University, University of Antwerp, and the MRtrix3 contributors \n \n"
"Permission is hereby granted, free of charge, to any non-commercial entity ('Recipient') obtaining a copy of this software and "
"associated documentation files (the 'Software'), to the Software solely for non-commercial research, including the rights to "
"use, copy and modify the Software, subject to the following conditions: \n \n"
"\t 1. The above copyright notice and this permission notice shall be included by Recipient in all copies or substantial portions of "
"the Software. \n \n"
"\t 2. 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. \n \n"
"\t 3. In no event shall NYU be liable for direct, indirect, special, incidental or consequential damages in connection with the Software. "
"Recipient will defend, indemnify and hold NYU harmless from any claims or liability resulting from the use of the Software by recipient. \n \n"
"\t 4. Neither anything contained herein nor the delivery of the Software to recipient shall be deemed to grant the Recipient any right or "
"licenses under any patents or patent application owned by NYU. \n \n"
"\t 5. The Software may only be used for non-commercial research and may not be used for clinical care. \n \n"
"\t 6. Any publication by Recipient of research involving the Software shall cite the references listed below.";
}
using value_type = float;
template <class ImageType, typename F = float>
class DenoisingFunctor {
MEMALIGN(DenoisingFunctor)
public:
typedef Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic> MatrixX;
typedef Eigen::Matrix<F, Eigen::Dynamic, 1> VectorX;
DenoisingFunctor (ImageType& dwi, vector<int> extent, Image<bool>& mask, ImageType& noise)
: extent {{extent[0]/2, extent[1]/2, extent[2]/2}},
m (dwi.size(3)), n (extent[0]*extent[1]*extent[2]),
r ((m<n) ? m : n), X (m,n), pos {{0, 0, 0}},
mask (mask), noise (noise)
{ }
void operator () (ImageType& dwi, ImageType& out)
{
// Process voxels in mask only
if (mask.valid()) {
assign_pos_of (dwi).to (mask);
if (!mask.value())
return;
}
// Load data in local window
load_data (dwi);
// Compute Eigendecomposition:
MatrixX XtX (r,r);
if (m <= n)
XtX.template triangularView<Eigen::Lower>() = X * X.adjoint();
else
XtX.template triangularView<Eigen::Lower>() = X.adjoint() * X;
Eigen::SelfAdjointEigenSolver<MatrixX> eig (XtX);
// eigenvalues provide squared singular values, sorted in increasing order:
VectorX s = eig.eigenvalues();
// Marchenko-Pastur optimal threshold
const double lam_r = std::max(double(s[0]), 0.0) / std::max(m,n);
double clam = 0.0;
sigma2 = 0.0;
ssize_t cutoff_p = 0;
for (ssize_t p = 0; p < r; ++p) // p+1 is the number of noise components
{ // (as opposed to the paper where p is defined as the number of signal components)
double lam = std::max(double(s[p]), 0.0) / std::max(m,n);
clam += lam;
double gam = double(p+1) / (std::max(m,n) - (r-p-1));
double sigsq1 = clam / double(p+1);
double sigsq2 = (lam - lam_r) / (4.0 * std::sqrt(gam));
// sigsq2 > sigsq1 if signal else noise
if (sigsq2 < sigsq1) {
sigma2 = sigsq1;
cutoff_p = p+1;
}
}
if (cutoff_p > 0) {
// recombine data using only eigenvectors above threshold:
s.head (cutoff_p).setZero();
s.tail (r-cutoff_p).setOnes();
if (m <= n)
X.col (n/2) = eig.eigenvectors() * ( s.asDiagonal() * ( eig.eigenvectors().adjoint() * X.col(n/2) ));
else
X.col (n/2) = X * ( eig.eigenvectors() * ( s.asDiagonal() * eig.eigenvectors().adjoint().col(n/2) ));
}
// Store output
assign_pos_of(dwi).to(out);
if (m <= n) {
for (auto l = Loop (3) (out); l; ++l)
out.value() = value_type (X(out.index(3), n/2));
}
else {
for (auto l = Loop (3) (out); l; ++l)
out.value() = value_type (X(out.index(3), n/2));
}
// store noise map if requested:
if (noise.valid()) {
assign_pos_of(dwi).to(noise);
noise.value() = value_type (std::sqrt(sigma2));
}
}
void load_data (ImageType& dwi)
{
pos[0] = dwi.index(0); pos[1] = dwi.index(1); pos[2] = dwi.index(2);
X.setZero();
size_t k = 0;
for (int z = -extent[2]; z <= extent[2]; z++) {
dwi.index(2) = wrapindex(z, 2, dwi.size(2));
for (int y = -extent[1]; y <= extent[1]; y++) {
dwi.index(1) = wrapindex(y, 1, dwi.size(1));
for (int x = -extent[0]; x <= extent[0]; x++, k++) {
dwi.index(0) = wrapindex(x, 0, dwi.size(0));
X.col(k) = dwi.row(3);
}
}
}
// reset image position
dwi.index(0) = pos[0];
dwi.index(1) = pos[1];
dwi.index(2) = pos[2];
}
private:
const std::array<ssize_t, 3> extent;
const ssize_t m, n, r;
MatrixX X;
VectorX Xm;
std::array<ssize_t, 3> pos;
double sigma2;
Image<bool> mask;
ImageType noise;
inline size_t wrapindex(int r, int axis, int max) const {
int rr = pos[axis] + r;
if (rr < 0) rr = extent[axis] - r;
if (rr >= max) rr = (max-1) - extent[axis] - r;
return rr;
}
};
void run ()
{
auto dwi_in = Image<value_type>::open (argument[0]).with_direct_io(3);
if (dwi_in.ndim() != 4 || dwi_in.size(3) <= 1)
throw Exception ("input image must be 4-dimensional");
Image<bool> mask;
auto opt = get_options ("mask");
if (opt.size()) {
mask = Image<bool>::open (opt[0][0]);
check_dimensions (mask, dwi_in, 0, 3);
}
auto header = Header (dwi_in);
header.datatype() = DataType::Float32;
auto dwi_out = Image<value_type>::create (argument[1], header);
opt = get_options("extent");
vector<int> extent = { DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE };
if (opt.size()) {
extent = parse_ints(opt[0][0]);
if (extent.size() == 1)
extent = {extent[0], extent[0], extent[0]};
if (extent.size() != 3)
throw Exception ("-extent must be either a scalar or a list of length 3");
for (auto &e : extent)
if (!(e & 1))
throw Exception ("-extent must be a (list of) odd numbers");
}
Image<value_type> noise;
opt = get_options("noise");
if (opt.size()) {
header.ndim() = 3;
noise = Image<value_type>::create (opt[0][0], header);
}
opt = get_options("datatype");
if (!opt.size() || (int(opt[0][0]) == 0)) {
DEBUG("Computing SVD with single precision.");
DenoisingFunctor< Image<value_type> , float > func (dwi_in, extent, mask, noise);
ThreadedLoop ("running MP-PCA denoising", dwi_in, 0, 3)
.run (func, dwi_in, dwi_out);
}
else if (int(opt[0][0]) == 1) {
DEBUG("Computing SVD with double precision.");
DenoisingFunctor< Image<value_type> , double > func (dwi_in, extent, mask, noise);
ThreadedLoop ("running MP-PCA denoising", dwi_in, 0, 3)
.run (func, dwi_in, dwi_out);
}
else {
assert(0);
}
}
<|endoftext|> |
<commit_before>#include <apfMesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <PCU.h>
#include <apf.h>
void testTriEdge()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 2, false);
apf::MeshEntity* v[3];
for (int i = 0; i < 3; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* ev[2];
ev[0] = v[2]; ev[1] = v[1];
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::EDGE, ev);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TRIANGLE, v);
int which, rotate;
bool flip;
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == 1);
assert(flip == true);
assert(rotate == 0);
m->destroyNative();
apf::destroyMesh(m);
}
void testTetTri1()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false);
apf::MeshEntity* v[4];
for (int i = 0; i < 4; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* tv[3];
tv[0] = v[2]; tv[1] = v[1]; tv[2] = v[0];
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::TRIANGLE, tv);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TET, v);
int which, rotate;
bool flip;
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == 0);
assert(flip == true);
assert(rotate == 0);
m->destroyNative();
apf::destroyMesh(m);
}
void testTetTri2()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false);
apf::MeshEntity* v[4];
for (int i = 0; i < 4; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* tv[3];
tv[0] = v[0]; tv[1] = v[1]; tv[2] = v[2];
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::TRIANGLE, tv);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TET, v);
int which, rotate;
bool flip;
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == 0);
assert(flip == false);
assert(rotate == 0);
m->destroyNative();
apf::destroyMesh(m);
}
void testTetTri3()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false);
apf::MeshEntity* v[4];
for (int i = 0; i < 4; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* tv[3];
tv[0] = v[0]; tv[1] = v[2]; tv[2] = v[1];
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::TRIANGLE, tv);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TET, v);
int which, rotate;
bool flip;
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == 0);
assert(flip == true);
assert(rotate == 2);
m->destroyNative();
apf::destroyMesh(m);
}
int main()
{
MPI_Init(0,0);
PCU_Comm_Init();
gmi_register_null();
testTriEdge();
testTetTri1();
testTetTri2();
testTetTri3();
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>mortals can write test functions<commit_after>#include <apfMesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <PCU.h>
#include <apf.h>
void testTriEdge()
{
int which, rotate;
bool flip;
for(int ed = 0; ed < 6; ++ed){
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 2, false);
apf::MeshEntity* v[3];
for (int i = 0; i < 3; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* ev[2];
ev[0] = v[apf::tri_edge_verts[ed % 3][ed >= 3]];
ev[1] = v[apf::tri_edge_verts[ed % 3][ed < 3]];
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::EDGE, ev);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TRIANGLE, v);
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == (ed % 3));
assert(flip == (ed >= 3));
assert(rotate == 0);
m->destroyNative();
apf::destroyMesh(m);
}
}
void testTetEdge()
{
int which, rotate;
bool flip;
for(int ed = 0; ed < 12; ++ed){
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false);
apf::MeshEntity* v[4];
for (int i = 0; i < 4; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* ev[2];
ev[0] = v[apf::tet_edge_verts[ed % 6][ed >= 6]];
ev[1] = v[apf::tet_edge_verts[ed % 6][ed < 6]];
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::EDGE, ev);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TET, v);
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == (ed % 6));
assert(flip == (ed >= 6));
assert(rotate == 0);
m->destroyNative();
apf::destroyMesh(m);
}
}
void testTetTri()
{
int which, rotate;
bool flip;
int r[6] = {0,2,1,2,1,0};
for(int flipped = 0; flipped < 2; ++flipped){
for(int fa = 0; fa < 12; ++fa){
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false);
apf::MeshEntity* v[4];
for (int i = 0; i < 4; ++i)
v[i] = m->createVert(0);
apf::MeshEntity* ev[3];
ev[0] = v[apf::tet_tri_verts[fa % 4][(0+fa/4) % 3]];
ev[1] = v[apf::tet_tri_verts[fa % 4][(1+fa/4) % 3]];
ev[2] = v[apf::tet_tri_verts[fa % 4][(2+fa/4) % 3]];
if(flipped)
std::swap(ev[1],ev[2]);
apf::MeshEntity* e =
apf::buildElement(m, 0, apf::Mesh::TRIANGLE, ev);
apf::MeshEntity* t =
apf::buildElement(m, 0, apf::Mesh::TET, v);
apf::getAlignment(m, t, e, which, flip, rotate);
assert(which == fa % 4);
assert(flip == flipped);
assert(rotate == r[flipped*3+fa/4]);
m->destroyNative();
apf::destroyMesh(m);
}
}
}
int main()
{
MPI_Init(0,0);
PCU_Comm_Init();
gmi_register_null();
testTriEdge();
testTetEdge();
testTetTri();
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "logger.h"
#include <stdarg.h> // for va_list, va_end, va_start
#include <stdio.h> // for fileno, vsnprintf, stderr
#include <unistd.h> // for isatty
#include <ctime> // for time_t
#include <functional> // for ref
#include <iostream> // for cerr
#include <regex> // for regex_replace, regex
#include <stdexcept> // for out_of_range
#include <system_error> // for system_error
#include "datetime.h" // for to_string
#include "exception.h" // for traceback
#include "utils.h" // for get_thread_name
#define BUFFER_SIZE (10 * 1024)
#define STACKED_INDENT "<indent>"
const std::regex filter_re("\033\\[[;\\d]*m");
std::mutex Log::stack_mtx;
std::unordered_map<std::thread::id, unsigned> Log::stack_levels;
const char *priorities[] = {
EMERG_COL "█" NO_COL, // LOG_EMERG 0 = System is unusable
ALERT_COL "▉" NO_COL, // LOG_ALERT 1 = Action must be taken immediately
CRIT_COL "▊" NO_COL, // LOG_CRIT 2 = Critical conditions
ERR_COL "▋" NO_COL, // LOG_ERR 3 = Error conditions
WARNING_COL "▌" NO_COL, // LOG_WARNING 4 = Warning conditions
NOTICE_COL "▍" NO_COL, // LOG_NOTICE 5 = Normal but significant condition
INFO_COL "▎" NO_COL, // LOG_INFO 6 = Informational
DEBUG_COL "▏" NO_COL, // LOG_DEBUG 7 = Debug-level messages
};
void
StreamLogger::log(int priority, const std::string& str)
{
ofs << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
void
StderrLogger::log(int priority, const std::string& str)
{
if (isatty(fileno(stderr))) {
std::cerr << priorities[priority < 0 ? -priority : priority] + str << std::endl;
} else {
std::cerr << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
}
SysLog::SysLog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void
SysLog::log(int priority, const std::string& str)
{
syslog(priority, "%s", std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "").c_str());
}
Log::Log(const std::string& str, bool clean_, bool stacked_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)
: stack_level(0),
stacked(stacked_),
clean(clean_),
created_at(created_at_),
cleared_at(created_at_),
str_start(str),
priority(priority_),
cleared(false),
cleaned(false) {
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
thread_id = std::this_thread::get_id();
try {
stack_level = ++stack_levels.at(thread_id);
} catch (const std::out_of_range&) {
stack_levels[thread_id] = 0;
}
}
}
Log::~Log()
{
cleanup();
}
void
Log::cleanup()
{
bool f = false;
if (cleared.compare_exchange_strong(f, clean)) {
cleared_at = std::chrono::system_clock::now();
}
if (!cleaned.exchange(true)) {
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
if (stack_levels.at(thread_id)-- == 0) {
stack_levels.erase(thread_id);
}
}
}
}
long double
Log::age()
{
auto now = (cleared_at > created_at) ? cleared_at : std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(now - created_at).count();
}
LogQueue::LogQueue()
: queue(now())
{ }
LogType&
LogQueue::next(bool final, uint64_t final_key, bool keep_going)
{
return queue.next(final, final_key, keep_going, false);
}
LogType&
LogQueue::peep()
{
return queue.next(false, 0, true, true);
}
void
LogQueue::add(const LogType& l_ptr, uint64_t key)
{
queue.add(l_ptr, key);
}
/*
* https://isocpp.org/wiki/faq/ctors#static-init-order
* Avoid the "static initialization order fiasco"
*/
LogThread&
Log::_thread()
{
static LogThread* thread = new LogThread();
return *thread;
}
int&
Log::_log_level()
{
static auto* log_level = new int(DEFAULT_LOG_LEVEL);
return *log_level;
}
std::vector<std::unique_ptr<Logger>>&
Log::_handlers()
{
static auto* handlers = new std::vector<std::unique_ptr<Logger>>();
return *handlers;
}
std::string
Log::str_format(bool stacked, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr)
{
char* buffer = new char[BUFFER_SIZE];
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
std::string msg(buffer);
auto iso8601 = "[" + Datetime::to_string(std::chrono::system_clock::now()) + "]";
auto tid = " (" + get_thread_name() + ")";
std::string result = iso8601 + tid;
#ifdef LOG_OBJ_ADDRESS
if (obj) {
snprintf(buffer, BUFFER_SIZE, " [%p]", obj);
result += buffer;
}
#endif
#ifdef TRACEBACK
auto location = (priority >= LOCATION_LOG_LEVEL) ? " " + std::string(file) + ":" + std::to_string(line) : std::string();
result += location + ": ";
#else
result += " ";
(void)obj;
#endif
if (stacked) {
result += STACKED_INDENT;
}
result += prefix + msg + suffix;
delete []buffer;
if (priority < 0) {
if (exc.empty()) {
result += DARK_GREY + traceback(file, line) + NO_COL;
} else {
result += NO_COL + exc + NO_COL;
}
}
return result;
}
LogWrapper
Log::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
std::string str(str_format(stacked, priority, exc, file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
return print(str, clean, stacked, wakeup, priority);
}
bool
Log::clear()
{
if (!cleared.exchange(true)) {
cleared_at = std::chrono::system_clock::now();
return true;
}
return false;
}
bool
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
if (!clear()) {
va_list argptr;
va_start(argptr, format);
std::string str(str_format(stacked, priority, std::string(), file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
print(str, false, stacked, 0, priority, created_at);
return true;
}
return false;
}
LogWrapper
Log::add(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
auto l_ptr = std::make_shared<Log>(str, clean, stacked, priority, created_at);
static LogThread& thread = _thread();
thread.add(l_ptr, wakeup);
return LogWrapper(l_ptr);
}
void
Log::log(int priority, std::string str, int indent)
{
static std::mutex log_mutex;
std::lock_guard<std::mutex> lk(log_mutex);
static const auto& handlers = _handlers();
auto needle = str.find(STACKED_INDENT);
if (needle != std::string::npos) {
str.replace(needle, sizeof(STACKED_INDENT) - 1, std::string(indent, ' '));
}
for (auto& handler : handlers) {
handler->log(priority, str);
}
}
LogWrapper
Log::print(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
static auto& log_level = _log_level();
if (priority > log_level) {
return LogWrapper(std::make_shared<Log>(str, clean, stacked, priority, created_at));
}
if (priority >= ASYNC_LOG_LEVEL || wakeup > std::chrono::system_clock::now()) {
return add(str, clean, stacked, wakeup, priority, created_at);
} else {
auto l_ptr = std::make_shared<Log>(str, clean, stacked, priority, created_at);
log(priority, str, l_ptr->stack_level * 2);
return LogWrapper(l_ptr);
}
}
void
Log::finish(int wait)
{
static LogThread& thread = _thread();
thread.finish(wait);
}
std::condition_variable LogThread::wakeup_signal;
std::atomic_ullong LogThread::next_wakeup_time;
LogThread::LogThread()
: running(-1),
inner_thread(&LogThread::thread_function, this, std::ref(log_queue)) { }
LogThread::~LogThread()
{
finish(true);
}
void
LogThread::finish(int wait)
{
running = wait;
wakeup_signal.notify_all();
if (wait) {
try {
inner_thread.join();
} catch (const std::system_error&) { }
}
}
void
LogThread::add(const LogType& l_ptr, std::chrono::time_point<std::chrono::system_clock> wakeup)
{
if (running != 0) {
wakeup += 2ms;
auto wt = time_point_to_ullong(wakeup);
l_ptr->wakeup_time = wt;
log_queue.add(l_ptr, time_point_to_key(wakeup));
auto now = std::chrono::system_clock::now();
if (wakeup < now) {
wakeup = now;
}
auto nwt = next_wakeup_time.load();
auto n = time_point_to_ullong(now);
bool notify;
do {
notify = (nwt < n || nwt >= wt);
} while (notify && !next_wakeup_time.compare_exchange_weak(nwt, wt));
if (notify) {
wakeup_signal.notify_one();
}
}
}
void
LogThread::thread_function(LogQueue& log_queue)
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
next_wakeup_time = time_point_to_ullong(std::chrono::system_clock::now() + 100ms);
while (running != 0) {
if (--running < 0) {
running = -1;
}
auto now = std::chrono::system_clock::now();
auto wakeup = now + (running < 0 ? 3s : 100ms);
auto wt = time_point_to_ullong(wakeup);
auto nwt = next_wakeup_time.load();
auto n = time_point_to_ullong(now);
bool notify;
do {
notify = (nwt < n || nwt >= wt);
} while (notify && !next_wakeup_time.compare_exchange_weak(nwt, wt));
wakeup_signal.wait_until(lk, time_point_from_ullong(next_wakeup_time.load()));
try {
do {
auto& l_ptr = log_queue.next(running < 0);
if (l_ptr) {
if (!l_ptr->cleared) {
auto msg = l_ptr->str_start;
auto age = l_ptr->age();
if (age > 2e8) {
msg += " ~" + delta_string(age, true);
}
if (l_ptr->clear()) {
Log::log(l_ptr->priority, msg, l_ptr->stack_level * 2);
}
}
l_ptr.reset();
}
} while (true);
} catch(const StashContinue&) { }
if (running >= 0) {
break;
}
}
}
<commit_msg>Logger: Wakeup deferring improved<commit_after>/*
* Copyright (C) 2016 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "logger.h"
#include <stdarg.h> // for va_list, va_end, va_start
#include <stdio.h> // for fileno, vsnprintf, stderr
#include <unistd.h> // for isatty
#include <ctime> // for time_t
#include <functional> // for ref
#include <iostream> // for cerr
#include <regex> // for regex_replace, regex
#include <stdexcept> // for out_of_range
#include <system_error> // for system_error
#include "datetime.h" // for to_string
#include "exception.h" // for traceback
#include "utils.h" // for get_thread_name
#define BUFFER_SIZE (10 * 1024)
#define STACKED_INDENT "<indent>"
const std::regex filter_re("\033\\[[;\\d]*m");
std::mutex Log::stack_mtx;
std::unordered_map<std::thread::id, unsigned> Log::stack_levels;
const char *priorities[] = {
EMERG_COL "█" NO_COL, // LOG_EMERG 0 = System is unusable
ALERT_COL "▉" NO_COL, // LOG_ALERT 1 = Action must be taken immediately
CRIT_COL "▊" NO_COL, // LOG_CRIT 2 = Critical conditions
ERR_COL "▋" NO_COL, // LOG_ERR 3 = Error conditions
WARNING_COL "▌" NO_COL, // LOG_WARNING 4 = Warning conditions
NOTICE_COL "▍" NO_COL, // LOG_NOTICE 5 = Normal but significant condition
INFO_COL "▎" NO_COL, // LOG_INFO 6 = Informational
DEBUG_COL "▏" NO_COL, // LOG_DEBUG 7 = Debug-level messages
};
void
StreamLogger::log(int priority, const std::string& str)
{
ofs << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
void
StderrLogger::log(int priority, const std::string& str)
{
if (isatty(fileno(stderr))) {
std::cerr << priorities[priority < 0 ? -priority : priority] + str << std::endl;
} else {
std::cerr << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
}
SysLog::SysLog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void
SysLog::log(int priority, const std::string& str)
{
syslog(priority, "%s", std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "").c_str());
}
Log::Log(const std::string& str, bool clean_, bool stacked_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)
: stack_level(0),
stacked(stacked_),
clean(clean_),
created_at(created_at_),
cleared_at(created_at_),
str_start(str),
priority(priority_),
cleared(false),
cleaned(false) {
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
thread_id = std::this_thread::get_id();
try {
stack_level = ++stack_levels.at(thread_id);
} catch (const std::out_of_range&) {
stack_levels[thread_id] = 0;
}
}
}
Log::~Log()
{
cleanup();
}
void
Log::cleanup()
{
bool f = false;
if (cleared.compare_exchange_strong(f, clean)) {
cleared_at = std::chrono::system_clock::now();
}
if (!cleaned.exchange(true)) {
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
if (stack_levels.at(thread_id)-- == 0) {
stack_levels.erase(thread_id);
}
}
}
}
long double
Log::age()
{
auto now = (cleared_at > created_at) ? cleared_at : std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(now - created_at).count();
}
LogQueue::LogQueue()
: queue(now())
{ }
LogType&
LogQueue::next(bool final, uint64_t final_key, bool keep_going)
{
return queue.next(final, final_key, keep_going, false);
}
LogType&
LogQueue::peep()
{
return queue.next(false, 0, true, true);
}
void
LogQueue::add(const LogType& l_ptr, uint64_t key)
{
queue.add(l_ptr, key);
}
/*
* https://isocpp.org/wiki/faq/ctors#static-init-order
* Avoid the "static initialization order fiasco"
*/
LogThread&
Log::_thread()
{
static LogThread* thread = new LogThread();
return *thread;
}
int&
Log::_log_level()
{
static auto* log_level = new int(DEFAULT_LOG_LEVEL);
return *log_level;
}
std::vector<std::unique_ptr<Logger>>&
Log::_handlers()
{
static auto* handlers = new std::vector<std::unique_ptr<Logger>>();
return *handlers;
}
std::string
Log::str_format(bool stacked, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr)
{
char* buffer = new char[BUFFER_SIZE];
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
std::string msg(buffer);
auto iso8601 = "[" + Datetime::to_string(std::chrono::system_clock::now()) + "]";
auto tid = " (" + get_thread_name() + ")";
std::string result = iso8601 + tid;
#ifdef LOG_OBJ_ADDRESS
if (obj) {
snprintf(buffer, BUFFER_SIZE, " [%p]", obj);
result += buffer;
}
#endif
#ifdef TRACEBACK
auto location = (priority >= LOCATION_LOG_LEVEL) ? " " + std::string(file) + ":" + std::to_string(line) : std::string();
result += location + ": ";
#else
result += " ";
(void)obj;
#endif
if (stacked) {
result += STACKED_INDENT;
}
result += prefix + msg + suffix;
delete []buffer;
if (priority < 0) {
if (exc.empty()) {
result += DARK_GREY + traceback(file, line) + NO_COL;
} else {
result += NO_COL + exc + NO_COL;
}
}
return result;
}
LogWrapper
Log::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
std::string str(str_format(stacked, priority, exc, file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
return print(str, clean, stacked, wakeup, priority);
}
bool
Log::clear()
{
if (!cleared.exchange(true)) {
cleared_at = std::chrono::system_clock::now();
return true;
}
return false;
}
bool
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
if (!clear()) {
va_list argptr;
va_start(argptr, format);
std::string str(str_format(stacked, priority, std::string(), file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
print(str, false, stacked, 0, priority, created_at);
return true;
}
return false;
}
LogWrapper
Log::add(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
auto l_ptr = std::make_shared<Log>(str, clean, stacked, priority, created_at);
static LogThread& thread = _thread();
thread.add(l_ptr, wakeup);
return LogWrapper(l_ptr);
}
void
Log::log(int priority, std::string str, int indent)
{
static std::mutex log_mutex;
std::lock_guard<std::mutex> lk(log_mutex);
static const auto& handlers = _handlers();
auto needle = str.find(STACKED_INDENT);
if (needle != std::string::npos) {
str.replace(needle, sizeof(STACKED_INDENT) - 1, std::string(indent, ' '));
}
for (auto& handler : handlers) {
handler->log(priority, str);
}
}
LogWrapper
Log::print(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
static auto& log_level = _log_level();
if (priority > log_level) {
return LogWrapper(std::make_shared<Log>(str, clean, stacked, priority, created_at));
}
if (priority >= ASYNC_LOG_LEVEL || wakeup > std::chrono::system_clock::now()) {
return add(str, clean, stacked, wakeup, priority, created_at);
} else {
auto l_ptr = std::make_shared<Log>(str, clean, stacked, priority, created_at);
log(priority, str, l_ptr->stack_level * 2);
return LogWrapper(l_ptr);
}
}
void
Log::finish(int wait)
{
static LogThread& thread = _thread();
thread.finish(wait);
}
std::condition_variable LogThread::wakeup_signal;
std::atomic_ullong LogThread::next_wakeup_time;
LogThread::LogThread()
: running(-1),
inner_thread(&LogThread::thread_function, this, std::ref(log_queue)) { }
LogThread::~LogThread()
{
finish(true);
}
void
LogThread::finish(int wait)
{
running = wait;
wakeup_signal.notify_all();
if (wait) {
try {
inner_thread.join();
} catch (const std::system_error&) { }
}
}
void
LogThread::add(const LogType& l_ptr, std::chrono::time_point<std::chrono::system_clock> wakeup)
{
if (running != 0) {
auto now = std::chrono::system_clock::now();
if (wakeup < now + 2ms) {
wakeup = now + 2ms; // defer log so we make sure we're not adding messages to the current slot
}
auto wt = time_point_to_ullong(wakeup);
l_ptr->wakeup_time = wt;
log_queue.add(l_ptr, time_point_to_key(wakeup));
auto nwt = next_wakeup_time.load();
auto n = time_point_to_ullong(now);
bool notify;
do {
notify = (nwt < n || nwt >= wt);
} while (notify && !next_wakeup_time.compare_exchange_weak(nwt, wt));
if (notify) {
wakeup_signal.notify_one();
}
}
}
void
LogThread::thread_function(LogQueue& log_queue)
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
next_wakeup_time = time_point_to_ullong(std::chrono::system_clock::now() + 100ms);
while (running != 0) {
if (--running < 0) {
running = -1;
}
auto now = std::chrono::system_clock::now();
auto wakeup = now + (running < 0 ? 3s : 100ms);
auto wt = time_point_to_ullong(wakeup);
auto nwt = next_wakeup_time.load();
auto n = time_point_to_ullong(now);
bool notify;
do {
notify = (nwt < n || nwt >= wt);
} while (notify && !next_wakeup_time.compare_exchange_weak(nwt, wt));
wakeup_signal.wait_until(lk, time_point_from_ullong(next_wakeup_time.load()));
try {
do {
auto& l_ptr = log_queue.next(running < 0);
if (l_ptr) {
if (!l_ptr->cleared) {
auto msg = l_ptr->str_start;
auto age = l_ptr->age();
if (age > 2e8) {
msg += " ~" + delta_string(age, true);
}
if (l_ptr->clear()) {
Log::log(l_ptr->priority, msg, l_ptr->stack_level * 2);
}
}
l_ptr.reset();
}
} while (true);
} catch(const StashContinue&) { }
if (running >= 0) {
break;
}
}
}
<|endoftext|> |
<commit_before>/* parse_bam.cc -- Example BAM parser using the htslib API
Copyright (c) 2015, Washington University
Author: Avinash Ramu <[email protected]>
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 <iostream>
#include "hts.h"
#include "sam.h"
using namespace std;
int usage() {
cerr << "./parse_bam example.bam";
return 0;
}
int parse_bam(int argc, char* argv[]) {
if(argc < 2) {
return usage();
}
string bam = string(argv[1]);
string region_ = ".";
if(argc > 2) {
region_ = string(argv[2]);
}
if(!bam.empty()) {
//open BAM for reading
samFile *in = sam_open(bam.c_str(), "r");
if(in == NULL) {
throw runtime_error("Unable to open BAM/SAM file.");
}
//Load the index
hts_idx_t *idx = sam_index_load(in, bam.c_str());
if(idx == NULL) {
throw runtime_error("Unable to open BAM/SAM index."
" Make sure alignments are indexed");
}
//Get the header
bam_hdr_t *header = sam_hdr_read(in);
//Initialize iterator
hts_itr_t *iter = NULL;
//Move the iterator to the region we are interested in
iter = sam_itr_querys(idx, header, region_.c_str());
if(header == NULL || iter == NULL) {
sam_close(in);
throw runtime_error("Unable to iterate to region within BAM.");
}
//Initiate the alignment record
bam1_t *aln = bam_init1();
while(sam_itr_next(in, iter, aln) >= 0) {
cout << "Read Chr: " << header->target_name[aln->core.tid];
cout << "\tPos: " << aln->core.pos;
cout << endl;
}
hts_itr_destroy(iter);
hts_idx_destroy(idx);
bam_destroy1(aln);
bam_hdr_destroy(header);
sam_close(in);
}
return 0;
}
int main(int argc, char* argv[]) {
try {
parse_bam(argc, argv);
} catch (const runtime_error& e) {
cerr << e.what();
}
}
<commit_msg>Print out sequence of BAM record<commit_after>/* parse_bam.cc -- Example BAM parser using the htslib API
Copyright (c) 2015, Washington University
Author: Avinash Ramu <[email protected]>
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 <iostream>
#include "hts.h"
#include "sam.h"
using namespace std;
int usage() {
cerr << "./parse_bam example.bam";
return 0;
}
int parse_bam(int argc, char* argv[]) {
if(argc < 2) {
return usage();
}
string bam = string(argv[1]);
string region_ = ".";
if(argc > 2) {
region_ = string(argv[2]);
}
if(!bam.empty()) {
//open BAM for reading
samFile *in = sam_open(bam.c_str(), "r");
if(in == NULL) {
throw runtime_error("Unable to open BAM/SAM file.");
}
//Load the index
hts_idx_t *idx = sam_index_load(in, bam.c_str());
if(idx == NULL) {
throw runtime_error("Unable to open BAM/SAM index."
" Make sure alignments are indexed");
}
//Get the header
bam_hdr_t *header = sam_hdr_read(in);
//Initialize iterator
hts_itr_t *iter = NULL;
//Move the iterator to the region we are interested in
iter = sam_itr_querys(idx, header, region_.c_str());
if(header == NULL || iter == NULL) {
sam_close(in);
throw runtime_error("Unable to iterate to region within BAM.");
}
//Initiate the alignment record
bam1_t *aln = bam_init1();
while(sam_itr_next(in, iter, aln) >= 0) {
cout << "Read Chr: " << header->target_name[aln->core.tid];
cout << "\tPos: " << aln->core.pos;
cout << "\tSeq: ";
for (int i = 0; i < aln->core.l_qseq; ++i)
cout << seq_nt16_str[bam_seqi(bam_get_seq(aln), i)];
cout << endl;
}
hts_itr_destroy(iter);
hts_idx_destroy(idx);
bam_destroy1(aln);
bam_hdr_destroy(header);
sam_close(in);
}
return 0;
}
int main(int argc, char* argv[]) {
try {
parse_bam(argc, argv);
} catch (const runtime_error& e) {
cerr << e.what();
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
copyright : (C) 2010 by Alex Novichkov
email : [email protected]
copyright : (C) 2006 by Lukáš Lalinský
email : [email protected]
(original WavPack implementation)
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tstring.h>
#include <tdebug.h>
#include <bitset>
#include "id3v2tag.h"
#include "apeproperties.h"
#include "apefile.h"
#include "apetag.h"
#include "apefooter.h"
using namespace TagLib;
class APE::Properties::PropertiesPrivate
{
public:
PropertiesPrivate() :
length(0),
bitrate(0),
sampleRate(0),
channels(0),
version(0),
bitsPerSample(0),
sampleFrames(0) {}
int length;
int bitrate;
int sampleRate;
int channels;
int version;
int bitsPerSample;
uint sampleFrames;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
APE::Properties::Properties(File *file, ReadStyle style) :
AudioProperties(style),
d(new PropertiesPrivate())
{
debug("APE::Properties::Properties() -- This constructor is no longer used.");
}
APE::Properties::Properties(File *file, long streamLength, ReadStyle style) :
AudioProperties(style),
d(new PropertiesPrivate())
{
read(file, streamLength);
}
APE::Properties::~Properties()
{
delete d;
}
int APE::Properties::length() const
{
return lengthInSeconds();
}
int APE::Properties::lengthInSeconds() const
{
return d->length / 1000;
}
int APE::Properties::lengthInMilliseconds() const
{
return d->length;
}
int APE::Properties::bitrate() const
{
return d->bitrate;
}
int APE::Properties::sampleRate() const
{
return d->sampleRate;
}
int APE::Properties::channels() const
{
return d->channels;
}
int APE::Properties::version() const
{
return d->version;
}
int APE::Properties::bitsPerSample() const
{
return d->bitsPerSample;
}
TagLib::uint APE::Properties::sampleFrames() const
{
return d->sampleFrames;
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
void APE::Properties::read(File *file, long streamLength)
{
// First we are searching the descriptor
const long offset = file->find("MAC ", file->tell());
if(offset < 0) {
debug("APE::Properties::read() -- APE descriptor not found");
return;
}
// Then we read the header common for all versions of APE
file->seek(offset);
const ByteVector commonHeader = file->readBlock(6);
if(commonHeader.size() < 6) {
debug("APE::Properties::read() -- header is too short.");
return;
}
d->version = commonHeader.toUShort(4, false);
if(d->version >= 3980)
analyzeCurrent(file);
else
analyzeOld(file);
if(d->sampleFrames > 0 && d->sampleRate > 0) {
const double length = d->sampleFrames * 1000.0 / d->sampleRate;
d->length = static_cast<int>(length + 0.5);
d->bitrate = static_cast<int>(streamLength * 8.0 / length + 0.5);
}
}
void APE::Properties::analyzeCurrent(File *file)
{
// Read the descriptor
file->seek(2, File::Current);
const ByteVector descriptor = file->readBlock(44);
if(descriptor.size() < 44) {
debug("APE::Properties::analyzeCurrent() -- descriptor is too short.");
return;
}
const uint descriptorBytes = descriptor.toUInt(0, false);
if((descriptorBytes - 52) > 0)
file->seek(descriptorBytes - 52, File::Current);
// Read the header
const ByteVector header = file->readBlock(24);
if(header.size() < 24) {
debug("APE::Properties::analyzeCurrent() -- MAC header is too short.");
return;
}
// Get the APE info
d->channels = header.toShort(18, false);
d->sampleRate = header.toUInt(20, false);
d->bitsPerSample = header.toShort(16, false);
const uint totalFrames = header.toUInt(12, false);
if(totalFrames == 0)
return;
const uint blocksPerFrame = header.toUInt(4, false);
const uint finalFrameBlocks = header.toUInt(8, false);
d->sampleFrames = (totalFrames - 1) * blocksPerFrame + finalFrameBlocks;
}
void APE::Properties::analyzeOld(File *file)
{
const ByteVector header = file->readBlock(26);
if(header.size() < 26) {
debug("APE::Properties::analyzeOld() -- MAC header is too short.");
return;
}
const uint totalFrames = header.toUInt(18, false);
// Fail on 0 length APE files (catches non-finalized APE files)
if(totalFrames == 0)
return;
const short compressionLevel = header.toShort(0, false);
uint blocksPerFrame;
if(d->version >= 3950)
blocksPerFrame = 73728 * 4;
else if(d->version >= 3900 || (d->version >= 3800 && compressionLevel == 4000))
blocksPerFrame = 73728;
else
blocksPerFrame = 9216;
// Get the APE info
d->channels = header.toShort(4, false);
d->sampleRate = header.toUInt(6, false);
const uint finalFrameBlocks = header.toUInt(22, false);
d->sampleFrames = (totalFrames - 1) * blocksPerFrame + finalFrameBlocks;
// Seek the RIFF chunk and get the bit depth
long offset = file->tell();
offset = file->find("WAVEfmt ", offset);
if(offset < 0)
return;
file->seek(offset + 12);
const ByteVector fmt = file->readBlock(16);
if(fmt.size() < 16) {
debug("APE::Properties::analyzeOld() -- fmt header is too short.");
return;
}
d->bitsPerSample = fmt.toShort(14, false);
}
<commit_msg>APE: Reduce useless File::Find() operations.<commit_after>/***************************************************************************
copyright : (C) 2010 by Alex Novichkov
email : [email protected]
copyright : (C) 2006 by Lukáš Lalinský
email : [email protected]
(original WavPack implementation)
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tstring.h>
#include <tdebug.h>
#include <bitset>
#include "id3v2tag.h"
#include "apeproperties.h"
#include "apefile.h"
#include "apetag.h"
#include "apefooter.h"
using namespace TagLib;
class APE::Properties::PropertiesPrivate
{
public:
PropertiesPrivate() :
length(0),
bitrate(0),
sampleRate(0),
channels(0),
version(0),
bitsPerSample(0),
sampleFrames(0) {}
int length;
int bitrate;
int sampleRate;
int channels;
int version;
int bitsPerSample;
uint sampleFrames;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
APE::Properties::Properties(File *file, ReadStyle style) :
AudioProperties(style),
d(new PropertiesPrivate())
{
debug("APE::Properties::Properties() -- This constructor is no longer used.");
}
APE::Properties::Properties(File *file, long streamLength, ReadStyle style) :
AudioProperties(style),
d(new PropertiesPrivate())
{
read(file, streamLength);
}
APE::Properties::~Properties()
{
delete d;
}
int APE::Properties::length() const
{
return lengthInSeconds();
}
int APE::Properties::lengthInSeconds() const
{
return d->length / 1000;
}
int APE::Properties::lengthInMilliseconds() const
{
return d->length;
}
int APE::Properties::bitrate() const
{
return d->bitrate;
}
int APE::Properties::sampleRate() const
{
return d->sampleRate;
}
int APE::Properties::channels() const
{
return d->channels;
}
int APE::Properties::version() const
{
return d->version;
}
int APE::Properties::bitsPerSample() const
{
return d->bitsPerSample;
}
TagLib::uint APE::Properties::sampleFrames() const
{
return d->sampleFrames;
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
namespace
{
inline int headerVersion(const ByteVector &header)
{
if(header.size() < 6 || !header.startsWith("MAC "))
return -1;
return header.toUShort(4, false);
}
}
void APE::Properties::read(File *file, long streamLength)
{
// First, we assume that the file pointer is set at the first descriptor.
long offset = file->tell();
int version = headerVersion(file->readBlock(6));
// Next, we look for the descriptor.
if(version < 0) {
offset = file->find("MAC ", offset);
file->seek(offset);
version = headerVersion(file->readBlock(6));
}
if(version < 0) {
debug("APE::Properties::read() -- APE descriptor not found");
return;
}
d->version = version;
if(d->version >= 3980)
analyzeCurrent(file);
else
analyzeOld(file);
if(d->sampleFrames > 0 && d->sampleRate > 0) {
const double length = d->sampleFrames * 1000.0 / d->sampleRate;
d->length = static_cast<int>(length + 0.5);
d->bitrate = static_cast<int>(streamLength * 8.0 / length + 0.5);
}
}
void APE::Properties::analyzeCurrent(File *file)
{
// Read the descriptor
file->seek(2, File::Current);
const ByteVector descriptor = file->readBlock(44);
if(descriptor.size() < 44) {
debug("APE::Properties::analyzeCurrent() -- descriptor is too short.");
return;
}
const uint descriptorBytes = descriptor.toUInt(0, false);
if((descriptorBytes - 52) > 0)
file->seek(descriptorBytes - 52, File::Current);
// Read the header
const ByteVector header = file->readBlock(24);
if(header.size() < 24) {
debug("APE::Properties::analyzeCurrent() -- MAC header is too short.");
return;
}
// Get the APE info
d->channels = header.toShort(18, false);
d->sampleRate = header.toUInt(20, false);
d->bitsPerSample = header.toShort(16, false);
const uint totalFrames = header.toUInt(12, false);
if(totalFrames == 0)
return;
const uint blocksPerFrame = header.toUInt(4, false);
const uint finalFrameBlocks = header.toUInt(8, false);
d->sampleFrames = (totalFrames - 1) * blocksPerFrame + finalFrameBlocks;
}
void APE::Properties::analyzeOld(File *file)
{
const ByteVector header = file->readBlock(26);
if(header.size() < 26) {
debug("APE::Properties::analyzeOld() -- MAC header is too short.");
return;
}
const uint totalFrames = header.toUInt(18, false);
// Fail on 0 length APE files (catches non-finalized APE files)
if(totalFrames == 0)
return;
const short compressionLevel = header.toShort(0, false);
uint blocksPerFrame;
if(d->version >= 3950)
blocksPerFrame = 73728 * 4;
else if(d->version >= 3900 || (d->version >= 3800 && compressionLevel == 4000))
blocksPerFrame = 73728;
else
blocksPerFrame = 9216;
// Get the APE info
d->channels = header.toShort(4, false);
d->sampleRate = header.toUInt(6, false);
const uint finalFrameBlocks = header.toUInt(22, false);
d->sampleFrames = (totalFrames - 1) * blocksPerFrame + finalFrameBlocks;
// Get the bit depth from the RIFF-fmt chunk.
file->seek(16, File::Current);
const ByteVector fmt = file->readBlock(28);
if(fmt.size() < 28 || !fmt.startsWith("WAVEfmt ")) {
debug("APE::Properties::analyzeOld() -- fmt header is too short.");
return;
}
d->bitsPerSample = fmt.toShort(26, false);
}
<|endoftext|> |
<commit_before>#include "ArmatureData.h"
#include "UserData.h"
#include "DragonBonesData.h"
#include "ConstraintData.h"
#include "DisplayData.h"
#include "AnimationData.h"
DRAGONBONES_NAMESPACE_BEGIN
void ArmatureData::_onClear()
{
for (const auto action : defaultActions)
{
action->returnToPool();
}
for (const auto action : actions)
{
action->returnToPool();
}
for (const auto& pair : bones)
{
pair.second->returnToPool();
}
for (const auto& pair : slots)
{
pair.second->returnToPool();
}
for (const auto& pair : skins)
{
pair.second->returnToPool();
}
for (const auto& pair : animations)
{
pair.second->returnToPool();
}
if (userData != nullptr)
{
userData->returnToPool();
}
type = ArmatureType::Armature;
frameRate = 0;
cacheFrameRate = 0;
scale = 1.0f;
name = "";
aabb.clear();
defaultActions.clear();
actions.clear();
bones.clear();
slots.clear();
skins.clear();
animations.clear();
parent = nullptr;
defaultSkin = nullptr;
defaultAnimation = nullptr;
userData = nullptr;
// TODO canvas
}
void ArmatureData::sortBones()
{
const auto total = sortedBones.size();
if (total <= 0)
{
return;
}
const auto sortHelper = sortedBones; // Copy.
unsigned index = 0;
unsigned count = 0;
sortedBones.clear();
while (count < total)
{
const auto bone = sortHelper[index++];
if (index >= total)
{
index = 0;
}
if (std::find(sortedBones.cbegin(), sortedBones.cend(), bone) != sortedBones.cend())
{
continue;
}
if(!bone->constraints.empty())
{
auto flag = false;
for(const auto constrait : bone->constraints)
{
if(std::find(sortedBones.cbegin(), sortedBones.cend(), constrait->target) == sortedBones.cend())
{
flag = true;
break;
}
}
if(flag)
{
continue;
}
}
if (bone->parent != nullptr && std::find(sortedBones.cbegin(), sortedBones.cend(), bone->parent) == sortedBones.cend())
{
continue;
}
sortedBones.push_back(bone);
count++;
}
}
void ArmatureData::cacheFrames(unsigned value)
{
if (cacheFrameRate > value) // TODO clear cache.
{
return;
}
cacheFrameRate = value;
for (const auto& pair : animations)
{
pair.second->cacheFrames(cacheFrameRate);
}
}
int ArmatureData::setCacheFrame(const Matrix& globalTransformMatrix, const Transform& transform)
{
auto& dataArray = *&parent->cachedFrames;
auto arrayOffset = dataArray.size();
dataArray.resize(arrayOffset + 10);
dataArray[arrayOffset] = globalTransformMatrix.a;
dataArray[arrayOffset + 1] = globalTransformMatrix.b;
dataArray[arrayOffset + 2] = globalTransformMatrix.c;
dataArray[arrayOffset + 3] = globalTransformMatrix.d;
dataArray[arrayOffset + 4] = globalTransformMatrix.tx;
dataArray[arrayOffset + 5] = globalTransformMatrix.ty;
dataArray[arrayOffset + 6] = transform.rotation;
dataArray[arrayOffset + 7] = transform.skew;
dataArray[arrayOffset + 8] = transform.scaleX;
dataArray[arrayOffset + 9] = transform.scaleY;
return arrayOffset;
}
void ArmatureData::getCacheFrame(Matrix& globalTransformMatrix, Transform& transform, unsigned arrayOffset)
{
auto& dataArray = *&parent->cachedFrames;
globalTransformMatrix.a = dataArray[arrayOffset];
globalTransformMatrix.b = dataArray[arrayOffset + 1];
globalTransformMatrix.c = dataArray[arrayOffset + 2];
globalTransformMatrix.d = dataArray[arrayOffset + 3];
globalTransformMatrix.tx = dataArray[arrayOffset + 4];
globalTransformMatrix.ty = dataArray[arrayOffset + 5];
transform.rotation = dataArray[arrayOffset + 6];
transform.skew = dataArray[arrayOffset + 7];
transform.scaleX = dataArray[arrayOffset + 8];
transform.scaleY = dataArray[arrayOffset + 9];
transform.x = globalTransformMatrix.tx;
transform.y = globalTransformMatrix.ty;
}
void ArmatureData::addBone(BoneData* value)
{
if (bones.find(value->name) != bones.cend())
{
DRAGONBONES_ASSERT(false, "Replace bone: " + value->name);
bones[value->name]->returnToPool();
}
bones[value->name] = value;
sortedBones.push_back(value);
}
void ArmatureData::addSlot(SlotData* value)
{
if (slots.find(value->name) != slots.cend())
{
DRAGONBONES_ASSERT(false, "Replace slot: " + value->name);
slots[value->name]->returnToPool();
}
slots[value->name] = value;
sortedSlots.push_back(value);
}
void ArmatureData::addSkin(SkinData* value)
{
if (skins.find(value->name) != skins.cend())
{
DRAGONBONES_ASSERT(false, "Replace skin: " + value->name);
skins[value->name]->returnToPool();
}
skins[value->name] = value;
if (defaultSkin == nullptr)
{
defaultSkin = value;
}
}
void ArmatureData::addAnimation(AnimationData* value)
{
if (animations.find(value->name) != animations.cend())
{
DRAGONBONES_ASSERT(false, "Replace animation: " + value->name);
animations[value->name]->returnToPool();
}
value->parent = this;
animations[value->name] = value;
animationNames.push_back(value->name);
if (defaultAnimation == nullptr)
{
defaultAnimation = value;
}
}
void BoneData::_onClear()
{
for (const auto constraint : constraints)
{
constraint->returnToPool();
}
if (userData != nullptr)
{
userData->returnToPool();
}
inheritTranslation = false;
inheritRotation = false;
inheritScale = false;
inheritReflection = false;
length = 0.0f;
name = "";
transform.identity();
constraints.clear();
parent = nullptr;
userData = nullptr;
}
ColorTransform SlotData::DEFAULT_COLOR;
ColorTransform* SlotData::createColor()
{
return new ColorTransform();
}
void SlotData::_onClear()
{
if (userData != nullptr)
{
userData->returnToPool();
}
if (color != nullptr && color != &DEFAULT_COLOR)
{
delete color;
}
blendMode = BlendMode::Normal;
displayIndex = 0;
zOrder = 0;
name = "";
parent = nullptr;
color = nullptr;
userData = nullptr;
}
void SkinData::_onClear()
{
for (const auto& pair : displays)
{
for (const auto display : pair.second)
{
if (display != nullptr)
{
display->returnToPool();
}
}
}
name = "";
displays.clear();
skinSlotNames.clear();
}
void SkinData::addDisplay(const std::string& slotName, DisplayData* value)
{
skinSlotNames.push_back(slotName);
displays[slotName].push_back(value); // TODO clear prev
}
DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName)
{
const auto slotDisplays = getDisplays(slotName);
if (slotDisplays != nullptr)
{
for (const auto display : *slotDisplays)
{
if (display != nullptr && display->name == displayName)
{
return display;
}
}
}
return nullptr;
}
DRAGONBONES_NAMESPACE_END
<commit_msg>fixed ArmatureData clean bug<commit_after>#include "ArmatureData.h"
#include "UserData.h"
#include "DragonBonesData.h"
#include "ConstraintData.h"
#include "DisplayData.h"
#include "AnimationData.h"
DRAGONBONES_NAMESPACE_BEGIN
void ArmatureData::_onClear()
{
for (const auto action : defaultActions)
{
action->returnToPool();
}
for (const auto action : actions)
{
action->returnToPool();
}
for (const auto& pair : bones)
{
pair.second->returnToPool();
}
for (const auto& pair : slots)
{
pair.second->returnToPool();
}
for (const auto& pair : skins)
{
pair.second->returnToPool();
}
for (const auto& pair : animations)
{
pair.second->returnToPool();
}
if (userData != nullptr)
{
userData->returnToPool();
}
type = ArmatureType::Armature;
frameRate = 0;
cacheFrameRate = 0;
scale = 1.0f;
name = "";
aabb.clear();
animationNames.clear();
sortedBones.clear();
sortedSlots.clear();
defaultActions.clear();
actions.clear();
bones.clear();
slots.clear();
skins.clear();
animations.clear();
parent = nullptr;
defaultSkin = nullptr;
defaultAnimation = nullptr;
userData = nullptr;
// TODO canvas
}
void ArmatureData::sortBones()
{
const auto total = sortedBones.size();
if (total <= 0)
{
return;
}
const auto sortHelper = sortedBones; // Copy.
unsigned index = 0;
unsigned count = 0;
sortedBones.clear();
while (count < total)
{
const auto bone = sortHelper[index++];
if (index >= total)
{
index = 0;
}
if (std::find(sortedBones.cbegin(), sortedBones.cend(), bone) != sortedBones.cend())
{
continue;
}
if(!bone->constraints.empty())
{
auto flag = false;
for(const auto constrait : bone->constraints)
{
if(std::find(sortedBones.cbegin(), sortedBones.cend(), constrait->target) == sortedBones.cend())
{
flag = true;
break;
}
}
if(flag)
{
continue;
}
}
if (bone->parent != nullptr && std::find(sortedBones.cbegin(), sortedBones.cend(), bone->parent) == sortedBones.cend())
{
continue;
}
sortedBones.push_back(bone);
count++;
}
}
void ArmatureData::cacheFrames(unsigned value)
{
if (cacheFrameRate > value) // TODO clear cache.
{
return;
}
cacheFrameRate = value;
for (const auto& pair : animations)
{
pair.second->cacheFrames(cacheFrameRate);
}
}
int ArmatureData::setCacheFrame(const Matrix& globalTransformMatrix, const Transform& transform)
{
auto& dataArray = *&parent->cachedFrames;
auto arrayOffset = dataArray.size();
dataArray.resize(arrayOffset + 10);
dataArray[arrayOffset] = globalTransformMatrix.a;
dataArray[arrayOffset + 1] = globalTransformMatrix.b;
dataArray[arrayOffset + 2] = globalTransformMatrix.c;
dataArray[arrayOffset + 3] = globalTransformMatrix.d;
dataArray[arrayOffset + 4] = globalTransformMatrix.tx;
dataArray[arrayOffset + 5] = globalTransformMatrix.ty;
dataArray[arrayOffset + 6] = transform.rotation;
dataArray[arrayOffset + 7] = transform.skew;
dataArray[arrayOffset + 8] = transform.scaleX;
dataArray[arrayOffset + 9] = transform.scaleY;
return arrayOffset;
}
void ArmatureData::getCacheFrame(Matrix& globalTransformMatrix, Transform& transform, unsigned arrayOffset)
{
auto& dataArray = *&parent->cachedFrames;
globalTransformMatrix.a = dataArray[arrayOffset];
globalTransformMatrix.b = dataArray[arrayOffset + 1];
globalTransformMatrix.c = dataArray[arrayOffset + 2];
globalTransformMatrix.d = dataArray[arrayOffset + 3];
globalTransformMatrix.tx = dataArray[arrayOffset + 4];
globalTransformMatrix.ty = dataArray[arrayOffset + 5];
transform.rotation = dataArray[arrayOffset + 6];
transform.skew = dataArray[arrayOffset + 7];
transform.scaleX = dataArray[arrayOffset + 8];
transform.scaleY = dataArray[arrayOffset + 9];
transform.x = globalTransformMatrix.tx;
transform.y = globalTransformMatrix.ty;
}
void ArmatureData::addBone(BoneData* value)
{
if (bones.find(value->name) != bones.cend())
{
DRAGONBONES_ASSERT(false, "Replace bone: " + value->name);
bones[value->name]->returnToPool();
}
bones[value->name] = value;
sortedBones.push_back(value);
}
void ArmatureData::addSlot(SlotData* value)
{
if (slots.find(value->name) != slots.cend())
{
DRAGONBONES_ASSERT(false, "Replace slot: " + value->name);
slots[value->name]->returnToPool();
}
slots[value->name] = value;
sortedSlots.push_back(value);
}
void ArmatureData::addSkin(SkinData* value)
{
if (skins.find(value->name) != skins.cend())
{
DRAGONBONES_ASSERT(false, "Replace skin: " + value->name);
skins[value->name]->returnToPool();
}
skins[value->name] = value;
if (defaultSkin == nullptr)
{
defaultSkin = value;
}
}
void ArmatureData::addAnimation(AnimationData* value)
{
if (animations.find(value->name) != animations.cend())
{
DRAGONBONES_ASSERT(false, "Replace animation: " + value->name);
animations[value->name]->returnToPool();
}
value->parent = this;
animations[value->name] = value;
animationNames.push_back(value->name);
if (defaultAnimation == nullptr)
{
defaultAnimation = value;
}
}
void BoneData::_onClear()
{
for (const auto constraint : constraints)
{
constraint->returnToPool();
}
if (userData != nullptr)
{
userData->returnToPool();
}
inheritTranslation = false;
inheritRotation = false;
inheritScale = false;
inheritReflection = false;
length = 0.0f;
name = "";
transform.identity();
constraints.clear();
parent = nullptr;
userData = nullptr;
}
ColorTransform SlotData::DEFAULT_COLOR;
ColorTransform* SlotData::createColor()
{
return new ColorTransform();
}
void SlotData::_onClear()
{
if (userData != nullptr)
{
userData->returnToPool();
}
if (color != nullptr && color != &DEFAULT_COLOR)
{
delete color;
}
blendMode = BlendMode::Normal;
displayIndex = 0;
zOrder = 0;
name = "";
parent = nullptr;
color = nullptr;
userData = nullptr;
}
void SkinData::_onClear()
{
for (const auto& pair : displays)
{
for (const auto display : pair.second)
{
if (display != nullptr)
{
display->returnToPool();
}
}
}
name = "";
displays.clear();
skinSlotNames.clear();
}
void SkinData::addDisplay(const std::string& slotName, DisplayData* value)
{
skinSlotNames.push_back(slotName);
displays[slotName].push_back(value); // TODO clear prev
}
DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName)
{
const auto slotDisplays = getDisplays(slotName);
if (slotDisplays != nullptr)
{
for (const auto display : *slotDisplays)
{
if (display != nullptr && display->name == displayName)
{
return display;
}
}
}
return nullptr;
}
DRAGONBONES_NAMESPACE_END
<|endoftext|> |
<commit_before>//
// gsl-lite is based on GSL: Guidelines Support Library,
// https://github.com/microsoft/gsl
//
// Copyright (c) 2015 Martin Moene
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "gsl-lite.t.h"
namespace {
CASE( "at(): Allows access to existing C-array elements" )
{
int a[] = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
EXPECT( at(a, i) == i + 1 );
}
}
CASE( "at(): Terminates access to non-existing C-array elements" )
{
int a[] = { 1, 2, 3, 4 };
EXPECT_THROWS( at(a, 4) );
}
CASE( "at(): Allows access to existing std::array elements" )
{
#if gsl_HAVE_ARRAY
std::array<int, 4> a = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
EXPECT( at(a, i) == i + 1 );
}
#else
EXPECT( !!"std::array<T> is not available (no C++11)" );
#endif
}
CASE( "at(): Terminates access to non-existing std::array elements" )
{
#if gsl_HAVE_ARRAY
std::array<int, 4> a = { 1, 2, 3, 4 };
EXPECT_THROWS( at(a, 4) );
#else
EXPECT( !!"std::array<T> is not available (no C++11)" );
#endif
}
} // anonymous namespace
#include <vector>
#if gsl_COMPILER_MSVC_VERSION == 6
gsl_MK_AT( std::vector )
#endif
namespace {
CASE( "at(): Allows access to existing std::vector elements" )
{
std::vector<int> a; // = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
a.push_back( i + 1 );
EXPECT( at(a, i) == i + 1 );
}
}
CASE( "at(): Terminates access to non-existing std::vector elements" )
{
std::vector<int> a; // = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
a.push_back( i + 1 );
}
EXPECT_THROWS( at(a, 4) );
}
}
// end of file
<commit_msg>Prevent warning for missing braces<commit_after>//
// gsl-lite is based on GSL: Guidelines Support Library,
// https://github.com/microsoft/gsl
//
// Copyright (c) 2015 Martin Moene
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "gsl-lite.t.h"
namespace {
CASE( "at(): Allows access to existing C-array elements" )
{
int a[] = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
EXPECT( at(a, i) == i + 1 );
}
}
CASE( "at(): Terminates access to non-existing C-array elements" )
{
int a[] = { 1, 2, 3, 4 };
EXPECT_THROWS( at(a, 4) );
}
CASE( "at(): Allows access to existing std::array elements" )
{
#if gsl_HAVE_ARRAY
std::array<int, 4> a = {{ 1, 2, 3, 4 }};
for ( int i = 0; i < 4; ++i )
{
EXPECT( at(a, i) == i + 1 );
}
#else
EXPECT( !!"std::array<T> is not available (no C++11)" );
#endif
}
CASE( "at(): Terminates access to non-existing std::array elements" )
{
#if gsl_HAVE_ARRAY
std::array<int, 4> a = {{ 1, 2, 3, 4 }};
EXPECT_THROWS( at(a, 4) );
#else
EXPECT( !!"std::array<T> is not available (no C++11)" );
#endif
}
} // anonymous namespace
#include <vector>
#if gsl_COMPILER_MSVC_VERSION == 6
gsl_MK_AT( std::vector )
#endif
namespace {
CASE( "at(): Allows access to existing std::vector elements" )
{
std::vector<int> a; // = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
a.push_back( i + 1 );
EXPECT( at(a, i) == i + 1 );
}
}
CASE( "at(): Terminates access to non-existing std::vector elements" )
{
std::vector<int> a; // = { 1, 2, 3, 4 };
for ( int i = 0; i < 4; ++i )
{
a.push_back( i + 1 );
}
EXPECT_THROWS( at(a, 4) );
}
}
// end of file
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* For more details, see http://www.mrtrix.org/
*/
#include <mutex>
#include "command.h"
#include "image.h"
#include "progressbar.h"
#include "thread_queue.h"
#include "types.h"
#include "algo/loop.h"
#include "adapter/subset.h"
#include "connectome/connectome.h"
#include "surface/mesh.h"
#include "surface/mesh_multi.h"
#include "surface/algo/image2mesh.h"
using namespace MR;
using namespace App;
using namespace MR::Surface;
void usage ()
{
AUTHOR = "Robert E. Smith ([email protected])";
SYNOPSIS = "Generate meshes from a label image";
ARGUMENTS
+ Argument ("nodes_in", "the input node parcellation image").type_image_in()
+ Argument ("mesh_out", "the output mesh file").type_file_out();
OPTIONS
+ Option ("blocky", "generate 'blocky' meshes with precise delineation of voxel edges, "
"rather than the default Marching Cubes approach");
}
void run ()
{
Header labels_header = Header::open (argument[0]);
Connectome::check (labels_header);
check_3D_nonunity (labels_header);
auto labels = labels_header.get_image<uint32_t>();
using voxel_corner_t = Eigen::Array<int, 3, 1>;
vector<voxel_corner_t> lower_corners, upper_corners;
{
for (auto i = Loop ("Importing label image", labels) (labels); i; ++i) {
const uint32_t index = labels.value();
if (index) {
if (index >= lower_corners.size()) {
lower_corners.resize (index+1, voxel_corner_t (labels.size(0), labels.size(1), labels.size(2)));
upper_corners.resize (index+1, voxel_corner_t (-1, -1, -1));
}
for (size_t axis = 0; axis != 3; ++axis) {
lower_corners[index][axis] = std::min (lower_corners[index][axis], int(labels.index (axis)));
upper_corners[index][axis] = std::max (upper_corners[index][axis], int(labels.index (axis)));
}
}
}
}
MeshMulti meshes (lower_corners.size(), MR::Surface::Mesh());
meshes[0].set_name ("none");
const bool blocky = get_options ("blocky").size();
{
std::mutex mutex;
ProgressBar progress ("Generating meshes from labels", lower_corners.size() - 1);
auto loader = [&] (size_t& out) { static size_t i = 1; out = i++; return (out != lower_corners.size()); };
auto worker = [&] (const size_t& in)
{
vector<int> from, dimensions;
for (size_t axis = 0; axis != 3; ++axis) {
from.push_back (lower_corners[in][axis]);
dimensions.push_back (upper_corners[in][axis] - lower_corners[in][axis] + 1);
}
Adapter::Subset<Image<uint32_t>> subset (labels, from, dimensions);
auto scratch = Image<bool>::scratch (subset, "Node " + str(in) + " mask");
for (auto i = Loop (subset) (subset, scratch); i; ++i)
scratch.value() = (subset.value() == in);
if (blocky)
MR::Surface::Algo::image2mesh_blocky (scratch, meshes[in]);
else
MR::Surface::Algo::image2mesh_mc (scratch, meshes[in], 0.5);
meshes[in].set_name (str(in));
std::lock_guard<std::mutex> lock (mutex);
++progress;
return true;
};
Thread::run_queue (loader, size_t(), Thread::multi (worker));
}
meshes.save (argument[1]);
}
<commit_msg>label2mesh: Skip absent parcels<commit_after>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* For more details, see http://www.mrtrix.org/
*/
#include <mutex>
#include "command.h"
#include "image.h"
#include "progressbar.h"
#include "thread_queue.h"
#include "types.h"
#include "algo/loop.h"
#include "adapter/subset.h"
#include "connectome/connectome.h"
#include "surface/mesh.h"
#include "surface/mesh_multi.h"
#include "surface/algo/image2mesh.h"
using namespace MR;
using namespace App;
using namespace MR::Surface;
void usage ()
{
AUTHOR = "Robert E. Smith ([email protected])";
SYNOPSIS = "Generate meshes from a label image";
ARGUMENTS
+ Argument ("nodes_in", "the input node parcellation image").type_image_in()
+ Argument ("mesh_out", "the output mesh file").type_file_out();
OPTIONS
+ Option ("blocky", "generate 'blocky' meshes with precise delineation of voxel edges, "
"rather than the default Marching Cubes approach");
}
void run ()
{
Header labels_header = Header::open (argument[0]);
Connectome::check (labels_header);
check_3D_nonunity (labels_header);
auto labels = labels_header.get_image<uint32_t>();
using voxel_corner_t = Eigen::Array<int, 3, 1>;
vector<voxel_corner_t> lower_corners, upper_corners;
{
for (auto i = Loop ("Importing label image", labels) (labels); i; ++i) {
const uint32_t index = labels.value();
if (index) {
if (index >= lower_corners.size()) {
lower_corners.resize (index+1, voxel_corner_t (labels.size(0), labels.size(1), labels.size(2)));
upper_corners.resize (index+1, voxel_corner_t (-1, -1, -1));
}
for (size_t axis = 0; axis != 3; ++axis) {
lower_corners[index][axis] = std::min (lower_corners[index][axis], int(labels.index (axis)));
upper_corners[index][axis] = std::max (upper_corners[index][axis], int(labels.index (axis)));
}
}
}
}
MeshMulti meshes (lower_corners.size(), MR::Surface::Mesh());
meshes[0].set_name ("none");
const bool blocky = get_options ("blocky").size();
{
std::mutex mutex;
ProgressBar progress ("Generating meshes from labels", lower_corners.size() - 1);
auto loader = [&] (size_t& out) { static size_t i = 1; out = i++; return (out != lower_corners.size()); };
auto worker = [&] (const size_t& in)
{
meshes[in].set_name (str(in));
vector<int> from, dimensions;
for (size_t axis = 0; axis != 3; ++axis) {
from.push_back (lower_corners[in][axis]);
dimensions.push_back (upper_corners[in][axis] - lower_corners[in][axis] + 1);
if (dimensions.back() < 1) {
std::lock_guard<std::mutex> lock (mutex);
WARN ("Index " + str(in) + " absent from label image; mesh data will be empty");
return true;
}
}
Adapter::Subset<Image<uint32_t>> subset (labels, from, dimensions);
auto scratch = Image<bool>::scratch (subset, "Node " + str(in) + " mask");
for (auto i = Loop (subset) (subset, scratch); i; ++i)
scratch.value() = (subset.value() == in);
if (blocky)
MR::Surface::Algo::image2mesh_blocky (scratch, meshes[in]);
else
MR::Surface::Algo::image2mesh_mc (scratch, meshes[in], 0.5);
std::lock_guard<std::mutex> lock (mutex);
++progress;
return true;
};
Thread::run_queue (loader, size_t(), Thread::multi (worker));
}
meshes.save (argument[1]);
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreMatrix4.h"
#include "OgreVector3.h"
#include "OgreMatrix3.h"
namespace Ogre
{
const Matrix4 Matrix4::ZERO(
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0 );
const Matrix4 Matrix4::IDENTITY(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 );
const Matrix4 Matrix4::CLIPSPACE2DTOIMAGESPACE(
0.5, 0, 0, 0.5,
0, -0.5, 0, 0.5,
0, 0, 1, 0,
0, 0, 0, 1);
//-----------------------------------------------------------------------
inline static Real
MINOR(const Matrix4& m, const size_t r0, const size_t r1, const size_t r2,
const size_t c0, const size_t c1, const size_t c2)
{
return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) -
m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) +
m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]);
}
//-----------------------------------------------------------------------
Matrix4 Matrix4::adjoint() const
{
return Matrix4( MINOR(*this, 1, 2, 3, 1, 2, 3),
-MINOR(*this, 0, 2, 3, 1, 2, 3),
MINOR(*this, 0, 1, 3, 1, 2, 3),
-MINOR(*this, 0, 1, 2, 1, 2, 3),
-MINOR(*this, 1, 2, 3, 0, 2, 3),
MINOR(*this, 0, 2, 3, 0, 2, 3),
-MINOR(*this, 0, 1, 3, 0, 2, 3),
MINOR(*this, 0, 1, 2, 0, 2, 3),
MINOR(*this, 1, 2, 3, 0, 1, 3),
-MINOR(*this, 0, 2, 3, 0, 1, 3),
MINOR(*this, 0, 1, 3, 0, 1, 3),
-MINOR(*this, 0, 1, 2, 0, 1, 3),
-MINOR(*this, 1, 2, 3, 0, 1, 2),
MINOR(*this, 0, 2, 3, 0, 1, 2),
-MINOR(*this, 0, 1, 3, 0, 1, 2),
MINOR(*this, 0, 1, 2, 0, 1, 2));
}
//-----------------------------------------------------------------------
Real Matrix4::determinant() const
{
return m[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) -
m[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) +
m[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) -
m[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2);
}
//-----------------------------------------------------------------------
Matrix4 Matrix4::inverse() const
{
Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2], m03 = m[0][3];
Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2], m13 = m[1][3];
Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2], m23 = m[2][3];
Real m30 = m[3][0], m31 = m[3][1], m32 = m[3][2], m33 = m[3][3];
Real v0 = m20 * m31 - m21 * m30;
Real v1 = m20 * m32 - m22 * m30;
Real v2 = m20 * m33 - m23 * m30;
Real v3 = m21 * m32 - m22 * m31;
Real v4 = m21 * m33 - m23 * m31;
Real v5 = m22 * m33 - m23 * m32;
Real t00 = + (v5 * m11 - v4 * m12 + v3 * m13);
Real t10 = - (v5 * m10 - v2 * m12 + v1 * m13);
Real t20 = + (v4 * m10 - v2 * m11 + v0 * m13);
Real t30 = - (v3 * m10 - v1 * m11 + v0 * m12);
Real invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03);
Real d00 = t00 * invDet;
Real d10 = t10 * invDet;
Real d20 = t20 * invDet;
Real d30 = t30 * invDet;
Real d01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
Real d11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
Real d21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
Real d31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
v0 = m10 * m31 - m11 * m30;
v1 = m10 * m32 - m12 * m30;
v2 = m10 * m33 - m13 * m30;
v3 = m11 * m32 - m12 * m31;
v4 = m11 * m33 - m13 * m31;
v5 = m12 * m33 - m13 * m32;
Real d02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
Real d12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
Real d22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
Real d32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
v0 = m21 * m10 - m20 * m11;
v1 = m22 * m10 - m20 * m12;
v2 = m23 * m10 - m20 * m13;
v3 = m22 * m11 - m21 * m12;
v4 = m23 * m11 - m21 * m13;
v5 = m23 * m12 - m22 * m13;
Real d03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
Real d13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
Real d23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
Real d33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
return Matrix4(
d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33);
}
//-----------------------------------------------------------------------
Matrix4 Matrix4::inverseAffine(void) const
{
assert(isAffine());
Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2];
Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2];
Real t00 = m22 * m11 - m21 * m12;
Real t10 = m20 * m12 - m22 * m10;
Real t20 = m21 * m10 - m20 * m11;
Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2];
Real invDet = 1 / (m00 * t00 + m01 * t10 + m02 * t20);
t00 *= invDet; t10 *= invDet; t20 *= invDet;
m00 *= invDet; m01 *= invDet; m02 *= invDet;
Real r00 = t00;
Real r01 = m02 * m21 - m01 * m22;
Real r02 = m01 * m12 - m02 * m11;
Real r10 = t10;
Real r11 = m00 * m22 - m02 * m20;
Real r12 = m02 * m10 - m00 * m12;
Real r20 = t20;
Real r21 = m01 * m20 - m00 * m21;
Real r22 = m00 * m11 - m01 * m10;
Real m03 = m[0][3], m13 = m[1][3], m23 = m[2][3];
Real r03 = - (r00 * m03 + r01 * m13 + r02 * m23);
Real r13 = - (r10 * m03 + r11 * m13 + r12 * m23);
Real r23 = - (r20 * m03 + r21 * m13 + r22 * m23);
return Matrix4(
r00, r01, r02, r03,
r10, r11, r12, r13,
r20, r21, r22, r23,
0, 0, 0, 1);
}
//-----------------------------------------------------------------------
void Matrix4::makeTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation)
{
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
Matrix3 rot3x3;
orientation.ToRotationMatrix(rot3x3);
// Set up final matrix with scale, rotation and translation
m[0][0] = scale.x * rot3x3[0][0]; m[0][1] = scale.y * rot3x3[0][1]; m[0][2] = scale.z * rot3x3[0][2]; m[0][3] = position.x;
m[1][0] = scale.x * rot3x3[1][0]; m[1][1] = scale.y * rot3x3[1][1]; m[1][2] = scale.z * rot3x3[1][2]; m[1][3] = position.y;
m[2][0] = scale.x * rot3x3[2][0]; m[2][1] = scale.y * rot3x3[2][1]; m[2][2] = scale.z * rot3x3[2][2]; m[2][3] = position.z;
// No projection term
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
}
//-----------------------------------------------------------------------
void Matrix4::makeInverseTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation)
{
// Invert the parameters
Vector3 invTranslate = -position;
Vector3 invScale(1 / scale.x, 1 / scale.y, 1 / scale.z);
Quaternion invRot = orientation.Inverse();
// Because we're inverting, order is translation, rotation, scale
// So make translation relative to scale & rotation
invTranslate *= invScale; // scale
invTranslate = invRot * invTranslate; // rotate
// Next, make a 3x3 rotation matrix
Matrix3 rot3x3;
invRot.ToRotationMatrix(rot3x3);
// Set up final matrix with scale, rotation and translation
m[0][0] = invScale.x * rot3x3[0][0]; m[0][1] = invScale.x * rot3x3[0][1]; m[0][2] = invScale.x * rot3x3[0][2]; m[0][3] = invTranslate.x;
m[1][0] = invScale.y * rot3x3[1][0]; m[1][1] = invScale.y * rot3x3[1][1]; m[1][2] = invScale.y * rot3x3[1][2]; m[1][3] = invTranslate.y;
m[2][0] = invScale.z * rot3x3[2][0]; m[2][1] = invScale.z * rot3x3[2][1]; m[2][2] = invScale.z * rot3x3[2][2]; m[2][3] = invTranslate.z;
// No projection term
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
}
//-----------------------------------------------------------------------
void Matrix4::decomposition(Vector3& position, Vector3& scale, Quaternion& orientation) const
{
assert(isAffine());
Matrix3 m3x3;
extract3x3Matrix(m3x3);
Matrix3 matQ;
Vector3 vecU;
m3x3.QDUDecomposition( matQ, scale, vecU );
orientation = Quaternion( matQ );
position = Vector3( m[0][3], m[1][3], m[2][3] );
}
}
<commit_msg>Patch 2979431: Matrix4::makeInverseTransform bug with non-uniform scale<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreMatrix4.h"
#include "OgreVector3.h"
#include "OgreMatrix3.h"
namespace Ogre
{
const Matrix4 Matrix4::ZERO(
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0 );
const Matrix4 Matrix4::IDENTITY(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 );
const Matrix4 Matrix4::CLIPSPACE2DTOIMAGESPACE(
0.5, 0, 0, 0.5,
0, -0.5, 0, 0.5,
0, 0, 1, 0,
0, 0, 0, 1);
//-----------------------------------------------------------------------
inline static Real
MINOR(const Matrix4& m, const size_t r0, const size_t r1, const size_t r2,
const size_t c0, const size_t c1, const size_t c2)
{
return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) -
m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) +
m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]);
}
//-----------------------------------------------------------------------
Matrix4 Matrix4::adjoint() const
{
return Matrix4( MINOR(*this, 1, 2, 3, 1, 2, 3),
-MINOR(*this, 0, 2, 3, 1, 2, 3),
MINOR(*this, 0, 1, 3, 1, 2, 3),
-MINOR(*this, 0, 1, 2, 1, 2, 3),
-MINOR(*this, 1, 2, 3, 0, 2, 3),
MINOR(*this, 0, 2, 3, 0, 2, 3),
-MINOR(*this, 0, 1, 3, 0, 2, 3),
MINOR(*this, 0, 1, 2, 0, 2, 3),
MINOR(*this, 1, 2, 3, 0, 1, 3),
-MINOR(*this, 0, 2, 3, 0, 1, 3),
MINOR(*this, 0, 1, 3, 0, 1, 3),
-MINOR(*this, 0, 1, 2, 0, 1, 3),
-MINOR(*this, 1, 2, 3, 0, 1, 2),
MINOR(*this, 0, 2, 3, 0, 1, 2),
-MINOR(*this, 0, 1, 3, 0, 1, 2),
MINOR(*this, 0, 1, 2, 0, 1, 2));
}
//-----------------------------------------------------------------------
Real Matrix4::determinant() const
{
return m[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) -
m[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) +
m[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) -
m[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2);
}
//-----------------------------------------------------------------------
Matrix4 Matrix4::inverse() const
{
Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2], m03 = m[0][3];
Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2], m13 = m[1][3];
Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2], m23 = m[2][3];
Real m30 = m[3][0], m31 = m[3][1], m32 = m[3][2], m33 = m[3][3];
Real v0 = m20 * m31 - m21 * m30;
Real v1 = m20 * m32 - m22 * m30;
Real v2 = m20 * m33 - m23 * m30;
Real v3 = m21 * m32 - m22 * m31;
Real v4 = m21 * m33 - m23 * m31;
Real v5 = m22 * m33 - m23 * m32;
Real t00 = + (v5 * m11 - v4 * m12 + v3 * m13);
Real t10 = - (v5 * m10 - v2 * m12 + v1 * m13);
Real t20 = + (v4 * m10 - v2 * m11 + v0 * m13);
Real t30 = - (v3 * m10 - v1 * m11 + v0 * m12);
Real invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03);
Real d00 = t00 * invDet;
Real d10 = t10 * invDet;
Real d20 = t20 * invDet;
Real d30 = t30 * invDet;
Real d01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
Real d11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
Real d21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
Real d31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
v0 = m10 * m31 - m11 * m30;
v1 = m10 * m32 - m12 * m30;
v2 = m10 * m33 - m13 * m30;
v3 = m11 * m32 - m12 * m31;
v4 = m11 * m33 - m13 * m31;
v5 = m12 * m33 - m13 * m32;
Real d02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
Real d12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
Real d22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
Real d32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
v0 = m21 * m10 - m20 * m11;
v1 = m22 * m10 - m20 * m12;
v2 = m23 * m10 - m20 * m13;
v3 = m22 * m11 - m21 * m12;
v4 = m23 * m11 - m21 * m13;
v5 = m23 * m12 - m22 * m13;
Real d03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
Real d13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
Real d23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
Real d33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
return Matrix4(
d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33);
}
//-----------------------------------------------------------------------
Matrix4 Matrix4::inverseAffine(void) const
{
assert(isAffine());
Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2];
Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2];
Real t00 = m22 * m11 - m21 * m12;
Real t10 = m20 * m12 - m22 * m10;
Real t20 = m21 * m10 - m20 * m11;
Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2];
Real invDet = 1 / (m00 * t00 + m01 * t10 + m02 * t20);
t00 *= invDet; t10 *= invDet; t20 *= invDet;
m00 *= invDet; m01 *= invDet; m02 *= invDet;
Real r00 = t00;
Real r01 = m02 * m21 - m01 * m22;
Real r02 = m01 * m12 - m02 * m11;
Real r10 = t10;
Real r11 = m00 * m22 - m02 * m20;
Real r12 = m02 * m10 - m00 * m12;
Real r20 = t20;
Real r21 = m01 * m20 - m00 * m21;
Real r22 = m00 * m11 - m01 * m10;
Real m03 = m[0][3], m13 = m[1][3], m23 = m[2][3];
Real r03 = - (r00 * m03 + r01 * m13 + r02 * m23);
Real r13 = - (r10 * m03 + r11 * m13 + r12 * m23);
Real r23 = - (r20 * m03 + r21 * m13 + r22 * m23);
return Matrix4(
r00, r01, r02, r03,
r10, r11, r12, r13,
r20, r21, r22, r23,
0, 0, 0, 1);
}
//-----------------------------------------------------------------------
void Matrix4::makeTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation)
{
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
Matrix3 rot3x3;
orientation.ToRotationMatrix(rot3x3);
// Set up final matrix with scale, rotation and translation
m[0][0] = scale.x * rot3x3[0][0]; m[0][1] = scale.y * rot3x3[0][1]; m[0][2] = scale.z * rot3x3[0][2]; m[0][3] = position.x;
m[1][0] = scale.x * rot3x3[1][0]; m[1][1] = scale.y * rot3x3[1][1]; m[1][2] = scale.z * rot3x3[1][2]; m[1][3] = position.y;
m[2][0] = scale.x * rot3x3[2][0]; m[2][1] = scale.y * rot3x3[2][1]; m[2][2] = scale.z * rot3x3[2][2]; m[2][3] = position.z;
// No projection term
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
}
//-----------------------------------------------------------------------
void Matrix4::makeInverseTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation)
{
// Invert the parameters
Vector3 invTranslate = -position;
Vector3 invScale(1 / scale.x, 1 / scale.y, 1 / scale.z);
Quaternion invRot = orientation.Inverse();
// Because we're inverting, order is translation, rotation, scale
// So make translation relative to scale & rotation
invTranslate = invRot * invTranslate; // rotate
invTranslate *= invScale; // scale
// Next, make a 3x3 rotation matrix
Matrix3 rot3x3;
invRot.ToRotationMatrix(rot3x3);
// Set up final matrix with scale, rotation and translation
m[0][0] = invScale.x * rot3x3[0][0]; m[0][1] = invScale.x * rot3x3[0][1]; m[0][2] = invScale.x * rot3x3[0][2]; m[0][3] = invTranslate.x;
m[1][0] = invScale.y * rot3x3[1][0]; m[1][1] = invScale.y * rot3x3[1][1]; m[1][2] = invScale.y * rot3x3[1][2]; m[1][3] = invTranslate.y;
m[2][0] = invScale.z * rot3x3[2][0]; m[2][1] = invScale.z * rot3x3[2][1]; m[2][2] = invScale.z * rot3x3[2][2]; m[2][3] = invTranslate.z;
// No projection term
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
}
//-----------------------------------------------------------------------
void Matrix4::decomposition(Vector3& position, Vector3& scale, Quaternion& orientation) const
{
assert(isAffine());
Matrix3 m3x3;
extract3x3Matrix(m3x3);
Matrix3 matQ;
Vector3 vecU;
m3x3.QDUDecomposition( matQ, scale, vecU );
orientation = Quaternion( matQ );
position = Vector3( m[0][3], m[1][3], m[2][3] );
}
}
<|endoftext|> |
<commit_before>/*
* Fonction
* ~~~~~~~~
* Gestion des extensions sous OpenGL
*
*
* Attention:
* ~~~~~~~~~~~
* Ce package a ete teste sur SGI, OSF, SUN, HP et WNT.
*
* Remarques:
* ~~~~~~~~~~~
* Le InitExtensionGLX permet d'initialiser le display. Ceci est necessaire
* pour travailler sur les extensions de GLX. On ne peut appeler QueryExtensionGLX
* si on n'a pas fait cette manip.
* Par contre QueryExtension gere les extensions a GL, on n'a pas besoin du
* Display.
*
* Pour l'instant on ne gere pas les extensions a GLU et a WGL.
*
* Historique des modifications
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* 14-10-97: FMN ; Creation
* 23-10-97: FMN ; Ajout gestion glx
* 19-11-97: FMN ; Ajout GetCurrentDisplay
* 04-12-97: FMN ; Ajout supportsOneDotOne
* 19-06-98: FMN ; Portage Optimizer (C++)
*/
/*----------------------------------------------------------------------*/
#ifndef _OPENGL_EXTENSION_H__
#define _OPENGL_EXTENSION_H__
/*----------------------------------------------------------------------*/
/*
* Includes
*/
#if defined(WNT) && !defined(HAVE_NO_DLL)
# ifdef __OpenGl_DLL
# define EXPORT __declspec(dllexport)
# else
# define EXPORT
# endif /* DLL */
# ifdef STRICT
# undef STRICT
# endif
# define STRICT
# include <windows.h>
#else
# define EXPORT
#endif /* WNT */
#include <GL/gl.h>
#include <GL/glu.h>
#ifdef WNT
# include <windows.h>
# ifndef Display
# define Display char
# endif /* Display */
#else
# include <GL/glx.h>
#endif /* WNT */
#ifdef GL_VERSION_1_1
#define GL_EXT_vertex_array 1
#define GL_EXT_polygon_offset 1
#define GL_EXT_blend_logic_op 1
#define GL_EXT_texture 1
#define GL_EXT_copy_texture 1
#define GL_EXT_subtexture 1
#define GL_EXT_texture_object 1
#endif /* GL_VERSION_1_1 */
#ifndef GLU_VERSION_1_2
#define GLUtesselator GLUtriangulatorObj
#define GLU_TESS_BEGIN 100100
#define GLU_TESS_VERTEX 100101
#define GLU_TESS_END 100102
#define GLU_TESS_ERROR 100103
#define GLU_TESS_COMBINE 100105
#endif
#define INVALID_EXT_FUNCTION_PTR 0xffffffff
/*
* Contournement temporaire glPolygoneOffsetEXT
* La syntaxe change entre OpenGL 1.0 et OpenGL 1.1
*/
#if defined (__sun) || defined (__osf__) || defined (__hp)
#define glPolygonOffsetEXT(a, b) glPolygonOffset(a, b)
#endif
#if defined (__sun)
#define GL_POLYGON_OFFSET_EXT GL_POLYGON_OFFSET_FILL
#endif
#ifdef WNT
#define glPolygonOffsetEXT(a, b) glPolygonOffset(a, b)
#define GL_POLYGON_OFFSET_EXT GL_POLYGON_OFFSET_FILL
#endif /* WNT */
#if defined (__sun) || defined (__osf__) || defined (__hp) || defined (__sgi)
#else
typedef void (APIENTRY * PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
#endif
/*----------------------------------------------------------------------*/
/*
* Prototypes
*/
/*
* Points d'entree Public du module
*/
extern GLboolean InitExtensionGLX(Display *display);
extern GLboolean QueryExtensionGLX(const char *extName);
extern GLboolean QueryExtension(const char *extName);
extern Display *GetCurrentDisplay(void);
extern GLboolean supportsOneDotOne(void);
extern GLboolean CheckExtension(const char *extName, const char *extString);
/* Methods defined in OpenGl_GraphicDriver.cxx */
EXPORT GLboolean OpenGl_QueryExtensionGLX (const char *extName);
EXPORT GLboolean OpenGl_QueryExtension (const char *extName);
/*----------------------------------------------------------------------*/
#endif /* _OPENGL_EXTENSION_H__ */
<commit_msg>Fix Win32 TKOpenGL build error when using static libraries<commit_after>/*
* Fonction
* ~~~~~~~~
* Gestion des extensions sous OpenGL
*
*
* Attention:
* ~~~~~~~~~~~
* Ce package a ete teste sur SGI, OSF, SUN, HP et WNT.
*
* Remarques:
* ~~~~~~~~~~~
* Le InitExtensionGLX permet d'initialiser le display. Ceci est necessaire
* pour travailler sur les extensions de GLX. On ne peut appeler QueryExtensionGLX
* si on n'a pas fait cette manip.
* Par contre QueryExtension gere les extensions a GL, on n'a pas besoin du
* Display.
*
* Pour l'instant on ne gere pas les extensions a GLU et a WGL.
*
* Historique des modifications
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* 14-10-97: FMN ; Creation
* 23-10-97: FMN ; Ajout gestion glx
* 19-11-97: FMN ; Ajout GetCurrentDisplay
* 04-12-97: FMN ; Ajout supportsOneDotOne
* 19-06-98: FMN ; Portage Optimizer (C++)
*/
/*----------------------------------------------------------------------*/
#ifndef _OPENGL_EXTENSION_H__
#define _OPENGL_EXTENSION_H__
/*----------------------------------------------------------------------*/
/*
* Includes
*/
#if defined(WNT) && !defined(HAVE_NO_DLL)
# ifdef __OpenGl_DLL
# define EXPORT __declspec(dllexport)
# else
# define EXPORT
# endif /* DLL */
#else
# define EXPORT
#endif /* WNT */
#if defined(WNT)
# ifdef STRICT
# undef STRICT
# endif
# define STRICT
# include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#ifdef WNT
# include <windows.h>
# ifndef Display
# define Display char
# endif /* Display */
#else
# include <GL/glx.h>
#endif /* WNT */
#ifdef GL_VERSION_1_1
#define GL_EXT_vertex_array 1
#define GL_EXT_polygon_offset 1
#define GL_EXT_blend_logic_op 1
#define GL_EXT_texture 1
#define GL_EXT_copy_texture 1
#define GL_EXT_subtexture 1
#define GL_EXT_texture_object 1
#endif /* GL_VERSION_1_1 */
#ifndef GLU_VERSION_1_2
#define GLUtesselator GLUtriangulatorObj
#define GLU_TESS_BEGIN 100100
#define GLU_TESS_VERTEX 100101
#define GLU_TESS_END 100102
#define GLU_TESS_ERROR 100103
#define GLU_TESS_COMBINE 100105
#endif
#define INVALID_EXT_FUNCTION_PTR 0xffffffff
/*
* Contournement temporaire glPolygoneOffsetEXT
* La syntaxe change entre OpenGL 1.0 et OpenGL 1.1
*/
#if defined (__sun) || defined (__osf__) || defined (__hp)
#define glPolygonOffsetEXT(a, b) glPolygonOffset(a, b)
#endif
#if defined (__sun)
#define GL_POLYGON_OFFSET_EXT GL_POLYGON_OFFSET_FILL
#endif
#ifdef WNT
#define glPolygonOffsetEXT(a, b) glPolygonOffset(a, b)
#define GL_POLYGON_OFFSET_EXT GL_POLYGON_OFFSET_FILL
#endif /* WNT */
#if defined (__sun) || defined (__osf__) || defined (__hp) || defined (__sgi)
#else
typedef void (APIENTRY * PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
#endif
/*----------------------------------------------------------------------*/
/*
* Prototypes
*/
/*
* Points d'entree Public du module
*/
extern GLboolean InitExtensionGLX(Display *display);
extern GLboolean QueryExtensionGLX(const char *extName);
extern GLboolean QueryExtension(const char *extName);
extern Display *GetCurrentDisplay(void);
extern GLboolean supportsOneDotOne(void);
extern GLboolean CheckExtension(const char *extName, const char *extString);
/* Methods defined in OpenGl_GraphicDriver.cxx */
EXPORT GLboolean OpenGl_QueryExtensionGLX (const char *extName);
EXPORT GLboolean OpenGl_QueryExtension (const char *extName);
/*----------------------------------------------------------------------*/
#endif /* _OPENGL_EXTENSION_H__ */
<|endoftext|> |
<commit_before>#ifndef CAFFE_OPTIMIZATION_SOLVER_HPP_
#define CAFFE_OPTIMIZATION_SOLVER_HPP_
#include <string>
#include <vector>
#include "caffe/net.hpp"
namespace caffe {
template <typename Dtype>
class Solver {
public:
explicit Solver(const SolverParameter& param);
explicit Solver(const string& param_file);
void Init(const SolverParameter& param);
void InitTrainNet();
void InitTestNets();
// The main entry of the solver function. In default, iter will be zero. Pass
// in a non-zero iter number to resume training for a pre-trained net.
virtual void Solve(const char* resume_file = NULL);
inline void Solve(const string resume_file) { Solve(resume_file.c_str()); }
virtual ~Solver() {}
inline shared_ptr<Net<Dtype> > net() { return net_; }
inline const vector<shared_ptr<Net<Dtype> > >& test_nets() {
return test_nets_;
}
protected:
// PreSolve is run before any solving iteration starts, allowing one to
// put up some scaffold.
virtual void PreSolve() {}
// Get the update value for the current iteration.
virtual void ComputeUpdateValue() = 0;
// The Solver::Snapshot function implements the basic snapshotting utility
// that stores the learned net. You should implement the SnapshotSolverState()
// function that produces a SolverState protocol buffer that needs to be
// written to disk together with the learned net.
void Snapshot();
// The test routine
void TestAll();
void Test(const int test_net_id = 0);
virtual void SnapshotSolverState(SolverState* state) = 0;
// The Restore function implements how one should restore the solver to a
// previously snapshotted state. You should implement the RestoreSolverState()
// function that restores the state from a SolverState protocol buffer.
void Restore(const char* resume_file);
virtual void RestoreSolverState(const SolverState& state) = 0;
void DisplayOutputBlobs(const int net_id);
SolverParameter param_;
int iter_;
shared_ptr<Net<Dtype> > net_;
vector<shared_ptr<Net<Dtype> > > test_nets_;
DISABLE_COPY_AND_ASSIGN(Solver);
};
template <typename Dtype>
class SGDSolver : public Solver<Dtype> {
public:
explicit SGDSolver(const SolverParameter& param)
: Solver<Dtype>(param) {}
explicit SGDSolver(const string& param_file)
: Solver<Dtype>(param_file) {}
protected:
void PreSolve();
Dtype GetLearningRate();
virtual void ComputeUpdateValue();
void SnapshotSolverState(SolverState * state);
void RestoreSolverState(const SolverState& state);
// history maintains the historical momentum data.
// update maintains update related data and is not needed in snapshots.
vector<shared_ptr<Blob<Dtype> > > history_, update_;
DISABLE_COPY_AND_ASSIGN(SGDSolver);
};
template <typename Dtype>
class NesterovSolver : public SGDSolver<Dtype> {
public:
explicit NesterovSolver(const SolverParameter& param)
: SGDSolver<Dtype>(param) {}
explicit NesterovSolver(const string& param_file)
: SGDSolver<Dtype>(param_file) {}
protected:
virtual void ComputeUpdateValue();
DISABLE_COPY_AND_ASSIGN(NesterovSolver);
};
template <typename Dtype>
class AdaGradSolver : public SGDSolver<Dtype> {
public:
explicit AdaGradSolver(const SolverParameter& param)
: SGDSolver<Dtype>(param) {}
explicit AdaGradSolver(const string& param_file)
: SGDSolver<Dtype>(param_file) {}
protected:
virtual void ComputeUpdateValue();
DISABLE_COPY_AND_ASSIGN(AdaGradSolver);
};
template <typename Dtype>
Solver<Dtype>* GetSolver(const SolverParameter& param) {
SolverParameter_SolverType type = param.solver_type();
switch (type) {
case SolverParameter_SolverType_SGD:
return new SGDSolver<Dtype>(param);
case SolverParameter_SolverType_NESTEROV:
return new NesterovSolver<Dtype>(param);
case SolverParameter_SolverType_ADAGRAD:
return new AdaGradSolver<Dtype>(param);
default:
LOG(FATAL) << "Unknown SolverType: " << type;
}
}
} // namespace caffe
#endif // CAFFE_OPTIMIZATION_SOLVER_HPP_
<commit_msg>restored vituals in solver.hpp<commit_after>#ifndef CAFFE_OPTIMIZATION_SOLVER_HPP_
#define CAFFE_OPTIMIZATION_SOLVER_HPP_
#include <string>
#include <vector>
#include "caffe/net.hpp"
namespace caffe {
template <typename Dtype>
class Solver {
public:
explicit Solver(const SolverParameter& param);
explicit Solver(const string& param_file);
void Init(const SolverParameter& param);
void InitTrainNet();
void InitTestNets();
// The main entry of the solver function. In default, iter will be zero. Pass
// in a non-zero iter number to resume training for a pre-trained net.
virtual void Solve(const char* resume_file = NULL);
inline void Solve(const string resume_file) { Solve(resume_file.c_str()); }
virtual ~Solver() {}
inline shared_ptr<Net<Dtype> > net() { return net_; }
inline const vector<shared_ptr<Net<Dtype> > >& test_nets() {
return test_nets_;
}
protected:
// PreSolve is run before any solving iteration starts, allowing one to
// put up some scaffold.
virtual void PreSolve() {}
// Get the update value for the current iteration.
virtual void ComputeUpdateValue() = 0;
// The Solver::Snapshot function implements the basic snapshotting utility
// that stores the learned net. You should implement the SnapshotSolverState()
// function that produces a SolverState protocol buffer that needs to be
// written to disk together with the learned net.
void Snapshot();
// The test routine
void TestAll();
void Test(const int test_net_id = 0);
virtual void SnapshotSolverState(SolverState* state) = 0;
// The Restore function implements how one should restore the solver to a
// previously snapshotted state. You should implement the RestoreSolverState()
// function that restores the state from a SolverState protocol buffer.
void Restore(const char* resume_file);
virtual void RestoreSolverState(const SolverState& state) = 0;
void DisplayOutputBlobs(const int net_id);
SolverParameter param_;
int iter_;
shared_ptr<Net<Dtype> > net_;
vector<shared_ptr<Net<Dtype> > > test_nets_;
DISABLE_COPY_AND_ASSIGN(Solver);
};
template <typename Dtype>
class SGDSolver : public Solver<Dtype> {
public:
explicit SGDSolver(const SolverParameter& param)
: Solver<Dtype>(param) {}
explicit SGDSolver(const string& param_file)
: Solver<Dtype>(param_file) {}
protected:
virtual void PreSolve();
Dtype GetLearningRate();
virtual void ComputeUpdateValue();
virtual void SnapshotSolverState(SolverState * state);
virtual void RestoreSolverState(const SolverState& state);
// history maintains the historical momentum data.
// update maintains update related data and is not needed in snapshots.
vector<shared_ptr<Blob<Dtype> > > history_, update_;
DISABLE_COPY_AND_ASSIGN(SGDSolver);
};
template <typename Dtype>
class NesterovSolver : public SGDSolver<Dtype> {
public:
explicit NesterovSolver(const SolverParameter& param)
: SGDSolver<Dtype>(param) {}
explicit NesterovSolver(const string& param_file)
: SGDSolver<Dtype>(param_file) {}
protected:
virtual void ComputeUpdateValue();
DISABLE_COPY_AND_ASSIGN(NesterovSolver);
};
template <typename Dtype>
class AdaGradSolver : public SGDSolver<Dtype> {
public:
explicit AdaGradSolver(const SolverParameter& param)
: SGDSolver<Dtype>(param) {}
explicit AdaGradSolver(const string& param_file)
: SGDSolver<Dtype>(param_file) {}
protected:
virtual void ComputeUpdateValue();
DISABLE_COPY_AND_ASSIGN(AdaGradSolver);
};
template <typename Dtype>
Solver<Dtype>* GetSolver(const SolverParameter& param) {
SolverParameter_SolverType type = param.solver_type();
switch (type) {
case SolverParameter_SolverType_SGD:
return new SGDSolver<Dtype>(param);
case SolverParameter_SolverType_NESTEROV:
return new NesterovSolver<Dtype>(param);
case SolverParameter_SolverType_ADAGRAD:
return new AdaGradSolver<Dtype>(param);
default:
LOG(FATAL) << "Unknown SolverType: " << type;
}
}
} // namespace caffe
#endif // CAFFE_OPTIMIZATION_SOLVER_HPP_
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include "vast/concept/parseable/vast/json.hpp"
#include "vast/defaults.hpp"
#include "vast/detail/line_range.hpp"
#include "vast/error.hpp"
#include "vast/event.hpp"
#include "vast/format/multi_layout_reader.hpp"
#include "vast/format/ostream_writer.hpp"
#include "vast/fwd.hpp"
#include "vast/json.hpp"
#include "vast/logger.hpp"
#include "vast/schema.hpp"
#include <caf/expected.hpp>
#include <caf/fwd.hpp>
namespace vast::format::json {
class writer : public ostream_writer {
public:
using defaults = vast::defaults::export_::json;
using super = ostream_writer;
using super::super;
caf::error write(const table_slice& x) override;
const char* name() const override;
};
/// Adds a JSON object to a table slice builder according to a given layout.
/// @param builder The builder to add the JSON object to.
/// @param xs The JSON object to add to *builder.
/// @param layout The record type describing *xs*.
/// @returns An error iff the operation failed.
caf::error add(table_slice_builder& builder, const vast::json::object& xs,
const record_type& layout);
/// @relates reader
struct default_selector {
caf::optional<record_type> operator()(const vast::json::object&) {
return layout;
}
caf::error schema(vast::schema sch) {
auto entry = *sch.begin();
if (!caf::holds_alternative<record_type>(entry))
return make_error(ec::invalid_configuration,
"only record_types supported for json schema");
layout = flatten(caf::get<record_type>(entry));
return caf::none;
}
vast::schema schema() const {
vast::schema result;
if (layout)
result.add(*layout);
return result;
}
static const char* name() {
return "json-reader";
}
caf::optional<record_type> layout = caf::none;
};
/// A reader for JSON data. It operates with a *selector* to determine the
/// mapping of JSON object to the appropriate record type in the schema.
template <class Selector = default_selector>
class reader final : public multi_layout_reader {
public:
using super = multi_layout_reader;
/// Constructs a JSON reader.
/// @param table_slice_type The ID for table slice type to build.
/// @param options Additional options.
/// @param in The stream of JSON objects.
explicit reader(caf::atom_value table_slice_type,
const caf::settings& options,
std::unique_ptr<std::istream> in = nullptr);
void reset(std::unique_ptr<std::istream> in);
caf::error schema(vast::schema sch) override;
vast::schema schema() const override;
const char* name() const override;
protected:
caf::error read_impl(size_t max_events, size_t max_slice_size,
consumer& f) override;
private:
using iterator_type = std::string_view::const_iterator;
Selector selector_;
std::unique_ptr<std::istream> input_;
std::unique_ptr<detail::line_range> lines_;
caf::optional<size_t> proto_field_;
std::vector<size_t> port_fields_;
};
// -- implementation ----------------------------------------------------------
template <class Selector>
reader<Selector>::reader(caf::atom_value table_slice_type,
const caf::settings& /*options*/,
std::unique_ptr<std::istream> in)
: super(table_slice_type) {
if (in != nullptr)
reset(std::move(in));
}
template <class Selector>
void reader<Selector>::reset(std::unique_ptr<std::istream> in) {
VAST_ASSERT(in != nullptr);
input_ = std::move(in);
lines_ = std::make_unique<detail::line_range>(*input_);
}
template <class Selector>
caf::error reader<Selector>::schema(vast::schema s) {
return selector_.schema(std::move(s));
}
template <class Selector>
vast::schema reader<Selector>::schema() const {
return selector_.schema();
}
template <class Selector>
const char* reader<Selector>::name() const {
return Selector::name();
}
template <class Selector>
caf::error reader<Selector>::read_impl(size_t max_events, size_t max_slice_size,
consumer& cons) {
VAST_ASSERT(max_events > 0);
VAST_ASSERT(max_slice_size > 0);
size_t produced = 0;
for (; produced < max_events; lines_->next()) {
// EOF check.
if (lines_->done())
return finish(cons, make_error(ec::end_of_input, "input exhausted"));
auto& line = lines_->get();
vast::json j;
if (!parsers::json(line, j))
return make_error(ec::parse_error, "unable to parse json");
auto xs = caf::get_if<vast::json::object>(&j);
if (!xs)
return make_error(ec::type_clash, "not a json object");
auto layout = selector_(*xs);
if (!layout)
continue;
auto bptr = builder(*layout);
if (bptr == nullptr)
return make_error(ec::parse_error, "unable to get a builder");
if (auto err = add(*bptr, *xs, *layout)) {
err.context() += caf::make_message("line", lines_->line_number());
return finish(cons, err);
}
produced++;
if (bptr->rows() == max_slice_size)
if (auto err = finish(cons, bptr))
return err;
}
return finish(cons);
}
} // namespace vast::format::json
<commit_msg>Be more resilient towards malformed JSON input<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include "vast/concept/parseable/vast/json.hpp"
#include "vast/defaults.hpp"
#include "vast/detail/line_range.hpp"
#include "vast/error.hpp"
#include "vast/event.hpp"
#include "vast/format/multi_layout_reader.hpp"
#include "vast/format/ostream_writer.hpp"
#include "vast/fwd.hpp"
#include "vast/json.hpp"
#include "vast/logger.hpp"
#include "vast/schema.hpp"
#include <caf/expected.hpp>
#include <caf/fwd.hpp>
namespace vast::format::json {
class writer : public ostream_writer {
public:
using defaults = vast::defaults::export_::json;
using super = ostream_writer;
using super::super;
caf::error write(const table_slice& x) override;
const char* name() const override;
};
/// Adds a JSON object to a table slice builder according to a given layout.
/// @param builder The builder to add the JSON object to.
/// @param xs The JSON object to add to *builder.
/// @param layout The record type describing *xs*.
/// @returns An error iff the operation failed.
caf::error add(table_slice_builder& builder, const vast::json::object& xs,
const record_type& layout);
/// @relates reader
struct default_selector {
caf::optional<record_type> operator()(const vast::json::object&) {
return layout;
}
caf::error schema(vast::schema sch) {
auto entry = *sch.begin();
if (!caf::holds_alternative<record_type>(entry))
return make_error(ec::invalid_configuration,
"only record_types supported for json schema");
layout = flatten(caf::get<record_type>(entry));
return caf::none;
}
vast::schema schema() const {
vast::schema result;
if (layout)
result.add(*layout);
return result;
}
static const char* name() {
return "json-reader";
}
caf::optional<record_type> layout = caf::none;
};
/// A reader for JSON data. It operates with a *selector* to determine the
/// mapping of JSON object to the appropriate record type in the schema.
template <class Selector = default_selector>
class reader final : public multi_layout_reader {
public:
using super = multi_layout_reader;
/// Constructs a JSON reader.
/// @param table_slice_type The ID for table slice type to build.
/// @param options Additional options.
/// @param in The stream of JSON objects.
explicit reader(caf::atom_value table_slice_type,
const caf::settings& options,
std::unique_ptr<std::istream> in = nullptr);
void reset(std::unique_ptr<std::istream> in);
caf::error schema(vast::schema sch) override;
vast::schema schema() const override;
const char* name() const override;
protected:
caf::error read_impl(size_t max_events, size_t max_slice_size,
consumer& f) override;
private:
using iterator_type = std::string_view::const_iterator;
Selector selector_;
std::unique_ptr<std::istream> input_;
std::unique_ptr<detail::line_range> lines_;
caf::optional<size_t> proto_field_;
std::vector<size_t> port_fields_;
};
// -- implementation ----------------------------------------------------------
template <class Selector>
reader<Selector>::reader(caf::atom_value table_slice_type,
const caf::settings& /*options*/,
std::unique_ptr<std::istream> in)
: super(table_slice_type) {
if (in != nullptr)
reset(std::move(in));
}
template <class Selector>
void reader<Selector>::reset(std::unique_ptr<std::istream> in) {
VAST_ASSERT(in != nullptr);
input_ = std::move(in);
lines_ = std::make_unique<detail::line_range>(*input_);
}
template <class Selector>
caf::error reader<Selector>::schema(vast::schema s) {
return selector_.schema(std::move(s));
}
template <class Selector>
vast::schema reader<Selector>::schema() const {
return selector_.schema();
}
template <class Selector>
const char* reader<Selector>::name() const {
return Selector::name();
}
template <class Selector>
caf::error reader<Selector>::read_impl(size_t max_events, size_t max_slice_size,
consumer& cons) {
VAST_ASSERT(max_events > 0);
VAST_ASSERT(max_slice_size > 0);
size_t produced = 0;
for (; produced < max_events; lines_->next()) {
// EOF check.
if (lines_->done())
return finish(cons, make_error(ec::end_of_input, "input exhausted"));
auto& line = lines_->get();
vast::json j;
if (!parsers::json(line, j)) {
VAST_WARNING(this, "failed to parse", line);
continue;
}
auto xs = caf::get_if<vast::json::object>(&j);
if (!xs)
return make_error(ec::type_clash, "not a json object");
auto layout = selector_(*xs);
if (!layout)
continue;
auto bptr = builder(*layout);
if (bptr == nullptr)
return make_error(ec::parse_error, "unable to get a builder");
if (auto err = add(*bptr, *xs, *layout)) {
err.context() += caf::make_message("line", lines_->line_number());
return finish(cons, err);
}
produced++;
if (bptr->rows() == max_slice_size)
if (auto err = finish(cons, bptr))
return err;
}
return finish(cons);
}
} // namespace vast::format::json
<|endoftext|> |
<commit_before>/**
* \file dcs/testbed/libvirt/virtual_machine_manager.hpp
*
* \brief Libvirt-based Virtual Machine Manager.
*
* \author Marco Guazzone ([email protected])
*
* <hr/>
*
* Copyright 2012 Marco Guazzone ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_TESTBED_LIBVIRT_VIRTUAL_MACHINE_MANAGER_HPP
#define DCS_TESTBED_LIBVIRT_VIRTUAL_MACHINE_MANAGER_HPP
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/logging.hpp>
#include <dcs/testbed/base_virtual_machine_manager.hpp>
#include <dcs/testbed/libvirt/detail/utility.hpp>
#include <dcs/testbed/libvirt/virtual_machine.hpp>
#include <dcs/uri.hpp>
#include <exception>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
namespace dcs { namespace testbed { namespace libvirt {
/*
inline
::std::string strip_vmm_uri(::std::string const& uri)
{
::std::ostringstream oss;
::dcs::uri u(uri);
if (!u.relative())
{
oss << u.scheme() << "://" << u.authority() << "/";
}
return oss.str();
}
*/
template <typename TraitsT>
class virtual_machine_manager: public base_virtual_machine_manager<TraitsT>
{
private: typedef base_virtual_machine_manager<TraitsT> base_type;
public: typedef typename base_type::traits_type traits_type;
public: typedef typename base_type::identifier_type identifier_type;
public: typedef typename base_type::vm_identifier_type vm_identifier_type;
public: typedef typename base_type::vm_pointer vm_pointer;
public: typedef typename base_type::uint_type uint_type;
private: typedef ::std::map<vm_identifier_type,vm_pointer> vm_container;
public: virtual_machine_manager(::std::string const& uri)
: uri_(detail::vmm_uri(uri)),
p_conn_(0)
{
init();
}
public: ~virtual_machine_manager()
{
// According to http://www.stlport.org/doc/exception_safety.html we avoid to throw any exception inside the destructor
try
{
if (p_conn_)
{
detail::disconnect(p_conn_);
}
}
catch (::std::exception const& e)
{
::std::ostringstream oss;
oss << "Failed to disconnect from hypervisor '" << uri_ << "': " << e.what();
dcs::log_error(DCS_LOGGING_AT, oss.str());
}
catch (...)
{
::std::ostringstream oss;
oss << "Failed to disconnect from hypervisor '" << uri_ << "': Unknown error";
dcs::log_error(DCS_LOGGING_AT, oss.str());
}
}
public: ::std::string uri() const
{
return uri_;
}
public: ::virConnectPtr connection()
{
return p_conn_;
}
public: ::virConnectPtr connection() const
{
return p_conn_;
}
private: void init()
{
// Connect to libvirtd daemon
p_conn_ = detail::connect(uri_);
}
private: identifier_type do_id() const
{
return uri_;
}
private: bool do_alive() const
{
int ret = ::virConnectIsAlive(p_conn_);
if (-1 == ret)
{
::std::ostringstream oss;
oss << "Failed to check for VMM aliveness " << detail::last_error(p_conn_);
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
return ret ? true : false;
}
private: vm_pointer do_vm(vm_identifier_type const& id)
{
if (vm_map_.count(id) == 0)
{
vm_map_[id] = ::boost::make_shared< virtual_machine<traits_type> >(this, id);
// check: vm_map.at(id) != null
DCS_DEBUG_ASSERT( vm_map_.at(id) );
}
return vm_map_.at(id);
}
private: vm_pointer do_vm(vm_identifier_type const& id) const
{
DCS_ASSERT(vm_map_.count(id) > 0,
DCS_EXCEPTION_THROW(::std::invalid_argument,
"VM not found"));
return vm_map_.at(id);
}
private: uint_type do_max_supported_num_vcpus() const
{
DCS_ASSERT(p_conn_,
DCS_EXCEPTION_THROW(::std::logic_error,
"Not connected"));
int max_nvcpus = detail::max_supported_num_vcpus(p_conn_);
return static_cast<uint_type>(max_nvcpus);
}
private: ::std::string uri_;
private: ::virConnectPtr p_conn_;
private: vm_container vm_map_;
}; // virtual_machine_manager
}}} // Namespace dcs::testbed::libvirt
#endif // DCS_TESTBED_LIBVIRT_VIRTUAL_MACHINE_MANAGER_HPP
<commit_msg>New function 'vmm_uri'<commit_after>/**
* \file dcs/testbed/libvirt/virtual_machine_manager.hpp
*
* \brief Libvirt-based Virtual Machine Manager.
*
* \author Marco Guazzone ([email protected])
*
* <hr/>
*
* Copyright 2012 Marco Guazzone ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_TESTBED_LIBVIRT_VIRTUAL_MACHINE_MANAGER_HPP
#define DCS_TESTBED_LIBVIRT_VIRTUAL_MACHINE_MANAGER_HPP
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/logging.hpp>
#include <dcs/testbed/base_virtual_machine_manager.hpp>
#include <dcs/testbed/libvirt/detail/utility.hpp>
#include <dcs/testbed/libvirt/virtual_machine.hpp>
#include <dcs/uri.hpp>
#include <exception>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
namespace dcs { namespace testbed { namespace libvirt {
/*
inline
::std::string strip_vmm_uri(::std::string const& uri)
{
::std::ostringstream oss;
::dcs::uri u(uri);
if (!u.relative())
{
oss << u.scheme() << "://" << u.authority() << "/";
}
return oss.str();
}
*/
/// Gets the URI for the virtual machine manager from the given URI
inline
std::string vmm_uri(std::string const& uri)
{
return detail::vmm_uri(uri);
}
template <typename TraitsT>
class virtual_machine_manager: public base_virtual_machine_manager<TraitsT>
{
private: typedef base_virtual_machine_manager<TraitsT> base_type;
public: typedef typename base_type::traits_type traits_type;
public: typedef typename base_type::identifier_type identifier_type;
public: typedef typename base_type::vm_identifier_type vm_identifier_type;
public: typedef typename base_type::vm_pointer vm_pointer;
public: typedef typename base_type::uint_type uint_type;
private: typedef ::std::map<vm_identifier_type,vm_pointer> vm_container;
public: virtual_machine_manager(::std::string const& uri)
: uri_(detail::vmm_uri(uri)),
p_conn_(0)
{
init();
}
public: ~virtual_machine_manager()
{
// According to http://www.stlport.org/doc/exception_safety.html we avoid to throw any exception inside the destructor
try
{
if (p_conn_)
{
detail::disconnect(p_conn_);
}
}
catch (::std::exception const& e)
{
::std::ostringstream oss;
oss << "Failed to disconnect from hypervisor '" << uri_ << "': " << e.what();
dcs::log_error(DCS_LOGGING_AT, oss.str());
}
catch (...)
{
::std::ostringstream oss;
oss << "Failed to disconnect from hypervisor '" << uri_ << "': Unknown error";
dcs::log_error(DCS_LOGGING_AT, oss.str());
}
}
public: ::std::string uri() const
{
return uri_;
}
public: ::virConnectPtr connection()
{
return p_conn_;
}
public: ::virConnectPtr connection() const
{
return p_conn_;
}
private: void init()
{
// Connect to libvirtd daemon
p_conn_ = detail::connect(uri_);
}
private: identifier_type do_id() const
{
return uri_;
}
private: bool do_alive() const
{
int ret = ::virConnectIsAlive(p_conn_);
if (-1 == ret)
{
::std::ostringstream oss;
oss << "Failed to check for VMM aliveness " << detail::last_error(p_conn_);
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
return ret ? true : false;
}
private: vm_pointer do_vm(vm_identifier_type const& id)
{
if (vm_map_.count(id) == 0)
{
vm_map_[id] = ::boost::make_shared< virtual_machine<traits_type> >(this, id);
// check: vm_map.at(id) != null
DCS_DEBUG_ASSERT( vm_map_.at(id) );
}
return vm_map_.at(id);
}
private: vm_pointer do_vm(vm_identifier_type const& id) const
{
DCS_ASSERT(vm_map_.count(id) > 0,
DCS_EXCEPTION_THROW(::std::invalid_argument,
"VM not found"));
return vm_map_.at(id);
}
private: uint_type do_max_supported_num_vcpus() const
{
DCS_ASSERT(p_conn_,
DCS_EXCEPTION_THROW(::std::logic_error,
"Not connected"));
int max_nvcpus = detail::max_supported_num_vcpus(p_conn_);
return static_cast<uint_type>(max_nvcpus);
}
private: ::std::string uri_;
private: ::virConnectPtr p_conn_;
private: vm_container vm_map_;
}; // virtual_machine_manager
}}} // Namespace dcs::testbed::libvirt
#endif // DCS_TESTBED_LIBVIRT_VIRTUAL_MACHINE_MANAGER_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2016, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#ifndef HPP_PINOCCHIO_CENTER_OF_MASS_COMPUTATION_HH
# define HPP_PINOCCHIO_CENTER_OF_MASS_COMPUTATION_HH
# include <list>
# include <pinocchio/multibody/model.hpp> // se3::Data
# include <hpp/pinocchio/fwd.hh>
# include <hpp/pinocchio/device.hh>
namespace hpp {
namespace pinocchio {
class CenterOfMassComputation
{
public:
typedef std::vector <JointIndex> JointRootIndexes_t;
/// \cond
// This fixes an alignment issue of se3::Data::hg
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/// \endcond
public:
static CenterOfMassComputationPtr_t create (const DevicePtr_t& device);
void add (const JointPtr_t& rootOfSubtree);
void compute (const Device::Computation_t& flag
= Device::ALL);
const vector3_t& com () const { return data.com [0]; }
const value_type& mass () const { return data.mass[0]; }
const ComJacobian_t& jacobian () const { return data.Jcom ; }
const JointRootIndexes_t & roots () const { return roots_; }
~CenterOfMassComputation ();
protected:
CenterOfMassComputation (const DevicePtr_t& device);
private:
DevicePtr_t robot_;
// Root of the subtrees
JointRootIndexes_t roots_;
// Specific pinocchio Data to store the computation results
Data data;
// value_type mass_;
// vector3_t com_;
// ComJacobian_t jacobianCom_;
}; // class CenterOfMassComputation
} // namespace pinocchio
} // namespace hpp
#endif // HPP_PINOCCHIO_CENTER_OF_MASS_COMPUTATION_HH
<commit_msg>Cosmetic: add documentation to class CenterOfMassComputation.<commit_after>// Copyright (c) 2016, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#ifndef HPP_PINOCCHIO_CENTER_OF_MASS_COMPUTATION_HH
# define HPP_PINOCCHIO_CENTER_OF_MASS_COMPUTATION_HH
# include <list>
# include <pinocchio/multibody/model.hpp> // se3::Data
# include <hpp/pinocchio/fwd.hh>
# include <hpp/pinocchio/device.hh>
namespace hpp {
namespace pinocchio {
/// Computation of the center of mass of a subtree of a kinematic tree
///
/// To use this class, create an instance using
/// CenterOfMassComputation::create method and call method
/// CenterOfMassComputation::add with parameter the root joint
/// of the subtree.
///
/// In most cases, the root joint of the subtree is the root joint of
/// the robot (hpp::pinocchio::Device::rootJoint ()), but in a manipulation
/// context, the kinematic tree contains several robots and objects.
/// This class enables users to compute the center of mass of only one
/// robot or object.
class CenterOfMassComputation
{
public:
typedef std::vector <JointIndex> JointRootIndexes_t;
/// \cond
// This fixes an alignment issue of se3::Data::hg
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/// \endcond
public:
/// Create instance and return shared pointer.
///
/// Do not forget to call method add to specify the root joint of
/// relevant kinematic tree.
static CenterOfMassComputationPtr_t create (const DevicePtr_t& device);
/// Add a subtree to the computation of the center of mass.
///
/// When several subtrees are provided, method \c compute computes the
/// center of mass of the union of the subtrees.
void add (const JointPtr_t& rootOfSubtree);
/// Compute the center of mass and Jacobian of the sub-trees.
void compute (const Device::Computation_t& flag
= Device::ALL);
/// Get center of mass of the subtree.
const vector3_t& com () const { return data.com [0]; }
/// Get mass of the sub-tree.
const value_type& mass () const { return data.mass[0]; }
/// Get Jacobian of center of mass of the sub-tree.
const ComJacobian_t& jacobian () const { return data.Jcom ; }
/// Get const reference to the vector of sub-tree roots.
const JointRootIndexes_t & roots () const { return roots_; }
~CenterOfMassComputation ();
protected:
CenterOfMassComputation (const DevicePtr_t& device);
private:
DevicePtr_t robot_;
// Root of the subtrees
JointRootIndexes_t roots_;
// Specific pinocchio Data to store the computation results
Data data;
// value_type mass_;
// vector3_t com_;
// ComJacobian_t jacobianCom_;
}; // class CenterOfMassComputation
} // namespace pinocchio
} // namespace hpp
#endif // HPP_PINOCCHIO_CENTER_OF_MASS_COMPUTATION_HH
<|endoftext|> |
<commit_before>/* File: BinaryFileFactory.cpp
* Desc: This file contains the implementation of the factory function
* BinaryFile::getInstanceFor(), and also BinaryFile::Load()
*
* This function determines the type of a binary and loads the appropriate
* loader class dynamically.
*/
#include "BinaryFile.h"
#include "ElfBinaryFile.h"
#include "Win32BinaryFile.h"
#include "PalmBinaryFile.h"
#include "HpSomBinaryFile.h"
#include "ExeBinaryFile.h"
#include <iostream>
#ifndef _WIN32
#include <dlfcn.h>
#else
#include <windows.h>
#endif
BinaryFile *BinaryFileFactory::Load( const char *sName )
{
BinaryFile *pBF = getInstanceFor( sName );
if( pBF == NULL ) {
std::cerr << "unrecognised binary file format.\n";
return NULL;
}
if( pBF->RealLoad( sName ) == 0 ) {
fprintf( stderr, "Loading '%s' failed\n", sName );
delete pBF;
return NULL;
}
pBF->getTextLimits();
return pBF;
}
#define TESTMAGIC2(buf,off,a,b) (buf[off] == a && buf[off+1] == b)
#define TESTMAGIC4(buf,off,a,b,c,d) (buf[off] == a && buf[off+1] == b && \
buf[off+2] == c && buf[off+3] == d)
// Declare a pointer to a constructor function; returns a BinaryFile*
typedef BinaryFile* (*constructFcn)();
BinaryFile* BinaryFileFactory::getInstanceFor( const char *sName )
{
FILE *f;
unsigned char buf[64];
std::string libName;
BinaryFile *res = NULL;
f = fopen (sName, "ro");
if( f == NULL ) {
fprintf(stderr, "Unable to open binary file: %s\n", sName );
return NULL;
}
fread (buf, sizeof(buf), 1, f);
if( TESTMAGIC4(buf,0, '\177','E','L','F') ) {
/* ELF Binary */
libName = "ElfBinaryFile";
} else if( TESTMAGIC2( buf,0, 'M','Z' ) ) { /* DOS-based file */
int peoff = LMMH(buf[0x3C]);
if( peoff != 0 && fseek(f, peoff, SEEK_SET) != -1 ) {
fread( buf, 4, 1, f );
if( TESTMAGIC4( buf,0, 'P','E',0,0 ) ) {
/* Win32 Binary */
libName = "Win32BinaryFile";
} else if( TESTMAGIC2( buf,0, 'N','E' ) ) {
/* Win16 / Old OS/2 Binary */
} else if( TESTMAGIC2( buf,0, 'L','E' ) ) {
/* Win32 VxD (Linear Executable) or DOS4GW app */
libName = "DOS4GWBinaryFile";
} else if( TESTMAGIC2( buf,0, 'L','X' ) ) {
/* New OS/2 Binary */
}
}
/* Assume MS-DOS Real-mode binary. */
if( libName.size() == 0 )
libName = "ExeBinaryFile";
} else if( TESTMAGIC4( buf,0x3C, 'a','p','p','l' ) ||
TESTMAGIC4( buf,0x3C, 'p','a','n','l' ) ) {
/* PRC Palm-pilot binary */
libName = "PalmBinaryFile";
} else if( buf[0] == 0xfe && buf[1] == 0xed && buf[2] == 0xfa && buf[3] == 0xce ) {
/* Mach-O Mac OS-X binary */
libName = "MachOBinaryFile";
} else if( buf[0] == 0x02 && buf[2] == 0x01 &&
(buf[1] == 0x10 || buf[1] == 0x0B) &&
(buf[3] == 0x07 || buf[3] == 0x08 || buf[4] == 0x0B) ) {
/* HP Som binary (last as it's not really particularly good magic) */
libName = "HpSomBinaryFile";
} else {
fprintf( stderr, "Unrecognised binary file\n" );
fclose(f);
return NULL;
}
// Load the specific loader library
#ifndef _WIN32 // Cygwin, Unix/Linux
libName = std::string("lib/lib") + libName;
#ifdef __CYGWIN__
libName += ".dll"; // Cygwin wants .dll, but is otherwise like Unix
#else
libName += ".so";
#endif
void* dlHandle = dlopen(libName.c_str(), RTLD_LAZY);
if (dlHandle == NULL) {
fprintf( stderr, "Could not open dynamic loader library %s\n", libName.c_str());
fprintf( stderr, "%s\n", dlerror());
fclose(f);
return NULL;
}
// Use the handle to find the "construct" function
constructFcn pFcn = (constructFcn) dlsym(dlHandle, "construct");
#else // Else MSVC, MinGW
libName += ".dll"; // Example: ElfBinaryFile.dll (same dir as boomerang.exe)
#ifdef __MINGW32__
libName = "lib/lib" + libName;
#endif
HMODULE hModule = LoadLibrary(libName.c_str());
if(hModule == NULL) {
int err = GetLastError();
fprintf( stderr, "Could not open dynamic loader library %s (error #%d)\n", libName.c_str(), err);
fclose(f);
return NULL;
}
// Use the handle to find the "construct" function
constructFcn pFcn = (constructFcn) GetProcAddress(hModule, "construct");
#endif
if (pFcn == NULL) {
fprintf( stderr, "Loader library %s does not have a construct function\n", libName.c_str());
fclose(f);
return NULL;
}
// Call the construct function
res = (*pFcn)();
fclose(f);
return res;
}
<commit_msg>Minor change to avoid a warning when compiling under Windows<commit_after>/* File: BinaryFileFactory.cpp
* Desc: This file contains the implementation of the factory function
* BinaryFile::getInstanceFor(), and also BinaryFile::Load()
*
* This function determines the type of a binary and loads the appropriate
* loader class dynamically.
*/
#ifndef _WIN32
#include <dlfcn.h>
#else
#include <windows.h> // include before types.h: name collision of NO_ADDRESS and WinSock.h
#endif
#include "BinaryFile.h"
#include "ElfBinaryFile.h"
#include "Win32BinaryFile.h"
#include "PalmBinaryFile.h"
#include "HpSomBinaryFile.h"
#include "ExeBinaryFile.h"
#include <iostream>
BinaryFile *BinaryFileFactory::Load( const char *sName )
{
BinaryFile *pBF = getInstanceFor( sName );
if( pBF == NULL ) {
std::cerr << "unrecognised binary file format.\n";
return NULL;
}
if( pBF->RealLoad( sName ) == 0 ) {
fprintf( stderr, "Loading '%s' failed\n", sName );
delete pBF;
return NULL;
}
pBF->getTextLimits();
return pBF;
}
#define TESTMAGIC2(buf,off,a,b) (buf[off] == a && buf[off+1] == b)
#define TESTMAGIC4(buf,off,a,b,c,d) (buf[off] == a && buf[off+1] == b && \
buf[off+2] == c && buf[off+3] == d)
// Declare a pointer to a constructor function; returns a BinaryFile*
typedef BinaryFile* (*constructFcn)();
BinaryFile* BinaryFileFactory::getInstanceFor( const char *sName )
{
FILE *f;
unsigned char buf[64];
std::string libName;
BinaryFile *res = NULL;
f = fopen (sName, "ro");
if( f == NULL ) {
fprintf(stderr, "Unable to open binary file: %s\n", sName );
return NULL;
}
fread (buf, sizeof(buf), 1, f);
if( TESTMAGIC4(buf,0, '\177','E','L','F') ) {
/* ELF Binary */
libName = "ElfBinaryFile";
} else if( TESTMAGIC2( buf,0, 'M','Z' ) ) { /* DOS-based file */
int peoff = LMMH(buf[0x3C]);
if( peoff != 0 && fseek(f, peoff, SEEK_SET) != -1 ) {
fread( buf, 4, 1, f );
if( TESTMAGIC4( buf,0, 'P','E',0,0 ) ) {
/* Win32 Binary */
libName = "Win32BinaryFile";
} else if( TESTMAGIC2( buf,0, 'N','E' ) ) {
/* Win16 / Old OS/2 Binary */
} else if( TESTMAGIC2( buf,0, 'L','E' ) ) {
/* Win32 VxD (Linear Executable) or DOS4GW app */
libName = "DOS4GWBinaryFile";
} else if( TESTMAGIC2( buf,0, 'L','X' ) ) {
/* New OS/2 Binary */
}
}
/* Assume MS-DOS Real-mode binary. */
if( libName.size() == 0 )
libName = "ExeBinaryFile";
} else if( TESTMAGIC4( buf,0x3C, 'a','p','p','l' ) ||
TESTMAGIC4( buf,0x3C, 'p','a','n','l' ) ) {
/* PRC Palm-pilot binary */
libName = "PalmBinaryFile";
} else if( buf[0] == 0xfe && buf[1] == 0xed && buf[2] == 0xfa && buf[3] == 0xce ) {
/* Mach-O Mac OS-X binary */
libName = "MachOBinaryFile";
} else if( buf[0] == 0x02 && buf[2] == 0x01 &&
(buf[1] == 0x10 || buf[1] == 0x0B) &&
(buf[3] == 0x07 || buf[3] == 0x08 || buf[4] == 0x0B) ) {
/* HP Som binary (last as it's not really particularly good magic) */
libName = "HpSomBinaryFile";
} else {
fprintf( stderr, "Unrecognised binary file\n" );
fclose(f);
return NULL;
}
// Load the specific loader library
#ifndef _WIN32 // Cygwin, Unix/Linux
libName = std::string("lib/lib") + libName;
#ifdef __CYGWIN__
libName += ".dll"; // Cygwin wants .dll, but is otherwise like Unix
#else
libName += ".so";
#endif
void* dlHandle = dlopen(libName.c_str(), RTLD_LAZY);
if (dlHandle == NULL) {
fprintf( stderr, "Could not open dynamic loader library %s\n", libName.c_str());
fprintf( stderr, "%s\n", dlerror());
fclose(f);
return NULL;
}
// Use the handle to find the "construct" function
constructFcn pFcn = (constructFcn) dlsym(dlHandle, "construct");
#else // Else MSVC, MinGW
libName += ".dll"; // Example: ElfBinaryFile.dll (same dir as boomerang.exe)
#ifdef __MINGW32__
libName = "lib/lib" + libName;
#endif
HMODULE hModule = LoadLibrary(libName.c_str());
if(hModule == NULL) {
int err = GetLastError();
fprintf( stderr, "Could not open dynamic loader library %s (error #%d)\n", libName.c_str(), err);
fclose(f);
return NULL;
}
// Use the handle to find the "construct" function
constructFcn pFcn = (constructFcn) GetProcAddress(hModule, "construct");
#endif
if (pFcn == NULL) {
fprintf( stderr, "Loader library %s does not have a construct function\n", libName.c_str());
fclose(f);
return NULL;
}
// Call the construct function
res = (*pFcn)();
fclose(f);
return res;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP
namespace third {
//#define THIRD_RBM_1 //One layer of RBM
//#define THIRD_RBM_2 //Two layers of RBM
//#define THIRD_RBM_3 //Three layers of RBM
//#define THIRD_CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1)
#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)
//#define THIRD_CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1)
//#define THIRD_CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)
//#define THIRD_COMPLEX_2 //Architecture to play around LCN
//#define THIRD_MODERN //Architecture to play around
constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width = 20;
// Data augmentation
constexpr const std::size_t elastic_augment = 1; //not ready
constexpr const std::size_t epochs = 10;
constexpr const std::size_t train_stride = 1;
constexpr const std::size_t test_stride = 1;
constexpr const std::size_t NF1 = 9;
constexpr const std::size_t K1 = 8;
constexpr const std::size_t C1 = 2;
constexpr const std::size_t B1 = 128;
constexpr const dll::unit_type HT1 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;
constexpr const bool shuffle_1 = false;
constexpr const std::size_t NF2 = 3;
constexpr const std::size_t K2 = 8;
constexpr const std::size_t C2 = 2;
constexpr const std::size_t B2 = 128;
constexpr const dll::unit_type HT2 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;
constexpr const bool shuffle_2 = false;
constexpr const std::size_t NF3 = 3;
constexpr const std::size_t K3 = 48;
constexpr const std::size_t C3 = 2;
constexpr const std::size_t B3 = 64;
constexpr const dll::unit_type HT3 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;
constexpr const bool shuffle_3 = true;
const auto rate_0 = [](weight& value) { value = 0.1 * value; };
const auto rate_1 = [](weight& value) { value = 0.1 * value; };
const auto rate_2 = [](weight& value) { value = 1.0 * value; };
const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };
const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };
const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };
#ifdef THIRD_CRBM_MP_2
const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#else
const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#endif
const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 1.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };
} // end of namespace third
#endif
<commit_msg>Switch to PAR values<commit_after>//=======================================================================
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP
namespace third {
//#define THIRD_RBM_1 //One layer of RBM
//#define THIRD_RBM_2 //Two layers of RBM
//#define THIRD_RBM_3 //Three layers of RBM
//#define THIRD_CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1)
#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)
//#define THIRD_CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1)
//#define THIRD_CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)
//#define THIRD_COMPLEX_2 //Architecture to play around LCN
//#define THIRD_MODERN //Architecture to play around
constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width = 20;
// Data augmentation
constexpr const std::size_t elastic_augment = 1; //not ready
constexpr const std::size_t epochs = 10;
constexpr const std::size_t train_stride = 1;
constexpr const std::size_t test_stride = 1;
constexpr const std::size_t NF1 = 9;
constexpr const std::size_t K1 = 12;
constexpr const std::size_t C1 = 2;
constexpr const std::size_t B1 = 128;
constexpr const dll::unit_type HT1 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;
constexpr const bool shuffle_1 = false;
constexpr const std::size_t NF2 = 3;
constexpr const std::size_t K2 = 12;
constexpr const std::size_t C2 = 2;
constexpr const std::size_t B2 = 128;
constexpr const dll::unit_type HT2 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;
constexpr const bool shuffle_2 = false;
constexpr const std::size_t NF3 = 3;
constexpr const std::size_t K3 = 48;
constexpr const std::size_t C3 = 2;
constexpr const std::size_t B3 = 64;
constexpr const dll::unit_type HT3 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;
constexpr const bool shuffle_3 = true;
const auto rate_0 = [](weight& value) { value = 0.1 * value; };
const auto rate_1 = [](weight& value) { value = 0.1 * value; };
const auto rate_2 = [](weight& value) { value = 1.0 * value; };
const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };
const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };
const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };
#ifdef THIRD_CRBM_MP_2
const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#else
const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#endif
const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 1.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };
} // end of namespace third
#endif
<|endoftext|> |
<commit_before>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include <AnalogOutput.h>
#include <AnalogPotentiometer.h>
#include <Timer.h>
#include "TestBench.h"
#include "gtest/gtest.h"
static const double kScale = 270.0;
static const double kVoltage = 3.33;
static const double kAngle = 180.0;
class AnalogPotentiometerTest : public testing::Test {
protected:
AnalogOutput *m_fakePot;
AnalogPotentiometer *m_pot;
virtual void SetUp() override {
m_fakePot = new AnalogOutput(TestBench::kAnalogOutputChannel);
m_pot =
new AnalogPotentiometer(TestBench::kFakeAnalogOutputChannel, kScale);
}
virtual void TearDown() override {
delete m_fakePot;
delete m_pot;
}
};
TEST_F(AnalogPotentiometerTest, TestInitialSettings) {
m_fakePot->SetVoltage(0.0);
Wait(0.1);
EXPECT_NEAR(0.0, m_pot->Get(), 5.0)
<< "The potentiometer did not initialize to 0.";
}
TEST_F(AnalogPotentiometerTest, TestRangeValues) {
m_fakePot->SetVoltage(kVoltage);
Wait(0.1);
EXPECT_NEAR(kAngle, m_pot->Get(), 2.0)
<< "The potentiometer did not measure the correct angle.";
}
<commit_msg>Make C++ Analog Potentiometer test work.<commit_after>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include <AnalogOutput.h>
#include <AnalogPotentiometer.h>
#include <Timer.h>
#include <ControllerPower.h>
#include "TestBench.h"
#include "gtest/gtest.h"
static const double kScale = 270.0;
static const double kAngle = 180.0;
class AnalogPotentiometerTest : public testing::Test {
protected:
AnalogOutput *m_fakePot;
AnalogPotentiometer *m_pot;
virtual void SetUp() override {
m_fakePot = new AnalogOutput(TestBench::kAnalogOutputChannel);
m_pot =
new AnalogPotentiometer(TestBench::kFakeAnalogOutputChannel, kScale);
}
virtual void TearDown() override {
delete m_fakePot;
delete m_pot;
}
};
TEST_F(AnalogPotentiometerTest, TestInitialSettings) {
m_fakePot->SetVoltage(0.0);
Wait(0.1);
EXPECT_NEAR(0.0, m_pot->Get(), 5.0)
<< "The potentiometer did not initialize to 0.";
}
TEST_F(AnalogPotentiometerTest, TestRangeValues) {
m_fakePot->SetVoltage(kAngle / kScale * ControllerPower::GetVoltage5V());
Wait(0.1);
EXPECT_NEAR(kAngle, m_pot->Get(), 2.0)
<< "The potentiometer did not measure the correct angle.";
}
<|endoftext|> |
<commit_before>#include "meanfield.h"
#include "solvers.h"
double timer;
// Catch errors
static void erfunc(char *err) {
mexErrMsgTxt(err);
}
void mexFunction(int nlhs, /* number of expected outputs */
mxArray *plhs[], /* mxArray output pointer array */
int nrhs, /* number of inputs */
const mxArray *prhs[] /* mxArray input pointer array */)
{
startTime();
// Parsing data from MATLAB
if (nrhs != 4)
mexErrMsgTxt("Expected 3 inputs");
const matrix<unsigned char> im_matrix(prhs[0]);
const matrix<float> unary_matrix(prhs[1]);
const matrix<unsigned int> im_size(prhs[2]);
//Structure to hold and parse additional parameters
MexParams params(1, prhs+3);
// Weights used to define the energy function
PairwiseWeights pairwiseWeights(params);
const bool debug = params.get<bool>("debug", false);
const int iterations = params.get<int>("iterations", 20);
// Used only for TRW-S
const double min_pairwise_cost = params.get<double>("min_pairwise_cost", 0);
string solver = params.get<string>("solver", "Not set");
// The image
const int M = im_size(0);
const int N = im_size(1);
const int C = im_size(2);
const int numVariables = M*N;
// Calculate number of labels
const int UC = unary_matrix.numel();
const int numberOfLabels = UC/(M*N);
// Read image and unary
const unsigned char * image = im_matrix.data;
float * unary_array = unary_matrix.data;
assert(M > 0);
assert(N > 0);
if (solver.compare("mean_field") && solver.compare("trws") && solver.compare("mean_field_explicit")) {
mexErrMsgTxt("Unknown solver");
}
// Oracle function to get cost
LinearIndex unaryLinearIndex(M,N, numberOfLabels);
LinearIndex imageLinearIndex(M,N, C);
Linear2sub linear2sub(M,N);
UnaryCost unaryCost(unary_array, unaryLinearIndex);
if (debug)
{
mexPrintf("min_pairwise_cost: %g \n", min_pairwise_cost);
mexPrintf("Problem size: %d x %d \n", M,N);
endTime("Reading data.");
}
matrix<double> result(M,N);
matrix<double> energy(1);
matrix<double> bound(1);
plhs[0] = result;
plhs[1] = energy;
plhs[2] = bound;
PairwiseCost pairwiseCost(image, pairwiseWeights, imageLinearIndex);
EnergyFunctor energyFunctor(unaryCost, pairwiseCost, M,N, numberOfLabels);
// Mean field
if(!solver.compare("mean_field"))
{
if (debug)
endTime("Solving using mean field approximation and approximate gaussian filters.");
// Setup the CRF model
extendedDenseCRF2D crf(M,N,numberOfLabels);
Map<MatrixXf> unary(unary_array, numberOfLabels, numVariables);
crf.setUnaryEnergy( unary );
KernelType kerneltype = CONST_KERNEL;
NormalizationType normalizationtype = parseNormalizationType(params);
// Setup pairwise cost
crf.addPairwiseGaussian(pairwiseWeights.gaussian_x_stddev,
pairwiseWeights.gaussian_y_stddev,
new PottsCompatibility(pairwiseWeights.gaussian_weight),
kerneltype,
normalizationtype);
crf.addPairwiseBilateral(pairwiseWeights.bilateral_x_stddev,
pairwiseWeights.bilateral_y_stddev,
pairwiseWeights.bilateral_r_stddev,
pairwiseWeights.bilateral_g_stddev,
pairwiseWeights.bilateral_b_stddev,
image,
new PottsCompatibility(pairwiseWeights.bilateral_weight),
kerneltype,
normalizationtype);
// Do map inference
VectorXs map = crf.map(iterations);
//Packing data in the same way as input
for (int i = 0; i < numVariables; i++ ) {
result(i) = (double)map[i];
}
energy(0) = crf.energy(map);
bound(0) = lowestUnaryCost( unary_array, M,N,numberOfLabels );
return;
}
if(!solver.compare("mean_field_explicit"))
{
if (debug)
endTime("Solving using mean field approximation by explicit summation");
// Init
matrix<double> Q(M,N,numberOfLabels);
matrix<double> addative_sum(M,N,numberOfLabels);
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
for (int l = 0; l < numberOfLabels; l++) {
Q(x,y,l) = exp(-unaryCost(x,y,l));
}}}
normalize(Q);
for (int i = 0; i < iterations; i++)
{
// Pairwise count negative when equal (faster)
for (int label = 0; label < numberOfLabels; label++) {
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
addative_sum(x,y,label) = unaryCost(x,y,label);
for (int x_target = 0; x_target < M; x_target++) {
for (int y_target = 0; y_target < N; y_target++) {
addative_sum(x,y,label) -=
pairwiseCost(x, y, x_target, y_target)*
Q( x_target, y_target, label );
}
}
}
}
}
for (int i = 0; i < Q.numel(); i++)
Q(i) = exp( - addative_sum(i) );
normalize(Q);
}
matrix<double> result(M,N);
matrix<double> energy(1);
matrix<double> bound(1);
double max_prob;
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
max_prob = Q(x,y,0);
result(x,y) = 0;
for (int l = 1; l < numberOfLabels; l++)
{
if (Q(x,y,l) > max_prob)
{
max_prob = Q(x,y,l);
result(x,y) = l;
}
}
}
}
energy(0) = std::numeric_limits<double>::quiet_NaN();
bound(0) = std::numeric_limits<double>::quiet_NaN();
plhs[0] = result;
plhs[1] = energy;
plhs[2] = bound;
return;
}
if(!solver.compare("trws"))
{
if (debug)
endTime("Convergent Tree-reweighted Message Passing");
TypePotts::REAL TRWSenergy, TRWSlb;
TRWSOptions options;
options.m_iterMax = iterations;
options.m_eps = 0;
if (!debug)
options.m_printMinIter = iterations+2;
TRWS * mrf = new TRWS(TypePotts::GlobalSize(numberOfLabels),erfunc);
TRWSNodes * nodes = new TRWSNodes[numVariables];
std::vector<TypePotts::REAL> D(numberOfLabels);
for (int i = 0; i < numVariables; i++)
{
for(int s = 0; s < numberOfLabels; ++s)
{
std::pair<int,int> p = linear2sub(i);
D[s] = unaryCost( p, s );
}
nodes[i] = mrf->AddNode(TypePotts::LocalSize(),
TypePotts::NodeData(&D[0]));
}
// Pairwise cost
for (int i = 0; i < numVariables; i++) {
for (int j = i+1; j < numVariables; j++) {
std::pair<int,int> p0 = linear2sub(i);
std::pair<int,int> p1 = linear2sub(j);
double pcost = pairwiseCost( p0, p1 );
if (pcost >= min_pairwise_cost)
mrf->AddEdge(nodes[i], nodes[j], TypePotts::EdgeData(pcost));
}
}
mrf->Minimize_TRW_S(options, TRWSlb, TRWSenergy);
for (int i = 0; i < numVariables; i++)
result(i) = mrf->GetSolution(nodes[i]);
energy(0) = TRWSenergy;
bound(0) = TRWSlb;
delete mrf;
delete nodes;
return;
}
}<commit_msg>Removing unnecessary code<commit_after>#include "meanfield.h"
#include "solvers.h"
double timer;
// Catch errors
static void erfunc(char *err) {
mexErrMsgTxt(err);
}
void mexFunction(int nlhs, /* number of expected outputs */
mxArray *plhs[], /* mxArray output pointer array */
int nrhs, /* number of inputs */
const mxArray *prhs[] /* mxArray input pointer array */)
{
startTime();
// Parsing data from MATLAB
if (nrhs != 4)
mexErrMsgTxt("Expected 3 inputs");
const matrix<unsigned char> im_matrix(prhs[0]);
const matrix<float> unary_matrix(prhs[1]);
const matrix<unsigned int> im_size(prhs[2]);
//Structure to hold and parse additional parameters
MexParams params(1, prhs+3);
// Weights used to define the energy function
PairwiseWeights pairwiseWeights(params);
const bool debug = params.get<bool>("debug", false);
const int iterations = params.get<int>("iterations", 20);
// Used only for TRW-S
const double min_pairwise_cost = params.get<double>("min_pairwise_cost", 0);
string solver = params.get<string>("solver", "Not set");
// The image
const int M = im_size(0);
const int N = im_size(1);
const int C = im_size(2);
const int numVariables = M*N;
// Calculate number of labels
const int UC = unary_matrix.numel();
const int numberOfLabels = UC/(M*N);
// Read image and unary
const unsigned char * image = im_matrix.data;
float * unary_array = unary_matrix.data;
assert(M > 0);
assert(N > 0);
if (solver.compare("mean_field") && solver.compare("trws") && solver.compare("mean_field_explicit")) {
mexErrMsgTxt("Unknown solver");
}
// Oracle function to get cost
LinearIndex unaryLinearIndex(M,N, numberOfLabels);
LinearIndex imageLinearIndex(M,N, C);
Linear2sub linear2sub(M,N);
UnaryCost unaryCost(unary_array, unaryLinearIndex);
if (debug)
{
mexPrintf("min_pairwise_cost: %g \n", min_pairwise_cost);
mexPrintf("Problem size: %d x %d \n", M,N);
endTime("Reading data.");
}
matrix<double> result(M,N);
matrix<double> energy(1);
matrix<double> bound(1);
plhs[0] = result;
plhs[1] = energy;
plhs[2] = bound;
PairwiseCost pairwiseCost(image, pairwiseWeights, imageLinearIndex);
EnergyFunctor energyFunctor(unaryCost, pairwiseCost, M,N, numberOfLabels);
// Mean field
if(!solver.compare("mean_field"))
{
if (debug)
endTime("Solving using mean field approximation and approximate gaussian filters.");
// Setup the CRF model
extendedDenseCRF2D crf(M,N,numberOfLabels);
Map<MatrixXf> unary(unary_array, numberOfLabels, numVariables);
crf.setUnaryEnergy( unary );
KernelType kerneltype = CONST_KERNEL;
NormalizationType normalizationtype = parseNormalizationType(params);
// Setup pairwise cost
crf.addPairwiseGaussian(pairwiseWeights.gaussian_x_stddev,
pairwiseWeights.gaussian_y_stddev,
new PottsCompatibility(pairwiseWeights.gaussian_weight),
kerneltype,
normalizationtype);
crf.addPairwiseBilateral(pairwiseWeights.bilateral_x_stddev,
pairwiseWeights.bilateral_y_stddev,
pairwiseWeights.bilateral_r_stddev,
pairwiseWeights.bilateral_g_stddev,
pairwiseWeights.bilateral_b_stddev,
image,
new PottsCompatibility(pairwiseWeights.bilateral_weight),
kerneltype,
normalizationtype);
// Do map inference
VectorXs map = crf.map(iterations);
//Packing data in the same way as input
for (int i = 0; i < numVariables; i++ ) {
result(i) = (double)map[i];
}
energy(0) = crf.energy(map);
bound(0) = lowestUnaryCost( unary_array, M,N,numberOfLabels );
return;
}
if(!solver.compare("mean_field_explicit"))
{
if (debug)
endTime("Solving using mean field approximation by explicit summation");
// Init
matrix<double> Q(M,N,numberOfLabels);
matrix<double> addative_sum(M,N,numberOfLabels);
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
for (int l = 0; l < numberOfLabels; l++) {
Q(x,y,l) = exp(-unaryCost(x,y,l));
}}}
normalize(Q);
for (int i = 0; i < iterations; i++)
{
// Pairwise count negative when equal (faster)
for (int label = 0; label < numberOfLabels; label++) {
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
addative_sum(x,y,label) = unaryCost(x,y,label);
for (int x_target = 0; x_target < M; x_target++) {
for (int y_target = 0; y_target < N; y_target++) {
addative_sum(x,y,label) -=
pairwiseCost(x, y, x_target, y_target)*
Q( x_target, y_target, label );
}
}
}
}
}
for (int i = 0; i < Q.numel(); i++)
Q(i) = exp( - addative_sum(i) );
normalize(Q);
}
matrix<double> result(M,N);
matrix<double> energy(1);
matrix<double> bound(1);
double max_prob;
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
max_prob = Q(x,y,0);
result(x,y) = 0;
for (int l = 1; l < numberOfLabels; l++)
{
if (Q(x,y,l) > max_prob)
{
max_prob = Q(x,y,l);
result(x,y) = l;
}
}
}
}
energy(0) = std::numeric_limits<double>::quiet_NaN();
bound(0) = std::numeric_limits<double>::quiet_NaN();
return;
}
if(!solver.compare("trws"))
{
if (debug)
endTime("Convergent Tree-reweighted Message Passing");
TypePotts::REAL TRWSenergy, TRWSlb;
TRWSOptions options;
options.m_iterMax = iterations;
options.m_eps = 0;
if (!debug)
options.m_printMinIter = iterations+2;
TRWS * mrf = new TRWS(TypePotts::GlobalSize(numberOfLabels),erfunc);
TRWSNodes * nodes = new TRWSNodes[numVariables];
std::vector<TypePotts::REAL> D(numberOfLabels);
for (int i = 0; i < numVariables; i++)
{
for(int s = 0; s < numberOfLabels; ++s)
{
std::pair<int,int> p = linear2sub(i);
D[s] = unaryCost( p, s );
}
nodes[i] = mrf->AddNode(TypePotts::LocalSize(),
TypePotts::NodeData(&D[0]));
}
// Pairwise cost
for (int i = 0; i < numVariables; i++) {
for (int j = i+1; j < numVariables; j++) {
std::pair<int,int> p0 = linear2sub(i);
std::pair<int,int> p1 = linear2sub(j);
double pcost = pairwiseCost( p0, p1 );
if (pcost >= min_pairwise_cost)
mrf->AddEdge(nodes[i], nodes[j], TypePotts::EdgeData(pcost));
}
}
mrf->Minimize_TRW_S(options, TRWSlb, TRWSenergy);
for (int i = 0; i < numVariables; i++)
result(i) = mrf->GetSolution(nodes[i]);
energy(0) = TRWSenergy;
bound(0) = TRWSlb;
delete mrf;
delete nodes;
return;
}
}<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/BrokerUrl.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/MessagingSettings.h"
#include "joynr/Future.h"
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/Semaphore.h"
#include "joynr/Settings.h"
#include "joynr/types/DiscoveryScope.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/vehicle/GpsProxy.h"
#include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockGpsProvider.h"
#include "tests/utils/PtrUtils.h"
#include "tests/utils/TestLibJoynrWebSocketRuntime.h"
using namespace ::testing;
using namespace joynr;
class End2EndProxyBuilderRobustnessTest : public Test {
public:
End2EndProxyBuilderRobustnessTest() :
domain("cppEnd2EndProxyBuilderRobustnessTest" + util::createUuid()),
discoveryTimeoutMs(5000),
retryIntervalMs(500),
consumerRuntime(),
providerRuntime(),
ccRuntime(),
discoveryQos()
{
auto settings = std::make_unique<Settings>();
consumerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));
settings = std::make_unique<Settings>();
providerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));
settings = std::make_unique<Settings>();
MessagingSettings ccSettings(*settings);
// use wrong broker-url to prevent global communication
BrokerUrl brokerUrl("mqtt://localhost:12347");
ccSettings.setBrokerUrl(brokerUrl);
ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings));
ccRuntime->init();
ccRuntime->start();
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(discoveryTimeoutMs);
discoveryQos.setCacheMaxAgeMs(discoveryTimeoutMs);
}
// Sets up the test fixture.
void SetUp() override
{
ASSERT_TRUE(consumerRuntime->connect(std::chrono::milliseconds(10000)));
ASSERT_TRUE(providerRuntime->connect(std::chrono::milliseconds(10000)));
}
~End2EndProxyBuilderRobustnessTest() override {
ccRuntime->shutdown();
consumerRuntime->shutdown();
providerRuntime->shutdown();
test::util::resetAndWaitUntilDestroyed(ccRuntime);
test::util::resetAndWaitUntilDestroyed(consumerRuntime);
test::util::resetAndWaitUntilDestroyed(providerRuntime);
// Delete persisted files
test::util::removeAllCreatedSettingsAndPersistencyFiles();
std::this_thread::sleep_for(std::chrono::milliseconds(550));
}
protected:
std::string domain;
const std::int64_t discoveryTimeoutMs;
const std::int64_t retryIntervalMs;
std::shared_ptr<TestLibJoynrWebSocketRuntime> consumerRuntime;
std::shared_ptr<TestLibJoynrWebSocketRuntime> providerRuntime;
std::shared_ptr<JoynrClusterControllerRuntime> ccRuntime;
joynr::DiscoveryQos discoveryQos;
void buildProxyBeforeProviderRegistration(const bool expectSuccess);
private:
DISALLOW_COPY_AND_ASSIGN(End2EndProxyBuilderRobustnessTest);
};
void End2EndProxyBuilderRobustnessTest::buildProxyBeforeProviderRegistration(const bool expectSuccess)
{
Semaphore semaphore(0);
// prepare provider
auto mockProvider = std::make_shared<MockGpsProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
// build proxy
std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);
auto onSuccess = [&semaphore, expectSuccess](std::shared_ptr<vehicle::GpsProxy> gpsProxy) {
if (!expectSuccess) {
ADD_FAILURE() << "proxy building succeeded unexpectedly";
semaphore.notify();
return;
}
// call proxy method
auto calculateOnSuccess = [&semaphore](int value) {
const int expectedValue = 42; // as defined in MockGpsProvider
EXPECT_EQ(expectedValue, value);
semaphore.notify();
};
gpsProxy->calculateAvailableSatellitesAsync(calculateOnSuccess);
};
auto onError = [&semaphore, expectSuccess] (const exceptions::DiscoveryException& exception) {
if (expectSuccess) {
ADD_FAILURE() << "proxy building failed unexpectedly, exception: " << exception.getMessage();
}
semaphore.notify();
};
std::int64_t qosRoundTripTTL = 10000;
gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->buildAsync(onSuccess, onError);
// wait some time so that the lookup request is likely to be processed at the cluster controller
// and make sure that no retry attempt has been started
std::this_thread::sleep_for(std::chrono::milliseconds(retryIntervalMs / 2));
// register provider
std::string participantId = providerRuntime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(qosRoundTripTTL + discoveryTimeoutMs)));
// unregister provider
providerRuntime->unregisterProvider(participantId);
}
// as soon as the provider gets registered, the lookup returns successful
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithoutRetry)
{
const bool expectedSuccess = true;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithRetry)
{
const bool expectedSuccess = true;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithoutRetry)
{
const bool expectedSuccess = false;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithRetry)
{
const bool expectedSuccess = false;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalOnly_failsWithoutRetry)
{
const bool expectedSuccess = false;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_LocalOnly_succeedsWithRetry)
{
const bool expectedSuccess = true;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_GlobalOnly_failsWithoutRetry)
{
const bool expectedSuccess = false;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest, buildProxyBeforeProviderRegistration_GlobalOnly_failsWithRetry)
{
const bool expectedSuccess = false;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
class End2EndProxyBuild : public End2EndProxyBuilderRobustnessTest {
protected:
void SetUp() override {
End2EndProxyBuilderRobustnessTest::SetUp();
auto mockProvider = std::make_shared<MockGpsProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerParticipantId = providerRuntime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
gpsProxyBuilder = consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);
}
void TearDown() override {
providerRuntime->unregisterProvider(providerParticipantId);
}
std::string providerParticipantId;
std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder;
};
TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQos) {
std::shared_ptr<vehicle::GpsProxy> gpsProxy;
JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->setDiscoveryQos(discoveryQos)
->build());
ASSERT_TRUE(gpsProxy);
}
TEST_F(End2EndProxyBuild, buildProxyWithoutSetDiscoveryQos) {
const std::int64_t qosRoundTripTTL = 10000;
std::shared_ptr<vehicle::GpsProxy> gpsProxy;
JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))
->build());
ASSERT_TRUE(gpsProxy);
}
TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQosAndWithoutSetDiscoveryQos) {
std::shared_ptr<vehicle::GpsProxy> gpsProxy;
JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->build());
ASSERT_TRUE(gpsProxy);
}
<commit_msg>[C++] format End2EndProxyBuilderRobustnessTest.cpp<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/BrokerUrl.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/MessagingSettings.h"
#include "joynr/Future.h"
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/Semaphore.h"
#include "joynr/Settings.h"
#include "joynr/types/DiscoveryScope.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/vehicle/GpsProxy.h"
#include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockGpsProvider.h"
#include "tests/utils/PtrUtils.h"
#include "tests/utils/TestLibJoynrWebSocketRuntime.h"
using namespace ::testing;
using namespace joynr;
class End2EndProxyBuilderRobustnessTest : public Test
{
public:
End2EndProxyBuilderRobustnessTest()
: domain("cppEnd2EndProxyBuilderRobustnessTest" + util::createUuid()),
discoveryTimeoutMs(5000),
retryIntervalMs(500),
consumerRuntime(),
providerRuntime(),
ccRuntime(),
discoveryQos()
{
auto settings = std::make_unique<Settings>();
consumerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));
settings = std::make_unique<Settings>();
providerRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(settings));
settings = std::make_unique<Settings>();
MessagingSettings ccSettings(*settings);
// use wrong broker-url to prevent global communication
BrokerUrl brokerUrl("mqtt://localhost:12347");
ccSettings.setBrokerUrl(brokerUrl);
ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings));
ccRuntime->init();
ccRuntime->start();
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(discoveryTimeoutMs);
discoveryQos.setCacheMaxAgeMs(discoveryTimeoutMs);
}
// Sets up the test fixture.
void SetUp() override
{
ASSERT_TRUE(consumerRuntime->connect(std::chrono::milliseconds(10000)));
ASSERT_TRUE(providerRuntime->connect(std::chrono::milliseconds(10000)));
}
~End2EndProxyBuilderRobustnessTest() override
{
ccRuntime->shutdown();
consumerRuntime->shutdown();
providerRuntime->shutdown();
test::util::resetAndWaitUntilDestroyed(ccRuntime);
test::util::resetAndWaitUntilDestroyed(consumerRuntime);
test::util::resetAndWaitUntilDestroyed(providerRuntime);
// Delete persisted files
test::util::removeAllCreatedSettingsAndPersistencyFiles();
std::this_thread::sleep_for(std::chrono::milliseconds(550));
}
protected:
std::string domain;
const std::int64_t discoveryTimeoutMs;
const std::int64_t retryIntervalMs;
std::shared_ptr<TestLibJoynrWebSocketRuntime> consumerRuntime;
std::shared_ptr<TestLibJoynrWebSocketRuntime> providerRuntime;
std::shared_ptr<JoynrClusterControllerRuntime> ccRuntime;
joynr::DiscoveryQos discoveryQos;
void buildProxyBeforeProviderRegistration(const bool expectSuccess);
private:
DISALLOW_COPY_AND_ASSIGN(End2EndProxyBuilderRobustnessTest);
};
void End2EndProxyBuilderRobustnessTest::buildProxyBeforeProviderRegistration(
const bool expectSuccess)
{
Semaphore semaphore(0);
// prepare provider
auto mockProvider = std::make_shared<MockGpsProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
// build proxy
std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);
auto onSuccess = [&semaphore, expectSuccess](std::shared_ptr<vehicle::GpsProxy> gpsProxy) {
if (!expectSuccess) {
ADD_FAILURE() << "proxy building succeeded unexpectedly";
semaphore.notify();
return;
}
// call proxy method
auto calculateOnSuccess = [&semaphore](int value) {
const int expectedValue = 42; // as defined in MockGpsProvider
EXPECT_EQ(expectedValue, value);
semaphore.notify();
};
gpsProxy->calculateAvailableSatellitesAsync(calculateOnSuccess);
};
auto onError = [&semaphore, expectSuccess](const exceptions::DiscoveryException& exception) {
if (expectSuccess) {
ADD_FAILURE() << "proxy building failed unexpectedly, exception: "
<< exception.getMessage();
}
semaphore.notify();
};
std::int64_t qosRoundTripTTL = 10000;
gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->buildAsync(onSuccess, onError);
// wait some time so that the lookup request is likely to be processed at the cluster controller
// and make sure that no retry attempt has been started
std::this_thread::sleep_for(std::chrono::milliseconds(retryIntervalMs / 2));
// register provider
std::string participantId = providerRuntime->registerProvider<vehicle::GpsProvider>(
domain, mockProvider, providerQos);
EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(qosRoundTripTTL + discoveryTimeoutMs)));
// unregister provider
providerRuntime->unregisterProvider(participantId);
}
// as soon as the provider gets registered, the lookup returns successful
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithoutRetry)
{
const bool expectedSuccess = true;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_LocalThenGlobal_succeedsWithRetry)
{
const bool expectedSuccess = true;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_THEN_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithoutRetry)
{
const bool expectedSuccess = false;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_LocalAndGlobal_failsWithRetry)
{
const bool expectedSuccess = false;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_AND_GLOBAL);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_LocalOnly_failsWithoutRetry)
{
const bool expectedSuccess = false;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_LocalOnly_succeedsWithRetry)
{
const bool expectedSuccess = true;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_GlobalOnly_failsWithoutRetry)
{
const bool expectedSuccess = false;
// disable retries for provider lookup
discoveryQos.setRetryIntervalMs(discoveryTimeoutMs * 2);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
// no retry until global lookup succeeds or times out
TEST_F(End2EndProxyBuilderRobustnessTest,
buildProxyBeforeProviderRegistration_GlobalOnly_failsWithRetry)
{
const bool expectedSuccess = false;
discoveryQos.setRetryIntervalMs(retryIntervalMs);
discoveryQos.setDiscoveryScope(types::DiscoveryScope::GLOBAL_ONLY);
buildProxyBeforeProviderRegistration(expectedSuccess);
}
class End2EndProxyBuild : public End2EndProxyBuilderRobustnessTest
{
protected:
void SetUp() override
{
End2EndProxyBuilderRobustnessTest::SetUp();
auto mockProvider = std::make_shared<MockGpsProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerParticipantId = providerRuntime->registerProvider<vehicle::GpsProvider>(
domain, mockProvider, providerQos);
gpsProxyBuilder = consumerRuntime->createProxyBuilder<vehicle::GpsProxy>(domain);
}
void TearDown() override
{
providerRuntime->unregisterProvider(providerParticipantId);
}
std::string providerParticipantId;
std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder;
};
TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQos)
{
std::shared_ptr<vehicle::GpsProxy> gpsProxy;
JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->setDiscoveryQos(discoveryQos)->build());
ASSERT_TRUE(gpsProxy);
}
TEST_F(End2EndProxyBuild, buildProxyWithoutSetDiscoveryQos)
{
const std::int64_t qosRoundTripTTL = 10000;
std::shared_ptr<vehicle::GpsProxy> gpsProxy;
JOYNR_EXPECT_NO_THROW(
gpsProxy = gpsProxyBuilder->setMessagingQos(MessagingQos(qosRoundTripTTL))->build());
ASSERT_TRUE(gpsProxy);
}
TEST_F(End2EndProxyBuild, buildProxyWithoutSetMessagingQosAndWithoutSetDiscoveryQos)
{
std::shared_ptr<vehicle::GpsProxy> gpsProxy;
JOYNR_EXPECT_NO_THROW(gpsProxy = gpsProxyBuilder->build());
ASSERT_TRUE(gpsProxy);
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include "I2PEndian.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <cryptopp/sha.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "base64.h"
#include "Timestamp.h"
#include "Log.h"
#include "RouterInfo.h"
#include "RouterContext.h"
namespace i2p
{
namespace data
{
RouterInfo::RouterInfo (const char * filename):
m_IsUpdated (false), m_IsUnreachable (false)
{
ReadFromFile (filename);
}
RouterInfo::RouterInfo (const uint8_t * buf, int len):
m_IsUpdated (true)
{
memcpy (m_Buffer, buf, len);
m_BufferLen = len;
ReadFromBuffer ();
}
void RouterInfo::SetRouterIdentity (const Identity& identity)
{
m_RouterIdentity = identity;
m_IdentHash = CalculateIdentHash (m_RouterIdentity);
UpdateIdentHashBase64 ();
UpdateRoutingKey ();
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch ();
}
void RouterInfo::ReadFromFile (const char * filename)
{
std::ifstream s(filename, std::ifstream::binary);
if (s.is_open ())
{
s.seekg (0,std::ios::end);
m_BufferLen = s.tellg ();
s.seekg(0, std::ios::beg);
s.read(m_Buffer,m_BufferLen);
ReadFromBuffer ();
}
else
LogPrint ("Can't open file ", filename);
}
void RouterInfo::ReadFromBuffer ()
{
std::stringstream str (std::string (m_Buffer, m_BufferLen));
ReadFromStream (str);
// verify signature
CryptoPP::DSA::PublicKey pubKey;
pubKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag, CryptoPP::Integer (m_RouterIdentity.signingKey, 128));
CryptoPP::DSA::Verifier verifier (pubKey);
int l = m_BufferLen - 40;
if (!verifier.VerifyMessage ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l, 40))
{
LogPrint ("signature verification failed");
}
}
void RouterInfo::ReadFromStream (std::istream& s)
{
s.read ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
s.read ((char *)&m_Timestamp, sizeof (m_Timestamp));
m_Timestamp = be64toh (m_Timestamp);
// read addresses
uint8_t numAddresses;
s.read ((char *)&numAddresses, sizeof (numAddresses));
for (int i = 0; i < numAddresses; i++)
{
Address address;
s.read ((char *)&address.cost, sizeof (address.cost));
s.read ((char *)&address.date, sizeof (address.date));
char transportStyle[5];
ReadString (transportStyle, s);
if (!strcmp (transportStyle, "NTCP"))
address.transportStyle = eTransportNTCP;
else if (!strcmp (transportStyle, "SSU"))
address.transportStyle = eTransportSSU;
else
address.transportStyle = eTransportUnknown;
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size));
size = be16toh (size);
while (r < size)
{
char key[500], value[500];
r += ReadString (key, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, s);
s.seekg (1, std::ios_base::cur); r++; // ;
if (!strcmp (key, "host"))
{
boost::system::error_code ecode;
address.host = boost::asio::ip::address::from_string (value, ecode);
if (ecode)
{
// TODO: we should try to resolve address here
LogPrint ("Unexpected address ", value);
SetUnreachable (true);
}
}
else if (!strcmp (key, "port"))
address.port = boost::lexical_cast<int>(value);
}
m_Addresses.push_back(address);
}
// read peers
uint8_t numPeers;
s.read ((char *)&numPeers, sizeof (numPeers));
s.seekg (numPeers*32, std::ios_base::cur); // TODO: read peers
// read properties
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size));
size = be16toh (size);
while (r < size)
{
char key[500], value[500];
r += ReadString (key, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, s);
s.seekg (1, std::ios_base::cur); r++; // ;
m_Properties[key] = value;
}
CryptoPP::SHA256().CalculateDigest(m_IdentHash, (uint8_t *)&m_RouterIdentity, sizeof (m_RouterIdentity));
UpdateIdentHashBase64 ();
UpdateRoutingKey ();
}
void RouterInfo::UpdateIdentHashBase64 ()
{
size_t l = i2p::data::ByteStreamToBase64 (m_IdentHash, 32, m_IdentHashBase64, 48);
m_IdentHashBase64[l] = 0;
memcpy (m_IdentHashAbbreviation, m_IdentHashBase64, 4);
m_IdentHashAbbreviation[4] = 0;
}
void RouterInfo::UpdateRoutingKey ()
{
m_RoutingKey = CreateRoutingKey (m_IdentHash);
}
void RouterInfo::WriteToStream (std::ostream& s)
{
s.write ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
uint64_t ts = htobe64 (m_Timestamp);
s.write ((char *)&ts, sizeof (ts));
// addresses
uint8_t numAddresses = m_Addresses.size ();
s.write ((char *)&numAddresses, sizeof (numAddresses));
for (auto& address : m_Addresses)
{
s.write ((char *)&address.cost, sizeof (address.cost));
s.write ((char *)&address.date, sizeof (address.date));
if (address.transportStyle == eTransportNTCP)
WriteString ("NTCP", s);
else if (address.transportStyle == eTransportSSU)
WriteString ("SSU", s);
else
WriteString ("", s);
std::stringstream properties;
WriteString ("host", properties);
properties << '=';
WriteString (address.host.to_string (), properties);
properties << ';';
WriteString ("port", properties);
properties << '=';
WriteString (boost::lexical_cast<std::string>(address.port), properties);
properties << ';';
uint16_t size = htobe16 (properties.str ().size ());
s.write ((char *)&size, sizeof (size));
s.write (properties.str ().c_str (), properties.str ().size ());
}
// peers
uint8_t numPeers = 0;
s.write ((char *)&numPeers, sizeof (numPeers));
// properties
std::stringstream properties;
for (auto& p : m_Properties)
{
WriteString (p.first, properties);
properties << '=';
WriteString (p.second, properties);
properties << ';';
}
uint16_t size = htobe16 (properties.str ().size ());
s.write ((char *)&size, sizeof (size));
s.write (properties.str ().c_str (), properties.str ().size ());
}
void RouterInfo::CreateBuffer ()
{
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch (); // refresh timstamp
std::stringstream s;
WriteToStream (s);
m_BufferLen = s.str ().size ();
memcpy (m_Buffer, s.str ().c_str (), m_BufferLen);
// signature
i2p::context.Sign ((uint8_t *)m_Buffer, m_BufferLen, (uint8_t *)m_Buffer + m_BufferLen);
m_BufferLen += 40;
}
size_t RouterInfo::ReadString (char * str, std::istream& s)
{
uint8_t len;
s.read ((char *)&len, 1);
s.read (str, len);
str[len] = 0;
return len+1;
}
void RouterInfo::WriteString (const std::string& str, std::ostream& s)
{
uint8_t len = str.size ();
s.write ((char *)&len, 1);
s.write (str.c_str (), len);
}
void RouterInfo::AddNTCPAddress (const char * host, int port)
{
Address addr;
addr.host = boost::asio::ip::address::from_string (host);
addr.port = port;
addr.transportStyle = eTransportNTCP;
addr.cost = 2;
addr.date = 0;
m_Addresses.push_back(addr);
}
void RouterInfo::SetProperty (const char * key, const char * value)
{
m_Properties[key] = value;
}
const char * RouterInfo::GetProperty (const char * key) const
{
auto it = m_Properties.find (key);
if (it != m_Properties.end ())
return it->second.c_str ();
return 0;
}
bool RouterInfo::IsFloodfill () const
{
const char * caps = GetProperty ("caps");
if (caps)
return strchr (caps, 'f');
return false;
}
bool RouterInfo::IsNTCP (bool v4only) const
{
for (auto& address : m_Addresses)
{
if (address.transportStyle == eTransportNTCP)
{
if (!v4only || address.host.is_v4 ())
return true;
}
}
return false;
}
RouterInfo::Address * RouterInfo::GetNTCPAddress (bool v4only)
{
for (auto& address : m_Addresses)
{
if (address.transportStyle == eTransportNTCP)
{
if (!v4only || address.host.is_v4 ())
return &address;
}
}
return nullptr;
}
}
}
<commit_msg>bigger buffer size temporary for win32<commit_after>#include <stdio.h>
#include <string.h>
#include "I2PEndian.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <cryptopp/sha.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "base64.h"
#include "Timestamp.h"
#include "Log.h"
#include "RouterInfo.h"
#include "RouterContext.h"
namespace i2p
{
namespace data
{
RouterInfo::RouterInfo (const char * filename):
m_IsUpdated (false), m_IsUnreachable (false)
{
ReadFromFile (filename);
}
RouterInfo::RouterInfo (const uint8_t * buf, int len):
m_IsUpdated (true)
{
memcpy (m_Buffer, buf, len);
m_BufferLen = len;
ReadFromBuffer ();
}
void RouterInfo::SetRouterIdentity (const Identity& identity)
{
m_RouterIdentity = identity;
m_IdentHash = CalculateIdentHash (m_RouterIdentity);
UpdateIdentHashBase64 ();
UpdateRoutingKey ();
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch ();
}
void RouterInfo::ReadFromFile (const char * filename)
{
std::ifstream s(filename, std::ifstream::binary);
if (s.is_open ())
{
s.seekg (0,std::ios::end);
m_BufferLen = s.tellg ();
s.seekg(0, std::ios::beg);
s.read(m_Buffer,m_BufferLen);
ReadFromBuffer ();
}
else
LogPrint ("Can't open file ", filename);
}
void RouterInfo::ReadFromBuffer ()
{
std::stringstream str (std::string (m_Buffer, m_BufferLen));
ReadFromStream (str);
// verify signature
CryptoPP::DSA::PublicKey pubKey;
pubKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag, CryptoPP::Integer (m_RouterIdentity.signingKey, 128));
CryptoPP::DSA::Verifier verifier (pubKey);
int l = m_BufferLen - 40;
if (!verifier.VerifyMessage ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l, 40))
{
LogPrint ("signature verification failed");
}
}
void RouterInfo::ReadFromStream (std::istream& s)
{
s.read ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
s.read ((char *)&m_Timestamp, sizeof (m_Timestamp));
m_Timestamp = be64toh (m_Timestamp);
// read addresses
uint8_t numAddresses;
s.read ((char *)&numAddresses, sizeof (numAddresses));
for (int i = 0; i < numAddresses; i++)
{
Address address;
s.read ((char *)&address.cost, sizeof (address.cost));
s.read ((char *)&address.date, sizeof (address.date));
char transportStyle[5];
ReadString (transportStyle, s);
if (!strcmp (transportStyle, "NTCP"))
address.transportStyle = eTransportNTCP;
else if (!strcmp (transportStyle, "SSU"))
address.transportStyle = eTransportSSU;
else
address.transportStyle = eTransportUnknown;
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size));
size = be16toh (size);
while (r < size)
{
char key[500], value[500];
r += ReadString (key, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, s);
s.seekg (1, std::ios_base::cur); r++; // ;
if (!strcmp (key, "host"))
{
boost::system::error_code ecode;
address.host = boost::asio::ip::address::from_string (value, ecode);
if (ecode)
{
// TODO: we should try to resolve address here
LogPrint ("Unexpected address ", value);
SetUnreachable (true);
}
}
else if (!strcmp (key, "port"))
address.port = boost::lexical_cast<int>(value);
}
m_Addresses.push_back(address);
}
// read peers
uint8_t numPeers;
s.read ((char *)&numPeers, sizeof (numPeers));
s.seekg (numPeers*32, std::ios_base::cur); // TODO: read peers
// read properties
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size));
size = be16toh (size);
while (r < size)
{
#ifdef _WIN32
char key[500], value[500];
// TODO: investigate why properties get read as one long string under Windows
// length should not be more than 44
#else
char key[50], value[50];
#endif
r += ReadString (key, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, s);
s.seekg (1, std::ios_base::cur); r++; // ;
m_Properties[key] = value;
}
CryptoPP::SHA256().CalculateDigest(m_IdentHash, (uint8_t *)&m_RouterIdentity, sizeof (m_RouterIdentity));
UpdateIdentHashBase64 ();
UpdateRoutingKey ();
}
void RouterInfo::UpdateIdentHashBase64 ()
{
size_t l = i2p::data::ByteStreamToBase64 (m_IdentHash, 32, m_IdentHashBase64, 48);
m_IdentHashBase64[l] = 0;
memcpy (m_IdentHashAbbreviation, m_IdentHashBase64, 4);
m_IdentHashAbbreviation[4] = 0;
}
void RouterInfo::UpdateRoutingKey ()
{
m_RoutingKey = CreateRoutingKey (m_IdentHash);
}
void RouterInfo::WriteToStream (std::ostream& s)
{
s.write ((char *)&m_RouterIdentity, sizeof (m_RouterIdentity));
uint64_t ts = htobe64 (m_Timestamp);
s.write ((char *)&ts, sizeof (ts));
// addresses
uint8_t numAddresses = m_Addresses.size ();
s.write ((char *)&numAddresses, sizeof (numAddresses));
for (auto& address : m_Addresses)
{
s.write ((char *)&address.cost, sizeof (address.cost));
s.write ((char *)&address.date, sizeof (address.date));
if (address.transportStyle == eTransportNTCP)
WriteString ("NTCP", s);
else if (address.transportStyle == eTransportSSU)
WriteString ("SSU", s);
else
WriteString ("", s);
std::stringstream properties;
WriteString ("host", properties);
properties << '=';
WriteString (address.host.to_string (), properties);
properties << ';';
WriteString ("port", properties);
properties << '=';
WriteString (boost::lexical_cast<std::string>(address.port), properties);
properties << ';';
uint16_t size = htobe16 (properties.str ().size ());
s.write ((char *)&size, sizeof (size));
s.write (properties.str ().c_str (), properties.str ().size ());
}
// peers
uint8_t numPeers = 0;
s.write ((char *)&numPeers, sizeof (numPeers));
// properties
std::stringstream properties;
for (auto& p : m_Properties)
{
WriteString (p.first, properties);
properties << '=';
WriteString (p.second, properties);
properties << ';';
}
uint16_t size = htobe16 (properties.str ().size ());
s.write ((char *)&size, sizeof (size));
s.write (properties.str ().c_str (), properties.str ().size ());
}
void RouterInfo::CreateBuffer ()
{
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch (); // refresh timstamp
std::stringstream s;
WriteToStream (s);
m_BufferLen = s.str ().size ();
memcpy (m_Buffer, s.str ().c_str (), m_BufferLen);
// signature
i2p::context.Sign ((uint8_t *)m_Buffer, m_BufferLen, (uint8_t *)m_Buffer + m_BufferLen);
m_BufferLen += 40;
}
size_t RouterInfo::ReadString (char * str, std::istream& s)
{
uint8_t len;
s.read ((char *)&len, 1);
s.read (str, len);
str[len] = 0;
return len+1;
}
void RouterInfo::WriteString (const std::string& str, std::ostream& s)
{
uint8_t len = str.size ();
s.write ((char *)&len, 1);
s.write (str.c_str (), len);
}
void RouterInfo::AddNTCPAddress (const char * host, int port)
{
Address addr;
addr.host = boost::asio::ip::address::from_string (host);
addr.port = port;
addr.transportStyle = eTransportNTCP;
addr.cost = 2;
addr.date = 0;
m_Addresses.push_back(addr);
}
void RouterInfo::SetProperty (const char * key, const char * value)
{
m_Properties[key] = value;
}
const char * RouterInfo::GetProperty (const char * key) const
{
auto it = m_Properties.find (key);
if (it != m_Properties.end ())
return it->second.c_str ();
return 0;
}
bool RouterInfo::IsFloodfill () const
{
const char * caps = GetProperty ("caps");
if (caps)
return strchr (caps, 'f');
return false;
}
bool RouterInfo::IsNTCP (bool v4only) const
{
for (auto& address : m_Addresses)
{
if (address.transportStyle == eTransportNTCP)
{
if (!v4only || address.host.is_v4 ())
return true;
}
}
return false;
}
RouterInfo::Address * RouterInfo::GetNTCPAddress (bool v4only)
{
for (auto& address : m_Addresses)
{
if (address.transportStyle == eTransportNTCP)
{
if (!v4only || address.host.is_v4 ())
return &address;
}
}
return nullptr;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 CNRS
// Authors: Joseph Mirabel
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PATH_SPLINE_HH
# define HPP_CORE_PATH_SPLINE_HH
# include <hpp/core/path.hh>
# include <hpp/pinocchio/device.hh>
# include <hpp/constraints/matrix-view.hh>
# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
namespace hpp {
namespace core {
namespace path {
/// \addtogroup path
/// \{
enum PolynomeBasisType {
CanonicalPolynomeBasis,
BernsteinBasis
};
/// \cond
namespace internal {
template <int SplineType, int Degree> struct spline_basis_function;
template <int SplineType, int Degree> struct sbf_traits {
enum { NbCoeffs = Degree + 1 };
typedef Eigen::Matrix<value_type, NbCoeffs, 1> Coeffs_t;
typedef Eigen::Matrix<value_type, NbCoeffs, NbCoeffs> IntegralCoeffs_t;
};
}
/// \endcond
/// Base class for spline paths
template <int _PolynomeBasis, int _Order>
class HPP_CORE_DLLAPI Spline : public Path
{
public:
enum {
PolynomeBasis = _PolynomeBasis,
Order = _Order,
NbCoeffs = _Order + 1,
NbPowerOfT = 2 * NbCoeffs + 1
};
typedef internal::sbf_traits<PolynomeBasis, Order> sbf_traits;
typedef internal::spline_basis_function<PolynomeBasis, Order> BasisFunction_t;
typedef Eigen::Matrix<value_type, NbPowerOfT, 1> PowersOfT_t;
typedef typename sbf_traits::Coeffs_t BasisFunctionVector_t;
typedef typename sbf_traits::IntegralCoeffs_t BasisFunctionIntegralMatrix_t;
typedef Eigen::Matrix<value_type, NbCoeffs, Eigen::Dynamic, Eigen::RowMajor> ParameterMatrix_t;
typedef Eigen::Map<const vector_t, Eigen::Aligned> ConstParameterVector_t;
typedef Eigen::Map< vector_t, Eigen::Aligned> ParameterVector_t;
typedef boost::shared_ptr<Spline> Ptr_t;
typedef boost::weak_ptr<Spline> WkPtr_t;
size_type parameterSize () const
{
return parameterSize_;
}
/** The partial derivative with respects to the parameters is of the form
/// \f{eqnarray*}{
/// \frac{\partial S}{\partial p_{k}} (q, p, t) &=& B_k(t) \times I \\
/// \frac{\partial S}{\partial q_{base}} (q, p, t) &=& I
/// \f}
/// This method returns the coefficients \f$ (B_k(t))_{k} \f$
**/
void parameterDerivativeCoefficients (vectorOut_t res, const value_type& t) const
{
assert (res.size() == NbCoeffs);
impl_paramDerivative (res, t);
}
void parameterIntegrate (vectorIn_t dParam)
{
assert (dParam.size() == NbCoeffs * parameterSize_);
impl_paramIntegrate (dParam);
}
value_type squaredNormIntegral (const size_type order);
void squaredNormIntegralDerivative (const size_type order, vectorOut_t res);
void basisFunctionDerivative (const size_type order, const value_type& u, BasisFunctionVector_t& res) const;
void basisFunctionDerivative (const size_type order, const value_type& u, vectorOut_t res) const
{
assert (res.size() == NbCoeffs);
BasisFunctionVector_t tmp;
basisFunctionDerivative(order, u, tmp);
res = tmp;
}
void maxVelocity (vectorOut_t res) const;
void squaredNormBasisFunctionIntegral (const size_type order, BasisFunctionIntegralMatrix_t& res) const;
void squaredNormBasisFunctionIntegral (const size_type order, matrixOut_t res) const
{
// assert (res.size() == NbCoeffs);
BasisFunctionIntegralMatrix_t tmp;
squaredNormBasisFunctionIntegral (order, tmp);
res = tmp;
}
Configuration_t initial () const
{
Configuration_t q (outputSize());
bool res = operator() (q, timeRange().first);
assert(res);
return q;
}
Configuration_t end () const
{
Configuration_t q (outputSize());
bool res = operator() (q, timeRange().second);
assert(res);
return q;
}
const Configuration_t& base () const
{
return base_;
}
void base (const Configuration_t& q)
{
base_ = q;
}
/// Each row corresponds to a velocity of the robot.
const ParameterMatrix_t& parameters () const
{
return parameters_;
}
void parameters (const ParameterMatrix_t& m)
{
parameters_ = m;
}
ConstParameterVector_t rowParameters () const
{
return ConstParameterVector_t (parameters_.data(), parameters_.size());
}
void rowParameters (vectorIn_t p)
{
ParameterVector_t(parameters_.data(), parameters_.size()) = p;
}
PathPtr_t copy () const
{
Ptr_t other (new Spline (*this));
other->initCopy(other);
return other;
}
PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
{
Ptr_t other (new Spline (*this, constraints));
other->initCopy(other);
return other;
}
virtual ~Spline () throw () {}
static Ptr_t create (const DevicePtr_t& robot,
const interval_t& interval,
const ConstraintSetPtr_t& constraints)
{
Ptr_t shPtr (new Spline(robot, interval, constraints));
shPtr->init(shPtr);
return shPtr;
}
protected:
Spline (const DevicePtr_t& robot,
const interval_t& interval,
const ConstraintSetPtr_t& constraints)
: Path (interval, robot->configSize(), robot->numberDof(), constraints),
parameterSize_ (robot->numberDof()),
robot_ (robot),
base_ (outputSize()),
parameters_ ((int)NbCoeffs, parameterSize_)
{
powersOfT_(0) = 1;
for (size_type i = 1; i < NbPowerOfT; ++i)
powersOfT_(i) = powersOfT_(i - 1) * length();
}
Spline (const Spline& path);
Spline (const Spline& path, const ConstraintSetPtr_t& constraints);
void init (const Ptr_t& self) { Path::init(self); weak_ = self; }
void initCopy (const Ptr_t& self) { Path::initCopy(self); weak_ = self; }
std::ostream& print (std::ostream &os) const;
bool impl_compute (ConfigurationOut_t configuration, value_type t) const;
void impl_derivative (vectorOut_t res, const value_type& t, size_type order) const;
void impl_paramDerivative (vectorOut_t res, const value_type& t) const;
void impl_paramIntegrate (vectorIn_t dParam);
size_type parameterSize_;
DevicePtr_t robot_;
Configuration_t base_;
ParameterMatrix_t parameters_;
private:
WkPtr_t weak_;
mutable vector_t velocity_;
mutable PowersOfT_t powersOfT_;
}; // class Spline
/// \}
} // namespace path
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_SPLINE_HH
<commit_msg>Remove compilation warning in release mode.<commit_after>// Copyright (c) 2017 CNRS
// Authors: Joseph Mirabel
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PATH_SPLINE_HH
# define HPP_CORE_PATH_SPLINE_HH
# include <hpp/core/path.hh>
# include <hpp/pinocchio/device.hh>
# include <hpp/constraints/matrix-view.hh>
# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
namespace hpp {
namespace core {
namespace path {
/// \addtogroup path
/// \{
enum PolynomeBasisType {
CanonicalPolynomeBasis,
BernsteinBasis
};
/// \cond
namespace internal {
template <int SplineType, int Degree> struct spline_basis_function;
template <int SplineType, int Degree> struct sbf_traits {
enum { NbCoeffs = Degree + 1 };
typedef Eigen::Matrix<value_type, NbCoeffs, 1> Coeffs_t;
typedef Eigen::Matrix<value_type, NbCoeffs, NbCoeffs> IntegralCoeffs_t;
};
}
/// \endcond
/// Base class for spline paths
template <int _PolynomeBasis, int _Order>
class HPP_CORE_DLLAPI Spline : public Path
{
public:
enum {
PolynomeBasis = _PolynomeBasis,
Order = _Order,
NbCoeffs = _Order + 1,
NbPowerOfT = 2 * NbCoeffs + 1
};
typedef internal::sbf_traits<PolynomeBasis, Order> sbf_traits;
typedef internal::spline_basis_function<PolynomeBasis, Order> BasisFunction_t;
typedef Eigen::Matrix<value_type, NbPowerOfT, 1> PowersOfT_t;
typedef typename sbf_traits::Coeffs_t BasisFunctionVector_t;
typedef typename sbf_traits::IntegralCoeffs_t BasisFunctionIntegralMatrix_t;
typedef Eigen::Matrix<value_type, NbCoeffs, Eigen::Dynamic, Eigen::RowMajor> ParameterMatrix_t;
typedef Eigen::Map<const vector_t, Eigen::Aligned> ConstParameterVector_t;
typedef Eigen::Map< vector_t, Eigen::Aligned> ParameterVector_t;
typedef boost::shared_ptr<Spline> Ptr_t;
typedef boost::weak_ptr<Spline> WkPtr_t;
size_type parameterSize () const
{
return parameterSize_;
}
/** The partial derivative with respects to the parameters is of the form
/// \f{eqnarray*}{
/// \frac{\partial S}{\partial p_{k}} (q, p, t) &=& B_k(t) \times I \\
/// \frac{\partial S}{\partial q_{base}} (q, p, t) &=& I
/// \f}
/// This method returns the coefficients \f$ (B_k(t))_{k} \f$
**/
void parameterDerivativeCoefficients (vectorOut_t res, const value_type& t) const
{
assert (res.size() == NbCoeffs);
impl_paramDerivative (res, t);
}
void parameterIntegrate (vectorIn_t dParam)
{
assert (dParam.size() == NbCoeffs * parameterSize_);
impl_paramIntegrate (dParam);
}
value_type squaredNormIntegral (const size_type order);
void squaredNormIntegralDerivative (const size_type order, vectorOut_t res);
void basisFunctionDerivative (const size_type order, const value_type& u, BasisFunctionVector_t& res) const;
void basisFunctionDerivative (const size_type order, const value_type& u, vectorOut_t res) const
{
assert (res.size() == NbCoeffs);
BasisFunctionVector_t tmp;
basisFunctionDerivative(order, u, tmp);
res = tmp;
}
void maxVelocity (vectorOut_t res) const;
void squaredNormBasisFunctionIntegral (const size_type order, BasisFunctionIntegralMatrix_t& res) const;
void squaredNormBasisFunctionIntegral (const size_type order, matrixOut_t res) const
{
// assert (res.size() == NbCoeffs);
BasisFunctionIntegralMatrix_t tmp;
squaredNormBasisFunctionIntegral (order, tmp);
res = tmp;
}
Configuration_t initial () const
{
Configuration_t q (outputSize());
bool res = operator() (q, timeRange().first);
assert(res); (void)res;
return q;
}
Configuration_t end () const
{
Configuration_t q (outputSize());
bool res = operator() (q, timeRange().second);
assert(res); (void)res;
return q;
}
const Configuration_t& base () const
{
return base_;
}
void base (const Configuration_t& q)
{
base_ = q;
}
/// Each row corresponds to a velocity of the robot.
const ParameterMatrix_t& parameters () const
{
return parameters_;
}
void parameters (const ParameterMatrix_t& m)
{
parameters_ = m;
}
ConstParameterVector_t rowParameters () const
{
return ConstParameterVector_t (parameters_.data(), parameters_.size());
}
void rowParameters (vectorIn_t p)
{
ParameterVector_t(parameters_.data(), parameters_.size()) = p;
}
PathPtr_t copy () const
{
Ptr_t other (new Spline (*this));
other->initCopy(other);
return other;
}
PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
{
Ptr_t other (new Spline (*this, constraints));
other->initCopy(other);
return other;
}
virtual ~Spline () throw () {}
static Ptr_t create (const DevicePtr_t& robot,
const interval_t& interval,
const ConstraintSetPtr_t& constraints)
{
Ptr_t shPtr (new Spline(robot, interval, constraints));
shPtr->init(shPtr);
return shPtr;
}
protected:
Spline (const DevicePtr_t& robot,
const interval_t& interval,
const ConstraintSetPtr_t& constraints)
: Path (interval, robot->configSize(), robot->numberDof(), constraints),
parameterSize_ (robot->numberDof()),
robot_ (robot),
base_ (outputSize()),
parameters_ ((int)NbCoeffs, parameterSize_)
{
powersOfT_(0) = 1;
for (size_type i = 1; i < NbPowerOfT; ++i)
powersOfT_(i) = powersOfT_(i - 1) * length();
}
Spline (const Spline& path);
Spline (const Spline& path, const ConstraintSetPtr_t& constraints);
void init (const Ptr_t& self) { Path::init(self); weak_ = self; }
void initCopy (const Ptr_t& self) { Path::initCopy(self); weak_ = self; }
std::ostream& print (std::ostream &os) const;
bool impl_compute (ConfigurationOut_t configuration, value_type t) const;
void impl_derivative (vectorOut_t res, const value_type& t, size_type order) const;
void impl_paramDerivative (vectorOut_t res, const value_type& t) const;
void impl_paramIntegrate (vectorIn_t dParam);
size_type parameterSize_;
DevicePtr_t robot_;
Configuration_t base_;
ParameterMatrix_t parameters_;
private:
WkPtr_t weak_;
mutable vector_t velocity_;
mutable PowersOfT_t powersOfT_;
}; // class Spline
/// \}
} // namespace path
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_SPLINE_HH
<|endoftext|> |
<commit_before>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#ifndef HTTPP_HTTP_PROTOCOL_HPP_
# define HTTPP_HTTP_PROTOCOL_HPP_
# include <string>
namespace HTTPP
{
namespace HTTP
{
using KV = std::pair<std::string, std::string>;
using Header = KV;
static char const HEADER_BODY_SEP[] = { '\r', '\n', '\r', '\n' };
enum class Method
{
HEAD,
GET,
POST,
PUT,
DELETE_, // '_' for msvc workaround
OPTIONS,
TRACE,
CONNECT
};
std::string to_string(Method method);
enum class HttpCode : unsigned int
{
Continue = 100,
Ok = 200,
Created = 201,
Accepted = 202,
NoContent = 204,
MultipleChoice = 300,
MovedPermentaly = 301,
MovedTemporarily = 302,
NotModified = 304,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
HttpVersionNotSupported = 505
};
std::string getDefaultMessage(HttpCode code);
} // namespace HTTP
} // namespace HTTPP
#endif // !HTTPP_HTTP_PROTOCOL_HPP_
<commit_msg>Add Http code<commit_after>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#ifndef HTTPP_HTTP_PROTOCOL_HPP_
# define HTTPP_HTTP_PROTOCOL_HPP_
# include <string>
namespace HTTPP
{
namespace HTTP
{
using KV = std::pair<std::string, std::string>;
using Header = KV;
static char const HEADER_BODY_SEP[] = { '\r', '\n', '\r', '\n' };
enum class Method
{
HEAD,
GET,
POST,
PUT,
DELETE_, // '_' for msvc workaround
OPTIONS,
TRACE,
CONNECT
};
std::string to_string(Method method);
enum class HttpCode : unsigned int
{
Continue = 100,
Ok = 200,
Created = 201,
Accepted = 202,
NoContent = 204,
MultipleChoice = 300,
MovedPermentaly = 301,
MovedTemporarily = 302,
NotModified = 304,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeOut = 504,
HttpVersionNotSupported = 505
};
std::string getDefaultMessage(HttpCode code);
} // namespace HTTP
} // namespace HTTPP
#endif // !HTTPP_HTTP_PROTOCOL_HPP_
<|endoftext|> |
<commit_before>#ifndef __BIGNUMS_HH_
#define __BIGNUMS_HH_
/// Extra support for bignums
#include <ikos_domains/bignums.hpp>
namespace llvm_ikos
{
using namespace ikos;
std::string toStr (z_number n)
{
std::ostringstream s;
s << n;
return s.str ();
}
}
#endif
<commit_msg>[FIX] mark toStr() inline<commit_after>#ifndef __BIGNUMS_HH_
#define __BIGNUMS_HH_
/// Extra support for bignums
#include <ikos_domains/bignums.hpp>
namespace llvm_ikos
{
using namespace ikos;
inline std::string toStr (z_number n)
{
std::ostringstream s;
s << n;
return s.str ();
}
}
#endif
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2005
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: testMacros.cpp,v 1.15 2010/03/26 23:24:15 javarias Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* dfugate 2005-04-04 created
*/
/************************************************************************
* NAME
*
*
* SYNOPSIS
*
*
* DESCRIPTION
*
* FILES
*
* ENVIRONMENT
*
* COMMANDS
*
* RETURN VALUES
*
* CAUTIONS
*
* EXAMPLES
*
* SEE ALSO
*
* BUGS
*
*------------------------------------------------------------------------
*/
#include "logging.h"
#include <acsutilTimeStamp.h>
#include "loggingACSLogger.h"
#include "loggingHandler.h"
#include "loggingLogTrace.h"
#include "logging.h"
namespace Logging {
class TestHandler : public virtual Handler
{
public:
TestHandler()
{setLevel(LM_TRACE);}
~TestHandler()
{}
virtual void
log(const LogRecord& lr)
{
std::string niceTime = getStringifiedUTC(lr.timeStamp).c_str();
std::cout << lr.priority << " " << lr.message << " " << lr.file << " " << lr.line << " " << lr.method << " " << niceTime << std::endl;
}
virtual std::string
getName() const
{return "TestHandler";}
};
};
void testAutoTraceFunc()
{
AUTO_TRACE("testAutoTraceFunc");
}
static void testStaticLoggingWithAudience()
{
STATIC_LOG(Logging::BaseLog::LM_INFO, __PRETTY_FUNCTION__,
"Testing Static Log");
STATIC_LOG_TO_DEVELOPER(LM_INFO, "STATIC_LOG_TO_DEVELOPER");
STATIC_LOG_TO_OPERATOR(LM_INFO, "STATIC_LOG_TO_OPERATOR");
STATIC_LOG_TO_SCIENCE(LM_INFO, "STATIC_LOG_TO_SCIENCE");
STATIC_LOG_TO_SCILOG(LM_INFO, "STATIC_LOG_TO_SCILOG");
}
int main(int argc, char *argv[])
{
char *tooLong_p = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
LoggingProxy m_logger(0, 0, 31, 0);
LoggingProxy::init (&m_logger);
ACS_CHECK_LOGGER;
AUTO_TRACE("someFunc");
testAutoTraceFunc();
ACS_SHORT_LOG((LM_INFO, "%s a %s b %s c %s d %s e %s f %s g %s h %s i %s j %s k Should never see this...\n",
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p));
//--------------------------------------------------------------------
//Test ACS_LOG
ACS_LOG(LM_RUNTIME_CONTEXT, "main",
(LM_INFO, "Test of formatted log 1 - %s",
"This is a string parameter"));
ACS_LOG( LM_SOURCE_INFO, "main",
(LM_INFO, "Test of formatted log 2 - %s",
"This is a string parameter"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_INFO, "Test of formatted log 3 - %s",
"This is a string parameter"));
//--------------------------------------------------------------------
//Test ACS_LOG_TIME
Logging::Logger::LoggerSmartPtr myLoggerSmartPtr = getLogger();
Logging::Handler::HandlerSmartPtr localHandler(new Logging::TestHandler());
myLoggerSmartPtr->addHandler(localHandler);
ACS_LOG_TIME(0, getTimeStamp(), "someRoutineName",
(LM_ERROR, "%s", "The actual time..."));
ACS_LOG_TIME(0, 132922080005000000ULL, "someRoutineName",
(LM_ERROR, "%s", "Should be January 1st 2004..."));
myLoggerSmartPtr->removeHandler(localHandler->getName());
//--------------------------------------------------------------------
//--------------------------------------------------------------------
//Test Add Data
char *tooLongAddData_p =
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789LAST01234567890123456789012345678906789012345678901234567890123456789012345678901234567890";
LoggingProxy::AddData("testTooLongValue", tooLongAddData_p);
ACS_SHORT_LOG((LM_ERROR, "add data for this log message should be too long (max is 1024 characters)"));
//--------------------------------------------------------------------
//Test Levels
ACS_LOG( LM_FULL_INFO, "main",
(LM_TRACE, "Test of LM_TRACE log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_ERROR, "Test of LM_ERROR log"));
ACS_LOG( LM_FULL_INFO, "main",
(03, "Test of LM_DELOUSE log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_DEBUG, "Test of LM_DEBUG log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_INFO, "Test of LM_INFO log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_NOTICE, "Test of LM_NOTICE log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_WARNING, "Test of LM_WARNING log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_CRITICAL, "Test of LM_CRITICAL log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_ALERT, "Test of LM_ALERT log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_EMERGENCY, "Test of LM_EMERGENCY log"));
//Test audience macros
LOG_TO_AUDIENCE_WITH_LOGGER(LM_INFO,
"Test of LOG_TO_AUDIENCE_WITH_LOGGER log",
log_audience::OPERATOR, myLoggerSmartPtr);
LOG_TO_DEVELOPER( LM_INFO, "Test of LOG_TO_DEVELOPER log");
LOG_TO_DEVELOPER_WITH_LOGGER(LM_INFO,
"Test of LOG_TO_DEVELOPER_WITH_LOGGER",
myLoggerSmartPtr);
LOG_TO_OPERATOR( LM_INFO, "Test of LOG_TO_OPERATOR log");
LOG_TO_OPERATOR_WITH_LOGGER(LM_INFO, "Test of LOG_TO_OPERATOR_WITH_LOGGER",
myLoggerSmartPtr);
LOG_TO_SCIENCE( LM_INFO, "Test of LOG_TO_SCIENCE log");
LOG_TO_SCILOG( LM_INFO, "Test of LOG_TO_SCILOG log");
testStaticLoggingWithAudience();
return 0;
}
<commit_msg>Changed the way to debug a DELOUSE log (using LM_DELOUSE)<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2005
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@(#) $Id: testMacros.cpp,v 1.16 2010/03/31 20:15:37 javarias Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* dfugate 2005-04-04 created
*/
/************************************************************************
* NAME
*
*
* SYNOPSIS
*
*
* DESCRIPTION
*
* FILES
*
* ENVIRONMENT
*
* COMMANDS
*
* RETURN VALUES
*
* CAUTIONS
*
* EXAMPLES
*
* SEE ALSO
*
* BUGS
*
*------------------------------------------------------------------------
*/
#include "logging.h"
#include <acsutilTimeStamp.h>
#include "loggingACSLogger.h"
#include "loggingHandler.h"
#include "loggingLogTrace.h"
#include "logging.h"
namespace Logging {
class TestHandler : public virtual Handler
{
public:
TestHandler()
{setLevel(LM_TRACE);}
~TestHandler()
{}
virtual void
log(const LogRecord& lr)
{
std::string niceTime = getStringifiedUTC(lr.timeStamp).c_str();
std::cout << lr.priority << " " << lr.message << " " << lr.file << " " << lr.line << " " << lr.method << " " << niceTime << std::endl;
}
virtual std::string
getName() const
{return "TestHandler";}
};
};
void testAutoTraceFunc()
{
AUTO_TRACE("testAutoTraceFunc");
}
static void testStaticLoggingWithAudience()
{
STATIC_LOG(Logging::BaseLog::LM_INFO, __PRETTY_FUNCTION__,
"Testing Static Log");
STATIC_LOG_TO_DEVELOPER(LM_INFO, "STATIC_LOG_TO_DEVELOPER");
STATIC_LOG_TO_OPERATOR(LM_INFO, "STATIC_LOG_TO_OPERATOR");
STATIC_LOG_TO_SCIENCE(LM_INFO, "STATIC_LOG_TO_SCIENCE");
STATIC_LOG_TO_SCILOG(LM_INFO, "STATIC_LOG_TO_SCILOG");
}
int main(int argc, char *argv[])
{
char *tooLong_p = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
LoggingProxy m_logger(0, 0, 31, 0);
LoggingProxy::init (&m_logger);
ACS_CHECK_LOGGER;
AUTO_TRACE("someFunc");
testAutoTraceFunc();
ACS_SHORT_LOG((LM_INFO, "%s a %s b %s c %s d %s e %s f %s g %s h %s i %s j %s k Should never see this...\n",
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p,
tooLong_p));
//--------------------------------------------------------------------
//Test ACS_LOG
ACS_LOG(LM_RUNTIME_CONTEXT, "main",
(LM_INFO, "Test of formatted log 1 - %s",
"This is a string parameter"));
ACS_LOG( LM_SOURCE_INFO, "main",
(LM_INFO, "Test of formatted log 2 - %s",
"This is a string parameter"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_INFO, "Test of formatted log 3 - %s",
"This is a string parameter"));
//--------------------------------------------------------------------
//Test ACS_LOG_TIME
Logging::Logger::LoggerSmartPtr myLoggerSmartPtr = getLogger();
Logging::Handler::HandlerSmartPtr localHandler(new Logging::TestHandler());
myLoggerSmartPtr->addHandler(localHandler);
ACS_LOG_TIME(0, getTimeStamp(), "someRoutineName",
(LM_ERROR, "%s", "The actual time..."));
ACS_LOG_TIME(0, 132922080005000000ULL, "someRoutineName",
(LM_ERROR, "%s", "Should be January 1st 2004..."));
myLoggerSmartPtr->removeHandler(localHandler->getName());
//--------------------------------------------------------------------
//--------------------------------------------------------------------
//Test Add Data
char *tooLongAddData_p =
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\
1234567890123456789LAST01234567890123456789012345678906789012345678901234567890123456789012345678901234567890";
LoggingProxy::AddData("testTooLongValue", tooLongAddData_p);
ACS_SHORT_LOG((LM_ERROR, "add data for this log message should be too long (max is 1024 characters)"));
//--------------------------------------------------------------------
//Test Levels
ACS_LOG( LM_FULL_INFO, "main",
(LM_TRACE, "Test of LM_TRACE log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_ERROR, "Test of LM_ERROR log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_DELOUSE, "Test of LM_DELOUSE log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_DEBUG, "Test of LM_DEBUG log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_INFO, "Test of LM_INFO log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_NOTICE, "Test of LM_NOTICE log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_WARNING, "Test of LM_WARNING log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_CRITICAL, "Test of LM_CRITICAL log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_ALERT, "Test of LM_ALERT log"));
ACS_LOG( LM_FULL_INFO, "main",
(LM_EMERGENCY, "Test of LM_EMERGENCY log"));
//Test audience macros
LOG_TO_AUDIENCE_WITH_LOGGER(LM_INFO,
"Test of LOG_TO_AUDIENCE_WITH_LOGGER log",
log_audience::OPERATOR, myLoggerSmartPtr);
LOG_TO_DEVELOPER( LM_INFO, "Test of LOG_TO_DEVELOPER log");
LOG_TO_DEVELOPER_WITH_LOGGER(LM_INFO,
"Test of LOG_TO_DEVELOPER_WITH_LOGGER",
myLoggerSmartPtr);
LOG_TO_OPERATOR( LM_INFO, "Test of LOG_TO_OPERATOR log");
LOG_TO_OPERATOR_WITH_LOGGER(LM_INFO, "Test of LOG_TO_OPERATOR_WITH_LOGGER",
myLoggerSmartPtr);
LOG_TO_SCIENCE( LM_INFO, "Test of LOG_TO_SCIENCE log");
LOG_TO_SCILOG( LM_INFO, "Test of LOG_TO_SCILOG log");
testStaticLoggingWithAudience();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright (c) 2012 Kohei Yoshida
*
* 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 __MDDS_GRID_MAP_TYPES_HPP__
#define __MDDS_GRID_MAP_TYPES_HPP__
#include <vector>
namespace mdds { namespace gridmap {
typedef int cell_t;
const cell_t celltype_numeric = 0;
const cell_t celltype_string = 1;
const cell_t celltype_index = 2;
const cell_t celltype_boolean = 3;
const cell_t celltype_user_start = 50;
struct base_cell_block;
cell_t get_block_type(const base_cell_block&);
struct base_cell_block
{
friend cell_t get_block_type(const base_cell_block&);
protected:
cell_t type;
base_cell_block(cell_t _t) : type(_t) {}
};
template<typename _Self, cell_t _TypeId, typename _Data>
class cell_block : public base_cell_block
{
struct print_block_array
{
void operator() (const _Data& val) const
{
std::cout << val << " ";
}
};
protected:
typedef std::vector<_Data> store_type;
store_type m_array;
cell_block() : base_cell_block(_TypeId) {}
cell_block(size_t n) : base_cell_block(_TypeId), m_array(n) {}
public:
bool operator== (const _Self& r) const
{
return m_array == r.m_array;
}
bool operator!= (const _Self& r) const
{
return !operator==(r);
}
static _Self& get(base_cell_block& block)
{
if (get_block_type(block) != _TypeId)
throw general_error("incorrect block type.");
return static_cast<_Self&>(block);
}
static const _Self& get(const base_cell_block& block)
{
if (get_block_type(block) != _TypeId)
throw general_error("incorrect block type.");
return static_cast<const _Self&>(block);
}
static void set_value(base_cell_block& blk, size_t pos, const _Data& val)
{
get(blk).m_array[pos] = val;
}
static void get_value(const base_cell_block& blk, size_t pos, _Data& val)
{
val = get(blk).m_array[pos];
}
static void append_value(base_cell_block& blk, const _Data& val)
{
get(blk).m_array.push_back(val);
}
static void prepend_value(base_cell_block& blk, const _Data& val)
{
store_type& blk2 = get(blk).m_array;
blk2.insert(blk2.begin(), val);
}
static _Self* create_block(size_t init_size)
{
return new _Self(init_size);
}
static _Self* clone_block(const base_cell_block& blk)
{
return new _Self(get(blk));
}
static void delete_block(const base_cell_block* p)
{
delete static_cast<const _Self*>(p);
}
static void resize_block(base_cell_block& blk, size_t new_size)
{
static_cast<_Self&>(blk).m_array.resize(new_size);
}
static void print_block(const base_cell_block& blk)
{
const store_type& blk2 = get(blk).m_array;
std::for_each(blk2.begin(), blk2.end(), print_block_array());
std::cout << std::endl;
}
static void erase_block(base_cell_block& blk, size_t pos)
{
store_type& blk2 = get(blk).m_array;
blk2.erase(blk2.begin()+pos);
}
static void erase_block(base_cell_block& blk, size_t pos, size_t size)
{
store_type& blk2 = get(blk).m_array;
blk2.erase(blk2.begin()+pos, blk2.begin()+pos+size);
}
static void append_values_from_block(base_cell_block& dest, const base_cell_block& src)
{
store_type& d = get(dest).m_array;
const store_type& s = get(src).m_array;
d.insert(d.end(), s.begin(), s.end());
}
static void append_values_from_block(
base_cell_block& dest, const base_cell_block& src, size_t begin_pos, size_t len)
{
store_type& d = get(dest).m_array;
const store_type& s = get(src).m_array;
typename store_type::const_iterator it = s.begin();
std::advance(it, begin_pos);
typename store_type::const_iterator it_end = it;
std::advance(it_end, len);
d.reserve(d.size() + len);
std::copy(it, it_end, std::back_inserter(d));
}
static void assign_values_from_block(
base_cell_block& dest, const base_cell_block& src, size_t begin_pos, size_t len)
{
store_type& d = get(dest).m_array;
const store_type& s = get(src).m_array;
typename store_type::const_iterator it = s.begin();
std::advance(it, begin_pos);
typename store_type::const_iterator it_end = it;
std::advance(it_end, len);
d.assign(it, it_end);
}
template<typename _Iter>
static void set_values(
base_cell_block& block, size_t pos, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(block).m_array;
for (_Iter it = it_begin; it != it_end; ++it, ++pos)
d[pos] = *it;
}
template<typename _Iter>
static void append_values(base_cell_block& block, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(block).m_array;
typename store_type::iterator it = d.end();
d.insert(it, it_begin, it_end);
}
template<typename _Iter>
static void prepend_values(base_cell_block& block, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(block).m_array;
d.insert(d.begin(), it_begin, it_end);
}
template<typename _Iter>
static void assign_values(base_cell_block& dest, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(dest).m_array;
d.assign(it_begin, it_end);
}
template<typename _Iter>
static void insert_values(
base_cell_block& block, size_t pos, const _Iter& it_begin, const _Iter& it_end)
{
store_type& blk = get(block).m_array;
blk.insert(blk.begin()+pos, it_begin, it_end);
}
};
/**
* Get the numerical block type ID from a given cell block instance.
*
* @param blk cell block instance
*
* @return numerical value representing the ID of a cell block.
*/
inline cell_t get_block_type(const base_cell_block& blk)
{
return blk.type;
}
/**
* Template for default, unmanaged cell block for use in grid_map.
*/
template<cell_t _TypeId, typename _Data>
struct default_cell_block : public cell_block<default_cell_block<_TypeId,_Data>, _TypeId, _Data>
{
typedef cell_block<default_cell_block, _TypeId, _Data> base_type;
default_cell_block() : base_type() {}
default_cell_block(size_t n) : base_type(n) {}
static void overwrite_cells(base_cell_block&, size_t, size_t)
{
// Do nothing.
}
};
/**
* Template for cell block that stores pointers to objects whose life cycles
* are managed by the block.
*/
template<cell_t _TypeId, typename _Data>
struct managed_cell_block : public cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*>
{
typedef cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*> base_type;
using base_type::get;
using base_type::m_array;
managed_cell_block() : base_type() {}
managed_cell_block(size_t n) : base_type(n) {}
managed_cell_block(const managed_cell_block& r)
{
m_array.reserve(r.m_array.size());
typename managed_cell_block::store_type::const_iterator it = r.m_array.begin(), it_end = r.m_array.end();
for (; it != it_end; ++it)
m_array.push_back(new _Data(**it));
}
~managed_cell_block()
{
std::for_each(m_array.begin(), m_array.end(), default_deleter<_Data>());
}
static void overwrite_cells(base_cell_block& block, size_t pos, size_t len)
{
managed_cell_block& blk = get(block);
typename managed_cell_block::store_type::iterator it = blk.m_array.begin() + pos;
typename managed_cell_block::store_type::iterator it_end = it + len;
std::for_each(it, it_end, default_deleter<_Data>());
}
};
}}
#endif
<commit_msg>I need to include this header here.<commit_after>/*************************************************************************
*
* Copyright (c) 2012 Kohei Yoshida
*
* 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 __MDDS_GRID_MAP_TYPES_HPP__
#define __MDDS_GRID_MAP_TYPES_HPP__
#include "mdds/default_deleter.hpp"
#include <vector>
namespace mdds { namespace gridmap {
typedef int cell_t;
const cell_t celltype_numeric = 0;
const cell_t celltype_string = 1;
const cell_t celltype_index = 2;
const cell_t celltype_boolean = 3;
const cell_t celltype_user_start = 50;
struct base_cell_block;
cell_t get_block_type(const base_cell_block&);
struct base_cell_block
{
friend cell_t get_block_type(const base_cell_block&);
protected:
cell_t type;
base_cell_block(cell_t _t) : type(_t) {}
};
template<typename _Self, cell_t _TypeId, typename _Data>
class cell_block : public base_cell_block
{
struct print_block_array
{
void operator() (const _Data& val) const
{
std::cout << val << " ";
}
};
protected:
typedef std::vector<_Data> store_type;
store_type m_array;
cell_block() : base_cell_block(_TypeId) {}
cell_block(size_t n) : base_cell_block(_TypeId), m_array(n) {}
public:
bool operator== (const _Self& r) const
{
return m_array == r.m_array;
}
bool operator!= (const _Self& r) const
{
return !operator==(r);
}
static _Self& get(base_cell_block& block)
{
if (get_block_type(block) != _TypeId)
throw general_error("incorrect block type.");
return static_cast<_Self&>(block);
}
static const _Self& get(const base_cell_block& block)
{
if (get_block_type(block) != _TypeId)
throw general_error("incorrect block type.");
return static_cast<const _Self&>(block);
}
static void set_value(base_cell_block& blk, size_t pos, const _Data& val)
{
get(blk).m_array[pos] = val;
}
static void get_value(const base_cell_block& blk, size_t pos, _Data& val)
{
val = get(blk).m_array[pos];
}
static void append_value(base_cell_block& blk, const _Data& val)
{
get(blk).m_array.push_back(val);
}
static void prepend_value(base_cell_block& blk, const _Data& val)
{
store_type& blk2 = get(blk).m_array;
blk2.insert(blk2.begin(), val);
}
static _Self* create_block(size_t init_size)
{
return new _Self(init_size);
}
static _Self* clone_block(const base_cell_block& blk)
{
return new _Self(get(blk));
}
static void delete_block(const base_cell_block* p)
{
delete static_cast<const _Self*>(p);
}
static void resize_block(base_cell_block& blk, size_t new_size)
{
static_cast<_Self&>(blk).m_array.resize(new_size);
}
static void print_block(const base_cell_block& blk)
{
const store_type& blk2 = get(blk).m_array;
std::for_each(blk2.begin(), blk2.end(), print_block_array());
std::cout << std::endl;
}
static void erase_block(base_cell_block& blk, size_t pos)
{
store_type& blk2 = get(blk).m_array;
blk2.erase(blk2.begin()+pos);
}
static void erase_block(base_cell_block& blk, size_t pos, size_t size)
{
store_type& blk2 = get(blk).m_array;
blk2.erase(blk2.begin()+pos, blk2.begin()+pos+size);
}
static void append_values_from_block(base_cell_block& dest, const base_cell_block& src)
{
store_type& d = get(dest).m_array;
const store_type& s = get(src).m_array;
d.insert(d.end(), s.begin(), s.end());
}
static void append_values_from_block(
base_cell_block& dest, const base_cell_block& src, size_t begin_pos, size_t len)
{
store_type& d = get(dest).m_array;
const store_type& s = get(src).m_array;
typename store_type::const_iterator it = s.begin();
std::advance(it, begin_pos);
typename store_type::const_iterator it_end = it;
std::advance(it_end, len);
d.reserve(d.size() + len);
std::copy(it, it_end, std::back_inserter(d));
}
static void assign_values_from_block(
base_cell_block& dest, const base_cell_block& src, size_t begin_pos, size_t len)
{
store_type& d = get(dest).m_array;
const store_type& s = get(src).m_array;
typename store_type::const_iterator it = s.begin();
std::advance(it, begin_pos);
typename store_type::const_iterator it_end = it;
std::advance(it_end, len);
d.assign(it, it_end);
}
template<typename _Iter>
static void set_values(
base_cell_block& block, size_t pos, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(block).m_array;
for (_Iter it = it_begin; it != it_end; ++it, ++pos)
d[pos] = *it;
}
template<typename _Iter>
static void append_values(base_cell_block& block, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(block).m_array;
typename store_type::iterator it = d.end();
d.insert(it, it_begin, it_end);
}
template<typename _Iter>
static void prepend_values(base_cell_block& block, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(block).m_array;
d.insert(d.begin(), it_begin, it_end);
}
template<typename _Iter>
static void assign_values(base_cell_block& dest, const _Iter& it_begin, const _Iter& it_end)
{
store_type& d = get(dest).m_array;
d.assign(it_begin, it_end);
}
template<typename _Iter>
static void insert_values(
base_cell_block& block, size_t pos, const _Iter& it_begin, const _Iter& it_end)
{
store_type& blk = get(block).m_array;
blk.insert(blk.begin()+pos, it_begin, it_end);
}
};
/**
* Get the numerical block type ID from a given cell block instance.
*
* @param blk cell block instance
*
* @return numerical value representing the ID of a cell block.
*/
inline cell_t get_block_type(const base_cell_block& blk)
{
return blk.type;
}
/**
* Template for default, unmanaged cell block for use in grid_map.
*/
template<cell_t _TypeId, typename _Data>
struct default_cell_block : public cell_block<default_cell_block<_TypeId,_Data>, _TypeId, _Data>
{
typedef cell_block<default_cell_block, _TypeId, _Data> base_type;
default_cell_block() : base_type() {}
default_cell_block(size_t n) : base_type(n) {}
static void overwrite_cells(base_cell_block&, size_t, size_t)
{
// Do nothing.
}
};
/**
* Template for cell block that stores pointers to objects whose life cycles
* are managed by the block.
*/
template<cell_t _TypeId, typename _Data>
struct managed_cell_block : public cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*>
{
typedef cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*> base_type;
using base_type::get;
using base_type::m_array;
managed_cell_block() : base_type() {}
managed_cell_block(size_t n) : base_type(n) {}
managed_cell_block(const managed_cell_block& r)
{
m_array.reserve(r.m_array.size());
typename managed_cell_block::store_type::const_iterator it = r.m_array.begin(), it_end = r.m_array.end();
for (; it != it_end; ++it)
m_array.push_back(new _Data(**it));
}
~managed_cell_block()
{
std::for_each(m_array.begin(), m_array.end(), mdds::default_deleter<_Data>());
}
static void overwrite_cells(base_cell_block& block, size_t pos, size_t len)
{
managed_cell_block& blk = get(block);
typename managed_cell_block::store_type::iterator it = blk.m_array.begin() + pos;
typename managed_cell_block::store_type::iterator it_end = it + len;
std::for_each(it, it_end, mdds::default_deleter<_Data>());
}
};
}}
#endif
<|endoftext|> |
<commit_before>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "ctkPluginFrameworkContext_p.h"
#include "ctkPluginFrameworkUtil_p.h"
#include "ctkPluginFramework_p.h"
#include "ctkPluginArchive_p.h"
#include "ctkPluginStorageSQL_p.h"
#include "ctkPluginConstants.h"
#include "ctkServices_p.h"
#include "ctkUtils.h"
//----------------------------------------------------------------------------
QMutex ctkPluginFrameworkContext::globalFwLock;
int ctkPluginFrameworkContext::globalId = 1;
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::ctkPluginFrameworkContext(
const ctkProperties& initProps)
: plugins(0), listeners(this), services(0), systemPlugin(new ctkPluginFramework()),
storage(0), firstInit(true), props(initProps), debug(props),
initialized(false)
{
{
QMutexLocker lock(&globalFwLock);
id = globalId++;
systemPlugin->ctkPlugin::init(new ctkPluginFrameworkPrivate(systemPlugin, this));
}
initProperties();
log() << "created";
}
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::~ctkPluginFrameworkContext()
{
if (initialized)
{
this->uninit();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::initProperties()
{
props[ctkPluginConstants::FRAMEWORK_VERSION] = "0.9";
props[ctkPluginConstants::FRAMEWORK_VENDOR] = "CommonTK";
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::init()
{
log() << "initializing";
if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT
== props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN])
{
deleteFWDir();
firstInit = false;
}
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->initSystemPlugin();
storage = new ctkPluginStorageSQL(this);
dataStorage = ctkPluginFrameworkUtil::getFileStorage(this, "data");
services = new ctkServices(this);
plugins = new ctkPlugins(this);
// Pre-load libraries
// This may speed up installing new plug-ins if they have dependencies on
// one of these libraries. It prevents repeated loading and unloading of the
// pre-loaded libraries during caching of the plug-in meta-data.
if (props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].isValid())
{
QStringList preloadLibs = props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].toStringList();
QLibrary::LoadHints loadHints;
QVariant loadHintsVariant = props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
if (loadHintsVariant.isValid())
{
loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
}
foreach(QString preloadLib, preloadLibs)
{
QLibrary lib;
QStringList nameAndVersion = preloadLib.split(":");
QString libraryName;
if (nameAndVersion.count() == 1)
{
libraryName = nameAndVersion.front();
lib.setFileName(nameAndVersion.front());
}
else if (nameAndVersion.count() == 2)
{
libraryName = nameAndVersion.front() + "." + nameAndVersion.back();
lib.setFileNameAndVersion(nameAndVersion.front(), nameAndVersion.back());
}
else
{
qWarning() << "Wrong syntax in" << preloadLib << ". Use <lib-name>[:version]. Skipping.";
continue;
}
lib.setLoadHints(loadHints);
log() << "Pre-loading library" << libraryName << "with hints [" << static_cast<int>(loadHints) << "]";
if (!lib.load())
{
qWarning() << "Pre-loading library" << libraryName << "failed. Check your library search paths.";
}
}
}
plugins->load();
log() << "inited";
initialized = true;
log() << "Installed plugins:";
// Use the ordering in the plugin storage to get a sorted list of plugins.
QList<QSharedPointer<ctkPluginArchive> > allPAs = storage->getAllPluginArchives();
foreach (QSharedPointer<ctkPluginArchive> pa, allPAs)
{
QSharedPointer<ctkPlugin> plugin = plugins->getPlugin(pa->getPluginLocation().toString());
log() << " #" << plugin->getPluginId() << " " << plugin->getSymbolicName() << ":"
<< plugin->getVersion() << " location:" << plugin->getLocation();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::uninit()
{
if (!initialized) return;
log() << "uninit";
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->uninitSystemPlugin();
plugins->clear();
delete plugins;
plugins = 0;
delete storage; // calls storage->close()
storage = 0;
delete services;
services = 0;
initialized = false;
}
//----------------------------------------------------------------------------
int ctkPluginFrameworkContext::getId() const
{
return id;
}
//----------------------------------------------------------------------------
QFileInfo ctkPluginFrameworkContext::getDataStorage(long id)
{
return QFileInfo(dataStorage.absolutePath() + '/' + QString::number(id) + '/');
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkOurPlugin(ctkPlugin* plugin) const
{
ctkPluginPrivate* pp = plugin->d_func();
if (this != pp->fwCtx)
{
throw ctkInvalidArgumentException("ctkPlugin does not belong to this framework: " + plugin->getSymbolicName());
}
}
//----------------------------------------------------------------------------
QDebug ctkPluginFrameworkContext::log() const
{
static QString nirvana;
nirvana.clear();
if (debug.framework)
return qDebug() << "Framework instance " << getId() << ": ";
else
return QDebug(&nirvana);
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::resolvePlugin(ctkPluginPrivate* plugin)
{
if (debug.resolve)
{
qDebug() << "resolve:" << plugin->symbolicName << "[" << plugin->id << "]";
}
// If we enter with tempResolved set, it means that we already have
// resolved plugins. Check that it is true!
if (tempResolved.size() > 0 && !tempResolved.contains(plugin))
{
ctkPluginException pe("resolve: InternalError1!", ctkPluginException::RESOLVE_ERROR);
listeners.frameworkError(plugin->q_func(), pe);
throw pe;
}
tempResolved.clear();
tempResolved.insert(plugin);
checkRequirePlugin(plugin);
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "resolve: Done for" << plugin->symbolicName << "[" << plugin->id << "]";
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkRequirePlugin(ctkPluginPrivate *plugin)
{
if (!plugin->require.isEmpty())
{
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: check requiring plugin" << plugin->id;
}
QListIterator<ctkRequirePlugin*> i(plugin->require);
while (i.hasNext())
{
ctkRequirePlugin* pr = i.next();
QList<ctkPlugin*> pl = plugins->getPlugins(pr->name, pr->pluginRange);
ctkPluginPrivate* ok = 0;
for (QListIterator<ctkPlugin*> pci(pl); pci.hasNext() && ok == 0; )
{
ctkPluginPrivate* p2 = pci.next()->d_func();
if (tempResolved.contains(p2))
{
ok = p2;
}
else if (ctkPluginPrivate::RESOLVED_FLAGS & p2->state)
{
ok = p2;
}
else if (p2->state == ctkPlugin::INSTALLED) {
QSet<ctkPluginPrivate*> oldTempResolved = tempResolved;
tempResolved.insert(p2);
// TODO check if operation locking is correct in case of
// multi-threaded plug-in start up. Maybe refactor out the dependency
// checking (use the "package" lock)
ctkPluginPrivate::Locker sync(&p2->operationLock);
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::RESOLVING);
checkRequirePlugin(p2);
tempResolved = oldTempResolved;
p2->state = ctkPlugin::RESOLVED;
listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, p2->q_func()));
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::IDLE);
ok = p2;
}
}
if (!ok && pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
{
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: failed to satisfy:" << pr->name;
}
throw ctkPluginException(QString("Failed to resolve required plugin: %1").arg(pr->name));
}
}
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::deleteFWDir()
{
QString d = ctkPluginFrameworkUtil::getFrameworkDir(this);
QFileInfo fwDirInfo(d);
if (fwDirInfo.exists())
{
if(fwDirInfo.isDir())
{
log() << "deleting old framework directory.";
bool bOK = ctk::removeDirRecursively(fwDirInfo.absoluteFilePath());
if(!bOK)
{
qDebug() << "Failed to remove existing fwdir" << fwDirInfo.absoluteFilePath();
}
}
}
}
<commit_msg>Moved library pre-loading before framework initialization. Fixes #324.<commit_after>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "ctkPluginFrameworkContext_p.h"
#include "ctkPluginFrameworkUtil_p.h"
#include "ctkPluginFramework_p.h"
#include "ctkPluginArchive_p.h"
#include "ctkPluginStorageSQL_p.h"
#include "ctkPluginConstants.h"
#include "ctkServices_p.h"
#include "ctkUtils.h"
//----------------------------------------------------------------------------
QMutex ctkPluginFrameworkContext::globalFwLock;
int ctkPluginFrameworkContext::globalId = 1;
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::ctkPluginFrameworkContext(
const ctkProperties& initProps)
: plugins(0), listeners(this), services(0), systemPlugin(new ctkPluginFramework()),
storage(0), firstInit(true), props(initProps), debug(props),
initialized(false)
{
{
QMutexLocker lock(&globalFwLock);
id = globalId++;
systemPlugin->ctkPlugin::init(new ctkPluginFrameworkPrivate(systemPlugin, this));
}
initProperties();
log() << "created";
}
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::~ctkPluginFrameworkContext()
{
if (initialized)
{
this->uninit();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::initProperties()
{
props[ctkPluginConstants::FRAMEWORK_VERSION] = "0.9";
props[ctkPluginConstants::FRAMEWORK_VENDOR] = "CommonTK";
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::init()
{
log() << "initializing";
if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT
== props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN])
{
deleteFWDir();
firstInit = false;
}
// Pre-load libraries
// This may speed up installing new plug-ins if they have dependencies on
// one of these libraries. It prevents repeated loading and unloading of the
// pre-loaded libraries during caching of the plug-in meta-data.
if (props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].isValid())
{
QStringList preloadLibs = props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].toStringList();
QLibrary::LoadHints loadHints;
QVariant loadHintsVariant = props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
if (loadHintsVariant.isValid())
{
loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
}
foreach(QString preloadLib, preloadLibs)
{
QLibrary lib;
QStringList nameAndVersion = preloadLib.split(":");
QString libraryName;
if (nameAndVersion.count() == 1)
{
libraryName = nameAndVersion.front();
lib.setFileName(nameAndVersion.front());
}
else if (nameAndVersion.count() == 2)
{
libraryName = nameAndVersion.front() + "." + nameAndVersion.back();
lib.setFileNameAndVersion(nameAndVersion.front(), nameAndVersion.back());
}
else
{
qWarning() << "Wrong syntax in" << preloadLib << ". Use <lib-name>[:version]. Skipping.";
continue;
}
lib.setLoadHints(loadHints);
log() << "Pre-loading library" << lib.fileName() << "with hints [" << static_cast<int>(loadHints) << "]";
if (!lib.load())
{
qWarning() << "Pre-loading library" << lib.fileName() << "failed:" << lib.errorString() << "\nCheck your library search paths.";
}
}
}
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->initSystemPlugin();
storage = new ctkPluginStorageSQL(this);
dataStorage = ctkPluginFrameworkUtil::getFileStorage(this, "data");
services = new ctkServices(this);
plugins = new ctkPlugins(this);
plugins->load();
log() << "inited";
initialized = true;
log() << "Installed plugins:";
// Use the ordering in the plugin storage to get a sorted list of plugins.
QList<QSharedPointer<ctkPluginArchive> > allPAs = storage->getAllPluginArchives();
foreach (QSharedPointer<ctkPluginArchive> pa, allPAs)
{
QSharedPointer<ctkPlugin> plugin = plugins->getPlugin(pa->getPluginLocation().toString());
log() << " #" << plugin->getPluginId() << " " << plugin->getSymbolicName() << ":"
<< plugin->getVersion() << " location:" << plugin->getLocation();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::uninit()
{
if (!initialized) return;
log() << "uninit";
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->uninitSystemPlugin();
plugins->clear();
delete plugins;
plugins = 0;
delete storage; // calls storage->close()
storage = 0;
delete services;
services = 0;
initialized = false;
}
//----------------------------------------------------------------------------
int ctkPluginFrameworkContext::getId() const
{
return id;
}
//----------------------------------------------------------------------------
QFileInfo ctkPluginFrameworkContext::getDataStorage(long id)
{
return QFileInfo(dataStorage.absolutePath() + '/' + QString::number(id) + '/');
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkOurPlugin(ctkPlugin* plugin) const
{
ctkPluginPrivate* pp = plugin->d_func();
if (this != pp->fwCtx)
{
throw ctkInvalidArgumentException("ctkPlugin does not belong to this framework: " + plugin->getSymbolicName());
}
}
//----------------------------------------------------------------------------
QDebug ctkPluginFrameworkContext::log() const
{
static QString nirvana;
nirvana.clear();
if (debug.framework)
return qDebug() << "Framework instance " << getId() << ": ";
else
return QDebug(&nirvana);
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::resolvePlugin(ctkPluginPrivate* plugin)
{
if (debug.resolve)
{
qDebug() << "resolve:" << plugin->symbolicName << "[" << plugin->id << "]";
}
// If we enter with tempResolved set, it means that we already have
// resolved plugins. Check that it is true!
if (tempResolved.size() > 0 && !tempResolved.contains(plugin))
{
ctkPluginException pe("resolve: InternalError1!", ctkPluginException::RESOLVE_ERROR);
listeners.frameworkError(plugin->q_func(), pe);
throw pe;
}
tempResolved.clear();
tempResolved.insert(plugin);
checkRequirePlugin(plugin);
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "resolve: Done for" << plugin->symbolicName << "[" << plugin->id << "]";
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkRequirePlugin(ctkPluginPrivate *plugin)
{
if (!plugin->require.isEmpty())
{
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: check requiring plugin" << plugin->id;
}
QListIterator<ctkRequirePlugin*> i(plugin->require);
while (i.hasNext())
{
ctkRequirePlugin* pr = i.next();
QList<ctkPlugin*> pl = plugins->getPlugins(pr->name, pr->pluginRange);
ctkPluginPrivate* ok = 0;
for (QListIterator<ctkPlugin*> pci(pl); pci.hasNext() && ok == 0; )
{
ctkPluginPrivate* p2 = pci.next()->d_func();
if (tempResolved.contains(p2))
{
ok = p2;
}
else if (ctkPluginPrivate::RESOLVED_FLAGS & p2->state)
{
ok = p2;
}
else if (p2->state == ctkPlugin::INSTALLED) {
QSet<ctkPluginPrivate*> oldTempResolved = tempResolved;
tempResolved.insert(p2);
// TODO check if operation locking is correct in case of
// multi-threaded plug-in start up. Maybe refactor out the dependency
// checking (use the "package" lock)
ctkPluginPrivate::Locker sync(&p2->operationLock);
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::RESOLVING);
checkRequirePlugin(p2);
tempResolved = oldTempResolved;
p2->state = ctkPlugin::RESOLVED;
listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, p2->q_func()));
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::IDLE);
ok = p2;
}
}
if (!ok && pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
{
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: failed to satisfy:" << pr->name;
}
throw ctkPluginException(QString("Failed to resolve required plugin: %1").arg(pr->name));
}
}
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::deleteFWDir()
{
QString d = ctkPluginFrameworkUtil::getFrameworkDir(this);
QFileInfo fwDirInfo(d);
if (fwDirInfo.exists())
{
if(fwDirInfo.isDir())
{
log() << "deleting old framework directory.";
bool bOK = ctk::removeDirRecursively(fwDirInfo.absoluteFilePath());
if(!bOK)
{
qDebug() << "Failed to remove existing fwdir" << fwDirInfo.absoluteFilePath();
}
}
}
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 Conrado Miranda
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.
*/
// Each archive has a entries with the following format:
// 1) Number of entries (size_t);
// 2.1) Size of the key (size_t);
// 2.2) Size of the object (size_t);
// 2.3) Key as serialized by boost;
// 2.4) Object as serialized by boost.
#ifndef __OBJECT_ARCHIVE_IMPL_HPP__
#define __OBJECT_ARCHIVE_IMPL_HPP__
#include "object_archive.hpp"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#if ENABLE_THREADS
#define OBJECT_ARCHIVE_MUTEX_GUARD \
boost::lock_guard<boost::recursive_mutex> __mutex_guard(mutex_)
#else
#define OBJECT_ARCHIVE_MUTEX_GUARD do { } while(0)
#endif
template <class Key>
ObjectArchive<Key>::ObjectArchive():
must_rebuild_file_(false),
max_buffer_size_(0),
buffer_size_(0),
temporary_file_(false) {
init();
set_buffer_size(0);
}
template <class Key>
ObjectArchive<Key>::~ObjectArchive() {
OBJECT_ARCHIVE_MUTEX_GUARD;
if (!temporary_file_)
internal_flush();
stream_.close();
if (temporary_file_)
boost::filesystem::remove(filename_);
}
template <class Key>
template <class T>
std::string ObjectArchive<Key>::serialize(T const& val) {
std::stringstream stream;
{
boost::iostreams::filtering_stream<boost::iostreams::output> filtering;
filtering.push(boost::iostreams::zlib_compressor());
filtering.push(stream);
boost::archive::binary_oarchive ofs(filtering);
ofs << val;
}
return stream.str();
}
template <class Key>
template <class T1, class T2>
std::string ObjectArchive<Key>::serialize(T2 const& val) {
std::stringstream stream;
{
boost::iostreams::filtering_stream<boost::iostreams::output> filtering;
filtering.push(boost::iostreams::zlib_compressor());
filtering.push(stream);
boost::archive::binary_oarchive ofs(filtering);
ofs.register_type<T1>();
ofs << val;
}
return stream.str();
}
template <class Key>
template <class T>
void ObjectArchive<Key>::deserialize(std::string const& str, T& val) {
std::stringstream stream(str);
boost::iostreams::filtering_stream<boost::iostreams::input> filtering;
filtering.push(boost::iostreams::zlib_decompressor());
filtering.push(stream);
boost::archive::binary_iarchive ifs(filtering);
ifs >> val;
}
template <class Key>
void ObjectArchive<Key>::init() {
std::string filename;
filename = boost::filesystem::temp_directory_path().string();
filename += '/';
filename += boost::filesystem::unique_path().string();
init(filename, true);
}
template <class Key>
void ObjectArchive<Key>::init(std::string const& filename,
bool temporary_file) {
OBJECT_ARCHIVE_MUTEX_GUARD;
internal_flush();
stream_.close();
if (temporary_file_)
boost::filesystem::remove(filename_);
filename_ = filename;
temporary_file_ = temporary_file;
buffer_size_ = 0;
objects_.clear();
LRU_.clear();
stream_.open(filename, std::ios_base::in | std::ios_base::out |
std::ios_base::binary);
stream_.seekg(0, std::ios_base::end);
// If the file seems ok and has entries, use it. Otherwise, overwrite.
if (stream_.good() && stream_.tellg() > 0) {
stream_.seekg(0);
size_t n_entries;
stream_.read((char*)&n_entries, sizeof(size_t));
for (size_t i = 0; i < n_entries; i++) {
size_t key_size;
size_t data_size;
stream_.read((char*)&key_size, sizeof(size_t));
stream_.read((char*)&data_size, sizeof(size_t));
std::string key_string;
key_string.resize(key_size);
stream_.read(&key_string[0], key_size);
Key key;
deserialize(key_string, key);
ObjectEntry entry;
entry.index_in_file = stream_.tellg();
entry.size = data_size;
entry.modified = false;
auto it = objects_.emplace(key, entry).first;
it->second.key = &it->first;
stream_.seekg(data_size, std::ios_base::cur);
}
}
else {
stream_.open(filename, std::ios_base::in | std::ios_base::out |
std::ios_base::binary | std::ios_base::trunc);
}
}
template <class Key>
void ObjectArchive<Key>::set_buffer_size(size_t max_buffer_size) {
max_buffer_size_ = max_buffer_size;
unload(max_buffer_size);
}
template <class Key>
void ObjectArchive<Key>::set_buffer_size(std::string const& max_buffer_size) {
size_t length = max_buffer_size.size();
double buffer_size = atof(max_buffer_size.c_str());
bool changed = false;
for (size_t i = 0; i< length && !changed; i++) {
switch (max_buffer_size[i]) {
case 'k':
case 'K':
buffer_size *= 1e3;
changed = true;
break;
case 'm':
case 'M':
buffer_size *= 1e6;
changed = true;
break;
case 'g':
case 'G':
buffer_size *= 1e9;
changed = true;
break;
}
}
set_buffer_size(buffer_size);
}
#if BOOST_OS_LINUX
#include <sys/sysinfo.h>
template <class Key>
void ObjectArchive<Key>::set_buffer_size_scale(float max_buffer_size) {
struct sysinfo info;
if (sysinfo(&info) == 0) {
unsigned long freeram = info.freeram;
set_buffer_size(freeram * max_buffer_size);
}
}
#endif
template <class Key>
size_t ObjectArchive<Key>::get_max_buffer_size() const {
return max_buffer_size_;
}
template <class Key>
size_t ObjectArchive<Key>::get_buffer_size() const {
return buffer_size_;
}
template <class Key>
void ObjectArchive<Key>::remove(Key const& key) {
if (!is_available(key))
return;
OBJECT_ARCHIVE_MUTEX_GUARD;
auto it = objects_.find(key);
if (it == objects_.end())
return;
ObjectEntry& entry = it->second;
if (entry.data.size())
buffer_size_ -= entry.size;
objects_.erase(key);
LRU_.remove(&entry);
must_rebuild_file_ = true;
}
template <class Key>
template <class T>
size_t ObjectArchive<Key>::insert(Key const& key, T const& obj,
bool keep_in_buffer) {
return insert_raw(key, serialize(obj), keep_in_buffer);
}
template <class Key>
size_t ObjectArchive<Key>::insert_raw(Key const& key, std::string const& data,
bool keep_in_buffer) {
return insert_raw(key, std::string(data), keep_in_buffer);
}
template <class Key>
size_t ObjectArchive<Key>::insert_raw(Key const& key, std::string&& data,
bool keep_in_buffer) {
size_t size = data.size();
if (size > max_buffer_size_)
keep_in_buffer = false;
ObjectArchive<Key>::remove(key);
if (size + buffer_size_ > max_buffer_size_ && keep_in_buffer)
unload(max_buffer_size_ - size);
OBJECT_ARCHIVE_MUTEX_GUARD;
buffer_size_ += size;
ObjectEntry entry;
entry.data.swap(data);
entry.size = size;
entry.modified = true;
auto it = objects_.emplace(key, entry).first;
it->second.key = &it->first;
touch_LRU(&it->second);
if (!keep_in_buffer)
write_back(it);
return size;
}
template <class Key>
template <class T>
size_t ObjectArchive<Key>::load(Key const& key, T& obj, bool keep_in_buffer) {
std::string s;
size_t ret = load_raw(key, s, keep_in_buffer);
if (ret == 0) return 0;
deserialize(s, obj);
return ret;
}
template <class Key>
size_t ObjectArchive<Key>::load_raw(Key const& key, std::string& data,
bool keep_in_buffer) {
if (!is_available(key))
return 0;
OBJECT_ARCHIVE_MUTEX_GUARD;
auto it = objects_.find(key);
if (it == objects_.end())
return 0;
ObjectEntry& entry = it->second;
size_t size = entry.size;
if (size > max_buffer_size_)
keep_in_buffer = false;
// If the result isn't in the buffer, we must read it.
if (entry.data.size() == 0) {
// Only check for size if we have to load.
if (size + buffer_size_ > max_buffer_size_ && keep_in_buffer)
unload(max_buffer_size_ - size);
stream_.seekg(entry.index_in_file);
std::string& buf = entry.data;
buf.resize(size);
stream_.read(&buf[0], size);
buffer_size_ += size;
entry.modified = false;
}
touch_LRU(&entry);
if (!keep_in_buffer) {
if (!entry.modified)
data.swap(entry.data);
else
data = entry.data;
write_back(it);
}
else
data = entry.data;
return size;
}
template <class Key>
void ObjectArchive<Key>::unload(size_t desired_size) {
OBJECT_ARCHIVE_MUTEX_GUARD;
while (buffer_size_ > desired_size)
write_back(*LRU_.back()->key);
}
template <class Key>
bool ObjectArchive<Key>::is_available(Key const& key) {
OBJECT_ARCHIVE_MUTEX_GUARD;
if (objects_.count(key) == 0)
return false;
return true;
}
template <class Key>
std::list<Key const*> ObjectArchive<Key>::available_objects() {
std::list<Key const*> list;
OBJECT_ARCHIVE_MUTEX_GUARD;
for (auto& it : objects_)
list.push_front(it.second.key);
return list;
}
template <class Key>
void ObjectArchive<Key>::flush() {
OBJECT_ARCHIVE_MUTEX_GUARD;
internal_flush();
init(filename_);
}
template <class Key>
void ObjectArchive<Key>::clear() {
OBJECT_ARCHIVE_MUTEX_GUARD;
auto key_list = available_objects();
for (auto& it : key_list)
remove(*it);
flush();
}
template <class Key>
void ObjectArchive<Key>::internal_flush() {
unload();
if (!must_rebuild_file_)
return;
must_rebuild_file_ = false;
boost::filesystem::path temp_filename;
temp_filename = boost::filesystem::temp_directory_path();
temp_filename += '/';
temp_filename += boost::filesystem::unique_path();
std::fstream temp_stream(temp_filename.string(),
std::ios_base::in | std::ios_base::out |
std::ios_base::binary | std::ios_base::trunc);
size_t n_entries = objects_.size();
temp_stream.write((char*)&n_entries, sizeof(size_t));
size_t local_max_buffer_size = (max_buffer_size_ == 0 ? 1 : max_buffer_size_);
char* temp_buffer = new char[local_max_buffer_size];
for (auto& it : objects_) {
ObjectEntry& entry = it.second;
std::string key_str = serialize(it.first);
size_t key_size = key_str.size();
size_t data_size = entry.size;
temp_stream.write((char*)&key_size, sizeof(size_t));
temp_stream.write((char*)&data_size, sizeof(size_t));
temp_stream.write((char*)&key_str[0], key_size);
stream_.seekg(entry.index_in_file);
size_t size = data_size;
// Only uses the allowed buffer memory.
for (;
size > local_max_buffer_size;
size -= local_max_buffer_size) {
stream_.read(temp_buffer, local_max_buffer_size);
temp_stream.write(temp_buffer, local_max_buffer_size);
}
stream_.read(temp_buffer, size);
temp_stream.write(temp_buffer, size);
}
delete[] temp_buffer;
stream_.close();
temp_stream.close();
boost::filesystem::remove(filename_);
boost::filesystem::rename(temp_filename, filename_);
}
template <class Key>
bool ObjectArchive<Key>::write_back(Key const& key) {
auto it = objects_.find(key);
if (it == objects_.end())
return false;
return write_back(it);
}
template <class Key>
bool ObjectArchive<Key>::write_back(
typename std::unordered_map<Key, ObjectEntry>::iterator const& it) {
ObjectEntry& entry = it->second;
if (entry.modified) {
stream_.seekp(0, std::ios_base::end);
entry.index_in_file = stream_.tellp();
stream_.write((char*)&entry.data[0], entry.size);
entry.modified = false;
must_rebuild_file_ = true;
}
entry.data.clear();
buffer_size_ -= entry.size;
LRU_.remove(&entry);
return true;
}
template <class Key>
void ObjectArchive<Key>::touch_LRU(ObjectEntry const* entry) {
LRU_.remove(entry);
LRU_.push_front(entry);
}
#endif
<commit_msg>Fixed another bug with virtual methods and added comment to remember.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 Conrado Miranda
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.
*/
// Each archive has a entries with the following format:
// 1) Number of entries (size_t);
// 2.1) Size of the key (size_t);
// 2.2) Size of the object (size_t);
// 2.3) Key as serialized by boost;
// 2.4) Object as serialized by boost.
#ifndef __OBJECT_ARCHIVE_IMPL_HPP__
#define __OBJECT_ARCHIVE_IMPL_HPP__
#include "object_archive.hpp"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#if ENABLE_THREADS
#define OBJECT_ARCHIVE_MUTEX_GUARD \
boost::lock_guard<boost::recursive_mutex> __mutex_guard(mutex_)
#else
#define OBJECT_ARCHIVE_MUTEX_GUARD do { } while(0)
#endif
template <class Key>
ObjectArchive<Key>::ObjectArchive():
must_rebuild_file_(false),
max_buffer_size_(0),
buffer_size_(0),
temporary_file_(false) {
init();
set_buffer_size(0);
}
template <class Key>
ObjectArchive<Key>::~ObjectArchive() {
OBJECT_ARCHIVE_MUTEX_GUARD;
if (!temporary_file_)
internal_flush();
stream_.close();
if (temporary_file_)
boost::filesystem::remove(filename_);
}
template <class Key>
template <class T>
std::string ObjectArchive<Key>::serialize(T const& val) {
std::stringstream stream;
{
boost::iostreams::filtering_stream<boost::iostreams::output> filtering;
filtering.push(boost::iostreams::zlib_compressor());
filtering.push(stream);
boost::archive::binary_oarchive ofs(filtering);
ofs << val;
}
return stream.str();
}
template <class Key>
template <class T1, class T2>
std::string ObjectArchive<Key>::serialize(T2 const& val) {
std::stringstream stream;
{
boost::iostreams::filtering_stream<boost::iostreams::output> filtering;
filtering.push(boost::iostreams::zlib_compressor());
filtering.push(stream);
boost::archive::binary_oarchive ofs(filtering);
ofs.register_type<T1>();
ofs << val;
}
return stream.str();
}
template <class Key>
template <class T>
void ObjectArchive<Key>::deserialize(std::string const& str, T& val) {
std::stringstream stream(str);
boost::iostreams::filtering_stream<boost::iostreams::input> filtering;
filtering.push(boost::iostreams::zlib_decompressor());
filtering.push(stream);
boost::archive::binary_iarchive ifs(filtering);
ifs >> val;
}
template <class Key>
void ObjectArchive<Key>::init() {
std::string filename;
filename = boost::filesystem::temp_directory_path().string();
filename += '/';
filename += boost::filesystem::unique_path().string();
init(filename, true);
}
template <class Key>
void ObjectArchive<Key>::init(std::string const& filename,
bool temporary_file) {
OBJECT_ARCHIVE_MUTEX_GUARD;
internal_flush();
stream_.close();
if (temporary_file_)
boost::filesystem::remove(filename_);
filename_ = filename;
temporary_file_ = temporary_file;
buffer_size_ = 0;
objects_.clear();
LRU_.clear();
stream_.open(filename, std::ios_base::in | std::ios_base::out |
std::ios_base::binary);
stream_.seekg(0, std::ios_base::end);
// If the file seems ok and has entries, use it. Otherwise, overwrite.
if (stream_.good() && stream_.tellg() > 0) {
stream_.seekg(0);
size_t n_entries;
stream_.read((char*)&n_entries, sizeof(size_t));
for (size_t i = 0; i < n_entries; i++) {
size_t key_size;
size_t data_size;
stream_.read((char*)&key_size, sizeof(size_t));
stream_.read((char*)&data_size, sizeof(size_t));
std::string key_string;
key_string.resize(key_size);
stream_.read(&key_string[0], key_size);
Key key;
deserialize(key_string, key);
ObjectEntry entry;
entry.index_in_file = stream_.tellg();
entry.size = data_size;
entry.modified = false;
auto it = objects_.emplace(key, entry).first;
it->second.key = &it->first;
stream_.seekg(data_size, std::ios_base::cur);
}
}
else {
stream_.open(filename, std::ios_base::in | std::ios_base::out |
std::ios_base::binary | std::ios_base::trunc);
}
}
template <class Key>
void ObjectArchive<Key>::set_buffer_size(size_t max_buffer_size) {
max_buffer_size_ = max_buffer_size;
unload(max_buffer_size);
}
template <class Key>
void ObjectArchive<Key>::set_buffer_size(std::string const& max_buffer_size) {
size_t length = max_buffer_size.size();
double buffer_size = atof(max_buffer_size.c_str());
bool changed = false;
for (size_t i = 0; i< length && !changed; i++) {
switch (max_buffer_size[i]) {
case 'k':
case 'K':
buffer_size *= 1e3;
changed = true;
break;
case 'm':
case 'M':
buffer_size *= 1e6;
changed = true;
break;
case 'g':
case 'G':
buffer_size *= 1e9;
changed = true;
break;
}
}
set_buffer_size(buffer_size);
}
#if BOOST_OS_LINUX
#include <sys/sysinfo.h>
template <class Key>
void ObjectArchive<Key>::set_buffer_size_scale(float max_buffer_size) {
struct sysinfo info;
if (sysinfo(&info) == 0) {
unsigned long freeram = info.freeram;
set_buffer_size(freeram * max_buffer_size);
}
}
#endif
template <class Key>
size_t ObjectArchive<Key>::get_max_buffer_size() const {
return max_buffer_size_;
}
template <class Key>
size_t ObjectArchive<Key>::get_buffer_size() const {
return buffer_size_;
}
template <class Key>
void ObjectArchive<Key>::remove(Key const& key) {
if (!is_available(key))
return;
OBJECT_ARCHIVE_MUTEX_GUARD;
auto it = objects_.find(key);
if (it == objects_.end())
return;
ObjectEntry& entry = it->second;
if (entry.data.size())
buffer_size_ -= entry.size;
objects_.erase(key);
LRU_.remove(&entry);
must_rebuild_file_ = true;
}
template <class Key>
template <class T>
size_t ObjectArchive<Key>::insert(Key const& key, T const& obj,
bool keep_in_buffer) {
return insert_raw(key, serialize(obj), keep_in_buffer);
}
template <class Key>
size_t ObjectArchive<Key>::insert_raw(Key const& key, std::string const& data,
bool keep_in_buffer) {
// Makes sure we call the local method, not its virtualization
return ObjectArchive<Key>::insert_raw(key, std::string(data), keep_in_buffer);
}
template <class Key>
size_t ObjectArchive<Key>::insert_raw(Key const& key, std::string&& data,
bool keep_in_buffer) {
size_t size = data.size();
if (size > max_buffer_size_)
keep_in_buffer = false;
// Makes sure we call the local method, not its virtualization
ObjectArchive<Key>::remove(key);
if (size + buffer_size_ > max_buffer_size_ && keep_in_buffer)
unload(max_buffer_size_ - size);
OBJECT_ARCHIVE_MUTEX_GUARD;
buffer_size_ += size;
ObjectEntry entry;
entry.data.swap(data);
entry.size = size;
entry.modified = true;
auto it = objects_.emplace(key, entry).first;
it->second.key = &it->first;
touch_LRU(&it->second);
if (!keep_in_buffer)
write_back(it);
return size;
}
template <class Key>
template <class T>
size_t ObjectArchive<Key>::load(Key const& key, T& obj, bool keep_in_buffer) {
std::string s;
size_t ret = load_raw(key, s, keep_in_buffer);
if (ret == 0) return 0;
deserialize(s, obj);
return ret;
}
template <class Key>
size_t ObjectArchive<Key>::load_raw(Key const& key, std::string& data,
bool keep_in_buffer) {
if (!is_available(key))
return 0;
OBJECT_ARCHIVE_MUTEX_GUARD;
auto it = objects_.find(key);
if (it == objects_.end())
return 0;
ObjectEntry& entry = it->second;
size_t size = entry.size;
if (size > max_buffer_size_)
keep_in_buffer = false;
// If the result isn't in the buffer, we must read it.
if (entry.data.size() == 0) {
// Only check for size if we have to load.
if (size + buffer_size_ > max_buffer_size_ && keep_in_buffer)
unload(max_buffer_size_ - size);
stream_.seekg(entry.index_in_file);
std::string& buf = entry.data;
buf.resize(size);
stream_.read(&buf[0], size);
buffer_size_ += size;
entry.modified = false;
}
touch_LRU(&entry);
if (!keep_in_buffer) {
if (!entry.modified)
data.swap(entry.data);
else
data = entry.data;
write_back(it);
}
else
data = entry.data;
return size;
}
template <class Key>
void ObjectArchive<Key>::unload(size_t desired_size) {
OBJECT_ARCHIVE_MUTEX_GUARD;
while (buffer_size_ > desired_size)
write_back(*LRU_.back()->key);
}
template <class Key>
bool ObjectArchive<Key>::is_available(Key const& key) {
OBJECT_ARCHIVE_MUTEX_GUARD;
if (objects_.count(key) == 0)
return false;
return true;
}
template <class Key>
std::list<Key const*> ObjectArchive<Key>::available_objects() {
std::list<Key const*> list;
OBJECT_ARCHIVE_MUTEX_GUARD;
for (auto& it : objects_)
list.push_front(it.second.key);
return list;
}
template <class Key>
void ObjectArchive<Key>::flush() {
OBJECT_ARCHIVE_MUTEX_GUARD;
internal_flush();
init(filename_);
}
template <class Key>
void ObjectArchive<Key>::clear() {
OBJECT_ARCHIVE_MUTEX_GUARD;
auto key_list = available_objects();
for (auto& it : key_list)
remove(*it);
flush();
}
template <class Key>
void ObjectArchive<Key>::internal_flush() {
unload();
if (!must_rebuild_file_)
return;
must_rebuild_file_ = false;
boost::filesystem::path temp_filename;
temp_filename = boost::filesystem::temp_directory_path();
temp_filename += '/';
temp_filename += boost::filesystem::unique_path();
std::fstream temp_stream(temp_filename.string(),
std::ios_base::in | std::ios_base::out |
std::ios_base::binary | std::ios_base::trunc);
size_t n_entries = objects_.size();
temp_stream.write((char*)&n_entries, sizeof(size_t));
size_t local_max_buffer_size = (max_buffer_size_ == 0 ? 1 : max_buffer_size_);
char* temp_buffer = new char[local_max_buffer_size];
for (auto& it : objects_) {
ObjectEntry& entry = it.second;
std::string key_str = serialize(it.first);
size_t key_size = key_str.size();
size_t data_size = entry.size;
temp_stream.write((char*)&key_size, sizeof(size_t));
temp_stream.write((char*)&data_size, sizeof(size_t));
temp_stream.write((char*)&key_str[0], key_size);
stream_.seekg(entry.index_in_file);
size_t size = data_size;
// Only uses the allowed buffer memory.
for (;
size > local_max_buffer_size;
size -= local_max_buffer_size) {
stream_.read(temp_buffer, local_max_buffer_size);
temp_stream.write(temp_buffer, local_max_buffer_size);
}
stream_.read(temp_buffer, size);
temp_stream.write(temp_buffer, size);
}
delete[] temp_buffer;
stream_.close();
temp_stream.close();
boost::filesystem::remove(filename_);
boost::filesystem::rename(temp_filename, filename_);
}
template <class Key>
bool ObjectArchive<Key>::write_back(Key const& key) {
auto it = objects_.find(key);
if (it == objects_.end())
return false;
return write_back(it);
}
template <class Key>
bool ObjectArchive<Key>::write_back(
typename std::unordered_map<Key, ObjectEntry>::iterator const& it) {
ObjectEntry& entry = it->second;
if (entry.modified) {
stream_.seekp(0, std::ios_base::end);
entry.index_in_file = stream_.tellp();
stream_.write((char*)&entry.data[0], entry.size);
entry.modified = false;
must_rebuild_file_ = true;
}
entry.data.clear();
buffer_size_ -= entry.size;
LRU_.remove(&entry);
return true;
}
template <class Key>
void ObjectArchive<Key>::touch_LRU(ObjectEntry const* entry) {
LRU_.remove(entry);
LRU_.push_front(entry);
}
#endif
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <memory>
#include <cstdlib>
#include <assert.h>
#include <type_traits>
namespace seastar {
/// \addtogroup memory-module
/// @{
/// Provides a mechanism for managing the lifetime of a buffer.
///
/// A \c deleter is an object that is used to inform the consumer
/// of some buffer (not referenced by the deleter itself) how to
/// delete the buffer. This can be by calling an arbitrary function
/// or destroying an object carried by the deleter. Examples of
/// a deleter's encapsulated actions are:
///
/// - calling \c std::free(p) on some captured pointer, p
/// - calling \c delete \c p on some captured pointer, p
/// - decrementing a reference count somewhere
///
/// A deleter performs its action from its destructor.
class deleter final {
public:
/// \cond internal
struct impl;
struct raw_object_tag {};
/// \endcond
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
/// Constructs an empty deleter that does nothing in its destructor.
deleter() = default;
deleter(const deleter&) = delete;
/// Moves a deleter.
deleter(deleter&& x) noexcept : _impl(x._impl) { x._impl = nullptr; }
/// \cond internal
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
/// \endcond
/// Destroys the deleter and carries out the encapsulated action.
~deleter();
deleter& operator=(deleter&& x) noexcept;
deleter& operator=(deleter&) = delete;
/// Performs a sharing operation. The encapsulated action will only
/// be carried out after both the original deleter and the returned
/// deleter are both destroyed.
///
/// \return a deleter with the same encapsulated action as this one.
deleter share();
/// Checks whether the deleter has an associated action.
explicit operator bool() const { return bool(_impl); }
/// \cond internal
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
/// \endcond
/// Appends another deleter to this deleter. When this deleter is
/// destroyed, both encapsulated actions will be carried out.
void append(deleter d);
private:
static bool is_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
/// \cond internal
struct deleter::impl {
unsigned refs = 1;
deleter next;
impl(deleter next) : next(std::move(next)) {}
virtual ~impl() {}
};
/// \endcond
inline
deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline
deleter& deleter::operator=(deleter&& x) noexcept {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
/// \cond internal
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
virtual ~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
inline
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
/// \endcond
/// Makes a \ref deleter that encapsulates the action of
/// destroying an object, as well as running another deleter. The input
/// object is moved to the deleter, and destroyed when the deleter is destroyed.
///
/// \param d deleter that will become part of the new deleter's encapsulated action
/// \param o object whose destructor becomes part of the new deleter's encapsulated action
/// \related deleter
template <typename Object>
deleter
make_deleter(deleter next, Object o) {
return deleter(new lambda_deleter_impl<Object>(std::move(next), std::move(o)));
}
/// Makes a \ref deleter that encapsulates the action of destroying an object. The input
/// object is moved to the deleter, and destroyed when the deleter is destroyed.
///
/// \param o object whose destructor becomes the new deleter's encapsulated action
/// \related deleter
template <typename Object>
deleter
make_deleter(Object o) {
return make_deleter(deleter(), std::move(o));
}
/// \cond internal
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
virtual ~free_deleter_impl() override { std::free(obj); }
};
/// \endcond
inline
deleter
deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline
void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
if (next_impl == d._impl) {
return; // Already appended
}
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(deleter(next_impl), std::move(d));
return;
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
/// Makes a deleter that calls \c std::free() when it is destroyed.
///
/// \param obj object to free.
/// \related deleter
inline
deleter
make_free_deleter(void* obj) {
if (!obj) {
return deleter();
}
return deleter(deleter::raw_object_tag(), obj);
}
/// Makes a deleter that calls \c std::free() when it is destroyed, as well
/// as invoking the encapsulated action of another deleter.
///
/// \param d deleter to invoke.
/// \param obj object to free.
/// \related deleter
inline
deleter
make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
/// \see make_deleter(Object)
/// \related deleter
template <typename T>
inline
deleter
make_object_deleter(T&& obj) {
return deleter{make_object_deleter_impl(deleter(), std::move(obj))};
}
/// \see make_deleter(deleter, Object)
/// \related deleter
template <typename T>
inline
deleter
make_object_deleter(deleter d, T&& obj) {
return deleter{make_object_deleter_impl(std::move(d), std::move(obj))};
}
/// @}
}
<commit_msg>deleter: mark non-throwing methods as noexcept<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <memory>
#include <cstdlib>
#include <assert.h>
#include <type_traits>
namespace seastar {
/// \addtogroup memory-module
/// @{
/// Provides a mechanism for managing the lifetime of a buffer.
///
/// A \c deleter is an object that is used to inform the consumer
/// of some buffer (not referenced by the deleter itself) how to
/// delete the buffer. This can be by calling an arbitrary function
/// or destroying an object carried by the deleter. Examples of
/// a deleter's encapsulated actions are:
///
/// - calling \c std::free(p) on some captured pointer, p
/// - calling \c delete \c p on some captured pointer, p
/// - decrementing a reference count somewhere
///
/// A deleter performs its action from its destructor.
class deleter final {
public:
/// \cond internal
struct impl;
struct raw_object_tag {};
/// \endcond
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
/// Constructs an empty deleter that does nothing in its destructor.
deleter() = default;
deleter(const deleter&) = delete;
/// Moves a deleter.
deleter(deleter&& x) noexcept : _impl(x._impl) { x._impl = nullptr; }
/// \cond internal
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
/// \endcond
/// Destroys the deleter and carries out the encapsulated action.
~deleter();
deleter& operator=(deleter&& x) noexcept;
deleter& operator=(deleter&) = delete;
/// Performs a sharing operation. The encapsulated action will only
/// be carried out after both the original deleter and the returned
/// deleter are both destroyed.
///
/// \return a deleter with the same encapsulated action as this one.
deleter share();
/// Checks whether the deleter has an associated action.
explicit operator bool() const noexcept { return bool(_impl); }
/// \cond internal
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
/// \endcond
/// Appends another deleter to this deleter. When this deleter is
/// destroyed, both encapsulated actions will be carried out.
void append(deleter d);
private:
static bool is_raw_object(impl* i) noexcept {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const noexcept {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) noexcept {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const noexcept {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) noexcept {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
/// \cond internal
struct deleter::impl {
unsigned refs = 1;
deleter next;
impl(deleter next) : next(std::move(next)) {}
virtual ~impl() {}
};
/// \endcond
inline
deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline
deleter& deleter::operator=(deleter&& x) noexcept {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
/// \cond internal
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
virtual ~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
inline
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
/// \endcond
/// Makes a \ref deleter that encapsulates the action of
/// destroying an object, as well as running another deleter. The input
/// object is moved to the deleter, and destroyed when the deleter is destroyed.
///
/// \param d deleter that will become part of the new deleter's encapsulated action
/// \param o object whose destructor becomes part of the new deleter's encapsulated action
/// \related deleter
template <typename Object>
deleter
make_deleter(deleter next, Object o) {
return deleter(new lambda_deleter_impl<Object>(std::move(next), std::move(o)));
}
/// Makes a \ref deleter that encapsulates the action of destroying an object. The input
/// object is moved to the deleter, and destroyed when the deleter is destroyed.
///
/// \param o object whose destructor becomes the new deleter's encapsulated action
/// \related deleter
template <typename Object>
deleter
make_deleter(Object o) {
return make_deleter(deleter(), std::move(o));
}
/// \cond internal
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
virtual ~free_deleter_impl() override { std::free(obj); }
};
/// \endcond
inline
deleter
deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline
void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
if (next_impl == d._impl) {
return; // Already appended
}
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(deleter(next_impl), std::move(d));
return;
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
/// Makes a deleter that calls \c std::free() when it is destroyed.
///
/// \param obj object to free.
/// \related deleter
inline
deleter
make_free_deleter(void* obj) {
if (!obj) {
return deleter();
}
return deleter(deleter::raw_object_tag(), obj);
}
/// Makes a deleter that calls \c std::free() when it is destroyed, as well
/// as invoking the encapsulated action of another deleter.
///
/// \param d deleter to invoke.
/// \param obj object to free.
/// \related deleter
inline
deleter
make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
/// \see make_deleter(Object)
/// \related deleter
template <typename T>
inline
deleter
make_object_deleter(T&& obj) {
return deleter{make_object_deleter_impl(deleter(), std::move(obj))};
}
/// \see make_deleter(deleter, Object)
/// \related deleter
template <typename T>
inline
deleter
make_object_deleter(deleter d, T&& obj) {
return deleter{make_object_deleter_impl(std::move(d), std::move(obj))};
}
/// @}
}
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_INTERNAL_WINDOWS_DIRENT_HPP__
#define __STOUT_INTERNAL_WINDOWS_DIRENT_HPP__
#include <assert.h>
#include <malloc.h>
#include <stout/windows.hpp>
// Abbreviated version of the POSIX `dirent` struct. cf. specification[1].
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
struct dirent
{
char d_name[MAX_PATH];
unsigned short d_namlen;
};
// `DIR` is normally an opaque struct in the standard, we expose the
// implementation here because this header is intended for internal use only.
struct DIR
{
struct dirent curr;
char *d_name;
WIN32_FIND_DATA fd;
HANDLE handle;
};
// Avoid the C++-style name-mangling linkage, and use C-style instead to give
// the appearance that this code is part of the real C standard library.
extern "C" {
namespace internal {
void free_dir(DIR* directory);
bool open_dir_stream(DIR* directory);
bool reentrant_advance_dir_stream(DIR* directory);
} // namespace internal {
// Windows implementation of POSIX standard `opendir`. cf. specification[1].
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Opening-a-Directory.html#Opening-a-Directory
inline DIR* opendir(const char* path)
{
if (path == nullptr) {
errno = ENOTDIR;
return nullptr;
}
const size_t path_size = strlen(path);
if (path_size == 0 || path_size >= MAX_PATH) {
errno = ENOENT;
return nullptr;
}
const char windows_folder_separator = '\\';
const char windows_drive_separator = ':';
const char wildcard[] = "*";
const char dir_separator_and_wildcard[] = "\\*";
// Allocate space for directory. Be sure to leave room at the end of
// `directory->d_name` for a directory separator and a wildcard.
DIR* directory = (DIR*) malloc(sizeof(DIR));
if (directory == nullptr) {
errno = ENOMEM;
return nullptr;
}
directory->d_name =
(char*) malloc(path_size + strlen(dir_separator_and_wildcard) + 1);
if (directory->d_name == nullptr) {
errno = ENOMEM;
free(directory);
return nullptr;
}
// Copy path over and append the appropriate postfix.
strcpy(directory->d_name, path);
const size_t last_char_in_name =
directory->d_name[strlen(directory->d_name) - 1];
if (last_char_in_name != windows_folder_separator &&
last_char_in_name != windows_drive_separator) {
strcat(directory->d_name, dir_separator_and_wildcard);
} else {
strcat(directory->d_name, wildcard);
}
if (!internal::open_dir_stream(directory)) {
internal::free_dir(directory);
return nullptr;
}
return directory;
}
// Implementation of the standard POSIX function. See documentation[1].
//
// On success: returns a pointer to the next directory entry, or `nullptr` if
// we've reached the end of the stream.
//
// On failure: returns `nullptr` and sets `errno`.
//
// NOTE: as with most POSIX implementations of this function, you must reset
// `errno` before calling `readdir`.
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html#Reading_002fClosing-Directory
inline struct dirent* readdir(DIR* directory)
{
if (directory == nullptr) {
errno = EBADF;
return nullptr;
}
if (!internal::reentrant_advance_dir_stream(directory)) {
return nullptr;
}
return &directory->curr;
}
// Implementation of the standard POSIX function. See documentation[1].
//
// On success, return 0; on failure, return -1 and set `errno` appropriately.
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html#Reading_002fClosing-Directory
inline int closedir(DIR* directory)
{
if (directory == nullptr) {
errno = EBADF;
return -1;
}
BOOL search_closed = false;
if (directory->handle != INVALID_HANDLE_VALUE) {
search_closed = FindClose(directory->handle);
}
internal::free_dir(directory);
return search_closed ? 0 : -1;
}
namespace internal {
inline void free_dir(DIR* directory)
{
if (directory != nullptr) {
free(directory->d_name);
}
free(directory);
}
inline bool open_dir_stream(DIR* directory)
{
assert(directory != nullptr);
directory->handle = FindFirstFile(directory->d_name, &directory->fd);
if (directory->handle == INVALID_HANDLE_VALUE) {
errno = ENOENT;
return false;
}
// NOTE: `d_name` can be a statically-sized array of `MAX_PATH` size because
// `cFileName` is. See[1]. This simplifies this copy operation because we
// don't have to `malloc`.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365740(v=vs.85).aspx
strcpy(directory->curr.d_name, directory->fd.cFileName);
directory->curr.d_namlen = strlen(directory->curr.d_name);
return true;
}
inline bool reentrant_advance_dir_stream(DIR* directory)
{
assert(directory != nullptr);
if (!FindNextFile(directory->handle, &directory->fd)) {
return false;
}
// NOTE: `d_name` can be a statically-sized array of `MAX_PATH` size because
// `cFileName` is. See[1]. This simplifies this copy operation because we
// don't have to `malloc`.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365740(v=vs.85).aspx
strcpy(directory->curr.d_name, directory->fd.cFileName);
directory->curr.d_namlen = strlen(directory->curr.d_name);
return true;
}
} // namespace internal {
} // extern "C" {
#endif // __STOUT_INTERNAL_WINDOWS_DIRENT_HPP__
<commit_msg>Windows: Fixed implicit cast warning in dirent.hpp.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_INTERNAL_WINDOWS_DIRENT_HPP__
#define __STOUT_INTERNAL_WINDOWS_DIRENT_HPP__
#include <assert.h>
#include <malloc.h>
#include <stout/windows.hpp>
// Abbreviated version of the POSIX `dirent` struct. cf. specification[1].
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
struct dirent
{
char d_name[MAX_PATH];
unsigned short d_namlen;
};
// `DIR` is normally an opaque struct in the standard, we expose the
// implementation here because this header is intended for internal use only.
struct DIR
{
struct dirent curr;
char *d_name;
WIN32_FIND_DATA fd;
HANDLE handle;
};
// Avoid the C++-style name-mangling linkage, and use C-style instead to give
// the appearance that this code is part of the real C standard library.
extern "C" {
namespace internal {
void free_dir(DIR* directory);
bool open_dir_stream(DIR* directory);
bool reentrant_advance_dir_stream(DIR* directory);
} // namespace internal {
// Windows implementation of POSIX standard `opendir`. cf. specification[1].
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Opening-a-Directory.html#Opening-a-Directory
inline DIR* opendir(const char* path)
{
if (path == nullptr) {
errno = ENOTDIR;
return nullptr;
}
const size_t path_size = strlen(path);
if (path_size == 0 || path_size >= MAX_PATH) {
errno = ENOENT;
return nullptr;
}
const char windows_folder_separator = '\\';
const char windows_drive_separator = ':';
const char wildcard[] = "*";
const char dir_separator_and_wildcard[] = "\\*";
// Allocate space for directory. Be sure to leave room at the end of
// `directory->d_name` for a directory separator and a wildcard.
DIR* directory = (DIR*) malloc(sizeof(DIR));
if (directory == nullptr) {
errno = ENOMEM;
return nullptr;
}
directory->d_name =
(char*) malloc(path_size + strlen(dir_separator_and_wildcard) + 1);
if (directory->d_name == nullptr) {
errno = ENOMEM;
free(directory);
return nullptr;
}
// Copy path over and append the appropriate postfix.
strcpy(directory->d_name, path);
const size_t last_char_in_name =
directory->d_name[strlen(directory->d_name) - 1];
if (last_char_in_name != windows_folder_separator &&
last_char_in_name != windows_drive_separator) {
strcat(directory->d_name, dir_separator_and_wildcard);
} else {
strcat(directory->d_name, wildcard);
}
if (!internal::open_dir_stream(directory)) {
internal::free_dir(directory);
return nullptr;
}
return directory;
}
// Implementation of the standard POSIX function. See documentation[1].
//
// On success: returns a pointer to the next directory entry, or `nullptr` if
// we've reached the end of the stream.
//
// On failure: returns `nullptr` and sets `errno`.
//
// NOTE: as with most POSIX implementations of this function, you must reset
// `errno` before calling `readdir`.
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html#Reading_002fClosing-Directory
inline struct dirent* readdir(DIR* directory)
{
if (directory == nullptr) {
errno = EBADF;
return nullptr;
}
if (!internal::reentrant_advance_dir_stream(directory)) {
return nullptr;
}
return &directory->curr;
}
// Implementation of the standard POSIX function. See documentation[1].
//
// On success, return 0; on failure, return -1 and set `errno` appropriately.
//
// [1] http://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html#Reading_002fClosing-Directory
inline int closedir(DIR* directory)
{
if (directory == nullptr) {
errno = EBADF;
return -1;
}
BOOL search_closed = false;
if (directory->handle != INVALID_HANDLE_VALUE) {
search_closed = FindClose(directory->handle);
}
internal::free_dir(directory);
return search_closed ? 0 : -1;
}
namespace internal {
inline void free_dir(DIR* directory)
{
if (directory != nullptr) {
free(directory->d_name);
}
free(directory);
}
inline bool open_dir_stream(DIR* directory)
{
assert(directory != nullptr);
directory->handle = FindFirstFile(directory->d_name, &directory->fd);
if (directory->handle == INVALID_HANDLE_VALUE) {
errno = ENOENT;
return false;
}
// NOTE: `d_name` can be a statically-sized array of `MAX_PATH` size because
// `cFileName` is. See[1]. This simplifies this copy operation because we
// don't have to `malloc`.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365740(v=vs.85).aspx
strcpy(directory->curr.d_name, directory->fd.cFileName);
directory->curr.d_namlen =
static_cast<unsigned short>(strlen(directory->curr.d_name));
return true;
}
inline bool reentrant_advance_dir_stream(DIR* directory)
{
assert(directory != nullptr);
if (!FindNextFile(directory->handle, &directory->fd)) {
return false;
}
// NOTE: `d_name` can be a statically-sized array of `MAX_PATH` size because
// `cFileName` is. See[1]. This simplifies this copy operation because we
// don't have to `malloc`.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365740(v=vs.85).aspx
strcpy(directory->curr.d_name, directory->fd.cFileName);
directory->curr.d_namlen =
static_cast<unsigned short>(strlen(directory->curr.d_name));
return true;
}
} // namespace internal {
} // extern "C" {
#endif // __STOUT_INTERNAL_WINDOWS_DIRENT_HPP__
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <algorithm>
#include <stdlib.h>
#include <Context.h>
#include <FS.h>
#include <test.h>
Context context;
int main (int argc, char** argv)
{
UnitTest t (108);
// Ensure environment has no influence.
unsetenv ("TASKDATA");
unsetenv ("TASKRC");
// Path ();
Path p0;
t.is (p0._data, "", "Path::Path");
// Path (const Path&);
Path p1 = Path ("foo");
t.is (p1._data, Directory::cwd () + "/foo", "Path::operator=");
// Path (const std::string&);
Path p2 ("~");
t.ok (p2._data != "~", "~ expanded to " + p2._data);
Path p3 ("/tmp");
t.ok (p3._data == "/tmp", "/tmp -> /tmp");
// Path& operator= (const Path&);
Path p3_copy (p3);
t.is (p3._data, p3_copy._data, "Path::Path (Path&)");
// operator (std::string) const;
t.is ((std::string) p3, "/tmp", "Path::operator (std::string) const");
// std::string name () const;
Path p4 ("/a/b/c/file.ext");
t.is (p4.name (), "file.ext", "/a/b/c/file.ext name is file.ext");
// std::string parent () const;
t.is (p4.parent (), "/a/b/c", "/a/b/c/file.ext parent is /a/b/c");
// std::string extension () const;
t.is (p4.extension (), "ext", "/a/b/c/file.ext extension is ext");
// bool exists () const;
t.ok (p2.exists (), "~ exists");
t.ok (p3.exists (), "/tmp exists");
// bool is_directory () const;
t.ok (p2.is_directory (), "~ is_directory");
t.ok (p3.is_directory (), "/tmp is_directory");
// bool readable () const;
t.ok (p2.readable (), "~ readable");
t.ok (p3.readable (), "/tmp readable");
// bool writable () const;
t.ok (p2.writable (), "~ writable");
t.ok (p3.writable (), "/tmp writable");
// bool executable () const;
t.ok (p2.executable (), "~ executable");
t.ok (p3.executable (), "/tmp executable");
// static std::string expand (const std::string&);
t.ok (Path::expand ("~") != "~", "Path::expand ~ != ~");
t.ok (Path::expand ("~/") != "~/", "Path::expand ~/ != ~/");
// static std::vector <std::string> glob (const std::string&);
std::vector <std::string> out = Path::glob ("/tmp");
t.ok (out.size () == 1, "/tmp -> 1 result");
t.is (out[0], "/tmp", "/tmp -> /tmp");
out = Path::glob ("/t?p");
t.ok (out.size () == 1, "/t?p -> 1 result");
t.is (out[0], "/tmp", "/t?p -> /tmp");
out = Path::glob ("/[s-u]mp");
t.ok (out.size () == 1, "/[s-u]mp -> 1 result");
t.is (out[0], "/tmp", "/[s-u]mp -> /tmp");
// bool is_absolute () const;
t.notok (p0.is_absolute (), "'' !is_absolute");
t.ok (p1.is_absolute (), "foo is_absolute");
t.ok (p2.is_absolute (), "~ is_absolute (after expansion)");
t.ok (p3.is_absolute (), "/tmp is_absolute");
t.ok (p4.is_absolute (), "/a/b/c/file.ext is_absolute");
Directory tmp ("tmp");
tmp.create ();
t.ok (tmp.exists (), "tmp dir created.");
File::write ("tmp/file.t.txt", "This is a test\n");
File f6 ("tmp/file.t.txt");
t.ok (f6.size () == 15, "File::size tmp/file.t.txt good");
t.ok (f6.mode () & S_IRUSR, "File::mode tmp/file.t.txt good");
t.ok (File::remove ("tmp/file.t.txt"), "File::remove tmp/file.t.txt good");
// operator (std::string) const;
t.is ((std::string) f6, Directory::cwd () + "/tmp/file.t.txt", "File::operator (std::string) const");
t.ok (File::create ("tmp/file.t.create"), "File::create tmp/file.t.create good");
t.ok (File::remove ("tmp/file.t.create"), "File::remove tmp/file.t.create good");
// basename (std::string) const;
t.is (f6.name (), "file.t.txt", "File::basename tmp/file.t.txt --> file.t.txt");
// dirname (std::string) const;
t.is (f6.parent (), Directory::cwd () + "/tmp", "File::dirname tmp/file.t.txt --> tmp");
// bool rename (const std::string&);
File f7 ("tmp/file.t.2.txt");
f7.append ("something\n");
f7.close ();
t.ok (f7.rename ("tmp/file.t.3.txt"), "File::rename did not fail");
t.is (f7._data, Directory::cwd () + "/tmp/file.t.3.txt", "File::rename stored new name");
t.ok (f7.exists (), "File::rename new file exists");
t.ok (f7.remove (), "File::remove tmp/file.t.3.txt good");
t.notok (f7.exists (), "File::remove new file no longer exists");
// Test permissions.
File f8 ("tmp/file.t.perm.txt");
f8.create (0744);
t.ok (f8.exists (), "File::create perm file exists");
mode_t m = f8.mode ();
t.ok (m & S_IFREG, "File::mode tmp/file.t.perm.txt S_IFREG good");
t.ok (m & S_IRUSR, "File::mode tmp/file.t.perm.txt r-------- good");
t.ok (m & S_IWUSR, "File::mode tmp/file.t.perm.txt -w------- good");
t.ok (m & S_IXUSR, "File::mode tmp/file.t.perm.txt --x------ good");
t.ok (m & S_IRGRP, "File::mode tmp/file.t.perm.txt ---r----- good");
t.notok (m & S_IWGRP, "File::mode tmp/file.t.perm.txt ----w---- good");
t.notok (m & S_IXGRP, "File::mode tmp/file.t.perm.txt -----x--- good");
t.ok (m & S_IROTH, "File::mode tmp/file.t.perm.txt ------r-- good");
t.notok (m & S_IWOTH, "File::mode tmp/file.t.perm.txt -------w- good");
t.notok (m & S_IXOTH, "File::mode tmp/file.t.perm.txt --------x good");
f8.remove ();
t.notok (f8.exists (), "File::remove perm file no longer exists");
tmp.remove ();
t.notok (tmp.exists (), "tmp dir removed.");
tmp.create ();
t.ok (tmp.exists (), "tmp dir created.");
// Directory (const File&);
// Directory (const Path&);
Directory d0 (Path ("tmp"));
Directory d1 (File ("tmp"));
Directory d2 (File (Path ("tmp")));
t.is (d0._data, d1._data, "Directory(std::string) == Directory (File&)");
t.is (d0._data, d2._data, "Directory(std::string) == Directory (File (Path &))");
t.is (d1._data, d2._data, "Directory(File&)) == Directory (File (Path &))");
// Directory (const Directory&);
Directory d3 (d2);
t.is (d3._data, Directory::cwd () + "/tmp", "Directory (Directory&)");
// Directory (const std::string&);
Directory d4 ("tmp/test_directory");
// Directory& operator= (const Directory&);
Directory d5 = d4;
t.is (d5._data, Directory::cwd () + "/tmp/test_directory", "Directory::operator=");
// operator (std::string) const;
t.is ((std::string) d3, Directory::cwd () + "/tmp", "Directory::operator (std::string) const");
// virtual bool create ();
t.ok (d5.create (), "Directory::create tmp/test_directory");
t.ok (d5.exists (), "Directory::exists tmp/test_directory");
Directory d6 (d5._data + "/dir");
t.ok (d6.create (), "Directory::create tmp/test_directory/dir");
File::create (d5._data + "/f0");
File::create (d6._data + "/f1");
// std::vector <std::string> list ();
std::vector <std::string> files = d5.list ();
std::sort (files.begin (), files.end ());
t.is ((int)files.size (), 2, "Directory::list 1 file");
t.is (files[0], Directory::cwd () + "/tmp/test_directory/dir", "file[0] is tmp/test_directory/dir");
t.is (files[1], Directory::cwd () + "/tmp/test_directory/f0", "file[1] is tmp/test_directory/f0");
// std::vector <std::string> listRecursive ();
files = d5.listRecursive ();
std::sort (files.begin (), files.end ());
t.is ((int)files.size (), 2, "Directory::list 1 file");
t.is (files[0], Directory::cwd () + "/tmp/test_directory/dir/f1", "file is tmp/test_directory/dir/f1");
t.is (files[1], Directory::cwd () + "/tmp/test_directory/f0", "file is tmp/test_directory/f0");
// virtual bool remove ();
t.ok (File::remove (d5._data + "/f0"), "File::remove tmp/test_directory/f0");
t.ok (File::remove (d6._data + "/f1"), "File::remove tmp/test_directory/dir/f1");
t.ok (d6.remove (), "Directory::remove tmp/test_directory/dir");
t.notok (d6.exists (), "Directory::exists tmp/test_directory/dir - no");
t.ok (d5.remove (), "Directory::remove tmp/test_directory");
t.notok (d5.exists (), "Directory::exists tmp/test_directory - no");
// bool remove (const std::string&);
Directory d7 ("tmp/to_be_removed");
t.ok (d7.create (), "Directory::create tmp/to_be_removed");
File::create (d7._data + "/f0");
Directory d8 (d7._data + "/another");
t.ok (d8.create (), "Directory::create tmp/to_be_removed/another");
File::create (d8._data + "/f1");
t.ok (d7.remove (), "Directory::remove tmp/to_be_removed");
t.notok (d7.exists (), "Directory tmp/to_be_removed gone");
// static std::string cwd ();
std::string cwd = Directory::cwd ();
t.ok (cwd.length () > 0, "Directory::cwd returned a value");
// bool parent (std::string&) const;
Directory d9 ("/one/two/three/four.txt");
t.ok (d9.up (), "parent /one/two/three/four.txt --> true");
t.is (d9._data, "/one/two/three", "parent /one/two/three/four.txt --> /one/two/three");
t.ok (d9.up (), "parent /one/two/three --> true");
t.is (d9._data, "/one/two", "parent /one/two/three --> /one/two");
t.ok (d9.up (), "parent /one/two --> true");
t.is (d9._data, "/one", "parent /one/two --> /one");
t.ok (d9.up (), "parent /one --> true");
t.is (d9._data, "/", "parent /one --> /");
t.notok (d9.up (), "parent / --> false");
// Test permissions.
umask (0022);
Directory d10 ("tmp/dir.perm");
d10.create (0750);
t.ok (d10.exists (), "Directory::create perm file exists");
m = d10.mode ();
t.ok (m & S_IFDIR, "Directory::mode tmp/dir.perm S_IFDIR good");
t.ok (m & S_IRUSR, "Directory::mode tmp/dir.perm r-------- good");
t.ok (m & S_IWUSR, "Directory::mode tmp/dir.perm -w------- good");
t.ok (m & S_IXUSR, "Directory::mode tmp/dir.perm --x------ good");
t.ok (m & S_IRGRP, "Directory::mode tmp/dir.perm ---r----- good");
t.notok (m & S_IWGRP, "Directory::mode tmp/dir.perm ----w---- good");
t.ok (m & S_IXGRP, "Directory::mode tmp/dir.perm -----x--- good");
t.notok (m & S_IROTH, "Directory::mode tmp/dir.perm ------r-- good");
t.notok (m & S_IWOTH, "Directory::mode tmp/dir.perm -------w- good");
t.notok (m & S_IXOTH, "Directory::mode tmp/dir.perm --------x good");
d10.remove ();
t.notok (d10.exists (), "Directory::remove temp/dir.perm file no longer exists");
tmp.remove ();
t.notok (tmp.exists (), "tmp dir removed.");
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Test: Added Path::is_link test<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <algorithm>
#include <stdlib.h>
#include <Context.h>
#include <FS.h>
#include <test.h>
Context context;
int main (int argc, char** argv)
{
UnitTest t (110);
// Ensure environment has no influence.
unsetenv ("TASKDATA");
unsetenv ("TASKRC");
// Path ();
Path p0;
t.is (p0._data, "", "Path::Path");
// Path (const Path&);
Path p1 = Path ("foo");
t.is (p1._data, Directory::cwd () + "/foo", "Path::operator=");
// Path (const std::string&);
Path p2 ("~");
t.ok (p2._data != "~", "~ expanded to " + p2._data);
Path p3 ("/tmp");
t.ok (p3._data == "/tmp", "/tmp -> /tmp");
// operator==
t.notok (p2 == p3, "p2 != p3");
// Path& operator= (const Path&);
Path p3_copy (p3);
t.is (p3._data, p3_copy._data, "Path::Path (Path&)");
// operator (std::string) const;
t.is ((std::string) p3, "/tmp", "Path::operator (std::string) const");
// std::string name () const;
Path p4 ("/a/b/c/file.ext");
t.is (p4.name (), "file.ext", "/a/b/c/file.ext name is file.ext");
// std::string parent () const;
t.is (p4.parent (), "/a/b/c", "/a/b/c/file.ext parent is /a/b/c");
// std::string extension () const;
t.is (p4.extension (), "ext", "/a/b/c/file.ext extension is ext");
// bool exists () const;
t.ok (p2.exists (), "~ exists");
t.ok (p3.exists (), "/tmp exists");
// bool is_directory () const;
t.ok (p2.is_directory (), "~ is_directory");
t.ok (p3.is_directory (), "/tmp is_directory");
// bool is_link () const;
t.notok (p2.is_link (), "~ !is_link");
// bool readable () const;
t.ok (p2.readable (), "~ readable");
t.ok (p3.readable (), "/tmp readable");
// bool writable () const;
t.ok (p2.writable (), "~ writable");
t.ok (p3.writable (), "/tmp writable");
// bool executable () const;
t.ok (p2.executable (), "~ executable");
t.ok (p3.executable (), "/tmp executable");
// static std::string expand (const std::string&);
t.ok (Path::expand ("~") != "~", "Path::expand ~ != ~");
t.ok (Path::expand ("~/") != "~/", "Path::expand ~/ != ~/");
// static std::vector <std::string> glob (const std::string&);
std::vector <std::string> out = Path::glob ("/tmp");
t.ok (out.size () == 1, "/tmp -> 1 result");
t.is (out[0], "/tmp", "/tmp -> /tmp");
out = Path::glob ("/t?p");
t.ok (out.size () == 1, "/t?p -> 1 result");
t.is (out[0], "/tmp", "/t?p -> /tmp");
out = Path::glob ("/[s-u]mp");
t.ok (out.size () == 1, "/[s-u]mp -> 1 result");
t.is (out[0], "/tmp", "/[s-u]mp -> /tmp");
// bool is_absolute () const;
t.notok (p0.is_absolute (), "'' !is_absolute");
t.ok (p1.is_absolute (), "foo is_absolute");
t.ok (p2.is_absolute (), "~ is_absolute (after expansion)");
t.ok (p3.is_absolute (), "/tmp is_absolute");
t.ok (p4.is_absolute (), "/a/b/c/file.ext is_absolute");
Directory tmp ("tmp");
tmp.create ();
t.ok (tmp.exists (), "tmp dir created.");
File::write ("tmp/file.t.txt", "This is a test\n");
File f6 ("tmp/file.t.txt");
t.ok (f6.size () == 15, "File::size tmp/file.t.txt good");
t.ok (f6.mode () & S_IRUSR, "File::mode tmp/file.t.txt good");
t.ok (File::remove ("tmp/file.t.txt"), "File::remove tmp/file.t.txt good");
// operator (std::string) const;
t.is ((std::string) f6, Directory::cwd () + "/tmp/file.t.txt", "File::operator (std::string) const");
t.ok (File::create ("tmp/file.t.create"), "File::create tmp/file.t.create good");
t.ok (File::remove ("tmp/file.t.create"), "File::remove tmp/file.t.create good");
// basename (std::string) const;
t.is (f6.name (), "file.t.txt", "File::basename tmp/file.t.txt --> file.t.txt");
// dirname (std::string) const;
t.is (f6.parent (), Directory::cwd () + "/tmp", "File::dirname tmp/file.t.txt --> tmp");
// bool rename (const std::string&);
File f7 ("tmp/file.t.2.txt");
f7.append ("something\n");
f7.close ();
t.ok (f7.rename ("tmp/file.t.3.txt"), "File::rename did not fail");
t.is (f7._data, Directory::cwd () + "/tmp/file.t.3.txt", "File::rename stored new name");
t.ok (f7.exists (), "File::rename new file exists");
t.ok (f7.remove (), "File::remove tmp/file.t.3.txt good");
t.notok (f7.exists (), "File::remove new file no longer exists");
// Test permissions.
File f8 ("tmp/file.t.perm.txt");
f8.create (0744);
t.ok (f8.exists (), "File::create perm file exists");
mode_t m = f8.mode ();
t.ok (m & S_IFREG, "File::mode tmp/file.t.perm.txt S_IFREG good");
t.ok (m & S_IRUSR, "File::mode tmp/file.t.perm.txt r-------- good");
t.ok (m & S_IWUSR, "File::mode tmp/file.t.perm.txt -w------- good");
t.ok (m & S_IXUSR, "File::mode tmp/file.t.perm.txt --x------ good");
t.ok (m & S_IRGRP, "File::mode tmp/file.t.perm.txt ---r----- good");
t.notok (m & S_IWGRP, "File::mode tmp/file.t.perm.txt ----w---- good");
t.notok (m & S_IXGRP, "File::mode tmp/file.t.perm.txt -----x--- good");
t.ok (m & S_IROTH, "File::mode tmp/file.t.perm.txt ------r-- good");
t.notok (m & S_IWOTH, "File::mode tmp/file.t.perm.txt -------w- good");
t.notok (m & S_IXOTH, "File::mode tmp/file.t.perm.txt --------x good");
f8.remove ();
t.notok (f8.exists (), "File::remove perm file no longer exists");
tmp.remove ();
t.notok (tmp.exists (), "tmp dir removed.");
tmp.create ();
t.ok (tmp.exists (), "tmp dir created.");
// Directory (const File&);
// Directory (const Path&);
Directory d0 (Path ("tmp"));
Directory d1 (File ("tmp"));
Directory d2 (File (Path ("tmp")));
t.is (d0._data, d1._data, "Directory(std::string) == Directory (File&)");
t.is (d0._data, d2._data, "Directory(std::string) == Directory (File (Path &))");
t.is (d1._data, d2._data, "Directory(File&)) == Directory (File (Path &))");
// Directory (const Directory&);
Directory d3 (d2);
t.is (d3._data, Directory::cwd () + "/tmp", "Directory (Directory&)");
// Directory (const std::string&);
Directory d4 ("tmp/test_directory");
// Directory& operator= (const Directory&);
Directory d5 = d4;
t.is (d5._data, Directory::cwd () + "/tmp/test_directory", "Directory::operator=");
// operator (std::string) const;
t.is ((std::string) d3, Directory::cwd () + "/tmp", "Directory::operator (std::string) const");
// virtual bool create ();
t.ok (d5.create (), "Directory::create tmp/test_directory");
t.ok (d5.exists (), "Directory::exists tmp/test_directory");
Directory d6 (d5._data + "/dir");
t.ok (d6.create (), "Directory::create tmp/test_directory/dir");
File::create (d5._data + "/f0");
File::create (d6._data + "/f1");
// std::vector <std::string> list ();
std::vector <std::string> files = d5.list ();
std::sort (files.begin (), files.end ());
t.is ((int)files.size (), 2, "Directory::list 1 file");
t.is (files[0], Directory::cwd () + "/tmp/test_directory/dir", "file[0] is tmp/test_directory/dir");
t.is (files[1], Directory::cwd () + "/tmp/test_directory/f0", "file[1] is tmp/test_directory/f0");
// std::vector <std::string> listRecursive ();
files = d5.listRecursive ();
std::sort (files.begin (), files.end ());
t.is ((int)files.size (), 2, "Directory::list 1 file");
t.is (files[0], Directory::cwd () + "/tmp/test_directory/dir/f1", "file is tmp/test_directory/dir/f1");
t.is (files[1], Directory::cwd () + "/tmp/test_directory/f0", "file is tmp/test_directory/f0");
// virtual bool remove ();
t.ok (File::remove (d5._data + "/f0"), "File::remove tmp/test_directory/f0");
t.ok (File::remove (d6._data + "/f1"), "File::remove tmp/test_directory/dir/f1");
t.ok (d6.remove (), "Directory::remove tmp/test_directory/dir");
t.notok (d6.exists (), "Directory::exists tmp/test_directory/dir - no");
t.ok (d5.remove (), "Directory::remove tmp/test_directory");
t.notok (d5.exists (), "Directory::exists tmp/test_directory - no");
// bool remove (const std::string&);
Directory d7 ("tmp/to_be_removed");
t.ok (d7.create (), "Directory::create tmp/to_be_removed");
File::create (d7._data + "/f0");
Directory d8 (d7._data + "/another");
t.ok (d8.create (), "Directory::create tmp/to_be_removed/another");
File::create (d8._data + "/f1");
t.ok (d7.remove (), "Directory::remove tmp/to_be_removed");
t.notok (d7.exists (), "Directory tmp/to_be_removed gone");
// static std::string cwd ();
std::string cwd = Directory::cwd ();
t.ok (cwd.length () > 0, "Directory::cwd returned a value");
// bool parent (std::string&) const;
Directory d9 ("/one/two/three/four.txt");
t.ok (d9.up (), "parent /one/two/three/four.txt --> true");
t.is (d9._data, "/one/two/three", "parent /one/two/three/four.txt --> /one/two/three");
t.ok (d9.up (), "parent /one/two/three --> true");
t.is (d9._data, "/one/two", "parent /one/two/three --> /one/two");
t.ok (d9.up (), "parent /one/two --> true");
t.is (d9._data, "/one", "parent /one/two --> /one");
t.ok (d9.up (), "parent /one --> true");
t.is (d9._data, "/", "parent /one --> /");
t.notok (d9.up (), "parent / --> false");
// Test permissions.
umask (0022);
Directory d10 ("tmp/dir.perm");
d10.create (0750);
t.ok (d10.exists (), "Directory::create perm file exists");
m = d10.mode ();
t.ok (m & S_IFDIR, "Directory::mode tmp/dir.perm S_IFDIR good");
t.ok (m & S_IRUSR, "Directory::mode tmp/dir.perm r-------- good");
t.ok (m & S_IWUSR, "Directory::mode tmp/dir.perm -w------- good");
t.ok (m & S_IXUSR, "Directory::mode tmp/dir.perm --x------ good");
t.ok (m & S_IRGRP, "Directory::mode tmp/dir.perm ---r----- good");
t.notok (m & S_IWGRP, "Directory::mode tmp/dir.perm ----w---- good");
t.ok (m & S_IXGRP, "Directory::mode tmp/dir.perm -----x--- good");
t.notok (m & S_IROTH, "Directory::mode tmp/dir.perm ------r-- good");
t.notok (m & S_IWOTH, "Directory::mode tmp/dir.perm -------w- good");
t.notok (m & S_IXOTH, "Directory::mode tmp/dir.perm --------x good");
d10.remove ();
t.notok (d10.exists (), "Directory::remove temp/dir.perm file no longer exists");
tmp.remove ();
t.notok (tmp.exists (), "tmp dir removed.");
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*******************************************************************************
Taichi - Physically based Computer Graphics Library
Copyright (c) 2016 Yuanming Hu <[email protected]>
All rights reserved. Use of this source code is governed by
the MIT license as written in the LICENSE file.
*******************************************************************************/
#include <taichi/visual/scene.h>
#include <taichi/visual/surface_material.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
TC_NAMESPACE_BEGIN
void Mesh::initialize(const Config &config) {
transform = Matrix4(1.0_f);
std::string filepath = config.get_string("filename");
if (!filepath.empty())
load_from_file(filepath, config.get("reverse_vertices", false));
else {
TC_ERROR("File name can not be empty");
}
}
void Mesh::load_from_file(const std::string &file_path,
bool reverse_vertices) {
std::string inputfile = file_path;
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
bool ret =
tinyobj::LoadObj(&attrib, &shapes, &materials, &err, inputfile.c_str());
if (!err.empty()) { // `err` may contain warning message.
std::cerr << err << std::endl;
}
TC_ASSERT_INFO(ret, "Loading " + file_path + " failed");
// Loop over shapes
for (size_t s = 0; s < shapes.size(); s++) {
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
TC_ASSERT_INFO(fv == 3, "Only triangles supported...");
int i = (int)vertices.size(), j = i + 1, k = i + 2;
if (reverse_vertices) {
std::swap(j, k);
}
bool has_normal = false;
for (int v = 0; v < fv; v++) {
// access to vertex
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
float vx = attrib.vertices[3 * idx.vertex_index + 0];
float vy = attrib.vertices[3 * idx.vertex_index + 1];
float vz = attrib.vertices[3 * idx.vertex_index + 2];
vertices.push_back(Vector3(vx, vy, vz));
if (idx.normal_index != -1) {
float nx = attrib.normals[3 * idx.normal_index + 0];
float ny = attrib.normals[3 * idx.normal_index + 1];
float nz = attrib.normals[3 * idx.normal_index + 2];
has_normal = true;
normals.push_back(Vector3(nx, ny, nz));
} else {
// should be consistent
assert(!has_normal);
has_normal = false;
}
float tx = 0.0_f, ty = 0.0_f;
if (idx.texcoord_index != -1) {
tx = attrib.texcoords[2 * idx.texcoord_index + 0];
ty = attrib.texcoords[2 * idx.texcoord_index + 1];
}
uvs.push_back(Vector2(tx, ty));
}
if (!has_normal) {
Vector3 *a = &vertices[vertices.size()] - 3;
Vector3 generated_normal = cross(a[1] - a[0], a[2] - a[0]);
if (length(generated_normal) > 1e-6f) {
generated_normal = normalize(generated_normal);
}
for (int v = 0; v < fv; v++) {
normals.push_back(generated_normal);
}
}
untransformed_triangles.push_back(
Triangle(vertices[i], vertices[j], vertices[k], normals[i],
normals[j], normals[k], uvs[i], uvs[j], uvs[k], i / 3));
index_offset += fv;
}
}
}
void Mesh::set_material(std::shared_ptr<SurfaceMaterial> material) {
this->material = material;
if (material->is_emissive()) {
this->emission_color =
Vector3(material->get_importance(Vector2(0.5f, 0.5f))); // TODO
this->emission = luminance(this->emission_color);
} else {
this->emission = 0.0_f;
this->emission_color = Vector3(0);
}
}
IntersectionInfo Scene::get_intersection_info(int triangle_id, Ray &ray) {
IntersectionInfo inter;
if (triangle_id == -1) {
return inter;
}
inter.intersected = true;
Triangle &t = triangles[triangle_id];
real coord_u = ray.u, coord_v = ray.v;
inter.tri_coord.x = coord_u;
inter.tri_coord.y = coord_u;
inter.pos =
t.v[0] + coord_u * (t.v[1] - t.v[0]) + coord_v * (t.v[2] - t.v[0]);
inter.front = dot(ray.orig - t.v[0], t.normal) > 0;
// Verify interpolated normals can lead specular rays to go inside the object.
Vector3 normal = t.get_normal(coord_u, coord_v);
Vector2 uv = t.get_uv(coord_u, coord_v);
inter.uv = uv;
inter.geometry_normal = inter.front ? t.normal : -t.normal;
inter.normal = inter.front ? normal : -normal;
// TODO: why unused?
// Mesh *mesh = triangle_id_to_mesh[t.id];
inter.triangle_id = triangle_id;
inter.dist = ray.dist;
// inter.material = mesh->material.get();
Vector3 u = normalized(t.v[1] - t.v[0]);
real sgn = inter.front ? 1.0_f : -1.0_f;
Vector3 v = normalized(
cross(sgn * inter.normal,
u)); // Due to shading normal, we have to normalize here...
inter.dt_du = t.get_duv(u);
inter.dt_dv = t.get_duv(v);
// TODO: ...
u = normalized(cross(v, inter.normal));
inter.to_world = Matrix3(u, v, inter.normal);
inter.to_local = transposed(inter.to_world);
return inter;
}
void Scene::add_mesh(std::shared_ptr<Mesh> mesh) {
meshes.push_back(*mesh);
}
void Scene::finalize_geometry() {
int triangle_count = 0;
for (auto &mesh : meshes) {
triangle_id_start[&mesh] = triangle_count;
auto sub = mesh.get_triangles();
for (int i = 0; i < (int)sub.size(); i++) {
sub[i].id = triangle_count + i;
}
triangle_count += (int)sub.size();
triangles.insert(triangles.end(), sub.begin(), sub.end());
if (mesh.emission > 0) {
emissive_triangles.insert(emissive_triangles.end(), sub.begin(),
sub.end());
}
for (auto &tri : sub) {
triangle_id_to_mesh[tri.id] = &mesh;
}
}
num_triangles = triangle_count;
printf("Scene loaded. Triangle count: %d\n", triangle_count);
};
void Scene::finalize_lighting() {
if (!emissive_triangles.empty()) {
update_emission_cdf();
update_light_emission_cdf();
} else {
envmap_sample_prob = 1.0_f;
assert_info(envmap != nullptr, "There should be light sources.");
}
}
void Scene::finalize() {
finalize_geometry();
finalize_lighting();
}
TC_NAMESPACE_END
<commit_msg>Fixed render<commit_after>/*******************************************************************************
Taichi - Physically based Computer Graphics Library
Copyright (c) 2016 Yuanming Hu <[email protected]>
All rights reserved. Use of this source code is governed by
the MIT license as written in the LICENSE file.
*******************************************************************************/
#include <taichi/visual/scene.h>
#include <taichi/visual/surface_material.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
TC_NAMESPACE_BEGIN
void Mesh::initialize(const Config &config) {
transform = Matrix4(1.0_f);
std::string filepath = config.get_string("filename");
if (!filepath.empty())
load_from_file(filepath, config.get("reverse_vertices", false));
}
void Mesh::load_from_file(const std::string &file_path,
bool reverse_vertices) {
std::string inputfile = file_path;
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
bool ret =
tinyobj::LoadObj(&attrib, &shapes, &materials, &err, inputfile.c_str());
if (!err.empty()) { // `err` may contain warning message.
std::cerr << err << std::endl;
}
TC_ASSERT_INFO(ret, "Loading " + file_path + " failed");
// Loop over shapes
for (size_t s = 0; s < shapes.size(); s++) {
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
TC_ASSERT_INFO(fv == 3, "Only triangles supported...");
int i = (int)vertices.size(), j = i + 1, k = i + 2;
if (reverse_vertices) {
std::swap(j, k);
}
bool has_normal = false;
for (int v = 0; v < fv; v++) {
// access to vertex
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
float vx = attrib.vertices[3 * idx.vertex_index + 0];
float vy = attrib.vertices[3 * idx.vertex_index + 1];
float vz = attrib.vertices[3 * idx.vertex_index + 2];
vertices.push_back(Vector3(vx, vy, vz));
if (idx.normal_index != -1) {
float nx = attrib.normals[3 * idx.normal_index + 0];
float ny = attrib.normals[3 * idx.normal_index + 1];
float nz = attrib.normals[3 * idx.normal_index + 2];
has_normal = true;
normals.push_back(Vector3(nx, ny, nz));
} else {
// should be consistent
assert(!has_normal);
has_normal = false;
}
float tx = 0.0_f, ty = 0.0_f;
if (idx.texcoord_index != -1) {
tx = attrib.texcoords[2 * idx.texcoord_index + 0];
ty = attrib.texcoords[2 * idx.texcoord_index + 1];
}
uvs.push_back(Vector2(tx, ty));
}
if (!has_normal) {
Vector3 *a = &vertices[vertices.size()] - 3;
Vector3 generated_normal = cross(a[1] - a[0], a[2] - a[0]);
if (length(generated_normal) > 1e-6f) {
generated_normal = normalize(generated_normal);
}
for (int v = 0; v < fv; v++) {
normals.push_back(generated_normal);
}
}
untransformed_triangles.push_back(
Triangle(vertices[i], vertices[j], vertices[k], normals[i],
normals[j], normals[k], uvs[i], uvs[j], uvs[k], i / 3));
index_offset += fv;
}
}
}
void Mesh::set_material(std::shared_ptr<SurfaceMaterial> material) {
this->material = material;
if (material->is_emissive()) {
this->emission_color =
Vector3(material->get_importance(Vector2(0.5f, 0.5f))); // TODO
this->emission = luminance(this->emission_color);
} else {
this->emission = 0.0_f;
this->emission_color = Vector3(0);
}
}
IntersectionInfo Scene::get_intersection_info(int triangle_id, Ray &ray) {
IntersectionInfo inter;
if (triangle_id == -1) {
return inter;
}
inter.intersected = true;
Triangle &t = triangles[triangle_id];
real coord_u = ray.u, coord_v = ray.v;
inter.tri_coord.x = coord_u;
inter.tri_coord.y = coord_u;
inter.pos =
t.v[0] + coord_u * (t.v[1] - t.v[0]) + coord_v * (t.v[2] - t.v[0]);
inter.front = dot(ray.orig - t.v[0], t.normal) > 0;
// Verify interpolated normals can lead specular rays to go inside the object.
Vector3 normal = t.get_normal(coord_u, coord_v);
Vector2 uv = t.get_uv(coord_u, coord_v);
inter.uv = uv;
inter.geometry_normal = inter.front ? t.normal : -t.normal;
inter.normal = inter.front ? normal : -normal;
// TODO: why unused?
// Mesh *mesh = triangle_id_to_mesh[t.id];
inter.triangle_id = triangle_id;
inter.dist = ray.dist;
// inter.material = mesh->material.get();
Vector3 u = normalized(t.v[1] - t.v[0]);
real sgn = inter.front ? 1.0_f : -1.0_f;
Vector3 v = normalized(
cross(sgn * inter.normal,
u)); // Due to shading normal, we have to normalize here...
inter.dt_du = t.get_duv(u);
inter.dt_dv = t.get_duv(v);
// TODO: ...
u = normalized(cross(v, inter.normal));
inter.to_world = Matrix3(u, v, inter.normal);
inter.to_local = transposed(inter.to_world);
return inter;
}
void Scene::add_mesh(std::shared_ptr<Mesh> mesh) {
meshes.push_back(*mesh);
}
void Scene::finalize_geometry() {
int triangle_count = 0;
for (auto &mesh : meshes) {
triangle_id_start[&mesh] = triangle_count;
auto sub = mesh.get_triangles();
for (int i = 0; i < (int)sub.size(); i++) {
sub[i].id = triangle_count + i;
}
triangle_count += (int)sub.size();
triangles.insert(triangles.end(), sub.begin(), sub.end());
if (mesh.emission > 0) {
emissive_triangles.insert(emissive_triangles.end(), sub.begin(),
sub.end());
}
for (auto &tri : sub) {
triangle_id_to_mesh[tri.id] = &mesh;
}
}
num_triangles = triangle_count;
printf("Scene loaded. Triangle count: %d\n", triangle_count);
};
void Scene::finalize_lighting() {
if (!emissive_triangles.empty()) {
update_emission_cdf();
update_light_emission_cdf();
} else {
envmap_sample_prob = 1.0_f;
assert_info(envmap != nullptr, "There should be light sources.");
}
}
void Scene::finalize() {
finalize_geometry();
finalize_lighting();
}
TC_NAMESPACE_END
<|endoftext|> |
<commit_before>/*!
\file hashlog.cpp
\brief Hash logs reader definition
\author Ivan Shynkarenka
\date 13.12.2021
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/hash_layout.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "../source/logging/appenders/minizip/unzip.h"
#if defined(_WIN32) || defined(_WIN64)
#include "../source/logging/appenders/minizip/iowin32.h"
#endif
#include "errors/fatal.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include "utility/countof.h"
#include "utility/resource.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
Path FindHashlog(const Path& path)
{
// Try to find .hashlog in the current path
Path hashlog = path.IsRegularFile() ? path : (path / ".hashlog");
if (hashlog.IsExists())
return hashlog;
// Try to find .hashlog in the parent path
Path parent = path.parent();
if (parent)
return FindHashlog(parent);
// Cannot find .hashlog file
return Path();
}
std::unordered_map<uint32_t, std::string> ReadHashlog(const Path& path)
{
std::unordered_map<uint32_t, std::string> hashmap;
File hashlog(path);
// Check if .hashlog is exists
if (!hashlog.IsExists())
return hashmap;
// Open .hashlog file
hashlog.Open(true, false);
// Check if .hashlog is opened
if (!hashlog)
return hashmap;
// Read the hash map size
uint32_t size;
if (hashlog.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
hashmap.reserve(size);
// Read the hash map content
while (size-- > 0)
{
uint32_t hash;
if (hashlog.Read(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
uint16_t length;
if (hashlog.Read(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return hashmap;
std::vector<uint8_t> buffer(length);
if (hashlog.Read(buffer.data(), length) != length)
return hashmap;
std::string message(buffer.begin(), buffer.end());
hashmap[hash] = message;
}
// Close .hashlog file
hashlog.Close();
return hashmap;
}
bool WriteHashlog(const Path& path, const std::unordered_map<uint32_t, std::string>& hashmap)
{
File hashlog(path);
// Open or create .hashlog file
hashlog.OpenOrCreate(false, true, true);
// Check if .hashlog is avaliable
if (!hashlog)
return false;
// Write the hash map size
uint32_t size = (uint32_t)hashmap.size();
if (hashlog.Write(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
// Read the hash map content
for (const auto& item : hashmap)
{
uint32_t hash = (uint32_t)item.first;
if (hashlog.Write(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
uint16_t length = (uint16_t)item.second.size();
if (hashlog.Write(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return false;
auto buffer = item.second.data();
if (hashlog.Write(buffer, length) != length)
return false;
}
// Close .hashlog file
hashlog.Close();
return true;
}
Path UnzipFile(const Path& path)
{
// Open a zip archive
unzFile unzf;
#if defined(_WIN32) || defined(_WIN64)
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzf = unzOpen2_64(path.wstring().c_str(), &ffunc);
#else
unzf = unzOpen64(path.string().c_str());
#endif
if (unzf == nullptr)
throwex FileSystemException("Cannot open a zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip = resource(unzf, [](unzFile handle) { unzClose(handle); });
File destination(path + ".tmp");
// Open the destination file for writing
destination.Create(false, true);
// Get info about the zip archive
unz_global_info global_info;
int result = unzGetGlobalInfo(unzf, &global_info);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive global info!").Attach(path);
// Loop to extract all files from the zip archive
uLong i;
for (i = 0; i < global_info.number_entry; ++i)
{
unz_file_info file_info;
char filename[1024];
// Get info about the current file in the zip archive
result = unzGetCurrentFileInfo(unzf, &file_info, filename, (unsigned)countof(filename), NULL, 0, NULL, 0);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive file info!").Attach(path);
// Check if this entry is a file
const size_t filename_length = strlen(filename);
if (filename[filename_length - 1] != '/')
{
// Open the current file in the zip archive
result = unzOpenCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot open a current file in the zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip_file = resource(unzf, [](unzFile handle) { unzCloseCurrentFile(handle); });
// Read data from the current file in the zip archive
do
{
uint8_t buffer[16384];
result = unzReadCurrentFile(unzf, buffer, (unsigned)countof(buffer));
if (result > 0)
destination.Write(buffer, (size_t)result);
else if (result < 0)
throwex FileSystemException("Cannot read the current file from the zip archive!").Attach(path);
} while (result != UNZ_EOF);
// Close the current file in the zip archive
result = unzCloseCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the current file in the zip archive!").Attach(path);
unzip_file.release();
}
}
// Close the destination file
destination.Close();
// Close the zip archive
result = unzClose(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the zip archive!").Attach(path);
unzip.release();
return std::move(destination);
}
bool InputRecord(Reader& input, Record& record)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
// Deserialize the logging message
uint16_t message_size;
std::memcpy(&message_size, buffer, sizeof(uint16_t));
buffer += sizeof(uint16_t);
record.message.insert(record.message.begin(), buffer, buffer + message_size);
buffer += message_size;
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool InputRecord(Reader& input, Record& record, const std::unordered_map<uint32_t, std::string>& hashmap)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint32_t logger_hash;
std::memcpy(&logger_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& logger = hashmap.find(logger_hash);
record.logger.assign((logger != hashmap.end()) ? logger->second : format("0x{:X}", logger_hash));
// Deserialize the logging message
uint32_t message_hash;
std::memcpy(&message_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& message = hashmap.find(message_hash);
record.message.assign((message != hashmap.end()) ? message->second : format("0x{:X}", message_hash));
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, std::string_view message, uint32_t message_hash)
{
if (hashmap.find(message_hash) == hashmap.end())
{
std::cout << format("Discovered logging message: \"{}\" with hash = 0x{:8X}", message, message_hash) << std::endl;
hashmap[message_hash] = message;
return true;
}
else if (message != hashmap[message_hash])
{
std::cerr << format("Collision detected!") << std::endl;
std::cerr << format("Previous logging message: \"{}\" with hash = 0x{:8X}", hashmap[message_hash], message_hash) << std::endl;
std::cerr << format("Conflict logging message: \"{}\" with hash = 0x{:8X}", message, message_hash) << std::endl;
throwex Exception("Collision detected!");
}
// Skip duplicates
return false;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, Record& record)
{
bool result = false;
// Check the logger name
result |= UpdateHashmap(hashmap, record.logger, HashLayout::Hash(record.logger));
// Check the logging message
result |= UpdateHashmap(hashmap, record.message, HashLayout::Hash(record.message));
return result;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-x", "--hashlog").dest("hashlog").help("Hashlog file name");
parser.add_option("-i", "--input").dest("input").help("Input file name");
parser.add_option("-o", "--output").dest("output").help("Output file name");
parser.add_option("-u", "--update").dest("update").help("Update .hashlog");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
try
{
// Open the hashlog file
Path hashlog = FindHashlog(Path::current());
if (options.is_set("hashlog"))
{
hashlog = Path(options.get("hashlog"));
if (hashlog.IsDirectory())
hashlog = FindHashlog(hashlog);
}
// Read .hashlog file and fill the logging messages hash map
std::unordered_map<uint32_t, std::string> hashmap = ReadHashlog(hashlog);
Path temp_file;
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input") || options.is_set("update"))
{
Path path(options.is_set("input") ? options.get("input") : options.get("update"));
if (path.IsRegularFile() && (path.extension() == ".zip"))
temp_file = path = UnzipFile(path);
File* file = new File(path);
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
if (options.is_set("update"))
{
bool store = false;
// Update hashmap with data from all logging records
Record record;
while (InputRecord(*input, record))
store |= UpdateHashmap(hashmap, record);
// Store updated .hashlog
if (store)
WriteHashlog(hashlog, hashmap);
}
else
{
// Process all logging records
Record record;
while (InputRecord(*input, record, hashmap))
if (!OutputRecord(*output, record))
break;
}
// Delete temporary file
if (temp_file)
Path::Remove(temp_file);
return 0;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return -1;
}
}
<commit_msg>Bugfixing<commit_after>/*!
\file hashlog.cpp
\brief Hash logs reader definition
\author Ivan Shynkarenka
\date 13.12.2021
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/hash_layout.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "../source/logging/appenders/minizip/unzip.h"
#if defined(_WIN32) || defined(_WIN64)
#include "../source/logging/appenders/minizip/iowin32.h"
#endif
#include "errors/fatal.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include "utility/countof.h"
#include "utility/resource.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
Path FindHashlog(const Path& path)
{
// Try to find .hashlog in the current path
Path hashlog = path.IsRegularFile() ? path : (path / ".hashlog");
if (hashlog.IsExists())
return hashlog;
// Try to find .hashlog in the parent path
Path parent = path.parent();
if (parent)
return FindHashlog(parent);
// Cannot find .hashlog file
return Path();
}
std::unordered_map<uint32_t, std::string> ReadHashlog(const Path& path)
{
std::unordered_map<uint32_t, std::string> hashmap;
File hashlog(path);
// Check if .hashlog is exists
if (!hashlog.IsExists())
return hashmap;
// Open .hashlog file
hashlog.Open(true, false);
// Check if .hashlog is opened
if (!hashlog)
return hashmap;
// Read the hash map size
uint32_t size;
if (hashlog.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
hashmap.reserve(size);
// Read the hash map content
while (size-- > 0)
{
uint32_t hash;
if (hashlog.Read(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
uint16_t length;
if (hashlog.Read(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return hashmap;
std::vector<uint8_t> buffer(length);
if (hashlog.Read(buffer.data(), length) != length)
return hashmap;
std::string message(buffer.begin(), buffer.end());
hashmap[hash] = message;
}
// Close .hashlog file
hashlog.Close();
return hashmap;
}
bool WriteHashlog(const Path& path, const std::unordered_map<uint32_t, std::string>& hashmap)
{
File hashlog(path);
// Open or create .hashlog file
hashlog.OpenOrCreate(false, true, true);
// Check if .hashlog is avaliable
if (!hashlog)
return false;
// Write the hash map size
uint32_t size = (uint32_t)hashmap.size();
if (hashlog.Write(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
// Read the hash map content
for (const auto& item : hashmap)
{
uint32_t hash = (uint32_t)item.first;
if (hashlog.Write(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
uint16_t length = (uint16_t)item.second.size();
if (hashlog.Write(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return false;
auto buffer = item.second.data();
if (hashlog.Write(buffer, length) != length)
return false;
}
// Close .hashlog file
hashlog.Close();
return true;
}
Path UnzipFile(const Path& path)
{
// Open a zip archive
unzFile unzf;
#if defined(_WIN32) || defined(_WIN64)
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzf = unzOpen2_64(path.wstring().c_str(), &ffunc);
#else
unzf = unzOpen64(path.string().c_str());
#endif
if (unzf == nullptr)
throwex FileSystemException("Cannot open a zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip = resource(unzf, [](unzFile handle) { unzClose(handle); });
File destination(path + ".tmp");
// Open the destination file for writing
destination.Create(false, true);
// Get info about the zip archive
unz_global_info global_info;
int result = unzGetGlobalInfo(unzf, &global_info);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive global info!").Attach(path);
// Loop to extract all files from the zip archive
uLong i;
for (i = 0; i < global_info.number_entry; ++i)
{
unz_file_info file_info;
char filename[1024];
// Get info about the current file in the zip archive
result = unzGetCurrentFileInfo(unzf, &file_info, filename, (unsigned)countof(filename), NULL, 0, NULL, 0);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive file info!").Attach(path);
// Check if this entry is a file
const size_t filename_length = strlen(filename);
if (filename[filename_length - 1] != '/')
{
// Open the current file in the zip archive
result = unzOpenCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot open a current file in the zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip_file = resource(unzf, [](unzFile handle) { unzCloseCurrentFile(handle); });
// Read data from the current file in the zip archive
do
{
uint8_t buffer[16384];
result = unzReadCurrentFile(unzf, buffer, (unsigned)countof(buffer));
if (result > 0)
destination.Write(buffer, (size_t)result);
else if (result < 0)
throwex FileSystemException("Cannot read the current file from the zip archive!").Attach(path);
} while (result != UNZ_EOF);
// Close the current file in the zip archive
result = unzCloseCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the current file in the zip archive!").Attach(path);
unzip_file.release();
}
}
// Close the destination file
destination.Close();
// Close the zip archive
result = unzClose(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the zip archive!").Attach(path);
unzip.release();
return std::move(destination);
}
bool InputRecord(Reader& input, Record& record)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
// Deserialize the logging message
uint16_t message_size;
std::memcpy(&message_size, buffer, sizeof(uint16_t));
buffer += sizeof(uint16_t);
record.message.insert(record.message.begin(), buffer, buffer + message_size);
buffer += message_size;
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool InputRecord(Reader& input, Record& record, const std::unordered_map<uint32_t, std::string>& hashmap)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint32_t logger_hash;
std::memcpy(&logger_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& logger = hashmap.find(logger_hash);
record.logger.assign((logger != hashmap.end()) ? logger->second : format("0x{:X}", logger_hash));
// Deserialize the logging message
uint32_t message_hash;
std::memcpy(&message_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& message = hashmap.find(message_hash);
record.message.assign((message != hashmap.end()) ? message->second : format("0x{:X}", message_hash));
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, std::string_view message, uint32_t message_hash)
{
if (hashmap.find(message_hash) == hashmap.end())
{
std::cout << format("Discovered logging message: \"{}\" with hash = 0x{:08X}", message, message_hash) << std::endl;
hashmap[message_hash] = message;
return true;
}
else if (message != hashmap[message_hash])
{
std::cerr << format("Collision detected!") << std::endl;
std::cerr << format("Previous logging message: \"{}\" with hash = 0x{:08X}", hashmap[message_hash], message_hash) << std::endl;
std::cerr << format("Conflict logging message: \"{}\" with hash = 0x{:08X}", message, message_hash) << std::endl;
throwex Exception("Collision detected!");
}
// Skip duplicates
return false;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, Record& record)
{
bool result = false;
// Check the logger name
result |= UpdateHashmap(hashmap, record.logger, HashLayout::Hash(record.logger));
// Check the logging message
result |= UpdateHashmap(hashmap, record.message, HashLayout::Hash(record.message));
return result;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-x", "--hashlog").dest("hashlog").help("Hashlog file name");
parser.add_option("-i", "--input").dest("input").help("Input file name");
parser.add_option("-o", "--output").dest("output").help("Output file name");
parser.add_option("-u", "--update").dest("update").help("Update .hashlog");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
try
{
// Open the hashlog file
Path hashlog = FindHashlog(Path::current());
if (options.is_set("hashlog"))
{
hashlog = Path(options.get("hashlog"));
if (hashlog.IsDirectory())
hashlog = FindHashlog(hashlog);
}
// Read .hashlog file and fill the logging messages hash map
std::unordered_map<uint32_t, std::string> hashmap = ReadHashlog(hashlog);
Path temp_file;
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input") || options.is_set("update"))
{
Path path(options.is_set("input") ? options.get("input") : options.get("update"));
if (path.IsRegularFile() && (path.extension() == ".zip"))
temp_file = path = UnzipFile(path);
File* file = new File(path);
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
if (options.is_set("update"))
{
bool store = false;
// Update hashmap with data from all logging records
Record record;
while (InputRecord(*input, record))
store |= UpdateHashmap(hashmap, record);
// Store updated .hashlog
if (store)
WriteHashlog(hashlog, hashmap);
}
else
{
// Process all logging records
Record record;
while (InputRecord(*input, record, hashmap))
if (!OutputRecord(*output, record))
break;
}
// Delete temporary file
if (temp_file)
Path::Remove(temp_file);
return 0;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return -1;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef LIBPORT_XLTDL_HH
# define LIBPORT_XLTDL_HH
# include <stdexcept>
# include <libport/fwd.hh>
# include <libport/compiler.hh>
# include <libport/export.hh>
# include <libport/file-library.hh>
# include <ltdl.h>
namespace libport
{
class LIBPORT_API xlt_advise
{
public:
/// Exceptions thrown on errors.
struct LIBPORT_API exception : std::runtime_error
{
exception(const std::string& msg);
};
xlt_advise() throw (exception);
~xlt_advise() throw (exception);
xlt_advise& global(bool global) throw (exception);
xlt_advise& ext() throw (exception);
const file_library& path() const throw ();
file_library& path() throw ();
xlt_handle open(const std::string& s) throw(exception);
/// Throw an exception, or exit with exit_status_ if nonnull.
ATTRIBUTE_NORETURN
static void fail(std::string msg) throw (exception);
private:
/// Does not use the search path. Can return 0.
lt_dlhandle dlopen_(const std::string& s) const throw (exception);
lt_dladvise advise_;
file_library path_;
};
class LIBPORT_API xlt_handle
{
public:
typedef xlt_advise::exception exception;
xlt_handle(lt_dlhandle h = 0);
~xlt_handle();
/// Close the handle.
void close() throw (exception);
/// Detach so that destruction does not close.
void detach();
/// Detach so that destruction does not close.
void attach(lt_dlhandle h);
/// Wrapper around lt_dlsym that exits on failures.
template <typename T>
T sym(const std::string& s) throw (exception);
/// Bounce to xlt_advise::fail.
ATTRIBUTE_NORETURN
static void fail(const std::string& msg) throw (exception);
/// The handle.
/// Exposed, as currently we don't cover the whole lt_ interface.
lt_dlhandle handle;
};
/// Wrapper around lt_dlopenext that exits on failures.
LIBPORT_API
xlt_handle
xlt_openext(const std::string& s, bool global, int exit_failure = 1)
throw (xlt_advise::exception);
}
// This function is here only for the testsuite; it opens libport.so,
// and try to fetch and use this symbol.
extern "C"
{
int libport_xlt_details_identity(int i);
}
# include <libport/xltdl.hxx>
#endif // ! LIBPORT_XLTDL_HH
<commit_msg>xltdl: export the test function.<commit_after>/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef LIBPORT_XLTDL_HH
# define LIBPORT_XLTDL_HH
# include <stdexcept>
# include <libport/fwd.hh>
# include <libport/compiler.hh>
# include <libport/export.hh>
# include <libport/file-library.hh>
# include <ltdl.h>
namespace libport
{
class LIBPORT_API xlt_advise
{
public:
/// Exceptions thrown on errors.
struct LIBPORT_API exception : std::runtime_error
{
exception(const std::string& msg);
};
xlt_advise() throw (exception);
~xlt_advise() throw (exception);
xlt_advise& global(bool global) throw (exception);
xlt_advise& ext() throw (exception);
const file_library& path() const throw ();
file_library& path() throw ();
xlt_handle open(const std::string& s) throw(exception);
/// Throw an exception, or exit with exit_status_ if nonnull.
ATTRIBUTE_NORETURN
static void fail(std::string msg) throw (exception);
private:
/// Does not use the search path. Can return 0.
lt_dlhandle dlopen_(const std::string& s) const throw (exception);
lt_dladvise advise_;
file_library path_;
};
class LIBPORT_API xlt_handle
{
public:
typedef xlt_advise::exception exception;
xlt_handle(lt_dlhandle h = 0);
~xlt_handle();
/// Close the handle.
void close() throw (exception);
/// Detach so that destruction does not close.
void detach();
/// Detach so that destruction does not close.
void attach(lt_dlhandle h);
/// Wrapper around lt_dlsym that exits on failures.
template <typename T>
T sym(const std::string& s) throw (exception);
/// Bounce to xlt_advise::fail.
ATTRIBUTE_NORETURN
static void fail(const std::string& msg) throw (exception);
/// The handle.
/// Exposed, as currently we don't cover the whole lt_ interface.
lt_dlhandle handle;
};
/// Wrapper around lt_dlopenext that exits on failures.
LIBPORT_API
xlt_handle
xlt_openext(const std::string& s, bool global, int exit_failure = 1)
throw (xlt_advise::exception);
}
// This function is here only for the testsuite; it opens libport.so,
// and try to fetch and use this symbol.
extern "C"
{
LIBPORT_API
int libport_xlt_details_identity(int i);
}
# include <libport/xltdl.hxx>
#endif // ! LIBPORT_XLTDL_HH
<|endoftext|> |
<commit_before>#include <clang-c/Index.h>
#include <cstdio>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data& data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print (const client_data& data, const char** lines, std::size_t num_lines)
{
std::string padding(indent_spaces, ' ');
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << padding << lines[i] << "\n";
else
std::cout << "\n";
}
}
void open_struct (const client_data& data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
"any_printable () = default;",
0,
"template <typename T_T__>",
"any_printable (T_T__ value) :",
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
"any_printable (any_printable && rhs) noexcept = default;",
0,
"template <typename T_T__>",
"any_printable & operator= (T_T__ value)",
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
"any_printable & operator= (any_printable && rhs) noexcept = default;"
};
print(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data& data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
// TODO: pure virtual
const char* handle_preamble[] = {
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
// TODO: virtual implementations
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function(const client_data& data, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data);
const std::string open_brace = "{";
const std::string semicolon = ";";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
std::cout << " ";
std::cout << c_str;
}
free_tokens(data.tu, tokens);
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ? "" : "return ";
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << return_str << "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( ";
const int args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < args; ++i) {
if (i)
std::cout << ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
std::cout << clang_getCString(clang_getCursorSpelling(arg_cursor));
}
std::cout << " ); }\n";
}
void open_namespace (const client_data& data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data& data)
{ std::cout << "\n" << indent(data) << "}\n"; }
void dump_cursor (const char* name, CXCursor cursor)
{
CXCursorKind kind = clang_getCursorKind(cursor);
CXString kind_spelling = clang_getCursorKindSpelling(kind);
CXString cursor_spelling = clang_getCursorSpelling(cursor);
std::cout << name << " "
<< clang_getCString(kind_spelling) << " "
<< clang_getCString(cursor_spelling) << " "
<< "\n";
}
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data& data = *static_cast<client_data*>(data_);
#if 0
std::cout << "\n";
dump_cursor("cursor", cursor);
dump_cursor("parent", parent);
#endif
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
#if 0
dump_cursor("enclosing_namespace", enclosing_namespace);
#endif
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
#if 0
dump_cursor("enclosing_struct", enclosing_struct);
#endif
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
}
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
return CXChildVisit_Recurse;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_None
);
client_data data = {tu, {}, clang_getNullCursor()};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<commit_msg>print() -> print_lines().<commit_after>#include <clang-c/Index.h>
#include <cstdio>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data& data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print_lines (const client_data& data,
const char** lines,
std::size_t num_lines)
{
std::string padding(indent_spaces, ' ');
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << padding << lines[i] << "\n";
else
std::cout << "\n";
}
}
void open_struct (const client_data& data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
"any_printable () = default;",
0,
"template <typename T_T__>",
"any_printable (T_T__ value) :",
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
"any_printable (any_printable && rhs) noexcept = default;",
0,
"template <typename T_T__>",
"any_printable & operator= (T_T__ value)",
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
"any_printable & operator= (any_printable && rhs) noexcept = default;"
};
print_lines(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data& data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print_lines(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
// TODO: pure virtual
const char* handle_preamble[] = {
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print_lines(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
// TODO: virtual implementations
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print_lines(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function(const client_data& data, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data);
const std::string open_brace = "{";
const std::string semicolon = ";";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
std::cout << " ";
std::cout << c_str;
}
free_tokens(data.tu, tokens);
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ? "" : "return ";
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << return_str << "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( ";
const int args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < args; ++i) {
if (i)
std::cout << ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
std::cout << clang_getCString(clang_getCursorSpelling(arg_cursor));
}
std::cout << " ); }\n";
}
void open_namespace (const client_data& data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data& data)
{ std::cout << "\n" << indent(data) << "}\n"; }
void dump_cursor (const char* name, CXCursor cursor)
{
CXCursorKind kind = clang_getCursorKind(cursor);
CXString kind_spelling = clang_getCursorKindSpelling(kind);
CXString cursor_spelling = clang_getCursorSpelling(cursor);
std::cout << name << " "
<< clang_getCString(kind_spelling) << " "
<< clang_getCString(cursor_spelling) << " "
<< "\n";
}
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data& data = *static_cast<client_data*>(data_);
#if 0
std::cout << "\n";
dump_cursor("cursor", cursor);
dump_cursor("parent", parent);
#endif
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
#if 0
dump_cursor("enclosing_namespace", enclosing_namespace);
#endif
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
#if 0
dump_cursor("enclosing_struct", enclosing_struct);
#endif
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
}
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
return CXChildVisit_Recurse;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_None
);
client_data data = {tu, {}, clang_getNullCursor()};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: color.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2008-02-19 13:11:43 $
*
* 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 _TOOLS_COLOR_HXX
#define _TOOLS_COLOR_HXX
#ifndef INCLUDED_TOOLSDLLAPI_H
#include "tools/toolsdllapi.h"
#endif
class SvStream;
class ResId;
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
// --------------------
// - ColorCount-Types -
// --------------------
#define COLCOUNT_MONOCHROM ((ULONG)2)
#define COLCOUNT_16 ((ULONG)16)
#define COLCOUNT_256 ((ULONG)256)
#define COLCOUNT_HICOLOR1 (((ULONG)0x00007FFF)+1)
#define COLCOUNT_HICOLOR2 (((ULONG)0x0000FFFF)+1)
#define COLCOUNT_TRUECOLOR (((ULONG)0x00FFFFFF)+1)
// ---------------
// - Color-Types -
// ---------------
typedef UINT32 ColorData;
#define RGB_COLORDATA( r,g,b ) ((ColorData)(((UINT32)((UINT8)(b))))|(((UINT32)((UINT8)(g)))<<8)|(((UINT32)((UINT8)(r)))<<16))
#define TRGB_COLORDATA( t,r,g,b ) ((ColorData)(((UINT32)((UINT8)(b))))|(((UINT32)((UINT8)(g)))<<8)|(((UINT32)((UINT8)(r)))<<16)|(((UINT32)((UINT8)(t)))<<24))
#define COLORDATA_RED( n ) ((UINT8)((n)>>16))
#define COLORDATA_GREEN( n ) ((UINT8)(((UINT16)(n)) >> 8))
#define COLORDATA_BLUE( n ) ((UINT8)(n))
#define COLORDATA_TRANSPARENCY( n ) ((UINT8)((n)>>24))
#define COLORDATA_RGB( n ) ((ColorData)((n) & 0x00FFFFFF))
#define COL_BLACK RGB_COLORDATA( 0x00, 0x00, 0x00 )
#define COL_BLUE RGB_COLORDATA( 0x00, 0x00, 0x80 )
#define COL_GREEN RGB_COLORDATA( 0x00, 0x80, 0x00 )
#define COL_CYAN RGB_COLORDATA( 0x00, 0x80, 0x80 )
#define COL_RED RGB_COLORDATA( 0x80, 0x00, 0x00 )
#define COL_MAGENTA RGB_COLORDATA( 0x80, 0x00, 0x80 )
#define COL_BROWN RGB_COLORDATA( 0x80, 0x80, 0x00 )
#define COL_GRAY RGB_COLORDATA( 0x80, 0x80, 0x80 )
#define COL_LIGHTGRAY RGB_COLORDATA( 0xC0, 0xC0, 0xC0 )
#define COL_LIGHTBLUE RGB_COLORDATA( 0x00, 0x00, 0xFF )
#define COL_LIGHTGREEN RGB_COLORDATA( 0x00, 0xFF, 0x00 )
#define COL_LIGHTCYAN RGB_COLORDATA( 0x00, 0xFF, 0xFF )
#define COL_LIGHTRED RGB_COLORDATA( 0xFF, 0x00, 0x00 )
#define COL_LIGHTMAGENTA RGB_COLORDATA( 0xFF, 0x00, 0xFF )
#define COL_YELLOW RGB_COLORDATA( 0xFF, 0xFF, 0x00 )
#define COL_WHITE RGB_COLORDATA( 0xFF, 0xFF, 0xFF )
#define COL_TRANSPARENT TRGB_COLORDATA( 0xFF, 0xFF, 0xFF, 0xFF )
#define COL_AUTO (UINT32)0xFFFFFFFF
#define COL_AUTHOR1_DARK RGB_COLORDATA(198, 146, 0)
#define COL_AUTHOR1_NORMAL RGB_COLORDATA(255, 255, 158)
#define COL_AUTHOR1_LIGHT RGB_COLORDATA(255, 255, 195)
#define COL_AUTHOR2_DARK RGB_COLORDATA(6, 70, 162)
#define COL_AUTHOR2_NORMAL RGB_COLORDATA(216, 232, 255)
#define COL_AUTHOR2_LIGHT RGB_COLORDATA(233, 242, 255)
#define COL_AUTHOR3_DARK RGB_COLORDATA(87, 157, 28)
#define COL_AUTHOR3_NORMAL RGB_COLORDATA(218, 248, 193)
#define COL_AUTHOR3_LIGHT RGB_COLORDATA(226, 250, 207)
#define COL_AUTHOR4_DARK RGB_COLORDATA(105, 43, 157)
#define COL_AUTHOR4_NORMAL RGB_COLORDATA(228, 210, 245)
#define COL_AUTHOR4_LIGHT RGB_COLORDATA(239, 228, 248)
#define COL_AUTHOR5_DARK RGB_COLORDATA(197, 0, 11)
#define COL_AUTHOR5_NORMAL RGB_COLORDATA(254, 205, 208)
#define COL_AUTHOR5_LIGHT RGB_COLORDATA(255, 227, 229)
#define COL_AUTHOR6_DARK RGB_COLORDATA(0, 128, 128)
#define COL_AUTHOR6_NORMAL RGB_COLORDATA(210, 246, 246)
#define COL_AUTHOR6_LIGHT RGB_COLORDATA(230, 250, 250)
#define COL_AUTHOR7_DARK RGB_COLORDATA(140, 132, 0)
#define COL_AUTHOR7_NORMAL RGB_COLORDATA(237, 252, 163)
#define COL_AUTHOR7_LIGHT RGB_COLORDATA(242, 254, 181)
#define COL_AUTHOR8_DARK RGB_COLORDATA(53, 85, 107)
#define COL_AUTHOR8_NORMAL RGB_COLORDATA(211, 222, 232)
#define COL_AUTHOR8_LIGHT RGB_COLORDATA(226, 234, 241)
#define COL_AUTHOR9_DARK RGB_COLORDATA(209, 118, 0)
#define COL_AUTHOR9_NORMAL RGB_COLORDATA(255, 226, 185)
#define COL_AUTHOR9_LIGHT RGB_COLORDATA(255, 231, 199)
#define COLOR_CHANNEL_MERGE( _def_cDst, _def_cSrc, _def_cSrcTrans ) \
((BYTE)((((long)(_def_cDst)-(_def_cSrc))*(_def_cSrcTrans)+(((_def_cSrc)<<8L)|(_def_cDst)))>>8L))
// ---------
// - Color -
// ---------
class TOOLS_DLLPUBLIC Color
{
protected:
ColorData mnColor;
public:
Color() { mnColor = COL_BLACK; }
Color( ColorData nColor ) { mnColor = nColor; }
Color( UINT8 nRed, UINT8 nGreen, UINT8 nBlue )
{ mnColor = RGB_COLORDATA( nRed, nGreen, nBlue ); }
Color( UINT8 nTransparency, UINT8 nRed, UINT8 nGreen, UINT8 nBlue )
{ mnColor = TRGB_COLORDATA( nTransparency, nRed, nGreen, nBlue ); }
Color( const ResId& rResId );
// This ctor is defined in svtools, not tools!
void SetRed( UINT8 nRed );
UINT8 GetRed() const { return COLORDATA_RED( mnColor ); }
void SetGreen( UINT8 nGreen );
UINT8 GetGreen() const { return COLORDATA_GREEN( mnColor ); }
void SetBlue( UINT8 nBlue );
UINT8 GetBlue() const { return COLORDATA_BLUE( mnColor ); }
void SetTransparency( UINT8 nTransparency );
UINT8 GetTransparency() const { return COLORDATA_TRANSPARENCY( mnColor ); }
void SetColor( ColorData nColor ) { mnColor = nColor; }
ColorData GetColor() const { return mnColor; }
ColorData GetRGBColor() const { return COLORDATA_RGB( mnColor ); }
UINT8 GetColorError( const Color& rCompareColor ) const;
UINT8 GetLuminance() const;
void IncreaseLuminance( UINT8 cLumInc );
void DecreaseLuminance( UINT8 cLumDec );
void IncreaseContrast( UINT8 cContInc );
void DecreaseContrast( UINT8 cContDec );
void Invert();
void Merge( const Color& rMergeColor, BYTE cTransparency );
BOOL IsRGBEqual( const Color& rColor ) const;
// comparison with luminance thresholds
BOOL IsDark() const;
BOOL IsBright() const;
// color space conversion tools
// the range for h/s/b is:
// Hue: 0-360 degree
// Saturation: 0-100 %
// Brightness: 0-100 %
static ColorData HSBtoRGB( USHORT nHue, USHORT nSat, USHORT nBri );
void RGBtoHSB( USHORT& nHue, USHORT& nSat, USHORT& nBri ) const;
BOOL operator==( const Color& rColor ) const
{ return (mnColor == rColor.mnColor); }
BOOL operator!=( const Color& rColor ) const
{ return !(Color::operator==( rColor )); }
SvStream& Read( SvStream& rIStm, BOOL bNewFormat = TRUE );
SvStream& Write( SvStream& rOStm, BOOL bNewFormat = TRUE );
TOOLS_DLLPUBLIC friend SvStream& operator>>( SvStream& rIStream, Color& rColor );
TOOLS_DLLPUBLIC friend SvStream& operator<<( SvStream& rOStream, const Color& rColor );
};
inline void Color::SetRed( UINT8 nRed )
{
mnColor &= 0xFF00FFFF;
mnColor |= ((UINT32)nRed)<<16;
}
inline void Color::SetGreen( UINT8 nGreen )
{
mnColor &= 0xFFFF00FF;
mnColor |= ((UINT16)nGreen)<<8;
}
inline void Color::SetBlue( UINT8 nBlue )
{
mnColor &= 0xFFFFFF00;
mnColor |= nBlue;
}
inline void Color::SetTransparency( UINT8 nTransparency )
{
mnColor &= 0x00FFFFFF;
mnColor |= ((UINT32)nTransparency)<<24;
}
inline BOOL Color::IsRGBEqual( const Color& rColor ) const
{
return (COLORDATA_RGB( mnColor ) == COLORDATA_RGB( rColor.mnColor ));
}
inline UINT8 Color::GetLuminance() const
{
return( (UINT8) ( ( COLORDATA_BLUE( mnColor ) * 28UL +
COLORDATA_GREEN( mnColor ) * 151UL +
COLORDATA_RED( mnColor ) * 77UL ) >> 8UL ) );
}
inline void Color::Merge( const Color& rMergeColor, BYTE cTransparency )
{
SetRed( COLOR_CHANNEL_MERGE( COLORDATA_RED( mnColor ), COLORDATA_RED( rMergeColor.mnColor ), cTransparency ) );
SetGreen( COLOR_CHANNEL_MERGE( COLORDATA_GREEN( mnColor ), COLORDATA_GREEN( rMergeColor.mnColor ), cTransparency ) );
SetBlue( COLOR_CHANNEL_MERGE( COLORDATA_BLUE( mnColor ), COLORDATA_BLUE( rMergeColor.mnColor ), cTransparency ) );
}
#endif // _TOOLS_COLOR_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.22); FILE MERGED 2008/04/01 12:57:19 thb 1.3.22.2: #i85898# Stripping all external header guards 2008/03/28 15:41:07 rt 1.3.22.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: color.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 _TOOLS_COLOR_HXX
#define _TOOLS_COLOR_HXX
#include "tools/toolsdllapi.h"
class SvStream;
class ResId;
#include <tools/solar.h>
// --------------------
// - ColorCount-Types -
// --------------------
#define COLCOUNT_MONOCHROM ((ULONG)2)
#define COLCOUNT_16 ((ULONG)16)
#define COLCOUNT_256 ((ULONG)256)
#define COLCOUNT_HICOLOR1 (((ULONG)0x00007FFF)+1)
#define COLCOUNT_HICOLOR2 (((ULONG)0x0000FFFF)+1)
#define COLCOUNT_TRUECOLOR (((ULONG)0x00FFFFFF)+1)
// ---------------
// - Color-Types -
// ---------------
typedef UINT32 ColorData;
#define RGB_COLORDATA( r,g,b ) ((ColorData)(((UINT32)((UINT8)(b))))|(((UINT32)((UINT8)(g)))<<8)|(((UINT32)((UINT8)(r)))<<16))
#define TRGB_COLORDATA( t,r,g,b ) ((ColorData)(((UINT32)((UINT8)(b))))|(((UINT32)((UINT8)(g)))<<8)|(((UINT32)((UINT8)(r)))<<16)|(((UINT32)((UINT8)(t)))<<24))
#define COLORDATA_RED( n ) ((UINT8)((n)>>16))
#define COLORDATA_GREEN( n ) ((UINT8)(((UINT16)(n)) >> 8))
#define COLORDATA_BLUE( n ) ((UINT8)(n))
#define COLORDATA_TRANSPARENCY( n ) ((UINT8)((n)>>24))
#define COLORDATA_RGB( n ) ((ColorData)((n) & 0x00FFFFFF))
#define COL_BLACK RGB_COLORDATA( 0x00, 0x00, 0x00 )
#define COL_BLUE RGB_COLORDATA( 0x00, 0x00, 0x80 )
#define COL_GREEN RGB_COLORDATA( 0x00, 0x80, 0x00 )
#define COL_CYAN RGB_COLORDATA( 0x00, 0x80, 0x80 )
#define COL_RED RGB_COLORDATA( 0x80, 0x00, 0x00 )
#define COL_MAGENTA RGB_COLORDATA( 0x80, 0x00, 0x80 )
#define COL_BROWN RGB_COLORDATA( 0x80, 0x80, 0x00 )
#define COL_GRAY RGB_COLORDATA( 0x80, 0x80, 0x80 )
#define COL_LIGHTGRAY RGB_COLORDATA( 0xC0, 0xC0, 0xC0 )
#define COL_LIGHTBLUE RGB_COLORDATA( 0x00, 0x00, 0xFF )
#define COL_LIGHTGREEN RGB_COLORDATA( 0x00, 0xFF, 0x00 )
#define COL_LIGHTCYAN RGB_COLORDATA( 0x00, 0xFF, 0xFF )
#define COL_LIGHTRED RGB_COLORDATA( 0xFF, 0x00, 0x00 )
#define COL_LIGHTMAGENTA RGB_COLORDATA( 0xFF, 0x00, 0xFF )
#define COL_YELLOW RGB_COLORDATA( 0xFF, 0xFF, 0x00 )
#define COL_WHITE RGB_COLORDATA( 0xFF, 0xFF, 0xFF )
#define COL_TRANSPARENT TRGB_COLORDATA( 0xFF, 0xFF, 0xFF, 0xFF )
#define COL_AUTO (UINT32)0xFFFFFFFF
#define COL_AUTHOR1_DARK RGB_COLORDATA(198, 146, 0)
#define COL_AUTHOR1_NORMAL RGB_COLORDATA(255, 255, 158)
#define COL_AUTHOR1_LIGHT RGB_COLORDATA(255, 255, 195)
#define COL_AUTHOR2_DARK RGB_COLORDATA(6, 70, 162)
#define COL_AUTHOR2_NORMAL RGB_COLORDATA(216, 232, 255)
#define COL_AUTHOR2_LIGHT RGB_COLORDATA(233, 242, 255)
#define COL_AUTHOR3_DARK RGB_COLORDATA(87, 157, 28)
#define COL_AUTHOR3_NORMAL RGB_COLORDATA(218, 248, 193)
#define COL_AUTHOR3_LIGHT RGB_COLORDATA(226, 250, 207)
#define COL_AUTHOR4_DARK RGB_COLORDATA(105, 43, 157)
#define COL_AUTHOR4_NORMAL RGB_COLORDATA(228, 210, 245)
#define COL_AUTHOR4_LIGHT RGB_COLORDATA(239, 228, 248)
#define COL_AUTHOR5_DARK RGB_COLORDATA(197, 0, 11)
#define COL_AUTHOR5_NORMAL RGB_COLORDATA(254, 205, 208)
#define COL_AUTHOR5_LIGHT RGB_COLORDATA(255, 227, 229)
#define COL_AUTHOR6_DARK RGB_COLORDATA(0, 128, 128)
#define COL_AUTHOR6_NORMAL RGB_COLORDATA(210, 246, 246)
#define COL_AUTHOR6_LIGHT RGB_COLORDATA(230, 250, 250)
#define COL_AUTHOR7_DARK RGB_COLORDATA(140, 132, 0)
#define COL_AUTHOR7_NORMAL RGB_COLORDATA(237, 252, 163)
#define COL_AUTHOR7_LIGHT RGB_COLORDATA(242, 254, 181)
#define COL_AUTHOR8_DARK RGB_COLORDATA(53, 85, 107)
#define COL_AUTHOR8_NORMAL RGB_COLORDATA(211, 222, 232)
#define COL_AUTHOR8_LIGHT RGB_COLORDATA(226, 234, 241)
#define COL_AUTHOR9_DARK RGB_COLORDATA(209, 118, 0)
#define COL_AUTHOR9_NORMAL RGB_COLORDATA(255, 226, 185)
#define COL_AUTHOR9_LIGHT RGB_COLORDATA(255, 231, 199)
#define COLOR_CHANNEL_MERGE( _def_cDst, _def_cSrc, _def_cSrcTrans ) \
((BYTE)((((long)(_def_cDst)-(_def_cSrc))*(_def_cSrcTrans)+(((_def_cSrc)<<8L)|(_def_cDst)))>>8L))
// ---------
// - Color -
// ---------
class TOOLS_DLLPUBLIC Color
{
protected:
ColorData mnColor;
public:
Color() { mnColor = COL_BLACK; }
Color( ColorData nColor ) { mnColor = nColor; }
Color( UINT8 nRed, UINT8 nGreen, UINT8 nBlue )
{ mnColor = RGB_COLORDATA( nRed, nGreen, nBlue ); }
Color( UINT8 nTransparency, UINT8 nRed, UINT8 nGreen, UINT8 nBlue )
{ mnColor = TRGB_COLORDATA( nTransparency, nRed, nGreen, nBlue ); }
Color( const ResId& rResId );
// This ctor is defined in svtools, not tools!
void SetRed( UINT8 nRed );
UINT8 GetRed() const { return COLORDATA_RED( mnColor ); }
void SetGreen( UINT8 nGreen );
UINT8 GetGreen() const { return COLORDATA_GREEN( mnColor ); }
void SetBlue( UINT8 nBlue );
UINT8 GetBlue() const { return COLORDATA_BLUE( mnColor ); }
void SetTransparency( UINT8 nTransparency );
UINT8 GetTransparency() const { return COLORDATA_TRANSPARENCY( mnColor ); }
void SetColor( ColorData nColor ) { mnColor = nColor; }
ColorData GetColor() const { return mnColor; }
ColorData GetRGBColor() const { return COLORDATA_RGB( mnColor ); }
UINT8 GetColorError( const Color& rCompareColor ) const;
UINT8 GetLuminance() const;
void IncreaseLuminance( UINT8 cLumInc );
void DecreaseLuminance( UINT8 cLumDec );
void IncreaseContrast( UINT8 cContInc );
void DecreaseContrast( UINT8 cContDec );
void Invert();
void Merge( const Color& rMergeColor, BYTE cTransparency );
BOOL IsRGBEqual( const Color& rColor ) const;
// comparison with luminance thresholds
BOOL IsDark() const;
BOOL IsBright() const;
// color space conversion tools
// the range for h/s/b is:
// Hue: 0-360 degree
// Saturation: 0-100 %
// Brightness: 0-100 %
static ColorData HSBtoRGB( USHORT nHue, USHORT nSat, USHORT nBri );
void RGBtoHSB( USHORT& nHue, USHORT& nSat, USHORT& nBri ) const;
BOOL operator==( const Color& rColor ) const
{ return (mnColor == rColor.mnColor); }
BOOL operator!=( const Color& rColor ) const
{ return !(Color::operator==( rColor )); }
SvStream& Read( SvStream& rIStm, BOOL bNewFormat = TRUE );
SvStream& Write( SvStream& rOStm, BOOL bNewFormat = TRUE );
TOOLS_DLLPUBLIC friend SvStream& operator>>( SvStream& rIStream, Color& rColor );
TOOLS_DLLPUBLIC friend SvStream& operator<<( SvStream& rOStream, const Color& rColor );
};
inline void Color::SetRed( UINT8 nRed )
{
mnColor &= 0xFF00FFFF;
mnColor |= ((UINT32)nRed)<<16;
}
inline void Color::SetGreen( UINT8 nGreen )
{
mnColor &= 0xFFFF00FF;
mnColor |= ((UINT16)nGreen)<<8;
}
inline void Color::SetBlue( UINT8 nBlue )
{
mnColor &= 0xFFFFFF00;
mnColor |= nBlue;
}
inline void Color::SetTransparency( UINT8 nTransparency )
{
mnColor &= 0x00FFFFFF;
mnColor |= ((UINT32)nTransparency)<<24;
}
inline BOOL Color::IsRGBEqual( const Color& rColor ) const
{
return (COLORDATA_RGB( mnColor ) == COLORDATA_RGB( rColor.mnColor ));
}
inline UINT8 Color::GetLuminance() const
{
return( (UINT8) ( ( COLORDATA_BLUE( mnColor ) * 28UL +
COLORDATA_GREEN( mnColor ) * 151UL +
COLORDATA_RED( mnColor ) * 77UL ) >> 8UL ) );
}
inline void Color::Merge( const Color& rMergeColor, BYTE cTransparency )
{
SetRed( COLOR_CHANNEL_MERGE( COLORDATA_RED( mnColor ), COLORDATA_RED( rMergeColor.mnColor ), cTransparency ) );
SetGreen( COLOR_CHANNEL_MERGE( COLORDATA_GREEN( mnColor ), COLORDATA_GREEN( rMergeColor.mnColor ), cTransparency ) );
SetBlue( COLOR_CHANNEL_MERGE( COLORDATA_BLUE( mnColor ), COLORDATA_BLUE( rMergeColor.mnColor ), cTransparency ) );
}
#endif // _TOOLS_COLOR_HXX
<|endoftext|> |
<commit_before>/**
*Implement wildcard pattern matching with support for '?' and '*'.
*'?' Matches any single character. '*' Matches any sequence of
*characters (including the empty sequence).
*The matching should cover the entire input string (not partial).
*The function prototype should be:
* bool isMatch(const char *s, const char *p)
*Some examples:
* isMatch("aa","a") → false
* isMatch("aa","aa") → true
* isMatch("aaa","aa") → false
* isMatch("aa", "*") → true
* isMatch("aa", "a*") → true
* isMatch("ab", "?*") → true
* isMatch("aab", "c*a*b") → false
* */
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if(s == NULL)
return p == NULL;
if(*p == '*') {
while(*p == '*')
p++;
if(*p == '\0')
return true;
while(*s != '\0' && !isMatch(s, p))
s++;
return *s != '\0';
} else if(*p == '\0' || *s == '\0') {
return *p == *s;
} else if(*p == *s || *p == '?') {
return isMatch(s++, p++);
} else {
return false;
}
}
};
<commit_msg>wildcard matching iteration<commit_after>/**
*Implement wildcard pattern matching with support for '?' and '*'.
*'?' Matches any single character. '*' Matches any sequence of
*characters (including the empty sequence).
*The matching should cover the entire input string (not partial).
*The function prototype should be:
* bool isMatch(const char *s, const char *p)
*Some examples:
* isMatch("aa","a") → false
* isMatch("aa","aa") → true
* isMatch("aaa","aa") → false
* isMatch("aa", "*") → true
* isMatch("aa", "a*") → true
* isMatch("ab", "?*") → true
* isMatch("aab", "c*a*b") → false
* */
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if(s == NULL)
return p == NULL;
if(*p == '*') {
while(*p == '*')
p++;
if(*p == '\0')
return true;
while(*s != '\0' && !isMatch(s, p))
s++;
return *s != '\0';
} else if(*p == '\0' || *s == '\0') {
return *p == *s;
} else if(*p == *s || *p == '?') {
return isMatch(s++, p++);
} else {
return false;
}
}
bool isMatch_iteration(const char *s, const char *p) {
bool star = false;
const char *str, *ptr;
for(str = s, ptr = p; *str; str++, ptr++) {
switch(*ptr) {
case '?':
break;
case '*':
star = true;
s = str, p = ptr;
while(*p == '*')
p++;
if(*p == '\0')
return true;
str = s - 1;
ptr = p - 1;
break;
default:
if(*str != *ptr) {
if(!star)
return false;
s++;
str = s - 1;
ptr = p - 1;
}
}
}
while(*ptr == '*')
ptr++;
return *ptr == '\0';
}
};
<|endoftext|> |
<commit_before>#include <bts/blockchain/asset_operations.hpp>
#include <bts/blockchain/chain_interface.hpp>
#include <bts/blockchain/exceptions.hpp>
namespace bts { namespace blockchain {
bool create_asset_operation::is_power_of_ten( uint64_t n )
{
switch( n )
{
case 1ll:
case 10ll:
case 100ll:
case 1000ll:
case 10000ll:
case 100000ll:
case 1000000ll:
case 10000000ll:
case 100000000ll:
case 1000000000ll:
case 10000000000ll:
case 100000000000ll:
case 1000000000000ll:
case 10000000000000ll:
case 100000000000000ll:
case 1000000000000000ll:
return true;
default:
return false;
}
}
void create_asset_operation::evaluate( transaction_evaluation_state& eval_state )
{ try {
if( NOT eval_state._current_state->is_valid_symbol_name( this->symbol ) )
FC_CAPTURE_AND_THROW( invalid_asset_symbol, (symbol) );
oasset_record current_asset_record = eval_state._current_state->get_asset_record( this->symbol );
if( current_asset_record.valid() )
FC_CAPTURE_AND_THROW( asset_symbol_in_use, (symbol) );
const asset_id_type asset_id = eval_state._current_state->last_asset_id() + 1;
current_asset_record = eval_state._current_state->get_asset_record( asset_id );
if( current_asset_record.valid() )
FC_CAPTURE_AND_THROW( asset_id_in_use, (asset_id) );
if( issuer_account_id != asset_record::market_issued_asset )
{
const oaccount_record issuer_account_record = eval_state._current_state->get_account_record( this->issuer_account_id );
if( NOT issuer_account_record.valid() )
FC_CAPTURE_AND_THROW( unknown_account_id, (issuer_account_id) );
}
if( this->maximum_share_supply <= 0 || this->maximum_share_supply > BTS_BLOCKCHAIN_MAX_SHARES )
FC_CAPTURE_AND_THROW( invalid_asset_amount, (maximum_share_supply) );
if( NOT is_power_of_ten( this->precision ) )
FC_CAPTURE_AND_THROW( invalid_precision, (precision) );
const asset reg_fee( eval_state._current_state->get_asset_registration_fee( this->symbol.size() ), 0 );
eval_state.required_fees += reg_fee;
asset_record new_record;
new_record.id = eval_state._current_state->new_asset_id();
new_record.symbol = this->symbol;
new_record.name = this->name;
new_record.description = this->description;
new_record.public_data = this->public_data;
new_record.issuer_account_id = this->issuer_account_id;
new_record.precision = this->precision;
new_record.registration_date = eval_state._current_state->now();
new_record.last_update = new_record.registration_date;
new_record.current_share_supply = 0;
new_record.maximum_share_supply = this->maximum_share_supply;
new_record.collected_fees = 0;
eval_state._current_state->store_asset_record( new_record );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
void update_asset_operation::evaluate( transaction_evaluation_state& eval_state )
{ try {
FC_ASSERT( !"Not enabled yet!" );
oasset_record current_asset_record = eval_state._current_state->get_asset_record( this->asset_id );
if( NOT current_asset_record.valid() )
FC_CAPTURE_AND_THROW( unknown_asset_id, (asset_id) );
// Cannot update name, description, max share supply, or precision if any shares have been issued
if( current_asset_record->current_share_supply > 0 )
{
FC_ASSERT( !this->name.valid() );
FC_ASSERT( !this->description.valid() );
FC_ASSERT( !this->maximum_share_supply.valid() );
FC_ASSERT( !this->precision.valid() );
}
const account_id_type& current_issuer_account_id = current_asset_record->issuer_account_id;
const oaccount_record current_issuer_account_record = eval_state._current_state->get_account_record( current_issuer_account_id );
if( NOT current_issuer_account_record.valid() )
FC_CAPTURE_AND_THROW( unknown_account_id, (current_issuer_account_id) );
if( NOT eval_state.account_or_any_parent_has_signed( *current_issuer_account_record ) )
FC_CAPTURE_AND_THROW( missing_signature, (*current_issuer_account_record) );
if( this->name.valid() )
current_asset_record->name = *this->name;
if( this->description.valid() )
current_asset_record->description = *this->description;
if( this->public_data.valid() )
current_asset_record->public_data = *this->public_data;
if( this->maximum_share_supply.valid() )
current_asset_record->maximum_share_supply = *this->maximum_share_supply;
if( this->precision.valid() )
current_asset_record->precision = *this->precision;
current_asset_record->last_update = eval_state._current_state->now();
eval_state._current_state->store_asset_record( *current_asset_record );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
void issue_asset_operation::evaluate( transaction_evaluation_state& eval_state )
{ try {
oasset_record current_asset_record = eval_state._current_state->get_asset_record( this->amount.asset_id );
if( NOT current_asset_record.valid() )
FC_CAPTURE_AND_THROW( unknown_asset_id, (amount.asset_id) );
if( current_asset_record->is_market_issued() )
FC_CAPTURE_AND_THROW( not_user_issued, (*current_asset_record) );
const account_id_type& issuer_account_id = current_asset_record->issuer_account_id;
const oaccount_record issuer_account_record = eval_state._current_state->get_account_record( issuer_account_id );
if( NOT issuer_account_record.valid() )
FC_CAPTURE_AND_THROW( unknown_account_id, (issuer_account_id) );
if( NOT eval_state.account_or_any_parent_has_signed( *issuer_account_record ) )
FC_CAPTURE_AND_THROW( missing_signature, (*issuer_account_record) );
if( this->amount.amount <= 0 )
FC_CAPTURE_AND_THROW( negative_issue, (amount) );
if( NOT current_asset_record->can_issue( this->amount ) )
FC_CAPTURE_AND_THROW( over_issue, (amount)(*current_asset_record) );
current_asset_record->current_share_supply += this->amount.amount;
eval_state.add_balance( this->amount );
current_asset_record->last_update = eval_state._current_state->now();
eval_state._current_state->store_asset_record( *current_asset_record );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
} } // bts::blockchain
<commit_msg>Only allow update asset operations that change something; issue #549<commit_after>#include <bts/blockchain/asset_operations.hpp>
#include <bts/blockchain/chain_interface.hpp>
#include <bts/blockchain/exceptions.hpp>
namespace bts { namespace blockchain {
bool create_asset_operation::is_power_of_ten( uint64_t n )
{
switch( n )
{
case 1ll:
case 10ll:
case 100ll:
case 1000ll:
case 10000ll:
case 100000ll:
case 1000000ll:
case 10000000ll:
case 100000000ll:
case 1000000000ll:
case 10000000000ll:
case 100000000000ll:
case 1000000000000ll:
case 10000000000000ll:
case 100000000000000ll:
case 1000000000000000ll:
return true;
default:
return false;
}
}
void create_asset_operation::evaluate( transaction_evaluation_state& eval_state )
{ try {
if( NOT eval_state._current_state->is_valid_symbol_name( this->symbol ) )
FC_CAPTURE_AND_THROW( invalid_asset_symbol, (symbol) );
oasset_record current_asset_record = eval_state._current_state->get_asset_record( this->symbol );
if( current_asset_record.valid() )
FC_CAPTURE_AND_THROW( asset_symbol_in_use, (symbol) );
const asset_id_type asset_id = eval_state._current_state->last_asset_id() + 1;
current_asset_record = eval_state._current_state->get_asset_record( asset_id );
if( current_asset_record.valid() )
FC_CAPTURE_AND_THROW( asset_id_in_use, (asset_id) );
if( issuer_account_id != asset_record::market_issued_asset )
{
const oaccount_record issuer_account_record = eval_state._current_state->get_account_record( this->issuer_account_id );
if( NOT issuer_account_record.valid() )
FC_CAPTURE_AND_THROW( unknown_account_id, (issuer_account_id) );
}
if( this->maximum_share_supply <= 0 || this->maximum_share_supply > BTS_BLOCKCHAIN_MAX_SHARES )
FC_CAPTURE_AND_THROW( invalid_asset_amount, (maximum_share_supply) );
if( NOT is_power_of_ten( this->precision ) )
FC_CAPTURE_AND_THROW( invalid_precision, (precision) );
const asset reg_fee( eval_state._current_state->get_asset_registration_fee( this->symbol.size() ), 0 );
eval_state.required_fees += reg_fee;
asset_record new_record;
new_record.id = eval_state._current_state->new_asset_id();
new_record.symbol = this->symbol;
new_record.name = this->name;
new_record.description = this->description;
new_record.public_data = this->public_data;
new_record.issuer_account_id = this->issuer_account_id;
new_record.precision = this->precision;
new_record.registration_date = eval_state._current_state->now();
new_record.last_update = new_record.registration_date;
new_record.current_share_supply = 0;
new_record.maximum_share_supply = this->maximum_share_supply;
new_record.collected_fees = 0;
eval_state._current_state->store_asset_record( new_record );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
#ifndef WIN32
#warning [SOFTFORK] Disable this operation until the next BTS hardfork, then remove
#endif
void update_asset_operation::evaluate( transaction_evaluation_state& eval_state )
{ try {
FC_ASSERT( !"Not enabled yet!" );
oasset_record current_asset_record = eval_state._current_state->get_asset_record( this->asset_id );
if( NOT current_asset_record.valid() )
FC_CAPTURE_AND_THROW( unknown_asset_id, (asset_id) );
// Reject no-ops
FC_ASSERT( this->name.valid() || this->description.valid() || this->public_data.valid()
|| this->maximum_share_supply.valid() || this->precision.valid() );
// Cannot update name, description, max share supply, or precision if any shares have been issued
if( current_asset_record->current_share_supply > 0 )
{
FC_ASSERT( !this->name.valid() );
FC_ASSERT( !this->description.valid() );
FC_ASSERT( !this->maximum_share_supply.valid() );
FC_ASSERT( !this->precision.valid() );
}
const account_id_type& current_issuer_account_id = current_asset_record->issuer_account_id;
const oaccount_record current_issuer_account_record = eval_state._current_state->get_account_record( current_issuer_account_id );
if( NOT current_issuer_account_record.valid() )
FC_CAPTURE_AND_THROW( unknown_account_id, (current_issuer_account_id) );
if( NOT eval_state.account_or_any_parent_has_signed( *current_issuer_account_record ) )
FC_CAPTURE_AND_THROW( missing_signature, (*current_issuer_account_record) );
if( this->name.valid() )
current_asset_record->name = *this->name;
if( this->description.valid() )
current_asset_record->description = *this->description;
if( this->public_data.valid() )
current_asset_record->public_data = *this->public_data;
if( this->maximum_share_supply.valid() )
current_asset_record->maximum_share_supply = *this->maximum_share_supply;
if( this->precision.valid() )
current_asset_record->precision = *this->precision;
current_asset_record->last_update = eval_state._current_state->now();
eval_state._current_state->store_asset_record( *current_asset_record );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
void issue_asset_operation::evaluate( transaction_evaluation_state& eval_state )
{ try {
oasset_record current_asset_record = eval_state._current_state->get_asset_record( this->amount.asset_id );
if( NOT current_asset_record.valid() )
FC_CAPTURE_AND_THROW( unknown_asset_id, (amount.asset_id) );
if( current_asset_record->is_market_issued() )
FC_CAPTURE_AND_THROW( not_user_issued, (*current_asset_record) );
const account_id_type& issuer_account_id = current_asset_record->issuer_account_id;
const oaccount_record issuer_account_record = eval_state._current_state->get_account_record( issuer_account_id );
if( NOT issuer_account_record.valid() )
FC_CAPTURE_AND_THROW( unknown_account_id, (issuer_account_id) );
if( NOT eval_state.account_or_any_parent_has_signed( *issuer_account_record ) )
FC_CAPTURE_AND_THROW( missing_signature, (*issuer_account_record) );
if( this->amount.amount <= 0 )
FC_CAPTURE_AND_THROW( negative_issue, (amount) );
if( NOT current_asset_record->can_issue( this->amount ) )
FC_CAPTURE_AND_THROW( over_issue, (amount)(*current_asset_record) );
current_asset_record->current_share_supply += this->amount.amount;
eval_state.add_balance( this->amount );
current_asset_record->last_update = eval_state._current_state->now();
eval_state._current_state->store_asset_record( *current_asset_record );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
} } // bts::blockchain
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#ifndef UAVCAN_BUILD_CONFIG_HPP_INCLUDED
#define UAVCAN_BUILD_CONFIG_HPP_INCLUDED
/**
* UAVCAN version definition
*/
#define UAVCAN_VERSION_MAJOR 0
#define UAVCAN_VERSION_MINOR 1
/**
* UAVCAN_CPP_VERSION - version of the C++ standard used during compilation.
* This definition contains the integer year number after which the standard was named:
* - 2003 for C++03
* - 2011 for C++11
*
* This config automatically sets according to the actual C++ standard used by the compiler.
*
* In C++03 mode the library has almost zero dependency on the C++ standard library, which allows
* to use it on platforms with a very limited C++ support. On the other hand, C++11 mode requires
* many parts of the standard library (e.g. <functional>), thus the user might want to force older
* standard than used by the compiler, in which case this symbol can be overridden manually via
* compiler flags.
*/
#define UAVCAN_CPP11 2011
#define UAVCAN_CPP03 2003
#ifndef UAVCAN_CPP_VERSION
# if __cplusplus > 201200
# error Unsupported C++ standard
# elif (__cplusplus > 201100) || defined(__GXX_EXPERIMENTAL_CXX0X__)
# define UAVCAN_CPP_VERSION UAVCAN_CPP11
# else
# define UAVCAN_CPP_VERSION UAVCAN_CPP03
# endif
#endif
/**
* This macro enables built-in runtime checks and debug output via printf().
* Should be used only for library development.
*/
#ifndef UAVCAN_DEBUG
# define UAVCAN_DEBUG 0
#endif
/**
* UAVCAN can be explicitly told to ignore exceptions, or it can be detected automatically.
* Autodetection is not expected to work with all compilers, so it's safer to define it explicitly.
* If the autodetection fails, exceptions will be disabled by default.
*/
#ifndef UAVCAN_EXCEPTIONS
# if defined(__EXCEPTIONS) || defined(_HAS_EXCEPTIONS)
# define UAVCAN_EXCEPTIONS 1
# else
# define UAVCAN_EXCEPTIONS 0
# endif
#endif
/**
* This specification is used by some error reporting functions like in the Logger class.
* The default can be overriden by defining the macro UAVCAN_NOEXCEPT explicitly, e.g. via compiler options.
*/
#ifndef UAVCAN_NOEXCEPT
# if UAVCAN_EXCEPTIONS
# if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
# define UAVCAN_NOEXCEPT noexcept
# else
# define UAVCAN_NOEXCEPT throw()
# endif
# else
# define UAVCAN_NOEXCEPT
# endif
#endif
/**
* Struct layout control.
* Set UAVCAN_PACK_STRUCTS=1 and define UAVCAN_PACKED_BEGIN and UAVCAN_PACKED_END to reduce memory usage.
* THIS MAY BREAK THE CODE.
*/
#ifndef UAVCAN_PACK_STRUCTS
# define UAVCAN_PACK_STRUCTS 0
#endif
#ifndef UAVCAN_PACKED_BEGIN
# define UAVCAN_PACKED_BEGIN
#endif
#ifndef UAVCAN_PACKED_END
# define UAVCAN_PACKED_END
#endif
/**
* Declaration visibility
* http://gcc.gnu.org/wiki/Visibility
*/
#ifndef UAVCAN_EXPORT
# define UAVCAN_EXPORT
#endif
/**
* Trade-off between ROM/RAM usage and functionality/determinism.
* Note that this feature is not well tested and should be avoided.
* Use code search for UAVCAN_TINY to find what functionality will be disabled.
* This is particularly useful for embedded systems with less than 40kB of ROM.
*/
#ifndef UAVCAN_TINY
# define UAVCAN_TINY 0
#endif
/**
* It might make sense to remove toString() methods for an embedded system.
* If the autodetect fails, toString() will be disabled, so it's pretty safe by default.
*/
#ifndef UAVCAN_TOSTRING
// Objective is to make sure that we're NOT on a resource constrained platform
# if defined(__linux__) || defined(__linux) || defined(__APPLE__) || defined(_WIN64) || defined(_WIN32)
# define UAVCAN_TOSTRING 1
# else
# define UAVCAN_TOSTRING 0
# endif
#endif
#if UAVCAN_TOSTRING
# include <string>
# include <cstdio>
#endif
/**
* Some C++ implementations are half-broken because they don't implement the placement new operator.
* If UAVCAN_IMPLEMENT_PLACEMENT_NEW is defined, libuavcan will implement its own operator new (std::size_t, void*)
* and its delete() counterpart, instead of relying on the standard header <new>.
*/
#ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW
# define UAVCAN_IMPLEMENT_PLACEMENT_NEW 0
#endif
/**
* Run time checks.
* Resolves to the standard assert() by default.
* Disabled completely if UAVCAN_NO_ASSERTIONS is defined.
*/
#ifndef UAVCAN_ASSERT
# ifndef UAVCAN_NO_ASSERTIONS
# define UAVCAN_NO_ASSERTIONS 0
# endif
# if UAVCAN_NO_ASSERTIONS
# define UAVCAN_ASSERT(x)
# else
# define UAVCAN_ASSERT(x) assert(x)
# endif
#endif
namespace uavcan
{
/**
* Memory pool block size.
*
* The default of 64 bytes should be OK for any target arch up to AMD64 and any compiler.
*
* The library leverages compile-time checks to ensure that all types that are subject to dynamic allocation
* fit this size, otherwise compilation fails.
*
* For platforms featuring small pointer width (16..32 bits), UAVCAN_MEM_POOL_BLOCK_SIZE can often be safely
* reduced to 56 or even 48 bytes, which leads to lower memory footprint.
*
* Note that the pool block size shall be aligned at biggest alignment of the target platform (detected and
* checked automatically at compile time).
*/
#ifdef UAVCAN_MEM_POOL_BLOCK_SIZE
/// Explicitly specified by the user.
static const unsigned MemPoolBlockSize = UAVCAN_MEM_POOL_BLOCK_SIZE;
#elif defined(__BIGGEST_ALIGNMENT__) && (__BIGGEST_ALIGNMENT__ <= 8)
/// Convenient default for GCC-like compilers - if alignment allows, pool block size can be safely reduced.
static const unsigned MemPoolBlockSize = 56;
#else
/// Safe default that should be OK for any platform.
static const unsigned MemPoolBlockSize = 64;
#endif
#ifdef __BIGGEST_ALIGNMENT__
static const unsigned MemPoolAlignment = __BIGGEST_ALIGNMENT__;
#else
static const unsigned MemPoolAlignment = 16;
#endif
typedef char _alignment_check_for_MEM_POOL_BLOCK_SIZE[((MemPoolBlockSize & (MemPoolAlignment - 1)) == 0) ? 1 : -1];
/**
* This class that allows to check at compile time whether type T can be allocated using the memory pool.
* If the check fails, compilation fails.
*/
template <typename T>
struct UAVCAN_EXPORT IsDynamicallyAllocatable
{
static void check()
{
char dummy[(sizeof(T) <= MemPoolBlockSize) ? 1 : -1] = { '0' };
(void)dummy;
}
};
/**
* Float comparison precision.
* For details refer to:
* http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
* https://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h
*/
#ifdef UAVCAN_FLOAT_COMPARISON_EPSILON_MULT
static const unsigned FloatComparisonEpsilonMult = UAVCAN_FLOAT_COMPARISON_EPSILON_MULT;
#else
static const unsigned FloatComparisonEpsilonMult = 10;
#endif
}
#endif // UAVCAN_BUILD_CONFIG_HPP_INCLUDED
<commit_msg>UAVCAN_VERSION_NUMBER set to 1.0. Although it is not a release yet, no major changes are anticipated<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#ifndef UAVCAN_BUILD_CONFIG_HPP_INCLUDED
#define UAVCAN_BUILD_CONFIG_HPP_INCLUDED
/**
* UAVCAN version definition
*/
#define UAVCAN_VERSION_MAJOR 1
#define UAVCAN_VERSION_MINOR 0
/**
* UAVCAN_CPP_VERSION - version of the C++ standard used during compilation.
* This definition contains the integer year number after which the standard was named:
* - 2003 for C++03
* - 2011 for C++11
*
* This config automatically sets according to the actual C++ standard used by the compiler.
*
* In C++03 mode the library has almost zero dependency on the C++ standard library, which allows
* to use it on platforms with a very limited C++ support. On the other hand, C++11 mode requires
* many parts of the standard library (e.g. <functional>), thus the user might want to force older
* standard than used by the compiler, in which case this symbol can be overridden manually via
* compiler flags.
*/
#define UAVCAN_CPP11 2011
#define UAVCAN_CPP03 2003
#ifndef UAVCAN_CPP_VERSION
# if __cplusplus > 201200
# error Unsupported C++ standard
# elif (__cplusplus > 201100) || defined(__GXX_EXPERIMENTAL_CXX0X__)
# define UAVCAN_CPP_VERSION UAVCAN_CPP11
# else
# define UAVCAN_CPP_VERSION UAVCAN_CPP03
# endif
#endif
/**
* This macro enables built-in runtime checks and debug output via printf().
* Should be used only for library development.
*/
#ifndef UAVCAN_DEBUG
# define UAVCAN_DEBUG 0
#endif
/**
* UAVCAN can be explicitly told to ignore exceptions, or it can be detected automatically.
* Autodetection is not expected to work with all compilers, so it's safer to define it explicitly.
* If the autodetection fails, exceptions will be disabled by default.
*/
#ifndef UAVCAN_EXCEPTIONS
# if defined(__EXCEPTIONS) || defined(_HAS_EXCEPTIONS)
# define UAVCAN_EXCEPTIONS 1
# else
# define UAVCAN_EXCEPTIONS 0
# endif
#endif
/**
* This specification is used by some error reporting functions like in the Logger class.
* The default can be overriden by defining the macro UAVCAN_NOEXCEPT explicitly, e.g. via compiler options.
*/
#ifndef UAVCAN_NOEXCEPT
# if UAVCAN_EXCEPTIONS
# if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
# define UAVCAN_NOEXCEPT noexcept
# else
# define UAVCAN_NOEXCEPT throw()
# endif
# else
# define UAVCAN_NOEXCEPT
# endif
#endif
/**
* Struct layout control.
* Set UAVCAN_PACK_STRUCTS=1 and define UAVCAN_PACKED_BEGIN and UAVCAN_PACKED_END to reduce memory usage.
* THIS MAY BREAK THE CODE.
*/
#ifndef UAVCAN_PACK_STRUCTS
# define UAVCAN_PACK_STRUCTS 0
#endif
#ifndef UAVCAN_PACKED_BEGIN
# define UAVCAN_PACKED_BEGIN
#endif
#ifndef UAVCAN_PACKED_END
# define UAVCAN_PACKED_END
#endif
/**
* Declaration visibility
* http://gcc.gnu.org/wiki/Visibility
*/
#ifndef UAVCAN_EXPORT
# define UAVCAN_EXPORT
#endif
/**
* Trade-off between ROM/RAM usage and functionality/determinism.
* Note that this feature is not well tested and should be avoided.
* Use code search for UAVCAN_TINY to find what functionality will be disabled.
* This is particularly useful for embedded systems with less than 40kB of ROM.
*/
#ifndef UAVCAN_TINY
# define UAVCAN_TINY 0
#endif
/**
* It might make sense to remove toString() methods for an embedded system.
* If the autodetect fails, toString() will be disabled, so it's pretty safe by default.
*/
#ifndef UAVCAN_TOSTRING
// Objective is to make sure that we're NOT on a resource constrained platform
# if defined(__linux__) || defined(__linux) || defined(__APPLE__) || defined(_WIN64) || defined(_WIN32)
# define UAVCAN_TOSTRING 1
# else
# define UAVCAN_TOSTRING 0
# endif
#endif
#if UAVCAN_TOSTRING
# include <string>
# include <cstdio>
#endif
/**
* Some C++ implementations are half-broken because they don't implement the placement new operator.
* If UAVCAN_IMPLEMENT_PLACEMENT_NEW is defined, libuavcan will implement its own operator new (std::size_t, void*)
* and its delete() counterpart, instead of relying on the standard header <new>.
*/
#ifndef UAVCAN_IMPLEMENT_PLACEMENT_NEW
# define UAVCAN_IMPLEMENT_PLACEMENT_NEW 0
#endif
/**
* Run time checks.
* Resolves to the standard assert() by default.
* Disabled completely if UAVCAN_NO_ASSERTIONS is defined.
*/
#ifndef UAVCAN_ASSERT
# ifndef UAVCAN_NO_ASSERTIONS
# define UAVCAN_NO_ASSERTIONS 0
# endif
# if UAVCAN_NO_ASSERTIONS
# define UAVCAN_ASSERT(x)
# else
# define UAVCAN_ASSERT(x) assert(x)
# endif
#endif
namespace uavcan
{
/**
* Memory pool block size.
*
* The default of 64 bytes should be OK for any target arch up to AMD64 and any compiler.
*
* The library leverages compile-time checks to ensure that all types that are subject to dynamic allocation
* fit this size, otherwise compilation fails.
*
* For platforms featuring small pointer width (16..32 bits), UAVCAN_MEM_POOL_BLOCK_SIZE can often be safely
* reduced to 56 or even 48 bytes, which leads to lower memory footprint.
*
* Note that the pool block size shall be aligned at biggest alignment of the target platform (detected and
* checked automatically at compile time).
*/
#ifdef UAVCAN_MEM_POOL_BLOCK_SIZE
/// Explicitly specified by the user.
static const unsigned MemPoolBlockSize = UAVCAN_MEM_POOL_BLOCK_SIZE;
#elif defined(__BIGGEST_ALIGNMENT__) && (__BIGGEST_ALIGNMENT__ <= 8)
/// Convenient default for GCC-like compilers - if alignment allows, pool block size can be safely reduced.
static const unsigned MemPoolBlockSize = 56;
#else
/// Safe default that should be OK for any platform.
static const unsigned MemPoolBlockSize = 64;
#endif
#ifdef __BIGGEST_ALIGNMENT__
static const unsigned MemPoolAlignment = __BIGGEST_ALIGNMENT__;
#else
static const unsigned MemPoolAlignment = 16;
#endif
typedef char _alignment_check_for_MEM_POOL_BLOCK_SIZE[((MemPoolBlockSize & (MemPoolAlignment - 1)) == 0) ? 1 : -1];
/**
* This class that allows to check at compile time whether type T can be allocated using the memory pool.
* If the check fails, compilation fails.
*/
template <typename T>
struct UAVCAN_EXPORT IsDynamicallyAllocatable
{
static void check()
{
char dummy[(sizeof(T) <= MemPoolBlockSize) ? 1 : -1] = { '0' };
(void)dummy;
}
};
/**
* Float comparison precision.
* For details refer to:
* http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
* https://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h
*/
#ifdef UAVCAN_FLOAT_COMPARISON_EPSILON_MULT
static const unsigned FloatComparisonEpsilonMult = UAVCAN_FLOAT_COMPARISON_EPSILON_MULT;
#else
static const unsigned FloatComparisonEpsilonMult = 10;
#endif
}
#endif // UAVCAN_BUILD_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>/************************************************
* map_iterator.hpp
* ESA++
*
* Copyright (c) 2014, Chi-En Wu
* Distributed under The BSD 3-Clause License
************************************************/
#ifndef ESAPP_MAP_ITERATOR_HPP_
#define ESAPP_MAP_ITERATOR_HPP_
#include <type_traits>
#include "generator.hpp"
namespace esapp
{
template <typename T, typename I> class map_iterator;
/************************************************
* Inline Helper Function(s)
************************************************/
template <typename Transform, typename Iterable>
inline auto make_map_iterator(Transform const &transform,
Iterable const &iterable)
-> map_iterator<Transform, decltype(iterable.begin())>
{
typedef decltype(make_map_iterator(transform, iterable)) it_t;
return it_t(transform, iterable.begin(), iterable.end());
}
/************************************************
* Declaration: class map_iterator
************************************************/
template <typename Transform, typename Iterator>
class map_iterator
: public generator<
map_iterator<Transform, Iterator>,
Iterator,
typename std::result_of<
Transform(decltype(*std::declval<Iterator>()))
>::type
>
{
private: // Private Type(s)
typedef generator<
map_iterator,
Iterator,
typename std::result_of<
Transform(decltype(*std::declval<Iterator>()))
>::type
> supercls_t;
public: // Public Type(s)
typedef typename supercls_t::iterator_category iterator_category;
typedef typename supercls_t::value_type value_type;
typedef typename supercls_t::reference reference;
typedef typename supercls_t::pointer pointer;
typedef typename supercls_t::difference_type difference_type;
typedef typename supercls_t::input_iterator input_iterator;
typedef Transform transform;
public: // Public Method(s)
map_iterator(void) = default;
map_iterator(transform const &trans,
input_iterator const &begin,
input_iterator const &end = input_iterator());
map_iterator(map_iterator const &it) = default;
map_iterator end(void) const;
void next(void);
reference dereference(void) const;
private: // Private Property(ies)
transform trans_;
value_type val_;
}; // class map_iterator
/************************************************
* Implementation: class map_iterator
************************************************/
template <typename T, typename I>
inline map_iterator<T, I>::map_iterator(transform const &trans,
input_iterator const &begin,
input_iterator const &end)
: supercls_t(begin, end), trans_(trans)
{
if (this->it_ != this->end_)
{
val_ = trans_(*(this->it_));
}
}
template <typename T, typename I>
inline map_iterator<T, I> map_iterator<T, I>::end(void) const
{
return map_iterator(trans_, this->end_, this->end_);
}
template <typename T, typename I>
inline void map_iterator<T, I>::next(void)
{
val_ = trans_(*(++(this->it_)));
}
template <typename T, typename I>
inline typename map_iterator<T, I>::reference
map_iterator<T, I>::dereference(void) const
{
return val_;
}
} // namespace esapp
#endif // ESAPP_MAP_ITERATOR_HPP_
<commit_msg>Fix map_iterator<commit_after>/************************************************
* map_iterator.hpp
* ESA++
*
* Copyright (c) 2014, Chi-En Wu
* Distributed under The BSD 3-Clause License
************************************************/
#ifndef ESAPP_MAP_ITERATOR_HPP_
#define ESAPP_MAP_ITERATOR_HPP_
#include <type_traits>
#include "generator.hpp"
namespace esapp
{
template <typename T, typename I> class map_iterator;
/************************************************
* Inline Helper Function(s)
************************************************/
template <typename Transform, typename Iterable>
inline auto make_map_iterator(Transform const &transform,
Iterable const &iterable)
-> map_iterator<Transform, decltype(iterable.begin())>
{
typedef decltype(make_map_iterator(transform, iterable)) it_t;
return it_t(transform, iterable.begin(), iterable.end());
}
/************************************************
* Declaration: class map_iterator
************************************************/
template <typename Transform, typename Iterator>
class map_iterator
: public generator<
map_iterator<Transform, Iterator>,
Iterator,
typename std::result_of<
Transform(decltype(*std::declval<Iterator>()))
>::type
>
{
private: // Private Type(s)
typedef generator<
map_iterator,
Iterator,
typename std::result_of<
Transform(decltype(*std::declval<Iterator>()))
>::type
> supercls_t;
public: // Public Type(s)
typedef typename supercls_t::iterator_category iterator_category;
typedef typename supercls_t::value_type value_type;
typedef typename supercls_t::reference reference;
typedef typename supercls_t::pointer pointer;
typedef typename supercls_t::difference_type difference_type;
typedef typename supercls_t::input_iterator input_iterator;
typedef Transform transform;
public: // Public Method(s)
map_iterator(void) = default;
map_iterator(transform const &trans,
input_iterator const &begin,
input_iterator const &end = input_iterator());
map_iterator(map_iterator const &it) = default;
map_iterator end(void) const;
void next(void);
reference dereference(void) const;
bool equal(map_iterator const &it) const;
private: // Private Property(ies)
transform trans_;
value_type val_;
bool has_next_;
}; // class map_iterator
/************************************************
* Implementation: class map_iterator
************************************************/
template <typename T, typename I>
inline map_iterator<T, I>::map_iterator(transform const &trans,
input_iterator const &begin,
input_iterator const &end)
: supercls_t(begin, end), trans_(trans)
{
next();
}
template <typename T, typename I>
inline map_iterator<T, I> map_iterator<T, I>::end(void) const
{
return map_iterator(trans_, this->end_, this->end_);
}
template <typename T, typename I>
inline void map_iterator<T, I>::next(void)
{
has_next_ = this->it_ != this->end_;
if (!has_next_) { return; }
val_ = trans_(*(this->it_));
this->it_++;
}
template <typename T, typename I>
inline typename map_iterator<T, I>::reference
map_iterator<T, I>::dereference(void) const
{
return val_;
}
template <typename T, typename I>
inline bool map_iterator<T, I>::equal(map_iterator const &it) const
{
return this->it_ == it.it_ && has_next_ == it.has_next_;
}
} // namespace esapp
#endif // ESAPP_MAP_ITERATOR_HPP_
<|endoftext|> |
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_STDINT_TYPES_HPP
#define NOMLIB_STDINT_TYPES_HPP
#include <string> // std::size_t
#include <vector>
#include <limits> // min && max types
#include "nomlib/platforms.hpp"
// RTTI for library objects.
#include "nomlib/core/ObjectTypeInfo.hpp"
/*
TODO: This should be replaced by an actual CMake script -- think:
compile-time check for the necessary feature support for C++11 style
headers support.
Look into why GCC doesn't like the inclusion of <cstdint> -- otherwise
known as stdint.h. MSVCPP2013 & llvm-clang are fine with it).
*/
#ifndef NOM_PLATFORM_LINUX // To be replace with NOM_COMPILER_FEATURE_NULLPTR
// (see above TODO note).
#include <cstdint>
#else
#include <sys/types.h>
#endif
// FIXME: The following declaration is necessary in order to avoid a very
// nasty compiling conflict that can happen under Windows anytime the
// windef.h header file is included (commonly from windows.h), due to min and
// max macros being declared there. This is why macros are evil.
//
// http://support.microsoft.com/kb/143208
// http://stackoverflow.com/questions/5004858/stdmin-gives-error
#if defined( NOM_PLATFORM_WINDOWS )
#undef min
#undef max
#endif
// Borrowed from /usr/include/MacTypes.h && /usr/include/objc/objc.h:
#ifndef NULL
#if defined( NOM_COMPILER_FEATURE_NULLPTR )
#define NULL nullptr
#else
#define NULL 0 //__DARWIN_NULL
#endif
#endif // ! NULL
// Portable fixed-size data types derive from stdint.h
namespace nom {
/// \brief Signed 8-bit integer.
typedef int8_t int8;
/// \brief Unsigned 8-bit integer.
typedef uint8_t uint8;
/// \brief Signed 16-bit integer.
typedef int16_t int16;
/// \brief Unsigned 16-bit integer.
typedef uint16_t uint16;
/// \brief Signed 32-bit integer.
typedef int32_t int32;
/// \brief Unsigned 16-bit integer.
typedef uint32_t uint32;
/// \brief 32-bit IEEE floating-point value.
typedef float real32;
/// \brief 64-bit IEEE floating-point value.
typedef double real64;
/// \brief 64-bit integer types
/// \note As per **/usr/include/MacTypes.h**:
///
/// "The MS Visual C/C++ compiler uses __int64 instead of long long".
#if defined( NOM_COMPILER_MSVCPP ) && defined( NOM_PLATFORM_ARCH_X86 )
typedef signed __int64 int64;
typedef unsigned __int64 uint64;
#else // Blindly assume a 64-bit architecture
typedef int64_t int64; //typedef signed long long int int64;
typedef uint64_t uint64; //typedef unsigned long long int uint64;
#endif
// Additional integer type definitions
/// \brief Unsigned 8-bit character.
typedef unsigned char uchar;
/// \brief Variable-size (platform-defined) signed integer.
/// \deprecated This will be removed in a future version; use int type instead.
typedef signed int sint;
/// \brief Variable-size (platform-defined) unsigned integer.
typedef unsigned int uint;
typedef std::size_t size_type;
typedef intptr_t* int_ptr;
typedef uintptr_t* uint_ptr;
/// \deprecated This will be removed in a future version; use int_ptr type
/// instead.
typedef sint* sint_ptr;
typedef int32_t* int32_ptr;
typedef uint32_t* uint32_ptr;
typedef void* void_ptr;
typedef unsigned long ulong;
// Definitions for minimum && maximum integral types
//
// http://en.cppreference.com/w/cpp/types/numeric_limits
const int int_min = std::numeric_limits<int>::lowest();
const int int_max = std::numeric_limits<int>::max();
const uint uint_min = std::numeric_limits<uint>::lowest();
const uint uint_max = std::numeric_limits<uint>::max();
const int char_min = std::numeric_limits<char>::lowest();
const int char_max = std::numeric_limits<char>::max();
const uint uchar_min = std::numeric_limits<uchar>::lowest();
const uint uchar_max = std::numeric_limits<uchar>::max();
// Always an unsigned type
const size_type size_type_min = std::numeric_limits<size_type>::lowest();
const size_type size_type_max = std::numeric_limits<size_type>::max();
const real32 real32_min = std::numeric_limits<real32>::lowest();
const real32 real32_max = std::numeric_limits<real32>::max();
const real64 real64_min = std::numeric_limits<real64>::lowest();
const real64 real64_max = std::numeric_limits<real64>::max();
/// \brief An integer indicating that there is no match, an error or NULL.
static const int npos = -1;
/// \brief The default standard point size for fonts.
///
/// \remarks Used in default initialization of nom::Text, nom::UIWidget, etc.
static const int DEFAULT_FONT_SIZE = 12;
/// \brief Alignment types.
///
/// \remarks See also, nom::Anchor enumeration.
///
/// \note Borrowed from [maelstrom's screenlib](https://hg.libsdl.org/Maelstrom/)
enum Alignment: uint32
{
NONE = 0x0,
X_LEFT = 0x01,
X_CENTER = 0x02,
X_RIGHT = 0x4,
/// \remarks Horizontal
X_MASK = ( X_LEFT | X_CENTER | X_RIGHT ),
Y_TOP = 0x10,
Y_CENTER = 0x20,
Y_BOTTOM = 0x40,
/// \remarks Vertical
Y_MASK = ( Y_TOP | Y_CENTER | Y_BOTTOM )
};
/// \note Borrowed from [maelstrom's screenlib](https://hg.libsdl.org/Maelstrom/)
enum Anchor: uint32
{
None = NONE, // 0
Left = X_LEFT, // 1
Center = X_CENTER, // 2
Right = X_RIGHT, // 4
TopLeft = Y_TOP | X_LEFT, // Hex: 0x11, Dec: 17
TopCenter = Y_TOP | X_CENTER, // Hex: 0x12, Dec: 18
TopRight = Y_TOP | X_RIGHT, // Hex: 0x14, Dec: 20
MiddleLeft = Y_CENTER | X_LEFT, // Hex: 0x21, Dec: 33
MiddleCenter = Y_CENTER | X_CENTER, // Hex: 0x22, Dec: 34
MiddleRight = Y_CENTER | X_RIGHT, // Hex: 0x24, Dec: 36
BottomLeft = Y_BOTTOM | X_LEFT, // Hex: 0x41, Dec: 65
BottomCenter = Y_BOTTOM | X_CENTER, // Hex: 0x42, Dec: 66
BottomRight = Y_BOTTOM | X_RIGHT // Hex: 0x44, Dec: 68
};
typedef std::vector<std::string> StringList;
} // namespace nom
/// Ensure our data types have the right sizes using C++11 compile-time asserts.
static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" );
static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" );
static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" );
static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" );
static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" );
static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" );
static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" );
static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" );
static_assert ( sizeof ( nom::real32 ) == 4, "nom::real32" );
static_assert ( sizeof ( nom::real64 ) == 8, "nom::real64" );
static_assert ( sizeof ( nom::uchar ) == 1, "nom::uchar" );
// Blindly assumes we are on either a 64-bit or 32-bit platform.
#if defined( NOM_PLATFORM_ARCH_X86_64 )
static_assert( sizeof ( nom::ulong ) == 8, "nom::ulong" );
static_assert( sizeof ( nom::size_type ) == 8, "nom::size_type" );
#else // #elif defined( NOM_PLATFORM_ARCH_X86_86 )
static_assert( sizeof ( nom::ulong ) == 4, "nom::ulong" );
static_assert( sizeof ( nom::size_type ) == 4, "nom::size_type" );
#endif
// Blindly assumes we are on either a 64-bit or 32-bit platform.
#if defined( NOM_PLATFORM_ARCH_X86_64 )
static_assert( sizeof(nom::int_ptr) == 8, "nom::int_ptr" );
static_assert( sizeof(nom::uint_ptr) == 8, "nom::uint_ptr" );
static_assert( sizeof ( nom::int32_ptr ) == ( sizeof(long) ), "nom::int32_ptr" );
static_assert( sizeof ( nom::uint32_ptr ) == ( sizeof(nom::ulong) ), "nom::uint32_ptr" );
#else // #elif defined(NOM_PLATFORM_ARCH_X86)
static_assert( sizeof(nom::int_ptr) == 4, "nom::int_ptr" );
static_assert( sizeof(nom::uint_ptr) == 4, "nom::uint_ptr" );
static_assert( sizeof( nom::int32_ptr ) == ( sizeof( long ) ), "nom::int32_ptr" );
static_assert( sizeof( nom::uint32_ptr ) == ( sizeof( nom::ulong ) ), "nom::uint32_ptr" );
#endif
/// Additional type definitions
const nom::sint NOM_EXIT_FAILURE = 1; // EXIT_FAILURE from cstdlib headers
const nom::sint NOM_EXIT_SUCCESS = 0; // EXIT_SUCCESS from cstdlib headers
//#if defined(HAVE_SDL2)
const nom::sint SDL_SUCCESS = 0; // Non-error return value for SDL2 API
//#endif
#endif // include guard defined
<commit_msg>types.hpp: Add SIZE_TYPE_MIN, SIZE_TYPE_MAX<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_STDINT_TYPES_HPP
#define NOMLIB_STDINT_TYPES_HPP
#include <string> // std::size_t
#include <vector>
#include <limits> // min && max types
#include "nomlib/platforms.hpp"
// RTTI for library objects.
#include "nomlib/core/ObjectTypeInfo.hpp"
/*
TODO: This should be replaced by an actual CMake script -- think:
compile-time check for the necessary feature support for C++11 style
headers support.
Look into why GCC doesn't like the inclusion of <cstdint> -- otherwise
known as stdint.h. MSVCPP2013 & llvm-clang are fine with it).
*/
#ifndef NOM_PLATFORM_LINUX // To be replace with NOM_COMPILER_FEATURE_NULLPTR
// (see above TODO note).
#include <cstdint>
#else
#include <sys/types.h>
#endif
// FIXME: The following declaration is necessary in order to avoid a very
// nasty compiling conflict that can happen under Windows anytime the
// windef.h header file is included (commonly from windows.h), due to min and
// max macros being declared there. This is why macros are evil.
//
// http://support.microsoft.com/kb/143208
// http://stackoverflow.com/questions/5004858/stdmin-gives-error
#if defined( NOM_PLATFORM_WINDOWS )
#undef min
#undef max
#endif
// Borrowed from /usr/include/MacTypes.h && /usr/include/objc/objc.h:
#ifndef NULL
#if defined( NOM_COMPILER_FEATURE_NULLPTR )
#define NULL nullptr
#else
#define NULL 0 //__DARWIN_NULL
#endif
#endif // ! NULL
// Portable fixed-size data types derive from stdint.h
namespace nom {
/// \brief Signed 8-bit integer.
typedef int8_t int8;
/// \brief Unsigned 8-bit integer.
typedef uint8_t uint8;
/// \brief Signed 16-bit integer.
typedef int16_t int16;
/// \brief Unsigned 16-bit integer.
typedef uint16_t uint16;
/// \brief Signed 32-bit integer.
typedef int32_t int32;
/// \brief Unsigned 16-bit integer.
typedef uint32_t uint32;
/// \brief 32-bit IEEE floating-point value.
typedef float real32;
/// \brief 64-bit IEEE floating-point value.
typedef double real64;
/// \brief 64-bit integer types
/// \note As per **/usr/include/MacTypes.h**:
///
/// "The MS Visual C/C++ compiler uses __int64 instead of long long".
#if defined( NOM_COMPILER_MSVCPP ) && defined( NOM_PLATFORM_ARCH_X86 )
typedef signed __int64 int64;
typedef unsigned __int64 uint64;
#else // Blindly assume a 64-bit architecture
typedef int64_t int64; //typedef signed long long int int64;
typedef uint64_t uint64; //typedef unsigned long long int uint64;
#endif
// Additional integer type definitions
/// \brief Unsigned 8-bit character.
typedef unsigned char uchar;
/// \brief Variable-size (platform-defined) signed integer.
/// \deprecated This will be removed in a future version; use int type instead.
typedef signed int sint;
/// \brief Variable-size (platform-defined) unsigned integer.
typedef unsigned int uint;
typedef std::size_t size_type;
typedef intptr_t* int_ptr;
typedef uintptr_t* uint_ptr;
/// \deprecated This will be removed in a future version; use int_ptr type
/// instead.
typedef sint* sint_ptr;
typedef int32_t* int32_ptr;
typedef uint32_t* uint32_ptr;
typedef void* void_ptr;
typedef unsigned long ulong;
// Definitions for minimum && maximum integral types
//
// http://en.cppreference.com/w/cpp/types/numeric_limits
const int int_min = std::numeric_limits<int>::lowest();
const int int_max = std::numeric_limits<int>::max();
const uint uint_min = std::numeric_limits<uint>::lowest();
const uint uint_max = std::numeric_limits<uint>::max();
const int char_min = std::numeric_limits<char>::lowest();
const int char_max = std::numeric_limits<char>::max();
const uint uchar_min = std::numeric_limits<uchar>::lowest();
const uint uchar_max = std::numeric_limits<uchar>::max();
// Always an unsigned type
const size_type size_type_min = std::numeric_limits<size_type>::lowest();
const size_type size_type_max = std::numeric_limits<size_type>::max();
const real32 real32_min = std::numeric_limits<real32>::lowest();
const real32 real32_max = std::numeric_limits<real32>::max();
const real64 real64_min = std::numeric_limits<real64>::lowest();
const real64 real64_max = std::numeric_limits<real64>::max();
const nom::size_type SIZE_TYPE_MIN =
std::numeric_limits<nom::size_type>::lowest();
const nom::size_type SIZE_TYPE_MAX =
std::numeric_limits<nom::size_type>::max();
/// \brief An integer indicating that there is no match, an error or NULL.
static const int npos = -1;
/// \brief The default standard point size for fonts.
///
/// \remarks Used in default initialization of nom::Text, nom::UIWidget, etc.
static const int DEFAULT_FONT_SIZE = 12;
/// \brief Alignment types.
///
/// \remarks See also, nom::Anchor enumeration.
///
/// \note Borrowed from [maelstrom's screenlib](https://hg.libsdl.org/Maelstrom/)
enum Alignment: uint32
{
NONE = 0x0,
X_LEFT = 0x01,
X_CENTER = 0x02,
X_RIGHT = 0x4,
/// \remarks Horizontal
X_MASK = ( X_LEFT | X_CENTER | X_RIGHT ),
Y_TOP = 0x10,
Y_CENTER = 0x20,
Y_BOTTOM = 0x40,
/// \remarks Vertical
Y_MASK = ( Y_TOP | Y_CENTER | Y_BOTTOM )
};
/// \note Borrowed from [maelstrom's screenlib](https://hg.libsdl.org/Maelstrom/)
enum Anchor: uint32
{
None = NONE, // 0
Left = X_LEFT, // 1
Center = X_CENTER, // 2
Right = X_RIGHT, // 4
TopLeft = Y_TOP | X_LEFT, // Hex: 0x11, Dec: 17
TopCenter = Y_TOP | X_CENTER, // Hex: 0x12, Dec: 18
TopRight = Y_TOP | X_RIGHT, // Hex: 0x14, Dec: 20
MiddleLeft = Y_CENTER | X_LEFT, // Hex: 0x21, Dec: 33
MiddleCenter = Y_CENTER | X_CENTER, // Hex: 0x22, Dec: 34
MiddleRight = Y_CENTER | X_RIGHT, // Hex: 0x24, Dec: 36
BottomLeft = Y_BOTTOM | X_LEFT, // Hex: 0x41, Dec: 65
BottomCenter = Y_BOTTOM | X_CENTER, // Hex: 0x42, Dec: 66
BottomRight = Y_BOTTOM | X_RIGHT // Hex: 0x44, Dec: 68
};
typedef std::vector<std::string> StringList;
} // namespace nom
/// Ensure our data types have the right sizes using C++11 compile-time asserts.
static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" );
static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" );
static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" );
static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" );
static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" );
static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" );
static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" );
static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" );
static_assert ( sizeof ( nom::real32 ) == 4, "nom::real32" );
static_assert ( sizeof ( nom::real64 ) == 8, "nom::real64" );
static_assert ( sizeof ( nom::uchar ) == 1, "nom::uchar" );
// Blindly assumes we are on either a 64-bit or 32-bit platform.
#if defined( NOM_PLATFORM_ARCH_X86_64 )
static_assert( sizeof ( nom::ulong ) == 8, "nom::ulong" );
static_assert( sizeof ( nom::size_type ) == 8, "nom::size_type" );
#else // #elif defined( NOM_PLATFORM_ARCH_X86_86 )
static_assert( sizeof ( nom::ulong ) == 4, "nom::ulong" );
static_assert( sizeof ( nom::size_type ) == 4, "nom::size_type" );
#endif
// Blindly assumes we are on either a 64-bit or 32-bit platform.
#if defined( NOM_PLATFORM_ARCH_X86_64 )
static_assert( sizeof(nom::int_ptr) == 8, "nom::int_ptr" );
static_assert( sizeof(nom::uint_ptr) == 8, "nom::uint_ptr" );
static_assert( sizeof ( nom::int32_ptr ) == ( sizeof(long) ), "nom::int32_ptr" );
static_assert( sizeof ( nom::uint32_ptr ) == ( sizeof(nom::ulong) ), "nom::uint32_ptr" );
#else // #elif defined(NOM_PLATFORM_ARCH_X86)
static_assert( sizeof(nom::int_ptr) == 4, "nom::int_ptr" );
static_assert( sizeof(nom::uint_ptr) == 4, "nom::uint_ptr" );
static_assert( sizeof( nom::int32_ptr ) == ( sizeof( long ) ), "nom::int32_ptr" );
static_assert( sizeof( nom::uint32_ptr ) == ( sizeof( nom::ulong ) ), "nom::uint32_ptr" );
#endif
/// Additional type definitions
const nom::sint NOM_EXIT_FAILURE = 1; // EXIT_FAILURE from cstdlib headers
const nom::sint NOM_EXIT_SUCCESS = 0; // EXIT_SUCCESS from cstdlib headers
//#if defined(HAVE_SDL2)
const nom::sint SDL_SUCCESS = 0; // Non-error return value for SDL2 API
//#endif
#endif // include guard defined
<|endoftext|> |
<commit_before>
#include <QDebug>
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtConcurrentRun>
#include "libsshqtclient.h"
#include "libsshqtprocess.h"
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseBase
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseOpts
{
public:
QEventLoop loop;
QUrl url;
QString password;
};
class TestCaseBase : public QObject
{
Q_OBJECT
public:
TestCaseBase(TestCaseOpts *opts);
void testSuccess();
void testFailed();
public slots:
void handleError();
public:
TestCaseOpts * const opts;
LibsshQtClient * const client;
};
TestCaseBase::TestCaseBase(TestCaseOpts *opts) :
opts(opts),
client(new LibsshQtClient(this))
{
//client->setDebug(true);
connect(client, SIGNAL(error()),
this, SLOT(handleError()));
connect(client, SIGNAL(closed()),
this, SLOT(handleError()));
connect(client, SIGNAL(allAuthsFailed()),
this, SLOT(handleError()));
client->setUrl(opts->url);
client->usePasswordAuth(true);
client->setPassword(opts->password);
client->connectToHost();
}
void TestCaseBase::testSuccess()
{
opts->loop.exit(0);
client->disconnect(this);
}
void TestCaseBase::testFailed()
{
opts->loop.exit(-1);
client->disconnect(this);
}
void TestCaseBase::handleError()
{
testFailed();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestConnect
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseConnect : public TestCaseBase
{
Q_OBJECT
public:
TestCaseConnect(TestCaseOpts *opts);
public slots:
void connectTest();
};
TestCaseConnect::TestCaseConnect(TestCaseOpts *opts) :
TestCaseBase(opts)
{
connect(client, SIGNAL(opened()),
this, SLOT(connectTest()));
}
void TestCaseConnect::connectTest()
{
testSuccess();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseReadline
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseReadline : public TestCaseBase
{
Q_OBJECT
public:
TestCaseReadline(TestCaseOpts *opts);
public slots:
void readLine();
void finished();
public:
LibsshQtProcess *process;
QIODevice *readdev;
QStringList expected;
int line_pos;
};
TestCaseReadline::TestCaseReadline(TestCaseOpts *opts) :
TestCaseBase(opts),
process(0),
readdev(0),
line_pos(0)
{
expected << "first" << "second" << "last";
}
void TestCaseReadline::readLine()
{
while ( readdev->canReadLine()) {
QString line = QString(readdev->readLine());
if ( line.endsWith('\n')) {
line.remove(line.length() - 1, 1);
}
if ( line == expected.at(line_pos)) {
qDebug() << "Readline:" << line;
line_pos++;
} else {
qDebug() << "Invalid line:" << line;
testFailed();
return;
}
}
}
void TestCaseReadline::finished()
{
if ( line_pos == expected.count()) {
testSuccess();
} else {
qDebug() << "Invalid number of lines read:" << line_pos;
testFailed();
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseReadlineStdout
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseReadlineStdout : public TestCaseReadline
{
Q_OBJECT
public:
TestCaseReadlineStdout(TestCaseOpts *opts);
};
TestCaseReadlineStdout::TestCaseReadlineStdout(TestCaseOpts *opts) :
TestCaseReadline(opts)
{
QString command = QString("echo -en %1").arg(expected.join("\\\\n"));
qDebug("Command: %s", qPrintable(command));
process = client->runCommand(command);
process->setStdoutBehaviour(LibsshQtProcess::OutputManual);
readdev = process;
connect(process, SIGNAL(finished(int)),
this, SLOT(finished()));
connect(process, SIGNAL(readyRead()),
this, SLOT(readLine()));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseReadlineStderr
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseReadlineStderr : public TestCaseReadline
{
Q_OBJECT
public:
TestCaseReadlineStderr(TestCaseOpts *opts);
};
TestCaseReadlineStderr::TestCaseReadlineStderr(TestCaseOpts *opts) :
TestCaseReadline(opts)
{
QString command = QString("echo -en %1 1>&2").arg(expected.join("\\\\n"));
qDebug("Command: %s", qPrintable(command));
process = client->runCommand(command);
process->setStderrBehaviour(LibsshQtProcess::OutputManual);
readdev = process->stderr();
connect(process, SIGNAL(finished(int)),
this, SLOT(finished()));
connect(readdev, SIGNAL(readyRead()),
this, SLOT(readLine()));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Test
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class Test : public QObject
{
Q_OBJECT
public:
Test();
private Q_SLOTS:
void testConnect();
void testReadlineStdin();
void testReadlineStderr();
private:
TestCaseOpts opts;
};
#define CONFIG_FILE
Test::Test()
{
const char conf_file[] = "./libsshqt-test-config";
const QString conf_help = QString(
"Please create configuration file:\n"
"\n"
" %1\n"
"\n"
"with the contents:\n"
"\n"
" ssh://user@hostname:port/\n"
" password\n")
.arg(conf_file);
QFile file;
file.setFileName(conf_file);
if ( ! file.open(QIODevice::ReadOnly)) {
qFatal("\nError: Could not open test configuration file: %s\n\n%s",
conf_file, qPrintable(conf_help));
}
QStringList config = QString(file.readAll()).split('\n');
if ( ! config.length() == 2 ) {
qFatal("\nError: Could not read SSH url and password from: %s\n\n%s",
conf_file, qPrintable(conf_help));
}
opts.url = config.at(0);
opts.password = config.at(1);
}
void Test::testConnect()
{
TestCaseConnect testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Could not connect to the SSH server");
}
void Test::testReadlineStdin()
{
TestCaseReadlineStdout testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Could not read lines correctly from STDOUT");
}
void Test::testReadlineStderr()
{
TestCaseReadlineStderr testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Could not read lines correctly from STDERR");
}
QTEST_MAIN(Test);
#include "test.moc"
<commit_msg>Test for data corruption in unit tests<commit_after>
#include <QDebug>
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtConcurrentRun>
#include "libsshqtclient.h"
#include "libsshqtprocess.h"
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseBase
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseOpts
{
public:
QEventLoop loop;
QUrl url;
QString password;
};
class TestCaseBase : public QObject
{
Q_OBJECT
public:
TestCaseBase(TestCaseOpts *opts);
void testSuccess();
void testFailed();
public slots:
void handleError();
public:
TestCaseOpts * const opts;
LibsshQtClient * const client;
};
TestCaseBase::TestCaseBase(TestCaseOpts *opts) :
opts(opts),
client(new LibsshQtClient(this))
{
//client->setDebug(true);
connect(client, SIGNAL(error()),
this, SLOT(handleError()));
connect(client, SIGNAL(closed()),
this, SLOT(handleError()));
connect(client, SIGNAL(allAuthsFailed()),
this, SLOT(handleError()));
client->setUrl(opts->url);
client->usePasswordAuth(true);
client->setPassword(opts->password);
client->connectToHost();
}
void TestCaseBase::testSuccess()
{
opts->loop.exit(0);
client->disconnect(this);
}
void TestCaseBase::testFailed()
{
opts->loop.exit(-1);
client->disconnect(this);
}
void TestCaseBase::handleError()
{
testFailed();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestConnect
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseConnect : public TestCaseBase
{
Q_OBJECT
public:
TestCaseConnect(TestCaseOpts *opts);
public slots:
void connectTest();
};
TestCaseConnect::TestCaseConnect(TestCaseOpts *opts) :
TestCaseBase(opts)
{
connect(client, SIGNAL(opened()),
this, SLOT(connectTest()));
}
void TestCaseConnect::connectTest()
{
testSuccess();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseReadline
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseReadline : public TestCaseBase
{
Q_OBJECT
public:
TestCaseReadline(TestCaseOpts *opts);
public slots:
void readLine();
void finished();
public:
LibsshQtProcess *process;
QIODevice *readdev;
QStringList expected;
int line_pos;
};
TestCaseReadline::TestCaseReadline(TestCaseOpts *opts) :
TestCaseBase(opts),
process(0),
readdev(0),
line_pos(0)
{
expected << "first" << "second" << "last";
}
void TestCaseReadline::readLine()
{
while ( readdev->canReadLine()) {
QString line = QString(readdev->readLine());
if ( line.endsWith('\n')) {
line.remove(line.length() - 1, 1);
}
if ( line == expected.at(line_pos)) {
qDebug() << "Readline:" << line;
line_pos++;
} else {
qDebug() << "Invalid line:" << line;
testFailed();
return;
}
}
}
void TestCaseReadline::finished()
{
if ( line_pos == expected.count()) {
testSuccess();
} else {
qDebug() << "Invalid number of lines read:" << line_pos;
testFailed();
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseReadlineStdout
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseReadlineStdout : public TestCaseReadline
{
Q_OBJECT
public:
TestCaseReadlineStdout(TestCaseOpts *opts);
};
TestCaseReadlineStdout::TestCaseReadlineStdout(TestCaseOpts *opts) :
TestCaseReadline(opts)
{
QString command = QString("echo -en %1").arg(expected.join("\\\\n"));
qDebug("Command: %s", qPrintable(command));
process = client->runCommand(command);
process->setStdoutBehaviour(LibsshQtProcess::OutputManual);
readdev = process;
connect(process, SIGNAL(finished(int)),
this, SLOT(finished()));
connect(process, SIGNAL(readyRead()),
this, SLOT(readLine()));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseReadlineStderr
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseReadlineStderr : public TestCaseReadline
{
Q_OBJECT
public:
TestCaseReadlineStderr(TestCaseOpts *opts);
};
TestCaseReadlineStderr::TestCaseReadlineStderr(TestCaseOpts *opts) :
TestCaseReadline(opts)
{
QString command = QString("echo -en %1 1>&2").arg(expected.join("\\\\n"));
qDebug("Command: %s", qPrintable(command));
process = client->runCommand(command);
process->setStderrBehaviour(LibsshQtProcess::OutputManual);
readdev = process->stderr();
connect(process, SIGNAL(finished(int)),
this, SLOT(finished()));
connect(readdev, SIGNAL(readyRead()),
this, SLOT(readLine()));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseIO
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseIO : public TestCaseBase
{
Q_OBJECT
public:
TestCaseIO(TestCaseOpts *opts);
quint16 posToValue(int pos);
public slots:
void writeData();
void readData();
public:
QIODevice *writedev;
QIODevice *readdev;
int error_count;
int max_uint16;
int write_pos;
int read_pos;
};
TestCaseIO::TestCaseIO(TestCaseOpts *opts) :
TestCaseBase(opts),
writedev(0),
readdev(0),
error_count(0),
max_uint16(0xFFFF),
write_pos(0),
read_pos(0)
{
}
quint16 TestCaseIO::posToValue(int pos)
{
int val = pos % ( max_uint16 + 1 );
//qDebug() << "Max:" << max << " Pos:" << pos << " Val:" << val;
return val;
}
void TestCaseIO::writeData()
{
if ( writedev->bytesToWrite() == 0 && write_pos <= max_uint16 + 1 ) {
quint16 val = posToValue(write_pos);
QByteArray data(reinterpret_cast< const char* >( &val ), sizeof(val));
writedev->write(data);
write_pos++;
}
}
void TestCaseIO::readData()
{
while ( readdev->bytesAvailable() >= 2 && read_pos <= max_uint16 + 1 ) {
quint16 read_val = 0;
readdev->read(reinterpret_cast< char* >( &read_val ), sizeof(quint16));
quint16 correct_val = posToValue(read_pos);
if ( read_val != correct_val ) {
error_count++;
qDebug() << "Position:" << read_pos
<< " Read:" << read_val
<< " Expected:" << correct_val
<< " Diff:" << read_val - correct_val;
}
read_pos++;
}
if ( read_pos > max_uint16 ) {
qDebug() << "Found" << error_count << "errors";
if ( error_count == 0 ) {
testSuccess();
} else {
testFailed();
}
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseIOStdout
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseIOStdout : public TestCaseIO
{
Q_OBJECT
public:
TestCaseIOStdout(TestCaseOpts *opts);
};
TestCaseIOStdout::TestCaseIOStdout(TestCaseOpts *opts) :
TestCaseIO(opts)
{
LibsshQtProcess *process = client->runCommand("cat");
process->setStdoutBehaviour(LibsshQtProcess::OutputManual);
readdev = process;
writedev = process;
connect(process, SIGNAL(opened()),
this, SLOT(writeData()));
connect(process, SIGNAL(bytesWritten(qint64)),
this, SLOT(writeData()));
connect(process, SIGNAL(readyRead()),
this, SLOT(readData()));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TestCaseIOStderr
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class TestCaseIOStderr : public TestCaseIO
{
Q_OBJECT
public:
TestCaseIOStderr(TestCaseOpts *opts);
};
TestCaseIOStderr::TestCaseIOStderr(TestCaseOpts *opts) :
TestCaseIO(opts)
{
LibsshQtProcess *process = client->runCommand("cat 1>&2");
process->setStderrBehaviour(LibsshQtProcess::OutputManual);
readdev = process->stderr();
writedev = process;
connect(process, SIGNAL(opened()),
this, SLOT(writeData()));
connect(process, SIGNAL(bytesWritten(qint64)),
this, SLOT(writeData()));
connect(readdev, SIGNAL(readyRead()),
this, SLOT(readData()));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Test
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class Test : public QObject
{
Q_OBJECT
public:
Test();
private Q_SLOTS:
void testConnect();
void testReadlineStdin();
void testReadlineStderr();
void testIoStdout();
void testIoStderr();
private:
TestCaseOpts opts;
};
Test::Test()
{
const char conf_file[] = "./libsshqt-test-config";
const QString conf_help = QString(
"Please create configuration file:\n"
"\n"
" %1\n"
"\n"
"with the contents:\n"
"\n"
" ssh://user@hostname:port/\n"
" password\n")
.arg(conf_file);
QFile file;
file.setFileName(conf_file);
if ( ! file.open(QIODevice::ReadOnly)) {
qFatal("\nError: Could not open test configuration file: %s\n\n%s",
conf_file, qPrintable(conf_help));
}
QStringList config = QString(file.readAll()).split('\n');
if ( ! config.length() == 2 ) {
qFatal("\nError: Could not read SSH url and password from: %s\n\n%s",
conf_file, qPrintable(conf_help));
}
opts.url = config.at(0);
opts.password = config.at(1);
}
void Test::testConnect()
{
TestCaseConnect testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Could not connect to the SSH server");
}
void Test::testReadlineStdin()
{
TestCaseReadlineStdout testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Could not read lines correctly from STDOUT");
}
void Test::testReadlineStderr()
{
TestCaseReadlineStderr testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Could not read lines correctly from STDERR");
}
void Test::testIoStdout()
{
TestCaseIOStdout testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Data corruption in STDOUT stream");
}
void Test::testIoStderr()
{
TestCaseIOStderr testcase(&opts);
QVERIFY2(opts.loop.exec() == 0, "Data corruption in STDERR stream");
}
QTEST_MAIN(Test);
#include "test.moc"
<|endoftext|> |
<commit_before>#ifndef _INCLUDED_ENV_HPP
#define _INCLUDED_ENV_HPP
#include <map>
#include <set>
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
#include <boost/utility/string_ref.hpp>
#include <boost/lexical_cast.hpp>
namespace tudocomp {
/// Local environment for a compression/encoding/decompression call.
///
/// Gives access to a statistic logger, and to environment
/// options that can be used to modify the default behavior of an algorithm.
class Env {
std::map<std::string, const std::string> options;
std::map<std::string, const std::string> stats;
mutable std::set<std::string> known_options;
public:
inline Env() {}
inline Env(std::map<std::string, const std::string> options_,
std::map<std::string, const std::string> stats_):
options(options_), stats(stats_) {}
/// Returns a copy of the backing map.
inline std::map<std::string, const std::string> get_options() const {
return options;
}
/// Returns a copy of the backing map.
inline std::map<std::string, const std::string> get_stats() const {
return stats;
}
/// Returns the set of options that got actually asked for by the algorithms
inline std::set<std::string> get_known_options() const {
return known_options;
}
/// Log a statistic.
///
/// Statistics will be gathered at a central location, and
/// can be used to judge the behavior and performance of an
/// implementation.
///
/// \param name The name of the statistic. Should be a unique identifier
/// with `.`-separated segments to allow easier grouping of
/// the gathered values. For example:
/// `"my_compressor.phase1.alphabet_size"`.
/// \param value The value of the statistic as a string.
template<class T>
inline void log_stat(const std::string& name, const T value) {
std::stringstream s;
s << value;
stats.emplace(name, s.str());
};
/// Returns whether a option has been set.
inline bool has_option(const std::string& name) const {
known_options.insert(name);
return options.count(name) > 0;
};
/// Returns a option as its raw string value, or the empty string if
/// it is not set..
///
/// \param name The name of the option. Should be a unique identifier
/// with `.`-separated segments to allow easier grouping.
/// For example:
/// `"my_compressor.xyz_threshold"`.
/// \param default_value The default value to use if the option is not set.
/// Defaults to the empty string.
inline const std::string& option(const std::string& name, const std::string& default_value = "") const {
known_options.insert(name);
if (has_option(name)) {
return options.at(name);
} else {
return default_value;
}
};
/// Returns a option by casting its raw string value
/// to the template type `T`.
/// If the option does not exists, it returns the `default_value` argument.
///
/// Example:
/// ```
/// int threshold = env.option_as<int>("my_compressor.xyz_threshold", 3);
/// ```
///
/// \param name The name of the option. Should be a unique identifier
/// with `.`-separated segments to allow easier grouping.
/// For example:
/// `"my_compressor.xyz_threshold"`.
/// \param default_value The default value to use if the option is not set.
/// Defaults to the default-constructed value of `T`.
template<class T>
T option_as(const std::string& name, T default_value = T()) const {
known_options.insert(name);
if (has_option(name)) {
return boost::lexical_cast<T>(options.at(name));
} else {
return default_value;
}
};
/// Log an error and end the current operation
inline void error(const std::string& msg) {
throw std::runtime_error(msg);
}
};
}
#endif
<commit_msg>Get rid of boost::lexical_cast in Env<commit_after>#ifndef _INCLUDED_ENV_HPP
#define _INCLUDED_ENV_HPP
#include <map>
#include <set>
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
namespace tudocomp {
//DIY lexical cast
template<typename T> T lexical_cast(const std::string& s) {
T val;
std::stringstream(s) >> val;
return val;
}
/// Local environment for a compression/encoding/decompression call.
///
/// Gives access to a statistic logger, and to environment
/// options that can be used to modify the default behavior of an algorithm.
class Env {
std::map<std::string, const std::string> options;
std::map<std::string, const std::string> stats;
mutable std::set<std::string> known_options;
public:
inline Env() {}
inline Env(std::map<std::string, const std::string> options_,
std::map<std::string, const std::string> stats_):
options(options_), stats(stats_) {}
/// Returns a copy of the backing map.
inline std::map<std::string, const std::string> get_options() const {
return options;
}
/// Returns a copy of the backing map.
inline std::map<std::string, const std::string> get_stats() const {
return stats;
}
/// Returns the set of options that got actually asked for by the algorithms
inline std::set<std::string> get_known_options() const {
return known_options;
}
/// Log a statistic.
///
/// Statistics will be gathered at a central location, and
/// can be used to judge the behavior and performance of an
/// implementation.
///
/// \param name The name of the statistic. Should be a unique identifier
/// with `.`-separated segments to allow easier grouping of
/// the gathered values. For example:
/// `"my_compressor.phase1.alphabet_size"`.
/// \param value The value of the statistic as a string.
template<class T>
inline void log_stat(const std::string& name, const T value) {
std::stringstream s;
s << value;
stats.emplace(name, s.str());
};
/// Returns whether a option has been set.
inline bool has_option(const std::string& name) const {
known_options.insert(name);
return options.count(name) > 0;
};
/// Returns a option as its raw string value, or the empty string if
/// it is not set..
///
/// \param name The name of the option. Should be a unique identifier
/// with `.`-separated segments to allow easier grouping.
/// For example:
/// `"my_compressor.xyz_threshold"`.
/// \param default_value The default value to use if the option is not set.
/// Defaults to the empty string.
inline const std::string& option(const std::string& name, const std::string& default_value = "") const {
known_options.insert(name);
if (has_option(name)) {
return options.at(name);
} else {
return default_value;
}
};
/// Returns a option by casting its raw string value
/// to the template type `T`.
/// If the option does not exists, it returns the `default_value` argument.
///
/// Example:
/// ```
/// int threshold = env.option_as<int>("my_compressor.xyz_threshold", 3);
/// ```
///
/// \param name The name of the option. Should be a unique identifier
/// with `.`-separated segments to allow easier grouping.
/// For example:
/// `"my_compressor.xyz_threshold"`.
/// \param default_value The default value to use if the option is not set.
/// Defaults to the default-constructed value of `T`.
template<class T>
T option_as(const std::string& name, T default_value = T()) const {
known_options.insert(name);
if (has_option(name)) {
return lexical_cast<T>(options.at(name));
} else {
return default_value;
}
};
/// Log an error and end the current operation
inline void error(const std::string& msg) {
throw std::runtime_error(msg);
}
};
}
#endif
<|endoftext|> |
<commit_before>
#include <html5.hpp>
#include <fstream>
#include <iostream>
#include <boost/locale.hpp>
const char msg_usage[] = "\nusage : %s <html file name> <selector>\n\n";
void callback(std::shared_ptr<html::dom>)
{}
int main(int argc, char *argv[])
{
if (argc < 3)
{
if (argc > 0)
printf(msg_usage, argv[0]);
else
printf(msg_usage, "html5test");
}
else {
html::dom cu_page;
std::ifstream ifs;
std::istream * instream;
std::string infile = argv[1];
if (infile == "-")
{
instream = &std::cin;
}
else
{
ifs.open(infile.c_str());
instream = & ifs;
}
(*instream) >> std::noskipws;
std::string test_page((std::istreambuf_iterator<char>(* instream)), std::istreambuf_iterator<char>());
cu_page.append_partial_html(test_page) | "div" | callback;
//; [](std::shared_ptr<html::dom>){};
auto charset = cu_page.charset();
auto dom_text = cu_page[argv[2]].to_html();
std::cout << boost::locale::conv::between(dom_text, "UTF-8", charset) << std::endl;
}
}
void test()
{
html::dom page;
page.append_partial_html("<html><head>");
page.append_partial_html("<title>hello world</title");
page.append_partial_html("></head></html>");
assert(page["title"].to_plain_text() == "hello world" );
}
<commit_msg>also lambda works<commit_after>
#include <html5.hpp>
#include <fstream>
#include <iostream>
#include <boost/locale.hpp>
const char msg_usage[] = "\nusage : %s <html file name> <selector>\n\n";
void callback(std::shared_ptr<html::dom>)
{}
int main(int argc, char *argv[])
{
if (argc < 3)
{
if (argc > 0)
printf(msg_usage, argv[0]);
else
printf(msg_usage, "html5test");
}
else {
html::dom cu_page;
std::ifstream ifs;
std::istream * instream;
std::string infile = argv[1];
if (infile == "-")
{
instream = &std::cin;
}
else
{
ifs.open(infile.c_str());
instream = & ifs;
}
(*instream) >> std::noskipws;
std::string test_page((std::istreambuf_iterator<char>(* instream)), std::istreambuf_iterator<char>());
cu_page.append_partial_html(test_page) | "div" | [](std::shared_ptr<html::dom>){};
auto charset = cu_page.charset();
auto dom_text = cu_page[argv[2]].to_html();
std::cout << boost::locale::conv::between(dom_text, "UTF-8", charset) << std::endl;
}
}
void test()
{
html::dom page;
page.append_partial_html("<html><head>");
page.append_partial_html("<title>hello world</title");
page.append_partial_html("></head></html>");
assert(page["title"].to_plain_text() == "hello world" );
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TEST_HPP
#define TEST_HPP
void report_failure(char const* str, char const* file, int line);
#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
struct BOOST_PP_CAT(type, _counter_guard) \
{ \
~BOOST_PP_CAT(type, _counter_guard()) \
{ \
TEST_CHECK(counted_type<type>::count == 0); \
} \
} BOOST_PP_CAT(type, _guard)
#endif
#define TEST_REPORT_AUX(x, line, file) \
report_failure(x, line, file)
#define TEST_CHECK(x) \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__)
#define TEST_ERROR(x) \
TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)
#define TEST_NOTHROW(x) \
try \
{ \
x; \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#endif // TEST_HPP
<commit_msg>catch exceptions from TEST_CHECK<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TEST_HPP
#define TEST_HPP
void report_failure(char const* str, char const* file, int line);
#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
struct BOOST_PP_CAT(type, _counter_guard) \
{ \
~BOOST_PP_CAT(type, _counter_guard()) \
{ \
TEST_CHECK(counted_type<type>::count == 0); \
} \
} BOOST_PP_CAT(type, _guard)
#endif
#define TEST_REPORT_AUX(x, line, file) \
report_failure(x, line, file)
#define TEST_CHECK(x) \
try \
{ \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
} \
catch (std::exception& e) \
{ \
TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#define TEST_ERROR(x) \
TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)
#define TEST_NOTHROW(x) \
try \
{ \
x; \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#endif // TEST_HPP
<|endoftext|> |
<commit_before>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <fstream>
#include "../util/continued_fraction.hpp"
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include <Eigen/SparseQR>
#include <Eigen/OrderingMethods>
using namespace std;
using namespace GiNaC;
typedef Eigen::Triplet<double> Triplet;
typedef Eigen::SparseMatrix<double> SparseMatrix;
double threshold = 1e-13;
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <graph-series-filename>\n\n"
<< "Accepts only homogeneous power series: graphs with n internal vertices at order n.\n";
return 1;
}
// Reading in graph series
string graph_series_filename(argv[1]);
ifstream graph_series_file(graph_series_filename);
parser coefficient_reader;
bool homogeneous = true;
map<size_t, set< vector<size_t> > > in_degrees;
KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file,
[&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); },
[&homogeneous, &in_degrees](KontsevichGraph graph, size_t order) -> bool
{
in_degrees[order].insert(graph.in_degrees());
return homogeneous &= graph.internal() == order;
}
);
size_t order = graph_series.precision();
if (!homogeneous)
{
cerr << "Only accepting homogeneous power series: graphs with n internal vertices at order n.\n";
return 1;
}
graph_series.reduce();
size_t counter = 0;
std::vector<symbol> coefficient_list;
for (size_t n = 2; n <= order; ++n) // need at least 2 internal vertices for Jacobi
{
if (graph_series[n].size() == 0)
continue;
cout << "h^" << n << ":\n";
// First we choose the target vertices i,j,k of the Jacobiator (which contains 2 bivectors), in increasing order (without loss of generality)
for (size_t i = 0; i != n + 3 - 4; ++i)
{
for (size_t j = i + 1; j != n + 3 - 3; ++j)
{
for (size_t k = j + 1; k != n + 3 - 2; ++k)
{
// Then we choose the target vertices of the remaining n - 2 bivectors, stored in a multi-index of length 2*(n-2)
// Here we have one fewer possible target: the internal vertex (n + 3 - 2) acts as a placeholder for the Jacobiator, to be replaced by the Leibniz rule later on
std::vector<size_t> remaining_edges(2*(n-2), n + 3 - 1);
CartesianProduct indices(remaining_edges);
for (auto multi_index = indices.begin(); multi_index != indices.end(); ++multi_index)
{
bool accept = true;
for (size_t idx = 0; idx != n - 2; ++idx)
{
if ((*multi_index)[2*idx] >= (*multi_index)[2*idx+1])
{
accept = false; // accept only strictly increasing indices
break;
}
// TODO: filter out tadpoles, maybe?
}
if (!accept)
continue;
// We build the list of targets for the graph, as described above (using i,j,k and the multi-index)
std::vector<KontsevichGraph::VertexPair> targets(n);
// first part:
for (size_t idx = 0; idx != n - 2; ++idx)
targets[idx] = {(*multi_index)[2*idx], (*multi_index)[2*idx+1]};
// second part:
targets[n-1].first = static_cast<KontsevichGraph::Vertex>(n + 3 - 2);
targets[n-1].second = k;
targets[n-2].first = i;
targets[n-2].second = j;
std::vector<KontsevichGraph::Vertex*> jacobi_targets { &targets[n-2].first, &targets[n-2].second, &targets[n-1].second };
std::vector<KontsevichGraph::Vertex> jacobi_vertices { // to be used for edges incoming on the Jacobiator, applying the Leibniz rule
KontsevichGraph::Vertex(i),
KontsevichGraph::Vertex(j),
KontsevichGraph::Vertex(k),
KontsevichGraph::Vertex(n + 3 - 2),
KontsevichGraph::Vertex(n + 3 - 1)
};
// Make vector of references to bad targets: those in first part with target equal to (n + 3 - 2), the placeholder for the Jacobiator:
std::vector<KontsevichGraph::Vertex*> bad_targets;
for (size_t idx = 0; idx != n - 2; ++idx) // look for bad targets in first part
{
if (targets[idx].first == KontsevichGraph::Vertex(n + 3 - 2))
bad_targets.push_back(&targets[idx].first);
if (targets[idx].second == KontsevichGraph::Vertex(n + 3 - 2))
bad_targets.push_back(&targets[idx].second);
}
KontsevichGraphSum<ex> graph_sum;
map< std::pair< vector<size_t>, vector<size_t> >, symbol > coefficients;
for (auto jacobi_targets_choice : std::vector< std::vector<KontsevichGraph::Vertex> >({ { targets[n-2].first, targets[n-2].second, targets[n-1].second },
{ targets[n-2].second, targets[n-1].second, targets[n-2].first },
{ targets[n-1].second, targets[n-2].first, targets[n-2].second } }))
{
// Set Jacobiator targets to one of the three permutatations
targets[n-2].first = jacobi_targets_choice[0];
targets[n-2].second = jacobi_targets_choice[1];
targets[n-1].second = jacobi_targets_choice[2];
// Replace bad targets by Leibniz rule:
std::vector<size_t> leibniz_sizes(bad_targets.size(), jacobi_vertices.size());
CartesianProduct leibniz_indices(leibniz_sizes);
for (auto leibniz_index = leibniz_indices.begin(); leibniz_index != leibniz_indices.end(); ++leibniz_index)
{
for (size_t idx = 0; idx != bad_targets.size(); ++idx)
{
*bad_targets[idx] = jacobi_vertices[(*leibniz_index)[idx]];
}
KontsevichGraph graph(n, 3, targets);
vector<size_t> indegrees = graph.in_degrees();
vector<size_t> jacobi_indegrees({ 1, 1, 1 });
for (size_t idx = 0; idx != bad_targets.size(); ++idx)
{
if ((*leibniz_index)[idx] < 3)
{
++jacobi_indegrees[(*leibniz_index)[idx]]; // this is correct, because the targets of Jacobi are permuted in place
}
}
if (jacobi_indegrees != vector<size_t>({ 1, 1, 1})) // it suffices to restrict the internal Jacobi to in-degree 1,1,1
continue;
if (in_degrees[n].find(indegrees) == in_degrees[n].end()) // skip terms
continue;
if (coefficients.find({ indegrees, jacobi_indegrees }) == coefficients.end())
{
symbol coefficient("c_" + to_string(counter) + "_" + to_string(indegrees[0]) + to_string(indegrees[1]) + to_string(indegrees[2]) + "_" + to_string(jacobi_indegrees[0]) + to_string(jacobi_indegrees[1]) + to_string(jacobi_indegrees[2]));
coefficients[{ indegrees, jacobi_indegrees}] = coefficient;
}
graph_sum += KontsevichGraphSum<ex>({ { coefficients[{ indegrees, jacobi_indegrees } ], graph } });
}
}
graph_sum.reduce();
if (graph_sum.size() != 0)
{
cerr << "\r" << ++counter;
for (auto& pair : coefficients)
{
coefficient_list.push_back(pair.second);
}
}
graph_series[n] -= graph_sum;
}
}
}
}
}
cout << "\nNumber of coefficients: " << coefficient_list.size() << "\n";
cout << "\nNumber of terms: " << graph_series[order].size() << "\n";
cout << "\nNumber of terms per coefficient: " << (float)graph_series[order].size()/coefficient_list.size() << "\n";
cout.flush();
cerr << "\nReducing...\n";
graph_series.reduce();
lst equations;
for (size_t n = 0; n <= order; ++n)
for (auto& term : graph_series[n])
equations.append(term.first);
// Set up sparse matrix linear system
cerr << "Setting up linear system...\n";
size_t rows = equations.nops();
size_t cols = coefficient_list.size();
Eigen::VectorXd b(rows);
SparseMatrix matrix(rows,cols);
std::vector<Triplet> tripletList;
size_t idx = 0;
for (ex equation : equations)
{
if (!is_a<add>(equation))
equation = lst(equation);
for (ex term : equation)
{
if (!is_a<mul>(term))
term = lst(term);
double prefactor = 1;
symbol coefficient("one");
for (ex factor : term)
{
if (is_a<numeric>(factor))
prefactor *= ex_to<numeric>(factor).to_double();
else if (is_a<symbol>(factor))
coefficient = ex_to<symbol>(factor);
}
if (coefficient.get_name() == "one") // constant term
b(idx) = -prefactor;
else
tripletList.push_back(Triplet(idx,find(coefficient_list.begin(), coefficient_list.end(), coefficient) - coefficient_list.begin(), prefactor));
// NB: Eigen uses zero-based indices (contrast MATLAB, Mathematica)
}
++idx;
}
matrix.setFromTriplets(tripletList.begin(), tripletList.end());
cerr << "Solving linear system numerically...\n";
Eigen::SparseQR< SparseMatrix, Eigen::COLAMDOrdering<int> > qr(matrix);
Eigen::VectorXd x = qr.solve(b);
cerr << "Residual norm = " << (matrix * x - b).squaredNorm() << "\n";
cerr << "Rounding...\n";
x = x.unaryExpr([](double elem) { return fabs(elem) < threshold ? 0.0 : elem; });
cerr << "Still a solution? Residual norm = " << (matrix * x - b).squaredNorm() << "\n";
cerr << "Approximating numerical solution by rational solution...\n";
lst zero_substitution;
lst solution_substitution;
for (int i = 0; i != x.size(); i++)
{
ex result = best_rational_approximation(x.coeff(i), threshold);
if (result == 0)
zero_substitution.append(coefficient_list[i] == 0);
else
solution_substitution.append(coefficient_list[i] == result);
}
cerr << "Substituting zeros...\n";
for (auto& order: graph_series)
for (auto& term : graph_series[order.first])
term.first = term.first.subs(zero_substitution);
cerr << "Reducing zeros...\n";
graph_series.reduce();
for (size_t n = 0; n <= graph_series.precision(); ++n)
{
cout << "h^" << n << ":\n";
for (auto& term : graph_series[n])
{
cout << term.second.encoding() << " " << term.first << "\n";
}
}
cerr << "Verifying solution...\n";
for (auto& order: graph_series)
for (auto& term : graph_series[order.first])
term.first = term.first.subs(solution_substitution);
graph_series.reduce();
cout << "Do we really have a solution? " << (graph_series == 0 ? "Yes" : "No") << "\n";
for (ex subs : solution_substitution)
cout << subs << "\n";
}
<commit_msg>Leibniz rule on Jacobiator: only on internal vertices<commit_after>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <fstream>
#include "../util/continued_fraction.hpp"
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include <Eigen/SparseQR>
#include <Eigen/OrderingMethods>
using namespace std;
using namespace GiNaC;
typedef Eigen::Triplet<double> Triplet;
typedef Eigen::SparseMatrix<double> SparseMatrix;
double threshold = 1e-13;
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <graph-series-filename>\n\n"
<< "Accepts only homogeneous power series: graphs with n internal vertices at order n.\n";
return 1;
}
// Reading in graph series
string graph_series_filename(argv[1]);
ifstream graph_series_file(graph_series_filename);
parser coefficient_reader;
bool homogeneous = true;
map<size_t, set< vector<size_t> > > in_degrees;
KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file,
[&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); },
[&homogeneous, &in_degrees](KontsevichGraph graph, size_t order) -> bool
{
in_degrees[order].insert(graph.in_degrees());
return homogeneous &= graph.internal() == order;
}
);
size_t order = graph_series.precision();
if (!homogeneous)
{
cerr << "Only accepting homogeneous power series: graphs with n internal vertices at order n.\n";
return 1;
}
graph_series.reduce();
size_t counter = 0;
std::vector<symbol> coefficient_list;
for (size_t n = 2; n <= order; ++n) // need at least 2 internal vertices for Jacobi
{
if (graph_series[n].size() == 0)
continue;
cout << "h^" << n << ":\n";
// First we choose the target vertices i,j,k of the Jacobiator (which contains 2 bivectors), in increasing order (without loss of generality)
for (size_t i = 0; i != n + 3 - 4; ++i)
{
for (size_t j = i + 1; j != n + 3 - 3; ++j)
{
for (size_t k = j + 1; k != n + 3 - 2; ++k)
{
// Then we choose the target vertices of the remaining n - 2 bivectors, stored in a multi-index of length 2*(n-2)
// Here we have one fewer possible target: the internal vertex (n + 3 - 2) acts as a placeholder for the Jacobiator, to be replaced by the Leibniz rule later on
std::vector<size_t> remaining_edges(2*(n-2), n + 3 - 1);
CartesianProduct indices(remaining_edges);
for (auto multi_index = indices.begin(); multi_index != indices.end(); ++multi_index)
{
bool accept = true;
for (size_t idx = 0; idx != n - 2; ++idx)
{
if ((*multi_index)[2*idx] >= (*multi_index)[2*idx+1])
{
accept = false; // accept only strictly increasing indices
break;
}
// TODO: filter out tadpoles, maybe?
}
if (!accept)
continue;
// We build the list of targets for the graph, as described above (using i,j,k and the multi-index)
std::vector<KontsevichGraph::VertexPair> targets(n);
// first part:
for (size_t idx = 0; idx != n - 2; ++idx)
targets[idx] = {(*multi_index)[2*idx], (*multi_index)[2*idx+1]};
// second part:
targets[n-1].first = static_cast<KontsevichGraph::Vertex>(n + 3 - 2);
targets[n-1].second = k;
targets[n-2].first = i;
targets[n-2].second = j;
std::vector<KontsevichGraph::Vertex*> jacobi_targets { &targets[n-2].first, &targets[n-2].second, &targets[n-1].second };
std::vector<KontsevichGraph::Vertex> jacobi_vertices { // to be used for edges incoming on the Jacobiator, applying the Leibniz rule
KontsevichGraph::Vertex(n + 3 - 2),
KontsevichGraph::Vertex(n + 3 - 1)
};
// Make vector of references to bad targets: those in first part with target equal to (n + 3 - 2), the placeholder for the Jacobiator:
std::vector<KontsevichGraph::Vertex*> bad_targets;
for (size_t idx = 0; idx != n - 2; ++idx) // look for bad targets in first part
{
if (targets[idx].first == KontsevichGraph::Vertex(n + 3 - 2))
bad_targets.push_back(&targets[idx].first);
if (targets[idx].second == KontsevichGraph::Vertex(n + 3 - 2))
bad_targets.push_back(&targets[idx].second);
}
KontsevichGraphSum<ex> graph_sum;
map< vector<size_t>, symbol > coefficients;
for (auto jacobi_targets_choice : std::vector< std::vector<KontsevichGraph::Vertex> >({ { targets[n-2].first, targets[n-2].second, targets[n-1].second },
{ targets[n-2].second, targets[n-1].second, targets[n-2].first },
{ targets[n-1].second, targets[n-2].first, targets[n-2].second } }))
{
// Set Jacobiator targets to one of the three permutatations
targets[n-2].first = jacobi_targets_choice[0];
targets[n-2].second = jacobi_targets_choice[1];
targets[n-1].second = jacobi_targets_choice[2];
// Replace bad targets by Leibniz rule:
std::vector<size_t> leibniz_sizes(bad_targets.size(), jacobi_vertices.size());
CartesianProduct leibniz_indices(leibniz_sizes);
for (auto leibniz_index = leibniz_indices.begin(); leibniz_index != leibniz_indices.end(); ++leibniz_index)
{
for (size_t idx = 0; idx != bad_targets.size(); ++idx)
{
*bad_targets[idx] = jacobi_vertices[(*leibniz_index)[idx]];
}
KontsevichGraph graph(n, 3, targets);
vector<size_t> indegrees = graph.in_degrees();
if (in_degrees[n].find(indegrees) == in_degrees[n].end()) // skip terms
continue;
if (coefficients.find(indegrees) == coefficients.end())
{
symbol coefficient("c_" + to_string(counter) + "_" + to_string(indegrees[0]) + to_string(indegrees[1]) + to_string(indegrees[2]));
coefficients[indegrees] = coefficient;
}
graph_sum += KontsevichGraphSum<ex>({ { coefficients[indegrees], graph } });
}
}
graph_sum.reduce();
if (graph_sum.size() != 0)
{
cerr << "\r" << ++counter;
for (auto& pair : coefficients)
{
coefficient_list.push_back(pair.second);
}
}
graph_series[n] -= graph_sum;
}
}
}
}
}
cout << "\nNumber of coefficients: " << coefficient_list.size() << "\n";
cout << "\nNumber of terms: " << graph_series[order].size() << "\n";
cout << "\nNumber of terms per coefficient: " << (float)graph_series[order].size()/coefficient_list.size() << "\n";
cout.flush();
cerr << "\nReducing...\n";
graph_series.reduce();
lst equations;
for (size_t n = 0; n <= order; ++n)
for (auto& term : graph_series[n])
equations.append(term.first);
// Set up sparse matrix linear system
cerr << "Setting up linear system...\n";
size_t rows = equations.nops();
size_t cols = coefficient_list.size();
Eigen::VectorXd b(rows);
SparseMatrix matrix(rows,cols);
std::vector<Triplet> tripletList;
size_t idx = 0;
for (ex equation : equations)
{
if (!is_a<add>(equation))
equation = lst(equation);
for (ex term : equation)
{
if (!is_a<mul>(term))
term = lst(term);
double prefactor = 1;
symbol coefficient("one");
for (ex factor : term)
{
if (is_a<numeric>(factor))
prefactor *= ex_to<numeric>(factor).to_double();
else if (is_a<symbol>(factor))
coefficient = ex_to<symbol>(factor);
}
if (coefficient.get_name() == "one") // constant term
b(idx) = -prefactor;
else
tripletList.push_back(Triplet(idx,find(coefficient_list.begin(), coefficient_list.end(), coefficient) - coefficient_list.begin(), prefactor));
// NB: Eigen uses zero-based indices (contrast MATLAB, Mathematica)
}
++idx;
}
matrix.setFromTriplets(tripletList.begin(), tripletList.end());
cerr << "Solving linear system numerically...\n";
Eigen::SparseQR< SparseMatrix, Eigen::COLAMDOrdering<int> > qr(matrix);
Eigen::VectorXd x = qr.solve(b);
cerr << "Residual norm = " << (matrix * x - b).squaredNorm() << "\n";
cerr << "Rounding...\n";
x = x.unaryExpr([](double elem) { return fabs(elem) < threshold ? 0.0 : elem; });
cerr << "Still a solution? Residual norm = " << (matrix * x - b).squaredNorm() << "\n";
cerr << "Approximating numerical solution by rational solution...\n";
lst zero_substitution;
lst solution_substitution;
for (int i = 0; i != x.size(); i++)
{
ex result = best_rational_approximation(x.coeff(i), threshold);
if (result == 0)
zero_substitution.append(coefficient_list[i] == 0);
else
solution_substitution.append(coefficient_list[i] == result);
}
cerr << "Substituting zeros...\n";
for (auto& order: graph_series)
for (auto& term : graph_series[order.first])
term.first = term.first.subs(zero_substitution);
cerr << "Reducing zeros...\n";
graph_series.reduce();
for (size_t n = 0; n <= graph_series.precision(); ++n)
{
cout << "h^" << n << ":\n";
for (auto& term : graph_series[n])
{
cout << term.second.encoding() << " " << term.first << "\n";
}
}
cerr << "Verifying solution...\n";
for (auto& order: graph_series)
for (auto& term : graph_series[order.first])
term.first = term.first.subs(solution_substitution);
graph_series.reduce();
cout << "Do we really have a solution? " << (graph_series == 0 ? "Yes" : "No") << "\n";
for (ex subs : solution_substitution)
cout << subs << "\n";
}
<|endoftext|> |
<commit_before>#ifndef V_SMC_SAMPLER_HPP
#define V_SMC_SAMPLER_HPP
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <gsl/gsl_cblas.h>
#include <boost/function.hpp>
#include <vDist/rng/gsl.hpp>
#include <vDist/tool/buffer.hpp>
#include <vSMC/history.hpp>
#include <vSMC/monitor.hpp>
#include <vSMC/particle.hpp>
namespace vSMC {
template <typename T>
class Sampler
{
public :
/// The type of particle values
typedef T value_type;
/// The type of partiles
typedef Particle<T> particle_type;
/// The type of initialize callable objects
typedef boost::function<std::size_t
(Particle<T> &, void *)> init_type;
/// The type of move callable objects
typedef boost::function<std::size_t
(std::size_t, Particle<T> &)> move_type;
/// The type of importance sampling integral
typedef boost::function<void
(std::size_t, const Particle<T> &, double *, void *)> integral_type;
/// The type of path sampling integration
typedef boost::function<double
(std::size_t, const Particle<T> &, double *)> path_type;
/// \brief Sampler does not have a default constructor
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param hist_mode The history storage mode. See HistoryMode
/// \param rs_scheme The resampling scheme. See ResampleScheme
/// \param seed The seed for the reampling RNG. See documentation of vDist
/// \param brng The basic RNG for resampling RNG. See documentation of GSL
Sampler (
std::size_t N,
const init_type &init, const move_type &move,
const typename Particle<T>::copy_type ©,
HistoryMode hist_mode = HISTORY_RAM,
ResampleScheme rs_scheme = RESIDUAL,
double rs_threshold = 0.5,
const int seed = V_DIST_SEED,
const gsl_rng_type *brng = V_DIST_GSL_BRNG) :
initialized(false), init_particle(init), move_particle(move),
rng(seed, brng), scheme(rs_scheme), threshold(rs_threshold* N),
particle(N, copy), iter_num(0), mode(hist_mode), history(hist_mode),
integrate_tmp(N), path_integral(NULL), path_estimate(0) {}
/// \brief Get ESS
///
/// \return The ESS value of the latest iteration
double ESS () const
{
return ess_history.back();
}
/// \brief Get all ESS
///
/// \return History of ESS for all iterations
std::vector<double> ESS_history () const
{
return ess_history;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the latest iteration was resampled
bool was_resampled () const
{
return resample_history.back();
}
/// \brief Get history of resampling
///
/// \return History of resampling for all iterations
std::vector<bool> was_resampled_history () const
{
return resample_history;
}
/// \brief Get accept count
///
/// \return The accept count of the latest iteration
std::size_t accept_count () const
{
return accept_history.back();
}
/// \brief Get history of accept count
///
/// \return History of accept count for all iterations
std::vector<std::size_t> accept_count_history () const
{
return accept_history;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
/// \note Any operations that change the state of the sampler (e.g., an
/// iteration) may invalidate the reference.
const Particle<T> &getParticle () const
{
return particle;
}
/// \brief (Re)initialize the particle set
///
/// \param param Additional parameters passed to initialization functor,
/// the default is NULL
void initialize (void *param = NULL)
{
history.clear();
ess_history.clear();
resample_history.clear();
accept_history.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor.begin(); imap != monitor.end(); ++imap)
imap->second.clear();
path_sample.clear();
path_width.clear();
iter_num = 0;
accept_history.push_back(init_particle(particle, param));
post_move();
initialized = true;
}
/// \brief Perform iteration
void iterate ()
{
if (!initialized)
throw std::runtime_error(
"ERROR: vSMC::Sampler::iterate: "
"Sampler has not been initialized yet");
++iter_num;
accept_history.push_back(move_particle(iter_num, particle));
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (std::size_t n)
{
for (std::size_t i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param intgral The functor used to compute the integrands
double integrate (typename Monitor<T>::integral_type integral) const
{
std::size_t n = particle.size();
integral(iter_num, particle, integrate_tmp);
return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
}
/// \brief Perform importance sampling integration
///
/// \param intgral The functor used to compute the integrands
/// \param param Additional parameters to be passed to integral
double integrate (integral_type integral, void *param) const
{
std::size_t n = particle.size();
integral(iter_num, particle, integrate_tmp, param);
return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
void add_monitor (const std::string &name,
const typename Monitor<T>::integral_type &integral)
{
monitor.insert(
typename std::map<std::string, Monitor<T> >::value_type(
name, Monitor<T>(integral, particle.size())));
}
/// \brief Get the iteration index of a monitor
///
/// \param The name of the monitor
/// \return A vector of the monitor index
typename Monitor<T>::index_type get_monitor_index (
const std::string &name) const
{
return monitor.find(name)->second.get_index();
}
/// \brief Get the record of Monite Carlo integration of a monitor
///
/// \param name The name of the monitor
/// \return A vector of the monitor record
typename Monitor<T>::record_type get_monitor_record (
const std::string &name) const
{
return monitor.find(name)->second.get_record();
}
/// \brief Get both the iteration index and record of a monitor
typename Monitor<T>::value_type get_monitor_value (
const std::string &name) const
{
return monitor.find(name)->second.get();
}
/// \brief Erase a monitor by name
///
/// \param name The name of the monitor
void erase_monitor (const std::string &name)
{
monitor.erase(name);
}
/// \brief Clear all monitors
void clear_monitor ()
{
monitor.clear();
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
void set_path_sampling (path_type integral)
{
path_integral = integral;
}
/// \brief Stop path sampling
void clear_path_sampling ()
{
path_integral = NULL;
}
/// \brief Get the results of path sampling
double get_path_sampling () const
{
return 0;
}
private :
/// Initialization indicator
bool initialized;
/// Initialization and movement
init_type init_particle;
move_type move_particle;
/// Resampling
vDist::RngGSL rng;
ResampleScheme scheme;
double threshold;
/// Particle sets
Particle<T> particle;
std::size_t iter_num;
std::vector<double> ess_history;
std::vector<bool> resample_history;
std::vector<std::size_t> accept_history;
/// History
HistoryMode mode;
History<T> history;
/// Monte Carlo estimation by integration
mutable vDist::tool::Buffer<double> integrate_tmp;
std::map<std::string, Monitor<T> > monitor;
/// Path sampling
path_type path_integral;
std::vector<double> path_sample;
std::vector<double> path_width;
double path_estimate;
void post_move ()
{
bool res_indicator = false;
if (particle.ESS() < threshold) {
res_indicator = true;
particle.resample(scheme, rng.get_rng());
}
ess_history.push_back(particle.ESS());
resample_history.push_back(res_indicator);
if (mode != HISTORY_NONE)
history.push_back(particle);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor.begin(); imap != monitor.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num, particle);
}
if (!path_integral.empty()) {
double width;
path_sample.push_back(eval_path(width));
path_width.push_back(width);
}
}
double eval_path (double &width)
{
width = path_integral(iter_num, particle, integrate_tmp);
return cblas_ddot(particle.size(),
particle.get_weight_ptr(), 1, integrate_tmp, 1);
}
}; // class Sampler
} // namespace vSMC
#endif // V_SMC_SAMPLER_HPP
<commit_msg>add path_sampling<commit_after>#ifndef V_SMC_SAMPLER_HPP
#define V_SMC_SAMPLER_HPP
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <gsl/gsl_cblas.h>
#include <boost/function.hpp>
#include <vDist/rng/gsl.hpp>
#include <vDist/tool/buffer.hpp>
#include <vSMC/history.hpp>
#include <vSMC/monitor.hpp>
#include <vSMC/particle.hpp>
namespace vSMC {
template <typename T>
class Sampler
{
public :
/// The type of particle values
typedef T value_type;
/// The type of partiles
typedef Particle<T> particle_type;
/// The type of initialize callable objects
typedef boost::function<std::size_t
(Particle<T> &, void *)> init_type;
/// The type of move callable objects
typedef boost::function<std::size_t
(std::size_t, Particle<T> &)> move_type;
/// The type of importance sampling integral
typedef boost::function<void
(std::size_t, const Particle<T> &, double *, void *)> integral_type;
/// The type of path sampling integration
typedef boost::function<double
(std::size_t, const Particle<T> &, double *)> path_type;
/// \brief Sampler does not have a default constructor
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param hist_mode The history storage mode. See HistoryMode
/// \param rs_scheme The resampling scheme. See ResampleScheme
/// \param seed The seed for the reampling RNG. See documentation of vDist
/// \param brng The basic RNG for resampling RNG. See documentation of GSL
Sampler (
std::size_t N,
const init_type &init, const move_type &move,
const typename Particle<T>::copy_type ©,
HistoryMode hist_mode = HISTORY_RAM,
ResampleScheme rs_scheme = RESIDUAL,
double rs_threshold = 0.5,
const int seed = V_DIST_SEED,
const gsl_rng_type *brng = V_DIST_GSL_BRNG) :
initialized(false), init_particle(init), move_particle(move),
rng(seed, brng), scheme(rs_scheme), threshold(rs_threshold* N),
particle(N, copy), iter_num(0), mode(hist_mode), history(hist_mode),
integrate_tmp(N), path_integral(NULL), path_estimate(0) {}
/// \brief Get ESS
///
/// \return The ESS value of the latest iteration
double ESS () const
{
return ess_history.back();
}
/// \brief Get all ESS
///
/// \return History of ESS for all iterations
std::vector<double> ESS_history () const
{
return ess_history;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the latest iteration was resampled
bool was_resampled () const
{
return resample_history.back();
}
/// \brief Get history of resampling
///
/// \return History of resampling for all iterations
std::vector<bool> was_resampled_history () const
{
return resample_history;
}
/// \brief Get accept count
///
/// \return The accept count of the latest iteration
std::size_t accept_count () const
{
return accept_history.back();
}
/// \brief Get history of accept count
///
/// \return History of accept count for all iterations
std::vector<std::size_t> accept_count_history () const
{
return accept_history;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
/// \note Any operations that change the state of the sampler (e.g., an
/// iteration) may invalidate the reference.
const Particle<T> &getParticle () const
{
return particle;
}
/// \brief (Re)initialize the particle set
///
/// \param param Additional parameters passed to initialization functor,
/// the default is NULL
void initialize (void *param = NULL)
{
history.clear();
ess_history.clear();
resample_history.clear();
accept_history.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor.begin(); imap != monitor.end(); ++imap)
imap->second.clear();
path_sample.clear();
path_width.clear();
iter_num = 0;
accept_history.push_back(init_particle(particle, param));
post_move();
initialized = true;
}
/// \brief Perform iteration
void iterate ()
{
if (!initialized)
throw std::runtime_error(
"ERROR: vSMC::Sampler::iterate: "
"Sampler has not been initialized yet");
++iter_num;
accept_history.push_back(move_particle(iter_num, particle));
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (std::size_t n)
{
for (std::size_t i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param intgral The functor used to compute the integrands
double integrate (typename Monitor<T>::integral_type integral) const
{
std::size_t n = particle.size();
integral(iter_num, particle, integrate_tmp);
return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
}
/// \brief Perform importance sampling integration
///
/// \param intgral The functor used to compute the integrands
/// \param param Additional parameters to be passed to integral
double integrate (integral_type integral, void *param) const
{
std::size_t n = particle.size();
integral(iter_num, particle, integrate_tmp, param);
return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
void add_monitor (const std::string &name,
const typename Monitor<T>::integral_type &integral)
{
monitor.insert(
typename std::map<std::string, Monitor<T> >::value_type(
name, Monitor<T>(integral, particle.size())));
}
/// \brief Get the iteration index of a monitor
///
/// \param The name of the monitor
/// \return A vector of the monitor index
typename Monitor<T>::index_type get_monitor_index (
const std::string &name) const
{
return monitor.find(name)->second.get_index();
}
/// \brief Get the record of Monite Carlo integration of a monitor
///
/// \param name The name of the monitor
/// \return A vector of the monitor record
typename Monitor<T>::record_type get_monitor_record (
const std::string &name) const
{
return monitor.find(name)->second.get_record();
}
/// \brief Get both the iteration index and record of a monitor
typename Monitor<T>::value_type get_monitor_value (
const std::string &name) const
{
return monitor.find(name)->second.get();
}
/// \brief Erase a monitor by name
///
/// \param name The name of the monitor
void erase_monitor (const std::string &name)
{
monitor.erase(name);
}
/// \brief Clear all monitors
void clear_monitor ()
{
monitor.clear();
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
void set_path_sampling (path_type integral)
{
path_integral = integral;
}
/// \brief Stop path sampling
void clear_path_sampling ()
{
path_integral = NULL;
}
/// \brief Get the results of path sampling
double get_path_sampling () const
{
std::size_t num = path_sample.size();
double sum = 0;
for (std::size_t i = 1; i != num; ++i)
sum += 0.5 * (path_sample[i-1] + path_sample[i]) * path_width[i];
return sum;
}
private :
/// Initialization indicator
bool initialized;
/// Initialization and movement
init_type init_particle;
move_type move_particle;
/// Resampling
vDist::RngGSL rng;
ResampleScheme scheme;
double threshold;
/// Particle sets
Particle<T> particle;
std::size_t iter_num;
std::vector<double> ess_history;
std::vector<bool> resample_history;
std::vector<std::size_t> accept_history;
/// History
HistoryMode mode;
History<T> history;
/// Monte Carlo estimation by integration
mutable vDist::tool::Buffer<double> integrate_tmp;
std::map<std::string, Monitor<T> > monitor;
/// Path sampling
path_type path_integral;
std::vector<double> path_sample;
std::vector<double> path_width;
double path_estimate;
void post_move ()
{
bool res_indicator = false;
if (particle.ESS() < threshold) {
res_indicator = true;
particle.resample(scheme, rng.get_rng());
}
ess_history.push_back(particle.ESS());
resample_history.push_back(res_indicator);
if (mode != HISTORY_NONE)
history.push_back(particle);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor.begin(); imap != monitor.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num, particle);
}
if (!path_integral.empty()) {
double width;
path_sample.push_back(eval_path(width));
path_width.push_back(width);
}
}
double eval_path (double &width)
{
width = path_integral(iter_num, particle, integrate_tmp);
return cblas_ddot(particle.size(),
particle.get_weight_ptr(), 1, integrate_tmp, 1);
}
}; // class Sampler
} // namespace vSMC
#endif // V_SMC_SAMPLER_HPP
<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <memory>
#include <string.h>
#include "../lcd/LcdDisplay.h"
#include "../src2/HealthStatus.h"
using namespace std;
using namespace std::chrono;
int main() {
unique_ptr<LcdDisplay> lcd(LcdDisplay::getLcdDisplayInstance());
lcd->init();
StatusInformation status;
beacon_info beacon;
memset(&beacon, sizeof(beacon), 0);
status.setScannerID("Room206");
// Add some events
sprintf(beacon.uuid, "UUID-%.10d", 66);
beacon.minor = 66;
beacon.major = 1;
beacon.manufacturer = 0xdead;
beacon.code = 0xbeef;
beacon.count = 3;
beacon.rssi = -68;
milliseconds now = duration_cast<milliseconds >(high_resolution_clock::now().time_since_epoch());
beacon.time = now.count();
status.addEvent(beacon, false);
beacon.isHeartbeat = true;
beacon.minor = 206;
beacon.time += 10;
status.addEvent(beacon, true);
beacon.isHeartbeat = false;
beacon.minor = 56;
beacon.time += 10;
status.addEvent(beacon, false);
beacon.isHeartbeat = true;
beacon.minor = 206;
beacon.time += 10;
status.addEvent(beacon, true);
HealthStatus healthStatus;
healthStatus.calculateStatus(status);
Properties statusProps = status.getLastStatus();
printf("StatusProps dump:\n");
for(Properties::const_iterator iter = statusProps.begin(); iter != statusProps.end(); iter ++) {
printf("%s = %s\n", iter->first.c_str(), iter->second.c_str());
}
printf("+++ End dump\n\n");
char tmp[21];
snprintf(tmp, sizeof(tmp), "01234567890123456789");
lcd->displayText(tmp, 0, 0);
cout << "\nEnter any key to test local layout: ";
std::string line;
std::getline(std::cin, line);
lcd->clear();
snprintf(tmp, sizeof(tmp), "%s:%.5d;%d", status.getScannerID().c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI());
lcd->displayText(tmp, 0, 0);
string uptime = statusProps["Uptime"];
const char *uptimeStr = uptime.c_str();
printf("%s; length=%d\n", uptimeStr, uptime.size());
int days=0, hrs=0, mins=0;
int count = sscanf (uptimeStr, "uptime: %*d, days:%d, hrs:%d, min:%d", &days, &hrs, &mins);
printf("matched:%d, UP D:%d H:%d M:%d\n", count, days, hrs, mins);
snprintf(tmp, sizeof(tmp), "UP D:%d H:%d M:%d", days, hrs, mins);
lcd->displayText(tmp, 0, 1);
const char *load = statusProps["LoadAverage"].c_str();
printf("Load: %s\n", load);
lcd->displayText(load, 0, 2);
snprintf(tmp, sizeof(tmp), "Events: %d; Msgs: %d", status.getRawEventCount(), status.getPublishEventCount());
lcd->displayText(tmp, 0, 3);
cout << "\nEnter any key to call displayStatus: ";
std::getline(std::cin, line);
lcd->clear();
lcd->displayStatus(status);
cout << "\nEnter any key to call exit: ";
std::getline(std::cin, line);
lcd->clear();
}
<commit_msg>Truncate the scanner name to 7 chars<commit_after>#include <chrono>
#include <iostream>
#include <memory>
#include <string.h>
#include "../lcd/LcdDisplay.h"
#include "../src2/HealthStatus.h"
using namespace std;
using namespace std::chrono;
static inline void truncateName(string& name) {
size_t length = name.length();
if(length > 7) {
int middle = length/2;
size_t count = length - 7;
middle -= count / 2;
name.erase(middle, count);
}
}
int main() {
unique_ptr<LcdDisplay> lcd(LcdDisplay::getLcdDisplayInstance());
lcd->init();
StatusInformation status;
beacon_info beacon;
memset(&beacon, sizeof(beacon), 0);
status.setScannerID("LCDScanner");
// Add some events
sprintf(beacon.uuid, "UUID-%.10d", 66);
beacon.minor = 66;
beacon.major = 1;
beacon.manufacturer = 0xdead;
beacon.code = 0xbeef;
beacon.count = 3;
beacon.rssi = -68;
milliseconds now = duration_cast<milliseconds >(high_resolution_clock::now().time_since_epoch());
beacon.time = now.count();
status.addEvent(beacon, false);
beacon.isHeartbeat = true;
beacon.minor = 206;
beacon.time += 10;
status.addEvent(beacon, true);
beacon.isHeartbeat = false;
beacon.minor = 56;
beacon.time += 10;
status.addEvent(beacon, false);
beacon.isHeartbeat = true;
beacon.minor = 206;
beacon.time += 10;
status.addEvent(beacon, true);
HealthStatus healthStatus;
healthStatus.calculateStatus(status);
Properties statusProps = status.getLastStatus();
printf("StatusProps dump:\n");
for(Properties::const_iterator iter = statusProps.begin(); iter != statusProps.end(); iter ++) {
printf("%s = %s\n", iter->first.c_str(), iter->second.c_str());
}
printf("+++ End dump\n\n");
char tmp[21];
snprintf(tmp, sizeof(tmp), "01234567890123456789");
lcd->displayText(tmp, 0, 0);
cout << "\nEnter any key to test local layout: ";
std::string line;
std::getline(std::cin, line);
lcd->clear();
string name(status.getScannerID());
truncateName(name);
snprintf(tmp, sizeof(tmp), "%s:%.7d;%d", name.c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI());
lcd->displayText(tmp, 0, 0);
string uptime = statusProps["Uptime"];
const char *uptimeStr = uptime.c_str();
printf("%s; length=%d\n", uptimeStr, uptime.size());
int days=0, hrs=0, mins=0;
int count = sscanf (uptimeStr, "uptime: %*d, days:%d, hrs:%d, min:%d", &days, &hrs, &mins);
printf("matched:%d, UP D:%d H:%d M:%d\n", count, days, hrs, mins);
snprintf(tmp, sizeof(tmp), "UP D:%d H:%d M:%d", days, hrs, mins);
lcd->displayText(tmp, 0, 1);
const char *load = statusProps["LoadAverage"].c_str();
printf("Load: %s\n", load);
lcd->displayText(load, 0, 2);
snprintf(tmp, sizeof(tmp), "Events: %d; Msgs: %d", status.getRawEventCount(), status.getPublishEventCount());
lcd->displayText(tmp, 0, 3);
cout << "\nEnter any key to call displayStatus: ";
std::getline(std::cin, line);
lcd->clear();
lcd->displayStatus(status);
cout << "\nEnter any key to call exit: ";
std::getline(std::cin, line);
lcd->clear();
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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/>.
*/
#ifndef module_hh
#define module_hh
#include "sofia-sip/nta_tport.h"
#include "sofia-sip/tport.h"
#include "sofia-sip/msg_header.h"
#include <string>
#include <memory>
#include <list>
#include "configmanager.hh"
#include "event.hh"
#include "transaction.hh"
class ModuleInfoBase;
class Module;
class Agent;
class StatCounter64;
class ModuleFactory {
public:
static ModuleFactory *get();
Module *createModuleInstance(Agent *ag, const std::string &modname);
const std::list<ModuleInfoBase *> &moduleInfos() {
return mModules;
}
private:
void registerModule(ModuleInfoBase *m);
std::list<ModuleInfoBase *> mModules;
static ModuleFactory *sInstance;
friend class ModuleInfoBase;
};
typedef enum { ModuleTypeExperimental, ModuleTypeProduction } ModuleType_e;
class ModuleInfoBase {
const std::string mName;
const std::string mHelp;
const oid mOidIndex;
static oid indexCount;
public:
Module *create(Agent *ag);
virtual Module *_create(Agent *ag) = 0;
const std::string &getModuleName() const {
return mName;
}
const std::string &getModuleHelp() const {
return mHelp;
}
unsigned int getOidIndex() const {
return mOidIndex;
}
virtual ~ModuleInfoBase();
ModuleType_e type() const {
return mType;
}
enum ModuleOid {
DoSProtection = 2,
SanityChecker = 3,
GarbageIn = 5,
NatHelper = 30,
Authentication = 60,
DateHandler = 75,
GatewayAdapter = 90,
Registrar = 120,
StatisticsCollector = 123,
Router = 125,
PushNotification = 130,
ContactRouteInserter = 150,
LoadBalancer = 180,
MediaRelay = 210,
Transcoder = 240,
Forward = 270,
Redirect = 290,
Presence = 300,
InterDomainConnections = 310
};
protected:
ModuleInfoBase(const char *modname, const char *help, enum ModuleOid oid, ModuleType_e type)
: mName(modname), mHelp(help), mOidIndex(oid), mType(type) {
// Oid::oidFromHashedString(modname)
ModuleFactory::get()->registerModule(this);
}
ModuleType_e mType;
};
template <typename _module_> class ModuleInfo : public ModuleInfoBase {
public:
ModuleInfo(const char *modname, const char *help, ModuleOid oid, ModuleType_e type = ModuleTypeProduction)
: ModuleInfoBase(modname, help, oid, type) {
}
protected:
virtual Module *_create(Agent *ag);
};
class EntryFilter;
/**
* Abstract base class for all Flexisip module.
* A module is an object that is able to process sip requests and sip responses.
* It must implements at least:
* virtual void onRequest(SipEvent *ev)=0;
* virtual void onResponse(SipEvent *ev)=0;
**/
class Module : protected ConfigValueListener {
friend class ModuleInfoBase;
public:
Module(Agent *);
virtual ~Module();
Agent *getAgent() const;
nta_agent_t *getSofiaAgent() const;
const std::string &getModuleName() const;
void declare(GenericStruct *root);
void checkConfig();
void load();
void reload();
void processRequest(std::shared_ptr<RequestSipEvent> &ev);
void processResponse(std::shared_ptr<ResponseSipEvent> &ev);
StatCounter64 &findStat(const std::string &statName) const;
void idle();
bool isEnabled() const;
ModuleType_e type() const;
inline void process(std::shared_ptr<RequestSipEvent> &ev) {
processRequest(ev);
}
inline void process(std::shared_ptr<ResponseSipEvent> &ev) {
processResponse(ev);
}
protected:
virtual void onDeclare(GenericStruct *root) {
}
virtual void onLoad(const GenericStruct *root) {
}
virtual void onUnload() {
}
virtual void onRequest(std::shared_ptr<RequestSipEvent> &ev) throw (FlexisipException) = 0;
virtual void onResponse(std::shared_ptr<ResponseSipEvent> &ev) throw (FlexisipException) = 0;
virtual bool doOnConfigStateChanged(const ConfigValue &conf, ConfigState state);
virtual void onIdle() {
}
virtual bool onCheckValidNextConfig() {
return true;
}
virtual bool isValidNextConfig(const ConfigValue &cv) {
return true;
}
void sendTrap(const std::string &msg) {
GenericManager::get()->sendTrap(mModuleConfig, msg);
}
Agent *mAgent;
protected:
static std::list<std::string> sPushNotifParams;
su_home_t *getHome() {
return &mHome;
}
private:
void setInfo(ModuleInfoBase *i);
ModuleInfoBase *mInfo;
GenericStruct *mModuleConfig;
EntryFilter *mFilter;
bool mDirtyConfig;
su_home_t mHome;
};
inline std::ostringstream &operator<<(std::ostringstream &__os, const Module &m) {
__os << m.getModuleName();
return __os;
}
template <typename _modtype> Module *ModuleInfo<_modtype>::_create(Agent *ag) {
Module *mod = new _modtype(ag);
return mod;
}
/**
* Some useful routines any module can use by derivating from this class.
**/
class ModuleToolbox {
public:
static msg_auth_t *findAuthorizationForRealm(su_home_t *home, msg_auth_t *au, const char *realm);
static const tport_t *getIncomingTport(const std::shared_ptr<RequestSipEvent> &ev, Agent *ag);
static void addRecordRouteIncoming(su_home_t *home, Agent *ag, const std::shared_ptr<RequestSipEvent> &ev);
static url_t *urlFromTportName(su_home_t *home, const tp_name_t *name);
static void addRecordRoute(su_home_t *home, Agent *ag, const std::shared_ptr<RequestSipEvent> &ev,
const tport_t *tport);
static void cleanAndPrependRoute(Agent *ag, msg_t *msg, sip_t *sip, sip_route_t *route);
static bool sipPortEquals(const char *p1, const char *p2, const char *transport = NULL);
static int sipPortToInt(const char *port);
static bool fromMatch(const sip_from_t *from1, const sip_from_t *from2);
static bool matchesOneOf(const char *item, const std::list<std::string> &set);
static bool fixAuthChallengeForSDP(su_home_t *home, msg_t *msg, sip_t *sip);
static bool transportEquals(const char *tr1, const char *tr2);
static bool isNumeric(const char *host);
static bool isManagedDomain(const Agent *agent, const std::list<std::string> &domains, const url_t *url);
static void addRoutingParam(su_home_t *home, sip_contact_t *contacts, const std::string &routingParam,
const char *domain);
static struct sip_route_s *prependNewRoutable(msg_t *msg, sip_t *sip, sip_route_t *&sipr, sip_route_t *value);
static void addPathHeader(Agent *ag, const std::shared_ptr<RequestSipEvent> &ev, const tport_t *tport,
const char *uniq = NULL);
/*these methods do host comparison taking into account that each one of argument can be an ipv6 address enclosed in
* brakets*/
static bool urlHostMatch(const char *host1, const char *host2);
static bool urlHostMatch(url_t *url, const char *host);
/*returns the host taking into account that if it is an ipv6 address, then brakets are removed*/
static string getHost(const char *host);
static string urlGetHost(url_t *url);
static void urlSetHost(su_home_t *home, url_t *url, const char *host);
static bool urlIsResolved(url_t *uri);
/**
* Returns true if via and url represent the same network address.
**/
static bool urlViaMatch(const url_t *url, const sip_via_t *via, bool use_received_rport);
/**
* Returns true if the destination represented by url is present in the via chain.
**/
static bool viaContainsUrl(const sip_via_t *vias, const url_t *url);
/*returns true if the two url represent the same transport channel (IP, port and protocol)*/
static bool urlTransportMatch(const url_t *url1, const url_t *url2);
static string urlGetTransport(const url_t *url);
static void removeParamsFromContacts(su_home_t *home, sip_contact_t *c, std::list<std::string> ¶ms);
static void removeParamsFromUrl(su_home_t *home, url_t *u, std::list<std::string> ¶ms);
static sip_unknown_t *getCustomHeaderByName(sip_t *sip, const char *name);
static int getCpuCount();
};
/*nice wrapper of the sofia-sip su_home_t, that performs automatic destruction of the home when it leaving a code block
* or function.*/
class SofiaAutoHome {
public:
SofiaAutoHome() {
su_home_init(&mHome);
}
su_home_t *home() {
return &mHome;
}
~SofiaAutoHome() {
su_home_deinit(&mHome);
}
private:
su_home_t mHome;
};
#endif
<commit_msg>Change the Oid of DosProtection module<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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/>.
*/
#ifndef module_hh
#define module_hh
#include "sofia-sip/nta_tport.h"
#include "sofia-sip/tport.h"
#include "sofia-sip/msg_header.h"
#include <string>
#include <memory>
#include <list>
#include "configmanager.hh"
#include "event.hh"
#include "transaction.hh"
class ModuleInfoBase;
class Module;
class Agent;
class StatCounter64;
class ModuleFactory {
public:
static ModuleFactory *get();
Module *createModuleInstance(Agent *ag, const std::string &modname);
const std::list<ModuleInfoBase *> &moduleInfos() {
return mModules;
}
private:
void registerModule(ModuleInfoBase *m);
std::list<ModuleInfoBase *> mModules;
static ModuleFactory *sInstance;
friend class ModuleInfoBase;
};
typedef enum { ModuleTypeExperimental, ModuleTypeProduction } ModuleType_e;
class ModuleInfoBase {
const std::string mName;
const std::string mHelp;
const oid mOidIndex;
static oid indexCount;
public:
Module *create(Agent *ag);
virtual Module *_create(Agent *ag) = 0;
const std::string &getModuleName() const {
return mName;
}
const std::string &getModuleHelp() const {
return mHelp;
}
unsigned int getOidIndex() const {
return mOidIndex;
}
virtual ~ModuleInfoBase();
ModuleType_e type() const {
return mType;
}
enum ModuleOid {
SanityChecker = 3,
DoSProtection = 4,
GarbageIn = 5,
NatHelper = 30,
Authentication = 60,
DateHandler = 75,
GatewayAdapter = 90,
Registrar = 120,
StatisticsCollector = 123,
Router = 125,
PushNotification = 130,
ContactRouteInserter = 150,
LoadBalancer = 180,
MediaRelay = 210,
Transcoder = 240,
Forward = 270,
Redirect = 290,
Presence = 300,
InterDomainConnections = 310
};
protected:
ModuleInfoBase(const char *modname, const char *help, enum ModuleOid oid, ModuleType_e type)
: mName(modname), mHelp(help), mOidIndex(oid), mType(type) {
// Oid::oidFromHashedString(modname)
ModuleFactory::get()->registerModule(this);
}
ModuleType_e mType;
};
template <typename _module_> class ModuleInfo : public ModuleInfoBase {
public:
ModuleInfo(const char *modname, const char *help, ModuleOid oid, ModuleType_e type = ModuleTypeProduction)
: ModuleInfoBase(modname, help, oid, type) {
}
protected:
virtual Module *_create(Agent *ag);
};
class EntryFilter;
/**
* Abstract base class for all Flexisip module.
* A module is an object that is able to process sip requests and sip responses.
* It must implements at least:
* virtual void onRequest(SipEvent *ev)=0;
* virtual void onResponse(SipEvent *ev)=0;
**/
class Module : protected ConfigValueListener {
friend class ModuleInfoBase;
public:
Module(Agent *);
virtual ~Module();
Agent *getAgent() const;
nta_agent_t *getSofiaAgent() const;
const std::string &getModuleName() const;
void declare(GenericStruct *root);
void checkConfig();
void load();
void reload();
void processRequest(std::shared_ptr<RequestSipEvent> &ev);
void processResponse(std::shared_ptr<ResponseSipEvent> &ev);
StatCounter64 &findStat(const std::string &statName) const;
void idle();
bool isEnabled() const;
ModuleType_e type() const;
inline void process(std::shared_ptr<RequestSipEvent> &ev) {
processRequest(ev);
}
inline void process(std::shared_ptr<ResponseSipEvent> &ev) {
processResponse(ev);
}
protected:
virtual void onDeclare(GenericStruct *root) {
}
virtual void onLoad(const GenericStruct *root) {
}
virtual void onUnload() {
}
virtual void onRequest(std::shared_ptr<RequestSipEvent> &ev) throw (FlexisipException) = 0;
virtual void onResponse(std::shared_ptr<ResponseSipEvent> &ev) throw (FlexisipException) = 0;
virtual bool doOnConfigStateChanged(const ConfigValue &conf, ConfigState state);
virtual void onIdle() {
}
virtual bool onCheckValidNextConfig() {
return true;
}
virtual bool isValidNextConfig(const ConfigValue &cv) {
return true;
}
void sendTrap(const std::string &msg) {
GenericManager::get()->sendTrap(mModuleConfig, msg);
}
Agent *mAgent;
protected:
static std::list<std::string> sPushNotifParams;
su_home_t *getHome() {
return &mHome;
}
private:
void setInfo(ModuleInfoBase *i);
ModuleInfoBase *mInfo;
GenericStruct *mModuleConfig;
EntryFilter *mFilter;
bool mDirtyConfig;
su_home_t mHome;
};
inline std::ostringstream &operator<<(std::ostringstream &__os, const Module &m) {
__os << m.getModuleName();
return __os;
}
template <typename _modtype> Module *ModuleInfo<_modtype>::_create(Agent *ag) {
Module *mod = new _modtype(ag);
return mod;
}
/**
* Some useful routines any module can use by derivating from this class.
**/
class ModuleToolbox {
public:
static msg_auth_t *findAuthorizationForRealm(su_home_t *home, msg_auth_t *au, const char *realm);
static const tport_t *getIncomingTport(const std::shared_ptr<RequestSipEvent> &ev, Agent *ag);
static void addRecordRouteIncoming(su_home_t *home, Agent *ag, const std::shared_ptr<RequestSipEvent> &ev);
static url_t *urlFromTportName(su_home_t *home, const tp_name_t *name);
static void addRecordRoute(su_home_t *home, Agent *ag, const std::shared_ptr<RequestSipEvent> &ev,
const tport_t *tport);
static void cleanAndPrependRoute(Agent *ag, msg_t *msg, sip_t *sip, sip_route_t *route);
static bool sipPortEquals(const char *p1, const char *p2, const char *transport = NULL);
static int sipPortToInt(const char *port);
static bool fromMatch(const sip_from_t *from1, const sip_from_t *from2);
static bool matchesOneOf(const char *item, const std::list<std::string> &set);
static bool fixAuthChallengeForSDP(su_home_t *home, msg_t *msg, sip_t *sip);
static bool transportEquals(const char *tr1, const char *tr2);
static bool isNumeric(const char *host);
static bool isManagedDomain(const Agent *agent, const std::list<std::string> &domains, const url_t *url);
static void addRoutingParam(su_home_t *home, sip_contact_t *contacts, const std::string &routingParam,
const char *domain);
static struct sip_route_s *prependNewRoutable(msg_t *msg, sip_t *sip, sip_route_t *&sipr, sip_route_t *value);
static void addPathHeader(Agent *ag, const std::shared_ptr<RequestSipEvent> &ev, const tport_t *tport,
const char *uniq = NULL);
/*these methods do host comparison taking into account that each one of argument can be an ipv6 address enclosed in
* brakets*/
static bool urlHostMatch(const char *host1, const char *host2);
static bool urlHostMatch(url_t *url, const char *host);
/*returns the host taking into account that if it is an ipv6 address, then brakets are removed*/
static string getHost(const char *host);
static string urlGetHost(url_t *url);
static void urlSetHost(su_home_t *home, url_t *url, const char *host);
static bool urlIsResolved(url_t *uri);
/**
* Returns true if via and url represent the same network address.
**/
static bool urlViaMatch(const url_t *url, const sip_via_t *via, bool use_received_rport);
/**
* Returns true if the destination represented by url is present in the via chain.
**/
static bool viaContainsUrl(const sip_via_t *vias, const url_t *url);
/*returns true if the two url represent the same transport channel (IP, port and protocol)*/
static bool urlTransportMatch(const url_t *url1, const url_t *url2);
static string urlGetTransport(const url_t *url);
static void removeParamsFromContacts(su_home_t *home, sip_contact_t *c, std::list<std::string> ¶ms);
static void removeParamsFromUrl(su_home_t *home, url_t *u, std::list<std::string> ¶ms);
static sip_unknown_t *getCustomHeaderByName(sip_t *sip, const char *name);
static int getCpuCount();
};
/*nice wrapper of the sofia-sip su_home_t, that performs automatic destruction of the home when it leaving a code block
* or function.*/
class SofiaAutoHome {
public:
SofiaAutoHome() {
su_home_init(&mHome);
}
su_home_t *home() {
return &mHome;
}
~SofiaAutoHome() {
su_home_deinit(&mHome);
}
private:
su_home_t mHome;
};
#endif
<|endoftext|> |
<commit_before>#include <algorithm>
#include <ctime>
#include <functional>
#include <map>
#include <memory>
#include "BrickCache.h"
#include "Controller/StackTimer.h"
namespace tuvok {
// This is used to basically get rid of a type. You can do:
// std::vector<TypeErase> data;
// std::vector<uint8_t> foo;
// std::vector<uint16_t> bar;
// data.push_back(TypeErase<std::vector<uint8_t>>(foo));
// data.push_back(TypeErase<std::vector<uint16_t>>(bar));
// with 'MyTypeOne' and 'MyTypeTwo' being completely unrelated (they do not
// need to have a common base class)
struct TypeErase {
struct GenericType {
virtual ~GenericType() {}
virtual size_t elems() const { return 0; }
};
template<typename T> struct TypeEraser : GenericType {
TypeEraser(const T& t) : thing(t) {}
TypeEraser(T&& t) : thing(std::forward<T>(t)) {}
virtual ~TypeEraser() {}
T& get() { return thing; }
size_t elems() const { return thing.size(); }
private: T thing;
};
std::shared_ptr<GenericType> gt;
size_t width;
TypeErase(const TypeErase& other)
: gt(other.gt)
, width(other.width)
{}
TypeErase(TypeErase&& other)
: gt(std::move(other.gt))
, width(other.width) // width should stay the same right?
{}
TypeErase& operator=(const TypeErase& other) {
if (this != &other) {
gt = other.gt;
width = other.width;
}
return *this;
}
TypeErase& operator=(TypeErase&& other) {
if (this != &other) {
gt = std::move(other.gt);
width = other.width; // width should stay the same right?
}
return *this;
}
// this isn't a very good type eraser, because we require that the type has
// an internal typedef 'value_type' which we can use to obtain the size of
// it. not to mention the '.size()' member function that TypeEraser<>
// requires, above.
// But that's fine for our usage here; we're really just using this to store
// vectors and erase the value_type in there anyway.
template<typename T> TypeErase(const T& t)
: gt(new TypeEraser<T>(t))
, width(sizeof(typename T::value_type))
{}
template<typename T> TypeErase(T&& t)
: gt(new TypeEraser<T>(std::forward<T>(t)))
, width(sizeof(typename std::remove_reference<T>::type::value_type))
{}
};
struct BrickInfo {
BrickKey key;
uint64_t access_time;
BrickInfo(const BrickKey& k, time_t t) : key(k),
access_time(uint64_t(t)) {}
};
struct CacheLRU {
typedef std::pair<BrickInfo, TypeErase> CacheElem;
bool operator()(const CacheElem& a, const CacheElem& b) const {
return a.first.access_time > b.first.access_time;
}
};
struct BrickCache::bcinfo {
bcinfo(): bytes(0) {}
// this is wordy but they all just forward to a real implementation below.
const void* lookup(const BrickKey& k) {
return this->typed_lookup<uint8_t>(k);
}
// the erasure means we can just do the insert with the thing we already
// have: it'll make a shared_ptr out of it and insert it into the
// container.
///@{
const void* add(const BrickKey& k, std::vector<uint8_t>& data) {
return this->typed_add<uint8_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<uint16_t>& data) {
return this->typed_add<uint16_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<uint32_t>& data) {
return this->typed_add<uint32_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<uint64_t>& data) {
return this->typed_add<uint64_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int8_t>& data) {
return this->typed_add<int8_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int16_t>& data) {
return this->typed_add<int16_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int32_t>& data) {
return this->typed_add<int32_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int64_t>& data) {
return this->typed_add<int64_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<float>& data) {
return this->typed_add<float>(k, data);
}
///@}
void remove() {
if(!cache.empty()) {
// libstdc++ complains it's not a heap otherwise.. somehow. bug?
std::make_heap(this->cache.begin(), this->cache.end(), CacheLRU());
const CacheElem& entry = this->cache.front();
TypeErase::GenericType& gt = *(entry.second.gt);
assert((entry.second.width * gt.elems()) <= this->bytes);
this->bytes -= entry.second.width * gt.elems();
std::pop_heap(this->cache.begin(), this->cache.end(), CacheLRU());
this->cache.pop_back();
}
assert(this->size() == this->bytes);
}
size_t size() const { return this->bytes; }
private:
template<typename T> const void* typed_lookup(const BrickKey& k);
template<typename T> const void* typed_add(const BrickKey&,
std::vector<T>&);
private:
typedef std::pair<BrickInfo, TypeErase> CacheElem;
std::vector<CacheElem> cache;
size_t bytes; ///< how much memory we're currently using for data.
};
struct KeyMatches {
bool operator()(const BrickKey& key,
const std::pair<BrickInfo,TypeErase>& a) const {
return key == a.first.key;
}
};
// if the key doesn't exist, you get an empty vector.
template<typename T>
const void* BrickCache::bcinfo::typed_lookup(const BrickKey& k) {
using namespace std::placeholders;
KeyMatches km;
auto func = std::bind(&KeyMatches::operator(), km, k, _1);
// gcc can't seem to deduce this with 'auto'.
typedef std::vector<CacheElem> maptype;
maptype::iterator i = std::find_if(this->cache.begin(), this->cache.end(),
func);
if(i == this->cache.end()) { return NULL; }
i->first.access_time = time(NULL);
TypeErase::GenericType& gt = *(i->second.gt);
assert(this->size() == this->bytes);
return dynamic_cast<TypeErase::TypeEraser<std::vector<T>>&>(gt).get().data();
}
template<typename T>
const void* BrickCache::bcinfo::typed_add(const BrickKey& k,
std::vector<T>& data) {
// maybe the case of a general cache allows duplicate insert, but for our uses
// there should never be a duplicate entry.
#ifndef NDEBUG
KeyMatches km;
using namespace std::placeholders;
auto func = std::bind(&KeyMatches::operator(), km, k, _1);
assert(std::find_if(this->cache.begin(), this->cache.end(), func) ==
this->cache.end());
#endif
this->bytes += sizeof(T) * data.size();
this->cache.push_back(std::make_pair(BrickInfo(k, time(NULL)),
std::move(data)));
assert(this->size() == this->bytes);
return this->typed_lookup<T>(k);
}
BrickCache::BrickCache() : ci(new BrickCache::bcinfo) {}
BrickCache::~BrickCache() {}
const void* BrickCache::lookup(const BrickKey& k) {
return this->ci->lookup(k);
}
#if 0
void BrickCache::lookup(const BrickKey& k, std::vector<uint16_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<uint32_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<uint64_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int8_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int16_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int32_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int64_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<float>& data) {
return this->ci->lookup(k, data);
}
#endif
const void* BrickCache::add(const BrickKey& k,
std::vector<uint8_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<uint16_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<uint32_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<uint64_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int8_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int16_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int32_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int64_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<float>& data) {
return this->ci->add(k, data);
}
void BrickCache::remove() { this->ci->remove(); }
size_t BrickCache::size() const { return this->ci->size(); }
}
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2013 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
<commit_msg>remove unused overloads<commit_after>#include <algorithm>
#include <ctime>
#include <functional>
#include <map>
#include <memory>
#include "BrickCache.h"
#include "Controller/StackTimer.h"
namespace tuvok {
// This is used to basically get rid of a type. You can do:
// std::vector<TypeErase> data;
// std::vector<uint8_t> foo;
// std::vector<uint16_t> bar;
// data.push_back(TypeErase<std::vector<uint8_t>>(foo));
// data.push_back(TypeErase<std::vector<uint16_t>>(bar));
// with 'MyTypeOne' and 'MyTypeTwo' being completely unrelated (they do not
// need to have a common base class)
struct TypeErase {
struct GenericType {
virtual ~GenericType() {}
virtual size_t elems() const { return 0; }
};
template<typename T> struct TypeEraser : GenericType {
TypeEraser(T&& t) : thing(std::forward<T>(t)) {}
virtual ~TypeEraser() {}
T& get() { return thing; }
size_t elems() const { return thing.size(); }
private: T thing;
};
std::shared_ptr<GenericType> gt;
size_t width;
TypeErase(TypeErase&& other)
: gt(std::move(other.gt))
, width(other.width) // width should stay the same right?
{}
TypeErase& operator=(TypeErase&& other) {
if (this != &other) {
gt = std::move(other.gt);
width = other.width; // width should stay the same right?
}
return *this;
}
// this isn't a very good type eraser, because we require that the type has
// an internal typedef 'value_type' which we can use to obtain the size of
// it. not to mention the '.size()' member function that TypeEraser<>
// requires, above.
// But that's fine for our usage here; we're really just using this to store
// vectors and erase the value_type in there anyway.
template<typename T> TypeErase(T&& t)
: gt(new TypeEraser<T>(std::forward<T>(t)))
, width(sizeof(typename std::remove_reference<T>::type::value_type))
{}
};
struct BrickInfo {
BrickKey key;
uint64_t access_time;
BrickInfo(const BrickKey& k, time_t t) : key(k),
access_time(uint64_t(t)) {}
};
struct CacheLRU {
typedef std::pair<BrickInfo, TypeErase> CacheElem;
bool operator()(const CacheElem& a, const CacheElem& b) const {
return a.first.access_time > b.first.access_time;
}
};
struct BrickCache::bcinfo {
bcinfo(): bytes(0) {}
// this is wordy but they all just forward to a real implementation below.
const void* lookup(const BrickKey& k) {
return this->typed_lookup<uint8_t>(k);
}
// the erasure means we can just do the insert with the thing we already
// have: it'll make a shared_ptr out of it and insert it into the
// container.
///@{
const void* add(const BrickKey& k, std::vector<uint8_t>& data) {
return this->typed_add<uint8_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<uint16_t>& data) {
return this->typed_add<uint16_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<uint32_t>& data) {
return this->typed_add<uint32_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<uint64_t>& data) {
return this->typed_add<uint64_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int8_t>& data) {
return this->typed_add<int8_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int16_t>& data) {
return this->typed_add<int16_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int32_t>& data) {
return this->typed_add<int32_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<int64_t>& data) {
return this->typed_add<int64_t>(k, data);
}
const void* add(const BrickKey& k, std::vector<float>& data) {
return this->typed_add<float>(k, data);
}
///@}
void remove() {
if(!cache.empty()) {
// libstdc++ complains it's not a heap otherwise.. somehow. bug?
std::make_heap(this->cache.begin(), this->cache.end(), CacheLRU());
const CacheElem& entry = this->cache.front();
TypeErase::GenericType& gt = *(entry.second.gt);
assert((entry.second.width * gt.elems()) <= this->bytes);
this->bytes -= entry.second.width * gt.elems();
std::pop_heap(this->cache.begin(), this->cache.end(), CacheLRU());
this->cache.pop_back();
}
assert(this->size() == this->bytes);
}
size_t size() const { return this->bytes; }
private:
template<typename T> const void* typed_lookup(const BrickKey& k);
template<typename T> const void* typed_add(const BrickKey&,
std::vector<T>&);
private:
typedef std::pair<BrickInfo, TypeErase> CacheElem;
std::vector<CacheElem> cache;
size_t bytes; ///< how much memory we're currently using for data.
};
struct KeyMatches {
bool operator()(const BrickKey& key,
const std::pair<BrickInfo,TypeErase>& a) const {
return key == a.first.key;
}
};
// if the key doesn't exist, you get an empty vector.
template<typename T>
const void* BrickCache::bcinfo::typed_lookup(const BrickKey& k) {
using namespace std::placeholders;
KeyMatches km;
auto func = std::bind(&KeyMatches::operator(), km, k, _1);
// gcc can't seem to deduce this with 'auto'.
typedef std::vector<CacheElem> maptype;
maptype::iterator i = std::find_if(this->cache.begin(), this->cache.end(),
func);
if(i == this->cache.end()) { return NULL; }
i->first.access_time = time(NULL);
TypeErase::GenericType& gt = *(i->second.gt);
assert(this->size() == this->bytes);
return dynamic_cast<TypeErase::TypeEraser<std::vector<T>>&>(gt).get().data();
}
template<typename T>
const void* BrickCache::bcinfo::typed_add(const BrickKey& k,
std::vector<T>& data) {
// maybe the case of a general cache allows duplicate insert, but for our uses
// there should never be a duplicate entry.
#ifndef NDEBUG
KeyMatches km;
using namespace std::placeholders;
auto func = std::bind(&KeyMatches::operator(), km, k, _1);
assert(std::find_if(this->cache.begin(), this->cache.end(), func) ==
this->cache.end());
#endif
this->bytes += sizeof(T) * data.size();
this->cache.push_back(std::make_pair(BrickInfo(k, time(NULL)),
std::move(data)));
assert(this->size() == this->bytes);
return this->typed_lookup<T>(k);
}
BrickCache::BrickCache() : ci(new BrickCache::bcinfo) {}
BrickCache::~BrickCache() {}
const void* BrickCache::lookup(const BrickKey& k) {
return this->ci->lookup(k);
}
#if 0
void BrickCache::lookup(const BrickKey& k, std::vector<uint16_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<uint32_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<uint64_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int8_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int16_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int32_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<int64_t>& data) {
return this->ci->lookup(k, data);
}
void BrickCache::lookup(const BrickKey& k, std::vector<float>& data) {
return this->ci->lookup(k, data);
}
#endif
const void* BrickCache::add(const BrickKey& k,
std::vector<uint8_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<uint16_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<uint32_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<uint64_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int8_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int16_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int32_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<int64_t>& data) {
return this->ci->add(k, data);
}
const void* BrickCache::add(const BrickKey& k,
std::vector<float>& data) {
return this->ci->add(k, data);
}
void BrickCache::remove() { this->ci->remove(); }
size_t BrickCache::size() const { return this->ci->size(); }
}
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2013 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include <valarray>
#include "nbody.hpp"
/*
* TODO:
* parse input file / arguments
*/
int main(int argc, char *argv[]) {
// number of bodies
//const int n = 2;
const int n = 3;
// time step
double dt = 1e-5;
int steps = 2e5;
// masses
//double m[n] = {1.0, 0.1};
double m[n] = {150.0, 200.0, 250.0};
// positions and velocities
//double x_init[6 * n] = {0.0, 1.0, 0.0, 0.0, 0.02, 0.0,
// 5.0, 0.0, 0.0, 0.0, -0.2, 0.0};
double x_init[6 * n] = { 3.0, 1.0, 0.0, 0.0, 0.0, 0.0,
-1.0, -2.0, 0.0, 0.0, 0.0, 0.0,
-1.0, 1.0, 0.0, 0.0, 0.0, 0.0};
std::valarray<double> x(x_init, 6 * n);
print_array(x);
x = rk4_integrate(x, m, n, dt, steps);
return 0;
}
void print_array(std::valarray<double> a) {
for (int i = 0; i < a.size() - 1; i++) {
std::cout << a[i] << " ";
}
std::cout << a[a.size() - 1] << "\n";
}
double dist(std::valarray<double> a, std::valarray<double> b) {
return sqrt(pow(b - a, 2).sum());
}
std::valarray<double> pos(std::valarray<double> x, int i) {
return x[std::slice(i * 6, 3, 1)];
}
std::valarray<double> vel(std::valarray<double> x, int i) {
return x[std::slice(i * 6 + 3, 3, 1)];
}
std::slice pos_sel(int i) { return std::slice(i * 6, 3, 1); }
std::slice vel_sel(int i) { return std::slice(i * 6 + 3, 3, 1); }
std::valarray<double> newton(std::valarray<double> x, double m[], int n) {
std::valarray<double> ri(3), rj(3);
std::valarray<double> x_dot(n * 6);
for (int i = 0; i < n; i++) {
ri = pos(x, i);
x_dot[pos_sel(i)] = vel(x, i);
for (int j = 0; j < n; j++) {
if (j != i) {
rj = pos(x, j);
x_dot[vel_sel(i)] += G * m[j] * (rj - ri)
/ pow(dist(rj, ri), 3);
}
}
}
return x_dot;
}
std::valarray<double> rk4_step(std::valarray<double> x, double m[], int n,
double dt) {
std::valarray<double> k1(n * 6), k2(n * 6), k3(n * 6), k4(n * 6);
k1 = dt * newton(x, m, n);
k2 = dt * newton(x + k1 / 2.0, m, n);
k3 = dt * newton(x + k2 / 2.0, m, n);
k4 = dt * newton(x + k3, m, n);
x += (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;
print_array(x);
return x;
}
std::valarray<double> rk4_integrate(std::valarray<double> x, double m[],
int n, double dt, int steps) {
while (steps--) {
x = rk4_step(x, m, n, dt);
}
return x;
}
<commit_msg>Base n-body integrator class<commit_after>#include <cmath>
#include <cstdlib>
#include <iostream>
#include <valarray>
#include "nbody.hpp"
void NBody::print_state() {
std::cout << t << " ";
for (int i = 0; i < X.size() - 1; i++)
std::cout << X[i] << " ";
std::cout << X[X.size() - 1] << "\n";
}
void NBody::write_state() {
// TODO
;
}
double NBody::dist(std::valarray<double> a, std::valarray<double> b) {
return std::sqrt(std::pow(b - a, 2).sum());
}
std::slice NBody::pos_sel(int i_body) {
return std::slice(2 * n_dims * i_body, n_dims, 1);
}
std::slice NBody::vel_sel(int i_body) {
return std::slice(2 * n_dims * i_body + n_dims, n_dims, 1);
}
std::valarray<double> NBody::pos(std::valarray<double> x, int i_body) {
return x[pos_sel(i_body)];
}
std::valarray<double> NBody::vel(std::valarray<double> x, int i_body) {
return x[vel_sel(i_body)];
}
<|endoftext|> |
<commit_before>#include "indexer/feature_meta.hpp"
#include "std/algorithm.hpp"
#include "std/target_os.hpp"
namespace feature
{
namespace
{
char constexpr const * kBaseWikiUrl =
#ifdef OMIM_OS_MOBILE
".m.wikipedia.org/wiki/";
#else
".wikipedia.org/wiki/";
#endif
} // namespace
string Metadata::GetWikiURL() const
{
string v = this->Get(FMD_WIKIPEDIA);
if (v.empty())
return v;
auto const colon = v.find(':');
if (colon == string::npos)
return v;
// Spaces and % sign should be replaced in urls.
replace(v.begin() + colon, v.end(), ' ', '_');
string::size_type percent, pos = colon;
string const escapedPercent("%25");
while ((percent = v.find('%', pos)) != string::npos)
{
v.replace(percent, 1, escapedPercent);
pos = percent + escapedPercent.size();
}
// Trying to avoid redirects by constructing the right link.
// TODO: Wikipedia article could be opened it a user's language, but need
// generator level support to check for available article languages first.
return "https://" + v.substr(0, colon) + kBaseWikiUrl + v.substr(colon + 1);
}
} // namespace feature
// Prints types in osm-friendly format.
string DebugPrint(feature::Metadata::EType type)
{
using feature::Metadata;
switch (type)
{
case Metadata::FMD_CUISINE: return "cuisine";
case Metadata::FMD_OPEN_HOURS: return "opening_hours";
case Metadata::FMD_PHONE_NUMBER: return "phone";
case Metadata::FMD_FAX_NUMBER: return "fax";
case Metadata::FMD_STARS: return "stars";
case Metadata::FMD_OPERATOR: return "operator";
case Metadata::FMD_URL: return "url";
case Metadata::FMD_WEBSITE: return "website";
case Metadata::FMD_INTERNET: return "internet_access";
case Metadata::FMD_ELE: return "elevation";
case Metadata::FMD_TURN_LANES: return "turn:lanes";
case Metadata::FMD_TURN_LANES_FORWARD: return "turn:lanes:forward";
case Metadata::FMD_TURN_LANES_BACKWARD: return "turn:lanes:backward";
case Metadata::FMD_EMAIL: return "email";
case Metadata::FMD_POSTCODE: return "addr:postcode";
case Metadata::FMD_WIKIPEDIA: return "wikipedia";
case Metadata::FMD_MAXSPEED: return "maxspeed";
case Metadata::FMD_FLATS: return "addr:flats";
case Metadata::FMD_HEIGHT: return "height";
case Metadata::FMD_MIN_HEIGHT: return "min_height";
case Metadata::FMD_DENOMINATION: return "denomination";
case Metadata::FMD_COUNT: CHECK(false, ("FMD_COUNT can not be used as a type."));
};
return string();
}
<commit_msg>Missing switch case for Metadata::FMD_BUILDING_LEVELS.<commit_after>#include "indexer/feature_meta.hpp"
#include "std/algorithm.hpp"
#include "std/target_os.hpp"
namespace feature
{
namespace
{
char constexpr const * kBaseWikiUrl =
#ifdef OMIM_OS_MOBILE
".m.wikipedia.org/wiki/";
#else
".wikipedia.org/wiki/";
#endif
} // namespace
string Metadata::GetWikiURL() const
{
string v = this->Get(FMD_WIKIPEDIA);
if (v.empty())
return v;
auto const colon = v.find(':');
if (colon == string::npos)
return v;
// Spaces and % sign should be replaced in urls.
replace(v.begin() + colon, v.end(), ' ', '_');
string::size_type percent, pos = colon;
string const escapedPercent("%25");
while ((percent = v.find('%', pos)) != string::npos)
{
v.replace(percent, 1, escapedPercent);
pos = percent + escapedPercent.size();
}
// Trying to avoid redirects by constructing the right link.
// TODO: Wikipedia article could be opened it a user's language, but need
// generator level support to check for available article languages first.
return "https://" + v.substr(0, colon) + kBaseWikiUrl + v.substr(colon + 1);
}
} // namespace feature
// Prints types in osm-friendly format.
string DebugPrint(feature::Metadata::EType type)
{
using feature::Metadata;
switch (type)
{
case Metadata::FMD_CUISINE: return "cuisine";
case Metadata::FMD_OPEN_HOURS: return "opening_hours";
case Metadata::FMD_PHONE_NUMBER: return "phone";
case Metadata::FMD_FAX_NUMBER: return "fax";
case Metadata::FMD_STARS: return "stars";
case Metadata::FMD_OPERATOR: return "operator";
case Metadata::FMD_URL: return "url";
case Metadata::FMD_WEBSITE: return "website";
case Metadata::FMD_INTERNET: return "internet_access";
case Metadata::FMD_ELE: return "elevation";
case Metadata::FMD_TURN_LANES: return "turn:lanes";
case Metadata::FMD_TURN_LANES_FORWARD: return "turn:lanes:forward";
case Metadata::FMD_TURN_LANES_BACKWARD: return "turn:lanes:backward";
case Metadata::FMD_EMAIL: return "email";
case Metadata::FMD_POSTCODE: return "addr:postcode";
case Metadata::FMD_WIKIPEDIA: return "wikipedia";
case Metadata::FMD_MAXSPEED: return "maxspeed";
case Metadata::FMD_FLATS: return "addr:flats";
case Metadata::FMD_HEIGHT: return "height";
case Metadata::FMD_MIN_HEIGHT: return "min_height";
case Metadata::FMD_DENOMINATION: return "denomination";
case Metadata::FMD_BUILDING_LEVELS: return "building:levels";
case Metadata::FMD_COUNT: CHECK(false, ("FMD_COUNT can not be used as a type."));
};
return string();
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief Class to allow simple byExample matching of mptr.
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ExampleMatcher.h"
#include "Basics/JsonHelper.h"
#include "Basics/StringUtils.h"
#include "Utils/V8ResolverGuard.h"
#include "V8/v8-utils.h"
#include "V8/v8-conv.h"
#include "V8Server/v8-shape-conv.h"
#include "V8Server/v8-vocbaseprivate.h"
#include "VocBase/VocShaper.h"
using namespace std;
using namespace triagens::arango;
using namespace triagens::basics;
////////////////////////////////////////////////////////////////////////////////
/// @brief cleans up the example object
////////////////////////////////////////////////////////////////////////////////
void ExampleMatcher::cleanup () {
auto zone = _shaper->memoryZone();
// clean shaped json objects
for (auto& def : definitions) {
for (auto& it : def._values) {
TRI_FreeShapedJson(zone, it);
}
}
}
void ExampleMatcher::fillExampleDefinition (v8::Isolate* isolate,
v8::Handle<v8::Object> const& example,
v8::Handle<v8::Array> const& names,
size_t& n,
std::string& errorMessage,
ExampleDefinition& def) {
TRI_IF_FAILURE("ExampleNoContextVocbase") {
// intentionally fail
THROW_ARANGO_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
TRI_vocbase_t* vocbase = GetContextVocBase(isolate);
if (vocbase == nullptr) {
// This should never be thrown as we are already in a transaction
THROW_ARANGO_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
def._pids.reserve(n);
def._values.reserve(n);
for (size_t i = 0; i < n; ++i) {
v8::Handle<v8::Value> key = names->Get((uint32_t) i);
v8::Handle<v8::Value> val = example->Get(key);
TRI_Utf8ValueNFC keyStr(TRI_UNKNOWN_MEM_ZONE, key);
if (*keyStr != nullptr) {
auto pid = _shaper->lookupAttributePathByName(*keyStr);
if (pid == 0) {
// Internal attributes do have pid == 0.
if (strncmp("_", *keyStr, 1) == 0) {
string const key(*keyStr, (size_t) keyStr.length());
string keyVal = TRI_ObjectToString(val);
if (TRI_VOC_ATTRIBUTE_KEY == key) {
def._internal.insert(make_pair(internalAttr::key, DocumentId(0, keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_REV == key) {
def._internal.insert(make_pair(internalAttr::rev, DocumentId(0, keyVal)));
}
else {
// We need a Collection Name Resolver here now!
V8ResolverGuard resolverGuard(vocbase);
CollectionNameResolver const* resolver = resolverGuard.getResolver();
string colName = keyVal.substr(0, keyVal.find("/"));
keyVal = keyVal.substr(keyVal.find("/") + 1, keyVal.length());
if (TRI_VOC_ATTRIBUTE_ID == key) {
def._internal.insert(make_pair(internalAttr::id, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_FROM == key) {
def._internal.insert(make_pair(internalAttr::from, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_TO == key) {
def._internal.insert(make_pair(internalAttr::to, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
else {
def._pids.push_back(pid);
auto value = TRI_ShapedJsonV8Object(isolate, val, _shaper, false);
if (value == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
def._values.push_back(value);
}
}
else {
errorMessage = "cannot convert attribute path to UTF8";
THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}
}
}
void ExampleMatcher::fillExampleDefinition (TRI_json_t const* example,
CollectionNameResolver const* resolver,
ExampleDefinition& def) {
if ( TRI_IsStringJson(example) ) {
// Example is an _id value
char const* _key = strchr(example->_value._string.data, '/');
if (_key != nullptr) {
_key += 1;
def._internal.insert(make_pair(internalAttr::key, DocumentId(0, _key)));
return;
} else {
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
TRI_vector_t objects = example->_value._objects;
// Trolololol std::vector in C... ;(
size_t n = TRI_LengthVector(&objects);
def._pids.reserve(n);
def._values.reserve(n);
try {
for (size_t i = 0; i < n; i += 2) {
auto keyObj = static_cast<TRI_json_t const*>(TRI_AtVector(&objects, i));
TRI_ASSERT(TRI_IsStringJson(keyObj));
char const* keyStr = keyObj->_value._string.data;
auto pid = _shaper->lookupAttributePathByName(keyStr);
if (pid == 0) {
// Internal attributes do have pid == 0.
if (strncmp("_", keyStr, 1) == 0) {
string const key(keyStr);
auto jsonValue = static_cast<TRI_json_t const*>(TRI_AtVector(&objects, i + 1));
if (! TRI_IsStringJson(jsonValue)) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_TYPE_ERROR);
}
string keyVal(jsonValue->_value._string.data);
if (TRI_VOC_ATTRIBUTE_KEY == key) {
def._internal.insert(make_pair(internalAttr::key, DocumentId(0, keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_REV == key) {
def._internal.insert(make_pair(internalAttr::rev, DocumentId(0, keyVal)));
}
else {
string colName = keyVal.substr(0, keyVal.find("/"));
keyVal = keyVal.substr(keyVal.find("/") + 1, keyVal.length());
if (TRI_VOC_ATTRIBUTE_ID == key) {
def._internal.insert(make_pair(internalAttr::id, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_FROM == key) {
def._internal.insert(make_pair(internalAttr::from, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_TO == key) {
def._internal.insert(make_pair(internalAttr::to, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
else {
def._pids.push_back(pid);
auto jsonValue = static_cast<TRI_json_t const*>(TRI_AtVector(&objects, i + 1));
auto value = TRI_ShapedJsonJson(_shaper, jsonValue, false);
if (value == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
def._values.push_back(value);
}
}
}
catch (bad_alloc&) {
ExampleMatcher::cleanup();
throw;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Constructor using a v8::Object example
////////////////////////////////////////////////////////////////////////////////
ExampleMatcher::ExampleMatcher (v8::Isolate* isolate,
v8::Handle<v8::Object> const example,
VocShaper* shaper,
std::string& errorMessage)
: _shaper(shaper) {
v8::Handle<v8::Array> names = example->GetOwnPropertyNames();
size_t n = names->Length();
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(isolate, example, names, n, errorMessage, def);
}
catch (...) {
ExampleMatcher::cleanup();
throw;
}
definitions.emplace_back(move(def));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Constructor using an v8::Array of v8::Object examples
////////////////////////////////////////////////////////////////////////////////
ExampleMatcher::ExampleMatcher (v8::Isolate* isolate,
v8::Handle<v8::Array> const examples,
VocShaper* shaper,
std::string& errorMessage)
: _shaper(shaper) {
size_t exCount = examples->Length();
for (size_t j = 0; j < exCount; ++j) {
auto tmp = examples->Get((uint32_t) j);
if (! tmp->IsObject() || tmp->IsArray()) {
// Right now silently ignore this example
continue;
}
v8::Handle<v8::Object> example = v8::Handle<v8::Object>::Cast(tmp);
v8::Handle<v8::Array> names = example->GetOwnPropertyNames();
size_t n = names->Length();
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(isolate, example, names, n, errorMessage, def);
}
catch (...) {
ExampleMatcher::cleanup();
throw;
}
definitions.emplace_back(move(def));
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Constructor using a TRI_json_t object
////////////////////////////////////////////////////////////////////////////////
ExampleMatcher::ExampleMatcher (TRI_json_t const* example,
VocShaper* shaper,
CollectionNameResolver const* resolver)
: _shaper(shaper) {
if (TRI_IsObjectJson(example) || TRI_IsStringJson(example)) {
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(example, resolver, def);
}
catch (...) {
ExampleMatcher::cleanup();
throw;
}
definitions.emplace_back(move(def));
}
else if (TRI_IsArrayJson(example)) {
size_t size = TRI_LengthArrayJson(example);
for (size_t i = 0; i < size; ++i) {
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(TRI_LookupArrayJson(example, i), resolver, def);
definitions.emplace_back(move(def));
}
catch (triagens::basics::Exception& e) {
if (e.code() != TRI_RESULT_ELEMENT_NOT_FOUND) {
ExampleMatcher::cleanup();
throw;
}
// Result not found might happen. Ignore here because all other elemens
// might be matched.
}
}
if (definitions.size() == 0) {
// None of the given examples could ever match.
// Throw result not found so client can short circuit.
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Checks if the given mptr matches the examples in this class
////////////////////////////////////////////////////////////////////////////////
bool ExampleMatcher::matches (TRI_voc_cid_t cid, TRI_doc_mptr_t const* mptr) const {
if (mptr == nullptr) {
return false;
}
TRI_shaped_json_t document;
TRI_EXTRACT_SHAPED_JSON_MARKER(document, mptr->getDataPtr());
for (auto def : definitions) {
if (def._internal.size() > 0) {
// Match _key
auto it = def._internal.find(internalAttr::key);
if (it != def._internal.end()) {
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_KEY(mptr)) != 0) {
goto nextExample;
}
}
// Match _rev
it = def._internal.find(internalAttr::rev);
if (it != def._internal.end()) {
if (triagens::basics::StringUtils::uint64(it->second.key) != mptr->_rid) {
goto nextExample;
}
}
// Match _id
it = def._internal.find(internalAttr::id);
if (it != def._internal.end()) {
if (cid != it->second.cid) {
goto nextExample;
}
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_KEY(mptr)) != 0) {
goto nextExample;
}
}
// Match _to
it = def._internal.find(internalAttr::to);
if (it != def._internal.end()) {
if (it->second.cid != TRI_EXTRACT_MARKER_TO_CID(mptr)) {
goto nextExample;
}
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_TO_KEY(mptr)) != 0) {
goto nextExample;
}
}
// Match _from
it = def._internal.find(internalAttr::from);
if (it != def._internal.end()) {
if (it->second.cid != TRI_EXTRACT_MARKER_FROM_CID(mptr)) {
goto nextExample;
}
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_FROM_KEY(mptr)) != 0) {
goto nextExample;
}
}
}
TRI_shaped_json_t result;
TRI_shape_t const* shape;
for (size_t i = 0; i < def._values.size(); ++i) {
TRI_shaped_json_t* example = def._values[i];
bool ok = _shaper->extractShapedJson(&document,
example->_sid,
def._pids[i],
&result,
&shape);
if (! ok || shape == nullptr) {
goto nextExample;
}
if (result._data.length != example->_data.length) {
// suppress excessive log spam
// LOG_TRACE("expecting length %lu, got length %lu for path %lu",
// (unsigned long) result._data.length,
// (unsigned long) example->_data.length,
// (unsigned long) pids[i]);
goto nextExample;
}
if (memcmp(result._data.data, example->_data.data, example->_data.length) != 0) {
// suppress excessive log spam
// LOG_TRACE("data mismatch at path %lu", (unsigned long) pids[i]);
goto nextExample;
}
}
// If you get here this example matches. Successful hit.
return true;
nextExample:
// This Example does not match, try the next one. Goto requires a statement
continue;
}
return false;
}
<commit_msg>Potential fix for memleak<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief Class to allow simple byExample matching of mptr.
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ExampleMatcher.h"
#include "Basics/JsonHelper.h"
#include "Basics/StringUtils.h"
#include "Utils/V8ResolverGuard.h"
#include "V8/v8-utils.h"
#include "V8/v8-conv.h"
#include "V8Server/v8-shape-conv.h"
#include "V8Server/v8-vocbaseprivate.h"
#include "VocBase/VocShaper.h"
using namespace std;
using namespace triagens::arango;
using namespace triagens::basics;
////////////////////////////////////////////////////////////////////////////////
/// @brief cleans up the example object
////////////////////////////////////////////////////////////////////////////////
void ExampleMatcher::cleanup () {
auto zone = _shaper->memoryZone();
// clean shaped json objects
for (auto& def : definitions) {
for (auto& it : def._values) {
TRI_FreeShapedJson(zone, it);
it = nullptr;
}
}
}
void ExampleMatcher::fillExampleDefinition (v8::Isolate* isolate,
v8::Handle<v8::Object> const& example,
v8::Handle<v8::Array> const& names,
size_t& n,
std::string& errorMessage,
ExampleDefinition& def) {
TRI_IF_FAILURE("ExampleNoContextVocbase") {
// intentionally fail
THROW_ARANGO_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
TRI_vocbase_t* vocbase = GetContextVocBase(isolate);
if (vocbase == nullptr) {
// This should never be thrown as we are already in a transaction
THROW_ARANGO_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
def._pids.reserve(n);
def._values.reserve(n);
for (size_t i = 0; i < n; ++i) {
v8::Handle<v8::Value> key = names->Get((uint32_t) i);
v8::Handle<v8::Value> val = example->Get(key);
TRI_Utf8ValueNFC keyStr(TRI_UNKNOWN_MEM_ZONE, key);
if (*keyStr != nullptr) {
auto pid = _shaper->lookupAttributePathByName(*keyStr);
if (pid == 0) {
// Internal attributes do have pid == 0.
if (strncmp("_", *keyStr, 1) == 0) {
string const key(*keyStr, (size_t) keyStr.length());
string keyVal = TRI_ObjectToString(val);
if (TRI_VOC_ATTRIBUTE_KEY == key) {
def._internal.insert(make_pair(internalAttr::key, DocumentId(0, keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_REV == key) {
def._internal.insert(make_pair(internalAttr::rev, DocumentId(0, keyVal)));
}
else {
// We need a Collection Name Resolver here now!
V8ResolverGuard resolverGuard(vocbase);
CollectionNameResolver const* resolver = resolverGuard.getResolver();
string colName = keyVal.substr(0, keyVal.find("/"));
keyVal = keyVal.substr(keyVal.find("/") + 1, keyVal.length());
if (TRI_VOC_ATTRIBUTE_ID == key) {
def._internal.insert(make_pair(internalAttr::id, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_FROM == key) {
def._internal.insert(make_pair(internalAttr::from, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_TO == key) {
def._internal.insert(make_pair(internalAttr::to, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
else {
def._pids.push_back(pid);
std::unique_ptr<TRI_shaped_json_t> value(TRI_ShapedJsonV8Object(isolate, val, _shaper, false));
if (value.get() == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
def._values.push_back(value.get());
value.release();
}
}
else {
errorMessage = "cannot convert attribute path to UTF8";
THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}
}
}
void ExampleMatcher::fillExampleDefinition (TRI_json_t const* example,
CollectionNameResolver const* resolver,
ExampleDefinition& def) {
if ( TRI_IsStringJson(example) ) {
// Example is an _id value
char const* _key = strchr(example->_value._string.data, '/');
if (_key != nullptr) {
_key += 1;
def._internal.insert(make_pair(internalAttr::key, DocumentId(0, _key)));
return;
} else {
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
TRI_vector_t objects = example->_value._objects;
// Trolololol std::vector in C... ;(
size_t n = TRI_LengthVector(&objects);
def._pids.reserve(n);
def._values.reserve(n);
try {
for (size_t i = 0; i < n; i += 2) {
auto keyObj = static_cast<TRI_json_t const*>(TRI_AtVector(&objects, i));
TRI_ASSERT(TRI_IsStringJson(keyObj));
char const* keyStr = keyObj->_value._string.data;
auto pid = _shaper->lookupAttributePathByName(keyStr);
if (pid == 0) {
// Internal attributes do have pid == 0.
if (strncmp("_", keyStr, 1) == 0) {
string const key(keyStr);
auto jsonValue = static_cast<TRI_json_t const*>(TRI_AtVector(&objects, i + 1));
if (! TRI_IsStringJson(jsonValue)) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_TYPE_ERROR);
}
string keyVal(jsonValue->_value._string.data);
if (TRI_VOC_ATTRIBUTE_KEY == key) {
def._internal.insert(make_pair(internalAttr::key, DocumentId(0, keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_REV == key) {
def._internal.insert(make_pair(internalAttr::rev, DocumentId(0, keyVal)));
}
else {
string colName = keyVal.substr(0, keyVal.find("/"));
keyVal = keyVal.substr(keyVal.find("/") + 1, keyVal.length());
if (TRI_VOC_ATTRIBUTE_ID == key) {
def._internal.insert(make_pair(internalAttr::id, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_FROM == key) {
def._internal.insert(make_pair(internalAttr::from, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else if (TRI_VOC_ATTRIBUTE_TO == key) {
def._internal.insert(make_pair(internalAttr::to, DocumentId(resolver->getCollectionId(colName), keyVal)));
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
}
else {
// no attribute path found. this means the result will be empty
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
else {
def._pids.push_back(pid);
auto jsonValue = static_cast<TRI_json_t const*>(TRI_AtVector(&objects, i + 1));
auto value = TRI_ShapedJsonJson(_shaper, jsonValue, false);
if (value == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
def._values.push_back(value);
}
}
}
catch (bad_alloc&) {
ExampleMatcher::cleanup();
throw;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Constructor using a v8::Object example
////////////////////////////////////////////////////////////////////////////////
ExampleMatcher::ExampleMatcher (v8::Isolate* isolate,
v8::Handle<v8::Object> const example,
VocShaper* shaper,
std::string& errorMessage)
: _shaper(shaper) {
v8::Handle<v8::Array> names = example->GetOwnPropertyNames();
size_t n = names->Length();
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(isolate, example, names, n, errorMessage, def);
}
catch (...) {
ExampleMatcher::cleanup();
throw;
}
definitions.emplace_back(move(def));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Constructor using an v8::Array of v8::Object examples
////////////////////////////////////////////////////////////////////////////////
ExampleMatcher::ExampleMatcher (v8::Isolate* isolate,
v8::Handle<v8::Array> const examples,
VocShaper* shaper,
std::string& errorMessage)
: _shaper(shaper) {
size_t exCount = examples->Length();
for (size_t j = 0; j < exCount; ++j) {
auto tmp = examples->Get((uint32_t) j);
if (! tmp->IsObject() || tmp->IsArray()) {
// Right now silently ignore this example
continue;
}
v8::Handle<v8::Object> example = v8::Handle<v8::Object>::Cast(tmp);
v8::Handle<v8::Array> names = example->GetOwnPropertyNames();
size_t n = names->Length();
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(isolate, example, names, n, errorMessage, def);
}
catch (...) {
ExampleMatcher::cleanup();
throw;
}
definitions.emplace_back(move(def));
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Constructor using a TRI_json_t object
////////////////////////////////////////////////////////////////////////////////
ExampleMatcher::ExampleMatcher (TRI_json_t const* example,
VocShaper* shaper,
CollectionNameResolver const* resolver)
: _shaper(shaper) {
if (TRI_IsObjectJson(example) || TRI_IsStringJson(example)) {
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(example, resolver, def);
}
catch (...) {
ExampleMatcher::cleanup();
throw;
}
definitions.emplace_back(move(def));
}
else if (TRI_IsArrayJson(example)) {
size_t size = TRI_LengthArrayJson(example);
for (size_t i = 0; i < size; ++i) {
ExampleDefinition def;
try {
ExampleMatcher::fillExampleDefinition(TRI_LookupArrayJson(example, i), resolver, def);
definitions.emplace_back(move(def));
}
catch (triagens::basics::Exception& e) {
if (e.code() != TRI_RESULT_ELEMENT_NOT_FOUND) {
ExampleMatcher::cleanup();
throw;
}
// Result not found might happen. Ignore here because all other elemens
// might be matched.
}
}
if (definitions.size() == 0) {
// None of the given examples could ever match.
// Throw result not found so client can short circuit.
THROW_ARANGO_EXCEPTION(TRI_RESULT_ELEMENT_NOT_FOUND);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Checks if the given mptr matches the examples in this class
////////////////////////////////////////////////////////////////////////////////
bool ExampleMatcher::matches (TRI_voc_cid_t cid, TRI_doc_mptr_t const* mptr) const {
if (mptr == nullptr) {
return false;
}
TRI_shaped_json_t document;
TRI_EXTRACT_SHAPED_JSON_MARKER(document, mptr->getDataPtr());
for (auto def : definitions) {
if (def._internal.size() > 0) {
// Match _key
auto it = def._internal.find(internalAttr::key);
if (it != def._internal.end()) {
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_KEY(mptr)) != 0) {
goto nextExample;
}
}
// Match _rev
it = def._internal.find(internalAttr::rev);
if (it != def._internal.end()) {
if (triagens::basics::StringUtils::uint64(it->second.key) != mptr->_rid) {
goto nextExample;
}
}
// Match _id
it = def._internal.find(internalAttr::id);
if (it != def._internal.end()) {
if (cid != it->second.cid) {
goto nextExample;
}
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_KEY(mptr)) != 0) {
goto nextExample;
}
}
// Match _to
it = def._internal.find(internalAttr::to);
if (it != def._internal.end()) {
if (it->second.cid != TRI_EXTRACT_MARKER_TO_CID(mptr)) {
goto nextExample;
}
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_TO_KEY(mptr)) != 0) {
goto nextExample;
}
}
// Match _from
it = def._internal.find(internalAttr::from);
if (it != def._internal.end()) {
if (it->second.cid != TRI_EXTRACT_MARKER_FROM_CID(mptr)) {
goto nextExample;
}
if (strcmp(it->second.key.c_str(), TRI_EXTRACT_MARKER_FROM_KEY(mptr)) != 0) {
goto nextExample;
}
}
}
TRI_shaped_json_t result;
TRI_shape_t const* shape;
for (size_t i = 0; i < def._values.size(); ++i) {
TRI_shaped_json_t* example = def._values[i];
bool ok = _shaper->extractShapedJson(&document,
example->_sid,
def._pids[i],
&result,
&shape);
if (! ok || shape == nullptr) {
goto nextExample;
}
if (result._data.length != example->_data.length) {
// suppress excessive log spam
// LOG_TRACE("expecting length %lu, got length %lu for path %lu",
// (unsigned long) result._data.length,
// (unsigned long) example->_data.length,
// (unsigned long) pids[i]);
goto nextExample;
}
if (memcmp(result._data.data, example->_data.data, example->_data.length) != 0) {
// suppress excessive log spam
// LOG_TRACE("data mismatch at path %lu", (unsigned long) pids[i]);
goto nextExample;
}
}
// If you get here this example matches. Successful hit.
return true;
nextExample:
// This Example does not match, try the next one. Goto requires a statement
continue;
}
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kaa/failover/DefaultFailoverStrategy.hpp"
namespace kaa {
const std::size_t DefaultFailoverStrategy::DEFAULT_BOOTSTRAP_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_OPERATION_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_NO_OPERATION_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_CURRENT_BOOTSTRAP_SERVER_NA;
const std::size_t DefaultFailoverStrategy::DEFAULT_NO_CONNECTIVITY_RETRY_PERIOD;
FailoverStrategyDecision DefaultFailoverStrategy::onFailover(KaaFailoverReason failover)
{
switch (failover) {
case KaaFailoverReason::BOOTSTRAP_SERVERS_NA:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY,
bootstrapServersRetryPeriod_);
case KaaFailoverReason::NO_OPERATION_SERVERS_RECEIVED:
return FailoverStrategyDecision(FailoverStrategyAction::USE_NEXT_BOOTSTRAP,
noOperationServersRetryPeriod_);
case KaaFailoverReason::OPERATION_SERVERS_NA:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY,
operationServersRetryPeriod_);
case KaaFailoverReason::NO_CONNECTIVITY:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY,
noConnectivityRetryPeriod_);
case KaaFailoverReason::CREDENTIALS_REVOKED:
case KaaFailoverReason::ENDPOINT_NOT_REGISTERED:
return FailoverStrategyDecision(FailoverStrategyAction::STOP_APP);
default:
return FailoverStrategyDecision(FailoverStrategyAction::NOOP);
}
}
}
<commit_msg>KAA-965 Change default behaviour<commit_after>/*
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kaa/failover/DefaultFailoverStrategy.hpp"
namespace kaa {
const std::size_t DefaultFailoverStrategy::DEFAULT_BOOTSTRAP_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_OPERATION_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_NO_OPERATION_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_CURRENT_BOOTSTRAP_SERVER_NA;
const std::size_t DefaultFailoverStrategy::DEFAULT_NO_CONNECTIVITY_RETRY_PERIOD;
FailoverStrategyDecision DefaultFailoverStrategy::onFailover(KaaFailoverReason failover)
{
switch (failover) {
case KaaFailoverReason::BOOTSTRAP_SERVERS_NA:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY,
bootstrapServersRetryPeriod_);
case KaaFailoverReason::NO_OPERATION_SERVERS_RECEIVED:
return FailoverStrategyDecision(FailoverStrategyAction::USE_NEXT_BOOTSTRAP,
noOperationServersRetryPeriod_);
case KaaFailoverReason::OPERATION_SERVERS_NA:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY,
operationServersRetryPeriod_);
case KaaFailoverReason::NO_CONNECTIVITY:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY,
noConnectivityRetryPeriod_);
case KaaFailoverReason::CREDENTIALS_REVOKED:
case KaaFailoverReason::ENDPOINT_NOT_REGISTERED:
return FailoverStrategyDecision(FailoverStrategyAction::RETRY);
default:
return FailoverStrategyDecision(FailoverStrategyAction::NOOP);
}
}
}
<|endoftext|> |
<commit_before>/*The MIT License (MIT)
Copyright (c) 2014 Johannes Häggqvist
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 "extract.h"
#include "pretty.h"
#include "options.h"
#include "path.h"
#include <ZAP/Archive.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
namespace cli
{
static void print(const ZAP::Archive &archive)
{
std::cout <<
"Version: " << getPrettyVersion(archive.getVersion()) <<
"\nCompression: " << getPrettyCompression(archive.getCompression()) << (archive.isSupportedCompression() ? " (supported)" : " (unsupported)") <<
"\nFile count: " << archive.getFileCount() <<
"\n\n";
ZAP::Archive::EntryList filelist;
archive.getFileList(filelist);
static const int fieldMargin = 1;
int field0 = 4+fieldMargin, field1 = 10+fieldMargin, field2 = 12+fieldMargin;
for (const ZAP::Archive::Entry &entry : filelist)
{
int newField0 = entry.virtual_path.size()+fieldMargin;
int newField1 = getPrettySize(entry.compressed_size).size()+fieldMargin;
int newField2 = getPrettySize(entry.decompressed_size).size()+fieldMargin;
if (newField0 > field0)
field0 = newField0;
if (newField1 > field1)
field1 = newField1;
if (newField2 > field2)
field2 = newField2;
}
int totalComp = 0, totalDecomp = 0;
std::ios::fmtflags nameFlags = std::ios::left;
std::ios::fmtflags sizeFlags = std::ios::right;
std::cout <<
std::setiosflags(nameFlags) <<
std::setw(field0) << "Path" <<
std::setiosflags(sizeFlags) <<
std::setw(field1) << "Comp. size" <<
std::setw(field2) << "Decomp. size" <<
std::resetiosflags(sizeFlags) <<
'\n';
for (const ZAP::Archive::Entry &file : filelist)
{
totalComp += file.compressed_size;
totalDecomp += file.decompressed_size;
std::cout <<
std::setiosflags(nameFlags) <<
std::setw(field0) << file.virtual_path <<
std::setiosflags(sizeFlags) <<
std::setw(field1) << getPrettySize(file.compressed_size) <<
std::setw(field2) << getPrettySize(file.decompressed_size) <<
std::resetiosflags(sizeFlags) <<
'\n';
}
std::cout <<
std::setw(16) << "\nTotal comp.: " << getPrettySize(totalComp) <<
std::setw(16) << "\nTotal decomp.: " << getPrettySize(totalDecomp) <<
'\n';
std::cout << std::flush;
}
int extract(option::Parser &parse, option::Option *options)
{
if (parse.nonOptionsCount() < 1)
{
std::cerr << "Filename required" << std::endl;
return 1;
}
std::string path = parse.nonOption(0);
ZAP::Archive archive;
if (!archive.openFile(path))
{
std::cerr << "Could not open file" << std::endl;
return 1;
}
if (options[LIST])
{
print(archive);
}
else
{
std::string outPath = ".";
if (parse.nonOptionsCount() >= 2)
{
outPath = parse.nonOption(1);
}
if (!isDirectory(outPath))
{
std::cerr << "Output is not a directory" << std::endl;
return 1;
}
ZAP::Archive::EntryList list;
archive.getFileList(list);
for (const ZAP::Archive::Entry &entry : list)
{
std::string fullpath = (outPath + '/' + entry.virtual_path);
cleanPath(fullpath);
if (!createPath(fullpath))
{
std::cerr << "Could not create path " << fullpath << std::endl;
continue;
}
std::fstream stream(fullpath.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
if (!stream.is_open())
{
std::cerr << "Could not create file " << entry.virtual_path << std::endl;
continue;
}
char *data;
size_t size;
bool extractSuccess = false;
if (options[RAW])
extractSuccess = archive.getRawData(entry.virtual_path, data, size);
else
extractSuccess = archive.getData(entry.virtual_path, data, size);
if (!extractSuccess)
{
std::cerr << "Could not extract file " << entry.virtual_path << std::endl;
continue;
}
stream.write(data, size);
delete[] data;
}
}
return 0;
}
}
<commit_msg>Changed "Could not open file" to "Could not open archive"<commit_after>/*The MIT License (MIT)
Copyright (c) 2014 Johannes Häggqvist
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 "extract.h"
#include "pretty.h"
#include "options.h"
#include "path.h"
#include <ZAP/Archive.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
namespace cli
{
static void print(const ZAP::Archive &archive)
{
std::cout <<
"Version: " << getPrettyVersion(archive.getVersion()) <<
"\nCompression: " << getPrettyCompression(archive.getCompression()) << (archive.isSupportedCompression() ? " (supported)" : " (unsupported)") <<
"\nFile count: " << archive.getFileCount() <<
"\n\n";
ZAP::Archive::EntryList filelist;
archive.getFileList(filelist);
static const int fieldMargin = 1;
int field0 = 4+fieldMargin, field1 = 10+fieldMargin, field2 = 12+fieldMargin;
for (const ZAP::Archive::Entry &entry : filelist)
{
int newField0 = entry.virtual_path.size()+fieldMargin;
int newField1 = getPrettySize(entry.compressed_size).size()+fieldMargin;
int newField2 = getPrettySize(entry.decompressed_size).size()+fieldMargin;
if (newField0 > field0)
field0 = newField0;
if (newField1 > field1)
field1 = newField1;
if (newField2 > field2)
field2 = newField2;
}
int totalComp = 0, totalDecomp = 0;
std::ios::fmtflags nameFlags = std::ios::left;
std::ios::fmtflags sizeFlags = std::ios::right;
std::cout <<
std::setiosflags(nameFlags) <<
std::setw(field0) << "Path" <<
std::setiosflags(sizeFlags) <<
std::setw(field1) << "Comp. size" <<
std::setw(field2) << "Decomp. size" <<
std::resetiosflags(sizeFlags) <<
'\n';
for (const ZAP::Archive::Entry &file : filelist)
{
totalComp += file.compressed_size;
totalDecomp += file.decompressed_size;
std::cout <<
std::setiosflags(nameFlags) <<
std::setw(field0) << file.virtual_path <<
std::setiosflags(sizeFlags) <<
std::setw(field1) << getPrettySize(file.compressed_size) <<
std::setw(field2) << getPrettySize(file.decompressed_size) <<
std::resetiosflags(sizeFlags) <<
'\n';
}
std::cout <<
std::setw(16) << "\nTotal comp.: " << getPrettySize(totalComp) <<
std::setw(16) << "\nTotal decomp.: " << getPrettySize(totalDecomp) <<
'\n';
std::cout << std::flush;
}
int extract(option::Parser &parse, option::Option *options)
{
if (parse.nonOptionsCount() < 1)
{
std::cerr << "Filename required" << std::endl;
return 1;
}
std::string path = parse.nonOption(0);
ZAP::Archive archive;
if (!archive.openFile(path))
{
std::cerr << "Could not open archive" << std::endl;
return 1;
}
if (options[LIST])
{
print(archive);
}
else
{
std::string outPath = ".";
if (parse.nonOptionsCount() >= 2)
{
outPath = parse.nonOption(1);
}
if (!isDirectory(outPath))
{
std::cerr << "Output is not a directory" << std::endl;
return 1;
}
ZAP::Archive::EntryList list;
archive.getFileList(list);
for (const ZAP::Archive::Entry &entry : list)
{
std::string fullpath = (outPath + '/' + entry.virtual_path);
cleanPath(fullpath);
if (!createPath(fullpath))
{
std::cerr << "Could not create path " << fullpath << std::endl;
continue;
}
std::fstream stream(fullpath.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
if (!stream.is_open())
{
std::cerr << "Could not create file " << entry.virtual_path << std::endl;
continue;
}
char *data;
size_t size;
bool extractSuccess = false;
if (options[RAW])
extractSuccess = archive.getRawData(entry.virtual_path, data, size);
else
extractSuccess = archive.getData(entry.virtual_path, data, size);
if (!extractSuccess)
{
std::cerr << "Could not extract file " << entry.virtual_path << std::endl;
continue;
}
stream.write(data, size);
delete[] data;
}
}
return 0;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactmemorybackenddata_simulator_p.h"
#include <QtCore/QDataStream>
#include <QtCore/QAtomicInt>
#include <qcontact_p.h>
#include <qcontactrelationship_p.h>
#include <qcontactdetail_p.h>
#include <qcontactid_p.h>
#include <qcontactdetaildefinition_p.h>
#include <qcontactdetailfielddefinition_p.h>
Q_DECLARE_METATYPE(QtMobility::QContactData)
Q_DECLARE_METATYPE(QtMobility::QContactRelationshipPrivate)
QTM_BEGIN_NAMESPACE
#ifdef SIMULATOR_APPLICATION
// Workaround for non-exported symbol that is used by this file.
// It won't matter if this wrong lastDetailKey is used here, , since m_id is always
// set again when a QContactDetail is sent through the sockets.
QAtomicInt QContactDetailPrivate::lastDetailKey(1);
// Should work too, since they are only used for performance.
QHash<QString, char*> QContactStringHolder::s_allocated;
QHash<const char *, QString> QContactStringHolder::s_qstrings;
uint qHash(const QContactStringHolder &h)
{ return qHash(h.toQString()); }
#endif
void qt_registerContactsTypes()
{
qRegisterMetaTypeStreamOperators<QContactSimulatorData>("QtMobility::QContactSimulatorData");
qRegisterMetaTypeStreamOperators<QContactStringHolder>("QtMobility::QContactStringHolder");
qRegisterMetaTypeStreamOperators<Simulator::SaveContactReply>("QtMobility::Simulator::SaveContactReply");
qRegisterMetaTypeStreamOperators<Simulator::SaveRelationshipReply>("QtMobility::Simulator::SaveRelationshipReply");
}
QDataStream &operator<<(QDataStream &out, const QContactStringHolder &s)
{
out << s.toQString();
return out;
}
QDataStream &operator>>(QDataStream &in, QContactStringHolder &s)
{
QString data;
in >> data;
s = QContactStringHolder(data);
return in;
}
QDataStream &operator<<(QDataStream &out, const QContactSimulatorData &s)
{
out << s.m_selfContactId << s.m_contacts << s.m_contactIds;
out << s.m_relationships << s.m_orderedRelationships;
out << s.m_definitionIds << s.m_definitions;
out << s.m_nextContactId << s.m_lastDetailId;
return out;
}
QDataStream &operator>>(QDataStream &in, QContactSimulatorData &s)
{
in >> s.m_selfContactId >> s.m_contacts >> s.m_contactIds;
in >> s.m_relationships >> s.m_orderedRelationships;
in >> s.m_definitionIds >> s.m_definitions;
in >> s.m_nextContactId >> s.m_lastDetailId;
return in;
}
namespace Simulator {
QDataStream &operator<<(QDataStream &out, const SaveContactReply &s)
{
out << s.savedContact;
qint32 error = s.error;
out << error;
return out;
}
QDataStream &operator>>(QDataStream &in, SaveContactReply &s)
{
in >> s.savedContact;
qint32 error;
in >> error;
s.error = static_cast<QContactManager::Error>(error);
return in;
}
QDataStream &operator<<(QDataStream &out, const SaveRelationshipReply &s)
{
out << s.savedRelationship;
qint32 error = s.error;
out << error;
return out;
}
QDataStream &operator>>(QDataStream &in, SaveRelationshipReply &s)
{
in >> s.savedRelationship;
qint32 error;
in >> error;
s.error = static_cast<QContactManager::Error>(error);
return in;
}
} // namespace Simulator
QTM_END_NAMESPACE
<commit_msg>Register stream operators in order to use them in contact connection<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactmemorybackenddata_simulator_p.h"
#include <QtCore/QDataStream>
#include <QtCore/QAtomicInt>
#include <qcontact_p.h>
#include <qcontactrelationship_p.h>
#include <qcontactdetail_p.h>
#include <qcontactid_p.h>
#include <qcontactdetaildefinition_p.h>
#include <qcontactdetailfielddefinition_p.h>
Q_DECLARE_METATYPE(QtMobility::QContactData)
Q_DECLARE_METATYPE(QtMobility::QContactRelationshipPrivate)
QTM_BEGIN_NAMESPACE
#ifdef SIMULATOR_APPLICATION
// Workaround for non-exported symbol that is used by this file.
// It won't matter if this wrong lastDetailKey is used here, , since m_id is always
// set again when a QContactDetail is sent through the sockets.
QAtomicInt QContactDetailPrivate::lastDetailKey(1);
// Should work too, since they are only used for performance.
QHash<QString, char*> QContactStringHolder::s_allocated;
QHash<const char *, QString> QContactStringHolder::s_qstrings;
uint qHash(const QContactStringHolder &h)
{ return qHash(h.toQString()); }
#endif
void qt_registerContactsTypes()
{
qRegisterMetaTypeStreamOperators<QContact>("QtMobility::QContact");
qRegisterMetaTypeStreamOperators<QContactId>("QtMobility::QContactId");
qRegisterMetaTypeStreamOperators<QContactDetail>("QtMobility::QContactDetail");
qRegisterMetaTypeStreamOperators<QContactDetailDefinition>("QtMobility::QContactDetailDefinition");
qRegisterMetaTypeStreamOperators<QContactDetailFieldDefinition>("QtMobility::QContactDetailFieldDefinition");
qRegisterMetaTypeStreamOperators<QContactRelationship>("QtMobility::QContactRelationship");
qRegisterMetaTypeStreamOperators<QContactSimulatorData>("QtMobility::QContactSimulatorData");
qRegisterMetaTypeStreamOperators<QContactStringHolder>("QtMobility::QContactStringHolder");
qRegisterMetaTypeStreamOperators<Simulator::SaveContactReply>("QtMobility::Simulator::SaveContactReply");
qRegisterMetaTypeStreamOperators<Simulator::SaveRelationshipReply>("QtMobility::Simulator::SaveRelationshipReply");
}
QDataStream &operator<<(QDataStream &out, const QContactStringHolder &s)
{
out << s.toQString();
return out;
}
QDataStream &operator>>(QDataStream &in, QContactStringHolder &s)
{
QString data;
in >> data;
s = QContactStringHolder(data);
return in;
}
QDataStream &operator<<(QDataStream &out, const QContactSimulatorData &s)
{
out << s.m_selfContactId << s.m_contacts << s.m_contactIds;
out << s.m_relationships << s.m_orderedRelationships;
out << s.m_definitionIds << s.m_definitions;
out << s.m_nextContactId << s.m_lastDetailId;
return out;
}
QDataStream &operator>>(QDataStream &in, QContactSimulatorData &s)
{
in >> s.m_selfContactId >> s.m_contacts >> s.m_contactIds;
in >> s.m_relationships >> s.m_orderedRelationships;
in >> s.m_definitionIds >> s.m_definitions;
in >> s.m_nextContactId >> s.m_lastDetailId;
return in;
}
namespace Simulator {
QDataStream &operator<<(QDataStream &out, const SaveContactReply &s)
{
out << s.savedContact;
qint32 error = s.error;
out << error;
return out;
}
QDataStream &operator>>(QDataStream &in, SaveContactReply &s)
{
in >> s.savedContact;
qint32 error;
in >> error;
s.error = static_cast<QContactManager::Error>(error);
return in;
}
QDataStream &operator<<(QDataStream &out, const SaveRelationshipReply &s)
{
out << s.savedRelationship;
qint32 error = s.error;
out << error;
return out;
}
QDataStream &operator>>(QDataStream &in, SaveRelationshipReply &s)
{
in >> s.savedRelationship;
qint32 error;
in >> error;
s.error = static_cast<QContactManager::Error>(error);
return in;
}
} // namespace Simulator
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
bool TBeing::canDisarm(TBeing *victim, silentTypeT silent)
{
switch (race->getBodyType()) {
case BODY_PIERCER:
case BODY_MOSS:
case BODY_KUOTOA:
case BODY_MANTICORE:
case BODY_GRIFFON:
case BODY_SHEDU:
case BODY_SPHINX:
case BODY_LAMMASU:
case BODY_WYVERN:
case BODY_DRAGONNE:
case BODY_HIPPOGRIFF:
case BODY_CHIMERA:
case BODY_SNAKE:
case BODY_NAGA:
case BODY_ORB:
case BODY_VEGGIE:
case BODY_LION:
case BODY_FELINE:
case BODY_REPTILE:
case BODY_DINOSAUR:
case BODY_FOUR_LEG:
case BODY_PIG:
case BODY_FOUR_HOOF:
case BODY_ELEPHANT:
case BODY_BAANTA:
case BODY_AMPHIBEAN:
case BODY_FROG:
case BODY_MIMIC:
case BODY_WYVELIN:
case BODY_FISH:
case BODY_TREE:
case BODY_SLIME:
if (!silent)
sendTo("You have the wrong bodyform for grappling.\n\r");
return FALSE;
default:
break;
}
if (checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (getCombatMode() == ATTACK_BERSERK) {
if (!silent)
sendTo("You are berserking! You can't focus enough to disarm anyone!\n\r ");
return FALSE;
}
if (victim == this) {
if (!silent)
sendTo("Aren't we funny today...\n\r");
return FALSE;
}
if (riding) {
if (!silent)
sendTo("Yeah... right... while mounted.\n\r");
return FALSE;
}
if (victim->isFlying() && (victim->fight() != this)) {
if (!silent)
sendTo("You can only disarm fliers that are fighting you.\n\r");
return FALSE;
}
if (!victim->heldInPrimHand() && !victim->heldInSecHand()) {
if (!silent)
act("$N is not wielding anything.",FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (isHumanoid()) {
if (bothArmsHurt()) {
if (!silent)
act("You need working arms to disarm!", FALSE, this, 0, 0, TO_CHAR);
return FALSE;
}
}
if (victim->attackers > 3) {
if (!silent)
act("There is no room around $N to disarm $M.", FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (attackers > 3) {
if (!silent)
sendTo("There is no room to disarm!\n\r");
return FALSE;
}
#if 0
if (!equipment[getPrimaryHold()]) {
sendTo("Your primary hand must be FREE in order to attempt a disarm!\n\r");
return FALSE;
}
#endif
return TRUE;
}
// uses the psionic skill telekinesis to automatically retrieve a disarmed wep
// victim is the disarmee, ie the one with the telekinesis skill
bool trytelekinesis(TBeing *caster, TBeing *victim, TObj *obj){
if(!victim->doesKnowSkill(SKILL_TELEKINESIS)){
return FALSE;
}
if(!bSuccess(victim, victim->getSkillValue(SKILL_TELEKINESIS),
SKILL_TELEKINESIS)){
act("You try to retrieve $p using telekinesis, but it is too difficult.",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_NORMAL);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_CHAR, ANSI_NORMAL);
} else {
act("You catch $p in mid-air with the powers of your mind and return it to your grasp!",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_CHAR, ANSI_CYAN);
return TRUE;
}
// shouldn't get here
return FALSE;
}
static int disarm(TBeing * caster, TBeing * victim, spellNumT skill)
{
int percent;
int level, i = 0;
if (!caster->canDisarm(victim, SILENT_NO))
return FALSE;
const int disarm_move = 20;
if (caster->getMove() < disarm_move) {
caster->sendTo("You are too tired to attempt a disarm maneuver!\n\r");
return FALSE;
}
caster->addToMove(-disarm_move);
level = caster->getSkillLevel(skill);
int bKnown = caster->getSkillValue(skill);
int level2 = victim->getSkillLevel(skill);
if (caster->isNotPowerful(victim, level, skill, SILENT_YES) ||
!victim->isNotPowerful(caster, level2, skill, SILENT_YES)) {
act("You try to disarm $N, but fail miserably.",
TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n does a nifty fighting move, but then falls on $s butt.",
TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at you, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_VICT);
act("$n lunges at $N, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_NOTVICT);
}
caster->setPosition(POSITION_SITTING);
if (dynamic_cast<TMonster *>(victim) && victim->awake() && !victim->fight())
caster->reconcileDamage(victim, 0, skill);;
return TRUE;
}
percent = 0;
percent += caster->getDexReaction() * 5;
percent -= victim->getDexReaction() * 5;
// if my hands are empty, make it easy
if (!caster->heldInPrimHand() &&
// !caster->hasClass(CLASS_MONK) &&
caster->isHumanoid())
percent += 10;
// if i am an equipped monk, make it tough
if (caster->heldInPrimHand() && caster->hasClass(CLASS_MONK))
percent -= 10;
i = caster->specialAttack(victim,skill);
if (i && bKnown >= 0 && i != GUARANTEED_FAILURE &&
bSuccess(caster, bKnown + percent, skill)) {
TObj * obj = NULL;
bool isobjprim=TRUE; // is the disarmed object the primary hand object?
if (!(obj=dynamic_cast<TObj *>(victim->heldInPrimHand()))){
obj = dynamic_cast<TObj *>(victim->heldInSecHand());
isobjprim=FALSE;
}
if (obj) {
act("You attempt to disarm $N.", TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n makes an impressive fighting move.", TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at $N!",
TRUE, caster, 0, victim, TO_NOTVICT);
act("$n lunges at you!",
TRUE, caster, 0, victim, TO_VICT);
}
act("You send $p flying from $N's grasp.", FALSE, caster, obj, victim, TO_CHAR);
act("$p flies from your grasp.", FALSE, caster, obj, victim, TO_VICT, ANSI_RED);
act("$p flies from $N's grasp.", FALSE, caster, obj, victim, TO_NOTVICT);
if(!trytelekinesis(caster, victim, obj)){
if(isobjprim){
victim->unequip(victim->getPrimaryHold());
} else {
victim->unequip(victim->getSecondaryHold());
}
*victim->roomp += *obj;
victim->logItem(obj, CMD_DISARM);
}
} else {
act("You try to disarm $N, but $E doesn't have a weapon.", TRUE, caster, 0, victim, TO_CHAR);
act("$n makes an impressive fighting move, but does little more.", TRUE, caster, 0, 0, TO_ROOM);
}
caster->reconcileDamage(victim, 0, skill);;
victim->addToWait(combatRound(1));
caster->reconcileHurt(victim, 0.01);
} else {
act("You try to disarm $N, but fail miserably, falling down in the process.", TRUE, caster, 0, victim, TO_CHAR, ANSI_YELLOW);
act("$n does a nifty fighting move, but then falls on $s butt.", TRUE, caster, 0, 0, TO_ROOM);
caster->setPosition(POSITION_SITTING);
caster->reconcileDamage(victim, 0, skill);;
}
return TRUE;
}
int TBeing::doDisarm(sstring argument, TThing *v)
{
sstring v_name;
TBeing * victim = NULL;
int rc;
spellNumT skill = getSkillNum(SKILL_DISARM);
if (checkBusy(NULL)) {
return FALSE;
}
one_argument(argument, v_name);
if (!v) {
if (!(victim = get_char_room_vis(this, v_name))) {
if (!(victim = fight())) {
if (argument.empty()) {
sendTo("Syntax: disarm <person | item>\n\r");
return FALSE;
} else {
rc = disarmTrap(argument.c_str(), NULL);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
} else {
// v is either a being or an obj, unknown at this point
victim = dynamic_cast<TBeing *>(v);
if (!victim) {
TObj *to = dynamic_cast<TObj *>(v);
if (to) {
rc = disarmTrap(argument.c_str(), to);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
if (!doesKnowSkill(skill)) {
sendTo("You know nothing about how to disarm someone.\n\r");
return FALSE;
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
rc = disarm(this, victim, skill);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
if (rc)
addSkillLag(skill, rc);
return TRUE;
}
<commit_msg>fixed dupe bug with disarm not saving<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
bool TBeing::canDisarm(TBeing *victim, silentTypeT silent)
{
switch (race->getBodyType()) {
case BODY_PIERCER:
case BODY_MOSS:
case BODY_KUOTOA:
case BODY_MANTICORE:
case BODY_GRIFFON:
case BODY_SHEDU:
case BODY_SPHINX:
case BODY_LAMMASU:
case BODY_WYVERN:
case BODY_DRAGONNE:
case BODY_HIPPOGRIFF:
case BODY_CHIMERA:
case BODY_SNAKE:
case BODY_NAGA:
case BODY_ORB:
case BODY_VEGGIE:
case BODY_LION:
case BODY_FELINE:
case BODY_REPTILE:
case BODY_DINOSAUR:
case BODY_FOUR_LEG:
case BODY_PIG:
case BODY_FOUR_HOOF:
case BODY_ELEPHANT:
case BODY_BAANTA:
case BODY_AMPHIBEAN:
case BODY_FROG:
case BODY_MIMIC:
case BODY_WYVELIN:
case BODY_FISH:
case BODY_TREE:
case BODY_SLIME:
if (!silent)
sendTo("You have the wrong bodyform for grappling.\n\r");
return FALSE;
default:
break;
}
if (checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (getCombatMode() == ATTACK_BERSERK) {
if (!silent)
sendTo("You are berserking! You can't focus enough to disarm anyone!\n\r ");
return FALSE;
}
if (victim == this) {
if (!silent)
sendTo("Aren't we funny today...\n\r");
return FALSE;
}
if (riding) {
if (!silent)
sendTo("Yeah... right... while mounted.\n\r");
return FALSE;
}
if (victim->isFlying() && (victim->fight() != this)) {
if (!silent)
sendTo("You can only disarm fliers that are fighting you.\n\r");
return FALSE;
}
if (!victim->heldInPrimHand() && !victim->heldInSecHand()) {
if (!silent)
act("$N is not wielding anything.",FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (isHumanoid()) {
if (bothArmsHurt()) {
if (!silent)
act("You need working arms to disarm!", FALSE, this, 0, 0, TO_CHAR);
return FALSE;
}
}
if (victim->attackers > 3) {
if (!silent)
act("There is no room around $N to disarm $M.", FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (attackers > 3) {
if (!silent)
sendTo("There is no room to disarm!\n\r");
return FALSE;
}
#if 0
if (!equipment[getPrimaryHold()]) {
sendTo("Your primary hand must be FREE in order to attempt a disarm!\n\r");
return FALSE;
}
#endif
return TRUE;
}
// uses the psionic skill telekinesis to automatically retrieve a disarmed wep
// victim is the disarmee, ie the one with the telekinesis skill
bool trytelekinesis(TBeing *caster, TBeing *victim, TObj *obj){
if(!victim->doesKnowSkill(SKILL_TELEKINESIS)){
return FALSE;
}
if(!bSuccess(victim, victim->getSkillValue(SKILL_TELEKINESIS),
SKILL_TELEKINESIS)){
act("You try to retrieve $p using telekinesis, but it is too difficult.",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_NORMAL);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_CHAR, ANSI_NORMAL);
} else {
act("You catch $p in mid-air with the powers of your mind and return it to your grasp!",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_CHAR, ANSI_CYAN);
return TRUE;
}
// shouldn't get here
return FALSE;
}
static int disarm(TBeing * caster, TBeing * victim, spellNumT skill)
{
int percent;
int level, i = 0;
if (!caster->canDisarm(victim, SILENT_NO))
return FALSE;
const int disarm_move = 20;
if (caster->getMove() < disarm_move) {
caster->sendTo("You are too tired to attempt a disarm maneuver!\n\r");
return FALSE;
}
caster->addToMove(-disarm_move);
level = caster->getSkillLevel(skill);
int bKnown = caster->getSkillValue(skill);
int level2 = victim->getSkillLevel(skill);
if (caster->isNotPowerful(victim, level, skill, SILENT_YES) ||
!victim->isNotPowerful(caster, level2, skill, SILENT_YES)) {
act("You try to disarm $N, but fail miserably.",
TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n does a nifty fighting move, but then falls on $s butt.",
TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at you, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_VICT);
act("$n lunges at $N, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_NOTVICT);
}
caster->setPosition(POSITION_SITTING);
if (dynamic_cast<TMonster *>(victim) && victim->awake() && !victim->fight())
caster->reconcileDamage(victim, 0, skill);;
return TRUE;
}
percent = 0;
percent += caster->getDexReaction() * 5;
percent -= victim->getDexReaction() * 5;
// if my hands are empty, make it easy
if (!caster->heldInPrimHand() &&
// !caster->hasClass(CLASS_MONK) &&
caster->isHumanoid())
percent += 10;
// if i am an equipped monk, make it tough
if (caster->heldInPrimHand() && caster->hasClass(CLASS_MONK))
percent -= 10;
i = caster->specialAttack(victim,skill);
if (i && bKnown >= 0 && i != GUARANTEED_FAILURE &&
bSuccess(caster, bKnown + percent, skill)) {
TObj * obj = NULL;
bool isobjprim=TRUE; // is the disarmed object the primary hand object?
if (!(obj=dynamic_cast<TObj *>(victim->heldInPrimHand()))){
obj = dynamic_cast<TObj *>(victim->heldInSecHand());
isobjprim=FALSE;
}
if (obj) {
act("You attempt to disarm $N.", TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n makes an impressive fighting move.", TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at $N!",
TRUE, caster, 0, victim, TO_NOTVICT);
act("$n lunges at you!",
TRUE, caster, 0, victim, TO_VICT);
}
act("You send $p flying from $N's grasp.", FALSE, caster, obj, victim, TO_CHAR);
act("$p flies from your grasp.", FALSE, caster, obj, victim, TO_VICT, ANSI_RED);
act("$p flies from $N's grasp.", FALSE, caster, obj, victim, TO_NOTVICT);
if(!trytelekinesis(caster, victim, obj)){
if(isobjprim){
victim->unequip(victim->getPrimaryHold());
} else {
victim->unequip(victim->getSecondaryHold());
}
*victim->roomp += *obj;
victim->logItem(obj, CMD_DISARM);
victim->doSave(SILENT_YES);
}
} else {
act("You try to disarm $N, but $E doesn't have a weapon.", TRUE, caster, 0, victim, TO_CHAR);
act("$n makes an impressive fighting move, but does little more.", TRUE, caster, 0, 0, TO_ROOM);
}
caster->reconcileDamage(victim, 0, skill);;
victim->addToWait(combatRound(1));
caster->reconcileHurt(victim, 0.01);
} else {
act("You try to disarm $N, but fail miserably, falling down in the process.", TRUE, caster, 0, victim, TO_CHAR, ANSI_YELLOW);
act("$n does a nifty fighting move, but then falls on $s butt.", TRUE, caster, 0, 0, TO_ROOM);
caster->setPosition(POSITION_SITTING);
caster->reconcileDamage(victim, 0, skill);;
}
return TRUE;
}
int TBeing::doDisarm(sstring argument, TThing *v)
{
sstring v_name;
TBeing * victim = NULL;
int rc;
spellNumT skill = getSkillNum(SKILL_DISARM);
if (checkBusy(NULL)) {
return FALSE;
}
one_argument(argument, v_name);
if (!v) {
if (!(victim = get_char_room_vis(this, v_name))) {
if (!(victim = fight())) {
if (argument.empty()) {
sendTo("Syntax: disarm <person | item>\n\r");
return FALSE;
} else {
rc = disarmTrap(argument.c_str(), NULL);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
} else {
// v is either a being or an obj, unknown at this point
victim = dynamic_cast<TBeing *>(v);
if (!victim) {
TObj *to = dynamic_cast<TObj *>(v);
if (to) {
rc = disarmTrap(argument.c_str(), to);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
if (!doesKnowSkill(skill)) {
sendTo("You know nothing about how to disarm someone.\n\r");
return FALSE;
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
rc = disarm(this, victim, skill);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
if (rc)
addSkillLag(skill, rc);
return TRUE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: svxdlg.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-01-05 11:33:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "svxdlg.hxx"
#include "cuilib.hxx"
#include <osl/module.hxx>
#include <tools/string.hxx>
SvxAbstractDialogFactory* SvxAbstractDialogFactory::Create()
{
return (SvxAbstractDialogFactory*) VclAbstractDialogFactory::Create();
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1072); FILE MERGED 2005/09/05 14:21:58 rt 1.2.1072.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svxdlg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:08:10 $
*
* 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 "svxdlg.hxx"
#include "cuilib.hxx"
#include <osl/module.hxx>
#include <tools/string.hxx>
SvxAbstractDialogFactory* SvxAbstractDialogFactory::Create()
{
return (SvxAbstractDialogFactory*) VclAbstractDialogFactory::Create();
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_rng_init_phase2.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_rng_init_phase2.C
/// @brief Perform NX RNG Phase 2 initialization (FAPI2)
///
/// @author Chen Qian <[email protected]>
///
//
// *HWP HWP Owner: Chen Qian <[email protected]>
// *HWP FW Owner: Thi Tran <[email protected]>
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_rng_init_phase2.H>
#include <p9_misc_scom_addresses.H>
#include <p9_misc_scom_addresses_fld.H>
#include <p9_fbc_utils.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_rng_init_phase2(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_INF("Start");
fapi2::buffer<uint64_t> l_rng_cfg_data;
fapi2::buffer<uint64_t> l_rng_bar_data;
fapi2::buffer<uint64_t> l_rng_failed_int_data;
fapi2::buffer<uint64_t> l_security_switch_data;
uint16_t l_rng_cfg_self_test_hard_fail_status = 0;
uint8_t l_nx_rng_bar_enable = 0;
uint64_t l_nx_rng_bar_addr = 0;
uint64_t l_nx_rng_bar_base_addr_offset = 0;
uint8_t l_nx_rng_failed_int_enable = 0;
uint64_t l_nx_rng_failed_int_addr = 0;
uint64_t l_base_addr_nm0;
uint64_t l_base_addr_nm1;
uint64_t l_base_addr_m;
uint64_t l_base_addr_mmio;
// 5. RNG is allowed to run for M cycles (M = enough time to complete init; recommend 1 second of time).
// NOTE: accomplished by delay in execution time between phase1/phase2 HWPs
// 6. Host boot checks RNG fail bits again and if a fail is detected then RNG is declared broken
// get the self test hard fail status in RNG CFG register
FAPI_TRY(fapi2::getScom(i_target, PU_NX_RNG_CFG, l_rng_cfg_data),
"Error from getScom (NX RNG Status and Control Register)");
// exit if failure is reported in self test hard fail status field
l_rng_cfg_data.extractToRight<PU_NX_RNG_CFG_FAIL_REG, PU_NX_RNG_CFG_FAIL_REG_LEN>(l_rng_cfg_self_test_hard_fail_status);
FAPI_ASSERT(!l_rng_cfg_self_test_hard_fail_status,
fapi2::P9_RNG_INIT_SELF_TEST_FAILED_ERR().
set_TARGET(i_target).
set_SELF_TEST_HARD_FAIL_STATUS(l_rng_cfg_self_test_hard_fail_status),
"Self test hard fail status indicates failure");
// 7. Host boot maps RNG BARs (see Section 5.31 RNG BAR on page 185).
// • NX RNG BAR (not mapped/enabled if RNG is broken)
// • NCU RNG BAR (always mapped to good RNG)
// • NX RNG Fail Interrupt Addres
// self test indicates no hard fail
// if instructed to map the BAR:
// - enable NX RNG MMIO BAR and get the bar address attributes
// - optionally map NX RNG failed interrupt address
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_BAR_ENABLE, i_target, l_nx_rng_bar_enable),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_BAR_ENABLE)");
FAPI_TRY(p9_fbc_utils_get_chip_base_address(i_target,
l_base_addr_nm0,
l_base_addr_nm1,
l_base_addr_m,
l_base_addr_mmio),
"Error from p9_fbc_utils_get_chip_base_address");
// get RNG BAR addr
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_BAR_BASE_ADDR_OFFSET, i_target.getParent<fapi2::TARGET_TYPE_SYSTEM>(),
l_nx_rng_bar_base_addr_offset),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_BAR_BASE_ADDR_OFFSET)");
// caculate the NX RNG BAR ADDR based on the bar adddr offset
l_nx_rng_bar_addr = l_base_addr_mmio;
l_nx_rng_bar_addr += l_nx_rng_bar_base_addr_offset;
if (l_nx_rng_bar_enable == fapi2::ENUM_ATTR_PROC_NX_RNG_BAR_ENABLE_ENABLE)
{
// map NX RNG MMIO BAR
l_rng_bar_data.setBit<PU_NX_MMIO_BAR_ENABLE>();
l_rng_bar_data.insert<PU_NX_MMIO_BAR_BAR, PU_NX_MMIO_BAR_BAR_LEN, PU_NX_MMIO_BAR_BAR>(l_nx_rng_bar_addr);
FAPI_TRY(fapi2::putScom(i_target, PU_NX_MMIO_BAR, l_rng_bar_data),
"Error from putScom (PU_NX_MMIO_BAR)");
// map NX RNG failed interrupt address
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_FAILED_INT_ENABLE, i_target, l_nx_rng_failed_int_enable),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_RNG_FAILED_INT_ENABLE)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_FAILED_INT_ADDR, i_target, l_nx_rng_failed_int_addr),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_RNG_FAILED_INT_ADDR)");
if (l_nx_rng_failed_int_enable == fapi2::ENUM_ATTR_PROC_NX_RNG_FAILED_INT_ENABLE_ENABLE)
{
l_rng_failed_int_data.setBit<PU_RNG_FAILED_INT_ENABLE>();
l_rng_failed_int_data.insert<PU_RNG_FAILED_INT_ADDRESS, PU_RNG_FAILED_INT_ADDRESS_LEN, PU_RNG_FAILED_INT_ADDRESS>
(l_nx_rng_failed_int_addr);
FAPI_TRY(fapi2::putScom(i_target, PU_RNG_FAILED_INT, l_rng_failed_int_data),
"Error from putScom (NX RNG Failed Interrupt Address Register");
}
else
{
FAPI_DBG("Skipping setup of NX RNG Failed Interrupt Address Register");
}
// set NX RNG enable
l_rng_cfg_data.setBit<PU_NX_RNG_CFG_ENABLE>();
FAPI_TRY(fapi2::putScom(i_target, PU_NX_RNG_CFG, l_rng_cfg_data),
"Error from putScom (NX RNG Status and Control Register)");
// 8. Host boot sets the NX “sticky bit” that asserts tc_nx_block_rng_scom_wr. If tc_nx_block_rng_scom_wr =
// 1 writes to RNG SCOM register addresses 32 - 38 and 40 are blocked. An attempted write sets Power-
// Bus Interface FIR Data Register[Write to RNG SCOM reg detected when writes disabled].
// set NX sticky bit to block future RNG SCOM writes (tc_nx_block_rng_scom_wr)
FAPI_TRY(fapi2::getScom(i_target, PU_SECURITY_SWITCH_REGISTER_SCOM, l_security_switch_data),
"Error from getScom (Security Switch Register");
l_security_switch_data.setBit<PU_SECURITY_SWITCH_REGISTER_NX_RAND_NUM_GEN_LOCK>();
FAPI_TRY(fapi2::putScom(i_target, PU_SECURITY_SWITCH_REGISTER_SCOM, l_security_switch_data),
"Error from putScom (Security Switch Register");
}
else
{
FAPI_DBG("Skipping NX RNG BAR programming, RNG function is not enabled!");
}
fapi_try_exit:
FAPI_INF("End");
return fapi2::current_err;
}
<commit_msg>p9_rng_init_phase2 -- set NX RNG enable/security lock even if not mapping BARs<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_rng_init_phase2.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_rng_init_phase2.C
/// @brief Perform NX RNG Phase 2 initialization (FAPI2)
///
/// @author Chen Qian <[email protected]>
///
//
// *HWP HWP Owner: Chen Qian <[email protected]>
// *HWP FW Owner: Thi Tran <[email protected]>
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_rng_init_phase2.H>
#include <p9_misc_scom_addresses.H>
#include <p9_misc_scom_addresses_fld.H>
#include <p9_fbc_utils.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_rng_init_phase2(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_INF("Start");
fapi2::buffer<uint64_t> l_rng_cfg_data;
fapi2::buffer<uint64_t> l_rng_bar_data;
fapi2::buffer<uint64_t> l_rng_failed_int_data;
fapi2::buffer<uint64_t> l_security_switch_data;
uint16_t l_rng_cfg_self_test_hard_fail_status = 0;
uint8_t l_nx_rng_bar_enable = 0;
uint64_t l_nx_rng_bar_addr = 0;
uint64_t l_nx_rng_bar_base_addr_offset = 0;
uint8_t l_nx_rng_failed_int_enable = 0;
uint64_t l_nx_rng_failed_int_addr = 0;
uint64_t l_base_addr_nm0;
uint64_t l_base_addr_nm1;
uint64_t l_base_addr_m;
uint64_t l_base_addr_mmio;
// 5. RNG is allowed to run for M cycles (M = enough time to complete init; recommend 1 second of time).
// NOTE: accomplished by delay in execution time between phase1/phase2 HWPs
// 6. Host boot checks RNG fail bits again and if a fail is detected then RNG is declared broken
// get the self test hard fail status in RNG CFG register
FAPI_TRY(fapi2::getScom(i_target, PU_NX_RNG_CFG, l_rng_cfg_data),
"Error from getScom (NX RNG Status and Control Register)");
// exit if failure is reported in self test hard fail status field
l_rng_cfg_data.extractToRight<PU_NX_RNG_CFG_FAIL_REG, PU_NX_RNG_CFG_FAIL_REG_LEN>(l_rng_cfg_self_test_hard_fail_status);
FAPI_ASSERT(!l_rng_cfg_self_test_hard_fail_status,
fapi2::P9_RNG_INIT_SELF_TEST_FAILED_ERR().
set_TARGET(i_target).
set_SELF_TEST_HARD_FAIL_STATUS(l_rng_cfg_self_test_hard_fail_status),
"Self test hard fail status indicates failure");
// 7. Host boot maps RNG BARs (see Section 5.31 RNG BAR on page 185).
// • NX RNG BAR (not mapped/enabled if RNG is broken)
// • NCU RNG BAR (always mapped to good RNG)
// • NX RNG Fail Interrupt Addres
// self test indicates no hard fail
// if instructed to map the BAR:
// - enable NX RNG MMIO BAR and get the bar address attributes
// - optionally map NX RNG failed interrupt address
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_BAR_ENABLE, i_target, l_nx_rng_bar_enable),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_BAR_ENABLE)");
FAPI_TRY(p9_fbc_utils_get_chip_base_address(i_target,
l_base_addr_nm0,
l_base_addr_nm1,
l_base_addr_m,
l_base_addr_mmio),
"Error from p9_fbc_utils_get_chip_base_address");
// get RNG BAR addr
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_BAR_BASE_ADDR_OFFSET, i_target.getParent<fapi2::TARGET_TYPE_SYSTEM>(),
l_nx_rng_bar_base_addr_offset),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_BAR_BASE_ADDR_OFFSET)");
// caculate the NX RNG BAR ADDR based on the bar adddr offset
l_nx_rng_bar_addr = l_base_addr_mmio;
l_nx_rng_bar_addr += l_nx_rng_bar_base_addr_offset;
if (l_nx_rng_bar_enable == fapi2::ENUM_ATTR_PROC_NX_RNG_BAR_ENABLE_ENABLE)
{
// map NX RNG MMIO BAR
l_rng_bar_data.setBit<PU_NX_MMIO_BAR_ENABLE>();
l_rng_bar_data.insert<PU_NX_MMIO_BAR_BAR, PU_NX_MMIO_BAR_BAR_LEN, PU_NX_MMIO_BAR_BAR>(l_nx_rng_bar_addr);
FAPI_TRY(fapi2::putScom(i_target, PU_NX_MMIO_BAR, l_rng_bar_data),
"Error from putScom (PU_NX_MMIO_BAR)");
// map NX RNG failed interrupt address
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_FAILED_INT_ENABLE, i_target, l_nx_rng_failed_int_enable),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_RNG_FAILED_INT_ENABLE)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_NX_RNG_FAILED_INT_ADDR, i_target, l_nx_rng_failed_int_addr),
"Error from FAPI_ATTR_GET (ATTR_PROC_NX_RNG_FAILED_INT_ADDR)");
if (l_nx_rng_failed_int_enable == fapi2::ENUM_ATTR_PROC_NX_RNG_FAILED_INT_ENABLE_ENABLE)
{
l_rng_failed_int_data.setBit<PU_RNG_FAILED_INT_ENABLE>();
l_rng_failed_int_data.insert<PU_RNG_FAILED_INT_ADDRESS, PU_RNG_FAILED_INT_ADDRESS_LEN, PU_RNG_FAILED_INT_ADDRESS>
(l_nx_rng_failed_int_addr);
FAPI_TRY(fapi2::putScom(i_target, PU_RNG_FAILED_INT, l_rng_failed_int_data),
"Error from putScom (NX RNG Failed Interrupt Address Register");
}
else
{
FAPI_DBG("Skipping setup of NX RNG Failed Interrupt Address Register");
}
}
else
{
FAPI_DBG("Skipping NX RNG BAR programming!");
}
// set NX RNG enable
l_rng_cfg_data.setBit<PU_NX_RNG_CFG_ENABLE>();
FAPI_TRY(fapi2::putScom(i_target, PU_NX_RNG_CFG, l_rng_cfg_data),
"Error from putScom (NX RNG Status and Control Register)");
// 8. Host boot sets the NX “sticky bit” that asserts tc_nx_block_rng_scom_wr. If tc_nx_block_rng_scom_wr =
// 1 writes to RNG SCOM register addresses 32 - 38 and 40 are blocked. An attempted write sets Power-
// Bus Interface FIR Data Register[Write to RNG SCOM reg detected when writes disabled].
// set NX sticky bit to block future RNG SCOM writes (tc_nx_block_rng_scom_wr)
FAPI_TRY(fapi2::getScom(i_target, PU_SECURITY_SWITCH_REGISTER_SCOM, l_security_switch_data),
"Error from getScom (Security Switch Register");
l_security_switch_data.setBit<PU_SECURITY_SWITCH_REGISTER_NX_RAND_NUM_GEN_LOCK>();
FAPI_TRY(fapi2::putScom(i_target, PU_SECURITY_SWITCH_REGISTER_SCOM, l_security_switch_data),
"Error from putScom (Security Switch Register");
fapi_try_exit:
FAPI_INF("End");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/*===========================================================================*\
|
| FILE: frame_mod.cpp
| A simple modifier that gets mapping coordinates from
| the UVW Frame helper object
| 3D Studio MAX R3.0
|
| AUTH: Diego A. Castao
| Mankua
| Copyright(c) Mankua 2001
|
| HIST: Started 6-6-2001
|
\*===========================================================================*/
#include "frame_mod.h"
#include "..\..\texlay\code\texlay.h"
IObjParam* UVWFrameModifier::ip = NULL;
/*===========================================================================*\
| Class Descriptor OSM
\*===========================================================================*/
class UVWFrameModClassDesc:public ClassDesc2 {
public:
int IsPublic() { return TRUE; }
void * Create( BOOL loading ) { return new UVWFrameModifier; }
const TCHAR * ClassName() { return GetString(IDS_FRAMEMOD_CLASSNAME); }
SClass_ID SuperClassID() { return OSM_CLASS_ID; }
Class_ID ClassID() { return PUREM_CLASSID; }
const TCHAR* Category() { return _T(""); }
// Hardwired name, used by MAX Script as unique identifier
const TCHAR* InternalName() { return _T("SkeletonPureMod"); }
HINSTANCE HInstance() { return hInstance; }
};
static UVWFrameModClassDesc UVWFrameModCD;
ClassDesc* GetUVWFrameModDesc() {return &UVWFrameModCD;}
/*===========================================================================*\
| Basic implimentation of a dialog handler
\*===========================================================================*/
static HIMAGELIST hmmFAbout = NULL;
static HIMAGELIST hmmFHelp = NULL;
static void LoadImages()
{
if (!hmmFAbout)
{
HBITMAP hBitmap, hMask;
hmmFAbout = ImageList_Create(16, 16, ILC_COLOR8|ILC_MASK, 3, 0);
hBitmap = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_ABOUT));
hMask = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_ABOUT_MASK));
ImageList_Add(hmmFAbout,hBitmap,hMask);
DeleteObject(hBitmap);
DeleteObject(hMask);
}
if (!hmmFHelp)
{
HBITMAP hBitmap, hMask;
hmmFHelp = ImageList_Create(16, 16, ILC_COLOR8|ILC_MASK, 3, 0);
hBitmap = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_HELP));
hMask = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_HELP_MASK));
ImageList_Add(hmmFHelp,hBitmap,hMask);
DeleteObject(hBitmap);
DeleteObject(hMask);
}
}
//Win32 : static BOOL CALLBACK AboutDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
static INT_PTR CALLBACK AboutDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_INITDIALOG:
{
CenterWindow(hWnd,GetParent(hWnd));
}
break;
case WM_CLOSE:
EndDialog(hWnd,1);
break;
default:
return FALSE;
}
return TRUE;
}
//Win32 : BOOL SkeletonPureModDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
INT_PTR SkeletonPureModDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
int id = LOWORD(wParam);
switch (msg)
{
case WM_INITDIALOG: {
LoadImages();
// About Button
ICustButton *iTmp;
iTmp = GetICustButton(GetDlgItem(hWnd,IDC_UVWF_ABOUT));
iTmp->SetImage(hmmFAbout, 0, 0, 0, 0, 16, 16);
iTmp->SetTooltip(TRUE,_T("About UVW Frame"));
iTmp = GetICustButton(GetDlgItem(hWnd,IDC_UVWF_HELP));
iTmp->SetImage(hmmFHelp, 0, 0, 0, 0, 16, 16);
iTmp->SetTooltip(TRUE,_T("UVW Frame Help"));
ReleaseICustButton(iTmp);
break;
}
case WM_DESTROY:
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_UVWF_ABOUT:
DialogBoxParam( hInstance, MAKEINTRESOURCE(IDD_ABOUT), mod->ip->GetMAXHWnd(), AboutDlgProc, 0);
break;
case IDC_UVWF_HELP:
ShellExecute(NULL, "open", "http://www.mankua.com/uvwframe.php", NULL, NULL, SW_SHOWNORMAL);
break;
}
break;
}
return FALSE;
}
/*===========================================================================*\
| Paramblock2 Descriptor
\*===========================================================================*/
static ParamBlockDesc2 skpurem_param_blk ( frame_mod_params, _T("SkeletonPureModParams"), 0, &UVWFrameModCD, P_AUTO_CONSTRUCT + P_AUTO_UI, 0,
//rollout
IDD_UVW_FRAME_MOD, IDS_FRAMEMOD_PARAMETERS, 0, 0, NULL,
// params
uvw_type, _T("uvw_type"), TYPE_INT, 0, IDS_SIMPLE,
p_default, 0,
p_range, 0, 1,
p_ui, TYPE_RADIO, 2, IDC_UVW_TYPE, IDC_VCC_TYPE,
end,
uvw_channel, _T("uvw_channel"), TYPE_INT, 0, IDS_SIMPLE,
p_default, 1,
p_range, 1, 99,
p_ui, TYPE_SPINNER, EDITTYPE_INT, IDC_UVWCH_EDIT, IDC_UVWCH_SPIN, 1.0,
end,
frame_node, _T("uvw_frame"), TYPE_INODE, 0, IDS_SIMPLE,
p_ui, TYPE_PICKNODEBUTTON, IDC_PICK_FRAME,
p_sclassID, HELPER_CLASS_ID,
p_classID, UVWFRAME_CLASSID,
end,
end
);
/*===========================================================================*\
| Constructor
| Ask the ClassDesc2 to make the AUTO_CONSTRUCT paramblocks and wire them in
\*===========================================================================*/
UVWFrameModifier::UVWFrameModifier()
{
pblock = NULL;
UVWFrameModCD.MakeAutoParamBlocks(this);
assert(pblock);
}
/*===========================================================================*\
| Invalidate our UI (or the recently changed parameter)
\*===========================================================================*/
void UVWFrameModifier::InvalidateUI()
{
skpurem_param_blk.InvalidateUI(pblock->LastNotifyParamID());
}
/*===========================================================================*\
| Open and Close dialog UIs
| We ask the ClassDesc2 to handle Beginning and Ending EditParams for us
\*===========================================================================*/
void UVWFrameModifier::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev )
{
this->ip = ip;
UVWFrameModCD.BeginEditParams(ip, this, flags, prev);
skpurem_param_blk.SetUserDlgProc(new SkeletonPureModDlgProc(this));
}
void UVWFrameModifier::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next )
{
UVWFrameModCD.EndEditParams(ip, this, flags, next);
this->ip = NULL;
}
/*===========================================================================*\
| Standard clone
\*===========================================================================*/
RefTargetHandle UVWFrameModifier::Clone(RemapDir& remap)
{
UVWFrameModifier* newmod = new UVWFrameModifier();
newmod->ReplaceReference(0,pblock->Clone(remap));
return(newmod);
}
/*===========================================================================*\
| Subanim & References support
\*===========================================================================*/
Animatable* UVWFrameModifier::SubAnim(int i)
{
switch (i)
{
case 0: return pblock;
default: return NULL;
}
}
TSTR UVWFrameModifier::SubAnimName(int i)
{
switch (i)
{
case 0: return GetString(IDS_FRAMEMOD_PARAMETERS);
default: return _T("");
}
}
RefTargetHandle UVWFrameModifier::GetReference(int i)
{
switch (i) {
case 0: return pblock;
default: return NULL;
}
}
void UVWFrameModifier::SetReference(int i, RefTargetHandle rtarg)
{
switch (i) {
case 0: pblock = (IParamBlock2*)rtarg; break;
}
}
RefResult UVWFrameModifier::NotifyRefChanged(
Interval changeInt, RefTargetHandle hTarget,
PartID& partID, RefMessage message)
{
switch (message) {
case REFMSG_CHANGE:
skpurem_param_blk.InvalidateUI();
break;
}
return REF_SUCCEED;
}
/*===========================================================================*\
| The validity of our parameters
| Start at FOREVER, and intersect with the validity of each item
\*===========================================================================*/
Interval UVWFrameModifier::GetValidity(TimeValue t)
{
float f;
Interval valid = FOREVER;
pblock->GetValue(uvw_channel, t, f, valid);
return valid;
}
Interval UVWFrameModifier::LocalValidity(TimeValue t)
{
return GetValidity(t);
}
<commit_msg>Added support for Max 2012 to 2015<commit_after>/*===========================================================================*\
|
| FILE: frame_mod.cpp
| A simple modifier that gets mapping coordinates from
| the UVW Frame helper object
| 3D Studio MAX R3.0
|
| AUTH: Diego A. Castaño
| Mankua
| Copyright(c) Mankua 2001
|
| HIST: Started 6-6-2001
|
\*===========================================================================*/
#include "frame_mod.h"
#include "..\..\texlay\code\texlay.h"
IObjParam* UVWFrameModifier::ip = NULL;
/*===========================================================================*\
| Class Descriptor OSM
\*===========================================================================*/
class UVWFrameModClassDesc:public ClassDesc2 {
public:
int IsPublic() { return TRUE; }
void * Create( BOOL loading ) { return new UVWFrameModifier; }
const TCHAR * ClassName() { return GetString(IDS_FRAMEMOD_CLASSNAME); }
SClass_ID SuperClassID() { return OSM_CLASS_ID; }
Class_ID ClassID() { return PUREM_CLASSID; }
const TCHAR* Category() { return _T(""); }
// Hardwired name, used by MAX Script as unique identifier
const TCHAR* InternalName() { return _T("SkeletonPureMod"); }
HINSTANCE HInstance() { return hInstance; }
};
static UVWFrameModClassDesc UVWFrameModCD;
ClassDesc* GetUVWFrameModDesc() {return &UVWFrameModCD;}
/*===========================================================================*\
| Basic implimentation of a dialog handler
\*===========================================================================*/
static HIMAGELIST hmmFAbout = NULL;
static HIMAGELIST hmmFHelp = NULL;
static void LoadImages()
{
if (!hmmFAbout)
{
HBITMAP hBitmap, hMask;
hmmFAbout = ImageList_Create(16, 16, ILC_COLOR8|ILC_MASK, 3, 0);
hBitmap = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_ABOUT));
hMask = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_ABOUT_MASK));
ImageList_Add(hmmFAbout,hBitmap,hMask);
DeleteObject(hBitmap);
DeleteObject(hMask);
}
if (!hmmFHelp)
{
HBITMAP hBitmap, hMask;
hmmFHelp = ImageList_Create(16, 16, ILC_COLOR8|ILC_MASK, 3, 0);
hBitmap = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_HELP));
hMask = LoadBitmap(hInstance,MAKEINTRESOURCE(IDB_HELP_MASK));
ImageList_Add(hmmFHelp,hBitmap,hMask);
DeleteObject(hBitmap);
DeleteObject(hMask);
}
}
//Win32 : static BOOL CALLBACK AboutDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
static INT_PTR CALLBACK AboutDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_INITDIALOG:
{
CenterWindow(hWnd,GetParent(hWnd));
}
break;
case WM_CLOSE:
EndDialog(hWnd,1);
break;
default:
return FALSE;
}
return TRUE;
}
//Win32 : BOOL SkeletonPureModDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
INT_PTR SkeletonPureModDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
int id = LOWORD(wParam);
switch (msg)
{
case WM_INITDIALOG: {
LoadImages();
// About Button
ICustButton *iTmp;
iTmp = GetICustButton(GetDlgItem(hWnd,IDC_UVWF_ABOUT));
iTmp->SetImage(hmmFAbout, 0, 0, 0, 0, 16, 16);
iTmp->SetTooltip(TRUE,_T("About UVW Frame"));
iTmp = GetICustButton(GetDlgItem(hWnd,IDC_UVWF_HELP));
iTmp->SetImage(hmmFHelp, 0, 0, 0, 0, 16, 16);
iTmp->SetTooltip(TRUE,_T("UVW Frame Help"));
ReleaseICustButton(iTmp);
break;
}
case WM_DESTROY:
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_UVWF_ABOUT:
DialogBoxParam( hInstance, MAKEINTRESOURCE(IDD_ABOUT), mod->ip->GetMAXHWnd(), AboutDlgProc, 0);
break;
case IDC_UVWF_HELP:
ShellExecute(NULL, _T("open"), _T("http://www.mankua.com/uvwframe.php"), NULL, NULL, SW_SHOWNORMAL);
break;
}
break;
}
return FALSE;
}
/*===========================================================================*\
| Paramblock2 Descriptor
\*===========================================================================*/
#if MAX_VERSION_MAJOR < 15 // Max2013
#define p_end end
#endif
static ParamBlockDesc2 skpurem_param_blk ( frame_mod_params, _T("SkeletonPureModParams"), 0, &UVWFrameModCD, P_AUTO_CONSTRUCT + P_AUTO_UI, 0,
//rollout
IDD_UVW_FRAME_MOD, IDS_FRAMEMOD_PARAMETERS, 0, 0, NULL,
// params
uvw_type, _T("uvw_type"), TYPE_INT, 0, IDS_SIMPLE,
p_default, 0,
p_range, 0, 1,
p_ui, TYPE_RADIO, 2, IDC_UVW_TYPE, IDC_VCC_TYPE,
p_end,
uvw_channel, _T("uvw_channel"), TYPE_INT, 0, IDS_SIMPLE,
p_default, 1,
p_range, 1, 99,
p_ui, TYPE_SPINNER, EDITTYPE_INT, IDC_UVWCH_EDIT, IDC_UVWCH_SPIN, 1.0,
p_end,
frame_node, _T("uvw_frame"), TYPE_INODE, 0, IDS_SIMPLE,
p_ui, TYPE_PICKNODEBUTTON, IDC_PICK_FRAME,
p_sclassID, HELPER_CLASS_ID,
p_classID, UVWFRAME_CLASSID,
p_end,
p_end
);
/*===========================================================================*\
| Constructor
| Ask the ClassDesc2 to make the AUTO_CONSTRUCT paramblocks and wire them in
\*===========================================================================*/
UVWFrameModifier::UVWFrameModifier()
{
pblock = NULL;
UVWFrameModCD.MakeAutoParamBlocks(this);
assert(pblock);
}
/*===========================================================================*\
| Invalidate our UI (or the recently changed parameter)
\*===========================================================================*/
void UVWFrameModifier::InvalidateUI()
{
skpurem_param_blk.InvalidateUI(pblock->LastNotifyParamID());
}
/*===========================================================================*\
| Open and Close dialog UIs
| We ask the ClassDesc2 to handle Beginning and Ending EditParams for us
\*===========================================================================*/
void UVWFrameModifier::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev )
{
this->ip = ip;
UVWFrameModCD.BeginEditParams(ip, this, flags, prev);
skpurem_param_blk.SetUserDlgProc(new SkeletonPureModDlgProc(this));
}
void UVWFrameModifier::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next )
{
UVWFrameModCD.EndEditParams(ip, this, flags, next);
this->ip = NULL;
}
/*===========================================================================*\
| Standard clone
\*===========================================================================*/
RefTargetHandle UVWFrameModifier::Clone(RemapDir& remap)
{
UVWFrameModifier* newmod = new UVWFrameModifier();
newmod->ReplaceReference(0,pblock->Clone(remap));
return(newmod);
}
/*===========================================================================*\
| Subanim & References support
\*===========================================================================*/
Animatable* UVWFrameModifier::SubAnim(int i)
{
switch (i)
{
case 0: return pblock;
default: return NULL;
}
}
TSTR UVWFrameModifier::SubAnimName(int i)
{
switch (i)
{
case 0: return GetString(IDS_FRAMEMOD_PARAMETERS);
default: return _T("");
}
}
RefTargetHandle UVWFrameModifier::GetReference(int i)
{
switch (i) {
case 0: return pblock;
default: return NULL;
}
}
void UVWFrameModifier::SetReference(int i, RefTargetHandle rtarg)
{
switch (i) {
case 0: pblock = (IParamBlock2*)rtarg; break;
}
}
#if MAX_VERSION_MAJOR < 17 //Max 2015
RefResult UVWFrameModifier::NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget,
PartID& partID, RefMessage message )
#else
RefResult UVWFrameModifier::NotifyRefChanged(const Interval& changeInt, RefTargetHandle hTarget,
PartID& partID, RefMessage message, BOOL propagate )
#endif
{
switch (message) {
case REFMSG_CHANGE:
skpurem_param_blk.InvalidateUI();
break;
}
return REF_SUCCEED;
}
/*===========================================================================*\
| The validity of our parameters
| Start at FOREVER, and intersect with the validity of each item
\*===========================================================================*/
Interval UVWFrameModifier::GetValidity(TimeValue t)
{
float f;
Interval valid = FOREVER;
pblock->GetValue(uvw_channel, t, f, valid);
return valid;
}
Interval UVWFrameModifier::LocalValidity(TimeValue t)
{
return GetValidity(t);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grfitem.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:20:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#define ITEMID_GRF_CROP 0
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVX_GRFCROP_HXX
#include <grfcrop.hxx>
#endif
#ifndef _SVX_ITEMTYPE_HXX //autogen
#include <itemtype.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_GRAPHICCROP_HPP_
#include <com/sun/star/text/GraphicCrop.hpp>
#endif
using namespace ::com::sun::star;
#define TWIP_TO_MM100(TWIP) ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100) ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))
//TYPEINIT1_AUTOFACTORY( SvxGrfCrop, SfxPoolItem )
/******************************************************************************
* Implementierung class SwCropGrf
******************************************************************************/
SvxGrfCrop::SvxGrfCrop( USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( 0 ), nRight( 0 ), nTop( 0 ), nBottom( 0 )
{}
SvxGrfCrop::SvxGrfCrop( sal_Int32 nL, sal_Int32 nR,
sal_Int32 nT, sal_Int32 nB, USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( nL ), nRight( nR ), nTop( nT ), nBottom( nB )
{}
SvxGrfCrop::~SvxGrfCrop()
{
}
int SvxGrfCrop::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rAttr ), "not equal attributes" );
return nLeft == ((const SvxGrfCrop&)rAttr).GetLeft() &&
nRight == ((const SvxGrfCrop&)rAttr).GetRight() &&
nTop == ((const SvxGrfCrop&)rAttr).GetTop() &&
nBottom == ((const SvxGrfCrop&)rAttr).GetBottom();
}
/*
SfxPoolItem* SvxGrfCrop::Clone( SfxItemPool* ) const
{
return new SvxGrfCrop( *this );
}
*/
/*
USHORT SvxGrfCrop::GetVersion( USHORT nFFVer ) const
{
DBG_ASSERT( SOFFICE_FILEFORMAT_31==nFFVer ||
SOFFICE_FILEFORMAT_40==nFFVer ||
SOFFICE_FILEFORMAT_NOW==nFFVer,
"SvxGrfCrop: exist a new fileformat?" );
return GRFCROP_VERSION_SWDEFAULT;
}
*/
SfxPoolItem* SvxGrfCrop::Create( SvStream& rStrm, USHORT nVersion ) const
{
INT32 top, left, right, bottom;
rStrm >> top >> left >> right >> bottom;
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
SvxGrfCrop* pNew = (SvxGrfCrop*)Clone();
pNew->SetLeft( left );
pNew->SetRight( right );
pNew->SetTop( top );
pNew->SetBottom( bottom );
return pNew;
}
SvStream& SvxGrfCrop::Store( SvStream& rStrm, USHORT nVersion ) const
{
INT32 left = GetLeft(), right = GetRight(),
top = GetTop(), bottom = GetBottom();
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
rStrm << top << left << right << bottom;
return rStrm;
}
BOOL SvxGrfCrop::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aRet;
aRet.Left = nLeft;
aRet.Right = nRight;
aRet.Top = nTop;
aRet.Bottom = nBottom;
if( bConvert )
{
aRet.Right = TWIP_TO_MM100(aRet.Right );
aRet.Top = TWIP_TO_MM100(aRet.Top );
aRet.Left = TWIP_TO_MM100(aRet.Left );
aRet.Bottom = TWIP_TO_MM100(aRet.Bottom);
}
rVal <<= aRet;
return sal_True;
}
BOOL SvxGrfCrop::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aVal;
if(!(rVal >>= aVal))
return sal_False;
if( bConvert )
{
aVal.Right = MM100_TO_TWIP(aVal.Right );
aVal.Top = MM100_TO_TWIP(aVal.Top );
aVal.Left = MM100_TO_TWIP(aVal.Left );
aVal.Bottom = MM100_TO_TWIP(aVal.Bottom);
}
nLeft = aVal.Left ;
nRight = aVal.Right ;
nTop = aVal.Top ;
nBottom = aVal.Bottom;
return sal_True;
}
SfxItemPresentation SvxGrfCrop::GetPresentation(
SfxItemPresentation ePres, SfxMapUnit eCoreUnit, SfxMapUnit /*ePresUnit*/,
String &rText, const IntlWrapper* pIntl ) const
{
rText.Erase();
switch( ePres )
{
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
if( SFX_ITEM_PRESENTATION_COMPLETE == ePres )
{
( rText.AssignAscii( "L: " )) += ::GetMetricText( GetLeft(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " R: " )) += ::GetMetricText( GetRight(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " T: " )) += ::GetMetricText( GetTop(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " B: " )) += ::GetMetricText( GetBottom(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
}
break;
default:
ePres = SFX_ITEM_PRESENTATION_NONE;
break;
}
return ePres;
}
<commit_msg>INTEGRATION: CWS pchfix04 (1.9.124); FILE MERGED 2007/02/05 12:14:04 os 1.9.124.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grfitem.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2007-05-10 14:51:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVX_GRFCROP_HXX
#include <grfcrop.hxx>
#endif
#ifndef _SVX_ITEMTYPE_HXX //autogen
#include <itemtype.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_GRAPHICCROP_HPP_
#include <com/sun/star/text/GraphicCrop.hpp>
#endif
using namespace ::com::sun::star;
#define TWIP_TO_MM100(TWIP) ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100) ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))
//TYPEINIT1_FACTORY( SvxGrfCrop, SfxPoolItem , new SvxGrfCrop(0))
/******************************************************************************
* Implementierung class SwCropGrf
******************************************************************************/
SvxGrfCrop::SvxGrfCrop( USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( 0 ), nRight( 0 ), nTop( 0 ), nBottom( 0 )
{}
SvxGrfCrop::SvxGrfCrop( sal_Int32 nL, sal_Int32 nR,
sal_Int32 nT, sal_Int32 nB, USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( nL ), nRight( nR ), nTop( nT ), nBottom( nB )
{}
SvxGrfCrop::~SvxGrfCrop()
{
}
int SvxGrfCrop::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rAttr ), "not equal attributes" );
return nLeft == ((const SvxGrfCrop&)rAttr).GetLeft() &&
nRight == ((const SvxGrfCrop&)rAttr).GetRight() &&
nTop == ((const SvxGrfCrop&)rAttr).GetTop() &&
nBottom == ((const SvxGrfCrop&)rAttr).GetBottom();
}
/*
SfxPoolItem* SvxGrfCrop::Clone( SfxItemPool* ) const
{
return new SvxGrfCrop( *this );
}
*/
/*
USHORT SvxGrfCrop::GetVersion( USHORT nFFVer ) const
{
DBG_ASSERT( SOFFICE_FILEFORMAT_31==nFFVer ||
SOFFICE_FILEFORMAT_40==nFFVer ||
SOFFICE_FILEFORMAT_NOW==nFFVer,
"SvxGrfCrop: exist a new fileformat?" );
return GRFCROP_VERSION_SWDEFAULT;
}
*/
SfxPoolItem* SvxGrfCrop::Create( SvStream& rStrm, USHORT nVersion ) const
{
INT32 top, left, right, bottom;
rStrm >> top >> left >> right >> bottom;
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
SvxGrfCrop* pNew = (SvxGrfCrop*)Clone();
pNew->SetLeft( left );
pNew->SetRight( right );
pNew->SetTop( top );
pNew->SetBottom( bottom );
return pNew;
}
SvStream& SvxGrfCrop::Store( SvStream& rStrm, USHORT nVersion ) const
{
INT32 left = GetLeft(), right = GetRight(),
top = GetTop(), bottom = GetBottom();
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
rStrm << top << left << right << bottom;
return rStrm;
}
BOOL SvxGrfCrop::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aRet;
aRet.Left = nLeft;
aRet.Right = nRight;
aRet.Top = nTop;
aRet.Bottom = nBottom;
if( bConvert )
{
aRet.Right = TWIP_TO_MM100(aRet.Right );
aRet.Top = TWIP_TO_MM100(aRet.Top );
aRet.Left = TWIP_TO_MM100(aRet.Left );
aRet.Bottom = TWIP_TO_MM100(aRet.Bottom);
}
rVal <<= aRet;
return sal_True;
}
BOOL SvxGrfCrop::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aVal;
if(!(rVal >>= aVal))
return sal_False;
if( bConvert )
{
aVal.Right = MM100_TO_TWIP(aVal.Right );
aVal.Top = MM100_TO_TWIP(aVal.Top );
aVal.Left = MM100_TO_TWIP(aVal.Left );
aVal.Bottom = MM100_TO_TWIP(aVal.Bottom);
}
nLeft = aVal.Left ;
nRight = aVal.Right ;
nTop = aVal.Top ;
nBottom = aVal.Bottom;
return sal_True;
}
SfxItemPresentation SvxGrfCrop::GetPresentation(
SfxItemPresentation ePres, SfxMapUnit eCoreUnit, SfxMapUnit /*ePresUnit*/,
String &rText, const IntlWrapper* pIntl ) const
{
rText.Erase();
switch( ePres )
{
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
if( SFX_ITEM_PRESENTATION_COMPLETE == ePres )
{
( rText.AssignAscii( "L: " )) += ::GetMetricText( GetLeft(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " R: " )) += ::GetMetricText( GetRight(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " T: " )) += ::GetMetricText( GetTop(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " B: " )) += ::GetMetricText( GetBottom(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
}
break;
default:
ePres = SFX_ITEM_PRESENTATION_NONE;
break;
}
return ePres;
}
<|endoftext|> |
<commit_before><commit_msg>remove obsolete SetContent/GetContent functions<commit_after><|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
// Screen
ofSetWindowTitle("beeeeeeeer");
ofBackground(255);
// Font
mainFont.loadFont("font/Ostrich.ttf", 40);
subFont.loadFont("font/Ostrich.ttf", 25);
// Misc
verbose = false;
cellWidth = 480;
cellHeight = 360;
// Camera
camWidth = 640;
camHeight = 480;
cropWidth = camWidth/2;
cropOffset = camWidth/4;
nearBeer = 160;
farBeer = 320;
lineCounter = 0;
tmpR = 0;
tmpG = 0;
tmpB = 0;
vector<ofVideoDevice> devices = camera.listDevices();
if(verbose) {
for(int i = 0; i < devices.size(); i++){
cout << devices[i].id << ": " << devices[i].deviceName;
if( devices[i].bAvailable ){
cout << endl;
}
else {
cout << " - unavailable " << endl;
}
}
}
camera.setDeviceID(0);
camera.setDesiredFrameRate(60);
camera.setVerbose(true);
camera.initGrabber(camWidth, camHeight);
croppedCamera.allocate(cropWidth, camHeight, OF_IMAGE_COLOR_ALPHA);
// Audio
int bufferSize = 256;
left.assign(bufferSize, 0.0);
right.assign(bufferSize, 0.0);
volHistory.assign(camWidth, 0.0);
bufferCounter = 0;
drawCounter = 0;
smoothedVol = 0.0;
scaledVol = 0.0;
soundStream.setup(this, 0, 2, 44100, bufferSize, 4);
soundStream.start();
// FBOs
averageLines.allocate(camWidth, camHeight, GL_RGBA);
averageLines.begin();
ofClear(255,255,255, 0);
averageLines.end();
sortedLines.allocate(camWidth, camHeight, GL_RGBA);
sortedLines.begin();
ofClear(255,255,255, 0);
sortedLines.end();
dataSet.allocate(camWidth, camHeight, GL_RGBA);
dataSet.begin();
ofClear(255,255,255, 0);
dataSet.end();
interpretivePanel.allocate(camWidth, camHeight, GL_RGBA);
interpretivePanel.begin();
ofClear(255,255,255, 0);
interpretivePanel.end();
audioFbo.allocate(camWidth, camHeight, GL_RGBA);
audioFbo.begin();
ofClear(255,255,255, 0);
audioFbo.end();
drawAvgLines = true;
// Syphon
mainOutputSyphonServer.setName("Screen Output");
individualTextureSyphonServer.setName("Texture Output");
mClient.setup();
mClient.set("","Simple Server");
tex.allocate(camWidth, camHeight, GL_RGBA);
pixelArray.allocate(camWidth, camHeight, OF_PIXELS_RGBA);
colorPixels = new unsigned char[640*480*4];
cout << " -- END OF SETUP -- " << endl;
}
//--------------------------------------------------------------
void ofApp::update() {
// Camera
camera.update();
if (camera.isFrameNew()){
// Get Camera Pixels
cameraPixels = camera.getPixels();
// Pull Cam Pix & Crop
tmpCamera.setFromPixels(cameraPixels, camWidth, camHeight, OF_IMAGE_COLOR);
croppedCamera.setFromPixels(tmpCamera);
croppedCamera.crop(cropOffset, 0, camWidth - cropWidth, camHeight);
croppedCamera.resize(camWidth, camHeight);
// Set CameraPix from Cropped Image
cameraPixels = croppedCamera.getPixels();
int totalPixels = camWidth * camHeight;
lineCounter = 0;
bool startAdding = false;
// Get Average Colours
for (int i = 0; i < totalPixels; i++) {
// Adding Colors
tmpR += cameraPixels[i*3];
tmpG += cameraPixels[i*3+1];
tmpB += cameraPixels[i*3+2];
// Store Color
if(i % camWidth == 0) {
// get the average value
tmpR = tmpR / camWidth;
tmpG = tmpG / camWidth;
tmpB = tmpB / camWidth;
// Set Avg Colours To Color Array
lineColors[lineCounter].r = tmpR;
lineColors[lineCounter].g = tmpG;
lineColors[lineCounter].b = tmpB;
// Add Averages
tmpR += tmpR;
tmpG += tmpG;
tmpB += tmpB;
// Set Block Averages
if(lineCounter % 10 == 0) {
blockColors[lineCounter/10].r = tmpR;
blockColors[lineCounter/10].g = tmpG;
blockColors[lineCounter/10].b = tmpB;
}
// Reset Temp Colors
tmpR = 0;
tmpG = 0;
tmpB = 0;
// Iterate
lineCounter++;
}
}
// Audio
scaledVol = ofMap(smoothedVol, 0.0, 0.17, 0.0, 1.0, true);
volHistory.push_back( scaledVol );
if( volHistory.size() >= 400 ){
volHistory.erase(volHistory.begin(), volHistory.begin()+1);
}
// Draw FBOs
averageLines.begin();
ofClear(128, 128, 128, 255);
for(int i = 0; i < camHeight; i++) {
ofSetColor(lineColors[i]);
ofLine(0, i, camWidth, i);
}
averageLines.end();
sortedLines.begin();
ofClear(128, 128, 128, 255);
for(int i = 0; i < camHeight/10; i++) {
ofSetColor(blockColors[i]);
ofRect(0, -10 + i*10, camWidth, -10 + i*10);
}
sortedLines.end();
dataSet.begin();
ofClear(0, 0, 0, 5);
ofSetBackgroundColor(0);
for(int i = 0; i < camHeight; i++) {
if(i % 10 == 0) {
ofSetColor(lineColors[i].r, 0, 0);
char r = lineColors[i].r;
mainFont.drawString(ofToString(r), (i*2) + 15, lineCounter/5);
ofSetColor(0, lineColors[i].g, 0);
char g = lineColors[i].g;
mainFont.drawString(ofToString(g), (i*2) + 15, 150 + lineCounter/5);
ofSetColor(0, 0, lineColors[i].b);
char b = lineColors[i].b;
mainFont.drawString(ofToString(b), (i*2) + 15, 300 + lineCounter/5);
}
}
dataSet.end();
interpretivePanel.begin();
ofClear(0, 0, 0, 255);
ofSetBackgroundColor(0);
ofSetColor(255);
string title = "DECANTER";
mainFont.drawString(title, camWidth/2 - 85, camHeight/2 - 50);
ofSetColor(200);
string subtitle = "- a generative audio alcoholic experience -";
subFont.drawString(subtitle, camWidth/4 - 75, camHeight/2);
interpretivePanel.end();
audioFbo.begin();
ofClear(0, 0, 0, 255);
ofSetLineWidth(3);
ofSetColor(245, 58, 135);
ofBeginShape();
for (unsigned int i = 0; i < left.size(); i++){
ofVertex(i*3, 100 -left[i]*180.0f);
}
ofEndShape(false);
ofBeginShape();
for (unsigned int i = 0; i < right.size(); i++){
ofVertex(i*3, 200 -right[i]*180.0f);
}
ofEndShape(false);
ofBeginShape();
for (unsigned int i = 0; i < volHistory.size(); i++){
if( i == 0 ) ofVertex(i, camHeight);
ofVertex(i, camHeight - volHistory[i] * 150);
if( i == volHistory.size() -1 ) ofVertex(i, camHeight);
}
ofEndShape(false);
audioFbo.end();
// Texture For Syphon
if(drawAvgLines) {
averageLines.readToPixels(pixelArray);
}
else {
sortedLines.readToPixels(pixelArray);
}
colorPixels = pixelArray.getPixels();
tex.loadData(colorPixels, 640, 480, GL_RGBA);
}
}
//--------------------------------------------------------------
void ofApp::draw() {
// Raw Camera
ofSetColor(255);
camera.draw(0, 0, cellWidth, cellHeight); // 0, 0 || TL
// Average Colour Lines
ofSetColor(255);
averageLines.draw(cellWidth, 0, cellWidth, cellHeight); // 0, 0 || TC
// Sorted Colour Lines
ofSetColor(255);
sortedLines.draw(cellWidth*2, 0, cellWidth, cellHeight); // 960, 0 || TR
// Data Set
ofSetColor(255);
dataSet.draw(0, cellHeight, cellWidth, cellHeight); // 0, 360 || ML
// Interpretive Text
ofSetColor(255);
interpretivePanel.draw(cellWidth, cellHeight, cellWidth, cellHeight); // 360, 360 || MC
// Audio Waverform
audioFbo.draw(cellWidth*2, cellHeight, cellWidth, cellHeight);
// Cropped Camera
//croppedCamera.draw(0, cellHeight, cellWidth, cellHeight); // 0, 360 || ML
// Texture
//tex.draw(cellWidth, cellHeight, cellWidth, cellHeight); // 480, 360 || MC
// ofSetColor(255, 0, 0);
// ofLine(ofGetWidth()/2, 0, ofGetWidth()/2, 720);
// Syphon
mainOutputSyphonServer.publishScreen();
individualTextureSyphonServer.publishTexture(&tex);
// Debug
if(verbose) {
ofSetColor(0);
char fpsStr[255];
sprintf(fpsStr, "frame rate: %f", ofGetFrameRate());
ofDrawBitmapString(fpsStr, 50, ofGetWindowHeight() - 50);
}
}
//--------------------------------------------------------------
void ofApp::audioIn(float * input, int bufferSize, int nChannels){
float curVol = 0.0;
int numCounted = 0;
for (int i = 0; i < bufferSize; i++){
left[i] = input[i*2]*0.5;
right[i] = input[i*2+1]*0.5;
curVol += left[i] * left[i];
curVol += right[i] * right[i];
numCounted+=2;
}
curVol /= (float)numCounted;
curVol = sqrt( curVol );
smoothedVol *= 0.93;
smoothedVol += 0.07 * curVol;
bufferCounter++;
}
//--------------------------------------------------------------
void ofApp::exit() {
ofLogNotice("Exiting App");
// Close Camera
camera.close();
// Close Audio
soundStream.stop();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
// Camera Settings
if (key == 's' || key == 'S') {
camera.videoSettings();
//ofSaveFrame();
}
// FBO -> Syphon
if (key == 'f' || key == 'F') {
drawAvgLines = !drawAvgLines;
cout << "DAL = " << ofToString(drawAvgLines) << endl;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Exhibition State<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
// Screen
ofSetWindowTitle("beeeeeeeer");
ofBackground(255);
// Font
mainFont.loadFont("font/Ostrich.ttf", 40);
subFont.loadFont("font/Ostrich.ttf", 25);
// Misc
verbose = false;
cellWidth = 480;
cellHeight = 360;
// Camera
camWidth = 640;
camHeight = 480;
nearBeer = 160;
farBeer = 320;
cropWidth = camWidth/2;
cropOffset = nearBeer;
lineCounter = 0;
tmpR = 0;
tmpG = 0;
tmpB = 0;
vector<ofVideoDevice> devices = camera.listDevices();
if(verbose) {
for(int i = 0; i < devices.size(); i++){
cout << devices[i].id << ": " << devices[i].deviceName;
if( devices[i].bAvailable ){
cout << endl;
}
else {
cout << " - unavailable " << endl;
}
}
}
camera.setDeviceID(0);
camera.setDesiredFrameRate(60);
camera.setVerbose(true);
camera.initGrabber(camWidth, camHeight);
croppedCamera.allocate(cropWidth, camHeight, OF_IMAGE_COLOR_ALPHA);
// Audio
int bufferSize = 256;
left.assign(bufferSize, 0.0);
right.assign(bufferSize, 0.0);
volHistory.assign(camWidth, 0.0);
bufferCounter = 0;
drawCounter = 0;
smoothedVol = 0.0;
scaledVol = 0.0;
soundStream.setup(this, 0, 2, 44100, bufferSize, 4);
soundStream.start();
// FBOs
averageLines.allocate(camWidth, camHeight, GL_RGBA);
averageLines.begin();
ofClear(255,255,255, 0);
averageLines.end();
sortedLines.allocate(camWidth, camHeight, GL_RGBA);
sortedLines.begin();
ofClear(255,255,255, 0);
sortedLines.end();
dataSet.allocate(camWidth, camHeight, GL_RGBA);
dataSet.begin();
ofClear(255,255,255, 0);
dataSet.end();
interpretivePanel.allocate(camWidth, camHeight, GL_RGBA);
interpretivePanel.begin();
ofClear(255,255,255, 0);
interpretivePanel.end();
audioFbo.allocate(camWidth, camHeight, GL_RGBA);
audioFbo.begin();
ofClear(255,255,255, 0);
audioFbo.end();
drawAvgLines = true;
// Syphon
mainOutputSyphonServer.setName("Screen Output");
individualTextureSyphonServer.setName("Texture Output");
mClient.setup();
mClient.set("","Simple Server");
tex.allocate(camWidth, camHeight, GL_RGBA);
pixelArray.allocate(camWidth, camHeight, OF_PIXELS_RGBA);
colorPixels = new unsigned char[640*480*4];
cout << " -- END OF SETUP -- " << endl;
}
//--------------------------------------------------------------
void ofApp::update() {
// Camera
camera.update();
if (camera.isFrameNew()){
// Get Camera Pixels
cameraPixels = camera.getPixels();
// Pull Cam Pix & Crop
tmpCamera.setFromPixels(cameraPixels, camWidth, camHeight, OF_IMAGE_COLOR);
croppedCamera.setFromPixels(tmpCamera);
croppedCamera.crop(cropOffset, 0, camWidth - cropWidth, camHeight);
croppedCamera.resize(camWidth, camHeight);
// Set CameraPix from Cropped Image
cameraPixels = croppedCamera.getPixels();
int totalPixels = camWidth * camHeight;
lineCounter = 0;
bool startAdding = false;
// Get Average Colours
for (int i = 0; i < totalPixels; i++) {
// Adding Colors
tmpR += cameraPixels[i*3];
tmpG += cameraPixels[i*3+1];
tmpB += cameraPixels[i*3+2];
// Store Color
if(i % camWidth == 0) {
// get the average value
tmpR = tmpR / camWidth;
tmpG = tmpG / camWidth;
tmpB = tmpB / camWidth;
// Set Avg Colours To Color Array
lineColors[lineCounter].r = tmpR;
lineColors[lineCounter].g = tmpG;
lineColors[lineCounter].b = tmpB;
// Add Averages
tmpR += tmpR;
tmpG += tmpG;
tmpB += tmpB;
// Set Block Averages
if(lineCounter % 10 == 0) {
blockColors[lineCounter/10].r = tmpR;
blockColors[lineCounter/10].g = tmpG;
blockColors[lineCounter/10].b = tmpB;
}
// Reset Temp Colors
tmpR = 0;
tmpG = 0;
tmpB = 0;
// Iterate
lineCounter++;
}
}
// Audio
scaledVol = ofMap(smoothedVol, 0.0, 0.17, 0.0, 1.0, true);
volHistory.push_back( scaledVol );
if( volHistory.size() >= 400 ){
volHistory.erase(volHistory.begin(), volHistory.begin()+1);
}
// Draw FBOs
averageLines.begin();
ofClear(128, 128, 128, 255);
for(int i = 0; i < camHeight; i++) {
ofSetColor(lineColors[i]);
ofLine(0, i, camWidth, i);
}
averageLines.end();
sortedLines.begin();
ofClear(128, 128, 128, 255);
for(int i = 0; i < camHeight/10; i++) {
ofSetColor(blockColors[i]);
ofRect(0, -10 + i*10, camWidth, -10 + i*10);
}
sortedLines.end();
dataSet.begin();
ofClear(0, 0, 0, 5);
ofSetBackgroundColor(0);
for(int i = 0; i < camHeight; i++) {
if(i % 10 == 0) {
ofSetColor(lineColors[i].r, 0, 0);
char r = lineColors[i].r;
mainFont.drawString(ofToString(r), (i*2) + 15, lineCounter/5);
ofSetColor(0, lineColors[i].g, 0);
char g = lineColors[i].g;
mainFont.drawString(ofToString(g), (i*2) + 15, 150 + lineCounter/5);
ofSetColor(0, 0, lineColors[i].b);
char b = lineColors[i].b;
mainFont.drawString(ofToString(b), (i*2) + 15, 300 + lineCounter/5);
}
}
dataSet.end();
interpretivePanel.begin();
ofClear(0, 0, 0, 255);
ofSetBackgroundColor(0);
ofSetColor(255);
string title = "DECANTER";
mainFont.drawString(title, camWidth/2 - 85, camHeight/2 - 50);
ofSetColor(200);
string subtitle = "- a generative audio alcoholic experience -";
subFont.drawString(subtitle, camWidth/4 - 75, camHeight/2);
interpretivePanel.end();
audioFbo.begin();
ofClear(0, 0, 0, 255);
ofSetLineWidth(3);
ofSetColor(245, 58, 135);
ofBeginShape();
for (unsigned int i = 0; i < left.size(); i++){
ofVertex(i*3, 100 -left[i]*180.0f);
}
ofEndShape(false);
ofBeginShape();
for (unsigned int i = 0; i < right.size(); i++){
ofVertex(i*3, 200 -right[i]*180.0f);
}
ofEndShape(false);
ofBeginShape();
for (unsigned int i = 0; i < volHistory.size(); i++){
if( i == 0 ) ofVertex(i, camHeight);
ofVertex(i, camHeight - volHistory[i] * 150);
if( i == volHistory.size() -1 ) ofVertex(i, camHeight);
}
ofEndShape(false);
audioFbo.end();
// Texture For Syphon
if(drawAvgLines) {
averageLines.readToPixels(pixelArray);
}
else {
sortedLines.readToPixels(pixelArray);
}
colorPixels = pixelArray.getPixels();
tex.loadData(colorPixels, 640, 480, GL_RGBA);
}
}
//--------------------------------------------------------------
void ofApp::draw() {
// Raw Camera
ofSetColor(255);
camera.draw(0, 0, cellWidth, cellHeight); // 0, 0 || TL
// Average Colour Lines
ofSetColor(255);
averageLines.draw(cellWidth, 0, cellWidth, cellHeight); // 0, 0 || TC
// Sorted Colour Lines
ofSetColor(255);
sortedLines.draw(cellWidth*2, 0, cellWidth, cellHeight); // 960, 0 || TR
// Data Set
ofSetColor(255);
//dataSet.draw(0, cellHeight, cellWidth, cellHeight); // 0, 360 || ML
// Interpretive Text
ofSetColor(255);
interpretivePanel.draw(cellWidth, cellHeight, cellWidth, cellHeight); // 360, 360 || MC
// Audio Waverform
audioFbo.draw(cellWidth*2, cellHeight, cellWidth, cellHeight);
// Cropped Camera
croppedCamera.draw(0, cellHeight, cellWidth, cellHeight); // 0, 360 || ML
// Texture
//tex.draw(cellWidth, cellHeight, cellWidth, cellHeight); // 480, 360 || MC
// ofSetColor(255, 0, 0);
// ofLine(ofGetWidth()/2, 0, ofGetWidth()/2, 720);
// Syphon
mainOutputSyphonServer.publishScreen();
individualTextureSyphonServer.publishTexture(&tex);
// Debug
if(verbose) {
ofSetColor(0);
char fpsStr[255];
sprintf(fpsStr, "frame rate: %f", ofGetFrameRate());
ofDrawBitmapString(fpsStr, 50, ofGetWindowHeight() - 50);
}
}
//--------------------------------------------------------------
void ofApp::audioIn(float * input, int bufferSize, int nChannels){
float curVol = 0.0;
int numCounted = 0;
for (int i = 0; i < bufferSize; i++){
left[i] = input[i*2]*0.5;
right[i] = input[i*2+1]*0.5;
curVol += left[i] * left[i];
curVol += right[i] * right[i];
numCounted+=2;
}
curVol /= (float)numCounted;
curVol = sqrt( curVol );
smoothedVol *= 0.93;
smoothedVol += 0.07 * curVol;
bufferCounter++;
}
//--------------------------------------------------------------
void ofApp::exit() {
ofLogNotice("Exiting App");
// Close Camera
camera.close();
// Close Audio
soundStream.stop();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
// Camera Settings
if (key == 's' || key == 'S') {
camera.videoSettings();
//ofSaveFrame();
}
// FBO -> Syphon
if (key == 'f' || key == 'F') {
drawAvgLines = !drawAvgLines;
cout << "DAL = " << ofToString(drawAvgLines) << endl;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
ofSetLogLevel(OF_LOG_VERBOSE);
ofSetLogLevel("ofThread", OF_LOG_ERROR);
ofSetVerticalSync(false);
ofEnableAlphaBlending();
doDrawInfo = true;
consoleListener.setup(this);
omxCameraSettings.width = 640;
omxCameraSettings.height = 480;
omxCameraSettings.framerate = 15;
omxCameraSettings.enableTexture = true;
videoGrabber.setup(omxCameraSettings);
filterCollection.setup();
doShader = true;
shader.load("shaderExample");
//fbo.allocate(omxCameraSettings.width, omxCameraSettings.height);
fbo.allocate(omxCameraSettings.width, omxCameraSettings.height);
fbo.begin();
ofClear(0, 0, 0, 0);
fbo.end();
// selfberry
videoTexture.allocate(omxCameraSettings.width, omxCameraSettings.height, GL_RGB);
bufferDir = "buffer";
//uiBackground.init("ui.png");
timeZero = ofGetElapsedTimeMicros();
frameNumber = 0;
slotRecording = 255;
slotAmount = 4;
if (dirSRC.doesDirectoryExist(bufferDir)) {
dirSRC.removeDirectory(bufferDir, true);
}
if (!dirSRC.doesDirectoryExist("slot1")) {
dirSRC.createDirectory("slot1");
}
if (!dirSRC.doesDirectoryExist("slot2")) {
dirSRC.createDirectory("slot2");
}
if (!dirSRC.doesDirectoryExist("slot3")) {
dirSRC.createDirectory("slot3");
}
if (!dirSRC.doesDirectoryExist("slot4")) {
dirSRC.createDirectory("slot4");
}
if (!dirSRC.doesDirectoryExist("tmp")) {
dirSRC.createDirectory("tmp");
}
dirSRC.createDirectory(bufferDir);
indexSavedPhoto = 0;
isRecording = false;
amountOfFrames = 10;
maxFrames = 10;
}
//--------------------------------------------------------------
void ofApp::update()
{
if (!doShader || !videoGrabber.isFrameNew())
{
return;
}
fbo.begin();
ofClear(0, 0, 0, 0);
shader.begin();
shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID());
shader.setUniform1f("time", ofGetElapsedTimef());
shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight());
videoGrabber.draw();
shader.end();
fbo.end();
if (isRecording == true) {
dirSRC.createDirectory(bufferDir);
dirSRC.listDir(bufferDir);
recordedFramesAmount = dirSRC.size();
ofLogNotice("AMOUNT OF FILES: "+ofToString(recordedFramesAmount)+"/"+ofToString(maxFrames));
if (recordedFramesAmount == maxFrames) {
isRecording = false;
indexSavedPhoto = 0;
}
else {
if (videoGrabber.isFrameNew()) {
string filename;
if (indexSavedPhoto < 10) filename = "seq00" + ofToString(indexSavedPhoto);
if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "seq0" + ofToString(indexSavedPhoto);
if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "seq" + ofToString(indexSavedPhoto);
// FBO TODO GETTEXTURE? videoTexture = videoGrabber.getTextureReference();
fbo.readToPixels(pix);
fbo.draw(0,0, omxCameraSettings.width, omxCameraSettings.height);
//pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR);
savedImage.setFromPixels(pix);
savedImage.setImageType(OF_IMAGE_COLOR);
savedImage.saveImage("buffer//" + filename + ".tga");
//omxCameraSettings.width, omxCameraSettings.height
// add frame to gif encoder
colorGifEncoder.addFrame(
pix.getPixels(),
640,
480,
pix.getBitsPerPixel()/*,
.1f duration */
);
/*colorGifEncoder.addFrame(
pix.getPixels(),
pix.getWidth(),
pix.getHeight(),
pix.getBitsPerPixel()
);*/
pix.clear();
savedImage.clear();
indexSavedPhoto++;
if (indexSavedPhoto == (amountOfFrames + 1)) {
isRecording = false;
indexSavedPhoto = 0;
saveGif();
}
}
}
}
}
void ofApp::saveGif()
{
string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
colorGifEncoder.save("gif//" + fileName + ".gif");
}
//--------------------------------------------------------------
void ofApp::draw(){
if (doShader)
{
fbo.draw(0, 0);
}else
{
videoGrabber.draw();
}
stringstream info;
info << "APP FPS: " << ofGetFrameRate() << "\n";
info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ "<< videoGrabber.getFrameRate() <<"FPS"<< "\n";
info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n";
info << "SHADER ENABLED: " << doShader << "\n";
//info << filterCollection.filterList << "\n";
info << "\n";
info << "Press e to increment filter" << "\n";
info << "Press g to Toggle info" << "\n";
info << "Press s to Toggle Shader" << "\n";
if (doDrawInfo)
{
ofDrawBitmapStringHighlight(info.str(), 100, 100, ofColor::black, ofColor::yellow);
}
//
}
//--------------------------------------------------------------
void ofApp::keyPressed (int key)
{
ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
ofLogNotice("PRESSED KEY: " + ofToString(key));
/*RED 13 10
WHITE 127 126
YELLOW 54
GREEN 357 65
BLUE 50*/
switch (key) {
case 65:
videoGrabber.setImageFilter(filterCollection.getNextFilter());
break;
case 10:
case 13:
if (!isRecording) {
isRecording = true;
indexSavedPhoto = 0;
bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
}
break;
case 126:
doDrawInfo = !doDrawInfo;
break;
}
/*
if (key == 's')
{
doShader = !doShader;
}*/
}
void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
keyPressed((int)e.character);
}
<commit_msg>works!<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
ofSetLogLevel(OF_LOG_VERBOSE);
ofSetLogLevel("ofThread", OF_LOG_ERROR);
ofSetVerticalSync(false);
ofEnableAlphaBlending();
doDrawInfo = true;
consoleListener.setup(this);
omxCameraSettings.width = 640;
omxCameraSettings.height = 480;
omxCameraSettings.framerate = 15;
omxCameraSettings.enableTexture = true;
videoGrabber.setup(omxCameraSettings);
filterCollection.setup();
doShader = true;
shader.load("shaderExample");
//fbo.allocate(omxCameraSettings.width, omxCameraSettings.height);
fbo.allocate(omxCameraSettings.width, omxCameraSettings.height);
fbo.begin();
ofClear(0, 0, 0, 0);
fbo.end();
// selfberry
colorGifEncoder.setup(omxCameraSettings.width, omxCameraSettings.height, .2, 256);
videoTexture.allocate(omxCameraSettings.width, omxCameraSettings.height, GL_RGB);
bufferDir = "buffer";
//uiBackground.init("ui.png");
timeZero = ofGetElapsedTimeMicros();
frameNumber = 0;
slotRecording = 255;
slotAmount = 4;
if (dirSRC.doesDirectoryExist(bufferDir)) {
dirSRC.removeDirectory(bufferDir, true);
}
if (!dirSRC.doesDirectoryExist("slot1")) {
dirSRC.createDirectory("slot1");
}
if (!dirSRC.doesDirectoryExist("slot2")) {
dirSRC.createDirectory("slot2");
}
if (!dirSRC.doesDirectoryExist("slot3")) {
dirSRC.createDirectory("slot3");
}
if (!dirSRC.doesDirectoryExist("slot4")) {
dirSRC.createDirectory("slot4");
}
if (!dirSRC.doesDirectoryExist("tmp")) {
dirSRC.createDirectory("tmp");
}
dirSRC.createDirectory(bufferDir);
indexSavedPhoto = 0;
isRecording = false;
amountOfFrames = 10;
maxFrames = 10;
}
//--------------------------------------------------------------
void ofApp::update()
{
if (!doShader || !videoGrabber.isFrameNew())
{
return;
}
fbo.begin();
ofClear(0, 0, 0, 0);
shader.begin();
shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID());
shader.setUniform1f("time", ofGetElapsedTimef());
shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight());
videoGrabber.draw();
shader.end();
fbo.end();
if (isRecording == true) {
dirSRC.createDirectory(bufferDir);
dirSRC.listDir(bufferDir);
recordedFramesAmount = dirSRC.size();
ofLogNotice("AMOUNT OF FILES: "+ofToString(recordedFramesAmount)+"/"+ofToString(maxFrames));
if (recordedFramesAmount == maxFrames) {
isRecording = false;
indexSavedPhoto = 0;
}
else {
if (videoGrabber.isFrameNew()) {
string filename;
if (indexSavedPhoto < 10) filename = "seq00" + ofToString(indexSavedPhoto);
if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "seq0" + ofToString(indexSavedPhoto);
if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "seq" + ofToString(indexSavedPhoto);
// FBO TODO GETTEXTURE? videoTexture = videoGrabber.getTextureReference();
fbo.readToPixels(pix);
fbo.draw(0,0, omxCameraSettings.width, omxCameraSettings.height);
ofLogNotice("AMOUNT OF FILES: "+ofToString(recordedFramesAmount)+"/"+ofToString(maxFrames));
//pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR);
savedImage.setFromPixels(pix);
savedImage.setImageType(OF_IMAGE_COLOR);
savedImage.saveImage("buffer//" + filename + ".tga");
//omxCameraSettings.width, omxCameraSettings.height
// add frame to gif encoder
colorGifEncoder.addFrame(
pix.getPixels(),
omxCameraSettings.width,
omxCameraSettings.height,
pix.getBitsPerPixel()/*,
.1f duration */
);
/*colorGifEncoder.addFrame(
pix.getPixels(),
pix.getWidth(),
pix.getHeight(),
pix.getBitsPerPixel()
);*/
recordedFramesAmount++;
pix.clear();
savedImage.clear();
indexSavedPhoto++;
if (indexSavedPhoto == (amountOfFrames + 1)) {
isRecording = false;
indexSavedPhoto = 0;
saveGif();
}
}
}
}
}
void ofApp::saveGif()
{
string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
colorGifEncoder.save("gif//" + fileName + ".gif");
}
//--------------------------------------------------------------
void ofApp::draw(){
if (doShader)
{
fbo.draw(0, 0);
}else
{
videoGrabber.draw();
}
stringstream info;
info << "APP FPS: " << ofGetFrameRate() << "\n";
info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ "<< videoGrabber.getFrameRate() <<"FPS"<< "\n";
info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n";
info << "SHADER ENABLED: " << doShader << "\n";
//info << filterCollection.filterList << "\n";
info << "\n";
info << "Press e to increment filter" << "\n";
info << "Press g to Toggle info" << "\n";
info << "Press s to Toggle Shader" << "\n";
if (doDrawInfo)
{
ofDrawBitmapStringHighlight(info.str(), 100, 100, ofColor::black, ofColor::yellow);
}
//
}
//--------------------------------------------------------------
void ofApp::keyPressed (int key)
{
ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
ofLogNotice("PRESSED KEY: " + ofToString(key));
/*RED 13 10
WHITE 127 126
YELLOW 54
GREEN 357 65
BLUE 50*/
switch (key) {
case 65:
videoGrabber.setImageFilter(filterCollection.getNextFilter());
break;
case 10:
case 13:
if (!isRecording) {
isRecording = true;
indexSavedPhoto = 0;
bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds());
}
break;
case 126:
doDrawInfo = !doDrawInfo;
break;
}
/*
if (key == 's')
{
doShader = !doShader;
}*/
}
void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
keyPressed((int)e.character);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: filenotation.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-03-19 12:26:08 $
*
* 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 EXPRESS 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 SVTOOLS_FILENOTATION_HXX
#define SVTOOLS_FILENOTATION_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
//.........................................................................
namespace svt
{
//.........................................................................
//=====================================================================
//= OFileNotation
//=====================================================================
class OFileNotation
{
protected:
::rtl::OUString m_sSystem;
::rtl::OUString m_sFileURL;
public:
enum NOTATION
{
N_SYSTEM,
N_URL
};
OFileNotation( const ::rtl::OUString& _rUrlOrPath );
OFileNotation( const ::rtl::OUString& _rUrlOrPath, NOTATION _eInputNotation );
::rtl::OUString get(NOTATION _eOutputNotation);
private:
void construct( const ::rtl::OUString& _rUrlOrPath );
bool implInitWithSystemNotation( const ::rtl::OUString& _rSystemPath );
bool implInitWithURLNotation( const ::rtl::OUString& _rURL );
};
//.........................................................................
} // namespace svt
//.........................................................................
#endif // SVTOOLS_FILENOTATION_HXX
<commit_msg>INTEGRATION: CWS visibility03 (1.2.406); FILE MERGED 2005/03/24 14:13:39 mhu 1.2.406.1: #i45006# Include svtools/(svl|svt)dllapi.h, declare symbol visibility with (SVL|SVT)_DLL(PUBLIC|PRIVATE) as appropriate; partial cleanup.<commit_after>/*************************************************************************
*
* $RCSfile: filenotation.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2005-04-13 10:07:51 $
*
* 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 EXPRESS 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 SVTOOLS_FILENOTATION_HXX
#define SVTOOLS_FILENOTATION_HXX
#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
//.........................................................................
namespace svt
{
//.........................................................................
//=====================================================================
//= OFileNotation
//=====================================================================
class SVL_DLLPUBLIC OFileNotation
{
protected:
::rtl::OUString m_sSystem;
::rtl::OUString m_sFileURL;
public:
enum NOTATION
{
N_SYSTEM,
N_URL
};
OFileNotation( const ::rtl::OUString& _rUrlOrPath );
OFileNotation( const ::rtl::OUString& _rUrlOrPath, NOTATION _eInputNotation );
::rtl::OUString get(NOTATION _eOutputNotation);
private:
SVL_DLLPRIVATE void construct( const ::rtl::OUString& _rUrlOrPath );
SVL_DLLPRIVATE bool implInitWithSystemNotation( const ::rtl::OUString& _rSystemPath );
SVL_DLLPRIVATE bool implInitWithURLNotation( const ::rtl::OUString& _rURL );
};
//.........................................................................
} // namespace svt
//.........................................................................
#endif // SVTOOLS_FILENOTATION_HXX
<|endoftext|> |
<commit_before>/*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <[email protected]>
* Simon Loesing <[email protected]>
* Thomas Etter <[email protected]>
* Kevin Bocksrocker <[email protected]>
* Lucas Braun <[email protected]>
*/
#include <crossbow/program_options.hpp>
#include <crossbow/logger.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>
#include "Client.hpp"
using namespace crossbow::program_options;
using namespace boost::asio;
using err_code = boost::system::error_code;
std::vector<std::string> split(const std::string str, const char delim) {
std::stringstream ss(str);
std::string item;
std::vector<std::string> result;
while (std::getline(ss, item, delim)) {
if (item.empty()) continue;
result.push_back(std::move(item));
}
return result;
}
int main(int argc, const char** argv) {
bool help = false;
bool populate = false;
int16_t numWarehouses = 1;
std::string host;
std::string port("8713");
std::string logLevel("DEBUG");
std::string outFile("out.csv");
size_t numClients = 1;
unsigned time = 5*60;
auto opts = create_options("tpcc_server",
value<'h'>("help", &help, tag::description{"print help"})
, value<'H'>("host", &host, tag::description{"Comma-separated list of hosts"})
, value<'l'>("log-level", &logLevel, tag::description{"The log level"})
, value<'c'>("num-clients", &numClients, tag::description{"Number of Clients to run per host"})
, value<'P'>("populate", &populate, tag::description{"Populate the database"})
, value<'W'>("num-warehouses", &numWarehouses, tag::description{"Number of warehouses"})
, value<'t'>("time", &time, tag::description{"Duration of the benchmark in seconds"})
, value<'o'>("out", &outFile, tag::description{"Path to the output file"})
);
try {
parse(opts, argc, argv);
} catch (argument_not_found& e) {
std::cerr << e.what() << std::endl << std::endl;
print_help(std::cout, opts);
return 1;
}
if (help) {
print_help(std::cout, opts);
return 0;
}
if (host.empty()) {
std::cerr << "No host\n";
return 1;
}
auto startTime = tpcc::Clock::now();
auto endTime = startTime + std::chrono::seconds(time);
crossbow::logger::logger->config.level = crossbow::logger::logLevelFromString(logLevel);
try {
auto hosts = split(host, ',');
io_service service;
auto sumClients = hosts.size() * numClients;
std::vector<tpcc::Client> clients;
clients.reserve(sumClients);
auto wareHousesPerClient = numWarehouses / sumClients;
for (decltype(sumClients) i = 0; i < sumClients; ++i) {
if (i >= unsigned(numWarehouses)) break;
clients.emplace_back(service, numWarehouses, int16_t(wareHousesPerClient * i + 1), int16_t(wareHousesPerClient * (i + 1)), endTime);
}
for (size_t i = 0; i < hosts.size(); ++i) {
auto h = hosts[i];
auto addr = split(h, ':');
assert(addr.size() <= 2);
auto p = addr.size() == 2 ? addr[1] : port;
ip::tcp::resolver resolver(service);
ip::tcp::resolver::iterator iter;
if (host == "") {
iter = resolver.resolve(ip::tcp::resolver::query(port));
} else {
iter = resolver.resolve(ip::tcp::resolver::query(host, port));
}
for (unsigned j = 0; j < numClients; ++j) {
LOG_INFO("Connected to client " + crossbow::to_string(i*numClients + j));
boost::asio::connect(clients[i*numClients + j].socket(), iter);
}
}
if (populate) {
auto& cmds = clients[0].commands();
cmds.execute<tpcc::Command::CREATE_SCHEMA>(
[&clients, numClients, wareHousesPerClient, numWarehouses](const err_code& ec,
const std::tuple<bool, crossbow::string>& res){
if (ec) {
LOG_ERROR(ec.message());
return;
}
if (!std::get<0>(res)) {
LOG_ERROR(std::get<1>(res));
return;
}
for (auto& client : clients) {
client.populate();
}
});
} else {
for (decltype(clients.size()) i = 0; i < clients.size(); ++i) {
auto& client = clients[i];
client.run();
}
}
service.run();
LOG_INFO("Done, writing results");
std::ofstream out(outFile.c_str());
out << "start,end,transaction,success,error\n";
for (const auto& client : clients) {
const auto& queue = client.log();
for (const auto& e : queue) {
crossbow::string tName;
switch (e.transaction) {
case tpcc::Command::POPULATE_WAREHOUSE:
tName = "Populate";
break;
case tpcc::Command::POPULATE_ITEMS:
tName = "Populate";
break;
case tpcc::Command::CREATE_SCHEMA:
tName = "Schema Create";
break;
case tpcc::Command::STOCK_LEVEL:
tName = "Stock Level";
break;
case tpcc::Command::DELIVERY:
tName = "Delivery";
break;
case tpcc::Command::NEW_ORDER:
tName = "New Order";
break;
case tpcc::Command::ORDER_STATUS:
tName = "Order Status";
break;
case tpcc::Command::PAYMENT:
tName = "Payment";
break;
}
out << std::chrono::duration_cast<std::chrono::seconds>(e.start - startTime).count()
<< std::chrono::duration_cast<std::chrono::seconds>(e.end - startTime).count()
<< tName
<< (e.success ? "true" : "false")
<< e.error
<< std::endl;
}
}
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
<commit_msg>Fix printing of out file<commit_after>/*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <[email protected]>
* Simon Loesing <[email protected]>
* Thomas Etter <[email protected]>
* Kevin Bocksrocker <[email protected]>
* Lucas Braun <[email protected]>
*/
#include <crossbow/program_options.hpp>
#include <crossbow/logger.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>
#include "Client.hpp"
using namespace crossbow::program_options;
using namespace boost::asio;
using err_code = boost::system::error_code;
std::vector<std::string> split(const std::string str, const char delim) {
std::stringstream ss(str);
std::string item;
std::vector<std::string> result;
while (std::getline(ss, item, delim)) {
if (item.empty()) continue;
result.push_back(std::move(item));
}
return result;
}
int main(int argc, const char** argv) {
bool help = false;
bool populate = false;
int16_t numWarehouses = 1;
std::string host;
std::string port("8713");
std::string logLevel("DEBUG");
std::string outFile("out.csv");
size_t numClients = 1;
unsigned time = 5*60;
auto opts = create_options("tpcc_server",
value<'h'>("help", &help, tag::description{"print help"})
, value<'H'>("host", &host, tag::description{"Comma-separated list of hosts"})
, value<'l'>("log-level", &logLevel, tag::description{"The log level"})
, value<'c'>("num-clients", &numClients, tag::description{"Number of Clients to run per host"})
, value<'P'>("populate", &populate, tag::description{"Populate the database"})
, value<'W'>("num-warehouses", &numWarehouses, tag::description{"Number of warehouses"})
, value<'t'>("time", &time, tag::description{"Duration of the benchmark in seconds"})
, value<'o'>("out", &outFile, tag::description{"Path to the output file"})
);
try {
parse(opts, argc, argv);
} catch (argument_not_found& e) {
std::cerr << e.what() << std::endl << std::endl;
print_help(std::cout, opts);
return 1;
}
if (help) {
print_help(std::cout, opts);
return 0;
}
if (host.empty()) {
std::cerr << "No host\n";
return 1;
}
auto startTime = tpcc::Clock::now();
auto endTime = startTime + std::chrono::seconds(time);
crossbow::logger::logger->config.level = crossbow::logger::logLevelFromString(logLevel);
try {
auto hosts = split(host, ',');
io_service service;
auto sumClients = hosts.size() * numClients;
std::vector<tpcc::Client> clients;
clients.reserve(sumClients);
auto wareHousesPerClient = numWarehouses / sumClients;
for (decltype(sumClients) i = 0; i < sumClients; ++i) {
if (i >= unsigned(numWarehouses)) break;
clients.emplace_back(service, numWarehouses, int16_t(wareHousesPerClient * i + 1), int16_t(wareHousesPerClient * (i + 1)), endTime);
}
for (size_t i = 0; i < hosts.size(); ++i) {
auto h = hosts[i];
auto addr = split(h, ':');
assert(addr.size() <= 2);
auto p = addr.size() == 2 ? addr[1] : port;
ip::tcp::resolver resolver(service);
ip::tcp::resolver::iterator iter;
if (host == "") {
iter = resolver.resolve(ip::tcp::resolver::query(port));
} else {
iter = resolver.resolve(ip::tcp::resolver::query(host, port));
}
for (unsigned j = 0; j < numClients; ++j) {
LOG_INFO("Connected to client " + crossbow::to_string(i*numClients + j));
boost::asio::connect(clients[i*numClients + j].socket(), iter);
}
}
if (populate) {
auto& cmds = clients[0].commands();
cmds.execute<tpcc::Command::CREATE_SCHEMA>(
[&clients, numClients, wareHousesPerClient, numWarehouses](const err_code& ec,
const std::tuple<bool, crossbow::string>& res){
if (ec) {
LOG_ERROR(ec.message());
return;
}
if (!std::get<0>(res)) {
LOG_ERROR(std::get<1>(res));
return;
}
for (auto& client : clients) {
client.populate();
}
});
} else {
for (decltype(clients.size()) i = 0; i < clients.size(); ++i) {
auto& client = clients[i];
client.run();
}
}
service.run();
LOG_INFO("Done, writing results");
std::ofstream out(outFile.c_str());
out << "start,end,transaction,success,error\n";
for (const auto& client : clients) {
const auto& queue = client.log();
for (const auto& e : queue) {
crossbow::string tName;
switch (e.transaction) {
case tpcc::Command::POPULATE_WAREHOUSE:
tName = "Populate";
break;
case tpcc::Command::POPULATE_ITEMS:
tName = "Populate";
break;
case tpcc::Command::CREATE_SCHEMA:
tName = "Schema Create";
break;
case tpcc::Command::STOCK_LEVEL:
tName = "Stock Level";
break;
case tpcc::Command::DELIVERY:
tName = "Delivery";
break;
case tpcc::Command::NEW_ORDER:
tName = "New Order";
break;
case tpcc::Command::ORDER_STATUS:
tName = "Order Status";
break;
case tpcc::Command::PAYMENT:
tName = "Payment";
break;
}
out << std::chrono::duration_cast<std::chrono::seconds>(e.start - startTime).count() << ','
<< std::chrono::duration_cast<std::chrono::seconds>(e.end - startTime).count() << ','
<< tName << ','
<< (e.success ? "true" : "false") << ','
<< e.error << std::endl;
}
}
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/message_box.h"
#include <windows.h>
#include <commctrl.h>
#include <map>
#include <vector>
#include "atom/browser/browser.h"
#include "atom/browser/native_window_views.h"
#include "base/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "base/win/scoped_gdi_object.h"
#include "content/public/browser/browser_thread.h"
#include "ui/gfx/icon_util.h"
namespace atom {
namespace {
// Small command ID values are already taken by Windows, we have to start from
// a large number to avoid conflicts with Windows.
const int kIDStart = 100;
// Get the common ID from button's name.
struct CommonButtonID {
int button;
int id;
};
CommonButtonID GetCommonID(const base::string16& button) {
base::string16 lower = base::StringToLowerASCII(button);
if (lower == L"ok")
return { TDCBF_OK_BUTTON, IDOK };
else if (lower == L"yes")
return { TDCBF_YES_BUTTON, IDYES };
else if (lower == L"no")
return { TDCBF_NO_BUTTON, IDNO };
else if (lower == L"cancel")
return { TDCBF_CANCEL_BUTTON, IDCANCEL };
else if (lower == L"retry")
return { TDCBF_RETRY_BUTTON, IDRETRY };
else if (lower == L"close")
return { TDCBF_CLOSE_BUTTON, IDCLOSE };
return { -1, -1 };
}
// Determine whether the buttons are common buttons, if so map common ID
// to button ID.
void MapToCommonID(const std::vector<base::string16>& buttons,
std::map<int, int>* id_map,
TASKDIALOG_COMMON_BUTTON_FLAGS* button_flags,
std::vector<TASKDIALOG_BUTTON>* dialog_buttons) {
for (size_t i = 0; i < buttons.size(); ++i) {
auto common = GetCommonID(buttons[i]);
if (common.button != -1) {
// It is a common button.
(*id_map)[common.id] = i;
(*button_flags) |= common.button;
} else {
// It is a custom button.
dialog_buttons->push_back({i + kIDStart, buttons[i].c_str()});
}
}
}
int ShowMessageBoxUTF16(HWND parent,
MessageBoxType type,
const std::vector<base::string16>& buttons,
int cancel_id,
int options,
const base::string16& title,
const base::string16& message,
const base::string16& detail,
const gfx::ImageSkia& icon) {
TASKDIALOG_FLAGS flags =
TDF_SIZE_TO_CONTENT | // Show all content.
TDF_ALLOW_DIALOG_CANCELLATION; // Allow canceling the dialog.
TASKDIALOGCONFIG config = { 0 };
config.cbSize = sizeof(config);
config.hwndParent = parent;
config.hInstance = GetModuleHandle(NULL);
config.dwFlags = flags;
// TaskDialogIndirect doesn't allow empty name, if we set empty title it
// will show "electron.exe" in title.
base::string16 app_name = base::UTF8ToUTF16(Browser::Get()->GetName());
if (title.empty())
config.pszWindowTitle = app_name.c_str();
else
config.pszWindowTitle = title.c_str();
base::win::ScopedHICON hicon;
if (!icon.isNull()) {
hicon.Set(IconUtil::CreateHICONFromSkBitmap(*icon.bitmap()));
config.dwFlags |= TDF_USE_HICON_MAIN;
config.hMainIcon = hicon.Get();
} else {
// Show icon according to dialog's type.
switch (type) {
case MESSAGE_BOX_TYPE_INFORMATION:
case MESSAGE_BOX_TYPE_QUESTION:
config.pszMainIcon = TD_INFORMATION_ICON;
break;
case MESSAGE_BOX_TYPE_WARNING:
config.pszMainIcon = TD_WARNING_ICON;
break;
case MESSAGE_BOX_TYPE_ERROR:
config.pszMainIcon = TD_ERROR_ICON;
break;
}
}
// If "detail" is empty then don't make message hilighted.
if (detail.empty()) {
config.pszContent = message.c_str();
} else {
config.pszMainInstruction = message.c_str();
config.pszContent = detail.c_str();
}
// Iterate through the buttons, put common buttons in dwCommonButtons
// and custom buttons in pButtons.
std::map<int, int> id_map;
std::vector<TASKDIALOG_BUTTON> dialog_buttons;
if (options & MESSAGE_BOX_NO_LINK) {
for (size_t i = 0; i < buttons.size(); ++i)
dialog_buttons.push_back({i + kIDStart, buttons[i].c_str()});
} else {
MapToCommonID(buttons, &id_map, &config.dwCommonButtons, &dialog_buttons);
}
if (dialog_buttons.size() > 0) {
config.pButtons = &dialog_buttons.front();
config.cButtons = dialog_buttons.size();
if (!(options & MESSAGE_BOX_NO_LINK))
config.dwFlags |= TDF_USE_COMMAND_LINKS; // custom buttons as links.
}
int id = 0;
TaskDialogIndirect(&config, &id, NULL, NULL);
if (id_map.find(id) != id_map.end()) // common button.
return id_map[id];
else if (id >= kIDStart) // custom button.
return id - kIDStart;
else
return cancel_id;
}
void RunMessageBoxInNewThread(base::Thread* thread,
NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon,
const MessageBoxCallback& callback) {
int result = ShowMessageBox(parent, type, buttons, cancel_id, options, title,
message, detail, icon);
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE, base::Bind(callback, result));
content::BrowserThread::DeleteSoon(
content::BrowserThread::UI, FROM_HERE, thread);
}
} // namespace
int ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon) {
std::vector<base::string16> utf16_buttons;
for (const auto& button : buttons)
utf16_buttons.push_back(base::UTF8ToUTF16(button));
HWND hwnd_parent = parent ?
static_cast<atom::NativeWindowViews*>(parent)->GetAcceleratedWidget() :
NULL;
NativeWindow::DialogScope dialog_scope(parent);
return ShowMessageBoxUTF16(hwnd_parent,
type,
utf16_buttons,
cancel_id,
options,
base::UTF8ToUTF16(title),
base::UTF8ToUTF16(message),
base::UTF8ToUTF16(detail),
icon);
}
void ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon,
const MessageBoxCallback& callback) {
scoped_ptr<base::Thread> thread(
new base::Thread(ATOM_PRODUCT_NAME "MessageBoxThread"));
thread->init_com_with_mta(false);
if (!thread->Start()) {
callback.Run(cancel_id);
return;
}
base::Thread* unretained = thread.release();
unretained->message_loop()->PostTask(
FROM_HERE,
base::Bind(&RunMessageBoxInNewThread, base::Unretained(unretained),
parent, type, buttons, cancel_id, options, title, message,
detail, icon, callback));
}
void ShowErrorBox(const base::string16& title, const base::string16& content) {
ShowMessageBoxUTF16(NULL, MESSAGE_BOX_TYPE_ERROR, {}, 0, 0, L"Error", title,
content, gfx::ImageSkia());
}
} // namespace atom
<commit_msg>Fixed comment spacing<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/message_box.h"
#include <windows.h>
#include <commctrl.h>
#include <map>
#include <vector>
#include "atom/browser/browser.h"
#include "atom/browser/native_window_views.h"
#include "base/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "base/win/scoped_gdi_object.h"
#include "content/public/browser/browser_thread.h"
#include "ui/gfx/icon_util.h"
namespace atom {
namespace {
// Small command ID values are already taken by Windows, we have to start from
// a large number to avoid conflicts with Windows.
const int kIDStart = 100;
// Get the common ID from button's name.
struct CommonButtonID {
int button;
int id;
};
CommonButtonID GetCommonID(const base::string16& button) {
base::string16 lower = base::StringToLowerASCII(button);
if (lower == L"ok")
return { TDCBF_OK_BUTTON, IDOK };
else if (lower == L"yes")
return { TDCBF_YES_BUTTON, IDYES };
else if (lower == L"no")
return { TDCBF_NO_BUTTON, IDNO };
else if (lower == L"cancel")
return { TDCBF_CANCEL_BUTTON, IDCANCEL };
else if (lower == L"retry")
return { TDCBF_RETRY_BUTTON, IDRETRY };
else if (lower == L"close")
return { TDCBF_CLOSE_BUTTON, IDCLOSE };
return { -1, -1 };
}
// Determine whether the buttons are common buttons, if so map common ID
// to button ID.
void MapToCommonID(const std::vector<base::string16>& buttons,
std::map<int, int>* id_map,
TASKDIALOG_COMMON_BUTTON_FLAGS* button_flags,
std::vector<TASKDIALOG_BUTTON>* dialog_buttons) {
for (size_t i = 0; i < buttons.size(); ++i) {
auto common = GetCommonID(buttons[i]);
if (common.button != -1) {
// It is a common button.
(*id_map)[common.id] = i;
(*button_flags) |= common.button;
} else {
// It is a custom button.
dialog_buttons->push_back({i + kIDStart, buttons[i].c_str()});
}
}
}
int ShowMessageBoxUTF16(HWND parent,
MessageBoxType type,
const std::vector<base::string16>& buttons,
int cancel_id,
int options,
const base::string16& title,
const base::string16& message,
const base::string16& detail,
const gfx::ImageSkia& icon) {
TASKDIALOG_FLAGS flags =
TDF_SIZE_TO_CONTENT | // Show all content.
TDF_ALLOW_DIALOG_CANCELLATION; // Allow canceling the dialog.
TASKDIALOGCONFIG config = { 0 };
config.cbSize = sizeof(config);
config.hwndParent = parent;
config.hInstance = GetModuleHandle(NULL);
config.dwFlags = flags;
// TaskDialogIndirect doesn't allow empty name, if we set empty title it
// will show "electron.exe" in title.
base::string16 app_name = base::UTF8ToUTF16(Browser::Get()->GetName());
if (title.empty())
config.pszWindowTitle = app_name.c_str();
else
config.pszWindowTitle = title.c_str();
base::win::ScopedHICON hicon;
if (!icon.isNull()) {
hicon.Set(IconUtil::CreateHICONFromSkBitmap(*icon.bitmap()));
config.dwFlags |= TDF_USE_HICON_MAIN;
config.hMainIcon = hicon.Get();
} else {
// Show icon according to dialog's type.
switch (type) {
case MESSAGE_BOX_TYPE_INFORMATION:
case MESSAGE_BOX_TYPE_QUESTION:
config.pszMainIcon = TD_INFORMATION_ICON;
break;
case MESSAGE_BOX_TYPE_WARNING:
config.pszMainIcon = TD_WARNING_ICON;
break;
case MESSAGE_BOX_TYPE_ERROR:
config.pszMainIcon = TD_ERROR_ICON;
break;
}
}
// If "detail" is empty then don't make message hilighted.
if (detail.empty()) {
config.pszContent = message.c_str();
} else {
config.pszMainInstruction = message.c_str();
config.pszContent = detail.c_str();
}
// Iterate through the buttons, put common buttons in dwCommonButtons
// and custom buttons in pButtons.
std::map<int, int> id_map;
std::vector<TASKDIALOG_BUTTON> dialog_buttons;
if (options & MESSAGE_BOX_NO_LINK) {
for (size_t i = 0; i < buttons.size(); ++i)
dialog_buttons.push_back({i + kIDStart, buttons[i].c_str()});
} else {
MapToCommonID(buttons, &id_map, &config.dwCommonButtons, &dialog_buttons);
}
if (dialog_buttons.size() > 0) {
config.pButtons = &dialog_buttons.front();
config.cButtons = dialog_buttons.size();
if (!(options & MESSAGE_BOX_NO_LINK))
config.dwFlags |= TDF_USE_COMMAND_LINKS; // custom buttons as links.
}
int id = 0;
TaskDialogIndirect(&config, &id, NULL, NULL);
if (id_map.find(id) != id_map.end()) // common button.
return id_map[id];
else if (id >= kIDStart) // custom button.
return id - kIDStart;
else
return cancel_id;
}
void RunMessageBoxInNewThread(base::Thread* thread,
NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon,
const MessageBoxCallback& callback) {
int result = ShowMessageBox(parent, type, buttons, cancel_id, options, title,
message, detail, icon);
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE, base::Bind(callback, result));
content::BrowserThread::DeleteSoon(
content::BrowserThread::UI, FROM_HERE, thread);
}
} // namespace
int ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon) {
std::vector<base::string16> utf16_buttons;
for (const auto& button : buttons)
utf16_buttons.push_back(base::UTF8ToUTF16(button));
HWND hwnd_parent = parent ?
static_cast<atom::NativeWindowViews*>(parent)->GetAcceleratedWidget() :
NULL;
NativeWindow::DialogScope dialog_scope(parent);
return ShowMessageBoxUTF16(hwnd_parent,
type,
utf16_buttons,
cancel_id,
options,
base::UTF8ToUTF16(title),
base::UTF8ToUTF16(message),
base::UTF8ToUTF16(detail),
icon);
}
void ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
int cancel_id,
int options,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon,
const MessageBoxCallback& callback) {
scoped_ptr<base::Thread> thread(
new base::Thread(ATOM_PRODUCT_NAME "MessageBoxThread"));
thread->init_com_with_mta(false);
if (!thread->Start()) {
callback.Run(cancel_id);
return;
}
base::Thread* unretained = thread.release();
unretained->message_loop()->PostTask(
FROM_HERE,
base::Bind(&RunMessageBoxInNewThread, base::Unretained(unretained),
parent, type, buttons, cancel_id, options, title, message,
detail, icon, callback));
}
void ShowErrorBox(const base::string16& title, const base::string16& content) {
ShowMessageBoxUTF16(NULL, MESSAGE_BOX_TYPE_ERROR, {}, 0, 0, L"Error", title,
content, gfx::ImageSkia());
}
} // namespace atom
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/win/notify_icon.h"
#include <shobjidl.h>
#include "atom/browser/ui/win/notify_icon_host.h"
#include "base/md5.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
NotifyIcon::NotifyIcon(NotifyIconHost* host,
UINT id,
HWND window,
UINT message)
: host_(host),
icon_id_(id),
window_(window),
message_id_(message),
menu_model_(NULL),
has_tray_app_id_hash_(false) {
// NB: If we have an App Model ID, we should propagate that to the tray.
// Doing this prevents duplicate items from showing up in the notification
// preferences (i.e. "Always Show / Show notifications only / etc")
PWSTR explicit_app_id;
if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&explicit_app_id))) {
// GUIDs and MD5 hashes are the same length. So convenient!
base::MD5Sum(explicit_app_id,
sizeof(wchar_t) * wcslen(explicit_app_id),
reinterpret_cast<base::MD5Digest*>(&tray_app_id_hash_));
has_tray_app_id_hash_ = true;
CoTaskMemFree(explicit_app_id);
}
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
// This can happen if the explorer process isn't running when we try to
// create the icon for some reason (for example, at startup).
if (!result)
LOG(WARNING) << "Unable to create status tray icon.";
}
NotifyIcon::~NotifyIcon() {
// Remove our icon.
host_->Remove(this);
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
Shell_NotifyIcon(NIM_DELETE, &icon_data);
}
void NotifyIcon::HandleClickEvent(const gfx::Point& cursor_pos,
bool left_mouse_click,
bool double_button_click) {
NOTIFYICONIDENTIFIER icon_id;
memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER));
icon_id.uID = icon_id_;
icon_id.hWnd = window_;
icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER);
RECT rect = { 0 };
Shell_NotifyIconGetRect(&icon_id, &rect);
if (left_mouse_click) {
if (double_button_click) // double left click
NotifyDoubleClicked(gfx::Rect(rect));
else // single left click
NotifyClicked(gfx::Rect(rect));
return;
} else if (!double_button_click) { // single right click
NotifyRightClicked(gfx::Rect(rect));
PopContextMenu(cursor_pos);
}
}
void NotifyIcon::ResetIcon() {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
// Delete any previously existing icon.
Shell_NotifyIcon(NIM_DELETE, &icon_data);
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
icon_data.hIcon = icon_.Get();
// If we have an image, then set the NIF_ICON flag, which tells
// Shell_NotifyIcon() to set the image for the status icon it creates.
if (icon_data.hIcon)
icon_data.uFlags |= NIF_ICON;
// Re-add our icon.
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
if (!result)
LOG(WARNING) << "Unable to re-create status tray icon.";
}
void NotifyIcon::SetImage(const gfx::Image& image) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_ICON;
icon_.Set(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap()));
icon_data.hIcon = icon_.Get();
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Error setting status tray icon image";
}
void NotifyIcon::SetPressedImage(const gfx::Image& image) {
// Ignore pressed images, since the standard on Windows is to not highlight
// pressed status icons.
}
void NotifyIcon::SetToolTip(const std::string& tool_tip) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_TIP;
wcscpy_s(icon_data.szTip, base::UTF8ToUTF16(tool_tip).c_str());
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to set tooltip for status tray icon";
}
void NotifyIcon::DisplayBalloon(const gfx::Image& icon,
const base::string16& title,
const base::string16& contents) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_INFO;
icon_data.dwInfoFlags = NIIF_INFO;
wcscpy_s(icon_data.szInfoTitle, title.c_str());
wcscpy_s(icon_data.szInfo, contents.c_str());
icon_data.uTimeout = 0;
base::win::Version win_version = base::win::GetVersion();
if (!icon.IsEmpty() && win_version != base::win::VERSION_PRE_XP) {
balloon_icon_.Set(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap()));
icon_data.hBalloonIcon = balloon_icon_.Get();
icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
}
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to create status tray balloon.";
}
void NotifyIcon::PopContextMenu(const gfx::Point& pos) {
// Set our window as the foreground window, so the context menu closes when
// we click away from it.
if (!SetForegroundWindow(window_))
return;
views::MenuRunner menu_runner(
menu_model_,
views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
ignore_result(menu_runner.RunMenuAt(
NULL,
NULL,
gfx::Rect(pos, gfx::Size()),
views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_MOUSE));
}
void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) {
menu_model_ = menu_model;
}
void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) {
memset(icon_data, 0, sizeof(NOTIFYICONDATA));
icon_data->cbSize = sizeof(NOTIFYICONDATA);
icon_data->hWnd = window_;
icon_data->uID = icon_id_;
if (has_tray_app_id_hash_) {
icon_data->uFlags |= NIF_GUID;
memcpy(reinterpret_cast<void*>(&icon_data->guidItem),
&tray_app_id_hash_,
sizeof(GUID));
}
}
} // namespace atom
<commit_msg>win: Set GUID when getting icon's bounds<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/win/notify_icon.h"
#include <shobjidl.h>
#include "atom/browser/ui/win/notify_icon_host.h"
#include "base/md5.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
NotifyIcon::NotifyIcon(NotifyIconHost* host,
UINT id,
HWND window,
UINT message)
: host_(host),
icon_id_(id),
window_(window),
message_id_(message),
menu_model_(NULL),
has_tray_app_id_hash_(false) {
// NB: If we have an App Model ID, we should propagate that to the tray.
// Doing this prevents duplicate items from showing up in the notification
// preferences (i.e. "Always Show / Show notifications only / etc")
PWSTR explicit_app_id;
if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&explicit_app_id))) {
// GUIDs and MD5 hashes are the same length. So convenient!
base::MD5Sum(explicit_app_id,
sizeof(wchar_t) * wcslen(explicit_app_id),
reinterpret_cast<base::MD5Digest*>(&tray_app_id_hash_));
has_tray_app_id_hash_ = true;
CoTaskMemFree(explicit_app_id);
}
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
// This can happen if the explorer process isn't running when we try to
// create the icon for some reason (for example, at startup).
if (!result)
LOG(WARNING) << "Unable to create status tray icon.";
}
NotifyIcon::~NotifyIcon() {
// Remove our icon.
host_->Remove(this);
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
Shell_NotifyIcon(NIM_DELETE, &icon_data);
}
void NotifyIcon::HandleClickEvent(const gfx::Point& cursor_pos,
bool left_mouse_click,
bool double_button_click) {
NOTIFYICONIDENTIFIER icon_id;
memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER));
icon_id.uID = icon_id_;
icon_id.hWnd = window_;
icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER);
if (has_tray_app_id_hash_)
memcpy(reinterpret_cast<void*>(&icon_id.guidItem),
&tray_app_id_hash_,
sizeof(GUID));
RECT rect = { 0 };
Shell_NotifyIconGetRect(&icon_id, &rect);
if (left_mouse_click) {
if (double_button_click) // double left click
NotifyDoubleClicked(gfx::Rect(rect));
else // single left click
NotifyClicked(gfx::Rect(rect));
return;
} else if (!double_button_click) { // single right click
NotifyRightClicked(gfx::Rect(rect));
PopContextMenu(cursor_pos);
}
}
void NotifyIcon::ResetIcon() {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
// Delete any previously existing icon.
Shell_NotifyIcon(NIM_DELETE, &icon_data);
InitIconData(&icon_data);
icon_data.uFlags |= NIF_MESSAGE;
icon_data.uCallbackMessage = message_id_;
icon_data.hIcon = icon_.Get();
// If we have an image, then set the NIF_ICON flag, which tells
// Shell_NotifyIcon() to set the image for the status icon it creates.
if (icon_data.hIcon)
icon_data.uFlags |= NIF_ICON;
// Re-add our icon.
BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
if (!result)
LOG(WARNING) << "Unable to re-create status tray icon.";
}
void NotifyIcon::SetImage(const gfx::Image& image) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_ICON;
icon_.Set(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap()));
icon_data.hIcon = icon_.Get();
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Error setting status tray icon image";
}
void NotifyIcon::SetPressedImage(const gfx::Image& image) {
// Ignore pressed images, since the standard on Windows is to not highlight
// pressed status icons.
}
void NotifyIcon::SetToolTip(const std::string& tool_tip) {
// Create the icon.
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_TIP;
wcscpy_s(icon_data.szTip, base::UTF8ToUTF16(tool_tip).c_str());
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to set tooltip for status tray icon";
}
void NotifyIcon::DisplayBalloon(const gfx::Image& icon,
const base::string16& title,
const base::string16& contents) {
NOTIFYICONDATA icon_data;
InitIconData(&icon_data);
icon_data.uFlags |= NIF_INFO;
icon_data.dwInfoFlags = NIIF_INFO;
wcscpy_s(icon_data.szInfoTitle, title.c_str());
wcscpy_s(icon_data.szInfo, contents.c_str());
icon_data.uTimeout = 0;
base::win::Version win_version = base::win::GetVersion();
if (!icon.IsEmpty() && win_version != base::win::VERSION_PRE_XP) {
balloon_icon_.Set(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap()));
icon_data.hBalloonIcon = balloon_icon_.Get();
icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
}
BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
if (!result)
LOG(WARNING) << "Unable to create status tray balloon.";
}
void NotifyIcon::PopContextMenu(const gfx::Point& pos) {
// Set our window as the foreground window, so the context menu closes when
// we click away from it.
if (!SetForegroundWindow(window_))
return;
views::MenuRunner menu_runner(
menu_model_,
views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
ignore_result(menu_runner.RunMenuAt(
NULL,
NULL,
gfx::Rect(pos, gfx::Size()),
views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_MOUSE));
}
void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) {
menu_model_ = menu_model;
}
void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) {
memset(icon_data, 0, sizeof(NOTIFYICONDATA));
icon_data->cbSize = sizeof(NOTIFYICONDATA);
icon_data->hWnd = window_;
icon_data->uID = icon_id_;
if (has_tray_app_id_hash_) {
icon_data->uFlags |= NIF_GUID;
memcpy(reinterpret_cast<void*>(&icon_data->guidItem),
&tray_app_id_hash_,
sizeof(GUID));
}
}
} // namespace atom
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "output.h"
#include "xact.h"
#include "post.h"
#include "account.h"
#include "session.h"
#include "report.h"
namespace ledger {
format_posts::format_posts(report_t& _report,
const string& format,
bool _print_raw)
: report(_report), last_xact(NULL), last_post(NULL),
print_raw(_print_raw)
{
TRACE_CTOR(format_posts, "report&, const string&, bool");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
first_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
next_lines_format.parse(string(n, 0, p - n));
between_format.parse(string(p + 2));
} else {
next_lines_format.parse(n);
}
} else {
first_line_format.parse(format);
next_lines_format.parse(format);
}
}
void format_posts::flush()
{
report.output_stream.flush();
}
void format_posts::operator()(post_t& post)
{
std::ostream& out(report.output_stream);
if (print_raw) {
if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
print_item(out, *post.xact);
out << '\n';
last_xact = post.xact;
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
else if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
bind_scope_t bound_scope(report, post);
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
first_line_format.format(out, bound_scope);
last_xact = post.xact;
}
else if (last_post && last_post->date() != post.date()) {
first_line_format.format(out, bound_scope);
}
else {
next_lines_format.format(out, bound_scope);
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
format_accounts::format_accounts(report_t& _report,
const string& format)
: report(_report), disp_pred()
{
TRACE_CTOR(format_accounts, "report&, const string&");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
account_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
total_line_format.parse(string(n, 0, p - n));
separator_format.parse(string(p + 2));
} else {
total_line_format.parse(n);
}
} else {
account_line_format.parse(format);
total_line_format.parse(format);
}
}
std::size_t format_accounts::post_account(account_t& account)
{
if (account.xdata().has_flags(ACCOUNT_EXT_TO_DISPLAY)) {
if (account.parent &&
account.parent->xdata().has_flags(ACCOUNT_EXT_TO_DISPLAY) &&
! account.parent->xdata().has_flags(ACCOUNT_EXT_DISPLAYED))
post_account(*account.parent);
account.xdata().add_flags(ACCOUNT_EXT_DISPLAYED);
bind_scope_t bound_scope(report, account);
account_line_format.format(report.output_stream, bound_scope);
return 1;
}
return 0;
}
std::pair<std::size_t, std::size_t>
format_accounts::mark_accounts(account_t& account, const bool flat)
{
std::size_t visited = 0;
std::size_t to_display = 0;
foreach (accounts_map::value_type& pair, account.accounts) {
std::pair<std::size_t, std::size_t> i = mark_accounts(*pair.second, flat);
visited += i.first;
to_display += i.second;
}
#if defined(DEBUG_ON)
DEBUG("account.display", "Considering account: " << account.fullname());
if (account.has_flags(ACCOUNT_EXT_VISITED))
DEBUG("account.display", " it was visited itself");
DEBUG("account.display", " it has " << visited << " visited children");
DEBUG("account.display",
" it has " << to_display << " children to display");
#endif
if (account.parent &&
(account.has_flags(ACCOUNT_EXT_VISITED) || (! flat && visited > 0))) {
bind_scope_t bound_scope(report, account);
if ((! flat && to_display > 1) ||
((flat || to_display != 1 ||
account.has_flags(ACCOUNT_EXT_VISITED)) &&
disp_pred(bound_scope))) {
account.xdata().add_flags(ACCOUNT_EXT_TO_DISPLAY);
DEBUG("account.display", "Marking account as TO_DISPLAY");
to_display = 1;
}
visited = 1;
}
return std::pair<std::size_t, std::size_t>(visited, to_display);
}
void format_accounts::flush()
{
std::ostream& out(report.output_stream);
if (report.HANDLED(display_)) {
DEBUG("account.display",
"Account display predicate: " << report.HANDLER(display_).str());
disp_pred.predicate.parse(report.HANDLER(display_).str());
}
mark_accounts(*report.session.master, report.HANDLED(flat));
std::size_t displayed = 0;
foreach (account_t * account, posted_accounts)
displayed += post_account(*account);
if (displayed > 1 &&
! report.HANDLED(no_total) && ! report.HANDLED(percent)) {
bind_scope_t bound_scope(report, *report.session.master);
separator_format.format(out, bound_scope);
total_line_format.format(out, bound_scope);
}
out.flush();
}
void format_accounts::operator()(account_t& account)
{
posted_accounts.push_back(&account);
}
} // namespace ledger
<commit_msg>In the balance report, don't output any account twice<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "output.h"
#include "xact.h"
#include "post.h"
#include "account.h"
#include "session.h"
#include "report.h"
namespace ledger {
format_posts::format_posts(report_t& _report,
const string& format,
bool _print_raw)
: report(_report), last_xact(NULL), last_post(NULL),
print_raw(_print_raw)
{
TRACE_CTOR(format_posts, "report&, const string&, bool");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
first_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
next_lines_format.parse(string(n, 0, p - n));
between_format.parse(string(p + 2));
} else {
next_lines_format.parse(n);
}
} else {
first_line_format.parse(format);
next_lines_format.parse(format);
}
}
void format_posts::flush()
{
report.output_stream.flush();
}
void format_posts::operator()(post_t& post)
{
std::ostream& out(report.output_stream);
if (print_raw) {
if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
print_item(out, *post.xact);
out << '\n';
last_xact = post.xact;
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
else if (! post.has_xdata() ||
! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
bind_scope_t bound_scope(report, post);
if (last_xact != post.xact) {
if (last_xact) {
bind_scope_t xact_scope(report, *last_xact);
between_format.format(out, xact_scope);
}
first_line_format.format(out, bound_scope);
last_xact = post.xact;
}
else if (last_post && last_post->date() != post.date()) {
first_line_format.format(out, bound_scope);
}
else {
next_lines_format.format(out, bound_scope);
}
post.xdata().add_flags(POST_EXT_DISPLAYED);
last_post = &post;
}
}
format_accounts::format_accounts(report_t& _report,
const string& format)
: report(_report), disp_pred()
{
TRACE_CTOR(format_accounts, "report&, const string&");
const char * f = format.c_str();
if (const char * p = std::strstr(f, "%/")) {
account_line_format.parse(string(f, 0, p - f));
const char * n = p + 2;
if (const char * p = std::strstr(n, "%/")) {
total_line_format.parse(string(n, 0, p - n));
separator_format.parse(string(p + 2));
} else {
total_line_format.parse(n);
}
} else {
account_line_format.parse(format);
total_line_format.parse(format);
}
}
std::size_t format_accounts::post_account(account_t& account)
{
if (account.xdata().has_flags(ACCOUNT_EXT_TO_DISPLAY) &&
! account.xdata().has_flags(ACCOUNT_EXT_DISPLAYED)) {
if (account.parent &&
account.parent->xdata().has_flags(ACCOUNT_EXT_TO_DISPLAY) &&
! account.parent->xdata().has_flags(ACCOUNT_EXT_DISPLAYED))
post_account(*account.parent);
account.xdata().add_flags(ACCOUNT_EXT_DISPLAYED);
bind_scope_t bound_scope(report, account);
account_line_format.format(report.output_stream, bound_scope);
return 1;
}
return 0;
}
std::pair<std::size_t, std::size_t>
format_accounts::mark_accounts(account_t& account, const bool flat)
{
std::size_t visited = 0;
std::size_t to_display = 0;
foreach (accounts_map::value_type& pair, account.accounts) {
std::pair<std::size_t, std::size_t> i = mark_accounts(*pair.second, flat);
visited += i.first;
to_display += i.second;
}
#if defined(DEBUG_ON)
DEBUG("account.display", "Considering account: " << account.fullname());
if (account.has_flags(ACCOUNT_EXT_VISITED))
DEBUG("account.display", " it was visited itself");
DEBUG("account.display", " it has " << visited << " visited children");
DEBUG("account.display",
" it has " << to_display << " children to display");
#endif
if (account.parent &&
(account.has_flags(ACCOUNT_EXT_VISITED) || (! flat && visited > 0))) {
bind_scope_t bound_scope(report, account);
if ((! flat && to_display > 1) ||
((flat || to_display != 1 ||
account.has_flags(ACCOUNT_EXT_VISITED)) &&
disp_pred(bound_scope))) {
account.xdata().add_flags(ACCOUNT_EXT_TO_DISPLAY);
DEBUG("account.display", "Marking account as TO_DISPLAY");
to_display = 1;
}
visited = 1;
}
return std::pair<std::size_t, std::size_t>(visited, to_display);
}
void format_accounts::flush()
{
std::ostream& out(report.output_stream);
if (report.HANDLED(display_)) {
DEBUG("account.display",
"Account display predicate: " << report.HANDLER(display_).str());
disp_pred.predicate.parse(report.HANDLER(display_).str());
}
mark_accounts(*report.session.master, report.HANDLED(flat));
std::size_t displayed = 0;
foreach (account_t * account, posted_accounts)
displayed += post_account(*account);
if (displayed > 1 &&
! report.HANDLED(no_total) && ! report.HANDLED(percent)) {
bind_scope_t bound_scope(report, *report.session.master);
separator_format.format(out, bound_scope);
total_line_format.format(out, bound_scope);
}
out.flush();
}
void format_accounts::operator()(account_t& account)
{
posted_accounts.push_back(&account);
}
} // namespace ledger
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: edws.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2004-05-18 14:03: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: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _ACORRECT_HXX
#include <acorrect.hxx>
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
#ifndef _SW_REWRITER_HXX
#include <SwRewriter.hxx>
#endif
/********************************************************
* Ctor/Dtor
********************************************************/
// verkleideter Copy-Constructor
SwEditShell::SwEditShell( SwEditShell& rEdSH, Window *pWin )
: SwCrsrShell( rEdSH, pWin )
{
}
// ctor/dtor
SwEditShell::SwEditShell( SwDoc& rDoc, Window *pWin, SwRootFrm *pRootFrm,
const SwViewOption *pOpt )
: SwCrsrShell( rDoc, pWin, pRootFrm, pOpt)
{
GetDoc()->DoUndo();
}
SwEditShell::~SwEditShell() // USED
{
}
/******************************************************************************
* sal_Bool SwEditShell::IsModified() const
******************************************************************************/
sal_Bool SwEditShell::IsModified() const
{
return GetDoc()->IsModified();
}
/******************************************************************************
* void SwEditShell::SetModified()
******************************************************************************/
void SwEditShell::SetModified()
{
GetDoc()->SetModified();
}
/******************************************************************************
* void SwEditShell::ResetModified()
******************************************************************************/
void SwEditShell::ResetModified()
{
GetDoc()->ResetModified();
}
void SwEditShell::SetUndoNoResetModified()
{
GetDoc()->SetModified();
GetDoc()->SetUndoNoResetModified();
}
#ifdef USED
/******************************************************************************
* void SwEditShell::StartAction()
******************************************************************************/
void SwEditShell::StartAction() // OPT: ganz wech
{
SwCrsrShell::StartAction();
}
/******************************************************************************
* void SwEditShell::EndAction()
******************************************************************************/
void SwEditShell::EndAction()
{
SwCrsrShell::EndAction();
}
#endif
/******************************************************************************
* void SwEditShell::StartAllAction()
******************************************************************************/
void SwEditShell::StartAllAction()
{
ViewShell *pSh = this;
do {
if( pSh->IsA( TYPE( SwEditShell ) ) )
((SwEditShell*)pSh)->StartAction();
else
pSh->StartAction();
pSh = (ViewShell *)pSh->GetNext();
} while(pSh != this);
}
/******************************************************************************
* void SwEditShell::EndAllAction()
******************************************************************************/
void SwEditShell::EndAllAction()
{
ViewShell *pSh = this;
do {
if( pSh->IsA( TYPE( SwEditShell ) ) )
((SwEditShell*)pSh)->EndAction();
else
pSh->EndAction();
pSh = (ViewShell *)pSh->GetNext();
} while(pSh != this);
}
/******************************************************************************
* void SwEditShell::CalcLayout()
******************************************************************************/
void SwEditShell::CalcLayout()
{
StartAllAction();
ViewShell::CalcLayout();
ViewShell *pSh = this;
do
{
if ( pSh->GetWin() )
pSh->GetWin()->Invalidate();
pSh = (ViewShell*)pSh->GetNext();
} while ( pSh != this );
EndAllAction();
}
/******************************************************************************
* Inhaltsform bestimmen, holen
******************************************************************************/
// OPT: wird fuer jedes Attribut gerufen?
sal_uInt16 SwEditShell::GetCntType() const
{
// nur noch am SPoint ist der Inhalt interessant
sal_uInt16 nRet = 0;
if( IsTableMode() )
nRet = CNT_TXT;
else
switch( GetCrsr()->GetNode()->GetNodeType() )
{
case ND_TEXTNODE: nRet = CNT_TXT; break;
case ND_GRFNODE: nRet = CNT_GRF; break;
case ND_OLENODE: nRet = CNT_OLE; break;
}
ASSERT( nRet, ERR_OUTOFSCOPE );
return nRet;
}
//------------------------------------------------------------------------------
sal_Bool SwEditShell::HasOtherCnt() const
{
const SwNodes &rNds = GetDoc()->GetNodes();
const SwNode *pNd;
return GetDoc()->GetSpzFrmFmts()->Count() ||
1 != (( pNd = &rNds.GetEndOfInserts() )->GetIndex() -
pNd->StartOfSectionIndex() ) ||
1 != (( pNd = &rNds.GetEndOfAutotext() )->GetIndex() -
pNd->StartOfSectionIndex() );
}
/******************************************************************************
* Zugriffsfunktionen fuer Filename-Behandlung
******************************************************************************/
SwActKontext::SwActKontext(SwEditShell *pShell)
: pSh(pShell)
{
pSh->StartAction();
}
SwActKontext::~SwActKontext()
{
pSh->EndAction();
}
/******************************************************************************
* Klasse fuer den automatisierten Aufruf von Start- und
* EndCrsrMove();
******************************************************************************/
SwMvKontext::SwMvKontext(SwEditShell *pShell ) : pSh(pShell)
{
pSh->SttCrsrMove();
}
SwMvKontext::~SwMvKontext()
{
pSh->EndCrsrMove();
}
SwFrmFmt *SwEditShell::GetTableFmt() // OPT: schnellster Test auf Tabelle?
{
const SwTableNode* pTblNd = IsCrsrInTbl();
return pTblNd ? (SwFrmFmt*)pTblNd->GetTable().GetFrmFmt() : 0;
}
// OPT: wieso 3x beim neuen Dokument
sal_uInt16 SwEditShell::GetTOXTypeCount(TOXTypes eTyp) const
{
return pDoc->GetTOXTypeCount(eTyp);
}
void SwEditShell::InsertTOXType(const SwTOXType& rTyp)
{
pDoc->InsertTOXType(rTyp);
}
void SwEditShell::DoUndo( sal_Bool bOn )
{ GetDoc()->DoUndo( bOn ); }
sal_Bool SwEditShell::DoesUndo() const
{ return GetDoc()->DoesUndo(); }
void SwEditShell::DoGroupUndo( sal_Bool bOn )
{ GetDoc()->DoGroupUndo( bOn ); }
sal_Bool SwEditShell::DoesGroupUndo() const
{ return GetDoc()->DoesGroupUndo(); }
void SwEditShell::DelAllUndoObj()
{
GetDoc()->DelAllUndoObj();
}
// Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von
// Charaktern. Default ist sdbcx::Group-Undo.
// setzt Undoklammerung auf, liefert nUndoId der Klammerung
sal_uInt16 SwEditShell::StartUndo( sal_uInt16 nUndoId,
const SwRewriter *pRewriter )
{ return GetDoc()->StartUndo( nUndoId, pRewriter ); }
// schliesst Klammerung der nUndoId, nicht vom UI benutzt
sal_uInt16 SwEditShell::EndUndo(sal_uInt16 nUndoId)
{ return GetDoc()->EndUndo(nUndoId); }
// liefert die Id der letzten undofaehigen Aktion zurueck
// fuellt ggf. VARARR mit sdbcx::User-UndoIds
sal_uInt16 SwEditShell::GetUndoIds(String* pStr,SwUndoIds *pUndoIds) const
{ return GetDoc()->GetUndoIds(pStr,pUndoIds); }
String SwEditShell::GetUndoIdsStr(String* pStr,SwUndoIds *pUndoIds) const
{ return GetDoc()->GetUndoIdsStr(pStr,pUndoIds); }
// liefert die Id der letzten Redofaehigen Aktion zurueck
// fuellt ggf. VARARR mit RedoIds
sal_uInt16 SwEditShell::GetRedoIds(String* pStr,SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRedoIds(pStr,pRedoIds); }
String SwEditShell::GetRedoIdsStr(String* pStr,SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRedoIdsStr(pStr,pRedoIds); }
// liefert die Id der letzten Repeatfaehigen Aktion zurueck
// fuellt ggf. VARARR mit RedoIds
sal_uInt16 SwEditShell::GetRepeatIds(String* pStr, SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRepeatIds(pStr,pRedoIds); }
String SwEditShell::GetRepeatIdsStr(String* pStr, SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRepeatIdsStr(pStr,pRedoIds); }
// AutoKorrektur - JP 27.01.94
void SwEditShell::AutoCorrect( SvxAutoCorrect& rACorr, sal_Bool bInsert,
sal_Unicode cChar )
{
SET_CURR_SHELL( this );
StartAllAction();
SwPaM* pCrsr = GetCrsr();
SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode();
SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, cChar );
rACorr.AutoCorrect( aSwAutoCorrDoc,
pTNd->GetTxt(), pCrsr->GetPoint()->nContent.GetIndex(),
cChar, bInsert );
if( cChar )
SaveTblBoxCntnt( pCrsr->GetPoint() );
EndAllAction();
}
void SwEditShell::SetNewDoc(sal_Bool bNew)
{
GetDoc()->SetNewDoc(bNew);
}
sal_Bool SwEditShell::GetPrevAutoCorrWord( SvxAutoCorrect& rACorr, String& rWord )
{
SET_CURR_SHELL( this );
sal_Bool bRet;
SwPaM* pCrsr = GetCrsr();
xub_StrLen nPos = pCrsr->GetPoint()->nContent.GetIndex();
SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode();
if( pTNd && nPos )
{
SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, 0 );
bRet = rACorr.GetPrevAutoCorrWord( aSwAutoCorrDoc,
pTNd->GetTxt(), nPos, rWord );
}
else
bRet = sal_False;
return bRet;
}
SwAutoCompleteWord& SwEditShell::GetAutoCompleteWords()
{
return SwDoc::GetAutoCompleteWords();
}
<commit_msg>INTEGRATION: CWS tune05 (1.4.54); FILE MERGED 2004/06/23 12:53:51 cmc 1.4.54.1: #i30554# remove unused code inside #ifdef USED guards<commit_after>/*************************************************************************
*
* $RCSfile: edws.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-08-12 12:24:32 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _ACORRECT_HXX
#include <acorrect.hxx>
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
#ifndef _SW_REWRITER_HXX
#include <SwRewriter.hxx>
#endif
/********************************************************
* Ctor/Dtor
********************************************************/
// verkleideter Copy-Constructor
SwEditShell::SwEditShell( SwEditShell& rEdSH, Window *pWin )
: SwCrsrShell( rEdSH, pWin )
{
}
// ctor/dtor
SwEditShell::SwEditShell( SwDoc& rDoc, Window *pWin, SwRootFrm *pRootFrm,
const SwViewOption *pOpt )
: SwCrsrShell( rDoc, pWin, pRootFrm, pOpt)
{
GetDoc()->DoUndo();
}
SwEditShell::~SwEditShell() // USED
{
}
/******************************************************************************
* sal_Bool SwEditShell::IsModified() const
******************************************************************************/
sal_Bool SwEditShell::IsModified() const
{
return GetDoc()->IsModified();
}
/******************************************************************************
* void SwEditShell::SetModified()
******************************************************************************/
void SwEditShell::SetModified()
{
GetDoc()->SetModified();
}
/******************************************************************************
* void SwEditShell::ResetModified()
******************************************************************************/
void SwEditShell::ResetModified()
{
GetDoc()->ResetModified();
}
void SwEditShell::SetUndoNoResetModified()
{
GetDoc()->SetModified();
GetDoc()->SetUndoNoResetModified();
}
/******************************************************************************
* void SwEditShell::StartAllAction()
******************************************************************************/
void SwEditShell::StartAllAction()
{
ViewShell *pSh = this;
do {
if( pSh->IsA( TYPE( SwEditShell ) ) )
((SwEditShell*)pSh)->StartAction();
else
pSh->StartAction();
pSh = (ViewShell *)pSh->GetNext();
} while(pSh != this);
}
/******************************************************************************
* void SwEditShell::EndAllAction()
******************************************************************************/
void SwEditShell::EndAllAction()
{
ViewShell *pSh = this;
do {
if( pSh->IsA( TYPE( SwEditShell ) ) )
((SwEditShell*)pSh)->EndAction();
else
pSh->EndAction();
pSh = (ViewShell *)pSh->GetNext();
} while(pSh != this);
}
/******************************************************************************
* void SwEditShell::CalcLayout()
******************************************************************************/
void SwEditShell::CalcLayout()
{
StartAllAction();
ViewShell::CalcLayout();
ViewShell *pSh = this;
do
{
if ( pSh->GetWin() )
pSh->GetWin()->Invalidate();
pSh = (ViewShell*)pSh->GetNext();
} while ( pSh != this );
EndAllAction();
}
/******************************************************************************
* Inhaltsform bestimmen, holen
******************************************************************************/
// OPT: wird fuer jedes Attribut gerufen?
sal_uInt16 SwEditShell::GetCntType() const
{
// nur noch am SPoint ist der Inhalt interessant
sal_uInt16 nRet = 0;
if( IsTableMode() )
nRet = CNT_TXT;
else
switch( GetCrsr()->GetNode()->GetNodeType() )
{
case ND_TEXTNODE: nRet = CNT_TXT; break;
case ND_GRFNODE: nRet = CNT_GRF; break;
case ND_OLENODE: nRet = CNT_OLE; break;
}
ASSERT( nRet, ERR_OUTOFSCOPE );
return nRet;
}
//------------------------------------------------------------------------------
sal_Bool SwEditShell::HasOtherCnt() const
{
const SwNodes &rNds = GetDoc()->GetNodes();
const SwNode *pNd;
return GetDoc()->GetSpzFrmFmts()->Count() ||
1 != (( pNd = &rNds.GetEndOfInserts() )->GetIndex() -
pNd->StartOfSectionIndex() ) ||
1 != (( pNd = &rNds.GetEndOfAutotext() )->GetIndex() -
pNd->StartOfSectionIndex() );
}
/******************************************************************************
* Zugriffsfunktionen fuer Filename-Behandlung
******************************************************************************/
SwActKontext::SwActKontext(SwEditShell *pShell)
: pSh(pShell)
{
pSh->StartAction();
}
SwActKontext::~SwActKontext()
{
pSh->EndAction();
}
/******************************************************************************
* Klasse fuer den automatisierten Aufruf von Start- und
* EndCrsrMove();
******************************************************************************/
SwMvKontext::SwMvKontext(SwEditShell *pShell ) : pSh(pShell)
{
pSh->SttCrsrMove();
}
SwMvKontext::~SwMvKontext()
{
pSh->EndCrsrMove();
}
SwFrmFmt *SwEditShell::GetTableFmt() // OPT: schnellster Test auf Tabelle?
{
const SwTableNode* pTblNd = IsCrsrInTbl();
return pTblNd ? (SwFrmFmt*)pTblNd->GetTable().GetFrmFmt() : 0;
}
// OPT: wieso 3x beim neuen Dokument
sal_uInt16 SwEditShell::GetTOXTypeCount(TOXTypes eTyp) const
{
return pDoc->GetTOXTypeCount(eTyp);
}
void SwEditShell::InsertTOXType(const SwTOXType& rTyp)
{
pDoc->InsertTOXType(rTyp);
}
void SwEditShell::DoUndo( sal_Bool bOn )
{ GetDoc()->DoUndo( bOn ); }
sal_Bool SwEditShell::DoesUndo() const
{ return GetDoc()->DoesUndo(); }
void SwEditShell::DoGroupUndo( sal_Bool bOn )
{ GetDoc()->DoGroupUndo( bOn ); }
sal_Bool SwEditShell::DoesGroupUndo() const
{ return GetDoc()->DoesGroupUndo(); }
void SwEditShell::DelAllUndoObj()
{
GetDoc()->DelAllUndoObj();
}
// Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von
// Charaktern. Default ist sdbcx::Group-Undo.
// setzt Undoklammerung auf, liefert nUndoId der Klammerung
sal_uInt16 SwEditShell::StartUndo( sal_uInt16 nUndoId,
const SwRewriter *pRewriter )
{ return GetDoc()->StartUndo( nUndoId, pRewriter ); }
// schliesst Klammerung der nUndoId, nicht vom UI benutzt
sal_uInt16 SwEditShell::EndUndo(sal_uInt16 nUndoId)
{ return GetDoc()->EndUndo(nUndoId); }
// liefert die Id der letzten undofaehigen Aktion zurueck
// fuellt ggf. VARARR mit sdbcx::User-UndoIds
sal_uInt16 SwEditShell::GetUndoIds(String* pStr,SwUndoIds *pUndoIds) const
{ return GetDoc()->GetUndoIds(pStr,pUndoIds); }
String SwEditShell::GetUndoIdsStr(String* pStr,SwUndoIds *pUndoIds) const
{ return GetDoc()->GetUndoIdsStr(pStr,pUndoIds); }
// liefert die Id der letzten Redofaehigen Aktion zurueck
// fuellt ggf. VARARR mit RedoIds
sal_uInt16 SwEditShell::GetRedoIds(String* pStr,SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRedoIds(pStr,pRedoIds); }
String SwEditShell::GetRedoIdsStr(String* pStr,SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRedoIdsStr(pStr,pRedoIds); }
// liefert die Id der letzten Repeatfaehigen Aktion zurueck
// fuellt ggf. VARARR mit RedoIds
sal_uInt16 SwEditShell::GetRepeatIds(String* pStr, SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRepeatIds(pStr,pRedoIds); }
String SwEditShell::GetRepeatIdsStr(String* pStr, SwUndoIds *pRedoIds) const
{ return GetDoc()->GetRepeatIdsStr(pStr,pRedoIds); }
// AutoKorrektur - JP 27.01.94
void SwEditShell::AutoCorrect( SvxAutoCorrect& rACorr, sal_Bool bInsert,
sal_Unicode cChar )
{
SET_CURR_SHELL( this );
StartAllAction();
SwPaM* pCrsr = GetCrsr();
SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode();
SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, cChar );
rACorr.AutoCorrect( aSwAutoCorrDoc,
pTNd->GetTxt(), pCrsr->GetPoint()->nContent.GetIndex(),
cChar, bInsert );
if( cChar )
SaveTblBoxCntnt( pCrsr->GetPoint() );
EndAllAction();
}
void SwEditShell::SetNewDoc(sal_Bool bNew)
{
GetDoc()->SetNewDoc(bNew);
}
sal_Bool SwEditShell::GetPrevAutoCorrWord( SvxAutoCorrect& rACorr, String& rWord )
{
SET_CURR_SHELL( this );
sal_Bool bRet;
SwPaM* pCrsr = GetCrsr();
xub_StrLen nPos = pCrsr->GetPoint()->nContent.GetIndex();
SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode();
if( pTNd && nPos )
{
SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, 0 );
bRet = rACorr.GetPrevAutoCorrWord( aSwAutoCorrDoc,
pTNd->GetTxt(), nPos, rWord );
}
else
bRet = sal_False;
return bRet;
}
SwAutoCompleteWord& SwEditShell::GetAutoCompleteWords()
{
return SwDoc::GetAutoCompleteWords();
}
<|endoftext|> |
<commit_before>#include "ShaderCompiler.h"
#include <cassert>
#include <iostream>
#include <vector>
#include <algorithm>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <iozeug/filename.h>
#include <iozeug/directorytraversal.h>
#include <glbinding/gl/functions.h>
#include <globjects/globjects.h>
#include <globjects/base/File.h>
#include <globjects/NamedString.h>
#include <globjects/Program.h>
#include <globjects/Shader.h>
#include <globjects/logging.h>
#include <globjects/base/File.h>
#include <globjects/base/StringTemplate.h>
#include "OpenGLContext.h"
bool ShaderCompiler::process(const QJsonDocument & configDocument)
{
return ShaderCompiler{}.parse(configDocument);
}
bool ShaderCompiler::parse(const QJsonDocument & configDocument)
{
if (!configDocument.isObject())
{
error(JsonParseError::DocumentNotAnObject);
return false;
}
const auto config = configDocument.object();
const auto jsonOpenGLConfig = config.value("opengl");
if (!jsonOpenGLConfig.isObject())
{
error(JsonParseError::PropertyNotFoundOrNotAnObject, "opengl");
return false;
}
auto parseError = JsonParseError{};
auto context = OpenGLContext::fromJsonConfig(jsonOpenGLConfig.toObject(), &parseError);
if (parseError)
{
error(parseError);
return false;
}
if (!context.create())
{
error(JsonParseError::ContextCreationFailed);
return false;
}
if (!context.makeCurrent())
{
error(JsonParseError::ContextActivationFailed);
return false;
}
globjects::init();
info(Info::Driver);
const auto jsonNamedStringPaths = config.value("namedStringPaths");
if (jsonNamedStringPaths.isArray())
{
if (!parseNamedStringPaths(jsonNamedStringPaths.toArray()))
return false;
}
const auto jsonPrograms = config.value("programs");
if (!jsonPrograms.isArray())
{
error(JsonParseError::ArrayNotFoundOrEmpty, "programs");
return false;
}
auto ok = parsePrograms(jsonPrograms.toArray());
context.doneCurrent();
info(Info::Failures);
return ok;
}
bool ShaderCompiler::parseNamedStringPaths(const QJsonArray & paths)
{
std::vector<std::string> namedStrings{};
for (const auto & namedStringPath : paths)
{
if (!namedStringPath.isObject())
{
error(JsonParseError::ElementNotObject, "namedStringPaths");
return false;
}
const auto pathObject = namedStringPath.toObject();
const auto pathString = pathObject.value("path").toString();
if (pathString.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "path");
return false;
}
const auto extensionsArray = pathObject.value("extensions").toArray();
if (extensionsArray.isEmpty())
{
error(JsonParseError::ArrayNotFoundOrEmpty, "extensions" );
return false;
}
bool ok{};
const auto extensions = parseExtensions(extensionsArray, ok);
if (!ok)
{
error(JsonParseError::ElementWrongFormat, "extensions");
return false;
}
auto files = scanDirectory(pathString.toStdString(), extensions);
if (files.empty())
{
error(JsonParseError::NoFilesWithExtensionFound, pathString);
return false;
}
const auto aliasString = pathObject.value("alias").toString();
auto aliases = files;
if (!aliasString.isNull())
{
aliases = createAliases(files,
pathString.toStdString(),
aliasString.toStdString());
}
std::copy(aliases.begin(), aliases.end(), std::back_inserter(namedStrings));
createNamedStrings(files, aliases);
}
qDebug() << "Registered Named Strings:";
for (const auto & namedString : namedStrings)
qDebug().nospace() << " " << QString::fromStdString(namedString);
return true;
}
std::set<std::string> ShaderCompiler::parseExtensions(
const QJsonArray & extensionsArray,
bool & ok)
{
auto extensions = std::set<std::string>{};
for (const auto & extensionValue : extensionsArray)
{
if (!extensionValue.isString())
{
ok = false;
return extensions;
}
extensions.insert(extensionValue.toString().toStdString());
}
ok = true;
return extensions;
}
std::vector<std::string> ShaderCompiler::scanDirectory(
const std::string & path,
const std::set<std::string> & extensions)
{
auto files = std::vector<std::string>{};
iozeug::scanDirectory(path, "*", true,
[&extensions, &files] (const std::string & fileName)
{
const auto fileExtension = iozeug::getExtension(fileName);
if (!extensions.count(fileExtension))
return;
files.push_back(fileName);
});
return files;
}
std::vector<std::string> ShaderCompiler::createAliases(
const std::vector<std::string> & files,
const std::string & path,
const std::string & alias)
{
std::vector<std::string> aliasedFiles{};
for (const auto & file : files)
{
auto aliasedFile = alias;
assert(file.size() >= path.size());
std::copy(file.begin() + path.size(), file.end(), std::back_inserter(aliasedFile));
aliasedFiles.push_back(aliasedFile);
}
return aliasedFiles;
}
void ShaderCompiler::createNamedStrings(
const std::vector<std::string> & files,
const std::vector<std::string> & aliases)
{
assert(files.size() == aliases.size());
for (auto i = 0u; i < files.size(); ++i)
{
const auto file = files[i];
const auto alias = aliases[i];
const auto fileObject = new globjects::File(file);
globjects::NamedString::create(alias, fileObject);
}
}
bool ShaderCompiler::parsePrograms(const QJsonArray & programs)
{
bool ok{};
for (const auto programValue : programs)
{
if (!programValue.isObject())
{
error(JsonParseError::ElementNotObject, "programs");
return false;
}
const auto programObject = programValue.toObject();
const auto name = programObject.value("name").toString();
if (name.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "name");
return false;
}
qDebug() << "";
qDebug().noquote() << "Process" << name;
const auto shadersArray = programObject.value("shaders");
if (!shadersArray.isArray())
{
error(JsonParseError::ArrayNotFoundOrEmpty, "shaders");
return false;
}
const auto shaders = parseShaders(shadersArray.toArray(), ok);
if (!ok)
{
m_linkFailures.push_back(name.toStdString());
continue;
}
qDebug().noquote() << "Link" << name;
ok = createAndLinkProgram(shaders);
if (!ok)
m_linkFailures.push_back(name.toStdString());
}
return true;
}
std::vector<globjects::ref_ptr<globjects::Shader>> ShaderCompiler::parseShaders(
const QJsonArray & shadersArray,
bool & ok)
{
std::vector<globjects::ref_ptr<globjects::Shader>> shaders{};
for (const auto & shaderValue : shadersArray)
{
if (!shaderValue.isObject())
{
error(JsonParseError::ElementNotObject, "shaders");
ok = false;
return shaders;
}
const auto shaderObject = shaderValue.toObject();
const auto fileName = shaderObject.value("file").toString();
if (fileName.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "file");
ok = false;
return shaders;
}
const auto name = shaderObject.value("name").toString();
if (name.isNull())
qDebug().noquote() << QString{"Compile %1"}.arg(fileName);
else
qDebug().noquote() << QString{"Compile %1 ('%2')"}.arg(name).arg(fileName);
const auto typeString = shaderObject.value("type").toString();
if (typeString.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "type");
ok = false;
return shaders;
}
const auto type = typeFromString(typeString);
if (type == gl::GL_NONE)
{
error(JsonParseError::ShaderTypeNotFound, typeString);
ok = false;
return shaders;
}
globjects::ref_ptr<globjects::AbstractStringSource> shaderFile = new globjects::File{fileName.toStdString()};
const auto replacementsValue = shaderObject.value("replacements");
if (!replacementsValue.isUndefined())
{
if (replacementsValue.isObject())
{
if (!replaceStrings(replacementsValue.toObject(), shaderFile))
{
ok = false;
return shaders;
}
}
else
{
error(JsonParseError::PropertyWrongFormat, "replacements");
ok = false;
return shaders;
}
}
auto shader = globjects::make_ref<globjects::Shader>(type, shaderFile);
if (!shader->compile())
{
m_compileFailures.push_back(fileName.toStdString());
ok = false;
return shaders;
}
shaders.push_back(globjects::ref_ptr<globjects::Shader>(shader));
}
ok = true;
return shaders;
}
bool ShaderCompiler::replaceStrings(
const QJsonObject & replacements,
globjects::ref_ptr<globjects::AbstractStringSource> & stringSource)
{
auto sourceTemplate = globjects::make_ref<globjects::StringTemplate>(stringSource);
for (auto it = replacements.begin(); it != replacements.end(); ++it)
{
const auto valueString = it.value().toString();
if (valueString.isNull())
{
error(JsonParseError::PropertyWrongFormat, it.key());
return false;
}
sourceTemplate->replace(it.key().toStdString(), valueString.toStdString());
}
stringSource = sourceTemplate;
return true;
}
gl::GLenum ShaderCompiler::typeFromString(const QString & typeString)
{
if (typeString == "GL_VERTEX_SHADER")
{
return gl::GL_VERTEX_SHADER;
}
else if (typeString == "GL_VERTEX_SHADER")
{
return gl::GL_TESS_CONTROL_SHADER;
}
else if (typeString == "GL_TESS_EVALUATION_SHADER")
{
return gl::GL_TESS_EVALUATION_SHADER;
}
else if (typeString == "GL_GEOMETRY_SHADER")
{
return gl::GL_GEOMETRY_SHADER;
}
else if (typeString == "GL_FRAGMENT_SHADER")
{
return gl::GL_FRAGMENT_SHADER;
}
else if (typeString == "GL_COMPUTE_SHADER")
{
return gl::GL_COMPUTE_SHADER;
}
return gl::GL_NONE;
}
bool ShaderCompiler::createAndLinkProgram(
const std::vector<globjects::ref_ptr<globjects::Shader>> & shaders)
{
auto program = globjects::make_ref<globjects::Program>();
for (auto & shader : shaders)
program->attach(shader);
program->link();
if (!program->isLinked())
return false;
return true;
}
void ShaderCompiler::info(Info type)
{
if (type == Info::Driver)
{
globjects::info() << "Driver: " << globjects::vendor();
globjects::info() << "Renderer: " << globjects::renderer();
}
else if (type == Info::Failures)
{
if (!m_compileFailures.empty())
{
globjects::info();
globjects::info() << "Compile Failures:";
for (const auto failure : m_compileFailures)
globjects::info() << " " << failure;
}
if (!m_linkFailures.empty())
{
globjects::info();
globjects::info() << "Link Failures:";
for (const auto failure : m_linkFailures)
globjects::info() << " " << failure;
}
}
}
void ShaderCompiler::error(JsonParseError error)
{
m_errorLog.error(error);
}
void ShaderCompiler::error(JsonParseError::Type type, const QString & info)
{
m_errorLog.error({ type, info });
}
<commit_msg>Rename aliasedFiles to aliases<commit_after>#include "ShaderCompiler.h"
#include <cassert>
#include <iostream>
#include <vector>
#include <algorithm>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <iozeug/filename.h>
#include <iozeug/directorytraversal.h>
#include <glbinding/gl/functions.h>
#include <globjects/globjects.h>
#include <globjects/base/File.h>
#include <globjects/NamedString.h>
#include <globjects/Program.h>
#include <globjects/Shader.h>
#include <globjects/logging.h>
#include <globjects/base/File.h>
#include <globjects/base/StringTemplate.h>
#include "OpenGLContext.h"
bool ShaderCompiler::process(const QJsonDocument & configDocument)
{
return ShaderCompiler{}.parse(configDocument);
}
bool ShaderCompiler::parse(const QJsonDocument & configDocument)
{
if (!configDocument.isObject())
{
error(JsonParseError::DocumentNotAnObject);
return false;
}
const auto config = configDocument.object();
const auto jsonOpenGLConfig = config.value("opengl");
if (!jsonOpenGLConfig.isObject())
{
error(JsonParseError::PropertyNotFoundOrNotAnObject, "opengl");
return false;
}
auto parseError = JsonParseError{};
auto context = OpenGLContext::fromJsonConfig(jsonOpenGLConfig.toObject(), &parseError);
if (parseError)
{
error(parseError);
return false;
}
if (!context.create())
{
error(JsonParseError::ContextCreationFailed);
return false;
}
if (!context.makeCurrent())
{
error(JsonParseError::ContextActivationFailed);
return false;
}
globjects::init();
info(Info::Driver);
const auto jsonNamedStringPaths = config.value("namedStringPaths");
if (jsonNamedStringPaths.isArray())
{
if (!parseNamedStringPaths(jsonNamedStringPaths.toArray()))
return false;
}
const auto jsonPrograms = config.value("programs");
if (!jsonPrograms.isArray())
{
error(JsonParseError::ArrayNotFoundOrEmpty, "programs");
return false;
}
auto ok = parsePrograms(jsonPrograms.toArray());
context.doneCurrent();
info(Info::Failures);
return ok;
}
bool ShaderCompiler::parseNamedStringPaths(const QJsonArray & paths)
{
std::vector<std::string> namedStrings{};
for (const auto & namedStringPath : paths)
{
if (!namedStringPath.isObject())
{
error(JsonParseError::ElementNotObject, "namedStringPaths");
return false;
}
const auto pathObject = namedStringPath.toObject();
const auto pathString = pathObject.value("path").toString();
if (pathString.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "path");
return false;
}
const auto extensionsArray = pathObject.value("extensions").toArray();
if (extensionsArray.isEmpty())
{
error(JsonParseError::ArrayNotFoundOrEmpty, "extensions" );
return false;
}
bool ok{};
const auto extensions = parseExtensions(extensionsArray, ok);
if (!ok)
{
error(JsonParseError::ElementWrongFormat, "extensions");
return false;
}
auto files = scanDirectory(pathString.toStdString(), extensions);
if (files.empty())
{
error(JsonParseError::NoFilesWithExtensionFound, pathString);
return false;
}
const auto aliasString = pathObject.value("alias").toString();
auto aliases = files;
if (!aliasString.isNull())
{
aliases = createAliases(files,
pathString.toStdString(),
aliasString.toStdString());
}
std::copy(aliases.begin(), aliases.end(), std::back_inserter(namedStrings));
createNamedStrings(files, aliases);
}
qDebug() << "Registered Named Strings:";
for (const auto & namedString : namedStrings)
qDebug().nospace() << " " << QString::fromStdString(namedString);
return true;
}
std::set<std::string> ShaderCompiler::parseExtensions(
const QJsonArray & extensionsArray,
bool & ok)
{
auto extensions = std::set<std::string>{};
for (const auto & extensionValue : extensionsArray)
{
if (!extensionValue.isString())
{
ok = false;
return extensions;
}
extensions.insert(extensionValue.toString().toStdString());
}
ok = true;
return extensions;
}
std::vector<std::string> ShaderCompiler::scanDirectory(
const std::string & path,
const std::set<std::string> & extensions)
{
auto files = std::vector<std::string>{};
iozeug::scanDirectory(path, "*", true,
[&extensions, &files] (const std::string & fileName)
{
const auto fileExtension = iozeug::getExtension(fileName);
if (!extensions.count(fileExtension))
return;
files.push_back(fileName);
});
return files;
}
std::vector<std::string> ShaderCompiler::createAliases(
const std::vector<std::string> & files,
const std::string & path,
const std::string & alias)
{
std::vector<std::string> aliases{};
for (const auto & file : files)
{
auto aliasedFile = alias;
assert(file.size() >= path.size());
std::copy(file.begin() + path.size(), file.end(), std::back_inserter(aliasedFile));
aliases.push_back(aliasedFile);
}
return aliases;
}
void ShaderCompiler::createNamedStrings(
const std::vector<std::string> & files,
const std::vector<std::string> & aliases)
{
assert(files.size() == aliases.size());
for (auto i = 0u; i < files.size(); ++i)
{
const auto file = files[i];
const auto alias = aliases[i];
const auto fileObject = new globjects::File(file);
globjects::NamedString::create(alias, fileObject);
}
}
bool ShaderCompiler::parsePrograms(const QJsonArray & programs)
{
bool ok{};
for (const auto programValue : programs)
{
if (!programValue.isObject())
{
error(JsonParseError::ElementNotObject, "programs");
return false;
}
const auto programObject = programValue.toObject();
const auto name = programObject.value("name").toString();
if (name.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "name");
return false;
}
qDebug() << "";
qDebug().noquote() << "Process" << name;
const auto shadersArray = programObject.value("shaders");
if (!shadersArray.isArray())
{
error(JsonParseError::ArrayNotFoundOrEmpty, "shaders");
return false;
}
const auto shaders = parseShaders(shadersArray.toArray(), ok);
if (!ok)
{
m_linkFailures.push_back(name.toStdString());
continue;
}
qDebug().noquote() << "Link" << name;
ok = createAndLinkProgram(shaders);
if (!ok)
m_linkFailures.push_back(name.toStdString());
}
return true;
}
std::vector<globjects::ref_ptr<globjects::Shader>> ShaderCompiler::parseShaders(
const QJsonArray & shadersArray,
bool & ok)
{
std::vector<globjects::ref_ptr<globjects::Shader>> shaders{};
for (const auto & shaderValue : shadersArray)
{
if (!shaderValue.isObject())
{
error(JsonParseError::ElementNotObject, "shaders");
ok = false;
return shaders;
}
const auto shaderObject = shaderValue.toObject();
const auto fileName = shaderObject.value("file").toString();
if (fileName.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "file");
ok = false;
return shaders;
}
const auto name = shaderObject.value("name").toString();
if (name.isNull())
qDebug().noquote() << QString{"Compile %1"}.arg(fileName);
else
qDebug().noquote() << QString{"Compile %1 ('%2')"}.arg(name).arg(fileName);
const auto typeString = shaderObject.value("type").toString();
if (typeString.isNull())
{
error(JsonParseError::PropertyNotFoundOrWrongFormat, "type");
ok = false;
return shaders;
}
const auto type = typeFromString(typeString);
if (type == gl::GL_NONE)
{
error(JsonParseError::ShaderTypeNotFound, typeString);
ok = false;
return shaders;
}
globjects::ref_ptr<globjects::AbstractStringSource> shaderFile = new globjects::File{fileName.toStdString()};
const auto replacementsValue = shaderObject.value("replacements");
if (!replacementsValue.isUndefined())
{
if (replacementsValue.isObject())
{
if (!replaceStrings(replacementsValue.toObject(), shaderFile))
{
ok = false;
return shaders;
}
}
else
{
error(JsonParseError::PropertyWrongFormat, "replacements");
ok = false;
return shaders;
}
}
auto shader = globjects::make_ref<globjects::Shader>(type, shaderFile);
if (!shader->compile())
{
m_compileFailures.push_back(fileName.toStdString());
ok = false;
return shaders;
}
shaders.push_back(globjects::ref_ptr<globjects::Shader>(shader));
}
ok = true;
return shaders;
}
bool ShaderCompiler::replaceStrings(
const QJsonObject & replacements,
globjects::ref_ptr<globjects::AbstractStringSource> & stringSource)
{
auto sourceTemplate = globjects::make_ref<globjects::StringTemplate>(stringSource);
for (auto it = replacements.begin(); it != replacements.end(); ++it)
{
const auto valueString = it.value().toString();
if (valueString.isNull())
{
error(JsonParseError::PropertyWrongFormat, it.key());
return false;
}
sourceTemplate->replace(it.key().toStdString(), valueString.toStdString());
}
stringSource = sourceTemplate;
return true;
}
gl::GLenum ShaderCompiler::typeFromString(const QString & typeString)
{
if (typeString == "GL_VERTEX_SHADER")
{
return gl::GL_VERTEX_SHADER;
}
else if (typeString == "GL_VERTEX_SHADER")
{
return gl::GL_TESS_CONTROL_SHADER;
}
else if (typeString == "GL_TESS_EVALUATION_SHADER")
{
return gl::GL_TESS_EVALUATION_SHADER;
}
else if (typeString == "GL_GEOMETRY_SHADER")
{
return gl::GL_GEOMETRY_SHADER;
}
else if (typeString == "GL_FRAGMENT_SHADER")
{
return gl::GL_FRAGMENT_SHADER;
}
else if (typeString == "GL_COMPUTE_SHADER")
{
return gl::GL_COMPUTE_SHADER;
}
return gl::GL_NONE;
}
bool ShaderCompiler::createAndLinkProgram(
const std::vector<globjects::ref_ptr<globjects::Shader>> & shaders)
{
auto program = globjects::make_ref<globjects::Program>();
for (auto & shader : shaders)
program->attach(shader);
program->link();
if (!program->isLinked())
return false;
return true;
}
void ShaderCompiler::info(Info type)
{
if (type == Info::Driver)
{
globjects::info() << "Driver: " << globjects::vendor();
globjects::info() << "Renderer: " << globjects::renderer();
}
else if (type == Info::Failures)
{
if (!m_compileFailures.empty())
{
globjects::info();
globjects::info() << "Compile Failures:";
for (const auto failure : m_compileFailures)
globjects::info() << " " << failure;
}
if (!m_linkFailures.empty())
{
globjects::info();
globjects::info() << "Link Failures:";
for (const auto failure : m_linkFailures)
globjects::info() << " " << failure;
}
}
}
void ShaderCompiler::error(JsonParseError error)
{
m_errorLog.error(error);
}
void ShaderCompiler::error(JsonParseError::Type type, const QString & info)
{
m_errorLog.error({ type, info });
}
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 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/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "server.h"
#include "../Interface/Server.h"
#include "../Interface/Database.h"
#include "../Interface/ThreadPool.h"
#include "server_get.h"
#include "database.h"
#include "../Interface/SettingsReader.h"
#include "server_status.h"
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include "InternetServiceConnector.h"
#include "../Interface/PipeThrottler.h"
#include <memory.h>
const unsigned int waittime=50*1000; //1 min
const int max_offline=5;
IPipeThrottler *BackupServer::global_internet_throttler=NULL;
IPipeThrottler *BackupServer::global_local_throttler=NULL;
IMutex *BackupServer::throttle_mutex=NULL;
BackupServer::BackupServer(IPipe *pExitpipe)
{
throttle_mutex=Server->createMutex();
exitpipe=pExitpipe;
if(Server->getServerParameter("internet_test_mode")=="true")
internet_test_mode=true;
else
internet_test_mode=false;
}
BackupServer::~BackupServer()
{
Server->destroy(throttle_mutex);
}
void BackupServer::operator()(void)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER);
ISettingsReader *settings=Server->createDBSettingsReader(Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER), "settings_db.settings");
#ifdef _WIN32
std::wstring tmpdir;
if(settings->getValue(L"tmpdir", &tmpdir) && !tmpdir.empty())
{
os_remove_nonempty_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
if(!os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp"))
{
Server->wait(5000);
os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
}
Server->setTemporaryDirectory(tmpdir+os_file_sep()+L"urbackup_tmp");
}
else
{
wchar_t tmpp[MAX_PATH];
DWORD l;
if((l=GetTempPathW(MAX_PATH, tmpp))==0 || l>MAX_PATH )
{
wcscpy_s(tmpp,L"C:\\");
}
std::wstring w_tmp=tmpp;
if(!w_tmp.empty() && w_tmp[w_tmp.size()-1]=='\\')
{
w_tmp.erase(w_tmp.size()-1, 1); }
os_remove_nonempty_dir(w_tmp+os_file_sep()+L"urbackup_tmp");
if(!os_create_dir(w_tmp+os_file_sep()+L"urbackup_tmp"))
{
Server->wait(5000);
os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
}
Server->setTemporaryDirectory(w_tmp+os_file_sep()+L"urbackup_tmp");
}
#endif
q_get_extra_hostnames=db->Prepare("SELECT id,hostname FROM settings_db.extra_clients");
q_update_extra_ip=db->Prepare("UPDATE settings_db.extra_clients SET lastip=? WHERE id=?");
FileClient fc;
Server->wait(1000);
while(true)
{
findClients(fc);
startClients(fc);
if(!ServerStatus::isActive() && settings->getValue("autoshutdown", "false")=="true")
{
writestring("true", "urbackup/shutdown_now");
#ifdef _WIN32
ExitWindowsEx(EWX_POWEROFF|EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_APPLICATION|SHTDN_REASON_MINOR_OTHER );
#endif
}
std::string r;
exitpipe->Read(&r, waittime);
if(r=="exit")
{
removeAllClients();
exitpipe->Write("ok");
Server->destroy(settings);
db->destroyAllQueries();
delete this;
return;
}
}
}
void BackupServer::findClients(FileClient &fc)
{
db_results res=q_get_extra_hostnames->Read();
q_get_extra_hostnames->Reset();
std::vector<in_addr> addr_hints;
for(size_t i=0;i<res.size();++i)
{
unsigned int dest;
bool b=os_lookuphostname(Server->ConvertToUTF8(res[i][L"hostname"]), &dest);
if(b)
{
q_update_extra_ip->Bind((_i64)dest);
q_update_extra_ip->Bind(res[i][L"id"]);
q_update_extra_ip->Write();
q_update_extra_ip->Reset();
in_addr tmp;
tmp.s_addr=dest;
addr_hints.push_back(tmp);
}
}
_u32 rc=fc.GetServers(true, addr_hints);
while(rc==ERR_CONTINUE)
{
Server->wait(50);
rc=fc.GetServers(false, addr_hints);
}
if(rc==ERR_ERROR)
{
Server->Log("Error in BackupServer::findClients rc==ERR_ERROR",LL_ERROR);
}
}
void BackupServer::startClients(FileClient &fc)
{
std::vector<std::wstring> names;
std::vector<sockaddr_in> servers;
if(!internet_test_mode)
{
names=fc.getServerNames();
servers=fc.getServers();
}
std::vector<bool> inetclient;
inetclient.resize(names.size());
std::fill(inetclient.begin(), inetclient.end(), false);
std::vector<std::string> anames=InternetServiceConnector::getOnlineClients();
for(size_t i=0;i<anames.size();++i)
{
names.push_back(Server->ConvertToUnicode(anames[i]));
inetclient.push_back(true);
sockaddr_in n;
memset(&n, 0, sizeof(sockaddr_in));
servers.push_back(n);
}
for(size_t i=0;i<names.size();++i)
{
names[i]=Server->ConvertToUnicode(conv_filename(Server->ConvertToUTF8(names[i])));
std::map<std::wstring, SClient>::iterator it=clients.find(names[i]);
if( it==clients.end() )
{
if(inetclient[i]==true)
{
bool skip=false;
for(size_t j=0;j<names.size();++j)
{
if(i!=j && names[i]==names[j] && inetclient[j]==false)
{
skip=true;
break;
}
}
if(skip)
continue;
}
Server->Log(L"New Backupclient: "+names[i]);
ServerStatus::setOnline(names[i], true);
IPipe *np=Server->createMemoryPipe();
BackupServerGet *client=new BackupServerGet(np, servers[i], names[i], inetclient[i]);
Server->getThreadPool()->execute(client);
SClient c;
c.pipe=np;
c.offlinecount=0;
c.addr=servers[i];
c.internet_connection=inetclient[i];
ServerStatus::setIP(names[i], c.addr.sin_addr.s_addr);
clients.insert(std::pair<std::wstring, SClient>(names[i], c) );
}
else if(it->second.offlinecount<max_offline)
{
bool found_lan=false;
if(inetclient[i]==false && it->second.internet_connection==true)
{
found_lan=true;
}
if(it->second.addr.sin_addr.s_addr==servers[i].sin_addr.s_addr && !found_lan)
{
it->second.offlinecount=0;
}
else
{
bool none_fits=true;
for(size_t j=0;j<names.size();++j)
{
if(i!=j && names[j]==names[i] && it->second.addr.sin_addr.s_addr==servers[j].sin_addr.s_addr)
{
none_fits=false;
break;
}
}
if(none_fits || found_lan)
{
it->second.addr=servers[i];
std::string msg;
msg.resize(7+sizeof(sockaddr_in)+1);
msg[0]='a'; msg[1]='d'; msg[2]='d'; msg[3]='r'; msg[4]='e'; msg[5]='s'; msg[6]='s';
memcpy(&msg[7], &it->second.addr, sizeof(sockaddr_in));
msg[7+sizeof(sockaddr_in)]=(inetclient[i]==true?1:0);
it->second.pipe->Write(msg);
char *ip=(char*)&it->second.addr.sin_addr.s_addr;
Server->Log("New client address: "+nconvert((unsigned char)ip[0])+"."+nconvert((unsigned char)ip[1])+"."+nconvert((unsigned char)ip[2])+"."+nconvert((unsigned char)ip[3]), LL_INFO);
ServerStatus::setIP(names[i], it->second.addr.sin_addr.s_addr);
it->second.offlinecount=0;
}
}
}
}
bool c=true;
size_t maxi=0;
while(c && !clients.empty())
{
c=false;
size_t i_c=0;
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
bool found=false;
for(size_t i=0;i<names.size();++i)
{
if( it->first==names[i] )
{
found=true;
break;
}
}
if( found==false || it->second.offlinecount>max_offline)
{
if(it->second.offlinecount==max_offline)
{
Server->Log(L"Client exitet: "+it->first);
it->second.pipe->Write("exit");
++it->second.offlinecount;
ServerStatus::setOnline(it->first, false);
}
else if(it->second.offlinecount>max_offline)
{
std::string msg;
std::vector<std::string> msgs;
while(it->second.pipe->Read(&msg,0)>0)
{
if(msg!="ok")
{
msgs.push_back(msg);
}
else
{
Server->Log(L"Client finished: "+it->first);
ServerStatus::setDone(it->first, true);
Server->destroy(it->second.pipe);
clients.erase(it);
maxi=i_c;
c=true;
break;
}
}
if( c==false )
{
for(size_t i=0;i<msgs.size();++i)
{
it->second.pipe->Write(msgs[i]);
}
}
else
{
break;
}
}
else if(i_c>=maxi)
{
SStatusAction s_action=ServerStatus::getStatus(it->first).statusaction;
if(s_action==sa_none)
{
++it->second.offlinecount;
}
}
}
++i_c;
}
}
}
void BackupServer::removeAllClients(void)
{
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
it->second.pipe->Write("exitnow");
std::string msg;
while(msg!="ok")
{
it->second.pipe->Read(&msg);
it->second.pipe->Write(msg.c_str());
Server->wait(500);
}
Server->destroy(it->second.pipe);
}
}
IPipeThrottler *BackupServer::getGlobalInternetThrottler(size_t speed_bps)
{
IScopedLock lock(throttle_mutex);
if(global_internet_throttler==NULL && speed_bps==0 )
return NULL;
if(global_internet_throttler==NULL)
{
global_internet_throttler=Server->createPipeThrottler(speed_bps);
}
else
{
global_internet_throttler->changeThrottleLimit(speed_bps);
}
return global_internet_throttler;
}
IPipeThrottler *BackupServer::getGlobalLocalThrottler(size_t speed_bps)
{
IScopedLock lock(throttle_mutex);
if(global_local_throttler==NULL && speed_bps==0 )
return NULL;
if(global_local_throttler==NULL)
{
global_local_throttler=Server->createPipeThrottler(speed_bps);
}
else
{
global_local_throttler->changeThrottleLimit(speed_bps);
}
return global_local_throttler;
}
void BackupServer::cleanupThrottlers(void)
{
if(global_internet_throttler!=NULL)
{
Server->destroy(global_internet_throttler);
}
if(global_local_throttler!=NULL)
{
Server->destroy(global_local_throttler);
}
}
#endif //CLIENT_ONLY
<commit_msg>Correctly skip internet connections if the client is available locally<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 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/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "server.h"
#include "../Interface/Server.h"
#include "../Interface/Database.h"
#include "../Interface/ThreadPool.h"
#include "server_get.h"
#include "database.h"
#include "../Interface/SettingsReader.h"
#include "server_status.h"
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include "InternetServiceConnector.h"
#include "../Interface/PipeThrottler.h"
#include <memory.h>
const unsigned int waittime=50*1000; //1 min
const int max_offline=5;
IPipeThrottler *BackupServer::global_internet_throttler=NULL;
IPipeThrottler *BackupServer::global_local_throttler=NULL;
IMutex *BackupServer::throttle_mutex=NULL;
BackupServer::BackupServer(IPipe *pExitpipe)
{
throttle_mutex=Server->createMutex();
exitpipe=pExitpipe;
if(Server->getServerParameter("internet_test_mode")=="true")
internet_test_mode=true;
else
internet_test_mode=false;
}
BackupServer::~BackupServer()
{
Server->destroy(throttle_mutex);
}
void BackupServer::operator()(void)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER);
ISettingsReader *settings=Server->createDBSettingsReader(Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER), "settings_db.settings");
#ifdef _WIN32
std::wstring tmpdir;
if(settings->getValue(L"tmpdir", &tmpdir) && !tmpdir.empty())
{
os_remove_nonempty_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
if(!os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp"))
{
Server->wait(5000);
os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
}
Server->setTemporaryDirectory(tmpdir+os_file_sep()+L"urbackup_tmp");
}
else
{
wchar_t tmpp[MAX_PATH];
DWORD l;
if((l=GetTempPathW(MAX_PATH, tmpp))==0 || l>MAX_PATH )
{
wcscpy_s(tmpp,L"C:\\");
}
std::wstring w_tmp=tmpp;
if(!w_tmp.empty() && w_tmp[w_tmp.size()-1]=='\\')
{
w_tmp.erase(w_tmp.size()-1, 1); }
os_remove_nonempty_dir(w_tmp+os_file_sep()+L"urbackup_tmp");
if(!os_create_dir(w_tmp+os_file_sep()+L"urbackup_tmp"))
{
Server->wait(5000);
os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
}
Server->setTemporaryDirectory(w_tmp+os_file_sep()+L"urbackup_tmp");
}
#endif
q_get_extra_hostnames=db->Prepare("SELECT id,hostname FROM settings_db.extra_clients");
q_update_extra_ip=db->Prepare("UPDATE settings_db.extra_clients SET lastip=? WHERE id=?");
FileClient fc;
Server->wait(1000);
while(true)
{
findClients(fc);
startClients(fc);
if(!ServerStatus::isActive() && settings->getValue("autoshutdown", "false")=="true")
{
writestring("true", "urbackup/shutdown_now");
#ifdef _WIN32
ExitWindowsEx(EWX_POWEROFF|EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_APPLICATION|SHTDN_REASON_MINOR_OTHER );
#endif
}
std::string r;
exitpipe->Read(&r, waittime);
if(r=="exit")
{
removeAllClients();
exitpipe->Write("ok");
Server->destroy(settings);
db->destroyAllQueries();
delete this;
return;
}
}
}
void BackupServer::findClients(FileClient &fc)
{
db_results res=q_get_extra_hostnames->Read();
q_get_extra_hostnames->Reset();
std::vector<in_addr> addr_hints;
for(size_t i=0;i<res.size();++i)
{
unsigned int dest;
bool b=os_lookuphostname(Server->ConvertToUTF8(res[i][L"hostname"]), &dest);
if(b)
{
q_update_extra_ip->Bind((_i64)dest);
q_update_extra_ip->Bind(res[i][L"id"]);
q_update_extra_ip->Write();
q_update_extra_ip->Reset();
in_addr tmp;
tmp.s_addr=dest;
addr_hints.push_back(tmp);
}
}
_u32 rc=fc.GetServers(true, addr_hints);
while(rc==ERR_CONTINUE)
{
Server->wait(50);
rc=fc.GetServers(false, addr_hints);
}
if(rc==ERR_ERROR)
{
Server->Log("Error in BackupServer::findClients rc==ERR_ERROR",LL_ERROR);
}
}
void BackupServer::startClients(FileClient &fc)
{
std::vector<std::wstring> names;
std::vector<sockaddr_in> servers;
if(!internet_test_mode)
{
names=fc.getServerNames();
servers=fc.getServers();
}
for(size_t i=0;i<names.size();++i)
{
names[i]=Server->ConvertToUnicode(conv_filename(Server->ConvertToUTF8(names[i])));
}
std::vector<bool> inetclient;
inetclient.resize(names.size());
std::fill(inetclient.begin(), inetclient.end(), false);
std::vector<std::string> anames=InternetServiceConnector::getOnlineClients();
for(size_t i=0;i<anames.size();++i)
{
std::wstring new_name=Server->ConvertToUnicode(conv_filename(anames[i]));
bool skip=false;
for(size_t j=0;j<names.size();++j)
{
if( new_name==names[j] )
{
skip=true;
break;
}
}
if(skip)
continue;
names.push_back(new_name);
inetclient.push_back(true);
sockaddr_in n;
memset(&n, 0, sizeof(sockaddr_in));
servers.push_back(n);
}
for(size_t i=0;i<names.size();++i)
{
std::map<std::wstring, SClient>::iterator it=clients.find(names[i]);
if( it==clients.end() )
{
Server->Log(L"New Backupclient: "+names[i]);
ServerStatus::setOnline(names[i], true);
IPipe *np=Server->createMemoryPipe();
BackupServerGet *client=new BackupServerGet(np, servers[i], names[i], inetclient[i]);
Server->getThreadPool()->execute(client);
SClient c;
c.pipe=np;
c.offlinecount=0;
c.addr=servers[i];
c.internet_connection=inetclient[i];
ServerStatus::setIP(names[i], c.addr.sin_addr.s_addr);
clients.insert(std::pair<std::wstring, SClient>(names[i], c) );
}
else if(it->second.offlinecount<max_offline)
{
bool found_lan=false;
if(inetclient[i]==false && it->second.internet_connection==true)
{
found_lan=true;
}
if(it->second.addr.sin_addr.s_addr==servers[i].sin_addr.s_addr && !found_lan)
{
it->second.offlinecount=0;
}
else
{
bool none_fits=true;
for(size_t j=0;j<names.size();++j)
{
if(i!=j && names[j]==names[i] && it->second.addr.sin_addr.s_addr==servers[j].sin_addr.s_addr)
{
none_fits=false;
break;
}
}
if(none_fits || found_lan)
{
it->second.addr=servers[i];
std::string msg;
msg.resize(7+sizeof(sockaddr_in)+1);
msg[0]='a'; msg[1]='d'; msg[2]='d'; msg[3]='r'; msg[4]='e'; msg[5]='s'; msg[6]='s';
memcpy(&msg[7], &it->second.addr, sizeof(sockaddr_in));
msg[7+sizeof(sockaddr_in)]=(inetclient[i]==true?1:0);
it->second.pipe->Write(msg);
char *ip=(char*)&it->second.addr.sin_addr.s_addr;
Server->Log("New client address: "+nconvert((unsigned char)ip[0])+"."+nconvert((unsigned char)ip[1])+"."+nconvert((unsigned char)ip[2])+"."+nconvert((unsigned char)ip[3]), LL_INFO);
ServerStatus::setIP(names[i], it->second.addr.sin_addr.s_addr);
it->second.offlinecount=0;
}
}
}
}
bool c=true;
size_t maxi=0;
while(c && !clients.empty())
{
c=false;
size_t i_c=0;
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
bool found=false;
for(size_t i=0;i<names.size();++i)
{
if( it->first==names[i] )
{
found=true;
break;
}
}
if( found==false || it->second.offlinecount>max_offline)
{
if(it->second.offlinecount==max_offline)
{
Server->Log(L"Client exitet: "+it->first);
it->second.pipe->Write("exit");
++it->second.offlinecount;
ServerStatus::setOnline(it->first, false);
}
else if(it->second.offlinecount>max_offline)
{
std::string msg;
std::vector<std::string> msgs;
while(it->second.pipe->Read(&msg,0)>0)
{
if(msg!="ok")
{
msgs.push_back(msg);
}
else
{
Server->Log(L"Client finished: "+it->first);
ServerStatus::setDone(it->first, true);
Server->destroy(it->second.pipe);
clients.erase(it);
maxi=i_c;
c=true;
break;
}
}
if( c==false )
{
for(size_t i=0;i<msgs.size();++i)
{
it->second.pipe->Write(msgs[i]);
}
}
else
{
break;
}
}
else if(i_c>=maxi)
{
SStatusAction s_action=ServerStatus::getStatus(it->first).statusaction;
if(s_action==sa_none)
{
++it->second.offlinecount;
}
}
}
++i_c;
}
}
}
void BackupServer::removeAllClients(void)
{
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
it->second.pipe->Write("exitnow");
std::string msg;
while(msg!="ok")
{
it->second.pipe->Read(&msg);
it->second.pipe->Write(msg.c_str());
Server->wait(500);
}
Server->destroy(it->second.pipe);
}
}
IPipeThrottler *BackupServer::getGlobalInternetThrottler(size_t speed_bps)
{
IScopedLock lock(throttle_mutex);
if(global_internet_throttler==NULL && speed_bps==0 )
return NULL;
if(global_internet_throttler==NULL)
{
global_internet_throttler=Server->createPipeThrottler(speed_bps);
}
else
{
global_internet_throttler->changeThrottleLimit(speed_bps);
}
return global_internet_throttler;
}
IPipeThrottler *BackupServer::getGlobalLocalThrottler(size_t speed_bps)
{
IScopedLock lock(throttle_mutex);
if(global_local_throttler==NULL && speed_bps==0 )
return NULL;
if(global_local_throttler==NULL)
{
global_local_throttler=Server->createPipeThrottler(speed_bps);
}
else
{
global_local_throttler->changeThrottleLimit(speed_bps);
}
return global_local_throttler;
}
void BackupServer::cleanupThrottlers(void)
{
if(global_internet_throttler!=NULL)
{
Server->destroy(global_internet_throttler);
}
if(global_local_throttler!=NULL)
{
Server->destroy(global_local_throttler);
}
}
#endif //CLIENT_ONLY
<|endoftext|> |
<commit_before>///
/// @file print.cpp
///
/// Copyright (C) 2019 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <print.hpp>
#include <primecount-internal.hpp>
#include <int128_t.hpp>
#include <stdint.h>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
namespace {
bool print_ = false;
bool print_variables_ = false;
bool is_print_variables()
{
return print_variables_;
}
} // naespace
namespace primecount {
void set_print(bool print)
{
#ifdef ENABLE_MPI
print_ = print && is_mpi_main_proc();
#else
print_ = print;
#endif
}
void set_print_variables(bool print_variables)
{
#ifdef ENABLE_MPI
print_variables_ = print_variables && is_mpi_main_proc();
#else
print_variables_ = print_variables;
#endif
}
bool is_print()
{
return print_;
}
/// The final combined result is always shown at
/// the end even if is_print = false. It is only
/// not shown for partial formulas.
///
bool is_print_combined_result()
{
#ifdef ENABLE_MPI
return !is_print_variables() && is_mpi_main_proc();
#else
return !is_print_variables();
#endif
}
void print_threads(int threads)
{
#ifdef ENABLE_MPI
cout << "processes = " << mpi_num_procs() << endl;
cout << "threads = " << mpi_num_procs() << " * " << threads << endl;
#else
cout << "threads = " << threads << endl;
#endif
}
void print_seconds(double seconds)
{
cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
}
void print(const string& str)
{
if (is_print())
cout << str << endl;
}
void print(const string& str, maxint_t res)
{
if (is_print())
cout << str << " = " << res << endl;
}
void print(const string& str, maxint_t res, double time)
{
if (is_print())
{
cout << "\r" << string(50,' ') << "\r";
cout << "Status: 100%" << endl;
cout << str << " = " << res << endl;
print_seconds(get_time() - time);
}
}
/// Used by pi_lmo(x), pi_deleglise_rivat(x)
void print(maxint_t x, int64_t y, int64_t z, int64_t c, int threads)
{
if (is_print())
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "c = " << c << endl;
cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
print_threads(threads);
}
}
/// Only enabled for partial formulas
void print_vars(maxint_t x, int64_t y, int threads)
{
if (is_print_variables())
{
maxint_t z = x / y;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
print_threads(threads);
cout << endl;
}
}
/// Only enabled for partial formulas
void print_vars(maxint_t x, int64_t y, int64_t c, int threads)
{
if (is_print_variables())
{
int64_t z = (int64_t)(x / y);
print(x, y, z, c, threads);
cout << endl;
}
}
/// Used by pi_gourdon(x)
void print_gourdon(maxint_t x, int64_t y, int64_t z, int64_t k, int threads)
{
if (is_print())
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "k = " << k << endl;
cout << "x_star = " << get_x_star_gourdon(x, y) << endl;
cout << "alpha_y = " << fixed << setprecision(3) << get_alpha_y(x, y) << endl;
cout << "alpha_z = " << fixed << setprecision(3) << get_alpha_z(y, z) << endl;
print_threads(threads);
}
}
/// Only enabled for partial formulas
void print_gourdon_vars(maxint_t x, int64_t y, int threads)
{
if (is_print_variables())
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "alpha_y = " << fixed << setprecision(3) << get_alpha_y(x, y) << endl;
print_threads(threads);
cout << endl;
}
}
/// Only enabled for partial formulas
void print_gourdon_vars(maxint_t x, int64_t y, int64_t z, int64_t k, int threads)
{
if (is_print_variables())
{
print_gourdon(x, y, z, k, threads);
cout << endl;
}
}
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file print.cpp
///
/// Copyright (C) 2020 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <print.hpp>
#include <primecount-internal.hpp>
#include <int128_t.hpp>
#include <stdint.h>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
namespace {
bool print_ = false;
bool print_variables_ = false;
bool is_print_variables()
{
return print_variables_;
}
void print_threads(int threads)
{
#ifdef ENABLE_MPI
using primecount::mpi_num_procs;
cout << "processes = " << mpi_num_procs() << endl;
cout << "threads = " << mpi_num_procs() << " * " << threads << endl;
#else
cout << "threads = " << threads << endl;
#endif
}
} // naespace
namespace primecount {
bool is_print()
{
return print_;
}
/// The final combined result is always shown at
/// the end even if is_print = false. It is only
/// not shown for partial formulas.
///
bool is_print_combined_result()
{
#ifdef ENABLE_MPI
return !is_print_variables() && is_mpi_main_proc();
#else
return !is_print_variables();
#endif
}
void set_print(bool print)
{
#ifdef ENABLE_MPI
print_ = print && is_mpi_main_proc();
#else
print_ = print;
#endif
}
void set_print_variables(bool print_variables)
{
#ifdef ENABLE_MPI
print_variables_ = print_variables && is_mpi_main_proc();
#else
print_variables_ = print_variables;
#endif
}
void print_seconds(double seconds)
{
cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
}
void print(const string& str)
{
if (is_print())
cout << str << endl;
}
void print(const string& str, maxint_t res)
{
if (is_print())
cout << str << " = " << res << endl;
}
void print(const string& str, maxint_t res, double time)
{
if (is_print())
{
cout << "\r" << string(50,' ') << "\r";
cout << "Status: 100%" << endl;
cout << str << " = " << res << endl;
print_seconds(get_time() - time);
}
}
/// Used by pi_lmo(x), pi_deleglise_rivat(x)
void print(maxint_t x, int64_t y, int64_t z, int64_t c, int threads)
{
if (is_print())
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "c = " << c << endl;
cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
print_threads(threads);
}
}
/// Only enabled for partial formulas
void print_vars(maxint_t x, int64_t y, int threads)
{
if (is_print_variables())
{
maxint_t z = x / y;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
print_threads(threads);
cout << endl;
}
}
/// Only enabled for partial formulas
void print_vars(maxint_t x, int64_t y, int64_t c, int threads)
{
if (is_print_variables())
{
int64_t z = (int64_t)(x / y);
print(x, y, z, c, threads);
cout << endl;
}
}
/// Used by pi_gourdon(x)
void print_gourdon(maxint_t x, int64_t y, int64_t z, int64_t k, int threads)
{
if (is_print())
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
cout << "k = " << k << endl;
cout << "x_star = " << get_x_star_gourdon(x, y) << endl;
cout << "alpha_y = " << fixed << setprecision(3) << get_alpha_y(x, y) << endl;
cout << "alpha_z = " << fixed << setprecision(3) << get_alpha_z(y, z) << endl;
print_threads(threads);
}
}
/// Only enabled for partial formulas
void print_gourdon_vars(maxint_t x, int64_t y, int threads)
{
if (is_print_variables())
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "alpha_y = " << fixed << setprecision(3) << get_alpha_y(x, y) << endl;
print_threads(threads);
cout << endl;
}
}
/// Only enabled for partial formulas
void print_gourdon_vars(maxint_t x, int64_t y, int64_t z, int64_t k, int threads)
{
if (is_print_variables())
{
print_gourdon(x, y, z, k, threads);
cout << endl;
}
}
} // namespace
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "qmlprojectrunconfiguration.h"
#include "qmlproject.h"
#include "qmlprojectmanagerconstants.h"
#include "qmlprojectrunconfigurationwidget.h"
#include <coreplugin/mimedatabase.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <qtsupport/qtprofileinformation.h>
#include <qtsupport/qtoutputformatter.h>
#include <qtsupport/qtsupportconstants.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
using Core::EditorManager;
using Core::ICore;
using Core::IEditor;
using namespace QmlProjectManager::Internal;
namespace QmlProjectManager {
const char * const M_CURRENT_FILE = "CurrentFile";
QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent) :
ProjectExplorer::RunConfiguration(parent, Core::Id(Constants::QML_RC_ID)),
m_scriptFile(M_CURRENT_FILE),
m_isEnabled(false)
{
ctor();
}
QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent,
QmlProjectRunConfiguration *source) :
ProjectExplorer::RunConfiguration(parent, source),
m_scriptFile(source->m_scriptFile),
m_qmlViewerArgs(source->m_qmlViewerArgs),
m_isEnabled(source->m_isEnabled),
m_userEnvironmentChanges(source->m_userEnvironmentChanges)
{
ctor();
}
bool QmlProjectRunConfiguration::isEnabled() const
{
return m_isEnabled;
}
QString QmlProjectRunConfiguration::disabledReason() const
{
if (!m_isEnabled)
return tr("No qmlviewer or qmlobserver found.");
return QString();
}
void QmlProjectRunConfiguration::ctor()
{
// reset default settings in constructor
debuggerAspect()->setUseCppDebugger(false);
debuggerAspect()->setUseQmlDebugger(true);
EditorManager *em = Core::EditorManager::instance();
connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(changeCurrentFile(Core::IEditor*)));
connect(target(), SIGNAL(profileChanged()),
this, SLOT(updateEnabled()));
setDisplayName(tr("QML Viewer", "QMLRunConfiguration display name."));
}
QmlProjectRunConfiguration::~QmlProjectRunConfiguration()
{
}
QString QmlProjectRunConfiguration::viewerPath() const
{
QtSupport::BaseQtVersion *version = qtVersion();
if (!version)
return QString();
else
return version->qmlviewerCommand();
}
QString QmlProjectRunConfiguration::observerPath() const
{
QtSupport::BaseQtVersion *version = qtVersion();
if (!version) {
return QString();
} else {
if (!version->needsQmlDebuggingLibrary())
return version->qmlviewerCommand();
return version->qmlObserverTool();
}
}
QString QmlProjectRunConfiguration::viewerArguments() const
{
// arguments in .user file
QString args = m_qmlViewerArgs;
// arguments from .qmlproject file
QmlProject *project = qobject_cast<QmlProject *>(target()->project());
if (!project)
return args;
foreach (const QString &importPath, project->importPaths()) {
Utils::QtcProcess::addArg(&args, "-I");
Utils::QtcProcess::addArg(&args, importPath);
}
QString s = mainScript();
if (!s.isEmpty()) {
s = canonicalCapsPath(s);
Utils::QtcProcess::addArg(&args, s);
}
return args;
}
QString QmlProjectRunConfiguration::workingDirectory() const
{
QFileInfo projectFile(target()->project()->document()->fileName());
return canonicalCapsPath(projectFile.absolutePath());
}
/* QtDeclarative checks explicitly that the capitalization for any URL / path
is exactly like the capitalization on disk.*/
QString QmlProjectRunConfiguration::canonicalCapsPath(const QString &fileName)
{
QString canonicalPath = QFileInfo(fileName).canonicalFilePath();
#if defined(Q_OS_WIN)
canonicalPath = Utils::normalizePathName(canonicalPath);
#endif
return canonicalPath;
}
QtSupport::BaseQtVersion *QmlProjectRunConfiguration::qtVersion() const
{
return QtSupport::QtProfileInformation::qtVersion(target()->profile());
}
QWidget *QmlProjectRunConfiguration::createConfigurationWidget()
{
QTC_ASSERT(m_configurationWidget.isNull(), return m_configurationWidget.data());
m_configurationWidget = new QmlProjectRunConfigurationWidget(this);
return m_configurationWidget.data();
}
Utils::OutputFormatter *QmlProjectRunConfiguration::createOutputFormatter() const
{
return new QtSupport::QtOutputFormatter(target()->project());
}
QmlProjectRunConfiguration::MainScriptSource QmlProjectRunConfiguration::mainScriptSource() const
{
QmlProject *project = qobject_cast<QmlProject *>(target()->project());
if (!project)
return FileInEditor;
if (!project->mainFile().isEmpty())
return FileInProjectFile;
if (!m_mainScriptFilename.isEmpty())
return FileInSettings;
return FileInEditor;
}
/**
Returns absolute path to main script file.
*/
QString QmlProjectRunConfiguration::mainScript() const
{
QmlProject *project = qobject_cast<QmlProject *>(target()->project());
if (!project)
return m_currentFileFilename;
if (!project->mainFile().isEmpty()) {
const QString pathInProject = project->mainFile();
if (QFileInfo(pathInProject).isAbsolute())
return pathInProject;
else
return project->projectDir().absoluteFilePath(pathInProject);
}
if (!m_mainScriptFilename.isEmpty())
return m_mainScriptFilename;
return m_currentFileFilename;
}
void QmlProjectRunConfiguration::setScriptSource(MainScriptSource source,
const QString &settingsPath)
{
if (source == FileInEditor) {
m_scriptFile = M_CURRENT_FILE;
m_mainScriptFilename.clear();
} else if (source == FileInProjectFile) {
m_scriptFile.clear();
m_mainScriptFilename.clear();
} else { // FileInSettings
m_scriptFile = settingsPath;
m_mainScriptFilename
= target()->project()->projectDirectory() + QLatin1Char('/') + m_scriptFile;
}
updateEnabled();
if (m_configurationWidget)
m_configurationWidget.data()->updateFileComboBox();
}
Utils::Environment QmlProjectRunConfiguration::environment() const
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
return env;
}
ProjectExplorer::Abi QmlProjectRunConfiguration::abi() const
{
ProjectExplorer::Abi hostAbi = ProjectExplorer::Abi::hostAbi();
return ProjectExplorer::Abi(hostAbi.architecture(), hostAbi.os(), hostAbi.osFlavor(),
ProjectExplorer::Abi::RuntimeQmlFormat, hostAbi.wordWidth());
}
QVariantMap QmlProjectRunConfiguration::toMap() const
{
QVariantMap map(ProjectExplorer::RunConfiguration::toMap());
map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs);
map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile);
map.insert(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY),
Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
return map;
}
bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)
{
m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();
m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(
map.value(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
if (m_scriptFile == M_CURRENT_FILE)
setScriptSource(FileInEditor);
else if (m_scriptFile.isEmpty())
setScriptSource(FileInProjectFile);
else
setScriptSource(FileInSettings, m_scriptFile);
return RunConfiguration::fromMap(map);
}
void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor)
{
if (editor)
m_currentFileFilename = editor->document()->fileName();
updateEnabled();
}
void QmlProjectRunConfiguration::updateEnabled()
{
bool qmlFileFound = false;
if (mainScriptSource() == FileInEditor) {
Core::IEditor *editor = Core::EditorManager::currentEditor();
Core::MimeDatabase *db = ICore::mimeDatabase();
if (editor) {
m_currentFileFilename = editor->document()->fileName();
if (db->findByFile(mainScript()).type() == QLatin1String("application/x-qml"))
qmlFileFound = true;
}
if (!editor
|| db->findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) {
// find a qml file with lowercase filename. This is slow, but only done
// in initialization/other border cases.
foreach (const QString &filename, target()->project()->files(ProjectExplorer::Project::AllFiles)) {
const QFileInfo fi(filename);
if (!filename.isEmpty() && fi.baseName()[0].isLower()
&& db->findByFile(fi).type() == QLatin1String("application/x-qml"))
{
m_currentFileFilename = filename;
qmlFileFound = true;
break;
}
}
}
} else { // use default one
qmlFileFound = !mainScript().isEmpty();
}
bool newValue = (QFileInfo(viewerPath()).exists()
|| QFileInfo(observerPath()).exists()) && qmlFileFound;
// Always emit change signal to force reevaluation of run/debug buttons
m_isEnabled = newValue;
emit enabledChanged();
}
bool QmlProjectRunConfiguration::isValidVersion(QtSupport::BaseQtVersion *version)
{
if (version
&& (version->type() == QtSupport::Constants::DESKTOPQT
|| version->type() == QtSupport::Constants::SIMULATORQT)
&& !version->qmlviewerCommand().isEmpty()) {
return true;
}
return false;
}
Utils::Environment QmlProjectRunConfiguration::baseEnvironment() const
{
Utils::Environment env;
if (qtVersion())
env = qtVersion()->qmlToolsEnvironment();
return env;
}
void QmlProjectRunConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges != diff) {
m_userEnvironmentChanges = diff;
if (m_configurationWidget)
m_configurationWidget.data()->userEnvironmentChangesChanged();
}
}
QList<Utils::EnvironmentItem> QmlProjectRunConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
} // namespace QmlProjectManager
<commit_msg>QmlProject: static_cast not qobject_cast<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "qmlprojectrunconfiguration.h"
#include "qmlproject.h"
#include "qmlprojectmanagerconstants.h"
#include "qmlprojectrunconfigurationwidget.h"
#include <coreplugin/mimedatabase.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <qtsupport/qtprofileinformation.h>
#include <qtsupport/qtoutputformatter.h>
#include <qtsupport/qtsupportconstants.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
using Core::EditorManager;
using Core::ICore;
using Core::IEditor;
using namespace QmlProjectManager::Internal;
namespace QmlProjectManager {
const char * const M_CURRENT_FILE = "CurrentFile";
QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent) :
ProjectExplorer::RunConfiguration(parent, Core::Id(Constants::QML_RC_ID)),
m_scriptFile(M_CURRENT_FILE),
m_isEnabled(false)
{
ctor();
}
QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent,
QmlProjectRunConfiguration *source) :
ProjectExplorer::RunConfiguration(parent, source),
m_scriptFile(source->m_scriptFile),
m_qmlViewerArgs(source->m_qmlViewerArgs),
m_isEnabled(source->m_isEnabled),
m_userEnvironmentChanges(source->m_userEnvironmentChanges)
{
ctor();
}
bool QmlProjectRunConfiguration::isEnabled() const
{
return m_isEnabled;
}
QString QmlProjectRunConfiguration::disabledReason() const
{
if (!m_isEnabled)
return tr("No qmlviewer or qmlobserver found.");
return QString();
}
void QmlProjectRunConfiguration::ctor()
{
// reset default settings in constructor
debuggerAspect()->setUseCppDebugger(false);
debuggerAspect()->setUseQmlDebugger(true);
EditorManager *em = Core::EditorManager::instance();
connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(changeCurrentFile(Core::IEditor*)));
connect(target(), SIGNAL(profileChanged()),
this, SLOT(updateEnabled()));
setDisplayName(tr("QML Viewer", "QMLRunConfiguration display name."));
}
QmlProjectRunConfiguration::~QmlProjectRunConfiguration()
{
}
QString QmlProjectRunConfiguration::viewerPath() const
{
QtSupport::BaseQtVersion *version = qtVersion();
if (!version)
return QString();
else
return version->qmlviewerCommand();
}
QString QmlProjectRunConfiguration::observerPath() const
{
QtSupport::BaseQtVersion *version = qtVersion();
if (!version) {
return QString();
} else {
if (!version->needsQmlDebuggingLibrary())
return version->qmlviewerCommand();
return version->qmlObserverTool();
}
}
QString QmlProjectRunConfiguration::viewerArguments() const
{
// arguments in .user file
QString args = m_qmlViewerArgs;
// arguments from .qmlproject file
QmlProject *project = static_cast<QmlProject *>(target()->project());
foreach (const QString &importPath, project->importPaths()) {
Utils::QtcProcess::addArg(&args, "-I");
Utils::QtcProcess::addArg(&args, importPath);
}
QString s = mainScript();
if (!s.isEmpty()) {
s = canonicalCapsPath(s);
Utils::QtcProcess::addArg(&args, s);
}
return args;
}
QString QmlProjectRunConfiguration::workingDirectory() const
{
QFileInfo projectFile(target()->project()->document()->fileName());
return canonicalCapsPath(projectFile.absolutePath());
}
/* QtDeclarative checks explicitly that the capitalization for any URL / path
is exactly like the capitalization on disk.*/
QString QmlProjectRunConfiguration::canonicalCapsPath(const QString &fileName)
{
QString canonicalPath = QFileInfo(fileName).canonicalFilePath();
#if defined(Q_OS_WIN)
canonicalPath = Utils::normalizePathName(canonicalPath);
#endif
return canonicalPath;
}
QtSupport::BaseQtVersion *QmlProjectRunConfiguration::qtVersion() const
{
return QtSupport::QtProfileInformation::qtVersion(target()->profile());
}
QWidget *QmlProjectRunConfiguration::createConfigurationWidget()
{
QTC_ASSERT(m_configurationWidget.isNull(), return m_configurationWidget.data());
m_configurationWidget = new QmlProjectRunConfigurationWidget(this);
return m_configurationWidget.data();
}
Utils::OutputFormatter *QmlProjectRunConfiguration::createOutputFormatter() const
{
return new QtSupport::QtOutputFormatter(target()->project());
}
QmlProjectRunConfiguration::MainScriptSource QmlProjectRunConfiguration::mainScriptSource() const
{
QmlProject *project = static_cast<QmlProject *>(target()->project());
if (!project->mainFile().isEmpty())
return FileInProjectFile;
if (!m_mainScriptFilename.isEmpty())
return FileInSettings;
return FileInEditor;
}
/**
Returns absolute path to main script file.
*/
QString QmlProjectRunConfiguration::mainScript() const
{
QmlProject *project = qobject_cast<QmlProject *>(target()->project());
if (!project)
return m_currentFileFilename;
if (!project->mainFile().isEmpty()) {
const QString pathInProject = project->mainFile();
if (QFileInfo(pathInProject).isAbsolute())
return pathInProject;
else
return project->projectDir().absoluteFilePath(pathInProject);
}
if (!m_mainScriptFilename.isEmpty())
return m_mainScriptFilename;
return m_currentFileFilename;
}
void QmlProjectRunConfiguration::setScriptSource(MainScriptSource source,
const QString &settingsPath)
{
if (source == FileInEditor) {
m_scriptFile = M_CURRENT_FILE;
m_mainScriptFilename.clear();
} else if (source == FileInProjectFile) {
m_scriptFile.clear();
m_mainScriptFilename.clear();
} else { // FileInSettings
m_scriptFile = settingsPath;
m_mainScriptFilename
= target()->project()->projectDirectory() + QLatin1Char('/') + m_scriptFile;
}
updateEnabled();
if (m_configurationWidget)
m_configurationWidget.data()->updateFileComboBox();
}
Utils::Environment QmlProjectRunConfiguration::environment() const
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
return env;
}
ProjectExplorer::Abi QmlProjectRunConfiguration::abi() const
{
ProjectExplorer::Abi hostAbi = ProjectExplorer::Abi::hostAbi();
return ProjectExplorer::Abi(hostAbi.architecture(), hostAbi.os(), hostAbi.osFlavor(),
ProjectExplorer::Abi::RuntimeQmlFormat, hostAbi.wordWidth());
}
QVariantMap QmlProjectRunConfiguration::toMap() const
{
QVariantMap map(ProjectExplorer::RunConfiguration::toMap());
map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs);
map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile);
map.insert(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY),
Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
return map;
}
bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)
{
m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();
m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(
map.value(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
if (m_scriptFile == M_CURRENT_FILE)
setScriptSource(FileInEditor);
else if (m_scriptFile.isEmpty())
setScriptSource(FileInProjectFile);
else
setScriptSource(FileInSettings, m_scriptFile);
return RunConfiguration::fromMap(map);
}
void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor)
{
if (editor)
m_currentFileFilename = editor->document()->fileName();
updateEnabled();
}
void QmlProjectRunConfiguration::updateEnabled()
{
bool qmlFileFound = false;
if (mainScriptSource() == FileInEditor) {
Core::IEditor *editor = Core::EditorManager::currentEditor();
Core::MimeDatabase *db = ICore::mimeDatabase();
if (editor) {
m_currentFileFilename = editor->document()->fileName();
if (db->findByFile(mainScript()).type() == QLatin1String("application/x-qml"))
qmlFileFound = true;
}
if (!editor
|| db->findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) {
// find a qml file with lowercase filename. This is slow, but only done
// in initialization/other border cases.
foreach (const QString &filename, target()->project()->files(ProjectExplorer::Project::AllFiles)) {
const QFileInfo fi(filename);
if (!filename.isEmpty() && fi.baseName()[0].isLower()
&& db->findByFile(fi).type() == QLatin1String("application/x-qml"))
{
m_currentFileFilename = filename;
qmlFileFound = true;
break;
}
}
}
} else { // use default one
qmlFileFound = !mainScript().isEmpty();
}
bool newValue = (QFileInfo(viewerPath()).exists()
|| QFileInfo(observerPath()).exists()) && qmlFileFound;
// Always emit change signal to force reevaluation of run/debug buttons
m_isEnabled = newValue;
emit enabledChanged();
}
bool QmlProjectRunConfiguration::isValidVersion(QtSupport::BaseQtVersion *version)
{
if (version
&& (version->type() == QtSupport::Constants::DESKTOPQT
|| version->type() == QtSupport::Constants::SIMULATORQT)
&& !version->qmlviewerCommand().isEmpty()) {
return true;
}
return false;
}
Utils::Environment QmlProjectRunConfiguration::baseEnvironment() const
{
Utils::Environment env;
if (qtVersion())
env = qtVersion()->qmlToolsEnvironment();
return env;
}
void QmlProjectRunConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges != diff) {
m_userEnvironmentChanges = diff;
if (m_configurationWidget)
m_configurationWidget.data()->userEnvironmentChangesChanged();
}
}
QList<Utils::EnvironmentItem> QmlProjectRunConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
} // namespace QmlProjectManager
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"
namespace net {
/* All verb handler identifiers */
enum class messaging_verb : int32_t {
MUTATION,
MUTATION_DONE,
BINARY, // Deprecated
READ_REPAIR,
READ,
REQUEST_RESPONSE, // client-initiated reads and writes
STREAM_INITIATE, // Deprecated
STREAM_INITIATE_DONE, // Deprecated
STREAM_REPLY, // Deprecated
STREAM_REQUEST, // Deprecated
RANGE_SLICE,
BOOTSTRAP_TOKEN, // Deprecated
TREE_REQUEST, // Deprecated
TREE_RESPONSE, // Deprecated
JOIN, // Deprecated
GOSSIP_DIGEST_SYN,
GOSSIP_DIGEST_ACK,
GOSSIP_DIGEST_ACK2,
DEFINITIONS_ANNOUNCE, // Deprecated
DEFINITIONS_UPDATE,
TRUNCATE,
SCHEMA_CHECK,
INDEX_SCAN, // Deprecated
REPLICATION_FINISHED,
INTERNAL_RESPONSE, // responses to internal calls
COUNTER_MUTATION,
STREAMING_REPAIR_REQUEST, // Deprecated
STREAMING_REPAIR_RESPONSE, // Deprecated
SNAPSHOT, // Similar to nt snapshot
MIGRATION_REQUEST,
GOSSIP_SHUTDOWN,
_TRACE,
ECHO,
REPAIR_MESSAGE,
PAXOS_PREPARE,
PAXOS_PROPOSE,
PAXOS_COMMIT,
PAGED_RANGE,
UNUSED_1,
UNUSED_2,
UNUSED_3,
};
} // namespace net
namespace std {
template <>
class hash<net::messaging_verb> {
public:
size_t operator()(const net::messaging_verb& x) const {
return hash<int32_t>()(int32_t(x));
}
};
} // namespace std
namespace net {
// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
// T object and should use placement new in case T is non POD
struct serializer {
// For integer type
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto v_ = net::hton(v);
return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
});
}
// For vectors
template<typename T>
inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
return operator()(out, v.size()).then([&out, &v, this] {
return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
return operator()(out, e);
});
});
}
template<typename T>
inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
using size_type = typename std::vector<T>::size_type;
return in.read_exactly(sizeof(size_type)).then([&v, &in, this] (temporary_buffer<char> buf) {
if (buf.size() != sizeof(size_type)) {
throw rpc::closed_error();
}
size_type c = net::ntoh(*reinterpret_cast<const net::packed<size_type>*>(buf.get()));
new (&v) std::vector<T>;
v.reserve(c);
union U {
U(){}
~U(){}
T v;
};
return do_until([c] () mutable {return !c--;}, [&v, &in, u = U(), this] () mutable {
return operator()(in, u.v).then([&u, &v] {
v.emplace_back(std::move(u.v));
});
});
});
}
// For messaging_verb
inline auto operator()(output_stream<char>& out, messaging_verb& v) {
bytes b(bytes::initialized_later(), sizeof(v));
auto _out = b.begin();
serialize_int32(_out, int32_t(v));
return out.write(reinterpret_cast<const char*>(b.c_str()), sizeof(v));
}
inline auto operator()(input_stream<char>& in, messaging_verb& v) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sizeof(v));
v = messaging_verb(read_simple<int32_t>(bv));
});
}
// For sstring
inline auto operator()(output_stream<char>& out, sstring& v) {
auto serialize_string_size = serialize_int16_size + v.size();
auto sz = serialize_int16_size + serialize_string_size;
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int16(_out, serialize_string_size);
serialize_string(_out, v);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
inline auto operator()(input_stream<char>& in, sstring& v) {
return in.read_exactly(serialize_int16_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int16_size) {
throw rpc::closed_error();
}
size_t serialize_string_size = net::ntoh(*reinterpret_cast<const net::packed<int16_t>*>(buf.get()));
return in.read_exactly(serialize_string_size).then([serialize_string_size, &v]
(temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_string_size) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), serialize_string_size);
new (&v) sstring(read_simple_short_string(bv));
return make_ready_future<>();
});
});
}
// For frozen_mutation
inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
db::frozen_mutation_serializer s(v);
uint32_t sz = s.size() + data_output::serialized_size(sz);
bytes b(bytes::initialized_later(), sz);
data_output o(b);
o.write<uint32_t>(sz - data_output::serialized_size(sz));
db::frozen_mutation_serializer::write(o, v);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
static auto sz = data_output::serialized_size<uint32_t>();
return in.read_exactly(sz).then([&v, &in] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
data_input i(bytes_view(reinterpret_cast<const int8_t*>(buf.get()), sz));
size_t msz = i.read<int32_t>();
return in.read_exactly(msz).then([&v, msz] (temporary_buffer<char> buf) {
if (buf.size() != msz) {
throw rpc::closed_error();
}
data_input i(bytes_view(reinterpret_cast<const int8_t*>(buf.get()), msz));
new (&v) frozen_mutation(db::frozen_mutation_serializer::read(i));
});
});
}
// For complex types which have serialize()/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
!std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto sz = serialize_int32_size + v.serialized_size();
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int32(_out, int32_t(sz - serialize_int32_size));
v.serialize(_out);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
!std::is_enum<T>::value, void*> = nullptr) {
return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int32_size) {
throw rpc::closed_error();
}
size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
new (&v) T(T::deserialize(bv));
return make_ready_future<>();
});
});
}
};
class messaging_service {
public:
struct shard_id {
gms::inet_address addr;
uint32_t cpu_id;
friend inline bool operator==(const shard_id& x, const shard_id& y) {
return x.addr == y.addr && x.cpu_id == y.cpu_id ;
}
friend inline bool operator<(const shard_id& x, const shard_id& y) {
if (x.addr < y.addr) {
return true;
} else if (y.addr < x.addr) {
return false;
} else {
return x.cpu_id < y.cpu_id;
}
}
friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
return os << x.addr << ":" << x.cpu_id;
}
struct hash {
size_t operator()(const shard_id& id) const {
return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
}
};
};
struct shard_info {
shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
: rpc_client(std::move(client)) {
}
std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
};
void foreach_client(std::function<void(const messaging_service::shard_id& id,
const messaging_service::shard_info& info)> f) const {
for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
f(i->first, i->second);
}
}
private:
static constexpr uint16_t _default_port = 7000;
gms::inet_address _listen_address;
uint16_t _port;
rpc::protocol<serializer, messaging_verb> _rpc;
rpc::protocol<serializer, messaging_verb>::server _server;
std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
public:
messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
: _listen_address(ip)
, _port(_default_port)
, _rpc(serializer{})
, _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
}
public:
uint16_t port() {
return _port;
}
auto listen_address() {
return _listen_address;
}
future<> stop() {
return make_ready_future<>();
}
static auto no_wait() {
return rpc::no_wait;
}
public:
// Register a handler (a callback lambda) for verb
template <typename Func>
void register_handler(messaging_verb verb, Func&& func) {
_rpc.register_handler(verb, std::move(func));
}
// Send a message for verb
template <typename MsgIn, typename... MsgOut>
auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
auto& rpc_client = get_rpc_client(id);
auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id] (auto&& f) {
try {
if (f.failed()) {
f.get();
assert(false); // never reached
}
return std::move(f);
} catch(...) {
// FIXME: we need to distinguish between a transport error and
// a server error.
// remove_rpc_client(id);
throw;
}
});
}
template <typename... MsgOut>
auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
}
private:
// Return rpc::protocol::client for a shard which is a ip + cpuid pair.
rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
auto it = _clients.find(id);
if (it == _clients.end()) {
auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
it = _clients.emplace(id, shard_info(std::move(client))).first;
return *it->second.rpc_client;
} else {
return *it->second.rpc_client;
}
}
void remove_rpc_client(shard_id id) {
_clients.erase(id);
}
};
extern distributed<messaging_service> _the_messaging_service;
inline distributed<messaging_service>& get_messaging_service() {
return _the_messaging_service;
}
inline messaging_service& get_local_messaging_service() {
return _the_messaging_service.local();
}
future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<commit_msg>Adding dropped messages counter to messaging_service<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
#include "db/config.hh"
#include "frozen_mutation.hh"
#include "db/serializer.hh"
namespace net {
/* All verb handler identifiers */
enum class messaging_verb : int32_t {
MUTATION,
MUTATION_DONE,
BINARY, // Deprecated
READ_REPAIR,
READ,
REQUEST_RESPONSE, // client-initiated reads and writes
STREAM_INITIATE, // Deprecated
STREAM_INITIATE_DONE, // Deprecated
STREAM_REPLY, // Deprecated
STREAM_REQUEST, // Deprecated
RANGE_SLICE,
BOOTSTRAP_TOKEN, // Deprecated
TREE_REQUEST, // Deprecated
TREE_RESPONSE, // Deprecated
JOIN, // Deprecated
GOSSIP_DIGEST_SYN,
GOSSIP_DIGEST_ACK,
GOSSIP_DIGEST_ACK2,
DEFINITIONS_ANNOUNCE, // Deprecated
DEFINITIONS_UPDATE,
TRUNCATE,
SCHEMA_CHECK,
INDEX_SCAN, // Deprecated
REPLICATION_FINISHED,
INTERNAL_RESPONSE, // responses to internal calls
COUNTER_MUTATION,
STREAMING_REPAIR_REQUEST, // Deprecated
STREAMING_REPAIR_RESPONSE, // Deprecated
SNAPSHOT, // Similar to nt snapshot
MIGRATION_REQUEST,
GOSSIP_SHUTDOWN,
_TRACE,
ECHO,
REPAIR_MESSAGE,
PAXOS_PREPARE,
PAXOS_PROPOSE,
PAXOS_COMMIT,
PAGED_RANGE,
UNUSED_1,
UNUSED_2,
UNUSED_3,
LAST,
};
} // namespace net
namespace std {
template <>
class hash<net::messaging_verb> {
public:
size_t operator()(const net::messaging_verb& x) const {
return hash<int32_t>()(int32_t(x));
}
};
} // namespace std
namespace net {
// NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized
// T object and should use placement new in case T is non POD
struct serializer {
// For integer type
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto v_ = net::hton(v);
return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
});
}
// For vectors
template<typename T>
inline auto operator()(output_stream<char>& out, std::vector<T>& v) {
return operator()(out, v.size()).then([&out, &v, this] {
return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {
return operator()(out, e);
});
});
}
template<typename T>
inline auto operator()(input_stream<char>& in, std::vector<T>& v) {
using size_type = typename std::vector<T>::size_type;
return in.read_exactly(sizeof(size_type)).then([&v, &in, this] (temporary_buffer<char> buf) {
if (buf.size() != sizeof(size_type)) {
throw rpc::closed_error();
}
size_type c = net::ntoh(*reinterpret_cast<const net::packed<size_type>*>(buf.get()));
new (&v) std::vector<T>;
v.reserve(c);
union U {
U(){}
~U(){}
T v;
};
return do_until([c] () mutable {return !c--;}, [&v, &in, u = U(), this] () mutable {
return operator()(in, u.v).then([&u, &v] {
v.emplace_back(std::move(u.v));
});
});
});
}
// For messaging_verb
inline auto operator()(output_stream<char>& out, messaging_verb& v) {
bytes b(bytes::initialized_later(), sizeof(v));
auto _out = b.begin();
serialize_int32(_out, int32_t(v));
return out.write(reinterpret_cast<const char*>(b.c_str()), sizeof(v));
}
inline auto operator()(input_stream<char>& in, messaging_verb& v) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sizeof(v));
v = messaging_verb(read_simple<int32_t>(bv));
});
}
// For sstring
inline auto operator()(output_stream<char>& out, sstring& v) {
auto serialize_string_size = serialize_int16_size + v.size();
auto sz = serialize_int16_size + serialize_string_size;
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int16(_out, serialize_string_size);
serialize_string(_out, v);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
inline auto operator()(input_stream<char>& in, sstring& v) {
return in.read_exactly(serialize_int16_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int16_size) {
throw rpc::closed_error();
}
size_t serialize_string_size = net::ntoh(*reinterpret_cast<const net::packed<int16_t>*>(buf.get()));
return in.read_exactly(serialize_string_size).then([serialize_string_size, &v]
(temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_string_size) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), serialize_string_size);
new (&v) sstring(read_simple_short_string(bv));
return make_ready_future<>();
});
});
}
// For frozen_mutation
inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {
db::frozen_mutation_serializer s(v);
uint32_t sz = s.size() + data_output::serialized_size(sz);
bytes b(bytes::initialized_later(), sz);
data_output o(b);
o.write<uint32_t>(sz - data_output::serialized_size(sz));
db::frozen_mutation_serializer::write(o, v);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
inline auto operator()(input_stream<char>& in, frozen_mutation& v) {
static auto sz = data_output::serialized_size<uint32_t>();
return in.read_exactly(sz).then([&v, &in] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
data_input i(bytes_view(reinterpret_cast<const int8_t*>(buf.get()), sz));
size_t msz = i.read<int32_t>();
return in.read_exactly(msz).then([&v, msz] (temporary_buffer<char> buf) {
if (buf.size() != msz) {
throw rpc::closed_error();
}
data_input i(bytes_view(reinterpret_cast<const int8_t*>(buf.get()), msz));
new (&v) frozen_mutation(db::frozen_mutation_serializer::read(i));
});
});
}
// For complex types which have serialize()/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
!std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto sz = serialize_int32_size + v.serialized_size();
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int32(_out, int32_t(sz - serialize_int32_size));
v.serialize(_out);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
!std::is_enum<T>::value, void*> = nullptr) {
return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int32_size) {
throw rpc::closed_error();
}
size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
new (&v) T(T::deserialize(bv));
return make_ready_future<>();
});
});
}
};
class messaging_service {
public:
struct shard_id {
gms::inet_address addr;
uint32_t cpu_id;
friend inline bool operator==(const shard_id& x, const shard_id& y) {
return x.addr == y.addr && x.cpu_id == y.cpu_id ;
}
friend inline bool operator<(const shard_id& x, const shard_id& y) {
if (x.addr < y.addr) {
return true;
} else if (y.addr < x.addr) {
return false;
} else {
return x.cpu_id < y.cpu_id;
}
}
friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
return os << x.addr << ":" << x.cpu_id;
}
struct hash {
size_t operator()(const shard_id& id) const {
return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
}
};
};
struct shard_info {
shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
: rpc_client(std::move(client)) {
}
std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
};
void foreach_client(std::function<void(const messaging_service::shard_id& id,
const messaging_service::shard_info& info)> f) const {
for (auto i = _clients.cbegin(); i != _clients.cend(); i++) {
f(i->first, i->second);
}
}
void increment_dropped_messages(messaging_verb verb) {
_dropped_messages[static_cast<int32_t>(verb)]++;
}
uint64_t get_dropped_messages(messaging_verb verb) const {
return _dropped_messages[static_cast<int32_t>(verb)];
}
const uint64_t* get_dropped_messages() const {
return _dropped_messages;
}
private:
static constexpr uint16_t _default_port = 7000;
gms::inet_address _listen_address;
uint16_t _port;
rpc::protocol<serializer, messaging_verb> _rpc;
rpc::protocol<serializer, messaging_verb>::server _server;
std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};
public:
messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
: _listen_address(ip)
, _port(_default_port)
, _rpc(serializer{})
, _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
}
public:
uint16_t port() {
return _port;
}
auto listen_address() {
return _listen_address;
}
future<> stop() {
return make_ready_future<>();
}
static auto no_wait() {
return rpc::no_wait;
}
public:
// Register a handler (a callback lambda) for verb
template <typename Func>
void register_handler(messaging_verb verb, Func&& func) {
_rpc.register_handler(verb, std::move(func));
}
// Send a message for verb
template <typename MsgIn, typename... MsgOut>
auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
auto& rpc_client = get_rpc_client(id);
auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {
try {
if (f.failed()) {
this->increment_dropped_messages(verb);
f.get();
assert(false); // never reached
}
return std::move(f);
} catch(...) {
// FIXME: we need to distinguish between a transport error and
// a server error.
// remove_rpc_client(id);
throw;
}
});
}
template <typename... MsgOut>
auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
}
private:
// Return rpc::protocol::client for a shard which is a ip + cpuid pair.
rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
auto it = _clients.find(id);
if (it == _clients.end()) {
auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
it = _clients.emplace(id, shard_info(std::move(client))).first;
return *it->second.rpc_client;
} else {
return *it->second.rpc_client;
}
}
void remove_rpc_client(shard_id id) {
_clients.erase(id);
}
};
extern distributed<messaging_service> _the_messaging_service;
inline distributed<messaging_service>& get_messaging_service() {
return _the_messaging_service;
}
inline messaging_service& get_local_messaging_service() {
return _the_messaging_service.local();
}
future<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);
} // namespace net
<|endoftext|> |
<commit_before>#include "scene_editor_gizmo_collection.h"
#include "gizmos/scripting/scripting_gizmo.h"
#include "gizmos/translate_gizmo.h"
#include "gizmos/selected_bounds_gizmo.h"
#include "gizmos/selection_box_gizmo.h"
#include "halley/core/graphics/camera.h"
using namespace Halley;
SceneEditorGizmoCollection::SceneEditorGizmoCollection(UIFactory& factory, Resources& resources, ISceneEditorWindow& sceneEditorWindow)
: factory(factory)
, resources(resources)
, sceneEditorWindow(sceneEditorWindow)
{
// TODO: read this elsewhere
snapRules.grid = GridSnapMode::Pixel;
snapRules.line = LineSnapMode::IsometricAxisAligned;
selectedBoundsGizmo = std::make_unique<SelectedBoundsGizmo>(snapRules, resources);
selectionBoxGizmo = std::make_unique<SelectionBoxGizmo>(snapRules, resources);
resetTools();
}
bool SceneEditorGizmoCollection::update(Time time, const Camera& camera, const ISceneEditor& sceneEditor, const SceneEditorInputState& inputState, SceneEditorOutputState& outputState)
{
selectedBoundsGizmo->setCamera(camera);
selectedBoundsGizmo->update(time, sceneEditor, inputState);
selectionBoxGizmo->setCamera(camera);
selectionBoxGizmo->update(time, sceneEditor, inputState);
if (activeGizmo) {
activeGizmo->setCamera(camera);
activeGizmo->setOutputState(&outputState);
activeGizmo->update(time, sceneEditor, inputState);
activeGizmo->setOutputState(nullptr);
return activeGizmo->isHighlighted();
}
return false;
}
void SceneEditorGizmoCollection::draw(Painter& painter)
{
selectedBoundsGizmo->draw(painter);
selectionBoxGizmo->draw(painter);
if (activeGizmo) {
activeGizmo->draw(painter);
}
}
void SceneEditorGizmoCollection::setSelectedEntity(const std::optional<EntityRef>& entity, EntityData& data)
{
selectedEntity = entity;
entityData = &data;
selectedBoundsGizmo->setSelectedEntity(entity, *entityData);
if (activeGizmo) {
activeGizmo->setSelectedEntity(entity, *entityData);
}
}
void SceneEditorGizmoCollection::refreshEntity()
{
selectedBoundsGizmo->refreshEntity();
if (activeGizmo) {
activeGizmo->refreshEntity();
}
}
void SceneEditorGizmoCollection::onEntityModified(const UUID& uuid, const EntityData& oldData, const EntityData& newData)
{
if (selectedEntity && selectedEntity->getInstanceUUID() == uuid) {
if (newData.getComponents().size() != oldData.getComponents().size()) {
refreshEntity();
}
}
}
std::shared_ptr<UIWidget> SceneEditorGizmoCollection::setTool(const String& tool, const String& componentName, const String& fieldName)
{
const bool changedTool = currentTool != tool;
currentTool = tool;
activeGizmo.reset();
const auto iter = gizmoFactories.find(tool);
if (iter != gizmoFactories.end()) {
if (iter->second) {
activeGizmo = iter->second(snapRules, componentName, fieldName);
}
} else {
activeGizmo.reset();
}
if (changedTool) {
sceneEditorWindow.setSetting(EditorSettingType::Temp, "tools.curTool", ConfigNode(tool));
sceneEditorWindow.setHighlightedComponents(activeGizmo ? activeGizmo->getHighlightedComponents() : std::vector<String>());
}
if (activeGizmo) {
activeGizmo->setSelectedEntity(selectedEntity, *entityData);
return activeGizmo->makeUI();
}
return {};
}
void SceneEditorGizmoCollection::deselect()
{
if (activeGizmo) {
activeGizmo->deselect();
}
}
void SceneEditorGizmoCollection::generateList(UIList& list)
{
const auto iconCol = factory.getColourScheme()->getColour("ui_text");
list.clear();
for (const auto& tool: tools) {
list.addImage(tool.id, std::make_shared<UIImage>(tool.icon.clone().setColour(iconCol)), 1, {}, UISizerAlignFlags::Centre)->setToolTip(tool.toolTip);
}
uiList = &list;
}
ISceneEditorWindow& SceneEditorGizmoCollection::getSceneEditorWindow()
{
return sceneEditorWindow;
}
bool SceneEditorGizmoCollection::onKeyPress(KeyboardKeyPress key, UIList& list)
{
for (const auto& t: tools) {
if (key == t.shortcut) {
list.setSelectedOptionId(t.id);
return true;
}
}
return false;
}
void SceneEditorGizmoCollection::addTool(const Tool& tool, GizmoFactory gizmoFactory)
{
tools.push_back(tool);
gizmoFactories[tool.id] = std::move(gizmoFactory);
}
void SceneEditorGizmoCollection::resetTools()
{
clear();
addTool(Tool("drag", LocalisedString::fromHardcodedString("Hand [H]"), Sprite().setImage(resources, "ui/scene_editor_drag.png"), KeyCode::H),
[this] (SnapRules snapRules, const String& componentName, const String& fieldName)
{
return std::unique_ptr<SceneEditorGizmo>{};
}
);
addTool(Tool("translate", LocalisedString::fromHardcodedString("Move [V]"), Sprite().setImage(resources, "ui/scene_editor_move.png"), KeyCode::V),
[this] (SnapRules snapRules, const String& componentName, const String& fieldName)
{
return std::make_unique<TranslateGizmo>(snapRules, factory, sceneEditorWindow);
}
);
addTool(Tool("scripting", LocalisedString::fromHardcodedString("Scripting [S]"), Sprite().setImage(resources, "ui/scene_editor_scripting.png"), KeyCode::S),
[this] (SnapRules snapRules, const String& componentName, const String& fieldName)
{
return std::make_unique<ScriptingGizmo>(snapRules, factory, sceneEditorWindow, sceneEditorWindow.getScriptNodeTypes());
}
);
}
void SceneEditorGizmoCollection::clear()
{
tools.clear();
gizmoFactories.clear();
if (uiList) {
uiList->clear();
uiList = nullptr;
}
}
<commit_msg>Fix crash when reloading DLL and one of the game-specific gizmos was selected<commit_after>#include "scene_editor_gizmo_collection.h"
#include "gizmos/scripting/scripting_gizmo.h"
#include "gizmos/translate_gizmo.h"
#include "gizmos/selected_bounds_gizmo.h"
#include "gizmos/selection_box_gizmo.h"
#include "halley/core/graphics/camera.h"
using namespace Halley;
SceneEditorGizmoCollection::SceneEditorGizmoCollection(UIFactory& factory, Resources& resources, ISceneEditorWindow& sceneEditorWindow)
: factory(factory)
, resources(resources)
, sceneEditorWindow(sceneEditorWindow)
{
// TODO: read this elsewhere
snapRules.grid = GridSnapMode::Pixel;
snapRules.line = LineSnapMode::IsometricAxisAligned;
selectedBoundsGizmo = std::make_unique<SelectedBoundsGizmo>(snapRules, resources);
selectionBoxGizmo = std::make_unique<SelectionBoxGizmo>(snapRules, resources);
resetTools();
}
bool SceneEditorGizmoCollection::update(Time time, const Camera& camera, const ISceneEditor& sceneEditor, const SceneEditorInputState& inputState, SceneEditorOutputState& outputState)
{
selectedBoundsGizmo->setCamera(camera);
selectedBoundsGizmo->update(time, sceneEditor, inputState);
selectionBoxGizmo->setCamera(camera);
selectionBoxGizmo->update(time, sceneEditor, inputState);
if (activeGizmo) {
activeGizmo->setCamera(camera);
activeGizmo->setOutputState(&outputState);
activeGizmo->update(time, sceneEditor, inputState);
activeGizmo->setOutputState(nullptr);
return activeGizmo->isHighlighted();
}
return false;
}
void SceneEditorGizmoCollection::draw(Painter& painter)
{
selectedBoundsGizmo->draw(painter);
selectionBoxGizmo->draw(painter);
if (activeGizmo) {
activeGizmo->draw(painter);
}
}
void SceneEditorGizmoCollection::setSelectedEntity(const std::optional<EntityRef>& entity, EntityData& data)
{
selectedEntity = entity;
entityData = &data;
selectedBoundsGizmo->setSelectedEntity(entity, *entityData);
if (activeGizmo) {
activeGizmo->setSelectedEntity(entity, *entityData);
}
}
void SceneEditorGizmoCollection::refreshEntity()
{
selectedBoundsGizmo->refreshEntity();
if (activeGizmo) {
activeGizmo->refreshEntity();
}
}
void SceneEditorGizmoCollection::onEntityModified(const UUID& uuid, const EntityData& oldData, const EntityData& newData)
{
if (selectedEntity && selectedEntity->getInstanceUUID() == uuid) {
if (newData.getComponents().size() != oldData.getComponents().size()) {
refreshEntity();
}
}
}
std::shared_ptr<UIWidget> SceneEditorGizmoCollection::setTool(const String& tool, const String& componentName, const String& fieldName)
{
const bool changedTool = currentTool != tool;
currentTool = tool;
activeGizmo.reset();
const auto iter = gizmoFactories.find(tool);
if (iter != gizmoFactories.end()) {
if (iter->second) {
activeGizmo = iter->second(snapRules, componentName, fieldName);
}
} else {
activeGizmo.reset();
}
if (changedTool) {
sceneEditorWindow.setSetting(EditorSettingType::Temp, "tools.curTool", ConfigNode(tool));
sceneEditorWindow.setHighlightedComponents(activeGizmo ? activeGizmo->getHighlightedComponents() : std::vector<String>());
}
if (activeGizmo) {
activeGizmo->setSelectedEntity(selectedEntity, *entityData);
return activeGizmo->makeUI();
}
return {};
}
void SceneEditorGizmoCollection::deselect()
{
if (activeGizmo) {
activeGizmo->deselect();
}
}
void SceneEditorGizmoCollection::generateList(UIList& list)
{
const auto iconCol = factory.getColourScheme()->getColour("ui_text");
list.clear();
for (const auto& tool: tools) {
list.addImage(tool.id, std::make_shared<UIImage>(tool.icon.clone().setColour(iconCol)), 1, {}, UISizerAlignFlags::Centre)->setToolTip(tool.toolTip);
}
uiList = &list;
}
ISceneEditorWindow& SceneEditorGizmoCollection::getSceneEditorWindow()
{
return sceneEditorWindow;
}
bool SceneEditorGizmoCollection::onKeyPress(KeyboardKeyPress key, UIList& list)
{
for (const auto& t: tools) {
if (key == t.shortcut) {
list.setSelectedOptionId(t.id);
return true;
}
}
return false;
}
void SceneEditorGizmoCollection::addTool(const Tool& tool, GizmoFactory gizmoFactory)
{
tools.push_back(tool);
gizmoFactories[tool.id] = std::move(gizmoFactory);
}
void SceneEditorGizmoCollection::resetTools()
{
clear();
addTool(Tool("drag", LocalisedString::fromHardcodedString("Hand [H]"), Sprite().setImage(resources, "ui/scene_editor_drag.png"), KeyCode::H),
[this] (SnapRules snapRules, const String& componentName, const String& fieldName)
{
return std::unique_ptr<SceneEditorGizmo>{};
}
);
addTool(Tool("translate", LocalisedString::fromHardcodedString("Move [V]"), Sprite().setImage(resources, "ui/scene_editor_move.png"), KeyCode::V),
[this] (SnapRules snapRules, const String& componentName, const String& fieldName)
{
return std::make_unique<TranslateGizmo>(snapRules, factory, sceneEditorWindow);
}
);
addTool(Tool("scripting", LocalisedString::fromHardcodedString("Scripting [S]"), Sprite().setImage(resources, "ui/scene_editor_scripting.png"), KeyCode::S),
[this] (SnapRules snapRules, const String& componentName, const String& fieldName)
{
return std::make_unique<ScriptingGizmo>(snapRules, factory, sceneEditorWindow, sceneEditorWindow.getScriptNodeTypes());
}
);
}
void SceneEditorGizmoCollection::clear()
{
tools.clear();
gizmoFactories.clear();
if (uiList) {
uiList->clear();
uiList = nullptr;
}
activeGizmo.reset();
}
<|endoftext|> |
<commit_before><commit_msg>Optimize debug line buffer resizing<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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 <math.h>
#include <votca/tools/histogramnew.h>
#include <votca/tools/tokenizer.h>
#include <votca/csg/csgapplication.h>
using namespace std;
using namespace votca::csg;
using namespace votca::tools;
class CsgDensityApp
: public CsgApplication
{
string ProgramName() { return "csg_density"; }
void HelpText(ostream &out) {
out << "Calculates the mass density distribution along a box axis or radial density profile from reference point";
}
// some program options are added here
void Initialize();
// we want to process a trajectory
bool DoTrajectory() {return true;}
bool DoMapping() {return true;}
bool DoMappingDefault(void) { return false; }
// write out results in EndEvaluate
void EndEvaluate();
void BeginEvaluate(Topology *top, Topology *top_atom);
void EvalConfiguration(Topology *top, Topology *top_ref);
bool EvaluateOptions() {
CsgApplication::EvaluateOptions();
CheckRequired("out", "no output topology specified");
CheckRequired("trj", "no trajectory file specified");
return true;
};
protected:
string _filter, _out;
HistogramNew _dist;
double _rmax;
int _nbin;
double _scale;
int _frames;
int _nblock;
int _block_length;
vec _ref;
vec _axis;
string _axisname;
string _molname;
double _area;
void WriteDensity(const string &suffix="");
};
int main(int argc, char** argv)
{
CsgDensityApp app;
return app.Exec(argc, argv);
}
void CsgDensityApp::BeginEvaluate(Topology *top, Topology *top_atom) {
matrix box = top->getBox();
vec a = box.getCol(0);
vec b = box.getCol(1);
vec c = box.getCol(2);
_dist.setPeriodic(true);
_axis=vec(0,0,0);
_area=0;
if(_axisname=="x") {
_axis.setX(1);
_rmax = abs(a);
_area= abs(b^c);
}
else if(_axisname=="y") {
_axis.setY(1);
_rmax = abs(b);
_area= abs(a^c);
}
else if(_axisname=="z") {
_axis.setZ(1);
_rmax = abs(c);
_area= abs(a^b);
}
else if(_axisname=="r") {
_dist.setPeriodic(false);
_rmax = min(min(abs(a/2), abs(b/2)), abs(c/2));
} else {
throw std::runtime_error("unknown axis type");
}
if(OptionsMap().count("rmax"))
_rmax = OptionsMap()["rmax"].as<double>();
if(OptionsMap().count("block-length")){
_block_length=OptionsMap()["block-length"].as<int>();
} else {
_block_length=0;
}
if (_axisname=="r") {
if(!OptionsMap().count("ref"))
_ref = a/2+b/2+c/2;
cout << "Using referece point: " << _ref << endl;
}
else if(OptionsMap().count("ref"))
throw std::runtime_error("reference center can only be used in case of spherical density");
_dist.Initialize(0, _rmax, _nbin);
cout << "rmax: " << _rmax << endl;
cout << "axis: " << _axisname << endl;
cout << "Bins: " << _nbin << endl;
_frames=0;
_nblock=0;
}
void CsgDensityApp::EvalConfiguration(Topology *top, Topology *top_ref)
{
// loop over all molecules
bool did_something = false;
for(MoleculeContainer::iterator imol=top->Molecules().begin(); imol!=top->Molecules().end(); ++imol) {
Molecule *mol = *imol;
if(!wildcmp(_molname.c_str(),mol->getName().c_str()))
continue;
int N = mol->BeadCount();
for(int i=0; i<N; i++) {
Bead *b = mol->getBead(i);
if(!wildcmp(_filter.c_str(), b->getName().c_str()))
continue;
double r;
if (_axisname=="r") {
r = abs(top->BCShortestConnection(_ref, b->getPos()));
} else {
r = b->getPos() * _axis;
}
_dist.Process(r, b->getM());
did_something = true;
}
}
_frames++;
if (!did_something) throw std::runtime_error("No molecule in selection");
if(_block_length != 0) {
if((_nframes % _block_length)==0) {
_nblock++;
string suffix = string("_") + boost::lexical_cast<string>(_nblock);
WriteDensity(suffix);
_dist.Clear();
}
}
}
// output everything when processing frames is done
void CsgDensityApp::WriteDensity(const string &suffix)
{
if (_axisname=="r") {
_dist.data().y() = _scale/(_frames*_rmax/(double)_nbin *4*M_PI) * element_div( _dist.data().y(),
element_prod(_dist.data().x(), _dist.data().x()));
} else {
_dist.data().y() = _scale/((double)_frames * _area * _rmax/ (double)_nbin ) *_dist.data().y();
}
_dist.data().Save(_out + suffix);
}
void CsgDensityApp::EndEvaluate()
{
if(_block_length == 0)
WriteDensity();
}
// add our user program options
void CsgDensityApp::Initialize()
{
CsgApplication::Initialize();
// add program option to pick molecule
AddProgramOptions("Specific options:")
("axis", boost::program_options::value<string>(&_axisname)->default_value("r"), "[x|y|z|r] density axis (r=spherical)")
("bins", boost::program_options::value<int>(&_nbin)->default_value(50), "bins")
("block-length", boost::program_options::value<int>(), " write blocks of this length, the averages are cleared after every write")
("out", boost::program_options::value<string>(&_out), "Output file")
("rmax", boost::program_options::value<double>(), "rmax (default for [r] =min of all box vectors/2, else l )")
("scale", boost::program_options::value<double>(&_scale)->default_value(1.0), "scale factor for the density")
("molname", boost::program_options::value<string>(&_molname)->default_value("*"), "molname")
("filter", boost::program_options::value<string>(&_filter)->default_value("*"), "filter bead names")
("ref", boost::program_options::value<vec>(&_ref), "reference zero point");
}
<commit_msg>csg_stat: fixed norm for block<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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 <math.h>
#include <votca/tools/histogramnew.h>
#include <votca/tools/tokenizer.h>
#include <votca/csg/csgapplication.h>
using namespace std;
using namespace votca::csg;
using namespace votca::tools;
class CsgDensityApp
: public CsgApplication
{
string ProgramName() { return "csg_density"; }
void HelpText(ostream &out) {
out << "Calculates the mass density distribution along a box axis or radial density profile from reference point";
}
// some program options are added here
void Initialize();
// we want to process a trajectory
bool DoTrajectory() {return true;}
bool DoMapping() {return true;}
bool DoMappingDefault(void) { return false; }
// write out results in EndEvaluate
void EndEvaluate();
void BeginEvaluate(Topology *top, Topology *top_atom);
void EvalConfiguration(Topology *top, Topology *top_ref);
bool EvaluateOptions() {
CsgApplication::EvaluateOptions();
CheckRequired("out", "no output topology specified");
CheckRequired("trj", "no trajectory file specified");
return true;
};
protected:
string _filter, _out;
HistogramNew _dist;
double _rmax;
int _nbin;
double _scale;
int _frames;
int _nblock;
int _block_length;
vec _ref;
vec _axis;
string _axisname;
string _molname;
double _area;
void WriteDensity(int nframes,const string &suffix="");
};
int main(int argc, char** argv)
{
CsgDensityApp app;
return app.Exec(argc, argv);
}
void CsgDensityApp::BeginEvaluate(Topology *top, Topology *top_atom) {
matrix box = top->getBox();
vec a = box.getCol(0);
vec b = box.getCol(1);
vec c = box.getCol(2);
_dist.setPeriodic(true);
_axis=vec(0,0,0);
_area=0;
if(_axisname=="x") {
_axis.setX(1);
_rmax = abs(a);
_area= abs(b^c);
}
else if(_axisname=="y") {
_axis.setY(1);
_rmax = abs(b);
_area= abs(a^c);
}
else if(_axisname=="z") {
_axis.setZ(1);
_rmax = abs(c);
_area= abs(a^b);
}
else if(_axisname=="r") {
_dist.setPeriodic(false);
_rmax = min(min(abs(a/2), abs(b/2)), abs(c/2));
} else {
throw std::runtime_error("unknown axis type");
}
if(OptionsMap().count("rmax"))
_rmax = OptionsMap()["rmax"].as<double>();
if(OptionsMap().count("block-length")){
_block_length=OptionsMap()["block-length"].as<int>();
} else {
_block_length=0;
}
if (_axisname=="r") {
if(!OptionsMap().count("ref"))
_ref = a/2+b/2+c/2;
cout << "Using referece point: " << _ref << endl;
}
else if(OptionsMap().count("ref"))
throw std::runtime_error("reference center can only be used in case of spherical density");
_dist.Initialize(0, _rmax, _nbin);
cout << "rmax: " << _rmax << endl;
cout << "axis: " << _axisname << endl;
cout << "Bins: " << _nbin << endl;
_frames=0;
_nblock=0;
}
void CsgDensityApp::EvalConfiguration(Topology *top, Topology *top_ref)
{
// loop over all molecules
bool did_something = false;
for(MoleculeContainer::iterator imol=top->Molecules().begin(); imol!=top->Molecules().end(); ++imol) {
Molecule *mol = *imol;
if(!wildcmp(_molname.c_str(),mol->getName().c_str()))
continue;
int N = mol->BeadCount();
for(int i=0; i<N; i++) {
Bead *b = mol->getBead(i);
if(!wildcmp(_filter.c_str(), b->getName().c_str()))
continue;
double r;
if (_axisname=="r") {
r = abs(top->BCShortestConnection(_ref, b->getPos()));
} else {
r = b->getPos() * _axis;
}
_dist.Process(r, b->getM());
did_something = true;
}
}
_frames++;
if (!did_something) throw std::runtime_error("No molecule in selection");
if(_block_length != 0) {
if((_nframes % _block_length)==0) {
_nblock++;
string suffix = string("_") + boost::lexical_cast<string>(_nblock);
WriteDensity(_block_length,suffix);
_dist.Clear();
}
}
}
// output everything when processing frames is done
void CsgDensityApp::WriteDensity(int nframes, const string &suffix)
{
if (_axisname=="r") {
_dist.data().y() = _scale/(nframes*_rmax/(double)_nbin *4*M_PI) * element_div( _dist.data().y(),
element_prod(_dist.data().x(), _dist.data().x()));
} else {
_dist.data().y() = _scale/((double)nframes * _area * _rmax/ (double)_nbin ) *_dist.data().y();
}
_dist.data().Save(_out + suffix);
}
void CsgDensityApp::EndEvaluate()
{
if(_block_length == 0)
WriteDensity(_frames);
}
// add our user program options
void CsgDensityApp::Initialize()
{
CsgApplication::Initialize();
// add program option to pick molecule
AddProgramOptions("Specific options:")
("axis", boost::program_options::value<string>(&_axisname)->default_value("r"), "[x|y|z|r] density axis (r=spherical)")
("bins", boost::program_options::value<int>(&_nbin)->default_value(50), "bins")
("block-length", boost::program_options::value<int>(), " write blocks of this length, the averages are cleared after every write")
("out", boost::program_options::value<string>(&_out), "Output file")
("rmax", boost::program_options::value<double>(), "rmax (default for [r] =min of all box vectors/2, else l )")
("scale", boost::program_options::value<double>(&_scale)->default_value(1.0), "scale factor for the density")
("molname", boost::program_options::value<string>(&_molname)->default_value("*"), "molname")
("filter", boost::program_options::value<string>(&_filter)->default_value("*"), "filter bead names")
("ref", boost::program_options::value<vec>(&_ref), "reference zero point");
}
<|endoftext|> |
<commit_before>class AliAnalysisGrid;
void RunAnalysisITS() {
//
// Macro to analyze ESDs from raw data reconstruction
// A.Dainese, [email protected]
//
//gSystem->Setenv("alien_CLOSE_SE","ALICE::CNAF::SE");
gSystem->SetIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -g");
//
TString analysisMode = "local"; // "local", "grid", or "proof" (not yet)
Long64_t nentries=1000000000000000,firstentry=0;
Bool_t useAlienPlugin=kFALSE;
Bool_t uselibPWG1=kTRUE;
TString pluginmode="full";
TString loadMacroPath="./";
Bool_t readHLT=kFALSE;
//
if(analysisMode=="grid") {
// Connect to AliEn
TGrid::Connect("alien://");
} else if(analysisMode=="proof") {
// Connect to the PROOF cluster
printf("PROOF mode not yet functional..\n");
return;
TProof::Open("alicecaf");
//TProof::Reset("alicecaf");
}
// Load analysis libraries
gSystem->Load("libANALYSIS.so");
gSystem->Load("libANALYSISalice.so");
if(uselibPWG1) {gSystem->Load("libTENDER.so"); gSystem->Load("libPWG1.so");}
// Create Alien plugin, if requested
if(useAlienPlugin) {
AliAnalysisGrid *alienHandler = CreateAlienHandler(pluginmode,uselibPWG1);
if(!alienHandler) return;
}
TChain *chainESD = 0;
if(!useAlienPlugin) {
// Prepare input chain
// chainESD = CreateESDChain("/home/dainesea/alignData/RAWdata_CosmicsSum09/RecoSPD/chunk.",13,13);
chainESD=new TChain("esdTree");
//chainESD->Add("alien:///alice/cern.ch/user/s/sitta/output/000088361/ESDs/pass1/09000088361017.10/AliESDs.root");
chainESD->Add("AliESDs.root");
}
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager");
// Enable debug printouts
mgr->SetDebugLevel(10);
// Connect plug-in to the analysis manager
if(useAlienPlugin) mgr->SetGridHandler(alienHandler);
// Add ESD handler
AliESDInputHandler *esdH = new AliESDInputHandler();
if(readHLT) esdH->SetReadHLT();
mgr->SetInputEventHandler(esdH);
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Analysis tasks (wagons of the train)
//
TString taskName;
if(!uselibPWG1) gROOT->LoadMacro("AliAlignmentDataFilterITS.cxx++g");
taskName="AddTaskAlignmentDataFilterITS.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliAlignmentDataFilterITS *itsTask = AddTaskAlignmentDataFilterITS();
if(!uselibPWG1) gROOT->LoadMacro("AliTrackMatchingTPCITSCosmics.cxx++g");
taskName="AddTaskTrackMatchingTPCITS.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliTrackMatchingTPCITSCosmics *tpcitsTask = AddTaskTrackMatchingTPCITS();
if(readHLT) tpcitsTask->SetReadHLTESD(kTRUE);
/*
Bool_t readMC=kTRUE;
if(!uselibPWG1) gROOT->LoadMacro("AliAnalysisTaskVertexESD.cxx++g");
taskName="AddTaskVertexESD.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliAnalysisTaskVertexESD *vtxTask = AddTaskVertexESD(readMC);
if(!uselibPWG1) gROOT->LoadMacro("AliAnalysisTaskITSTrackingCheck.cxx++g");
taskName="AddTaskPerformanceITS.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliAnalysisTaskITSTrackingCheck *itsTask = AddTaskPerformanceITS(readMC);
if(readMC) {
AliMCEventHandler *mcH = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mcH);
}
*/
//
// Run the analysis
//
if(chainESD) printf("CHAIN HAS %d ENTRIES\n",(Int_t)chainESD->GetEntries());
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
if(analysisMode=="grid" && !useAlienPlugin) analysisMode="local";
mgr->StartAnalysis(analysisMode.Data(),chainESD,nentries,firstentry);
return;
}
//_____________________________________________________________________________
//
AliAnalysisGrid* CreateAlienHandler(TString pluginmode="test",
Bool_t uselibPWG1=kFALSE)
{
// Check if user has a valid token, otherwise make one. This has limitations.
// One can always follow the standard procedure of calling alien-token-init then
// source /tmp/gclient_env_$UID in the current shell.
if (!AliAnalysisGrid::CreateToken()) return NULL;
AliAnalysisAlien *plugin = new AliAnalysisAlien();
// Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
plugin->SetRunMode(pluginmode.Data());
plugin->SetUser("dainesea");
plugin->SetNtestFiles(1);
// Set versions of used packages
plugin->SetAPIVersion("V2.4");
plugin->SetROOTVersion("v5-24-00");
plugin->SetAliROOTVersion("v4-18-07-AN");
// Declare input data to be processed.
// Method 1: Create automatically XML collections using alien 'find' command.
// Define production directory LFN
plugin->SetGridDataDir("/alice/data/2009/LHC09c");
//plugin->SetGridDataDir("/alice/cern.ch/user/s/sitta/output/000088361/");
// Set data search pattern
//plugin->SetDataPattern("AliESDs.root");
plugin->SetDataPattern("ESD.tag.root");
Int_t n=0;
n++; plugin->AddRunNumber("000080015");
n++; plugin->AddRunNumber("000080261");
plugin->SetNrunsPerMaster(n);
// Method 2: Declare existing data files (raw collections, xml collections, root file)
// If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
// XML collections added via this method can be combined with the first method if
// the content is compatible (using or not tags)
// e.g.: find -z -x 80015 /alice/data/2009/LHC09c/000080015/ESDs/ ESD.tag.root > 80015.xml
//plugin->AddDataFile("79876.xml");
//plugin->AddDataFile("80015.xml");
//plugin->AddDataFile("80261.xml");
// plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
// Define alien work directory where all files will be copied. Relative to alien $HOME.
plugin->SetGridWorkingDir("analysisITS");
// Declare alien output directory. Relative to working directory.
plugin->SetGridOutputDir("output151009"); // In this case will be $HOME/work/output
// Declare the analysis source files names separated by blancs. To be compiled runtime
// using ACLiC on the worker nodes.
if(!uselibPWG1) {
plugin->SetAnalysisSource("AliAlignmentDataFilterITS.cxx");
plugin->SetAnalysisSource("AliTrackMatchingTPCITSCosmics.cxx");
}
// Declare all libraries (other than the default ones for the framework. These will be
// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
//plugin->SetAdditionalLibs("AliAlignmentDataFilterITS.h AliAlignmentDataFilterITS.cxx libProof.so libRAWDatabase.so libRAWDatarec.so libCDB.so libSTEER.so libITSbase.so libITSrec.so");
plugin->AddIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -g");
if(!uselibPWG1) {
plugin->SetAdditionalLibs("AliAlignmentDataFilterITS.h AliAlignmentDataFilterITS.cxx AliTrackMatchingTPCITSCosmics.h AliTrackMatchingTPCITSCosmics.cxx libProof.so libRAWDatabase.so libRAWDatarec.so libCDB.so libSTEER.so libITSbase.so libITSrec.so");
} else {
plugin->SetAdditionalLibs("libGui.so libProof.so libMinuit.so libRAWDatabase.so libRAWDatarec.so libCDB.so libSTEER.so libITSbase.so libITSrec.so libTPCbase.so libTPCrec.so libTRDbase.so libTRDrec.so libTENDER.so libPWG1.so");
}
// Declare the output file names separated by blancs.
// (can be like: file.root or file.root@ALICE::Niham::File)
plugin->SetDefaultOutputs(kTRUE);
// Optionally define the files to be archived.
// plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:*.root@ALICE::NIHAM::File");
plugin->SetOutputArchive("log_archive.zip:stdout,stderr");
// Optionally set a name for the generated analysis macro (default MyAnalysis.C)
plugin->SetAnalysisMacro("AnalysisITS.C");
// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
plugin->SetSplitMaxInputFileNumber(1);
// Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
//plugin->SetMaxInitFailed(5);
// Optionally resubmit threshold.
//plugin->SetMasterResubmitThreshold(90);
// Optionally set time to live (default 30000 sec)
//plugin->SetTTL(20000);
// Optionally set input format (default xml-single)
plugin->SetInputFormat("xml-single");
// Optionally modify the name of the generated JDL (default analysis.jdl)
plugin->SetJDLName("TaskAnalysisITS.jdl");
// Optionally modify job price (default 1)
//plugin->SetPrice(1);
// Optionally modify split mode (default 'se')
plugin->SetSplitMode("se");
// Optionally set the preferred SE
plugin->SetPreferedSE("ALICE::CNAF::SE");
return plugin;
}
//-----------------------------------------------------------------------------
TChain *CreateESDChain(TString esdpath=".",Int_t ifirst=-1,Int_t ilast=-1) {
TChain *chainESD = new TChain("esdTree");
if(ifirst<0) {
chainESD->Add("AliESDs.root");
} else {
for(Int_t i=ifirst; i<=ilast; i++) {
TString esdfile=esdpath; esdfile+=i; esdfile.Append("/AliESDs.root");
chainESD->Add(esdfile.Data());
}
}
return chainESD;
}
<commit_msg>Add possbility to read also the RecPoints<commit_after>class AliAnalysisGrid;
void RunAnalysisITS() {
//
// Macro to analyze ESDs from raw data reconstruction
// A.Dainese, [email protected]
//
//gSystem->Setenv("alien_CLOSE_SE","ALICE::CNAF::SE");
gSystem->SetIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -g");
//
TString analysisMode = "local"; // "local", "grid", or "proof" (not yet)
Long64_t nentries=1000000000000000,firstentry=0;
Bool_t useAlienPlugin=kFALSE;
Bool_t uselibPWG1=kTRUE;
TString pluginmode="full";
TString loadMacroPath="./";
Bool_t readHLT=kFALSE;
//
if(analysisMode=="grid") {
// Connect to AliEn
TGrid::Connect("alien://");
} else if(analysisMode=="proof") {
// Connect to the PROOF cluster
printf("PROOF mode not yet functional..\n");
return;
TProof::Open("alicecaf");
//TProof::Reset("alicecaf");
}
// Load analysis libraries
gSystem->Load("libANALYSIS.so");
gSystem->Load("libANALYSISalice.so");
if(uselibPWG1) {gSystem->Load("libTENDER.so");gSystem->Load("libPWG1.so");}
// Create Alien plugin, if requested
if(useAlienPlugin) {
AliAnalysisGrid *alienHandler = CreateAlienHandler(pluginmode,uselibPWG1);
if(!alienHandler) return;
}
TChain *chainESD = 0;
if(!useAlienPlugin) {
// Prepare input chain
chainESD = CreateESDChain("/home/dainesea/alignEvents2/boxTRUNK280909_zero/event.",1,48);
//chainESD=new TChain("esdTree");
//chainESD->Add("alien:///alice/cern.ch/user/s/sitta/output/000088361/ESDs/pass1/09000088361017.10/AliESDs.root");
//chainESD->Add("./AliESDs.root");
}
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager");
// Enable debug printouts
mgr->SetDebugLevel(10);
// Connect plug-in to the analysis manager
if(useAlienPlugin) mgr->SetGridHandler(alienHandler);
//-------------------------------------------------------------------
// Add ESD handler
Bool_t readRP=kTRUE;
AliESDInputHandler *esdH = 0;
if(readRP) {
esdH = new AliESDInputHandlerRP();
} else {
esdH = new AliESDInputHandler();
}
if(readHLT) esdH->SetReadHLT();
mgr->SetInputEventHandler(esdH);
//-------------------------------------------------------------------
// Analysis tasks (wagons of the train)
//
TString taskName;
/*
if(!uselibPWG1) gROOT->LoadMacro("AliAlignmentDataFilterITS.cxx++g");
taskName="AddTaskAlignmentDataFilterITS.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliAlignmentDataFilterITS *itsTask = AddTaskAlignmentDataFilterITS();
if(!uselibPWG1) gROOT->LoadMacro("AliTrackMatchingTPCITSCosmics.cxx++g");
taskName="AddTaskTrackMatchingTPCITS.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliTrackMatchingTPCITSCosmics *tpcitsTask = AddTaskTrackMatchingTPCITS();
if(readHLT) tpcitsTask->SetReadHLTESD(kTRUE);
*/
Bool_t readMC=kTRUE;
if(!uselibPWG1) gROOT->LoadMacro("AliAnalysisTaskVertexESD.cxx++g");
taskName="AddTaskVertexESD.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
//AliAnalysisTaskVertexESD *vtxTask = AddTaskVertexESD(readMC);
if(!uselibPWG1) gROOT->LoadMacro("AliAnalysisTaskITSTrackingCheck.cxx++g");
taskName="AddTaskPerformanceITS.C";
taskName.Prepend(loadMacroPath.Data());
gROOT->LoadMacro(taskName.Data());
AliAnalysisTaskITSTrackingCheck *itsTask = AddTaskPerformanceITS(readMC,readRP);
if(readMC) {
AliMCEventHandler *mcH = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mcH);
}
//
// Run the analysis
//
if(chainESD) printf("CHAIN HAS %d ENTRIES\n",(Int_t)chainESD->GetEntries());
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
if(analysisMode=="grid" && !useAlienPlugin) analysisMode="local";
mgr->StartAnalysis(analysisMode.Data(),chainESD,nentries,firstentry);
return;
}
//_____________________________________________________________________________
//
AliAnalysisGrid* CreateAlienHandler(TString pluginmode="test",
Bool_t uselibPWG1=kFALSE)
{
// Check if user has a valid token, otherwise make one. This has limitations.
// One can always follow the standard procedure of calling alien-token-init then
// source /tmp/gclient_env_$UID in the current shell.
if (!AliAnalysisGrid::CreateToken()) return NULL;
AliAnalysisAlien *plugin = new AliAnalysisAlien();
// Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
plugin->SetRunMode(pluginmode.Data());
plugin->SetUser("dainesea");
plugin->SetNtestFiles(1);
// Set versions of used packages
plugin->SetAPIVersion("V2.4");
plugin->SetROOTVersion("v5-24-00");
plugin->SetAliROOTVersion("v4-18-07-AN");
// Declare input data to be processed.
// Method 1: Create automatically XML collections using alien 'find' command.
// Define production directory LFN
plugin->SetGridDataDir("/alice/data/2009/LHC09c");
//plugin->SetGridDataDir("/alice/cern.ch/user/s/sitta/output/000088361/");
// Set data search pattern
//plugin->SetDataPattern("AliESDs.root");
plugin->SetDataPattern("ESD.tag.root");
Int_t n=0;
n++; plugin->AddRunNumber("000080015");
n++; plugin->AddRunNumber("000080261");
plugin->SetNrunsPerMaster(n);
// Method 2: Declare existing data files (raw collections, xml collections, root file)
// If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
// XML collections added via this method can be combined with the first method if
// the content is compatible (using or not tags)
// e.g.: find -z -x 80015 /alice/data/2009/LHC09c/000080015/ESDs/ ESD.tag.root > 80015.xml
//plugin->AddDataFile("79876.xml");
//plugin->AddDataFile("80015.xml");
//plugin->AddDataFile("80261.xml");
// plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
// Define alien work directory where all files will be copied. Relative to alien $HOME.
plugin->SetGridWorkingDir("analysisITS");
// Declare alien output directory. Relative to working directory.
plugin->SetGridOutputDir("output151009"); // In this case will be $HOME/work/output
// Declare the analysis source files names separated by blancs. To be compiled runtime
// using ACLiC on the worker nodes.
if(!uselibPWG1) {
plugin->SetAnalysisSource("AliAlignmentDataFilterITS.cxx");
plugin->SetAnalysisSource("AliTrackMatchingTPCITSCosmics.cxx");
}
// Declare all libraries (other than the default ones for the framework. These will be
// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
//plugin->SetAdditionalLibs("AliAlignmentDataFilterITS.h AliAlignmentDataFilterITS.cxx libProof.so libRAWDatabase.so libRAWDatarec.so libCDB.so libSTEER.so libITSbase.so libITSrec.so");
plugin->AddIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER -I$ALICE_ROOT/TRD -I$ALICE_ROOT/macros -I$ALICE_ROOT/ANALYSIS -g");
if(!uselibPWG1) {
plugin->SetAdditionalLibs("AliAlignmentDataFilterITS.h AliAlignmentDataFilterITS.cxx AliTrackMatchingTPCITSCosmics.h AliTrackMatchingTPCITSCosmics.cxx libProof.so libRAWDatabase.so libRAWDatarec.so libCDB.so libSTEER.so libITSbase.so libITSrec.so");
} else {
plugin->SetAdditionalLibs("libGui.so libProof.so libMinuit.so libRAWDatabase.so libRAWDatarec.so libCDB.so libSTEER.so libITSbase.so libITSrec.so libTPCbase.so libTPCrec.so libTRDbase.so libTRDrec.so libTENDER.so libPWG1.so");
}
// Declare the output file names separated by blancs.
// (can be like: file.root or file.root@ALICE::Niham::File)
plugin->SetDefaultOutputs(kTRUE);
// Optionally define the files to be archived.
// plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:*.root@ALICE::NIHAM::File");
plugin->SetOutputArchive("log_archive.zip:stdout,stderr");
// Optionally set a name for the generated analysis macro (default MyAnalysis.C)
plugin->SetAnalysisMacro("AnalysisITS.C");
// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
plugin->SetSplitMaxInputFileNumber(1);
// Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
//plugin->SetMaxInitFailed(5);
// Optionally resubmit threshold.
//plugin->SetMasterResubmitThreshold(90);
// Optionally set time to live (default 30000 sec)
//plugin->SetTTL(20000);
// Optionally set input format (default xml-single)
plugin->SetInputFormat("xml-single");
// Optionally modify the name of the generated JDL (default analysis.jdl)
plugin->SetJDLName("TaskAnalysisITS.jdl");
// Optionally modify job price (default 1)
//plugin->SetPrice(1);
// Optionally modify split mode (default 'se')
plugin->SetSplitMode("se");
// Optionally set the preferred SE
plugin->SetPreferedSE("ALICE::CNAF::SE");
return plugin;
}
//-----------------------------------------------------------------------------
TChain *CreateESDChain(TString esdpath=".",Int_t ifirst=-1,Int_t ilast=-1) {
TChain *chainESD = new TChain("esdTree");
if(ifirst<0) {
chainESD->Add("AliESDs.root");
} else {
for(Int_t i=ifirst; i<=ilast; i++) {
TString command=".! ln -s ";
command+=esdpath.Data();
command+=i;
command+= "/AliESDs_def.root ";
command+=esdpath.Data();
command+=i;
command+= "/AliESDs.root ";
gROOT->ProcessLine(command.Data());
command.ReplaceAll("AliESDs","AliESDfriends");
gROOT->ProcessLine(command.Data());
TString esdfile=esdpath; esdfile+=i; esdfile.Append("/AliESDs.root");
chainESD->Add(esdfile.Data());
}
}
return chainESD;
}
<|endoftext|> |
<commit_before>#include "StableHeaders.h"
#include "EC_ParticleSystem.h"
#include "ModuleInterface.h"
#include "Entity.h"
#include "Renderer.h"
#include "EC_OgrePlaceable.h"
#include "OgreParticleResource.h"
#include "SceneManager.h"
#include "OgreRenderingModule.h"
#include "RexUUID.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_ParticleSystem")
#include <Ogre.h>
EC_ParticleSystem::EC_ParticleSystem(Foundation::ModuleInterface *module):
Foundation::ComponentInterface(module->GetFramework()),
framework_(module->GetFramework()),
particleSystem_(0),
particle_tag_(0),
particleId_(this, "Particle id"),
castShadows_(this, "Cast shadows", false),
renderingDistance_(this, "Rendering distance", 0.0f)
{
OgreRenderer::OgreRenderingModule *rendererModule = framework_->GetModuleManager()->GetModule<OgreRenderer::OgreRenderingModule>().lock().get();
if(!rendererModule)
return;
renderer_ = OgreRenderer::RendererWeakPtr(rendererModule->GetRenderer());
QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()));
}
EC_ParticleSystem::~EC_ParticleSystem()
{
DeleteParticleSystem();
}
Foundation::ComponentPtr EC_ParticleSystem::GetPlaceable() const
{
return placeable_;
}
void EC_ParticleSystem::SetPlaceable(Foundation::ComponentPtr comp)
{
placeable_ = comp;
}
bool EC_ParticleSystem::HandleResourceEvent(event_id_t event_id, Foundation::EventDataInterface* data)
{
if (event_id != Resource::Events::RESOURCE_READY)
return false;
Resource::Events::ResourceReady* event_data = checked_static_cast<Resource::Events::ResourceReady*>(data);
if(!event_data)
return false;
if (particle_tag_ != event_data->tag_)
return false;
particle_tag_ = 0;
OgreRenderer::OgreParticleResource* partres = checked_static_cast<OgreRenderer::OgreParticleResource*>(event_data->resource_.get());
if(!partres)
return false;
if(partres->GetNumTemplates())
CreateParticleSystem(QString::fromStdString(partres->GetTemplateName(0)));
}
void EC_ParticleSystem::CreateParticleSystem(const QString &systemName)
{
if (renderer_.expired())
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
try
{
DeleteParticleSystem();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
particleSystem_ = scene_mgr->createParticleSystem(renderer->GetUniqueObjectName(), systemName.toStdString());
if(particleSystem_)
{
OgreRenderer::EC_OgrePlaceable *placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_.get());
if(!placeable)
return;
placeable->GetSceneNode()->attachObject(particleSystem_);
particleSystem_->setCastShadows(castShadows_.Get());
particleSystem_->setRenderingDistance(renderingDistance_.Get());
return;
}
}
catch (Ogre::Exception& e)
{
LogError("Could not add particle system " + Name().toStdString() + ": " + std::string(e.what()));
}
return;
}
void EC_ParticleSystem::DeleteParticleSystem()
{
if (renderer_.expired() || !particleSystem_)
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
OgreRenderer::EC_OgrePlaceable *placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_.get());
if(!placeable)
return;
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
if(!scene_mgr)
return;
try
{
//placeable->GetSceneNode()->detachObject(particleSystem_);
Ogre::SceneNode *node = placeable->GetSceneNode();
if(!node)
return;
node->detachObject(particleSystem_);
}
catch (Ogre::Exception& e)
{
LogError("Could not delete particle system " + Name().toStdString() + ": " + std::string(e.what()));
}
scene_mgr->destroyParticleSystem(particleSystem_);
particleSystem_ = 0;
return;
}
void EC_ParticleSystem::AttributeUpdated(Foundation::ComponentInterface *component, Foundation::AttributeInterface *attribute)
{
if(component != this)
return;
if(attribute->GetNameString() == particleId_.GetNameString())
{
/*if(particle_tag_)
return;*/
Foundation::Attribute<std::string> *particleAtt = dynamic_cast<Foundation::Attribute<std::string> *>(attribute);
if(!particleAtt)
return;
particle_tag_ = RequestResource(particleAtt->Get(), OgreRenderer::OgreParticleResource::GetTypeStatic());
if(!particle_tag_) // To visualize that resource id was wrong delete previous particle effect off.
DeleteParticleSystem();
}
else if(attribute->GetNameString() == castShadows_.GetNameString())
{
if(particleSystem_)
particleSystem_->setCastShadows(castShadows_.Get());
}
else if(attribute->GetNameString() == renderingDistance_.GetNameString())
{
if(particleSystem_)
particleSystem_->setRenderingDistance(renderingDistance_.Get());
}
}
void EC_ParticleSystem::UpdateSignals()
{
disconnect(this, SLOT(AttributeUpdated(Foundation::ComponentInterface *, Foundation::AttributeInterface *)));
FindPlaceable();
connect(GetParentEntity()->GetScene(), SIGNAL(AttributeChanged(Foundation::ComponentInterface*, Foundation::AttributeInterface*, AttributeChange::Type)),
this, SLOT(AttributeUpdated(Foundation::ComponentInterface*, Foundation::AttributeInterface*)));
}
void EC_ParticleSystem::FindPlaceable()
{
assert(framework_);
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
placeable_ = GetParentEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>();
if(!placeable_)
LogError("Couldn't find a EC_OgrePlaceable coponent in this entity.");
return;
}
request_tag_t EC_ParticleSystem::RequestResource(const std::string& id, const std::string& type)
{
request_tag_t tag = 0;
if(renderer_.expired())
return tag;
tag = renderer_.lock()->RequestResource(id, type);
if(tag == 0)
{
LogWarning("Failed to request resource:" + id + " : " + type);
return 0;
}
return tag;
}<commit_msg>Fix "warning C4715: 'EC_ParticleSystem::HandleResourceEvent' : not all control paths return a value"<commit_after>#include "StableHeaders.h"
#include "EC_ParticleSystem.h"
#include "ModuleInterface.h"
#include "Entity.h"
#include "Renderer.h"
#include "EC_OgrePlaceable.h"
#include "OgreParticleResource.h"
#include "SceneManager.h"
#include "OgreRenderingModule.h"
#include "RexUUID.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_ParticleSystem")
#include <Ogre.h>
EC_ParticleSystem::EC_ParticleSystem(Foundation::ModuleInterface *module):
Foundation::ComponentInterface(module->GetFramework()),
framework_(module->GetFramework()),
particleSystem_(0),
particle_tag_(0),
particleId_(this, "Particle id"),
castShadows_(this, "Cast shadows", false),
renderingDistance_(this, "Rendering distance", 0.0f)
{
OgreRenderer::OgreRenderingModule *rendererModule = framework_->GetModuleManager()->GetModule<OgreRenderer::OgreRenderingModule>().lock().get();
if(!rendererModule)
return;
renderer_ = OgreRenderer::RendererWeakPtr(rendererModule->GetRenderer());
QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()));
}
EC_ParticleSystem::~EC_ParticleSystem()
{
DeleteParticleSystem();
}
Foundation::ComponentPtr EC_ParticleSystem::GetPlaceable() const
{
return placeable_;
}
void EC_ParticleSystem::SetPlaceable(Foundation::ComponentPtr comp)
{
placeable_ = comp;
}
bool EC_ParticleSystem::HandleResourceEvent(event_id_t event_id, Foundation::EventDataInterface* data)
{
Resource::Events::ResourceReady* event_data = checked_static_cast<Resource::Events::ResourceReady*>(data);
if (event_id != Resource::Events::RESOURCE_READY || !event_data || particle_tag_ != event_data->tag_)
return false;
OgreRenderer::OgreParticleResource* partres = checked_static_cast<OgreRenderer::OgreParticleResource*>(event_data->resource_.get());
if (!partres)
return false;
if (partres->GetNumTemplates())
CreateParticleSystem(QString::fromStdString(partres->GetTemplateName(0)));
return false;
}
void EC_ParticleSystem::CreateParticleSystem(const QString &systemName)
{
if (renderer_.expired())
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
try
{
DeleteParticleSystem();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
particleSystem_ = scene_mgr->createParticleSystem(renderer->GetUniqueObjectName(), systemName.toStdString());
if(particleSystem_)
{
OgreRenderer::EC_OgrePlaceable *placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_.get());
if(!placeable)
return;
placeable->GetSceneNode()->attachObject(particleSystem_);
particleSystem_->setCastShadows(castShadows_.Get());
particleSystem_->setRenderingDistance(renderingDistance_.Get());
return;
}
}
catch (Ogre::Exception& e)
{
LogError("Could not add particle system " + Name().toStdString() + ": " + std::string(e.what()));
}
return;
}
void EC_ParticleSystem::DeleteParticleSystem()
{
if (renderer_.expired() || !particleSystem_)
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
OgreRenderer::EC_OgrePlaceable *placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_.get());
if(!placeable)
return;
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
if(!scene_mgr)
return;
try
{
//placeable->GetSceneNode()->detachObject(particleSystem_);
Ogre::SceneNode *node = placeable->GetSceneNode();
if(!node)
return;
node->detachObject(particleSystem_);
}
catch (Ogre::Exception& e)
{
LogError("Could not delete particle system " + Name().toStdString() + ": " + std::string(e.what()));
}
scene_mgr->destroyParticleSystem(particleSystem_);
particleSystem_ = 0;
return;
}
void EC_ParticleSystem::AttributeUpdated(Foundation::ComponentInterface *component, Foundation::AttributeInterface *attribute)
{
if(component != this)
return;
if(attribute->GetNameString() == particleId_.GetNameString())
{
/*if(particle_tag_)
return;*/
Foundation::Attribute<std::string> *particleAtt = dynamic_cast<Foundation::Attribute<std::string> *>(attribute);
if(!particleAtt)
return;
particle_tag_ = RequestResource(particleAtt->Get(), OgreRenderer::OgreParticleResource::GetTypeStatic());
if(!particle_tag_) // To visualize that resource id was wrong delete previous particle effect off.
DeleteParticleSystem();
}
else if(attribute->GetNameString() == castShadows_.GetNameString())
{
if(particleSystem_)
particleSystem_->setCastShadows(castShadows_.Get());
}
else if(attribute->GetNameString() == renderingDistance_.GetNameString())
{
if(particleSystem_)
particleSystem_->setRenderingDistance(renderingDistance_.Get());
}
}
void EC_ParticleSystem::UpdateSignals()
{
disconnect(this, SLOT(AttributeUpdated(Foundation::ComponentInterface *, Foundation::AttributeInterface *)));
FindPlaceable();
connect(GetParentEntity()->GetScene(), SIGNAL(AttributeChanged(Foundation::ComponentInterface*, Foundation::AttributeInterface*, AttributeChange::Type)),
this, SLOT(AttributeUpdated(Foundation::ComponentInterface*, Foundation::AttributeInterface*)));
}
void EC_ParticleSystem::FindPlaceable()
{
assert(framework_);
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
placeable_ = GetParentEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>();
if(!placeable_)
LogError("Couldn't find a EC_OgrePlaceable coponent in this entity.");
return;
}
request_tag_t EC_ParticleSystem::RequestResource(const std::string& id, const std::string& type)
{
request_tag_t tag = 0;
if(renderer_.expired())
return tag;
tag = renderer_.lock()->RequestResource(id, type);
if(tag == 0)
{
LogWarning("Failed to request resource:" + id + " : " + type);
return 0;
}
return tag;
}<|endoftext|> |
<commit_before>#include "math.hpp"
#include "util.hpp"
#include "muglm/matrix_helper.hpp"
#include "muglm/muglm_impl.hpp"
#include "memory_mapped_texture.hpp"
using namespace muglm;
using namespace Granite;
using namespace Granite::SceneFormats;
// Shameless copy-pasta from learnopengl.com. :)
static float RadicalInverse_VdC(uint32_t bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10f; // / 0x100000000
}
static vec2 Hammersley(uint i, uint N)
{
return vec2(float(i) / float(N), RadicalInverse_VdC(i));
}
static vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness)
{
float a = roughness * roughness;
float phi = 2.0f * pi<float>() * Xi.x;
float cosTheta = sqrt((1.0f - Xi.y) / (1.0f + (a * a - 1.0f) * Xi.y));
float sinTheta = sqrt(1.0f - cosTheta * cosTheta);
// from spherical coordinates to cartesian coordinates
vec3 H;
H.x = cos(phi) * sinTheta;
H.y = sin(phi) * sinTheta;
H.z = cosTheta;
// from tangent-space vector to world-space sample vector
vec3 up = abs(N.z) < 0.999f ? vec3(0.0f, 0.0f, 1.0f) : vec3(1.0f, 0.0f, 0.0f);
vec3 tangent = normalize(cross(up, N));
vec3 bitangent = cross(N, tangent);
vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;
return normalize(sampleVec);
}
static float GeometrySchlickGGX(float NdotV, float roughness)
{
float a = roughness;
float k = (a * a) / 2.0f;
float nom = NdotV;
float denom = NdotV * (1.0f - k) + k;
return nom / denom;
}
static float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
{
float NdotV = max(dot(N, V), 0.0f);
float NdotL = max(dot(N, L), 0.0f);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
static vec2 IntegrateBRDF(float NdotV, float roughness)
{
vec3 V;
V.x = sqrt(1.0f - NdotV * NdotV);
V.y = 0.0f;
V.z = NdotV;
float A = 0.0f;
float B = 0.0f;
vec3 N = vec3(0.0f, 0.0f, 1.0f);
const unsigned SAMPLE_COUNT = 1024u;
for (unsigned i = 0u; i < SAMPLE_COUNT; i++)
{
vec2 Xi = Hammersley(i, SAMPLE_COUNT);
vec3 H = ImportanceSampleGGX(Xi, N, roughness);
vec3 L = normalize(2.0f * dot(V, H) * H - V);
float NdotL = max(L.z, 0.0f);
float NdotH = max(H.z, 0.0f);
float VdotH = max(dot(V, H), 0.0f);
if (NdotL > 0.0f)
{
float G = GeometrySmith(N, V, L, roughness);
float G_Vis = (G * VdotH) / (NdotH * NdotV);
float Fc = pow(1.0f - VdotH, 5.0f);
A += (1.0f - Fc) * G_Vis;
B += Fc * G_Vis;
}
}
A /= float(SAMPLE_COUNT);
B /= float(SAMPLE_COUNT);
return vec2(A, B);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
LOGE("Usage: %s <output.gtx>\n", argv[0]);
return 1;
}
const unsigned width = 256;
const unsigned height = 256;
MemoryMappedTexture tex;
tex.set_2d(VK_FORMAT_R16G16_SFLOAT, width, height);
if (!tex.map_write(argv[1]))
{
LOGE("Failed to save image to: %s\n", argv[1]);
return 1;
}
for (unsigned y = 0; y < height; y++)
{
for (unsigned x = 0; x < width; x++)
{
float NoV = (x + 0.5f) * (1.0f / width);
float roughness = (y + 0.5f) * (1.0f / height);
//roughness = roughness * 0.75f + 0.25f;
*tex.get_layout().data_2d<uint32_t>(x, y) = packHalf2x16(IntegrateBRDF(NoV, roughness));
}
}
}
<commit_msg>Build fix for MSVC.<commit_after>#include "math.hpp"
#include "util.hpp"
#include "muglm/matrix_helper.hpp"
#include "muglm/muglm_impl.hpp"
#include "memory_mapped_texture.hpp"
using namespace muglm;
using namespace Granite;
using namespace Granite::SceneFormats;
// Shameless copy-pasta from learnopengl.com. :)
static float RadicalInverse_VdC(uint32_t bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10f; // / 0x100000000
}
static vec2 Hammersley(uint i, uint N)
{
return vec2(float(i) / float(N), RadicalInverse_VdC(i));
}
static vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness)
{
float a = roughness * roughness;
float phi = 2.0f * pi<float>() * Xi.x;
float cosTheta = muglm::sqrt((1.0f - Xi.y) / (1.0f + (a * a - 1.0f) * Xi.y));
float sinTheta = muglm::sqrt(1.0f - cosTheta * cosTheta);
// from spherical coordinates to cartesian coordinates
vec3 H;
H.x = cos(phi) * sinTheta;
H.y = sin(phi) * sinTheta;
H.z = cosTheta;
// from tangent-space vector to world-space sample vector
vec3 up = abs(N.z) < 0.999f ? vec3(0.0f, 0.0f, 1.0f) : vec3(1.0f, 0.0f, 0.0f);
vec3 tangent = normalize(cross(up, N));
vec3 bitangent = cross(N, tangent);
vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;
return normalize(sampleVec);
}
static float GeometrySchlickGGX(float NdotV, float roughness)
{
float a = roughness;
float k = (a * a) / 2.0f;
float nom = NdotV;
float denom = NdotV * (1.0f - k) + k;
return nom / denom;
}
static float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
{
float NdotV = max(dot(N, V), 0.0f);
float NdotL = max(dot(N, L), 0.0f);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
static vec2 IntegrateBRDF(float NdotV, float roughness)
{
vec3 V;
V.x = muglm::sqrt(1.0f - NdotV * NdotV);
V.y = 0.0f;
V.z = NdotV;
float A = 0.0f;
float B = 0.0f;
vec3 N = vec3(0.0f, 0.0f, 1.0f);
const unsigned SAMPLE_COUNT = 1024u;
for (unsigned i = 0u; i < SAMPLE_COUNT; i++)
{
vec2 Xi = Hammersley(i, SAMPLE_COUNT);
vec3 H = ImportanceSampleGGX(Xi, N, roughness);
vec3 L = normalize(2.0f * dot(V, H) * H - V);
float NdotL = max(L.z, 0.0f);
float NdotH = max(H.z, 0.0f);
float VdotH = max(dot(V, H), 0.0f);
if (NdotL > 0.0f)
{
float G = GeometrySmith(N, V, L, roughness);
float G_Vis = (G * VdotH) / (NdotH * NdotV);
float Fc = pow(1.0f - VdotH, 5.0f);
A += (1.0f - Fc) * G_Vis;
B += Fc * G_Vis;
}
}
A /= float(SAMPLE_COUNT);
B /= float(SAMPLE_COUNT);
return vec2(A, B);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
LOGE("Usage: %s <output.gtx>\n", argv[0]);
return 1;
}
const unsigned width = 256;
const unsigned height = 256;
MemoryMappedTexture tex;
tex.set_2d(VK_FORMAT_R16G16_SFLOAT, width, height);
if (!tex.map_write(argv[1]))
{
LOGE("Failed to save image to: %s\n", argv[1]);
return 1;
}
for (unsigned y = 0; y < height; y++)
{
for (unsigned x = 0; x < width; x++)
{
float NoV = (x + 0.5f) * (1.0f / width);
float roughness = (y + 0.5f) * (1.0f / height);
//roughness = roughness * 0.75f + 0.25f;
*tex.get_layout().data_2d<uint32_t>(x, y) = packHalf2x16(IntegrateBRDF(NoV, roughness));
}
}
}
<|endoftext|> |
<commit_before>/*
* SessionBuildEnvironment.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionBuildEnvironment.hpp"
#include <string>
#include <vector>
#include <boost/regex.hpp>
#include <boost/format.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <core/r_util/RToolsInfo.hpp>
#include <r/RExec.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core ;
namespace session {
namespace modules {
namespace build {
#ifdef _WIN32
namespace {
r_util::RToolsInfo scanPathForRTools()
{
// first confirm ls.exe is in Rtools
r_util::RToolsInfo noToolsFound;
FilePath lsPath = module_context::findProgram("ls.exe");
if (lsPath.empty())
return noToolsFound;
// we have a candidate installPath
FilePath installPath = lsPath.parent().parent();
core::system::ensureLongPath(&installPath);
if (!installPath.childPath("Rtools.txt").exists())
return noToolsFound;
// find the version path
FilePath versionPath = installPath.childPath("VERSION.txt");
if (!versionPath.exists())
return noToolsFound;
// further verify that gcc is in Rtools
FilePath gccPath = module_context::findProgram("gcc.exe");
if (!gccPath.exists())
return noToolsFound;
if (!gccPath.parent().parent().parent().childPath("Rtools.txt").exists())
return noToolsFound;
// Rtools is in the path -- now crack the VERSION file
std::string contents;
Error error = core::readStringFromFile(versionPath, &contents);
if (error)
{
LOG_ERROR(error);
return noToolsFound;
}
// extract the version
boost::algorithm::trim(contents);
boost::regex pattern("Rtools version (\\d\\.\\d\\d)[\\d\\.]+$");
boost::smatch match;
if (boost::regex_search(contents, match, pattern))
return r_util::RToolsInfo(match[1], installPath);
else
return noToolsFound;
}
std::string formatPath(const FilePath& filePath)
{
FilePath displayPath = filePath;
core::system::ensureLongPath(&displayPath);
return boost::algorithm::replace_all_copy(
displayPath.absolutePath(), "/", "\\");
}
template <typename T>
bool doAddRtoolsToPathIfNecessary(T* pTarget, std::string* pWarningMessage)
{
// can we find ls.exe and gcc.exe on the path? if so then
// we assume Rtools are already there (this is the same test
// used by devtools)
bool rToolsOnPath = false;
Error error = r::exec::RFunction(".rs.isRtoolsOnPath").call(&rToolsOnPath);
if (error)
LOG_ERROR(error);
if (rToolsOnPath)
{
// perform an extra check to see if the version on the path is not
// compatible with the currenly running version of R
r_util::RToolsInfo rTools = scanPathForRTools();
if (!rTools.empty())
{
if (!isRtoolsCompatible(rTools))
{
boost::format fmt(
"WARNING: Rtools version %1% is on the PATH (intalled at %2%) "
"but is "
"not compatible with the currently running version of R."
"\n\nPlease download and install the appropriate version of "
"Rtools to ensure that packages are built correctly:"
"\n\nhttp://cran.rstudio.com/bin/windows/Rtools/"
"\n\nNote that in addition to installing a compatible verison you "
"also need to remove the incompatible version from your PATH");
*pWarningMessage = boost::str(
fmt % rTools.name() % formatPath(rTools.installPath()));
}
}
return false;
}
// ok so scan for R tools
std::vector<r_util::RToolsInfo> rTools;
error = core::r_util::scanRegistryForRTools(&rTools);
if (error)
{
LOG_ERROR(error);
return false;
}
// enumerate them to see if we have a compatible version
// (go in reverse order for most recent first)
std::vector<r_util::RToolsInfo>::const_reverse_iterator it = rTools.rbegin();
for ( ; it != rTools.rend(); ++it)
{
if (isRtoolsCompatible(*it))
{
r_util::prependToSystemPath(*it, pTarget);
return true;
}
}
// if we found no version of rtools whatsoever then print warning and return
if (rTools.empty())
{
*pWarningMessage =
"WARNING: Rtools is required to build R packages but is not "
"currently installed. "
"Please download and install the appropriate "
"version of Rtools before proceeding:\n\n"
"http://cran.rstudio.com/bin/windows/Rtools/";
}
else
{
// Rtools installed but no compatible version, print a suitable warning
pWarningMessage->append(
"WARNING: Rtools is required to build R packages but no version "
"of Rtools compatible with the currently running version of R "
"was found. Note that the following incompatible version(s) "
"of Rtools were found:\n\n");
std::vector<r_util::RToolsInfo>::const_iterator fwdIt = rTools.begin();
for (; fwdIt != rTools.end(); ++fwdIt)
{
std::string path = formatPath(fwdIt->installPath());
boost::format fmt(" - Rtools %1% (installed at %2%)\n");
pWarningMessage->append(boost::str(fmt % fwdIt->name() % path));
}
pWarningMessage->append(
"\nPlease download and install the appropriate "
"version of Rtools before proceeding:\n\n"
"http://cran.rstudio.com/bin/windows/Rtools/");
}
return false;
}
} // anonymous namespace
bool isRtoolsCompatible(const r_util::RToolsInfo& rTools)
{
bool isCompatible = false;
Error error = r::exec::evaluateString(rTools.versionPredicate(),
&isCompatible);
if (error)
LOG_ERROR(error);
return isCompatible;
}
bool addRtoolsToPathIfNecessary(std::string* pPath,
std::string* pWarningMessage)
{
return doAddRtoolsToPathIfNecessary(pPath, pWarningMessage);
}
bool addRtoolsToPathIfNecessary(core::system::Options* pEnvironment,
std::string* pWarningMessage)
{
return doAddRtoolsToPathIfNecessary(pEnvironment, pWarningMessage);
}
#else
bool isRtoolsCompatible(const r_util::RToolsInfo& rTools)
{
return false;
}
bool addRtoolsToPathIfNecessary(std::string* pPath,
std::string* pWarningMessage)
{
return false;
}
bool addRtoolsToPathIfNecessary(core::system::Options* pEnvironment,
std::string* pWarningMessage)
{
return false;
}
#endif
} // namespace build
} // namespace modules
} // namespace session
<commit_msg>always use Rtools for windows build functions (never use what's on the PATH)<commit_after>/*
* SessionBuildEnvironment.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionBuildEnvironment.hpp"
#include <string>
#include <vector>
#include <boost/regex.hpp>
#include <boost/format.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <core/r_util/RToolsInfo.hpp>
#include <r/RExec.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core ;
namespace session {
namespace modules {
namespace build {
#ifdef _WIN32
namespace {
r_util::RToolsInfo scanPathForRTools()
{
// first confirm ls.exe is in Rtools
r_util::RToolsInfo noToolsFound;
FilePath lsPath = module_context::findProgram("ls.exe");
if (lsPath.empty())
return noToolsFound;
// we have a candidate installPath
FilePath installPath = lsPath.parent().parent();
core::system::ensureLongPath(&installPath);
if (!installPath.childPath("Rtools.txt").exists())
return noToolsFound;
// find the version path
FilePath versionPath = installPath.childPath("VERSION.txt");
if (!versionPath.exists())
return noToolsFound;
// further verify that gcc is in Rtools
FilePath gccPath = module_context::findProgram("gcc.exe");
if (!gccPath.exists())
return noToolsFound;
if (!gccPath.parent().parent().parent().childPath("Rtools.txt").exists())
return noToolsFound;
// Rtools is in the path -- now crack the VERSION file
std::string contents;
Error error = core::readStringFromFile(versionPath, &contents);
if (error)
{
LOG_ERROR(error);
return noToolsFound;
}
// extract the version
boost::algorithm::trim(contents);
boost::regex pattern("Rtools version (\\d\\.\\d\\d)[\\d\\.]+$");
boost::smatch match;
if (boost::regex_search(contents, match, pattern))
return r_util::RToolsInfo(match[1], installPath);
else
return noToolsFound;
}
std::string formatPath(const FilePath& filePath)
{
FilePath displayPath = filePath;
core::system::ensureLongPath(&displayPath);
return boost::algorithm::replace_all_copy(
displayPath.absolutePath(), "/", "\\");
}
template <typename T>
bool doAddRtoolsToPathIfNecessary(T* pTarget, std::string* pWarningMessage)
{
// ok so scan for R tools
std::vector<r_util::RToolsInfo> rTools;
Error error = core::r_util::scanRegistryForRTools(&rTools);
if (error)
{
LOG_ERROR(error);
return false;
}
// enumerate them to see if we have a compatible version
// (go in reverse order for most recent first)
std::vector<r_util::RToolsInfo>::const_reverse_iterator it = rTools.rbegin();
for ( ; it != rTools.rend(); ++it)
{
if (isRtoolsCompatible(*it))
{
r_util::prependToSystemPath(*it, pTarget);
return true;
}
}
// if we found no version of rtools whatsoever then print warning and return
if (rTools.empty())
{
*pWarningMessage =
"WARNING: Rtools is required to build R packages but is not "
"currently installed. "
"Please download and install the appropriate "
"version of Rtools before proceeding:\n\n"
"http://cran.rstudio.com/bin/windows/Rtools/";
}
else
{
// Rtools installed but no compatible version, print a suitable warning
pWarningMessage->append(
"WARNING: Rtools is required to build R packages but no version "
"of Rtools compatible with the currently running version of R "
"was found. Note that the following incompatible version(s) "
"of Rtools were found:\n\n");
std::vector<r_util::RToolsInfo>::const_iterator fwdIt = rTools.begin();
for (; fwdIt != rTools.end(); ++fwdIt)
{
std::string path = formatPath(fwdIt->installPath());
boost::format fmt(" - Rtools %1% (installed at %2%)\n");
pWarningMessage->append(boost::str(fmt % fwdIt->name() % path));
}
pWarningMessage->append(
"\nPlease download and install the appropriate "
"version of Rtools before proceeding:\n\n"
"http://cran.rstudio.com/bin/windows/Rtools/");
}
return false;
}
} // anonymous namespace
bool isRtoolsCompatible(const r_util::RToolsInfo& rTools)
{
bool isCompatible = false;
Error error = r::exec::evaluateString(rTools.versionPredicate(),
&isCompatible);
if (error)
LOG_ERROR(error);
return isCompatible;
}
bool addRtoolsToPathIfNecessary(std::string* pPath,
std::string* pWarningMessage)
{
return doAddRtoolsToPathIfNecessary(pPath, pWarningMessage);
}
bool addRtoolsToPathIfNecessary(core::system::Options* pEnvironment,
std::string* pWarningMessage)
{
return doAddRtoolsToPathIfNecessary(pEnvironment, pWarningMessage);
}
#else
bool isRtoolsCompatible(const r_util::RToolsInfo& rTools)
{
return false;
}
bool addRtoolsToPathIfNecessary(std::string* pPath,
std::string* pWarningMessage)
{
return false;
}
bool addRtoolsToPathIfNecessary(core::system::Options* pEnvironment,
std::string* pWarningMessage)
{
return false;
}
#endif
} // namespace build
} // namespace modules
} // namespace session
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOpenGLGLXPBTextureTarget.cpp
created: Sat Jan 31 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUIOpenGLGLXPBTextureTarget.h"
#include "CEGUIExceptions.h"
#include "CEGUIRenderQueue.h"
#include "CEGUIGeometryBuffer.h"
#include "CEGUIOpenGLRenderer.h"
#include "CEGUIOpenGLTexture.h"
#include <iostream>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OpenGLGLXPBTextureTarget::DEFAULT_SIZE = 128.0f;
//----------------------------------------------------------------------------//
// internal attribute array used to get pbuffer configs
int pbAttrs[] =
{
GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
GLX_DOUBLEBUFFER, GL_FALSE,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
None
};
//----------------------------------------------------------------------------//
OpenGLGLXPBTextureTarget::OpenGLGLXPBTextureTarget(OpenGLRenderer& owner) :
OpenGLTextureTarget(owner),
d_pbuffer(0)
{
if (!GLXEW_VERSION_1_3)
CEGUI_THROW(InvalidRequestException("System does not support GLX >= 1.3 "
"required by CEGUI pbuffer usage under GLX"));
d_dpy = glXGetCurrentDisplay();
selectFBConfig();
createContext();
initialiseTexture();
// set default size (and cause initialisation of the pbuffer)
declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
// set some states as a one-time thing (because we use a separate context)
enablePBuffer();
glEnable(GL_SCISSOR_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
glDisableClientState(GL_INDEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_FOG_COORDINATE_ARRAY);
glDisableClientState(GL_EDGE_FLAG_ARRAY);
glClearColor(0,0,0,0);
disablePBuffer();
}
//----------------------------------------------------------------------------//
OpenGLGLXPBTextureTarget::~OpenGLGLXPBTextureTarget()
{
if (d_pbuffer)
glXDestroyPbuffer(d_dpy, d_pbuffer);
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::activate()
{
enablePBuffer();
OpenGLRenderTarget::activate();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::deactivate()
{
// grab what we rendered into the texture
glBindTexture(GL_TEXTURE_2D, d_texture);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
0, 0,
static_cast<GLsizei>(d_area.d_right),
static_cast<GLsizei>(d_area.d_bottom), 0);
disablePBuffer();
OpenGLRenderTarget::deactivate();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::clear()
{
enablePBuffer();
glDisable(GL_SCISSOR_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_SCISSOR_TEST);
disablePBuffer();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::declareRenderSize(const Size& sz)
{
// exit if current size is enough
if ((d_area.getWidth() >= sz.d_width) &&
(d_area.getHeight() >= sz.d_height))
return;
setArea(Rect(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz)));
initialisePBuffer();
clear();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::initialisePBuffer()
{
int creation_attrs[] =
{
GLX_PBUFFER_WIDTH, d_area.getWidth(),
GLX_PBUFFER_HEIGHT, d_area.getHeight(),
GLX_LARGEST_PBUFFER, True,
GLX_PRESERVED_CONTENTS, True,
None
};
// release any existing pbuffer
if (d_pbuffer)
glXDestroyPbuffer(d_dpy, d_pbuffer);
d_pbuffer = glXCreatePbuffer(d_dpy, d_fbconfig, creation_attrs);
if (!d_pbuffer)
CEGUI_THROW(RendererException(
"OpenGLGLXPBTextureTarget::initialisePBuffer - "
"pbuffer creation error: glXCreatePbuffer() failed"));
// get the real size of the buffer that was created
GLuint actual_width, actual_height;
glXQueryDrawable(d_dpy, d_pbuffer, GLX_WIDTH, &actual_width);
glXQueryDrawable(d_dpy, d_pbuffer, GLX_HEIGHT, &actual_height);
d_area.setSize(Size(actual_width, actual_height));
// ensure CEGUI::Texture is wrapping real GL texture and has correct size
d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize());
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::enablePBuffer() const
{
// switch to using the pbuffer
d_prevDisplay = glXGetCurrentDisplay();
d_prevDrawable = glXGetCurrentDrawable();
d_prevContext = glXGetCurrentContext();
if (!glXMakeCurrent(d_dpy, d_pbuffer, d_context))
std::cerr << "Failed to switch to pbuffer for rendering" << std::endl;
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::disablePBuffer() const
{
// switch back to rendering to previous set up
if (!glXMakeCurrent(d_prevDisplay, d_prevDrawable, d_prevContext))
std::cerr << "Failed to switch from pbuffer rendering" << std::endl;
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::initialiseTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// create and setup texture which pbuffer content will be loaded to
glGenTextures(1, &d_texture);
glBindTexture(GL_TEXTURE_2D, d_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::selectFBConfig()
{
int cfgcnt;
GLXFBConfig* glxcfgs;
glxcfgs = glXChooseFBConfig(d_dpy, DefaultScreen(d_dpy), pbAttrs, &cfgcnt);
if (!glxcfgs)
CEGUI_THROW(RendererException(
"OpenGLGLXPBTextureTarget::selectFBConfig - pbuffer creation "
"failure, can't get suitable configuration."));
d_fbconfig = glxcfgs[0];
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::createContext()
{
d_context = glXCreateNewContext(d_dpy, d_fbconfig, GLX_RGBA_TYPE,
glXGetCurrentContext(), true);
if (!d_context)
CEGUI_THROW(RendererException(
"OpenGLGLXPBTextureTarget::createContext - "
"Failed to create GLX context for pbuffer."));
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::grabTexture()
{
if (d_pbuffer)
{
glXDestroyPbuffer(d_dpy, d_pbuffer);
d_pbuffer = 0;
}
OpenGLTextureTarget::grabTexture();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::restoreTexture()
{
OpenGLTextureTarget::restoreTexture();
initialiseTexture();
initialisePBuffer();
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>FIX: Blend mode issue in OpenGL renderer when using GLX pbuffer based targets.<commit_after>/***********************************************************************
filename: CEGUIOpenGLGLXPBTextureTarget.cpp
created: Sat Jan 31 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUIOpenGLGLXPBTextureTarget.h"
#include "CEGUIExceptions.h"
#include "CEGUIRenderQueue.h"
#include "CEGUIGeometryBuffer.h"
#include "CEGUIOpenGLRenderer.h"
#include "CEGUIOpenGLTexture.h"
#include <iostream>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OpenGLGLXPBTextureTarget::DEFAULT_SIZE = 128.0f;
//----------------------------------------------------------------------------//
// internal attribute array used to get pbuffer configs
int pbAttrs[] =
{
GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
GLX_DOUBLEBUFFER, GL_FALSE,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
None
};
//----------------------------------------------------------------------------//
OpenGLGLXPBTextureTarget::OpenGLGLXPBTextureTarget(OpenGLRenderer& owner) :
OpenGLTextureTarget(owner),
d_pbuffer(0)
{
if (!GLXEW_VERSION_1_3)
CEGUI_THROW(InvalidRequestException("System does not support GLX >= 1.3 "
"required by CEGUI pbuffer usage under GLX"));
d_dpy = glXGetCurrentDisplay();
selectFBConfig();
createContext();
initialiseTexture();
// set default size (and cause initialisation of the pbuffer)
declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
// set some states as a one-time thing (because we use a separate context)
enablePBuffer();
glEnable(GL_SCISSOR_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
glDisableClientState(GL_INDEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_FOG_COORDINATE_ARRAY);
glDisableClientState(GL_EDGE_FLAG_ARRAY);
glClearColor(0,0,0,0);
disablePBuffer();
}
//----------------------------------------------------------------------------//
OpenGLGLXPBTextureTarget::~OpenGLGLXPBTextureTarget()
{
if (d_pbuffer)
glXDestroyPbuffer(d_dpy, d_pbuffer);
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::activate()
{
enablePBuffer();
// we clear the blend mode here so the next setupRenderingBlendMode call
// is forced to update states for our local context.
d_owner.setupRenderingBlendMode(BM_INVALID);
OpenGLRenderTarget::activate();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::deactivate()
{
// grab what we rendered into the texture
glBindTexture(GL_TEXTURE_2D, d_texture);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
0, 0,
static_cast<GLsizei>(d_area.d_right),
static_cast<GLsizei>(d_area.d_bottom), 0);
disablePBuffer();
// Clear the blend mode again so the next setupRenderingBlendMode call
// is forced to update states for the main / previous context.
d_owner.setupRenderingBlendMode(BM_INVALID);
OpenGLRenderTarget::deactivate();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::clear()
{
enablePBuffer();
glDisable(GL_SCISSOR_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_SCISSOR_TEST);
disablePBuffer();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::declareRenderSize(const Size& sz)
{
// exit if current size is enough
if ((d_area.getWidth() >= sz.d_width) &&
(d_area.getHeight() >= sz.d_height))
return;
setArea(Rect(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz)));
initialisePBuffer();
clear();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::initialisePBuffer()
{
int creation_attrs[] =
{
GLX_PBUFFER_WIDTH, d_area.getWidth(),
GLX_PBUFFER_HEIGHT, d_area.getHeight(),
GLX_LARGEST_PBUFFER, True,
GLX_PRESERVED_CONTENTS, True,
None
};
// release any existing pbuffer
if (d_pbuffer)
glXDestroyPbuffer(d_dpy, d_pbuffer);
d_pbuffer = glXCreatePbuffer(d_dpy, d_fbconfig, creation_attrs);
if (!d_pbuffer)
CEGUI_THROW(RendererException(
"OpenGLGLXPBTextureTarget::initialisePBuffer - "
"pbuffer creation error: glXCreatePbuffer() failed"));
// get the real size of the buffer that was created
GLuint actual_width, actual_height;
glXQueryDrawable(d_dpy, d_pbuffer, GLX_WIDTH, &actual_width);
glXQueryDrawable(d_dpy, d_pbuffer, GLX_HEIGHT, &actual_height);
d_area.setSize(Size(actual_width, actual_height));
// ensure CEGUI::Texture is wrapping real GL texture and has correct size
d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize());
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::enablePBuffer() const
{
// switch to using the pbuffer
d_prevDisplay = glXGetCurrentDisplay();
d_prevDrawable = glXGetCurrentDrawable();
d_prevContext = glXGetCurrentContext();
if (!glXMakeCurrent(d_dpy, d_pbuffer, d_context))
std::cerr << "Failed to switch to pbuffer for rendering" << std::endl;
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::disablePBuffer() const
{
// switch back to rendering to previous set up
if (!glXMakeCurrent(d_prevDisplay, d_prevDrawable, d_prevContext))
std::cerr << "Failed to switch from pbuffer rendering" << std::endl;
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::initialiseTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// create and setup texture which pbuffer content will be loaded to
glGenTextures(1, &d_texture);
glBindTexture(GL_TEXTURE_2D, d_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::selectFBConfig()
{
int cfgcnt;
GLXFBConfig* glxcfgs;
glxcfgs = glXChooseFBConfig(d_dpy, DefaultScreen(d_dpy), pbAttrs, &cfgcnt);
if (!glxcfgs)
CEGUI_THROW(RendererException(
"OpenGLGLXPBTextureTarget::selectFBConfig - pbuffer creation "
"failure, can't get suitable configuration."));
d_fbconfig = glxcfgs[0];
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::createContext()
{
d_context = glXCreateNewContext(d_dpy, d_fbconfig, GLX_RGBA_TYPE,
glXGetCurrentContext(), true);
if (!d_context)
CEGUI_THROW(RendererException(
"OpenGLGLXPBTextureTarget::createContext - "
"Failed to create GLX context for pbuffer."));
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::grabTexture()
{
if (d_pbuffer)
{
glXDestroyPbuffer(d_dpy, d_pbuffer);
d_pbuffer = 0;
}
OpenGLTextureTarget::grabTexture();
}
//----------------------------------------------------------------------------//
void OpenGLGLXPBTextureTarget::restoreTexture()
{
OpenGLTextureTarget::restoreTexture();
initialiseTexture();
initialisePBuffer();
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <iostream>
#include "Stroika/Foundation/Characters/Format.h"
#include "Stroika/Foundation/DataExchange/JSON/Writer.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#if qPlatform_POSIX
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#endif
#include "Stroika/Foundation/Execution/WaitableEvent.h"
#include "Stroika/Foundation/Memory/Optional.h"
#include "Stroika/Foundation/Streams/BasicBinaryOutputStream.h"
#include "Stroika/Frameworks/SystemPerformance/AllInstruments.h"
#include "Stroika/Frameworks/SystemPerformance/Capturer.h"
#include "Stroika/Frameworks/SystemPerformance/Measurement.h"
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using Characters::Character;
using Characters::String;
using Containers::Sequence;
using Memory::Optional;
namespace {
string Serialize_ (VariantValue v, bool oneLineMode)
{
Streams::BasicBinaryOutputStream out;
DataExchange::JSON::Writer ().Write (v, out);
// strip CRLF - so shows up on one line
String result = String::FromUTF8 (out.As<string> ());
if (oneLineMode) {
result = result.StripAll ([] (Character c)-> bool { return c == '\n' or c == '\r';});
}
return result.AsNarrowSDKString ();
}
}
int main (int argc, const char* argv[])
{
#if qPlatform_POSIX
// Many performance instruments use pipes
// @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE?
// --LGP 2014-02-05
Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED);
#endif
bool printUsage = false;
bool printNames = false;
bool oneLineMode = false;
Time::DurationSecondsType runFor = 30.0;
Set<InstrumentNameType> run;
Sequence<String> args = Execution::ParseCommandLine (argc, argv);
for (auto argi = args.begin (); argi != args.end(); ++argi) {
if (Execution::MatchesCommandLineArgument (*argi, L"h")) {
printUsage = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"l")) {
printNames = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"o")) {
oneLineMode = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"r")) {
++argi;
if (argi != args.end ()) {
run.Add (*argi);
}
else {
cerr << "Expected arg to -r" << endl;
return EXIT_FAILURE;
}
}
if (Execution::MatchesCommandLineArgument (*argi, L"t")) {
++argi;
if (argi != args.end ()) {
runFor = Characters::String2Float<Time::DurationSecondsType> (*argi);
}
else {
cerr << "Expected arg to -t" << endl;
return EXIT_FAILURE;
}
}
}
if (printUsage) {
cerr << "Usage: SystemPerformanceClient [-h] [-l] [-f] [-r RUN-INSTRUMENT]*" << endl;
cerr << " -h prints this help" << endl;
cerr << " -o prints instrument results (with newlines stripped)" << endl;
cerr << " -l prints only the instrument names" << endl;
cerr << " -r runs the given instrument (it can be repeated)" << endl;
cerr << " -t time to run for" << endl;
return EXIT_SUCCESS;
}
try {
if (printNames) {
cout << "Instrument:" << endl;
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl;
// print measurements too?
}
return EXIT_SUCCESS;
}
#if 1
Capturer capturer;
{
CaptureSet cs;
cs.SetRunPeriod (Duration (15));
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.fInstrumentName)) {
continue;
}
}
cs.AddInstrument (i);
}
capturer.AddCaptureSet (cs);
}
capturer.AddMeasurementsCallback ([oneLineMode] (MeasurementSet ms) {
cout << " Measured-At: " << ms.fMeasuredAt.Format ().AsNarrowSDKString () << endl;
for (Measurement mi : ms.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
});
// run til timeout and then fall out...
IgnoreExceptionsForCall (Execution::WaitableEvent ().Wait (runFor));
#else
cout << "Results for each instrument:" << endl;
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.fInstrumentName)) {
continue;
}
}
cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl;
MeasurementSet m = i.Capture ();
if (m.fMeasurements.empty ()) {
cout << " NO DATA";
}
else {
cout << " Measured-At: " << m.fMeasuredAt.Format ().AsNarrowSDKString () << endl;
for (Measurement mi : m.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
}
}
#endif
}
catch (...) {
cerr << "Exception - terminating..." << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Updated SamplePerformacneClient so had demo with and without Capturer module<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <iostream>
#include "Stroika/Foundation/Characters/Format.h"
#include "Stroika/Foundation/DataExchange/JSON/Writer.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#if qPlatform_POSIX
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#endif
#include "Stroika/Foundation/Execution/WaitableEvent.h"
#include "Stroika/Foundation/Memory/Optional.h"
#include "Stroika/Foundation/Streams/BasicBinaryOutputStream.h"
#include "Stroika/Frameworks/SystemPerformance/AllInstruments.h"
#include "Stroika/Frameworks/SystemPerformance/Capturer.h"
#include "Stroika/Frameworks/SystemPerformance/Measurement.h"
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using Characters::Character;
using Characters::String;
using Containers::Sequence;
using Memory::Optional;
namespace {
string Serialize_ (VariantValue v, bool oneLineMode)
{
Streams::BasicBinaryOutputStream out;
DataExchange::JSON::Writer ().Write (v, out);
// strip CRLF - so shows up on one line
String result = String::FromUTF8 (out.As<string> ());
if (oneLineMode) {
result = result.StripAll ([] (Character c)-> bool { return c == '\n' or c == '\r';});
}
return result.AsNarrowSDKString ();
}
}
int main (int argc, const char* argv[])
{
#if qPlatform_POSIX
// Many performance instruments use pipes
// @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE?
// --LGP 2014-02-05
Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED);
#endif
bool printUsage = false;
bool printNames = false;
bool oneLineMode = false;
Time::DurationSecondsType runFor = 30.0;
Set<InstrumentNameType> run;
Sequence<String> args = Execution::ParseCommandLine (argc, argv);
for (auto argi = args.begin (); argi != args.end(); ++argi) {
if (Execution::MatchesCommandLineArgument (*argi, L"h")) {
printUsage = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"l")) {
printNames = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"o")) {
oneLineMode = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"r")) {
++argi;
if (argi != args.end ()) {
run.Add (*argi);
}
else {
cerr << "Expected arg to -r" << endl;
return EXIT_FAILURE;
}
}
if (Execution::MatchesCommandLineArgument (*argi, L"t")) {
++argi;
if (argi != args.end ()) {
runFor = Characters::String2Float<Time::DurationSecondsType> (*argi);
}
else {
cerr << "Expected arg to -t" << endl;
return EXIT_FAILURE;
}
}
}
if (printUsage) {
cerr << "Usage: SystemPerformanceClient [-h] [-l] [-f] [-r RUN-INSTRUMENT]*" << endl;
cerr << " -h prints this help" << endl;
cerr << " -o prints instrument results (with newlines stripped)" << endl;
cerr << " -l prints only the instrument names" << endl;
cerr << " -r runs the given instrument (it can be repeated)" << endl;
cerr << " -t time to run for" << endl;
return EXIT_SUCCESS;
}
try {
if (printNames) {
cout << "Instrument:" << endl;
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl;
// print measurements too?
}
return EXIT_SUCCESS;
}
bool useCapturer = runFor > 0;
if (useCapturer) {
/*
* Demo using capturer
*/
Capturer capturer;
{
CaptureSet cs;
cs.SetRunPeriod (Duration (15));
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.fInstrumentName)) {
continue;
}
}
cs.AddInstrument (i);
}
capturer.AddCaptureSet (cs);
}
capturer.AddMeasurementsCallback ([oneLineMode] (MeasurementSet ms) {
cout << " Measured-At: " << ms.fMeasuredAt.Format ().AsNarrowSDKString () << endl;
for (Measurement mi : ms.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
});
// run til timeout and then fall out...
IgnoreExceptionsForCall (Execution::WaitableEvent ().Wait (runFor));
}
else {
/*
* Demo NOT using capturer
*/
cout << "Results for each instrument:" << endl;
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.fInstrumentName)) {
continue;
}
}
cout << " " << i.fInstrumentName.GetPrintName ().AsNarrowSDKString () << endl;
MeasurementSet m = i.Capture ();
if (m.fMeasurements.empty ()) {
cout << " NO DATA";
}
else {
cout << " Measured-At: " << m.fMeasuredAt.Format ().AsNarrowSDKString () << endl;
for (Measurement mi : m.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
}
}
}
}
catch (...) {
cerr << "Exception - terminating..." << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 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/chromeos/extensions/virtual_keyboard_browsertest.h"
#include <vector>
#include "ash/shell.h"
#include "base/command_line.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/common/extension.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/base/ime/input_method.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_switches.h"
namespace {
const base::FilePath::CharType kWebuiTestDir[] = FILE_PATH_LITERAL("webui");
const base::FilePath::CharType kMockController[] =
FILE_PATH_LITERAL("mock_controller.js");
const base::FilePath::CharType kMockTimer[] =
FILE_PATH_LITERAL("mock_timer.js");
const char kVirtualKeyboardTestDir[] = "chromeos/virtual_keyboard";
const char kBaseKeyboardTestFramework[] = "virtual_keyboard_test_base.js";
const char kExtensionId[] = "mppnpdlheglhdfmldimlhpnegondlapf";
const char kVirtualKeyboardURL[] = "chrome://keyboard";
} // namespace
VirtualKeyboardBrowserTestConfig::VirtualKeyboardBrowserTestConfig()
: base_framework_(kBaseKeyboardTestFramework),
extension_id_(kExtensionId),
test_dir_(kVirtualKeyboardTestDir),
url_(kVirtualKeyboardURL) {
}
VirtualKeyboardBrowserTestConfig::~VirtualKeyboardBrowserTestConfig() {};
void VirtualKeyboardBrowserTest::SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(keyboard::switches::kEnableVirtualKeyboard);
}
void VirtualKeyboardBrowserTest::RunTest(
const base::FilePath& file,
const VirtualKeyboardBrowserTestConfig& config) {
ui_test_utils::NavigateToURL(browser(), GURL(config.url_));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::WaitForLoadStop(web_contents);
ASSERT_TRUE(web_contents);
// Inject testing scripts.
InjectJavascript(base::FilePath(kWebuiTestDir),
base::FilePath(kMockController));
InjectJavascript(base::FilePath(kWebuiTestDir), base::FilePath(kMockTimer));
InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)),
base::FilePath(FILE_PATH_LITERAL(config.base_framework_)));
InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)), file);
ASSERT_TRUE(content::ExecuteScript(web_contents, utf8_content_));
// Inject DOM-automation test harness and run tests.
std::vector<int> resource_ids;
EXPECT_TRUE(ExecuteWebUIResourceTest(web_contents, resource_ids));
}
void VirtualKeyboardBrowserTest::ShowVirtualKeyboard() {
aura::Window* window = ash::Shell::GetPrimaryRootWindow();
ui::InputMethod* input_method =
window->GetProperty(aura::client::kRootWindowInputMethodKey);
ASSERT_TRUE(input_method);
input_method->ShowImeIfNeeded();
}
content::RenderViewHost* VirtualKeyboardBrowserTest::GetKeyboardRenderViewHost(
const std::string& id) {
ShowVirtualKeyboard();
GURL url = extensions::Extension::GetBaseURLFromExtensionId(id);
scoped_ptr<content::RenderWidgetHostIterator> widgets(
content::RenderWidgetHost::GetRenderWidgetHosts());
while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
if (widget->IsRenderView()) {
content::RenderViewHost* view = content::RenderViewHost::From(widget);
if (url == view->GetSiteInstance()->GetSiteURL()) {
content::WebContents* wc =
content::WebContents::FromRenderViewHost(view);
// Waits for Polymer to load.
content::WaitForLoadStop(wc);
return view;
}
}
}
LOG(ERROR) << "Extension not found:" << url;
return NULL;
}
void VirtualKeyboardBrowserTest::InjectJavascript(const base::FilePath& dir,
const base::FilePath& file) {
base::FilePath path = ui_test_utils::GetTestFilePath(dir, file);
std::string library_content;
ASSERT_TRUE(base::ReadFileToString(path, &library_content)) << path.value();
utf8_content_.append(library_content);
utf8_content_.append(";\n");
}
// crbug.com/367817. Either this feature or just the test are depending
// on the presense of Object.observe which is presently disabled by default.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_AttributesTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("attributes_test.js")),
VirtualKeyboardBrowserTestConfig());
}
// crbug.com/387372. This test started failing at Blink r176582.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_TypingTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("typing_test.js")),
VirtualKeyboardBrowserTestConfig());
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, ControlKeysTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("control_keys_test.js")),
VirtualKeyboardBrowserTestConfig());
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, HideKeyboardKeyTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("hide_keyboard_key_test.js")),
VirtualKeyboardBrowserTestConfig());
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, KeysetTransitionTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("keyset_transition_test.js")),
VirtualKeyboardBrowserTestConfig());
}
// Fails when enabling Object.observe. See http://crbug.com/370004
#if defined(OS_CHROMEOS)
#define MAYBE_IsKeyboardLoaded DISABLED_IsKeyboardLoaded
#else
#define MAYBE_IsKeyboardLoaded IsKeyboardLoaded
#endif
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, MAYBE_IsKeyboardLoaded) {
content::RenderViewHost* keyboard_rvh =
GetKeyboardRenderViewHost(kExtensionId);
ASSERT_TRUE(keyboard_rvh);
bool loaded = false;
std::string script = "!!chrome.virtualKeyboardPrivate";
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
keyboard_rvh,
"window.domAutomationController.send(" + script + ");",
&loaded));
// Catches the regression in crbug.com/308653.
ASSERT_TRUE(loaded);
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_EndToEndTest) {
// Get the virtual keyboard's render view host.
content::RenderViewHost* keyboard_rvh =
GetKeyboardRenderViewHost(kExtensionId);
ASSERT_TRUE(keyboard_rvh);
// Get the test page's render view host.
content::RenderViewHost* browser_rvh = browser()->tab_strip_model()->
GetActiveWebContents()->GetRenderViewHost();
ASSERT_TRUE(browser_rvh);
// Set up the test page.
GURL url = ui_test_utils::GetTestUrl(
base::FilePath(),
base::FilePath(FILE_PATH_LITERAL(
"chromeos/virtual_keyboard/end_to_end_test.html")));
ui_test_utils::NavigateToURL(browser(), url);
// Press 'a' on keyboard.
base::FilePath path = ui_test_utils::GetTestFilePath(
base::FilePath(FILE_PATH_LITERAL(kVirtualKeyboardTestDir)),
base::FilePath(FILE_PATH_LITERAL("end_to_end_test.js")));
std::string script;
ASSERT_TRUE(base::ReadFileToString(path, &script));
EXPECT_TRUE(content::ExecuteScript(keyboard_rvh, script));
// Verify 'a' appeared on test page.
bool success = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
browser_rvh,
"success ? verifyInput('a') : waitForInput('a');",
&success));
ASSERT_TRUE(success);
}
// TODO(kevers|rsadam|bshe): Add UI tests for remaining virtual keyboard
// functionality.
<commit_msg>Disable failing VirtualKeyboardBrowserTest.ControlKeysTest.<commit_after>/*
* Copyright 2013 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/chromeos/extensions/virtual_keyboard_browsertest.h"
#include <vector>
#include "ash/shell.h"
#include "base/command_line.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/common/extension.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/base/ime/input_method.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_switches.h"
namespace {
const base::FilePath::CharType kWebuiTestDir[] = FILE_PATH_LITERAL("webui");
const base::FilePath::CharType kMockController[] =
FILE_PATH_LITERAL("mock_controller.js");
const base::FilePath::CharType kMockTimer[] =
FILE_PATH_LITERAL("mock_timer.js");
const char kVirtualKeyboardTestDir[] = "chromeos/virtual_keyboard";
const char kBaseKeyboardTestFramework[] = "virtual_keyboard_test_base.js";
const char kExtensionId[] = "mppnpdlheglhdfmldimlhpnegondlapf";
const char kVirtualKeyboardURL[] = "chrome://keyboard";
} // namespace
VirtualKeyboardBrowserTestConfig::VirtualKeyboardBrowserTestConfig()
: base_framework_(kBaseKeyboardTestFramework),
extension_id_(kExtensionId),
test_dir_(kVirtualKeyboardTestDir),
url_(kVirtualKeyboardURL) {
}
VirtualKeyboardBrowserTestConfig::~VirtualKeyboardBrowserTestConfig() {};
void VirtualKeyboardBrowserTest::SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(keyboard::switches::kEnableVirtualKeyboard);
}
void VirtualKeyboardBrowserTest::RunTest(
const base::FilePath& file,
const VirtualKeyboardBrowserTestConfig& config) {
ui_test_utils::NavigateToURL(browser(), GURL(config.url_));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::WaitForLoadStop(web_contents);
ASSERT_TRUE(web_contents);
// Inject testing scripts.
InjectJavascript(base::FilePath(kWebuiTestDir),
base::FilePath(kMockController));
InjectJavascript(base::FilePath(kWebuiTestDir), base::FilePath(kMockTimer));
InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)),
base::FilePath(FILE_PATH_LITERAL(config.base_framework_)));
InjectJavascript(base::FilePath(FILE_PATH_LITERAL(config.test_dir_)), file);
ASSERT_TRUE(content::ExecuteScript(web_contents, utf8_content_));
// Inject DOM-automation test harness and run tests.
std::vector<int> resource_ids;
EXPECT_TRUE(ExecuteWebUIResourceTest(web_contents, resource_ids));
}
void VirtualKeyboardBrowserTest::ShowVirtualKeyboard() {
aura::Window* window = ash::Shell::GetPrimaryRootWindow();
ui::InputMethod* input_method =
window->GetProperty(aura::client::kRootWindowInputMethodKey);
ASSERT_TRUE(input_method);
input_method->ShowImeIfNeeded();
}
content::RenderViewHost* VirtualKeyboardBrowserTest::GetKeyboardRenderViewHost(
const std::string& id) {
ShowVirtualKeyboard();
GURL url = extensions::Extension::GetBaseURLFromExtensionId(id);
scoped_ptr<content::RenderWidgetHostIterator> widgets(
content::RenderWidgetHost::GetRenderWidgetHosts());
while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
if (widget->IsRenderView()) {
content::RenderViewHost* view = content::RenderViewHost::From(widget);
if (url == view->GetSiteInstance()->GetSiteURL()) {
content::WebContents* wc =
content::WebContents::FromRenderViewHost(view);
// Waits for Polymer to load.
content::WaitForLoadStop(wc);
return view;
}
}
}
LOG(ERROR) << "Extension not found:" << url;
return NULL;
}
void VirtualKeyboardBrowserTest::InjectJavascript(const base::FilePath& dir,
const base::FilePath& file) {
base::FilePath path = ui_test_utils::GetTestFilePath(dir, file);
std::string library_content;
ASSERT_TRUE(base::ReadFileToString(path, &library_content)) << path.value();
utf8_content_.append(library_content);
utf8_content_.append(";\n");
}
// crbug.com/367817. Either this feature or just the test are depending
// on the presense of Object.observe which is presently disabled by default.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_AttributesTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("attributes_test.js")),
VirtualKeyboardBrowserTestConfig());
}
// crbug.com/387372. This test started failing at Blink r176582.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_TypingTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("typing_test.js")),
VirtualKeyboardBrowserTestConfig());
}
// crbug.com/387372. This test started failing at Blink r176582.
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_ControlKeysTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("control_keys_test.js")),
VirtualKeyboardBrowserTestConfig());
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, HideKeyboardKeyTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("hide_keyboard_key_test.js")),
VirtualKeyboardBrowserTestConfig());
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, KeysetTransitionTest) {
RunTest(base::FilePath(FILE_PATH_LITERAL("keyset_transition_test.js")),
VirtualKeyboardBrowserTestConfig());
}
// Fails when enabling Object.observe. See http://crbug.com/370004
#if defined(OS_CHROMEOS)
#define MAYBE_IsKeyboardLoaded DISABLED_IsKeyboardLoaded
#else
#define MAYBE_IsKeyboardLoaded IsKeyboardLoaded
#endif
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, MAYBE_IsKeyboardLoaded) {
content::RenderViewHost* keyboard_rvh =
GetKeyboardRenderViewHost(kExtensionId);
ASSERT_TRUE(keyboard_rvh);
bool loaded = false;
std::string script = "!!chrome.virtualKeyboardPrivate";
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
keyboard_rvh,
"window.domAutomationController.send(" + script + ");",
&loaded));
// Catches the regression in crbug.com/308653.
ASSERT_TRUE(loaded);
}
IN_PROC_BROWSER_TEST_F(VirtualKeyboardBrowserTest, DISABLED_EndToEndTest) {
// Get the virtual keyboard's render view host.
content::RenderViewHost* keyboard_rvh =
GetKeyboardRenderViewHost(kExtensionId);
ASSERT_TRUE(keyboard_rvh);
// Get the test page's render view host.
content::RenderViewHost* browser_rvh = browser()->tab_strip_model()->
GetActiveWebContents()->GetRenderViewHost();
ASSERT_TRUE(browser_rvh);
// Set up the test page.
GURL url = ui_test_utils::GetTestUrl(
base::FilePath(),
base::FilePath(FILE_PATH_LITERAL(
"chromeos/virtual_keyboard/end_to_end_test.html")));
ui_test_utils::NavigateToURL(browser(), url);
// Press 'a' on keyboard.
base::FilePath path = ui_test_utils::GetTestFilePath(
base::FilePath(FILE_PATH_LITERAL(kVirtualKeyboardTestDir)),
base::FilePath(FILE_PATH_LITERAL("end_to_end_test.js")));
std::string script;
ASSERT_TRUE(base::ReadFileToString(path, &script));
EXPECT_TRUE(content::ExecuteScript(keyboard_rvh, script));
// Verify 'a' appeared on test page.
bool success = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
browser_rvh,
"success ? verifyInput('a') : waitForInput('a');",
&success));
ASSERT_TRUE(success);
}
// TODO(kevers|rsadam|bshe): Add UI tests for remaining virtual keyboard
// functionality.
<|endoftext|> |
<commit_before>#include <QObject>
#include <QGraphicsSceneMouseEvent>
#include "dcpappletplugin.h"
#include "ut_dcpappletplugin.h"
#include "dcpappletplugin_p.h"
#include "qpluginloader-fake.h"
#include "dcpappletmetadata-fake.h"
void Ut_DcpAppletPlugin::init()
{
}
void Ut_DcpAppletPlugin::cleanup()
{
delete m_subject;
m_subject = 0;
}
void Ut_DcpAppletPlugin::initTestCase()
{
}
void Ut_DcpAppletPlugin::cleanupTestCase()
{
}
/**
* checks if appletloader calls applet's init function
*/
void Ut_DcpAppletPlugin::testLoadBinaryOk()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_BINARY;
qPluginLoaderFakeSuccessful = true;
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(m_subject->applet());
QVERIFY(
dynamic_cast<DcpAppletPluginApplet*>(m_subject->applet())->initialized()
);
delete metadata;
QVERIFY(m_subject->isAppletLoaded());
}
/**
* checks if appletloader returns 0 on load error and
* errorMsg() contains the load error message coming from the QPluginLoader
*/
void Ut_DcpAppletPlugin::testLoadBinaryError()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_BINARY;
qPluginLoaderFakeSuccessful = false;
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(!m_subject->applet());
QVERIFY(m_subject->errorMsg().contains(fakeErrorMsg));
QVERIFY(!m_subject->isAppletLoaded());
delete metadata;
}
/**
* TODO
*/
void Ut_DcpAppletPlugin::testLoadDsl()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_DSL;
QSKIP("TODO: test DSL loading", SkipAll);
}
/**
* checks if metadata() returns the same pointer that was given in
* initialization
*/
void Ut_DcpAppletPlugin::testMetadata()
{
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(m_subject->metadata() == metadata);
delete metadata;
}
void Ut_DcpAppletPlugin::testInterfaceVersion()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_BINARY;
qPluginLoaderFakeSuccessful = true;
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(m_subject->applet());
QCOMPARE(m_subject->interfaceVersion(), 2);
delete m_subject->d_ptr->appletInstance;
m_subject->d_ptr->appletInstance = 0;
QCOMPARE(m_subject->interfaceVersion(), -1);
delete metadata;
}
QTEST_APPLESS_MAIN(Ut_DcpAppletPlugin)
<commit_msg>fixing interface version in ut_dcpappletplugin<commit_after>#include <QObject>
#include <QGraphicsSceneMouseEvent>
#include "dcpappletplugin.h"
#include "ut_dcpappletplugin.h"
#include "dcpappletplugin_p.h"
#include "qpluginloader-fake.h"
#include "dcpappletmetadata-fake.h"
void Ut_DcpAppletPlugin::init()
{
}
void Ut_DcpAppletPlugin::cleanup()
{
delete m_subject;
m_subject = 0;
}
void Ut_DcpAppletPlugin::initTestCase()
{
}
void Ut_DcpAppletPlugin::cleanupTestCase()
{
}
/**
* checks if appletloader calls applet's init function
*/
void Ut_DcpAppletPlugin::testLoadBinaryOk()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_BINARY;
qPluginLoaderFakeSuccessful = true;
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(m_subject->applet());
QVERIFY(
dynamic_cast<DcpAppletPluginApplet*>(m_subject->applet())->initialized()
);
delete metadata;
QVERIFY(m_subject->isAppletLoaded());
}
/**
* checks if appletloader returns 0 on load error and
* errorMsg() contains the load error message coming from the QPluginLoader
*/
void Ut_DcpAppletPlugin::testLoadBinaryError()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_BINARY;
qPluginLoaderFakeSuccessful = false;
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(!m_subject->applet());
QVERIFY(m_subject->errorMsg().contains(fakeErrorMsg));
QVERIFY(!m_subject->isAppletLoaded());
delete metadata;
}
/**
* TODO
*/
void Ut_DcpAppletPlugin::testLoadDsl()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_DSL;
QSKIP("TODO: test DSL loading", SkipAll);
}
/**
* checks if metadata() returns the same pointer that was given in
* initialization
*/
void Ut_DcpAppletPlugin::testMetadata()
{
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(m_subject->metadata() == metadata);
delete metadata;
}
void Ut_DcpAppletPlugin::testInterfaceVersion()
{
DcpAppletMetadataFake::appletType =
DcpAppletMetadataFake::TYPE_BINARY;
qPluginLoaderFakeSuccessful = true;
DcpAppletMetadata *metadata = new DcpAppletMetadata("dummy-binary");
m_subject = new DcpAppletPlugin(metadata);
QVERIFY(m_subject->applet());
QCOMPARE(m_subject->interfaceVersion(), 3);
delete m_subject->d_ptr->appletInstance;
m_subject->d_ptr->appletInstance = 0;
QCOMPARE(m_subject->interfaceVersion(), -1);
delete metadata;
}
QTEST_APPLESS_MAIN(Ut_DcpAppletPlugin)
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdarg>
#include <cstdlib>
#include <iomanip>
#include <limits>
#include <sstream>
#include "../Containers/Common.h"
#include "../Debug/Assertions.h"
#include "../Debug/Trace.h"
#include "../Math/Common.h"
#include "../Memory/SmallStackBuffer.h"
#include "CodePage.h"
#include "Format.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Memory;
/*
********************************************************************************
************************************* Format ***********************************
********************************************************************************
*/
DISABLE_COMPILER_MSC_WARNING_START(6262)
String Characters::FormatV (const wchar_t* format, va_list argsList)
{
RequireNotNull (format);
Memory::SmallStackBuffer<wchar_t, 10 * 1024> msgBuf (10 * 1024);
const wchar_t* useFormat = format;
#if !qStdLibSprintfAssumesPctSIsWideInFormatIfWideFormat
wchar_t newFormat[5 * 1024];
{
size_t origFormatLen = wcslen (format);
Require (origFormatLen < NEltsOf (newFormat) / 2); // just to be sure safe - this is already crazy-big for format string...
// Could use Memory::SmallStackBuffer<> but I doubt this will ever get triggered
bool lookingAtFmtCvt = false;
size_t newFormatIdx = 0;
for (size_t i = 0; i < origFormatLen; ++i) {
if (lookingAtFmtCvt) {
switch (format[i]) {
case '%': {
lookingAtFmtCvt = false;
}
break;
case 's': {
newFormat[newFormatIdx] = 'l';
newFormatIdx++;
lookingAtFmtCvt = false; // DONE
}
break;
case '.': {
// could still be part for format string
}
break;
default: {
if (isdigit (format[i])) {
// could still be part for format string
}
else {
lookingAtFmtCvt = false; // DONE
}
}
break;
}
}
else {
if (format[i] == '%') {
lookingAtFmtCvt = true;
}
}
newFormat[newFormatIdx] = format[i];
newFormatIdx++;
}
Assert (newFormatIdx >= origFormatLen);
if (newFormatIdx > origFormatLen) {
newFormat[newFormatIdx] = '\0';
useFormat = newFormat;
}
}
#endif
#if qSupportValgrindQuirks
// Makes little sense - even msgBuf[0] not sufficient - but this silences lots of warnings.
// -- LGP 2012-05-19
memset (msgBuf, 0, sizeof (msgBuf[0]) * msgBuf.GetSize());
#endif
// Assume only reason for failure is not enuf bytes, so allocate more.
// If I'm wrong, we'll just runout of memory and throw out...
while (::vswprintf (msgBuf, msgBuf.GetSize (), useFormat, argsList) < 0) {
msgBuf.GrowToSize (msgBuf.GetSize () * 2);
}
Assert (::wcslen (msgBuf) < msgBuf.GetSize ());
return String (msgBuf);
}
DISABLE_COMPILER_MSC_WARNING_END(6262)
/*
********************************************************************************
************************************* Format ***********************************
********************************************************************************
*/
String Characters::Format (const wchar_t* format, ...)
{
va_list argsList;
va_start (argsList, format);
String tmp = FormatV (format, argsList);
va_end (argsList);
return move (tmp);
}
/*
********************************************************************************
*************************** StripTrailingCharIfAny *****************************
********************************************************************************
*/
String Characters::StripTrailingCharIfAny (const String& s, wchar_t c)
{
if (s.size () > 0 and s[s.size () - 1] == c) {
String tmp = s;
tmp.erase (tmp.size () - 1);
return tmp;
}
return s;
}
<commit_msg>Cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdarg>
#include <cstdlib>
#include <iomanip>
#include <limits>
#include <sstream>
#include "../Containers/Common.h"
#include "../Debug/Assertions.h"
#include "../Debug/Trace.h"
#include "../Math/Common.h"
#include "../Memory/SmallStackBuffer.h"
#include "CodePage.h"
#include "Format.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Memory;
/*
********************************************************************************
************************************* Format ***********************************
********************************************************************************
*/
DISABLE_COMPILER_MSC_WARNING_START(6262)
String Characters::FormatV (const wchar_t* format, va_list argsList)
{
RequireNotNull (format);
Memory::SmallStackBuffer<wchar_t, 10 * 1024> msgBuf (10 * 1024);
const wchar_t* useFormat = format;
#if !qStdLibSprintfAssumesPctSIsWideInFormatIfWideFormat
wchar_t newFormat[5 * 1024];
{
size_t origFormatLen = wcslen (format);
Require (origFormatLen < NEltsOf (newFormat) / 2); // just to be sure safe - this is already crazy-big for format string...
// Could use Memory::SmallStackBuffer<> but I doubt this will ever get triggered
bool lookingAtFmtCvt = false;
size_t newFormatIdx = 0;
for (size_t i = 0; i < origFormatLen; ++i) {
if (lookingAtFmtCvt) {
switch (format[i]) {
case '%': {
lookingAtFmtCvt = false;
}
break;
case 's': {
newFormat[newFormatIdx] = 'l';
newFormatIdx++;
lookingAtFmtCvt = false; // DONE
}
break;
case '.': {
// could still be part for format string
}
break;
default: {
if (isdigit (format[i])) {
// could still be part for format string
}
else {
lookingAtFmtCvt = false; // DONE
}
}
break;
}
}
else {
if (format[i] == '%') {
lookingAtFmtCvt = true;
}
}
newFormat[newFormatIdx] = format[i];
newFormatIdx++;
}
Assert (newFormatIdx >= origFormatLen);
if (newFormatIdx > origFormatLen) {
newFormat[newFormatIdx] = '\0';
useFormat = newFormat;
}
}
#endif
#if qSupportValgrindQuirks
// Makes little sense - even msgBuf[0] not sufficient - but this silences lots of warnings.
// -- LGP 2012-05-19
memset (msgBuf, 0, sizeof (msgBuf[0]) * msgBuf.GetSize());
#endif
// Assume only reason for failure is not enuf bytes, so allocate more.
// If I'm wrong, we'll just runout of memory and throw out...
while (::vswprintf (msgBuf, msgBuf.GetSize (), useFormat, argsList) < 0) {
msgBuf.GrowToSize (msgBuf.GetSize () * 2);
}
Assert (::wcslen (msgBuf) < msgBuf.GetSize ());
return String (msgBuf);
}
DISABLE_COMPILER_MSC_WARNING_END(6262)
/*
********************************************************************************
************************************* Format ***********************************
********************************************************************************
*/
String Characters::Format (const wchar_t* format, ...)
{
va_list argsList;
va_start (argsList, format);
String tmp = FormatV (format, argsList);
va_end (argsList);
return move (tmp);
}
/*
********************************************************************************
*************************** StripTrailingCharIfAny *****************************
********************************************************************************
*/
String Characters::StripTrailingCharIfAny (const String& s, wchar_t c)
{
if (s.size () > 0 and s[s.size () - 1] == c) {
String tmp = s;
tmp.erase (tmp.size () - 1);
return tmp;
}
return s;
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Chain drive.
//
// =============================================================================
#include <cstdio>
#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
#include "assets/ChAssetLevel.h"
#include "physics/ChGlobal.h"
#include "DriveChain.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
// collision mesh
#include "geometry/ChCTriangleMeshSoup.h"
namespace chrono {
// -----------------------------------------------------------------------------
// Static variables
// idler, relative to gear/chassis
const ChVector<> DriveChain::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys
const ChQuaternion<> DriveChain::m_idlerRot(QUNIT);
/// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff
DriveChain::DriveChain(const std::string& name, VisualizationType vis, CollisionType collide)
: m_ownsSystem(true),
m_stepsize(1e-3),
m_num_idlers(1)
{
// Integration and Solver settings
SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
SetIterLCPmaxItersSpeed(150);
SetIterLCPmaxItersStab(150);
SetMaxPenetrationRecoverySpeed(2.0);
// SetIterLCPomega(2.0);
// SetIterLCPsharpnessLambda(2.0);
// create the chassis body
m_chassis = ChSharedPtr<ChBody>(new ChBody);
m_chassis->SetIdentifier(0);
m_chassis->SetNameString(name);
// basic body info. Not relevant since it's fixed.
m_chassis->SetMass(100);
m_chassis->SetInertiaXX(ChVector<>(10,10,10));
// chassis is fixed to ground
m_chassis->SetBodyFixed(true);
// add the chassis body to the system
Add(m_chassis);
// build one of each of the following subsystems.
m_gear = ChSharedPtr<DriveGear>(new DriveGear("drive gear",
vis, //VisualizationType::PRIMITIVES,
collide)); //CollisionType::PRIMITIVES) );
m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler",
vis, // VisualizationType::PRIMITIVES,
collide)); // CollisionType::PRIMITIVES) );
m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain",
vis, // VisualizationType::PRIMITIVES,
collide)); // CollisionType::PRIMITIVES) );
// create the powertrain and drivelines
m_driveline = ChSharedPtr<TrackDriveline_1WD>(new TrackDriveline_1WD("driveline ") );
m_ptrain = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain ") );
}
DriveChain::~DriveChain()
{
if(m_ownsSystem)
delete m_system;
}
// Set any collision geometry on the hull, then Initialize() all subsystems
void DriveChain::Initialize(const ChCoordsys<>& gear_Csys)
{
// initialize the drive gear, idler and track chain
m_idlerPosRel = m_idlerPos;
m_chassis->SetPos(gear_Csys.pos);
m_chassis->SetRot(gear_Csys.rot);
// initialize 1 of each of the following subsystems.
// will use the chassis ref frame to do the transforms, since the TrackSystem
// local ref. frame has same rot (just difference in position)
m_gear->Initialize(m_chassis,
m_chassis->GetFrame_REF_to_abs(),
ChCoordsys<>());
m_idler->Initialize(m_chassis,
m_chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_idlerPosRel, QUNIT) );
// Create list of the center location of the rolling elements and their clearance.
// Clearance is a sphere shaped envelope at each center location, where it can
// be guaranteed that the track chain geometry will not penetrate the sphere.
std::vector<ChVector<>> rolling_elem_locs; // w.r.t. chassis ref. frame
std::vector<double> clearance; // 1 per rolling elem
// drive sprocket is First added to the lists passed into TrackChain Init()
rolling_elem_locs.push_back(gear_Csys.pos );
clearance.push_back(m_gear->GetRadius() );
// add to the lists passed into the track chain Init()
rolling_elem_locs.push_back(m_idlerPosRel );
clearance.push_back(m_idler->GetRadius() );
// Assumption: start_pos should lie close to where the actual track chain would
// pass between the idler and driveGears.
// MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
// rolling_elem_locs, start_pos w.r.t. chassis c-sys
m_chain->Initialize(m_chassis,
m_chassis->GetFrame_REF_to_abs(),
rolling_elem_locs, clearance, ChVector<>(m_gear->GetRadius(),0,0) );
// initialize the powertrain, drivelines
m_driveline->Initialize(m_chassis, m_gear);
m_ptrain->Initialize(m_chassis, m_driveline->GetDriveshaft() );
}
void DriveChain::Update(double time,
double throttle,
double braking)
{
// update left and right powertrains, with the new left and right throttle/shaftspeed
m_ptrain->Update(time, throttle, m_driveline->GetDriveshaftSpeed() );
}
void DriveChain::Advance(double step)
{
double t = 0;
double settlePhaseA = 0.001;
double settlePhaseB = 0.1;
while (t < step) {
double h = std::min<>(m_stepsize, step - t);
if( GetChTime() < settlePhaseA )
{
h = 1e-5;
} else if ( GetChTime() < settlePhaseB )
{
h = 1e-4;
}
DoStepDynamics(h);
t += h;
}
}
double DriveChain::GetIdlerForce(size_t idler_idx)
{
assert(idler_idx < m_num_idlers);
// only 1 idler, for now
ChVector<> out_force = m_idler->GetSpringForce();
return out_force.Length();
}
} // end namespace chrono
<commit_msg>remove code that's now in the abstract class.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Chain drive.
//
// =============================================================================
#include <cstdio>
#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
#include "assets/ChAssetLevel.h"
#include "physics/ChGlobal.h"
#include "DriveChain.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
// collision mesh
#include "geometry/ChCTriangleMeshSoup.h"
namespace chrono {
// -----------------------------------------------------------------------------
// Static variables
// idler, relative to gear/chassis
const ChVector<> DriveChain::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys
const ChQuaternion<> DriveChain::m_idlerRot(QUNIT);
/// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff
DriveChain::DriveChain(const std::string& name, VisualizationType vis, CollisionType collide)
: m_ownsSystem(true),
m_stepsize(1e-3),
m_num_idlers(1)
{
// Integration and Solver settings set in ChTrackVehicle
// create the chassis body
m_chassis = ChSharedPtr<ChBody>(new ChBody);
m_chassis->SetIdentifier(0);
m_chassis->SetNameString(name);
// basic body info. Not relevant since it's fixed.
m_chassis->SetMass(100);
m_chassis->SetInertiaXX(ChVector<>(10,10,10));
// chassis is fixed to ground
m_chassis->SetBodyFixed(true);
// add the chassis body to the system
m_system->Add(m_chassis);
// build one of each of the following subsystems.
m_gear = ChSharedPtr<DriveGear>(new DriveGear("drive gear",
vis, //VisualizationType::PRIMITIVES,
collide)); //CollisionType::PRIMITIVES) );
m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler",
vis, // VisualizationType::PRIMITIVES,
collide)); // CollisionType::PRIMITIVES) );
m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain",
vis, // VisualizationType::PRIMITIVES,
collide)); // CollisionType::PRIMITIVES) );
// create the powertrain and drivelines
m_driveline = ChSharedPtr<TrackDriveline_1WD>(new TrackDriveline_1WD("driveline ") );
m_ptrain = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain ") );
}
DriveChain::~DriveChain()
{
if(m_ownsSystem)
delete m_system;
}
// Set any collision geometry on the hull, then Initialize() all subsystems
void DriveChain::Initialize(const ChCoordsys<>& gear_Csys)
{
// initialize the drive gear, idler and track chain
m_idlerPosRel = m_idlerPos;
m_chassis->SetPos(gear_Csys.pos);
m_chassis->SetRot(gear_Csys.rot);
// initialize 1 of each of the following subsystems.
// will use the chassis ref frame to do the transforms, since the TrackSystem
// local ref. frame has same rot (just difference in position)
m_gear->Initialize(m_chassis,
m_chassis->GetFrame_REF_to_abs(),
ChCoordsys<>());
m_idler->Initialize(m_chassis,
m_chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_idlerPosRel, QUNIT) );
// Create list of the center location of the rolling elements and their clearance.
// Clearance is a sphere shaped envelope at each center location, where it can
// be guaranteed that the track chain geometry will not penetrate the sphere.
std::vector<ChVector<>> rolling_elem_locs; // w.r.t. chassis ref. frame
std::vector<double> clearance; // 1 per rolling elem
// drive sprocket is First added to the lists passed into TrackChain Init()
rolling_elem_locs.push_back(gear_Csys.pos );
clearance.push_back(m_gear->GetRadius() );
// add to the lists passed into the track chain Init()
rolling_elem_locs.push_back(m_idlerPosRel );
clearance.push_back(m_idler->GetRadius() );
// Assumption: start_pos should lie close to where the actual track chain would
// pass between the idler and driveGears.
// MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
// rolling_elem_locs, start_pos w.r.t. chassis c-sys
m_chain->Initialize(m_chassis,
m_chassis->GetFrame_REF_to_abs(),
rolling_elem_locs, clearance, ChVector<>(m_gear->GetRadius(),0,0) );
// initialize the powertrain, drivelines
m_driveline->Initialize(m_chassis, m_gear);
m_ptrain->Initialize(m_chassis, m_driveline->GetDriveshaft() );
}
void DriveChain::Update(double time,
double throttle,
double braking)
{
// update left and right powertrains, with the new left and right throttle/shaftspeed
m_ptrain->Update(time, throttle, m_driveline->GetDriveshaftSpeed() );
}
void DriveChain::Advance(double step)
{
double t = 0;
double settlePhaseA = 0.001;
double settlePhaseB = 0.1;
while (t < step) {
double h = std::min<>(m_stepsize, step - t);
if( m_system->GetChTime() < settlePhaseA )
{
h = 1e-5;
} else if ( m_system->GetChTime() < settlePhaseB )
{
h = 1e-4;
}
m_system->DoStepDynamics(h);
t += h;
}
}
double DriveChain::GetIdlerForce(size_t idler_idx)
{
assert(idler_idx < m_num_idlers);
// only 1 idler, for now
ChVector<> out_force = m_idler->GetSpringForce();
return out_force.Length();
}
} // end namespace chrono
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkDummyImageToListAdaptorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <time.h>
#include "itkFixedArray.h"
#include "itkImageAdaptor.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkObject.h"
#include "itkMacro.h"
#include "itkPixelTraits.h"
#include "vcl/vcl_config_compiler.h"
#include "itkListSampleBase.h"
#include "itkImageToListAdaptor.h"
#include "itkScalarToArrayCastImageFilter.h"
// #ifdef VCL_CAN_DO_PARTIAL_SPECIALIZATION
template < class TImage, class TMeasurementVector = typename TImage::PixelType >
class DummyImageToListAdaptor :
// public itk::Statistics::ListSampleBase<
// itk::FixedArray< typename MyPixelTraits< typename TImage::PixelType >::ValueType,
// MyPixelTraits< typename TImage::PixelType >::Dimension > >
public itk::Object
{
public:
typedef DummyImageToListAdaptor Self ;
typedef itk::Object Superclass ;
typedef itk::SmartPointer< Self > Pointer ;
typedef itk::SmartPointer< const Self > ConstPointer ;
itkTypeMacro( DummyImageToListAdaptor, Object ) ;
itkNewMacro( Self ) ;
typedef typename TImage::PixelType PixelType ;
typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ;
itkStaticConstMacro( MeasurementVectorSize, unsigned int,
itk::PixelTraits< PixelType >::Dimension ) ;
typedef TMeasurementVector MeasurementVectorType ;
void SetImage( TImage* image )
{
m_Image = image ;
m_ImageBuffer = m_Image->GetPixelContainer() ;
if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 )
{
m_UseBuffer = false ;
}
else
{
m_UseBuffer = true ;
}
}
MeasurementVectorType& GetMeasurementVector(int id)
{
if( m_UseBuffer )
{
return *(reinterpret_cast< TMeasurementVector* >
( &(*m_ImageBuffer)[id] ) ) ;
}
else
{
return *(reinterpret_cast< TMeasurementVector* >
( &(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ;
}
}
protected:
DummyImageToListAdaptor()
{
m_Image = 0 ;
}
virtual ~DummyImageToListAdaptor() {}
private:
DummyImageToListAdaptor(const Self&) ;
void operator=(const Self&) ;
typename TImage::Pointer m_Image ;
typename TImage::PixelContainer* m_ImageBuffer ;
bool m_UseBuffer ;
} ;
int itkDummyImageToListAdaptorTest(int, char* [] )
{
typedef int ScalarPixelType ;
typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ;
typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ;
typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ;
typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ;
typedef itk::Image< VectorPixelType, 3 > VectorImageType ;
typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ;
typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ;
typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ;
itk::Size< 3 > size ;
size.Fill(100) ;
ScalarImageType::Pointer scalarImage = ScalarImageType::New() ;
scalarImage->SetRegions(size) ;
scalarImage->Allocate() ;
int count = 0 ;
ScalarImageIteratorType s_iter =
ScalarImageIteratorType(scalarImage,
scalarImage->GetLargestPossibleRegion() ) ;
while ( !s_iter.IsAtEnd() )
{
s_iter.Set(count) ;
++count ;
++s_iter ;
}
VectorImageType::Pointer vectorImage = VectorImageType::New() ;
vectorImage->SetRegions(size) ;
vectorImage->Allocate() ;
count = 0 ;
VectorImageType::PixelType vPixel ;
VectorImageIteratorType v_iter =
VectorImageIteratorType(vectorImage,
vectorImage->GetLargestPossibleRegion()) ;
while ( !v_iter.IsAtEnd() )
{
vPixel[0] = count ;
vPixel[1] = count ;
v_iter.Set( vPixel ) ;
++count ;
++v_iter ;
}
typedef DummyImageToListAdaptor< ScalarImageType,
itk::FixedArray< ScalarPixelType , 1 > > ScalarListType ;
ScalarListType::Pointer sList = ScalarListType::New() ;
sList->SetImage( scalarImage ) ;
typedef DummyImageToListAdaptor< VectorImageType > VectorListType ;
VectorListType::Pointer vList = VectorListType::New() ;
vList->SetImage( vectorImage ) ;
typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ;
CasterType::Pointer caster = CasterType::New() ;
caster->SetInput( scalarImage ) ;
caster->Update() ;
typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ;
ImageListType::Pointer imageList = ImageListType::New() ;
imageList->SetImage( caster->GetOutput() ) ;
std::cout << "Testing the each measurement values:" << std::endl ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
if ( sList->GetMeasurementVector( i )[0] != vList->GetMeasurementVector( i )[0]
|| sList->GetMeasurementVector( i )[0] != imageList->GetMeasurementVector( i )[0] )
{
std::cout << "ERROR: measurement mismatch!!!" << std::endl ;
return EXIT_FAILURE ;
}
}
std::cout << std::endl ;
std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ;
time_t begin = clock() ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
ArrayPixelType& temp = imageList->GetMeasurementVector( i ) ;
}
time_t end = clock() ;
std::cout << "time: "
<< (double(end - begin) /CLOCKS_PER_SEC)
<< " seconds" << std::endl ;
std::cout << "Scalar image pixel access performance test:" << std::endl ;
begin = clock() ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
ArrayPixelType& temp = sList->GetMeasurementVector( i ) ;
}
end = clock() ;
std::cout << "time: "
<< (double(end - begin) /CLOCKS_PER_SEC)
<< " seconds" << std::endl ;
std::cout << "Vector image pixel access performance test:" << std::endl ;
begin = clock() ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
VectorPixelType& temp = vList->GetMeasurementVector( i ) ;
}
end = clock() ;
std::cout << "time: "
<< (double(end - begin) /CLOCKS_PER_SEC)
<< " seconds" << std::endl ;
return EXIT_SUCCESS ;
}
<commit_msg><commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkDummyImageToListAdaptorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <time.h>
#include "itkFixedArray.h"
#include "itkImageAdaptor.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkObject.h"
#include "itkMacro.h"
#include "itkPixelTraits.h"
#include "itkListSampleBase.h"
#include "itkImageToListAdaptor.h"
#include "itkScalarToArrayCastImageFilter.h"
// #ifdef VCL_CAN_DO_PARTIAL_SPECIALIZATION
template < class TImage, class TMeasurementVector = typename TImage::PixelType >
class DummyImageToListAdaptor :
// public itk::Statistics::ListSampleBase<
// itk::FixedArray< typename MyPixelTraits< typename TImage::PixelType >::ValueType,
// MyPixelTraits< typename TImage::PixelType >::Dimension > >
public itk::Object
{
public:
typedef DummyImageToListAdaptor Self ;
typedef itk::Object Superclass ;
typedef itk::SmartPointer< Self > Pointer ;
typedef itk::SmartPointer< const Self > ConstPointer ;
itkTypeMacro( DummyImageToListAdaptor, Object ) ;
itkNewMacro( Self ) ;
typedef typename TImage::PixelType PixelType ;
typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ;
itkStaticConstMacro( MeasurementVectorSize, unsigned int,
itk::PixelTraits< PixelType >::Dimension ) ;
typedef TMeasurementVector MeasurementVectorType ;
void SetImage( TImage* image )
{
m_Image = image ;
m_ImageBuffer = m_Image->GetPixelContainer() ;
if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 )
{
m_UseBuffer = false ;
}
else
{
m_UseBuffer = true ;
}
}
MeasurementVectorType& GetMeasurementVector(int id)
{
if( m_UseBuffer )
{
return *(reinterpret_cast< TMeasurementVector* >
( &(*m_ImageBuffer)[id] ) ) ;
}
else
{
return *(reinterpret_cast< TMeasurementVector* >
( &(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ;
}
}
protected:
DummyImageToListAdaptor()
{
m_Image = 0 ;
}
virtual ~DummyImageToListAdaptor() {}
private:
DummyImageToListAdaptor(const Self&) ;
void operator=(const Self&) ;
typename TImage::Pointer m_Image ;
typename TImage::PixelContainer* m_ImageBuffer ;
bool m_UseBuffer ;
} ;
int itkDummyImageToListAdaptorTest(int, char* [] )
{
typedef int ScalarPixelType ;
typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ;
typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ;
typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ;
typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ;
typedef itk::Image< VectorPixelType, 3 > VectorImageType ;
typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ;
typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ;
typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ;
itk::Size< 3 > size ;
size.Fill(100) ;
ScalarImageType::Pointer scalarImage = ScalarImageType::New() ;
scalarImage->SetRegions(size) ;
scalarImage->Allocate() ;
int count = 0 ;
ScalarImageIteratorType s_iter =
ScalarImageIteratorType(scalarImage,
scalarImage->GetLargestPossibleRegion() ) ;
while ( !s_iter.IsAtEnd() )
{
s_iter.Set(count) ;
++count ;
++s_iter ;
}
VectorImageType::Pointer vectorImage = VectorImageType::New() ;
vectorImage->SetRegions(size) ;
vectorImage->Allocate() ;
count = 0 ;
VectorImageType::PixelType vPixel ;
VectorImageIteratorType v_iter =
VectorImageIteratorType(vectorImage,
vectorImage->GetLargestPossibleRegion()) ;
while ( !v_iter.IsAtEnd() )
{
vPixel[0] = count ;
vPixel[1] = count ;
v_iter.Set( vPixel ) ;
++count ;
++v_iter ;
}
typedef DummyImageToListAdaptor< ScalarImageType,
itk::FixedArray< ScalarPixelType , 1 > > ScalarListType ;
ScalarListType::Pointer sList = ScalarListType::New() ;
sList->SetImage( scalarImage ) ;
typedef DummyImageToListAdaptor< VectorImageType > VectorListType ;
VectorListType::Pointer vList = VectorListType::New() ;
vList->SetImage( vectorImage ) ;
typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ;
CasterType::Pointer caster = CasterType::New() ;
caster->SetInput( scalarImage ) ;
caster->Update() ;
typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ;
ImageListType::Pointer imageList = ImageListType::New() ;
imageList->SetImage( caster->GetOutput() ) ;
std::cout << "Testing the each measurement values:" << std::endl ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
if ( sList->GetMeasurementVector( i )[0] != vList->GetMeasurementVector( i )[0]
|| sList->GetMeasurementVector( i )[0] != imageList->GetMeasurementVector( i )[0] )
{
std::cout << "ERROR: measurement mismatch!!!" << std::endl ;
return EXIT_FAILURE ;
}
}
std::cout << std::endl ;
std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ;
time_t begin = clock() ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
ArrayPixelType& temp = imageList->GetMeasurementVector( i ) ;
}
time_t end = clock() ;
std::cout << "time: "
<< (double(end - begin) /CLOCKS_PER_SEC)
<< " seconds" << std::endl ;
std::cout << "Scalar image pixel access performance test:" << std::endl ;
begin = clock() ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
ArrayPixelType& temp = sList->GetMeasurementVector( i ) ;
}
end = clock() ;
std::cout << "time: "
<< (double(end - begin) /CLOCKS_PER_SEC)
<< " seconds" << std::endl ;
std::cout << "Vector image pixel access performance test:" << std::endl ;
begin = clock() ;
for ( int i = 0 ; i < size[0] * size[1] * size[2] ; ++i )
{
VectorPixelType& temp = vList->GetMeasurementVector( i ) ;
}
end = clock() ;
std::cout << "time: "
<< (double(end - begin) /CLOCKS_PER_SEC)
<< " seconds" << std::endl ;
return EXIT_SUCCESS ;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pwd.h>
using namespace std;
bool inside = false;
void handler(int signum)
{
if(signum == SIGINT){
if(SIG_ERR == (signal(SIGINT, handler))){
perror("signal");
exit(1);
}
if(inside){
exit(1);
}
}
return;
}
int main()
{
bool run= true;
if(SIG_ERR == (signal(SIGINT, handler))){
perror("signal");
exit(1);
}
char* char_dir = get_current_dir_name();
string curr_dir = char_dir;
string prev_dir = curr_dir;
free(char_dir);
while(run)
{
bool changedir = false;
//extra credit part
char* username;
char hostname[128];
char_dir = get_current_dir_name();
prev_dir = curr_dir;
curr_dir = char_dir;
free(char_dir);
username = getlogin();
if(NULL == username)
{
perror("getlogin");
exit(1);
}
int errorhost = gethostname(hostname, 128);
if(errorhost == -1){
perror("gethostname");
exit(1);
}
cerr << username << "@" << hostname << ":~" << curr_dir << " $ ";
//get command
vector<char*> commandvector;
char* token;
char* fullcommand;
fullcommand = new char[600];
string stringcommand;
//
getline(cin, stringcommand);
memcpy(fullcommand, stringcommand.c_str(), stringcommand.size()+1);
//break command into smaller pieces according to ";"
token = strtok(fullcommand, ";");
while(token != NULL)
{
commandvector.push_back(token);
token = strtok(NULL, ";");
}
for(unsigned x = 0; x < commandvector.size(); x++)
{
//ints and bools for redirection
int new_in = -2, new_out = -2, new_append = -2;
int old_in = -2, old_out = -2, old_append = -2;
bool do_in = false, do_out = false, do_append = false;
int out_file = 1;
char** argv = new char*[400];
char* token2 = strtok(commandvector.at(x), " ");
int y = 0;
bool iscomment = false;
for(; (token2 != NULL) && (!iscomment); y++)
{
string stringtoken2 = token2;
if(stringtoken2 == "exit"){
delete [] argv;
delete [] fullcommand;
return 0;
}
if(stringtoken2.at(0) == '#'){
iscomment = true;
token2 = NULL;
commandvector.clear();
}
if(stringtoken2 == "cd" && y == 0)
{
token2 = strtok(NULL, " ");
char dash[] = "-";
if(token2 == NULL){
struct passwd *pw = getpwuid(getuid());
if(-1 == chdir(pw->pw_dir)){
perror("homedir");
exit(1);
}
}
else if(strcmp(dash, token2) == 0)
{
if(-1 == chdir(prev_dir.c_str()))
{
perror("prev_dir");
exit(1);
}
}
else if(-1 == chdir(token2))
{
perror("chdir");
exit(1);
}
changedir = true;
}
for(unsigned i = 0; i < stringtoken2.size(); i++)
{
if(stringtoken2.at(i) == '<')
{
do_in = true;
}
else if(stringtoken2.at(i) == '>'){
if(stringtoken2.size() > 1 && !(do_append||do_out))
{
if(stringtoken2.size() - 1 > i){
if(stringtoken2.at(i+1) == '>')
{
do_append = true;
}
}
if(i > 0)
{
if(token2[i-1] >= '0' && token2[i-1] <= '9')
{
out_file = token2[i-1] - 48;
}
}
}
if(!(do_append))
{
do_out = true;
}
}
}
if(!(iscomment|do_in|do_out|do_append)){
argv[y] = token2;
token2 = strtok(NULL, " ");
}
else if(do_in)
{
token2 = strtok(NULL, " ");
new_in = open(token2, O_CREAT | O_RDONLY, 0666);
if(new_in < 0)
{
perror("new_in open");
exit(1);
}
do_in = false;
token2 = strtok(NULL, " ");
}
else if(do_out)
{
token2 = strtok(NULL, " ");
new_out = open(token2, O_CREAT | O_TRUNC | O_WRONLY, 0666);
if(new_out < 0)
{
perror("new_out open");
exit(1);
}
do_out = false;
token2 = strtok(NULL, " ");
}
else if(do_append)
{
token2 = strtok(NULL, " ");
new_append = open(token2, O_CREAT | O_APPEND | O_WRONLY, 0666);
if(new_append < 0)
{
perror("new_append open");
exit(1);
}
do_append = false;
token2 = strtok(NULL, " ");
}
}
argv[y] = NULL;
if(changedir){
continue;
}
int pid = fork();
if(pid == -1){
perror("fork");
exit(1);
}
if(pid == 0)
{
if(new_in != -2){
if(-1 == (old_in = dup(0))){
perror("dup old_in");
exit(1);
}
if( -1 == close(0)){
perror("close 0");
exit(1);
}
if(-1 == dup(new_in)){
perror("dup new_in");
exit(1);
}
}
if(new_out != -2){
if(-1 == (old_out = dup(out_file))){
perror("dup out");
exit(1);
}
if( -1 == close(out_file)){
perror("close 1 out");
exit(1);
}
if(-1 == dup(new_out)){
perror("dup new_out");
exit(1);
}
}
if(new_append != -2){
if(-1 == (old_append = dup(out_file))){
perror("dup new_append");
exit(1);
}
if( -1 == close(out_file)){
perror("close 1 append");
exit(1);
}
if(-1 == dup(new_append)){
perror("dup new_append");
exit(1);
}
}
inside = true;
int execvperror = execvp(argv[0], argv);
if(execvperror == -1){
perror("execvp");
exit(1);
}
}
else
{
int waiterror = wait(NULL);
if(waiterror == -1)
{
perror("wait");
exit(1);
}
}
delete [] argv;
delete [] fullcommand;
}
}
return 0;
}
<commit_msg>fixed ; bug<commit_after>#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pwd.h>
using namespace std;
bool inside = false;
void handler(int signum)
{
if(signum == SIGINT){
if(SIG_ERR == (signal(SIGINT, handler))){
perror("signal");
exit(1);
}
if(inside){
exit(1);
}
}
return;
}
int main()
{
bool run= true;
if(SIG_ERR == (signal(SIGINT, handler))){
perror("signal");
exit(1);
}
char* char_dir = get_current_dir_name();
string curr_dir = char_dir;
string prev_dir = curr_dir;
free(char_dir);
while(run)
{
bool changedir = false;
//extra credit part
char* username;
char hostname[128];
char_dir = get_current_dir_name();
prev_dir = curr_dir;
curr_dir = char_dir;
free(char_dir);
username = getlogin();
if(NULL == username)
{
perror("getlogin");
exit(1);
}
int errorhost = gethostname(hostname, 128);
if(errorhost == -1){
perror("gethostname");
exit(1);
}
cerr << username << "@" << hostname << ":~" << curr_dir << " $ ";
//get command
vector<char*> commandvector;
char* token;
char* fullcommand;
fullcommand = new char[600];
string stringcommand;
//
getline(cin, stringcommand);
memcpy(fullcommand, stringcommand.c_str(), stringcommand.size()+1);
//break command into smaller pieces according to ";"
token = strtok(fullcommand, ";");
while(token != NULL)
{
commandvector.push_back(token);
token = strtok(NULL, ";");
}
for(unsigned x = 0; x < commandvector.size(); x++)
{
//ints and bools for redirection
int new_in = -2, new_out = -2, new_append = -2;
int old_in = -2, old_out = -2, old_append = -2;
bool do_in = false, do_out = false, do_append = false;
int out_file = 1;
char** argv = new char*[400];
char* token2 = strtok(commandvector.at(x), " ");
int y = 0;
bool iscomment = false;
for(; (token2 != NULL) && (!iscomment); y++)
{
string stringtoken2 = token2;
if(stringtoken2 == "exit"){
delete [] argv;
delete [] fullcommand;
return 0;
}
if(stringtoken2.at(0) == '#'){
iscomment = true;
token2 = NULL;
commandvector.clear();
}
if(stringtoken2 == "cd" && y == 0)
{
token2 = strtok(NULL, " ");
char dash[] = "-";
if(token2 == NULL){
struct passwd *pw = getpwuid(getuid());
if(-1 == chdir(pw->pw_dir)){
perror("homedir");
exit(1);
}
}
else if(strcmp(dash, token2) == 0)
{
if(-1 == chdir(prev_dir.c_str()))
{
perror("prev_dir");
exit(1);
}
}
else if(-1 == chdir(token2))
{
perror("chdir");
exit(1);
}
changedir = true;
}
for(unsigned i = 0; i < stringtoken2.size(); i++)
{
if(stringtoken2.at(i) == '<')
{
do_in = true;
}
else if(stringtoken2.at(i) == '>'){
if(stringtoken2.size() > 1 && !(do_append||do_out))
{
if(stringtoken2.size() - 1 > i){
if(stringtoken2.at(i+1) == '>')
{
do_append = true;
}
}
if(i > 0)
{
if(token2[i-1] >= '0' && token2[i-1] <= '9')
{
out_file = token2[i-1] - 48;
}
}
}
if(!(do_append))
{
do_out = true;
}
}
}
if(!(iscomment|do_in|do_out|do_append)){
argv[y] = token2;
token2 = strtok(NULL, " ");
}
else if(do_in)
{
token2 = strtok(NULL, " ");
new_in = open(token2, O_CREAT | O_RDONLY, 0666);
if(new_in < 0)
{
perror("new_in open");
exit(1);
}
do_in = false;
token2 = strtok(NULL, " ");
}
else if(do_out)
{
token2 = strtok(NULL, " ");
new_out = open(token2, O_CREAT | O_TRUNC | O_WRONLY, 0666);
if(new_out < 0)
{
perror("new_out open");
exit(1);
}
do_out = false;
token2 = strtok(NULL, " ");
}
else if(do_append)
{
token2 = strtok(NULL, " ");
new_append = open(token2, O_CREAT | O_APPEND | O_WRONLY, 0666);
if(new_append < 0)
{
perror("new_append open");
exit(1);
}
do_append = false;
token2 = strtok(NULL, " ");
}
}
argv[y] = NULL;
if(changedir){
continue;
}
int pid = fork();
if(pid == -1){
perror("fork");
exit(1);
}
if(pid == 0)
{
if(new_in != -2){
if(-1 == (old_in = dup(0))){
perror("dup old_in");
exit(1);
}
if( -1 == close(0)){
perror("close 0");
exit(1);
}
if(-1 == dup(new_in)){
perror("dup new_in");
exit(1);
}
}
if(new_out != -2){
if(-1 == (old_out = dup(out_file))){
perror("dup out");
exit(1);
}
if( -1 == close(out_file)){
perror("close 1 out");
exit(1);
}
if(-1 == dup(new_out)){
perror("dup new_out");
exit(1);
}
}
if(new_append != -2){
if(-1 == (old_append = dup(out_file))){
perror("dup new_append");
exit(1);
}
if( -1 == close(out_file)){
perror("close 1 append");
exit(1);
}
if(-1 == dup(new_append)){
perror("dup new_append");
exit(1);
}
}
inside = true;
int execvperror = execvp(argv[0], argv);
if(execvperror == -1){
perror("execvp");
exit(1);
}
}
else
{
int waiterror = wait(NULL);
if(waiterror == -1)
{
perror("wait");
exit(1);
}
}
delete [] argv;
}
delete [] fullcommand;
}
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.