text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "rdb_protocol/artificial_table/cfeed_backend.hpp"
#include "concurrency/cross_thread_signal.hpp"
/* We destroy the machinery if there have been no changefeeds for this many seconds */
static const int machinery_expiration_secs = 60;
void cfeed_artificial_table_backend_t::machinery_t::send_all_change(
const store_key_t &key,
const ql::datum_t &old_val,
const ql::datum_t &new_val) {
ql::changefeed::msg_t::change_t change;
change.pkey = key;
change.old_val = old_val;
change.new_val = new_val;
send_all(ql::changefeed::msg_t(change));
}
void cfeed_artificial_table_backend_t::machinery_t::send_all_stop() {
send_all(ql::changefeed::msg_t(ql::changefeed::msg_t::stop_t()));
}
void cfeed_artificial_table_backend_t::machinery_t::maybe_remove() {
assert_thread();
last_subscriber_time = current_microtime();
/* The `cfeed_artificial_table_backend_t` has a repeating timer that will eventually
clean us up */
}
cfeed_artificial_table_backend_t::cfeed_artificial_table_backend_t() :
begin_destruction_was_called(false),
remove_machinery_timer(
machinery_expiration_secs * THOUSAND,
[this]() { maybe_remove_machinery(); })
{ }
cfeed_artificial_table_backend_t::~cfeed_artificial_table_backend_t() {
/* Catch subclasses that forget to call `begin_changefeed_destruction()`. This isn't
strictly necessary (some hypothetical subclasses might not have any reason to call
it) but it's far more likely that the subclass should have called it but forgot to.
*/
guarantee(begin_destruction_was_called);
}
bool cfeed_artificial_table_backend_t::read_changes(
ql::env_t *env,
const ql::protob_t<const Backtrace> &bt,
ql::changefeed::keyspec_t::spec_t &&spec,
signal_t *interruptor,
counted_t<ql::datum_stream_t> *cfeed_out,
std::string *error_out) {
guarantee(!begin_destruction_was_called);
class visitor_t : public boost::static_visitor<bool> {
public:
bool operator()(const ql::changefeed::keyspec_t::limit_t &) const {
return false;
}
bool operator()(const ql::changefeed::keyspec_t::range_t &) const {
return true;
}
bool operator()(const ql::changefeed::keyspec_t::point_t &) const {
return true;
}
};
if (!boost::apply_visitor(visitor_t(), spec)) {
*error_out = "System tables don't support changefeeds on `.limit()`.";
return false;
}
threadnum_t request_thread = get_thread_id();
cross_thread_signal_t interruptor2(interruptor, home_thread());
on_thread_t thread_switcher(home_thread());
new_mutex_in_line_t mutex_lock(&mutex);
wait_interruptible(mutex_lock.acq_signal(), &interruptor2);
if (!machinery.has()) {
machinery = construct_changefeed_machinery(&interruptor2);
}
/* We construct two `on_thread_t`s for a total of four thread switches. This is
necessary because we have to call `subscribe()` on the client thread, but we don't
want to release the lock on the home thread until `subscribe()` returns. */
on_thread_t thread_switcher_2(request_thread);
*cfeed_out = machinery->subscribe(env, std::move(spec), this, bt);
return true;
}
void cfeed_artificial_table_backend_t::begin_changefeed_destruction() {
new_mutex_in_line_t mutex_lock(&mutex);
mutex_lock.acq_signal()->wait_lazily_unordered();
guarantee(!begin_destruction_was_called);
if (machinery.has()) {
/* All changefeeds should be closed before we start destruction */
guarantee(machinery->can_be_removed());
machinery.reset();
}
begin_destruction_was_called = true;
}
void cfeed_artificial_table_backend_t::maybe_remove_machinery() {
/* This is called periodically by a repeating timer */
assert_thread();
if (machinery.has() && machinery->can_be_removed() &&
machinery->last_subscriber_time + machinery_expiration_secs * MILLION <
current_microtime()) {
auto_drainer_t::lock_t keepalive(&drainer);
coro_t::spawn_sometime([this, keepalive /* important to capture */]() {
try {
new_mutex_in_line_t mutex_lock(&mutex);
wait_interruptible(mutex_lock.acq_signal(),
keepalive.get_drain_signal());
if (machinery.has() && machinery->can_be_removed()) {
/* Make sure that we unset `machinery` before we start deleting the
underlying `machinery_t`, because calls to `notify_*` may otherwise
try to access the `machinery_t` while it is being deleted */
scoped_ptr_t<machinery_t> temp;
std::swap(temp, machinery);
}
} catch (const interrupted_exc_t &) {
/* We're shutting down. The machinery will get cleaned up anyway */
}
});
}
}
<commit_msg>Added handling for QL exceptions thrown by `subscribe`.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "rdb_protocol/artificial_table/cfeed_backend.hpp"
#include "concurrency/cross_thread_signal.hpp"
/* We destroy the machinery if there have been no changefeeds for this many seconds */
static const int machinery_expiration_secs = 60;
void cfeed_artificial_table_backend_t::machinery_t::send_all_change(
const store_key_t &key,
const ql::datum_t &old_val,
const ql::datum_t &new_val) {
ql::changefeed::msg_t::change_t change;
change.pkey = key;
change.old_val = old_val;
change.new_val = new_val;
send_all(ql::changefeed::msg_t(change));
}
void cfeed_artificial_table_backend_t::machinery_t::send_all_stop() {
send_all(ql::changefeed::msg_t(ql::changefeed::msg_t::stop_t()));
}
void cfeed_artificial_table_backend_t::machinery_t::maybe_remove() {
assert_thread();
last_subscriber_time = current_microtime();
/* The `cfeed_artificial_table_backend_t` has a repeating timer that will eventually
clean us up */
}
cfeed_artificial_table_backend_t::cfeed_artificial_table_backend_t() :
begin_destruction_was_called(false),
remove_machinery_timer(
machinery_expiration_secs * THOUSAND,
[this]() { maybe_remove_machinery(); })
{ }
cfeed_artificial_table_backend_t::~cfeed_artificial_table_backend_t() {
/* Catch subclasses that forget to call `begin_changefeed_destruction()`. This isn't
strictly necessary (some hypothetical subclasses might not have any reason to call
it) but it's far more likely that the subclass should have called it but forgot to.
*/
guarantee(begin_destruction_was_called);
}
bool cfeed_artificial_table_backend_t::read_changes(
ql::env_t *env,
const ql::protob_t<const Backtrace> &bt,
ql::changefeed::keyspec_t::spec_t &&spec,
signal_t *interruptor,
counted_t<ql::datum_stream_t> *cfeed_out,
std::string *error_out) {
guarantee(!begin_destruction_was_called);
class visitor_t : public boost::static_visitor<bool> {
public:
bool operator()(const ql::changefeed::keyspec_t::limit_t &) const {
return false;
}
bool operator()(const ql::changefeed::keyspec_t::range_t &) const {
return true;
}
bool operator()(const ql::changefeed::keyspec_t::point_t &) const {
return true;
}
};
if (!boost::apply_visitor(visitor_t(), spec)) {
*error_out = "System tables don't support changefeeds on `.limit()`.";
return false;
}
threadnum_t request_thread = get_thread_id();
cross_thread_signal_t interruptor2(interruptor, home_thread());
on_thread_t thread_switcher(home_thread());
new_mutex_in_line_t mutex_lock(&mutex);
wait_interruptible(mutex_lock.acq_signal(), &interruptor2);
if (!machinery.has()) {
machinery = construct_changefeed_machinery(&interruptor2);
}
/* We construct two `on_thread_t`s for a total of four thread switches. This is
necessary because we have to call `subscribe()` on the client thread, but we don't
want to release the lock on the home thread until `subscribe()` returns. */
on_thread_t thread_switcher_2(request_thread);
try {
*cfeed_out = machinery->subscribe(env, std::move(spec), this, bt);
} catch (const ql::base_exc_t &e) {
*error_out = e.what();
return false;
}
return true;
}
void cfeed_artificial_table_backend_t::begin_changefeed_destruction() {
new_mutex_in_line_t mutex_lock(&mutex);
mutex_lock.acq_signal()->wait_lazily_unordered();
guarantee(!begin_destruction_was_called);
if (machinery.has()) {
/* All changefeeds should be closed before we start destruction */
guarantee(machinery->can_be_removed());
machinery.reset();
}
begin_destruction_was_called = true;
}
void cfeed_artificial_table_backend_t::maybe_remove_machinery() {
/* This is called periodically by a repeating timer */
assert_thread();
if (machinery.has() && machinery->can_be_removed() &&
machinery->last_subscriber_time + machinery_expiration_secs * MILLION <
current_microtime()) {
auto_drainer_t::lock_t keepalive(&drainer);
coro_t::spawn_sometime([this, keepalive /* important to capture */]() {
try {
new_mutex_in_line_t mutex_lock(&mutex);
wait_interruptible(mutex_lock.acq_signal(),
keepalive.get_drain_signal());
if (machinery.has() && machinery->can_be_removed()) {
/* Make sure that we unset `machinery` before we start deleting the
underlying `machinery_t`, because calls to `notify_*` may otherwise
try to access the `machinery_t` while it is being deleted */
scoped_ptr_t<machinery_t> temp;
std::swap(temp, machinery);
}
} catch (const interrupted_exc_t &) {
/* We're shutting down. The machinery will get cleaned up anyway */
}
});
}
}
<|endoftext|> |
<commit_before><commit_msg>Perception: Fix build error (#1000)<commit_after><|endoftext|> |
<commit_before>#include "udp_server.h"
#include <thread>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <boost/bind.hpp>
namespace Akumuli {
UdpServer::UdpServer(std::shared_ptr<IngestionPipeline> pipeline, int nworkers, int port)
: pipeline_(pipeline)
, start_barrier_(nworkers + 1)
, stop_barrier_(nworkers + 1)
, stop_{0}
, port_(port)
, nworkers_(nworkers)
, logger_("UdpServer", 128)
{
}
void UdpServer::start(SignalHandler *sig, int id) {
auto self = shared_from_this();
sig->add_handler(boost::bind(&UdpServer::stop, std::move(self)), id);
// Create workers
for (int i = 0; i < nworkers_; i++) {
auto spout = pipeline_->make_spout();
std::thread thread(std::bind(&UdpServer::worker, shared_from_this(), spout));
thread.detach();
}
start_barrier_.wait();
}
void UdpServer::stop() {
stop_.store(1, std::memory_order_relaxed);
stop_barrier_.wait();
}
void UdpServer::worker(std::shared_ptr<PipelineSpout> spout) {
start_barrier_.wait();
int sockfd, retval;
sockaddr_in sa;
try {
ProtocolParser parser(spout);
// Create socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't create socket: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
// Set socket options
int optval = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't set socket options: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
timeval tval;
tval.tv_sec = 0;
tval.tv_usec = 1000; // 1ms
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tval, sizeof(tval)) == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't set socket timeout: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
// Bind socket to port
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons(port_);
if (bind(sockfd, (sockaddr *) &sa, sizeof(sa)) == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't bind socket: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
std::shared_ptr<IOBuf> iobuf(new IOBuf());
while(!stop_.load(std::memory_order_relaxed)) {
if (!iobuf) {
iobuf.reset(new IOBuf());
}
retval = recvmmsg(sockfd, iobuf->msgs, NPACKETS, MSG_WAITFORONE, nullptr);
// TODO: uset timeout to wake up thread periodically
if (retval == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "socket read error: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
iobuf->pps++;
for (int i = 0; i < retval; i++) {
// reset buffer to receive new message
iobuf->bps += iobuf->msgs[i].msg_len;
iobuf->msgs[i].msg_len = 0;
// parse message content
PDU pdu = {
std::shared_ptr<Byte>(iobuf, iobuf->bufs[i]),
MSS,
0u,
};
parser.parse_next(pdu);
iobuf.reset();
}
}
} catch(...) {
logger_.error() << boost::current_exception_diagnostic_information();
}
stop_barrier_.wait();
}
struct UdpServerBuilder {
UdpServerBuilder() {
ServerFactory::instance().register_type("UDP", *this);
}
std::shared_ptr<Server> operator () (std::shared_ptr<IngestionPipeline> pipeline,
std::shared_ptr<ReadOperationBuilder>,
const ServerSettings& settings) {
return std::make_shared<UdpServer>(pipeline, settings.nworkers, settings.port);
}
};
static UdpServerBuilder reg_type;
}
<commit_msg>UDP server fixed<commit_after>#include "udp_server.h"
#include <thread>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <boost/bind.hpp>
namespace Akumuli {
UdpServer::UdpServer(std::shared_ptr<IngestionPipeline> pipeline, int nworkers, int port)
: pipeline_(pipeline)
, start_barrier_(nworkers + 1)
, stop_barrier_(nworkers + 1)
, stop_{0}
, port_(port)
, nworkers_(nworkers)
, logger_("UdpServer", 128)
{
}
void UdpServer::start(SignalHandler *sig, int id) {
auto self = shared_from_this();
sig->add_handler(boost::bind(&UdpServer::stop, std::move(self)), id);
// Create workers
for (int i = 0; i < nworkers_; i++) {
auto spout = pipeline_->make_spout();
std::thread thread(std::bind(&UdpServer::worker, shared_from_this(), spout));
thread.detach();
}
start_barrier_.wait();
}
void UdpServer::stop() {
stop_.store(1, std::memory_order_relaxed);
stop_barrier_.wait();
}
void UdpServer::worker(std::shared_ptr<PipelineSpout> spout) {
start_barrier_.wait();
int sockfd, retval;
sockaddr_in sa;
try {
ProtocolParser parser(spout);
// Create socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't create socket: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
// Set socket options
int optval = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't set socket options: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
timeval tval;
tval.tv_sec = 0;
tval.tv_usec = 1000; // 1ms
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tval, sizeof(tval)) == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't set socket timeout: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
// Bind socket to port
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons(port_);
if (bind(sockfd, (sockaddr *) &sa, sizeof(sa)) == -1) {
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "can't bind socket: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
std::shared_ptr<IOBuf> iobuf(new IOBuf());
while(!stop_.load(std::memory_order_relaxed)) {
if (!iobuf) {
iobuf.reset(new IOBuf());
}
retval = recvmmsg(sockfd, iobuf->msgs, NPACKETS, MSG_WAITFORONE, nullptr);
if (retval == -1) {
if (errno == EAGAIN) {
continue;
}
const char* msg = strerror(errno);
std::stringstream fmt;
fmt << "socket read error: " << msg;
std::runtime_error err(fmt.str());
BOOST_THROW_EXCEPTION(err);
}
iobuf->pps++;
for (int i = 0; i < retval; i++) {
// reset buffer to receive new message
iobuf->bps += iobuf->msgs[i].msg_len;
iobuf->msgs[i].msg_len = 0;
// parse message content
PDU pdu = {
std::shared_ptr<Byte>(iobuf, iobuf->bufs[i]),
MSS,
0u,
};
parser.parse_next(pdu);
iobuf.reset();
}
}
} catch(...) {
logger_.error() << boost::current_exception_diagnostic_information();
}
stop_barrier_.wait();
}
struct UdpServerBuilder {
UdpServerBuilder() {
ServerFactory::instance().register_type("UDP", *this);
}
std::shared_ptr<Server> operator () (std::shared_ptr<IngestionPipeline> pipeline,
std::shared_ptr<ReadOperationBuilder>,
const ServerSettings& settings) {
return std::make_shared<UdpServer>(pipeline, settings.nworkers, settings.port);
}
};
static UdpServerBuilder reg_type;
}
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/compiler/Dialect/VM/Conversion/StandardToVM/ConvertStandardToVM.h"
#include "iree/compiler/Dialect/IREE/IR/IREETypes.h"
#include "iree/compiler/Dialect/VM/Conversion/TypeConverter.h"
#include "iree/compiler/Dialect/VM/IR/VMOps.h"
#include "mlir/Dialect/StandardOps/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Module.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace iree_compiler {
namespace {
class ModuleOpConversion : public OpConversionPattern<ModuleOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
ModuleOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
// Do not attempt to convert the top level module.
// This mechanism can only support rewriting non top-level modules.
if (!srcOp.getParentOp()) {
return matchFailure();
}
StringRef name = srcOp.getName() ? *srcOp.getName() : "module";
auto newModuleOp =
rewriter.create<IREE::VM::ModuleOp>(srcOp.getLoc(), name);
newModuleOp.getBodyRegion().takeBody(srcOp.getBodyRegion());
// Replace the terminator.
Operation *srcTerminator =
newModuleOp.getBodyRegion().back().getTerminator();
rewriter.setInsertionPointToEnd(&newModuleOp.getBodyRegion().back());
rewriter.replaceOpWithNewOp<IREE::VM::ModuleEndOp>(srcTerminator);
rewriter.eraseOp(srcOp);
return matchSuccess();
}
};
class FuncOpConversion : public OpConversionPattern<FuncOp> {
using OpConversionPattern::OpConversionPattern;
// Whitelist of function attributes to retain when converting to vm.func.
static constexpr std::array<const char *, 1> kRetainedAttributes = {
"iree.reflection",
};
PatternMatchResult matchAndRewrite(
FuncOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
FunctionType srcFuncType = srcOp.getType();
VMTypeConverter typeConverter;
TypeConverter::SignatureConversion signatureConversion(
srcOp.getNumArguments());
// Convert function arguments.
for (unsigned i = 0, e = srcFuncType.getNumInputs(); i < e; ++i) {
if (failed(typeConverter.convertSignatureArg(i, srcFuncType.getInput(i),
signatureConversion))) {
return matchFailure();
}
}
// Convert function results.
SmallVector<Type, 1> convertedResultTypes;
if (failed(typeConverter.convertTypes(srcFuncType.getResults(),
convertedResultTypes))) {
return matchFailure();
}
// Create new function with converted argument and result types.
// Note that attributes are dropped. Consider preserving some if needed.
auto newFuncType =
mlir::FunctionType::get(signatureConversion.getConvertedTypes(),
convertedResultTypes, srcOp.getContext());
auto newFuncOp = rewriter.create<IREE::VM::FuncOp>(
srcOp.getLoc(), srcOp.getName(), newFuncType);
// Retain function attributes in the whitelist.
for (auto retainAttrName : kRetainedAttributes) {
StringRef attrName(retainAttrName);
Attribute attr = srcOp.getAttr(attrName);
if (attr) {
newFuncOp.setAttr(attrName, attr);
}
}
// Move the body region from src -> new.
auto &srcRegion = srcOp.getOperation()->getRegion(0);
auto &newRegion = newFuncOp.getOperation()->getRegion(0);
newRegion.takeBody(srcRegion);
// Tell the rewriter to convert the region signature.
rewriter.applySignatureConversion(&newFuncOp.getBody(),
signatureConversion);
// Also add an export if the function is tagged. Ideally this would be
// replaced with river sym_vis magic.
if (srcOp.getAttr("iree.module.export")) {
rewriter.create<IREE::VM::ExportOp>(srcOp.getLoc(), newFuncOp);
}
rewriter.replaceOp(srcOp, llvm::None);
return matchSuccess();
}
};
class ReturnOpConversion : public OpConversionPattern<ReturnOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
ReturnOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<IREE::VM::ReturnOp>(srcOp, operands);
return matchSuccess();
}
};
class ConstantOpConversion : public OpConversionPattern<ConstantOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
ConstantOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto integerAttr = srcOp.getValue().dyn_cast<IntegerAttr>();
// Only 32bit integer supported for now.
if (!integerAttr) {
srcOp.emitRemark() << "unsupported const type for dialect";
return matchFailure();
}
int numBits = integerAttr.getType().getIntOrFloatBitWidth();
if (numBits != 1 && numBits != 32) {
srcOp.emitRemark() << "unsupported bit width for dialect constant";
return matchFailure();
}
auto intValue = integerAttr.getInt();
if (intValue == 0) {
rewriter.replaceOpWithNewOp<IREE::VM::ConstI32ZeroOp>(srcOp);
} else {
rewriter.replaceOpWithNewOp<IREE::VM::ConstI32Op>(srcOp, intValue);
}
return matchSuccess();
}
};
class CmpIOpConversion : public OpConversionPattern<CmpIOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
CmpIOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
CmpIOpOperandAdaptor srcAdapter(operands);
auto returnType = rewriter.getIntegerType(32);
switch (srcOp.getPredicate()) {
case CmpIPredicate::eq:
rewriter.replaceOpWithNewOp<IREE::VM::CmpEQI32Op>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ne:
rewriter.replaceOpWithNewOp<IREE::VM::CmpNEI32Op>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::slt:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::sle:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTEI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::sgt:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::sge:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTEI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ult:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ule:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTEI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ugt:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::uge:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTEI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
}
}
};
template <typename SrcOpTy, typename DstOpTy>
class BinaryArithmeticOpConversion : public OpConversionPattern<SrcOpTy> {
using OpConversionPattern<SrcOpTy>::OpConversionPattern;
using OpConversionPattern<SrcOpTy>::matchSuccess;
PatternMatchResult matchAndRewrite(
SrcOpTy srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
typename SrcOpTy::OperandAdaptor srcAdapter(operands);
rewriter.replaceOpWithNewOp<DstOpTy>(srcOp, srcOp.getType(),
srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
}
};
template <typename SrcOpTy, typename DstOpTy, unsigned kBits = 32>
class ShiftArithmeticOpConversion : public OpConversionPattern<SrcOpTy> {
using OpConversionPattern<SrcOpTy>::OpConversionPattern;
using OpConversionPattern<SrcOpTy>::matchFailure;
using OpConversionPattern<SrcOpTy>::matchSuccess;
PatternMatchResult matchAndRewrite(
SrcOpTy srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
typename SrcOpTy::OperandAdaptor srcAdaptor(operands);
auto type = srcOp.getType();
if (!type.template isa<IntegerType>() ||
type.getIntOrFloatBitWidth() != kBits) {
return matchFailure();
}
APInt amount;
if (!matchPattern(srcAdaptor.rhs(), m_ConstantInt(&amount))) {
return matchFailure();
}
uint64_t amountRaw = amount.getZExtValue();
if (amountRaw > kBits) return matchFailure();
IntegerAttr amountAttr =
IntegerAttr::get(IntegerType::get(8, srcOp.getContext()), amountRaw);
rewriter.replaceOpWithNewOp<DstOpTy>(srcOp, srcOp.getType(),
srcAdaptor.lhs(), amountAttr);
return matchSuccess();
}
};
class SelectI32OpConversion : public OpConversionPattern<SelectOp> {
using OpConversionPattern::OpConversionPattern;
static constexpr unsigned kBits = 32;
PatternMatchResult matchAndRewrite(
SelectOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
SelectOpOperandAdaptor srcAdaptor(operands);
IntegerType requiredType = IntegerType::get(kBits, srcOp.getContext());
if (srcAdaptor.true_value().getType() != requiredType)
return matchFailure();
rewriter.replaceOpWithNewOp<IREE::VM::SelectI32Op>(
srcOp, requiredType, srcAdaptor.condition(), srcAdaptor.true_value(),
srcAdaptor.false_value());
return matchSuccess();
}
};
class BranchOpConversion : public OpConversionPattern<BranchOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
BranchOp srcOp, ArrayRef<Value> properOperands,
ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value>> operands,
ConversionPatternRewriter &rewriter) const override {
assert(destinations.size() == 1 && operands.size() == 1);
rewriter.replaceOpWithNewOp<IREE::VM::BranchOp>(srcOp, destinations[0],
operands[0]);
return matchSuccess();
}
};
class CondBranchOpConversion : public OpConversionPattern<CondBranchOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
CondBranchOp srcOp, ArrayRef<Value> properOperands,
ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value>> operands,
ConversionPatternRewriter &rewriter) const override {
assert(destinations.size() == 2 && operands.size() == 2);
CondBranchOpOperandAdaptor srcAdaptor(properOperands);
rewriter.replaceOpWithNewOp<IREE::VM::CondBranchOp>(
srcOp, srcAdaptor.condition(), destinations[0], operands[0], // true
destinations[1], operands[1]); // false;
return matchSuccess();
}
};
class CallOpConversion : public OpConversionPattern<CallOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
CallOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
CallOpOperandAdaptor srcAdaptor(operands);
// Convert function result types. The conversion framework will ensure
// that the callee has been equivalently converted.
VMTypeConverter typeConverter;
SmallVector<Type, 4> resultTypes;
for (auto resultType : srcOp.getResultTypes()) {
resultType = typeConverter.convertType(resultType);
if (!resultType) {
return matchFailure();
}
resultTypes.push_back(resultType);
}
rewriter.replaceOpWithNewOp<IREE::VM::CallOp>(
srcOp, srcOp.getCallee(), resultTypes, srcAdaptor.operands());
return matchSuccess();
}
};
} // namespace
void populateStandardToVMPatterns(MLIRContext *context,
OwningRewritePatternList &patterns) {
patterns
.insert<BranchOpConversion, CallOpConversion, CmpIOpConversion,
CondBranchOpConversion, ConstantOpConversion, ModuleOpConversion,
FuncOpConversion, ReturnOpConversion, SelectI32OpConversion>(
context);
// Binary arithmetic ops
patterns
.insert<BinaryArithmeticOpConversion<AddIOp, IREE::VM::AddI32Op>,
BinaryArithmeticOpConversion<SignedDivIOp, IREE::VM::DivI32SOp>,
BinaryArithmeticOpConversion<UnsignedDivIOp, IREE::VM::DivI32UOp>,
BinaryArithmeticOpConversion<MulIOp, IREE::VM::MulI32Op>,
BinaryArithmeticOpConversion<SignedRemIOp, IREE::VM::RemI32SOp>,
BinaryArithmeticOpConversion<UnsignedRemIOp, IREE::VM::RemI32UOp>,
BinaryArithmeticOpConversion<SubIOp, IREE::VM::SubI32Op>,
BinaryArithmeticOpConversion<AndOp, IREE::VM::AndI32Op>,
BinaryArithmeticOpConversion<OrOp, IREE::VM::OrI32Op>,
BinaryArithmeticOpConversion<XOrOp, IREE::VM::XorI32Op>>(context);
// Shift ops
// TODO(laurenzo): The standard dialect is missing shr ops. Add once in place.
patterns.insert<ShiftArithmeticOpConversion<ShiftLeftOp, IREE::VM::ShlI32Op>>(
context);
}
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Move static constexpr to namespace scope<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/compiler/Dialect/VM/Conversion/StandardToVM/ConvertStandardToVM.h"
#include "iree/compiler/Dialect/IREE/IR/IREETypes.h"
#include "iree/compiler/Dialect/VM/Conversion/TypeConverter.h"
#include "iree/compiler/Dialect/VM/IR/VMOps.h"
#include "mlir/Dialect/StandardOps/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Module.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace iree_compiler {
namespace {
class ModuleOpConversion : public OpConversionPattern<ModuleOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
ModuleOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
// Do not attempt to convert the top level module.
// This mechanism can only support rewriting non top-level modules.
if (!srcOp.getParentOp()) {
return matchFailure();
}
StringRef name = srcOp.getName() ? *srcOp.getName() : "module";
auto newModuleOp =
rewriter.create<IREE::VM::ModuleOp>(srcOp.getLoc(), name);
newModuleOp.getBodyRegion().takeBody(srcOp.getBodyRegion());
// Replace the terminator.
Operation *srcTerminator =
newModuleOp.getBodyRegion().back().getTerminator();
rewriter.setInsertionPointToEnd(&newModuleOp.getBodyRegion().back());
rewriter.replaceOpWithNewOp<IREE::VM::ModuleEndOp>(srcTerminator);
rewriter.eraseOp(srcOp);
return matchSuccess();
}
};
// Whitelist of function attributes to retain when converting to vm.func.
constexpr std::array<const char *, 1> kRetainedAttributes = {
"iree.reflection",
};
class FuncOpConversion : public OpConversionPattern<FuncOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
FuncOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
FunctionType srcFuncType = srcOp.getType();
VMTypeConverter typeConverter;
TypeConverter::SignatureConversion signatureConversion(
srcOp.getNumArguments());
// Convert function arguments.
for (unsigned i = 0, e = srcFuncType.getNumInputs(); i < e; ++i) {
if (failed(typeConverter.convertSignatureArg(i, srcFuncType.getInput(i),
signatureConversion))) {
return matchFailure();
}
}
// Convert function results.
SmallVector<Type, 1> convertedResultTypes;
if (failed(typeConverter.convertTypes(srcFuncType.getResults(),
convertedResultTypes))) {
return matchFailure();
}
// Create new function with converted argument and result types.
// Note that attributes are dropped. Consider preserving some if needed.
auto newFuncType =
mlir::FunctionType::get(signatureConversion.getConvertedTypes(),
convertedResultTypes, srcOp.getContext());
auto newFuncOp = rewriter.create<IREE::VM::FuncOp>(
srcOp.getLoc(), srcOp.getName(), newFuncType);
// Retain function attributes in the whitelist.
for (auto retainAttrName : kRetainedAttributes) {
StringRef attrName(retainAttrName);
Attribute attr = srcOp.getAttr(attrName);
if (attr) {
newFuncOp.setAttr(attrName, attr);
}
}
// Move the body region from src -> new.
auto &srcRegion = srcOp.getOperation()->getRegion(0);
auto &newRegion = newFuncOp.getOperation()->getRegion(0);
newRegion.takeBody(srcRegion);
// Tell the rewriter to convert the region signature.
rewriter.applySignatureConversion(&newFuncOp.getBody(),
signatureConversion);
// Also add an export if the function is tagged. Ideally this would be
// replaced with river sym_vis magic.
if (srcOp.getAttr("iree.module.export")) {
rewriter.create<IREE::VM::ExportOp>(srcOp.getLoc(), newFuncOp);
}
rewriter.replaceOp(srcOp, llvm::None);
return matchSuccess();
}
};
class ReturnOpConversion : public OpConversionPattern<ReturnOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
ReturnOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<IREE::VM::ReturnOp>(srcOp, operands);
return matchSuccess();
}
};
class ConstantOpConversion : public OpConversionPattern<ConstantOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
ConstantOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto integerAttr = srcOp.getValue().dyn_cast<IntegerAttr>();
// Only 32bit integer supported for now.
if (!integerAttr) {
srcOp.emitRemark() << "unsupported const type for dialect";
return matchFailure();
}
int numBits = integerAttr.getType().getIntOrFloatBitWidth();
if (numBits != 1 && numBits != 32) {
srcOp.emitRemark() << "unsupported bit width for dialect constant";
return matchFailure();
}
auto intValue = integerAttr.getInt();
if (intValue == 0) {
rewriter.replaceOpWithNewOp<IREE::VM::ConstI32ZeroOp>(srcOp);
} else {
rewriter.replaceOpWithNewOp<IREE::VM::ConstI32Op>(srcOp, intValue);
}
return matchSuccess();
}
};
class CmpIOpConversion : public OpConversionPattern<CmpIOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
CmpIOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
CmpIOpOperandAdaptor srcAdapter(operands);
auto returnType = rewriter.getIntegerType(32);
switch (srcOp.getPredicate()) {
case CmpIPredicate::eq:
rewriter.replaceOpWithNewOp<IREE::VM::CmpEQI32Op>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ne:
rewriter.replaceOpWithNewOp<IREE::VM::CmpNEI32Op>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::slt:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::sle:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTEI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::sgt:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::sge:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTEI32SOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ult:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ule:
rewriter.replaceOpWithNewOp<IREE::VM::CmpLTEI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::ugt:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
case CmpIPredicate::uge:
rewriter.replaceOpWithNewOp<IREE::VM::CmpGTEI32UOp>(
srcOp, returnType, srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
}
}
};
template <typename SrcOpTy, typename DstOpTy>
class BinaryArithmeticOpConversion : public OpConversionPattern<SrcOpTy> {
using OpConversionPattern<SrcOpTy>::OpConversionPattern;
using OpConversionPattern<SrcOpTy>::matchSuccess;
PatternMatchResult matchAndRewrite(
SrcOpTy srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
typename SrcOpTy::OperandAdaptor srcAdapter(operands);
rewriter.replaceOpWithNewOp<DstOpTy>(srcOp, srcOp.getType(),
srcAdapter.lhs(), srcAdapter.rhs());
return matchSuccess();
}
};
template <typename SrcOpTy, typename DstOpTy, unsigned kBits = 32>
class ShiftArithmeticOpConversion : public OpConversionPattern<SrcOpTy> {
using OpConversionPattern<SrcOpTy>::OpConversionPattern;
using OpConversionPattern<SrcOpTy>::matchFailure;
using OpConversionPattern<SrcOpTy>::matchSuccess;
PatternMatchResult matchAndRewrite(
SrcOpTy srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
typename SrcOpTy::OperandAdaptor srcAdaptor(operands);
auto type = srcOp.getType();
if (!type.template isa<IntegerType>() ||
type.getIntOrFloatBitWidth() != kBits) {
return matchFailure();
}
APInt amount;
if (!matchPattern(srcAdaptor.rhs(), m_ConstantInt(&amount))) {
return matchFailure();
}
uint64_t amountRaw = amount.getZExtValue();
if (amountRaw > kBits) return matchFailure();
IntegerAttr amountAttr =
IntegerAttr::get(IntegerType::get(8, srcOp.getContext()), amountRaw);
rewriter.replaceOpWithNewOp<DstOpTy>(srcOp, srcOp.getType(),
srcAdaptor.lhs(), amountAttr);
return matchSuccess();
}
};
class SelectI32OpConversion : public OpConversionPattern<SelectOp> {
using OpConversionPattern::OpConversionPattern;
static constexpr unsigned kBits = 32;
PatternMatchResult matchAndRewrite(
SelectOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
SelectOpOperandAdaptor srcAdaptor(operands);
IntegerType requiredType = IntegerType::get(kBits, srcOp.getContext());
if (srcAdaptor.true_value().getType() != requiredType)
return matchFailure();
rewriter.replaceOpWithNewOp<IREE::VM::SelectI32Op>(
srcOp, requiredType, srcAdaptor.condition(), srcAdaptor.true_value(),
srcAdaptor.false_value());
return matchSuccess();
}
};
class BranchOpConversion : public OpConversionPattern<BranchOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
BranchOp srcOp, ArrayRef<Value> properOperands,
ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value>> operands,
ConversionPatternRewriter &rewriter) const override {
assert(destinations.size() == 1 && operands.size() == 1);
rewriter.replaceOpWithNewOp<IREE::VM::BranchOp>(srcOp, destinations[0],
operands[0]);
return matchSuccess();
}
};
class CondBranchOpConversion : public OpConversionPattern<CondBranchOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
CondBranchOp srcOp, ArrayRef<Value> properOperands,
ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value>> operands,
ConversionPatternRewriter &rewriter) const override {
assert(destinations.size() == 2 && operands.size() == 2);
CondBranchOpOperandAdaptor srcAdaptor(properOperands);
rewriter.replaceOpWithNewOp<IREE::VM::CondBranchOp>(
srcOp, srcAdaptor.condition(), destinations[0], operands[0], // true
destinations[1], operands[1]); // false;
return matchSuccess();
}
};
class CallOpConversion : public OpConversionPattern<CallOp> {
using OpConversionPattern::OpConversionPattern;
PatternMatchResult matchAndRewrite(
CallOp srcOp, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
CallOpOperandAdaptor srcAdaptor(operands);
// Convert function result types. The conversion framework will ensure
// that the callee has been equivalently converted.
VMTypeConverter typeConverter;
SmallVector<Type, 4> resultTypes;
for (auto resultType : srcOp.getResultTypes()) {
resultType = typeConverter.convertType(resultType);
if (!resultType) {
return matchFailure();
}
resultTypes.push_back(resultType);
}
rewriter.replaceOpWithNewOp<IREE::VM::CallOp>(
srcOp, srcOp.getCallee(), resultTypes, srcAdaptor.operands());
return matchSuccess();
}
};
} // namespace
void populateStandardToVMPatterns(MLIRContext *context,
OwningRewritePatternList &patterns) {
patterns
.insert<BranchOpConversion, CallOpConversion, CmpIOpConversion,
CondBranchOpConversion, ConstantOpConversion, ModuleOpConversion,
FuncOpConversion, ReturnOpConversion, SelectI32OpConversion>(
context);
// Binary arithmetic ops
patterns
.insert<BinaryArithmeticOpConversion<AddIOp, IREE::VM::AddI32Op>,
BinaryArithmeticOpConversion<SignedDivIOp, IREE::VM::DivI32SOp>,
BinaryArithmeticOpConversion<UnsignedDivIOp, IREE::VM::DivI32UOp>,
BinaryArithmeticOpConversion<MulIOp, IREE::VM::MulI32Op>,
BinaryArithmeticOpConversion<SignedRemIOp, IREE::VM::RemI32SOp>,
BinaryArithmeticOpConversion<UnsignedRemIOp, IREE::VM::RemI32UOp>,
BinaryArithmeticOpConversion<SubIOp, IREE::VM::SubI32Op>,
BinaryArithmeticOpConversion<AndOp, IREE::VM::AndI32Op>,
BinaryArithmeticOpConversion<OrOp, IREE::VM::OrI32Op>,
BinaryArithmeticOpConversion<XOrOp, IREE::VM::XorI32Op>>(context);
// Shift ops
// TODO(laurenzo): The standard dialect is missing shr ops. Add once in place.
patterns.insert<ShiftArithmeticOpConversion<ShiftLeftOp, IREE::VM::ShlI32Op>>(
context);
}
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>#include "sockets.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
class Plaintext : public Socket {
public:
unsigned int apiVersion() { return 3000; }
void connectServer(const std::string& server, const std::string& port, const std::string& bindAddr = "");
std::string receive();
void sendData(const std::string& data);
void closeConnection();
private:
int socketfd;
std::ostringstream recvBuffer;
};
void Plaintext::connectServer(const std::string& server, const std::string& port, const std::string& bindAddr) {
addrinfo* addrInfoList;
addrinfo hints;
hints.ai_family = PF_UNSPEC; // Don't specify whether IPv6 or IPv4
hints.ai_socktype = SOCK_STREAM; // IRC uses TCP, so make a streaming socket
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST;
// AI_ADDRCONFIG doesn't allow IPv4 when the machine doesn't have IPv4 or IPv6 if the machine doesn't have IPv6
// AI_NUMERICHOST signals that we're passing a numeric port
int status = getaddrinfo(server.c_str(), port.c_str(), &hints, &addrInfoList);
if (status != 0)
throw SocketOperationFailed ("An error occurred getting the hosts.");
for (addrinfo* thisAddr = addrInfoList; thisAddr != nullptr; thisAddr = thisAddr->ai_next) {
socketfd = socket(thisAddr->ai_family, thisAddr->ai_socktype | SOCK_NONBLOCK, thisAddr->ai_protocol);
if (socketfd == -1)
continue;
if (!bindAddr.empty()) {
addrinfo bindHints;
bindHints.ai_family = thisAddr->ai_family;
bindHints.ai_socktype = SOCK_STREAM;
bindHints.ai_protocol = IPPROTO_TCP;
bindHints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST;
addrinfo* bindLoc;
status = getaddrinfo(bindAddr.c_str(), "0", &bindHints, &bindLoc);
if (status != 0) {
close(socketfd);
socketfd = -1;
continue;
}
for (addrinfo* currBind = bindLoc; currBind != nullptr; currBind = currBind->ai_next) {
status = bind(socketfd, currBind->ai_addr, currBind->ai_addrlen);
if (status == -1)
continue;
}
freeaddrinfo(bindLoc);
if (status != 0) { // If the status still isn't 0, then the binding never worked
close(socketfd);
socketfd = -1;
freeaddrinfo(addrInfoList);
throw SocketOperationFailed ("The socket could not be bound.");
}
}
status = connect(socketfd, thisAddr->ai_addr, thisAddr->ai_addrlen);
if (status != 0 && errno != EINPROGRESS) {
close(socketfd);
socketfd = -1;
continue;
}
break; // If we haven't continued yet, we're connected and the socket is suitable.
}
freeaddrinfo(addrInfoList);
if (socketfd == -1)
throw SocketOperationFailed ("No suitable host was found.");
connected = true;
}
std::string Plaintext::receive() {
std::string bufferStr (recvBuffer.str());
size_t delimPos = bufferStr.find(delimiter);
if (delimPos != std::string::npos) {
std::string nextLine (bufferStr.substr(0, delimPos));
if (delimPos + delimiter.size() < bufferStr.size())
recvBuffer.str(bufferStr.substr(delimPos + delimiter.size()));
else
recvBuffer.str("");
return nextLine;
}
char inputBuffer[1025];
int status;
while (true) {
status = recv(socketfd, &inputBuffer, 1024, 0);
while (status < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // Give some (although brief) wait before checking again
status = recv(socketfd, &inputBuffer, 1024, 0);
}
if (status <= 0) {
close(socketfd);
connected = false;
throw SocketOperationFailed ("The connection has broken.");
}
recvBuffer << inputBuffer;
bufferStr = recvBuffer.str();
delimPos = bufferStr.find(delimiter);
if (delimPos != std::string::npos) {
std::string nextLine (bufferStr.substr(0, delimPos));
if (delimPos + delimiter.size() < bufferStr.size())
recvBuffer.str(bufferStr.substr(delimPos + delimiter.size()));
else
recvBuffer.str("");
return nextLine;
}
}
}
void Plaintext::sendData(const std::string& data) {
std::string line (data + delimiter);
ssize_t status;
do
status = send(socketfd, line.c_str(), line.size(), 0);
while (status <= 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
}
void Plaintext::closeConnection() {
close(socketfd);
connected = false;
}
SOCKET_SPAWN(Plaintext)<commit_msg>Make plaintext socket able to reconnect<commit_after>#include "sockets.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
class Plaintext : public Socket {
public:
unsigned int apiVersion() { return 3000; }
void connectServer(const std::string& server, const std::string& port, const std::string& bindAddr = "");
std::string receive();
void sendData(const std::string& data);
void closeConnection();
private:
int socketfd;
std::ostringstream recvBuffer;
};
void Plaintext::connectServer(const std::string& server, const std::string& port, const std::string& bindAddr) {
if (connected)
return;
socketfd = -1;
addrinfo* addrInfoList;
addrinfo hints;
hints.ai_family = PF_UNSPEC; // Don't specify whether IPv6 or IPv4
hints.ai_socktype = SOCK_STREAM; // IRC uses TCP, so make a streaming socket
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST;
// AI_ADDRCONFIG doesn't allow IPv4 when the machine doesn't have IPv4 or IPv6 if the machine doesn't have IPv6
// AI_NUMERICHOST signals that we're passing a numeric port
int status = getaddrinfo(server.c_str(), port.c_str(), &hints, &addrInfoList);
if (status != 0)
throw SocketOperationFailed ("An error occurred getting the hosts.");
for (addrinfo* thisAddr = addrInfoList; thisAddr != nullptr; thisAddr = thisAddr->ai_next) {
socketfd = socket(thisAddr->ai_family, thisAddr->ai_socktype | SOCK_NONBLOCK, thisAddr->ai_protocol);
if (socketfd == -1)
continue;
if (!bindAddr.empty()) {
addrinfo bindHints;
bindHints.ai_family = thisAddr->ai_family;
bindHints.ai_socktype = SOCK_STREAM;
bindHints.ai_protocol = IPPROTO_TCP;
bindHints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST;
addrinfo* bindLoc;
status = getaddrinfo(bindAddr.c_str(), "0", &bindHints, &bindLoc);
if (status != 0) {
close(socketfd);
socketfd = -1;
continue;
}
for (addrinfo* currBind = bindLoc; currBind != nullptr; currBind = currBind->ai_next) {
status = bind(socketfd, currBind->ai_addr, currBind->ai_addrlen);
if (status == -1)
continue;
}
freeaddrinfo(bindLoc);
if (status != 0) { // If the status still isn't 0, then the binding never worked
close(socketfd);
socketfd = -1;
freeaddrinfo(addrInfoList);
throw SocketOperationFailed ("The socket could not be bound.");
}
}
status = connect(socketfd, thisAddr->ai_addr, thisAddr->ai_addrlen);
if (status != 0 && errno != EINPROGRESS) {
close(socketfd);
socketfd = -1;
continue;
}
break; // If we haven't continued yet, we're connected and the socket is suitable.
}
freeaddrinfo(addrInfoList);
if (socketfd == -1)
throw SocketOperationFailed ("No suitable host was found.");
connected = true;
}
std::string Plaintext::receive() {
std::string bufferStr (recvBuffer.str());
size_t delimPos = bufferStr.find(delimiter);
if (delimPos != std::string::npos) {
std::string nextLine (bufferStr.substr(0, delimPos));
if (delimPos + delimiter.size() < bufferStr.size())
recvBuffer.str(bufferStr.substr(delimPos + delimiter.size()));
else
recvBuffer.str("");
return nextLine;
}
char inputBuffer[1025];
int status;
while (true) {
status = recv(socketfd, &inputBuffer, 1024, 0);
while (status < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // Give some (although brief) wait before checking again
status = recv(socketfd, &inputBuffer, 1024, 0);
}
if (status <= 0) {
close(socketfd);
connected = false;
throw SocketOperationFailed ("The connection has broken.");
}
recvBuffer << inputBuffer;
bufferStr = recvBuffer.str();
delimPos = bufferStr.find(delimiter);
if (delimPos != std::string::npos) {
std::string nextLine (bufferStr.substr(0, delimPos));
if (delimPos + delimiter.size() < bufferStr.size())
recvBuffer.str(bufferStr.substr(delimPos + delimiter.size()));
else
recvBuffer.str("");
return nextLine;
}
}
}
void Plaintext::sendData(const std::string& data) {
std::string line (data + delimiter);
ssize_t status;
do
status = send(socketfd, line.c_str(), line.size(), 0);
while (status <= 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
}
void Plaintext::closeConnection() {
close(socketfd);
connected = false;
}
SOCKET_SPAWN(Plaintext)<|endoftext|> |
<commit_before>#pragma once
// Instead of working with the 1 to 1 correspondence p <-> (j,r,s,k),
// it is convenient to collect tuples with the same index j. This
// gives a 1-to-many correspondence
//
// j <-> { list of IndexTuple(p,r,s,k) }
//
// IndexTuple is simply a named version of the 4-tuple (p,r,s,k). A
// given IndexTuple uniquely specifies a constraint matrix A_p.
//
class Index_Tuple
{
public:
int p; // overall index of the constraint
int r; // first index for E^{rs}
int s; // second index for E^{rs}
int k; // index for v_{b,k}
Index_Tuple(int p, int r, int s, int k) : p(p), r(r), s(s), k(k) {}
Index_Tuple() {}
};
<commit_msg>Add pretty print for Index_Tuple<commit_after>#pragma once
#include <iostream>
// Instead of working with the 1 to 1 correspondence p <-> (j,r,s,k),
// it is convenient to collect tuples with the same index j. This
// gives a 1-to-many correspondence
//
// j <-> { list of IndexTuple(p,r,s,k) }
//
// IndexTuple is simply a named version of the 4-tuple (p,r,s,k). A
// given IndexTuple uniquely specifies a constraint matrix A_p.
//
class Index_Tuple
{
public:
int p; // overall index of the constraint
int r; // first index for E^{rs}
int s; // second index for E^{rs}
int k; // index for v_{b,k}
Index_Tuple(int p, int r, int s, int k) : p(p), r(r), s(s), k(k) {}
Index_Tuple() {}
};
inline std::ostream & operator<<(std::ostream &os, const Index_Tuple &index_tuple)
{
os << '{'
<< index_tuple.p << ' '
<< index_tuple.r << ' '
<< index_tuple.s << ' '
<< index_tuple.k << '}';
return os;
}
<|endoftext|> |
<commit_before>#include "SwitchState.h"
#include "TransitionState.h"
#include "ViewState.h"
#include "Log.h"
State* SwitchState::action(){
if ( !browser() ){
return new ViewState(this);
}
const char* filename = browser()->get_next_file();
if ( !filename ){
Log::message(Log::Warning, "Kernel: Queue is empty\n", filename);
} else {
Log::message(Log::Debug, "Kernel: Switching to image \"%s\"\n", filename);
}
try {
gfx()->load_image( filename );
} catch ( ... ) {
Log::message(Log::Warning, "Kernel: Failed to load image '%s'\n", filename);
return this;
}
return new TransitionState(this);
}
<commit_msg>Staying on the same image if the next cannot be loaded<commit_after>#include "SwitchState.h"
#include "TransitionState.h"
#include "ViewState.h"
#include "Log.h"
State* SwitchState::action(){
if ( !browser() ){
return new ViewState(this);
}
const char* filename = browser()->get_next_file();
if ( !filename ){
Log::message(Log::Warning, "Kernel: Queue is empty\n", filename);
} else {
Log::message(Log::Debug, "Kernel: Switching to image \"%s\"\n", filename);
}
try {
gfx()->load_image( filename );
} catch ( ... ) {
Log::message(Log::Warning, "Kernel: Failed to load image '%s'\n", filename);
return new ViewState(this);
}
return new TransitionState(this);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: langbox.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: pb $ $Date: 2000-11-24 10:22:55 $
*
* 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 ---------------------------------------------------------------
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#pragma hdrstop
#include "langbox.hxx"
#include "langtab.hxx"
#include "dialmgr.hxx"
#include "dialogs.hrc"
#include "unolingu.hxx"
using namespace ::com::sun::star::util;
//========================================================================
// class SvxLanguageBox
//========================================================================
USHORT TypeToPos_Impl( LanguageType eType, const ListBox& rLb )
{
USHORT nPos = LISTBOX_ENTRY_NOTFOUND;
USHORT nCount = rLb.GetEntryCount();
for ( USHORT i=0; nPos == LISTBOX_ENTRY_NOTFOUND && i<nCount; i++ )
if ( eType == LanguageType((ULONG)rLb.GetEntryData(i)) )
nPos = i;
return nPos;
}
//-----------------------------------------------------------------------
/*!!! (pb) obsolete
SvxLanguageBox::SvxLanguageBox( Window* pParent, WinBits nWinStyle ) :
ListBox( pParent, nWinStyle )
{
m_pLangTable = new SvxLanguageTable;
aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );
aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );
}
*/
//------------------------------------------------------------------------
SvxLanguageBox::SvxLanguageBox( Window* pParent, const ResId& rResId, BOOL bCheck ) :
ListBox( pParent, rResId ),
m_bWithCheckmark( bCheck )
{
m_pLangTable = new SvxLanguageTable;
m_aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );
m_aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );
if ( m_bWithCheckmark )
{
const USHORT nCount = International::GetAvailableFormatCount();
for ( USHORT i = 0; i < nCount; i++ )
{
LanguageType eLngType = International::GetAvailableFormat( i );
if ( eLngType != LANGUAGE_SYSTEM )
InsertLanguage( eLngType );
}
}
}
//------------------------------------------------------------------------
SvxLanguageBox::~SvxLanguageBox()
{
delete m_pLangTable;
}
//------------------------------------------------------------------------
USHORT SvxLanguageBox::InsertLanguage( const LanguageType eLangType, USHORT nPos )
{
String aStrEntry = m_pLangTable->GetString( eLangType );
USHORT nAt = 0;
if ( m_bWithCheckmark )
{
const USHORT nLanguageCount = SvxGetSelectableLanguages().getLength();
const Language* pLangList = SvxGetSelectableLanguages().getConstArray();
sal_Bool bFound = sal_False;
for ( USHORT i = 0; i < nLanguageCount; ++i )
{
if ( eLangType == pLangList[i] )
{
bFound = sal_True;
break;
}
}
if ( !bFound )
nAt = InsertEntry( aStrEntry, m_aNotCheckedImage, nPos );
else
nAt = InsertEntry( aStrEntry, m_aCheckedImage, nPos );
}
else
nAt = InsertEntry( aStrEntry, nPos );
SetEntryData( nAt, (void*)(ULONG)eLangType );
return nPos;
}
//------------------------------------------------------------------------
void SvxLanguageBox::RemoveLanguage( const LanguageType eLangType )
{
USHORT nAt = TypeToPos_Impl( eLangType, *this );
if ( nAt != LISTBOX_ENTRY_NOTFOUND )
RemoveEntry( nAt );
}
//------------------------------------------------------------------------
LanguageType SvxLanguageBox::GetSelectLanguage() const
{
LanguageType eType = LanguageType(LANGUAGE_DONTKNOW);
USHORT nPos = GetSelectEntryPos();
if ( nPos != LISTBOX_ENTRY_NOTFOUND )
return LanguageType( (ULONG)GetEntryData(nPos) );
else
return LanguageType( LANGUAGE_DONTKNOW );
}
//------------------------------------------------------------------------
void SvxLanguageBox::SelectLanguage( const LanguageType eLangType, BOOL bSelect )
{
USHORT nAt = TypeToPos_Impl( eLangType, *this );
if ( nAt != LISTBOX_ENTRY_NOTFOUND )
SelectEntryPos( nAt, bSelect );
}
//------------------------------------------------------------------------
BOOL SvxLanguageBox::IsLanguageSelected( const LanguageType eLangType ) const
{
USHORT nAt = TypeToPos_Impl( eLangType, *this );
if ( nAt != LISTBOX_ENTRY_NOTFOUND )
return IsEntryPosSelected( nAt );
else
return FALSE;
}
<commit_msg>constructors modified/added, SetLanguageList new<commit_after>/*************************************************************************
*
* $RCSfile: langbox.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: tl $ $Date: 2001-03-22 08:28:26 $
*
* 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 ---------------------------------------------------------------
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HDL_
#include <com/sun/star/linguistic2/XLinguServiceManager.hdl>
#endif
#ifndef _LINGUISTIC_MISC_HXX_
#include <linguistic/misc.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include<rtl/ustring.hxx>
#endif
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#pragma hdrstop
#ifndef _SVX_SCRIPTTYPEITEM_HXX
#include <scripttypeitem.hxx>
#endif
#ifndef _UNO_LINGU_HXX
#include <unolingu.hxx>
#endif
#ifndef _SVX_LANGTAB_HXX
#include <langtab.hxx>
#endif
#include "langbox.hxx"
#include "langtab.hxx"
#include "dialmgr.hxx"
#include "dialogs.hrc"
#include "unolingu.hxx"
using namespace ::rtl;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;
using namespace ::com::sun::star::uno;
#define A2OU(x) OUString::createFromAscii( x )
//========================================================================
// list of languages for forbidden chars
//========================================================================
static const LanguageType aForbiddenCharLang[] =
{
LANGUAGE_CHINESE_TRADITIONAL,
LANGUAGE_CHINESE_SIMPLIFIED,
LANGUAGE_JAPANESE,
LANGUAGE_KOREAN
};
static const int nForbiddenCharLang = sizeof( aForbiddenCharLang ) / sizeof( aForbiddenCharLang[0] );
static BOOL lcl_HasLanguage( const LanguageType *pLang, int nCount, LanguageType nLang )
{
int i = -1;
if (pLang && nCount > 0)
{
for (i = 0; i < nCount; ++i )
{
if (pLang[i] == nLang)
break;
}
}
return i >= 0 && i < nCount;
}
//========================================================================
// misc local helper functions
//========================================================================
static Sequence< INT16 > lcl_LocaleSeqToLangSeq( Sequence< Locale > &rSeq )
{
const Locale *pLocale = rSeq.getConstArray();
INT32 nCount = rSeq.getLength();
Sequence< INT16 > aLangs( nCount );
INT16 *pLang = aLangs.getArray();
for (INT32 i = 0; i < nCount; ++i)
{
pLang[i] = SvxLocaleToLanguage( pLocale[i] );
}
return aLangs;
}
static BOOL lcl_SeqHasLang( const Sequence< INT16 > & rLangSeq, INT16 nLang )
{
INT32 i = -1;
INT32 nLen = rLangSeq.getLength();
if (nLen)
{
const INT16 *pLang = rLangSeq.getConstArray();
for (i = 0; i < nLen; ++i)
{
if (nLang == pLang[i])
break;
}
}
return i >= 0 && i < nLen;
}
//========================================================================
// class SvxLanguageBox
//========================================================================
USHORT TypeToPos_Impl( LanguageType eType, const ListBox& rLb )
{
USHORT nPos = LISTBOX_ENTRY_NOTFOUND;
USHORT nCount = rLb.GetEntryCount();
for ( USHORT i=0; nPos == LISTBOX_ENTRY_NOTFOUND && i<nCount; i++ )
if ( eType == LanguageType((ULONG)rLb.GetEntryData(i)) )
nPos = i;
return nPos;
}
//-----------------------------------------------------------------------
/*!!! (pb) obsolete
SvxLanguageBox::SvxLanguageBox( Window* pParent, WinBits nWinStyle ) :
ListBox( pParent, nWinStyle )
{
m_pLangTable = new SvxLanguageTable;
aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );
aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );
}
*/
//------------------------------------------------------------------------
SvxLanguageBox::SvxLanguageBox( Window* pParent, const ResId& rResId, BOOL bCheck ) :
ListBox( pParent, rResId ),
m_bWithCheckmark( bCheck )
{
m_pLangTable = new SvxLanguageTable;
m_aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );
m_aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );
m_aAllString = String( SVX_RESSTR( RID_SVXSTR_LANGUAGE_ALL ) );
m_nLangList = LANG_LIST_EMPTY;
m_bHasLangNone = FALSE;
m_bLangNoneIsLangAll = FALSE;
// display entries sorted
SetStyle( GetStyle() | WB_SORT );
if ( m_bWithCheckmark )
{
SvxLanguageTable aLangTable;
const USHORT nCount = aLangTable.GetEntryCount();
for ( USHORT i = 0; i < nCount; i++ )
{
LanguageType nLangType = aLangTable.GetTypeAtIndex( i );
BOOL bInsert = TRUE;
if ((LANGUAGE_DONTKNOW == nLangType) ||
(LANGUAGE_SYSTEM == nLangType) ||
(LANGUAGE_USER1 <= nLangType && nLangType <= LANGUAGE_USER9))
{
bInsert = FALSE;
}
if ( bInsert )
InsertLanguage( nLangType );
}
m_nLangList = LANG_LIST_ALL;
}
}
//------------------------------------------------------------------------
SvxLanguageBox::SvxLanguageBox( Window* pParent, const ResId& rResId ) :
ListBox( pParent, rResId )
{
m_pLangTable = new SvxLanguageTable;
m_aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );
m_aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );
m_bWithCheckmark = FALSE;
m_aAllString = String( SVX_RESSTR( RID_SVXSTR_LANGUAGE_ALL ) );
m_nLangList = LANG_LIST_EMPTY;
m_bHasLangNone = FALSE;
m_bLangNoneIsLangAll = FALSE;
// display entries sorted
SetStyle( GetStyle() | WB_SORT );
}
//------------------------------------------------------------------------
SvxLanguageBox::~SvxLanguageBox()
{
delete m_pLangTable;
}
//------------------------------------------------------------------------
void SvxLanguageBox::SetLanguageList( INT16 nLangList,
BOOL bHasLangNone, BOOL bLangNoneIsLangAll, BOOL bCheckSpellAvail )
{
Clear();
m_nLangList = nLangList;
m_bHasLangNone = bHasLangNone;
m_bLangNoneIsLangAll = bLangNoneIsLangAll;
m_bWithCheckmark = bCheckSpellAvail;
if ( LANG_LIST_EMPTY != nLangList )
{
Sequence< INT16 > aSpellAvailLang;
Sequence< INT16 > aHyphAvailLang;
Sequence< INT16 > aThesAvailLang;
if (LinguMgr::GetLngSvcMgr().is())
{
Sequence< Locale > aTmp;
if (LANG_LIST_SPELL_AVAIL & nLangList)
{
aTmp = LinguMgr::GetLngSvcMgr()
->getAvailableLocales( A2OU( SN_SPELLCHECKER ) );
aSpellAvailLang = lcl_LocaleSeqToLangSeq( aTmp );
}
if (LANG_LIST_HYPH_AVAIL & nLangList)
{
aTmp = LinguMgr::GetLngSvcMgr()
->getAvailableLocales( A2OU( SN_HYPHENATOR ) );
aHyphAvailLang = lcl_LocaleSeqToLangSeq( aTmp );
}
if (LANG_LIST_THES_AVAIL & nLangList)
{
aTmp = LinguMgr::GetLngSvcMgr()
->getAvailableLocales( A2OU( SN_THESAURUS ) );
aThesAvailLang = lcl_LocaleSeqToLangSeq( aTmp );
}
}
SvxLanguageTable aLangTable;
const USHORT nCount = aLangTable.GetEntryCount();
for ( USHORT i = 0; i < nCount; i++ )
{
LanguageType nLangType = aLangTable.GetTypeAtIndex( i );
BOOL bInsert = FALSE;
if ( nLangType != LANGUAGE_SYSTEM &&
nLangType != LANGUAGE_NONE )
{
if (nLangList & LANG_LIST_ALL)
bInsert |= TRUE;
if (nLangList & LANG_LIST_WESTERN)
bInsert |= SCRIPTTYPE_LATIN == GetScriptTypeOfLanguage( nLangType );
if (nLangList & LANG_LIST_CTL)
bInsert |= SCRIPTTYPE_COMPLEX == GetScriptTypeOfLanguage( nLangType );
if (nLangList & LANG_LIST_CJK)
bInsert |= SCRIPTTYPE_ASIAN == GetScriptTypeOfLanguage( nLangType );
if (nLangList & LANG_LIST_FBD_CHARS)
bInsert |= lcl_HasLanguage( aForbiddenCharLang,
nForbiddenCharLang, nLangType );
if (nLangList & LANG_LIST_SPELL_AVAIL)
bInsert |= lcl_SeqHasLang( aSpellAvailLang, nLangType );
if (nLangList & LANG_LIST_HYPH_AVAIL)
bInsert |= lcl_SeqHasLang( aHyphAvailLang, nLangType );
if (nLangList & LANG_LIST_THES_AVAIL)
bInsert |= lcl_SeqHasLang( aThesAvailLang, nLangType );
}
if ((LANGUAGE_DONTKNOW == nLangType) ||
(LANGUAGE_USER1 <= nLangType && nLangType <= LANGUAGE_USER9))
{
bInsert = FALSE;
}
if (bInsert)
InsertLanguage( nLangType );
}
if (bHasLangNone)
InsertLanguage( LANGUAGE_NONE );
}
}
//------------------------------------------------------------------------
USHORT SvxLanguageBox::InsertLanguage( const LanguageType nLangType, USHORT nPos )
{
String aStrEntry = m_pLangTable->GetString( nLangType );
if (LANGUAGE_NONE == nLangType && m_bHasLangNone && m_bLangNoneIsLangAll)
aStrEntry = m_aAllString;
USHORT nAt = 0;
if ( m_bWithCheckmark )
{
const USHORT nLanguageCount = SvxGetSelectableLanguages().getLength();
const Language* pLangList = SvxGetSelectableLanguages().getConstArray();
sal_Bool bFound = sal_False;
for ( USHORT i = 0; i < nLanguageCount; ++i )
{
if ( nLangType == pLangList[i] )
{
bFound = sal_True;
break;
}
}
if ( !bFound )
nAt = InsertEntry( aStrEntry, m_aNotCheckedImage, nPos );
else
nAt = InsertEntry( aStrEntry, m_aCheckedImage, nPos );
}
else
nAt = InsertEntry( aStrEntry, nPos );
SetEntryData( nAt, (void*)(ULONG)nLangType );
return nPos;
}
//------------------------------------------------------------------------
void SvxLanguageBox::RemoveLanguage( const LanguageType eLangType )
{
USHORT nAt = TypeToPos_Impl( eLangType, *this );
if ( nAt != LISTBOX_ENTRY_NOTFOUND )
RemoveEntry( nAt );
}
//------------------------------------------------------------------------
LanguageType SvxLanguageBox::GetSelectLanguage() const
{
LanguageType eType = LanguageType(LANGUAGE_DONTKNOW);
USHORT nPos = GetSelectEntryPos();
if ( nPos != LISTBOX_ENTRY_NOTFOUND )
return LanguageType( (ULONG)GetEntryData(nPos) );
else
return LanguageType( LANGUAGE_DONTKNOW );
}
//------------------------------------------------------------------------
void SvxLanguageBox::SelectLanguage( const LanguageType eLangType, BOOL bSelect )
{
USHORT nAt = TypeToPos_Impl( eLangType, *this );
if ( nAt != LISTBOX_ENTRY_NOTFOUND )
SelectEntryPos( nAt, bSelect );
}
//------------------------------------------------------------------------
BOOL SvxLanguageBox::IsLanguageSelected( const LanguageType eLangType ) const
{
USHORT nAt = TypeToPos_Impl( eLangType, *this );
if ( nAt != LISTBOX_ENTRY_NOTFOUND )
return IsEntryPosSelected( nAt );
else
return FALSE;
}
<|endoftext|> |
<commit_before>#include "utils/PVLog.hpp"
//#include "utils/conversions.h"
#include <cmath>
#include <cstring>
namespace PV {
template <class T>
Buffer<T>::Buffer(int width, int height, int features) {
resize(width, height, features);
}
template <class T>
Buffer<T>::Buffer() {
resize(1, 1, 1);
}
template <class T>
Buffer<T>::Buffer(const std::vector<T> &data, int width, int height, int features) {
set(data, width, height, features);
}
// This constructor is for backwards compatibility with raw float buffers.
// It lacks bounds checking and should be removed when layers used Buffers
// instead of malloc'd floats.
template <class T>
Buffer<T>::Buffer(const T *data, int width, int height, int features) {
set(data, width, height, features);
}
template <class T>
T const Buffer<T>::at(int x, int y, int feature) const {
return at(index(x, y, feature));
}
template <class T>
T const Buffer<T>::at(int k) const {
return mData.at(k);
}
template <class T>
void Buffer<T>::set(int x, int y, int feature, T value) {
set(index(x, y, feature), value);
}
template <class T>
void Buffer<T>::set(int k, T value) {
mData.at(k) = value;
}
template <class T>
void Buffer<T>::set(const std::vector<T> &vector, int width, int height, int features) {
FatalIf(
vector.size() != width * height * features,
"Invalid vector size: Expected %d elements, vector contained %d elements.\n",
width * height * features,
vector.size());
mData = vector;
mWidth = width;
mHeight = height;
mFeatures = features;
}
template <class T>
void Buffer<T>::set(const T *data, int width, int height, int features) {
std::vector<T> tempVector(width * height * features);
for (size_t i = 0; i < tempVector.size(); ++i) {
tempVector.at(i) = data[i];
}
set(tempVector, width, height, features);
}
template <class T>
void Buffer<T>::set(Buffer<T> other) {
set(other.asVector(), other.getWidth(), other.getHeight(), other.getFeatures());
}
// Resizing a Buffer will clear its contents. Use rescale, crop, or grow to preserve values.
template <class T>
void Buffer<T>::resize(int width, int height, int features) {
mData.clear();
mData.resize(height * width * features);
mWidth = width;
mHeight = height;
mFeatures = features;
}
// Grows a buffer
template <class T>
void Buffer<T>::grow(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth < getWidth() && newHeight < getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, getWidth(), newWidth);
int offsetY = getAnchorY(anchor, getHeight(), newHeight);
Buffer bigger(newWidth, newHeight, getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + offsetX;
int destY = y + offsetY;
if (destX < 0 || destX >= newWidth)
continue;
if (destY < 0 || destY >= newHeight)
continue;
bigger.set(destX, destY, f, at(x, y, f));
}
}
}
set(bigger.asVector(), newWidth, newHeight, getFeatures());
}
// Crops a buffer down to the specified size
template <class T>
void Buffer<T>::crop(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth >= getWidth() && newHeight >= getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, newWidth, getWidth());
int offsetY = getAnchorY(anchor, newHeight, getHeight());
Buffer cropped(newWidth, newHeight, getFeatures());
for (int destY = 0; destY < newHeight; ++destY) {
for (int destX = 0; destX < newWidth; ++destX) {
for (int f = 0; f < getFeatures(); ++f) {
int sourceX = destX + offsetX;
int sourceY = destY + offsetY;
if (sourceX < 0 || sourceX >= getWidth())
continue;
if (sourceY < 0 || sourceY >= getHeight())
continue;
cropped.set(destX, destY, f, at(sourceX, sourceY, f));
}
}
}
set(cropped.asVector(), newWidth, newHeight, getFeatures());
}
template <class T>
void Buffer<T>::flip(bool xFlip, bool yFlip) {
if (!xFlip && !yFlip) {
return;
}
Buffer result(getWidth(), getHeight(), getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = xFlip ? getWidth() - 1 - x : x;
int destY = yFlip ? getHeight() - 1 - y : y;
result.set(destX, destY, f, at(x, y, f));
}
}
}
set(result.asVector(), getWidth(), getHeight(), getFeatures());
}
// Shift a buffer, clipping any values that land out of bounds
template <class T>
void Buffer<T>::translate(int xShift, int yShift) {
if (xShift == 0 && yShift == 0) {
return;
}
Buffer result(getWidth(), getHeight(), getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + xShift;
int destY = y + yShift;
if (destX < 0 || destX >= getWidth())
continue;
if (destY < 0 || destY >= getHeight())
continue;
result.set(destX, destY, f, at(x, y, f));
}
}
}
set(result.asVector(), getWidth(), getHeight(), getFeatures());
}
template <class T>
int Buffer<T>::getAnchorX(enum Anchor anchor, int smallerWidth, int biggerWidth) {
int resultX;
switch (anchor) {
case NORTHWEST:
case WEST:
case SOUTHWEST: resultX = 0; break;
case NORTH:
case CENTER:
case SOUTH: resultX = biggerWidth / 2 - smallerWidth / 2; break;
case NORTHEAST:
case EAST:
case SOUTHEAST: resultX = biggerWidth - smallerWidth; break;
default: resultX = 0; break;
}
return resultX;
}
template <class T>
int Buffer<T>::getAnchorY(enum Anchor anchor, int smallerHeight, int biggerHeight) {
int resultY;
switch (anchor) {
case NORTHWEST:
case NORTH:
case NORTHEAST: resultY = 0; break;
case WEST:
case CENTER:
case EAST: resultY = biggerHeight / 2 - smallerHeight / 2; break;
case SOUTHWEST:
case SOUTH:
case SOUTHEAST: resultY = biggerHeight - smallerHeight; break;
default: resultY = 0; break;
}
return resultY;
}
} // end namespace PV
<commit_msg>Fixed jitter bug<commit_after>#include "utils/PVLog.hpp"
//#include "utils/conversions.h"
#include <cmath>
#include <cstring>
namespace PV {
template <class T>
Buffer<T>::Buffer(int width, int height, int features) {
resize(width, height, features);
}
template <class T>
Buffer<T>::Buffer() {
resize(1, 1, 1);
}
template <class T>
Buffer<T>::Buffer(const std::vector<T> &data, int width, int height, int features) {
set(data, width, height, features);
}
// This constructor is for backwards compatibility with raw float buffers.
// It lacks bounds checking and should be removed when layers used Buffers
// instead of malloc'd floats.
template <class T>
Buffer<T>::Buffer(const T *data, int width, int height, int features) {
set(data, width, height, features);
}
template <class T>
T const Buffer<T>::at(int x, int y, int feature) const {
return at(index(x, y, feature));
}
template <class T>
T const Buffer<T>::at(int k) const {
return mData.at(k);
}
template <class T>
void Buffer<T>::set(int x, int y, int feature, T value) {
set(index(x, y, feature), value);
}
template <class T>
void Buffer<T>::set(int k, T value) {
mData.at(k) = value;
}
template <class T>
void Buffer<T>::set(const std::vector<T> &vector, int width, int height, int features) {
FatalIf(
vector.size() != width * height * features,
"Invalid vector size: Expected %d elements, vector contained %d elements.\n",
width * height * features,
vector.size());
mData = vector;
mWidth = width;
mHeight = height;
mFeatures = features;
}
template <class T>
void Buffer<T>::set(const T *data, int width, int height, int features) {
std::vector<T> tempVector(width * height * features);
for (size_t i = 0; i < tempVector.size(); ++i) {
tempVector.at(i) = data[i];
}
set(tempVector, width, height, features);
}
template <class T>
void Buffer<T>::set(Buffer<T> other) {
set(other.asVector(), other.getWidth(), other.getHeight(), other.getFeatures());
}
// Resizing a Buffer will clear its contents. Use rescale, crop, or grow to preserve values.
template <class T>
void Buffer<T>::resize(int width, int height, int features) {
mData.clear();
mData.resize(height * width * features);
mWidth = width;
mHeight = height;
mFeatures = features;
}
// Grows a buffer
template <class T>
void Buffer<T>::grow(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth <= getWidth() && newHeight <= getHeight()) {
return;
}
newWidth = std::max(newWidth, getWidth());
newHeight = std::max(newHeight, getHeight());
int offsetX = getAnchorX(anchor, getWidth(), newWidth);
int offsetY = getAnchorY(anchor, getHeight(), newHeight);
Buffer bigger(newWidth, newHeight, getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + offsetX;
int destY = y + offsetY;
if (destX < 0 || destX >= newWidth)
continue;
if (destY < 0 || destY >= newHeight)
continue;
bigger.set(destX, destY, f, at(x, y, f));
}
}
}
set(bigger.asVector(), newWidth, newHeight, getFeatures());
}
// Crops a buffer down to the specified size
template <class T>
void Buffer<T>::crop(int newWidth, int newHeight, enum Anchor anchor) {
if (newWidth >= getWidth() && newHeight >= getHeight()) {
return;
}
int offsetX = getAnchorX(anchor, newWidth, getWidth());
int offsetY = getAnchorY(anchor, newHeight, getHeight());
Buffer cropped(newWidth, newHeight, getFeatures());
for (int destY = 0; destY < newHeight; ++destY) {
for (int destX = 0; destX < newWidth; ++destX) {
for (int f = 0; f < getFeatures(); ++f) {
int sourceX = destX + offsetX;
int sourceY = destY + offsetY;
if (sourceX < 0 || sourceX >= getWidth())
continue;
if (sourceY < 0 || sourceY >= getHeight())
continue;
cropped.set(destX, destY, f, at(sourceX, sourceY, f));
}
}
}
set(cropped.asVector(), newWidth, newHeight, getFeatures());
}
template <class T>
void Buffer<T>::flip(bool xFlip, bool yFlip) {
if (!xFlip && !yFlip) {
return;
}
Buffer result(getWidth(), getHeight(), getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = xFlip ? getWidth() - 1 - x : x;
int destY = yFlip ? getHeight() - 1 - y : y;
result.set(destX, destY, f, at(x, y, f));
}
}
}
set(result.asVector(), getWidth(), getHeight(), getFeatures());
}
// Shift a buffer, clipping any values that land out of bounds
template <class T>
void Buffer<T>::translate(int xShift, int yShift) {
if (xShift == 0 && yShift == 0) {
return;
}
Buffer result(getWidth(), getHeight(), getFeatures());
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
for (int f = 0; f < getFeatures(); ++f) {
int destX = x + xShift;
int destY = y + yShift;
if (destX < 0 || destX >= getWidth())
continue;
if (destY < 0 || destY >= getHeight())
continue;
result.set(destX, destY, f, at(x, y, f));
}
}
}
set(result.asVector(), getWidth(), getHeight(), getFeatures());
}
template <class T>
int Buffer<T>::getAnchorX(enum Anchor anchor, int smallerWidth, int biggerWidth) {
int resultX;
switch (anchor) {
case NORTHWEST:
case WEST:
case SOUTHWEST: resultX = 0; break;
case NORTH:
case CENTER:
case SOUTH: resultX = biggerWidth / 2 - smallerWidth / 2; break;
case NORTHEAST:
case EAST:
case SOUTHEAST: resultX = biggerWidth - smallerWidth; break;
default: resultX = 0; break;
}
return resultX;
}
template <class T>
int Buffer<T>::getAnchorY(enum Anchor anchor, int smallerHeight, int biggerHeight) {
int resultY;
switch (anchor) {
case NORTHWEST:
case NORTH:
case NORTHEAST: resultY = 0; break;
case WEST:
case CENTER:
case EAST: resultY = biggerHeight / 2 - smallerHeight / 2; break;
case SOUTHWEST:
case SOUTH:
case SOUTHEAST: resultY = biggerHeight - smallerHeight; break;
default: resultY = 0; break;
}
return resultY;
}
} // end namespace PV
<|endoftext|> |
<commit_before><commit_msg>fixed header info<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rotmodit.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:14:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLVERTJUSTIFY_HPP_
#include <com/sun/star/table/CellVertJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWLOCATION_HPP_
#include <com/sun/star/table/ShadowLocation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEBORDER_HPP_
#include <com/sun/star/table/TableBorder.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWFORMAT_HPP_
#include <com/sun/star/table/ShadowFormat.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLCONTENTTYPE_HPP_
#include <com/sun/star/table/CellContentType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEORIENTATION_HPP_
#include <com/sun/star/table/TableOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLHORIJUSTIFY_HPP_
#include <com/sun/star/table/CellHoriJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELD_HPP_
#include <com/sun/star/util/SortField.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELDTYPE_HPP_
#include <com/sun/star/util/SortFieldType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLORIENTATION_HPP_
#include <com/sun/star/table/CellOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#include "rotmodit.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxRotateModeItem, SfxEnumItem);
//-----------------------------------------------------------------------
// SvxRotateModeItem - Ausrichtung bei gedrehtem Text
//-----------------------------------------------------------------------
SvxRotateModeItem::SvxRotateModeItem( SvxRotateMode eMode, USHORT _nWhich )
: SfxEnumItem( _nWhich, eMode )
{
}
SvxRotateModeItem::SvxRotateModeItem( const SvxRotateModeItem& rItem )
: SfxEnumItem( rItem )
{
}
__EXPORT SvxRotateModeItem::~SvxRotateModeItem()
{
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Create( SvStream& rStream, USHORT ) const
{
USHORT nVal;
rStream >> nVal;
return new SvxRotateModeItem( (SvxRotateMode) nVal,Which() );
}
SfxItemPresentation __EXPORT SvxRotateModeItem::GetPresentation(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/, SfxMapUnit /*ePresUnit*/,
String& rText, const IntlWrapper * ) const
{
rText.Erase();
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_COMPLETE:
rText.AppendAscii("...");
rText.AppendAscii(": ");
// break; // DURCHFALLEN!!!
case SFX_ITEM_PRESENTATION_NAMELESS:
rText += UniString::CreateFromInt32( GetValue() );
break;
default: ;//prevent warning
}
return ePres;
}
String __EXPORT SvxRotateModeItem::GetValueText( USHORT nVal ) const
{
String aText;
switch ( nVal )
{
case SVX_ROTATE_MODE_STANDARD:
case SVX_ROTATE_MODE_TOP:
case SVX_ROTATE_MODE_CENTER:
case SVX_ROTATE_MODE_BOTTOM:
aText.AppendAscii("...");
break;
default:
DBG_ERROR("SvxRotateModeItem: falscher enum");
break;
}
return aText;
}
USHORT __EXPORT SvxRotateModeItem::GetValueCount() const
{
return 4; // STANDARD, TOP, CENTER, BOTTOM
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Clone( SfxItemPool* ) const
{
return new SvxRotateModeItem( *this );
}
USHORT __EXPORT SvxRotateModeItem::GetVersion( USHORT /*nFileVersion*/ ) const
{
return 0;
}
// QueryValue/PutValue: Der ::com::sun::star::table::CellVertJustify enum wird mitbenutzt...
sal_Bool SvxRotateModeItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
table::CellVertJustify eUno = table::CellVertJustify_STANDARD;
switch ( (SvxRotateMode)GetValue() )
{
case SVX_ROTATE_MODE_STANDARD: eUno = table::CellVertJustify_STANDARD; break;
case SVX_ROTATE_MODE_TOP: eUno = table::CellVertJustify_TOP; break;
case SVX_ROTATE_MODE_CENTER: eUno = table::CellVertJustify_CENTER; break;
case SVX_ROTATE_MODE_BOTTOM: eUno = table::CellVertJustify_BOTTOM; break;
}
rVal <<= eUno;
return sal_True;
}
sal_Bool SvxRotateModeItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
table::CellVertJustify eUno;
if(!(rVal >>= eUno))
{
sal_Int32 nValue;
if(!(rVal >>= nValue))
return sal_False;
eUno = (table::CellVertJustify)nValue;
}
SvxRotateMode eSvx = SVX_ROTATE_MODE_STANDARD;
switch (eUno)
{
case table::CellVertJustify_STANDARD: eSvx = SVX_ROTATE_MODE_STANDARD; break;
case table::CellVertJustify_TOP: eSvx = SVX_ROTATE_MODE_TOP; break;
case table::CellVertJustify_CENTER: eSvx = SVX_ROTATE_MODE_CENTER; break;
case table::CellVertJustify_BOTTOM: eSvx = SVX_ROTATE_MODE_BOTTOM; break;
default: ;//prevent warning
}
SetValue( eSvx );
return sal_True;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.116); FILE MERGED 2006/09/01 17:47:01 kaib 1.5.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rotmodit.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:22:52 $
*
* 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 _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLVERTJUSTIFY_HPP_
#include <com/sun/star/table/CellVertJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWLOCATION_HPP_
#include <com/sun/star/table/ShadowLocation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEBORDER_HPP_
#include <com/sun/star/table/TableBorder.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWFORMAT_HPP_
#include <com/sun/star/table/ShadowFormat.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLCONTENTTYPE_HPP_
#include <com/sun/star/table/CellContentType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEORIENTATION_HPP_
#include <com/sun/star/table/TableOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLHORIJUSTIFY_HPP_
#include <com/sun/star/table/CellHoriJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELD_HPP_
#include <com/sun/star/util/SortField.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELDTYPE_HPP_
#include <com/sun/star/util/SortFieldType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLORIENTATION_HPP_
#include <com/sun/star/table/CellOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#include "rotmodit.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxRotateModeItem, SfxEnumItem);
//-----------------------------------------------------------------------
// SvxRotateModeItem - Ausrichtung bei gedrehtem Text
//-----------------------------------------------------------------------
SvxRotateModeItem::SvxRotateModeItem( SvxRotateMode eMode, USHORT _nWhich )
: SfxEnumItem( _nWhich, eMode )
{
}
SvxRotateModeItem::SvxRotateModeItem( const SvxRotateModeItem& rItem )
: SfxEnumItem( rItem )
{
}
__EXPORT SvxRotateModeItem::~SvxRotateModeItem()
{
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Create( SvStream& rStream, USHORT ) const
{
USHORT nVal;
rStream >> nVal;
return new SvxRotateModeItem( (SvxRotateMode) nVal,Which() );
}
SfxItemPresentation __EXPORT SvxRotateModeItem::GetPresentation(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/, SfxMapUnit /*ePresUnit*/,
String& rText, const IntlWrapper * ) const
{
rText.Erase();
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_COMPLETE:
rText.AppendAscii("...");
rText.AppendAscii(": ");
// break; // DURCHFALLEN!!!
case SFX_ITEM_PRESENTATION_NAMELESS:
rText += UniString::CreateFromInt32( GetValue() );
break;
default: ;//prevent warning
}
return ePres;
}
String __EXPORT SvxRotateModeItem::GetValueText( USHORT nVal ) const
{
String aText;
switch ( nVal )
{
case SVX_ROTATE_MODE_STANDARD:
case SVX_ROTATE_MODE_TOP:
case SVX_ROTATE_MODE_CENTER:
case SVX_ROTATE_MODE_BOTTOM:
aText.AppendAscii("...");
break;
default:
DBG_ERROR("SvxRotateModeItem: falscher enum");
break;
}
return aText;
}
USHORT __EXPORT SvxRotateModeItem::GetValueCount() const
{
return 4; // STANDARD, TOP, CENTER, BOTTOM
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Clone( SfxItemPool* ) const
{
return new SvxRotateModeItem( *this );
}
USHORT __EXPORT SvxRotateModeItem::GetVersion( USHORT /*nFileVersion*/ ) const
{
return 0;
}
// QueryValue/PutValue: Der ::com::sun::star::table::CellVertJustify enum wird mitbenutzt...
sal_Bool SvxRotateModeItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
table::CellVertJustify eUno = table::CellVertJustify_STANDARD;
switch ( (SvxRotateMode)GetValue() )
{
case SVX_ROTATE_MODE_STANDARD: eUno = table::CellVertJustify_STANDARD; break;
case SVX_ROTATE_MODE_TOP: eUno = table::CellVertJustify_TOP; break;
case SVX_ROTATE_MODE_CENTER: eUno = table::CellVertJustify_CENTER; break;
case SVX_ROTATE_MODE_BOTTOM: eUno = table::CellVertJustify_BOTTOM; break;
}
rVal <<= eUno;
return sal_True;
}
sal_Bool SvxRotateModeItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
table::CellVertJustify eUno;
if(!(rVal >>= eUno))
{
sal_Int32 nValue;
if(!(rVal >>= nValue))
return sal_False;
eUno = (table::CellVertJustify)nValue;
}
SvxRotateMode eSvx = SVX_ROTATE_MODE_STANDARD;
switch (eUno)
{
case table::CellVertJustify_STANDARD: eSvx = SVX_ROTATE_MODE_STANDARD; break;
case table::CellVertJustify_TOP: eSvx = SVX_ROTATE_MODE_TOP; break;
case table::CellVertJustify_CENTER: eSvx = SVX_ROTATE_MODE_CENTER; break;
case table::CellVertJustify_BOTTOM: eSvx = SVX_ROTATE_MODE_BOTTOM; break;
default: ;//prevent warning
}
SetValue( eSvx );
return sal_True;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdoimp.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 19:06:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SVX_SVDOIMP_HXX
#include <svdoimp.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SVX_XLNSTIT_HXX
#include <svx/xlnstit.hxx>
#endif
#ifndef _SVX_XLNEDIT_HXX
#include <svx/xlnedit.hxx>
#endif
#ifndef _SVX_XLNWTIT_HXX
#include <svx/xlnwtit.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX
#include <svx/xlineit0.hxx>
#endif
#ifndef _SVX_XLNSTWIT_HXX
#include <svx/xlnstwit.hxx>
#endif
#ifndef _SVX_XLNEDWIT_HXX
#include <svx/xlnedwit.hxx>
#endif
#ifndef _SVX_XLNSTCIT_HXX
#include <svx/xlnstcit.hxx>
#endif
#ifndef _SVX_XLNEDCIT_HXX
#include <svx/xlnedcit.hxx>
#endif
#ifndef _SVX_XLINJOIT_HXX
#include <xlinjoit.hxx>
#endif
#ifndef _SVX_XLNDSIT_HXX
#include <svx/xlndsit.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYGON_HXX
#include <basegfx/polygon/b2dpolygon.hxx>
#endif
#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif
#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYGONTOOLS_HXX
#include <basegfx/polygon/b2dpolygontools.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_POLYPOLYGON_B2DPOLYGONTOOLS_HXX
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DLINEGEOMETRY_HXX
#include <basegfx/polygon/b2dlinegeometry.hxx>
#endif
///////////////////////////////////////////////////////////////////////////////
ImpLineStyleParameterPack::ImpLineStyleParameterPack(
const SfxItemSet& rSet,
bool _bForceHair)
: mbForceNoArrowsLeft(false),
mbForceNoArrowsRight(false),
mbForceHair(_bForceHair)
{
maStartPolyPolygon = ((const XLineStartItem&)(rSet.Get(XATTR_LINESTART))).GetLineStartValue();
if(maStartPolyPolygon.count())
{
if(maStartPolyPolygon.areControlPointsUsed())
{
maStartPolyPolygon = basegfx::tools::adaptiveSubdivideByAngle(maStartPolyPolygon);
}
if(basegfx::ORIENTATION_NEGATIVE == basegfx::tools::getOrientation(maStartPolyPolygon.getB2DPolygon(0L)))
{
maStartPolyPolygon.flip();
}
}
maEndPolyPolygon = ((const XLineEndItem&)(rSet.Get(XATTR_LINEEND))).GetLineEndValue();
if(maEndPolyPolygon.count())
{
if(maEndPolyPolygon.areControlPointsUsed())
{
maEndPolyPolygon = basegfx::tools::adaptiveSubdivideByAngle(maEndPolyPolygon);
}
if(basegfx::ORIENTATION_NEGATIVE == basegfx::tools::getOrientation(maEndPolyPolygon.getB2DPolygon(0L)))
{
maEndPolyPolygon.flip();
}
}
mnLineWidth = ((const XLineWidthItem&)(rSet.Get(XATTR_LINEWIDTH))).GetValue();
mbLineStyleSolid = (XLINE_SOLID == (XLineStyle)((const XLineStyleItem&)rSet.Get(XATTR_LINESTYLE)).GetValue());
mnStartWidth = ((const XLineStartWidthItem&)(rSet.Get(XATTR_LINESTARTWIDTH))).GetValue();
if(mnStartWidth < 0)
mnStartWidth = -mnLineWidth * mnStartWidth / 100L;
mnEndWidth = ((const XLineEndWidthItem&)(rSet.Get(XATTR_LINEENDWIDTH))).GetValue();
if(mnEndWidth < 0)
mnEndWidth = -mnLineWidth * mnEndWidth / 100L;
mbStartCentered = ((const XLineStartCenterItem&)(rSet.Get(XATTR_LINESTARTCENTER))).GetValue();
mbEndCentered = ((const XLineEndCenterItem&)(rSet.Get(XATTR_LINEENDCENTER))).GetValue();
mfDegreeStepWidth = 10.0;
meLineJoint = ((const XLineJointItem&)(rSet.Get(XATTR_LINEJOINT))).GetValue();
XDash aDash = ((const XLineDashItem&)(rSet.Get(XATTR_LINEDASH))).GetDashValue();
// fill local dash info
mfFullDotDashLen = aDash.CreateDotDashArray(maDotDashArray, (double)GetDisplayLineWidth());
}
ImpLineStyleParameterPack::~ImpLineStyleParameterPack()
{
}
bool ImpLineStyleParameterPack::IsStartActive() const
{
if(!mbForceNoArrowsLeft && maStartPolyPolygon.count() && GetStartWidth())
{
return (0L != maStartPolyPolygon.getB2DPolygon(0L).count());
}
return false;
}
bool ImpLineStyleParameterPack::IsEndActive() const
{
if(!mbForceNoArrowsRight && maEndPolyPolygon.count() && GetEndWidth())
{
return (0L != maEndPolyPolygon.getB2DPolygon(0L).count());
}
return false;
}
void ImpLineGeometryCreator::ImpCreateLineGeometry(const basegfx::B2DPolygon& rSourcePoly)
{
if(rSourcePoly.count() > 1L)
{
basegfx::B2DPolygon aSourceLineGeometry(rSourcePoly);
if(aSourceLineGeometry.areControlPointsUsed())
{
aSourceLineGeometry = basegfx::tools::adaptiveSubdivideByAngle(aSourceLineGeometry);
}
sal_uInt32 nCount(aSourceLineGeometry.count());
if(!aSourceLineGeometry.isClosed())
{
nCount--;
const double fPolyLength(basegfx::tools::getLength(aSourceLineGeometry));
double fStart(0.0);
double fEnd(0.0);
if(mrLineAttr.IsStartActive())
{
// create line start polygon and move line end
basegfx::B2DPolyPolygon aArrowPolyPolygon;
aArrowPolyPolygon.append(mrLineAttr.GetStartPolyPolygon());
basegfx::B2DPolyPolygon aArrow = basegfx::tools::createAreaGeometryForLineStartEnd(
aSourceLineGeometry,
aArrowPolyPolygon,
true,
(double)mrLineAttr.GetStartWidth(),
mrLineAttr.IsStartCentered() ? 0.5 : 0.0,
&fStart);
maAreaPolyPolygon.append(aArrow);
fStart *= 0.8;
}
if(mrLineAttr.IsEndActive())
{
// create line end polygon and move line end
basegfx::B2DPolyPolygon aArrowPolyPolygon;
aArrowPolyPolygon.append(mrLineAttr.GetEndPolyPolygon());
basegfx::B2DPolyPolygon aArrow = basegfx::tools::createAreaGeometryForLineStartEnd(
aSourceLineGeometry,
aArrowPolyPolygon,
false,
(double)mrLineAttr.GetEndWidth(),
mrLineAttr.IsEndCentered() ? 0.5 : 0.0,
&fEnd);
maAreaPolyPolygon.append(aArrow);
fEnd *= 0.8;
}
if(fStart != 0.0 || fEnd != 0.0)
{
// build new poly, consume something from old poly
aSourceLineGeometry = basegfx::tools::getSnippetAbsolute(
aSourceLineGeometry, fStart, fPolyLength - fEnd, fPolyLength);
nCount = aSourceLineGeometry.count() - 1L;
}
}
if(nCount)
{
basegfx::B2DPolyPolygon aHairLinePolyPolygon;
if(mbLineDraft || mrLineAttr.IsLineStyleSolid())
{
// no LineStyle
aHairLinePolyPolygon.append(aSourceLineGeometry);
}
else
{
// apply LineStyle
aHairLinePolyPolygon = basegfx::tools::applyLineDashing(aSourceLineGeometry, mrLineAttr.GetDotDash(), mrLineAttr.GetFullDotDashLen());
// merge LineStyle polygons to bigger parts
aHairLinePolyPolygon = basegfx::tools::mergeDashedLines(aHairLinePolyPolygon);
}
if(!mrLineAttr.GetDisplayLineWidth())
{
// LineWidth zero, add directly to linePoly
maLinePolyPolygon.append(aHairLinePolyPolygon);
}
else
{
basegfx::tools::B2DLineJoin aB2DLineJoin(basegfx::tools::B2DLINEJOIN_NONE);
switch(mrLineAttr.GetLineJoint())
{
case XLINEJOINT_NONE : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_NONE; break;
case XLINEJOINT_MIDDLE : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_MIDDLE; break;
case XLINEJOINT_BEVEL : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_BEVEL; break;
case XLINEJOINT_MITER : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_MITER; break;
case XLINEJOINT_ROUND : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_ROUND; break;
}
for(sal_uInt32 a(0L); a < aHairLinePolyPolygon.count(); a++)
{
basegfx::B2DPolygon aCandidate = aHairLinePolyPolygon.getB2DPolygon(a);
basegfx::B2DPolyPolygon aAreaPolyPolygon = basegfx::tools::createAreaGeometryForPolygon(
aCandidate,
(double)mrLineAttr.GetDisplayLineWidth() / 2.0,
aB2DLineJoin,
(double)mrLineAttr.GetDegreeStepWidth() * F_PI180,
(double)mrLineAttr.GetLinejointMiterMinimumAngle() * F_PI180);
maAreaPolyPolygon.append(aAreaPolyPolygon);
}
}
}
}
}
// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.7.366); FILE MERGED 2008/04/01 15:51:41 thb 1.7.366.3: #i85898# Stripping all external header guards 2008/04/01 12:50:00 thb 1.7.366.2: #i85898# Stripping all external header guards 2008/03/31 14:23:32 rt 1.7.366.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: svdoimp.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svdoimp.hxx>
#include <svtools/itemset.hxx>
#include <svx/xlnstit.hxx>
#include <svx/xlnedit.hxx>
#include <svx/xlnwtit.hxx>
#include <svx/xlineit0.hxx>
#include <svx/xlnstwit.hxx>
#include <svx/xlnedwit.hxx>
#include <svx/xlnstcit.hxx>
#include <svx/xlnedcit.hxx>
#include <xlinjoit.hxx>
#include <svx/xlndsit.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dlinegeometry.hxx>
///////////////////////////////////////////////////////////////////////////////
ImpLineStyleParameterPack::ImpLineStyleParameterPack(
const SfxItemSet& rSet,
bool _bForceHair)
: mbForceNoArrowsLeft(false),
mbForceNoArrowsRight(false),
mbForceHair(_bForceHair)
{
maStartPolyPolygon = ((const XLineStartItem&)(rSet.Get(XATTR_LINESTART))).GetLineStartValue();
if(maStartPolyPolygon.count())
{
if(maStartPolyPolygon.areControlPointsUsed())
{
maStartPolyPolygon = basegfx::tools::adaptiveSubdivideByAngle(maStartPolyPolygon);
}
if(basegfx::ORIENTATION_NEGATIVE == basegfx::tools::getOrientation(maStartPolyPolygon.getB2DPolygon(0L)))
{
maStartPolyPolygon.flip();
}
}
maEndPolyPolygon = ((const XLineEndItem&)(rSet.Get(XATTR_LINEEND))).GetLineEndValue();
if(maEndPolyPolygon.count())
{
if(maEndPolyPolygon.areControlPointsUsed())
{
maEndPolyPolygon = basegfx::tools::adaptiveSubdivideByAngle(maEndPolyPolygon);
}
if(basegfx::ORIENTATION_NEGATIVE == basegfx::tools::getOrientation(maEndPolyPolygon.getB2DPolygon(0L)))
{
maEndPolyPolygon.flip();
}
}
mnLineWidth = ((const XLineWidthItem&)(rSet.Get(XATTR_LINEWIDTH))).GetValue();
mbLineStyleSolid = (XLINE_SOLID == (XLineStyle)((const XLineStyleItem&)rSet.Get(XATTR_LINESTYLE)).GetValue());
mnStartWidth = ((const XLineStartWidthItem&)(rSet.Get(XATTR_LINESTARTWIDTH))).GetValue();
if(mnStartWidth < 0)
mnStartWidth = -mnLineWidth * mnStartWidth / 100L;
mnEndWidth = ((const XLineEndWidthItem&)(rSet.Get(XATTR_LINEENDWIDTH))).GetValue();
if(mnEndWidth < 0)
mnEndWidth = -mnLineWidth * mnEndWidth / 100L;
mbStartCentered = ((const XLineStartCenterItem&)(rSet.Get(XATTR_LINESTARTCENTER))).GetValue();
mbEndCentered = ((const XLineEndCenterItem&)(rSet.Get(XATTR_LINEENDCENTER))).GetValue();
mfDegreeStepWidth = 10.0;
meLineJoint = ((const XLineJointItem&)(rSet.Get(XATTR_LINEJOINT))).GetValue();
XDash aDash = ((const XLineDashItem&)(rSet.Get(XATTR_LINEDASH))).GetDashValue();
// fill local dash info
mfFullDotDashLen = aDash.CreateDotDashArray(maDotDashArray, (double)GetDisplayLineWidth());
}
ImpLineStyleParameterPack::~ImpLineStyleParameterPack()
{
}
bool ImpLineStyleParameterPack::IsStartActive() const
{
if(!mbForceNoArrowsLeft && maStartPolyPolygon.count() && GetStartWidth())
{
return (0L != maStartPolyPolygon.getB2DPolygon(0L).count());
}
return false;
}
bool ImpLineStyleParameterPack::IsEndActive() const
{
if(!mbForceNoArrowsRight && maEndPolyPolygon.count() && GetEndWidth())
{
return (0L != maEndPolyPolygon.getB2DPolygon(0L).count());
}
return false;
}
void ImpLineGeometryCreator::ImpCreateLineGeometry(const basegfx::B2DPolygon& rSourcePoly)
{
if(rSourcePoly.count() > 1L)
{
basegfx::B2DPolygon aSourceLineGeometry(rSourcePoly);
if(aSourceLineGeometry.areControlPointsUsed())
{
aSourceLineGeometry = basegfx::tools::adaptiveSubdivideByAngle(aSourceLineGeometry);
}
sal_uInt32 nCount(aSourceLineGeometry.count());
if(!aSourceLineGeometry.isClosed())
{
nCount--;
const double fPolyLength(basegfx::tools::getLength(aSourceLineGeometry));
double fStart(0.0);
double fEnd(0.0);
if(mrLineAttr.IsStartActive())
{
// create line start polygon and move line end
basegfx::B2DPolyPolygon aArrowPolyPolygon;
aArrowPolyPolygon.append(mrLineAttr.GetStartPolyPolygon());
basegfx::B2DPolyPolygon aArrow = basegfx::tools::createAreaGeometryForLineStartEnd(
aSourceLineGeometry,
aArrowPolyPolygon,
true,
(double)mrLineAttr.GetStartWidth(),
mrLineAttr.IsStartCentered() ? 0.5 : 0.0,
&fStart);
maAreaPolyPolygon.append(aArrow);
fStart *= 0.8;
}
if(mrLineAttr.IsEndActive())
{
// create line end polygon and move line end
basegfx::B2DPolyPolygon aArrowPolyPolygon;
aArrowPolyPolygon.append(mrLineAttr.GetEndPolyPolygon());
basegfx::B2DPolyPolygon aArrow = basegfx::tools::createAreaGeometryForLineStartEnd(
aSourceLineGeometry,
aArrowPolyPolygon,
false,
(double)mrLineAttr.GetEndWidth(),
mrLineAttr.IsEndCentered() ? 0.5 : 0.0,
&fEnd);
maAreaPolyPolygon.append(aArrow);
fEnd *= 0.8;
}
if(fStart != 0.0 || fEnd != 0.0)
{
// build new poly, consume something from old poly
aSourceLineGeometry = basegfx::tools::getSnippetAbsolute(
aSourceLineGeometry, fStart, fPolyLength - fEnd, fPolyLength);
nCount = aSourceLineGeometry.count() - 1L;
}
}
if(nCount)
{
basegfx::B2DPolyPolygon aHairLinePolyPolygon;
if(mbLineDraft || mrLineAttr.IsLineStyleSolid())
{
// no LineStyle
aHairLinePolyPolygon.append(aSourceLineGeometry);
}
else
{
// apply LineStyle
aHairLinePolyPolygon = basegfx::tools::applyLineDashing(aSourceLineGeometry, mrLineAttr.GetDotDash(), mrLineAttr.GetFullDotDashLen());
// merge LineStyle polygons to bigger parts
aHairLinePolyPolygon = basegfx::tools::mergeDashedLines(aHairLinePolyPolygon);
}
if(!mrLineAttr.GetDisplayLineWidth())
{
// LineWidth zero, add directly to linePoly
maLinePolyPolygon.append(aHairLinePolyPolygon);
}
else
{
basegfx::tools::B2DLineJoin aB2DLineJoin(basegfx::tools::B2DLINEJOIN_NONE);
switch(mrLineAttr.GetLineJoint())
{
case XLINEJOINT_NONE : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_NONE; break;
case XLINEJOINT_MIDDLE : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_MIDDLE; break;
case XLINEJOINT_BEVEL : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_BEVEL; break;
case XLINEJOINT_MITER : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_MITER; break;
case XLINEJOINT_ROUND : aB2DLineJoin = basegfx::tools::B2DLINEJOIN_ROUND; break;
}
for(sal_uInt32 a(0L); a < aHairLinePolyPolygon.count(); a++)
{
basegfx::B2DPolygon aCandidate = aHairLinePolyPolygon.getB2DPolygon(a);
basegfx::B2DPolyPolygon aAreaPolyPolygon = basegfx::tools::createAreaGeometryForPolygon(
aCandidate,
(double)mrLineAttr.GetDisplayLineWidth() / 2.0,
aB2DLineJoin,
(double)mrLineAttr.GetDegreeStepWidth() * F_PI180,
(double)mrLineAttr.GetLinejointMiterMinimumAngle() * F_PI180);
maAreaPolyPolygon.append(aAreaPolyPolygon);
}
}
}
}
}
// eof
<|endoftext|> |
<commit_before><commit_msg>Revert "optimise SdrObjList::SetObjectOrdNum"<commit_after><|endoftext|> |
<commit_before><commit_msg>Remove repeated check<commit_after><|endoftext|> |
<commit_before><commit_msg>coverity#1266473 Dereference null return value<commit_after><|endoftext|> |
<commit_before><commit_msg>sw: Prefix _SaveTable member variables.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbinsdlg.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:09:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBINSDLG_HXX
#define _DBINSDLG_HXX
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _SWNUMFMTLB_HXX //autogen
#include <numfmtlb.hxx>
#endif
#ifndef _SWDBDATA_HXX
#include <swdbdata.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
namespace com{namespace sun{namespace star{
namespace sdbcx{
class XColumnsSupplier;
}
namespace sdbc{
class XDataSource;
class XConnection;
class XResultSet;
}
}}}
class SwTableAutoFmt;
class SwView;
class SfxItemSet;
class SwTableRep;
class _DB_Columns;
struct SwInsDBColumn
{
rtl::OUString sColumn, sUsrNumFmt;
sal_Int32 nDBNumFmt;
ULONG nUsrNumFmt;
LanguageType eUsrNumFmtLng;
USHORT nCol;
BOOL bHasFmt : 1;
BOOL bIsDBFmt : 1;
SwInsDBColumn( const String& rStr, USHORT nColumn )
: sColumn( rStr ), nCol( nColumn ), nDBNumFmt( 0 ), nUsrNumFmt( 0 ),
bHasFmt(FALSE), bIsDBFmt(TRUE), eUsrNumFmtLng( LANGUAGE_SYSTEM )
{}
int operator==( const SwInsDBColumn& rCmp ) const
{ return sColumn == rCmp.sColumn; }
int operator<( const SwInsDBColumn& rCmp ) const;
};
typedef SwInsDBColumn* SwInsDBColumnPtr;
SV_DECL_PTRARR_SORT_DEL( SwInsDBColumns, SwInsDBColumnPtr, 32, 32 )
class SwInsertDBColAutoPilot : public SfxModalDialog, public utl::ConfigItem
{
FixedText aFtInsertData;
RadioButton aRbAsTable;
RadioButton aRbAsField;
RadioButton aRbAsText;
FixedLine aFlHead;
FixedText aFtDbColumn;
ListBox aLbTblDbColumn;
ListBox aLbTxtDbColumn;
FixedLine aFlFormat;
RadioButton aRbDbFmtFromDb;
RadioButton aRbDbFmtFromUsr;
NumFormatListBox aLbDbFmtFromUsr;
/* ----- Page Text/Field ------- */
ImageButton aIbDbcolToEdit;
MultiLineEdit aEdDbText;
FixedText aFtDbParaColl;
ListBox aLbDbParaColl;
/* ----- Page Table ------------ */
ImageButton aIbDbcolAllTo;
ImageButton aIbDbcolOneTo;
ImageButton aIbDbcolOneFrom;
ImageButton aIbDbcolAllFrom;
FixedText aFtTableCol;
ListBox aLbTableCol;
CheckBox aCbTableHeadon;
RadioButton aRbHeadlColnms;
RadioButton aRbHeadlEmpty;
PushButton aPbTblFormat;
PushButton aPbTblAutofmt;
OKButton aBtOk;
CancelButton aBtCancel;
HelpButton aBtHelp;
FixedLine aFlBottom;
SwInsDBColumns aDBColumns;
const SwDBData aDBData;
Link aOldNumFmtLnk;
String sNoTmpl;
SwView* pView;
SwTableAutoFmt* pTAutoFmt;
SfxItemSet* pTblSet;
SwTableRep* pRep;
USHORT nGBFmtLen;
DECL_LINK( PageHdl, Button* );
DECL_LINK( AutoFmtHdl, PushButton* );
DECL_LINK( TblFmtHdl, PushButton* );
DECL_LINK( DBFormatHdl, Button* );
DECL_LINK( TblToFromHdl, Button* );
DECL_LINK( SelectHdl, ListBox* );
DECL_LINK( DblClickHdl, ListBox* );
DECL_LINK( HeaderHdl, Button* );
FASTBOOL SplitTextToColArr( const String& rTxt, _DB_Columns& rColArr, BOOL bInsField );
virtual void Commit();
void Load();
// setze die Tabellen - Eigenschaften
void SetTabSet();
public:
SwInsertDBColAutoPilot( SwView& rView,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource> rxSource,
com::sun::star::uno::Reference<com::sun::star::sdbcx::XColumnsSupplier>,
const SwDBData& rData );
virtual ~SwInsertDBColAutoPilot();
void DataToDoc( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rSelection,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource> rxSource,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> xConnection,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xResultSet);
};
#endif
<commit_msg>INTEGRATION: CWS numberformat (1.9.74); FILE MERGED 2005/10/26 17:50:49 kendy 1.9.74.1: #i55546# The ULONG -> sal_uInt32 patches related to NumberFormat extracted from ooo64bit02 CWS.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbinsdlg.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-12-14 14:51:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBINSDLG_HXX
#define _DBINSDLG_HXX
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _SWNUMFMTLB_HXX //autogen
#include <numfmtlb.hxx>
#endif
#ifndef _SWDBDATA_HXX
#include <swdbdata.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
namespace com{namespace sun{namespace star{
namespace sdbcx{
class XColumnsSupplier;
}
namespace sdbc{
class XDataSource;
class XConnection;
class XResultSet;
}
}}}
class SwTableAutoFmt;
class SwView;
class SfxItemSet;
class SwTableRep;
class _DB_Columns;
struct SwInsDBColumn
{
rtl::OUString sColumn, sUsrNumFmt;
sal_Int32 nDBNumFmt;
sal_uInt32 nUsrNumFmt;
LanguageType eUsrNumFmtLng;
USHORT nCol;
BOOL bHasFmt : 1;
BOOL bIsDBFmt : 1;
SwInsDBColumn( const String& rStr, USHORT nColumn )
: sColumn( rStr ), nCol( nColumn ), nDBNumFmt( 0 ), nUsrNumFmt( 0 ),
bHasFmt(FALSE), bIsDBFmt(TRUE), eUsrNumFmtLng( LANGUAGE_SYSTEM )
{}
int operator==( const SwInsDBColumn& rCmp ) const
{ return sColumn == rCmp.sColumn; }
int operator<( const SwInsDBColumn& rCmp ) const;
};
typedef SwInsDBColumn* SwInsDBColumnPtr;
SV_DECL_PTRARR_SORT_DEL( SwInsDBColumns, SwInsDBColumnPtr, 32, 32 )
class SwInsertDBColAutoPilot : public SfxModalDialog, public utl::ConfigItem
{
FixedText aFtInsertData;
RadioButton aRbAsTable;
RadioButton aRbAsField;
RadioButton aRbAsText;
FixedLine aFlHead;
FixedText aFtDbColumn;
ListBox aLbTblDbColumn;
ListBox aLbTxtDbColumn;
FixedLine aFlFormat;
RadioButton aRbDbFmtFromDb;
RadioButton aRbDbFmtFromUsr;
NumFormatListBox aLbDbFmtFromUsr;
/* ----- Page Text/Field ------- */
ImageButton aIbDbcolToEdit;
MultiLineEdit aEdDbText;
FixedText aFtDbParaColl;
ListBox aLbDbParaColl;
/* ----- Page Table ------------ */
ImageButton aIbDbcolAllTo;
ImageButton aIbDbcolOneTo;
ImageButton aIbDbcolOneFrom;
ImageButton aIbDbcolAllFrom;
FixedText aFtTableCol;
ListBox aLbTableCol;
CheckBox aCbTableHeadon;
RadioButton aRbHeadlColnms;
RadioButton aRbHeadlEmpty;
PushButton aPbTblFormat;
PushButton aPbTblAutofmt;
OKButton aBtOk;
CancelButton aBtCancel;
HelpButton aBtHelp;
FixedLine aFlBottom;
SwInsDBColumns aDBColumns;
const SwDBData aDBData;
Link aOldNumFmtLnk;
String sNoTmpl;
SwView* pView;
SwTableAutoFmt* pTAutoFmt;
SfxItemSet* pTblSet;
SwTableRep* pRep;
USHORT nGBFmtLen;
DECL_LINK( PageHdl, Button* );
DECL_LINK( AutoFmtHdl, PushButton* );
DECL_LINK( TblFmtHdl, PushButton* );
DECL_LINK( DBFormatHdl, Button* );
DECL_LINK( TblToFromHdl, Button* );
DECL_LINK( SelectHdl, ListBox* );
DECL_LINK( DblClickHdl, ListBox* );
DECL_LINK( HeaderHdl, Button* );
FASTBOOL SplitTextToColArr( const String& rTxt, _DB_Columns& rColArr, BOOL bInsField );
virtual void Commit();
void Load();
// setze die Tabellen - Eigenschaften
void SetTabSet();
public:
SwInsertDBColAutoPilot( SwView& rView,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource> rxSource,
com::sun::star::uno::Reference<com::sun::star::sdbcx::XColumnsSupplier>,
const SwDBData& rData );
virtual ~SwInsertDBColAutoPilot();
void DataToDoc( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rSelection,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource> rxSource,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> xConnection,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xResultSet);
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inputwin.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-10-22 15:19:26 $
*
* 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 SW_INPUTWIN_HXX
#define SW_INPUTWIN_HXX
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
class SwFldMgr;
class SwWrtShell;
class SwView;
class SfxDispatcher;
//========================================================================
class InputEdit : public Edit
{
public:
InputEdit(Window* pParent, WinBits nStyle) :
Edit(pParent , nStyle){}
void UpdateRange(const String& aSel,
const String& aTblName );
protected:
virtual void KeyInput( const KeyEvent& );
};
//========================================================================
class SwInputWindow : public ToolBox
{
friend class InputEdit;
Edit aPos;
InputEdit aEdit;
PopupMenu aPopMenu;
SwFldMgr* pMgr;
SwWrtShell* pWrtShell;
SwView* pView;
SfxBindings* pBindings;
String aAktTableName, sOldFml;
USHORT nActionCnt;
BOOL bFirst : 1; //Initialisierungen beim ersten Aufruf
BOOL bActive : 1; //fuer Hide/Show beim Dokumentwechsel
BOOL bIsTable : 1;
BOOL bDelSel : 1;
BOOL bDoesUndo : 1;
BOOL bResetUndo : 1;
BOOL bCallUndo : 1;
void DelBoxCntnt();
DECL_LINK( ModifyHdl, InputEdit* );
using Window::IsActive;
protected:
virtual void Resize();
virtual void Click();
DECL_LINK( MenuHdl, Menu * );
DECL_LINK( DropdownClickHdl, ToolBox* );
void ApplyFormula();
void CancelFormula();
public:
SwInputWindow( Window* pParent, SfxBindings* pBindings );
virtual ~SwInputWindow();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
void SelectHdl( ToolBox*);
void ShowWin();
BOOL IsActive(){ return bActive; };
DECL_LINK( SelTblCellsNotify, SwWrtShell * );
void SetFormula( const String& rFormula, BOOL bDelSel = TRUE );
const SwView* GetView() const{return pView;}
};
class SwInputChild : public SfxChildWindow
{
BOOL bObjVis;
SfxDispatcher* pDispatch;
public:
SwInputChild( Window* ,
USHORT nId,
SfxBindings*,
SfxChildWinInfo* );
~SwInputChild();
SFX_DECL_CHILDWINDOW( SwInputChild );
void SetFormula( const String& rFormula, BOOL bDelSel = TRUE )
{ ((SwInputWindow*)pWindow)->SetFormula(
rFormula, bDelSel ); }
const SwView* GetView() const{return ((SwInputWindow*)pWindow)->GetView();}
};
//==================================================================
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.7.216); FILE MERGED 2008/04/01 15:59:14 thb 1.7.216.2: #i85898# Stripping all external header guards 2008/03/31 16:58:33 rt 1.7.216.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: inputwin.hxx,v $
* $Revision: 1.8 $
*
* 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 SW_INPUTWIN_HXX
#define SW_INPUTWIN_HXX
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#include <sfx2/childwin.hxx>
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
class SwFldMgr;
class SwWrtShell;
class SwView;
class SfxDispatcher;
//========================================================================
class InputEdit : public Edit
{
public:
InputEdit(Window* pParent, WinBits nStyle) :
Edit(pParent , nStyle){}
void UpdateRange(const String& aSel,
const String& aTblName );
protected:
virtual void KeyInput( const KeyEvent& );
};
//========================================================================
class SwInputWindow : public ToolBox
{
friend class InputEdit;
Edit aPos;
InputEdit aEdit;
PopupMenu aPopMenu;
SwFldMgr* pMgr;
SwWrtShell* pWrtShell;
SwView* pView;
SfxBindings* pBindings;
String aAktTableName, sOldFml;
USHORT nActionCnt;
BOOL bFirst : 1; //Initialisierungen beim ersten Aufruf
BOOL bActive : 1; //fuer Hide/Show beim Dokumentwechsel
BOOL bIsTable : 1;
BOOL bDelSel : 1;
BOOL bDoesUndo : 1;
BOOL bResetUndo : 1;
BOOL bCallUndo : 1;
void DelBoxCntnt();
DECL_LINK( ModifyHdl, InputEdit* );
using Window::IsActive;
protected:
virtual void Resize();
virtual void Click();
DECL_LINK( MenuHdl, Menu * );
DECL_LINK( DropdownClickHdl, ToolBox* );
void ApplyFormula();
void CancelFormula();
public:
SwInputWindow( Window* pParent, SfxBindings* pBindings );
virtual ~SwInputWindow();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
void SelectHdl( ToolBox*);
void ShowWin();
BOOL IsActive(){ return bActive; };
DECL_LINK( SelTblCellsNotify, SwWrtShell * );
void SetFormula( const String& rFormula, BOOL bDelSel = TRUE );
const SwView* GetView() const{return pView;}
};
class SwInputChild : public SfxChildWindow
{
BOOL bObjVis;
SfxDispatcher* pDispatch;
public:
SwInputChild( Window* ,
USHORT nId,
SfxBindings*,
SfxChildWinInfo* );
~SwInputChild();
SFX_DECL_CHILDWINDOW( SwInputChild );
void SetFormula( const String& rFormula, BOOL bDelSel = TRUE )
{ ((SwInputWindow*)pWindow)->SetFormula(
rFormula, bDelSel ); }
const SwView* GetView() const{return ((SwInputWindow*)pWindow)->GetView();}
};
//==================================================================
#endif
<|endoftext|> |
<commit_before><commit_msg>fdo#50386 Page count field makes scrolling impossible<commit_after><|endoftext|> |
<commit_before>#include "tasks-utils.h"
WARNINGS_DISABLE
#include <QDir>
#include <QRegExp>
#include <QString>
#include <QStringList>
WARNINGS_ENABLE
#include <TSettings.h>
#include "tasks-defs.h"
QString makeTarsnapCommand(QString cmd)
{
TSettings settings;
QString tarsnapDir = settings.value("tarsnap/path", "").toString();
if(tarsnapDir.isEmpty())
return cmd;
else
return tarsnapDir + QDir::separator() + cmd;
}
QStringList makeTarsnapArgs()
{
TSettings settings;
QStringList args;
/* Default arguments: --keyfile and --cachedir. */
QString tarsnapKeyFile = settings.value("tarsnap/key", "").toString();
if(!tarsnapKeyFile.isEmpty())
args << "--keyfile" << tarsnapKeyFile;
QString tarsnapCacheDir = settings.value("tarsnap/cache", "").toString();
if(!tarsnapCacheDir.isEmpty())
args << "--cachedir" << tarsnapCacheDir;
/* Network rate limits: --maxbw-rate-down and --maxbw-rate-up. */
int download_rate_kbps = settings.value("app/limit_download", 0).toInt();
if(download_rate_kbps)
{
args << "--maxbw-rate-down"
<< QString::number(1024 * quint64(download_rate_kbps));
}
int upload_rate_kbps = settings.value("app/limit_upload", 0).toInt();
if(upload_rate_kbps)
{
args << "--maxbw-rate-up"
<< QString::number(1024 * quint64(upload_rate_kbps));
}
/* Add --no-default-config. */
if(settings.value("tarsnap/no_default_config", DEFAULT_NO_DEFAULT_CONFIG)
.toBool())
args.prepend("--no-default-config");
return (args);
}
/*
* The QVersionNumber class was introduced in Qt 5.6, which is later than
* our target of Qt 5.2.1.
*/
int versionCompare(QString found, QString fixed)
{
int i;
/* Parse strings. */
QStringList foundlist = found.split(QRegExp("\\."));
QStringList fixedlist = fixed.split(QRegExp("\\."));
/* Sanity check. */
Q_ASSERT(fixedlist.size() == 3);
Q_ASSERT(foundlist.size() >= 3);
/* Append extra 0s to the "fixed" string. */
for(i = 0; i < foundlist.size() - fixedlist.size(); i++)
fixedlist.append("0");
/* Compare each portion of the strings. */
for(i = 0; i < fixedlist.size(); i++)
{
if(foundlist[i] > fixedlist[i])
return (1);
else if(foundlist[i] < fixedlist[i])
return (-1);
}
/* Strings are equal. */
return (0);
}
<commit_msg>versionCompare(): actually do numerical comparisons<commit_after>#include "tasks-utils.h"
WARNINGS_DISABLE
#include <QDir>
#include <QRegExp>
#include <QString>
#include <QStringList>
WARNINGS_ENABLE
#include <TSettings.h>
#include "tasks-defs.h"
QString makeTarsnapCommand(QString cmd)
{
TSettings settings;
QString tarsnapDir = settings.value("tarsnap/path", "").toString();
if(tarsnapDir.isEmpty())
return cmd;
else
return tarsnapDir + QDir::separator() + cmd;
}
QStringList makeTarsnapArgs()
{
TSettings settings;
QStringList args;
/* Default arguments: --keyfile and --cachedir. */
QString tarsnapKeyFile = settings.value("tarsnap/key", "").toString();
if(!tarsnapKeyFile.isEmpty())
args << "--keyfile" << tarsnapKeyFile;
QString tarsnapCacheDir = settings.value("tarsnap/cache", "").toString();
if(!tarsnapCacheDir.isEmpty())
args << "--cachedir" << tarsnapCacheDir;
/* Network rate limits: --maxbw-rate-down and --maxbw-rate-up. */
int download_rate_kbps = settings.value("app/limit_download", 0).toInt();
if(download_rate_kbps)
{
args << "--maxbw-rate-down"
<< QString::number(1024 * quint64(download_rate_kbps));
}
int upload_rate_kbps = settings.value("app/limit_upload", 0).toInt();
if(upload_rate_kbps)
{
args << "--maxbw-rate-up"
<< QString::number(1024 * quint64(upload_rate_kbps));
}
/* Add --no-default-config. */
if(settings.value("tarsnap/no_default_config", DEFAULT_NO_DEFAULT_CONFIG)
.toBool())
args.prepend("--no-default-config");
return (args);
}
/*
* The QVersionNumber class was introduced in Qt 5.6, which is later than
* our target of Qt 5.2.1.
*/
int versionCompare(QString found, QString fixed)
{
int i;
/* Parse strings. */
QStringList foundlist = found.split(QRegExp("\\."));
QStringList fixedlist = fixed.split(QRegExp("\\."));
/* Sanity check. */
Q_ASSERT(fixedlist.size() == 3);
Q_ASSERT(foundlist.size() >= 3);
/* Append extra 0s to the "fixed" string. */
for(i = 0; i < foundlist.size() - fixedlist.size(); i++)
fixedlist.append("0");
/* Numerically compare each portion of the strings. */
for(i = 0; i < fixedlist.size(); i++)
{
if(foundlist[i].toInt() > fixedlist[i].toInt())
return (1);
else if(foundlist[i].toInt() < fixedlist[i].toInt())
return (-1);
}
/* Strings are equal. */
return (0);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For 64-bit file access (off_t = off64_t, lseek64, etc).
#define _FILE_OFFSET_BITS 64
#include "net/base/file_stream.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "base/worker_pool.h"
#include "net/base/net_errors.h"
// We cast back and forth, so make sure it's the size we're expecting.
COMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);
// Make sure our Whence mappings match the system headers.
COMPILE_ASSERT(net::FROM_BEGIN == SEEK_SET &&
net::FROM_CURRENT == SEEK_CUR &&
net::FROM_END == SEEK_END, whence_matches_system);
namespace net {
namespace {
// Map from errno to net error codes.
int64 MapErrorCode(int err) {
switch (err) {
case ENOENT:
return ERR_FILE_NOT_FOUND;
case EACCES:
return ERR_ACCESS_DENIED;
default:
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
// ReadFile() is a simple wrapper around read() that handles EINTR signals and
// calls MapErrorCode() to map errno to net error codes.
int ReadFile(base::PlatformFile file, char* buf, int buf_len) {
// read(..., 0) returns 0 to indicate end-of-file.
// Loop in the case of getting interrupted by a signal.
ssize_t res = HANDLE_EINTR(read(file, buf, static_cast<size_t>(buf_len)));
if (res == static_cast<ssize_t>(-1))
return MapErrorCode(errno);
return static_cast<int>(res);
}
// WriteFile() is a simple wrapper around write() that handles EINTR signals and
// calls MapErrorCode() to map errno to net error codes. It tries to write to
// completion.
int WriteFile(base::PlatformFile file, const char* buf, int buf_len) {
ssize_t res = HANDLE_EINTR(write(file, buf, buf_len));
if (res == -1)
return MapErrorCode(errno);
return res;
}
// BackgroundReadTask is a simple task that reads a file and then runs
// |callback|. AsyncContext will post this task to the WorkerPool.
class BackgroundReadTask : public Task {
public:
BackgroundReadTask(base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback);
~BackgroundReadTask();
virtual void Run();
private:
const base::PlatformFile file_;
char* const buf_;
const int buf_len_;
CompletionCallback* const callback_;
DISALLOW_COPY_AND_ASSIGN(BackgroundReadTask);
};
BackgroundReadTask::BackgroundReadTask(
base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback)
: file_(file), buf_(buf), buf_len_(buf_len), callback_(callback) {}
BackgroundReadTask::~BackgroundReadTask() {}
void BackgroundReadTask::Run() {
int result = ReadFile(file_, buf_, buf_len_);
callback_->Run(result);
}
// BackgroundWriteTask is a simple task that writes to a file and then runs
// |callback|. AsyncContext will post this task to the WorkerPool.
class BackgroundWriteTask : public Task {
public:
BackgroundWriteTask(base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback);
~BackgroundWriteTask();
virtual void Run();
private:
const base::PlatformFile file_;
const char* const buf_;
const int buf_len_;
CompletionCallback* const callback_;
DISALLOW_COPY_AND_ASSIGN(BackgroundWriteTask);
};
BackgroundWriteTask::BackgroundWriteTask(
base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback)
: file_(file), buf_(buf), buf_len_(buf_len), callback_(callback) {}
BackgroundWriteTask::~BackgroundWriteTask() {}
void BackgroundWriteTask::Run() {
int result = WriteFile(file_, buf_, buf_len_);
callback_->Run(result);
}
} // namespace
// CancelableCallbackTask takes ownership of the Callback. This task gets
// posted to the MessageLoopForIO instance.
class CancelableCallbackTask : public CancelableTask {
public:
explicit CancelableCallbackTask(Callback0::Type* callback)
: canceled_(false), callback_(callback) {}
virtual void Run() {
if (!canceled_)
callback_->Run();
}
virtual void Cancel() {
canceled_ = true;
}
private:
bool canceled_;
scoped_ptr<Callback0::Type> callback_;
};
// FileStream::AsyncContext ----------------------------------------------
class FileStream::AsyncContext {
public:
AsyncContext();
~AsyncContext();
// These methods post synchronous read() and write() calls to a WorkerThread.
void InitiateAsyncRead(
base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback);
void InitiateAsyncWrite(
base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback);
CompletionCallback* callback() const { return callback_; }
// Called by the WorkerPool thread executing the IO after the IO completes.
// This method queues RunAsynchronousCallback() on the MessageLoop and signals
// |background_io_completed_callback_|, in case the destructor is waiting. In
// that case, the destructor will call RunAsynchronousCallback() instead, and
// cancel |message_loop_task_|.
// |result| is the result of the Read/Write task.
void OnBackgroundIOCompleted(int result);
private:
// Always called on the IO thread, either directly by a task on the
// MessageLoop or by ~AsyncContext().
void RunAsynchronousCallback();
// The MessageLoopForIO that this AsyncContext is running on.
MessageLoopForIO* const message_loop_;
CompletionCallback* callback_; // The user provided callback.
// A callback wrapper around OnBackgroundIOCompleted(). Run by the WorkerPool
// thread doing the background IO on our behalf.
CompletionCallbackImpl<AsyncContext> background_io_completed_callback_;
// This is used to synchronize between the AsyncContext destructor (which runs
// on the IO thread and OnBackgroundIOCompleted() which runs on the WorkerPool
// thread.
base::WaitableEvent background_io_completed_;
// These variables are only valid when background_io_completed is signaled.
int result_;
CancelableCallbackTask* message_loop_task_;
bool is_closing_;
DISALLOW_COPY_AND_ASSIGN(AsyncContext);
};
FileStream::AsyncContext::AsyncContext()
: message_loop_(MessageLoopForIO::current()),
callback_(NULL),
background_io_completed_callback_(
this, &AsyncContext::OnBackgroundIOCompleted),
background_io_completed_(true, false),
message_loop_task_(NULL),
is_closing_(false) {}
FileStream::AsyncContext::~AsyncContext() {
is_closing_ = true;
if (callback_) {
// If |callback_| is non-NULL, that implies either the worker thread is
// still running the IO task, or the completion callback is queued up on the
// MessageLoopForIO, but AsyncContext() got deleted before then.
const bool need_to_wait = !background_io_completed_.IsSignaled();
base::TimeTicks start = base::TimeTicks::Now();
RunAsynchronousCallback();
if (need_to_wait) {
// We want to see if we block the message loop for too long.
UMA_HISTOGRAM_TIMES("AsyncIO.FileStreamClose",
base::TimeTicks::Now() - start);
}
}
}
void FileStream::AsyncContext::InitiateAsyncRead(
base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(!callback_);
callback_ = callback;
WorkerPool::PostTask(FROM_HERE,
new BackgroundReadTask(
file, buf, buf_len,
&background_io_completed_callback_),
true /* task_is_slow */);
}
void FileStream::AsyncContext::InitiateAsyncWrite(
base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(!callback_);
callback_ = callback;
WorkerPool::PostTask(FROM_HERE,
new BackgroundWriteTask(
file, buf, buf_len,
&background_io_completed_callback_),
true /* task_is_slow */);
}
void FileStream::AsyncContext::OnBackgroundIOCompleted(int result) {
result_ = result;
message_loop_task_ = new CancelableCallbackTask(
NewCallback(this, &AsyncContext::RunAsynchronousCallback));
message_loop_->PostTask(FROM_HERE, message_loop_task_);
background_io_completed_.Signal();
}
void FileStream::AsyncContext::RunAsynchronousCallback() {
// Wait() here ensures that all modifications from the WorkerPool thread are
// now visible.
background_io_completed_.Wait();
// Either we're in the MessageLoop's task, in which case Cancel() doesn't do
// anything, or we're in ~AsyncContext(), in which case this prevents the call
// from happening again. Must do it here after calling Wait().
message_loop_task_->Cancel();
message_loop_task_ = NULL;
if (is_closing_) {
callback_ = NULL;
return;
}
DCHECK(callback_);
CompletionCallback* temp = NULL;
std::swap(temp, callback_);
background_io_completed_.Reset();
temp->Run(result_);
}
// FileStream ------------------------------------------------------------
FileStream::FileStream()
: file_(base::kInvalidPlatformFileValue),
open_flags_(0),
auto_closed_(true) {
DCHECK(!IsOpen());
}
FileStream::FileStream(base::PlatformFile file, int flags)
: file_(file),
open_flags_(flags),
auto_closed_(false) {
// If the file handle is opened with base::PLATFORM_FILE_ASYNC, we need to
// make sure we will perform asynchronous File IO to it.
if (flags & base::PLATFORM_FILE_ASYNC) {
async_context_.reset(new AsyncContext());
}
}
FileStream::~FileStream() {
Close();
}
void FileStream::Close() {
// Abort any existing asynchronous operations.
async_context_.reset();
if (file_ != base::kInvalidPlatformFileValue) {
if (close(file_) != 0) {
NOTREACHED();
}
file_ = base::kInvalidPlatformFileValue;
}
}
int FileStream::Open(const FilePath& path, int open_flags) {
if (IsOpen()) {
DLOG(FATAL) << "File is already open!";
return ERR_UNEXPECTED;
}
open_flags_ = open_flags;
file_ = base::CreatePlatformFile(path, open_flags_, NULL);
if (file_ == base::kInvalidPlatformFileValue) {
LOG(WARNING) << "Failed to open file: " << errno
<< " (" << path.ToWStringHack() << ")";
return MapErrorCode(errno);
}
if (open_flags_ & base::PLATFORM_FILE_ASYNC) {
async_context_.reset(new AsyncContext());
}
return OK;
}
bool FileStream::IsOpen() const {
return file_ != base::kInvalidPlatformFileValue;
}
int64 FileStream::Seek(Whence whence, int64 offset) {
if (!IsOpen())
return ERR_UNEXPECTED;
// If we're in async, make sure we don't have a request in flight.
DCHECK(!async_context_.get() || !async_context_->callback());
off_t res = lseek(file_, static_cast<off_t>(offset),
static_cast<int>(whence));
if (res == static_cast<off_t>(-1))
return MapErrorCode(errno);
return res;
}
int64 FileStream::Available() {
if (!IsOpen())
return ERR_UNEXPECTED;
int64 cur_pos = Seek(FROM_CURRENT, 0);
if (cur_pos < 0)
return cur_pos;
struct stat info;
if (fstat(file_, &info) != 0)
return MapErrorCode(errno);
int64 size = static_cast<int64>(info.st_size);
DCHECK_GT(size, cur_pos);
return size - cur_pos;
}
int FileStream::Read(
char* buf, int buf_len, CompletionCallback* callback) {
if (!IsOpen())
return ERR_UNEXPECTED;
// read(..., 0) will return 0, which indicates end-of-file.
DCHECK(buf_len > 0);
DCHECK(open_flags_ & base::PLATFORM_FILE_READ);
if (async_context_.get()) {
DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
// If we're in async, make sure we don't have a request in flight.
DCHECK(!async_context_->callback());
async_context_->InitiateAsyncRead(file_, buf, buf_len, callback);
return ERR_IO_PENDING;
} else {
return ReadFile(file_, buf, buf_len);
}
}
int FileStream::ReadUntilComplete(char *buf, int buf_len) {
int to_read = buf_len;
int bytes_total = 0;
do {
int bytes_read = Read(buf, to_read, NULL);
if (bytes_read <= 0) {
if (bytes_total == 0)
return bytes_read;
return bytes_total;
}
bytes_total += bytes_read;
buf += bytes_read;
to_read -= bytes_read;
} while (bytes_total < buf_len);
return bytes_total;
}
int FileStream::Write(
const char* buf, int buf_len, CompletionCallback* callback) {
// write(..., 0) will return 0, which indicates end-of-file.
DCHECK(buf_len > 0);
if (!IsOpen())
return ERR_UNEXPECTED;
if (async_context_.get()) {
DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
// If we're in async, make sure we don't have a request in flight.
DCHECK(!async_context_->callback());
async_context_->InitiateAsyncWrite(file_, buf, buf_len, callback);
return ERR_IO_PENDING;
} else {
return WriteFile(file_, buf, buf_len);
}
}
int64 FileStream::Truncate(int64 bytes) {
if (!IsOpen())
return ERR_UNEXPECTED;
// We better be open for reading.
DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
// Seek to the position to truncate from.
int64 seek_position = Seek(FROM_BEGIN, bytes);
if (seek_position != bytes)
return ERR_UNEXPECTED;
// And truncate the file.
int result = ftruncate(file_, bytes);
return result == 0 ? seek_position : MapErrorCode(errno);
}
} // namespace net
<commit_msg>Fix ~FileStream in POSIX to auto close if the flag is set. This is left from my last patch.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For 64-bit file access (off_t = off64_t, lseek64, etc).
#define _FILE_OFFSET_BITS 64
#include "net/base/file_stream.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "base/worker_pool.h"
#include "net/base/net_errors.h"
// We cast back and forth, so make sure it's the size we're expecting.
COMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);
// Make sure our Whence mappings match the system headers.
COMPILE_ASSERT(net::FROM_BEGIN == SEEK_SET &&
net::FROM_CURRENT == SEEK_CUR &&
net::FROM_END == SEEK_END, whence_matches_system);
namespace net {
namespace {
// Map from errno to net error codes.
int64 MapErrorCode(int err) {
switch (err) {
case ENOENT:
return ERR_FILE_NOT_FOUND;
case EACCES:
return ERR_ACCESS_DENIED;
default:
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
// ReadFile() is a simple wrapper around read() that handles EINTR signals and
// calls MapErrorCode() to map errno to net error codes.
int ReadFile(base::PlatformFile file, char* buf, int buf_len) {
// read(..., 0) returns 0 to indicate end-of-file.
// Loop in the case of getting interrupted by a signal.
ssize_t res = HANDLE_EINTR(read(file, buf, static_cast<size_t>(buf_len)));
if (res == static_cast<ssize_t>(-1))
return MapErrorCode(errno);
return static_cast<int>(res);
}
// WriteFile() is a simple wrapper around write() that handles EINTR signals and
// calls MapErrorCode() to map errno to net error codes. It tries to write to
// completion.
int WriteFile(base::PlatformFile file, const char* buf, int buf_len) {
ssize_t res = HANDLE_EINTR(write(file, buf, buf_len));
if (res == -1)
return MapErrorCode(errno);
return res;
}
// BackgroundReadTask is a simple task that reads a file and then runs
// |callback|. AsyncContext will post this task to the WorkerPool.
class BackgroundReadTask : public Task {
public:
BackgroundReadTask(base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback);
~BackgroundReadTask();
virtual void Run();
private:
const base::PlatformFile file_;
char* const buf_;
const int buf_len_;
CompletionCallback* const callback_;
DISALLOW_COPY_AND_ASSIGN(BackgroundReadTask);
};
BackgroundReadTask::BackgroundReadTask(
base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback)
: file_(file), buf_(buf), buf_len_(buf_len), callback_(callback) {}
BackgroundReadTask::~BackgroundReadTask() {}
void BackgroundReadTask::Run() {
int result = ReadFile(file_, buf_, buf_len_);
callback_->Run(result);
}
// BackgroundWriteTask is a simple task that writes to a file and then runs
// |callback|. AsyncContext will post this task to the WorkerPool.
class BackgroundWriteTask : public Task {
public:
BackgroundWriteTask(base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback);
~BackgroundWriteTask();
virtual void Run();
private:
const base::PlatformFile file_;
const char* const buf_;
const int buf_len_;
CompletionCallback* const callback_;
DISALLOW_COPY_AND_ASSIGN(BackgroundWriteTask);
};
BackgroundWriteTask::BackgroundWriteTask(
base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback)
: file_(file), buf_(buf), buf_len_(buf_len), callback_(callback) {}
BackgroundWriteTask::~BackgroundWriteTask() {}
void BackgroundWriteTask::Run() {
int result = WriteFile(file_, buf_, buf_len_);
callback_->Run(result);
}
} // namespace
// CancelableCallbackTask takes ownership of the Callback. This task gets
// posted to the MessageLoopForIO instance.
class CancelableCallbackTask : public CancelableTask {
public:
explicit CancelableCallbackTask(Callback0::Type* callback)
: canceled_(false), callback_(callback) {}
virtual void Run() {
if (!canceled_)
callback_->Run();
}
virtual void Cancel() {
canceled_ = true;
}
private:
bool canceled_;
scoped_ptr<Callback0::Type> callback_;
};
// FileStream::AsyncContext ----------------------------------------------
class FileStream::AsyncContext {
public:
AsyncContext();
~AsyncContext();
// These methods post synchronous read() and write() calls to a WorkerThread.
void InitiateAsyncRead(
base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback);
void InitiateAsyncWrite(
base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback);
CompletionCallback* callback() const { return callback_; }
// Called by the WorkerPool thread executing the IO after the IO completes.
// This method queues RunAsynchronousCallback() on the MessageLoop and signals
// |background_io_completed_callback_|, in case the destructor is waiting. In
// that case, the destructor will call RunAsynchronousCallback() instead, and
// cancel |message_loop_task_|.
// |result| is the result of the Read/Write task.
void OnBackgroundIOCompleted(int result);
private:
// Always called on the IO thread, either directly by a task on the
// MessageLoop or by ~AsyncContext().
void RunAsynchronousCallback();
// The MessageLoopForIO that this AsyncContext is running on.
MessageLoopForIO* const message_loop_;
CompletionCallback* callback_; // The user provided callback.
// A callback wrapper around OnBackgroundIOCompleted(). Run by the WorkerPool
// thread doing the background IO on our behalf.
CompletionCallbackImpl<AsyncContext> background_io_completed_callback_;
// This is used to synchronize between the AsyncContext destructor (which runs
// on the IO thread and OnBackgroundIOCompleted() which runs on the WorkerPool
// thread.
base::WaitableEvent background_io_completed_;
// These variables are only valid when background_io_completed is signaled.
int result_;
CancelableCallbackTask* message_loop_task_;
bool is_closing_;
DISALLOW_COPY_AND_ASSIGN(AsyncContext);
};
FileStream::AsyncContext::AsyncContext()
: message_loop_(MessageLoopForIO::current()),
callback_(NULL),
background_io_completed_callback_(
this, &AsyncContext::OnBackgroundIOCompleted),
background_io_completed_(true, false),
message_loop_task_(NULL),
is_closing_(false) {}
FileStream::AsyncContext::~AsyncContext() {
is_closing_ = true;
if (callback_) {
// If |callback_| is non-NULL, that implies either the worker thread is
// still running the IO task, or the completion callback is queued up on the
// MessageLoopForIO, but AsyncContext() got deleted before then.
const bool need_to_wait = !background_io_completed_.IsSignaled();
base::TimeTicks start = base::TimeTicks::Now();
RunAsynchronousCallback();
if (need_to_wait) {
// We want to see if we block the message loop for too long.
UMA_HISTOGRAM_TIMES("AsyncIO.FileStreamClose",
base::TimeTicks::Now() - start);
}
}
}
void FileStream::AsyncContext::InitiateAsyncRead(
base::PlatformFile file, char* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(!callback_);
callback_ = callback;
WorkerPool::PostTask(FROM_HERE,
new BackgroundReadTask(
file, buf, buf_len,
&background_io_completed_callback_),
true /* task_is_slow */);
}
void FileStream::AsyncContext::InitiateAsyncWrite(
base::PlatformFile file, const char* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(!callback_);
callback_ = callback;
WorkerPool::PostTask(FROM_HERE,
new BackgroundWriteTask(
file, buf, buf_len,
&background_io_completed_callback_),
true /* task_is_slow */);
}
void FileStream::AsyncContext::OnBackgroundIOCompleted(int result) {
result_ = result;
message_loop_task_ = new CancelableCallbackTask(
NewCallback(this, &AsyncContext::RunAsynchronousCallback));
message_loop_->PostTask(FROM_HERE, message_loop_task_);
background_io_completed_.Signal();
}
void FileStream::AsyncContext::RunAsynchronousCallback() {
// Wait() here ensures that all modifications from the WorkerPool thread are
// now visible.
background_io_completed_.Wait();
// Either we're in the MessageLoop's task, in which case Cancel() doesn't do
// anything, or we're in ~AsyncContext(), in which case this prevents the call
// from happening again. Must do it here after calling Wait().
message_loop_task_->Cancel();
message_loop_task_ = NULL;
if (is_closing_) {
callback_ = NULL;
return;
}
DCHECK(callback_);
CompletionCallback* temp = NULL;
std::swap(temp, callback_);
background_io_completed_.Reset();
temp->Run(result_);
}
// FileStream ------------------------------------------------------------
FileStream::FileStream()
: file_(base::kInvalidPlatformFileValue),
open_flags_(0),
auto_closed_(true) {
DCHECK(!IsOpen());
}
FileStream::FileStream(base::PlatformFile file, int flags)
: file_(file),
open_flags_(flags),
auto_closed_(false) {
// If the file handle is opened with base::PLATFORM_FILE_ASYNC, we need to
// make sure we will perform asynchronous File IO to it.
if (flags & base::PLATFORM_FILE_ASYNC) {
async_context_.reset(new AsyncContext());
}
}
FileStream::~FileStream() {
if (auto_closed_)
Close();
}
void FileStream::Close() {
// Abort any existing asynchronous operations.
async_context_.reset();
if (file_ != base::kInvalidPlatformFileValue) {
if (close(file_) != 0) {
NOTREACHED();
}
file_ = base::kInvalidPlatformFileValue;
}
}
int FileStream::Open(const FilePath& path, int open_flags) {
if (IsOpen()) {
DLOG(FATAL) << "File is already open!";
return ERR_UNEXPECTED;
}
open_flags_ = open_flags;
file_ = base::CreatePlatformFile(path, open_flags_, NULL);
if (file_ == base::kInvalidPlatformFileValue) {
LOG(WARNING) << "Failed to open file: " << errno
<< " (" << path.ToWStringHack() << ")";
return MapErrorCode(errno);
}
if (open_flags_ & base::PLATFORM_FILE_ASYNC) {
async_context_.reset(new AsyncContext());
}
return OK;
}
bool FileStream::IsOpen() const {
return file_ != base::kInvalidPlatformFileValue;
}
int64 FileStream::Seek(Whence whence, int64 offset) {
if (!IsOpen())
return ERR_UNEXPECTED;
// If we're in async, make sure we don't have a request in flight.
DCHECK(!async_context_.get() || !async_context_->callback());
off_t res = lseek(file_, static_cast<off_t>(offset),
static_cast<int>(whence));
if (res == static_cast<off_t>(-1))
return MapErrorCode(errno);
return res;
}
int64 FileStream::Available() {
if (!IsOpen())
return ERR_UNEXPECTED;
int64 cur_pos = Seek(FROM_CURRENT, 0);
if (cur_pos < 0)
return cur_pos;
struct stat info;
if (fstat(file_, &info) != 0)
return MapErrorCode(errno);
int64 size = static_cast<int64>(info.st_size);
DCHECK_GT(size, cur_pos);
return size - cur_pos;
}
int FileStream::Read(
char* buf, int buf_len, CompletionCallback* callback) {
if (!IsOpen())
return ERR_UNEXPECTED;
// read(..., 0) will return 0, which indicates end-of-file.
DCHECK(buf_len > 0);
DCHECK(open_flags_ & base::PLATFORM_FILE_READ);
if (async_context_.get()) {
DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
// If we're in async, make sure we don't have a request in flight.
DCHECK(!async_context_->callback());
async_context_->InitiateAsyncRead(file_, buf, buf_len, callback);
return ERR_IO_PENDING;
} else {
return ReadFile(file_, buf, buf_len);
}
}
int FileStream::ReadUntilComplete(char *buf, int buf_len) {
int to_read = buf_len;
int bytes_total = 0;
do {
int bytes_read = Read(buf, to_read, NULL);
if (bytes_read <= 0) {
if (bytes_total == 0)
return bytes_read;
return bytes_total;
}
bytes_total += bytes_read;
buf += bytes_read;
to_read -= bytes_read;
} while (bytes_total < buf_len);
return bytes_total;
}
int FileStream::Write(
const char* buf, int buf_len, CompletionCallback* callback) {
// write(..., 0) will return 0, which indicates end-of-file.
DCHECK(buf_len > 0);
if (!IsOpen())
return ERR_UNEXPECTED;
if (async_context_.get()) {
DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
// If we're in async, make sure we don't have a request in flight.
DCHECK(!async_context_->callback());
async_context_->InitiateAsyncWrite(file_, buf, buf_len, callback);
return ERR_IO_PENDING;
} else {
return WriteFile(file_, buf, buf_len);
}
}
int64 FileStream::Truncate(int64 bytes) {
if (!IsOpen())
return ERR_UNEXPECTED;
// We better be open for reading.
DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
// Seek to the position to truncate from.
int64 seek_position = Seek(FROM_BEGIN, bytes);
if (seek_position != bytes)
return ERR_UNEXPECTED;
// And truncate the file.
int result = ftruncate(file_, bytes);
return result == 0 ? seek_position : MapErrorCode(errno);
}
} // namespace net
<|endoftext|> |
<commit_before>#include "googletest/googletest/include/gtest/gtest.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "base58.h"
#include "util.h"
using namespace json_spirit;
extern Array read_json(const std::string& filename);
// Goal: test low-level base58 encoding functionality
TEST(base58_tests, base58_EncodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::vector<unsigned char> sourcedata = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
EXPECT_TRUE(EncodeBase58(&sourcedata[0], &sourcedata[sourcedata.size()]) == base58string) << strTest;
}
}
// Goal: test low-level base58 decoding functionality
TEST(base58_tests, base58_DecodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
std::vector<unsigned char> result;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::vector<unsigned char> expected = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
EXPECT_TRUE(DecodeBase58(base58string, result)) << strTest;
EXPECT_TRUE(result.size() == expected.size() && std::equal(result.begin(), result.end(), expected.begin())) << strTest;
}
EXPECT_TRUE(!DecodeBase58("invalid", result));
}
// Visitor to check address type
class TestAddrTypeVisitor : public boost::static_visitor<bool>
{
private:
std::string exp_addrType;
public:
TestAddrTypeVisitor(const std::string &exp_addrType) : exp_addrType(exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
}
bool operator()(const CScriptID &id) const
{
return (exp_addrType == "script");
}
bool operator()(const CNoDestination &no) const
{
return (exp_addrType == "none");
}
};
// Visitor to check address payload
class TestPayloadVisitor : public boost::static_visitor<bool>
{
private:
std::vector<unsigned char> exp_payload;
public:
TestPayloadVisitor(std::vector<unsigned char> &exp_payload) : exp_payload(exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CScriptID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CNoDestination &no) const
{
return exp_payload.size() == 0;
}
};
// Goal: check that parsed keys match test payload
TEST(base58_tests, base58_keys_valid_parse)
{
Array tests = read_json("base58_keys_valid.json");
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
// Save global state
bool fTestNet_stored = fTestNet;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> privkey_bin_from_hex = ParseHex(test[1].get_str());
const Object &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
fTestNet = isTestnet; // Override testnet flag
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
// Must be valid private key
EXPECT_TRUE(secret.SetString(exp_base58string)) << "!SetString:"+ strTest;
EXPECT_TRUE(secret.IsValid()) << "!IsValid:" + strTest;
bool fCompressedOut = false;
CSecret privkey = secret.GetSecret(fCompressedOut);
EXPECT_TRUE(fCompressedOut == isCompressed) << "compressed mismatch:" + strTest;
EXPECT_TRUE(privkey.size() == privkey_bin_from_hex.size() && std::equal(privkey.begin(), privkey.end(), privkey_bin_from_hex.begin())) << "key mismatch:" + strTest;
// Private key must be invalid public key
addr.SetString(exp_base58string);
EXPECT_TRUE(!addr.IsValid()) << "IsValid privkey as pubkey:" + strTest;
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str(); // "script" or "pubkey"
// Must be valid public key
EXPECT_TRUE(addr.SetString(exp_base58string)) << "SetString:" + strTest;
EXPECT_TRUE(addr.IsValid()) << "!IsValid:" + strTest;
EXPECT_TRUE(addr.IsScript() == (exp_addrType == "script")) << "isScript mismatch" + strTest;
CTxDestination dest = addr.Get();
EXPECT_TRUE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest)) << "addrType mismatch" + strTest;
// Public key must be invalid private key
secret.SetString(exp_base58string);
EXPECT_TRUE(!secret.IsValid()) << "IsValid pubkey as privkey:" + strTest;
}
}
// Restore global state
fTestNet = fTestNet_stored;
}
// Goal: check that base58 parsing code is robust against a variety of corrupted data
TEST(base58_tests, base58_keys_invalid)
{
Array tests = read_json("base58_keys_invalid.json"); // Negative testcases
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::string exp_base58string = test[0].get_str();
// must be invalid as public and as private key
addr.SetString(exp_base58string);
EXPECT_TRUE(!addr.IsValid()) << "IsValid pubkey:" + strTest;
secret.SetString(exp_base58string);
EXPECT_TRUE(!secret.IsValid()) << "IsValid privkey:" + strTest;
}
}
<commit_msg>Added TODO<commit_after>#include "googletest/googletest/include/gtest/gtest.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "base58.h"
#include "util.h"
using namespace json_spirit;
extern Array read_json(const std::string& filename);
// Goal: test low-level base58 encoding functionality
TEST(base58_tests, base58_EncodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::vector<unsigned char> sourcedata = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
EXPECT_TRUE(EncodeBase58(&sourcedata[0], &sourcedata[sourcedata.size()]) == base58string) << strTest;
}
}
// Goal: test low-level base58 decoding functionality
TEST(base58_tests, base58_DecodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
std::vector<unsigned char> result;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::vector<unsigned char> expected = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
EXPECT_TRUE(DecodeBase58(base58string, result)) << strTest;
EXPECT_TRUE(result.size() == expected.size() && std::equal(result.begin(), result.end(), expected.begin())) << strTest;
}
EXPECT_TRUE(!DecodeBase58("invalid", result));
}
// Visitor to check address type
class TestAddrTypeVisitor : public boost::static_visitor<bool>
{
private:
std::string exp_addrType;
public:
TestAddrTypeVisitor(const std::string &exp_addrType) : exp_addrType(exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
}
bool operator()(const CScriptID &id) const
{
return (exp_addrType == "script");
}
bool operator()(const CNoDestination &no) const
{
return (exp_addrType == "none");
}
};
// Visitor to check address payload
class TestPayloadVisitor : public boost::static_visitor<bool>
{
private:
std::vector<unsigned char> exp_payload;
public:
TestPayloadVisitor(std::vector<unsigned char> &exp_payload) : exp_payload(exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CScriptID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CNoDestination &no) const
{
return exp_payload.size() == 0;
}
};
// Goal: check that parsed keys match test payload
TEST(base58_tests, base58_keys_valid_parse)
{
Array tests = read_json("base58_keys_valid.json");
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
// Save global state
bool fTestNet_stored = fTestNet;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> privkey_bin_from_hex = ParseHex(test[1].get_str());
const Object &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
fTestNet = isTestnet; // Override testnet flag
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
// Must be valid private key
EXPECT_TRUE(secret.SetString(exp_base58string)) << "!SetString:"+ strTest;
EXPECT_TRUE(secret.IsValid()) << "!IsValid:" + strTest;
bool fCompressedOut = false;
CSecret privkey = secret.GetSecret(fCompressedOut);
EXPECT_TRUE(fCompressedOut == isCompressed) << "compressed mismatch:" + strTest;
EXPECT_TRUE(privkey.size() == privkey_bin_from_hex.size() && std::equal(privkey.begin(), privkey.end(), privkey_bin_from_hex.begin())) << "key mismatch:" + strTest;
// Private key must be invalid public key
addr.SetString(exp_base58string);
EXPECT_TRUE(!addr.IsValid()) << "IsValid privkey as pubkey:" + strTest;
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str(); // "script" or "pubkey"
// Must be valid public key
EXPECT_TRUE(addr.SetString(exp_base58string)) << "SetString:" + strTest;
EXPECT_TRUE(addr.IsValid()) << "!IsValid:" + strTest;
EXPECT_TRUE(addr.IsScript() == (exp_addrType == "script")) << "isScript mismatch" + strTest;
CTxDestination dest = addr.Get();
EXPECT_TRUE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest)) << "addrType mismatch" + strTest;
// Public key must be invalid private key
secret.SetString(exp_base58string);
EXPECT_TRUE(!secret.IsValid()) << "IsValid pubkey as privkey:" + strTest;
}
}
// Restore global state
fTestNet = fTestNet_stored;
}
// Goal: check that base58 parsing code is robust against a variety of corrupted data
TEST(base58_tests, base58_keys_invalid)
{
Array tests = read_json("base58_keys_invalid.json"); // Negative testcases
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
ADD_FAILURE() << "Bad test: " << strTest;
continue;
}
std::string exp_base58string = test[0].get_str();
// must be invalid as public and as private key
addr.SetString(exp_base58string);
EXPECT_TRUE(!addr.IsValid()) << "IsValid pubkey:" + strTest;
secret.SetString(exp_base58string);
EXPECT_TRUE(!secret.IsValid()) << "IsValid privkey:" + strTest;
}
}
// TODO: Create tests that take private keys, and generate public keys and addresses
<|endoftext|> |
<commit_before>// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/validation.h>
#include <miner.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/util/mining.h>
#include <test/util/script.h>
#include <test/util/setup_common.h>
#include <util/rbf.h>
#include <validation.h>
#include <validationinterface.h>
namespace {
const TestingSetup* g_setup;
std::vector<COutPoint> g_outpoints_coinbase_init_mature;
std::vector<COutPoint> g_outpoints_coinbase_init_immature;
struct MockedTxPool : public CTxMemPool {
void RollingFeeUpdate()
{
lastRollingFeeUpdate = GetTime();
blockSinceLastRollingFeeBump = true;
}
};
void initialize_tx_pool()
{
static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
g_setup = testing_setup.get();
for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
CTxIn in = MineBlock(g_setup->m_node, P2WSH_OP_TRUE);
// Remember the txids to avoid expensive disk access later on
auto& outpoints = i < COINBASE_MATURITY ?
g_outpoints_coinbase_init_mature :
g_outpoints_coinbase_init_immature;
outpoints.push_back(in.prevout);
}
SyncWithValidationInterfaceQueue();
}
struct TransactionsDelta final : public CValidationInterface {
std::set<CTransactionRef>& m_removed;
std::set<CTransactionRef>& m_added;
explicit TransactionsDelta(std::set<CTransactionRef>& r, std::set<CTransactionRef>& a)
: m_removed{r}, m_added{a} {}
void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override
{
Assert(m_added.insert(tx).second);
}
void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
{
Assert(m_removed.insert(tx).second);
}
};
void SetMempoolConstraints(ArgsManager& args, FuzzedDataProvider& fuzzed_data_provider)
{
args.ForceSetArg("-limitancestorcount",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50)));
args.ForceSetArg("-limitancestorsize",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202)));
args.ForceSetArg("-limitdescendantcount",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50)));
args.ForceSetArg("-limitdescendantsize",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202)));
args.ForceSetArg("-maxmempool",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200)));
args.ForceSetArg("-mempoolexpiry",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)));
}
void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, CChainState& chainstate)
{
WITH_LOCK(::cs_main, tx_pool.check(chainstate));
{
BlockAssembler::Options options;
options.nBlockMaxWeight = fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BLOCK_WEIGHT);
options.blockMinFeeRate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /* max */ COIN)};
auto assembler = BlockAssembler{chainstate, *static_cast<CTxMemPool*>(&tx_pool), ::Params(), options};
auto block_template = assembler.CreateNewBlock(CScript{} << OP_TRUE);
Assert(block_template->block.vtx.size() >= 1);
}
const auto info_all = tx_pool.infoAll();
if (!info_all.empty()) {
const auto& tx_to_remove = *PickValue(fuzzed_data_provider, info_all).tx;
WITH_LOCK(tx_pool.cs, tx_pool.removeRecursive(tx_to_remove, /* dummy */ MemPoolRemovalReason::BLOCK));
std::vector<uint256> all_txids;
tx_pool.queryHashes(all_txids);
assert(all_txids.size() < info_all.size());
WITH_LOCK(::cs_main, tx_pool.check(chainstate));
}
SyncWithValidationInterfaceQueue();
}
void MockTime(FuzzedDataProvider& fuzzed_data_provider, const CChainState& chainstate)
{
const auto time = ConsumeTime(fuzzed_data_provider,
chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
SetMockTime(time);
}
FUZZ_TARGET_INIT(tx_pool_standard, initialize_tx_pool)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node;
auto& chainstate = node.chainman->ActiveChainstate();
MockTime(fuzzed_data_provider, chainstate);
SetMempoolConstraints(*node.args, fuzzed_data_provider);
// All RBF-spendable outpoints
std::set<COutPoint> outpoints_rbf;
// All outpoints counting toward the total supply (subset of outpoints_rbf)
std::set<COutPoint> outpoints_supply;
for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
Assert(outpoints_supply.insert(outpoint).second);
}
outpoints_rbf = outpoints_supply;
// The sum of the values of all spendable outpoints
constexpr CAmount SUPPLY_TOTAL{COINBASE_MATURITY * 50 * COIN};
CTxMemPool tx_pool_{/* estimator */ nullptr, /* check_ratio */ 1};
MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
// Helper to query an amount
const CCoinsViewMemPool amount_view{WITH_LOCK(::cs_main, return &chainstate.CoinsTip()), tx_pool};
const auto GetAmount = [&](const COutPoint& outpoint) {
Coin c;
Assert(amount_view.GetCoin(outpoint, c));
return c.out.nValue;
};
while (fuzzed_data_provider.ConsumeBool()) {
{
// Total supply is the mempool fee + all outpoints
CAmount supply_now{WITH_LOCK(tx_pool.cs, return tx_pool.GetTotalFee())};
for (const auto& op : outpoints_supply) {
supply_now += GetAmount(op);
}
Assert(supply_now == SUPPLY_TOTAL);
}
Assert(!outpoints_supply.empty());
// Create transaction to add to the mempool
const CTransactionRef tx = [&] {
CMutableTransaction tx_mut;
tx_mut.nVersion = CTransaction::CURRENT_VERSION;
tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size());
const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size() * 2);
CAmount amount_in{0};
for (int i = 0; i < num_in; ++i) {
// Pop random outpoint
auto pop = outpoints_rbf.begin();
std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints_rbf.size() - 1));
const auto outpoint = *pop;
outpoints_rbf.erase(pop);
amount_in += GetAmount(outpoint);
// Create input
const auto sequence = ConsumeSequence(fuzzed_data_provider);
const auto script_sig = CScript{};
const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
CTxIn in;
in.prevout = outpoint;
in.nSequence = sequence;
in.scriptSig = script_sig;
in.scriptWitness.stack = script_wit_stack;
tx_mut.vin.push_back(in);
}
const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1000, amount_in);
const auto amount_out = (amount_in - amount_fee) / num_out;
for (int i = 0; i < num_out; ++i) {
tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE);
}
const auto tx = MakeTransactionRef(tx_mut);
// Restore previously removed outpoints
for (const auto& in : tx->vin) {
Assert(outpoints_rbf.insert(in.prevout).second);
}
return tx;
}();
if (fuzzed_data_provider.ConsumeBool()) {
MockTime(fuzzed_data_provider, chainstate);
}
if (fuzzed_data_provider.ConsumeBool()) {
SetMempoolConstraints(*node.args, fuzzed_data_provider);
}
if (fuzzed_data_provider.ConsumeBool()) {
tx_pool.RollingFeeUpdate();
}
if (fuzzed_data_provider.ConsumeBool()) {
const auto& txid = fuzzed_data_provider.ConsumeBool() ?
tx->GetHash() :
PickValue(fuzzed_data_provider, outpoints_rbf).hash;
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid, delta);
}
// Remember all removed and added transactions
std::set<CTransactionRef> removed;
std::set<CTransactionRef> added;
auto txr = std::make_shared<TransactionsDelta>(removed, added);
RegisterSharedValidationInterface(txr);
const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
::fRequireStandard = fuzzed_data_provider.ConsumeBool();
const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx_pool, tx, bypass_limits));
const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
SyncWithValidationInterfaceQueue();
UnregisterSharedValidationInterface(txr);
Assert(accepted != added.empty());
Assert(accepted == res.m_state.IsValid());
Assert(accepted != res.m_state.IsInvalid());
if (accepted) {
Assert(added.size() == 1); // For now, no package acceptance
Assert(tx == *added.begin());
} else {
// Do not consider rejected transaction removed
removed.erase(tx);
}
// Helper to insert spent and created outpoints of a tx into collections
using Sets = std::vector<std::reference_wrapper<std::set<COutPoint>>>;
const auto insert_tx = [](Sets created_by_tx, Sets consumed_by_tx, const auto& tx) {
for (size_t i{0}; i < tx.vout.size(); ++i) {
for (auto& set : created_by_tx) {
Assert(set.get().emplace(tx.GetHash(), i).second);
}
}
for (const auto& in : tx.vin) {
for (auto& set : consumed_by_tx) {
Assert(set.get().insert(in.prevout).second);
}
}
};
// Add created outpoints, remove spent outpoints
{
// Outpoints that no longer exist at all
std::set<COutPoint> consumed_erased;
// Outpoints that no longer count toward the total supply
std::set<COutPoint> consumed_supply;
for (const auto& removed_tx : removed) {
insert_tx(/* created_by_tx */ {consumed_erased}, /* consumed_by_tx */ {outpoints_supply}, /* tx */ *removed_tx);
}
for (const auto& added_tx : added) {
insert_tx(/* created_by_tx */ {outpoints_supply, outpoints_rbf}, /* consumed_by_tx */ {consumed_supply}, /* tx */ *added_tx);
}
for (const auto& p : consumed_erased) {
Assert(outpoints_supply.erase(p) == 1);
Assert(outpoints_rbf.erase(p) == 1);
}
for (const auto& p : consumed_supply) {
Assert(outpoints_supply.erase(p) == 1);
}
}
}
Finish(fuzzed_data_provider, tx_pool, chainstate);
}
FUZZ_TARGET_INIT(tx_pool, initialize_tx_pool)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node;
auto& chainstate = node.chainman->ActiveChainstate();
MockTime(fuzzed_data_provider, chainstate);
SetMempoolConstraints(*node.args, fuzzed_data_provider);
std::vector<uint256> txids;
for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
txids.push_back(outpoint.hash);
}
for (int i{0}; i <= 3; ++i) {
// Add some immature and non-existent outpoints
txids.push_back(g_outpoints_coinbase_init_immature.at(i).hash);
txids.push_back(ConsumeUInt256(fuzzed_data_provider));
}
CTxMemPool tx_pool_{/* estimator */ nullptr, /* check_ratio */ 1};
MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
while (fuzzed_data_provider.ConsumeBool()) {
const auto mut_tx = ConsumeTransaction(fuzzed_data_provider, txids);
if (fuzzed_data_provider.ConsumeBool()) {
MockTime(fuzzed_data_provider, chainstate);
}
if (fuzzed_data_provider.ConsumeBool()) {
SetMempoolConstraints(*node.args, fuzzed_data_provider);
}
if (fuzzed_data_provider.ConsumeBool()) {
tx_pool.RollingFeeUpdate();
}
if (fuzzed_data_provider.ConsumeBool()) {
const auto& txid = fuzzed_data_provider.ConsumeBool() ?
mut_tx.GetHash() :
PickValue(fuzzed_data_provider, txids);
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid, delta);
}
const auto tx = MakeTransactionRef(mut_tx);
const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
::fRequireStandard = fuzzed_data_provider.ConsumeBool();
const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(node.chainman->ActiveChainstate(), tx_pool, tx, bypass_limits));
const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
if (accepted) {
txids.push_back(tx->GetHash());
}
}
Finish(fuzzed_data_provider, tx_pool, chainstate);
}
} // namespace
<commit_msg>[fuzz] add ProcessNewPackage call in tx_pool fuzzer<commit_after>// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/validation.h>
#include <miner.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/util/mining.h>
#include <test/util/script.h>
#include <test/util/setup_common.h>
#include <util/rbf.h>
#include <validation.h>
#include <validationinterface.h>
namespace {
const TestingSetup* g_setup;
std::vector<COutPoint> g_outpoints_coinbase_init_mature;
std::vector<COutPoint> g_outpoints_coinbase_init_immature;
struct MockedTxPool : public CTxMemPool {
void RollingFeeUpdate()
{
lastRollingFeeUpdate = GetTime();
blockSinceLastRollingFeeBump = true;
}
};
void initialize_tx_pool()
{
static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
g_setup = testing_setup.get();
for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
CTxIn in = MineBlock(g_setup->m_node, P2WSH_OP_TRUE);
// Remember the txids to avoid expensive disk access later on
auto& outpoints = i < COINBASE_MATURITY ?
g_outpoints_coinbase_init_mature :
g_outpoints_coinbase_init_immature;
outpoints.push_back(in.prevout);
}
SyncWithValidationInterfaceQueue();
}
struct TransactionsDelta final : public CValidationInterface {
std::set<CTransactionRef>& m_removed;
std::set<CTransactionRef>& m_added;
explicit TransactionsDelta(std::set<CTransactionRef>& r, std::set<CTransactionRef>& a)
: m_removed{r}, m_added{a} {}
void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override
{
Assert(m_added.insert(tx).second);
}
void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
{
Assert(m_removed.insert(tx).second);
}
};
void SetMempoolConstraints(ArgsManager& args, FuzzedDataProvider& fuzzed_data_provider)
{
args.ForceSetArg("-limitancestorcount",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50)));
args.ForceSetArg("-limitancestorsize",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202)));
args.ForceSetArg("-limitdescendantcount",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50)));
args.ForceSetArg("-limitdescendantsize",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202)));
args.ForceSetArg("-maxmempool",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200)));
args.ForceSetArg("-mempoolexpiry",
ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)));
}
void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, CChainState& chainstate)
{
WITH_LOCK(::cs_main, tx_pool.check(chainstate));
{
BlockAssembler::Options options;
options.nBlockMaxWeight = fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BLOCK_WEIGHT);
options.blockMinFeeRate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /* max */ COIN)};
auto assembler = BlockAssembler{chainstate, *static_cast<CTxMemPool*>(&tx_pool), ::Params(), options};
auto block_template = assembler.CreateNewBlock(CScript{} << OP_TRUE);
Assert(block_template->block.vtx.size() >= 1);
}
const auto info_all = tx_pool.infoAll();
if (!info_all.empty()) {
const auto& tx_to_remove = *PickValue(fuzzed_data_provider, info_all).tx;
WITH_LOCK(tx_pool.cs, tx_pool.removeRecursive(tx_to_remove, /* dummy */ MemPoolRemovalReason::BLOCK));
std::vector<uint256> all_txids;
tx_pool.queryHashes(all_txids);
assert(all_txids.size() < info_all.size());
WITH_LOCK(::cs_main, tx_pool.check(chainstate));
}
SyncWithValidationInterfaceQueue();
}
void MockTime(FuzzedDataProvider& fuzzed_data_provider, const CChainState& chainstate)
{
const auto time = ConsumeTime(fuzzed_data_provider,
chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
SetMockTime(time);
}
FUZZ_TARGET_INIT(tx_pool_standard, initialize_tx_pool)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node;
auto& chainstate = node.chainman->ActiveChainstate();
MockTime(fuzzed_data_provider, chainstate);
SetMempoolConstraints(*node.args, fuzzed_data_provider);
// All RBF-spendable outpoints
std::set<COutPoint> outpoints_rbf;
// All outpoints counting toward the total supply (subset of outpoints_rbf)
std::set<COutPoint> outpoints_supply;
for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
Assert(outpoints_supply.insert(outpoint).second);
}
outpoints_rbf = outpoints_supply;
// The sum of the values of all spendable outpoints
constexpr CAmount SUPPLY_TOTAL{COINBASE_MATURITY * 50 * COIN};
CTxMemPool tx_pool_{/* estimator */ nullptr, /* check_ratio */ 1};
MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
// Helper to query an amount
const CCoinsViewMemPool amount_view{WITH_LOCK(::cs_main, return &chainstate.CoinsTip()), tx_pool};
const auto GetAmount = [&](const COutPoint& outpoint) {
Coin c;
Assert(amount_view.GetCoin(outpoint, c));
return c.out.nValue;
};
while (fuzzed_data_provider.ConsumeBool()) {
{
// Total supply is the mempool fee + all outpoints
CAmount supply_now{WITH_LOCK(tx_pool.cs, return tx_pool.GetTotalFee())};
for (const auto& op : outpoints_supply) {
supply_now += GetAmount(op);
}
Assert(supply_now == SUPPLY_TOTAL);
}
Assert(!outpoints_supply.empty());
// Create transaction to add to the mempool
const CTransactionRef tx = [&] {
CMutableTransaction tx_mut;
tx_mut.nVersion = CTransaction::CURRENT_VERSION;
tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size());
const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size() * 2);
CAmount amount_in{0};
for (int i = 0; i < num_in; ++i) {
// Pop random outpoint
auto pop = outpoints_rbf.begin();
std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints_rbf.size() - 1));
const auto outpoint = *pop;
outpoints_rbf.erase(pop);
amount_in += GetAmount(outpoint);
// Create input
const auto sequence = ConsumeSequence(fuzzed_data_provider);
const auto script_sig = CScript{};
const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
CTxIn in;
in.prevout = outpoint;
in.nSequence = sequence;
in.scriptSig = script_sig;
in.scriptWitness.stack = script_wit_stack;
tx_mut.vin.push_back(in);
}
const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1000, amount_in);
const auto amount_out = (amount_in - amount_fee) / num_out;
for (int i = 0; i < num_out; ++i) {
tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE);
}
const auto tx = MakeTransactionRef(tx_mut);
// Restore previously removed outpoints
for (const auto& in : tx->vin) {
Assert(outpoints_rbf.insert(in.prevout).second);
}
return tx;
}();
if (fuzzed_data_provider.ConsumeBool()) {
MockTime(fuzzed_data_provider, chainstate);
}
if (fuzzed_data_provider.ConsumeBool()) {
SetMempoolConstraints(*node.args, fuzzed_data_provider);
}
if (fuzzed_data_provider.ConsumeBool()) {
tx_pool.RollingFeeUpdate();
}
if (fuzzed_data_provider.ConsumeBool()) {
const auto& txid = fuzzed_data_provider.ConsumeBool() ?
tx->GetHash() :
PickValue(fuzzed_data_provider, outpoints_rbf).hash;
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid, delta);
}
// Remember all removed and added transactions
std::set<CTransactionRef> removed;
std::set<CTransactionRef> added;
auto txr = std::make_shared<TransactionsDelta>(removed, added);
RegisterSharedValidationInterface(txr);
const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
::fRequireStandard = fuzzed_data_provider.ConsumeBool();
// Make sure ProcessNewPackage on one transaction works and always fully validates the transaction.
// The result is not guaranteed to be the same as what is returned by ATMP.
const auto result_package = WITH_LOCK(::cs_main,
return ProcessNewPackage(node.chainman->ActiveChainstate(), tx_pool, {tx}, true));
auto it = result_package.m_tx_results.find(tx->GetWitnessHash());
Assert(it != result_package.m_tx_results.end());
Assert(it->second.m_result_type == MempoolAcceptResult::ResultType::VALID ||
it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx_pool, tx, bypass_limits));
const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
SyncWithValidationInterfaceQueue();
UnregisterSharedValidationInterface(txr);
Assert(accepted != added.empty());
Assert(accepted == res.m_state.IsValid());
Assert(accepted != res.m_state.IsInvalid());
if (accepted) {
Assert(added.size() == 1); // For now, no package acceptance
Assert(tx == *added.begin());
} else {
// Do not consider rejected transaction removed
removed.erase(tx);
}
// Helper to insert spent and created outpoints of a tx into collections
using Sets = std::vector<std::reference_wrapper<std::set<COutPoint>>>;
const auto insert_tx = [](Sets created_by_tx, Sets consumed_by_tx, const auto& tx) {
for (size_t i{0}; i < tx.vout.size(); ++i) {
for (auto& set : created_by_tx) {
Assert(set.get().emplace(tx.GetHash(), i).second);
}
}
for (const auto& in : tx.vin) {
for (auto& set : consumed_by_tx) {
Assert(set.get().insert(in.prevout).second);
}
}
};
// Add created outpoints, remove spent outpoints
{
// Outpoints that no longer exist at all
std::set<COutPoint> consumed_erased;
// Outpoints that no longer count toward the total supply
std::set<COutPoint> consumed_supply;
for (const auto& removed_tx : removed) {
insert_tx(/* created_by_tx */ {consumed_erased}, /* consumed_by_tx */ {outpoints_supply}, /* tx */ *removed_tx);
}
for (const auto& added_tx : added) {
insert_tx(/* created_by_tx */ {outpoints_supply, outpoints_rbf}, /* consumed_by_tx */ {consumed_supply}, /* tx */ *added_tx);
}
for (const auto& p : consumed_erased) {
Assert(outpoints_supply.erase(p) == 1);
Assert(outpoints_rbf.erase(p) == 1);
}
for (const auto& p : consumed_supply) {
Assert(outpoints_supply.erase(p) == 1);
}
}
}
Finish(fuzzed_data_provider, tx_pool, chainstate);
}
FUZZ_TARGET_INIT(tx_pool, initialize_tx_pool)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const auto& node = g_setup->m_node;
auto& chainstate = node.chainman->ActiveChainstate();
MockTime(fuzzed_data_provider, chainstate);
SetMempoolConstraints(*node.args, fuzzed_data_provider);
std::vector<uint256> txids;
for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
txids.push_back(outpoint.hash);
}
for (int i{0}; i <= 3; ++i) {
// Add some immature and non-existent outpoints
txids.push_back(g_outpoints_coinbase_init_immature.at(i).hash);
txids.push_back(ConsumeUInt256(fuzzed_data_provider));
}
CTxMemPool tx_pool_{/* estimator */ nullptr, /* check_ratio */ 1};
MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
while (fuzzed_data_provider.ConsumeBool()) {
const auto mut_tx = ConsumeTransaction(fuzzed_data_provider, txids);
if (fuzzed_data_provider.ConsumeBool()) {
MockTime(fuzzed_data_provider, chainstate);
}
if (fuzzed_data_provider.ConsumeBool()) {
SetMempoolConstraints(*node.args, fuzzed_data_provider);
}
if (fuzzed_data_provider.ConsumeBool()) {
tx_pool.RollingFeeUpdate();
}
if (fuzzed_data_provider.ConsumeBool()) {
const auto& txid = fuzzed_data_provider.ConsumeBool() ?
mut_tx.GetHash() :
PickValue(fuzzed_data_provider, txids);
const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
tx_pool.PrioritiseTransaction(txid, delta);
}
const auto tx = MakeTransactionRef(mut_tx);
const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
::fRequireStandard = fuzzed_data_provider.ConsumeBool();
const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(node.chainman->ActiveChainstate(), tx_pool, tx, bypass_limits));
const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
if (accepted) {
txids.push_back(tx->GetHash());
}
}
Finish(fuzzed_data_provider, tx_pool, chainstate);
}
} // namespace
<|endoftext|> |
<commit_before>#ifndef CMDSTAN_ARGUMENTS_ARG_OUTPUT_PRECISION_HPP
#define CMDSTAN_ARGUMENTS_ARG_OUTPUT_PRECISION_HPP
#include <cmdstan/arguments/singleton_argument.hpp>
namespace cmdstan {
class arg_output_precision : public int_argument {
public:
arg_output_precision() : int_argument() {
_name = "precision";
_description = "The precision used for the output CSV files.";
_validity = "integer > 0 or -1 to use the defautl precision";
_default = "-1";
_default_value = -1;
_constrained = true;
_good_value = 8;
_bad_value = -2;
_value = _default_value;
}
bool is_valid(int value) { return value > 0 || value == _default_value; }
};
} // namespace cmdstan
#endif
<commit_msg>cleanup<commit_after>#ifndef CMDSTAN_ARGUMENTS_ARG_OUTPUT_PRECISION_HPP
#define CMDSTAN_ARGUMENTS_ARG_OUTPUT_PRECISION_HPP
#include <cmdstan/arguments/singleton_argument.hpp>
namespace cmdstan {
class arg_output_precision : public int_argument {
public:
arg_output_precision() : int_argument() {
_name = "precision";
_description = "The decimal precision used for the output CSV files.";
_validity = "integer >= 0 or -1 to use the default precision";
_default = "-1";
_default_value = -1;
_constrained = true;
_good_value = 8;
_bad_value = -2;
_value = _default_value;
}
bool is_valid(int value) { return value >= 0 || value == _default_value; }
};
} // namespace cmdstan
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define BOOST_TEST_MODULE Bitcoin Test Suite
#include "test_bitcoin.h"
#include "main.h"
#include "random.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet/db.h"
#include "wallet/wallet.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
CClientUIInterface uiInterface;
CWallet* pwalletMain;
extern bool fPrintToConsole;
extern void noui_connect();
BasicTestingSetup::BasicTestingSetup()
{
fPrintToDebugLog = false; // don't want to write to debug.log file
SelectParams(CBaseChainParams::MAIN);
}
BasicTestingSetup::~BasicTestingSetup()
{
}
TestingSetup::TestingSetup()
{
#ifdef ENABLE_WALLET
bitdb.MakeMock();
#endif
ClearDatadirCache();
pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex();
#ifdef ENABLE_WALLET
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
#endif
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
RegisterNodeSignals(GetNodeSignals());
}
TestingSetup::~TestingSetup()
{
UnregisterNodeSignals(GetNodeSignals());
threadGroup.interrupt_all();
threadGroup.join_all();
#ifdef ENABLE_WALLET
UnregisterValidationInterface(pwalletMain);
delete pwalletMain;
pwalletMain = NULL;
#endif
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
#ifdef ENABLE_WALLET
bitdb.Flush(true);
bitdb.Reset();
#endif
boost::filesystem::remove_all(pathTemp);
}
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
bool ShutdownRequested()
{
return false;
}
<commit_msg>Initialization: setup environment before starting tests<commit_after>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define BOOST_TEST_MODULE Bitcoin Test Suite
#include "test_bitcoin.h"
#include "main.h"
#include "random.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet/db.h"
#include "wallet/wallet.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
CClientUIInterface uiInterface;
CWallet* pwalletMain;
extern bool fPrintToConsole;
extern void noui_connect();
BasicTestingSetup::BasicTestingSetup()
{
SetupEnvironment();
fPrintToDebugLog = false; // don't want to write to debug.log file
SelectParams(CBaseChainParams::MAIN);
}
BasicTestingSetup::~BasicTestingSetup()
{
}
TestingSetup::TestingSetup()
{
#ifdef ENABLE_WALLET
bitdb.MakeMock();
#endif
ClearDatadirCache();
pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex();
#ifdef ENABLE_WALLET
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
#endif
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
RegisterNodeSignals(GetNodeSignals());
}
TestingSetup::~TestingSetup()
{
UnregisterNodeSignals(GetNodeSignals());
threadGroup.interrupt_all();
threadGroup.join_all();
#ifdef ENABLE_WALLET
UnregisterValidationInterface(pwalletMain);
delete pwalletMain;
pwalletMain = NULL;
#endif
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
#ifdef ENABLE_WALLET
bitdb.Flush(true);
bitdb.Reset();
#endif
boost::filesystem::remove_all(pathTemp);
}
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
bool ShutdownRequested()
{
return false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define BOOST_TEST_MODULE Bitcoin Test Suite
#include "main.h"
#include "random.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
CClientUIInterface uiInterface;
CWallet* pwalletMain;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
boost::filesystem::path pathTemp;
boost::thread_group threadGroup;
TestingSetup() {
fPrintToDebugLog = false; // don't want to write to debug.log file
SelectParams(CBaseChainParams::UNITTEST);
noui_connect();
#ifdef ENABLE_WALLET
bitdb.MakeMock();
#endif
pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex();
#ifdef ENABLE_WALLET
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
#endif
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
RegisterNodeSignals(GetNodeSignals());
}
~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
UnregisterNodeSignals(GetNodeSignals());
#ifdef ENABLE_WALLET
delete pwalletMain;
pwalletMain = NULL;
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
#ifdef ENABLE_WALLET
bitdb.Flush(true);
#endif
boost::filesystem::remove_all(pathTemp);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
bool ShutdownRequested()
{
return false;
}
<commit_msg>Tests: setup environment before testing<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define BOOST_TEST_MODULE Bitcoin Test Suite
#include "main.h"
#include "random.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
CClientUIInterface uiInterface;
CWallet* pwalletMain;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
boost::filesystem::path pathTemp;
boost::thread_group threadGroup;
TestingSetup() {
SetupEnvironment();
fPrintToDebugLog = false; // don't want to write to debug.log file
SelectParams(CBaseChainParams::UNITTEST);
noui_connect();
#ifdef ENABLE_WALLET
bitdb.MakeMock();
#endif
pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex();
#ifdef ENABLE_WALLET
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
#endif
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
RegisterNodeSignals(GetNodeSignals());
}
~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
UnregisterNodeSignals(GetNodeSignals());
#ifdef ENABLE_WALLET
delete pwalletMain;
pwalletMain = NULL;
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
#ifdef ENABLE_WALLET
bitdb.Flush(true);
#endif
boost::filesystem::remove_all(pathTemp);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
bool ShutdownRequested()
{
return false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Chaos/Base/Platform.h>
#include <Chaos/Base/Types.h>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "buffer.h"
#include "primitive.h"
#include "address.h"
#include "socket.h"
#include "acceptor.h"
#include "socket_service.h"
void echo_tcp_server(void) {
netpp::SocketService service;
#if defined(CHAOS_POSIX)
netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v6(), 5555));
#else
netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v4(), 5555));
#endif
acceptor.set_non_blocking(true);
std::vector<std::unique_ptr<std::thread>> threads;
netpp::TcpSocket conn(service);
acceptor.async_accept(conn,
[&threads, &acceptor, &conn](const std::error_code& ec) {
if (!ec) {
threads.emplace_back(new std::thread([](netpp::TcpSocket&& conn) {
std::error_code ec;
std::vector<char> buf(1024);
for (;;) {
auto n = conn.read(netpp::buffer(buf));
if (n > 0)
conn.write(netpp::buffer(buf, n));
else
break;
}
conn.close();
}, std::move(conn)));
}
});
service.run();
for (auto& t : threads)
t->join();
}
void echo_tcp_client(void) {
netpp::SocketService service;
netpp::TcpSocket s(service, netpp::Tcp::v4());
s.set_non_blocking(true);
s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));
std::string line;
std::vector<char> buf(1024);
while (std::getline(std::cin, line)) {
if (line == "quit")
break;
s.write(netpp::buffer(line));
buf.assign(buf.size(), 0);
if (s.read(netpp::buffer(buf)) > 0)
std::cout << "echo read: " << buf.data() << std::endl;
else
break;
}
s.close();
}
void echo_udp_server(void) {
netpp::SocketService service;
netpp::UdpSocket s(service, netpp::Address(netpp::IP::v4(), 5555));
s.set_non_blocking(true);
std::vector<char> buf(1024);
for (;;) {
netpp::Address addr(netpp::IP::v4());
auto n = s.read_from(netpp::buffer(buf), addr);
if (n > 0)
s.write_to(netpp::buffer(buf, n), addr);
else
break;
}
s.close();
}
void echo_udp_client(void) {
netpp::SocketService service;
netpp::UdpSocket s(service, netpp::UdpSocket::ProtocolType::v4());
s.set_non_blocking(true);
s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));
std::string line;
std::vector<char> buf(1024);
while (std::getline(std::cin, line)) {
if (line == "quit")
break;
s.write(netpp::buffer(line));
buf.assign(buf.size(), 0);
if (s.read(netpp::buffer(buf)) > 0)
std::cout << "from{127.0.0.1:5555} read: " << buf.data() << std::endl;
}
s.close();
}
void echo_sample(const char* c) {
netpp::startup();
if (std::strcmp(c, "ts") == 0)
echo_tcp_server();
else if (std::strcmp(c, "tc") == 0)
echo_tcp_client();
else if (std::strcmp(c, "us") == 0)
echo_udp_server();
else if (std::strcmp(c, "uc") == 0)
echo_udp_client();
netpp::cleanup();
}
int main(int argc, char* argv[]) {
CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);
if (argc > 1)
echo_sample(argv[1]);
return 0;
}
<commit_msg>:construction: chore(netpp): updated the demo of netpp<commit_after>// Copyright (c) 2017 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Chaos/Base/Platform.h>
#include <Chaos/Base/Types.h>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "buffer.h"
#include "primitive.h"
#include "address.h"
#include "socket.h"
#include "acceptor.h"
#include "socket_service.h"
void echo_tcp_server(void) {
netpp::SocketService service;
#if defined(CHAOS_POSIX)
netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v6(), 5555));
#else
netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v4(), 5555));
#endif
acceptor.set_non_blocking(true);
std::vector<std::unique_ptr<std::thread>> threads;
netpp::TcpSocket conn(service);
acceptor.async_accept(conn,
[&threads, &acceptor, &conn](const std::error_code& ec) {
if (!ec) {
threads.emplace_back(new std::thread([](netpp::TcpSocket&& conn) {
std::error_code ec;
std::vector<char> buf(1024);
for (;;) {
auto n = conn.read_some(netpp::buffer(buf));
if (n > 0)
conn.write_some(netpp::buffer(buf, n));
else
break;
}
conn.close();
}, std::move(conn)));
}
});
service.run();
for (auto& t : threads)
t->join();
}
void echo_tcp_client(void) {
netpp::SocketService service;
netpp::TcpSocket s(service, netpp::Tcp::v4());
s.set_non_blocking(true);
s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));
std::string line;
std::vector<char> buf(1024);
while (std::getline(std::cin, line)) {
if (line == "quit")
break;
s.write(netpp::buffer(line));
buf.assign(buf.size(), 0);
if (s.read(netpp::buffer(buf)) > 0)
std::cout << "echo read: " << buf.data() << std::endl;
else
break;
}
s.close();
}
void echo_udp_server(void) {
netpp::SocketService service;
netpp::UdpSocket s(service, netpp::Address(netpp::IP::v4(), 5555));
s.set_non_blocking(true);
std::vector<char> buf(1024);
for (;;) {
netpp::Address addr(netpp::IP::v4());
auto n = s.read_from(netpp::buffer(buf), addr);
if (n > 0)
s.write_to(netpp::buffer(buf, n), addr);
else
break;
}
s.close();
}
void echo_udp_client(void) {
netpp::SocketService service;
netpp::UdpSocket s(service, netpp::UdpSocket::ProtocolType::v4());
s.set_non_blocking(true);
s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));
std::string line;
std::vector<char> buf(1024);
while (std::getline(std::cin, line)) {
if (line == "quit")
break;
s.write(netpp::buffer(line));
buf.assign(buf.size(), 0);
if (s.read(netpp::buffer(buf)) > 0)
std::cout << "from{127.0.0.1:5555} read: " << buf.data() << std::endl;
}
s.close();
}
void echo_sample(const char* c) {
netpp::startup();
if (std::strcmp(c, "ts") == 0)
echo_tcp_server();
else if (std::strcmp(c, "tc") == 0)
echo_tcp_client();
else if (std::strcmp(c, "us") == 0)
echo_udp_server();
else if (std::strcmp(c, "uc") == 0)
echo_udp_client();
netpp::cleanup();
}
int main(int argc, char* argv[]) {
CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);
if (argc > 1)
echo_sample(argv[1]);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) Paul Hodge. See LICENSE file for license terms.
#include <circa.h>
namespace circa {
namespace names_tests {
void test_find_named()
{
Branch branch;
Term* a = create_int(branch, 1, "a");
test_assert(find_named(branch, "a") == a);
test_assert(find_named(branch, "b") == NULL);
Branch& sub = create_branch(branch, "sub");
test_assert(find_named(sub, "a") == a);
}
void test_name_is_reachable_from()
{
Branch branch;
Term* a = create_int(branch, 5, "a");
test_assert(name_is_reachable_from(a, branch));
Branch& sub_1 = create_branch(branch, "sub_1");
test_assert(name_is_reachable_from(a, sub_1));
Branch& sub_2 = create_branch(sub_1, "sub_2");
test_assert(name_is_reachable_from(a, sub_2));
}
void test_get_relative_name()
{
Branch branch;
Term* a = create_int(branch, 5, "A");
test_assert(get_relative_name(branch, a) == "A");
Branch& ns = create_namespace(branch, "ns");
test_assert(ns.owningTerm != NULL);
Term* b = create_int(ns, 5, "B");
test_assert(is_namespace(branch["ns"]));
test_assert(ns.owningTerm != NULL);
test_assert(ns.owningTerm == branch["ns"]);
test_assert(get_relative_name(ns, b) == "B");
test_equals(get_relative_name(branch, b), "ns:B");
// This code once had a bug:
Term* c = branch.compile("[1 1] -> Point");
test_assert(c->function->name == "cast");
test_assert(c->type->name == "Point");
test_equals(get_relative_name(c, c->type), "Point");
}
void test_get_relative_name_from_hidden_branch()
{
// This code once had a bug
Branch branch;
branch.eval("if true { a = 1 } else { a = 2 }");
test_equals(get_relative_name(branch, branch["a"]), "a");
}
void test_lookup_qualified_name()
{
Branch branch;
Term* a = branch.compile("namespace a { b = 1 }");
Term* b = nested_contents(a)["b"];
test_assert(b != NULL);
test_assert(branch["a:b"] == b);
Term* x = branch.compile("namespace x { namespace y { namespace z { w = 1 }}}");
Term* w = x->contents("y")->contents("z")->contents("w");
test_assert(branch["x:y:z:w"] == w);
}
void test_get_named_at()
{
Branch branch;
// Simple case
Term* a = create_int(branch, 1, "a");
Term* b = create_int(branch, 1, "b");
create_int(branch, 1, "a");
test_assert(get_named_at(b, "a") == a);
// Make sure that the location term is not checked, should only check
// things before that.
Term* c1 = create_int(branch, 1, "c");
Term* c2 = create_int(branch, 1, "c");
create_int(branch, 1, "c");
test_assert(get_named_at(c2, "c") != c2);
test_assert(get_named_at(c2, "c") == c1);
// Find names in outer scopes
Term* d = create_int(branch, 1, "d");
Branch& subBranch = create_branch(branch);
Term* e = create_int(subBranch, 1, "e");
test_assert(get_named_at(e, "d") == d);
// Make sure that when we look into outer scopes, we don't check the name of
// our enclosing branch, or any names after that.
Term* f1 = create_int(branch, 1, "f");
Branch& subBranch2 = create_branch(branch, "f");
Term* fsub = create_int(subBranch2, 1, "f");
create_int(branch, 1, "f");
test_assert(get_named_at(fsub, "f") == f1);
// Find names in exposed-name branches
Branch& subBranch3 = create_branch(branch);
Term* h = create_int(subBranch3, 1, "h");
subBranch3.owningTerm->setBoolProp("exposesNames", true);
Term* i = create_int(branch, 1, "i");
test_assert(get_named_at(i, "h") == h);
}
void test_get_named_at_after_if_block()
{
Branch branch;
Term* originalA = branch.compile("a = 1");
branch.compile("if true { a = 2 }");
Term* b = branch.compile("b = 1");
test_assert(branch["a"] != originalA); // sanity check
test_assert(get_named_at(b, "a") != originalA);
test_assert(get_named_at(b, "a") == branch["a"]);
}
void test_find_first_common_branch()
{
Branch branch;
Term* a = create_int(branch, 0);
Term* b = create_int(branch, 0);
test_assert(find_first_common_branch(a,b) == &branch);
test_assert(find_first_common_branch(b,a) == &branch);
Branch& b1 = create_branch(branch);
Term* c = create_int(b1, 0);
Term* d = create_int(b1, 0);
test_assert(find_first_common_branch(c,d) == &b1);
test_assert(find_first_common_branch(d,c) == &b1);
test_assert(find_first_common_branch(a,c) == &branch);
test_assert(find_first_common_branch(d,b) == &branch);
Branch alternate;
Term* e = create_int(alternate, 0);
test_assert(find_first_common_branch(a,e) == NULL);
}
void test_unique_names()
{
Branch branch;
Term* a0 = create_int(branch, 5, "a");
Term* a1 = create_int(branch, 5, "a");
test_equals(a0->uniqueName.name, "a");
test_assert(a0->uniqueName.ordinal == 0);
test_equals(a1->uniqueName.name, "a_1");
test_assert(a1->uniqueName.ordinal == 1);
// Declare a name which overlaps with the next unique name that we'll
// try to generate for 'a'.
create_int(branch, 5, "a_2");
Term* a3 = create_int(branch, 5, "a");
test_equals(a3->uniqueName.name, "a_3");
test_assert(a3->uniqueName.ordinal == 3);
}
void test_unique_names_for_anons()
{
Branch branch;
Term* a = branch.compile("add(1,2)");
test_equals(a->uniqueName.name, "_add");
Term* b = branch.compile("add(3,4)");
test_equals(b->uniqueName.name, "_add_1");
Term* c = branch.compile("_add_2 = add(3,4)");
test_equals(c->uniqueName.name, "_add_2");
Term* d = branch.compile("add(3,4)");
test_equals(d->uniqueName.name, "_add_3");
}
void test_find_from_unique_name()
{
Branch branch;
Term* a0 = branch.compile("a = 0");
Term* a1 = branch.compile("a = 1");
Term* a2 = branch.compile("a = 2");
test_assert(find_from_unique_name(branch, "a") == a0);
test_assert(find_from_unique_name(branch, "a_1") == a1);
test_assert(find_from_unique_name(branch, "a_2") == a2);
test_assert(find_from_unique_name(branch, "b") == NULL);
}
void test_with_include()
{
#if 0
TEST_DISABLED
FakeFileSystem files;
files["a"] = "namespace ns { a = 1 }";
Branch branch;
branch.compile("include('a')");
Term* a = find_named(branch, "ns:a");
test_assert(a != NULL);
test_assert(name_is_reachable_from(a, branch));
#endif
}
void register_tests()
{
REGISTER_TEST_CASE(names_tests::test_find_named);
REGISTER_TEST_CASE(names_tests::test_name_is_reachable_from);
REGISTER_TEST_CASE(names_tests::test_get_relative_name);
REGISTER_TEST_CASE(names_tests::test_get_relative_name_from_hidden_branch);
//TEST_DISABLED REGISTER_TEST_CASE(names_tests::test_lookup_qualified_name);
REGISTER_TEST_CASE(names_tests::test_get_named_at);
REGISTER_TEST_CASE(names_tests::test_get_named_at_after_if_block);
REGISTER_TEST_CASE(names_tests::test_find_first_common_branch);
REGISTER_TEST_CASE(names_tests::test_unique_names);
REGISTER_TEST_CASE(names_tests::test_unique_names_for_anons);
REGISTER_TEST_CASE(names_tests::test_find_from_unique_name);
REGISTER_TEST_CASE(names_tests::test_with_include);
}
} // namespace names_tests
} // namespace circa
<commit_msg>add names_test::name_with_colons<commit_after>// Copyright (c) Paul Hodge. See LICENSE file for license terms.
#include <circa.h>
namespace circa {
namespace names_tests {
void test_find_named()
{
Branch branch;
Term* a = create_int(branch, 1, "a");
test_assert(find_named(branch, "a") == a);
test_assert(find_named(branch, "b") == NULL);
Branch& sub = create_branch(branch, "sub");
test_assert(find_named(sub, "a") == a);
}
void test_name_is_reachable_from()
{
Branch branch;
Term* a = create_int(branch, 5, "a");
test_assert(name_is_reachable_from(a, branch));
Branch& sub_1 = create_branch(branch, "sub_1");
test_assert(name_is_reachable_from(a, sub_1));
Branch& sub_2 = create_branch(sub_1, "sub_2");
test_assert(name_is_reachable_from(a, sub_2));
}
void test_get_relative_name()
{
Branch branch;
Term* a = create_int(branch, 5, "A");
test_assert(get_relative_name(branch, a) == "A");
Branch& ns = create_namespace(branch, "ns");
test_assert(ns.owningTerm != NULL);
Term* b = create_int(ns, 5, "B");
test_assert(is_namespace(branch["ns"]));
test_assert(ns.owningTerm != NULL);
test_assert(ns.owningTerm == branch["ns"]);
test_assert(get_relative_name(ns, b) == "B");
test_equals(get_relative_name(branch, b), "ns:B");
// This code once had a bug:
Term* c = branch.compile("[1 1] -> Point");
test_assert(c->function->name == "cast");
test_assert(c->type->name == "Point");
test_equals(get_relative_name(c, c->type), "Point");
}
void test_get_relative_name_from_hidden_branch()
{
// This code once had a bug
Branch branch;
branch.eval("if true { a = 1 } else { a = 2 }");
test_equals(get_relative_name(branch, branch["a"]), "a");
}
void test_lookup_qualified_name()
{
Branch branch;
Term* a = branch.compile("namespace a { b = 1 }");
Term* b = nested_contents(a)["b"];
test_assert(b != NULL);
test_assert(branch["a:b"] == b);
Term* x = branch.compile("namespace x { namespace y { namespace z { w = 1 }}}");
Term* w = x->contents("y")->contents("z")->contents("w");
test_assert(branch["x:y:z:w"] == w);
}
void test_get_named_at()
{
Branch branch;
// Simple case
Term* a = create_int(branch, 1, "a");
Term* b = create_int(branch, 1, "b");
create_int(branch, 1, "a");
test_assert(get_named_at(b, "a") == a);
// Make sure that the location term is not checked, should only check
// things before that.
Term* c1 = create_int(branch, 1, "c");
Term* c2 = create_int(branch, 1, "c");
create_int(branch, 1, "c");
test_assert(get_named_at(c2, "c") != c2);
test_assert(get_named_at(c2, "c") == c1);
// Find names in outer scopes
Term* d = create_int(branch, 1, "d");
Branch& subBranch = create_branch(branch);
Term* e = create_int(subBranch, 1, "e");
test_assert(get_named_at(e, "d") == d);
// Make sure that when we look into outer scopes, we don't check the name of
// our enclosing branch, or any names after that.
Term* f1 = create_int(branch, 1, "f");
Branch& subBranch2 = create_branch(branch, "f");
Term* fsub = create_int(subBranch2, 1, "f");
create_int(branch, 1, "f");
test_assert(get_named_at(fsub, "f") == f1);
// Find names in exposed-name branches
Branch& subBranch3 = create_branch(branch);
Term* h = create_int(subBranch3, 1, "h");
subBranch3.owningTerm->setBoolProp("exposesNames", true);
Term* i = create_int(branch, 1, "i");
test_assert(get_named_at(i, "h") == h);
}
void test_get_named_at_after_if_block()
{
Branch branch;
Term* originalA = branch.compile("a = 1");
branch.compile("if true { a = 2 }");
Term* b = branch.compile("b = 1");
test_assert(branch["a"] != originalA); // sanity check
test_assert(get_named_at(b, "a") != originalA);
test_assert(get_named_at(b, "a") == branch["a"]);
}
void test_find_first_common_branch()
{
Branch branch;
Term* a = create_int(branch, 0);
Term* b = create_int(branch, 0);
test_assert(find_first_common_branch(a,b) == &branch);
test_assert(find_first_common_branch(b,a) == &branch);
Branch& b1 = create_branch(branch);
Term* c = create_int(b1, 0);
Term* d = create_int(b1, 0);
test_assert(find_first_common_branch(c,d) == &b1);
test_assert(find_first_common_branch(d,c) == &b1);
test_assert(find_first_common_branch(a,c) == &branch);
test_assert(find_first_common_branch(d,b) == &branch);
Branch alternate;
Term* e = create_int(alternate, 0);
test_assert(find_first_common_branch(a,e) == NULL);
}
void test_unique_names()
{
Branch branch;
Term* a0 = create_int(branch, 5, "a");
Term* a1 = create_int(branch, 5, "a");
test_equals(a0->uniqueName.name, "a");
test_assert(a0->uniqueName.ordinal == 0);
test_equals(a1->uniqueName.name, "a_1");
test_assert(a1->uniqueName.ordinal == 1);
// Declare a name which overlaps with the next unique name that we'll
// try to generate for 'a'.
create_int(branch, 5, "a_2");
Term* a3 = create_int(branch, 5, "a");
test_equals(a3->uniqueName.name, "a_3");
test_assert(a3->uniqueName.ordinal == 3);
}
void test_unique_names_for_anons()
{
Branch branch;
Term* a = branch.compile("add(1,2)");
test_equals(a->uniqueName.name, "_add");
Term* b = branch.compile("add(3,4)");
test_equals(b->uniqueName.name, "_add_1");
Term* c = branch.compile("_add_2 = add(3,4)");
test_equals(c->uniqueName.name, "_add_2");
Term* d = branch.compile("add(3,4)");
test_equals(d->uniqueName.name, "_add_3");
}
void test_find_from_unique_name()
{
Branch branch;
Term* a0 = branch.compile("a = 0");
Term* a1 = branch.compile("a = 1");
Term* a2 = branch.compile("a = 2");
test_assert(find_from_unique_name(branch, "a") == a0);
test_assert(find_from_unique_name(branch, "a_1") == a1);
test_assert(find_from_unique_name(branch, "a_2") == a2);
test_assert(find_from_unique_name(branch, "b") == NULL);
}
void test_with_include()
{
FakeFileSystem files;
files["a"] = "namespace ns { a = 1 }";
Branch branch;
branch.compile("include('a')");
Term* a = find_named(branch, "ns:a");
test_assert(a != NULL);
test_assert(name_is_reachable_from(a, branch));
}
void name_with_colons()
{
Branch branch;
Term* one = branch.compile("1");
branch.bindName(one, "qualified:name");
test_assert(branch["qualified:name"] == one);
test_assert(find_named(branch, "qualified:name") == one);
Branch& ns = create_namespace(branch, "ns");
Term* two = ns.compile("2");
ns.bindName(two, "another:name");
test_assert(branch["ns:another:name"] == two);
test_assert(find_named(branch, "ns:another:name") == two);
}
void register_tests()
{
REGISTER_TEST_CASE(names_tests::test_find_named);
REGISTER_TEST_CASE(names_tests::test_name_is_reachable_from);
REGISTER_TEST_CASE(names_tests::test_get_relative_name);
REGISTER_TEST_CASE(names_tests::test_get_relative_name_from_hidden_branch);
//TEST_DISABLED REGISTER_TEST_CASE(names_tests::test_lookup_qualified_name);
REGISTER_TEST_CASE(names_tests::test_get_named_at);
REGISTER_TEST_CASE(names_tests::test_get_named_at_after_if_block);
REGISTER_TEST_CASE(names_tests::test_find_first_common_branch);
REGISTER_TEST_CASE(names_tests::test_unique_names);
REGISTER_TEST_CASE(names_tests::test_unique_names_for_anons);
REGISTER_TEST_CASE(names_tests::test_find_from_unique_name);
//TEST_DISABLED REGISTER_TEST_CASE(names_tests::test_with_include);
REGISTER_TEST_CASE(names_tests::name_with_colons);
}
} // namespace names_tests
} // namespace circa
<|endoftext|> |
<commit_before>/*
Copyright © 2015 Alexey Kudrin. All rights reserved.
Licensed under the Apache License, Version 2.0
*/
#include <QString>
#include <QTextCodec>
#include <QTextStream>
#include <time.h>
#include "src/getFiles.h"
#include "src/crc16.h"
#include "src/calcMd5.h"
#include "consoleMode.h"
namespace CloneHunter
{
int startConsoleMode(const CloneHunter::PROGRAMPARAMS& params)
{
time_t tStart = time(0);
consoleOut("READ FILES");
CloneHunter::FilesInfo filesInfo;
CloneHunter::getFilesInfo(params, filesInfo);
int totalFilesCount = filesInfo.size();
consoleOut(QString("TOTAL FILES: %1").arg(totalFilesCount));
if (filesInfo.size() != 0)
{
consoleOut("SORT BY SIZE");
CloneHunter::sortFilesInfoBySize(filesInfo);
consoleOut("FILTER BY SIZE");
CloneHunter::removeUniqueSizes(filesInfo);
consoleOut(QString("FILES COUNT: %1").arg(filesInfo.size()));
if (filesInfo.size() != 0)
{
// qWarning() << "CALC CRC16";
// CloneHunter::calcFilesCrc16(filesInfo);
// qWarning() << "SORT BY CRC16";
// CloneHunter::sortFilesInfoByCrc16(filesInfo);
// qWarning() << "FILTER BY CRC16";
// CloneHunter::removeUniqueCrc16(filesInfo);
// qWarning() << "FILES COUNT: " << filesInfo.size();
consoleOut("CALC MD5");
CloneHunter::calcFilesMd5(filesInfo, params);
consoleOut("SORT BY MD5");
CloneHunter::sortFilesInfoByMd5(filesInfo);
consoleOut("FILTER BY MD5");
CloneHunter::removeUniqueMd5(filesInfo);
consoleOut(QString("FILES COUNT: %1").arg(filesInfo.size()));
if (params.sort)
{
CloneHunter::sortFilesInfoByPath(filesInfo);
}
consoleOut("FILES (WITHOUT EMPTY):");
}
}
int notEmptyCount(0);
for (int i = 0; i < filesInfo.count(); i++)
{
// if (filesInfo[i].size >= params.min && (filesInfo[i].size <= params.max))
if (!filesInfo[i].md5.isEmpty())
{
notEmptyCount++;
consoleOut(QString("%1 %2 %3").arg(filesInfo[i].md5).arg(filesInfo[i].name).arg(filesInfo[i].size));
}
}
consoleOut(QString("TOTAL NOT EMPTY DUP FILES: %1 TOTAL DUP FILES: %2 TOTAL FILES: %3")
.arg(notEmptyCount)
.arg(filesInfo.size())
.arg(totalFilesCount));
if (params.other)
{
consoleOut("OTHER FILES WITH EQUAL SIZES:");
CloneHunter::sortFilesInfoBySize(filesInfo);
for (int i = 0; i < filesInfo.count(); i++)
{
if (filesInfo[i].md5.isEmpty())
{
notEmptyCount++;
consoleOut(QString("%1 %2").arg(filesInfo[i].name).arg(filesInfo[i].size));
}
}
}
consoleOut(QString("Time: %1").arg(time(0) - tStart));
return 0;
}
void consoleOut(const QString& text)
{
QTextStream out(stdout);
#if defined(__WIN32)
out.setCodec("IBM866");
#endif
out << text << endl;
}
}
<commit_msg>[+] Sort files before md5 sum calc for speedup file scan.<commit_after>/*
Copyright © 2015 Alexey Kudrin. All rights reserved.
Licensed under the Apache License, Version 2.0
*/
#include <QString>
#include <QTextCodec>
#include <QTextStream>
#include <time.h>
#include "src/getFiles.h"
#include "src/crc16.h"
#include "src/calcMd5.h"
#include "consoleMode.h"
namespace CloneHunter
{
int startConsoleMode(const CloneHunter::PROGRAMPARAMS& params)
{
time_t tStart = time(0);
consoleOut("READ FILES");
CloneHunter::FilesInfo filesInfo;
CloneHunter::getFilesInfo(params, filesInfo);
int totalFilesCount = filesInfo.size();
consoleOut(QString("TOTAL FILES: %1").arg(totalFilesCount));
if (filesInfo.size() != 0)
{
consoleOut("SORT BY SIZE");
CloneHunter::sortFilesInfoBySize(filesInfo);
consoleOut("FILTER BY SIZE");
CloneHunter::removeUniqueSizes(filesInfo);
consoleOut(QString("FILES COUNT: %1").arg(filesInfo.size()));
if (filesInfo.size() != 0)
{
// qWarning() << "CALC CRC16";
// CloneHunter::calcFilesCrc16(filesInfo);
// qWarning() << "SORT BY CRC16";
// CloneHunter::sortFilesInfoByCrc16(filesInfo);
// qWarning() << "FILTER BY CRC16";
// CloneHunter::removeUniqueCrc16(filesInfo);
// qWarning() << "FILES COUNT: " << filesInfo.size();
// For sequental file access.
CloneHunter::sortFilesInfoByPath(filesInfo);
consoleOut("CALC MD5");
CloneHunter::calcFilesMd5(filesInfo, params);
consoleOut("SORT BY MD5");
CloneHunter::sortFilesInfoByMd5(filesInfo);
consoleOut("FILTER BY MD5");
CloneHunter::removeUniqueMd5(filesInfo);
consoleOut(QString("FILES COUNT: %1").arg(filesInfo.size()));
if (params.sort)
{
CloneHunter::sortFilesInfoByPath(filesInfo);
}
consoleOut("FILES (WITHOUT EMPTY):");
}
}
int notEmptyCount(0);
for (int i = 0; i < filesInfo.count(); i++)
{
// if (filesInfo[i].size >= params.min && (filesInfo[i].size <= params.max))
if (!filesInfo[i].md5.isEmpty())
{
notEmptyCount++;
consoleOut(QString("%1 %2 %3").arg(filesInfo[i].md5).arg(filesInfo[i].name).arg(filesInfo[i].size));
}
}
consoleOut(QString("TOTAL NOT EMPTY DUP FILES: %1 TOTAL DUP FILES: %2 TOTAL FILES: %3")
.arg(notEmptyCount)
.arg(filesInfo.size())
.arg(totalFilesCount));
if (params.other)
{
consoleOut("OTHER FILES WITH EQUAL SIZES:");
CloneHunter::sortFilesInfoBySize(filesInfo);
for (int i = 0; i < filesInfo.count(); i++)
{
if (filesInfo[i].md5.isEmpty())
{
notEmptyCount++;
consoleOut(QString("%1 %2").arg(filesInfo[i].name).arg(filesInfo[i].size));
}
}
}
consoleOut(QString("Time: %1").arg(time(0) - tStart));
return 0;
}
void consoleOut(const QString& text)
{
QTextStream out(stdout);
#if defined(__WIN32)
out.setCodec("IBM866");
#endif
out << text << endl;
}
}
<|endoftext|> |
<commit_before>#ifndef CONTAINERS_BUFFER_GROUP_HPP_
#define CONTAINERS_BUFFER_GROUP_HPP_
#include <stdlib.h>
#include <vector>
#include "utils.hpp"
class const_buffer_group_t {
public:
struct buffer_t {
ssize_t size;
const void *data;
};
const_buffer_group_t() { }
void add_buffer(size_t s, const void *d) {
buffer_t b;
b.size = s;
b.data = d;
buffers_.push_back(b);
}
size_t num_buffers() const { return buffers_.size(); }
buffer_t get_buffer(size_t i) const {
rassert(i < buffers_.size());
return buffers_[i];
}
size_t get_size() const {
size_t s = 0;
for (size_t i = 0; i < buffers_.size(); ++i) {
s += buffers_[i].size;
}
return s;
}
// TODO: Get rid of this overengineered crap.
class iterator {
private:
std::vector<buffer_t>::iterator it;
ssize_t offset;
friend class const_buffer_group_t;
iterator(std::vector<buffer_t>::iterator _it, ssize_t _offset)
: it(_it), offset(_offset)
{ }
public:
char operator*() {
rassert(offset < it->size);
return *(reinterpret_cast<const char *>(it->data) + offset);
}
iterator operator++() {
rassert(offset < it->size);
offset++;
if (offset == it->size) {
it++;
offset = 0;
}
return *this;
}
bool operator==(iterator const &other) {
return it == other.it && offset == other.offset;
}
bool operator!=(iterator const &other) {
return !operator==(other);
}
};
iterator begin() {
return iterator(buffers_.begin(), 0);
}
iterator end() {
return iterator(buffers_.end(), 0);
}
private:
std::vector<buffer_t> buffers_;
DISABLE_COPYING(const_buffer_group_t);
public:
void print() {
printf("Buffer group with %zu buffers\n", buffers_.size());
for (std::vector<buffer_t>::const_iterator it = buffers_.begin(); it != buffers_.end(); ++it) {
fprintf(stderr, "-- Buffer %ld --\n", it - buffers_.begin());
print_hd(it->data, 0, it->size);
}
}
};
class buffer_group_t {
public:
struct buffer_t {
ssize_t size;
void *data;
};
buffer_group_t() { }
void add_buffer(size_t s, const void *d) { inner_.add_buffer(s, d); }
size_t num_buffers() const { return inner_.num_buffers(); }
buffer_t get_buffer(size_t i) const {
rassert(i < inner_.num_buffers());
buffer_t ret;
const_buffer_group_t::buffer_t tmp = inner_.get_buffer(i);
ret.size = tmp.size;
ret.data = const_cast<void *>(tmp.data);
return ret;
}
size_t get_size() const { return inner_.get_size(); }
friend const const_buffer_group_t *const_view(const buffer_group_t *group);
const_buffer_group_t::iterator begin() {
return inner_.begin();
}
const_buffer_group_t::iterator end() {
return inner_.end();
}
private:
const_buffer_group_t inner_;
DISABLE_COPYING(buffer_group_t);
public:
void print() {
inner_.print();
}
};
inline const const_buffer_group_t *const_view(const buffer_group_t *group) {
return &group->inner_;
}
/* Copies all the bytes from "in" to "out". "in" and "out" must be the same size. */
void buffer_group_copy_data(const buffer_group_t *out, const const_buffer_group_t *in);
void buffer_group_copy_data(const buffer_group_t *out, const char *in, int64_t size);
#endif // CONTAINERS_BUFFER_GROUP_HPP_
<commit_msg>Removed the overengineered buffer_group_t::iterator type which fortunately was also unused.<commit_after>#ifndef CONTAINERS_BUFFER_GROUP_HPP_
#define CONTAINERS_BUFFER_GROUP_HPP_
#include <stdlib.h>
#include <vector>
#include "utils.hpp"
class const_buffer_group_t {
public:
struct buffer_t {
ssize_t size;
const void *data;
};
const_buffer_group_t() { }
void add_buffer(size_t s, const void *d) {
buffer_t b;
b.size = s;
b.data = d;
buffers_.push_back(b);
}
size_t num_buffers() const { return buffers_.size(); }
buffer_t get_buffer(size_t i) const {
rassert(i < buffers_.size());
return buffers_[i];
}
size_t get_size() const {
size_t s = 0;
for (size_t i = 0; i < buffers_.size(); ++i) {
s += buffers_[i].size;
}
return s;
}
private:
std::vector<buffer_t> buffers_;
DISABLE_COPYING(const_buffer_group_t);
public:
void print() {
printf("Buffer group with %zu buffers\n", buffers_.size());
for (std::vector<buffer_t>::const_iterator it = buffers_.begin(); it != buffers_.end(); ++it) {
fprintf(stderr, "-- Buffer %ld --\n", it - buffers_.begin());
print_hd(it->data, 0, it->size);
}
}
};
class buffer_group_t {
public:
struct buffer_t {
ssize_t size;
void *data;
};
buffer_group_t() { }
void add_buffer(size_t s, const void *d) { inner_.add_buffer(s, d); }
size_t num_buffers() const { return inner_.num_buffers(); }
buffer_t get_buffer(size_t i) const {
rassert(i < inner_.num_buffers());
buffer_t ret;
const_buffer_group_t::buffer_t tmp = inner_.get_buffer(i);
ret.size = tmp.size;
ret.data = const_cast<void *>(tmp.data);
return ret;
}
size_t get_size() const { return inner_.get_size(); }
friend const const_buffer_group_t *const_view(const buffer_group_t *group);
private:
const_buffer_group_t inner_;
DISABLE_COPYING(buffer_group_t);
public:
void print() {
inner_.print();
}
};
inline const const_buffer_group_t *const_view(const buffer_group_t *group) {
return &group->inner_;
}
/* Copies all the bytes from "in" to "out". "in" and "out" must be the same size. */
void buffer_group_copy_data(const buffer_group_t *out, const const_buffer_group_t *in);
void buffer_group_copy_data(const buffer_group_t *out, const char *in, int64_t size);
#endif // CONTAINERS_BUFFER_GROUP_HPP_
<|endoftext|> |
<commit_before>/*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "test_runner.h"
#include "tests.h"
#include <botan/version.h>
#include <botan/rotate.h>
#include <botan/loadstor.h>
namespace Botan_Tests {
Test_Runner::Test_Runner(std::ostream& out) : m_output(out) {}
namespace {
/*
* This is a fast, simple, deterministic PRNG that's used for running
* the tests. It is not intended to be cryptographically secure.
*/
class Testsuite_RNG final : public Botan::RandomNumberGenerator
{
public:
std::string name() const override { return "Testsuite_RNG"; }
void clear() override
{
m_a = m_b = m_c = m_d = 0;
}
void add_entropy(const uint8_t data[], size_t len) override
{
for(size_t i = 0; i != len; ++i)
{
m_a ^= data[i];
m_b ^= i;
mix();
}
}
bool is_seeded() const override
{
return true;
}
void randomize(uint8_t out[], size_t len) override
{
for(size_t i = 0; i != len; ++i)
{
out[i] = static_cast<uint8_t>(m_a);
mix();
}
}
Testsuite_RNG(const std::vector<uint8_t>& seed, size_t test_counter = 0)
{
m_d = static_cast<uint32_t>(test_counter);
add_entropy(seed.data(), seed.size());
}
private:
void mix()
{
const size_t ROUNDS = 3;
for(size_t i = 0; i != ROUNDS; ++i)
{
m_a += i;
m_a = Botan::rotl<9>(m_a);
m_b ^= m_a;
m_d ^= m_c;
m_a += m_d;
m_c += m_b;
m_c = Botan::rotl<23>(m_c);
}
}
uint32_t m_a = 0, m_b = 0, m_c = 0, m_d = 0;
};
}
int Test_Runner::run(const std::vector<std::string>& requested_tests,
const std::string& data_dir,
const std::string& pkcs11_lib,
const std::string& provider,
bool log_success,
bool run_online_tests,
bool run_long_tests,
const std::string& drbg_seed,
size_t runs)
{
std::vector<std::string> req = requested_tests;
if(req.empty())
{
/*
If nothing was requested on the command line, run everything. First
run the "essentials" to smoke test, then everything else in
alphabetical order.
*/
req = {"block", "stream", "hash", "mac", "modes", "aead"
"kdf", "pbkdf", "hmac_drbg", "util"
};
std::set<std::string> all_others = Botan_Tests::Test::registered_tests();
if(pkcs11_lib.empty())
{
// do not run pkcs11 tests by default unless pkcs11-lib set
for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();)
{
if((*iter).find("pkcs11") != std::string::npos)
{
iter = all_others.erase(iter);
}
else
{
++iter;
}
}
}
for(auto f : req)
{
all_others.erase(f);
}
req.insert(req.end(), all_others.begin(), all_others.end());
}
else if(req.size() == 1 && req.at(0) == "pkcs11")
{
req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa",
"pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509"
};
}
else
{
std::set<std::string> all = Botan_Tests::Test::registered_tests();
for(auto const& r : req)
{
if(all.find(r) == all.end())
{
throw Botan_Tests::Test_Error("Unknown test suite: " + r);
}
}
}
output() << "Testing " << Botan::version_string() << "\n";
output() << "Starting tests";
if(!pkcs11_lib.empty())
{
output() << " pkcs11 library:" << pkcs11_lib;
}
Botan_Tests::Provider_Filter pf;
if(!provider.empty())
{
output() << " provider:" << provider;
pf.set(provider);
}
std::vector<uint8_t> seed = Botan::hex_decode(drbg_seed);
if(seed.empty())
{
const uint64_t ts = Botan_Tests::Test::timestamp();
seed.resize(8);
Botan::store_be(ts, seed.data());
}
output() << " drbg_seed:" << Botan::hex_encode(seed) << "\n";
Botan_Tests::Test::set_test_options(log_success,
run_online_tests,
run_long_tests,
data_dir,
pkcs11_lib,
pf);
for(size_t i = 0; i != runs; ++i)
{
std::unique_ptr<Botan::RandomNumberGenerator> rng =
std::unique_ptr<Botan::RandomNumberGenerator>(new Testsuite_RNG(seed, i));
Botan_Tests::Test::set_test_rng(std::move(rng));
const size_t failed = run_tests(req, i, runs);
if(failed > 0)
return failed;
}
return 0;
}
namespace {
std::string report_out(const std::vector<Botan_Tests::Test::Result>& results,
size_t& tests_failed,
size_t& tests_ran)
{
std::ostringstream out;
std::map<std::string, Botan_Tests::Test::Result> combined;
for(auto const& result : results)
{
const std::string who = result.who();
auto i = combined.find(who);
if(i == combined.end())
{
combined.insert(std::make_pair(who, Botan_Tests::Test::Result(who)));
i = combined.find(who);
}
i->second.merge(result);
}
for(auto const& result : combined)
{
const bool verbose = false;
out << result.second.result_string(verbose);
tests_failed += result.second.tests_failed();
tests_ran += result.second.tests_run();
}
return out.str();
}
}
size_t Test_Runner::run_tests(const std::vector<std::string>& tests_to_run,
size_t test_run,
size_t tot_test_runs)
{
size_t tests_ran = 0, tests_failed = 0;
const uint64_t start_time = Botan_Tests::Test::timestamp();
for(auto const& test_name : tests_to_run)
{
output() << test_name << ':' << std::endl;
std::vector<Test::Result> results;
try
{
if(Test* test = Test::get_test(test_name))
{
std::vector<Test::Result> test_results = test->run();
results.insert(results.end(), test_results.begin(), test_results.end());
}
else
{
results.push_back(Test::Result::Note(test_name, "Test missing or unavailable"));
}
}
catch(std::exception& e)
{
results.push_back(Test::Result::Failure(test_name, e.what()));
}
catch(...)
{
results.push_back(Test::Result::Failure(test_name, "unknown exception"));
}
output() << report_out(results, tests_failed, tests_ran) << std::flush;
}
const uint64_t total_ns = Botan_Tests::Test::timestamp() - start_time;
if(test_run == 0 && tot_test_runs == 1)
output() << "Tests";
else
output() << "Test run " << (1+test_run) << "/" << tot_test_runs;
output() << " complete ran " << tests_ran << " tests in "
<< Botan_Tests::Test::format_time(total_ns) << " ";
if(tests_failed > 0)
{
output() << tests_failed << " tests failed";
}
else if(tests_ran > 0)
{
output() << "all tests ok";
}
output() << std::endl;
return tests_failed;
}
}
<commit_msg>Fix missing comma in test runner [ci skip]<commit_after>/*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "test_runner.h"
#include "tests.h"
#include <botan/version.h>
#include <botan/rotate.h>
#include <botan/loadstor.h>
namespace Botan_Tests {
Test_Runner::Test_Runner(std::ostream& out) : m_output(out) {}
namespace {
/*
* This is a fast, simple, deterministic PRNG that's used for running
* the tests. It is not intended to be cryptographically secure.
*/
class Testsuite_RNG final : public Botan::RandomNumberGenerator
{
public:
std::string name() const override { return "Testsuite_RNG"; }
void clear() override
{
m_a = m_b = m_c = m_d = 0;
}
void add_entropy(const uint8_t data[], size_t len) override
{
for(size_t i = 0; i != len; ++i)
{
m_a ^= data[i];
m_b ^= i;
mix();
}
}
bool is_seeded() const override
{
return true;
}
void randomize(uint8_t out[], size_t len) override
{
for(size_t i = 0; i != len; ++i)
{
out[i] = static_cast<uint8_t>(m_a);
mix();
}
}
Testsuite_RNG(const std::vector<uint8_t>& seed, size_t test_counter = 0)
{
m_d = static_cast<uint32_t>(test_counter);
add_entropy(seed.data(), seed.size());
}
private:
void mix()
{
const size_t ROUNDS = 3;
for(size_t i = 0; i != ROUNDS; ++i)
{
m_a += i;
m_a = Botan::rotl<9>(m_a);
m_b ^= m_a;
m_d ^= m_c;
m_a += m_d;
m_c += m_b;
m_c = Botan::rotl<23>(m_c);
}
}
uint32_t m_a = 0, m_b = 0, m_c = 0, m_d = 0;
};
}
int Test_Runner::run(const std::vector<std::string>& requested_tests,
const std::string& data_dir,
const std::string& pkcs11_lib,
const std::string& provider,
bool log_success,
bool run_online_tests,
bool run_long_tests,
const std::string& drbg_seed,
size_t runs)
{
std::vector<std::string> req = requested_tests;
if(req.empty())
{
/*
If nothing was requested on the command line, run everything. First
run the "essentials" to smoke test, then everything else in
alphabetical order.
*/
req = {"block", "stream", "hash", "mac", "modes", "aead",
"kdf", "pbkdf", "hmac_drbg", "util"
};
std::set<std::string> all_others = Botan_Tests::Test::registered_tests();
if(pkcs11_lib.empty())
{
// do not run pkcs11 tests by default unless pkcs11-lib set
for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();)
{
if((*iter).find("pkcs11") != std::string::npos)
{
iter = all_others.erase(iter);
}
else
{
++iter;
}
}
}
for(auto f : req)
{
all_others.erase(f);
}
req.insert(req.end(), all_others.begin(), all_others.end());
}
else if(req.size() == 1 && req.at(0) == "pkcs11")
{
req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa",
"pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509"
};
}
else
{
std::set<std::string> all = Botan_Tests::Test::registered_tests();
for(auto const& r : req)
{
if(all.find(r) == all.end())
{
throw Botan_Tests::Test_Error("Unknown test suite: " + r);
}
}
}
output() << "Testing " << Botan::version_string() << "\n";
output() << "Starting tests";
if(!pkcs11_lib.empty())
{
output() << " pkcs11 library:" << pkcs11_lib;
}
Botan_Tests::Provider_Filter pf;
if(!provider.empty())
{
output() << " provider:" << provider;
pf.set(provider);
}
std::vector<uint8_t> seed = Botan::hex_decode(drbg_seed);
if(seed.empty())
{
const uint64_t ts = Botan_Tests::Test::timestamp();
seed.resize(8);
Botan::store_be(ts, seed.data());
}
output() << " drbg_seed:" << Botan::hex_encode(seed) << "\n";
Botan_Tests::Test::set_test_options(log_success,
run_online_tests,
run_long_tests,
data_dir,
pkcs11_lib,
pf);
for(size_t i = 0; i != runs; ++i)
{
std::unique_ptr<Botan::RandomNumberGenerator> rng =
std::unique_ptr<Botan::RandomNumberGenerator>(new Testsuite_RNG(seed, i));
Botan_Tests::Test::set_test_rng(std::move(rng));
const size_t failed = run_tests(req, i, runs);
if(failed > 0)
return failed;
}
return 0;
}
namespace {
std::string report_out(const std::vector<Botan_Tests::Test::Result>& results,
size_t& tests_failed,
size_t& tests_ran)
{
std::ostringstream out;
std::map<std::string, Botan_Tests::Test::Result> combined;
for(auto const& result : results)
{
const std::string who = result.who();
auto i = combined.find(who);
if(i == combined.end())
{
combined.insert(std::make_pair(who, Botan_Tests::Test::Result(who)));
i = combined.find(who);
}
i->second.merge(result);
}
for(auto const& result : combined)
{
const bool verbose = false;
out << result.second.result_string(verbose);
tests_failed += result.second.tests_failed();
tests_ran += result.second.tests_run();
}
return out.str();
}
}
size_t Test_Runner::run_tests(const std::vector<std::string>& tests_to_run,
size_t test_run,
size_t tot_test_runs)
{
size_t tests_ran = 0, tests_failed = 0;
const uint64_t start_time = Botan_Tests::Test::timestamp();
for(auto const& test_name : tests_to_run)
{
output() << test_name << ':' << std::endl;
std::vector<Test::Result> results;
try
{
if(Test* test = Test::get_test(test_name))
{
std::vector<Test::Result> test_results = test->run();
results.insert(results.end(), test_results.begin(), test_results.end());
}
else
{
results.push_back(Test::Result::Note(test_name, "Test missing or unavailable"));
}
}
catch(std::exception& e)
{
results.push_back(Test::Result::Failure(test_name, e.what()));
}
catch(...)
{
results.push_back(Test::Result::Failure(test_name, "unknown exception"));
}
output() << report_out(results, tests_failed, tests_ran) << std::flush;
}
const uint64_t total_ns = Botan_Tests::Test::timestamp() - start_time;
if(test_run == 0 && tot_test_runs == 1)
output() << "Tests";
else
output() << "Test run " << (1+test_run) << "/" << tot_test_runs;
output() << " complete ran " << tests_ran << " tests in "
<< Botan_Tests::Test::format_time(total_ns) << " ";
if(tests_failed > 0)
{
output() << tests_failed << " tests failed";
}
else if(tests_ran > 0)
{
output() << "all tests ok";
}
output() << std::endl;
return tests_failed;
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkColorPriv.h"
#include "SkFlattenableBuffers.h"
#include "SkPixelRef.h"
bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {
switch (bm.config()) {
case SkBitmap::kA8_Config:
case SkBitmap::kRGB_565_Config:
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
// if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))
return true;
default:
break;
}
return false;
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
fRawBitmap = src;
fState.fTileModeX = (uint8_t)tmx;
fState.fTileModeY = (uint8_t)tmy;
fFlags = 0; // computed in setContext
}
SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
buffer.readBitmap(&fRawBitmap);
fRawBitmap.setImmutable();
fState.fTileModeX = buffer.readUInt();
fState.fTileModeY = buffer.readUInt();
fFlags = 0; // computed in setContext
}
SkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,
SkMatrix* texM,
TileMode xy[]) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fState.fTileModeX;
xy[1] = (TileMode)fState.fTileModeY;
}
return kDefault_BitmapType;
}
void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeBitmap(fRawBitmap);
buffer.writeUInt(fState.fTileModeX);
buffer.writeUInt(fState.fTileModeY);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
bool SkBitmapProcShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
// do this first, so we have a correct inverse matrix
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
fState.fOrigBitmap = fRawBitmap;
fState.fOrigBitmap.lockPixels();
if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {
fState.fOrigBitmap.unlockPixels();
return false;
}
if (!fState.chooseProcs(this->getTotalInverse(), paint)) {
fState.fOrigBitmap.unlockPixels();
return false;
}
const SkBitmap& bitmap = *fState.fBitmap;
bool bitmapIsOpaque = bitmap.isOpaque();
// update fFlags
uint32_t flags = 0;
if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {
flags |= kOpaqueAlpha_Flag;
}
switch (bitmap.config()) {
case SkBitmap::kRGB_565_Config:
flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
if (bitmapIsOpaque) {
flags |= kHasSpan16_Flag;
}
break;
case SkBitmap::kA8_Config:
break; // never set kHasSpan16_Flag
default:
break;
}
if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {
// gradients can auto-dither in their 16bit sampler, but we don't so
// we clear the flag here.
flags &= ~kHasSpan16_Flag;
}
// if we're only 1-pixel heigh, and we don't rotate, then we can claim this
if (1 == bitmap.height() &&
only_scale_and_translate(this->getTotalInverse())) {
flags |= kConstInY32_Flag;
if (flags & kHasSpan16_Flag) {
flags |= kConstInY16_Flag;
}
}
fFlags = flags;
return true;
}
void SkBitmapProcShader::endContext() {
fState.fOrigBitmap.unlockPixels();
this->INHERITED::endContext();
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc32()) {
state.getShaderProc32()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();
int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
SkShader::ShadeProc SkBitmapProcShader::asAShadeProc(void** ctx) {
if (fState.getShaderProc32()) {
*ctx = &fState;
return (ShadeProc)fState.getShaderProc32();
}
return NULL;
}
void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc16()) {
state.getShaderProc16()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc16 sproc = state.getSampleProc16();
int max = fState.maxCountForBufferSize(sizeof(buffer));
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
mproc(state, buffer, n, x, y);
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
x += n;
dstC += n;
}
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool canUseColorShader(const SkBitmap& bm, SkColor* color) {
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.config()) {
case SkBitmap::kARGB_8888_Config:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case SkBitmap::kRGB_565_Config:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case SkBitmap::kIndex8_Config:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
#include "SkTemplatesPriv.h"
static bool bitmapIsTooBig(const SkBitmap& bm) {
// SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
// communicates between its matrix-proc and its sampler-proc. Until we can
// widen that, we have to reject bitmaps that are larger.
//
const int maxSize = 65535;
return bm.width() > maxSize || bm.height() > maxSize;
}
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy,
void* storage, size_t storageSize) {
SkShader* shader;
SkColor color;
if (src.isNull() || bitmapIsTooBig(src)) {
SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);
}
else if (canUseColorShader(src, &color)) {
SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,
(color));
} else {
SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,
storageSize, (src, tmx, tmy));
}
return shader;
}
///////////////////////////////////////////////////////////////////////////////
static const char* gTileModeName[] = {
"clamp", "repeat", "mirror"
};
bool SkBitmapProcShader::toDumpString(SkString* str) const {
str->printf("BitmapShader: [%d %d %d",
fRawBitmap.width(), fRawBitmap.height(),
fRawBitmap.bytesPerPixel());
// add the pixelref
SkPixelRef* pr = fRawBitmap.pixelRef();
if (pr) {
const char* uri = pr->getURI();
if (uri) {
str->appendf(" \"%s\"", uri);
}
}
// add the (optional) matrix
{
if (this->hasLocalMatrix()) {
SkString info;
this->getLocalMatrix().toDumpString(&info);
str->appendf(" %s", info.c_str());
}
}
str->appendf(" [%s %s]]",
gTileModeName[fState.fTileModeX],
gTileModeName[fState.fTileModeY]);
return true;
}
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "GrTextureAccess.h"
#include "effects/GrSingleTextureEffect.h"
#include "SkGr.h"
GrEffect* SkBitmapProcShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
SkMatrix matrix;
matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());
if (this->hasLocalMatrix()) {
SkMatrix inverse;
if (!this->getLocalMatrix().invert(&inverse)) {
return false;
}
matrix.preConcat(inverse);
}
SkShader::TileMode tm[] = {
(TileMode)fState.fTileModeX,
(TileMode)fState.fTileModeY,
};
// Must set wrap and filter on the sampler before requesting a texture.
GrTextureParams params(tm, paint.isFilterBitmap());
GrTexture* texture = GrLockCachedBitmapTexture(context, fRawBitmap, ¶ms);
if (NULL == texture) {
SkDebugf("Couldn't convert bitmap to texture.\n");
return NULL;
}
GrEffect* effect = SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, params));
GrUnlockCachedBitmapTexture(texture);
return effect;
}
#endif
<commit_msg>false --> NULL for failure return<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkColorPriv.h"
#include "SkFlattenableBuffers.h"
#include "SkPixelRef.h"
bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {
switch (bm.config()) {
case SkBitmap::kA8_Config:
case SkBitmap::kRGB_565_Config:
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
// if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))
return true;
default:
break;
}
return false;
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
fRawBitmap = src;
fState.fTileModeX = (uint8_t)tmx;
fState.fTileModeY = (uint8_t)tmy;
fFlags = 0; // computed in setContext
}
SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
buffer.readBitmap(&fRawBitmap);
fRawBitmap.setImmutable();
fState.fTileModeX = buffer.readUInt();
fState.fTileModeY = buffer.readUInt();
fFlags = 0; // computed in setContext
}
SkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,
SkMatrix* texM,
TileMode xy[]) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fState.fTileModeX;
xy[1] = (TileMode)fState.fTileModeY;
}
return kDefault_BitmapType;
}
void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeBitmap(fRawBitmap);
buffer.writeUInt(fState.fTileModeX);
buffer.writeUInt(fState.fTileModeY);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
bool SkBitmapProcShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
// do this first, so we have a correct inverse matrix
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
fState.fOrigBitmap = fRawBitmap;
fState.fOrigBitmap.lockPixels();
if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {
fState.fOrigBitmap.unlockPixels();
return false;
}
if (!fState.chooseProcs(this->getTotalInverse(), paint)) {
fState.fOrigBitmap.unlockPixels();
return false;
}
const SkBitmap& bitmap = *fState.fBitmap;
bool bitmapIsOpaque = bitmap.isOpaque();
// update fFlags
uint32_t flags = 0;
if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {
flags |= kOpaqueAlpha_Flag;
}
switch (bitmap.config()) {
case SkBitmap::kRGB_565_Config:
flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
if (bitmapIsOpaque) {
flags |= kHasSpan16_Flag;
}
break;
case SkBitmap::kA8_Config:
break; // never set kHasSpan16_Flag
default:
break;
}
if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {
// gradients can auto-dither in their 16bit sampler, but we don't so
// we clear the flag here.
flags &= ~kHasSpan16_Flag;
}
// if we're only 1-pixel heigh, and we don't rotate, then we can claim this
if (1 == bitmap.height() &&
only_scale_and_translate(this->getTotalInverse())) {
flags |= kConstInY32_Flag;
if (flags & kHasSpan16_Flag) {
flags |= kConstInY16_Flag;
}
}
fFlags = flags;
return true;
}
void SkBitmapProcShader::endContext() {
fState.fOrigBitmap.unlockPixels();
this->INHERITED::endContext();
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc32()) {
state.getShaderProc32()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();
int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
SkShader::ShadeProc SkBitmapProcShader::asAShadeProc(void** ctx) {
if (fState.getShaderProc32()) {
*ctx = &fState;
return (ShadeProc)fState.getShaderProc32();
}
return NULL;
}
void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.getShaderProc16()) {
state.getShaderProc16()(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX];
SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();
SkBitmapProcState::SampleProc16 sproc = state.getSampleProc16();
int max = fState.maxCountForBufferSize(sizeof(buffer));
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
mproc(state, buffer, n, x, y);
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
x += n;
dstC += n;
}
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool canUseColorShader(const SkBitmap& bm, SkColor* color) {
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.config()) {
case SkBitmap::kARGB_8888_Config:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case SkBitmap::kRGB_565_Config:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case SkBitmap::kIndex8_Config:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
#include "SkTemplatesPriv.h"
static bool bitmapIsTooBig(const SkBitmap& bm) {
// SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it
// communicates between its matrix-proc and its sampler-proc. Until we can
// widen that, we have to reject bitmaps that are larger.
//
const int maxSize = 65535;
return bm.width() > maxSize || bm.height() > maxSize;
}
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy,
void* storage, size_t storageSize) {
SkShader* shader;
SkColor color;
if (src.isNull() || bitmapIsTooBig(src)) {
SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);
}
else if (canUseColorShader(src, &color)) {
SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,
(color));
} else {
SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,
storageSize, (src, tmx, tmy));
}
return shader;
}
///////////////////////////////////////////////////////////////////////////////
static const char* gTileModeName[] = {
"clamp", "repeat", "mirror"
};
bool SkBitmapProcShader::toDumpString(SkString* str) const {
str->printf("BitmapShader: [%d %d %d",
fRawBitmap.width(), fRawBitmap.height(),
fRawBitmap.bytesPerPixel());
// add the pixelref
SkPixelRef* pr = fRawBitmap.pixelRef();
if (pr) {
const char* uri = pr->getURI();
if (uri) {
str->appendf(" \"%s\"", uri);
}
}
// add the (optional) matrix
{
if (this->hasLocalMatrix()) {
SkString info;
this->getLocalMatrix().toDumpString(&info);
str->appendf(" %s", info.c_str());
}
}
str->appendf(" [%s %s]]",
gTileModeName[fState.fTileModeX],
gTileModeName[fState.fTileModeY]);
return true;
}
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
#include "GrTextureAccess.h"
#include "effects/GrSingleTextureEffect.h"
#include "SkGr.h"
GrEffect* SkBitmapProcShader::asNewEffect(GrContext* context, const SkPaint& paint) const {
SkMatrix matrix;
matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());
if (this->hasLocalMatrix()) {
SkMatrix inverse;
if (!this->getLocalMatrix().invert(&inverse)) {
return NULL;
}
matrix.preConcat(inverse);
}
SkShader::TileMode tm[] = {
(TileMode)fState.fTileModeX,
(TileMode)fState.fTileModeY,
};
// Must set wrap and filter on the sampler before requesting a texture.
GrTextureParams params(tm, paint.isFilterBitmap());
GrTexture* texture = GrLockCachedBitmapTexture(context, fRawBitmap, ¶ms);
if (NULL == texture) {
SkDebugf("Couldn't convert bitmap to texture.\n");
return NULL;
}
GrEffect* effect = SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, params));
GrUnlockCachedBitmapTexture(texture);
return effect;
}
#endif
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkColorPriv.h"
#include "SkPixelRef.h"
bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {
switch (bm.config()) {
case SkBitmap::kA8_Config:
case SkBitmap::kRGB_565_Config:
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
// if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))
return true;
default:
break;
}
return false;
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
fRawBitmap = src;
fState.fTileModeX = (uint8_t)tmx;
fState.fTileModeY = (uint8_t)tmy;
fFlags = 0; // computed in setContext
}
SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fRawBitmap.unflatten(buffer);
fState.fTileModeX = buffer.readU8();
fState.fTileModeY = buffer.readU8();
fFlags = 0; // computed in setContext
}
void SkBitmapProcShader::beginSession() {
this->INHERITED::beginSession();
fRawBitmap.lockPixels();
}
void SkBitmapProcShader::endSession() {
fRawBitmap.unlockPixels();
this->INHERITED::endSession();
}
SkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,
SkMatrix* texM,
TileMode xy[],
SkScalar* twoPointRadialParams) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fState.fTileModeX;
xy[1] = (TileMode)fState.fTileModeY;
}
return kDefault_BitmapType;
}
void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
fRawBitmap.flatten(buffer);
buffer.write8(fState.fTileModeX);
buffer.write8(fState.fTileModeY);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
bool SkBitmapProcShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
// do this first, so we have a correct inverse matrix
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
fState.fOrigBitmap = fRawBitmap;
fState.fOrigBitmap.lockPixels();
if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {
fState.fOrigBitmap.unlockPixels();
return false;
}
if (!fState.chooseProcs(this->getTotalInverse(), paint)) {
return false;
}
const SkBitmap& bitmap = *fState.fBitmap;
bool bitmapIsOpaque = bitmap.isOpaque();
// update fFlags
uint32_t flags = 0;
if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {
flags |= kOpaqueAlpha_Flag;
}
switch (bitmap.config()) {
case SkBitmap::kRGB_565_Config:
flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
if (bitmapIsOpaque) {
flags |= kHasSpan16_Flag;
}
break;
case SkBitmap::kA8_Config:
break; // never set kHasSpan16_Flag
default:
break;
}
if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {
// gradients can auto-dither in their 16bit sampler, but we don't so
// we clear the flag here.
flags &= ~kHasSpan16_Flag;
}
// if we're only 1-pixel heigh, and we don't rotate, then we can claim this
if (1 == bitmap.height() &&
only_scale_and_translate(this->getTotalInverse())) {
flags |= kConstInY32_Flag;
if (flags & kHasSpan16_Flag) {
flags |= kConstInY16_Flag;
}
}
fFlags = flags;
return true;
}
#define BUF_MAX 128
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
#if defined(__ARM_HAVE_NEON)
void clampx_nofilter_trans(const SkBitmapProcState& s,
uint32_t xy[], int count, int x, int y) ;
void S16_opaque_D32_nofilter_DX(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, uint32_t* SK_RESTRICT colors) ;
void clampx_nofilter_trans_S16_D32_DX(const SkBitmapProcState& s,
uint32_t xy[], int count, int x, int y, uint32_t* SK_RESTRICT colors) ;
#endif
void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.fShaderProc32) {
state.fShaderProc32(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.fMatrixProc;
SkBitmapProcState::SampleProc32 sproc = state.fSampleProc32;
int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#if defined(__ARM_HAVE_NEON)
if( sproc == S16_opaque_D32_nofilter_DX && mproc == clampx_nofilter_trans ){
clampx_nofilter_trans_S16_D32_DX(state, buffer, n, x, y, dstC);
} else {
#endif
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
#if defined(__ARM_HAVE_NEON)
}
#endif
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.fShaderProc16) {
state.fShaderProc16(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX];
SkBitmapProcState::MatrixProc mproc = state.fMatrixProc;
SkBitmapProcState::SampleProc16 sproc = state.fSampleProc16;
int max = fState.maxCountForBufferSize(sizeof(buffer));
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
mproc(state, buffer, n, x, y);
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
x += n;
dstC += n;
}
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool canUseColorShader(const SkBitmap& bm, SkColor* color) {
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.config()) {
case SkBitmap::kARGB_8888_Config:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case SkBitmap::kRGB_565_Config:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case SkBitmap::kIndex8_Config:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
#include "SkTemplatesPriv.h"
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy,
void* storage, size_t storageSize) {
SkShader* shader;
SkColor color;
if (src.isNull()) {
SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);
}
else if (canUseColorShader(src, &color)) {
SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,
(color));
} else {
SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,
storageSize, (src, tmx, tmy));
}
return shader;
}
SK_DEFINE_FLATTENABLE_REGISTRAR(SkBitmapProcShader)
///////////////////////////////////////////////////////////////////////////////
static const char* gTileModeName[] = {
"clamp", "repeat", "mirror"
};
bool SkBitmapProcShader::toDumpString(SkString* str) const {
str->printf("BitmapShader: [%d %d %d",
fRawBitmap.width(), fRawBitmap.height(),
fRawBitmap.bytesPerPixel());
// add the pixelref
SkPixelRef* pr = fRawBitmap.pixelRef();
if (pr) {
const char* uri = pr->getURI();
if (uri) {
str->appendf(" \"%s\"", uri);
}
}
// add the (optional) matrix
{
SkMatrix m;
if (this->getLocalMatrix(&m)) {
SkString info;
m.toDumpString(&info);
str->appendf(" %s", info.c_str());
}
}
str->appendf(" [%s %s]]",
gTileModeName[fState.fTileModeX],
gTileModeName[fState.fTileModeY]);
return true;
}
<commit_msg>Modify sample buffer size for larger displays.<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcShader.h"
#include "SkColorPriv.h"
#include "SkPixelRef.h"
bool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {
switch (bm.config()) {
case SkBitmap::kA8_Config:
case SkBitmap::kRGB_565_Config:
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
// if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))
return true;
default:
break;
}
return false;
}
SkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,
TileMode tmx, TileMode tmy) {
fRawBitmap = src;
fState.fTileModeX = (uint8_t)tmx;
fState.fTileModeY = (uint8_t)tmy;
fFlags = 0; // computed in setContext
}
SkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fRawBitmap.unflatten(buffer);
fState.fTileModeX = buffer.readU8();
fState.fTileModeY = buffer.readU8();
fFlags = 0; // computed in setContext
}
void SkBitmapProcShader::beginSession() {
this->INHERITED::beginSession();
fRawBitmap.lockPixels();
}
void SkBitmapProcShader::endSession() {
fRawBitmap.unlockPixels();
this->INHERITED::endSession();
}
SkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,
SkMatrix* texM,
TileMode xy[],
SkScalar* twoPointRadialParams) const {
if (texture) {
*texture = fRawBitmap;
}
if (texM) {
texM->reset();
}
if (xy) {
xy[0] = (TileMode)fState.fTileModeX;
xy[1] = (TileMode)fState.fTileModeY;
}
return kDefault_BitmapType;
}
void SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
fRawBitmap.flatten(buffer);
buffer.write8(fState.fTileModeX);
buffer.write8(fState.fTileModeY);
}
static bool only_scale_and_translate(const SkMatrix& matrix) {
unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;
return (matrix.getType() & ~mask) == 0;
}
bool SkBitmapProcShader::isOpaque() const {
return fRawBitmap.isOpaque();
}
bool SkBitmapProcShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
// do this first, so we have a correct inverse matrix
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
fState.fOrigBitmap = fRawBitmap;
fState.fOrigBitmap.lockPixels();
if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {
fState.fOrigBitmap.unlockPixels();
return false;
}
if (!fState.chooseProcs(this->getTotalInverse(), paint)) {
return false;
}
const SkBitmap& bitmap = *fState.fBitmap;
bool bitmapIsOpaque = bitmap.isOpaque();
// update fFlags
uint32_t flags = 0;
if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {
flags |= kOpaqueAlpha_Flag;
}
switch (bitmap.config()) {
case SkBitmap::kRGB_565_Config:
flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);
break;
case SkBitmap::kIndex8_Config:
case SkBitmap::kARGB_8888_Config:
if (bitmapIsOpaque) {
flags |= kHasSpan16_Flag;
}
break;
case SkBitmap::kA8_Config:
break; // never set kHasSpan16_Flag
default:
break;
}
if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {
// gradients can auto-dither in their 16bit sampler, but we don't so
// we clear the flag here.
flags &= ~kHasSpan16_Flag;
}
// if we're only 1-pixel heigh, and we don't rotate, then we can claim this
if (1 == bitmap.height() &&
only_scale_and_translate(this->getTotalInverse())) {
flags |= kConstInY32_Flag;
if (flags & kHasSpan16_Flag) {
flags |= kConstInY16_Flag;
}
}
fFlags = flags;
return true;
}
/* Defines the buffer size for sample pixel indexes, used in the sample proc
* function calls. If the buffer is not large enough, the job is split into
* several calls. This would impact the performance of SIMD optimizations.
* A display with a 720p resolution requires a buffer size of at least 361,
* to run uninterrupted.
*/
#define BUF_MAX 384
#define TEST_BUFFER_OVERRITEx
#ifdef TEST_BUFFER_OVERRITE
#define TEST_BUFFER_EXTRA 32
#define TEST_PATTERN 0x88888888
#else
#define TEST_BUFFER_EXTRA 0
#endif
#if defined(__ARM_HAVE_NEON)
void clampx_nofilter_trans(const SkBitmapProcState& s,
uint32_t xy[], int count, int x, int y) ;
void S16_opaque_D32_nofilter_DX(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, uint32_t* SK_RESTRICT colors) ;
void clampx_nofilter_trans_S16_D32_DX(const SkBitmapProcState& s,
uint32_t xy[], int count, int x, int y, uint32_t* SK_RESTRICT colors) ;
#endif
void SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.fShaderProc32) {
state.fShaderProc32(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];
SkBitmapProcState::MatrixProc mproc = state.fMatrixProc;
SkBitmapProcState::SampleProc32 sproc = state.fSampleProc32;
int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
SkASSERT(n > 0 && n < BUF_MAX*2);
#if defined(__ARM_HAVE_NEON)
if( sproc == S16_opaque_D32_nofilter_DX && mproc == clampx_nofilter_trans ){
clampx_nofilter_trans_S16_D32_DX(state, buffer, n, x, y, dstC);
} else {
#endif
#ifdef TEST_BUFFER_OVERRITE
for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {
buffer[BUF_MAX + i] = TEST_PATTERN;
}
#endif
mproc(state, buffer, n, x, y);
#ifdef TEST_BUFFER_OVERRITE
for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {
SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);
}
#endif
sproc(state, buffer, n, dstC);
#if defined(__ARM_HAVE_NEON)
}
#endif
if ((count -= n) == 0) {
break;
}
SkASSERT(count > 0);
x += n;
dstC += n;
}
}
void SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
const SkBitmapProcState& state = fState;
if (state.fShaderProc16) {
state.fShaderProc16(state, x, y, dstC, count);
return;
}
uint32_t buffer[BUF_MAX];
SkBitmapProcState::MatrixProc mproc = state.fMatrixProc;
SkBitmapProcState::SampleProc16 sproc = state.fSampleProc16;
int max = fState.maxCountForBufferSize(sizeof(buffer));
SkASSERT(state.fBitmap->getPixels());
SkASSERT(state.fBitmap->pixelRef() == NULL ||
state.fBitmap->pixelRef()->isLocked());
for (;;) {
int n = count;
if (n > max) {
n = max;
}
mproc(state, buffer, n, x, y);
sproc(state, buffer, n, dstC);
if ((count -= n) == 0) {
break;
}
x += n;
dstC += n;
}
}
///////////////////////////////////////////////////////////////////////////////
#include "SkUnPreMultiply.h"
#include "SkColorShader.h"
#include "SkEmptyShader.h"
// returns true and set color if the bitmap can be drawn as a single color
// (for efficiency)
static bool canUseColorShader(const SkBitmap& bm, SkColor* color) {
if (1 != bm.width() || 1 != bm.height()) {
return false;
}
SkAutoLockPixels alp(bm);
if (!bm.readyToDraw()) {
return false;
}
switch (bm.config()) {
case SkBitmap::kARGB_8888_Config:
*color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));
return true;
case SkBitmap::kRGB_565_Config:
*color = SkPixel16ToColor(*bm.getAddr16(0, 0));
return true;
case SkBitmap::kIndex8_Config:
*color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));
return true;
default: // just skip the other configs for now
break;
}
return false;
}
#include "SkTemplatesPriv.h"
SkShader* SkShader::CreateBitmapShader(const SkBitmap& src,
TileMode tmx, TileMode tmy,
void* storage, size_t storageSize) {
SkShader* shader;
SkColor color;
if (src.isNull()) {
SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);
}
else if (canUseColorShader(src, &color)) {
SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,
(color));
} else {
SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,
storageSize, (src, tmx, tmy));
}
return shader;
}
SK_DEFINE_FLATTENABLE_REGISTRAR(SkBitmapProcShader)
///////////////////////////////////////////////////////////////////////////////
static const char* gTileModeName[] = {
"clamp", "repeat", "mirror"
};
bool SkBitmapProcShader::toDumpString(SkString* str) const {
str->printf("BitmapShader: [%d %d %d",
fRawBitmap.width(), fRawBitmap.height(),
fRawBitmap.bytesPerPixel());
// add the pixelref
SkPixelRef* pr = fRawBitmap.pixelRef();
if (pr) {
const char* uri = pr->getURI();
if (uri) {
str->appendf(" \"%s\"", uri);
}
}
// add the (optional) matrix
{
SkMatrix m;
if (this->getLocalMatrix(&m)) {
SkString info;
m.toDumpString(&info);
str->appendf(" %s", info.c_str());
}
}
str->appendf(" [%s %s]]",
gTileModeName[fState.fTileModeX],
gTileModeName[fState.fTileModeY]);
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 offa
//
// 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 "danek/internal/ToString.h"
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include "danek/internal/UidIdentifierProcessor.h"
#include <algorithm>
#include <iterator>
#include <sstream>
namespace danek
{
namespace
{
std::string indent(std::size_t level)
{
constexpr std::size_t indentCount = 4;
return std::string(level * indentCount, ' ');
}
void replaceInplace(std::string& input, const std::string& str, const std::string& replacement)
{
if( str.empty() == false )
{
std::size_t pos = 0;
while( ( pos = input.find(str, pos) ) != std::string::npos )
{
input.replace(pos, str.size(), replacement);
pos += replacement.size();
}
}
}
std::string escape(const std::string& str)
{
auto output = str;
replaceInplace(output, "%", "%%");
replaceInplace(output, "\t", "%t");
replaceInplace(output, "\n", "%n");
replaceInplace(output, "\"", "%\"");
return "\"" + output + "\"";
}
std::string expandUid(const std::string& name, bool expand)
{
if( expand == false )
{
UidIdentifierProcessor uidIdProc;
StringBuffer nameBuf;
return uidIdProc.unexpand(name.c_str(), nameBuf);
}
return name;
}
void appendConfType(std::stringstream& stream, const ConfigScope& scope, ConfType type, bool expandUid, std::size_t indentLevel)
{
auto names = scope.listLocallyScopedNames(type, false, { });
std::sort(names.begin(), names.end());
for( std::size_t i=0; i<names.size(); ++i )
{
const auto item = scope.findItem(names[i]);
stream << toString(*item, item->name(), expandUid, indentLevel);
}
}
}
std::string toString(const ConfigItem& item, const std::string& name, bool expandUidNames, std::size_t indentLevel)
{
const std::string nameStr = expandUid(name, expandUidNames);
std::stringstream os;
os << indent(indentLevel);
switch(item.type())
{
case ConfType::String:
os << nameStr << " = " << escape(item.stringVal()) << ";\n";
break;
case ConfType::List:
{
os << nameStr << " = [";
const auto values = item.listVal();
if( values.empty() == false )
{
using OItr = std::ostream_iterator<std::string>;
std::transform(values.cbegin(), std::prev(values.cend()), OItr{os, ", "}, escape);
std::transform(std::prev(values.cend()), values.cend(), OItr{os}, escape);
}
os << "];\n";
}
break;
case ConfType::Scope:
{
os << nameStr << " {\n";
StringBuffer buffer;
os << toString(*(item.scopeVal()), expandUidNames, indentLevel + 1);
//item.scopeVal()->dump(buffer, expandUidNames, indentLevel + 1);
os << indent(indentLevel) << buffer.str() << "}\n";
}
break;
default:
break;
}
return os.str();
}
std::string toString(const ConfigScope& scope, bool expandUidNames, std::size_t indentLevel)
{
std::stringstream ss;
appendConfType(ss, scope, ConfType::Variables, expandUidNames, indentLevel);
appendConfType(ss, scope, ConfType::Scope, expandUidNames, indentLevel);
return ss.str();
}
}
<commit_msg>Commented out code removed.<commit_after>// Copyright (c) 2017 offa
//
// 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 "danek/internal/ToString.h"
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include "danek/internal/UidIdentifierProcessor.h"
#include <algorithm>
#include <iterator>
#include <sstream>
namespace danek
{
namespace
{
std::string indent(std::size_t level)
{
constexpr std::size_t indentCount = 4;
return std::string(level * indentCount, ' ');
}
void replaceInplace(std::string& input, const std::string& str, const std::string& replacement)
{
if( str.empty() == false )
{
std::size_t pos = 0;
while( ( pos = input.find(str, pos) ) != std::string::npos )
{
input.replace(pos, str.size(), replacement);
pos += replacement.size();
}
}
}
std::string escape(const std::string& str)
{
auto output = str;
replaceInplace(output, "%", "%%");
replaceInplace(output, "\t", "%t");
replaceInplace(output, "\n", "%n");
replaceInplace(output, "\"", "%\"");
return "\"" + output + "\"";
}
std::string expandUid(const std::string& name, bool expand)
{
if( expand == false )
{
UidIdentifierProcessor uidIdProc;
StringBuffer nameBuf;
return uidIdProc.unexpand(name.c_str(), nameBuf);
}
return name;
}
void appendConfType(std::stringstream& stream, const ConfigScope& scope, ConfType type, bool expandUid, std::size_t indentLevel)
{
auto names = scope.listLocallyScopedNames(type, false, { });
std::sort(names.begin(), names.end());
for( std::size_t i=0; i<names.size(); ++i )
{
const auto item = scope.findItem(names[i]);
stream << toString(*item, item->name(), expandUid, indentLevel);
}
}
}
std::string toString(const ConfigItem& item, const std::string& name, bool expandUidNames, std::size_t indentLevel)
{
const std::string nameStr = expandUid(name, expandUidNames);
std::stringstream os;
os << indent(indentLevel);
switch(item.type())
{
case ConfType::String:
os << nameStr << " = " << escape(item.stringVal()) << ";\n";
break;
case ConfType::List:
{
os << nameStr << " = [";
const auto values = item.listVal();
if( values.empty() == false )
{
using OItr = std::ostream_iterator<std::string>;
std::transform(values.cbegin(), std::prev(values.cend()), OItr{os, ", "}, escape);
std::transform(std::prev(values.cend()), values.cend(), OItr{os}, escape);
}
os << "];\n";
}
break;
case ConfType::Scope:
{
os << nameStr << " {\n";
StringBuffer buffer;
os << toString(*(item.scopeVal()), expandUidNames, indentLevel + 1);
os << indent(indentLevel) << buffer.str() << "}\n";
}
break;
default:
break;
}
return os.str();
}
std::string toString(const ConfigScope& scope, bool expandUidNames, std::size_t indentLevel)
{
std::stringstream ss;
appendConfType(ss, scope, ConfType::Variables, expandUidNames, indentLevel);
appendConfType(ss, scope, ConfType::Scope, expandUidNames, indentLevel);
return ss.str();
}
}
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "helpers/pipeline_builder.h"
#include "helpers/tool_main.h"
#include "helpers/tool_usage.h"
#include <vistk/pipeline_util/pipe_declaration_types.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/modules.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/pipeline_exception.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_cluster.h>
#include <vistk/pipeline/types.h>
#include <vistk/utilities/path.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/variant.hpp>
#include <iostream>
#include <set>
#include <stdexcept>
#include <cstdlib>
class config_printer
: public boost::static_visitor<>
{
public:
config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf);
~config_printer();
void operator () (vistk::config_pipe_block const& config_block) const;
void operator () (vistk::process_pipe_block const& process_block);
void operator () (vistk::connect_pipe_block const& connect_block) const;
void output_process_defaults();
private:
void print_config_value(vistk::config_value_t const& config_value) const;
void output_process(vistk::process_t const& proc);
typedef std::set<vistk::process::name_t> process_set_t;
std::ostream& m_ostr;
vistk::pipeline_t const m_pipe;
vistk::config_t const m_config;
process_set_t m_visited;
};
int
tool_main(int argc, char* argv[])
{
vistk::load_known_modules();
boost::program_options::options_description desc;
desc
.add(tool_common_options())
.add(pipeline_common_options())
.add(pipeline_input_options())
.add(pipeline_output_options());
boost::program_options::variables_map const vm = tool_parse(argc, argv, desc);
pipeline_builder const builder(vm, desc);
vistk::pipeline_t const pipe = builder.pipeline();
vistk::config_t const config = builder.config();
vistk::pipe_blocks const blocks = builder.blocks();
if (!pipe)
{
std::cerr << "Error: Unable to bake pipeline" << std::endl;
return EXIT_FAILURE;
}
std::ostream* postr;
boost::filesystem::ofstream fout;
vistk::path_t const opath = vm["output"].as<vistk::path_t>();
if (opath == vistk::path_t("-"))
{
postr = &std::cout;
}
else
{
fout.open(opath);
if (fout.bad())
{
std::cerr << "Error: Unable to open output file" << std::endl;
return EXIT_FAILURE;
}
postr = &fout;
}
std::ostream& ostr = *postr;
config_printer printer(ostr, pipe, config);
std::for_each(blocks.begin(), blocks.end(), boost::apply_visitor(printer));
printer.output_process_defaults();
return EXIT_SUCCESS;
}
config_printer
::config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf)
: m_ostr(ostr)
, m_pipe(pipe)
, m_config(conf)
{
}
config_printer
::~config_printer()
{
}
class key_printer
{
public:
key_printer(std::ostream& ostr);
~key_printer();
void operator () (vistk::config_value_t const& config_value) const;
private:
std::ostream& m_ostr;
};
void
config_printer
::operator () (vistk::config_pipe_block const& config_block) const
{
vistk::config::keys_t const& keys = config_block.key;
vistk::config_values_t const& values = config_block.values;
vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);
m_ostr << "config " << key_path << std::endl;
key_printer const printer(m_ostr);
std::for_each(values.begin(), values.end(), printer);
m_ostr << std::endl;
}
void
config_printer
::operator () (vistk::process_pipe_block const& process_block)
{
vistk::process::name_t const& name = process_block.name;
vistk::process::type_t const& type = process_block.type;
vistk::config_values_t const& values = process_block.config_values;
m_ostr << "process " << name << std::endl;
m_ostr << " :: " << type << std::endl;
key_printer const printer(m_ostr);
std::for_each(values.begin(), values.end(), printer);
vistk::process_t proc;
try
{
proc = m_pipe->process_by_name(name);
}
catch (vistk::no_such_process_exception const& /*e*/)
{
try
{
vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);
proc = boost::static_pointer_cast<vistk::process>(cluster);
}
catch (vistk::no_such_process_exception const& /*e*/)
{
std::string const reason = "A process block did not result in a process being "
"added to the pipeline: " + name;
throw std::logic_error(reason);
}
}
output_process(proc);
}
void
config_printer
::operator () (vistk::connect_pipe_block const& connect_block) const
{
vistk::process::port_addr_t const& upstream_addr = connect_block.from;
vistk::process::port_addr_t const& downstream_addr = connect_block.to;
vistk::process::name_t const& upstream_name = upstream_addr.first;
vistk::process::port_t const& upstream_port = upstream_addr.second;
vistk::process::name_t const& downstream_name = downstream_addr.first;
vistk::process::port_t const& downstream_port = downstream_addr.second;
m_ostr << "connect from " << upstream_name << "." << upstream_port << std::endl;
m_ostr << " to " << downstream_name << "." << downstream_port << std::endl;
m_ostr << std::endl;
}
void
config_printer
::output_process_defaults()
{
vistk::process::names_t const cluster_names = m_pipe->cluster_names();
BOOST_FOREACH (vistk::process::name_t const& name, cluster_names)
{
if (m_visited.count(name))
{
continue;
}
vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);
vistk::process_t const proc = boost::static_pointer_cast<vistk::process>(cluster);
vistk::process::type_t const& type = proc->type();
m_ostr << "# Defaults for \'" << name << "\' cluster." << std::endl;
m_ostr << "config " << name << std::endl;
m_ostr << "# :: " << type << std::endl;
output_process(proc);
}
vistk::process::names_t const process_names = m_pipe->process_names();
BOOST_FOREACH (vistk::process::name_t const& name, process_names)
{
if (m_visited.count(name))
{
continue;
}
vistk::process_t const proc = m_pipe->process_by_name(name);
vistk::process::type_t const& type = proc->type();
m_ostr << "# Defaults for \'" << name << "\' process." << std::endl;
m_ostr << "config " << name << std::endl;
m_ostr << "# :: " << type << std::endl;
output_process(proc);
}
}
void
config_printer
::output_process(vistk::process_t const& proc)
{
vistk::process::name_t const name = proc->name();
vistk::config::keys_t const keys = proc->available_config();
BOOST_FOREACH (vistk::config::key_t const& key, keys)
{
if (boost::starts_with(key, "_"))
{
continue;
}
m_ostr << std::endl;
vistk::process::conf_info_t const& info = proc->config_info(key);
vistk::config::description_t const desc = boost::replace_all_copy(info->description, "\n", "\n # ");
m_ostr << " # Key: " << key << std::endl;
m_ostr << " # Description: " << desc << std::endl;
vistk::config::value_t const& def = info->def;
if (def.empty())
{
m_ostr << " # No default value" << std::endl;
}
else
{
m_ostr << " # Default value: " << def << std::endl;
}
vistk::config::key_t const resolved_key = name + vistk::config::block_sep + key;
if (m_config->has_value(resolved_key))
{
vistk::config::value_t const cur_value = m_config->get_value<vistk::config::value_t>(resolved_key);
m_ostr << " # Current value: " << cur_value << std::endl;
}
else
{
m_ostr << " # No current value" << std::endl;
}
}
m_ostr << std::endl;
m_visited.insert(name);
}
key_printer
::key_printer(std::ostream& ostr)
: m_ostr(ostr)
{
}
key_printer
::~key_printer()
{
}
void
key_printer
::operator () (vistk::config_value_t const& config_value) const
{
vistk::config_key_t const& key = config_value.key;
vistk::config::value_t const& value = config_value.value;
vistk::config::keys_t const& keys = key.key_path;
vistk::config_key_options_t const& options = key.options;
vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);
boost::optional<vistk::config_flags_t> const& flags = options.flags;
boost::optional<vistk::config_provider_t> const& provider = options.provider;
m_ostr << " " << vistk::config::block_sep << key_path;
if (flags)
{
vistk::config_flag_t const flag_list = boost::join(*flags, ",");
m_ostr << "[" << flag_list << "]";
}
if (provider)
{
m_ostr << "{" << *provider << "}";
}
m_ostr << " " << value << std::endl;
}
<commit_msg>Use colons for "labels" in comments<commit_after>/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "helpers/pipeline_builder.h"
#include "helpers/tool_main.h"
#include "helpers/tool_usage.h"
#include <vistk/pipeline_util/pipe_declaration_types.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/modules.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/pipeline_exception.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_cluster.h>
#include <vistk/pipeline/types.h>
#include <vistk/utilities/path.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/variant.hpp>
#include <iostream>
#include <set>
#include <stdexcept>
#include <cstdlib>
class config_printer
: public boost::static_visitor<>
{
public:
config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf);
~config_printer();
void operator () (vistk::config_pipe_block const& config_block) const;
void operator () (vistk::process_pipe_block const& process_block);
void operator () (vistk::connect_pipe_block const& connect_block) const;
void output_process_defaults();
private:
void print_config_value(vistk::config_value_t const& config_value) const;
void output_process(vistk::process_t const& proc);
typedef std::set<vistk::process::name_t> process_set_t;
std::ostream& m_ostr;
vistk::pipeline_t const m_pipe;
vistk::config_t const m_config;
process_set_t m_visited;
};
int
tool_main(int argc, char* argv[])
{
vistk::load_known_modules();
boost::program_options::options_description desc;
desc
.add(tool_common_options())
.add(pipeline_common_options())
.add(pipeline_input_options())
.add(pipeline_output_options());
boost::program_options::variables_map const vm = tool_parse(argc, argv, desc);
pipeline_builder const builder(vm, desc);
vistk::pipeline_t const pipe = builder.pipeline();
vistk::config_t const config = builder.config();
vistk::pipe_blocks const blocks = builder.blocks();
if (!pipe)
{
std::cerr << "Error: Unable to bake pipeline" << std::endl;
return EXIT_FAILURE;
}
std::ostream* postr;
boost::filesystem::ofstream fout;
vistk::path_t const opath = vm["output"].as<vistk::path_t>();
if (opath == vistk::path_t("-"))
{
postr = &std::cout;
}
else
{
fout.open(opath);
if (fout.bad())
{
std::cerr << "Error: Unable to open output file" << std::endl;
return EXIT_FAILURE;
}
postr = &fout;
}
std::ostream& ostr = *postr;
config_printer printer(ostr, pipe, config);
std::for_each(blocks.begin(), blocks.end(), boost::apply_visitor(printer));
printer.output_process_defaults();
return EXIT_SUCCESS;
}
config_printer
::config_printer(std::ostream& ostr, vistk::pipeline_t const& pipe, vistk::config_t const& conf)
: m_ostr(ostr)
, m_pipe(pipe)
, m_config(conf)
{
}
config_printer
::~config_printer()
{
}
class key_printer
{
public:
key_printer(std::ostream& ostr);
~key_printer();
void operator () (vistk::config_value_t const& config_value) const;
private:
std::ostream& m_ostr;
};
void
config_printer
::operator () (vistk::config_pipe_block const& config_block) const
{
vistk::config::keys_t const& keys = config_block.key;
vistk::config_values_t const& values = config_block.values;
vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);
m_ostr << "config " << key_path << std::endl;
key_printer const printer(m_ostr);
std::for_each(values.begin(), values.end(), printer);
m_ostr << std::endl;
}
void
config_printer
::operator () (vistk::process_pipe_block const& process_block)
{
vistk::process::name_t const& name = process_block.name;
vistk::process::type_t const& type = process_block.type;
vistk::config_values_t const& values = process_block.config_values;
m_ostr << "process " << name << std::endl;
m_ostr << " :: " << type << std::endl;
key_printer const printer(m_ostr);
std::for_each(values.begin(), values.end(), printer);
vistk::process_t proc;
try
{
proc = m_pipe->process_by_name(name);
}
catch (vistk::no_such_process_exception const& /*e*/)
{
try
{
vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);
proc = boost::static_pointer_cast<vistk::process>(cluster);
}
catch (vistk::no_such_process_exception const& /*e*/)
{
std::string const reason = "A process block did not result in a process being "
"added to the pipeline: " + name;
throw std::logic_error(reason);
}
}
output_process(proc);
}
void
config_printer
::operator () (vistk::connect_pipe_block const& connect_block) const
{
vistk::process::port_addr_t const& upstream_addr = connect_block.from;
vistk::process::port_addr_t const& downstream_addr = connect_block.to;
vistk::process::name_t const& upstream_name = upstream_addr.first;
vistk::process::port_t const& upstream_port = upstream_addr.second;
vistk::process::name_t const& downstream_name = downstream_addr.first;
vistk::process::port_t const& downstream_port = downstream_addr.second;
m_ostr << "connect from " << upstream_name << "." << upstream_port << std::endl;
m_ostr << " to " << downstream_name << "." << downstream_port << std::endl;
m_ostr << std::endl;
}
void
config_printer
::output_process_defaults()
{
vistk::process::names_t const cluster_names = m_pipe->cluster_names();
BOOST_FOREACH (vistk::process::name_t const& name, cluster_names)
{
if (m_visited.count(name))
{
continue;
}
vistk::process_cluster_t const cluster = m_pipe->cluster_by_name(name);
vistk::process_t const proc = boost::static_pointer_cast<vistk::process>(cluster);
vistk::process::type_t const& type = proc->type();
m_ostr << "# Defaults for \'" << name << "\' cluster:" << std::endl;
m_ostr << "config " << name << std::endl;
m_ostr << "# :: " << type << std::endl;
output_process(proc);
}
vistk::process::names_t const process_names = m_pipe->process_names();
BOOST_FOREACH (vistk::process::name_t const& name, process_names)
{
if (m_visited.count(name))
{
continue;
}
vistk::process_t const proc = m_pipe->process_by_name(name);
vistk::process::type_t const& type = proc->type();
m_ostr << "# Defaults for \'" << name << "\' process:" << std::endl;
m_ostr << "config " << name << std::endl;
m_ostr << "# :: " << type << std::endl;
output_process(proc);
}
}
void
config_printer
::output_process(vistk::process_t const& proc)
{
vistk::process::name_t const name = proc->name();
vistk::config::keys_t const keys = proc->available_config();
BOOST_FOREACH (vistk::config::key_t const& key, keys)
{
if (boost::starts_with(key, "_"))
{
continue;
}
m_ostr << std::endl;
vistk::process::conf_info_t const& info = proc->config_info(key);
vistk::config::description_t const desc = boost::replace_all_copy(info->description, "\n", "\n # ");
m_ostr << " # Key: " << key << std::endl;
m_ostr << " # Description: " << desc << std::endl;
vistk::config::value_t const& def = info->def;
if (def.empty())
{
m_ostr << " # No default value" << std::endl;
}
else
{
m_ostr << " # Default value: " << def << std::endl;
}
vistk::config::key_t const resolved_key = name + vistk::config::block_sep + key;
if (m_config->has_value(resolved_key))
{
vistk::config::value_t const cur_value = m_config->get_value<vistk::config::value_t>(resolved_key);
m_ostr << " # Current value: " << cur_value << std::endl;
}
else
{
m_ostr << " # No current value" << std::endl;
}
}
m_ostr << std::endl;
m_visited.insert(name);
}
key_printer
::key_printer(std::ostream& ostr)
: m_ostr(ostr)
{
}
key_printer
::~key_printer()
{
}
void
key_printer
::operator () (vistk::config_value_t const& config_value) const
{
vistk::config_key_t const& key = config_value.key;
vistk::config::value_t const& value = config_value.value;
vistk::config::keys_t const& keys = key.key_path;
vistk::config_key_options_t const& options = key.options;
vistk::config::key_t const key_path = boost::join(keys, vistk::config::block_sep);
boost::optional<vistk::config_flags_t> const& flags = options.flags;
boost::optional<vistk::config_provider_t> const& provider = options.provider;
m_ostr << " " << vistk::config::block_sep << key_path;
if (flags)
{
vistk::config_flag_t const flag_list = boost::join(*flags, ",");
m_ostr << "[" << flag_list << "]";
}
if (provider)
{
m_ostr << "{" << *provider << "}";
}
m_ostr << " " << value << std::endl;
}
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/pipeline_util/load_pipe.h>
#include <vistk/pipeline/modules.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/process.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
namespace po = boost::program_options;
static po::options_description make_options();
static void usage(po::options_description const& options);
static std::string const node_suffix_main = "_main";
static std::string const node_prefix_input = "_input_";
static std::string const node_prefix_output = "_output_";
static std::string const style_process_subgraph = "color=lightgray;style=filled;";
static std::string const style_process = "shape=ellipse,rank=same";
static std::string const style_port = "shape=none,height=0,width=0,fontsize=7";
static std::string const style_port_edge = "arrowhead=none,color=black";
static std::string const style_input_port = style_port;
static std::string const style_input_port_edge = style_port_edge;
static std::string const style_output_port = style_port;
static std::string const style_output_port_edge = style_port_edge;
static std::string const style_connection_edge = "minlen=1,color=black,weight=1";
int main(int argc, char* argv[])
{
vistk::load_known_modules();
po::options_description const desc = make_options();
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
usage(desc);
}
if (!vm.count("input"))
{
std::cerr << "Error: input not set" << std::endl;
usage(desc);
}
vistk::pipeline_t pipe;
{
std::istream* pistr;
std::ifstream fin;
boost::filesystem::path const ipath = vm["input"].as<boost::filesystem::path>();
if (ipath.native() == "-")
{
pistr = &std::cin;
}
else
{
fin.open(ipath.native().c_str());
if (fin.bad())
{
/// \todo Throw an exception.
}
pistr = &fin;
}
std::istream& istr = *pistr;
/// \todo Include paths?
pipe = vistk::bake_pipe(istr, boost::filesystem::current_path());
}
if (!pipe)
{
/// \todo Throw exception.
return 1;
}
std::ostream* postr;
std::ofstream fout;
boost::filesystem::path const opath = vm["output"].as<boost::filesystem::path>();
if (opath.native() == "-")
{
postr = &std::cout;
}
else
{
fout.open(opath.native().c_str());
if (fout.bad())
{
/// \todo Throw an exception.
}
postr = &fout;
}
std::ostream& ostr = *postr;
std::string const graph_name = vm["name"].as<std::string>();
ostr << "strict digraph " << graph_name << " {" << std::endl;
ostr << std::endl;
vistk::process::names_t const proc_names = pipe->process_names();
// Output nodes
BOOST_FOREACH (vistk::process::name_t const& name, proc_names)
{
vistk::process_t const proc = pipe->process_by_name(name);
ostr << "subgraph cluster_" << name << " {" << std::endl;
ostr << style_process_subgraph << std::endl;
ostr << std::endl;
std::string const node_name = name + node_suffix_main;
// Central node
ostr << node_name << " ["
<< "label=\"" << name << "\\n:: " << proc->type() << "\","
<< style_process
<< "];" << std::endl;
ostr << std::endl;
// Input ports
vistk::process::ports_t const iports = proc->input_ports();
BOOST_FOREACH (vistk::process::port_t const& port, iports)
{
vistk::process::port_type_name_t const ptype = proc->input_port_type(port).get<0>();
std::string const node_port_name = name + node_prefix_input + port;
ostr << node_port_name << " ["
<< "label=\"" << port << "\\n:: " << ptype << "\","
<< style_input_port
<< "];" << std::endl;
ostr << node_port_name << " -> "
<< node_name << " ["
<< style_input_port_edge
<< "];" << std::endl;
ostr << std::endl;
}
ostr << std::endl;
// Output ports
vistk::process::ports_t const oports = proc->output_ports();
BOOST_FOREACH (vistk::process::port_t const& port, oports)
{
vistk::process::port_type_name_t const ptype = proc->output_port_type(port).get<0>();
std::string const node_port_name = name + node_prefix_output + port;
ostr << node_port_name << " ["
<< "label=\"" << port << "\\n:: " << ptype << "\","
<< style_output_port
<< "];" << std::endl;
ostr << node_name << " -> "
<< node_port_name << " ["
<< style_output_port_edge
<< "];" << std::endl;
ostr << std::endl;
}
ostr << std::endl;
ostr << "}" << std::endl;
}
ostr << std::endl;
// Output connections
BOOST_FOREACH (vistk::process::name_t const& name, proc_names)
{
vistk::process_t const proc = pipe->process_by_name(name);
vistk::process::ports_t const oports = proc->output_ports();
BOOST_FOREACH (vistk::process::port_t const& port, oports)
{
std::string const node_from_port_name = name + node_prefix_output + port;
vistk::process::port_addrs_t const addrs = pipe->receivers_for_port(name, port);
BOOST_FOREACH (vistk::process::port_addr_t const& addr, addrs)
{
std::string const node_to_port_name = addr.first + node_prefix_input + addr.second;
ostr << node_from_port_name << " -> "
<< node_to_port_name << " ["
<< style_connection_edge
<< "];" << std::endl;
}
}
ostr << std::endl;
}
ostr << std::endl;
ostr << "}" << std::endl;
return 0;
}
po::options_description
make_options()
{
po::options_description desc;
desc.add_options()
("help,h", "output help message and quit")
("input,i", po::value<boost::filesystem::path>(), "input path")
("output,o", po::value<boost::filesystem::path>()->default_value("-"), "output path")
("include,I", po::value<std::vector<boost::filesystem::path> >(), "configuration include path")
("name,n", po::value<std::string>()->default_value("(unnamed)"), "name of the graph")
;
return desc;
}
void
usage(po::options_description const& options)
{
std::cerr << options << std::endl;
exit(1);
}
<commit_msg>Output error messages when failures occur<commit_after>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/pipeline_util/load_pipe.h>
#include <vistk/pipeline/modules.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/process.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
namespace po = boost::program_options;
static po::options_description make_options();
static void usage(po::options_description const& options);
static std::string const node_suffix_main = "_main";
static std::string const node_prefix_input = "_input_";
static std::string const node_prefix_output = "_output_";
static std::string const style_process_subgraph = "color=lightgray;style=filled;";
static std::string const style_process = "shape=ellipse,rank=same";
static std::string const style_port = "shape=none,height=0,width=0,fontsize=7";
static std::string const style_port_edge = "arrowhead=none,color=black";
static std::string const style_input_port = style_port;
static std::string const style_input_port_edge = style_port_edge;
static std::string const style_output_port = style_port;
static std::string const style_output_port_edge = style_port_edge;
static std::string const style_connection_edge = "minlen=1,color=black,weight=1";
int main(int argc, char* argv[])
{
vistk::load_known_modules();
po::options_description const desc = make_options();
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
usage(desc);
}
if (!vm.count("input"))
{
std::cerr << "Error: input not set" << std::endl;
usage(desc);
}
vistk::pipeline_t pipe;
{
std::istream* pistr;
std::ifstream fin;
boost::filesystem::path const ipath = vm["input"].as<boost::filesystem::path>();
if (ipath.native() == "-")
{
pistr = &std::cin;
}
else
{
fin.open(ipath.native().c_str());
if (fin.bad())
{
std::cerr << "Error: Unable to open input file" << std::endl;
return 1;
}
pistr = &fin;
}
std::istream& istr = *pistr;
/// \todo Include paths?
pipe = vistk::bake_pipe(istr, boost::filesystem::current_path());
}
if (!pipe)
{
std::cerr << "Error: Unable to bake pipeline" << std::endl;
return 1;
}
std::ostream* postr;
std::ofstream fout;
boost::filesystem::path const opath = vm["output"].as<boost::filesystem::path>();
if (opath.native() == "-")
{
postr = &std::cout;
}
else
{
fout.open(opath.native().c_str());
if (fout.bad())
{
std::cerr << "Error: Unable to open output file" << std::endl;
return 1;
}
postr = &fout;
}
std::ostream& ostr = *postr;
std::string const graph_name = vm["name"].as<std::string>();
ostr << "strict digraph " << graph_name << " {" << std::endl;
ostr << std::endl;
vistk::process::names_t const proc_names = pipe->process_names();
// Output nodes
BOOST_FOREACH (vistk::process::name_t const& name, proc_names)
{
vistk::process_t const proc = pipe->process_by_name(name);
ostr << "subgraph cluster_" << name << " {" << std::endl;
ostr << style_process_subgraph << std::endl;
ostr << std::endl;
std::string const node_name = name + node_suffix_main;
// Central node
ostr << node_name << " ["
<< "label=\"" << name << "\\n:: " << proc->type() << "\","
<< style_process
<< "];" << std::endl;
ostr << std::endl;
// Input ports
vistk::process::ports_t const iports = proc->input_ports();
BOOST_FOREACH (vistk::process::port_t const& port, iports)
{
vistk::process::port_type_name_t const ptype = proc->input_port_type(port).get<0>();
std::string const node_port_name = name + node_prefix_input + port;
ostr << node_port_name << " ["
<< "label=\"" << port << "\\n:: " << ptype << "\","
<< style_input_port
<< "];" << std::endl;
ostr << node_port_name << " -> "
<< node_name << " ["
<< style_input_port_edge
<< "];" << std::endl;
ostr << std::endl;
}
ostr << std::endl;
// Output ports
vistk::process::ports_t const oports = proc->output_ports();
BOOST_FOREACH (vistk::process::port_t const& port, oports)
{
vistk::process::port_type_name_t const ptype = proc->output_port_type(port).get<0>();
std::string const node_port_name = name + node_prefix_output + port;
ostr << node_port_name << " ["
<< "label=\"" << port << "\\n:: " << ptype << "\","
<< style_output_port
<< "];" << std::endl;
ostr << node_name << " -> "
<< node_port_name << " ["
<< style_output_port_edge
<< "];" << std::endl;
ostr << std::endl;
}
ostr << std::endl;
ostr << "}" << std::endl;
}
ostr << std::endl;
// Output connections
BOOST_FOREACH (vistk::process::name_t const& name, proc_names)
{
vistk::process_t const proc = pipe->process_by_name(name);
vistk::process::ports_t const oports = proc->output_ports();
BOOST_FOREACH (vistk::process::port_t const& port, oports)
{
std::string const node_from_port_name = name + node_prefix_output + port;
vistk::process::port_addrs_t const addrs = pipe->receivers_for_port(name, port);
BOOST_FOREACH (vistk::process::port_addr_t const& addr, addrs)
{
std::string const node_to_port_name = addr.first + node_prefix_input + addr.second;
ostr << node_from_port_name << " -> "
<< node_to_port_name << " ["
<< style_connection_edge
<< "];" << std::endl;
}
}
ostr << std::endl;
}
ostr << std::endl;
ostr << "}" << std::endl;
return 0;
}
po::options_description
make_options()
{
po::options_description desc;
desc.add_options()
("help,h", "output help message and quit")
("input,i", po::value<boost::filesystem::path>(), "input path")
("output,o", po::value<boost::filesystem::path>()->default_value("-"), "output path")
("include,I", po::value<std::vector<boost::filesystem::path> >(), "configuration include path")
("name,n", po::value<std::string>()->default_value("(unnamed)"), "name of the graph")
;
return desc;
}
void
usage(po::options_description const& options)
{
std::cerr << options << std::endl;
exit(1);
}
<|endoftext|> |
<commit_before>#include "compiler/build_tables/build_parse_table.h"
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include "compiler/parse_table.h"
#include "compiler/build_tables/parse_conflict_manager.h"
#include "compiler/build_tables/remove_duplicate_states.h"
#include "compiler/build_tables/parse_item.h"
#include "compiler/build_tables/item_set_closure.h"
#include "compiler/build_tables/symbols_by_first_symbol.h"
#include "compiler/lexical_grammar.h"
#include "compiler/syntax_grammar.h"
#include "compiler/rules/symbol.h"
#include "compiler/rules/built_in_symbols.h"
namespace tree_sitter {
namespace build_tables {
using std::find;
using std::pair;
using std::vector;
using std::set;
using std::map;
using std::string;
using std::to_string;
using std::unordered_map;
using std::make_shared;
using rules::Symbol;
class ParseTableBuilder {
const SyntaxGrammar grammar;
const LexicalGrammar lexical_grammar;
ParseConflictManager conflict_manager;
unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids;
vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process;
ParseTable parse_table;
std::set<string> conflicts;
ParseItemSet null_item_set;
std::set<const Production *> fragile_productions;
bool allow_any_conflict;
public:
ParseTableBuilder(const SyntaxGrammar &grammar,
const LexicalGrammar &lex_grammar)
: grammar(grammar),
lexical_grammar(lex_grammar),
allow_any_conflict(false) {}
pair<ParseTable, CompileError> build() {
Symbol start_symbol = Symbol(0, grammar.variables.empty());
Production start_production({
ProductionStep(start_symbol, 0, rules::AssociativityNone),
});
add_parse_state(ParseItemSet({
{
ParseItem(rules::START(), start_production, 0),
LookaheadSet({ rules::END_OF_INPUT() }),
},
}));
CompileError error = process_part_state_queue();
if (error.type != TSCompileErrorTypeNone) {
return { parse_table, error };
}
add_out_of_context_parse_states();
allow_any_conflict = true;
process_part_state_queue();
allow_any_conflict = false;
for (ParseStateId state = 0; state < parse_table.states.size(); state++) {
add_shift_extra_actions(state);
add_reduce_extra_actions(state);
}
mark_fragile_actions();
remove_duplicate_parse_states();
return { parse_table, CompileError::none() };
}
private:
CompileError process_part_state_queue() {
while (!item_sets_to_process.empty()) {
auto pair = item_sets_to_process.back();
ParseItemSet item_set = item_set_closure(pair.first, grammar);
ParseStateId state_id = pair.second;
item_sets_to_process.pop_back();
add_reduce_actions(item_set, state_id);
add_shift_actions(item_set, state_id);
if (!conflicts.empty()) {
return CompileError(TSCompileErrorTypeParseConflict,
"Unresolved conflict.\n\n" + *conflicts.begin());
}
}
return CompileError::none();
}
void add_out_of_context_parse_states() {
map<Symbol, set<Symbol>> symbols_by_first = symbols_by_first_symbol(grammar);
for (size_t i = 0; i < lexical_grammar.variables.size(); i++) {
Symbol symbol(i, true);
if (!grammar.extra_tokens.count(symbol))
add_out_of_context_parse_state(symbol, symbols_by_first[symbol]);
}
for (size_t i = 0; i < grammar.variables.size(); i++) {
Symbol symbol(i, false);
add_out_of_context_parse_state(Symbol(i, false), symbols_by_first[symbol]);
}
}
void add_out_of_context_parse_state(const rules::Symbol &symbol,
const set<Symbol> &symbols) {
ParseItemSet item_set;
for (const auto &parse_state_entry : parse_state_ids) {
ParseItemSet state_item_set = parse_state_entry.first;
for (const auto &pair : state_item_set.entries) {
const ParseItem &item = pair.first;
const LookaheadSet &lookahead_set = pair.second;
if (symbols.count(item.next_symbol())) {
item_set.entries[item].insert_all(lookahead_set);
}
}
}
ParseStateId state = add_parse_state(item_set);
parse_table.out_of_context_state_indices[symbol] = state;
}
ParseStateId add_parse_state(const ParseItemSet &item_set) {
auto pair = parse_state_ids.find(item_set);
if (pair == parse_state_ids.end()) {
ParseStateId state_id = parse_table.add_state();
for (const auto &entry : item_set.entries) {
const ParseItem &item = entry.first;
if (item.step_index > 0 && item.lhs() != rules::START() && !allow_any_conflict)
parse_table.states[state_id].in_progress_symbols.insert(item.lhs());
}
parse_state_ids[item_set] = state_id;
item_sets_to_process.push_back({ item_set, state_id });
return state_id;
} else {
return pair->second;
}
}
void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &transition : item_set.transitions()) {
const Symbol &symbol = transition.first;
const ParseItemSet &next_item_set = transition.second.first;
const PrecedenceRange &precedence = transition.second.second;
ParseAction *new_action = add_action(
state_id, symbol, ParseAction::Shift(0, precedence), item_set);
if (new_action)
new_action->state_index = add_parse_state(next_item_set);
}
}
void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const auto &lookahead_symbols = pair.second;
ParseItem::CompletionStatus status = item.completion_status();
if (status.is_done) {
ParseAction action =
(item.lhs() == rules::START())
? ParseAction::Accept()
: ParseAction::Reduce(Symbol(item.variable_index), item.step_index,
status.precedence, status.associativity,
*item.production);
for (const auto &lookahead_sym : *lookahead_symbols.entries)
add_action(state_id, lookahead_sym, action, item_set);
}
}
}
void add_shift_extra_actions(ParseStateId state_id) {
ParseAction action = ParseAction::ShiftExtra();
for (const Symbol &extra_symbol : grammar.extra_tokens)
add_action(state_id, extra_symbol, action, null_item_set);
}
void add_reduce_extra_actions(ParseStateId state_id) {
const ParseState &state = parse_table.states[state_id];
for (const Symbol &extra_symbol : grammar.extra_tokens) {
const auto &actions_for_symbol = state.actions.find(extra_symbol);
if (actions_for_symbol == state.actions.end())
continue;
for (const ParseAction &action : actions_for_symbol->second)
if (action.type == ParseActionTypeShift && !action.extra) {
size_t dest_state_id = action.state_index;
ParseAction reduce_extra = ParseAction::ReduceExtra(extra_symbol);
for (const auto &pair : state.actions)
add_action(dest_state_id, pair.first, reduce_extra, null_item_set);
}
}
}
void mark_fragile_actions() {
for (ParseState &state : parse_table.states) {
set<Symbol> symbols_with_multiple_actions;
for (auto &entry : state.actions) {
if (entry.second.size() > 1)
symbols_with_multiple_actions.insert(entry.first);
for (ParseAction &action : entry.second) {
if (action.type == ParseActionTypeReduce && !action.extra) {
if (has_fragile_production(action.production))
action.fragile = true;
action.production = NULL;
action.precedence_range = PrecedenceRange();
action.associativity = rules::AssociativityNone;
}
}
}
if (!symbols_with_multiple_actions.empty()) {
for (auto &entry : state.actions) {
if (!entry.first.is_token) {
set<Symbol> first_set = get_first_set(entry.first);
for (const Symbol &symbol : symbols_with_multiple_actions) {
if (first_set.count(symbol)) {
entry.second[0].can_hide_split = true;
break;
}
}
}
}
}
}
}
void remove_duplicate_parse_states() {
auto replacements = remove_duplicate_states<ParseState, ParseAction>(
&parse_table.states);
for (auto &pair : parse_table.out_of_context_state_indices) {
auto replacement = replacements.find(pair.second);
if (replacement != replacements.end())
pair.second = replacement->second;
}
}
ParseAction *add_action(ParseStateId state_id, Symbol lookahead,
const ParseAction &new_action,
const ParseItemSet &item_set) {
const auto ¤t_actions = parse_table.states[state_id].actions;
const auto ¤t_entry = current_actions.find(lookahead);
if (current_entry == current_actions.end())
return &parse_table.set_action(state_id, lookahead, new_action);
if (allow_any_conflict)
return &parse_table.add_action(state_id, lookahead, new_action);
const ParseAction old_action = current_entry->second[0];
auto resolution = conflict_manager.resolve(new_action, old_action);
switch (resolution.second) {
case ConflictTypeNone:
if (resolution.first)
return &parse_table.set_action(state_id, lookahead, new_action);
break;
case ConflictTypeResolved: {
if (resolution.first) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
return &parse_table.set_action(state_id, lookahead, new_action);
} else {
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
break;
}
}
case ConflictTypeUnresolved: {
if (handle_unresolved_conflict(item_set, lookahead)) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
return &parse_table.add_action(state_id, lookahead, new_action);
}
break;
}
}
return nullptr;
}
bool handle_unresolved_conflict(const ParseItemSet &item_set,
const Symbol &lookahead) {
set<Symbol> involved_symbols;
set<ParseItem> reduce_items;
set<ParseItem> core_shift_items;
set<ParseItem> other_shift_items;
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const LookaheadSet &lookahead_set = pair.second;
Symbol next_symbol = item.next_symbol();
if (next_symbol == rules::NONE()) {
if (lookahead_set.contains(lookahead)) {
involved_symbols.insert(item.lhs());
reduce_items.insert(item);
}
} else {
if (item.step_index > 0) {
set<Symbol> first_set = get_first_set(next_symbol);
if (first_set.count(lookahead)) {
involved_symbols.insert(item.lhs());
core_shift_items.insert(item);
}
} else if (next_symbol == lookahead) {
other_shift_items.insert(item);
}
}
}
for (const auto &conflict_set : grammar.expected_conflicts)
if (involved_symbols == conflict_set)
return true;
string description = "Lookahead symbol: " + symbol_name(lookahead) + "\n";
if (!reduce_items.empty()) {
description += "Reduce items:\n";
for (const ParseItem &item : reduce_items)
description += " " + item_string(item) + "\n";
}
if (!core_shift_items.empty()) {
description += "Core shift items:\n";
for (const ParseItem &item : core_shift_items)
description += " " + item_string(item) + "\n";
}
if (!other_shift_items.empty()) {
description += "Other shift items:\n";
for (const ParseItem &item : other_shift_items)
description += " " + item_string(item) + "\n";
}
conflicts.insert(description);
return false;
}
string item_string(const ParseItem &item) const {
string result = symbol_name(item.lhs()) + " ->";
size_t i = 0;
for (const ProductionStep &step : *item.production) {
if (i == item.step_index)
result += " \u2022";
result += " " + symbol_name(step.symbol);
i++;
}
if (i == item.step_index)
result += " \u2022";
result += " (prec " + to_string(item.precedence());
switch (item.associativity()) {
case rules::AssociativityNone:
result += ")";
break;
case rules::AssociativityLeft:
result += ", assoc left)";
break;
case rules::AssociativityRight:
result += ", assoc right)";
break;
}
return result;
}
set<Symbol> get_first_set(const Symbol &start_symbol) {
set<Symbol> result;
vector<Symbol> symbols_to_process({ start_symbol });
while (!symbols_to_process.empty()) {
Symbol symbol = symbols_to_process.back();
symbols_to_process.pop_back();
if (result.insert(symbol).second)
for (const Production &production : grammar.productions(symbol))
if (!production.empty())
symbols_to_process.push_back(production[0].symbol);
}
return result;
}
string symbol_name(const rules::Symbol &symbol) const {
if (symbol.is_built_in()) {
if (symbol == rules::END_OF_INPUT())
return "END_OF_INPUT";
else
return "";
} else if (symbol.is_token) {
const Variable &variable = lexical_grammar.variables[symbol.index];
if (variable.type == VariableTypeNamed)
return variable.name;
else
return "'" + variable.name + "'";
} else {
return grammar.variables[symbol.index].name;
}
}
bool has_fragile_production(const Production *production) {
auto end = fragile_productions.end();
return std::find(fragile_productions.begin(), end, production) != end;
}
};
pair<ParseTable, CompileError> build_parse_table(
const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) {
return ParseTableBuilder(grammar, lex_grammar).build();
}
} // namespace build_tables
} // namespace tree_sitter
<commit_msg>Remove duplicate parse actions<commit_after>#include "compiler/build_tables/build_parse_table.h"
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include "compiler/parse_table.h"
#include "compiler/build_tables/parse_conflict_manager.h"
#include "compiler/build_tables/remove_duplicate_states.h"
#include "compiler/build_tables/parse_item.h"
#include "compiler/build_tables/item_set_closure.h"
#include "compiler/build_tables/symbols_by_first_symbol.h"
#include "compiler/lexical_grammar.h"
#include "compiler/syntax_grammar.h"
#include "compiler/rules/symbol.h"
#include "compiler/rules/built_in_symbols.h"
namespace tree_sitter {
namespace build_tables {
using std::find;
using std::pair;
using std::vector;
using std::set;
using std::map;
using std::string;
using std::to_string;
using std::unordered_map;
using std::make_shared;
using rules::Symbol;
class ParseTableBuilder {
const SyntaxGrammar grammar;
const LexicalGrammar lexical_grammar;
ParseConflictManager conflict_manager;
unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids;
vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process;
ParseTable parse_table;
std::set<string> conflicts;
ParseItemSet null_item_set;
std::set<const Production *> fragile_productions;
bool allow_any_conflict;
public:
ParseTableBuilder(const SyntaxGrammar &grammar,
const LexicalGrammar &lex_grammar)
: grammar(grammar),
lexical_grammar(lex_grammar),
allow_any_conflict(false) {}
pair<ParseTable, CompileError> build() {
Symbol start_symbol = Symbol(0, grammar.variables.empty());
Production start_production({
ProductionStep(start_symbol, 0, rules::AssociativityNone),
});
add_parse_state(ParseItemSet({
{
ParseItem(rules::START(), start_production, 0),
LookaheadSet({ rules::END_OF_INPUT() }),
},
}));
CompileError error = process_part_state_queue();
if (error.type != TSCompileErrorTypeNone) {
return { parse_table, error };
}
add_out_of_context_parse_states();
allow_any_conflict = true;
process_part_state_queue();
allow_any_conflict = false;
for (ParseStateId state = 0; state < parse_table.states.size(); state++) {
add_shift_extra_actions(state);
add_reduce_extra_actions(state);
}
mark_fragile_actions();
remove_duplicate_parse_states();
return { parse_table, CompileError::none() };
}
private:
CompileError process_part_state_queue() {
while (!item_sets_to_process.empty()) {
auto pair = item_sets_to_process.back();
ParseItemSet item_set = item_set_closure(pair.first, grammar);
ParseStateId state_id = pair.second;
item_sets_to_process.pop_back();
add_reduce_actions(item_set, state_id);
add_shift_actions(item_set, state_id);
if (!conflicts.empty()) {
return CompileError(TSCompileErrorTypeParseConflict,
"Unresolved conflict.\n\n" + *conflicts.begin());
}
}
return CompileError::none();
}
void add_out_of_context_parse_states() {
map<Symbol, set<Symbol>> symbols_by_first = symbols_by_first_symbol(grammar);
for (size_t i = 0; i < lexical_grammar.variables.size(); i++) {
Symbol symbol(i, true);
if (!grammar.extra_tokens.count(symbol))
add_out_of_context_parse_state(symbol, symbols_by_first[symbol]);
}
for (size_t i = 0; i < grammar.variables.size(); i++) {
Symbol symbol(i, false);
add_out_of_context_parse_state(Symbol(i, false), symbols_by_first[symbol]);
}
}
void add_out_of_context_parse_state(const rules::Symbol &symbol,
const set<Symbol> &symbols) {
ParseItemSet item_set;
for (const auto &parse_state_entry : parse_state_ids) {
ParseItemSet state_item_set = parse_state_entry.first;
for (const auto &pair : state_item_set.entries) {
const ParseItem &item = pair.first;
const LookaheadSet &lookahead_set = pair.second;
if (symbols.count(item.next_symbol())) {
item_set.entries[item].insert_all(lookahead_set);
}
}
}
ParseStateId state = add_parse_state(item_set);
parse_table.out_of_context_state_indices[symbol] = state;
}
ParseStateId add_parse_state(const ParseItemSet &item_set) {
auto pair = parse_state_ids.find(item_set);
if (pair == parse_state_ids.end()) {
ParseStateId state_id = parse_table.add_state();
for (const auto &entry : item_set.entries) {
const ParseItem &item = entry.first;
if (item.step_index > 0 && item.lhs() != rules::START() && !allow_any_conflict)
parse_table.states[state_id].in_progress_symbols.insert(item.lhs());
}
parse_state_ids[item_set] = state_id;
item_sets_to_process.push_back({ item_set, state_id });
return state_id;
} else {
return pair->second;
}
}
void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &transition : item_set.transitions()) {
const Symbol &symbol = transition.first;
const ParseItemSet &next_item_set = transition.second.first;
const PrecedenceRange &precedence = transition.second.second;
ParseAction *new_action = add_action(
state_id, symbol, ParseAction::Shift(0, precedence), item_set);
if (new_action)
new_action->state_index = add_parse_state(next_item_set);
}
}
void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const auto &lookahead_symbols = pair.second;
ParseItem::CompletionStatus status = item.completion_status();
if (status.is_done) {
ParseAction action =
(item.lhs() == rules::START())
? ParseAction::Accept()
: ParseAction::Reduce(Symbol(item.variable_index), item.step_index,
status.precedence, status.associativity,
*item.production);
for (const auto &lookahead_sym : *lookahead_symbols.entries)
add_action(state_id, lookahead_sym, action, item_set);
}
}
}
void add_shift_extra_actions(ParseStateId state_id) {
ParseAction action = ParseAction::ShiftExtra();
for (const Symbol &extra_symbol : grammar.extra_tokens)
add_action(state_id, extra_symbol, action, null_item_set);
}
void add_reduce_extra_actions(ParseStateId state_id) {
const ParseState &state = parse_table.states[state_id];
for (const Symbol &extra_symbol : grammar.extra_tokens) {
const auto &actions_for_symbol = state.actions.find(extra_symbol);
if (actions_for_symbol == state.actions.end())
continue;
for (const ParseAction &action : actions_for_symbol->second)
if (action.type == ParseActionTypeShift && !action.extra) {
size_t dest_state_id = action.state_index;
ParseAction reduce_extra = ParseAction::ReduceExtra(extra_symbol);
for (const auto &pair : state.actions)
add_action(dest_state_id, pair.first, reduce_extra, null_item_set);
}
}
}
void mark_fragile_actions() {
for (ParseState &state : parse_table.states) {
set<Symbol> symbols_with_multiple_actions;
for (auto &entry : state.actions) {
if (entry.second.size() > 1)
symbols_with_multiple_actions.insert(entry.first);
for (ParseAction &action : entry.second) {
if (action.type == ParseActionTypeReduce && !action.extra) {
if (has_fragile_production(action.production))
action.fragile = true;
action.production = NULL;
action.precedence_range = PrecedenceRange();
action.associativity = rules::AssociativityNone;
}
}
for (auto i = entry.second.begin(); i != entry.second.end();) {
bool erased = false;
for (auto j = entry.second.begin(); j != i; j++) {
if (*j == *i) {
entry.second.erase(i);
erased = true;
break;
}
}
if (!erased)
++i;
}
}
if (!symbols_with_multiple_actions.empty()) {
for (auto &entry : state.actions) {
if (!entry.first.is_token) {
set<Symbol> first_set = get_first_set(entry.first);
for (const Symbol &symbol : symbols_with_multiple_actions) {
if (first_set.count(symbol)) {
entry.second[0].can_hide_split = true;
break;
}
}
}
}
}
}
}
void remove_duplicate_parse_states() {
auto replacements = remove_duplicate_states<ParseState, ParseAction>(
&parse_table.states);
for (auto &pair : parse_table.out_of_context_state_indices) {
auto replacement = replacements.find(pair.second);
if (replacement != replacements.end())
pair.second = replacement->second;
}
}
ParseAction *add_action(ParseStateId state_id, Symbol lookahead,
const ParseAction &new_action,
const ParseItemSet &item_set) {
const auto ¤t_actions = parse_table.states[state_id].actions;
const auto ¤t_entry = current_actions.find(lookahead);
if (current_entry == current_actions.end())
return &parse_table.set_action(state_id, lookahead, new_action);
if (allow_any_conflict)
return &parse_table.add_action(state_id, lookahead, new_action);
const ParseAction old_action = current_entry->second[0];
auto resolution = conflict_manager.resolve(new_action, old_action);
switch (resolution.second) {
case ConflictTypeNone:
if (resolution.first)
return &parse_table.set_action(state_id, lookahead, new_action);
break;
case ConflictTypeResolved: {
if (resolution.first) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
return &parse_table.set_action(state_id, lookahead, new_action);
} else {
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
break;
}
}
case ConflictTypeUnresolved: {
if (handle_unresolved_conflict(item_set, lookahead)) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
return &parse_table.add_action(state_id, lookahead, new_action);
}
break;
}
}
return nullptr;
}
bool handle_unresolved_conflict(const ParseItemSet &item_set,
const Symbol &lookahead) {
set<Symbol> involved_symbols;
set<ParseItem> reduce_items;
set<ParseItem> core_shift_items;
set<ParseItem> other_shift_items;
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const LookaheadSet &lookahead_set = pair.second;
Symbol next_symbol = item.next_symbol();
if (next_symbol == rules::NONE()) {
if (lookahead_set.contains(lookahead)) {
involved_symbols.insert(item.lhs());
reduce_items.insert(item);
}
} else {
if (item.step_index > 0) {
set<Symbol> first_set = get_first_set(next_symbol);
if (first_set.count(lookahead)) {
involved_symbols.insert(item.lhs());
core_shift_items.insert(item);
}
} else if (next_symbol == lookahead) {
other_shift_items.insert(item);
}
}
}
for (const auto &conflict_set : grammar.expected_conflicts)
if (involved_symbols == conflict_set)
return true;
string description = "Lookahead symbol: " + symbol_name(lookahead) + "\n";
if (!reduce_items.empty()) {
description += "Reduce items:\n";
for (const ParseItem &item : reduce_items)
description += " " + item_string(item) + "\n";
}
if (!core_shift_items.empty()) {
description += "Core shift items:\n";
for (const ParseItem &item : core_shift_items)
description += " " + item_string(item) + "\n";
}
if (!other_shift_items.empty()) {
description += "Other shift items:\n";
for (const ParseItem &item : other_shift_items)
description += " " + item_string(item) + "\n";
}
conflicts.insert(description);
return false;
}
string item_string(const ParseItem &item) const {
string result = symbol_name(item.lhs()) + " ->";
size_t i = 0;
for (const ProductionStep &step : *item.production) {
if (i == item.step_index)
result += " \u2022";
result += " " + symbol_name(step.symbol);
i++;
}
if (i == item.step_index)
result += " \u2022";
result += " (prec " + to_string(item.precedence());
switch (item.associativity()) {
case rules::AssociativityNone:
result += ")";
break;
case rules::AssociativityLeft:
result += ", assoc left)";
break;
case rules::AssociativityRight:
result += ", assoc right)";
break;
}
return result;
}
set<Symbol> get_first_set(const Symbol &start_symbol) {
set<Symbol> result;
vector<Symbol> symbols_to_process({ start_symbol });
while (!symbols_to_process.empty()) {
Symbol symbol = symbols_to_process.back();
symbols_to_process.pop_back();
if (result.insert(symbol).second)
for (const Production &production : grammar.productions(symbol))
if (!production.empty())
symbols_to_process.push_back(production[0].symbol);
}
return result;
}
string symbol_name(const rules::Symbol &symbol) const {
if (symbol.is_built_in()) {
if (symbol == rules::END_OF_INPUT())
return "END_OF_INPUT";
else
return "";
} else if (symbol.is_token) {
const Variable &variable = lexical_grammar.variables[symbol.index];
if (variable.type == VariableTypeNamed)
return variable.name;
else
return "'" + variable.name + "'";
} else {
return grammar.variables[symbol.index].name;
}
}
bool has_fragile_production(const Production *production) {
auto end = fragile_productions.end();
return std::find(fragile_productions.begin(), end, production) != end;
}
};
pair<ParseTable, CompileError> build_parse_table(
const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) {
return ParseTableBuilder(grammar, lex_grammar).build();
}
} // namespace build_tables
} // namespace tree_sitter
<|endoftext|> |
<commit_before>/*
* SessionClang.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 "SessionClang.hpp"
#include <core/system/System.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/IncrementalFileChangeHandler.hpp>
#include "Clang.hpp"
#include "UnsavedFiles.hpp"
#include "SourceIndex.hpp"
using namespace core ;
namespace session {
namespace modules {
namespace clang {
namespace {
bool isCppSourceDoc(const FilePath& docPath, bool includeHeaders)
{
std::string ex = docPath.extensionLowerCase();
if (ex == ".c" || ex == ".cc" || ex == ".cpp" || ex == ".m" || ex == ".mm"
|| (includeHeaders && (ex == ".h" || ex == ".hpp")))
{
return module_context::isUserFile(docPath);
}
else
{
return false;
}
}
bool translationUnitFilter(const FileInfo& fileInfo)
{
return isCppSourceDoc(FilePath(fileInfo.absolutePath()), false);
}
void translationUnitChangeHandler(const core::system::FileChangeEvent& event)
{
using namespace core::system;
switch(event.type())
{
case FileChangeEvent::FileAdded:
case FileChangeEvent::FileModified:
sourceIndex().updateTranslationUnit(event.fileInfo().absolutePath());
break;
case FileChangeEvent::FileRemoved:
sourceIndex().removeTranslationUnit(event.fileInfo().absolutePath());
break;
case FileChangeEvent::None:
break;
}
}
void onSourceDocUpdated(boost::shared_ptr<source_database::SourceDocument> pDoc)
{
// ignore if the file doesn't have a path
if (pDoc->path().empty())
return;
// resolve to a full path
FilePath docPath = module_context::resolveAliasedPath(pDoc->path());
// verify that it's an indexable C/C++ file
if (!isCppSourceDoc(docPath, true))
return;
// update unsaved files (we do this even if the document is dirty
// as even in this case it will need to be removed from the list
// of unsaved files)
unsavedFiles().update(pDoc);
// update the main index (but only if it's not dirty as unsaved
// edits are tracked separately)
if (!pDoc->dirty())
sourceIndex().updateTranslationUnit(docPath.absolutePath());
}
// diagnostic function to assist in determine whether/where
// libclang was loaded from (and any errors which occurred
// that prevented loading, e.g. inadequate version, missing
// symbols, etc.)
SEXP rs_isClangAvailable()
{
// check availability
std::string diagnostics;
bool isAvailable = isClangAvailable(&diagnostics);
// print diagnostics
module_context::consoleWriteOutput(diagnostics);
// return status
r::sexp::Protect rProtect;
return r::sexp::create(isAvailable, &rProtect);
}
// incremental file change handler
boost::scoped_ptr<IncrementalFileChangeHandler> pFileChangeHandler;
} // anonymous namespace
bool isClangAvailable()
{
return clang().isLoaded();
}
Error initialize()
{
// attempt to load clang interface
loadClang();
// register diagnostics function
R_CallMethodDef methodDef ;
methodDef.name = "rs_isClangAvailable" ;
methodDef.fun = (DL_FUNC)rs_isClangAvailable;
methodDef.numArgs = 0;
r::routines::addCallMethod(methodDef);
// subscribe to onSourceDocUpdated (used for maintaining both the
// main source index and the unsaved files list)
source_database::events().onDocUpdated.connect(onSourceDocUpdated);
// connect source doc removed events to unsaved files list
source_database::events().onDocRemoved.connect(
boost::bind(&UnsavedFiles::remove, &unsavedFiles(), _1));
source_database::events().onRemoveAll.connect(
boost::bind(&UnsavedFiles::removeAll, &unsavedFiles()));
// create incremental file change handler (this is used for updating
// the main source index). also subscribe it to the file monitor
pFileChangeHandler.reset(new IncrementalFileChangeHandler(
translationUnitFilter,
translationUnitChangeHandler,
boost::posix_time::milliseconds(200),
boost::posix_time::milliseconds(20),
false)); /* allow indexing during idle time */
pFileChangeHandler->subscribeToFileMonitor("C++ Code Completion");
// return success
return Success();
}
} // namespace clang
} // namespace modules
} // namesapce session
<commit_msg>include all types of cpp source docs (including headers)<commit_after>/*
* SessionClang.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 "SessionClang.hpp"
#include <core/system/System.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/IncrementalFileChangeHandler.hpp>
#include "Clang.hpp"
#include "UnsavedFiles.hpp"
#include "SourceIndex.hpp"
using namespace core ;
namespace session {
namespace modules {
namespace clang {
namespace {
bool isCppSourceDoc(const FilePath& docPath)
{
std::string ex = docPath.extensionLowerCase();
if (ex == ".c" || ex == ".cc" || ex == ".cpp" || ex == ".m" ||
ex == ".mm" || ex == ".h" || ex == ".hpp")
{
return module_context::isUserFile(docPath);
}
else
{
return false;
}
}
bool translationUnitFilter(const FileInfo& fileInfo)
{
return isCppSourceDoc(FilePath(fileInfo.absolutePath()));
}
void translationUnitChangeHandler(const core::system::FileChangeEvent& event)
{
using namespace core::system;
switch(event.type())
{
case FileChangeEvent::FileAdded:
case FileChangeEvent::FileModified:
sourceIndex().updateTranslationUnit(event.fileInfo().absolutePath());
break;
case FileChangeEvent::FileRemoved:
sourceIndex().removeTranslationUnit(event.fileInfo().absolutePath());
break;
case FileChangeEvent::None:
break;
}
}
void onSourceDocUpdated(boost::shared_ptr<source_database::SourceDocument> pDoc)
{
// ignore if the file doesn't have a path
if (pDoc->path().empty())
return;
// resolve to a full path
FilePath docPath = module_context::resolveAliasedPath(pDoc->path());
// verify that it's an indexable C/C++ file
if (!isCppSourceDoc(docPath))
return;
// update unsaved files (we do this even if the document is dirty
// as even in this case it will need to be removed from the list
// of unsaved files)
unsavedFiles().update(pDoc);
// update the main index (but only if it's not dirty as unsaved
// edits are tracked separately)
if (!pDoc->dirty())
sourceIndex().updateTranslationUnit(docPath.absolutePath());
}
// diagnostic function to assist in determine whether/where
// libclang was loaded from (and any errors which occurred
// that prevented loading, e.g. inadequate version, missing
// symbols, etc.)
SEXP rs_isClangAvailable()
{
// check availability
std::string diagnostics;
bool isAvailable = isClangAvailable(&diagnostics);
// print diagnostics
module_context::consoleWriteOutput(diagnostics);
// return status
r::sexp::Protect rProtect;
return r::sexp::create(isAvailable, &rProtect);
}
// incremental file change handler
boost::scoped_ptr<IncrementalFileChangeHandler> pFileChangeHandler;
} // anonymous namespace
bool isClangAvailable()
{
return clang().isLoaded();
}
Error initialize()
{
// attempt to load clang interface
loadClang();
// register diagnostics function
R_CallMethodDef methodDef ;
methodDef.name = "rs_isClangAvailable" ;
methodDef.fun = (DL_FUNC)rs_isClangAvailable;
methodDef.numArgs = 0;
r::routines::addCallMethod(methodDef);
// subscribe to onSourceDocUpdated (used for maintaining both the
// main source index and the unsaved files list)
source_database::events().onDocUpdated.connect(onSourceDocUpdated);
// connect source doc removed events to unsaved files list
source_database::events().onDocRemoved.connect(
boost::bind(&UnsavedFiles::remove, &unsavedFiles(), _1));
source_database::events().onRemoveAll.connect(
boost::bind(&UnsavedFiles::removeAll, &unsavedFiles()));
// create incremental file change handler (this is used for updating
// the main source index). also subscribe it to the file monitor
pFileChangeHandler.reset(new IncrementalFileChangeHandler(
translationUnitFilter,
translationUnitChangeHandler,
boost::posix_time::milliseconds(200),
boost::posix_time::milliseconds(20),
false)); /* allow indexing during idle time */
pFileChangeHandler->subscribeToFileMonitor("C++ Code Completion");
// return success
return Success();
}
} // namespace clang
} // namespace modules
} // namesapce session
<|endoftext|> |
<commit_before>
#include "contactsmodel.h"
#include <kabc/addressee.h>
#include <kabc/contactgroup.h>
#include <kdebug.h>
using namespace Akonadi;
class ContactsModelPrivate
{
public:
ContactsModelPrivate(ContactsModel *model)
: q_ptr(model)
{
}
Q_DECLARE_PUBLIC(ContactsModel);
ContactsModel *q_ptr;
};
ContactsModel::ContactsModel(Session *session, Monitor *monitor, QObject *parent)
: EntityTreeModel(session, monitor, parent)
{
}
ContactsModel::~ContactsModel()
{
}
QVariant ContactsModel::getData(Item item, int column, int role) const
{
if ( item.mimeType() == "text/directory" )
{
if ( !item.hasPayload<KABC::Addressee>() )
{
// Pass modeltest
if (role == Qt::DisplayRole)
return item.remoteId();
return QVariant();
}
const KABC::Addressee addr = item.payload<KABC::Addressee>();
if ((role == Qt::DisplayRole) || (role == Qt::EditRole))
{
switch (column)
{
case 0:
return addr.familyName();
case 1:
return addr.preferredEmail();
case 2:
return addr.givenName() + " " + addr.familyName() + " " + "<" + addr.preferredEmail() + ">";
}
}
}
return EntityTreeModel::getData(item, column, role);
}
QVariant ContactsModel::getData(Collection collection, int column, int role) const
{
if (role == Qt::DisplayRole)
{
switch (column)
{
case 0:
return EntityTreeModel::getData(collection, column, role);
case 1:
return rowCount(EntityTreeModel::indexForCollection(collection));
default:
// Return a QString to pass modeltest.
return QString();
// return QVariant();
}
}
return EntityTreeModel::getData(collection, column, role);
}
int ContactsModel::columnCount(const QModelIndex &index) const
{
Q_UNUSED(index);
return 3;
}
QVariant ContactsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
// if (role == EntityTreeModel::CollectionTreeHeaderDisplayRole)
// {
// switch(section)
// {
// case 0:
// return "Collection";
// case 1:
// return "Count";
// }
//
// } else if (role == EntityTreeModel::ItemListHeaderDisplayRole)
// {
// switch(section)
// {
// case 0:
// return "Given Name";
// case 1:
// return "Family Name";
// }
// }
return EntityTreeModel::headerData(section, orientation, role);
}
#include "contactsmodel.moc"
<commit_msg>Use different header data in the views in the contacts app.<commit_after>
#include "contactsmodel.h"
#include <kabc/addressee.h>
#include <kabc/contactgroup.h>
#include <kdebug.h>
using namespace Akonadi;
class ContactsModelPrivate
{
public:
ContactsModelPrivate(ContactsModel *model)
: q_ptr(model)
{
m_collectionHeaders << "Collection" << "Count";
m_itemHeaders << "Given Name" << "Family Name" << "Email";
}
Q_DECLARE_PUBLIC(ContactsModel);
ContactsModel *q_ptr;
QStringList m_itemHeaders;
QStringList m_collectionHeaders;
};
ContactsModel::ContactsModel(Session *session, Monitor *monitor, QObject *parent)
: EntityTreeModel(session, monitor, parent), d_ptr(new ContactsModelPrivate(this))
{
}
ContactsModel::~ContactsModel()
{
}
QVariant ContactsModel::getData(Item item, int column, int role) const
{
if ( item.mimeType() == "text/directory" )
{
if ( !item.hasPayload<KABC::Addressee>() )
{
// Pass modeltest
if (role == Qt::DisplayRole)
return item.remoteId();
return QVariant();
}
const KABC::Addressee addr = item.payload<KABC::Addressee>();
if ((role == Qt::DisplayRole) || (role == Qt::EditRole))
{
switch (column)
{
case 0:
return addr.givenName();
case 1:
return addr.familyName();
case 2:
return addr.preferredEmail();
case 3:
return addr.givenName() + " " + addr.familyName() + " " + "<" + addr.preferredEmail() + ">";
}
}
}
return EntityTreeModel::getData(item, column, role);
}
QVariant ContactsModel::getData(Collection collection, int column, int role) const
{
if (role == Qt::DisplayRole)
{
switch (column)
{
case 0:
return EntityTreeModel::getData(collection, column, role);
case 1:
return rowCount(EntityTreeModel::indexForCollection(collection));
default:
// Return a QString to pass modeltest.
return QString();
// return QVariant();
}
}
return EntityTreeModel::getData(collection, column, role);
}
int ContactsModel::columnCount(const QModelIndex &index) const
{
Q_UNUSED(index);
return 4;
}
QVariant ContactsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
Q_D(const ContactsModel);
const int roleSectionSize = 1000;
const int headerType = (role / roleSectionSize);
if (orientation == Qt::Horizontal)
{
if (headerType == EntityTreeModel::CollectionTreeHeaders)
{
role %= roleSectionSize;
if (role == Qt::DisplayRole)
{
if (section >= d->m_collectionHeaders.size() )
return QVariant();
return d->m_collectionHeaders.at(section);
}
} else if (headerType == EntityTreeModel::ItemListHeaders)
{
role %= roleSectionSize;
if (role == Qt::DisplayRole)
{
if (section >= d->m_itemHeaders.size() )
return QVariant();
return d->m_itemHeaders.at(section);
}
}
}
return EntityTreeModel::headerData(section, orientation, role);
}
#include "contactsmodel.moc"
<|endoftext|> |
<commit_before>/**
* \file traceroute_results.cc
* \author Andrea Barberio <insomniac@slackware.it>
* \copyright 2-clause BSD
* \date October 2015
* \brief Traceroute results class for dublin-traceroute
*
* This file contains the Traceroute results class for dublin-traceroute.
*
* This class is a container for a per-flow hops representation, and offers
* facilities to print the traceroute output and convert it to a JSON
* representation.
*
* \sa traceroute_results.h
*/
#include <random>
#include <future>
#include "dublintraceroute/traceroute_results.h"
#include "dublintraceroute/icmp_messages.h"
TracerouteResults::TracerouteResults(std::shared_ptr<flow_map_t> flows, const uint8_t min_ttl = 1, const bool broken_nat = true):
flows_(flows), min_ttl(min_ttl), compressed_(false), broken_nat_(broken_nat) {
}
std::shared_ptr<IP> TracerouteResults::match_packet(const Packet &packet) {
// Is this an IP packet?
IP ip;
try {
ip = packet.pdu()->rfind_pdu<IP>();
} catch (pdu_not_found) {
return nullptr;
}
// Does it contain an ICMP response?
ICMP icmp;
try {
icmp = ip.rfind_pdu<ICMP>();
} catch (pdu_not_found) {
return nullptr;
}
// does the ICMP contain an inner IP packet sent by us?
IP inner_ip;
try {
inner_ip = icmp.rfind_pdu<RawPDU>().to<IP>();
} catch (pdu_not_found) {
return nullptr;
}
// does the inner packet contain our original UDP packet?
UDP inner_udp;
try {
inner_udp = inner_ip.rfind_pdu<UDP>();
} catch (pdu_not_found) {
return nullptr;
}
// Try to match the received packet against the sent packets. The flow
// is identified by the UDP destination port
auto flow_id = inner_udp.dport();
// FIXME this can throw std::out_of_range
hops_t hops(flows().at(flow_id));
unsigned int index = 0;
for (auto &hop: *hops) {
auto &sent = hop.sent()->rfind_pdu<IP>();
if (!broken_nat_) {
if (sent.src_addr() != inner_ip.src_addr())
continue;
}
auto &udp = hop.sent()->rfind_pdu<UDP>();
/*
* The original paris-traceroute would match the checksum, but
* this does not work when there is NAT translation. Using the
* IP ID to match the packets works through NAT rewriting
* instead, and only requires the inner IP layer, which is
* guaranteed to return entirely in ICMP ttl-exceeded responses.
*
* To use the paris-traceroute approach, undefine
* USE_IP_ID_MATCHING in common.h .
*/
#ifdef USE_IP_ID_MATCHING
if (udp.checksum() == inner_ip.id()) {
#else /* USE_IP_ID_MATCHING */
if (udp.checksum() == inner_udp.checksum()) {
#endif /* USE_IP_ID_MATCHING */
try {
hop.received(ip, packet.timestamp());
return std::make_shared<IP>(ip);
} catch (std::out_of_range) {
// this should never happen
throw;
}
}
index++;
}
return nullptr;
}
void TracerouteResults::show(std::ostream &stream) {
compress();
icmpmessages icmpm;
for (auto &iter: flows()) {
unsigned int hopnum = min_ttl;
unsigned int index = 0;
uint16_t prev_nat_id = 0;
stream << "== Flow ID " << iter.first << " ==" << std::endl;
for (auto &hop: *iter.second) {
stream << hopnum << " ";
if (!hop) {
stream << "*" << std::endl;
} else {
// print the IP address of the hop
stream << hop.received()->src_addr() << " (" << *hop.name() << ")";
// print the response IP ID, useful to detect
// loops due to NATs, fake hops, etc
stream << ", IP ID: " << hop.received()->id();
// print the RTT
std::stringstream rttss;
rttss << (hop.rtt() / 1000) << "." << (hop.rtt() % 1000) << " ms ";
stream << " RTT " << rttss.str();
// print the ICMP type and code
ICMP icmp;
try {
icmp = hop.received()->rfind_pdu<ICMP>();
stream << " ICMP "
<< "(type=" << icmp.type() << ", code=" << static_cast<int>(icmp.code()) << ") '"
<< icmpm.get(icmp.type(), icmp.code()) << "'";
if (icmp.has_extensions()) {
for (auto &extension : icmp.extensions().extensions()) {
unsigned int ext_class = static_cast<unsigned int>(extension.extension_class());
unsigned int ext_type = static_cast<unsigned int>(extension.extension_type());
auto &payload = extension.payload();
if (ext_class == ICMP_EXTENSION_MPLS_CLASS && ext_type == ICMP_EXTENSION_MPLS_TYPE) {
// expecting size to be a multiple of 4 in valid MPLS label stacks
unsigned int num_labels = (extension.size() - 4) / 4;
for (unsigned int idx = 0; idx < payload.size() ; idx += 4) {
unsigned int label = (payload[idx + 0] << 12) + (payload[idx + 1] << 4) + (payload[idx + 2] >> 4);
unsigned int experimental = (payload[idx + 2] & 0x0f) >> 1;
unsigned int bottom_of_stack = payload[idx + 2] & 0x01;
unsigned int ttl = payload[idx + 3];
stream << ", MPLS(label=" << label << ", experimental=" << experimental << ", bottom_of_stack=" << bottom_of_stack << ", ttl=" << ttl << ")";
}
} else {
stream
<< ", Extension("
<< "class=" << ext_class
<< ", type=" << ext_type
<< ", payload_size=" << payload.size()
<< ")";
}
}
}
} catch (pdu_not_found) {
}
/* NAT detection.
* Note that if the previous hop was not
* responding, the detected NAT could have been
* started before
*/
auto inner_ip = hop.received()->rfind_pdu<RawPDU>().to<IP>();
stream << ", NAT ID: " << hop.nat_id();
if (hopnum > 1 && hop.nat_id() != prev_nat_id)
stream << " (NAT detected)";
prev_nat_id = hop.nat_id();
stream << std::endl;
}
// Break if we reached the target hop
if (hop.is_last_hop())
break;
hopnum++;
index++;
}
}
}
void TracerouteResults::compress() {
/** \brief compress the traceroute graph
*
* Compress the traceroute graph in order to remove repetitions of
* non-responding hops (i.e. the ones that show a "*" in a traceroute).
*
* Implementation note: this is not actually a compression, since the
* traceroute is not implemented (yet) as a graph, but this will come in
* a future release. Currently this method simply marks the first
* non-responding hop at the end of a path as last-hop.
*
* It is safe to call this method multiple times, and there is no
* performance penalty.
*/
if (compressed_)
return;
for (auto &iter: flows()) {
IPv4Address target = iter.second->at(0).sent()->dst_addr();
for (auto hop = iter.second->rbegin(); hop != iter.second->rend(); hop++) {
// TODO also check for ICMP type==3 and code==3
if (hop->received()) {
if (hop->received()->src_addr() != target)
break;
}
hop->is_last_hop(true);
}
}
compressed_ = true;
}
std::string TracerouteResults::to_json() {
compress();
std::stringstream json;
Json::Value root;
for (auto &iter: flows()) {
auto flow_id = std::to_string(iter.first);
Json::Value hops(Json::arrayValue);
for (auto &hop: *iter.second) {
hops.append(hop.to_json());
if (hop.is_last_hop())
break;
}
root["flows"][flow_id] = hops;
}
json << root;
return json.str();
}
<commit_msg>Fixed long-standing old bug<commit_after>/**
* \file traceroute_results.cc
* \author Andrea Barberio <insomniac@slackware.it>
* \copyright 2-clause BSD
* \date October 2015
* \brief Traceroute results class for dublin-traceroute
*
* This file contains the Traceroute results class for dublin-traceroute.
*
* This class is a container for a per-flow hops representation, and offers
* facilities to print the traceroute output and convert it to a JSON
* representation.
*
* \sa traceroute_results.h
*/
#include <random>
#include <future>
#include "dublintraceroute/traceroute_results.h"
#include "dublintraceroute/icmp_messages.h"
TracerouteResults::TracerouteResults(std::shared_ptr<flow_map_t> flows, const uint8_t min_ttl = 1, const bool broken_nat = true):
flows_(flows), min_ttl(min_ttl), compressed_(false), broken_nat_(broken_nat) {
}
std::shared_ptr<IP> TracerouteResults::match_packet(const Packet &packet) {
// Is this an IP packet?
IP ip;
try {
ip = packet.pdu()->rfind_pdu<IP>();
} catch (pdu_not_found) {
return nullptr;
}
// Does it contain an ICMP response?
ICMP icmp;
try {
icmp = ip.rfind_pdu<ICMP>();
} catch (pdu_not_found) {
return nullptr;
}
// does the ICMP contain an inner IP packet sent by us?
IP inner_ip;
try {
inner_ip = icmp.rfind_pdu<RawPDU>().to<IP>();
} catch (pdu_not_found) {
return nullptr;
}
// does the inner packet contain our original UDP packet?
UDP inner_udp;
try {
inner_udp = inner_ip.rfind_pdu<UDP>();
} catch (pdu_not_found) {
return nullptr;
}
// Try to match the received packet against the sent packets. The flow
// is identified by the UDP destination port
auto flow_id = inner_udp.dport();
hops_t hops;
try {
hops = flows().at(flow_id);
} catch (std::out_of_range) {
return nullptr;
}
unsigned int index = 0;
for (auto &hop: *hops) {
auto &sent = hop.sent()->rfind_pdu<IP>();
if (!broken_nat_) {
if (sent.src_addr() != inner_ip.src_addr())
continue;
}
auto &udp = hop.sent()->rfind_pdu<UDP>();
/*
* The original paris-traceroute would match the checksum, but
* this does not work when there is NAT translation. Using the
* IP ID to match the packets works through NAT rewriting
* instead, and only requires the inner IP layer, which is
* guaranteed to return entirely in ICMP ttl-exceeded responses.
*
* To use the paris-traceroute approach, undefine
* USE_IP_ID_MATCHING in common.h .
*/
#ifdef USE_IP_ID_MATCHING
if (udp.checksum() == inner_ip.id()) {
#else /* USE_IP_ID_MATCHING */
if (udp.checksum() == inner_udp.checksum()) {
#endif /* USE_IP_ID_MATCHING */
try {
hop.received(ip, packet.timestamp());
return std::make_shared<IP>(ip);
} catch (std::out_of_range) {
// this should never happen
throw;
}
}
index++;
}
return nullptr;
}
void TracerouteResults::show(std::ostream &stream) {
compress();
icmpmessages icmpm;
for (auto &iter: flows()) {
unsigned int hopnum = min_ttl;
unsigned int index = 0;
uint16_t prev_nat_id = 0;
stream << "== Flow ID " << iter.first << " ==" << std::endl;
for (auto &hop: *iter.second) {
stream << hopnum << " ";
if (!hop) {
stream << "*" << std::endl;
} else {
// print the IP address of the hop
stream << hop.received()->src_addr() << " (" << *hop.name() << ")";
// print the response IP ID, useful to detect
// loops due to NATs, fake hops, etc
stream << ", IP ID: " << hop.received()->id();
// print the RTT
std::stringstream rttss;
rttss << (hop.rtt() / 1000) << "." << (hop.rtt() % 1000) << " ms ";
stream << " RTT " << rttss.str();
// print the ICMP type and code
ICMP icmp;
try {
icmp = hop.received()->rfind_pdu<ICMP>();
stream << " ICMP "
<< "(type=" << icmp.type() << ", code=" << static_cast<int>(icmp.code()) << ") '"
<< icmpm.get(icmp.type(), icmp.code()) << "'";
if (icmp.has_extensions()) {
for (auto &extension : icmp.extensions().extensions()) {
unsigned int ext_class = static_cast<unsigned int>(extension.extension_class());
unsigned int ext_type = static_cast<unsigned int>(extension.extension_type());
auto &payload = extension.payload();
if (ext_class == ICMP_EXTENSION_MPLS_CLASS && ext_type == ICMP_EXTENSION_MPLS_TYPE) {
// expecting size to be a multiple of 4 in valid MPLS label stacks
unsigned int num_labels = (extension.size() - 4) / 4;
for (unsigned int idx = 0; idx < payload.size() ; idx += 4) {
unsigned int label = (payload[idx + 0] << 12) + (payload[idx + 1] << 4) + (payload[idx + 2] >> 4);
unsigned int experimental = (payload[idx + 2] & 0x0f) >> 1;
unsigned int bottom_of_stack = payload[idx + 2] & 0x01;
unsigned int ttl = payload[idx + 3];
stream << ", MPLS(label=" << label << ", experimental=" << experimental << ", bottom_of_stack=" << bottom_of_stack << ", ttl=" << ttl << ")";
}
} else {
stream
<< ", Extension("
<< "class=" << ext_class
<< ", type=" << ext_type
<< ", payload_size=" << payload.size()
<< ")";
}
}
}
} catch (pdu_not_found) {
}
/* NAT detection.
* Note that if the previous hop was not
* responding, the detected NAT could have been
* started before
*/
auto inner_ip = hop.received()->rfind_pdu<RawPDU>().to<IP>();
stream << ", NAT ID: " << hop.nat_id();
if (hopnum > 1 && hop.nat_id() != prev_nat_id)
stream << " (NAT detected)";
prev_nat_id = hop.nat_id();
stream << std::endl;
}
// Break if we reached the target hop
if (hop.is_last_hop())
break;
hopnum++;
index++;
}
}
}
void TracerouteResults::compress() {
/** \brief compress the traceroute graph
*
* Compress the traceroute graph in order to remove repetitions of
* non-responding hops (i.e. the ones that show a "*" in a traceroute).
*
* Implementation note: this is not actually a compression, since the
* traceroute is not implemented (yet) as a graph, but this will come in
* a future release. Currently this method simply marks the first
* non-responding hop at the end of a path as last-hop.
*
* It is safe to call this method multiple times, and there is no
* performance penalty.
*/
if (compressed_)
return;
for (auto &iter: flows()) {
IPv4Address target = iter.second->at(0).sent()->dst_addr();
for (auto hop = iter.second->rbegin(); hop != iter.second->rend(); hop++) {
// TODO also check for ICMP type==3 and code==3
if (hop->received()) {
if (hop->received()->src_addr() != target)
break;
}
hop->is_last_hop(true);
}
}
compressed_ = true;
}
std::string TracerouteResults::to_json() {
compress();
std::stringstream json;
Json::Value root;
for (auto &iter: flows()) {
auto flow_id = std::to_string(iter.first);
Json::Value hops(Json::arrayValue);
for (auto &hop: *iter.second) {
hops.append(hop.to_json());
if (hop.is_last_hop())
break;
}
root["flows"][flow_id] = hops;
}
json << root;
return json.str();
}
<|endoftext|> |
<commit_before><commit_msg>remove testing FIXME<commit_after><|endoftext|> |
<commit_before>#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include <QMap>
#include <algorithm>
#include <utility>
#include <map>
#include <unordered_map>
#include "qfasthash_p.h"
#include <stdint.h>
#ifdef USE_BOOST
#include <boost/unordered_map.hpp>
#endif
#ifdef TEST_KEY_STRING
namespace std{
/* std::hash specialization for QString so it can be used
* as a key in std::unordered_map */
template<class Key> struct hash;
template<> struct hash<QString> {
typedef QString Key;
typedef uint result_type;
inline uint operator()(const QString &s) const { return qHash(s); }
};
}
static std::vector<QString> s_vec;
void createStringNumberArray(int n)
{
if(n >= s_vec.size())
{
for (int i=s_vec.size(); i <= n; ++i)
s_vec.push_back(QString::number(i));
}
}
typedef QString tTestKey;
#define MAKE_KEY(x) s_vec[x]
//#define MAKE_KEY(x) QString::number(x)
#else
typedef int32_t tTestKey;
#define MAKE_KEY(x) x
#endif
typedef int32_t tTestValue;
struct tVecData
{
tVecData(tTestKey f,tTestValue s)
:first(f)
,second(s)
{}
tVecData()
:
#ifndef TEST_KEY_STRING
first(0),
#endif
second(0)
{}
bool operator<( const tVecData &t2) const
{
return first < t2.first;
}
tTestKey first;
tTestValue second;
};
class Map_hast_Test : public QObject
{
Q_OBJECT
public:
Map_hast_Test();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testCase_insert_data();
void testCase_insert();
void testCase_find();
void testCase_find_data();
};
Map_hast_Test::Map_hast_Test()
{
}
void Map_hast_Test::initTestCase()
{
}
void Map_hast_Test::cleanupTestCase()
{
}
static int testcounts[] = {5,7,10,12,15,17,20,25,29,34,41,47, 50,75,80,90,100};//,1000,10000,100000,1000000};
void Map_hast_Test::testCase_insert_data()
{
QTest::addColumn<QString>("testcontainer");
QTest::addColumn<int>("testcount");
QString testContainer;
static const char * tests[] = {
"QMap_insert",
"QHash_insert",
"stdmap_insert",
"stdunordered_insert",
"qfasthash_insert",
#ifdef USE_BOOST
"boostunordered_insert"
#endif
};
for (unsigned int t = 0; t < sizeof(tests)/sizeof(tests[0]);++t)
{
for(int count : testcounts)
{
QString text;
text += QLatin1String(tests[t]);
text = text.leftJustified(20, ' ', true);
text += QLatin1String(" -- ");
text += QString::number(count).leftJustified(12, ' ');
QTest::newRow(text.toLatin1().constData()) << QString(tests[t]) << count;
}
}
}
void Map_hast_Test::testCase_find_data()
{
QTest::addColumn<QString>("testcontainer");
QTest::addColumn<int>("testcount");
QString testContainer;
static const char * tests[] = {
"QMap_find",
"QMap_constFind",
"QHash_find",
"QHash_constFind",
"QVector_lowerbound",
"stdvector_lowerbound",
"stdmap_find",
"stdunordered_find",
"qfasthash_find",
#ifdef USE_BOOST
"boostunordered_find"
#endif
};
for (unsigned int t = 0; t < sizeof(tests)/sizeof(tests[0]);++t)
{
for(int count : testcounts)
{
QString text;
text += QLatin1String(tests[t]);
text = text.leftJustified(20, ' ', true);
text += QLatin1String(" -- ");
text += QString::number(count).leftJustified(12, ' ');
QTest::newRow(text.toLatin1().constData()) << QString(tests[t]) << count;
}
}
}
inline void insertdata(QMap<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m.insert(MAKE_KEY(i),i);
}
}
inline void insertdata(QHash<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m.insert(MAKE_KEY(i),i);
}
}
inline void insertdata(std::map<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
inline void insertdata(std::unordered_map <tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
#ifdef USE_BOOST
inline void insertdata(boost::unordered_map <tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
#endif
inline void insertdata(QFastHash<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
void Map_hast_Test::testCase_insert()
{
QFETCH(QString,testcontainer);
QFETCH(int,testcount);
#ifdef TEST_KEY_STRING
createStringNumberArray(testcount);
#endif
if(testcontainer == QLatin1String("QMap_insert"))
{
QMap<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(*it != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("QHash_insert"))
{
QHash<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(*it != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("stdmap_insert"))
{
std::map<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(it->second != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("stdunordered_insert"))
{
std::unordered_map<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(it->second != testcount) QFAIL( "fail");
}
#ifdef USE_BOOST
else if (testcontainer == QLatin1String("boostunordered_insert"))
{
boost::unordered_map<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount);
if(it->second != testcount) QFAIL( "fail");
}
#endif
else if (testcontainer == QLatin1String("qfasthash_insert"))
{
QFastHash<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.constFind(MAKE_KEY(testcount));
if(it != testcount) QFAIL( "fail");
}
}
void Map_hast_Test::testCase_find()
{
QFETCH(QString,testcontainer);
QFETCH(int,testcount);
#ifdef TEST_KEY_STRING
createStringNumberArray(testcount);
#endif
if(testcontainer == QLatin1String("QMap_find"))
{
QMap<tTestKey,tTestValue> m_mapTest;
insertdata(m_mapTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_mapTest.find(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QMap_constFind"))
{
QMap<tTestKey,tTestValue> m_mapTest;
insertdata(m_mapTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_mapTest.constFind(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QHash_find"))
{
QHash<tTestKey,tTestValue> m_hashTest;
insertdata(m_hashTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_hashTest.find(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QHash_constFind"))
{
QHash<tTestKey,tTestValue> m_hashTest;
insertdata(m_hashTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_hashTest.constFind(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QVector_lowerbound"))
{
QVector<tVecData> m_vecTest;
for(int i = 1 ;i<= testcount ;++i)
{
m_vecTest.push_back(tVecData(MAKE_KEY(i),i));
}
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = std::lower_bound(std::begin(m_vecTest),std::end(m_vecTest),tVecData(MAKE_KEY(i),0));
if(it->second != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("stdvector_lowerbound"))
{
std::vector<tVecData> m_vecTest;
for(int i = 1 ;i<= testcount ;++i)
{
m_vecTest.push_back(tVecData(MAKE_KEY(i),i));
}
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = std::lower_bound(std::begin(m_vecTest),std::end(m_vecTest),tVecData(MAKE_KEY(i),0));
if(it->second != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("stdmap_find"))
{
std::map<tTestKey,tTestValue> m_stdmapTest;
insertdata(m_stdmapTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_stdmapTest.find(MAKE_KEY(i));
if(it->second != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("stdunordered_find"))
{
std::unordered_map <tTestKey,tTestValue> m_stdunorderedTest;
insertdata(m_stdunorderedTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_stdunorderedTest.find(MAKE_KEY(i));
if(it->second != i) QFAIL( "fail");
}
}
}
#ifdef USE_BOOST
else if (testcontainer == QLatin1String("boostunordered_find"))
{
boost::unordered_map <tTestKey,tTestValue> m_stdunorderedTest;
insertdata(m_stdunorderedTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_stdunorderedTest.find(MAKE_KEY(i);
if(it->second != i) QFAIL( "fail");
}
}
}
#endif
else if (testcontainer == QLatin1String("qfasthash_find"))
{
QFastHash<tTestKey,tTestValue> m_fasthash_Test;
insertdata(m_fasthash_Test,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_fasthash_Test.constFind(MAKE_KEY(i));
if(it != i) QFAIL( "fail");
}
}
}
else
{
QFAIL( "fail, unknown test ");
}
}
QTEST_MAIN(Map_hast_Test)
#include "tst_map_hast_test.moc"
<commit_msg>fix merge from master, remove warning<commit_after>#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include <QMap>
#include <algorithm>
#include <utility>
#include <map>
#include <unordered_map>
#include "qfasthash_p.h"
#include <stdint.h>
#ifdef USE_BOOST
#include <boost/unordered_map.hpp>
#endif
#ifdef TEST_KEY_STRING
namespace std{
/* std::hash specialization for QString so it can be used
* as a key in std::unordered_map */
template<class Key> struct hash;
template<> struct hash<QString> {
typedef QString Key;
typedef uint result_type;
inline uint operator()(const QString &s) const { return qHash(s); }
};
}
static std::vector<QString> s_vec;
void createStringNumberArray(size_t n)
{
if(n >= s_vec.size())
{
for (auto i=s_vec.size(); i <= n; ++i)
s_vec.push_back(QString::number(i));
}
}
typedef QString tTestKey;
#define MAKE_KEY(x) s_vec[x]
//#define MAKE_KEY(x) QString::number(x)
#else
typedef int32_t tTestKey;
#define MAKE_KEY(x) x
#endif
typedef int32_t tTestValue;
struct tVecData
{
tVecData(tTestKey f,tTestValue s)
:first(f)
,second(s)
{}
tVecData()
:
#ifndef TEST_KEY_STRING
first(0),
#endif
second(0)
{}
bool operator<( const tVecData &t2) const
{
return first < t2.first;
}
tTestKey first;
tTestValue second;
};
class Map_hast_Test : public QObject
{
Q_OBJECT
public:
Map_hast_Test();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testCase_insert_data();
void testCase_insert();
void testCase_find();
void testCase_find_data();
};
Map_hast_Test::Map_hast_Test()
{
}
void Map_hast_Test::initTestCase()
{
}
void Map_hast_Test::cleanupTestCase()
{
}
static int testcounts[] = {5,7,10,12,15,17,20,25,29,34,41,47, 50,75,80,90,100,1000,10000};//,1000,10000,100000,1000000};
void Map_hast_Test::testCase_insert_data()
{
QTest::addColumn<QString>("testcontainer");
QTest::addColumn<int>("testcount");
QString testContainer;
static const char * tests[] = {
"QMap_insert",
"QHash_insert",
"stdmap_insert",
"stdvector_pb_sort",
"stdunordered_insert",
"qfasthash_insert",
#ifdef USE_BOOST
"boostunordered_insert"
#endif
};
for (unsigned int t = 0; t < sizeof(tests)/sizeof(tests[0]);++t)
{
for(int count : testcounts)
{
QString text;
text += QLatin1String(tests[t]);
text = text.leftJustified(20, ' ', true);
text += QLatin1String(" -- ");
text += QString::number(count).leftJustified(12, ' ');
QTest::newRow(text.toLatin1().constData()) << QString(tests[t]) << count;
}
}
}
void Map_hast_Test::testCase_find_data()
{
QTest::addColumn<QString>("testcontainer");
QTest::addColumn<int>("testcount");
QString testContainer;
static const char * tests[] = {
"QMap_find",
"QMap_constFind",
"QHash_find",
"QHash_constFind",
"QVector_lowerbound",
"stdvector_lowerbound",
"stdmap_find",
"stdunordered_find",
"qfasthash_find",
#ifdef USE_BOOST
"boostunordered_find"
#endif
};
for (unsigned int t = 0; t < sizeof(tests)/sizeof(tests[0]);++t)
{
for(int count : testcounts)
{
QString text;
text += QLatin1String(tests[t]);
text = text.leftJustified(20, ' ', true);
text += QLatin1String(" -- ");
text += QString::number(count).leftJustified(12, ' ');
QTest::newRow(text.toLatin1().constData()) << QString(tests[t]) << count;
}
}
}
inline void insertdata(QMap<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m.insert(MAKE_KEY(i),i);
}
}
inline void insertdata(QHash<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m.insert(MAKE_KEY(i),i);
}
}
inline void insertdata(std::map<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
inline void insertdata(std::unordered_map <tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
#ifdef USE_BOOST
inline void insertdata(boost::unordered_map <tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
#endif
inline void insertdata(QFastHash<tTestKey,tTestValue> & m,int testcount)
{
for(int i = testcount ;i> 0 ;--i)
{
m[MAKE_KEY(i)]=i;
}
}
inline void insertdata(std::vector<tVecData> & m,int testcount)
{
for(int i = testcount ;i>0 ;--i)
{
m.push_back(tVecData(MAKE_KEY(i),i));
}
std::sort(std::begin(m),std::end(m),std::less<tVecData>());
}
void Map_hast_Test::testCase_insert()
{
QFETCH(QString,testcontainer);
QFETCH(int,testcount);
#ifdef TEST_KEY_STRING
createStringNumberArray(testcount);
#endif
if(testcontainer == QLatin1String("QMap_insert"))
{
QMap<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(*it != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("QHash_insert"))
{
QHash<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(*it != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("stdvector_pb_sort"))
{
std::vector<tVecData> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = std::lower_bound(std::begin(m),std::end(m),tVecData(MAKE_KEY(testcount),0));
if(it->second != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("stdmap_insert"))
{
std::map<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(it->second != testcount) QFAIL( "fail");
}
else if (testcontainer == QLatin1String("stdunordered_insert"))
{
std::unordered_map<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount));
if(it->second != testcount) QFAIL( "fail");
}
#ifdef USE_BOOST
else if (testcontainer == QLatin1String("boostunordered_insert"))
{
boost::unordered_map<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.find(MAKE_KEY(testcount);
if(it->second != testcount) QFAIL( "fail");
}
#endif
else if (testcontainer == QLatin1String("qfasthash_insert"))
{
QFastHash<tTestKey,tTestValue> m;
QBENCHMARK {
insertdata(m,testcount);
}
auto it = m.constFind(MAKE_KEY(testcount));
if(it != testcount) QFAIL( "fail");
}
}
void Map_hast_Test::testCase_find()
{
QFETCH(QString,testcontainer);
QFETCH(int,testcount);
#ifdef TEST_KEY_STRING
createStringNumberArray(testcount);
#endif
if(testcontainer == QLatin1String("QMap_find"))
{
QMap<tTestKey,tTestValue> m_mapTest;
insertdata(m_mapTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_mapTest.find(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QMap_constFind"))
{
QMap<tTestKey,tTestValue> m_mapTest;
insertdata(m_mapTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_mapTest.constFind(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QHash_find"))
{
QHash<tTestKey,tTestValue> m_hashTest;
insertdata(m_hashTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_hashTest.find(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QHash_constFind"))
{
QHash<tTestKey,tTestValue> m_hashTest;
insertdata(m_hashTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_hashTest.constFind(MAKE_KEY(i));
if(*it != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("QVector_lowerbound"))
{
QVector<tVecData> m_vecTest;
for(int i = 1 ;i<= testcount ;++i)
{
m_vecTest.push_back(tVecData(MAKE_KEY(i),i));
}
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = std::lower_bound(std::begin(m_vecTest),std::end(m_vecTest),tVecData(MAKE_KEY(i),0));
if(it->second != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("stdvector_lowerbound"))
{
std::vector<tVecData> m_vecTest;
for(int i = 1 ;i<= testcount ;++i)
{
m_vecTest.push_back(tVecData(MAKE_KEY(i),i));
}
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = std::lower_bound(std::begin(m_vecTest),std::end(m_vecTest),tVecData(MAKE_KEY(i),0));
if(it->second != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("stdmap_find"))
{
std::map<tTestKey,tTestValue> m_stdmapTest;
insertdata(m_stdmapTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_stdmapTest.find(MAKE_KEY(i));
if(it->second != i) QFAIL( "fail");
}
}
}
else if (testcontainer == QLatin1String("stdunordered_find"))
{
std::unordered_map <tTestKey,tTestValue> m_stdunorderedTest;
insertdata(m_stdunorderedTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_stdunorderedTest.find(MAKE_KEY(i));
if(it->second != i) QFAIL( "fail");
}
}
}
#ifdef USE_BOOST
else if (testcontainer == QLatin1String("boostunordered_find"))
{
boost::unordered_map <tTestKey,tTestValue> m_stdunorderedTest;
insertdata(m_stdunorderedTest,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_stdunorderedTest.find(MAKE_KEY(i);
if(it->second != i) QFAIL( "fail");
}
}
}
#endif
else if (testcontainer == QLatin1String("qfasthash_find"))
{
QFastHash<tTestKey,tTestValue> m_fasthash_Test;
insertdata(m_fasthash_Test,testcount);
QBENCHMARK {
for(int i = 1 ;i <= testcount ;++i)
{
auto it = m_fasthash_Test.constFind(MAKE_KEY(i));
if(it != i) QFAIL( "fail");
}
}
}
else
{
QFAIL( "fail, unknown test ");
}
}
QTEST_MAIN(Map_hast_Test)
#include "tst_map_hast_test.moc"
<|endoftext|> |
<commit_before>#include "FactorizationElf.h"
#include "FactorizationScheduler.h"
#include "main/ProblemStatement.h"
#include <memory>
#include <mpi.h>
#include <stdexcept>
#include <vector>
using namespace std;
using namespace std::chrono;
FactorizationScheduler::FactorizationScheduler() :
Scheduler()
{
}
FactorizationScheduler::FactorizationScheduler(const BenchmarkResult& result) :
Scheduler(result)
{
}
void FactorizationScheduler::provideData(ProblemStatement& statement)
{
*(statement.input) >> number;
if (statement.input->fail())
throw runtime_error("Failed to read BigInt from ProblemStatement in " __FILE__);
}
void FactorizationScheduler::outputData(ProblemStatement& statement)
{
*(statement.output) << a << endl;
*(statement.output) << b << endl;
}
void FactorizationScheduler::doDispatch()
{
distributeNumber();
future<BigIntPair> f = async(launch::async, [&]{
return factorizeNumber();
});
int rank = distributeFinishedStateRegularly(f);
stopFactorization();
sendResultToMaster(rank, f);
}
bool FactorizationScheduler::hasData()
{
return number != 0;
}
void FactorizationScheduler::distributeNumber()
{
if (MpiHelper::isMaster())
{
vector<uint32_t> items = number.buffer();
unsigned long size = items.size();
MPI::COMM_WORLD.Bcast(&size, 1, MPI::UNSIGNED_LONG, MpiHelper::MASTER);
MPI::COMM_WORLD.Bcast(items.data(), size, MPI::UNSIGNED, MpiHelper::MASTER);
}
else
{
unsigned long size = 0;
MPI::COMM_WORLD.Bcast(&size, 1, MPI::UNSIGNED_LONG, MpiHelper::MASTER);
unique_ptr<uint32_t[]> items(new uint32_t[size]);
MPI::COMM_WORLD.Bcast(items.get(), size, MPI::UNSIGNED, MpiHelper::MASTER);
number = BigInt(vector<uint32_t>(items.get(), items.get() + size));
}
}
FactorizationScheduler::BigIntPair FactorizationScheduler::factorizeNumber()
{
FactorizationElf* factorizer = dynamic_cast<FactorizationElf*>(elf);
if (factorizer == nullptr)
return BigIntPair(0, 0);
BigIntPair result = factorizer->factorize(number);
return result;
}
void FactorizationScheduler::sendResultToMaster(int rank, future<BigIntPair>& f)
{
if (!MpiHelper::isMaster() && rank != MpiHelper::rank())
return;
if (rank == MpiHelper::rank())
{
BigIntPair pair = f.get();
a = pair.first;
b = pair.second;
}
if (MpiHelper::isMaster())
{
unsigned long sizes[] = { 0, 0 };
MPI::COMM_WORLD.Recv(sizes, 2, MPI::UNSIGNED_LONG, rank, 1);
unique_ptr<uint32_t[]> first(new uint32_t[sizes[0]]);
unique_ptr<uint32_t[]> second(new uint32_t[sizes[1]]);
MPI::COMM_WORLD.Recv(first.get(), sizes[0], MPI::UNSIGNED, rank, 2);
MPI::COMM_WORLD.Recv(second.get(), sizes[1], MPI::UNSIGNED, rank, 3);
a = BigInt(vector<uint32_t>(first.get(), first.get() + sizes[0]));
b = BigInt(vector<uint32_t>(second.get(), second.get() + sizes[1]));
}
else
{
vector<uint32_t> first = a.buffer();
vector<uint32_t> second = b.buffer();
unsigned long sizes[] = { first.size(), second.size() };
MPI::COMM_WORLD.Send(sizes, 2, MPI::UNSIGNED_LONG, MpiHelper::MASTER, 1);
MPI::COMM_WORLD.Send(first.data(), first.size(), MPI::UNSIGNED, MpiHelper::MASTER, 2);
MPI::COMM_WORLD.Send(second.data(), second.size(), MPI::UNSIGNED, MpiHelper::MASTER, 3);
}
}
int FactorizationScheduler::distributeFinishedStateRegularly(future<BigIntPair>& f) const
{
unique_ptr<bool[]> states(new bool[MpiHelper::numberOfNodes()]);
while (true)
{
bool finished = f.wait_for(seconds(5)) == future_status::ready;
MPI::COMM_WORLD.Allgather(
&finished, 1, MPI::BOOL,
states.get(), 1, MPI::BOOL
);
for (size_t i=0; i<MpiHelper::numberOfNodes(); i++)
{
if (states[i])
return i;
}
}
}
void FactorizationScheduler::stopFactorization()
{
FactorizationElf* factorizer = dynamic_cast<FactorizationElf*>(elf);
if (factorizer == nullptr)
return;
factorizer->stop();
}
<commit_msg>BugFix: If the MPI master found the number factorization first, he don't have to wait for himself to send the results (deadlock otherwise)<commit_after>#include "FactorizationElf.h"
#include "FactorizationScheduler.h"
#include "main/ProblemStatement.h"
#include <memory>
#include <mpi.h>
#include <stdexcept>
#include <vector>
using namespace std;
using namespace std::chrono;
FactorizationScheduler::FactorizationScheduler() :
Scheduler()
{
}
FactorizationScheduler::FactorizationScheduler(const BenchmarkResult& result) :
Scheduler(result)
{
}
void FactorizationScheduler::provideData(ProblemStatement& statement)
{
*(statement.input) >> number;
if (statement.input->fail())
throw runtime_error("Failed to read BigInt from ProblemStatement in " __FILE__);
}
void FactorizationScheduler::outputData(ProblemStatement& statement)
{
*(statement.output) << a << endl;
*(statement.output) << b << endl;
}
void FactorizationScheduler::doDispatch()
{
distributeNumber();
future<BigIntPair> f = async(launch::async, [&]{
return factorizeNumber();
});
int rank = distributeFinishedStateRegularly(f);
stopFactorization();
sendResultToMaster(rank, f);
}
bool FactorizationScheduler::hasData()
{
return number != 0;
}
void FactorizationScheduler::distributeNumber()
{
if (MpiHelper::isMaster())
{
vector<uint32_t> items = number.buffer();
unsigned long size = items.size();
MPI::COMM_WORLD.Bcast(&size, 1, MPI::UNSIGNED_LONG, MpiHelper::MASTER);
MPI::COMM_WORLD.Bcast(items.data(), size, MPI::UNSIGNED, MpiHelper::MASTER);
}
else
{
unsigned long size = 0;
MPI::COMM_WORLD.Bcast(&size, 1, MPI::UNSIGNED_LONG, MpiHelper::MASTER);
unique_ptr<uint32_t[]> items(new uint32_t[size]);
MPI::COMM_WORLD.Bcast(items.get(), size, MPI::UNSIGNED, MpiHelper::MASTER);
number = BigInt(vector<uint32_t>(items.get(), items.get() + size));
}
}
FactorizationScheduler::BigIntPair FactorizationScheduler::factorizeNumber()
{
FactorizationElf* factorizer = dynamic_cast<FactorizationElf*>(elf);
if (factorizer == nullptr)
return BigIntPair(0, 0);
BigIntPair result = factorizer->factorize(number);
return result;
}
void FactorizationScheduler::sendResultToMaster(int rank, future<BigIntPair>& f)
{
if (!MpiHelper::isMaster() && rank != MpiHelper::rank())
return;
if (rank == MpiHelper::rank())
{
BigIntPair pair = f.get();
a = pair.first;
b = pair.second;
}
// if the master found the result, nothing more to do
if(MpiHelper::isMaster(rank))
return;
// a slave found the result, he has to send it to the master
if (MpiHelper::isMaster())
{
unsigned long sizes[] = { 0, 0 };
MPI::COMM_WORLD.Recv(sizes, 2, MPI::UNSIGNED_LONG, rank, 1);
unique_ptr<uint32_t[]> first(new uint32_t[sizes[0]]);
unique_ptr<uint32_t[]> second(new uint32_t[sizes[1]]);
MPI::COMM_WORLD.Recv(first.get(), sizes[0], MPI::UNSIGNED, rank, 2);
MPI::COMM_WORLD.Recv(second.get(), sizes[1], MPI::UNSIGNED, rank, 3);
a = BigInt(vector<uint32_t>(first.get(), first.get() + sizes[0]));
b = BigInt(vector<uint32_t>(second.get(), second.get() + sizes[1]));
}
else
{
vector<uint32_t> first = a.buffer();
vector<uint32_t> second = b.buffer();
unsigned long sizes[] = { first.size(), second.size() };
MPI::COMM_WORLD.Send(sizes, 2, MPI::UNSIGNED_LONG, MpiHelper::MASTER, 1);
MPI::COMM_WORLD.Send(first.data(), first.size(), MPI::UNSIGNED, MpiHelper::MASTER, 2);
MPI::COMM_WORLD.Send(second.data(), second.size(), MPI::UNSIGNED, MpiHelper::MASTER, 3);
}
}
int FactorizationScheduler::distributeFinishedStateRegularly(future<BigIntPair>& f) const
{
unique_ptr<bool[]> states(new bool[MpiHelper::numberOfNodes()]);
while (true)
{
bool finished = f.wait_for(seconds(5)) == future_status::ready;
MPI::COMM_WORLD.Allgather(
&finished, 1, MPI::BOOL,
states.get(), 1, MPI::BOOL
);
for (size_t i=0; i<MpiHelper::numberOfNodes(); i++)
{
if (states[i])
return i;
}
}
}
void FactorizationScheduler::stopFactorization()
{
FactorizationElf* factorizer = dynamic_cast<FactorizationElf*>(elf);
if (factorizer == nullptr)
return;
factorizer->stop();
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.10 2000/03/28 19:43:19 roddey
* Fixes for signed/unsigned warnings. New work for two way transcoding
* stuff.
*
* Revision 1.9 2000/03/17 23:59:54 roddey
* Initial updates for two way transcoding support
*
* Revision 1.8 2000/03/02 19:54:46 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.7 2000/02/24 20:05:25 abagchi
* Swat for removing Log from API docs
*
* Revision 1.6 2000/02/06 07:48:04 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/25 22:49:55 roddey
* Moved the supportsSrcOfs() method from the individual transcoder to the
* transcoding service, where it should have been to begin with.
*
* Revision 1.4 2000/01/25 19:19:07 roddey
* Simple addition of a getId() method to the xcode and netacess abstractions to
* allow each impl to give back an id string.
*
* Revision 1.3 1999/12/18 00:18:10 roddey
* More changes to support the new, completely orthagonal support for
* intrinsic encodings.
*
* Revision 1.2 1999/12/15 19:41:28 roddey
* Support for the new transcoder system, where even intrinsic encodings are
* done via the same transcoder abstraction as external ones.
*
* Revision 1.1.1.1 1999/11/09 01:05:16 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:16 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#ifndef TRANSSERVICE_HPP
#define TRANSSERVICE_HPP
#include <util/XercesDefs.hpp>
// Forward references
class XMLPlatformUtils;
class XMLLCPTranscoder;
class XMLTranscoder;
//
// This class is an abstract base class which are used to abstract the
// transcoding services that Xerces uses. The parser's actual transcoding
// needs are small so it is desirable to allow different implementations
// to be provided.
//
// The transcoding service has to provide a couple of required string
// and character operations, but its most important service is the creation
// of transcoder objects. There are two types of transcoders, which are
// discussed below in the XMLTranscoder class' description.
//
class XMLUTIL_EXPORT XMLTransService
{
public :
// -----------------------------------------------------------------------
// Class specific types
// -----------------------------------------------------------------------
enum Codes
{
Ok
, UnsupportedEncoding
, InternalFailure
, SupportFilesNotFound
};
struct TransRec
{
XMLCh intCh;
XMLByte extCh;
};
// -----------------------------------------------------------------------
// Public constructors and destructor
// -----------------------------------------------------------------------
virtual ~XMLTransService();
// -----------------------------------------------------------------------
// Non-virtual API
// -----------------------------------------------------------------------
XMLTranscoder* makeNewTranscoderFor
(
const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
);
XMLTranscoder* makeNewTranscoderFor
(
const char* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
);
// -----------------------------------------------------------------------
// The virtual transcoding service API
// -----------------------------------------------------------------------
virtual int compareIString
(
const XMLCh* const comp1
, const XMLCh* const comp2
) = 0;
virtual int compareNIString
(
const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars
) = 0;
virtual const XMLCh* getId() const = 0;
virtual bool isSpace(const XMLCh toCheck) const = 0;
virtual XMLLCPTranscoder* makeNewLCPTranscoder() = 0;
virtual bool supportsSrcOfs() const = 0;
virtual void upperCase(XMLCh* const toUpperCase) const = 0;
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
XMLTransService();
// -----------------------------------------------------------------------
// Protected virtual methods.
// -----------------------------------------------------------------------
virtual XMLTranscoder* makeNewXMLTranscoder
(
const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
) = 0;
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLTransService(const XMLTransService&);
void operator=(const XMLTransService&);
// -----------------------------------------------------------------------
// Hidden init method for platform utils to call
// -----------------------------------------------------------------------
friend class XMLPlatformUtils;
void initTransService();
};
//
// This type of transcoder is for non-local code page encodings, i.e.
// named encodings. These are used internally by the scanner to internalize
// raw XML into the internal Unicode format, and by writer classes to
// convert that internal Unicode format (which comes out of the parser)
// back out to a format that the receiving client code wants to use.
//
class XMLUTIL_EXPORT XMLTranscoder
{
public :
// -----------------------------------------------------------------------
// This enum is used by the transcodeTo() method to indicate how to
// react to unrepresentable characters. The transcodeFrom() method always
// works the same. It will consider any invalid data to be an error and
// throw.
//
// The options mean:
// Throw - Throw an exception
// RepChar - Use the replacement char
// -----------------------------------------------------------------------
enum UnRepOpts
{
UnRep_Throw
, UnRep_RepChar
};
// -----------------------------------------------------------------------
// Public constructors and destructor
// -----------------------------------------------------------------------
virtual ~XMLTranscoder();
// -----------------------------------------------------------------------
// The virtual transcoding interface
// -----------------------------------------------------------------------
virtual unsigned int transcodeFrom
(
const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes
) = 0;
virtual unsigned int transcodeTo
(
const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options
) = 0;
virtual bool canTranscodeTo
(
const unsigned int toCheck
) const = 0;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
unsigned int getBlockSize() const;
const XMLCh* getEncodingName() const;
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
XMLTranscoder
(
const XMLCh* const encodingName
, const unsigned int blockSize
);
// -----------------------------------------------------------------------
// Protected helper methods
// -----------------------------------------------------------------------
void checkBlockSize(const unsigned int toCheck);
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLTranscoder(const XMLTranscoder&);
void operator=(const XMLTranscoder&);
// -----------------------------------------------------------------------
// Private data members
//
// fBlockSize
// This is the block size indicated in the constructor. This lets
// the derived class preallocate appopriately sized buffers. This
// sets the maximum number of characters which can be internalized
// per call to transcodeXML().
//
// fEncodingName
// This is the name of the encoding this encoder is for. All basic
// XML transcoder's are for named encodings.
// -----------------------------------------------------------------------
unsigned int fBlockSize;
XMLCh* fEncodingName;
};
//
// This class is a specialized transcoder that only transcodes between
// the internal XMLCh format and the local code page. It is specialized
// for the very common job of translating data from the client app's
// native code page to the internal format and vice versa.
//
class XMLUTIL_EXPORT XMLLCPTranscoder
{
public :
// -----------------------------------------------------------------------
// Public constructors and destructor
// -----------------------------------------------------------------------
virtual ~XMLLCPTranscoder();
// -----------------------------------------------------------------------
// The virtual transcoder API
//
// NOTE: All these APIs don't include null terminator characters in
// their parameters. So calcRequiredSize() returns the number
// of actual chars, not including the null. maxBytes and maxChars
// parameters refer to actual chars, not including the null so
// its assumed that the buffer is physically one char or byte
// larger.
// -----------------------------------------------------------------------
virtual unsigned int calcRequiredSize(const char* const srcText) = 0;
virtual unsigned int calcRequiredSize(const XMLCh* const srcText) = 0;
virtual char* transcode(const XMLCh* const toTranscode) = 0;
virtual XMLCh* transcode(const char* const toTranscode) = 0;
virtual bool transcode
(
const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars
) = 0;
virtual bool transcode
(
const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxChars
) = 0;
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
XMLLCPTranscoder();
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLLCPTranscoder(const XMLLCPTranscoder&);
void operator=(const XMLLCPTranscoder&);
};
// ---------------------------------------------------------------------------
// XMLTranscoder: Protected helper methods
// ---------------------------------------------------------------------------
inline unsigned int XMLTranscoder::getBlockSize() const
{
return fBlockSize;
}
inline const XMLCh* XMLTranscoder::getEncodingName() const
{
return fEncodingName;
}
#endif
<commit_msg>A couple of fixes to comments and parameter names to make them more correct.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.11 2000/04/12 22:57:45 roddey
* A couple of fixes to comments and parameter names to make them
* more correct.
*
* Revision 1.10 2000/03/28 19:43:19 roddey
* Fixes for signed/unsigned warnings. New work for two way transcoding
* stuff.
*
* Revision 1.9 2000/03/17 23:59:54 roddey
* Initial updates for two way transcoding support
*
* Revision 1.8 2000/03/02 19:54:46 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.7 2000/02/24 20:05:25 abagchi
* Swat for removing Log from API docs
*
* Revision 1.6 2000/02/06 07:48:04 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/25 22:49:55 roddey
* Moved the supportsSrcOfs() method from the individual transcoder to the
* transcoding service, where it should have been to begin with.
*
* Revision 1.4 2000/01/25 19:19:07 roddey
* Simple addition of a getId() method to the xcode and netacess abstractions to
* allow each impl to give back an id string.
*
* Revision 1.3 1999/12/18 00:18:10 roddey
* More changes to support the new, completely orthagonal support for
* intrinsic encodings.
*
* Revision 1.2 1999/12/15 19:41:28 roddey
* Support for the new transcoder system, where even intrinsic encodings are
* done via the same transcoder abstraction as external ones.
*
* Revision 1.1.1.1 1999/11/09 01:05:16 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:16 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#ifndef TRANSSERVICE_HPP
#define TRANSSERVICE_HPP
#include <util/XercesDefs.hpp>
// Forward references
class XMLPlatformUtils;
class XMLLCPTranscoder;
class XMLTranscoder;
//
// This class is an abstract base class which are used to abstract the
// transcoding services that Xerces uses. The parser's actual transcoding
// needs are small so it is desirable to allow different implementations
// to be provided.
//
// The transcoding service has to provide a couple of required string
// and character operations, but its most important service is the creation
// of transcoder objects. There are two types of transcoders, which are
// discussed below in the XMLTranscoder class' description.
//
class XMLUTIL_EXPORT XMLTransService
{
public :
// -----------------------------------------------------------------------
// Class specific types
// -----------------------------------------------------------------------
enum Codes
{
Ok
, UnsupportedEncoding
, InternalFailure
, SupportFilesNotFound
};
struct TransRec
{
XMLCh intCh;
XMLByte extCh;
};
// -----------------------------------------------------------------------
// Public constructors and destructor
// -----------------------------------------------------------------------
virtual ~XMLTransService();
// -----------------------------------------------------------------------
// Non-virtual API
// -----------------------------------------------------------------------
XMLTranscoder* makeNewTranscoderFor
(
const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
);
XMLTranscoder* makeNewTranscoderFor
(
const char* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
);
// -----------------------------------------------------------------------
// The virtual transcoding service API
// -----------------------------------------------------------------------
virtual int compareIString
(
const XMLCh* const comp1
, const XMLCh* const comp2
) = 0;
virtual int compareNIString
(
const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars
) = 0;
virtual const XMLCh* getId() const = 0;
virtual bool isSpace(const XMLCh toCheck) const = 0;
virtual XMLLCPTranscoder* makeNewLCPTranscoder() = 0;
virtual bool supportsSrcOfs() const = 0;
virtual void upperCase(XMLCh* const toUpperCase) const = 0;
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
XMLTransService();
// -----------------------------------------------------------------------
// Protected virtual methods.
// -----------------------------------------------------------------------
virtual XMLTranscoder* makeNewXMLTranscoder
(
const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize
) = 0;
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLTransService(const XMLTransService&);
void operator=(const XMLTransService&);
// -----------------------------------------------------------------------
// Hidden init method for platform utils to call
// -----------------------------------------------------------------------
friend class XMLPlatformUtils;
void initTransService();
};
//
// This type of transcoder is for non-local code page encodings, i.e.
// named encodings. These are used internally by the scanner to internalize
// raw XML into the internal Unicode format, and by writer classes to
// convert that internal Unicode format (which comes out of the parser)
// back out to a format that the receiving client code wants to use.
//
class XMLUTIL_EXPORT XMLTranscoder
{
public :
// -----------------------------------------------------------------------
// This enum is used by the transcodeTo() method to indicate how to
// react to unrepresentable characters. The transcodeFrom() method always
// works the same. It will consider any invalid data to be an error and
// throw.
//
// The options mean:
// Throw - Throw an exception
// RepChar - Use the replacement char
// -----------------------------------------------------------------------
enum UnRepOpts
{
UnRep_Throw
, UnRep_RepChar
};
// -----------------------------------------------------------------------
// Public constructors and destructor
// -----------------------------------------------------------------------
virtual ~XMLTranscoder();
// -----------------------------------------------------------------------
// The virtual transcoding interface
// -----------------------------------------------------------------------
virtual unsigned int transcodeFrom
(
const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes
) = 0;
virtual unsigned int transcodeTo
(
const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options
) = 0;
virtual bool canTranscodeTo
(
const unsigned int toCheck
) const = 0;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
unsigned int getBlockSize() const;
const XMLCh* getEncodingName() const;
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
XMLTranscoder
(
const XMLCh* const encodingName
, const unsigned int blockSize
);
// -----------------------------------------------------------------------
// Protected helper methods
// -----------------------------------------------------------------------
void checkBlockSize(const unsigned int toCheck);
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLTranscoder(const XMLTranscoder&);
void operator=(const XMLTranscoder&);
// -----------------------------------------------------------------------
// Private data members
//
// fBlockSize
// This is the block size indicated in the constructor. This lets
// the derived class preallocate appopriately sized buffers. This
// sets the maximum number of characters which can be internalized
// per call to transcodeFrom() and transcodeTo().
//
// fEncodingName
// This is the name of the encoding this encoder is for. All basic
// XML transcoder's are for named encodings.
// -----------------------------------------------------------------------
unsigned int fBlockSize;
XMLCh* fEncodingName;
};
//
// This class is a specialized transcoder that only transcodes between
// the internal XMLCh format and the local code page. It is specialized
// for the very common job of translating data from the client app's
// native code page to the internal format and vice versa.
//
class XMLUTIL_EXPORT XMLLCPTranscoder
{
public :
// -----------------------------------------------------------------------
// Public constructors and destructor
// -----------------------------------------------------------------------
virtual ~XMLLCPTranscoder();
// -----------------------------------------------------------------------
// The virtual transcoder API
//
// NOTE: All these APIs don't include null terminator characters in
// their parameters. So calcRequiredSize() returns the number
// of actual chars, not including the null. maxBytes and maxChars
// parameters refer to actual chars, not including the null so
// its assumed that the buffer is physically one char or byte
// larger.
// -----------------------------------------------------------------------
virtual unsigned int calcRequiredSize(const char* const srcText) = 0;
virtual unsigned int calcRequiredSize(const XMLCh* const srcText) = 0;
virtual char* transcode(const XMLCh* const toTranscode) = 0;
virtual XMLCh* transcode(const char* const toTranscode) = 0;
virtual bool transcode
(
const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars
) = 0;
virtual bool transcode
(
const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxBytes
) = 0;
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
XMLLCPTranscoder();
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLLCPTranscoder(const XMLLCPTranscoder&);
void operator=(const XMLLCPTranscoder&);
};
// ---------------------------------------------------------------------------
// XMLTranscoder: Protected helper methods
// ---------------------------------------------------------------------------
inline unsigned int XMLTranscoder::getBlockSize() const
{
return fBlockSize;
}
inline const XMLCh* XMLTranscoder::getEncodingName() const
{
return fEncodingName;
}
#endif
<|endoftext|> |
<commit_before>#include "util/bitmap.h"
#include "util/trans-bitmap.h"
#include "util/font.h"
#include "lineedit.h"
#include "keys.h"
#include "globals.h"
#include "util/debug.h"
#include <iostream>
using namespace Gui;
static std::ostream & debug( int level ){
Global::debug(level) << "[line edit] ";
return Global::debug(level);
}
LineEdit::LineEdit() :
currentSetFont(0),
hAlignment(T_Middle),
hAlignMod(T_Middle),
vAlignment(T_Middle),
inputTypeValue(inputGeneral),
changed_(0),
autoResizable(0),
textX(0),
textY(0),
cursorX(0),
cursorY(0),
cursorIndex(0),
textColor(Graphics::makeColor(0, 0, 0)),
textSizeH(0),
limit(0),
blinkRate(500),
blink(false),
focused(false),
changeCounter(0){
cursorTime.reset();
}
LineEdit::~LineEdit(){
if (focused){
input.disable();
}
}
void LineEdit::hookKey(int key, void (*callback)(void *), void * arg){
input.addBlockingHandle(key, callback, arg);
}
bool LineEdit::didChanged(unsigned long long & counter){
bool did = counter < changeCounter;
counter = changeCounter;
return did;
}
// If the font size changes
void LineEdit::fontChange(){
changed();
}
// Update
void LineEdit::act(const Font & font){
if (cursorTime.msecs() >= blinkRate){
cursorTime.reset();
blink = !blink;
changed();
}
/*
if ((blinkRate * 2) <= cursorTime.msecs()){
cursorTime.reset();
changed();
}
*/
if (input.doInput()){
changed();
cursorIndex = input.getText().size();
}
if (changed_){
textSizeH = currentSetFont->getHeight();
if (autoResizable) {
location.setDimensions(textSizeH+2, currentSetFont->textLength(input.getText().c_str()) + 4);
} else {
if (hAlignMod==T_Left){
if (currentSetFont->textLength(input.getText().c_str())>location.getWidth()){
hAlignment = T_Right;
} else {
hAlignment = T_Left;
}
}
}
switch (hAlignment) {
case T_Left:
textX = 2;
cursorX = textX + currentSetFont->textLength(input.getText().substr(0,cursorIndex).c_str()) + 1;
break;
case T_Middle:
textX = (location.getWidth()/2) - (currentSetFont->textLength(input.getText().c_str())/2);
cursorX = (textX) + currentSetFont->textLength(input.getText().substr(0,cursorIndex).c_str()) + 1;
break;
case T_Right:
textX = location.getWidth() - currentSetFont->textLength(input.getText().c_str());//(position.width - 1)-2;
cursorX = location.getWidth() - currentSetFont->textLength(input.getText().substr(0, input.getText().length()-cursorIndex).c_str());
break;
case T_Bottom:
case T_Top:
break;
}
switch (vAlignment) {
case T_Top:
textY = 1;
cursorY = 1;
break;
case T_Middle:
textY = cursorY = (location.getHeight() - textSizeH-(5))/2;
break;
case T_Bottom:
textY = (location.getHeight() - 1) - textSizeH - 1;
cursorY = textY - textSizeH;
break;
case T_Right:
case T_Left:
break;
}
//textY++;
//textX++;
stable();
}
}
// Draw
void LineEdit::render(const Graphics::Bitmap & work){
Util::ReferenceCount<Graphics::Bitmap> workArea = checkWorkArea(work);
// Check if we are using a rounded box
/*
if (transforms.getRadius()>0) {
Graphics::Bitmap::transBlender( 0, 0, 0, colors.bodyAlpha );
roundRectFill( *workArea, (int)transforms.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
workArea->translucent().draw(location.getX(),location.getY(),work);
workArea->fill(Graphics::makeColor(255,0,255));
Graphics::Bitmap::transBlender( 0, 0, 0, colors.borderAlpha );
roundRect( *workArea, (int)transforms.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
workArea->translucent().draw(location.getX(),location.getY(),work);
} else {
Graphics::Bitmap::transBlender( 0, 0, 0, colors.bodyAlpha );
workArea->rectangleFill( 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
workArea->translucent().draw(location.getX(),location.getY(),work);
workArea->fill(Graphics::makeColor(255,0,255));
Graphics::Bitmap::transBlender( 0, 0, 0, colors.borderAlpha );
workArea->rectangle( 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
workArea->translucent().draw(location.getX(),location.getY(),work);
}
*/
// work.drawingMode( Bitmap::MODE_SOLID );
workArea->fill(Graphics::makeColor(255,0,255));
if (currentSetFont){
currentSetFont->printf(textX, textY, textColor, *workArea, input.getText(), 0);
}
if (focused){
/*
if (cursorTime.msecs() <= blinkRate){
workArea->line(cursorX,cursorY,cursorX,cursorY+textSizeH-5,textColor);
}
*/
if (blink){
workArea->line(cursorX, cursorY, cursorX, cursorY+textSizeH-5, textColor);
}
}
// workArea->draw(location.getX(), location.getY(), work);
}
#if 0
// Keypresses
sigslot::slot LineEdit::keyPress(const keys &k)
{
debug( 5 ) << "Received key press " << k.getValue() << std::endl;
if(focused)
{
if(k.isCharacter())
{
char keyValue = k.getValue();
bool addValue = false;
switch(inputTypeValue){
case inputNumerical:
if ( k.isNumber() ) addValue = !addValue;
break;
case inputNoCaps:
keyValue = tolower(keyValue);
addValue = !addValue;
break;
case inputAllCaps:
keyValue = toupper(keyValue);
addValue = !addValue;
break;
case inputGeneral:
default:
addValue = !addValue;
break;
}
if(addValue){
if(limit!=0)
{
if(currentSetText.length()<limit)
{
//currentSetText += k.getValue();
currentSetText.insert(cursorIndex, std::string(1,keyValue));
++cursorIndex;
changed();
}
}
else
{
//currentSetText += k.getValue();
currentSetText.insert(cursorIndex, std::string(1,keyValue));
++cursorIndex;
changed();
}
}
}
else
{
switch(k.getValue())
{
case keys::DEL:
if(cursorIndex<currentSetText.length())
{
currentSetText.erase(cursorIndex,1);
}
break;
case keys::BACKSPACE:
if(cursorIndex>0)
{
currentSetText.erase(cursorIndex - 1, 1);
--cursorIndex;
}
break;
case keys::RIGHT:
if(cursorIndex<currentSetText.length())++cursorIndex;
break;
case keys::LEFT:
if(cursorIndex>0)--cursorIndex;
break;
case keys::INSERT:
break;
}
changed();
}
}
}
#endif
// Set text
void LineEdit::setText(const std::string & text){
input.setText(text);
if (limit!=0) {
if (input.getText().length() > limit) {
while (input.getText().length() > limit){
// currentSetText.erase(currentSetText.begin()+currentSetText.length()-1);
}
}
}
cursorIndex = input.getText().length();
changed();
}
//! Get text
const std::string LineEdit::getText(){
return input.getText();
}
//! Clear text
void LineEdit::clearText(){
input.clearInput();
cursorIndex=0;
changed();
}
//! Set text limit
void LineEdit::setLimit(unsigned int l){
limit = l;
if (limit!=0){
if (input.getText().length()>limit){
while (input.getText().length()>limit){
// currentSetText.erase(currentSetText.begin()+currentSetText.length()-1);
}
}
}
cursorIndex = input.getText().length();
changed();
}
// Set Horizontal Alignment
void LineEdit::setHorizontalAlign(const textAlign & a){
hAlignment = hAlignMod = a;
changed();
}
// Set Vertical Alignment
void LineEdit::setVerticalAlign(const textAlign & a){
vAlignment = a;
changed();
}
//! Set the type of input default general
void LineEdit::setInputType(const inputType i){
inputTypeValue = i;
}
// Set textColor
void LineEdit::setTextColor(const Graphics::Color color){
textColor = color;
}
//! Set textColor
void LineEdit::setCursorColor(const Graphics::Color color){
textColor = color;
}
// Set font
void LineEdit::setFont(const Font *f){
currentSetFont = f;
if (currentSetFont) changed();
}
// Set autoResizeable
void LineEdit::setAutoResize(bool r){
autoResizable = r;
}
// Set the cursor blink rate in miliseconds (default 500)
void LineEdit::setCursorBlinkRate(unsigned int msecs){
blinkRate = msecs;
}
//! set Focus
void LineEdit::setFocused(bool focus){
focused = focus;
if (focus){
input.enable();
} else {
input.disable();
}
}
//! check Focus
bool LineEdit::isFocused(){
return focused;
}
<commit_msg>draw the line edit box<commit_after>#include "util/bitmap.h"
#include "util/trans-bitmap.h"
#include "util/font.h"
#include "lineedit.h"
#include "keys.h"
#include "globals.h"
#include "util/debug.h"
#include <iostream>
using namespace Gui;
static std::ostream & debug( int level ){
Global::debug(level) << "[line edit] ";
return Global::debug(level);
}
LineEdit::LineEdit() :
currentSetFont(0),
hAlignment(T_Middle),
hAlignMod(T_Middle),
vAlignment(T_Middle),
inputTypeValue(inputGeneral),
changed_(0),
autoResizable(0),
textX(0),
textY(0),
cursorX(0),
cursorY(0),
cursorIndex(0),
textColor(Graphics::makeColor(0, 0, 0)),
textSizeH(0),
limit(0),
blinkRate(500),
blink(false),
focused(false),
changeCounter(0){
cursorTime.reset();
}
LineEdit::~LineEdit(){
if (focused){
input.disable();
}
}
void LineEdit::hookKey(int key, void (*callback)(void *), void * arg){
input.addBlockingHandle(key, callback, arg);
}
bool LineEdit::didChanged(unsigned long long & counter){
bool did = counter < changeCounter;
counter = changeCounter;
return did;
}
// If the font size changes
void LineEdit::fontChange(){
changed();
}
// Update
void LineEdit::act(const Font & font){
if (cursorTime.msecs() >= blinkRate){
cursorTime.reset();
blink = !blink;
changed();
}
/*
if ((blinkRate * 2) <= cursorTime.msecs()){
cursorTime.reset();
changed();
}
*/
if (input.doInput()){
changed();
cursorIndex = input.getText().size();
}
if (changed_){
textSizeH = currentSetFont->getHeight();
if (autoResizable) {
location.setDimensions(textSizeH+2, currentSetFont->textLength(input.getText().c_str()) + 4);
} else {
if (hAlignMod==T_Left){
if (currentSetFont->textLength(input.getText().c_str())>location.getWidth()){
hAlignment = T_Right;
} else {
hAlignment = T_Left;
}
}
}
switch (hAlignment) {
case T_Left:
textX = 2;
cursorX = textX + currentSetFont->textLength(input.getText().substr(0,cursorIndex).c_str()) + 1;
break;
case T_Middle:
textX = (location.getWidth()/2) - (currentSetFont->textLength(input.getText().c_str())/2);
cursorX = (textX) + currentSetFont->textLength(input.getText().substr(0,cursorIndex).c_str()) + 1;
break;
case T_Right:
textX = location.getWidth() - currentSetFont->textLength(input.getText().c_str());//(position.width - 1)-2;
cursorX = location.getWidth() - currentSetFont->textLength(input.getText().substr(0, input.getText().length()-cursorIndex).c_str());
break;
case T_Bottom:
case T_Top:
break;
}
switch (vAlignment) {
case T_Top:
textY = 1;
cursorY = 1;
break;
case T_Middle:
textY = cursorY = (location.getHeight() - textSizeH-(5))/2;
break;
case T_Bottom:
textY = (location.getHeight() - 1) - textSizeH - 1;
cursorY = textY - textSizeH;
break;
case T_Right:
case T_Left:
break;
}
//textY++;
//textX++;
stable();
}
}
// Draw
void LineEdit::render(const Graphics::Bitmap & work){
Util::ReferenceCount<Graphics::Bitmap> workArea = checkWorkArea(work);
// Check if we are using a rounded box
/*
if (transforms.getRadius()>0) {
Graphics::Bitmap::transBlender( 0, 0, 0, colors.bodyAlpha );
roundRectFill( *workArea, (int)transforms.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
workArea->translucent().draw(location.getX(),location.getY(),work);
workArea->fill(Graphics::makeColor(255,0,255));
Graphics::Bitmap::transBlender( 0, 0, 0, colors.borderAlpha );
roundRect( *workArea, (int)transforms.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
workArea->translucent().draw(location.getX(),location.getY(),work);
} else {
Graphics::Bitmap::transBlender( 0, 0, 0, colors.bodyAlpha );
workArea->rectangleFill( 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
workArea->translucent().draw(location.getX(),location.getY(),work);
workArea->fill(Graphics::makeColor(255,0,255));
Graphics::Bitmap::transBlender( 0, 0, 0, colors.borderAlpha );
workArea->rectangle( 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
workArea->translucent().draw(location.getX(),location.getY(),work);
}
*/
if (transforms.getRadius() > 0){
Graphics::Bitmap::transBlender(0, 0, 0, colors.bodyAlpha);
workArea->translucent().roundRectFill((int)transforms.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
Graphics::Bitmap::transBlender(0, 0, 0, colors.borderAlpha);
workArea->translucent().roundRect((int)transforms.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border);
} else {
Graphics::Bitmap::transBlender(0, 0, 0, colors.bodyAlpha);
workArea->translucent().rectangleFill(0, 0, location.getWidth()-1, location.getHeight()-1, colors.body);
Graphics::Bitmap::transBlender(0, 0, 0, colors.borderAlpha);
workArea->translucent().rectangle(0, 0, location.getWidth()-1, location.getHeight()-1, colors.border);
}
// work.drawingMode( Bitmap::MODE_SOLID );
// workArea->fill(Graphics::makeColor(255,0,255));
if (currentSetFont){
currentSetFont->printf(textX, textY, textColor, *workArea, input.getText(), 0);
}
if (focused){
/*
if (cursorTime.msecs() <= blinkRate){
workArea->line(cursorX,cursorY,cursorX,cursorY+textSizeH-5,textColor);
}
*/
if (blink){
workArea->line(cursorX, cursorY, cursorX, cursorY+textSizeH-5, textColor);
}
}
// workArea->draw(location.getX(), location.getY(), work);
}
#if 0
// Keypresses
sigslot::slot LineEdit::keyPress(const keys &k)
{
debug( 5 ) << "Received key press " << k.getValue() << std::endl;
if(focused)
{
if(k.isCharacter())
{
char keyValue = k.getValue();
bool addValue = false;
switch(inputTypeValue){
case inputNumerical:
if ( k.isNumber() ) addValue = !addValue;
break;
case inputNoCaps:
keyValue = tolower(keyValue);
addValue = !addValue;
break;
case inputAllCaps:
keyValue = toupper(keyValue);
addValue = !addValue;
break;
case inputGeneral:
default:
addValue = !addValue;
break;
}
if(addValue){
if(limit!=0)
{
if(currentSetText.length()<limit)
{
//currentSetText += k.getValue();
currentSetText.insert(cursorIndex, std::string(1,keyValue));
++cursorIndex;
changed();
}
}
else
{
//currentSetText += k.getValue();
currentSetText.insert(cursorIndex, std::string(1,keyValue));
++cursorIndex;
changed();
}
}
}
else
{
switch(k.getValue())
{
case keys::DEL:
if(cursorIndex<currentSetText.length())
{
currentSetText.erase(cursorIndex,1);
}
break;
case keys::BACKSPACE:
if(cursorIndex>0)
{
currentSetText.erase(cursorIndex - 1, 1);
--cursorIndex;
}
break;
case keys::RIGHT:
if(cursorIndex<currentSetText.length())++cursorIndex;
break;
case keys::LEFT:
if(cursorIndex>0)--cursorIndex;
break;
case keys::INSERT:
break;
}
changed();
}
}
}
#endif
// Set text
void LineEdit::setText(const std::string & text){
input.setText(text);
if (limit!=0) {
if (input.getText().length() > limit) {
while (input.getText().length() > limit){
// currentSetText.erase(currentSetText.begin()+currentSetText.length()-1);
}
}
}
cursorIndex = input.getText().length();
changed();
}
//! Get text
const std::string LineEdit::getText(){
return input.getText();
}
//! Clear text
void LineEdit::clearText(){
input.clearInput();
cursorIndex=0;
changed();
}
//! Set text limit
void LineEdit::setLimit(unsigned int l){
limit = l;
if (limit!=0){
if (input.getText().length()>limit){
while (input.getText().length()>limit){
// currentSetText.erase(currentSetText.begin()+currentSetText.length()-1);
}
}
}
cursorIndex = input.getText().length();
changed();
}
// Set Horizontal Alignment
void LineEdit::setHorizontalAlign(const textAlign & a){
hAlignment = hAlignMod = a;
changed();
}
// Set Vertical Alignment
void LineEdit::setVerticalAlign(const textAlign & a){
vAlignment = a;
changed();
}
//! Set the type of input default general
void LineEdit::setInputType(const inputType i){
inputTypeValue = i;
}
// Set textColor
void LineEdit::setTextColor(const Graphics::Color color){
textColor = color;
}
//! Set textColor
void LineEdit::setCursorColor(const Graphics::Color color){
textColor = color;
}
// Set font
void LineEdit::setFont(const Font *f){
currentSetFont = f;
if (currentSetFont) changed();
}
// Set autoResizeable
void LineEdit::setAutoResize(bool r){
autoResizable = r;
}
// Set the cursor blink rate in miliseconds (default 500)
void LineEdit::setCursorBlinkRate(unsigned int msecs){
blinkRate = msecs;
}
//! set Focus
void LineEdit::setFocused(bool focus){
focused = focus;
if (focus){
input.enable();
} else {
input.disable();
}
}
//! check Focus
bool LineEdit::isFocused(){
return focused;
}
<|endoftext|> |
<commit_before>#include "process.h"
#include <sys/sysctl.h>
typedef struct kinfo_proc kinfo_proc;
static int GetBSDProcessList (kinfo_proc **procList, size_t *procCount)
{
int err;
kinfo_proc * result;
bool done;
static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
// Declaring name as const requires us to cast it when passing it to
// sysctl because the prototype doesn't include the const modifier.
size_t length;
assert ( procList != NULL);
assert (*procList == NULL);
assert (procCount != NULL);
*procCount = 0;
// We start by calling sysctl with result == NULL and length == 0.
// That will succeed, and set length to the appropriate length.
// We then allocate a buffer of that size and call sysctl again
// with that buffer. If that succeeds, we're done. If that fails
// with ENOMEM, we have to throw away our buffer and loop. Note
// that the loop causes use to call sysctl with NULL again; this
// is necessary because the ENOMEM failure case sets length to
// the amount of data returned, not the amount of data that
// could have been returned.
result = NULL;
done = false;
do {
assert (result == NULL);
// Call sysctl with a NULL buffer.
length = 0;
err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1,
NULL, &length,
NULL, 0);
if (err == -1) {
err = errno;
}
// Allocate an appropriately sized buffer based on the results
// from the previous call.
if (err == 0) {
result = (kinfo_proc *)malloc (length);
if (result == NULL) {
err = ENOMEM;
}
}
// Call sysctl again with the new buffer. If we get an ENOMEM
// error, toss away our buffer and start again.
if (err == 0) {
err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1,
result, &length,
NULL, 0);
if (err == -1) {
err = errno;
}
if (err == 0) {
done = true;
} else if (err == ENOMEM) {
assert(result != NULL);
free (result);
result = NULL;
err = 0;
}
}
} while (err == 0 && ! done);
// Clean up and establish post conditions.
if (err != 0 && result != NULL) {
free (result);
result = NULL;
}
*procList = result;
if (err == 0) {
*procCount = length / sizeof(kinfo_proc);
}
assert ( (err == 0) == (*procList != NULL) );
return err;
}
static int getBSDProcessPid (const char *name, int except_pid)
{
int pid = 0;
struct kinfo_proc *mylist = NULL;
size_t mycount = 0;
GetBSDProcessList (&mylist, &mycount);
for (size_t k = 0; k < mycount; k++) {
kinfo_proc *proc = &mylist[k];
if (proc->kp_proc.p_pid != except_pid
&& strcmp (proc->kp_proc.p_comm, name) == 0){
pid = proc->kp_proc.p_pid;
break;
}
}
free (mylist);
return pid;
}
int process_is_running (const char *name)
{
int pid = getBSDProcessPid (name, getpid ());
if (pid)
return true;
return false;
}
void shutdown_process (const char *name)
{
struct kinfo_proc *mylist = NULL;
size_t mycount = 0;
GetBSDProcessList (&mylist, &mycount);
for (size_t k = 0; k < mycount; k++) {
kinfo_proc *proc = &mylist[k];
if (strcmp (proc->kp_proc.p_comm, name) == 0){
kill (proc->kp_proc.p_pid, SIGKILL);
}
}
free (mylist);
}
<commit_msg>Add missed function for mac<commit_after>#include "process.h"
#include <sys/sysctl.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <glib.h>
typedef struct kinfo_proc kinfo_proc;
static int GetBSDProcessList (kinfo_proc **procList, size_t *procCount)
{
int err;
kinfo_proc * result;
bool done;
static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
// Declaring name as const requires us to cast it when passing it to
// sysctl because the prototype doesn't include the const modifier.
size_t length;
assert ( procList != NULL);
assert (*procList == NULL);
assert (procCount != NULL);
*procCount = 0;
// We start by calling sysctl with result == NULL and length == 0.
// That will succeed, and set length to the appropriate length.
// We then allocate a buffer of that size and call sysctl again
// with that buffer. If that succeeds, we're done. If that fails
// with ENOMEM, we have to throw away our buffer and loop. Note
// that the loop causes use to call sysctl with NULL again; this
// is necessary because the ENOMEM failure case sets length to
// the amount of data returned, not the amount of data that
// could have been returned.
result = NULL;
done = false;
do {
assert (result == NULL);
// Call sysctl with a NULL buffer.
length = 0;
err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1,
NULL, &length,
NULL, 0);
if (err == -1) {
err = errno;
}
// Allocate an appropriately sized buffer based on the results
// from the previous call.
if (err == 0) {
result = (kinfo_proc *)malloc (length);
if (result == NULL) {
err = ENOMEM;
}
}
// Call sysctl again with the new buffer. If we get an ENOMEM
// error, toss away our buffer and start again.
if (err == 0) {
err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1,
result, &length,
NULL, 0);
if (err == -1) {
err = errno;
}
if (err == 0) {
done = true;
} else if (err == ENOMEM) {
assert(result != NULL);
free (result);
result = NULL;
err = 0;
}
}
} while (err == 0 && ! done);
// Clean up and establish post conditions.
if (err != 0 && result != NULL) {
free (result);
result = NULL;
}
*procList = result;
if (err == 0) {
*procCount = length / sizeof(kinfo_proc);
}
assert ( (err == 0) == (*procList != NULL) );
return err;
}
static int getBSDProcessPid (const char *name, int except_pid)
{
int pid = 0;
struct kinfo_proc *mylist = NULL;
size_t mycount = 0;
GetBSDProcessList (&mylist, &mycount);
for (size_t k = 0; k < mycount; k++) {
kinfo_proc *proc = &mylist[k];
if (proc->kp_proc.p_pid != except_pid
&& strcmp (proc->kp_proc.p_comm, name) == 0){
pid = proc->kp_proc.p_pid;
break;
}
}
free (mylist);
return pid;
}
int process_is_running (const char *name)
{
int pid = getBSDProcessPid (name, getpid ());
if (pid)
return true;
return false;
}
void shutdown_process (const char *name)
{
struct kinfo_proc *mylist = NULL;
size_t mycount = 0;
GetBSDProcessList (&mylist, &mycount);
for (size_t k = 0; k < mycount; k++) {
kinfo_proc *proc = &mylist[k];
if (strcmp (proc->kp_proc.p_comm, name) == 0){
kill (proc->kp_proc.p_pid, SIGKILL);
}
}
free (mylist);
}
int count_process(const char *process_name)
{
int count = 0;
struct kinfo_proc *mylist = NULL;
size_t mycount = 0;
GetBSDProcessList (&mylist, &mycount);
for (size_t k = 0; k < mycount; k++) {
kinfo_proc *proc = &mylist[k];
if (strcmp (proc->kp_proc.p_comm, process_name) == 0){
count++;
}
}
free (mylist);
return count;
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Adam Dabrowski <adabrowski@piap.pl> <adamdbrw@gmail.com>
//
#include <MarbleQuickItem.h>
#include <QPainter>
#include <QPaintDevice>
#include <QtMath>
#include <MarbleModel.h>
#include <MarbleMap.h>
#include <ViewportParams.h>
#include <GeoPainter.h>
#include <GeoDataLookAt.h>
#include <MarbleLocale.h>
#include <Planet.h>
#include <MarbleAbstractPresenter.h>
#include <AbstractFloatItem.h>
#include <MarbleInputHandler.h>
#include <PositionTracking.h>
#include <PositionProviderPlugin.h>
#include <PluginManager.h>
#include <RenderPlugin.h>
namespace Marble
{
//TODO - move to separate files
class QuickItemSelectionRubber : public AbstractSelectionRubber
{ //TODO: support rubber selection in MarbleQuickItem
public:
void show() { m_visible = true; }
void hide() { m_visible = false; }
bool isVisible() const { return m_visible; }
const QRect &geometry() const { return m_geometry; }
void setGeometry(const QRect &/*geometry*/) {}
private:
QRect m_geometry;
bool m_visible;
};
//TODO - implement missing functionalities
class MarbleQuickInputHandler : public MarbleDefaultInputHandler
{
public:
MarbleQuickInputHandler(MarbleAbstractPresenter *marblePresenter, MarbleQuickItem *marbleQuick)
: MarbleDefaultInputHandler(marblePresenter)
,m_marbleQuick(marbleQuick)
{
setInertialEarthRotationEnabled(false); //Disabled by default, it's buggy. TODO - fix
}
bool acceptMouse()
{
return true;
}
void pinch(QPointF center, qreal scale, Qt::GestureState state)
{ //TODO - this whole thing should be moved to MarbleAbstractPresenter
(void)handlePinch(center, scale, state);
}
private slots:
void showLmbMenu(int, int) {}
void showRmbMenu(int, int) {}
void openItemToolTip() {}
void setCursor(const QCursor &cursor)
{
m_marbleQuick->setCursor(cursor);
}
private slots:
void installPluginEventFilter(RenderPlugin *) {}
private:
bool layersEventFilter(QObject *o, QEvent *e)
{
return m_marbleQuick->layersEventFilter(o, e);
}
//empty - don't check. It would be invalid with quick items
void checkReleasedMove(QMouseEvent *) {}
bool handleTouch(QTouchEvent *event)
{
if (event->touchPoints().count() > 1)
{ //not handling multi-touch at all, let PinchArea or MultiPointTouchArea take care of it
return false;
}
if (event->touchPoints().count() == 1)
{ //handle - but do not accept. I.e. pinchArea still needs to get this
QTouchEvent::TouchPoint p = event->touchPoints().at(0);
if (event->type() == QEvent::TouchBegin)
{
QMouseEvent press(QMouseEvent::MouseButtonPress, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&press);
}
else if (event->type() == QEvent::TouchUpdate)
{
QMouseEvent move(QMouseEvent::MouseMove, p.pos(),
Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&move);
}
else if (event->type() == QEvent::TouchEnd)
{
QMouseEvent release(QMouseEvent::MouseButtonRelease, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&release);
}
}
return false;
}
AbstractSelectionRubber *selectionRubber()
{
return &m_selectionRubber;
}
MarbleQuickItem *m_marbleQuick;
QuickItemSelectionRubber m_selectionRubber;
bool m_usePinchArea;
};
class MarbleQuickItemPrivate : public MarbleAbstractPresenter
{
public:
MarbleQuickItemPrivate(MarbleQuickItem *marble) : MarbleAbstractPresenter()
,m_marble(marble)
,m_inputHandler(this, marble)
{
connect(this, SIGNAL(updateRequired()), m_marble, SLOT(update()));
}
private:
MarbleQuickItem *m_marble;
friend class MarbleQuickItem;
MarbleQuickInputHandler m_inputHandler;
};
MarbleQuickItem::MarbleQuickItem(QQuickItem *parent) : QQuickPaintedItem(parent)
,d(new MarbleQuickItemPrivate(this))
{
QStringList const whitelist = QStringList() << "license";
foreach (AbstractFloatItem *item, d->map()->floatItems()) {
if ( !whitelist.contains( item->nameId() ) ) {
item->hide();
}
}
connect(d->map(), SIGNAL(repaintNeeded(QRegion)), this, SLOT(update()));
connect(this, SIGNAL(widthChanged()), this, SLOT(resizeMap()));
connect(this, SIGNAL(heightChanged()), this, SLOT(resizeMap()));
setAcceptedMouseButtons(Qt::AllButtons);
installEventFilter(&d->m_inputHandler);
}
void MarbleQuickItem::resizeMap()
{
const int minWidth = 100;
const int minHeight = 100;
int newWidth = width() > minWidth ? (int)width() : minWidth;
int newHeight = height() > minHeight ? (int)height() : minHeight;
d->map()->setSize(newWidth, newHeight);
update();
}
void MarbleQuickItem::paint(QPainter *painter)
{ //TODO - much to be done here still, i.e paint !enabled version
QPaintDevice *paintDevice = painter->device();
QImage image;
QRect rect = contentsBoundingRect().toRect();
{
painter->end();
GeoPainter geoPainter(paintDevice, d->map()->viewport(), d->map()->mapQuality());
d->map()->paint(geoPainter, rect);
}
painter->begin(paintDevice);
}
void MarbleQuickItem::classBegin()
{
}
void MarbleQuickItem::componentComplete()
{
}
int MarbleQuickItem::mapWidth() const
{
return d->map()->width();
}
int MarbleQuickItem::mapHeight() const
{
return d->map()->height();
}
bool MarbleQuickItem::showFrameRate() const
{
return d->map()->showFrameRate();
}
MarbleQuickItem::Projection MarbleQuickItem::projection() const
{
return (Projection)d->map()->projection();
}
QString MarbleQuickItem::mapThemeId() const
{
return d->map()->mapThemeId();
}
bool MarbleQuickItem::showAtmosphere() const
{
return d->map()->showAtmosphere();
}
bool MarbleQuickItem::showCompass() const
{
return d->map()->showCompass();
}
bool MarbleQuickItem::showClouds() const
{
return d->map()->showClouds();
}
bool MarbleQuickItem::showCrosshairs() const
{
return d->map()->showCrosshairs();
}
bool MarbleQuickItem::showGrid() const
{
return d->map()->showGrid();
}
bool MarbleQuickItem::showOverviewMap() const
{
return d->map()->showOverviewMap();
}
bool MarbleQuickItem::showOtherPlaces() const
{
return d->map()->showOtherPlaces();
}
bool MarbleQuickItem::showScaleBar() const
{
return d->map()->showScaleBar();
}
bool MarbleQuickItem::showBackground() const
{
return d->map()->showBackground();
}
bool MarbleQuickItem::showPositionMarker() const
{
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach (const RenderPlugin * plugin, plugins) {
if (plugin->nameId() == "positionMarker") {
return plugin->visible();
}
}
return false;
}
QString MarbleQuickItem::positionProvider() const
{
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
return this->model()->positionTracking()->positionProviderPlugin()->nameId();
}
return "";
}
MarbleModel* MarbleQuickItem::model()
{
return d->model();
}
const MarbleModel* MarbleQuickItem::model() const
{
return d->model();
}
MarbleMap* MarbleQuickItem::map()
{
return d->map();
}
const MarbleMap* MarbleQuickItem::map() const
{
return d->map();
}
void MarbleQuickItem::setZoom(int newZoom, FlyToMode mode)
{
d->setZoom(newZoom, mode);
}
void MarbleQuickItem::centerOn(const GeoDataPlacemark& placemark, bool animated)
{
d->centerOn(placemark, animated);
}
void MarbleQuickItem::centerOn(const GeoDataLatLonBox& box, bool animated)
{
d->centerOn(box, animated);
}
void MarbleQuickItem::goHome()
{
d->goHome();
}
void MarbleQuickItem::zoomIn(FlyToMode mode)
{
d->zoomIn(mode);
}
void MarbleQuickItem::zoomOut(FlyToMode mode)
{
d->zoomOut(mode);
}
void MarbleQuickItem::handlePinchStarted(const QPointF &point)
{
pinch(point, 1, Qt::GestureStarted);
}
void MarbleQuickItem::handlePinchFinished(const QPointF &point)
{
pinch(point, 1, Qt::GestureFinished);
}
void MarbleQuickItem::handlePinchUpdated(const QPointF &point, qreal scale)
{
scale = sqrt(sqrt(scale));
scale = qBound(0.5, scale, 2.0);
pinch(point, scale, Qt::GestureUpdated);
}
void MarbleQuickItem::setMapWidth(int mapWidth)
{
if (d->map()->width() == mapWidth) {
return;
}
d->map()->setSize(mapWidth, mapHeight());
emit mapWidthChanged(mapWidth);
}
void MarbleQuickItem::setMapHeight(int mapHeight)
{
if (this->mapHeight() == mapHeight) {
return;
}
d->map()->setSize(mapWidth(), mapHeight);
emit mapHeightChanged(mapHeight);
}
void MarbleQuickItem::setShowFrameRate(bool showFrameRate)
{
if (this->showFrameRate() == showFrameRate) {
return;
}
d->map()->setShowFrameRate(showFrameRate);
emit showFrameRateChanged(showFrameRate);
}
void MarbleQuickItem::setProjection(Projection projection)
{
if (this->projection() == projection) {
return;
}
d->map()->setProjection((Marble::Projection)projection);
emit projectionChanged(projection);
}
void MarbleQuickItem::setMapThemeId(QString mapThemeId)
{
if (this->mapThemeId() == mapThemeId) {
return;
}
bool const showCompass = d->map()->showCompass();
bool const showOverviewMap = d->map()->showOverviewMap();
bool const showOtherPlaces = d->map()->showOtherPlaces();
bool const showGrid = d->map()->showGrid();
bool const showScaleBar = d->map()->showScaleBar();
d->map()->setMapThemeId(mapThemeId);
// Map themes are allowed to change properties. Enforce ours.
d->map()->setShowCompass(showCompass);
d->map()->setShowOverviewMap(showOverviewMap);
d->map()->setShowOtherPlaces(showOtherPlaces);
d->map()->setShowGrid(showGrid);
d->map()->setShowScaleBar(showScaleBar);
emit mapThemeIdChanged(mapThemeId);
}
void MarbleQuickItem::setShowAtmosphere(bool showAtmosphere)
{
if (this->showAtmosphere() == showAtmosphere) {
return;
}
d->map()->setShowAtmosphere(showAtmosphere);
emit showAtmosphereChanged(showAtmosphere);
}
void MarbleQuickItem::setShowCompass(bool showCompass)
{
if (this->showCompass() == showCompass) {
return;
}
d->map()->setShowCompass(showCompass);
emit showCompassChanged(showCompass);
}
void MarbleQuickItem::setShowClouds(bool showClouds)
{
if (this->showClouds() == showClouds) {
return;
}
d->map()->setShowClouds(showClouds);
emit showCloudsChanged(showClouds);
}
void MarbleQuickItem::setShowCrosshairs(bool showCrosshairs)
{
if (this->showCrosshairs() == showCrosshairs) {
return;
}
d->map()->setShowCrosshairs(showCrosshairs);
emit showCrosshairsChanged(showCrosshairs);
}
void MarbleQuickItem::setShowGrid(bool showGrid)
{
if (this->showGrid() == showGrid) {
return;
}
d->map()->setShowGrid(showGrid);
emit showGridChanged(showGrid);
}
void MarbleQuickItem::setShowOverviewMap(bool showOverviewMap)
{
if (this->showOverviewMap() == showOverviewMap) {
return;
}
d->map()->setShowOverviewMap(showOverviewMap);
emit showOverviewMapChanged(showOverviewMap);
}
void MarbleQuickItem::setShowOtherPlaces(bool showOtherPlaces)
{
if (this->showOtherPlaces() == showOtherPlaces) {
return;
}
d->map()->setShowOtherPlaces(showOtherPlaces);
emit showOtherPlacesChanged(showOtherPlaces);
}
void MarbleQuickItem::setShowScaleBar(bool showScaleBar)
{
if (this->showScaleBar() == showScaleBar) {
return;
}
d->map()->setShowScaleBar(showScaleBar);
emit showScaleBarChanged(showScaleBar);
}
void MarbleQuickItem::setShowBackground(bool showBackground)
{
if (this->showBackground() == showBackground) {
return;
}
d->map()->setShowBackground(showBackground);
emit showBackgroundChanged(showBackground);
}
void MarbleQuickItem::setShowPositionMarker(bool showPositionMarker)
{
if (this->showPositionMarker() == showPositionMarker) {
return;
}
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach ( RenderPlugin * plugin, plugins ) {
if ( plugin->nameId() == "positionMarker" ) {
plugin->setVisible(showPositionMarker);
break;
}
}
emit showPositionMarkerChanged(showPositionMarker);
}
void MarbleQuickItem::setPositionProvider(const QString &positionProvider)
{
QString name = "";
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
name = this->model()->positionTracking()->positionProviderPlugin()->nameId();
if ( name == positionProvider ) {
return;
}
}
QList<const PositionProviderPlugin*> plugins = model()->pluginManager()->positionProviderPlugins();
foreach (const PositionProviderPlugin* plugin, plugins) {
if ( plugin->nameId() == positionProvider) {
model()->positionTracking()->setPositionProviderPlugin(plugin->newInstance());
emit positionProviderChanged(positionProvider);
break;
}
}
}
QObject *MarbleQuickItem::getEventFilter() const
{ //We would want to install the same event filter for abstract layer QuickItems such as PinchArea
return &d->m_inputHandler;
}
void MarbleQuickItem::pinch(QPointF center, qreal scale, Qt::GestureState state)
{
d->m_inputHandler.pinch(center, scale, state);
}
MarbleInputHandler *MarbleQuickItem::inputHandler()
{
return &d->m_inputHandler;
}
int MarbleQuickItem::zoom() const
{
return d->logzoom();
}
bool MarbleQuickItem::layersEventFilter(QObject *, QEvent *)
{ //Does nothing, but can be reimplemented in a subclass
return false;
}
}
<commit_msg>Provide a way to disable position tracking<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Adam Dabrowski <adabrowski@piap.pl> <adamdbrw@gmail.com>
//
#include <MarbleQuickItem.h>
#include <QPainter>
#include <QPaintDevice>
#include <QtMath>
#include <MarbleModel.h>
#include <MarbleMap.h>
#include <ViewportParams.h>
#include <GeoPainter.h>
#include <GeoDataLookAt.h>
#include <MarbleLocale.h>
#include <Planet.h>
#include <MarbleAbstractPresenter.h>
#include <AbstractFloatItem.h>
#include <MarbleInputHandler.h>
#include <PositionTracking.h>
#include <PositionProviderPlugin.h>
#include <PluginManager.h>
#include <RenderPlugin.h>
namespace Marble
{
//TODO - move to separate files
class QuickItemSelectionRubber : public AbstractSelectionRubber
{ //TODO: support rubber selection in MarbleQuickItem
public:
void show() { m_visible = true; }
void hide() { m_visible = false; }
bool isVisible() const { return m_visible; }
const QRect &geometry() const { return m_geometry; }
void setGeometry(const QRect &/*geometry*/) {}
private:
QRect m_geometry;
bool m_visible;
};
//TODO - implement missing functionalities
class MarbleQuickInputHandler : public MarbleDefaultInputHandler
{
public:
MarbleQuickInputHandler(MarbleAbstractPresenter *marblePresenter, MarbleQuickItem *marbleQuick)
: MarbleDefaultInputHandler(marblePresenter)
,m_marbleQuick(marbleQuick)
{
setInertialEarthRotationEnabled(false); //Disabled by default, it's buggy. TODO - fix
}
bool acceptMouse()
{
return true;
}
void pinch(QPointF center, qreal scale, Qt::GestureState state)
{ //TODO - this whole thing should be moved to MarbleAbstractPresenter
(void)handlePinch(center, scale, state);
}
private slots:
void showLmbMenu(int, int) {}
void showRmbMenu(int, int) {}
void openItemToolTip() {}
void setCursor(const QCursor &cursor)
{
m_marbleQuick->setCursor(cursor);
}
private slots:
void installPluginEventFilter(RenderPlugin *) {}
private:
bool layersEventFilter(QObject *o, QEvent *e)
{
return m_marbleQuick->layersEventFilter(o, e);
}
//empty - don't check. It would be invalid with quick items
void checkReleasedMove(QMouseEvent *) {}
bool handleTouch(QTouchEvent *event)
{
if (event->touchPoints().count() > 1)
{ //not handling multi-touch at all, let PinchArea or MultiPointTouchArea take care of it
return false;
}
if (event->touchPoints().count() == 1)
{ //handle - but do not accept. I.e. pinchArea still needs to get this
QTouchEvent::TouchPoint p = event->touchPoints().at(0);
if (event->type() == QEvent::TouchBegin)
{
QMouseEvent press(QMouseEvent::MouseButtonPress, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&press);
}
else if (event->type() == QEvent::TouchUpdate)
{
QMouseEvent move(QMouseEvent::MouseMove, p.pos(),
Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&move);
}
else if (event->type() == QEvent::TouchEnd)
{
QMouseEvent release(QMouseEvent::MouseButtonRelease, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&release);
}
}
return false;
}
AbstractSelectionRubber *selectionRubber()
{
return &m_selectionRubber;
}
MarbleQuickItem *m_marbleQuick;
QuickItemSelectionRubber m_selectionRubber;
bool m_usePinchArea;
};
class MarbleQuickItemPrivate : public MarbleAbstractPresenter
{
public:
MarbleQuickItemPrivate(MarbleQuickItem *marble) : MarbleAbstractPresenter()
,m_marble(marble)
,m_inputHandler(this, marble)
{
connect(this, SIGNAL(updateRequired()), m_marble, SLOT(update()));
}
private:
MarbleQuickItem *m_marble;
friend class MarbleQuickItem;
MarbleQuickInputHandler m_inputHandler;
};
MarbleQuickItem::MarbleQuickItem(QQuickItem *parent) : QQuickPaintedItem(parent)
,d(new MarbleQuickItemPrivate(this))
{
QStringList const whitelist = QStringList() << "license";
foreach (AbstractFloatItem *item, d->map()->floatItems()) {
if ( !whitelist.contains( item->nameId() ) ) {
item->hide();
}
}
connect(d->map(), SIGNAL(repaintNeeded(QRegion)), this, SLOT(update()));
connect(this, SIGNAL(widthChanged()), this, SLOT(resizeMap()));
connect(this, SIGNAL(heightChanged()), this, SLOT(resizeMap()));
setAcceptedMouseButtons(Qt::AllButtons);
installEventFilter(&d->m_inputHandler);
}
void MarbleQuickItem::resizeMap()
{
const int minWidth = 100;
const int minHeight = 100;
int newWidth = width() > minWidth ? (int)width() : minWidth;
int newHeight = height() > minHeight ? (int)height() : minHeight;
d->map()->setSize(newWidth, newHeight);
update();
}
void MarbleQuickItem::paint(QPainter *painter)
{ //TODO - much to be done here still, i.e paint !enabled version
QPaintDevice *paintDevice = painter->device();
QImage image;
QRect rect = contentsBoundingRect().toRect();
{
painter->end();
GeoPainter geoPainter(paintDevice, d->map()->viewport(), d->map()->mapQuality());
d->map()->paint(geoPainter, rect);
}
painter->begin(paintDevice);
}
void MarbleQuickItem::classBegin()
{
}
void MarbleQuickItem::componentComplete()
{
}
int MarbleQuickItem::mapWidth() const
{
return d->map()->width();
}
int MarbleQuickItem::mapHeight() const
{
return d->map()->height();
}
bool MarbleQuickItem::showFrameRate() const
{
return d->map()->showFrameRate();
}
MarbleQuickItem::Projection MarbleQuickItem::projection() const
{
return (Projection)d->map()->projection();
}
QString MarbleQuickItem::mapThemeId() const
{
return d->map()->mapThemeId();
}
bool MarbleQuickItem::showAtmosphere() const
{
return d->map()->showAtmosphere();
}
bool MarbleQuickItem::showCompass() const
{
return d->map()->showCompass();
}
bool MarbleQuickItem::showClouds() const
{
return d->map()->showClouds();
}
bool MarbleQuickItem::showCrosshairs() const
{
return d->map()->showCrosshairs();
}
bool MarbleQuickItem::showGrid() const
{
return d->map()->showGrid();
}
bool MarbleQuickItem::showOverviewMap() const
{
return d->map()->showOverviewMap();
}
bool MarbleQuickItem::showOtherPlaces() const
{
return d->map()->showOtherPlaces();
}
bool MarbleQuickItem::showScaleBar() const
{
return d->map()->showScaleBar();
}
bool MarbleQuickItem::showBackground() const
{
return d->map()->showBackground();
}
bool MarbleQuickItem::showPositionMarker() const
{
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach (const RenderPlugin * plugin, plugins) {
if (plugin->nameId() == "positionMarker") {
return plugin->visible();
}
}
return false;
}
QString MarbleQuickItem::positionProvider() const
{
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
return this->model()->positionTracking()->positionProviderPlugin()->nameId();
}
return "";
}
MarbleModel* MarbleQuickItem::model()
{
return d->model();
}
const MarbleModel* MarbleQuickItem::model() const
{
return d->model();
}
MarbleMap* MarbleQuickItem::map()
{
return d->map();
}
const MarbleMap* MarbleQuickItem::map() const
{
return d->map();
}
void MarbleQuickItem::setZoom(int newZoom, FlyToMode mode)
{
d->setZoom(newZoom, mode);
}
void MarbleQuickItem::centerOn(const GeoDataPlacemark& placemark, bool animated)
{
d->centerOn(placemark, animated);
}
void MarbleQuickItem::centerOn(const GeoDataLatLonBox& box, bool animated)
{
d->centerOn(box, animated);
}
void MarbleQuickItem::goHome()
{
d->goHome();
}
void MarbleQuickItem::zoomIn(FlyToMode mode)
{
d->zoomIn(mode);
}
void MarbleQuickItem::zoomOut(FlyToMode mode)
{
d->zoomOut(mode);
}
void MarbleQuickItem::handlePinchStarted(const QPointF &point)
{
pinch(point, 1, Qt::GestureStarted);
}
void MarbleQuickItem::handlePinchFinished(const QPointF &point)
{
pinch(point, 1, Qt::GestureFinished);
}
void MarbleQuickItem::handlePinchUpdated(const QPointF &point, qreal scale)
{
scale = sqrt(sqrt(scale));
scale = qBound(0.5, scale, 2.0);
pinch(point, scale, Qt::GestureUpdated);
}
void MarbleQuickItem::setMapWidth(int mapWidth)
{
if (d->map()->width() == mapWidth) {
return;
}
d->map()->setSize(mapWidth, mapHeight());
emit mapWidthChanged(mapWidth);
}
void MarbleQuickItem::setMapHeight(int mapHeight)
{
if (this->mapHeight() == mapHeight) {
return;
}
d->map()->setSize(mapWidth(), mapHeight);
emit mapHeightChanged(mapHeight);
}
void MarbleQuickItem::setShowFrameRate(bool showFrameRate)
{
if (this->showFrameRate() == showFrameRate) {
return;
}
d->map()->setShowFrameRate(showFrameRate);
emit showFrameRateChanged(showFrameRate);
}
void MarbleQuickItem::setProjection(Projection projection)
{
if (this->projection() == projection) {
return;
}
d->map()->setProjection((Marble::Projection)projection);
emit projectionChanged(projection);
}
void MarbleQuickItem::setMapThemeId(QString mapThemeId)
{
if (this->mapThemeId() == mapThemeId) {
return;
}
bool const showCompass = d->map()->showCompass();
bool const showOverviewMap = d->map()->showOverviewMap();
bool const showOtherPlaces = d->map()->showOtherPlaces();
bool const showGrid = d->map()->showGrid();
bool const showScaleBar = d->map()->showScaleBar();
d->map()->setMapThemeId(mapThemeId);
// Map themes are allowed to change properties. Enforce ours.
d->map()->setShowCompass(showCompass);
d->map()->setShowOverviewMap(showOverviewMap);
d->map()->setShowOtherPlaces(showOtherPlaces);
d->map()->setShowGrid(showGrid);
d->map()->setShowScaleBar(showScaleBar);
emit mapThemeIdChanged(mapThemeId);
}
void MarbleQuickItem::setShowAtmosphere(bool showAtmosphere)
{
if (this->showAtmosphere() == showAtmosphere) {
return;
}
d->map()->setShowAtmosphere(showAtmosphere);
emit showAtmosphereChanged(showAtmosphere);
}
void MarbleQuickItem::setShowCompass(bool showCompass)
{
if (this->showCompass() == showCompass) {
return;
}
d->map()->setShowCompass(showCompass);
emit showCompassChanged(showCompass);
}
void MarbleQuickItem::setShowClouds(bool showClouds)
{
if (this->showClouds() == showClouds) {
return;
}
d->map()->setShowClouds(showClouds);
emit showCloudsChanged(showClouds);
}
void MarbleQuickItem::setShowCrosshairs(bool showCrosshairs)
{
if (this->showCrosshairs() == showCrosshairs) {
return;
}
d->map()->setShowCrosshairs(showCrosshairs);
emit showCrosshairsChanged(showCrosshairs);
}
void MarbleQuickItem::setShowGrid(bool showGrid)
{
if (this->showGrid() == showGrid) {
return;
}
d->map()->setShowGrid(showGrid);
emit showGridChanged(showGrid);
}
void MarbleQuickItem::setShowOverviewMap(bool showOverviewMap)
{
if (this->showOverviewMap() == showOverviewMap) {
return;
}
d->map()->setShowOverviewMap(showOverviewMap);
emit showOverviewMapChanged(showOverviewMap);
}
void MarbleQuickItem::setShowOtherPlaces(bool showOtherPlaces)
{
if (this->showOtherPlaces() == showOtherPlaces) {
return;
}
d->map()->setShowOtherPlaces(showOtherPlaces);
emit showOtherPlacesChanged(showOtherPlaces);
}
void MarbleQuickItem::setShowScaleBar(bool showScaleBar)
{
if (this->showScaleBar() == showScaleBar) {
return;
}
d->map()->setShowScaleBar(showScaleBar);
emit showScaleBarChanged(showScaleBar);
}
void MarbleQuickItem::setShowBackground(bool showBackground)
{
if (this->showBackground() == showBackground) {
return;
}
d->map()->setShowBackground(showBackground);
emit showBackgroundChanged(showBackground);
}
void MarbleQuickItem::setShowPositionMarker(bool showPositionMarker)
{
if (this->showPositionMarker() == showPositionMarker) {
return;
}
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach ( RenderPlugin * plugin, plugins ) {
if ( plugin->nameId() == "positionMarker" ) {
plugin->setVisible(showPositionMarker);
break;
}
}
emit showPositionMarkerChanged(showPositionMarker);
}
void MarbleQuickItem::setPositionProvider(const QString &positionProvider)
{
QString name = "";
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
name = this->model()->positionTracking()->positionProviderPlugin()->nameId();
if ( name == positionProvider ) {
return;
}
}
if ( positionProvider.isEmpty() ) {
model()->positionTracking()->setPositionProviderPlugin( nullptr );
return;
}
QList<const PositionProviderPlugin*> plugins = model()->pluginManager()->positionProviderPlugins();
foreach (const PositionProviderPlugin* plugin, plugins) {
if ( plugin->nameId() == positionProvider) {
model()->positionTracking()->setPositionProviderPlugin(plugin->newInstance());
emit positionProviderChanged(positionProvider);
break;
}
}
}
QObject *MarbleQuickItem::getEventFilter() const
{ //We would want to install the same event filter for abstract layer QuickItems such as PinchArea
return &d->m_inputHandler;
}
void MarbleQuickItem::pinch(QPointF center, qreal scale, Qt::GestureState state)
{
d->m_inputHandler.pinch(center, scale, state);
}
MarbleInputHandler *MarbleQuickItem::inputHandler()
{
return &d->m_inputHandler;
}
int MarbleQuickItem::zoom() const
{
return d->logzoom();
}
bool MarbleQuickItem::layersEventFilter(QObject *, QEvent *)
{ //Does nothing, but can be reimplemented in a subclass
return false;
}
}
<|endoftext|> |
<commit_before>#include "SciDataManager.h"
#include <iostream>
#include <fstream>
void SciDataManager::writeToFile(std::string const & FileName)
{
std::ofstream File(FileName, std::ios::out | std::ios::binary);
if (File.is_open())
{
u32 Dims = GridDimensions ? 3 : 0;
File.write((char *) & Dims, 4);
for (u32 i = 0; i < Dims; ++ i)
{
Dims = GridDimensions[i];
File.write((char *) & Dims, 4);
}
Dims = GridValues.size();
File.write((char *) & Dims, 4);
for (auto it = GridValues.Values.begin(); it != GridValues.Values.end(); ++ it)
{
File.write((char *) & it->Location.X, sizeof(double));
File.write((char *) & it->Location.Y, sizeof(double));
File.write((char *) & it->Location.Z, sizeof(double));
Dims = it->ScalarFields.size();
File.write((char *) & Dims, 4);
for (auto jt = it->ScalarFields.begin(); jt != it->ScalarFields.end(); ++ jt)
{
Dims = jt->first.length();
File.write((char *) & Dims, 4);
File.write(jt->first.c_str(), Dims);
File.write((char *) & jt->second, sizeof(double));
}
}
Dims = RawValues.size();
File.write((char *) & Dims, 4);
for (auto it = RawValues.Values.begin(); it != RawValues.Values.end(); ++ it)
{
File.write((char *) & it->Location.X, sizeof(double));
File.write((char *) & it->Location.Y, sizeof(double));
File.write((char *) & it->Location.Z, sizeof(double));
Dims = it->ScalarFields.size();
File.write((char *) & Dims, 4);
for (auto jt = it->ScalarFields.begin(); jt != it->ScalarFields.end(); ++ jt)
{
Dims = jt->first.length();
File.write((char *) & Dims, 4);
File.write(jt->first.c_str(), Dims);
File.write((char *) & jt->second, sizeof(double));
}
}
}
File.close();
}
void SciDataManager::readFromFile(std::string const & FileName)
{
std::ifstream File(FileName, std::ios::out | std::ios::binary);
if (File.is_open())
{
u32 Dims;
File.read((char *) & Dims, 4);
if (Dims)
GridDimensions = new int[Dims];
for (u32 i = 0; i < Dims; ++ i)
{
File.read((char *) & Dims, 4);
GridDimensions[i] = Dims;
}
File.read((char *) & Dims, 4);
u32 DataCount = Dims;
for (u32 i = 0; i < DataCount; ++ i)
{
SciData d;
File.read((char *) & d.Location.X, sizeof(double));
File.read((char *) & d.Location.Y, sizeof(double));
File.read((char *) & d.Location.Z, sizeof(double));
File.read((char *) & Dims, 4);
u32 FieldCount = Dims;
for (u32 j = 0; j < FieldCount; ++ j)
{
File.read((char *) & Dims, 4);
char * Buffer = new char[Dims + 1];
File.read(Buffer, Dims);
Buffer[Dims] = '\0';
double Value;
File.read((char *) & Value, sizeof(double));
d.ScalarFields[std::string(Buffer)] = Value;
}
GridValues.Values.push_back(d);
}
File.read((char *) & Dims, 4);
DataCount = Dims;
for (u32 i = 0; i < DataCount; ++ i)
{
SciData d;
File.read((char *) & d.Location.X, sizeof(double));
File.read((char *) & d.Location.Y, sizeof(double));
File.read((char *) & d.Location.Z, sizeof(double));
File.read((char *) & Dims, 4);
u32 FieldCount = Dims;
for (u32 j = 0; j < FieldCount; ++ j)
{
File.read((char *) & Dims, 4);
char * Buffer = new char[Dims + 1];
File.read(Buffer, Dims);
Buffer[Dims] = '\0';
double Value;
File.read((char *) & Value, sizeof(double));
d.ScalarFields[std::string(Buffer)] = Value;
}
RawValues.Values.push_back(d);
}
}
File.close();
}
<commit_msg>+ Improved binary read speed<commit_after>#include "SciDataManager.h"
#include <iostream>
#include <fstream>
void SciDataManager::writeToFile(std::string const & FileName)
{
std::ofstream File(FileName, std::ios::out | std::ios::binary);
if (File.is_open())
{
u32 Dims = GridDimensions ? 3 : 0;
File.write((char *) & Dims, 4);
for (u32 i = 0; i < Dims; ++ i)
{
Dims = GridDimensions[i];
File.write((char *) & Dims, 4);
}
Dims = GridValues.size();
File.write((char *) & Dims, 4);
for (auto it = GridValues.Values.begin(); it != GridValues.Values.end(); ++ it)
{
File.write((char *) & it->Location.X, sizeof(double));
File.write((char *) & it->Location.Y, sizeof(double));
File.write((char *) & it->Location.Z, sizeof(double));
Dims = it->ScalarFields.size();
File.write((char *) & Dims, 4);
for (auto jt = it->ScalarFields.begin(); jt != it->ScalarFields.end(); ++ jt)
{
Dims = jt->first.length();
File.write((char *) & Dims, 4);
File.write(jt->first.c_str(), Dims);
File.write((char *) & jt->second, sizeof(double));
}
}
Dims = RawValues.size();
File.write((char *) & Dims, 4);
for (auto it = RawValues.Values.begin(); it != RawValues.Values.end(); ++ it)
{
File.write((char *) & it->Location.X, sizeof(double));
File.write((char *) & it->Location.Y, sizeof(double));
File.write((char *) & it->Location.Z, sizeof(double));
Dims = it->ScalarFields.size();
File.write((char *) & Dims, 4);
for (auto jt = it->ScalarFields.begin(); jt != it->ScalarFields.end(); ++ jt)
{
Dims = jt->first.length();
File.write((char *) & Dims, 4);
File.write(jt->first.c_str(), Dims);
File.write((char *) & jt->second, sizeof(double));
}
}
}
File.close();
}
void SciDataManager::readFromFile(std::string const & FileName)
{
std::ifstream File(FileName, std::ios::out | std::ios::binary);
if (File.is_open())
{
u32 Dims;
File.read((char *) & Dims, 4);
if (Dims)
GridDimensions = new int[Dims];
for (u32 i = 0; i < Dims; ++ i)
{
File.read((char *) & Dims, 4);
GridDimensions[i] = Dims;
}
File.read((char *) & Dims, 4);
u32 DataCount = Dims;
GridValues.Values.reserve(DataCount);
for (u32 i = 0; i < DataCount; ++ i)
{
SciData d;
File.read((char *) & d.Location.X, sizeof(double));
File.read((char *) & d.Location.Y, sizeof(double));
File.read((char *) & d.Location.Z, sizeof(double));
File.read((char *) & Dims, 4);
u32 FieldCount = Dims;
for (u32 j = 0; j < FieldCount; ++ j)
{
File.read((char *) & Dims, 4);
char * Buffer = new char[Dims + 1];
File.read(Buffer, Dims);
Buffer[Dims] = '\0';
double Value;
File.read((char *) & Value, sizeof(double));
d.ScalarFields[std::string(Buffer)] = Value;
}
GridValues.Values.push_back(d);
}
File.read((char *) & Dims, 4);
DataCount = Dims;
RawValues.Values.reserve(DataCount);
for (u32 i = 0; i < DataCount; ++ i)
{
SciData d;
File.read((char *) & d.Location.X, sizeof(double));
File.read((char *) & d.Location.Y, sizeof(double));
File.read((char *) & d.Location.Z, sizeof(double));
File.read((char *) & Dims, 4);
u32 FieldCount = Dims;
for (u32 j = 0; j < FieldCount; ++ j)
{
File.read((char *) & Dims, 4);
char * Buffer = new char[Dims + 1];
File.read(Buffer, Dims);
Buffer[Dims] = '\0';
double Value;
File.read((char *) & Value, sizeof(double));
d.ScalarFields[std::string(Buffer)] = Value;
}
RawValues.Values.push_back(d);
}
}
File.close();
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_ExternallyOwnedMemoryInputStream_inl_
#define _Stroika_Foundation_Streams_ExternallyOwnedMemoryInputStream_inl_ 1
#include "../Debug/AssertExternallySynchronizedLock.h"
#include "../Traversal/Iterator.h"
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
************** Streams::ExternallyOwnedMemoryInputStream::Rep_ *****************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Rep_ : public InputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
Rep_ () = delete;
Rep_ (const Rep_&) = delete;
Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: fStart_ (start)
, fEnd_ (end)
, fCursor_ (start)
{
}
public:
nonvirtual Rep_& operator= (const Rep_&) = delete;
protected:
virtual bool IsSeekable () const override
{
return true;
}
virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
size_t nRequested = intoEnd - intoStart;
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Assert ((fStart_ <= fCursor_) and (fCursor_ <= fEnd_));
size_t nAvail = fEnd_ - fCursor_;
size_t nCopied = min (nAvail, nRequested);
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (fCursor_, fCursor_ + nCopied, intoStart);
#else
std::copy (fCursor_, fCursor_ + nCopied, intoStart);
#endif
fCursor_ += nCopied;
return nCopied; // this can be zero on EOF
}
virtual Memory::Optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
// https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
WeakAssert (false);
// @todo - FIX TO REALLY CHECK
return {};
}
virtual SeekOffsetType GetReadOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
return fCursor_ - fStart_;
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (offset > (fEnd_ - fStart_)) {
Execution::Throw (std::range_error ("seek"));
}
fCursor_ = fStart_ + offset;
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fCursor_ - fStart_;
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd_ - fStart_)) {
Execution::Throw (std::range_error ("seek"));
}
fCursor_ = fStart_ + newOffset;
} break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fCursor_ - fStart_;
Streams::SignedSeekOffsetType newOffset = (fEnd_ - fStart_) + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd_ - fStart_)) {
Execution::Throw (std::range_error ("seek"));
}
fCursor_ = fStart_ + newOffset;
} break;
}
Ensure ((fStart_ <= fCursor_) and (fCursor_ <= fEnd_));
return fCursor_ - fStart_;
}
private:
const ELEMENT_TYPE* fStart_;
const ELEMENT_TYPE* fEnd_;
const ELEMENT_TYPE* fCursor_;
};
/*
********************************************************************************
********** Streams::ExternallyOwnedMemoryInputStream<ELEMENT_TYPE> *************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::ExternallyOwnedMemoryInputStream (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: inherited (make_shared<Rep_> (start, end))
{
}
template <typename ELEMENT_TYPE>
template <typename ELEMENT_RANDOM_ACCESS_ITERATOR>
inline ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::ExternallyOwnedMemoryInputStream (ELEMENT_RANDOM_ACCESS_ITERATOR start, ELEMENT_RANDOM_ACCESS_ITERATOR end)
: ExternallyOwnedMemoryInputStream<ELEMENT_TYPE> (static_cast<const ELEMENT_TYPE*> (Traversal::Iterator2Pointer (start)), static_cast<const ELEMENT_TYPE*> (Traversal::Iterator2Pointer (start) + (end - start)))
{
}
/*
********************************************************************************
*********** ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr ****************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr::Ptr (const ExternallyOwnedMemoryInputStream& from)
: InputStream<ELEMENT_TYPE>::Ptr (from)
{
}
template <typename ELEMENT_TYPE>
inline typename ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr& ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr::operator= (const ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>& rhs)
{
InputStream<ELEMENT_TYPE>::Ptr::operator= (rhs);
return *this;
}
}
}
}
#endif /*_Stroika_Foundation_Streams_ExternallyOwnedMemoryInputStream_inl_*/
<commit_msg>back to names BufferedInputStream, ETC - all without the Ptr at the end, and instead made them not copyable (just assignable to base class Ptr types). And added nested Ptr classes they could be assigned to (like BufferedOutputStream<T>::Ptr)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_ExternallyOwnedMemoryInputStream_inl_
#define _Stroika_Foundation_Streams_ExternallyOwnedMemoryInputStream_inl_ 1
#include "../Debug/AssertExternallySynchronizedLock.h"
#include "../Traversal/Iterator.h"
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
************** Streams::ExternallyOwnedMemoryInputStream::Rep_ *****************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Rep_ : public InputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
public:
Rep_ () = delete;
Rep_ (const Rep_&) = delete;
Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: fStart_ (start)
, fEnd_ (end)
, fCursor_ (start)
{
}
public:
nonvirtual Rep_& operator= (const Rep_&) = delete;
protected:
virtual bool IsSeekable () const override
{
return true;
}
virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
size_t nRequested = intoEnd - intoStart;
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Assert ((fStart_ <= fCursor_) and (fCursor_ <= fEnd_));
size_t nAvail = fEnd_ - fCursor_;
size_t nCopied = min (nAvail, nRequested);
#if qSilenceAnnoyingCompilerWarnings && _MSC_VER
Memory::Private::VC_BWA_std_copy (fCursor_, fCursor_ + nCopied, intoStart);
#else
std::copy (fCursor_, fCursor_ + nCopied, intoStart);
#endif
fCursor_ += nCopied;
return nCopied; // this can be zero on EOF
}
virtual Memory::Optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
{
// https://stroika.atlassian.net/browse/STK-567 EXPERIMENTAL DRAFT API
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
WeakAssert (false);
// @todo - FIX TO REALLY CHECK
return {};
}
virtual SeekOffsetType GetReadOffset () const override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
return fCursor_ - fStart_;
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (offset > (fEnd_ - fStart_)) {
Execution::Throw (std::range_error ("seek"));
}
fCursor_ = fStart_ + offset;
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fCursor_ - fStart_;
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd_ - fStart_)) {
Execution::Throw (std::range_error ("seek"));
}
fCursor_ = fStart_ + newOffset;
} break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fCursor_ - fStart_;
Streams::SignedSeekOffsetType newOffset = (fEnd_ - fStart_) + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd_ - fStart_)) {
Execution::Throw (std::range_error ("seek"));
}
fCursor_ = fStart_ + newOffset;
} break;
}
Ensure ((fStart_ <= fCursor_) and (fCursor_ <= fEnd_));
return fCursor_ - fStart_;
}
private:
const ELEMENT_TYPE* fStart_;
const ELEMENT_TYPE* fEnd_;
const ELEMENT_TYPE* fCursor_;
};
/*
********************************************************************************
********** Streams::ExternallyOwnedMemoryInputStream<ELEMENT_TYPE> *************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::ExternallyOwnedMemoryInputStream (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end)
: inherited (make_shared<Rep_> (start, end))
{
}
template <typename ELEMENT_TYPE>
template <typename ELEMENT_RANDOM_ACCESS_ITERATOR>
inline ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::ExternallyOwnedMemoryInputStream (ELEMENT_RANDOM_ACCESS_ITERATOR start, ELEMENT_RANDOM_ACCESS_ITERATOR end)
: ExternallyOwnedMemoryInputStream<ELEMENT_TYPE> (static_cast<const ELEMENT_TYPE*> (Traversal::Iterator2Pointer (start)), static_cast<const ELEMENT_TYPE*> (Traversal::Iterator2Pointer (start) + (end - start)))
{
}
/*
********************************************************************************
*********** ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr ****************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr::Ptr (const ExternallyOwnedMemoryInputStream& from)
: InputStream<ELEMENT_TYPE>::Ptr (from)
{
}
template <typename ELEMENT_TYPE>
inline typename ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr& ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>::Ptr::operator= (const ExternallyOwnedMemoryInputStream<ELEMENT_TYPE>& rhs)
{
InputStream<ELEMENT_TYPE>::Ptr::operator= (rhs);
return *this;
}
}
}
}
#endif /*_Stroika_Foundation_Streams_ExternallyOwnedMemoryInputStream_inl_*/
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLASCIITranscoder.hpp>
#include <util/XMLString.hpp>
#include <util/TranscodingException.hpp>
#include <memory.h>
// ---------------------------------------------------------------------------
// XMLASCIITranscoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLASCIITranscoder::XMLASCIITranscoder( const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
{
}
XMLASCIITranscoder::~XMLASCIITranscoder()
{
}
// ---------------------------------------------------------------------------
// XMLASCIITranscoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
unsigned int
XMLASCIITranscoder::transcodeFrom( const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the source byte count.
//
const unsigned int countToDo = srcCount < maxChars ? srcCount : maxChars;
//
// Now loop through that many source chars and just cast each one
// over to the XMLCh format. Check each source that its really a
// valid ASCI char.
//
const XMLByte* srcPtr = srcData;
XMLCh* outPtr = toFill;
unsigned int countDone = 0;
for (; countDone < countToDo; countDone++)
{
// Do the optimistic work up front
if (*srcPtr < 0x80)
{
*outPtr++ = XMLCh(*srcPtr++);
continue;
}
//
// We got non source encoding char. If we got more than 32 chars,
// the just break out. We'll come back here later to hit this again
// and give an error much closer to the real source position.
//
if (countDone > 32)
break;
XMLCh tmpBuf[16];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
// Set the bytes we ate
bytesEaten = countDone;
// Set the char sizes to the fixed size
memset(charSizes, 1, countDone);
// Return the chars we transcoded
return countDone;
}
unsigned int
XMLASCIITranscoder::transcodeTo(const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxBytes);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the source byte count.
//
const unsigned int countToDo = srcCount < maxBytes ? srcCount : maxBytes;
const XMLCh* srcPtr = srcData;
XMLByte* outPtr = toFill;
for (unsigned int index; index < countToDo; index++)
{
// If its legal, do it and jump back to the top
if (*srcPtr < 0x80)
{
*outPtr++ = XMLByte(*srcPtr++);
continue;
}
//
// Its not representable so use a replacement char. According to
// the options, either throw or use the replacement.
//
if (options == UnRep_Throw)
{
XMLCh tmpBuf[16];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
// Use the replacement char
*outPtr++ = 0x1A;
}
// Set the chars we ate
charsEaten = countToDo;
// Return the byte we transcoded
return countToDo;
}
bool XMLASCIITranscoder::canTranscodeTo(const unsigned int toCheck) const
{
return (toCheck < 0x80);
}
<commit_msg>Initialized the loop variable 'index'. CC under HPUX complained of it being used before being initialized.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XMLASCIITranscoder.hpp>
#include <util/XMLString.hpp>
#include <util/TranscodingException.hpp>
#include <memory.h>
// ---------------------------------------------------------------------------
// XMLASCIITranscoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLASCIITranscoder::XMLASCIITranscoder( const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
{
}
XMLASCIITranscoder::~XMLASCIITranscoder()
{
}
// ---------------------------------------------------------------------------
// XMLASCIITranscoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
unsigned int
XMLASCIITranscoder::transcodeFrom( const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the source byte count.
//
const unsigned int countToDo = srcCount < maxChars ? srcCount : maxChars;
//
// Now loop through that many source chars and just cast each one
// over to the XMLCh format. Check each source that its really a
// valid ASCI char.
//
const XMLByte* srcPtr = srcData;
XMLCh* outPtr = toFill;
unsigned int countDone = 0;
for (; countDone < countToDo; countDone++)
{
// Do the optimistic work up front
if (*srcPtr < 0x80)
{
*outPtr++ = XMLCh(*srcPtr++);
continue;
}
//
// We got non source encoding char. If we got more than 32 chars,
// the just break out. We'll come back here later to hit this again
// and give an error much closer to the real source position.
//
if (countDone > 32)
break;
XMLCh tmpBuf[16];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
// Set the bytes we ate
bytesEaten = countDone;
// Set the char sizes to the fixed size
memset(charSizes, 1, countDone);
// Return the chars we transcoded
return countDone;
}
unsigned int
XMLASCIITranscoder::transcodeTo(const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options)
{
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxBytes);
#endif
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the source byte count.
//
const unsigned int countToDo = srcCount < maxBytes ? srcCount : maxBytes;
const XMLCh* srcPtr = srcData;
XMLByte* outPtr = toFill;
for (unsigned int index = 0; index < countToDo; index++)
{
// If its legal, do it and jump back to the top
if (*srcPtr < 0x80)
{
*outPtr++ = XMLByte(*srcPtr++);
continue;
}
//
// Its not representable so use a replacement char. According to
// the options, either throw or use the replacement.
//
if (options == UnRep_Throw)
{
XMLCh tmpBuf[16];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
// Use the replacement char
*outPtr++ = 0x1A;
}
// Set the chars we ate
charsEaten = countToDo;
// Return the byte we transcoded
return countToDo;
}
bool XMLASCIITranscoder::canTranscodeTo(const unsigned int toCheck) const
{
return (toCheck < 0x80);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_vector.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// The LifeCycleObject notifies its Observer upon construction & destruction.
class LifeCycleObject {
public:
class Observer {
public:
virtual void OnLifeCycleConstruct(LifeCycleObject* o) = 0;
virtual void OnLifeCycleDestroy(LifeCycleObject* o) = 0;
protected:
virtual ~Observer() {}
};
~LifeCycleObject() {
observer_->OnLifeCycleDestroy(this);
}
private:
friend class LifeCycleWatcher;
explicit LifeCycleObject(Observer* observer)
: observer_(observer) {
observer_->OnLifeCycleConstruct(this);
}
Observer* observer_;
DISALLOW_COPY_AND_ASSIGN(LifeCycleObject);
};
// The life cycle states we care about for the purposes of testing ScopedVector
// against objects.
enum LifeCycleState {
LC_INITIAL,
LC_CONSTRUCTED,
LC_DESTROYED,
};
// Because we wish to watch the life cycle of an object being constructed and
// destroyed, and further wish to test expectations against the state of that
// object, we cannot save state in that object itself. Instead, we use this
// pairing of the watcher, which observes the object and notifies of
// construction & destruction. Since we also may be testing assumptions about
// things not getting freed, this class also acts like a scoping object and
// deletes the |constructed_life_cycle_object_|, if any when the
// LifeCycleWatcher is destroyed. To keep this simple, the only expected state
// changes are:
// INITIAL -> CONSTRUCTED -> DESTROYED.
// Anything more complicated than that should start another test.
class LifeCycleWatcher : public LifeCycleObject::Observer {
public:
LifeCycleWatcher()
: life_cycle_state_(LC_INITIAL),
constructed_life_cycle_object_(NULL) {}
virtual ~LifeCycleWatcher() {}
// Assert INITIAL -> CONSTRUCTED and no LifeCycleObject associated with this
// LifeCycleWatcher.
virtual void OnLifeCycleConstruct(LifeCycleObject* object) OVERRIDE {
ASSERT_EQ(LC_INITIAL, life_cycle_state_);
ASSERT_EQ(NULL, constructed_life_cycle_object_.get());
life_cycle_state_ = LC_CONSTRUCTED;
constructed_life_cycle_object_.reset(object);
}
// Assert CONSTRUCTED -> DESTROYED and the |object| being destroyed is the
// same one we saw constructed.
virtual void OnLifeCycleDestroy(LifeCycleObject* object) OVERRIDE {
ASSERT_EQ(LC_CONSTRUCTED, life_cycle_state_);
LifeCycleObject* constructed_life_cycle_object =
constructed_life_cycle_object_.release();
ASSERT_EQ(constructed_life_cycle_object, object);
life_cycle_state_ = LC_DESTROYED;
}
LifeCycleState life_cycle_state() const { return life_cycle_state_; }
// Factory method for creating a new LifeCycleObject tied to this
// LifeCycleWatcher.
LifeCycleObject* NewLifeCycleObject() {
return new LifeCycleObject(this);
}
private:
LifeCycleState life_cycle_state_;
scoped_ptr<LifeCycleObject> constructed_life_cycle_object_;
DISALLOW_COPY_AND_ASSIGN(LifeCycleWatcher);
};
TEST(ScopedVectorTest, LifeCycleWatcher) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
LifeCycleObject* object = watcher.NewLifeCycleObject();
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
delete object;
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
TEST(ScopedVectorTest, Clear) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
scoped_vector.clear();
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
EXPECT_TRUE(scoped_vector.empty());
}
TEST(ScopedVectorTest, WeakClear) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
scoped_vector.weak_clear();
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_TRUE(scoped_vector.empty());
}
TEST(ScopedVectorTest, ResizeShrink) {
LifeCycleWatcher first_watcher;
EXPECT_EQ(LC_INITIAL, first_watcher.life_cycle_state());
LifeCycleWatcher second_watcher;
EXPECT_EQ(LC_INITIAL, second_watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(first_watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, first_watcher.life_cycle_state());
EXPECT_EQ(LC_INITIAL, second_watcher.life_cycle_state());
scoped_vector.push_back(second_watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, first_watcher.life_cycle_state());
EXPECT_EQ(LC_CONSTRUCTED, second_watcher.life_cycle_state());
// Test that shrinking a vector deletes elements in the dissapearing range.
scoped_vector.resize(1);
EXPECT_EQ(LC_CONSTRUCTED, first_watcher.life_cycle_state());
EXPECT_EQ(LC_DESTROYED, second_watcher.life_cycle_state());
EXPECT_EQ(1u, scoped_vector.size());
}
TEST(ScopedVectorTest, ResizeGrow) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
scoped_vector.resize(5);
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_EQ(5u, scoped_vector.size());
}
TEST(ScopedVectorTest, Scope) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
}
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
TEST(ScopedVectorTest, MoveConstruct) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_FALSE(scoped_vector.empty());
ScopedVector<LifeCycleObject> scoped_vector_copy(scoped_vector.Pass());
EXPECT_TRUE(scoped_vector.empty());
EXPECT_FALSE(scoped_vector_copy.empty());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
}
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
TEST(ScopedVectorTest, MoveAssign) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
ScopedVector<LifeCycleObject> scoped_vector_assign;
EXPECT_FALSE(scoped_vector.empty());
scoped_vector_assign = scoped_vector.Pass();
EXPECT_TRUE(scoped_vector.empty());
EXPECT_FALSE(scoped_vector_assign.empty());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
}
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
class DeleteCounter {
public:
explicit DeleteCounter(int* deletes)
: deletes_(deletes) {
}
~DeleteCounter() {
(*deletes_)++;
}
void VoidMethod0() {}
private:
int* const deletes_;
DISALLOW_COPY_AND_ASSIGN(DeleteCounter);
};
template <typename T>
ScopedVector<T> PassThru(ScopedVector<T> scoper) {
return scoper.Pass();
}
TEST(ScopedVectorTest, Passed) {
int deletes = 0;
ScopedVector<DeleteCounter> deleter_vector;
deleter_vector.push_back(new DeleteCounter(&deletes));
EXPECT_EQ(0, deletes);
base::Callback<ScopedVector<DeleteCounter>(void)> callback =
base::Bind(&PassThru<DeleteCounter>, base::Passed(&deleter_vector));
EXPECT_EQ(0, deletes);
ScopedVector<DeleteCounter> result = callback.Run();
EXPECT_EQ(0, deletes);
result.clear();
EXPECT_EQ(1, deletes);
};
TEST(ScopedVectorTest, InsertRange) {
LifeCycleWatcher watchers[5];
std::vector<LifeCycleObject*> vec;
for(LifeCycleWatcher* it = watchers; it != watchers + arraysize(watchers);
++it) {
EXPECT_EQ(LC_INITIAL, it->life_cycle_state());
vec.push_back(it->NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
}
// Start scope for ScopedVector.
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.insert(scoped_vector.end(), vec.begin() + 1, vec.begin() + 3);
for(LifeCycleWatcher* it = watchers; it != watchers + arraysize(watchers);
++it)
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
}
for(LifeCycleWatcher* it = watchers; it != watchers + 1; ++it)
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
for(LifeCycleWatcher* it = watchers + 1; it != watchers + 3; ++it)
EXPECT_EQ(LC_DESTROYED, it->life_cycle_state());
for(LifeCycleWatcher* it = watchers + 3; it != watchers + arraysize(watchers);
++it)
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
}
} // namespace
<commit_msg>Assert on actual contents of ScopedVector in scoped_vector_unittest.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_vector.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// The LifeCycleObject notifies its Observer upon construction & destruction.
class LifeCycleObject {
public:
class Observer {
public:
virtual void OnLifeCycleConstruct(LifeCycleObject* o) = 0;
virtual void OnLifeCycleDestroy(LifeCycleObject* o) = 0;
protected:
virtual ~Observer() {}
};
~LifeCycleObject() {
observer_->OnLifeCycleDestroy(this);
}
private:
friend class LifeCycleWatcher;
explicit LifeCycleObject(Observer* observer)
: observer_(observer) {
observer_->OnLifeCycleConstruct(this);
}
Observer* observer_;
DISALLOW_COPY_AND_ASSIGN(LifeCycleObject);
};
// The life cycle states we care about for the purposes of testing ScopedVector
// against objects.
enum LifeCycleState {
LC_INITIAL,
LC_CONSTRUCTED,
LC_DESTROYED,
};
// Because we wish to watch the life cycle of an object being constructed and
// destroyed, and further wish to test expectations against the state of that
// object, we cannot save state in that object itself. Instead, we use this
// pairing of the watcher, which observes the object and notifies of
// construction & destruction. Since we also may be testing assumptions about
// things not getting freed, this class also acts like a scoping object and
// deletes the |constructed_life_cycle_object_|, if any when the
// LifeCycleWatcher is destroyed. To keep this simple, the only expected state
// changes are:
// INITIAL -> CONSTRUCTED -> DESTROYED.
// Anything more complicated than that should start another test.
class LifeCycleWatcher : public LifeCycleObject::Observer {
public:
LifeCycleWatcher()
: life_cycle_state_(LC_INITIAL),
constructed_life_cycle_object_(NULL) {}
virtual ~LifeCycleWatcher() {}
// Assert INITIAL -> CONSTRUCTED and no LifeCycleObject associated with this
// LifeCycleWatcher.
virtual void OnLifeCycleConstruct(LifeCycleObject* object) OVERRIDE {
ASSERT_EQ(LC_INITIAL, life_cycle_state_);
ASSERT_EQ(NULL, constructed_life_cycle_object_.get());
life_cycle_state_ = LC_CONSTRUCTED;
constructed_life_cycle_object_.reset(object);
}
// Assert CONSTRUCTED -> DESTROYED and the |object| being destroyed is the
// same one we saw constructed.
virtual void OnLifeCycleDestroy(LifeCycleObject* object) OVERRIDE {
ASSERT_EQ(LC_CONSTRUCTED, life_cycle_state_);
LifeCycleObject* constructed_life_cycle_object =
constructed_life_cycle_object_.release();
ASSERT_EQ(constructed_life_cycle_object, object);
life_cycle_state_ = LC_DESTROYED;
}
LifeCycleState life_cycle_state() const { return life_cycle_state_; }
// Factory method for creating a new LifeCycleObject tied to this
// LifeCycleWatcher.
LifeCycleObject* NewLifeCycleObject() {
return new LifeCycleObject(this);
}
// Returns true iff |object| is the same object that this watcher is tracking.
bool IsWatching(LifeCycleObject* object) const {
return object == constructed_life_cycle_object_.get();
}
private:
LifeCycleState life_cycle_state_;
scoped_ptr<LifeCycleObject> constructed_life_cycle_object_;
DISALLOW_COPY_AND_ASSIGN(LifeCycleWatcher);
};
TEST(ScopedVectorTest, LifeCycleWatcher) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
LifeCycleObject* object = watcher.NewLifeCycleObject();
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
delete object;
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
TEST(ScopedVectorTest, Clear) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_TRUE(watcher.IsWatching(scoped_vector.back()));
scoped_vector.clear();
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
EXPECT_TRUE(scoped_vector.empty());
}
TEST(ScopedVectorTest, WeakClear) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_TRUE(watcher.IsWatching(scoped_vector.back()));
scoped_vector.weak_clear();
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_TRUE(scoped_vector.empty());
}
TEST(ScopedVectorTest, ResizeShrink) {
LifeCycleWatcher first_watcher;
EXPECT_EQ(LC_INITIAL, first_watcher.life_cycle_state());
LifeCycleWatcher second_watcher;
EXPECT_EQ(LC_INITIAL, second_watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(first_watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, first_watcher.life_cycle_state());
EXPECT_EQ(LC_INITIAL, second_watcher.life_cycle_state());
EXPECT_TRUE(first_watcher.IsWatching(scoped_vector[0]));
EXPECT_FALSE(second_watcher.IsWatching(scoped_vector[0]));
scoped_vector.push_back(second_watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, first_watcher.life_cycle_state());
EXPECT_EQ(LC_CONSTRUCTED, second_watcher.life_cycle_state());
EXPECT_FALSE(first_watcher.IsWatching(scoped_vector[1]));
EXPECT_TRUE(second_watcher.IsWatching(scoped_vector[1]));
// Test that shrinking a vector deletes elements in the disappearing range.
scoped_vector.resize(1);
EXPECT_EQ(LC_CONSTRUCTED, first_watcher.life_cycle_state());
EXPECT_EQ(LC_DESTROYED, second_watcher.life_cycle_state());
EXPECT_EQ(1u, scoped_vector.size());
EXPECT_TRUE(first_watcher.IsWatching(scoped_vector[0]));
}
TEST(ScopedVectorTest, ResizeGrow) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_TRUE(watcher.IsWatching(scoped_vector.back()));
scoped_vector.resize(5);
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
ASSERT_EQ(5u, scoped_vector.size());
EXPECT_TRUE(watcher.IsWatching(scoped_vector[0]));
EXPECT_FALSE(watcher.IsWatching(scoped_vector[1]));
EXPECT_FALSE(watcher.IsWatching(scoped_vector[2]));
EXPECT_FALSE(watcher.IsWatching(scoped_vector[3]));
EXPECT_FALSE(watcher.IsWatching(scoped_vector[4]));
}
TEST(ScopedVectorTest, Scope) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
EXPECT_TRUE(watcher.IsWatching(scoped_vector.back()));
}
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
TEST(ScopedVectorTest, MoveConstruct) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
EXPECT_FALSE(scoped_vector.empty());
EXPECT_TRUE(watcher.IsWatching(scoped_vector.back()));
ScopedVector<LifeCycleObject> scoped_vector_copy(scoped_vector.Pass());
EXPECT_TRUE(scoped_vector.empty());
EXPECT_FALSE(scoped_vector_copy.empty());
EXPECT_TRUE(watcher.IsWatching(scoped_vector_copy.back()));
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
}
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
TEST(ScopedVectorTest, MoveAssign) {
LifeCycleWatcher watcher;
EXPECT_EQ(LC_INITIAL, watcher.life_cycle_state());
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.push_back(watcher.NewLifeCycleObject());
ScopedVector<LifeCycleObject> scoped_vector_assign;
EXPECT_FALSE(scoped_vector.empty());
EXPECT_TRUE(watcher.IsWatching(scoped_vector.back()));
scoped_vector_assign = scoped_vector.Pass();
EXPECT_TRUE(scoped_vector.empty());
EXPECT_FALSE(scoped_vector_assign.empty());
EXPECT_TRUE(watcher.IsWatching(scoped_vector_assign.back()));
EXPECT_EQ(LC_CONSTRUCTED, watcher.life_cycle_state());
}
EXPECT_EQ(LC_DESTROYED, watcher.life_cycle_state());
}
class DeleteCounter {
public:
explicit DeleteCounter(int* deletes)
: deletes_(deletes) {
}
~DeleteCounter() {
(*deletes_)++;
}
void VoidMethod0() {}
private:
int* const deletes_;
DISALLOW_COPY_AND_ASSIGN(DeleteCounter);
};
template <typename T>
ScopedVector<T> PassThru(ScopedVector<T> scoper) {
return scoper.Pass();
}
TEST(ScopedVectorTest, Passed) {
int deletes = 0;
ScopedVector<DeleteCounter> deleter_vector;
deleter_vector.push_back(new DeleteCounter(&deletes));
EXPECT_EQ(0, deletes);
base::Callback<ScopedVector<DeleteCounter>(void)> callback =
base::Bind(&PassThru<DeleteCounter>, base::Passed(&deleter_vector));
EXPECT_EQ(0, deletes);
ScopedVector<DeleteCounter> result = callback.Run();
EXPECT_EQ(0, deletes);
result.clear();
EXPECT_EQ(1, deletes);
};
TEST(ScopedVectorTest, InsertRange) {
LifeCycleWatcher watchers[5];
std::vector<LifeCycleObject*> vec;
for(LifeCycleWatcher* it = watchers; it != watchers + arraysize(watchers);
++it) {
EXPECT_EQ(LC_INITIAL, it->life_cycle_state());
vec.push_back(it->NewLifeCycleObject());
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
}
// Start scope for ScopedVector.
{
ScopedVector<LifeCycleObject> scoped_vector;
scoped_vector.insert(scoped_vector.end(), vec.begin() + 1, vec.begin() + 3);
for(LifeCycleWatcher* it = watchers; it != watchers + arraysize(watchers);
++it)
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
}
for(LifeCycleWatcher* it = watchers; it != watchers + 1; ++it)
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
for(LifeCycleWatcher* it = watchers + 1; it != watchers + 3; ++it)
EXPECT_EQ(LC_DESTROYED, it->life_cycle_state());
for(LifeCycleWatcher* it = watchers + 3; it != watchers + arraysize(watchers);
++it)
EXPECT_EQ(LC_CONSTRUCTED, it->life_cycle_state());
}
} // namespace
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "AsyncVideoDecoder.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <math.h>
#include <iostream>
using namespace boost;
using namespace std;
namespace avg {
AsyncVideoDecoder::AsyncVideoDecoder(VideoDecoderPtr pSyncDecoder, int queueLength)
: m_State(CLOSED),
m_pSyncDecoder(pSyncDecoder),
m_QueueLength(queueLength),
m_pVDecoderThread(0),
m_pADecoderThread(0),
m_PF(NO_PIXELFORMAT),
m_bAudioEOF(false),
m_bVideoEOF(false),
m_bSeekPending(false),
m_Volume(1.0),
m_LastVideoFrameTime(-1),
m_LastAudioFrameTime(-1)
{
ObjectCounter::get()->incRef(&typeid(*this));
}
AsyncVideoDecoder::~AsyncVideoDecoder()
{
if (m_pVDecoderThread || m_pADecoderThread) {
close();
}
ObjectCounter::get()->decRef(&typeid(*this));
}
void AsyncVideoDecoder::open(const std::string& sFilename, bool bThreadedDemuxer)
{
m_bAudioEOF = false;
m_bVideoEOF = false;
m_bSeekPending = false;
m_sFilename = sFilename;
m_pSyncDecoder->open(m_sFilename, bThreadedDemuxer);
m_VideoInfo = m_pSyncDecoder->getVideoInfo();
// Temporary pf - always assumes shaders will be available.
m_PF = m_pSyncDecoder->getPixelFormat();
m_State = OPENED;
}
void AsyncVideoDecoder::startDecoding(bool bDeliverYCbCr, const AudioParams* pAP)
{
AVG_ASSERT(m_State == OPENED);
m_pSyncDecoder->startDecoding(bDeliverYCbCr, pAP);
m_VideoInfo = m_pSyncDecoder->getVideoInfo();
if (m_VideoInfo.m_bHasVideo) {
m_LastVideoFrameTime = -1;
m_PF = m_pSyncDecoder->getPixelFormat();
m_pVCmdQ = VideoDecoderThread::CQueuePtr(new VideoDecoderThread::CQueue);
m_pVMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(m_QueueLength));
m_pVDecoderThread = new boost::thread(
VideoDecoderThread(*m_pVCmdQ, *m_pVMsgQ, m_pSyncDecoder));
}
if (m_VideoInfo.m_bHasAudio) {
m_pACmdQ = AudioDecoderThread::CQueuePtr(new AudioDecoderThread::CQueue);
m_pAMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8));
m_pADecoderThread = new boost::thread(
AudioDecoderThread(*m_pACmdQ, *m_pAMsgQ, m_pSyncDecoder, *pAP));
m_AudioMsgData = 0;
m_AudioMsgSize = 0;
m_LastAudioFrameTime = 0;
setVolume(m_Volume);
}
m_State = DECODING;
}
void AsyncVideoDecoder::close()
{
AVG_ASSERT(m_State != CLOSED);
if (m_pVDecoderThread) {
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::stop, _1));
getNextBmps(false); // If the Queue is full, this breaks the lock in the thread.
m_pVDecoderThread->join();
delete m_pVDecoderThread;
m_pVDecoderThread = 0;
m_pVMsgQ = VideoMsgQueuePtr();
}
{
scoped_lock lock1(m_AudioMutex);
if (m_pADecoderThread) {
m_pACmdQ->pushCmd(boost::bind(&AudioDecoderThread::stop, _1));
m_pAMsgQ->pop(false);
m_pAMsgQ->pop(false);
m_pADecoderThread->join();
delete m_pADecoderThread;
m_pADecoderThread = 0;
m_pAMsgQ = VideoMsgQueuePtr();
}
m_pSyncDecoder->close();
}
}
IVideoDecoder::DecoderState AsyncVideoDecoder::getState() const
{
return m_State;
}
VideoInfo AsyncVideoDecoder::getVideoInfo() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo;
}
void AsyncVideoDecoder::seek(double destTime)
{
AVG_ASSERT(m_State == DECODING);
waitForSeekDone();
scoped_lock lock1(m_AudioMutex);
scoped_lock Lock2(m_SeekMutex);
m_bAudioEOF = false;
m_bVideoEOF = false;
m_bSeekPending = false;
m_LastVideoFrameTime = -1;
m_bSeekPending = true;
if (m_pVCmdQ) {
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::seek, _1, destTime));
} else {
m_pACmdQ->pushCmd(boost::bind(&AudioDecoderThread::seek, _1, destTime));
}
bool bDone = false;
while (!bDone && m_bSeekPending) {
VideoMsgPtr pMsg;
if (m_pVCmdQ) {
pMsg = m_pVMsgQ->pop(false);
} else {
pMsg = m_pAMsgQ->pop(false);
}
if (pMsg) {
switch (pMsg->getType()) {
case VideoMsg::SEEK_DONE:
m_bSeekPending = false;
m_LastVideoFrameTime = pMsg->getSeekVideoFrameTime();
m_LastAudioFrameTime = pMsg->getSeekAudioFrameTime();
break;
case VideoMsg::FRAME:
returnFrame(pMsg);
break;
default:
break;
}
} else {
bDone = true;
}
}
}
void AsyncVideoDecoder::loop()
{
m_LastVideoFrameTime = -1;
m_bAudioEOF = false;
m_bVideoEOF = false;
}
IntPoint AsyncVideoDecoder::getSize() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo.m_Size;
}
int AsyncVideoDecoder::getCurFrame() const
{
AVG_ASSERT(m_State != CLOSED);
return int(getCurTime(SS_VIDEO)*m_VideoInfo.m_StreamFPS+0.5);
}
int AsyncVideoDecoder::getNumFramesQueued() const
{
AVG_ASSERT(m_State == DECODING);
return m_pVMsgQ->size();
}
double AsyncVideoDecoder::getCurTime(StreamSelect stream) const
{
AVG_ASSERT(m_State != CLOSED);
switch (stream) {
case SS_DEFAULT:
case SS_VIDEO:
AVG_ASSERT(m_VideoInfo.m_bHasVideo);
return m_LastVideoFrameTime;
break;
case SS_AUDIO:
AVG_ASSERT(m_VideoInfo.m_bHasAudio);
return m_LastAudioFrameTime;
break;
default:
AVG_ASSERT(false);
}
return -1;
}
double AsyncVideoDecoder::getNominalFPS() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo.m_StreamFPS;
}
double AsyncVideoDecoder::getFPS() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo.m_FPS;
}
void AsyncVideoDecoder::setFPS(double fps)
{
AVG_ASSERT(!m_pADecoderThread);
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::setFPS, _1, fps));
if (fps != 0) {
m_VideoInfo.m_FPS = fps;
}
}
double AsyncVideoDecoder::getVolume() const
{
AVG_ASSERT(m_State != CLOSED);
return m_Volume;
}
void AsyncVideoDecoder::setVolume(double volume)
{
m_Volume = volume;
if (m_State != CLOSED && m_VideoInfo.m_bHasAudio && m_pACmdQ) {
m_pACmdQ->pushCmd(boost::bind(&AudioDecoderThread::setVolume, _1, volume));
}
}
PixelFormat AsyncVideoDecoder::getPixelFormat() const
{
AVG_ASSERT(m_State != CLOSED);
return m_PF;
}
FrameAvailableCode AsyncVideoDecoder::renderToBmps(vector<BitmapPtr>& pBmps,
double timeWanted)
{
AVG_ASSERT(m_State == DECODING);
FrameAvailableCode frameAvailable;
VideoMsgPtr pFrameMsg = getBmpsForTime(timeWanted, frameAvailable);
if (frameAvailable == FA_NEW_FRAME) {
AVG_ASSERT(pFrameMsg);
for (unsigned i = 0; i < pBmps.size(); ++i) {
pBmps[i]->copyPixels(*(pFrameMsg->getFrameBitmap(i)));
}
returnFrame(pFrameMsg);
}
return frameAvailable;
}
bool AsyncVideoDecoder::isEOF(StreamSelect stream) const
{
AVG_ASSERT(m_State == DECODING);
switch(stream) {
case SS_AUDIO:
return (!m_VideoInfo.m_bHasAudio || m_bAudioEOF);
case SS_VIDEO:
return (!m_VideoInfo.m_bHasVideo || m_bVideoEOF);
case SS_ALL:
return isEOF(SS_VIDEO) && isEOF(SS_AUDIO);
default:
return false;
}
}
void AsyncVideoDecoder::throwAwayFrame(double timeWanted)
{
AVG_ASSERT(m_State == DECODING);
FrameAvailableCode frameAvailable;
VideoMsgPtr pFrameMsg = getBmpsForTime(timeWanted, frameAvailable);
}
int AsyncVideoDecoder::fillAudioBuffer(AudioBufferPtr pBuffer)
{
AVG_ASSERT(m_State == DECODING);
AVG_ASSERT (m_pADecoderThread);
if (m_bAudioEOF) {
return 0;
}
scoped_lock lock(m_AudioMutex);
waitForSeekDone();
unsigned char* pDest = (unsigned char *)(pBuffer->getData());
int bufferLeftToFill = pBuffer->getNumBytes();
VideoMsgPtr pMsg;
while (bufferLeftToFill > 0) {
while (m_AudioMsgSize > 0 && bufferLeftToFill > 0) {
int copyBytes = min(bufferLeftToFill, m_AudioMsgSize);
memcpy(pDest, m_AudioMsgData, copyBytes);
m_AudioMsgSize -= copyBytes;
m_AudioMsgData += copyBytes;
bufferLeftToFill -= copyBytes;
pDest += copyBytes;
m_LastAudioFrameTime += copyBytes /
(pBuffer->getFrameSize() * pBuffer->getRate());
}
if (bufferLeftToFill != 0) {
pMsg = m_pAMsgQ->pop(false);
if (pMsg) {
if (pMsg->getType() == VideoMsg::END_OF_FILE) {
m_bAudioEOF = true;
return pBuffer->getNumFrames()-bufferLeftToFill/
pBuffer->getFrameSize();
}
AVG_ASSERT(pMsg->getType() == VideoMsg::AUDIO);
m_AudioMsgSize = pMsg->getAudioBuffer()->getNumFrames()
*pBuffer->getFrameSize();
m_AudioMsgData = (unsigned char *)(pMsg->getAudioBuffer()->getData());
m_LastAudioFrameTime = pMsg->getAudioTime();
} else {
return pBuffer->getNumFrames()-bufferLeftToFill/pBuffer->getFrameSize();
}
}
}
return pBuffer->getNumFrames();
}
VideoMsgPtr AsyncVideoDecoder::getBmpsForTime(double timeWanted,
FrameAvailableCode& frameAvailable)
{
if (timeWanted < 0 && timeWanted != -1) {
cerr << "Illegal timeWanted: " << timeWanted << endl;
AVG_ASSERT(false);
}
// XXX: This code is sort-of duplicated in FFMpegDecoder::readFrameForTime()
double frameTime = -1;
VideoMsgPtr pFrameMsg;
if (timeWanted == -1) {
pFrameMsg = getNextBmps(true);
frameAvailable = FA_NEW_FRAME;
} else {
double timePerFrame = 1.0/getFPS();
if (fabs(double(timeWanted-m_LastVideoFrameTime)) < 0.5*timePerFrame ||
m_LastVideoFrameTime > timeWanted+timePerFrame) {
// The last frame is still current. Display it again.
frameAvailable = FA_USE_LAST_FRAME;
return VideoMsgPtr();
} else {
if (m_bVideoEOF) {
frameAvailable = FA_USE_LAST_FRAME;
return VideoMsgPtr();
}
while (frameTime-timeWanted < -0.5*timePerFrame && !m_bVideoEOF) {
returnFrame(pFrameMsg);
pFrameMsg = getNextBmps(false);
if (pFrameMsg) {
frameTime = pFrameMsg->getFrameTime();
} else {
frameAvailable = FA_STILL_DECODING;
return VideoMsgPtr();
}
}
if (!pFrameMsg) {
cerr << "frameTime=" << frameTime << ", timeWanted=" << timeWanted
<< ", timePerFrame=" << timePerFrame << ", m_bVideoEOF="
<< m_bVideoEOF << endl;
AVG_ASSERT(false);
}
frameAvailable = FA_NEW_FRAME;
}
}
if (pFrameMsg) {
m_LastVideoFrameTime = pFrameMsg->getFrameTime();
}
return pFrameMsg;
}
VideoMsgPtr AsyncVideoDecoder::getNextBmps(bool bWait)
{
waitForSeekDone();
VideoMsgPtr pMsg = m_pVMsgQ->pop(bWait);
if (pMsg) {
switch (pMsg->getType()) {
case VideoMsg::FRAME:
return pMsg;
case VideoMsg::END_OF_FILE:
m_bVideoEOF = true;
return VideoMsgPtr();
case VideoMsg::ERROR:
m_bVideoEOF = true;
return VideoMsgPtr();
default:
// Unhandled message type.
AVG_ASSERT(false);
return VideoMsgPtr();
}
} else {
return pMsg;
}
}
void AsyncVideoDecoder::waitForSeekDone()
{
scoped_lock lock(m_SeekMutex);
if (m_bSeekPending) {
do {
VideoMsgPtr pMsg;
if (m_pVCmdQ) {
pMsg = m_pVMsgQ->pop(true);
} else {
pMsg = m_pAMsgQ->pop(true);
}
switch (pMsg->getType()) {
case VideoMsg::SEEK_DONE:
m_bSeekPending = false;
m_LastVideoFrameTime = pMsg->getSeekVideoFrameTime();
m_LastAudioFrameTime = pMsg->getSeekAudioFrameTime();
break;
case VideoMsg::FRAME:
returnFrame(pMsg);
break;
default:
// TODO: Handle ERROR messages here.
break;
}
} while (m_bSeekPending);
}
}
void AsyncVideoDecoder::returnFrame(VideoMsgPtr& pFrameMsg)
{
if (pFrameMsg) {
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::returnFrame, _1, pFrameMsg));
}
}
}
<commit_msg>Fixed volume setting on sound start (first few samples were played back at volume=1).<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "AsyncVideoDecoder.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <math.h>
#include <iostream>
using namespace boost;
using namespace std;
namespace avg {
AsyncVideoDecoder::AsyncVideoDecoder(VideoDecoderPtr pSyncDecoder, int queueLength)
: m_State(CLOSED),
m_pSyncDecoder(pSyncDecoder),
m_QueueLength(queueLength),
m_pVDecoderThread(0),
m_pADecoderThread(0),
m_PF(NO_PIXELFORMAT),
m_bAudioEOF(false),
m_bVideoEOF(false),
m_bSeekPending(false),
m_Volume(1.0),
m_LastVideoFrameTime(-1),
m_LastAudioFrameTime(-1)
{
ObjectCounter::get()->incRef(&typeid(*this));
}
AsyncVideoDecoder::~AsyncVideoDecoder()
{
if (m_pVDecoderThread || m_pADecoderThread) {
close();
}
ObjectCounter::get()->decRef(&typeid(*this));
}
void AsyncVideoDecoder::open(const std::string& sFilename, bool bThreadedDemuxer)
{
m_bAudioEOF = false;
m_bVideoEOF = false;
m_bSeekPending = false;
m_sFilename = sFilename;
m_pSyncDecoder->open(m_sFilename, bThreadedDemuxer);
m_VideoInfo = m_pSyncDecoder->getVideoInfo();
// Temporary pf - always assumes shaders will be available.
m_PF = m_pSyncDecoder->getPixelFormat();
m_State = OPENED;
}
void AsyncVideoDecoder::startDecoding(bool bDeliverYCbCr, const AudioParams* pAP)
{
AVG_ASSERT(m_State == OPENED);
m_pSyncDecoder->startDecoding(bDeliverYCbCr, pAP);
m_VideoInfo = m_pSyncDecoder->getVideoInfo();
if (m_VideoInfo.m_bHasVideo) {
m_LastVideoFrameTime = -1;
m_PF = m_pSyncDecoder->getPixelFormat();
m_pVCmdQ = VideoDecoderThread::CQueuePtr(new VideoDecoderThread::CQueue);
m_pVMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(m_QueueLength));
m_pVDecoderThread = new boost::thread(
VideoDecoderThread(*m_pVCmdQ, *m_pVMsgQ, m_pSyncDecoder));
}
if (m_VideoInfo.m_bHasAudio) {
m_pACmdQ = AudioDecoderThread::CQueuePtr(new AudioDecoderThread::CQueue);
m_pAMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8));
m_pSyncDecoder->setVolume(m_Volume);
m_pADecoderThread = new boost::thread(
AudioDecoderThread(*m_pACmdQ, *m_pAMsgQ, m_pSyncDecoder, *pAP));
m_AudioMsgData = 0;
m_AudioMsgSize = 0;
m_LastAudioFrameTime = 0;
}
m_State = DECODING;
}
void AsyncVideoDecoder::close()
{
AVG_ASSERT(m_State != CLOSED);
if (m_pVDecoderThread) {
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::stop, _1));
getNextBmps(false); // If the Queue is full, this breaks the lock in the thread.
m_pVDecoderThread->join();
delete m_pVDecoderThread;
m_pVDecoderThread = 0;
m_pVMsgQ = VideoMsgQueuePtr();
}
{
scoped_lock lock1(m_AudioMutex);
if (m_pADecoderThread) {
m_pACmdQ->pushCmd(boost::bind(&AudioDecoderThread::stop, _1));
m_pAMsgQ->pop(false);
m_pAMsgQ->pop(false);
m_pADecoderThread->join();
delete m_pADecoderThread;
m_pADecoderThread = 0;
m_pAMsgQ = VideoMsgQueuePtr();
}
m_pSyncDecoder->close();
}
}
IVideoDecoder::DecoderState AsyncVideoDecoder::getState() const
{
return m_State;
}
VideoInfo AsyncVideoDecoder::getVideoInfo() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo;
}
void AsyncVideoDecoder::seek(double destTime)
{
AVG_ASSERT(m_State == DECODING);
waitForSeekDone();
scoped_lock lock1(m_AudioMutex);
scoped_lock Lock2(m_SeekMutex);
m_bAudioEOF = false;
m_bVideoEOF = false;
m_bSeekPending = false;
m_LastVideoFrameTime = -1;
m_bSeekPending = true;
if (m_pVCmdQ) {
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::seek, _1, destTime));
} else {
m_pACmdQ->pushCmd(boost::bind(&AudioDecoderThread::seek, _1, destTime));
}
bool bDone = false;
while (!bDone && m_bSeekPending) {
VideoMsgPtr pMsg;
if (m_pVCmdQ) {
pMsg = m_pVMsgQ->pop(false);
} else {
pMsg = m_pAMsgQ->pop(false);
}
if (pMsg) {
switch (pMsg->getType()) {
case VideoMsg::SEEK_DONE:
m_bSeekPending = false;
m_LastVideoFrameTime = pMsg->getSeekVideoFrameTime();
m_LastAudioFrameTime = pMsg->getSeekAudioFrameTime();
break;
case VideoMsg::FRAME:
returnFrame(pMsg);
break;
default:
break;
}
} else {
bDone = true;
}
}
}
void AsyncVideoDecoder::loop()
{
m_LastVideoFrameTime = -1;
m_bAudioEOF = false;
m_bVideoEOF = false;
}
IntPoint AsyncVideoDecoder::getSize() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo.m_Size;
}
int AsyncVideoDecoder::getCurFrame() const
{
AVG_ASSERT(m_State != CLOSED);
return int(getCurTime(SS_VIDEO)*m_VideoInfo.m_StreamFPS+0.5);
}
int AsyncVideoDecoder::getNumFramesQueued() const
{
AVG_ASSERT(m_State == DECODING);
return m_pVMsgQ->size();
}
double AsyncVideoDecoder::getCurTime(StreamSelect stream) const
{
AVG_ASSERT(m_State != CLOSED);
switch (stream) {
case SS_DEFAULT:
case SS_VIDEO:
AVG_ASSERT(m_VideoInfo.m_bHasVideo);
return m_LastVideoFrameTime;
break;
case SS_AUDIO:
AVG_ASSERT(m_VideoInfo.m_bHasAudio);
return m_LastAudioFrameTime;
break;
default:
AVG_ASSERT(false);
}
return -1;
}
double AsyncVideoDecoder::getNominalFPS() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo.m_StreamFPS;
}
double AsyncVideoDecoder::getFPS() const
{
AVG_ASSERT(m_State != CLOSED);
return m_VideoInfo.m_FPS;
}
void AsyncVideoDecoder::setFPS(double fps)
{
AVG_ASSERT(!m_pADecoderThread);
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::setFPS, _1, fps));
if (fps != 0) {
m_VideoInfo.m_FPS = fps;
}
}
double AsyncVideoDecoder::getVolume() const
{
AVG_ASSERT(m_State != CLOSED);
return m_Volume;
}
void AsyncVideoDecoder::setVolume(double volume)
{
m_Volume = volume;
if (m_State != CLOSED && m_VideoInfo.m_bHasAudio && m_pACmdQ) {
m_pACmdQ->pushCmd(boost::bind(&AudioDecoderThread::setVolume, _1, volume));
}
}
PixelFormat AsyncVideoDecoder::getPixelFormat() const
{
AVG_ASSERT(m_State != CLOSED);
return m_PF;
}
FrameAvailableCode AsyncVideoDecoder::renderToBmps(vector<BitmapPtr>& pBmps,
double timeWanted)
{
AVG_ASSERT(m_State == DECODING);
FrameAvailableCode frameAvailable;
VideoMsgPtr pFrameMsg = getBmpsForTime(timeWanted, frameAvailable);
if (frameAvailable == FA_NEW_FRAME) {
AVG_ASSERT(pFrameMsg);
for (unsigned i = 0; i < pBmps.size(); ++i) {
pBmps[i]->copyPixels(*(pFrameMsg->getFrameBitmap(i)));
}
returnFrame(pFrameMsg);
}
return frameAvailable;
}
bool AsyncVideoDecoder::isEOF(StreamSelect stream) const
{
AVG_ASSERT(m_State == DECODING);
switch(stream) {
case SS_AUDIO:
return (!m_VideoInfo.m_bHasAudio || m_bAudioEOF);
case SS_VIDEO:
return (!m_VideoInfo.m_bHasVideo || m_bVideoEOF);
case SS_ALL:
return isEOF(SS_VIDEO) && isEOF(SS_AUDIO);
default:
return false;
}
}
void AsyncVideoDecoder::throwAwayFrame(double timeWanted)
{
AVG_ASSERT(m_State == DECODING);
FrameAvailableCode frameAvailable;
VideoMsgPtr pFrameMsg = getBmpsForTime(timeWanted, frameAvailable);
}
int AsyncVideoDecoder::fillAudioBuffer(AudioBufferPtr pBuffer)
{
AVG_ASSERT(m_State == DECODING);
AVG_ASSERT (m_pADecoderThread);
if (m_bAudioEOF) {
return 0;
}
scoped_lock lock(m_AudioMutex);
waitForSeekDone();
unsigned char* pDest = (unsigned char *)(pBuffer->getData());
int bufferLeftToFill = pBuffer->getNumBytes();
VideoMsgPtr pMsg;
while (bufferLeftToFill > 0) {
while (m_AudioMsgSize > 0 && bufferLeftToFill > 0) {
int copyBytes = min(bufferLeftToFill, m_AudioMsgSize);
memcpy(pDest, m_AudioMsgData, copyBytes);
m_AudioMsgSize -= copyBytes;
m_AudioMsgData += copyBytes;
bufferLeftToFill -= copyBytes;
pDest += copyBytes;
m_LastAudioFrameTime += copyBytes /
(pBuffer->getFrameSize() * pBuffer->getRate());
}
if (bufferLeftToFill != 0) {
pMsg = m_pAMsgQ->pop(false);
if (pMsg) {
if (pMsg->getType() == VideoMsg::END_OF_FILE) {
m_bAudioEOF = true;
return pBuffer->getNumFrames()-bufferLeftToFill/
pBuffer->getFrameSize();
}
AVG_ASSERT(pMsg->getType() == VideoMsg::AUDIO);
m_AudioMsgSize = pMsg->getAudioBuffer()->getNumFrames()
*pBuffer->getFrameSize();
m_AudioMsgData = (unsigned char *)(pMsg->getAudioBuffer()->getData());
m_LastAudioFrameTime = pMsg->getAudioTime();
} else {
return pBuffer->getNumFrames()-bufferLeftToFill/pBuffer->getFrameSize();
}
}
}
return pBuffer->getNumFrames();
}
VideoMsgPtr AsyncVideoDecoder::getBmpsForTime(double timeWanted,
FrameAvailableCode& frameAvailable)
{
if (timeWanted < 0 && timeWanted != -1) {
cerr << "Illegal timeWanted: " << timeWanted << endl;
AVG_ASSERT(false);
}
// XXX: This code is sort-of duplicated in FFMpegDecoder::readFrameForTime()
double frameTime = -1;
VideoMsgPtr pFrameMsg;
if (timeWanted == -1) {
pFrameMsg = getNextBmps(true);
frameAvailable = FA_NEW_FRAME;
} else {
double timePerFrame = 1.0/getFPS();
if (fabs(double(timeWanted-m_LastVideoFrameTime)) < 0.5*timePerFrame ||
m_LastVideoFrameTime > timeWanted+timePerFrame) {
// The last frame is still current. Display it again.
frameAvailable = FA_USE_LAST_FRAME;
return VideoMsgPtr();
} else {
if (m_bVideoEOF) {
frameAvailable = FA_USE_LAST_FRAME;
return VideoMsgPtr();
}
while (frameTime-timeWanted < -0.5*timePerFrame && !m_bVideoEOF) {
returnFrame(pFrameMsg);
pFrameMsg = getNextBmps(false);
if (pFrameMsg) {
frameTime = pFrameMsg->getFrameTime();
} else {
frameAvailable = FA_STILL_DECODING;
return VideoMsgPtr();
}
}
if (!pFrameMsg) {
cerr << "frameTime=" << frameTime << ", timeWanted=" << timeWanted
<< ", timePerFrame=" << timePerFrame << ", m_bVideoEOF="
<< m_bVideoEOF << endl;
AVG_ASSERT(false);
}
frameAvailable = FA_NEW_FRAME;
}
}
if (pFrameMsg) {
m_LastVideoFrameTime = pFrameMsg->getFrameTime();
}
return pFrameMsg;
}
VideoMsgPtr AsyncVideoDecoder::getNextBmps(bool bWait)
{
waitForSeekDone();
VideoMsgPtr pMsg = m_pVMsgQ->pop(bWait);
if (pMsg) {
switch (pMsg->getType()) {
case VideoMsg::FRAME:
return pMsg;
case VideoMsg::END_OF_FILE:
m_bVideoEOF = true;
return VideoMsgPtr();
case VideoMsg::ERROR:
m_bVideoEOF = true;
return VideoMsgPtr();
default:
// Unhandled message type.
AVG_ASSERT(false);
return VideoMsgPtr();
}
} else {
return pMsg;
}
}
void AsyncVideoDecoder::waitForSeekDone()
{
scoped_lock lock(m_SeekMutex);
if (m_bSeekPending) {
do {
VideoMsgPtr pMsg;
if (m_pVCmdQ) {
pMsg = m_pVMsgQ->pop(true);
} else {
pMsg = m_pAMsgQ->pop(true);
}
switch (pMsg->getType()) {
case VideoMsg::SEEK_DONE:
m_bSeekPending = false;
m_LastVideoFrameTime = pMsg->getSeekVideoFrameTime();
m_LastAudioFrameTime = pMsg->getSeekAudioFrameTime();
break;
case VideoMsg::FRAME:
returnFrame(pMsg);
break;
default:
// TODO: Handle ERROR messages here.
break;
}
} while (m_bSeekPending);
}
}
void AsyncVideoDecoder::returnFrame(VideoMsgPtr& pFrameMsg)
{
if (pFrameMsg) {
m_pVCmdQ->pushCmd(boost::bind(&VideoDecoderThread::returnFrame, _1, pFrameMsg));
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: metafunctions.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2007-07-05 08:54:06 $
*
* 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 INCLUDED_BASEBMP_METAFUNCTIONS_HXX
#define INCLUDED_BASEBMP_METAFUNCTIONS_HXX
#include <boost/mpl/integral_c.hpp>
#include <vigra/metaprogramming.hxx>
#include <vigra/numerictraits.hxx>
namespace basebmp
{
// TODO(Q3): move to generic place (o3tl?)
/** template meta function: add const qualifier to 2nd type, if given
1st type has it
*/
template<typename A, typename B> struct clone_const
{
typedef B type;
};
template<typename A, typename B> struct clone_const<const A,B>
{
typedef const B type;
};
/** template meta function: add const qualifier to plain type (if not
already there)
*/
template <typename T> struct add_const
{
typedef const T type;
};
template <typename T> struct add_const<const T>
{
typedef const T type;
};
/// template meta function: remove const qualifier from plain type
template <typename T> struct remove_const
{
typedef T type;
};
template <typename T> struct remove_const<const T>
{
typedef T type;
};
//--------------------------------------------------------------
/// Base class for an adaptable ternary functor
template< typename A1, typename A2, typename A3, typename R > struct TernaryFunctorBase
{
typedef A1 first_argument_type;
typedef A2 second_argument_type;
typedef A3 third_argument_type;
typedef R result_type;
};
//--------------------------------------------------------------
/** template meta function: ensure that given integer type is unsigned
If given integer type is already unsigned, return as-is -
otherwise, convert to unsigned type of same or greater range.
*/
template< typename T > struct make_unsigned;
#define BASEBMP_MAKE_UNSIGNED(T,U) \
template<> struct make_unsigned<T> { \
typedef U type; \
};
BASEBMP_MAKE_UNSIGNED(signed char,unsigned char)
BASEBMP_MAKE_UNSIGNED(unsigned char,unsigned char)
BASEBMP_MAKE_UNSIGNED(short,unsigned short)
BASEBMP_MAKE_UNSIGNED(unsigned short,unsigned short)
BASEBMP_MAKE_UNSIGNED(int,unsigned int)
BASEBMP_MAKE_UNSIGNED(unsigned int,unsigned int)
BASEBMP_MAKE_UNSIGNED(long,unsigned long)
BASEBMP_MAKE_UNSIGNED(unsigned long,unsigned long)
#undef BASEBMP_MAKE_UNSIGNED
/// cast integer to unsigned type of similar size
template< typename T > inline typename make_unsigned<T>::type unsigned_cast( T value )
{
return static_cast< typename make_unsigned<T>::type >(value);
}
//--------------------------------------------------------------
/// returns true, if given number is strictly less than 0
template< typename T > inline bool is_negative( T x )
{
return x < 0;
}
/// Overload for ints (branch-free)
inline bool is_negative( int x )
{
// force logic shift (result for signed shift right is undefined)
return static_cast<unsigned int>(x) >> (sizeof(int)*8-1);
}
//--------------------------------------------------------------
/// Results in VigraTrueType, if T is of integer type and scalar
template< typename T, typename trueCase, typename falseCase >
struct ifScalarIntegral
{
typedef
typename vigra::If<
typename vigra::NumericTraits< T >::isIntegral,
typename vigra::If<
typename vigra::NumericTraits< T >::isScalar,
trueCase,
falseCase >::type,
falseCase >::type type;
};
/// Results in VigraTrueType, if T is of non-integer type and scalar
template< typename T, typename trueCase, typename falseCase >
struct ifScalarNonIntegral
{
typedef
typename vigra::If<
typename vigra::NumericTraits< T >::isIntegral,
falseCase,
typename vigra::If<
typename vigra::NumericTraits< T >::isScalar,
trueCase,
falseCase >::type >::type type;
};
/// Results in VigraTrueType, if both T1 and T2 are of integer type and scalar
template< typename T1, typename T2, typename trueCase, typename falseCase >
struct ifBothScalarIntegral
{
typedef
typename ifScalarIntegral<
T1,
typename ifScalarIntegral<
T2,
trueCase,
falseCase >::type,
falseCase >::type type;
};
//--------------------------------------------------------------
/// Count number of trailing zeros
template< unsigned int val > struct numberOfTrailingZeros
{
enum { next = val >> 1 };
enum { value = vigra::IfBool< (val & 1) == 0,
numberOfTrailingZeros<next>,
boost::mpl::integral_c< int,-1 > > ::type::value + 1 };
};
template<> struct numberOfTrailingZeros<0>
{
enum { value = 0 };
};
//--------------------------------------------------------------
/// Count number of one bits
template< unsigned int val > struct bitcount
{
enum { next = val >> 1 };
enum { value = bitcount<next>::value + (val & 1) };
};
template<> struct bitcount<0>
{
enum { value = 0 };
};
//--------------------------------------------------------------
/// Shift left for positive shift value, and right otherwise
template< typename T > inline T shiftLeft( T v, int shift )
{
return shift > 0 ? v << shift : v >> (-shift);
}
/// Shift right for positive shift value, and left otherwise
template< typename T > inline T shiftRight( T v, int shift )
{
return shift > 0 ? v >> shift : v << (-shift);
}
} // namespace basebmp
#endif /* INCLUDED_BASEBMP_METAFUNCTIONS_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.8.24); FILE MERGED 2008/03/31 13:07:56 rt 1.8.24.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: metafunctions.hxx,v $
* $Revision: 1.9 $
*
* 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 INCLUDED_BASEBMP_METAFUNCTIONS_HXX
#define INCLUDED_BASEBMP_METAFUNCTIONS_HXX
#include <boost/mpl/integral_c.hpp>
#include <vigra/metaprogramming.hxx>
#include <vigra/numerictraits.hxx>
namespace basebmp
{
// TODO(Q3): move to generic place (o3tl?)
/** template meta function: add const qualifier to 2nd type, if given
1st type has it
*/
template<typename A, typename B> struct clone_const
{
typedef B type;
};
template<typename A, typename B> struct clone_const<const A,B>
{
typedef const B type;
};
/** template meta function: add const qualifier to plain type (if not
already there)
*/
template <typename T> struct add_const
{
typedef const T type;
};
template <typename T> struct add_const<const T>
{
typedef const T type;
};
/// template meta function: remove const qualifier from plain type
template <typename T> struct remove_const
{
typedef T type;
};
template <typename T> struct remove_const<const T>
{
typedef T type;
};
//--------------------------------------------------------------
/// Base class for an adaptable ternary functor
template< typename A1, typename A2, typename A3, typename R > struct TernaryFunctorBase
{
typedef A1 first_argument_type;
typedef A2 second_argument_type;
typedef A3 third_argument_type;
typedef R result_type;
};
//--------------------------------------------------------------
/** template meta function: ensure that given integer type is unsigned
If given integer type is already unsigned, return as-is -
otherwise, convert to unsigned type of same or greater range.
*/
template< typename T > struct make_unsigned;
#define BASEBMP_MAKE_UNSIGNED(T,U) \
template<> struct make_unsigned<T> { \
typedef U type; \
};
BASEBMP_MAKE_UNSIGNED(signed char,unsigned char)
BASEBMP_MAKE_UNSIGNED(unsigned char,unsigned char)
BASEBMP_MAKE_UNSIGNED(short,unsigned short)
BASEBMP_MAKE_UNSIGNED(unsigned short,unsigned short)
BASEBMP_MAKE_UNSIGNED(int,unsigned int)
BASEBMP_MAKE_UNSIGNED(unsigned int,unsigned int)
BASEBMP_MAKE_UNSIGNED(long,unsigned long)
BASEBMP_MAKE_UNSIGNED(unsigned long,unsigned long)
#undef BASEBMP_MAKE_UNSIGNED
/// cast integer to unsigned type of similar size
template< typename T > inline typename make_unsigned<T>::type unsigned_cast( T value )
{
return static_cast< typename make_unsigned<T>::type >(value);
}
//--------------------------------------------------------------
/// returns true, if given number is strictly less than 0
template< typename T > inline bool is_negative( T x )
{
return x < 0;
}
/// Overload for ints (branch-free)
inline bool is_negative( int x )
{
// force logic shift (result for signed shift right is undefined)
return static_cast<unsigned int>(x) >> (sizeof(int)*8-1);
}
//--------------------------------------------------------------
/// Results in VigraTrueType, if T is of integer type and scalar
template< typename T, typename trueCase, typename falseCase >
struct ifScalarIntegral
{
typedef
typename vigra::If<
typename vigra::NumericTraits< T >::isIntegral,
typename vigra::If<
typename vigra::NumericTraits< T >::isScalar,
trueCase,
falseCase >::type,
falseCase >::type type;
};
/// Results in VigraTrueType, if T is of non-integer type and scalar
template< typename T, typename trueCase, typename falseCase >
struct ifScalarNonIntegral
{
typedef
typename vigra::If<
typename vigra::NumericTraits< T >::isIntegral,
falseCase,
typename vigra::If<
typename vigra::NumericTraits< T >::isScalar,
trueCase,
falseCase >::type >::type type;
};
/// Results in VigraTrueType, if both T1 and T2 are of integer type and scalar
template< typename T1, typename T2, typename trueCase, typename falseCase >
struct ifBothScalarIntegral
{
typedef
typename ifScalarIntegral<
T1,
typename ifScalarIntegral<
T2,
trueCase,
falseCase >::type,
falseCase >::type type;
};
//--------------------------------------------------------------
/// Count number of trailing zeros
template< unsigned int val > struct numberOfTrailingZeros
{
enum { next = val >> 1 };
enum { value = vigra::IfBool< (val & 1) == 0,
numberOfTrailingZeros<next>,
boost::mpl::integral_c< int,-1 > > ::type::value + 1 };
};
template<> struct numberOfTrailingZeros<0>
{
enum { value = 0 };
};
//--------------------------------------------------------------
/// Count number of one bits
template< unsigned int val > struct bitcount
{
enum { next = val >> 1 };
enum { value = bitcount<next>::value + (val & 1) };
};
template<> struct bitcount<0>
{
enum { value = 0 };
};
//--------------------------------------------------------------
/// Shift left for positive shift value, and right otherwise
template< typename T > inline T shiftLeft( T v, int shift )
{
return shift > 0 ? v << shift : v >> (-shift);
}
/// Shift right for positive shift value, and left otherwise
template< typename T > inline T shiftRight( T v, int shift )
{
return shift > 0 ? v >> shift : v << (-shift);
}
} // namespace basebmp
#endif /* INCLUDED_BASEBMP_METAFUNCTIONS_HXX */
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "Reader.h"
//// SEEE http://www.zlib.net/zlib_how.html
/// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object
/// where inner loop is done each time through with a CHUNK
#if qHasFeature_ZLib
#include <zlib.h>
#if defined (_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment (lib, "zlib.lib")
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::DataExchange::Compression;
using namespace Stroika::Foundation::Streams;
namespace {
void ThrowIfZLibErr_ (int err)
{
if (err != Z_OK) {
Execution::Throw (Execution::StringException (L"ZLIB ERR")); // @todo embelish
}
}
using Memory::Byte;
struct MyCompressionStream_ : InputStream<Byte> {
struct BaseRep_ : public _IRep {
Streams::InputStream<Memory::Byte> fInStream_;
z_stream strm;
BaseRep_ (const Streams::InputStream<Memory::Byte>& in)
: fInStream_ (in)
, strm {}
{
}
virtual ~BaseRep_ () = default;
virtual bool IsSeekable () const
{
// for now - KISS
return false; // SHOULD allow seekable IFF src is seekable
}
virtual SeekOffsetType GetReadOffset () const override
{
return SeekOffsetType {};
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
RequireNotReached ();
return SeekOffsetType {};
}
};
struct DeflateRep_ : BaseRep_ {
DeflateRep_ (const Streams::InputStream<Memory::Byte>& in)
: BaseRep_ (in)
{
int level = 1;
ThrowIfZLibErr_ (::deflateInit (&strm, level));
}
virtual ~DeflateRep_ ()
{
Verify (::deflateEnd (&strm) == Z_OK);
}
virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override
{
// @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data
//tmphack - do 1 byte at a time
Require (intoStart < intoEnd);
Byte b[1];
size_t n = fInStream_.Read (&b[0], &b[1]);
if (n == 0) {
return 0;
}
Assert (n == 1);
strm.next_in = b;
strm.avail_in = n;
strm.avail_out = intoEnd - intoStart;
strm.next_out = intoStart;
ThrowIfZLibErr_ (::deflate (&strm, Z_NO_FLUSH));
Assert (static_cast<ptrdiff_t> (strm.avail_out) < intoEnd - intoStart);
return strm.avail_out;
}
};
struct InflateRep_ : BaseRep_ {
InflateRep_ (const Streams::InputStream<Memory::Byte>& in)
: BaseRep_ (in)
{
ThrowIfZLibErr_ (::inflateInit (&strm));
}
virtual ~InflateRep_ ()
{
Verify (::inflateEnd (&strm) == Z_OK);
}
virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override
{
// @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data
//tmphack - do 1 byte at a time
Require (intoStart < intoEnd);
Byte b[1];
size_t n = fInStream_.Read (&b[0], &b[1]);
if (n == 0) {
return 0;
}
Assert (n == 1);
strm.next_in = b;
strm.avail_in = n;
strm.avail_out = intoEnd - intoStart;
strm.next_out = intoStart;
ThrowIfZLibErr_ (::inflate (&strm, Z_NO_FLUSH));
Assert (static_cast<ptrdiff_t> (strm.avail_out) < intoEnd - intoStart);
return strm.avail_out;
}
};
enum Compression {eCompression};
enum DeCompression {eDeCompression};
MyCompressionStream_ (Compression, const Streams::InputStream<Memory::Byte>& in)
: InputStream<Byte> (make_shared<DeflateRep_> (in))
{
}
MyCompressionStream_ (DeCompression, const Streams::InputStream<Memory::Byte>& in)
: InputStream<Byte> (make_shared<InflateRep_> (in))/// tmphack cuz NYI otjer
{
}
};
}
#endif
#if qHasFeature_ZLib
class Zip::Reader::Rep_ : public Reader::_IRep {
public:
Rep_ () = default;
~Rep_ () = default;
virtual InputStream<Byte> Compress (const InputStream<Byte>& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eCompression, src);
}
virtual InputStream<Byte> Decompress (const InputStream<Byte>& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src);
}
};
Zip::Reader::Reader ()
: DataExchange::Compression::Reader (make_shared<Rep_> ())
{
}
#endif
<commit_msg>testable version of Zip::Reader<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "Reader.h"
//// SEEE http://www.zlib.net/zlib_how.html
/// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object
/// where inner loop is done each time through with a CHUNK
#if qHasFeature_ZLib
#include <zlib.h>
#if defined (_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment (lib, "zlib.lib")
#endif
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::DataExchange::Compression;
using namespace Stroika::Foundation::Streams;
namespace {
void ThrowIfZLibErr_ (int err)
{
if (err != Z_OK) {
Execution::Throw (Execution::StringException (L"ZLIB ERR")); // @todo embelish
}
}
using Memory::Byte;
struct MyCompressionStream_ : InputStream<Byte> {
struct BaseRep_ : public _IRep {
static constexpr size_t CHUNK = 16384;
Streams::InputStream<Memory::Byte> fInStream_;
z_stream fZStream_;
Byte fInBuf_[CHUNK];
BaseRep_ (const Streams::InputStream<Memory::Byte>& in)
: fInStream_ (in)
, fZStream_ {}
{
}
virtual ~BaseRep_ () = default;
virtual bool IsSeekable () const
{
// for now - KISS
return false; // SHOULD allow seekable IFF src is seekable
}
virtual SeekOffsetType GetReadOffset () const override
{
return SeekOffsetType {};
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
RequireNotReached ();
return SeekOffsetType {};
}
void _AssureInputAvailable ()
{
if (fZStream_.avail_in == 0) {
fZStream_.avail_in = fInStream_.Read (begin (fInBuf_), end (fInBuf_));
fZStream_.next_in = begin (fInBuf_);
}
}
};
struct DeflateRep_ : BaseRep_ {
DeflateRep_ (const Streams::InputStream<Memory::Byte>& in)
: BaseRep_ (in)
{
int level = Z_DEFAULT_COMPRESSION;
ThrowIfZLibErr_ (::deflateInit (&fZStream_, level));
}
virtual ~DeflateRep_ ()
{
Verify (::deflateEnd (&fZStream_) == Z_OK);
}
virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override
{
_AssureInputAvailable ();
// @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data
//tmphack - do 1 byte at a time
Require (intoStart < intoEnd);
fZStream_.avail_out = intoEnd - intoStart;
fZStream_.next_out = intoStart;
ThrowIfZLibErr_ (::deflate (&fZStream_, Z_NO_FLUSH));
ptrdiff_t have = CHUNK - fZStream_.avail_out;
Assert (have < intoEnd - intoStart);
return have;
}
};
struct InflateRep_ : BaseRep_ {
InflateRep_ (const Streams::InputStream<Memory::Byte>& in)
: BaseRep_ (in)
{
ThrowIfZLibErr_ (::inflateInit (&fZStream_));
}
virtual ~InflateRep_ ()
{
Verify (::inflateEnd (&fZStream_) == Z_OK);
}
virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override
{
_AssureInputAvailable ();
// @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data
//tmphack - do 1 byte at a time
Require (intoStart < intoEnd);
fZStream_.avail_out = intoEnd - intoStart;
fZStream_.next_out = intoStart;
ThrowIfZLibErr_ (::inflate (&fZStream_, Z_NO_FLUSH));
ptrdiff_t have = CHUNK - fZStream_.avail_out;
Assert (have < intoEnd - intoStart);
return have;
}
};
enum Compression {eCompression};
enum DeCompression {eDeCompression};
MyCompressionStream_ (Compression, const Streams::InputStream<Memory::Byte>& in)
: InputStream<Byte> (make_shared<DeflateRep_> (in))
{
}
MyCompressionStream_ (DeCompression, const Streams::InputStream<Memory::Byte>& in)
: InputStream<Byte> (make_shared<InflateRep_> (in))/// tmphack cuz NYI otjer
{
}
};
}
#endif
#if qHasFeature_ZLib
class Zip::Reader::Rep_ : public Reader::_IRep {
public:
virtual InputStream<Byte> Compress (const InputStream<Byte>& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eCompression, src);
}
virtual InputStream<Byte> Decompress (const InputStream<Byte>& src) const override
{
return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src);
}
};
Zip::Reader::Reader ()
: DataExchange::Compression::Reader (make_shared<Rep_> ())
{
}
#endif
<|endoftext|> |
<commit_before>AliAnalysisTaskMuonHadronCorrelations *AddAnalysisTaskMuonHadronCorrelations(const char *centMethod = "V0M") {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
printf("Error in adding AnalysisTaskMuonHadronCorrelations: no Analysis Manager found!\n");
return NULL;
}
AliAnalysisTaskMuonHadronCorrelations *task = new AliAnalysisTaskMuonHadronCorrelations("AliAnalysisTaskMuonHadronCorrelations");
// Set analysis cuts
task->SetFilterBitCentralBarrel(7); // -> 128
task->SetMaxEtaCentralBarrel(1.0);
task->SetTriggerMatchLevelMuon(1);
const Int_t nBinCent = 4;
Double_t centLimits[nBinCent+1] = {0., 20., 40, 60., 100.};
task->SetCentBinning(nBinCent, centLimits);
task->SetCentMethod(centMethod);
const Int_t nBinPt = 3;
Double_t ptLimits[nBinPt+1] = {0., 1., 2., 4.};
task->SetPtBinning(nBinPt, ptLimits);
mgr->AddTask(task);
// create output container
AliAnalysisDataContainer *output = mgr->CreateContainer("MuonHadronCorrHistos", TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s:MuonHadronCorrelations_%s", AliAnalysisManager::GetCommonFileName(), centMethod));
// finaly connect input and output
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<commit_msg>Add centrality estimator to task name.<commit_after>AliAnalysisTaskMuonHadronCorrelations *AddAnalysisTaskMuonHadronCorrelations(const char *centMethod = "V0M") {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
printf("Error in adding AnalysisTaskMuonHadronCorrelations: no Analysis Manager found!\n");
return NULL;
}
AliAnalysisTaskMuonHadronCorrelations *task = new AliAnalysisTaskMuonHadronCorrelations(Form("AliAnalysisTaskMuonHadronCorrelations_%s",centMethod));
// Set analysis cuts
task->SetFilterBitCentralBarrel(7); // -> 128
task->SetMaxEtaCentralBarrel(1.0);
task->SetTriggerMatchLevelMuon(1);
const Int_t nBinCent = 4;
Double_t centLimits[nBinCent+1] = {0., 20., 40, 60., 100.};
task->SetCentBinning(nBinCent, centLimits);
task->SetCentMethod(centMethod);
const Int_t nBinPt = 3;
Double_t ptLimits[nBinPt+1] = {0., 1., 2., 4.};
task->SetPtBinning(nBinPt, ptLimits);
mgr->AddTask(task);
// create output container
AliAnalysisDataContainer *output = mgr->CreateContainer("MuonHadronCorrHistos", TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s:MuonHadronCorrelations_%s", AliAnalysisManager::GetCommonFileName(), centMethod));
// finaly connect input and output
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<|endoftext|> |
<commit_before>/**
* @file pooling_layer.hpp
* @author Marcus Edel
*
* Definition of the PoolingLayer class, which attaches various pooling
* functions to the embedding layer.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_POOLING_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_POOLING_LAYER_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/pooling_rules/mean_pooling.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the pooling layer. The pooling layer works as a metaclass
* which attaches various functions to the embedding layer.
*
* @tparam PoolingRule Pooling function used for the embedding layer.
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename PoolingRule = MeanPooling,
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
class PoolingLayer
{
public:
/**
* Create the PoolingLayer object using the specified number of units.
*
* @param kSize Size of the pooling window.
* @param pooling The pooling strategy.
*/
PoolingLayer(const size_t kSize, PoolingRule pooling = PoolingRule()) :
kSize(kSize), pooling(pooling)
{
// Nothing to do here.
}
PoolingLayer(PoolingLayer &&layer) noexcept
{
*this = std::move(layer);
}
PoolingLayer& operator=(PoolingLayer &&layer) noexcept
{
kSize = layer.kSize;
delta.swap(layer.delta);
inputParameter.swap(layer.inputParameter);
outputParameter.swap(layer.outputParameter);
pooling = std::move(layer.pooling);
return *this;
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
Pooling(input, output);
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
output = arma::zeros<arma::Cube<eT> >(input.n_rows / kSize,
input.n_cols / kSize, input.n_slices);
for (size_t s = 0; s < input.n_slices; s++)
Pooling(input.slice(s), output.slice(s));
}
/**
* Ordinary feed backward pass of a neural network, using 3rd-order tensors as
* input, calculating the function f(x) by propagating x backwards through f.
* Using the results from the feed forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Cube<eT>& /* unused */,
const arma::Cube<eT>& gy,
arma::Cube<eT>& g)
{
g = arma::zeros<arma::Cube<eT> >(inputParameter.n_rows,
inputParameter.n_cols, inputParameter.n_slices);
for (size_t s = 0; s < gy.n_slices; s++)
{
Unpooling(inputParameter.slice(s), gy.slice(s), g.slice(s));
}
}
/**
* Ordinary feed backward pass of a neural network, using 3rd-order tensors as
* input, calculating the function f(x) by propagating x backwards through f.
* Using the results from the feed forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Cube<eT>& /* unused */,
const arma::Mat<eT>& gy,
arma::Cube<eT>& g)
{
// Generate a cube from the error matrix.
arma::Cube<eT> mappedError = arma::zeros<arma::cube>(outputParameter.n_rows,
outputParameter.n_cols, outputParameter.n_slices);
for (size_t s = 0, j = 0; s < mappedError.n_slices; s+= gy.n_cols, j++)
{
for (size_t i = 0; i < gy.n_cols; i++)
{
arma::Col<eT> temp = gy.col(i).subvec(
j * outputParameter.n_rows * outputParameter.n_cols,
(j + 1) * outputParameter.n_rows * outputParameter.n_cols - 1);
mappedError.slice(s + i) = arma::Mat<eT>(temp.memptr(),
outputParameter.n_rows, outputParameter.n_cols);
}
}
Backward(inputParameter, mappedError, g);
}
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
InputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
InputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
private:
/**
* Apply pooling to the input and store the results.
*
* @param input The input to be apply the pooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Pooling(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
const size_t rStep = kSize;
const size_t cStep = kSize;
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
output(i / rStep, j / cStep) += pooling.Pooling(
input(arma::span(i, i + rStep - 1), arma::span(j, j + cStep - 1)));
}
}
}
/**
* Apply unpooling to the input and store the results.
*
* @param input The input to be apply the unpooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Unpooling(const arma::Mat<eT>& input,
const arma::Mat<eT>& error,
arma::Mat<eT>& output)
{
const size_t rStep = input.n_rows / error.n_rows;
const size_t cStep = input.n_cols / error.n_cols;
arma::Mat<eT> unpooledError;
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
const arma::Mat<eT>& inputArea = input(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1));
pooling.Unpooling(inputArea, error(i / rStep, j / cStep),
unpooledError);
output(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1)) += unpooledError;
}
}
}
//! Locally-stored size of the pooling window.
size_t kSize;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored pooling strategy.
PoolingRule pooling;
}; // class PoolingLayer
//! Layer traits for the pooling layer.
template<
typename PoolingRule,
typename InputDataType,
typename OutputDataType
>
class LayerTraits<PoolingLayer<PoolingRule, InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
} // namespace ann
} // namespace mlpack
#endif
<commit_msg>implement serialize<commit_after>/**
* @file pooling_layer.hpp
* @author Marcus Edel
*
* Definition of the PoolingLayer class, which attaches various pooling
* functions to the embedding layer.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_POOLING_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_POOLING_LAYER_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/pooling_rules/mean_pooling.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the pooling layer. The pooling layer works as a metaclass
* which attaches various functions to the embedding layer.
*
* @tparam PoolingRule Pooling function used for the embedding layer.
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename PoolingRule = MeanPooling,
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
class PoolingLayer
{
public:
/**
* Create the PoolingLayer object using the specified number of units.
*
* @param kSize Size of the pooling window.
* @param pooling The pooling strategy.
*/
PoolingLayer(const size_t kSize, PoolingRule pooling = PoolingRule()) :
kSize(kSize), pooling(pooling)
{
// Nothing to do here.
}
PoolingLayer(PoolingLayer &&layer) noexcept
{
*this = std::move(layer);
}
PoolingLayer& operator=(PoolingLayer &&layer) noexcept
{
kSize = layer.kSize;
delta.swap(layer.delta);
inputParameter.swap(layer.inputParameter);
outputParameter.swap(layer.outputParameter);
pooling = std::move(layer.pooling);
return *this;
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
Pooling(input, output);
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
output = arma::zeros<arma::Cube<eT> >(input.n_rows / kSize,
input.n_cols / kSize, input.n_slices);
for (size_t s = 0; s < input.n_slices; s++)
Pooling(input.slice(s), output.slice(s));
}
/**
* Ordinary feed backward pass of a neural network, using 3rd-order tensors as
* input, calculating the function f(x) by propagating x backwards through f.
* Using the results from the feed forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Cube<eT>& /* unused */,
const arma::Cube<eT>& gy,
arma::Cube<eT>& g)
{
g = arma::zeros<arma::Cube<eT> >(inputParameter.n_rows,
inputParameter.n_cols, inputParameter.n_slices);
for (size_t s = 0; s < gy.n_slices; s++)
{
Unpooling(inputParameter.slice(s), gy.slice(s), g.slice(s));
}
}
/**
* Ordinary feed backward pass of a neural network, using 3rd-order tensors as
* input, calculating the function f(x) by propagating x backwards through f.
* Using the results from the feed forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Cube<eT>& /* unused */,
const arma::Mat<eT>& gy,
arma::Cube<eT>& g)
{
// Generate a cube from the error matrix.
arma::Cube<eT> mappedError = arma::zeros<arma::cube>(outputParameter.n_rows,
outputParameter.n_cols, outputParameter.n_slices);
for (size_t s = 0, j = 0; s < mappedError.n_slices; s+= gy.n_cols, j++)
{
for (size_t i = 0; i < gy.n_cols; i++)
{
arma::Col<eT> temp = gy.col(i).subvec(
j * outputParameter.n_rows * outputParameter.n_cols,
(j + 1) * outputParameter.n_rows * outputParameter.n_cols - 1);
mappedError.slice(s + i) = arma::Mat<eT>(temp.memptr(),
outputParameter.n_rows, outputParameter.n_cols);
}
}
Backward(inputParameter, mappedError, g);
}
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
InputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
InputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
/**
* Serialize the layer
*/
template<typename Archive>
void Serialize(Archive& ar, const unsigned int /* version */)
{
}
private:
/**
* Apply pooling to the input and store the results.
*
* @param input The input to be apply the pooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Pooling(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
const size_t rStep = kSize;
const size_t cStep = kSize;
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
output(i / rStep, j / cStep) += pooling.Pooling(
input(arma::span(i, i + rStep - 1), arma::span(j, j + cStep - 1)));
}
}
}
/**
* Apply unpooling to the input and store the results.
*
* @param input The input to be apply the unpooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Unpooling(const arma::Mat<eT>& input,
const arma::Mat<eT>& error,
arma::Mat<eT>& output)
{
const size_t rStep = input.n_rows / error.n_rows;
const size_t cStep = input.n_cols / error.n_cols;
arma::Mat<eT> unpooledError;
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
const arma::Mat<eT>& inputArea = input(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1));
pooling.Unpooling(inputArea, error(i / rStep, j / cStep),
unpooledError);
output(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1)) += unpooledError;
}
}
}
//! Locally-stored size of the pooling window.
size_t kSize;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored pooling strategy.
PoolingRule pooling;
}; // class PoolingLayer
//! Layer traits for the pooling layer.
template<
typename PoolingRule,
typename InputDataType,
typename OutputDataType
>
class LayerTraits<PoolingLayer<PoolingRule, InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
} // namespace ann
} // namespace mlpack
#endif
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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
#include <map>
#include <string>
#include <vector>
#include <utility>
#include <gtest/gtest.h>
#include <pficommon/lang/scoped_ptr.h>
#include "nearest_neighbor_base.hpp"
#include "nearest_neighbor_factory.hpp"
using namespace std;
using namespace jubatus::table;
using pfi::lang::scoped_ptr;
namespace jubatus {
namespace nearest_neighbor {
namespace {
// utility to write map<string, string> value in an expression
class make_config_type {
public:
make_config_type& operator()(const string& key, const string& value) {
config_.insert(make_pair(key, value));
return *this;
}
map<string, string> operator()() {
map<string, string> ret;
ret.swap(config_);
return ret;
}
private:
map<string, string> config_;
} make_config;
} // namespace
class nearest_neighbor_test
: public ::testing::TestWithParam<map<string, string> > {
protected:
void SetUp() {
map<string, string> param = GetParam();
string name = param["nearest_neighbor:name"];
param.erase("nearest_neighbor:name");
using pfi::text::json::json;
json config_js(new pfi::text::json::json_object);
for (map<string, string>::iterator it = param.begin(); it != param.end(); ++it)
config_js.add(it->first, json(new pfi::text::json::json_string(it->second)));
using jubatus::jsonconfig::config;
using pfi::text::json::json;
table_.reset(new column_table);
nn_.reset(create_nearest_neighbor(name, config(config_js, ""), table_.get(), "localhost"));
}
column_table* get_table() { return table_.get(); }
nearest_neighbor_base* get_nn() { return nn_.get(); }
private:
scoped_ptr<column_table> table_;
scoped_ptr<nearest_neighbor_base> nn_;
};
TEST_P(nearest_neighbor_test, type) {
map<string, string> param = GetParam();
const string name = param["nearest_neighbor:name"];
nearest_neighbor_base* nn = get_nn();
EXPECT_EQ(name, nn->type());
}
TEST_P(nearest_neighbor_test, empty_get_all_row_ids) {
nearest_neighbor_base* nn = get_nn();
vector<string> ids;
nn->get_all_row_ids(ids);
EXPECT_TRUE(ids.empty());
}
TEST_P(nearest_neighbor_test, get_all_row_ids) {
nearest_neighbor_base* nn = get_nn();
vector<string> expect;
expect.push_back("jubatus");
expect.push_back("kyun");
expect.push_back("hah hah");
for (int count = 0; count < 2; ++count) { // duplicated set_row
for (size_t i = 0; i < expect.size(); ++i) {
nn->set_row(expect[i], sfv_t());
}
}
vector<string> actual;
nn->get_all_row_ids(actual);
EXPECT_EQ(expect, actual);
}
TEST_P(nearest_neighbor_test, empty_neighbor_row) {
nearest_neighbor_base* nn = get_nn();
vector<pair<string, float> > ids;
nn->neighbor_row("", ids, 1);
EXPECT_TRUE(ids.empty());
nn->neighbor_row(sfv_t(), ids, 1);
EXPECT_TRUE(ids.empty());
}
// TODO: Write approximated test of neighbor_row().
const map<string, string> configs[] = {
make_config("nearest_neighbor:name", "lsh")("lsh:bitnum", "64")(),
make_config("nearest_neighbor:name", "minhash")("minhash:bitnum", "64")(),
make_config(
"nearest_neighbor:name",
"euclid_lsh")("euclid_lsh:hash_num", "64")()
};
INSTANTIATE_TEST_CASE_P(lsh_test,
nearest_neighbor_test,
::testing::ValuesIn(configs));
} // namespace nearest_neighbor
} // namespace jubatus
<commit_msg>Modified to pass test.<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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
#include <map>
#include <string>
#include <vector>
#include <utility>
#include <gtest/gtest.h>
#include <pficommon/lang/scoped_ptr.h>
#include <pficommon/lang/cast.h>
#include "nearest_neighbor_base.hpp"
#include "nearest_neighbor_factory.hpp"
#include "../common/jsonconfig.hpp"
using namespace std;
using namespace jubatus::table;
using pfi::lang::scoped_ptr;
namespace jubatus {
namespace nearest_neighbor {
namespace {
// utility to write map<string, string> value in an expression
class make_config_type {
public:
make_config_type& operator()(const string& key, const string& value) {
config_.insert(make_pair(key, value));
return *this;
}
map<string, string> operator()() {
map<string, string> ret;
ret.swap(config_);
return ret;
}
private:
map<string, string> config_;
} make_config;
} // namespace
class nearest_neighbor_test
: public ::testing::TestWithParam<map<string, string> > {
protected:
void SetUp() {
try {
map<string, string> param = GetParam();
string name = param["nearest_neighbor:name"];
param.erase("nearest_neighbor:name");
using pfi::text::json::json;
json config_js(new pfi::text::json::json_object);
for (map<string, string>::iterator it = param.begin(); it != param.end(); ++it)
config_js.add(it->first, json(new pfi::text::json::json_integer(pfi::lang::lexical_cast<int>(it->second))));
using jubatus::jsonconfig::config;
using pfi::text::json::json;
table_.reset(new column_table);
nn_.reset(create_nearest_neighbor(name, config(config_js, ""), table_.get(), "localhost"));
} catch (jubatus::jsonconfig::cast_check_error& e) {
std::cout << "In Setup():" <<e.what() << '\n';
std::vector<pfi::lang::shared_ptr<jubatus::jsonconfig::config_error> > v = e.errors();
for (size_t i = 0; i < v.size(); ++i) {
std::cout << v[i]->what() << '\n';
}
throw;
}
}
column_table* get_table() { return table_.get(); }
nearest_neighbor_base* get_nn() { return nn_.get(); }
private:
scoped_ptr<column_table> table_;
scoped_ptr<nearest_neighbor_base> nn_;
};
TEST_P(nearest_neighbor_test, type) {
map<string, string> param = GetParam();
const string name = param["nearest_neighbor:name"];
nearest_neighbor_base* nn = get_nn();
EXPECT_EQ(name, nn->type());
}
TEST_P(nearest_neighbor_test, empty_get_all_row_ids) {
nearest_neighbor_base* nn = get_nn();
vector<string> ids;
nn->get_all_row_ids(ids);
EXPECT_TRUE(ids.empty());
}
TEST_P(nearest_neighbor_test, get_all_row_ids) {
nearest_neighbor_base* nn = get_nn();
vector<string> expect;
expect.push_back("jubatus");
expect.push_back("kyun");
expect.push_back("hah hah");
for (int count = 0; count < 2; ++count) { // duplicated set_row
for (size_t i = 0; i < expect.size(); ++i) {
nn->set_row(expect[i], sfv_t());
}
}
vector<string> actual;
nn->get_all_row_ids(actual);
EXPECT_EQ(expect, actual);
}
TEST_P(nearest_neighbor_test, empty_neighbor_row) {
nearest_neighbor_base* nn = get_nn();
vector<pair<string, float> > ids;
nn->neighbor_row("", ids, 1);
EXPECT_TRUE(ids.empty());
nn->neighbor_row(sfv_t(), ids, 1);
EXPECT_TRUE(ids.empty());
}
// TODO: Write approximated test of neighbor_row().
const map<string, string> configs[] = {
make_config("nearest_neighbor:name", "lsh")("bitnum", "64")(),
make_config("nearest_neighbor:name", "minhash")("bitnum", "64")(),
make_config(
"nearest_neighbor:name",
"euclid_lsh")("hash_num", "64")()
};
INSTANTIATE_TEST_CASE_P(lsh_test,
nearest_neighbor_test,
::testing::ValuesIn(configs));
} // namespace nearest_neighbor
} // namespace jubatus
<|endoftext|> |
<commit_before>#ifdef WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "fmod.hpp"
#include <random>
#include <ctime>
#define FMOD_GAIN_USEPROCESSCALLBACK /* FMOD plugins have 2 methods of processing data.
1. via a 'read' callback which is compatible with FMOD Ex but limited in functionality, or
2. via a 'process' callback which exposes more functionality, like masks and query before process early out logic. */
extern "C" {
F_DECLSPEC F_DLLEXPORT FMOD_DSP_DESCRIPTION* F_STDCALL FMODGetDSPDescription();
}
const float CX2_DELAY_PARAM_TIME_MIN = 0.0f;
const float CX2_DELAY_PARAM_TIME_MAX = 2.0f;
const float CX2_DELAY_PARAM_TIME_DEFAULT = 1.0f;
enum
{
FMOD_GAIN_PARAM_TIME = 0,
FMOD_GAIN_NUM_PARAMETERS
};
#define DECIBELS_TO_LINEAR(__dbval__) ((__dbval__ <= FMOD_GAIN_PARAM_GAIN_MIN) ? 0.0f : powf(10.0f, __dbval__ / 20.0f))
#define LINEAR_TO_DECIBELS(__linval__) ((__linval__ <= 0.0f) ? FMOD_GAIN_PARAM_GAIN_MIN : 20.0f * log10f((float)__linval__))
FMOD_RESULT F_CALLBACK FMOD_Gain_dspcreate(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_dsprelease(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspreset(FMOD_DSP_STATE *dsp_state);
#ifdef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_RESULT F_CALLBACK FMOD_Gain_dspprocess(FMOD_DSP_STATE *dsp_state, unsigned int length, const FMOD_DSP_BUFFER_ARRAY *inbufferarray, FMOD_DSP_BUFFER_ARRAY *outbufferarray, FMOD_BOOL inputsidle, FMOD_DSP_PROCESS_OPERATION op);
#else
FMOD_RESULT F_CALLBACK FMOD_Gain_dspread(FMOD_DSP_STATE *dsp_state, float *inbuffer, float *outbuffer, unsigned int length, int inchannels, int *outchannels);
#endif
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float value);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamint(FMOD_DSP_STATE *dsp_state, int index, int value);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparambool(FMOD_DSP_STATE *dsp_state, int index, FMOD_BOOL value);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamdata(FMOD_DSP_STATE *dsp_state, int index, void *data, unsigned int length);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float *value, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamint(FMOD_DSP_STATE *dsp_state, int index, int *value, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparambool(FMOD_DSP_STATE *dsp_state, int index, FMOD_BOOL *value, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamdata(FMOD_DSP_STATE *dsp_state, int index, void **value, unsigned int *length, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_shouldiprocess(FMOD_DSP_STATE *dsp_state, FMOD_BOOL inputsidle, unsigned int length, FMOD_CHANNELMASK inmask, int inchannels, FMOD_SPEAKERMODE speakermode);
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_register(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_deregister(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_mix(FMOD_DSP_STATE *dsp_state, int stage);
static bool FMOD_Gain_Running = false;
static FMOD_DSP_PARAMETER_DESC p_time;
FMOD_DSP_PARAMETER_DESC *FMOD_Gain_dspparam[FMOD_GAIN_NUM_PARAMETERS] =
{
&p_time,
};
FMOD_DSP_DESCRIPTION FMOD_Gain_Desc =
{
FMOD_PLUGIN_SDK_VERSION,
"CX2 Glitch Soundtrack", // name
0x00000001, // plug-in version
1, // number of input buffers to process
1, // number of output buffers to process
FMOD_Gain_dspcreate,
FMOD_Gain_dsprelease,
FMOD_Gain_dspreset,
#ifndef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_Gain_dspread,
#else
0,
#endif
#ifdef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_Gain_dspprocess,
#else
0,
#endif
0,
FMOD_GAIN_NUM_PARAMETERS,
FMOD_Gain_dspparam,
FMOD_Gain_dspsetparamfloat,
0, // FMOD_Gain_dspsetparamint,
0, //FMOD_Gain_dspsetparambool,
0, // FMOD_Gain_dspsetparamdata,
FMOD_Gain_dspgetparamfloat,
0, // FMOD_Gain_dspgetparamint,
0, // FMOD_Gain_dspgetparambool,
0, // FMOD_Gain_dspgetparamdata,
FMOD_Gain_shouldiprocess,
0, // userdata
FMOD_Gain_sys_register,
FMOD_Gain_sys_deregister,
FMOD_Gain_sys_mix
};
extern "C"
{
F_DECLSPEC F_DLLEXPORT FMOD_DSP_DESCRIPTION* F_STDCALL FMODGetDSPDescription()
{
FMOD_DSP_INIT_PARAMDESC_FLOAT(p_time, "Time", "ms", "Time in milliseconds.", CX2_DELAY_PARAM_TIME_MIN, CX2_DELAY_PARAM_TIME_MAX, CX2_DELAY_PARAM_TIME_DEFAULT);
return &FMOD_Gain_Desc;
}
}
class FMODGainState
{
public:
FMODGainState();
~FMODGainState();
void init();
void read(float *inbuffer, float *outbuffer, unsigned int length, int channels);
void reset();
void setDelayTime(float);
float delayTime() const { return m_delay_time; }
static int sampleRate;
private:
float m_delay_time;
float* m_delay_buffer = nullptr;
int m_delay_buffer_size;
float m_max_delay_sec = CX2_DELAY_PARAM_TIME_MAX;
int m_currentDelayIndex = 0;
};
int FMODGainState::sampleRate = 44100;
FMODGainState::FMODGainState()
{
init();
}
FMODGainState::~FMODGainState() {
delete m_delay_buffer;
}
void FMODGainState::init() {
srand(time(0));
m_max_delay_sec = CX2_DELAY_PARAM_TIME_MAX;
m_currentDelayIndex = 0;
m_delay_buffer_size = (int)(m_max_delay_sec * FMODGainState::sampleRate);
if (m_delay_buffer == nullptr) {
m_delay_buffer = new float[m_delay_buffer_size]();
}
reset();
}
void FMODGainState::read(float *inbuffer, float *outbuffer, unsigned int length, int channels)
{
unsigned int samples = length * channels;
while (samples--) {
//Saturation ?
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
//float r = 0.5;
float inSamp = *inbuffer;
if (inSamp > r) {
inSamp = r + (inSamp-r)/ (1+((inSamp-r)/(1-r)) * (1+((inSamp-r)/(1-r))));
} else if (inSamp > 1) {
inSamp = (r+1)/2;
}
// Check delay index
if (m_currentDelayIndex > m_delay_buffer_size - 1) {
m_currentDelayIndex = 0;
}
// Delay
if ((m_currentDelayIndex + (m_delay_time * FMODGainState::sampleRate)) > m_delay_buffer_size){
m_delay_buffer[(int)((m_currentDelayIndex + (m_delay_time * FMODGainState::sampleRate)) - m_delay_buffer_size)] = inSamp * .25f;
} else {
m_delay_buffer[(int)(m_currentDelayIndex + (m_delay_time * FMODGainState::sampleRate))] = inSamp * .25f;
}
*outbuffer++ = *inbuffer++ + m_delay_buffer[m_currentDelayIndex++];
}
}
void FMODGainState::reset()
{
m_currentDelayIndex = 0;
}
void FMODGainState::setDelayTime(float delay)
{
m_delay_time = delay;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dspcreate(FMOD_DSP_STATE *dsp_state)
{
dsp_state->plugindata = (FMODGainState *)FMOD_DSP_STATE_MEMALLOC(dsp_state, sizeof(FMODGainState), FMOD_MEMORY_NORMAL, "FMODGainState");
if (!dsp_state->plugindata)
{
return FMOD_ERR_MEMORY;
}
int sr;
dsp_state->callbacks->getsamplerate(dsp_state, &sr);
FMODGainState::sampleRate = sr;
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
state->init();
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dsprelease(FMOD_DSP_STATE *dsp_state)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
FMOD_DSP_STATE_MEMFREE(dsp_state, state, FMOD_MEMORY_NORMAL, "FMODGainState");
return FMOD_OK;
}
#ifdef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_RESULT F_CALLBACK FMOD_Gain_dspprocess(FMOD_DSP_STATE *dsp_state, unsigned int length, const FMOD_DSP_BUFFER_ARRAY *inbufferarray, FMOD_DSP_BUFFER_ARRAY *outbufferarray, FMOD_BOOL /*inputsidle*/, FMOD_DSP_PROCESS_OPERATION op)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
if (op == FMOD_DSP_PROCESS_QUERY)
{
if (outbufferarray && inbufferarray)
{
outbufferarray[0].bufferchannelmask[0] = inbufferarray[0].bufferchannelmask[0];
outbufferarray[0].buffernumchannels[0] = inbufferarray[0].buffernumchannels[0];
outbufferarray[0].speakermode = inbufferarray[0].speakermode;
}
}
else
{
state->read(inbufferarray[0].buffers[0], outbufferarray[0].buffers[0], length, inbufferarray[0].buffernumchannels[0]); // input and output channels count match for this effect
}
return FMOD_OK;
}
#else
FMOD_RESULT F_CALLBACK FMOD_Gain_dspread(FMOD_DSP_STATE *dsp_state, float *inbuffer, float *outbuffer, unsigned int length, int inchannels, int * /*outchannels*/)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
state->read(inbuffer, outbuffer, length, inchannels); // input and output channels count match for this effect
return FMOD_OK;
}
#endif
FMOD_RESULT F_CALLBACK FMOD_Gain_dspreset(FMOD_DSP_STATE *dsp_state)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
state->reset();
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float value)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
switch (index)
{
case FMOD_GAIN_PARAM_TIME:
state->setDelayTime(value);
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float *value, char *valuestr)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
switch (index)
{
case FMOD_GAIN_PARAM_TIME:
*value = state->delayTime();
if (valuestr) sprintf(valuestr, "%.1f ms", state->delayTime());
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_shouldiprocess(FMOD_DSP_STATE * /*dsp_state*/, FMOD_BOOL inputsidle, unsigned int /*length*/, FMOD_CHANNELMASK /*inmask*/, int /*inchannels*/, FMOD_SPEAKERMODE /*speakermode*/)
{
if (inputsidle)
{
return FMOD_ERR_DSP_DONTPROCESS;
}
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_register(FMOD_DSP_STATE * /*dsp_state*/)
{
FMOD_Gain_Running = true;
// called once for this type of dsp being loaded or registered (it is not per instance)
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_deregister(FMOD_DSP_STATE * /*dsp_state*/)
{
FMOD_Gain_Running = false;
// called once for this type of dsp being unloaded or de-registered (it is not per instance)
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_mix(FMOD_DSP_STATE * /*dsp_state*/, int /*stage*/)
{
// stage == 0 , before all dsps are processed/mixed, this callback is called once for this type.
// stage == 1 , after all dsps are processed/mixed, this callback is called once for this type.
return FMOD_OK;
}
<commit_msg>Added reverse pitch down.<commit_after>#ifdef WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "fmod.hpp"
#include <random>
#include <ctime>
#define FMOD_GAIN_USEPROCESSCALLBACK /* FMOD plugins have 2 methods of processing data.
1. via a 'read' callback which is compatible with FMOD Ex but limited in functionality, or
2. via a 'process' callback which exposes more functionality, like masks and query before process early out logic. */
extern "C" {
F_DECLSPEC F_DLLEXPORT FMOD_DSP_DESCRIPTION* F_STDCALL FMODGetDSPDescription();
}
const float CX2_DELAY_PARAM_TIME_MIN = 0.0f;
const float CX2_DELAY_PARAM_TIME_MAX = 2.0f;
const float CX2_DELAY_PARAM_TIME_DEFAULT = 1.0f;
enum
{
FMOD_GAIN_PARAM_TIME = 0,
FMOD_GAIN_NUM_PARAMETERS
};
#define DECIBELS_TO_LINEAR(__dbval__) ((__dbval__ <= FMOD_GAIN_PARAM_GAIN_MIN) ? 0.0f : powf(10.0f, __dbval__ / 20.0f))
#define LINEAR_TO_DECIBELS(__linval__) ((__linval__ <= 0.0f) ? FMOD_GAIN_PARAM_GAIN_MIN : 20.0f * log10f((float)__linval__))
FMOD_RESULT F_CALLBACK FMOD_Gain_dspcreate(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_dsprelease(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspreset(FMOD_DSP_STATE *dsp_state);
#ifdef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_RESULT F_CALLBACK FMOD_Gain_dspprocess(FMOD_DSP_STATE *dsp_state, unsigned int length, const FMOD_DSP_BUFFER_ARRAY *inbufferarray, FMOD_DSP_BUFFER_ARRAY *outbufferarray, FMOD_BOOL inputsidle, FMOD_DSP_PROCESS_OPERATION op);
#else
FMOD_RESULT F_CALLBACK FMOD_Gain_dspread(FMOD_DSP_STATE *dsp_state, float *inbuffer, float *outbuffer, unsigned int length, int inchannels, int *outchannels);
#endif
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float value);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamint(FMOD_DSP_STATE *dsp_state, int index, int value);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparambool(FMOD_DSP_STATE *dsp_state, int index, FMOD_BOOL value);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamdata(FMOD_DSP_STATE *dsp_state, int index, void *data, unsigned int length);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float *value, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamint(FMOD_DSP_STATE *dsp_state, int index, int *value, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparambool(FMOD_DSP_STATE *dsp_state, int index, FMOD_BOOL *value, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamdata(FMOD_DSP_STATE *dsp_state, int index, void **value, unsigned int *length, char *valuestr);
FMOD_RESULT F_CALLBACK FMOD_Gain_shouldiprocess(FMOD_DSP_STATE *dsp_state, FMOD_BOOL inputsidle, unsigned int length, FMOD_CHANNELMASK inmask, int inchannels, FMOD_SPEAKERMODE speakermode);
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_register(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_deregister(FMOD_DSP_STATE *dsp_state);
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_mix(FMOD_DSP_STATE *dsp_state, int stage);
static bool FMOD_Gain_Running = false;
static FMOD_DSP_PARAMETER_DESC p_time;
FMOD_DSP_PARAMETER_DESC *FMOD_Gain_dspparam[FMOD_GAIN_NUM_PARAMETERS] =
{
&p_time,
};
FMOD_DSP_DESCRIPTION FMOD_Gain_Desc =
{
FMOD_PLUGIN_SDK_VERSION,
"CX2 Glitch Soundtrack", // name
0x00000001, // plug-in version
1, // number of input buffers to process
1, // number of output buffers to process
FMOD_Gain_dspcreate,
FMOD_Gain_dsprelease,
FMOD_Gain_dspreset,
#ifndef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_Gain_dspread,
#else
0,
#endif
#ifdef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_Gain_dspprocess,
#else
0,
#endif
0,
FMOD_GAIN_NUM_PARAMETERS,
FMOD_Gain_dspparam,
FMOD_Gain_dspsetparamfloat,
0, // FMOD_Gain_dspsetparamint,
0, //FMOD_Gain_dspsetparambool,
0, // FMOD_Gain_dspsetparamdata,
FMOD_Gain_dspgetparamfloat,
0, // FMOD_Gain_dspgetparamint,
0, // FMOD_Gain_dspgetparambool,
0, // FMOD_Gain_dspgetparamdata,
FMOD_Gain_shouldiprocess,
0, // userdata
FMOD_Gain_sys_register,
FMOD_Gain_sys_deregister,
FMOD_Gain_sys_mix
};
extern "C"
{
F_DECLSPEC F_DLLEXPORT FMOD_DSP_DESCRIPTION* F_STDCALL FMODGetDSPDescription()
{
FMOD_DSP_INIT_PARAMDESC_FLOAT(p_time, "Time", "ms", "Time in milliseconds.", CX2_DELAY_PARAM_TIME_MIN, CX2_DELAY_PARAM_TIME_MAX, CX2_DELAY_PARAM_TIME_DEFAULT);
return &FMOD_Gain_Desc;
}
}
class FMODGainState
{
public:
FMODGainState();
~FMODGainState();
void init();
void read(float *inbuffer, float *outbuffer, unsigned int length, int channels);
void reset();
void setDelayTime(float);
float delayTime() const { return m_delay_time; }
static int sampleRate;
private:
float m_delay_time;
float* m_delay_buffer = nullptr;
int m_delay_buffer_size;
float m_max_delay_sec = CX2_DELAY_PARAM_TIME_MAX;
int m_currentDelayIndex = 0;
int m_readDelayIndex = 0;
int m_pitch_delay;
};
int FMODGainState::sampleRate = 44100;
FMODGainState::FMODGainState()
{
init();
}
FMODGainState::~FMODGainState() {
delete m_delay_buffer;
}
void FMODGainState::init() {
srand(time(0));
m_max_delay_sec = CX2_DELAY_PARAM_TIME_MAX;
m_currentDelayIndex = 0;
m_readDelayIndex = 0;
m_delay_buffer_size = (int)(m_max_delay_sec * FMODGainState::sampleRate);
if (m_delay_buffer == nullptr) {
m_delay_buffer = new float[m_delay_buffer_size]();
}
reset();
}
void FMODGainState::read(float *inbuffer, float *outbuffer, unsigned int length, int channels)
{
unsigned int samples = length * channels;
while (samples--) {
//Saturation ?
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
//float r = 0.5;
float inSamp = *inbuffer;
if (inSamp > r) {
inSamp = r + (inSamp-r)/ (1+((inSamp-r)/(1-r)) * (1+((inSamp-r)/(1-r))));
} else if (inSamp > 1) {
inSamp = (r+1)/2;
}
// Check delay index
if (m_currentDelayIndex > m_delay_buffer_size - 1) {
m_currentDelayIndex = 0;
}
if (m_readDelayIndex < 0) {
m_readDelayIndex = m_delay_buffer_size - 1;
}
// Delay
if ((m_currentDelayIndex + (m_delay_time * FMODGainState::sampleRate)) > m_delay_buffer_size){
m_delay_buffer[(int)((m_currentDelayIndex + (m_delay_time * FMODGainState::sampleRate)) - m_delay_buffer_size)] = inSamp;
} else {
m_delay_buffer[(int)(m_currentDelayIndex + (m_delay_time * FMODGainState::sampleRate))] = inSamp;
}
m_currentDelayIndex++;
if (m_pitch_delay % 2 == 0) {
*outbuffer++ = *inbuffer++ + m_delay_buffer[m_readDelayIndex--];
}
else {
*outbuffer++ = *inbuffer++;
}
//*outbuffer++ = *inbuffer++ + m_delay_buffer[m_readDelayIndex];
//m_readDelayIndex += 2;
m_pitch_delay++;
}
}
void FMODGainState::reset()
{
m_currentDelayIndex = 0;
}
void FMODGainState::setDelayTime(float delay)
{
m_delay_time = delay;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dspcreate(FMOD_DSP_STATE *dsp_state)
{
dsp_state->plugindata = (FMODGainState *)FMOD_DSP_STATE_MEMALLOC(dsp_state, sizeof(FMODGainState), FMOD_MEMORY_NORMAL, "FMODGainState");
if (!dsp_state->plugindata)
{
return FMOD_ERR_MEMORY;
}
int sr;
dsp_state->callbacks->getsamplerate(dsp_state, &sr);
FMODGainState::sampleRate = sr;
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
state->init();
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dsprelease(FMOD_DSP_STATE *dsp_state)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
FMOD_DSP_STATE_MEMFREE(dsp_state, state, FMOD_MEMORY_NORMAL, "FMODGainState");
return FMOD_OK;
}
#ifdef FMOD_GAIN_USEPROCESSCALLBACK
FMOD_RESULT F_CALLBACK FMOD_Gain_dspprocess(FMOD_DSP_STATE *dsp_state, unsigned int length, const FMOD_DSP_BUFFER_ARRAY *inbufferarray, FMOD_DSP_BUFFER_ARRAY *outbufferarray, FMOD_BOOL /*inputsidle*/, FMOD_DSP_PROCESS_OPERATION op)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
if (op == FMOD_DSP_PROCESS_QUERY)
{
if (outbufferarray && inbufferarray)
{
outbufferarray[0].bufferchannelmask[0] = inbufferarray[0].bufferchannelmask[0];
outbufferarray[0].buffernumchannels[0] = inbufferarray[0].buffernumchannels[0];
outbufferarray[0].speakermode = inbufferarray[0].speakermode;
}
}
else
{
state->read(inbufferarray[0].buffers[0], outbufferarray[0].buffers[0], length, inbufferarray[0].buffernumchannels[0]); // input and output channels count match for this effect
}
return FMOD_OK;
}
#else
FMOD_RESULT F_CALLBACK FMOD_Gain_dspread(FMOD_DSP_STATE *dsp_state, float *inbuffer, float *outbuffer, unsigned int length, int inchannels, int * /*outchannels*/)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
state->read(inbuffer, outbuffer, length, inchannels); // input and output channels count match for this effect
return FMOD_OK;
}
#endif
FMOD_RESULT F_CALLBACK FMOD_Gain_dspreset(FMOD_DSP_STATE *dsp_state)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
state->reset();
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dspsetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float value)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
switch (index)
{
case FMOD_GAIN_PARAM_TIME:
state->setDelayTime(value);
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_dspgetparamfloat(FMOD_DSP_STATE *dsp_state, int index, float *value, char *valuestr)
{
FMODGainState *state = (FMODGainState *)dsp_state->plugindata;
switch (index)
{
case FMOD_GAIN_PARAM_TIME:
*value = state->delayTime();
if (valuestr) sprintf(valuestr, "%.1f ms", state->delayTime());
return FMOD_OK;
}
return FMOD_ERR_INVALID_PARAM;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_shouldiprocess(FMOD_DSP_STATE * /*dsp_state*/, FMOD_BOOL inputsidle, unsigned int /*length*/, FMOD_CHANNELMASK /*inmask*/, int /*inchannels*/, FMOD_SPEAKERMODE /*speakermode*/)
{
if (inputsidle)
{
return FMOD_ERR_DSP_DONTPROCESS;
}
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_register(FMOD_DSP_STATE * /*dsp_state*/)
{
FMOD_Gain_Running = true;
// called once for this type of dsp being loaded or registered (it is not per instance)
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_deregister(FMOD_DSP_STATE * /*dsp_state*/)
{
FMOD_Gain_Running = false;
// called once for this type of dsp being unloaded or de-registered (it is not per instance)
return FMOD_OK;
}
FMOD_RESULT F_CALLBACK FMOD_Gain_sys_mix(FMOD_DSP_STATE * /*dsp_state*/, int /*stage*/)
{
// stage == 0 , before all dsps are processed/mixed, this callback is called once for this type.
// stage == 1 , after all dsps are processed/mixed, this callback is called once for this type.
return FMOD_OK;
}
<|endoftext|> |
<commit_before>The Node struct is defined as follows:
struct Node {
int data;
Node* left;
Node* right;
}
*/
#include <limits.h>
bool checkBST(Node* root) {
return is_BST(root, INT_MIN, INT_MAX);
}
bool is_BST(Node* node, int min, int max) {
if (node == NULL) return true;
if (node->data <= min || node->data >= max) return false;
return is_BST(node->left, min, node->data) && is_BST(node->right, node->data, max);
}<commit_msg>fixed comments<commit_after>// The Node struct is defined as follows:
// struct Node {
// int data;
// Node* left;
// Node* right;
// }
#include <limits.h>
bool checkBST(Node* root) {
return is_BST(root, INT_MIN, INT_MAX);
}
bool is_BST(Node* node, int min, int max) {
if (node == NULL) return true;
if (node->data <= min || node->data >= max) return false;
return is_BST(node->left, min, node->data) && is_BST(node->right, node->data, max);
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageCheckerboard.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageCheckerboard.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkImageCheckerboard, "1.9");
vtkStandardNewMacro(vtkImageCheckerboard);
//----------------------------------------------------------------------------
vtkImageCheckerboard::vtkImageCheckerboard()
{
this->NumberOfDivisions[0] = 2;
this->NumberOfDivisions[1] = 2;
this->NumberOfDivisions[2] = 2;
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
// Handles the two input operations
template <class T>
void vtkImageCheckerboardExecute2(vtkImageCheckerboard *self,
vtkImageData *in1Data, T *in1Ptr,
vtkImageData *in2Data, T *in2Ptr,
vtkImageData *outData,
T *outPtr,
int outExt[6], int id)
{
int idxR, idxY, idxZ;
int maxY, maxZ;
int dimWholeX, dimWholeY, dimWholeZ;
int divX, divY, divZ;
int nComp;
int selectX, selectY, selectZ;
int which;
int inIncX, inIncY, inIncZ;
int in2IncX, in2IncY, in2IncZ;
int outIncX, outIncY, outIncZ;
int wholeExt[6];
int rowLength;
unsigned long count = 0;
unsigned long target;
int threadOffsetX, threadOffsetY, threadOffsetZ;
int numDivX, numDivY, numDivZ;
// find the region to loop over
nComp = in1Data->GetNumberOfScalarComponents();
rowLength = (outExt[1] - outExt[0]+1)*nComp;
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
outData->GetWholeExtent(wholeExt);
dimWholeX = wholeExt[1] - wholeExt[0] + 1;
dimWholeY = wholeExt[3] - wholeExt[2] + 1;
dimWholeZ = wholeExt[5] - wholeExt[4] + 1;
threadOffsetX = (outExt[0] - wholeExt[0]) * nComp;
threadOffsetY = outExt[2] - wholeExt[2];
threadOffsetZ = outExt[4] - wholeExt[4];
target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
in2Data->GetContinuousIncrements(outExt, in2IncX, in2IncY, in2IncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// make sure number of divisions is not 0
numDivX = (self->GetNumberOfDivisions()[0] == 0) ? 1 : self->GetNumberOfDivisions()[0];
numDivY = (self->GetNumberOfDivisions()[1] == 0) ? 1 : self->GetNumberOfDivisions()[1];
numDivZ = (self->GetNumberOfDivisions()[2] == 0) ? 1 : self->GetNumberOfDivisions()[2];
divX = dimWholeX / numDivX * nComp;
divY = dimWholeY / numDivY;
divZ = dimWholeZ / numDivZ;
// Loop through output pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
selectZ = (((idxZ + threadOffsetZ) / divZ) % 2) << 2;
for (idxY = 0; idxY <= maxY; idxY++)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
selectY = (((idxY + threadOffsetY) / divY) % 2) << 1;
for (idxR = 0; idxR < rowLength; idxR++)
{
selectX = ((idxR + threadOffsetX) / divX) % 2;
which = selectZ + selectY + selectX;
switch (which)
{
case 0:
*outPtr = *in1Ptr;
break;
case 1:
*outPtr = *in2Ptr;
break;
case 2:
*outPtr = *in2Ptr;
break;
case 3:
*outPtr = *in1Ptr;
break;
case 4:
*outPtr = *in2Ptr;
break;
case 5:
*outPtr = *in1Ptr;
break;
case 6:
*outPtr = *in1Ptr;
break;
case 7:
*outPtr = *in2Ptr;
break;
}
outPtr++;
in1Ptr++;
in2Ptr++;
}
outPtr += outIncY;
in1Ptr += inIncY;
in2Ptr += in2IncY;
}
outPtr += outIncZ;
in1Ptr += inIncZ;
in2Ptr += in2IncZ;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output regions, and executes the filter
// algorithm to fill the output from the inputs.
void vtkImageCheckerboard::ThreadedExecute(vtkImageData **inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *in1Ptr, *in2Ptr;
void *outPtr;
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
if (inData[0] == NULL)
{
vtkErrorMacro(<< "Input " << 0 << " must be specified.");
return;
}
in1Ptr = inData[0]->GetScalarPointerForExtent(outExt);
outPtr = outData->GetScalarPointerForExtent(outExt);
// this filter expects that input is the same type as output.
if (inData[0]->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData[0]->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
if (inData[1] == NULL)
{
vtkErrorMacro(<< "Input " << 1 << " must be specified.");
return;
}
in2Ptr = inData[1]->GetScalarPointerForExtent(outExt);
// this filter expects that inputs that have the same number of components
if (inData[0]->GetNumberOfScalarComponents() !=
inData[1]->GetNumberOfScalarComponents())
{
vtkErrorMacro(<< "Execute: input1 NumberOfScalarComponents, "
<< inData[0]->GetNumberOfScalarComponents()
<< ", must match out input2 NumberOfScalarComponents "
<< inData[1]->GetNumberOfScalarComponents());
return;
}
switch (inData[0]->GetScalarType())
{
vtkTemplateMacro9(vtkImageCheckerboardExecute2, this, inData[0],
(VTK_TT *)(in1Ptr), inData[1], (VTK_TT *)(in2Ptr),
outData, (VTK_TT *)(outPtr), outExt, id);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
void vtkImageCheckerboard::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "NumberOfDivisions: (" << this->NumberOfDivisions[0] << ", "
<< this->NumberOfDivisions[1] << ", "
<< this->NumberOfDivisions[2] << ")\n";
}
<commit_msg>ERR: was not checking for empty inputs.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageCheckerboard.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageCheckerboard.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkImageCheckerboard, "1.10");
vtkStandardNewMacro(vtkImageCheckerboard);
//----------------------------------------------------------------------------
vtkImageCheckerboard::vtkImageCheckerboard()
{
this->NumberOfDivisions[0] = 2;
this->NumberOfDivisions[1] = 2;
this->NumberOfDivisions[2] = 2;
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
// Handles the two input operations
template <class T>
void vtkImageCheckerboardExecute2(vtkImageCheckerboard *self,
vtkImageData *in1Data, T *in1Ptr,
vtkImageData *in2Data, T *in2Ptr,
vtkImageData *outData,
T *outPtr,
int outExt[6], int id)
{
int idxR, idxY, idxZ;
int maxY, maxZ;
int dimWholeX, dimWholeY, dimWholeZ;
int divX, divY, divZ;
int nComp;
int selectX, selectY, selectZ;
int which;
int inIncX, inIncY, inIncZ;
int in2IncX, in2IncY, in2IncZ;
int outIncX, outIncY, outIncZ;
int wholeExt[6];
int rowLength;
unsigned long count = 0;
unsigned long target;
int threadOffsetX, threadOffsetY, threadOffsetZ;
int numDivX, numDivY, numDivZ;
// find the region to loop over
nComp = in1Data->GetNumberOfScalarComponents();
rowLength = (outExt[1] - outExt[0]+1)*nComp;
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
outData->GetWholeExtent(wholeExt);
dimWholeX = wholeExt[1] - wholeExt[0] + 1;
dimWholeY = wholeExt[3] - wholeExt[2] + 1;
dimWholeZ = wholeExt[5] - wholeExt[4] + 1;
threadOffsetX = (outExt[0] - wholeExt[0]) * nComp;
threadOffsetY = outExt[2] - wholeExt[2];
threadOffsetZ = outExt[4] - wholeExt[4];
target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
in2Data->GetContinuousIncrements(outExt, in2IncX, in2IncY, in2IncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// make sure number of divisions is not 0
numDivX = (self->GetNumberOfDivisions()[0] == 0) ? 1 : self->GetNumberOfDivisions()[0];
numDivY = (self->GetNumberOfDivisions()[1] == 0) ? 1 : self->GetNumberOfDivisions()[1];
numDivZ = (self->GetNumberOfDivisions()[2] == 0) ? 1 : self->GetNumberOfDivisions()[2];
divX = dimWholeX / numDivX * nComp;
divY = dimWholeY / numDivY;
divZ = dimWholeZ / numDivZ;
// Loop through output pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
selectZ = (((idxZ + threadOffsetZ) / divZ) % 2) << 2;
for (idxY = 0; idxY <= maxY; idxY++)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
selectY = (((idxY + threadOffsetY) / divY) % 2) << 1;
for (idxR = 0; idxR < rowLength; idxR++)
{
selectX = ((idxR + threadOffsetX) / divX) % 2;
which = selectZ + selectY + selectX;
switch (which)
{
case 0:
*outPtr = *in1Ptr;
break;
case 1:
*outPtr = *in2Ptr;
break;
case 2:
*outPtr = *in2Ptr;
break;
case 3:
*outPtr = *in1Ptr;
break;
case 4:
*outPtr = *in2Ptr;
break;
case 5:
*outPtr = *in1Ptr;
break;
case 6:
*outPtr = *in1Ptr;
break;
case 7:
*outPtr = *in2Ptr;
break;
}
outPtr++;
in1Ptr++;
in2Ptr++;
}
outPtr += outIncY;
in1Ptr += inIncY;
in2Ptr += in2IncY;
}
outPtr += outIncZ;
in1Ptr += inIncZ;
in2Ptr += in2IncZ;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output regions, and executes the filter
// algorithm to fill the output from the inputs.
void vtkImageCheckerboard::ThreadedExecute(vtkImageData **inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *in1Ptr, *in2Ptr;
void *outPtr;
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
if (inData[0] == NULL)
{
vtkErrorMacro(<< "Input " << 0 << " must be specified.");
return;
}
in1Ptr = inData[0]->GetScalarPointerForExtent(outExt);
if (!in1Ptr)
{
vtkErrorMacro(<< "Input " << 0 << " cannot be empty.");
return;
}
outPtr = outData->GetScalarPointerForExtent(outExt);
// this filter expects that input is the same type as output.
if (inData[0]->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData[0]->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
if (inData[1] == NULL)
{
vtkErrorMacro(<< "Input " << 1 << " must be specified.");
return;
}
in2Ptr = inData[1]->GetScalarPointerForExtent(outExt);
if (!in2Ptr)
{
vtkErrorMacro(<< "Input " << 1 << " cannot be empty.");
return;
}
// this filter expects that inputs that have the same number of components
if (inData[0]->GetNumberOfScalarComponents() !=
inData[1]->GetNumberOfScalarComponents())
{
vtkErrorMacro(<< "Execute: input1 NumberOfScalarComponents, "
<< inData[0]->GetNumberOfScalarComponents()
<< ", must match out input2 NumberOfScalarComponents "
<< inData[1]->GetNumberOfScalarComponents());
return;
}
switch (inData[0]->GetScalarType())
{
vtkTemplateMacro9(vtkImageCheckerboardExecute2, this, inData[0],
(VTK_TT *)(in1Ptr), inData[1], (VTK_TT *)(in2Ptr),
outData, (VTK_TT *)(outPtr), outExt, id);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
void vtkImageCheckerboard::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "NumberOfDivisions: (" << this->NumberOfDivisions[0] << ", "
<< this->NumberOfDivisions[1] << ", "
<< this->NumberOfDivisions[2] << ")\n";
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <v8.h>
#include <string.h>
#include "V8Runtime.h"
#include "AndroidUtil.h"
#include "EventEmitter.h"
#include "JNIUtil.h"
#include "V8Util.h"
#include "KrollJavaScript.h"
#include "KrollProxy.h"
#include "TypeConverter.h"
#include "APIModule.h"
#include "ScriptsModule.h"
#define TAG "V8Runtime"
namespace titanium {
/* static */
void V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)
{
jobject v8Object = (jobject) parameter;
ref.Dispose();
JNIUtil::getJNIEnv()->DeleteGlobalRef(v8Object);
}
/* static */
jobject V8Runtime::newObject(Handle<Object> object)
{
HandleScope scope;
LOGI(TAG, "Creating new object...");
JNIEnv *env = JNIUtil::getJNIEnv();
if (!env) return NULL;
jlong ptr = reinterpret_cast<jlong>(*Persistent<Object>::New(object));jobject
v8Object = env->NewGlobalRef(env->NewObject(JNIUtil::v8ObjectClass, JNIUtil::v8ObjectInitMethod, ptr));
// make a 2nd persistent weakref so we can be informed of GC
Persistent<Object> weakRef = Persistent<Object>::New(object);
weakRef.MakeWeak(reinterpret_cast<void*>(v8Object), V8Runtime::collectWeakRef);
return v8Object;
}
static Persistent<Object> global;
static Handle<Value> binding(const Arguments& args)
{
static Persistent<Object> binding_cache;
HandleScope scope;
Local<String> module = args[0]->ToString();
String::Utf8Value module_v(module);
if (binding_cache.IsEmpty()) {
binding_cache = Persistent<Object>::New(Object::New());
}
Local<Object> exports;
if (binding_cache->Has(module)) {
exports = binding_cache->Get(module)->ToObject();
} else if (!strcmp(*module_v, "natives")) {
exports = Object::New();
KrollJavaScript::DefineNatives(exports);
binding_cache->Set(module, exports);
} else if (!strcmp(*module_v, "evals")) {
exports = Object::New();
ScriptsModule::Initialize(exports);
binding_cache->Set(module, exports);
} else {
return ThrowException(Exception::Error(String::New("No such module")));
}
return scope.Close(exports);
}
/* static */
void V8Runtime::bootstrap()
{
Local<FunctionTemplate> global_template = FunctionTemplate::New();
EventEmitter::Initialize(global_template);
global = Persistent<Object>::New(global_template->GetFunction()->NewInstance());
global->Set(String::NewSymbol("binding"), FunctionTemplate::New(binding)->GetFunction());
global->Set(String::NewSymbol("EventEmitter"), EventEmitter::constructorTemplate->GetFunction());
global->Set(String::NewSymbol("API"), APIModule::init());
TryCatch try_catch;
Handle<Value> result = ExecuteString(KrollJavaScript::MainSource(), IMMUTABLE_STRING_LITERAL("kroll.js"));
if (try_catch.HasCaught()) {
ReportException(try_catch, true);
JNIUtil::terminateVM();
}
if (!result->IsFunction()) {
LOGF(TAG, "kroll.js result is not a function");
ReportException(try_catch, true);
JNIUtil::terminateVM();
}
Handle<Function> mainFunction = Handle<Function>::Cast(result);
Local<Object> global = v8::Context::GetCurrent()->Global();
Local<Value> args[] = { Local<Value>::New(global) };
mainFunction->Call(global, 1, args);
if (try_catch.HasCaught()) {
ReportException(try_catch, true);
JNIUtil::terminateVM();
}
}
}
static jobject jruntime;
static Persistent<Context> context;
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: init
* Signature: (Lorg/appcelerator/kroll/runtime/v8/V8Runtime;)V
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_init(JNIEnv *env, jclass clazz, jobject self)
{
jruntime = env->NewGlobalRef(self);
titanium::JNIUtil::initCache(env);
V8::Initialize();
HandleScope scope;
context = Context::New();
Context::Scope context_scope(context);
titanium::V8Runtime::bootstrap();
titanium::initKrollProxy();
}
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_evalData(JNIEnv *env, jclass clazz, jcharArray buffer, jstring filename)
{
HandleScope scope;
if (!buffer) {
// TODO throw exception
return;
}
jint len = env->GetArrayLength(buffer);
jchar *pchars = (jchar*) env->GetPrimitiveArrayCritical(buffer, 0);
if (!pchars) {
// TODO throw exception
return;
}
Handle<String> jsFilename = titanium::TypeConverter::javaStringToJsString(filename);
ScriptOrigin origin(jsFilename);
v8::Handle<v8::String> jsString = v8::String::New(pchars, len);
v8::Handle<v8::Script> script = Script::New(jsString, &origin);
env->ReleasePrimitiveArrayCritical(buffer, pchars, 0);
script->Run();
}
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: dispose
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_dispose(JNIEnv *env, jclass clazz)
{
context.Dispose();
V8::Dispose();
env->DeleteGlobalRef(jruntime);
jruntime = NULL;
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
titanium::JNIUtil::javaVm = vm;
return JNI_VERSION_1_4;
}
#ifdef __cplusplus
}
#endif
<commit_msg>adding basic init logging<commit_after>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <v8.h>
#include <string.h>
#include "V8Runtime.h"
#include "AndroidUtil.h"
#include "EventEmitter.h"
#include "JNIUtil.h"
#include "V8Util.h"
#include "KrollJavaScript.h"
#include "KrollProxy.h"
#include "TypeConverter.h"
#include "APIModule.h"
#include "ScriptsModule.h"
#define TAG "V8Runtime"
namespace titanium {
/* static */
void V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)
{
jobject v8Object = (jobject) parameter;
ref.Dispose();
JNIUtil::getJNIEnv()->DeleteGlobalRef(v8Object);
}
/* static */
jobject V8Runtime::newObject(Handle<Object> object)
{
HandleScope scope;
LOGI(TAG, "Creating new object...");
JNIEnv *env = JNIUtil::getJNIEnv();
if (!env) return NULL;
jlong ptr = reinterpret_cast<jlong>(*Persistent<Object>::New(object));jobject
v8Object = env->NewGlobalRef(env->NewObject(JNIUtil::v8ObjectClass, JNIUtil::v8ObjectInitMethod, ptr));
// make a 2nd persistent weakref so we can be informed of GC
Persistent<Object> weakRef = Persistent<Object>::New(object);
weakRef.MakeWeak(reinterpret_cast<void*>(v8Object), V8Runtime::collectWeakRef);
return v8Object;
}
static Persistent<Object> global;
static Handle<Value> binding(const Arguments& args)
{
static Persistent<Object> binding_cache;
HandleScope scope;
Local<String> module = args[0]->ToString();
String::Utf8Value module_v(module);
if (binding_cache.IsEmpty()) {
binding_cache = Persistent<Object>::New(Object::New());
}
Local<Object> exports;
if (binding_cache->Has(module)) {
exports = binding_cache->Get(module)->ToObject();
} else if (!strcmp(*module_v, "natives")) {
exports = Object::New();
KrollJavaScript::DefineNatives(exports);
binding_cache->Set(module, exports);
} else if (!strcmp(*module_v, "evals")) {
exports = Object::New();
ScriptsModule::Initialize(exports);
binding_cache->Set(module, exports);
} else {
return ThrowException(Exception::Error(String::New("No such module")));
}
return scope.Close(exports);
}
/* static */
void V8Runtime::bootstrap()
{
Local<FunctionTemplate> global_template = FunctionTemplate::New();
EventEmitter::Initialize(global_template);
global = Persistent<Object>::New(global_template->GetFunction()->NewInstance());
global->Set(String::NewSymbol("binding"), FunctionTemplate::New(binding)->GetFunction());
global->Set(String::NewSymbol("EventEmitter"), EventEmitter::constructorTemplate->GetFunction());
global->Set(String::NewSymbol("API"), APIModule::init());
TryCatch try_catch;
Handle<Value> result = ExecuteString(KrollJavaScript::MainSource(), IMMUTABLE_STRING_LITERAL("kroll.js"));
if (try_catch.HasCaught()) {
ReportException(try_catch, true);
JNIUtil::terminateVM();
}
if (!result->IsFunction()) {
LOGF(TAG, "kroll.js result is not a function");
ReportException(try_catch, true);
JNIUtil::terminateVM();
}
Handle<Function> mainFunction = Handle<Function>::Cast(result);
Local<Object> global = v8::Context::GetCurrent()->Global();
Local<Value> args[] = { Local<Value>::New(global) };
mainFunction->Call(global, 1, args);
if (try_catch.HasCaught()) {
ReportException(try_catch, true);
JNIUtil::terminateVM();
}
}
}
static jobject jruntime;
static Persistent<Context> context;
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: init
* Signature: (Lorg/appcelerator/kroll/runtime/v8/V8Runtime;)V
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_init(JNIEnv *env, jclass clazz, jobject self)
{
LOGD("init", "-------1:");
jruntime = env->NewGlobalRef(self);
LOGD("init", "-------2:");
titanium::JNIUtil::initCache(env);
LOGD("init", "-------3");
V8::Initialize();
LOGD("init", "-------4");
HandleScope scope;
LOGD("init", "-------5");
context = Context::New();
LOGD("init", "-------6:");
Context::Scope context_scope(context);
LOGD("init", "-------7:");
titanium::V8Runtime::bootstrap();
LOGD("init", "-------8");
titanium::initKrollProxy();
LOGD("init", "-------9");
}
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_evalData(JNIEnv *env, jclass clazz, jcharArray buffer, jstring filename)
{
HandleScope scope;
if (!buffer) {
// TODO throw exception
return;
}
jint len = env->GetArrayLength(buffer);
jchar *pchars = (jchar*) env->GetPrimitiveArrayCritical(buffer, 0);
if (!pchars) {
// TODO throw exception
return;
}
Handle<String> jsFilename = titanium::TypeConverter::javaStringToJsString(filename);
ScriptOrigin origin(jsFilename);
v8::Handle<v8::String> jsString = v8::String::New(pchars, len);
v8::Handle<v8::Script> script = Script::New(jsString, &origin);
env->ReleasePrimitiveArrayCritical(buffer, pchars, 0);
script->Run();
}
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: dispose
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_dispose(JNIEnv *env, jclass clazz)
{
context.Dispose();
V8::Dispose();
env->DeleteGlobalRef(jruntime);
jruntime = NULL;
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
titanium::JNIUtil::javaVm = vm;
return JNI_VERSION_1_4;
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <algorithm>
#include <string>
#include <sstream>
#include "LIEF/MachO/hash.hpp"
#include "LIEF/MachO/BuildVersion.hpp"
#include "LIEF/MachO/EnumToString.hpp"
#include "enums_wrapper.hpp"
#include "pyMachO.hpp"
#define PY_ENUM(x) LIEF::MachO::to_string(x), x
namespace LIEF {
namespace MachO {
template<class T>
using getter_t = T (BuildVersion::*)(void) const;
template<class T>
using setter_t = void (BuildVersion::*)(T);
template<>
void create<BuildVersion>(py::module& m) {
py::class_<BuildVersion, LoadCommand> cls(m, "BuildVersion");
py::class_<BuildToolVersion, LIEF::Object> tool_version_cls(m, "BuildToolVersion");
// Build Tool Version
// ==================
tool_version_cls
.def_property_readonly("tool",
&BuildToolVersion::tool,
"" RST_CLASS_REF(.BuildeVersion.TOOLS) " type")
.def_property_readonly("version",
&BuildToolVersion::version,
"Version of the tool")
.def("__eq__", &BuildToolVersion::operator==)
.def("__ne__", &BuildToolVersion::operator!=)
.def("__hash__",
[] (const BuildToolVersion& version) {
return Hash::hash(version);
})
.def("__str__",
[] (const BuildToolVersion& version)
{
std::ostringstream stream;
stream << version;
return stream.str();
});
LIEF::enum_<BuildToolVersion::TOOLS>(tool_version_cls, "TOOLS")
.value(PY_ENUM(BuildToolVersion::TOOLS::UNKNOWN))
.value(PY_ENUM(BuildToolVersion::TOOLS::CLANG))
.value(PY_ENUM(BuildToolVersion::TOOLS::SWIFT))
.value(PY_ENUM(BuildToolVersion::TOOLS::LD));
cls
.def_property("platform",
static_cast<getter_t<BuildVersion::PLATFORMS>>(&BuildVersion::platform),
static_cast<setter_t<BuildVersion::PLATFORMS>>(&BuildVersion::platform),
"Target " RST_CLASS_REF(.BuildVersion.PLATFORMS) "")
.def_property("minos",
static_cast<getter_t<BuildVersion::version_t>>(&BuildVersion::minos),
static_cast<setter_t<BuildVersion::version_t>>(&BuildVersion::minos),
"Minimal OS version on which this binary was built to run")
.def_property("sdk",
static_cast<getter_t<BuildVersion::version_t>>(&BuildVersion::minos),
static_cast<setter_t<BuildVersion::version_t>>(&BuildVersion::minos),
"SDK Version")
.def_property_readonly("tools",
static_cast<getter_t<BuildVersion::tools_list_t>>(&BuildVersion::tools),
"List of " RST_CLASS_REF(BuildToolVersion) " used when while this binary")
.def("__eq__", &BuildVersion::operator==)
.def("__ne__", &BuildVersion::operator!=)
.def("__hash__",
[] (const BuildVersion& version) {
return Hash::hash(version);
})
.def("__str__",
[] (const BuildVersion& version)
{
std::ostringstream stream;
stream << version;
return stream.str();
});
LIEF::enum_<BuildVersion::PLATFORMS>(cls, "PLATFORMS")
.value(PY_ENUM(BuildVersion::PLATFORMS::UNKNOWN))
.value(PY_ENUM(BuildVersion::PLATFORMS::MACOS))
.value(PY_ENUM(BuildVersion::PLATFORMS::IOS))
.value(PY_ENUM(BuildVersion::PLATFORMS::TVOS))
.value(PY_ENUM(BuildVersion::PLATFORMS::WATCHOS));
}
}
}
<commit_msg>Fix typo BuildeVersion => BuildVersion which may lead to my link failures<commit_after>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <algorithm>
#include <string>
#include <sstream>
#include "LIEF/MachO/hash.hpp"
#include "LIEF/MachO/BuildVersion.hpp"
#include "LIEF/MachO/EnumToString.hpp"
#include "enums_wrapper.hpp"
#include "pyMachO.hpp"
#define PY_ENUM(x) LIEF::MachO::to_string(x), x
namespace LIEF {
namespace MachO {
template<class T>
using getter_t = T (BuildVersion::*)(void) const;
template<class T>
using setter_t = void (BuildVersion::*)(T);
template<>
void create<BuildVersion>(py::module& m) {
py::class_<BuildVersion, LoadCommand> cls(m, "BuildVersion");
py::class_<BuildToolVersion, LIEF::Object> tool_version_cls(m, "BuildToolVersion");
// Build Tool Version
// ==================
tool_version_cls
.def_property_readonly("tool",
&BuildToolVersion::tool,
"" RST_CLASS_REF(.BuildVersion.TOOLS) " type")
.def_property_readonly("version",
&BuildToolVersion::version,
"Version of the tool")
.def("__eq__", &BuildToolVersion::operator==)
.def("__ne__", &BuildToolVersion::operator!=)
.def("__hash__",
[] (const BuildToolVersion& version) {
return Hash::hash(version);
})
.def("__str__",
[] (const BuildToolVersion& version)
{
std::ostringstream stream;
stream << version;
return stream.str();
});
LIEF::enum_<BuildToolVersion::TOOLS>(tool_version_cls, "TOOLS")
.value(PY_ENUM(BuildToolVersion::TOOLS::UNKNOWN))
.value(PY_ENUM(BuildToolVersion::TOOLS::CLANG))
.value(PY_ENUM(BuildToolVersion::TOOLS::SWIFT))
.value(PY_ENUM(BuildToolVersion::TOOLS::LD));
cls
.def_property("platform",
static_cast<getter_t<BuildVersion::PLATFORMS>>(&BuildVersion::platform),
static_cast<setter_t<BuildVersion::PLATFORMS>>(&BuildVersion::platform),
"Target " RST_CLASS_REF(.BuildVersion.PLATFORMS) "")
.def_property("minos",
static_cast<getter_t<BuildVersion::version_t>>(&BuildVersion::minos),
static_cast<setter_t<BuildVersion::version_t>>(&BuildVersion::minos),
"Minimal OS version on which this binary was built to run")
.def_property("sdk",
static_cast<getter_t<BuildVersion::version_t>>(&BuildVersion::minos),
static_cast<setter_t<BuildVersion::version_t>>(&BuildVersion::minos),
"SDK Version")
.def_property_readonly("tools",
static_cast<getter_t<BuildVersion::tools_list_t>>(&BuildVersion::tools),
"List of " RST_CLASS_REF(BuildToolVersion) " used when while this binary")
.def("__eq__", &BuildVersion::operator==)
.def("__ne__", &BuildVersion::operator!=)
.def("__hash__",
[] (const BuildVersion& version) {
return Hash::hash(version);
})
.def("__str__",
[] (const BuildVersion& version)
{
std::ostringstream stream;
stream << version;
return stream.str();
});
LIEF::enum_<BuildVersion::PLATFORMS>(cls, "PLATFORMS")
.value(PY_ENUM(BuildVersion::PLATFORMS::UNKNOWN))
.value(PY_ENUM(BuildVersion::PLATFORMS::MACOS))
.value(PY_ENUM(BuildVersion::PLATFORMS::IOS))
.value(PY_ENUM(BuildVersion::PLATFORMS::TVOS))
.value(PY_ENUM(BuildVersion::PLATFORMS::WATCHOS));
}
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <limits>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <queue>
class Token {
public:
int source;
double cost;
Token(): source(-1), cost(std::numeric_limits<double>::max()) {};
Token(int src, double cst): source(src), cost(cst) {};
Token(const Token& orig) { this->source=orig.source; this->cost=orig.cost; };
};
bool operator< (const Token& token1, const Token &token2)
{
return token1.cost > token2.cost;
}
bool operator> (const Token& token1, const Token &token2)
{
return token1.cost < token2.cost;
}
typedef std::priority_queue<Token> Node;
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " <vocabulary>" << std::endl;
exit(0);
}
std::ifstream vocabfile(argv[1]);
if (!vocabfile) exit(1);
std::cerr << "Reading vocabulary " << argv[1] << std::endl;
double count;
int maxlen = 0;
std::string line, word;
std::map<std::string, double> vocab;
while (getline(vocabfile, line)) {
std::stringstream ss(line);
ss >> count;
ss >> word;
vocab[word] = count;
maxlen = std::max(maxlen, int(word.length()));
}
vocabfile.close();
std::cerr << "\t" << "size: " << vocab.size() << std::endl;
std::cerr << "\t" << "maximum string length: " << maxlen << std::endl;
std::cerr << "Segmenting corpus" << std::endl;
std::vector<std::string> best_path;
while (getline(std::cin, line)) {
std::cerr << "Segmenting sentence: " << line << std::endl;
std::vector<Node> search(line.length());
int start_pos = 0;
int end_pos = 0;
int len = 0;
for (int i=0; i<line.length(); i++) {
// std::cerr << "end index: " << i << std::endl;
// Iterate all factor ending in this position
for (int j=std::max(0, i-maxlen); j<=i; j++) {
start_pos = j;
end_pos = i+1;
len = end_pos-start_pos;
// std::cerr << "trying indices: " << start_pos << " " << end_pos << std::endl;
// std::cerr << "trying factor: " << line.substr(start_pos, len) << std::endl;
if (vocab.find(line.substr(start_pos, len)) != vocab.end()) {
std::cerr << "factor: " << line.substr(start_pos, len) << " cost: " << vocab[line.substr(start_pos, len)] << std::endl;
Token tok(j, vocab[line.substr(start_pos, len)]);
if (i > 0) {
if (search[j].size() > 0) {
Token source_top = search[j].top();
tok.cost += source_top.cost;
}
}
else {
tok.source = -1;
}
search[i].push(tok);
}
}
std::cerr << std::endl;
}
// Look up the best path
int target = search.size()-1;
Token top = search[target].top();
int source = top.source;
while (true) {
best_path.push_back(line.substr(source+1, target-source));
if (source == -1) break;
target = source;
Token top = search[target].top();
source = top.source;
}
// Print out the best path
for (int i=best_path.size()-1; i<0; i--)
std::cout << best_path[i] << " ";
std::cout << best_path[0] << std::endl;
best_path.clear();
}
exit(1);
}
<commit_msg>Version which produces some splits.<commit_after>#include <algorithm>
#include <limits>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <queue>
class Token {
public:
int source;
double cost;
Token(): source(-1), cost(std::numeric_limits<double>::max()) {};
Token(int src, double cst): source(src), cost(cst) {};
Token(const Token& orig) { this->source=orig.source; this->cost=orig.cost; };
};
// Note just changed > to < ..
bool operator< (const Token& token1, const Token &token2)
{
return token1.cost < token2.cost;
}
typedef std::priority_queue<Token> Node;
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " <vocabulary>" << std::endl;
exit(0);
}
std::ifstream vocabfile(argv[1]);
if (!vocabfile) exit(1);
std::cerr << "Reading vocabulary " << argv[1] << std::endl;
double count;
int maxlen = 0;
std::string line, word;
std::map<std::string, double> vocab;
while (getline(vocabfile, line)) {
std::stringstream ss(line);
ss >> count;
ss >> word;
vocab[word] = count;
maxlen = std::max(maxlen, int(word.length()));
}
vocabfile.close();
std::cerr << "\t" << "size: " << vocab.size() << std::endl;
std::cerr << "\t" << "maximum string length: " << maxlen << std::endl;
std::cerr << "Segmenting corpus" << std::endl;
std::vector<std::string> best_path;
while (getline(std::cin, line)) {
std::vector<Node> search(line.length());
int start_pos = 0;
int end_pos = 0;
int len = 0;
for (int i=0; i<line.length(); i++) {
// Iterate all factors ending in this position
for (int j=std::max(0, i-maxlen); j<=i; j++) {
start_pos = j;
end_pos = i+1;
len = end_pos-start_pos;
if (vocab.find(line.substr(start_pos, len)) != vocab.end()) {
Token tok(j-1, vocab[line.substr(start_pos, len)]);
if (i > 0 && search[j].size() > 0) {
Token source_top = search[j].top();
tok.cost += source_top.cost;
}
search[i].push(tok);
}
}
}
// Look up the best path
int target = search.size()-1;
Token top = search[target].top();
int source = top.source;
while (true) {
best_path.push_back(line.substr(source+1, target-source));
if (source < 0) break;
target = source;
Token top = search[target].top();
source = top.source;
}
// Print out the best path
for (int i=best_path.size()-1; i>0; i--)
std::cout << best_path[i] << " ";
std::cout << best_path[0] << std::endl;
best_path.clear();
}
exit(1);
}
<|endoftext|> |
<commit_before><commit_msg>All things done well<commit_after><|endoftext|> |
<commit_before><commit_msg>Some minor cleaning up [ci skip].<commit_after><|endoftext|> |
<commit_before>/**
* @file device_properties.hxx
* @author Cameron Shinn (ctshinn@ucdavis.edu)
* @brief
* @version 0.1
* @date 2020-11-09
*
* @copyright Copyright (c) 2020
*
*/
#pragma once
#include <type_traits>
namespace gunrock {
namespace cuda {
/**
* @brief Struct holding kernel parameters will be passed in upon launch
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*
* @todo dimensions should be dim3 instead of unsigned int
*/
template<
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct launch_params_t {
enum : unsigned int {
block_dimensions = block_dimensions_,
grid_dimensions = grid_dimensions_,
shared_memory_bytes = shared_memory_bytes_
};
};
#define TEST_SM 75 // Temporary until we figure out how to get cabability combined
/**
* @brief Struct holding kernel parameters for a specific SM version
* @tparam combined_ver_ Combined major and minor compute capability version
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*/
template<
unsigned int combined_ver_,
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct sm_launch_params_t : launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {
enum : unsigned int {combined_ver = combined_ver_};
};
// Alias fallback with SM version 0 (which isn't real)
template<
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct fallback_launch_params_t : sm_launch_params_t<
0,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {};
// Easier declaration inside launch box template
template<
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using fallback_t = fallback_launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Easier declaration inside launch box template
template<
unsigned int combined_ver_,
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using sm_t = sm_launch_params_t<
combined_ver_,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Define named sm_launch_params_t structs for each SM version
#define SM_LAUNCH_PARAMS(combined) \
template< \
unsigned int block_dimensions_, \
unsigned int grid_dimensions_, \
unsigned int shared_memory_bytes_ = 0 \
> \
using sm_##combined##_t = sm_launch_params_t< \
combined, \
block_dimensions_, \
grid_dimensions_, \
shared_memory_bytes_ \
>;
SM_LAUNCH_PARAMS(86)
SM_LAUNCH_PARAMS(80)
SM_LAUNCH_PARAMS(75)
SM_LAUNCH_PARAMS(72)
SM_LAUNCH_PARAMS(70)
SM_LAUNCH_PARAMS(62)
SM_LAUNCH_PARAMS(61)
SM_LAUNCH_PARAMS(60)
SM_LAUNCH_PARAMS(53)
SM_LAUNCH_PARAMS(52)
SM_LAUNCH_PARAMS(50)
SM_LAUNCH_PARAMS(37)
SM_LAUNCH_PARAMS(35)
SM_LAUNCH_PARAMS(30)
#undef SM_LAUNCH_PARAMS
template<typename... sm_lp_v>
struct device_launch_params_t;
// 1st to (N-1)th sm_launch_param_t template parameters
template<typename sm_lp_t, typename... sm_lp_v>
struct device_launch_params_t<sm_lp_t, sm_lp_v...> :
std::conditional_t<
sm_lp_t::combined_ver == 0,
device_launch_params_t<sm_lp_v..., sm_lp_t>, // If found, move fallback_launch_params_t to end of template parameter pack
std::conditional_t< // Otherwise check sm_lp_t for device's SM version
sm_lp_t::combined_ver == TEST_SM,
sm_lp_t,
device_launch_params_t<sm_lp_v...>
>
> {};
// Nth sm_launch_param_t template parameter
// Throws an error if the launch box can't find a launch_params_t to use (no fallback and can't find corresponding SM)
// In that case I'd think we might want to throw our own error somehow
template<typename sm_lp_t>
struct device_launch_params_t<sm_lp_t> :
std::enable_if_t<
sm_lp_t::combined_ver == TEST_SM || sm_lp_t::combined_ver == 0, // Throws a compile-time error (that mostly reads like jibberish) if this line is false
sm_lp_t
> {};
/**
* @brief Collection of kernel launch parameters for multiple architectures
* @tparam sm_lp_v... Pack of sm_launch_params_t types for each desired arch
*/
template<typename... sm_lp_v>
struct launch_box_t : device_launch_params_t<sm_lp_v...> {
// Some methods to make it easy to access launch_params
};
} // namespace gunrock
} // namespace cuda
<commit_msg>Add error when launch params for device not found<commit_after>/**
* @file device_properties.hxx
* @author Cameron Shinn (ctshinn@ucdavis.edu)
* @brief
* @version 0.1
* @date 2020-11-09
*
* @copyright Copyright (c) 2020
*
*/
#pragma once
#include <type_traits>
namespace gunrock {
namespace cuda {
/**
* @brief Struct holding kernel parameters will be passed in upon launch
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*
* @todo dimensions should be dim3 instead of unsigned int
*/
template<
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct launch_params_t {
enum : unsigned int {
block_dimensions = block_dimensions_,
grid_dimensions = grid_dimensions_,
shared_memory_bytes = shared_memory_bytes_
};
};
#define TEST_SM 75 // Temporary until we figure out how to get cabability combined
/**
* @brief Struct holding kernel parameters for a specific SM version
* @tparam combined_ver_ Combined major and minor compute capability version
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*/
template<
unsigned int combined_ver_,
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct sm_launch_params_t : launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {
enum : unsigned int {combined_ver = combined_ver_};
};
// Alias fallback with SM version 0 (which isn't real)
template<
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct fallback_launch_params_t : sm_launch_params_t<
0,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {};
// Easier declaration inside launch box template
template<
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using fallback_t = fallback_launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Easier declaration inside launch box template
template<
unsigned int combined_ver_,
unsigned int block_dimensions_,
unsigned int grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using sm_t = sm_launch_params_t<
combined_ver_,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Define named sm_launch_params_t structs for each SM version
#define SM_LAUNCH_PARAMS(combined) \
template< \
unsigned int block_dimensions_, \
unsigned int grid_dimensions_, \
unsigned int shared_memory_bytes_ = 0 \
> \
using sm_##combined##_t = sm_launch_params_t< \
combined, \
block_dimensions_, \
grid_dimensions_, \
shared_memory_bytes_ \
>;
SM_LAUNCH_PARAMS(86)
SM_LAUNCH_PARAMS(80)
SM_LAUNCH_PARAMS(75)
SM_LAUNCH_PARAMS(72)
SM_LAUNCH_PARAMS(70)
SM_LAUNCH_PARAMS(62)
SM_LAUNCH_PARAMS(61)
SM_LAUNCH_PARAMS(60)
SM_LAUNCH_PARAMS(53)
SM_LAUNCH_PARAMS(52)
SM_LAUNCH_PARAMS(50)
SM_LAUNCH_PARAMS(37)
SM_LAUNCH_PARAMS(35)
SM_LAUNCH_PARAMS(30)
#undef SM_LAUNCH_PARAMS
template<typename... sm_lp_v>
struct device_launch_params_t;
// 1st to (N-1)th sm_launch_param_t template parameters
template<typename sm_lp_t, typename... sm_lp_v>
struct device_launch_params_t<sm_lp_t, sm_lp_v...> :
std::conditional_t<
sm_lp_t::combined_ver == 0,
device_launch_params_t<sm_lp_v..., sm_lp_t>, // If found, move fallback_launch_params_t to end of template parameter pack
std::conditional_t< // Otherwise check sm_lp_t for device's SM version
sm_lp_t::combined_ver == TEST_SM,
sm_lp_t,
device_launch_params_t<sm_lp_v...>
>
> {};
//////////////// https://stackoverflow.com/a/3926854
// "false" but dependent on a template parameter so the compiler can't optimize it for static_assert()
template<typename T>
struct always_false {
enum { value = false };
};
// Raises static (compile-time) assert when referenced
template<typename T>
struct raise_not_found_error_t {
static_assert(always_false<T>::value, "launch_box_t could not find valid launch_params_t");
};
////////////////
// Nth sm_launch_param_t template parameter
template<typename sm_lp_t>
struct device_launch_params_t<sm_lp_t> :
std::conditional_t<
sm_lp_t::combined_ver == TEST_SM || sm_lp_t::combined_ver == 0,
sm_lp_t,
raise_not_found_error_t<void> // Raises a compiler error
> {};
/**
* @brief Collection of kernel launch parameters for multiple architectures
* @tparam sm_lp_v... Pack of sm_launch_params_t types for each desired arch
*/
template<typename... sm_lp_v>
struct launch_box_t : device_launch_params_t<sm_lp_v...> {
// Some methods to make it easy to access launch_params
};
} // namespace gunrock
} // namespace cuda
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2017 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: joaander
/*! \file NeighborListGPU.cc
\brief Implementation of the NeighborListGPU class
*/
#include "NeighborListGPU.h"
#include "NeighborListGPU.cuh"
namespace py = pybind11;
#ifdef ENABLE_MPI
#include "hoomd/Communicator.h"
#endif
#include "hoomd/CachedAllocator.h"
#include <iostream>
using namespace std;
/*! \param num_iters Number of iterations to average for the benchmark
\returns Milliseconds of execution time per calculation
Calls filterNlist repeatedly to benchmark the neighbor list filter step.
*/
double NeighborListGPU::benchmarkFilter(unsigned int num_iters)
{
ClockSource t;
// warm up run
forceUpdate();
compute(0);
buildNlist(0);
filterNlist();
#ifdef ENABLE_CUDA
if(m_exec_conf->isCUDAEnabled())
{
cudaThreadSynchronize();
CHECK_CUDA_ERROR();
}
#endif
// benchmark
uint64_t start_time = t.getTime();
for (unsigned int i = 0; i < num_iters; i++)
filterNlist();
#ifdef ENABLE_CUDA
if(m_exec_conf->isCUDAEnabled())
cudaThreadSynchronize();
#endif
uint64_t total_time_ns = t.getTime() - start_time;
// convert the run time to milliseconds
return double(total_time_ns) / 1e6 / double(num_iters);
}
void NeighborListGPU::buildNlist(unsigned int timestep)
{
m_exec_conf->msg->error() << "nlist: O(N^2) neighbor lists are no longer supported." << endl;
throw runtime_error("Error updating neighborlist bins");
}
bool NeighborListGPU::distanceCheck(unsigned int timestep)
{
// prevent against unnecessary calls
if (! shouldCheckDistance(timestep))
{
return false;
}
// scan through the particle data arrays and calculate distances
if (m_prof) m_prof->push(m_exec_conf, "dist-check");
// access data
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
BoxDim box = m_pdata->getBox();
ArrayHandle<Scalar4> d_last_pos(m_last_pos, access_location::device, access_mode::read);
// get current global nearest plane distance
Scalar3 L_g = m_pdata->getGlobalBox().getNearestPlaneDistance();
// Find direction of maximum box length contraction (smallest eigenvalue of deformation tensor)
Scalar3 lambda = L_g / m_last_L;
Scalar lambda_min = (lambda.x < lambda.y) ? lambda.x : lambda.y;
lambda_min = (lambda_min < lambda.z) ? lambda_min : lambda.z;
ArrayHandle<Scalar> d_rcut_max(m_rcut_max, access_location::device, access_mode::read);
gpu_nlist_needs_update_check_new(m_flags.getDeviceFlags(),
d_last_pos.data,
d_pos.data,
m_pdata->getN(),
box,
d_rcut_max.data,
m_r_buff,
m_pdata->getNTypes(),
lambda_min,
lambda,
++m_checkn);
if(m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
if (m_prof) m_prof->pop(m_exec_conf);
bool result = m_flags.readFlags() == m_checkn;
#ifdef ENABLE_MPI
if (m_pdata->getDomainDecomposition())
{
if (m_prof) m_prof->push(m_exec_conf,"MPI allreduce");
// check if migrate criterium is fulfilled on any rank
int local_result = result ? 1 : 0;
int global_result = 0;
MPI_Allreduce(&local_result,
&global_result,
1,
MPI_INT,
MPI_MAX,
m_exec_conf->getMPICommunicator());
result = (global_result > 0);
if (m_prof) m_prof->pop();
}
#endif
return result;
}
/*! Calls gpu_nlsit_filter() to filter the neighbor list on the GPU
*/
void NeighborListGPU::filterNlist()
{
if (m_prof)
m_prof->push(m_exec_conf, "filter");
// access data
ArrayHandle<unsigned int> d_n_ex_idx(m_n_ex_idx, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_ex_list_idx(m_ex_list_idx, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_n_neigh(m_n_neigh, access_location::device, access_mode::readwrite);
ArrayHandle<unsigned int> d_nlist(m_nlist, access_location::device, access_mode::readwrite);
ArrayHandle<unsigned int> d_head_list(m_head_list, access_location::device, access_mode::read);
m_tuner_filter->begin();
gpu_nlist_filter(d_n_neigh.data,
d_nlist.data,
d_head_list.data,
d_n_ex_idx.data,
d_ex_list_idx.data,
m_ex_list_indexer,
m_pdata->getN(),
m_tuner_filter->getParam());
if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR();
m_tuner_filter->end();
if (m_prof)
m_prof->pop(m_exec_conf);
}
//! Update the exclusion list on the GPU
void NeighborListGPU::updateExListIdx()
{
assert(! m_need_reallocate_exlist);
if (m_prof)
m_prof->push(m_exec_conf,"update-ex");
ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_n_ex_tag(m_n_ex_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_ex_list_tag(m_ex_list_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_n_ex_idx(m_n_ex_idx, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_ex_list_idx(m_ex_list_idx, access_location::device, access_mode::overwrite);
gpu_update_exclusion_list(d_tag.data,
d_rtag.data,
d_n_ex_tag.data,
d_ex_list_tag.data,
m_ex_list_indexer_tag,
d_n_ex_idx.data,
d_ex_list_idx.data,
m_ex_list_indexer,
m_pdata->getN());
if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR();
if (m_prof)
m_prof->pop(m_exec_conf);
}
//! Build the head list for neighbor list indexing on the GPU
void NeighborListGPU::buildHeadList()
{
// don't do anything if there are no particles owned by this rank
if (!m_pdata->getN())
return;
if (m_prof) m_prof->push(exec_conf, "head-list");
ArrayHandle<unsigned int> d_head_list(m_head_list, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_Nmax(m_Nmax, access_location::device, access_mode::read);
m_req_size_nlist.resetFlags(0);
m_tuner_head_list->begin();
gpu_nlist_build_head_list(d_head_list.data,
m_req_size_nlist.getDeviceFlags(),
d_Nmax.data,
d_pos.data,
m_pdata->getN(),
m_pdata->getNTypes(),
m_tuner_head_list->getParam());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_head_list->end();
unsigned int req_size_nlist = m_req_size_nlist.readFlags();
resizeNlist(req_size_nlist);
if (m_prof) m_prof->pop(exec_conf);
}
void export_NeighborListGPU(py::module& m)
{
py::class_<NeighborListGPU, std::shared_ptr<NeighborListGPU> >(m, "NeighborListGPU", py::base<NeighborList>())
.def(py::init< std::shared_ptr<SystemDefinition>, Scalar, Scalar >())
.def("benchmarkFilter", &NeighborListGPU::benchmarkFilter)
;
}
<commit_msg>Moving the NeighborListGPU::dist_check profiler::pop include reading flags and MPI in the profiling.<commit_after>// Copyright (c) 2009-2017 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: joaander
/*! \file NeighborListGPU.cc
\brief Implementation of the NeighborListGPU class
*/
#include "NeighborListGPU.h"
#include "NeighborListGPU.cuh"
namespace py = pybind11;
#ifdef ENABLE_MPI
#include "hoomd/Communicator.h"
#endif
#include "hoomd/CachedAllocator.h"
#include <iostream>
using namespace std;
/*! \param num_iters Number of iterations to average for the benchmark
\returns Milliseconds of execution time per calculation
Calls filterNlist repeatedly to benchmark the neighbor list filter step.
*/
double NeighborListGPU::benchmarkFilter(unsigned int num_iters)
{
ClockSource t;
// warm up run
forceUpdate();
compute(0);
buildNlist(0);
filterNlist();
#ifdef ENABLE_CUDA
if(m_exec_conf->isCUDAEnabled())
{
cudaThreadSynchronize();
CHECK_CUDA_ERROR();
}
#endif
// benchmark
uint64_t start_time = t.getTime();
for (unsigned int i = 0; i < num_iters; i++)
filterNlist();
#ifdef ENABLE_CUDA
if(m_exec_conf->isCUDAEnabled())
cudaThreadSynchronize();
#endif
uint64_t total_time_ns = t.getTime() - start_time;
// convert the run time to milliseconds
return double(total_time_ns) / 1e6 / double(num_iters);
}
void NeighborListGPU::buildNlist(unsigned int timestep)
{
m_exec_conf->msg->error() << "nlist: O(N^2) neighbor lists are no longer supported." << endl;
throw runtime_error("Error updating neighborlist bins");
}
bool NeighborListGPU::distanceCheck(unsigned int timestep)
{
// prevent against unnecessary calls
if (! shouldCheckDistance(timestep))
{
return false;
}
// scan through the particle data arrays and calculate distances
if (m_prof) m_prof->push(m_exec_conf, "dist-check");
// access data
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
BoxDim box = m_pdata->getBox();
ArrayHandle<Scalar4> d_last_pos(m_last_pos, access_location::device, access_mode::read);
// get current global nearest plane distance
Scalar3 L_g = m_pdata->getGlobalBox().getNearestPlaneDistance();
// Find direction of maximum box length contraction (smallest eigenvalue of deformation tensor)
Scalar3 lambda = L_g / m_last_L;
Scalar lambda_min = (lambda.x < lambda.y) ? lambda.x : lambda.y;
lambda_min = (lambda_min < lambda.z) ? lambda_min : lambda.z;
ArrayHandle<Scalar> d_rcut_max(m_rcut_max, access_location::device, access_mode::read);
gpu_nlist_needs_update_check_new(m_flags.getDeviceFlags(),
d_last_pos.data,
d_pos.data,
m_pdata->getN(),
box,
d_rcut_max.data,
m_r_buff,
m_pdata->getNTypes(),
lambda_min,
lambda,
++m_checkn);
if(m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
bool result = m_flags.readFlags() == m_checkn;
#ifdef ENABLE_MPI
if (m_pdata->getDomainDecomposition())
{
if (m_prof) m_prof->push(m_exec_conf,"MPI allreduce");
// check if migrate criterium is fulfilled on any rank
int local_result = result ? 1 : 0;
int global_result = 0;
MPI_Allreduce(&local_result,
&global_result,
1,
MPI_INT,
MPI_MAX,
m_exec_conf->getMPICommunicator());
result = (global_result > 0);
if (m_prof) m_prof->pop();
}
#endif
if (m_prof) m_prof->pop(m_exec_conf);
return result;
}
/*! Calls gpu_nlsit_filter() to filter the neighbor list on the GPU
*/
void NeighborListGPU::filterNlist()
{
if (m_prof)
m_prof->push(m_exec_conf, "filter");
// access data
ArrayHandle<unsigned int> d_n_ex_idx(m_n_ex_idx, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_ex_list_idx(m_ex_list_idx, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_n_neigh(m_n_neigh, access_location::device, access_mode::readwrite);
ArrayHandle<unsigned int> d_nlist(m_nlist, access_location::device, access_mode::readwrite);
ArrayHandle<unsigned int> d_head_list(m_head_list, access_location::device, access_mode::read);
m_tuner_filter->begin();
gpu_nlist_filter(d_n_neigh.data,
d_nlist.data,
d_head_list.data,
d_n_ex_idx.data,
d_ex_list_idx.data,
m_ex_list_indexer,
m_pdata->getN(),
m_tuner_filter->getParam());
if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR();
m_tuner_filter->end();
if (m_prof)
m_prof->pop(m_exec_conf);
}
//! Update the exclusion list on the GPU
void NeighborListGPU::updateExListIdx()
{
assert(! m_need_reallocate_exlist);
if (m_prof)
m_prof->push(m_exec_conf,"update-ex");
ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_n_ex_tag(m_n_ex_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_ex_list_tag(m_ex_list_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_n_ex_idx(m_n_ex_idx, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_ex_list_idx(m_ex_list_idx, access_location::device, access_mode::overwrite);
gpu_update_exclusion_list(d_tag.data,
d_rtag.data,
d_n_ex_tag.data,
d_ex_list_tag.data,
m_ex_list_indexer_tag,
d_n_ex_idx.data,
d_ex_list_idx.data,
m_ex_list_indexer,
m_pdata->getN());
if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR();
if (m_prof)
m_prof->pop(m_exec_conf);
}
//! Build the head list for neighbor list indexing on the GPU
void NeighborListGPU::buildHeadList()
{
// don't do anything if there are no particles owned by this rank
if (!m_pdata->getN())
return;
if (m_prof) m_prof->push(exec_conf, "head-list");
ArrayHandle<unsigned int> d_head_list(m_head_list, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_Nmax(m_Nmax, access_location::device, access_mode::read);
m_req_size_nlist.resetFlags(0);
m_tuner_head_list->begin();
gpu_nlist_build_head_list(d_head_list.data,
m_req_size_nlist.getDeviceFlags(),
d_Nmax.data,
d_pos.data,
m_pdata->getN(),
m_pdata->getNTypes(),
m_tuner_head_list->getParam());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_head_list->end();
unsigned int req_size_nlist = m_req_size_nlist.readFlags();
resizeNlist(req_size_nlist);
if (m_prof) m_prof->pop(exec_conf);
}
void export_NeighborListGPU(py::module& m)
{
py::class_<NeighborListGPU, std::shared_ptr<NeighborListGPU> >(m, "NeighborListGPU", py::base<NeighborList>())
.def(py::init< std::shared_ptr<SystemDefinition>, Scalar, Scalar >())
.def("benchmarkFilter", &NeighborListGPU::benchmarkFilter)
;
}
<|endoftext|> |
<commit_before>#include <stan/agrad/rev/functions/pow.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
TEST(AgradRev,pow_var_var) {
AVAR a(3.0);
AVAR b(4.0);
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(81.0,f.val());
AVEC x = createAVEC(a,b);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(4.0 * pow(3.0,4.0-1.0), g[0]);
EXPECT_FLOAT_EQ(log(3.0) * pow(3.0,4.0), g[1]);
}
TEST(AgradRev,pow_var_double) {
AVAR a(3.0);
double b = 4.0;
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(81.0,f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(4.0 * pow(3.0,4.0-1.0), g[0]);
}
TEST(AgradRev,pow_double_var) {
double a = 3.0;
AVAR b(4.0);
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(81.0,f.val());
AVEC x = createAVEC(b);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(log(3.0) * pow(3.0,4.0), g[0]);
}
TEST(AgradRev,pow_boundry) {
double inf = std::numeric_limits<double>::infinity();
AVAR a = inf;
AVAR b = 5;
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(inf, f.val());
AVAR g = pow(b,a);
EXPECT_FLOAT_EQ(inf, g.val());
AVAR c = -inf;
AVAR d = 6;
AVAR h = pow(c,b);
EXPECT_FLOAT_EQ(-inf, h.val());
AVAR i = pow(c,d);
EXPECT_FLOAT_EQ(inf, i.val());
AVAR j = pow(b,c);
EXPECT_FLOAT_EQ( 0.0 ,j.val());
}
<commit_msg>added NaN test for pow<commit_after>#include <stan/agrad/rev/functions/pow.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
#include <test/unit-agrad-rev/nan_util.hpp>
#include <stan/meta/traits.hpp>
TEST(AgradRev,pow_var_var) {
AVAR a(3.0);
AVAR b(4.0);
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(81.0,f.val());
AVEC x = createAVEC(a,b);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(4.0 * pow(3.0,4.0-1.0), g[0]);
EXPECT_FLOAT_EQ(log(3.0) * pow(3.0,4.0), g[1]);
}
TEST(AgradRev,pow_var_double) {
AVAR a(3.0);
double b = 4.0;
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(81.0,f.val());
AVEC x = createAVEC(a);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(4.0 * pow(3.0,4.0-1.0), g[0]);
}
TEST(AgradRev,pow_double_var) {
double a = 3.0;
AVAR b(4.0);
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(81.0,f.val());
AVEC x = createAVEC(b);
VEC g;
f.grad(x,g);
EXPECT_FLOAT_EQ(log(3.0) * pow(3.0,4.0), g[0]);
}
TEST(AgradRev,pow_boundry) {
double inf = std::numeric_limits<double>::infinity();
AVAR a = inf;
AVAR b = 5;
AVAR f = pow(a,b);
EXPECT_FLOAT_EQ(inf, f.val());
AVAR g = pow(b,a);
EXPECT_FLOAT_EQ(inf, g.val());
AVAR c = -inf;
AVAR d = 6;
AVAR h = pow(c,b);
EXPECT_FLOAT_EQ(-inf, h.val());
AVAR i = pow(c,d);
EXPECT_FLOAT_EQ(inf, i.val());
AVAR j = pow(b,c);
EXPECT_FLOAT_EQ( 0.0 ,j.val());
}
struct pow_fun {
template <typename T0, typename T1>
inline
typename stan::return_type<T0,T1>::type
operator()(const T0& arg1,
const T1& arg2) const {
return pow(arg1,arg2);
}
};
TEST(AgradRev, pow_nan) {
pow_fun pow_;
test_nan(pow_,3.0,5.0,false, false);
}
<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <uv.h>
#include <string>
#include <sstream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "../../message.h"
#include "../../log.h"
#include "../../lock.h"
using std::string;
using std::wstring;
using std::ostringstream;
using std::unique_ptr;
using std::shared_ptr;
using std::default_delete;
using std::map;
using std::pair;
using std::make_pair;
using std::vector;
using std::move;
using std::endl;
const DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;
const DWORD NETWORK_BUFFER_SIZE = 64 * 1024;
static void CALLBACK command_perform_helper(__in ULONG_PTR payload);
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);
static Result<string> to_utf8(const wstring &in);
static Result<wstring> to_wchar(const string &in);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix, DWORD error_code);
class WindowsWorkerPlatform;
class Subscription {
public:
Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :
channel{channel},
platform{platform},
path{path},
root{root},
buffer_size{DEFAULT_BUFFER_SIZE},
buffer{new BYTE[buffer_size]},
written{new BYTE[buffer_size]}
{
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
overlapped.hEvent = this;
}
~Subscription()
{
CloseHandle(root);
}
Result<> schedule()
{
int success = ReadDirectoryChangesW(
root, // root directory handle
buffer.get(), // result buffer
buffer_size, // result buffer size
TRUE, // recursive
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES
| FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS
| FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, // change flags
NULL, // bytes returned
&overlapped, // overlapped
&event_helper // completion routine
);
if (!success) {
return windows_error_result<>("Unable to subscribe to filesystem events");
}
return ok_result();
}
Result<> use_network_size()
{
if (buffer_size <= NETWORK_BUFFER_SIZE) {
ostringstream out("Buffer size of ");
out
<< buffer_size
<< " is already lower than the network buffer size "
<< NETWORK_BUFFER_SIZE;
return error_result(out.str());
}
buffer_size = NETWORK_BUFFER_SIZE;
buffer.reset(new BYTE[buffer_size]);
written.reset(new BYTE[buffer_size]);
return ok_result();
}
ChannelID get_channel() const {
return channel;
}
WindowsWorkerPlatform* get_platform() const {
return platform;
}
BYTE *get_written(DWORD written_size) {
memcpy(written.get(), buffer.get(), written_size);
return written.get();
}
string make_absolute(const string &sub_path)
{
ostringstream out;
out << path;
if (path.back() != '\\' && sub_path.front() != '\\') {
out << '\\';
}
out << sub_path;
return out.str();
}
private:
ChannelID channel;
WindowsWorkerPlatform *platform;
string path;
HANDLE root;
OVERLAPPED overlapped;
DWORD buffer_size;
unique_ptr<BYTE[]> buffer;
unique_ptr<BYTE[]> written;
};
class WindowsWorkerPlatform : public WorkerPlatform {
public:
WindowsWorkerPlatform(WorkerThread *thread) :
WorkerPlatform(thread),
thread_handle{0}
{
int err;
err = uv_mutex_init(&thread_handle_mutex);
if (err) {
report_uv_error(err);
}
};
~WindowsWorkerPlatform() override
{
uv_mutex_destroy(&thread_handle_mutex);
}
Result<> wake() override
{
Lock lock(thread_handle_mutex);
if (!thread_handle) {
return ok_result();
}
BOOL success = QueueUserAPC(
command_perform_helper,
thread_handle,
reinterpret_cast<ULONG_PTR>(this)
);
if (!success) {
return windows_error_result<>("Unable to queue APC");
}
return ok_result();
}
Result<> listen() override
{
{
Lock lock(thread_handle_mutex);
HANDLE pseudo_handle = GetCurrentThread();
BOOL success = DuplicateHandle(
GetCurrentProcess(), // Source process
pseudo_handle, // Source handle
GetCurrentProcess(), // Destination process
&thread_handle, // Destination handle
0, // Desired access
FALSE, // Inheritable by new processes
DUPLICATE_SAME_ACCESS // options
);
if (!success) {
Result<> r = windows_error_result<>("Unable to duplicate thread handle");
report_error("Unable to acquire thread handle");
return r;
}
}
while (true) {
SleepEx(INFINITE, true);
}
report_error("listen loop ended unexpectedly");
return health_err_result();
}
Result<> handle_add_command(const ChannelID channel, const string &root_path)
{
// Convert the path to a wide-character string
Result<wstring> convr = to_wchar(root_path);
if (convr.is_error()) return convr.propagate<>();
wstring &root_path_w = convr.get_value();
// Open a directory handle
HANDLE root = CreateFileW(
root_path_w.c_str(), // null-terminated wchar file name
FILE_LIST_DIRECTORY, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // flags and attributes
NULL // template file
);
if (root == INVALID_HANDLE_VALUE) {
return windows_error_result<>("Unable to open directory handle");
}
// Allocate and persist the subscription
Subscription *sub = new Subscription(channel, root, root_path, this);
auto insert_result = subscriptions.insert(make_pair(channel, sub));
if (!insert_result.second) {
delete sub;
ostringstream msg("Channel collision: ");
msg << channel;
return error_result(msg.str());
}
LOGGER << "Now watching directory " << root_path << "." << endl;
return sub->schedule();
}
Result<> handle_remove_command(const ChannelID channel)
{
return ok_result();
}
Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)
{
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
// Handle errors.
if (error_code == ERROR_OPERATION_ABORTED) {
LOGGER << "Operation aborted." << endl;
subscriptions.erase(it);
delete sub;
return ok_result();
}
if (error_code == ERROR_INVALID_PARAMETER) {
Result<> resize = sub->use_network_size();
if (resize.is_error()) return resize;
return sub->schedule();
}
if (error_code == ERROR_NOTIFY_ENUM_DIR) {
LOGGER << "Change buffer overflow. Some events may have been lost." << endl;
return sub->schedule();
}
if (error_code != ERROR_SUCCESS) {
return windows_error_result<>("Completion callback error", error_code);
}
// Schedule the next completion callback.
BYTE *base = sub->get_written(num_bytes);
Result<> next = sub->schedule();
if (next.is_error()) {
report_error(string(next.get_error()));
}
// Process received events.
vector<Message> messages;
bool old_path_seen = false;
string old_path;
while (true) {
PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);
wstring wpath{info->FileName, info->FileNameLength};
Result<string> u8r = to_utf8(wpath);
if (u8r.is_error()) {
LOGGER << "Skipping path: " << u8r << "." << endl;
} else {
string path = sub->make_absolute(u8r.get_value());
switch (info->Action) {
case FILE_ACTION_ADDED:
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_MODIFIED:
{
FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_REMOVED:
{
FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_RENAMED_OLD_NAME:
old_path_seen = true;
old_path = move(path);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
if (old_path_seen) {
// Old name received first
{
FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
old_path_seen = false;
} else {
// No old name. Treat it as a creation
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
}
break;
default:
LOGGER << "Skipping unexpected action " << info->Action << "." << endl;
break;
}
}
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) {
LOGGER << "Unable to emit messages: " << er << "." << endl;
}
}
return next;
}
private:
uv_mutex_t thread_handle_mutex;
HANDLE thread_handle;
map<ChannelID, Subscription*> subscriptions;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));
}
void CALLBACK command_perform_helper(__in ULONG_PTR payload)
{
WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform*>(payload);
platform->handle_commands();
}
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)
{
Subscription *sub = static_cast<Subscription*>(overlapped->hEvent);
Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);
if (r.is_error()) {
LOGGER << "Unable to handle filesystem events: " << r << "." << endl;
}
}
Result<string> to_utf8(const wstring &in)
{
size_t len = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
nullptr, // destination string, null to measure
0, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!len) {
return windows_error_result<string>("Unable to measure string as UTF-8");
}
unique_ptr<char[]> payload(new char[len]);
size_t copied = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
payload.get(), // destination string
len, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!copied) {
return windows_error_result<string>("Unable to convert string to UTF-8");
}
return ok_result(string(payload.get(), len));
}
Result<wstring> to_wchar(const string &in)
{
size_t wlen = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags
in.c_str(), // source string data
-1, // source string length (null-terminated)
0, // output buffer
0 // output buffer size
);
if (wlen == 0) {
return windows_error_result<wstring>("Unable to measure string as wide string");
}
unique_ptr<WCHAR[]> payload(new WCHAR[wlen]);
size_t conv_success = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags,
in.c_str(), // source string data
-1, // source string length (null-terminated)
payload.get(), // output buffer
wlen // output buffer size (in bytes)
);
if (!conv_success) {
return windows_error_result<wstring>("Unable to convert string to wide string");
}
return ok_result(wstring(payload.get(), wlen - 1));
}
template < class V >
Result<V> windows_error_result(const string &prefix)
{
return windows_error_result<V>(prefix, GetLastError());
}
template < class V >
Result<V> windows_error_result(const string &prefix, DWORD error_code)
{
LPVOID msg_buffer;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, // source
error_code, // message ID
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // language ID
(LPSTR) &msg_buffer, // output buffer
0, // size
NULL // arguments
);
ostringstream msg;
msg << prefix << "\n (" << error_code << ") " << (char*) msg_buffer;
LocalFree(msg_buffer);
return Result<V>::make_error(msg.str());
}
<commit_msg>Use wide strings in Subscription::make_absolute<commit_after>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <uv.h>
#include <string>
#include <sstream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "../../message.h"
#include "../../log.h"
#include "../../lock.h"
using std::string;
using std::wstring;
using std::ostringstream;
using std::wostringstream;
using std::unique_ptr;
using std::shared_ptr;
using std::default_delete;
using std::map;
using std::pair;
using std::make_pair;
using std::vector;
using std::move;
using std::endl;
const DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;
const DWORD NETWORK_BUFFER_SIZE = 64 * 1024;
static void CALLBACK command_perform_helper(__in ULONG_PTR payload);
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);
static Result<string> to_utf8(const wstring &in);
static Result<wstring> to_wchar(const string &in);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix);
template < class V = void* >
static Result<V> windows_error_result(const string &prefix, DWORD error_code);
class WindowsWorkerPlatform;
class Subscription {
public:
Subscription(
ChannelID channel,
HANDLE root,
const wstring &path,
WindowsWorkerPlatform *platform
) :
channel{channel},
platform{platform},
path{path},
root{root},
buffer_size{DEFAULT_BUFFER_SIZE},
buffer{new BYTE[buffer_size]},
written{new BYTE[buffer_size]}
{
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
overlapped.hEvent = this;
}
~Subscription()
{
CloseHandle(root);
}
Result<> schedule()
{
int success = ReadDirectoryChangesW(
root, // root directory handle
buffer.get(), // result buffer
buffer_size, // result buffer size
TRUE, // recursive
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES
| FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS
| FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, // change flags
NULL, // bytes returned
&overlapped, // overlapped
&event_helper // completion routine
);
if (!success) {
return windows_error_result<>("Unable to subscribe to filesystem events");
}
return ok_result();
}
Result<> use_network_size()
{
if (buffer_size <= NETWORK_BUFFER_SIZE) {
ostringstream out("Buffer size of ");
out
<< buffer_size
<< " is already lower than the network buffer size "
<< NETWORK_BUFFER_SIZE;
return error_result(out.str());
}
buffer_size = NETWORK_BUFFER_SIZE;
buffer.reset(new BYTE[buffer_size]);
written.reset(new BYTE[buffer_size]);
return ok_result();
}
ChannelID get_channel() const {
return channel;
}
WindowsWorkerPlatform* get_platform() const {
return platform;
}
BYTE *get_written(DWORD written_size) {
memcpy(written.get(), buffer.get(), written_size);
return written.get();
}
wstring make_absolute(const wstring &sub_path)
{
wostringstream out;
out << path;
if (path.back() != L'\\' && sub_path.front() != L'\\') {
out << L'\\';
}
out << sub_path;
return out.str();
}
private:
ChannelID channel;
WindowsWorkerPlatform *platform;
wstring path;
HANDLE root;
OVERLAPPED overlapped;
DWORD buffer_size;
unique_ptr<BYTE[]> buffer;
unique_ptr<BYTE[]> written;
};
class WindowsWorkerPlatform : public WorkerPlatform {
public:
WindowsWorkerPlatform(WorkerThread *thread) :
WorkerPlatform(thread),
thread_handle{0}
{
int err;
err = uv_mutex_init(&thread_handle_mutex);
if (err) {
report_uv_error(err);
}
};
~WindowsWorkerPlatform() override
{
uv_mutex_destroy(&thread_handle_mutex);
}
Result<> wake() override
{
Lock lock(thread_handle_mutex);
if (!thread_handle) {
return ok_result();
}
BOOL success = QueueUserAPC(
command_perform_helper,
thread_handle,
reinterpret_cast<ULONG_PTR>(this)
);
if (!success) {
return windows_error_result<>("Unable to queue APC");
}
return ok_result();
}
Result<> listen() override
{
{
Lock lock(thread_handle_mutex);
HANDLE pseudo_handle = GetCurrentThread();
BOOL success = DuplicateHandle(
GetCurrentProcess(), // Source process
pseudo_handle, // Source handle
GetCurrentProcess(), // Destination process
&thread_handle, // Destination handle
0, // Desired access
FALSE, // Inheritable by new processes
DUPLICATE_SAME_ACCESS // options
);
if (!success) {
Result<> r = windows_error_result<>("Unable to duplicate thread handle");
report_error("Unable to acquire thread handle");
return r;
}
}
while (true) {
SleepEx(INFINITE, true);
}
report_error("listen loop ended unexpectedly");
return health_err_result();
}
Result<> handle_add_command(const ChannelID channel, const string &root_path)
{
// Convert the path to a wide-character string
Result<wstring> convr = to_wchar(root_path);
if (convr.is_error()) return convr.propagate<>();
wstring &root_path_w = convr.get_value();
// Open a directory handle
HANDLE root = CreateFileW(
root_path_w.c_str(), // null-terminated wchar file name
FILE_LIST_DIRECTORY, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // flags and attributes
NULL // template file
);
if (root == INVALID_HANDLE_VALUE) {
return windows_error_result<>("Unable to open directory handle");
}
// Allocate and persist the subscription
Subscription *sub = new Subscription(channel, root, root_path_w, this);
auto insert_result = subscriptions.insert(make_pair(channel, sub));
if (!insert_result.second) {
delete sub;
ostringstream msg("Channel collision: ");
msg << channel;
return error_result(msg.str());
}
LOGGER << "Now watching directory " << root_path << "." << endl;
return sub->schedule();
}
Result<> handle_remove_command(const ChannelID channel)
{
return ok_result();
}
Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)
{
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
// Handle errors.
if (error_code == ERROR_OPERATION_ABORTED) {
LOGGER << "Operation aborted." << endl;
subscriptions.erase(it);
delete sub;
return ok_result();
}
if (error_code == ERROR_INVALID_PARAMETER) {
Result<> resize = sub->use_network_size();
if (resize.is_error()) return resize;
return sub->schedule();
}
if (error_code == ERROR_NOTIFY_ENUM_DIR) {
LOGGER << "Change buffer overflow. Some events may have been lost." << endl;
return sub->schedule();
}
if (error_code != ERROR_SUCCESS) {
return windows_error_result<>("Completion callback error", error_code);
}
// Schedule the next completion callback.
BYTE *base = sub->get_written(num_bytes);
Result<> next = sub->schedule();
if (next.is_error()) {
report_error(string(next.get_error()));
}
// Process received events.
vector<Message> messages;
bool old_path_seen = false;
string old_path;
while (true) {
PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);
wstring wpath{info->FileName, info->FileNameLength};
Result<string> u8r = to_utf8(wpath);
if (u8r.is_error()) {
LOGGER << "Skipping path: " << u8r << "." << endl;
} else {
string path = sub->make_absolute(u8r.get_value());
switch (info->Action) {
case FILE_ACTION_ADDED:
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_MODIFIED:
{
FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_REMOVED:
{
FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
break;
case FILE_ACTION_RENAMED_OLD_NAME:
old_path_seen = true;
old_path = move(path);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
if (old_path_seen) {
// Old name received first
{
FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
old_path_seen = false;
} else {
// No old name. Treat it as a creation
{
FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), "");
Message message(move(payload));
LOGGER << "Emitting filesystem message " << message << "." << endl;
messages.push_back(move(message));
}
}
break;
default:
LOGGER << "Skipping unexpected action " << info->Action << "." << endl;
break;
}
}
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) {
LOGGER << "Unable to emit messages: " << er << "." << endl;
}
}
return next;
}
private:
uv_mutex_t thread_handle_mutex;
HANDLE thread_handle;
map<ChannelID, Subscription*> subscriptions;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));
}
void CALLBACK command_perform_helper(__in ULONG_PTR payload)
{
WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform*>(payload);
platform->handle_commands();
}
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)
{
Subscription *sub = static_cast<Subscription*>(overlapped->hEvent);
Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);
if (r.is_error()) {
LOGGER << "Unable to handle filesystem events: " << r << "." << endl;
}
}
Result<string> to_utf8(const wstring &in)
{
size_t len = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
nullptr, // destination string, null to measure
0, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!len) {
return windows_error_result<string>("Unable to measure string as UTF-8");
}
unique_ptr<char[]> payload(new char[len]);
size_t copied = WideCharToMultiByte(
CP_UTF8, // code page
0, // flags
in.data(), // source string
in.size(), // source string length
payload.get(), // destination string
len, // destination string length
nullptr, // default char
nullptr // used default char
);
if (!copied) {
return windows_error_result<string>("Unable to convert string to UTF-8");
}
return ok_result(string(payload.get(), len));
}
Result<wstring> to_wchar(const string &in)
{
size_t wlen = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags
in.c_str(), // source string data
-1, // source string length (null-terminated)
0, // output buffer
0 // output buffer size
);
if (wlen == 0) {
return windows_error_result<wstring>("Unable to measure string as wide string");
}
unique_ptr<WCHAR[]> payload(new WCHAR[wlen]);
size_t conv_success = MultiByteToWideChar(
CP_UTF8, // code page
0, // flags,
in.c_str(), // source string data
-1, // source string length (null-terminated)
payload.get(), // output buffer
wlen // output buffer size (in bytes)
);
if (!conv_success) {
return windows_error_result<wstring>("Unable to convert string to wide string");
}
return ok_result(wstring(payload.get(), wlen - 1));
}
template < class V >
Result<V> windows_error_result(const string &prefix)
{
return windows_error_result<V>(prefix, GetLastError());
}
template < class V >
Result<V> windows_error_result(const string &prefix, DWORD error_code)
{
LPVOID msg_buffer;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, // source
error_code, // message ID
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // language ID
(LPSTR) &msg_buffer, // output buffer
0, // size
NULL // arguments
);
ostringstream msg;
msg << prefix << "\n (" << error_code << ") " << (char*) msg_buffer;
LocalFree(msg_buffer);
return Result<V>::make_error(msg.str());
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_ERR_IS_LOWER_TRIANGULAR_HPP
#define STAN_MATH_PRIM_MAT_ERR_IS_LOWER_TRIANGULAR_HPP
#include <Eigen/Dense>
#include <math.h>
namespace stan {
namespace math {
double notNan(double x) { return std::isnan(x) ? 1.0 : x; }
/**
* Return <code>true</code> is matrix is lower triangular.
* A matrix x is not lower triangular if there is a non-zero entry
* x[m, n] with m < n. This function only inspect the upper and
* triangular portion of the matrix, not including the diagonal.
* @tparam T Type of scalar of the matrix, requires class method
* <code>.rows()</code> and <code>.cols()</code>
* @param y Matrix to test
* @return <code>true</code> is matrix is lower triangular
*/
template <typename T_y>
inline bool is_lower_triangular(
const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y) {
Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic> m
= y.unaryExpr(std::ptr_fun(notNan));
return m.transpose().isUpperTriangular();
}
} // namespace math
} // namespace stan
#endif
<commit_msg>jenkins build failure<commit_after>#ifndef STAN_MATH_PRIM_MAT_ERR_IS_LOWER_TRIANGULAR_HPP
#define STAN_MATH_PRIM_MAT_ERR_IS_LOWER_TRIANGULAR_HPP
#include <Eigen/Dense>
#include <math.h>
namespace stan {
namespace math {
double notLowerNan(double x) { return std::isnan(x) ? 1.0 : x; }
/**
* Return <code>true</code> is matrix is lower triangular.
* A matrix x is not lower triangular if there is a non-zero entry
* x[m, n] with m < n. This function only inspect the upper and
* triangular portion of the matrix, not including the diagonal.
* @tparam T Type of scalar of the matrix, requires class method
* <code>.rows()</code> and <code>.cols()</code>
* @param y Matrix to test
* @return <code>true</code> is matrix is lower triangular
*/
template <typename T_y>
inline bool is_lower_triangular(
const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y) {
Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic> m
= y.unaryExpr(std::ptr_fun(notLowerNan));
return m.transpose().isUpperTriangular();
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkMacro.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbMeanShiftSmoothingImageFilter.h"
#include "otbDifferenceImageFilter.h"
#include "otbMultiChannelExtractROI.h"
#include <iomanip>
int otbMeanShiftSmoothingImageFilterSpatialStability(int argc, char * argv[])
{
if (argc != 10)
{
std::cerr << "Usage: " << argv[0] <<
" infname spatialdifffname spectraldifffname spatialBandwidth rangeBandwidth threshold maxiterationnumber startx starty sizex sizey"
<< std::endl;
return EXIT_FAILURE;
}
const char * infname = argv[1];
const double spatialBandwidth = atof(argv[2]);
const double rangeBandwidth = atof(argv[3]);
const double threshold = atof(argv[4]);
const unsigned int maxiterationnumber = atoi(argv[5]);
const unsigned int startX = atoi(argv[6]);
const unsigned int startY = atoi(argv[7]);
const unsigned int sizeX = atoi(argv[8]);
const unsigned int sizeY = atoi(argv[9]);
/* maxit - threshold */
const unsigned int Dimension = 2;
typedef float PixelType;
typedef double KernelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::MeanShiftSmoothingImageFilter<ImageType, ImageType> FilterType;
typedef FilterType::OutputIterationImageType IterationImageType;
typedef FilterType::OutputSpatialImageType SpatialImageType;
typedef SpatialImageType::InternalPixelType SpatialPixelType;
typedef FilterType::OutputLabelImageType LabelImageType;
typedef otb::MultiChannelExtractROI<PixelType,PixelType> ExtractROIFilterType;
typedef otb::MultiChannelExtractROI<SpatialPixelType,SpatialPixelType> SpatialExtractROIFilterType;
typedef otb::DifferenceImageFilter<ImageType,ImageType> SubtractFilterType;
typedef otb::DifferenceImageFilter<SpatialImageType,SpatialImageType> SpatialSubtractFilterType;
// Instantiating object
FilterType::Pointer MSfilter = FilterType::New();
FilterType::Pointer MSfilterROI = FilterType::New();
ExtractROIFilterType::Pointer filterROI = ExtractROIFilterType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
//first pipeline
// Set filter parameters
MSfilter->SetSpatialBandwidth(spatialBandwidth);
MSfilter->SetRangeBandwidth(rangeBandwidth);
MSfilter->SetThreshold(threshold);
MSfilter->SetMaxIterationNumber(maxiterationnumber);
MSfilter->SetInput(reader->GetOutput());
MSfilter->SetModeSearch(false);
MSfilter->Update();
//second pipeline
filterROI->SetInput(reader->GetOutput());
filterROI->SetStartX(startX);
filterROI->SetStartY(startY);
filterROI->SetSizeX(sizeX);
filterROI->SetSizeY(sizeY);
filterROI->UpdateOutputInformation();
MSfilterROI->SetSpatialBandwidth(spatialBandwidth);
MSfilterROI->SetRangeBandwidth(rangeBandwidth);
MSfilterROI->SetThreshold(threshold);
MSfilterROI->SetMaxIterationNumber(maxiterationnumber);
MSfilterROI->SetInput(filterROI->GetOutput());
MSfilterROI->SetModeSearch(false);
// GlobalShift ensure spatial stability
ImageType::IndexType globalShift;
globalShift[0]=startX;
globalShift[1]=startY;
MSfilterROI->SetGlobalShift(globalShift);
//compare output
const unsigned int border=maxiterationnumber*spatialBandwidth+1;
const unsigned int startXROI2=border;
const unsigned int startXROI=border+startX;
const unsigned int startYROI2=border;
const unsigned int startYROI=border+startY;
const unsigned int sizeXROI=sizeX-2*border;
const unsigned int sizeYROI=sizeY-2*border;
SpatialExtractROIFilterType::Pointer filterROISpatial1 = SpatialExtractROIFilterType::New();
filterROISpatial1->SetInput(MSfilter->GetSpatialOutput());
filterROISpatial1->SetStartX(startXROI);
filterROISpatial1->SetStartY(startYROI);
filterROISpatial1->SetSizeX(sizeXROI);
filterROISpatial1->SetSizeY(sizeYROI);
SpatialExtractROIFilterType::Pointer filterROISpatial2 = SpatialExtractROIFilterType::New();
filterROISpatial2->SetInput(MSfilterROI->GetSpatialOutput());
filterROISpatial2->SetStartX(startXROI2);
filterROISpatial2->SetStartY(startYROI2);
filterROISpatial2->SetSizeX(sizeXROI);
filterROISpatial2->SetSizeY(sizeYROI);
SpatialSubtractFilterType::Pointer filterSubSpatial = SpatialSubtractFilterType::New();
filterSubSpatial->SetValidInput(filterROISpatial1->GetOutput());
filterSubSpatial->SetTestInput(filterROISpatial2->GetOutput());
filterSubSpatial->Update();
SpatialImageType::PixelType spatialOutputDiff = filterSubSpatial->GetTotalDifference();
ExtractROIFilterType::Pointer filterROISpectral1 = ExtractROIFilterType::New();
filterROISpectral1->SetInput(MSfilter->GetRangeOutput());
filterROISpectral1->SetStartX(startXROI);
filterROISpectral1->SetStartY(startYROI);
filterROISpectral1->SetSizeX(sizeXROI);
filterROISpectral1->SetSizeY(sizeYROI);
ExtractROIFilterType::Pointer filterROISpectral2 = ExtractROIFilterType::New();
filterROISpectral2->SetInput(MSfilterROI->GetRangeOutput());
filterROISpectral2->SetStartX(startXROI2);
filterROISpectral2->SetStartY(startYROI2);
filterROISpectral2->SetSizeX(sizeXROI);
filterROISpectral2->SetSizeY(sizeYROI);
SubtractFilterType::Pointer filterSubSpectral = SubtractFilterType::New();
filterSubSpectral->SetValidInput(filterROISpectral1->GetOutput());
filterSubSpectral->SetTestInput(filterROISpectral2->GetOutput());
filterSubSpectral->Update();
ImageType::PixelType spectralOutputDiff = filterSubSpectral->GetTotalDifference();
bool spatialUnstable = false;
bool spectralUnstable = false;
for(unsigned int i = 0; i < spectralOutputDiff.Size(); ++i)
{
if(spatialOutputDiff[i] > 0)
{
spatialUnstable = true;
}
}
for(unsigned int i = 0; i < spectralOutputDiff.Size(); ++i)
{
if(spectralOutputDiff[i] > 0)
{
spectralUnstable = true;
}
}
std::cerr<<std::setprecision(10);
if(spatialUnstable)
{
std::cerr<<"Spatial output is unstable (total difference = "<<spatialOutputDiff<<")"<<std::endl;
}
if(spectralUnstable)
{
std::cerr<<"Spectral output is unstable (total difference = "<<spectralOutputDiff<<")"<<std::endl;
}
if(spatialUnstable || spectralUnstable)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>TEST: small error in test (should fix failing platforms)<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkMacro.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbMeanShiftSmoothingImageFilter.h"
#include "otbDifferenceImageFilter.h"
#include "otbMultiChannelExtractROI.h"
#include <iomanip>
int otbMeanShiftSmoothingImageFilterSpatialStability(int argc, char * argv[])
{
if (argc != 10)
{
std::cerr << "Usage: " << argv[0] <<
" infname spatialdifffname spectraldifffname spatialBandwidth rangeBandwidth threshold maxiterationnumber startx starty sizex sizey"
<< std::endl;
return EXIT_FAILURE;
}
const char * infname = argv[1];
const double spatialBandwidth = atof(argv[2]);
const double rangeBandwidth = atof(argv[3]);
const double threshold = atof(argv[4]);
const unsigned int maxiterationnumber = atoi(argv[5]);
const unsigned int startX = atoi(argv[6]);
const unsigned int startY = atoi(argv[7]);
const unsigned int sizeX = atoi(argv[8]);
const unsigned int sizeY = atoi(argv[9]);
/* maxit - threshold */
const unsigned int Dimension = 2;
typedef float PixelType;
typedef double KernelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::MeanShiftSmoothingImageFilter<ImageType, ImageType> FilterType;
typedef FilterType::OutputIterationImageType IterationImageType;
typedef FilterType::OutputSpatialImageType SpatialImageType;
typedef SpatialImageType::InternalPixelType SpatialPixelType;
typedef FilterType::OutputLabelImageType LabelImageType;
typedef otb::MultiChannelExtractROI<PixelType,PixelType> ExtractROIFilterType;
typedef otb::MultiChannelExtractROI<SpatialPixelType,SpatialPixelType> SpatialExtractROIFilterType;
typedef otb::DifferenceImageFilter<ImageType,ImageType> SubtractFilterType;
typedef otb::DifferenceImageFilter<SpatialImageType,SpatialImageType> SpatialSubtractFilterType;
// Instantiating object
FilterType::Pointer MSfilter = FilterType::New();
FilterType::Pointer MSfilterROI = FilterType::New();
ExtractROIFilterType::Pointer filterROI = ExtractROIFilterType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
//first pipeline
// Set filter parameters
MSfilter->SetSpatialBandwidth(spatialBandwidth);
MSfilter->SetRangeBandwidth(rangeBandwidth);
MSfilter->SetThreshold(threshold);
MSfilter->SetMaxIterationNumber(maxiterationnumber);
MSfilter->SetInput(reader->GetOutput());
MSfilter->SetModeSearch(false);
MSfilter->Update();
//second pipeline
filterROI->SetInput(reader->GetOutput());
filterROI->SetStartX(startX);
filterROI->SetStartY(startY);
filterROI->SetSizeX(sizeX);
filterROI->SetSizeY(sizeY);
filterROI->UpdateOutputInformation();
MSfilterROI->SetSpatialBandwidth(spatialBandwidth);
MSfilterROI->SetRangeBandwidth(rangeBandwidth);
MSfilterROI->SetThreshold(threshold);
MSfilterROI->SetMaxIterationNumber(maxiterationnumber);
MSfilterROI->SetInput(filterROI->GetOutput());
MSfilterROI->SetModeSearch(false);
// GlobalShift ensure spatial stability
ImageType::IndexType globalShift;
globalShift[0]=startX;
globalShift[1]=startY;
MSfilterROI->SetGlobalShift(globalShift);
//compare output
const unsigned int border=maxiterationnumber*spatialBandwidth+1;
const unsigned int startXROI2=border;
const unsigned int startXROI=border+startX;
const unsigned int startYROI2=border;
const unsigned int startYROI=border+startY;
const unsigned int sizeXROI=sizeX-2*border;
const unsigned int sizeYROI=sizeY-2*border;
SpatialExtractROIFilterType::Pointer filterROISpatial1 = SpatialExtractROIFilterType::New();
filterROISpatial1->SetInput(MSfilter->GetSpatialOutput());
filterROISpatial1->SetStartX(startXROI);
filterROISpatial1->SetStartY(startYROI);
filterROISpatial1->SetSizeX(sizeXROI);
filterROISpatial1->SetSizeY(sizeYROI);
SpatialExtractROIFilterType::Pointer filterROISpatial2 = SpatialExtractROIFilterType::New();
filterROISpatial2->SetInput(MSfilterROI->GetSpatialOutput());
filterROISpatial2->SetStartX(startXROI2);
filterROISpatial2->SetStartY(startYROI2);
filterROISpatial2->SetSizeX(sizeXROI);
filterROISpatial2->SetSizeY(sizeYROI);
SpatialSubtractFilterType::Pointer filterSubSpatial = SpatialSubtractFilterType::New();
filterSubSpatial->SetValidInput(filterROISpatial1->GetOutput());
filterSubSpatial->SetTestInput(filterROISpatial2->GetOutput());
filterSubSpatial->Update();
SpatialImageType::PixelType spatialOutputDiff = filterSubSpatial->GetTotalDifference();
ExtractROIFilterType::Pointer filterROISpectral1 = ExtractROIFilterType::New();
filterROISpectral1->SetInput(MSfilter->GetRangeOutput());
filterROISpectral1->SetStartX(startXROI);
filterROISpectral1->SetStartY(startYROI);
filterROISpectral1->SetSizeX(sizeXROI);
filterROISpectral1->SetSizeY(sizeYROI);
ExtractROIFilterType::Pointer filterROISpectral2 = ExtractROIFilterType::New();
filterROISpectral2->SetInput(MSfilterROI->GetRangeOutput());
filterROISpectral2->SetStartX(startXROI2);
filterROISpectral2->SetStartY(startYROI2);
filterROISpectral2->SetSizeX(sizeXROI);
filterROISpectral2->SetSizeY(sizeYROI);
SubtractFilterType::Pointer filterSubSpectral = SubtractFilterType::New();
filterSubSpectral->SetValidInput(filterROISpectral1->GetOutput());
filterSubSpectral->SetTestInput(filterROISpectral2->GetOutput());
filterSubSpectral->Update();
ImageType::PixelType spectralOutputDiff = filterSubSpectral->GetTotalDifference();
bool spatialUnstable = false;
bool spectralUnstable = false;
for(unsigned int i = 0; i < spatialOutputDiff.Size(); ++i)
{
if(spatialOutputDiff[i] > 0)
{
spatialUnstable = true;
}
}
for(unsigned int i = 0; i < spectralOutputDiff.Size(); ++i)
{
if(spectralOutputDiff[i] > 0)
{
spectralUnstable = true;
}
}
std::cerr<<std::setprecision(10);
if(spatialUnstable)
{
std::cerr<<"Spatial output is unstable (total difference = "<<spatialOutputDiff<<")"<<std::endl;
}
if(spectralUnstable)
{
std::cerr<<"Spectral output is unstable (total difference = "<<spectralOutputDiff<<")"<<std::endl;
}
if(spatialUnstable || spectralUnstable)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "aerial_autonomy/controller_connectors/qrotor_backstepping_controller_connector.h"
#include "aerial_autonomy/tests/test_utils.h"
#include <quad_simulator_parser/quad_simulator.h>
#include <gtest/gtest.h>
using namespace quad_simulator;
using namespace test_utils;
class QrotorBacksteppingControllerConnectorTests : public ::testing::Test {
public:
/* Todo Constructor
*/
/* Todo QrotorBacksteppingControllerConfig config;
*/
/* Todo reset unique_ptr
*/
controller_.reset(new QrotorBacksteppingController(config);
controller_connector_.reset(new QrotorBacksteppingControllerConnector(drone_hardware_, *controller_, thrust_gain_estimator_, config, std::chrono::milliseconds(20)));
drone_hardware_.usePerfectTime();
/* Todo static void SetUpTestCase()
*/
/* Todo void runUntilConvergence()
*/
QuadSimulator drone_hardware_;
std::unique_ptr<QrotorBacksteppingController> controller_;
std::unique_ptr<QrotorBacksteppingControllerConnector> controller_connector_;
ThrustGainEstimator thrust_gain_estimator_;
};
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Add unit_tests for the connector<commit_after>#include "aerial_autonomy/controller_connectors/qrotor_backstepping_controller_connector.h"
#include "aerial_autonomy/controllers/qrotor_backstepping_controller.h"
#include "aerial_autonomy/log/log.h"
#include "aerial_autonomy/tests/test_utils.h"
#include "aerial_autonomy/types/minimum_snap_reference_trajectory.h"
#include <gcop/hrotor.h>
#include <quad_simulator_parser/quad_simulator.h>
#include <gtest/gtest.h>
using namespace quad_simulator;
using namespace gcop;
using namespace test_utils;
class QrotorBacksteppingControllerConnectorTests : public ::testing::Test {
public:
/* Todo Constructor
*/
QrotorBacksteppingControllerConnectorTests()
: thrust_gain_estimator_(0.14), sys() {
// QrotorBacksteppingControllerConfig config;
config_.set_mass(sys.m);
config_.set_jxx(sys.J(0));
config_.set_jyy(sys.J(1));
config_.set_jzz(sys.J(2));
config_.set_k2(2);
config_.set_k1(2);
config_.set_kp_xy(1000);
config_.set_kp_z(4000);
config_.set_kd_xy(0.2);
config_.set_kd_z(0.2);
// auto vel_tolerance = config_.mutable_goal_velocity_tolerance();
// vel_tolerance->set_vx(0.05);
// vel_tolerance->set_vy(0.05);
// vel_tolerance->set_vz(0.05);
//
// auto pos_tolerance = config_.mutable_goal_position_tolerance();
// pos_tolerance->set_x(0.05);
// pos_tolerance->set_y(0.05);
// pos_tolerance->set_z(0.05);
controller_.reset(new QrotorBacksteppingController(config_));
controller_connector_.reset(new QrotorBacksteppingControllerConnector(
drone_hardware_, *controller_, thrust_gain_estimator_, config_,
std::chrono::duration<double>(0.01)));
drone_hardware_.usePerfectTime();
}
/* Todo static void SetUpTestCase()
*/
static void SetUpTestCase() {
// Configure logging
LogConfig log_config;
log_config.set_directory("/tmp/data");
Log::instance().configure(log_config);
DataStreamConfig data_config;
data_config.set_stream_id("qrotor_backstepping_controller");
Log::instance().addDataStream(data_config);
data_config.set_stream_id("thrust_gain_estimator");
Log::instance().addDataStream(data_config);
}
void runUntilConvergence(
std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal,
bool check_thrust_gain = true) {
ParticleState initial_desired_state = std::get<0>(goal->atTime(0.0));
drone_hardware_.setBatteryPercent(60);
drone_hardware_.takeoff();
geometry_msgs::Vector3 init_position;
init_position.x = initial_desired_state.p.x;
init_position.y = initial_desired_state.p.y;
init_position.z = initial_desired_state.p.z;
drone_hardware_.cmdwaypoint(init_position);
controller_connector_->setGoal(goal);
auto runController = [&]() {
controller_connector_->run();
return controller_connector_->getStatus() == ControllerStatus::Active;
};
ASSERT_FALSE(test_utils::waitUntilFalse()(runController,
std::chrono::seconds(20),
std::chrono::milliseconds(10)));
// Check position is goal position
parsernode::common::quaddata sensor_data;
drone_hardware_.getquaddata(sensor_data);
/* Homogenous mat for current quad */
tf::Transform quad_transform(
tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z),
tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y,
sensor_data.localpos.z));
/* Homogenous mat for Goal */
ParticleState goal_desired_state = std::get<0>(goal->atTime(20));
tf::Transform goal_transform(tf::createQuaternionFromRPY(0, 0, 0),
tf::Vector3(goal_desired_state.p.x,
goal_desired_state.p.y,
goal_desired_state.p.z));
// ASSERT_TF_NEAR(quad_transform, goal_transform, 0.1);
ASSERT_EQ(controller_connector_->getStatus(), ControllerStatus::Completed);
}
ThrustGainEstimator thrust_gain_estimator_;
Hrotor sys;
QrotorBacksteppingControllerConfig config_;
QuadSimulator drone_hardware_;
std::unique_ptr<QrotorBacksteppingController> controller_;
std::unique_ptr<QrotorBacksteppingControllerConnector> controller_connector_;
};
TEST_F(QrotorBacksteppingControllerConnectorTests, test1) {
int r = 4;
Eigen::VectorXd tau_vec(2);
tau_vec << 3, 3;
Eigen::MatrixXd path(3, 3);
path << 0, 0, 0, 0.5, 0, 0.5, 1, 1, 1;
std::shared_ptr<ReferenceTrajectory<ParticleState, Snap>> goal(
new MinimumSnapReferenceTrajectory(r, tau_vec, path));
runUntilConvergence(goal);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before><commit_msg>planning: fix compile warning. (#2171)<commit_after><|endoftext|> |
<commit_before>#include "TeamCommReceiver.h"
#include "TeamCommSender.h"
#include <Tools/Debug/DebugRequest.h>
#include <Messages/Representations.pb.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace std;
TeamCommReceiver::TeamCommReceiver() : droppedMessages(0)
{
DEBUG_REQUEST_REGISTER("TeamCommReceiver:artificial_delay",
"Add an artificial delay to all team comm messages", false );
getDebugParameterList().add(¶meters);
}
void TeamCommReceiver::execute()
{
const naoth::TeamMessageDataIn& teamMessageData = getTeamMessageDataIn();
bool usingDelayBuffer = false;
DEBUG_REQUEST("TeamCommReceiver:artificial_delay",
usingDelayBuffer = true;
);
for(vector<string>::const_iterator iter = teamMessageData.data.begin();
iter != teamMessageData.data.end(); ++iter)
{
if(usingDelayBuffer) {
delayBuffer.add(*iter);
} else {
handleMessage(*iter);
}
}
// handle messages if buffer half full (so we get really old messages)
if(usingDelayBuffer
&& delayBuffer.size() >= delayBuffer.getMaxEntries()/2)
{
// only handle a quarter of the messages
for(int i=0; i < delayBuffer.getMaxEntries()/4; i++)
{
handleMessage(delayBuffer.first());
delayBuffer.removeFirst();
}
}
// add our own status as artifical message
// (so we are not dependant on a lousy network)
TeamMessage::Data ownTeamData;
TeamCommSender::fillMessage(getPlayerInfo(), getRobotInfo(), getFrameInfo(),
getBallModel(), getRobotPose(), getBodyState(),
getSoccerStrategy(), getPlayersModel(),
getBatteryData(),
ownTeamData);
// we don't have the right player number in the beginning, wait to send
// one to ourself until we have a valid one
if(ownTeamData.playerNum > 0)
{
SPLStandardMessage ownSPLMsg;
TeamCommSender::convertToSPLMessage(ownTeamData, ownSPLMsg);
std::string ownMsgData;
ownMsgData.assign((char*) &ownSPLMsg, sizeof(SPLStandardMessage));
handleMessage(ownMsgData, true);
}
PLOT("TeamCommReceiver:droppedMessages", droppedMessages);
}
TeamCommReceiver::~TeamCommReceiver()
{
getDebugParameterList().remove(¶meters);
}
bool TeamCommReceiver::parseSPLStandardMessage(const std::string& data, SPLStandardMessage& msg) const
{
if(data.size() > sizeof(SPLStandardMessage)) {
//std::cerr << "wrong package size for teamcomm (allow own: " << allowOwn << ")" << std::endl;
// invalid message size
return false;
}
memcpy(&msg, data.c_str(), sizeof(SPLStandardMessage));
// furter sanity check for header and version
if(msg.header[0] != 'S' ||
msg.header[1] != 'P' ||
msg.header[2] != 'L' ||
msg.header[3] != ' ')
{
//std::cerr << "wrong header '" << spl.header << "' for teamcomm (allow own: " << allowOwn << ")" << std::endl;
return false;
}
if(msg.version != SPL_STANDARD_MESSAGE_STRUCT_VERSION) {
//std::cerr << "wrong version for teamcomm (allow own: " << allowOwn << ")" << std::endl;
return false;
}
return true;
}
bool TeamCommReceiver::parseTeamMessage(const SPLStandardMessage& spl, TeamMessage::Data& msg) const
{
msg.frameInfo = getFrameInfo();
msg.playerNum = spl.playerNum;
if(spl.teamColor < GameData::numOfTeamColor) {
msg.teamColor = (GameData::TeamColor) spl.teamColor;
}
msg.pose.translation.x = spl.pose[0];
msg.pose.translation.y = spl.pose[1];
msg.pose.rotation = spl.pose[2];
msg.ballAge = spl.ballAge;
msg.ballPosition.x = spl.ball[0];
msg.ballPosition.y = spl.ball[1];
msg.ballVelocity.x = spl.ballVel[0];
msg.ballVelocity.y = spl.ballVel[1];
msg.fallen = (spl.fallen == 1);
// check if we can deserialize the user defined data
if(spl.numOfDataBytes > 0 && spl.numOfDataBytes <= SPL_STANDARD_MESSAGE_DATA_SIZE)
{
naothmessages::BUUserTeamMessage userData;
try
{
if(userData.ParseFromArray(spl.data, spl.numOfDataBytes))
{
msg.timestamp = userData.timestamp();
msg.bodyID = userData.bodyid();
msg.timeToBall = userData.timetoball();
msg.wasStriker = userData.wasstriker();
msg.isPenalized = userData.ispenalized();
msg.batteryCharge = userData.batterycharge();
msg.temperature = userData.temperature();
msg.teamNumber = userData.teamnumber();
msg.opponents = std::vector<TeamMessage::Opponent>(userData.opponents_size());
for(size_t i=0; i < msg.opponents.size(); i++)
{
const naothmessages::Opponent& oppMsg = userData.opponents(i);
TeamMessage::Opponent& opp = msg.opponents[i];
opp.playerNum = oppMsg.playernum();
DataConversion::fromMessage(oppMsg.poseonfield(), opp.poseOnField);
}
}
}
catch(...)
{
// well, this is not one of our messages, ignore
// TODO: we might want to maintain a list of robots which send
// non-compliant messages in order to avoid overhead when trying to parse it
return false;
}
}
return true;
}
void TeamCommReceiver::handleMessage(const std::string& data, bool allowOwn)
{
SPLStandardMessage spl;
if(!parseSPLStandardMessage(data, spl)) {
return;
}
GameData::TeamColor teamColor = (GameData::TeamColor) spl.teamColor;
if ( teamColor == getPlayerInfo().gameData.teamColor
// ignore our own messages, we are adding it artficially later
&& (allowOwn || spl.playerNum != getPlayerInfo().gameData.playerNumber)
)
{
TeamMessage::Data msg;
if(parseTeamMessage(spl, msg)) {
// copy new data to the blackboard if it's a message from our team
if(!parameters.monotonicTimestampCheck || monotonicTimeStamp(msg)) {
getTeamMessage().data[msg.playerNum] = msg;
} else {
droppedMessages++;
}
}
}
}
<commit_msg>explicit cast to int to avoid warning<commit_after>#include "TeamCommReceiver.h"
#include "TeamCommSender.h"
#include <Tools/Debug/DebugRequest.h>
#include <Messages/Representations.pb.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace std;
TeamCommReceiver::TeamCommReceiver() : droppedMessages(0)
{
DEBUG_REQUEST_REGISTER("TeamCommReceiver:artificial_delay",
"Add an artificial delay to all team comm messages", false );
getDebugParameterList().add(¶meters);
}
void TeamCommReceiver::execute()
{
const naoth::TeamMessageDataIn& teamMessageData = getTeamMessageDataIn();
bool usingDelayBuffer = false;
DEBUG_REQUEST("TeamCommReceiver:artificial_delay",
usingDelayBuffer = true;
);
for(vector<string>::const_iterator iter = teamMessageData.data.begin();
iter != teamMessageData.data.end(); ++iter)
{
if(usingDelayBuffer) {
delayBuffer.add(*iter);
} else {
handleMessage(*iter);
}
}
// handle messages if buffer half full (so we get really old messages)
if(usingDelayBuffer
&& delayBuffer.size() >= delayBuffer.getMaxEntries()/2)
{
// only handle a quarter of the messages
for(int i=0; i < delayBuffer.getMaxEntries()/4; i++)
{
handleMessage(delayBuffer.first());
delayBuffer.removeFirst();
}
}
// add our own status as artifical message
// (so we are not dependant on a lousy network)
TeamMessage::Data ownTeamData;
TeamCommSender::fillMessage(getPlayerInfo(), getRobotInfo(), getFrameInfo(),
getBallModel(), getRobotPose(), getBodyState(),
getSoccerStrategy(), getPlayersModel(),
getBatteryData(),
ownTeamData);
// we don't have the right player number in the beginning, wait to send
// one to ourself until we have a valid one
if(ownTeamData.playerNum > 0)
{
SPLStandardMessage ownSPLMsg;
TeamCommSender::convertToSPLMessage(ownTeamData, ownSPLMsg);
std::string ownMsgData;
ownMsgData.assign((char*) &ownSPLMsg, sizeof(SPLStandardMessage));
handleMessage(ownMsgData, true);
}
PLOT("TeamCommReceiver:droppedMessages", droppedMessages);
}
TeamCommReceiver::~TeamCommReceiver()
{
getDebugParameterList().remove(¶meters);
}
bool TeamCommReceiver::parseSPLStandardMessage(const std::string& data, SPLStandardMessage& msg) const
{
if(data.size() > sizeof(SPLStandardMessage)) {
//std::cerr << "wrong package size for teamcomm (allow own: " << allowOwn << ")" << std::endl;
// invalid message size
return false;
}
memcpy(&msg, data.c_str(), sizeof(SPLStandardMessage));
// furter sanity check for header and version
if(msg.header[0] != 'S' ||
msg.header[1] != 'P' ||
msg.header[2] != 'L' ||
msg.header[3] != ' ')
{
//std::cerr << "wrong header '" << spl.header << "' for teamcomm (allow own: " << allowOwn << ")" << std::endl;
return false;
}
if(msg.version != SPL_STANDARD_MESSAGE_STRUCT_VERSION) {
//std::cerr << "wrong version for teamcomm (allow own: " << allowOwn << ")" << std::endl;
return false;
}
return true;
}
bool TeamCommReceiver::parseTeamMessage(const SPLStandardMessage& spl, TeamMessage::Data& msg) const
{
msg.frameInfo = getFrameInfo();
msg.playerNum = spl.playerNum;
if(spl.teamColor < GameData::numOfTeamColor) {
msg.teamColor = (GameData::TeamColor) spl.teamColor;
}
msg.pose.translation.x = spl.pose[0];
msg.pose.translation.y = spl.pose[1];
msg.pose.rotation = spl.pose[2];
msg.ballAge = spl.ballAge;
msg.ballPosition.x = spl.ball[0];
msg.ballPosition.y = spl.ball[1];
msg.ballVelocity.x = spl.ballVel[0];
msg.ballVelocity.y = spl.ballVel[1];
msg.fallen = (spl.fallen == 1);
// check if we can deserialize the user defined data
if(spl.numOfDataBytes > 0 && spl.numOfDataBytes <= SPL_STANDARD_MESSAGE_DATA_SIZE)
{
naothmessages::BUUserTeamMessage userData;
try
{
if(userData.ParseFromArray(spl.data, spl.numOfDataBytes))
{
msg.timestamp = userData.timestamp();
msg.bodyID = userData.bodyid();
msg.timeToBall = userData.timetoball();
msg.wasStriker = userData.wasstriker();
msg.isPenalized = userData.ispenalized();
msg.batteryCharge = userData.batterycharge();
msg.temperature = userData.temperature();
msg.teamNumber = userData.teamnumber();
msg.opponents = std::vector<TeamMessage::Opponent>(userData.opponents_size());
for(size_t i=0; i < msg.opponents.size(); i++)
{
const naothmessages::Opponent& oppMsg = userData.opponents((int) i);
TeamMessage::Opponent& opp = msg.opponents[i];
opp.playerNum = oppMsg.playernum();
DataConversion::fromMessage(oppMsg.poseonfield(), opp.poseOnField);
}
}
}
catch(...)
{
// well, this is not one of our messages, ignore
// TODO: we might want to maintain a list of robots which send
// non-compliant messages in order to avoid overhead when trying to parse it
return false;
}
}
return true;
}
void TeamCommReceiver::handleMessage(const std::string& data, bool allowOwn)
{
SPLStandardMessage spl;
if(!parseSPLStandardMessage(data, spl)) {
return;
}
GameData::TeamColor teamColor = (GameData::TeamColor) spl.teamColor;
if ( teamColor == getPlayerInfo().gameData.teamColor
// ignore our own messages, we are adding it artficially later
&& (allowOwn || spl.playerNum != getPlayerInfo().gameData.playerNumber)
)
{
TeamMessage::Data msg;
if(parseTeamMessage(spl, msg)) {
// copy new data to the blackboard if it's a message from our team
if(!parameters.monotonicTimestampCheck || monotonicTimeStamp(msg)) {
getTeamMessage().data[msg.playerNum] = msg;
} else {
droppedMessages++;
}
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: localedata.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: er $ $Date: 2001-11-12 16:23:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _I18N_LOCALEDATA_HXX_
#define _I18N_LOCALEDATA_HXX_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <cppuhelper/implbase2.hxx> // helper for implementations
#include <cppu/macros.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/i18n/Calendar.hpp>
#include <com/sun/star/i18n/FormatElement.hpp>
#include <com/sun/star/i18n/Currency.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/i18n/LocaleDataItem.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/XInterface.hpp>
#include <rtl/ustring.hxx>
#include <tools/string.hxx>
#include <tools/list.hxx>
#include <tableelement.h>
#include <osl/module.h>
//
#ifndef _I18N_DEFAULT_NUMBERING_PROVIDER_HXX_
#include <defaultnumberingprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_HORIORIENTATION_HPP_
#include <com/sun/star/text/HoriOrientation.hpp>
#endif
//
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
class LocaleData : public cppu::WeakImplHelper2
<
::com::sun::star::i18n::XLocaleData,
::com::sun::star::lang::XServiceInfo
>
{
public:
LocaleData(){
}
~LocaleData();
virtual ::com::sun::star::i18n::LanguageCountryInfo SAL_CALL getLanguageCountryInfo( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::i18n::LocaleDataItem SAL_CALL getLocaleItem( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Calendar > SAL_CALL getAllCalendars( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Currency > SAL_CALL getAllCurrencies( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::FormatElement > SAL_CALL getAllFormats( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Implementation > SAL_CALL getCollatorImplementations( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getTransliterations( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::i18n::ForbiddenCharacters SAL_CALL getForbiddenCharacters( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getReservedWord( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException) ;
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getAllInstalledLocaleNames() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSearchOptions( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getCollationOptions( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getContinuousNumberingLevels( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > > SAL_CALL getOutlineNumberingLevels( const ::com::sun::star::lang::Locale& rLocale ) throw(::com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName(void)
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void)
throw( ::com::sun::star::uno::RuntimeException );
private :
struct lookupTableItem {
::rtl::OUString adllName;
oslModule dllHandle;
};
List lookupTable;
// static const TableElement dllsTable[];
static const sal_Int16 nbOfLocales;
void* getFunctionSymbol( const ::com::sun::star::lang::Locale& rLocale,
const sal_Char* pFunction, sal_Bool bFallBack = sal_True );
void setFunctionName( const ::com::sun::star::lang::Locale& rLocale,
const ::rtl::OUString& function, ::rtl::OUString& dllName,
::rtl::OUString& functionName, sal_Bool bFallBack );
sal_Bool SAL_CALL lookupDLLName(const ::rtl::OUString& localeName, TableElement& element);
TableElement SAL_CALL getDLLName( const ::com::sun::star::lang::Locale& rLocale,
sal_Bool bFallBack );
oslModule getModuleHandle(const ::rtl::OUString& dllName);
};
#endif // _I18N_LOCALEDATA_HXX_
<commit_msg>#97583# added new locales<commit_after>/*************************************************************************
*
* $RCSfile: localedata.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: bustamam $ $Date: 2002-03-16 18:38:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _I18N_LOCALEDATA_HXX_
#define _I18N_LOCALEDATA_HXX_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <cppuhelper/implbase2.hxx> // helper for implementations
#include <cppu/macros.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/i18n/Calendar.hpp>
#include <com/sun/star/i18n/FormatElement.hpp>
#include <com/sun/star/i18n/Currency.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/i18n/LocaleDataItem.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/XInterface.hpp>
#include <rtl/ustring.hxx>
#include <tools/string.hxx>
#include <tools/list.hxx>
#include <osl/module.hxx>
//
#ifndef _I18N_DEFAULT_NUMBERING_PROVIDER_HXX_
#include <defaultnumberingprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_HORIORIENTATION_HPP_
#include <com/sun/star/text/HoriOrientation.hpp>
#endif
//
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
using namespace com::sun::star::i18n;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
class LocaleData : public cppu::WeakImplHelper2
<
XLocaleData,
XServiceInfo
>
{
public:
LocaleData(){
cachedItem = NULL;
}
~LocaleData();
virtual LanguageCountryInfo SAL_CALL getLanguageCountryInfo( const lang::Locale& rLocale ) throw(RuntimeException);
virtual LocaleDataItem SAL_CALL getLocaleItem( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< i18n::Calendar > SAL_CALL getAllCalendars( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< Currency > SAL_CALL getAllCurrencies( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< FormatElement > SAL_CALL getAllFormats( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< Implementation > SAL_CALL getCollatorImplementations( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< OUString > SAL_CALL getTransliterations( const lang::Locale& rLocale ) throw(RuntimeException);
virtual ForbiddenCharacters SAL_CALL getForbiddenCharacters( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< OUString > SAL_CALL getReservedWord( const lang::Locale& rLocale ) throw(RuntimeException) ;
virtual Sequence< lang::Locale > SAL_CALL getAllInstalledLocaleNames() throw(RuntimeException);
virtual Sequence< OUString > SAL_CALL getSearchOptions( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< OUString > SAL_CALL getCollationOptions( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< Sequence< beans::PropertyValue > > SAL_CALL getContinuousNumberingLevels( const lang::Locale& rLocale ) throw(RuntimeException);
virtual Sequence< Reference< container::XIndexAccess > > SAL_CALL getOutlineNumberingLevels( const lang::Locale& rLocale ) throw(RuntimeException);
//XServiceInfo
virtual OUString SAL_CALL getImplementationName() throw( RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw( RuntimeException );
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw( RuntimeException );
private :
struct lookupTableItem {
lookupTableItem(const sal_Char *name, osl::Module* m) : dllName(name), module(m) {}
const sal_Char* dllName;
const sal_Char* localeName;
lang::Locale aLocale;
osl::Module *module;
sal_Bool equals(const lang::Locale& rLocale) {
return ((rLocale.Language == aLocale.Language &&
rLocale.Country == aLocale.Country &&
rLocale.Variant == aLocale.Variant) ? sal_True : sal_False);
}
};
List lookupTable;
lookupTableItem *cachedItem;
void* SAL_CALL getFunctionSymbol( const lang::Locale& rLocale, const sal_Char* pFunction ) throw( RuntimeException );
void* SAL_CALL getFunctionSymbolByName( const OUString& localeName, const sal_Char* pFunction );
};
} } } }
#endif // _I18N_LOCALEDATA_HXX_
<|endoftext|> |
<commit_before>///
/// @file S2_easy.cpp
/// @brief Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves in the Deleglise-Rivat
/// algorithm.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <PiTable.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace S2_easy {
/// Print the current S2_easy() status in percent.
/// Requires --status command-line flag.
///
class Percent
{
public:
Percent() : percent_(-1) { }
void print(int64_t iter, int64_t max)
{
int b_percent = get_percent(iter, max);
if (percent_ < b_percent)
{
#pragma omp critical (S2_easy)
{
percent_ = b_percent;
cout << "\rStatus: " << percent_ << '%' << flush;
}
}
}
private:
int percent_;
};
/// Calculate the contribution of the clustered easy
/// leaves and the sparse easy leaves.
/// @param T either int64_t or uint128_t.
///
template <typename T1, typename T2, typename T3>
T1 S2_easy(T1 x,
int64_t y,
int64_t z,
int64_t c,
T2& pi,
vector<T3>& primes,
int threads)
{
if (print_status())
{
cout << endl;
cout << "=== S2_easy(x, y) ===" << endl;
cout << "Computation of the easy special leaves" << endl;
}
int64_t pi_sqrty = pi[isqrt(y)];
int64_t pi_x13 = pi[iroot<3>(x)];
T1 S2_total = 0;
double time = get_wtime();
Percent percent;
#pragma omp parallel for schedule(dynamic, 1) num_threads(threads) reduction(+: S2_total)
for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++)
{
T1 prime = primes[b];
int64_t prime64 = primes[b];
int64_t min_trivial_leaf = min(x / (prime * prime), y);
int64_t min_clustered_easy_leaf = isqrt(x / prime64);
int64_t min_sparse_easy_leaf = z / prime64;
int64_t min_hard_leaf = max(y / prime64, prime64);
min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf);
min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf);
int64_t l = pi[min_trivial_leaf];
T1 S2_result = 0;
// Find all clustered easy leaves:
// x / n <= y and phi(x / n, b - 1) == phi(x / m, b - 1)
// where phi(x / n, b - 1) = pi(x / n) - b + 2
while (primes[l] > min_clustered_easy_leaf)
{
T1 n = prime * primes[l];
int64_t xn = (int64_t) (x / n);
int64_t phi_xn = pi[xn] - b + 2;
T1 m = prime * primes[b + phi_xn - 1];
int64_t xm = max((int64_t) (x / m), min_clustered_easy_leaf);
int64_t l2 = pi[xm];
T1 phi_factor = l - l2;
S2_result += phi_xn * phi_factor;
l = l2;
}
// Find all sparse easy leaves:
// x / n <= y and phi(x / n, b - 1) = pi(x / n) - b + 2
for (; primes[l] > min_sparse_easy_leaf; l--)
{
T1 n = prime * primes[l];
int64_t xn = (int64_t) (x / n);
S2_result += pi[xn] - b + 2;
}
if (print_status())
percent.print(b, pi_x13);
S2_total += S2_result;
}
if (print_status())
print_result("S2_easy", S2_total, time);
return S2_total;
}
} // namespace S2_easy
namespace primecount {
int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& pi, vector<int32_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<int32_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
#ifdef HAVE_INT128_T
int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<uint32_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<uint64_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
#endif
} // namespace primecount
<commit_msg>Include PiTable.hpp first<commit_after>///
/// @file S2_easy.cpp
/// @brief Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves in the Deleglise-Rivat
/// algorithm.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace S2_easy {
/// Print the current S2_easy() status in percent.
/// Requires --status command-line flag.
///
class Percent
{
public:
Percent() : percent_(-1) { }
void print(int64_t iter, int64_t max)
{
int b_percent = get_percent(iter, max);
if (percent_ < b_percent)
{
#pragma omp critical (S2_easy)
{
percent_ = b_percent;
cout << "\rStatus: " << percent_ << '%' << flush;
}
}
}
private:
int percent_;
};
/// Calculate the contribution of the clustered easy
/// leaves and the sparse easy leaves.
/// @param T either int64_t or uint128_t.
///
template <typename T1, typename T2, typename T3>
T1 S2_easy(T1 x,
int64_t y,
int64_t z,
int64_t c,
T2& pi,
vector<T3>& primes,
int threads)
{
if (print_status())
{
cout << endl;
cout << "=== S2_easy(x, y) ===" << endl;
cout << "Computation of the easy special leaves" << endl;
}
int64_t pi_sqrty = pi[isqrt(y)];
int64_t pi_x13 = pi[iroot<3>(x)];
T1 S2_total = 0;
double time = get_wtime();
Percent percent;
#pragma omp parallel for schedule(dynamic, 1) num_threads(threads) reduction(+: S2_total)
for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++)
{
T1 prime = primes[b];
int64_t prime64 = primes[b];
int64_t min_trivial_leaf = min(x / (prime * prime), y);
int64_t min_clustered_easy_leaf = isqrt(x / prime64);
int64_t min_sparse_easy_leaf = z / prime64;
int64_t min_hard_leaf = max(y / prime64, prime64);
min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf);
min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf);
int64_t l = pi[min_trivial_leaf];
T1 S2_result = 0;
// Find all clustered easy leaves:
// x / n <= y and phi(x / n, b - 1) == phi(x / m, b - 1)
// where phi(x / n, b - 1) = pi(x / n) - b + 2
while (primes[l] > min_clustered_easy_leaf)
{
T1 n = prime * primes[l];
int64_t xn = (int64_t) (x / n);
int64_t phi_xn = pi[xn] - b + 2;
T1 m = prime * primes[b + phi_xn - 1];
int64_t xm = max((int64_t) (x / m), min_clustered_easy_leaf);
int64_t l2 = pi[xm];
T1 phi_factor = l - l2;
S2_result += phi_xn * phi_factor;
l = l2;
}
// Find all sparse easy leaves:
// x / n <= y and phi(x / n, b - 1) = pi(x / n) - b + 2
for (; primes[l] > min_sparse_easy_leaf; l--)
{
T1 n = prime * primes[l];
int64_t xn = (int64_t) (x / n);
S2_result += pi[xn] - b + 2;
}
if (print_status())
percent.print(b, pi_x13);
S2_total += S2_result;
}
if (print_status())
print_result("S2_easy", S2_total, time);
return S2_total;
}
} // namespace S2_easy
namespace primecount {
int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& pi, vector<int32_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<int32_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
#ifdef HAVE_INT128_T
int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<uint32_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<uint64_t>& primes, int threads)
{
return S2_easy::S2_easy(x, y, z, c, pi, primes, threads);
}
#endif
} // namespace primecount
<|endoftext|> |
<commit_before>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "Binding.h"
#include "Converter.h"
DC_BEGIN_DREEMCHEST
namespace mvvm {
IMPLEMENT_LOGGER( log )
// -------------------------------------------------- BindingFactory -------------------------------------------------- //
// ** BindingFactory::BindingFactory
BindingFactory::BindingFactory( void )
{
registerConverter<GuidToTextConverter>();
registerConverter<FloatToTextConverter>();
registerConverter<IntegerToTextConverter>();
}
// ** BindingFactory::bindableValueTypes
ValueTypes BindingFactory::bindableValueTypes( void ) const
{
ValueTypes result;
for( Bindings::const_iterator i = m_bindings.begin(), end = m_bindings.end(); i != end; ++i ) {
result.push_back( i->first );
}
return result;
}
// ** BindingFactory::create
BindingPtr BindingFactory::create( ValueTypeIdx valueType, WidgetTypeIdx widgetType, const String& widgetProperty )
{
Bindings::iterator byValueType = m_bindings.find( valueType );
if( byValueType == m_bindings.end() ) {
return BindingPtr();
}
BindingByWidgetType::iterator byWidgetType = byValueType->second.find( widgetType );
if( byWidgetType == byValueType->second.end() ) {
return BindingPtr();
}
BindingByProperty::iterator byProperty = byWidgetType->second.find( widgetProperty );
if( byProperty == byWidgetType->second.end() ) {
return BindingPtr();
}
return byProperty->second->clone();
}
// ** BindingFactory::createConverter
BindingPtr BindingFactory::createConverter( ValueTypeIdx inputType, ValueTypeIdx outputType )
{
ConvertersByInputType::iterator i = m_converters.find( inputType );
if( i == m_converters.end() ) {
return BindingPtr();
}
ConverterByOutputType::iterator j = i->second.find( outputType );
if( j == i->second.end() ) {
return BindingPtr();
}
return j->second->clone();
}
// ----------------------------------------------------- Bindings ------------------------------------------------------ //
// ** Bindings::Bindings
Bindings::Bindings( const BindingFactoryPtr& factory, const ObjectWPtr& root ) : m_factory( factory ), m_root( root )
{
}
// ** Bindings::setRoot
void Bindings::setRoot( const ObjectWPtr& value )
{
m_root = value;
}
// ** Bindings::root
ObjectWPtr Bindings::root( void ) const
{
return m_root;
}
//! Binds the widget to a value with specified URI.
bool Bindings::bind( const String& widget, const String& uri, ObjectWPtr root )
{
if( !root.valid() ) {
root = m_root;
}
ValueWPtr value = root->resolve( uri );
return bind( widget, value );
}
//! Binds the widget to a value.
bool Bindings::bind( const String& widget, const ValueWPtr& value )
{
DC_BREAK_IF( !value.valid() );
// Split the widget & it's property.
String widgetName = widget;
String widgetProperty = "";
if( widget.find( '.' ) != String::npos ) {
u32 idx = widget.find( '.' );
widgetName = widget.substr( 0, idx );
widgetProperty = widget.substr( idx + 1 );
}
// Get the widget value type and widget pointer.
WidgetTypeChain widgetType = resolveWidgetTypeChain( widgetName );
Widget widgetPtr = findWidget( widgetName );
return createBinding( value, widgetPtr, widgetType, widgetProperty );
/*
if( !widgetPtr ) {
log::error( "Bindings::bind : no widget with name '%s' found\n", widgetName.c_str() );
return false;
}
// Create binding instance
BindingPtr binding = m_factory->create( value->type(), widgetType[0], widgetProperty );
if( !binding.valid() ) {
log::error( "Bindings::bind : do not know how to bind property to '%s'\n", widgetName.c_str() );
return false;
}
if( !binding->bind( value, widgetPtr ) ) {
log::error( "Bindings::bind : failed to bind property to '%s'\n", widgetName.c_str() );
return false;
}
binding->handleValueChanged();
m_bindings.push_back( binding );
return true;*/
}
// ** Bindings::createBinding
bool Bindings::createBinding( ValueWPtr value, Widget widget, const WidgetTypeChain& widgetType, const String& key )
{
// Get the set of value types that can be bound.
ValueTypes bindableTypes = m_factory->bindableValueTypes();
// Push the actual property type to the begining.
bindableTypes.insert( bindableTypes.begin(), value->type() );
// For each widget type & value type pair try to create the binding - the first one wins.
for( u32 i = 0, nwidgets = ( u32 )widgetType.size(); i < nwidgets; i++ ) {
// Iterate over types
for( u32 j = 0, ntypes = ( u32 )bindableTypes.size(); j < ntypes; j++ ) {
ValueTypeIdx valueType = bindableTypes[j];
BindingPtr binding = m_factory->create( valueType, widgetType[i], key );
if( !binding.valid() ) {
continue;
}
// Binding found
if( j == 0 ) {
binding->bind( value, widget );
binding->handleValueChanged();
m_bindings.push_back( binding );
return true;
}
// We have to create the converter.
BindingPtr converter = m_factory->createConverter( value->type(), binding->type() );
if( !converter.valid() ) {
log::warn( "Bindings::createBinding : no converter found to bind the value to a widget.\n" );
return false;
}
if( !converter->bind( value, NULL ) ) {
log::warn( "Bindings::createBinding : failed to create converter.\n" );
return false;
}
if( !binding->bind( converter->converted(), widget ) ) {
log::warn( "Bindings::createBinding : failed to bind to a converted value.\n" );
return false;
}
converter->handleValueChanged();
binding->handleValueChanged();
m_bindings.push_back( converter );
m_bindings.push_back( binding );
return true;
}
}
return false;
}
} // namespace mvvm
DC_END_DREEMCHEST
<commit_msg>Removed deprecated code<commit_after>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "Binding.h"
#include "Converter.h"
DC_BEGIN_DREEMCHEST
namespace mvvm {
IMPLEMENT_LOGGER( log )
// -------------------------------------------------- BindingFactory -------------------------------------------------- //
// ** BindingFactory::BindingFactory
BindingFactory::BindingFactory( void )
{
registerConverter<GuidToTextConverter>();
registerConverter<FloatToTextConverter>();
registerConverter<IntegerToTextConverter>();
}
// ** BindingFactory::bindableValueTypes
ValueTypes BindingFactory::bindableValueTypes( void ) const
{
ValueTypes result;
for( Bindings::const_iterator i = m_bindings.begin(), end = m_bindings.end(); i != end; ++i ) {
result.push_back( i->first );
}
return result;
}
// ** BindingFactory::create
BindingPtr BindingFactory::create( ValueTypeIdx valueType, WidgetTypeIdx widgetType, const String& widgetProperty )
{
Bindings::iterator byValueType = m_bindings.find( valueType );
if( byValueType == m_bindings.end() ) {
return BindingPtr();
}
BindingByWidgetType::iterator byWidgetType = byValueType->second.find( widgetType );
if( byWidgetType == byValueType->second.end() ) {
return BindingPtr();
}
BindingByProperty::iterator byProperty = byWidgetType->second.find( widgetProperty );
if( byProperty == byWidgetType->second.end() ) {
return BindingPtr();
}
return byProperty->second->clone();
}
// ** BindingFactory::createConverter
BindingPtr BindingFactory::createConverter( ValueTypeIdx inputType, ValueTypeIdx outputType )
{
ConvertersByInputType::iterator i = m_converters.find( inputType );
if( i == m_converters.end() ) {
return BindingPtr();
}
ConverterByOutputType::iterator j = i->second.find( outputType );
if( j == i->second.end() ) {
return BindingPtr();
}
return j->second->clone();
}
// ----------------------------------------------------- Bindings ------------------------------------------------------ //
// ** Bindings::Bindings
Bindings::Bindings( const BindingFactoryPtr& factory, const ObjectWPtr& root ) : m_factory( factory ), m_root( root )
{
}
// ** Bindings::setRoot
void Bindings::setRoot( const ObjectWPtr& value )
{
m_root = value;
}
// ** Bindings::root
ObjectWPtr Bindings::root( void ) const
{
return m_root;
}
//! Binds the widget to a value with specified URI.
bool Bindings::bind( const String& widget, const String& uri, ObjectWPtr root )
{
if( !root.valid() ) {
root = m_root;
}
ValueWPtr value = root->resolve( uri );
return bind( widget, value );
}
//! Binds the widget to a value.
bool Bindings::bind( const String& widget, const ValueWPtr& value )
{
DC_BREAK_IF( !value.valid() );
// Split the widget & it's property.
String widgetName = widget;
String widgetProperty = "";
if( widget.find( '.' ) != String::npos ) {
u32 idx = widget.find( '.' );
widgetName = widget.substr( 0, idx );
widgetProperty = widget.substr( idx + 1 );
}
// Get the widget value type and widget pointer.
WidgetTypeChain widgetType = resolveWidgetTypeChain( widgetName );
Widget widgetPtr = findWidget( widgetName );
return createBinding( value, widgetPtr, widgetType, widgetProperty );
}
binding->handleValueChanged();
m_bindings.push_back( binding );
return true;*/
}
// ** Bindings::createBinding
bool Bindings::createBinding( ValueWPtr value, Widget widget, const WidgetTypeChain& widgetType, const String& key )
{
// Get the set of value types that can be bound.
ValueTypes bindableTypes = m_factory->bindableValueTypes();
// Push the actual property type to the begining.
bindableTypes.insert( bindableTypes.begin(), value->type() );
// For each widget type & value type pair try to create the binding - the first one wins.
for( u32 i = 0, nwidgets = ( u32 )widgetType.size(); i < nwidgets; i++ ) {
// Iterate over types
for( u32 j = 0, ntypes = ( u32 )bindableTypes.size(); j < ntypes; j++ ) {
ValueTypeIdx valueType = bindableTypes[j];
BindingPtr binding = m_factory->create( valueType, widgetType[i], key );
if( !binding.valid() ) {
continue;
}
// Binding found
if( j == 0 ) {
binding->bind( value, widget );
binding->handleValueChanged();
m_bindings.push_back( binding );
return true;
}
// We have to create the converter.
BindingPtr converter = m_factory->createConverter( value->type(), binding->type() );
if( !converter.valid() ) {
log::warn( "Bindings::createBinding : no converter found to bind the value to a widget.\n" );
return false;
}
if( !converter->bind( value, NULL ) ) {
log::warn( "Bindings::createBinding : failed to create converter.\n" );
return false;
}
if( !binding->bind( converter->converted(), widget ) ) {
log::warn( "Bindings::createBinding : failed to bind to a converted value.\n" );
return false;
}
converter->handleValueChanged();
binding->handleValueChanged();
m_bindings.push_back( converter );
m_bindings.push_back( binding );
return true;
}
}
return false;
}
} // namespace mvvm
DC_END_DREEMCHEST
<|endoftext|> |
<commit_before>#ifndef BULL_ANGLE_HPP
#define BULL_ANGLE_HPP
#include <Bull/Math/Constants.hpp>
namespace Bull
{
/*! \class Angle
*
* \brief Implement an universal Angle to handle both degree and radian angles
*
* \tparam T The type of the Angle value
*
*/
template <typename T>
class Angle
{
public:
static Angle<T> Zero;
/*! \brief Create a Angle in degree
*
* \param value The value of the Angle
*
* \return The Angle
*
*/
static Angle<T> degree(T value)
{
return Angle<T>(value, true);
}
/*! \brief Create a Angle in radian
*
* \param value The value of the Angle
*
* \return The Angle
*
*/
static Angle<T> radian(T value)
{
return Angle<T>(value);
}
/*! \brief Normalize an Angle
*
* \param angle The Angle to normalize
*
* \return The normalized Angle
*
*/
static Angle<T> normalize(const Angle<T>& angle)
{
return Angle<T>(angle).normalize();
}
/*! \brief Clamp an Angle
*
* \param angle The Angle to clamp
* \param min The min value of the Angle
* \param max The max value of the Angle
*
* \return The clamped Angle
*
*/
static Angle<T> clamp(const Angle<T>& angle, const Angle<T>& min, const Angle<T>& max)
{
return Angle<T>(angle).clamp(min, max);
}
public:
/*! \brief Default constructor
*
*/
Angle() :
Angle(0, false)
{
/// Nothing
}
/*! \brief Normalize the Angle
*
* \return This
*
*/
Angle<T>& normalize()
{
while(m_value >= 2 * Pi)
{
m_value /= 2 * Pi;
}
return (*this);
}
/*! \brief Clamp the Angle
*
* \param min The min value of the Angle
* \param max The max value of the Angle
*
* \return This
*
*/
Angle<T>& clamp(const Angle<T>& min, const Angle<T>& max)
{
if(m_value < min.m_value)
{
m_value = min.m_value;
}
else if(m_value > max.m_value)
{
m_value = max.m_value;
}
return (*this);
}
/*! \brief Compare two Angle
*
* \param right The Angle to compare to this
*
* \return True if this and right are equal
*
*/
bool operator==(const Angle<T>& right)
{
return m_value == right.m_value;
}
/*! \brief Compare two Angle
*
* \param right The Angle to compare to this
*
* \return True if left and right are not equal
*
*/
bool operator!=(const Angle<T>& right)
{
return m_value != right.m_value;
}
bool operator<(const Angle<T>& right)
{
return m_value < right.m_value;
}
bool operator<=(const Angle<T>& right)
{
return m_value <= right.m_value;
}
bool operator>(const Angle<T>& right)
{
return m_value > right.m_value;
}
bool operator>=(const Angle<T>& right)
{
return m_value >= right.m_value;
}
Angle<T> operator+(const Angle<T>& right)
{
return Angle<T>(m_value + right.m_value);
}
Angle<T> operator-(const Angle<T>& right)
{
return Angle<T>(m_value - right.m_value);
}
template <typename U>
friend Angle<U> operator*(U left, const Angle<U>& right)
{
return Angle<U>(left * right.m_value);
}
template <typename U>
friend Angle<U> operator*(const Angle<U>& left, U right)
{
return Angle<U>(left.m_value * right);
}
template <typename U>
friend Angle<U> operator/(U left, const Angle<U>& right)
{
return Angle<U>(left / right.m_value);
}
template <typename U>
friend Angle<U> operator/(const Angle<U>& left, U right)
{
return Angle<U>(left.m_value / right);
}
Angle<T>& operator+=(const Angle<T>& right)
{
m_value += right.m_value;
return (*this);
}
Angle<T>& operator-=(const Angle<T>& right)
{
m_value -= right.m_value;
return (*this);
}
Angle<T>& operator*=(T right)
{
m_value *= right;
return (*this);
}
Angle<T>& operator/=(T right)
{
m_value /= right;
return (*this);
}
template <typename U>
friend float std::cos(const Bull::Angle<U>& angle);
template <typename U>
friend float std::acos(const Bull::Angle<U>& angle);
template <typename U>
friend float std::sin(const Bull::Angle<U>& angle);
template <typename U>
friend float std::asin(const Bull::Angle<U>& angle);
template <typename U>
friend float std::tan(const Bull::Angle<U>& angle);
template <typename U>
friend float std::atan(const Bull::Angle<U>& angle);
private:
/*! \brief Constructor
*
* \param value The value of the Angle
* \param convert True if the value needs to be converted in radian
*
*/
explicit Angle(T value, bool convert = false)
{
if(convert)
{
value = value * Pi / 180;
}
m_value = value;
}
T m_value;
};
template <typename T>
Angle<T> Angle<T>::Zero = Angle<T>();
typedef Angle<int> AngleI;
typedef Angle<float> AngleF;
typedef Angle<double> AngleD;
typedef Angle<unsigned int> AngleUI;
}
namespace std
{
template <typename U>
float cos(const Bull::Angle<U>& angle)
{
return std::cos(angle.m_value);
}
template <typename U>
float acos(const Bull::Angle<U>& angle)
{
return std::acos(angle.m_value);
}
template <typename U>
float sin(const Bull::Angle<U>& angle)
{
return std::sin(angle.m_value);
}
template <typename U>
float asin(const Bull::Angle<U>& angle)
{
return std::asin(angle.m_value);
}
template <typename U>
float tan(const Bull::Angle<U>& angle)
{
return std::tan(angle.m_value);
}
template <typename U>
float atan(const Bull::Angle<U>& angle)
{
return std::atan(angle.m_value);
}
}
#endif // BULL_ANGLE_HPP
<commit_msg>[Math/Angle] Fix normalize<commit_after>#ifndef BULL_ANGLE_HPP
#define BULL_ANGLE_HPP
#include <Bull/Math/Constants.hpp>
namespace Bull
{
/*! \class Angle
*
* \brief Implement an universal Angle to handle both degree and radian angles
*
* \tparam T The type of the Angle value
*
*/
template <typename T>
class Angle
{
public:
static Angle<T> Zero;
/*! \brief Create a Angle in degree
*
* \param value The value of the Angle
*
* \return The Angle
*
*/
static Angle<T> degree(T value)
{
return Angle<T>(value, true);
}
/*! \brief Create a Angle in radian
*
* \param value The value of the Angle
*
* \return The Angle
*
*/
static Angle<T> radian(T value)
{
return Angle<T>(value);
}
/*! \brief Normalize an Angle
*
* \param angle The Angle to normalize
*
* \return The normalized Angle
*
*/
static Angle<T> normalize(const Angle<T>& angle)
{
return Angle<T>(angle).normalize();
}
/*! \brief Clamp an Angle
*
* \param angle The Angle to clamp
* \param min The min value of the Angle
* \param max The max value of the Angle
*
* \return The clamped Angle
*
*/
static Angle<T> clamp(const Angle<T>& angle, const Angle<T>& min, const Angle<T>& max)
{
return Angle<T>(angle).clamp(min, max);
}
public:
/*! \brief Default constructor
*
*/
Angle() :
Angle(0, false)
{
/// Nothing
}
/*! \brief Normalize the Angle
*
* \return This
*
*/
Angle<T>& normalize()
{
const float pi2 = 2 * Pi;
while(m_value >= 2 * Pi)
{
m_value -= 2 * Pi;
}
return (*this);
}
float toDegree() const
{
return m_value * 180 / Pi;
}
float toRadian() const
{
return m_value;
}
/*! \brief Clamp the Angle
*
* \param min The min value of the Angle
* \param max The max value of the Angle
*
* \return This
*
*/
Angle<T>& clamp(const Angle<T>& min, const Angle<T>& max)
{
if(m_value < min.m_value)
{
m_value = min.m_value;
}
else if(m_value > max.m_value)
{
m_value = max.m_value;
}
return (*this);
}
/*! \brief Compare two Angle
*
* \param right The Angle to compare to this
*
* \return True if this and right are equal
*
*/
bool operator==(const Angle<T>& right)
{
return m_value == right.m_value;
}
/*! \brief Compare two Angle
*
* \param right The Angle to compare to this
*
* \return True if left and right are not equal
*
*/
bool operator!=(const Angle<T>& right)
{
return m_value != right.m_value;
}
bool operator<(const Angle<T>& right)
{
return m_value < right.m_value;
}
bool operator<=(const Angle<T>& right)
{
return m_value <= right.m_value;
}
bool operator>(const Angle<T>& right)
{
return m_value > right.m_value;
}
bool operator>=(const Angle<T>& right)
{
return m_value >= right.m_value;
}
Angle<T> operator+(const Angle<T>& right)
{
return Angle<T>(m_value + right.m_value);
}
Angle<T> operator-(const Angle<T>& right)
{
return Angle<T>(m_value - right.m_value);
}
template <typename U>
friend Angle<U> operator*(U left, const Angle<U>& right)
{
return Angle<U>(left * right.m_value);
}
template <typename U>
friend Angle<U> operator*(const Angle<U>& left, U right)
{
return Angle<U>(left.m_value * right);
}
template <typename U>
friend Angle<U> operator/(U left, const Angle<U>& right)
{
return Angle<U>(left / right.m_value);
}
template <typename U>
friend Angle<U> operator/(const Angle<U>& left, U right)
{
return Angle<U>(left.m_value / right);
}
Angle<T>& operator+=(const Angle<T>& right)
{
m_value += right.m_value;
return (*this);
}
Angle<T>& operator-=(const Angle<T>& right)
{
m_value -= right.m_value;
return (*this);
}
Angle<T>& operator*=(T right)
{
m_value *= right;
return (*this);
}
Angle<T>& operator/=(T right)
{
m_value /= right;
return (*this);
}
template <typename U>
friend float std::cos(const Bull::Angle<U>& angle);
template <typename U>
friend float std::acos(const Bull::Angle<U>& angle);
template <typename U>
friend float std::sin(const Bull::Angle<U>& angle);
template <typename U>
friend float std::asin(const Bull::Angle<U>& angle);
template <typename U>
friend float std::tan(const Bull::Angle<U>& angle);
template <typename U>
friend float std::atan(const Bull::Angle<U>& angle);
private:
/*! \brief Constructor
*
* \param value The value of the Angle
* \param convert True if the value needs to be converted in radian
*
*/
explicit Angle(T value, bool convert = false)
{
if(convert)
{
value = value * Pi / 180;
}
m_value = value;
}
T m_value;
};
template <typename T>
Angle<T> Angle<T>::Zero = Angle<T>();
typedef Angle<int> AngleI;
typedef Angle<float> AngleF;
typedef Angle<double> AngleD;
typedef Angle<unsigned int> AngleUI;
}
namespace std
{
template <typename U>
float cos(const Bull::Angle<U>& angle)
{
return std::cos(angle.m_value);
}
template <typename U>
float acos(const Bull::Angle<U>& angle)
{
return std::acos(angle.m_value);
}
template <typename U>
float sin(const Bull::Angle<U>& angle)
{
return std::sin(angle.m_value);
}
template <typename U>
float asin(const Bull::Angle<U>& angle)
{
return std::asin(angle.m_value);
}
template <typename U>
float tan(const Bull::Angle<U>& angle)
{
return std::tan(angle.m_value);
}
template <typename U>
float atan(const Bull::Angle<U>& angle)
{
return std::atan(angle.m_value);
}
}
#endif // BULL_ANGLE_HPP
<|endoftext|> |
<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <limits>
#include "person.hpp"
/*char russian_letters[6];
size_t russianLetterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
size_t result = static_cast<int>(letter) - first_letter_code + 2;
return result;
}
else {
if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
return 7;
}
size_t result = static_cast<int>(letter) - first_letter_code + 2;
return result;
}
}*/
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
Persons_File() : is_empty(true), file_size(0) {
;
}
std::string file_name;
size_t file_size;
bool is_empty;
char * key;
bool is_same;
std::fstream stream;
void openNew(std::string _file_name) {
file_name = _file_name;
stream.open(file_name, std::ios::out);
}
};
using Output_Files = std::vector<std::ofstream>;
class Database_Sorter {
bool is_database_empty;
std::string database_file_name;
std::string vault_name;
public:
Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount,
std::string _vault_name = "F:\\1\\temp_files\\")
: database_file_name(database_file_name),
database_file(database_file_name),
output_file(output_file_name),
RAM_amount(_RAM_amount * 1024 * 1024),
is_database_empty(true),
vault_name(_vault_name)
{
;
}
void sortDatabase() {
database_file.seekg(0, std::ios::end);
size_t database_size = static_cast<size_t>(database_file.tellg());
database_file.seekg(0, std::ios::beg);
sortFile(database_file_name, database_size, 0);
}
void closeDatabase() {
database_file.close();
output_file.close();
}
private:
void outputFile(std::string const & file_name) {
if (is_database_empty) {
is_database_empty = false;
}
else {
output_file << std::endl;
}
std::ifstream file(file_name);
char ch;
while (file.get(ch)) {
output_file.put(ch);
}
file.close();
}
void sortFile(std::string const & file_name, size_t file_size, size_t sort_i) {
if (file_size < RAM_amount) {
RAMsort(file_name, sort_i);
}
else {
std::vector<Persons_File> persons_files = stuffPersonsToFiles(file_name, sort_i);
for (size_t i = 0; i < persons_files.size(); i++) {
if (!persons_files[i].is_empty) {
if (persons_files[i].is_same) {
outputFile(persons_files[i].file_name);
}
else {
sortFile(persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
}
}
}
}
}
void RAMsort(std::string const & file_name, size_t sort_i) {
persons.clear();
readFileIntoRAM(file_name);
sortPersons(persons, sort_i);
}
void readFileIntoRAM(std::string const & file_name) {
/*std::string str;
std::ifstream file(file_name, std::ios::in | std::ios::ate);
if (file) {
std::ifstream::streampos filesize = file.tellg();
str.reserve(filesize);
file.seekg(0);
while (!file.eof())
{
str += file.get();
}
}*/
std::ifstream is(file_name, std::ifstream::binary);
if (is) {
// get length of file:
is.seekg(0, is.end);
size_t length = is.tellg();
is.seekg(0, is.beg);
char * buffer = new char[length];
// read data as a block:
is.read(buffer, length);
is.close();
size_t previous_i = 0;
size_t i = 0;
bool state = false;
person current_person;
while (i < length) {
if (buffer[i] == ' ') {
if (!state) {
current_person.name_i = i - previous_i + 1;
state = true;
}
else {
current_person.name_length = i - previous_i - current_person.name_i;
state = false;
}
}
else if (buffer[i] == '\r') {
current_person.str = new char[i - previous_i + 1];
strncpy(current_person.str, &(buffer[previous_i]), i - previous_i);
current_person.str[i - previous_i] = '\0';
persons.push_back(current_person);
previous_i = i + 2;
i++;
}
i++;
}
persons.shrink_to_fit();
delete[] buffer;
}
/*std::ifstream file(file_name);
std::stringstream s;
person current_person;
while (!file.eof()) {
file >> current_person;
current_person.name.shrink_to_fit();
current_person.surname.shrink_to_fit();
persons.push_back(current_person);
}*/
}
void sortPersons(Persons & entered_persons, size_t sort_i) {
size_t full_bucket_i;
Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i, full_bucket_i);
if (full_bucket_i != std::numeric_limits<size_t>::max()) {
outputBucket(buckets[full_bucket_i], output_file);
}
else {
for (auto bucket : buckets) {
if (!bucket.empty()) {
sortPersons(bucket, sort_i + 1);
}
}
}
}
Buckets stuffPersonsToBuckets(Persons & persons, size_t sort_i, size_t & full_bucket_i) {
bool is_same = true;
char * key = new char[persons[0].name_length + 1];
strncpy(key, persons[0].getName(), persons[0].name_length);
key[persons[0].name_length] = '\0';
full_bucket_i = persons[0].i(sort_i);
size_t persons_size = persons.size();
Buckets buckets(n_literals);
for (auto person : persons) {
size_t currentI = person.i(sort_i);
full_bucket_i = currentI;
buckets[currentI].push_back(std::move(person));
if (is_same) {
if (strcmp(key, person.getName()) != 0) {
is_same = false;
}
}
}
persons.clear();
persons.shrink_to_fit();
if (!is_same) {
full_bucket_i = std::numeric_limits<size_t>::max();
}
delete[] key;
return buckets;
}
void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
for (auto person : bucket) {
outputPerson(person);
}
}
void outputPerson(person _person) {
if (is_database_empty) {
is_database_empty = false;
}
else {
output_file << std::endl;
}
output_file << _person.str;
}
std::vector<Persons_File> stuffPersonsToFiles(/*std::ifstream & base_file, */
std::string base_file_name, size_t sort_i) {
std::ifstream base_file(base_file_name);
bool is_same = true;
std::vector<Persons_File> files(n_literals);
person current_person;
size_t currentTargetFileI;
std::string str1, str2, str3;
while (!base_file.eof()) {
base_file >> str1;
current_person.name_i = str1.length() + 1;
base_file >> str2;
current_person.name_length = str2.length();
base_file >> str3;
str1 += " " + str2 + " " + str3;
current_person.str = new char[str1.length() + 1];
strncpy(current_person.str, str1.c_str(), str1.length());
current_person.str[str1.length()] = '\0';
currentTargetFileI = current_person.i(sort_i);
if (files[currentTargetFileI].is_empty) {
files[currentTargetFileI].openNew(calcDerivedFileName(base_file_name, currentTargetFileI));
files[currentTargetFileI].is_empty = false;
files[currentTargetFileI].key = new char[current_person.name_length + 1];
strncpy(files[currentTargetFileI].key, current_person.str, current_person.name_length);
files[currentTargetFileI].key[current_person.name_length] = '\0';
files[currentTargetFileI].is_same = true;
}
else {
if (files[currentTargetFileI].is_same) {
//char * temp = current_person.getName();
if (strcmp(files[currentTargetFileI].key, str2.c_str()) != 0) {
files[currentTargetFileI].is_same = false;
}
}
files[currentTargetFileI].stream << std::endl;
}
files[currentTargetFileI].stream << current_person;
}
for (size_t i = 0; i < files.size(); i++) {
if (!files[i].is_empty) {
files[i].file_size = static_cast<size_t>(files[i].stream.tellg());
}
files[i].stream.close();
}
base_file.close();
return files;
}
std::vector<Persons_File> createDerivedFiles(std::string const & base_file_name) {
std::vector<Persons_File> files(n_literals);
for (size_t i = 0; i < files.size(); i++) {
std::string str;
if (base_file_name == database_file_name) {
str = vault_name + static_cast<char>(i + 64) + ".txt";
}
else {
str = base_file_name + static_cast<char>(i + 64) + ".txt";
}
files[i].openNew(str);
}
return files;
}
std::string calcDerivedFileName(const std::string & base_file_name, size_t file_i) {
std::string derived_file_name;
if (base_file_name == database_file_name) {
derived_file_name = vault_name + static_cast<char>(file_i + 64) + ".txt";
}
else {
derived_file_name = base_file_name + static_cast<char>(file_i + 64) + ".txt";
}
return derived_file_name;
}
std::vector<person> persons;
std::ifstream database_file;
std::ofstream output_file;
const size_t RAM_amount;
};
//memory: max 27 files,
<commit_msg>Update Database_Sorter.hpp<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <limits>
#include "person.hpp"
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
Persons_File() : is_empty(true), file_size(0) {
;
}
std::string file_name;
size_t file_size;
bool is_empty;
char * key;
bool is_same;
std::fstream stream;
void openNew(std::string _file_name) {
file_name = _file_name;
stream.open(file_name, std::ios::out);
}
};
using Output_Files = std::vector<std::ofstream>;
class Database_Sorter {
bool is_database_empty;
std::string database_file_name;
std::string vault_name;
public:
Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount,
std::string _vault_name = "F:\\1\\temp_files\\")
: database_file_name(database_file_name),
database_file(database_file_name),
output_file(output_file_name),
RAM_amount(_RAM_amount * 1024 * 1024),
is_database_empty(true),
vault_name(_vault_name)
{
;
}
void sortDatabase() {
database_file.seekg(0, std::ios::end);
size_t database_size = static_cast<size_t>(database_file.tellg());
database_file.seekg(0, std::ios::beg);
sortFile(database_file_name, database_size, 0);
}
void closeDatabase() {
database_file.close();
output_file.close();
}
private:
void outputFile(std::string const & file_name) {
if (is_database_empty) {
is_database_empty = false;
}
else {
output_file << std::endl;
}
std::ifstream file(file_name);
char ch;
while (file.get(ch)) {
output_file.put(ch);
}
file.close();
}
void sortFile(std::string const & file_name, size_t file_size, size_t sort_i) {
if (file_size < RAM_amount) {
RAMsort(file_name, sort_i);
}
else {
std::vector<Persons_File> persons_files = stuffPersonsToFiles(file_name, sort_i);
for (size_t i = 0; i < persons_files.size(); i++) {
if (!persons_files[i].is_empty) {
if (persons_files[i].is_same) {
outputFile(persons_files[i].file_name);
}
else {
sortFile(persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
}
}
}
}
}
void RAMsort(std::string const & file_name, size_t sort_i) {
persons.clear();
readFileIntoRAM(file_name);
sortPersons(persons, sort_i);
}
void readFileIntoRAM(std::string const & file_name) {
/*std::string str;
std::ifstream file(file_name, std::ios::in | std::ios::ate);
if (file) {
std::ifstream::streampos filesize = file.tellg();
str.reserve(filesize);
file.seekg(0);
while (!file.eof())
{
str += file.get();
}
}*/
std::ifstream is(file_name, std::ifstream::binary);
if (is) {
// get length of file:
is.seekg(0, is.end);
size_t length = is.tellg();
is.seekg(0, is.beg);
char * buffer = new char[length];
// read data as a block:
is.read(buffer, length);
is.close();
size_t previous_i = 0;
size_t i = 0;
bool state = false;
person current_person;
while (i < length) {
if (buffer[i] == ' ') {
if (!state) {
current_person.name_i = i - previous_i + 1;
state = true;
}
else {
current_person.name_length = i - previous_i - current_person.name_i;
state = false;
}
}
else if (buffer[i] == '\r') {
current_person.str = new char[i - previous_i + 1];
strncpy(current_person.str, &(buffer[previous_i]), i - previous_i);
current_person.str[i - previous_i] = '\0';
persons.push_back(current_person);
previous_i = i + 2;
i++;
}
i++;
}
persons.shrink_to_fit();
delete[] buffer;
}
/*std::ifstream file(file_name);
std::stringstream s;
person current_person;
while (!file.eof()) {
file >> current_person;
current_person.name.shrink_to_fit();
current_person.surname.shrink_to_fit();
persons.push_back(current_person);
}*/
}
void sortPersons(Persons & entered_persons, size_t sort_i) {
size_t full_bucket_i;
Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i, full_bucket_i);
if (full_bucket_i != std::numeric_limits<size_t>::max()) {
outputBucket(buckets[full_bucket_i], output_file);
}
else {
for (auto bucket : buckets) {
if (!bucket.empty()) {
sortPersons(bucket, sort_i + 1);
}
}
}
}
Buckets stuffPersonsToBuckets(Persons & persons, size_t sort_i, size_t & full_bucket_i) {
bool is_same = true;
char * key = new char[persons[0].name_length + 1];
strncpy(key, persons[0].getName(), persons[0].name_length);
key[persons[0].name_length] = '\0';
full_bucket_i = persons[0].i(sort_i);
size_t persons_size = persons.size();
Buckets buckets(n_literals);
for (auto person : persons) {
size_t currentI = person.i(sort_i);
full_bucket_i = currentI;
buckets[currentI].push_back(std::move(person));
if (is_same) {
if (strcmp(key, person.getName()) != 0) {
is_same = false;
}
}
}
persons.clear();
persons.shrink_to_fit();
if (!is_same) {
full_bucket_i = std::numeric_limits<size_t>::max();
}
delete[] key;
return buckets;
}
void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
for (auto person : bucket) {
outputPerson(person);
}
}
void outputPerson(person _person) {
if (is_database_empty) {
is_database_empty = false;
}
else {
output_file << std::endl;
}
output_file << _person.str;
}
std::vector<Persons_File> stuffPersonsToFiles(/*std::ifstream & base_file, */
std::string base_file_name, size_t sort_i) {
std::ifstream base_file(base_file_name);
bool is_same = true;
std::vector<Persons_File> files(n_literals);
person current_person;
size_t currentTargetFileI;
std::string str1, str2, str3;
while (!base_file.eof()) {
base_file >> str1;
current_person.name_i = str1.length() + 1;
base_file >> str2;
current_person.name_length = str2.length();
base_file >> str3;
str1 += " " + str2 + " " + str3;
current_person.str = new char[str1.length() + 1];
strncpy(current_person.str, str1.c_str(), str1.length());
current_person.str[str1.length()] = '\0';
currentTargetFileI = current_person.i(sort_i);
if (files[currentTargetFileI].is_empty) {
files[currentTargetFileI].openNew(calcDerivedFileName(base_file_name, currentTargetFileI));
files[currentTargetFileI].is_empty = false;
files[currentTargetFileI].key = new char[current_person.name_length + 1];
strncpy(files[currentTargetFileI].key, current_person.str, current_person.name_length);
files[currentTargetFileI].key[current_person.name_length] = '\0';
files[currentTargetFileI].is_same = true;
}
else {
if (files[currentTargetFileI].is_same) {
//char * temp = current_person.getName();
if (strcmp(files[currentTargetFileI].key, str2.c_str()) != 0) {
files[currentTargetFileI].is_same = false;
}
}
files[currentTargetFileI].stream << std::endl;
}
files[currentTargetFileI].stream << current_person;
}
for (size_t i = 0; i < files.size(); i++) {
if (!files[i].is_empty) {
files[i].file_size = static_cast<size_t>(files[i].stream.tellg());
}
files[i].stream.close();
}
base_file.close();
return files;
}
std::vector<Persons_File> createDerivedFiles(std::string const & base_file_name) {
std::vector<Persons_File> files(n_literals);
for (size_t i = 0; i < files.size(); i++) {
std::string str;
if (base_file_name == database_file_name) {
str = vault_name + static_cast<char>(i + 64) + ".txt";
}
else {
str = base_file_name + static_cast<char>(i + 64) + ".txt";
}
files[i].openNew(str);
}
return files;
}
std::string calcDerivedFileName(const std::string & base_file_name, size_t file_i) {
std::string derived_file_name;
if (base_file_name == database_file_name) {
derived_file_name = vault_name + static_cast<char>(file_i + 64) + ".txt";
}
else {
derived_file_name = base_file_name + static_cast<char>(file_i + 64) + ".txt";
}
return derived_file_name;
}
std::vector<person> persons;
std::ifstream database_file;
std::ofstream output_file;
const size_t RAM_amount;
};
//memory: max 27 files,
<|endoftext|> |
<commit_before>
#pragma once
/**
* OptimalMatching.hpp
* Purpose: Find the optimal matching over MxN bipartite pairings.
*
* This class uses Munkres' adaptation of the paper-based Hungarian algorithm
* to find the optimal matching over an MxN matrix of costs.
*
* @author Kevin A. Naud
* @version 1.1
*/
#include <algorithm>
#include <memory>
#include <assert.h>
#include <ArrayView.hpp>
#include <BitStructures.hpp>
namespace kn
{
template <typename T>
struct Matching
{
std::size_t u, v;
T score;
};
template <typename T>
class MatchingOptimiser
{
public:
static constexpr T Zero = 0;
static constexpr std::size_t Unused = ~0;
private:
std::size_t majorDim, minorDim;
ArrayView<T>* arrayTs;
T* arrayT;
std::size_t* arraySizeT;
Matching<T>* arrayMatching;
std::size_t rows, columns;
ArrayView<ArrayView<T> > costs;
ArrayView<ArrayView<T> > matrix;
ArrayView<std::size_t> chain;
ArrayView<std::size_t> columnStars, rowStars, rowPrimes;
IntegerSet rowsCovered, columnsCovered, rowPrimesTouched;
std::size_t numColumnStars, numRowStars, numRowPrimes;
std::size_t chainLen, numColumnsCovered;
bool transposed, maximise;
ArrayView<Matching<T> > mapping;
void prepare();
void engageNext(std::size_t pi, std::size_t pj);
bool findUncoveredZero(std::size_t& pi, std::size_t& pj);
T findSmallestUncovered();
void doNext();
void extractMapping();
public:
MatchingOptimiser() : MatchingOptimiser(50) {}
MatchingOptimiser(std::size_t estDim) : MatchingOptimiser(estDim, estDim) {}
MatchingOptimiser(std::size_t estDim1, std::size_t estDim2);
~MatchingOptimiser();
void reallocate(std::size_t estDim1, std::size_t estDim2);
const ArrayView<ArrayView<T> >& defineProblem(std::size_t m, std::size_t n, bool maximise);
void clearCosts(T defaultCost = Zero);
const ArrayView<Matching<T> >& solve(T& sum);
};
template<typename T>
MatchingOptimiser<T>::MatchingOptimiser(std::size_t estDim1, std::size_t estDim2)
: rowsCovered(std::min(estDim1, estDim2)), columnsCovered(std::max(estDim1, estDim2)), rowPrimesTouched(std::min(estDim1, estDim2))
{
minorDim = std::min(estDim1, estDim2);
majorDim = std::max(estDim1, estDim2);
arrayTs = new ArrayView<T>[majorDim * 2];
arrayT = new T[majorDim * minorDim * 2];
arraySizeT = new std::size_t[majorDim + minorDim * 4 + 1];
arrayMatching = new Matching<T>[minorDim];
}
template<typename T>
MatchingOptimiser<T>::~MatchingOptimiser()
{
delete[] arrayMatching;
delete[] arraySizeT;
delete[] arrayT;
delete[] arrayTs;
}
template<typename T>
void MatchingOptimiser<T>::reallocate(std::size_t estDim1, std::size_t estDim2)
{
std::size_t newMinorDim = std::min(estDim1, estDim2);
std::size_t newMajorDim = std::max(estDim1, estDim2);
if ((minorDim != newMinorDim) || (majorDim != newMajorDim))
{
delete[] arrayMatching;
delete[] arraySizeT;
delete[] arrayT;
delete[] arrayTs;
minorDim = newMinorDim;
majorDim = newMajorDim;
arrayTs = new ArrayView<T>[majorDim];
arrayT = new T[majorDim * minorDim * 2];
arraySizeT = new std::size_t[majorDim + minorDim * 4 + 1];
arrayMatching = new Matching<T>[minorDim];
}
}
template<typename T>
const ArrayView<ArrayView<T> >& MatchingOptimiser<T>::defineProblem(std::size_t m, std::size_t n, bool maximise)
{
this->maximise = maximise;
transposed = (m > n);
rows = std::min(m, n);
columns = std::max(m, n);
if ((rows > minorDim) || (columns > majorDim)) reallocate(rows, columns);
costs = ArrayView<ArrayView<T> >(arrayTs, m);
matrix = ArrayView<ArrayView<T> >(arrayTs + m, rows);
chain = ArrayView<std::size_t>(arraySizeT, rows * 2 + 1);
rowStars = ArrayView<std::size_t>(arraySizeT + rows * 2 + 1, rows);
rowPrimes = ArrayView<std::size_t>(arraySizeT + rows * 3 + 1, rows);
columnStars = ArrayView<std::size_t>(arraySizeT + rows * 4 + 1, columns);
mapping = ArrayView<Matching<T> >(arrayMatching, rows);
for (std::size_t mi = 0; mi < m; mi++)
{
costs[mi] = ArrayView<T>(arrayT + mi * n, n);
}
for (std::size_t ri = 0; ri < rows; ri++)
{
matrix[ri] = ArrayView<T>((arrayT + m * n) + ri * columns, columns);
}
return costs;
}
template<typename T>
void MatchingOptimiser<T>::clearCosts(T defaultCost)
{
for (std::size_t i = 0; i < costs.size(); i++)
{
ArrayView<T> row = costs[i];
for (std::size_t j = 0; j < row.size(); j++)
{
row[j] = defaultCost;
}
}
}
template<typename T>
void MatchingOptimiser<T>::prepare()
{
if (transposed)
{
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
matrix[u][v] = costs[v][u];
}
}
}
else
{
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
matrix[u][v] = costs[u][v];
}
}
}
if (maximise)
{
double big = costs[0][0];
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
if (matrix[u][v] > big) big = matrix[u][v];
}
}
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
matrix[u][v] = big - matrix[u][v];
}
}
}
for (std::size_t t = 0; t < mapping.size(); t++)
{
mapping[t].u = Unused;
mapping[t].v = Unused;
}
chainLen = 0;
numColumnsCovered = 0;
for (std::size_t t = 0; t < rows; t++)
{
rowStars[t] = Unused;
rowPrimes[t] = Unused;
}
for (std::size_t t = 0; t < columns; t++)
{
columnStars[t] = Unused;
}
numColumnStars = 0;
numRowStars = 0;
numRowPrimes = 0;
rowsCovered.clear();
columnsCovered.clear();
rowPrimesTouched.clear();
}
template<typename T>
void MatchingOptimiser<T>::engageNext(std::size_t pi, std::size_t pj)
{
// InitChain(pi, pj);
chain[0] = pi;
chain[1] = pj;
chainLen = 2;
// TouchPrimedRow(pi);
rowPrimesTouched.add(pi);
for (;;)
{
if (columnStars[pj] != Unused)
{
// the starred zero being displaced is ...
std::size_t qj = pj;
std::size_t qi = columnStars[qj];
// AddStarChain(qi);
chain[chainLen++] = qi;
//if (!rowPrimes.contains(qi))
// throw new InternalError("Unexpected error in Hungarian method: The current row *should* have a primed entry.");
if (!rowPrimesTouched.contains(qi))
{
// the next primed zero in the chain is ...
std::size_t ri = qi;
std::size_t rj = rowPrimes[ri];
// AddPrimeChain(rj);
chain[chainLen++] = rj;
// rowPrimesTouched.set(ri, True);
rowPrimesTouched.add(ri);
pi = ri;
pj = rj;
}
else
break; // break: must break for now, due to local cycle.
}
else
break; // break: there are no more starred zeros in the primed zero's column.
}
// RemoveChainStars();
for (std::size_t c = 1; (c + 1) < chainLen; c += 2)
{
// RemoveStar(chain[c + 1], chain[c]);
std::size_t col = chain[c];
std::size_t row = chain[c + 1];
if (columnStars[col] != Unused) { columnStars[col] = Unused; numColumnStars--; }
if (rowStars[row] != Unused) { rowStars[row] = Unused; numRowStars--; }
}
// ResolveChainPrimes();
for (std::size_t c = 0; (c + 1) < chainLen; c += 2)
{
// AddStar(chain[c], target);
std::size_t row = chain[c];
std::size_t col = chain[c + 1];
if (columnStars[col] == Unused) numColumnStars++;
columnStars[col] = row;
if (rowStars[row] == Unused) numRowStars++;
rowStars[row] = col;
// CoverColumn(col);
numColumnsCovered++;
columnsCovered.add(col);
}
rowsCovered.clear();
rowPrimesTouched.clear();
numRowPrimes = 0;
for (std::size_t c = 0; c < rows; c++)
{
rowPrimes[c] = Unused;
}
// VerifyStars();
for (std::size_t c = 0; c < columns; c++)
{
if ((columnStars[c] != Unused) && !columnsCovered.contains(c))
{
// CoverColumn(c);
numColumnsCovered++;
columnsCovered.add(c);
}
}
}
template<typename T>
bool MatchingOptimiser<T>::findUncoveredZero(std::size_t& pi, std::size_t& pj)
{
for (std::size_t i = 0; i < rows; i++)
{
if (rowsCovered.contains(i)) continue;
for (std::size_t j = 0; j < columns; j++)
{
if (columnsCovered.contains(j)) continue;
// Exact test for 0 is ok due to subtraction performed in Hungarian method
if (matrix[i][j] == Zero)
{
pi = i;
pj = j;
return true;
}
}
}
return false;
}
template<typename T>
T MatchingOptimiser<T>::findSmallestUncovered()
{
T smallest = matrix[0][0];
for (std::size_t i = 0; i < rows; i++)
{
if (rowsCovered.contains(i)) continue;
for (std::size_t j = 0; j < columns; j++)
{
if (columnsCovered.contains(j)) continue;
T value = matrix[i][j];
if (value < smallest) smallest = value;
}
}
return smallest;
}
template<typename T>
void MatchingOptimiser<T>::doNext()
{
for (;;)
{
std::size_t pi, pj;
if (findUncoveredZero(pi, pj)) // populates pi and pj
{
// AddPrime(pi, pj);
numRowPrimes++;
rowPrimes[pi] = pj;
if (rowStars[pi] != Unused)
{
std::size_t j = rowStars[pi];
// UncoverColumn(j);
numColumnsCovered--;
columnsCovered.remove(j);
// CoverRow(pi);
rowsCovered.add(pi);
}
else
{
// We've primed a zero in a starless row.
engageNext(pi, pj);
return;
}
}
else
{
// There were no uncovered zeros, so they must be created.
T smallest = findSmallestUncovered();
for (std::size_t j = 0; j < columns; j++)
{
if (columnsCovered.contains(j)) continue;
for (std::size_t i = 0; i < rows; i++)
{
matrix[i][j] -= smallest;
}
}
for (std::size_t i = 0; i < rows; i++)
{
if (!rowsCovered.contains(i)) continue;
for (std::size_t j = 0; j < columns; j++)
{
matrix[i][j] += smallest;
}
}
}
}
}
template<typename T>
void MatchingOptimiser<T>::extractMapping()
{
for (std::size_t i = 0; i < rows; i++)
{
std::size_t j = rowStars[i];
// RecordResult(i, j);
if (transposed)
{
mapping[i].u = j;
mapping[i].v = i;
mapping[i].score = costs[j][i];
}
else
{
mapping[i].u = i;
mapping[i].v = j;
mapping[i].score = costs[i][j];
}
}
}
template<typename T>
const ArrayView<Matching<T> >& MatchingOptimiser<T>::solve(T& sum)
{
prepare();
while (numColumnsCovered < rows)
{
doNext();
}
extractMapping();
double localSum = 0.0;
for (std::size_t i = 0; i < rows; i++)
{
localSum += mapping[i].score;
}
sum = localSum;
return mapping;
}
}
<commit_msg>Optimal matching: added support to exlude negatives in matched sum<commit_after>
#pragma once
/**
* OptimalMatching.hpp
* Purpose: Find the optimal matching over MxN bipartite pairings.
*
* This class uses Munkres' adaptation of the paper-based Hungarian algorithm
* to find the optimal matching over an MxN matrix of costs.
*
* @author Kevin A. Naud
* @version 1.1
*/
#include <algorithm>
#include <memory>
#include <assert.h>
#include <ArrayView.hpp>
#include <BitStructures.hpp>
namespace kn
{
template <typename T>
struct Matching
{
std::size_t u, v;
T score;
};
template <typename T>
class MatchingOptimiser
{
public:
static constexpr T Zero = 0;
static constexpr std::size_t Unused = ~0;
private:
std::size_t majorDim, minorDim;
ArrayView<T>* arrayTs;
T* arrayT;
std::size_t* arraySizeT;
Matching<T>* arrayMatching;
std::size_t rows, columns;
ArrayView<ArrayView<T> > costs;
ArrayView<ArrayView<T> > matrix;
ArrayView<std::size_t> chain;
ArrayView<std::size_t> columnStars, rowStars, rowPrimes;
IntegerSet rowsCovered, columnsCovered, rowPrimesTouched;
std::size_t numColumnStars, numRowStars, numRowPrimes;
std::size_t chainLen, numColumnsCovered;
bool transposed, maximise;
ArrayView<Matching<T> > mapping;
void prepare();
void engageNext(std::size_t pi, std::size_t pj);
bool findUncoveredZero(std::size_t& pi, std::size_t& pj);
T findSmallestUncovered();
void doNext();
void extractMapping();
public:
MatchingOptimiser() : MatchingOptimiser(50) {}
MatchingOptimiser(std::size_t estDim) : MatchingOptimiser(estDim, estDim) {}
MatchingOptimiser(std::size_t estDim1, std::size_t estDim2);
~MatchingOptimiser();
void reallocate(std::size_t estDim1, std::size_t estDim2);
const ArrayView<ArrayView<T> >& defineProblem(std::size_t m, std::size_t n, bool maximise);
void clearCosts(T defaultCost = Zero);
const ArrayView<Matching<T> >& solve(T& sum, bool excludeNegatives);
};
template<typename T>
MatchingOptimiser<T>::MatchingOptimiser(std::size_t estDim1, std::size_t estDim2)
: rowsCovered(std::min(estDim1, estDim2)), columnsCovered(std::max(estDim1, estDim2)), rowPrimesTouched(std::min(estDim1, estDim2))
{
minorDim = std::min(estDim1, estDim2);
majorDim = std::max(estDim1, estDim2);
arrayTs = new ArrayView<T>[majorDim * 2];
arrayT = new T[majorDim * minorDim * 2];
arraySizeT = new std::size_t[majorDim + minorDim * 4 + 1];
arrayMatching = new Matching<T>[minorDim];
}
template<typename T>
MatchingOptimiser<T>::~MatchingOptimiser()
{
delete[] arrayMatching;
delete[] arraySizeT;
delete[] arrayT;
delete[] arrayTs;
}
template<typename T>
void MatchingOptimiser<T>::reallocate(std::size_t estDim1, std::size_t estDim2)
{
std::size_t newMinorDim = std::min(estDim1, estDim2);
std::size_t newMajorDim = std::max(estDim1, estDim2);
if ((minorDim != newMinorDim) || (majorDim != newMajorDim))
{
delete[] arrayMatching;
delete[] arraySizeT;
delete[] arrayT;
delete[] arrayTs;
minorDim = newMinorDim;
majorDim = newMajorDim;
arrayTs = new ArrayView<T>[majorDim];
arrayT = new T[majorDim * minorDim * 2];
arraySizeT = new std::size_t[majorDim + minorDim * 4 + 1];
arrayMatching = new Matching<T>[minorDim];
}
}
template<typename T>
const ArrayView<ArrayView<T> >& MatchingOptimiser<T>::defineProblem(std::size_t m, std::size_t n, bool maximise)
{
this->maximise = maximise;
transposed = (m > n);
rows = std::min(m, n);
columns = std::max(m, n);
if ((rows > minorDim) || (columns > majorDim)) reallocate(rows, columns);
costs = ArrayView<ArrayView<T> >(arrayTs, m);
matrix = ArrayView<ArrayView<T> >(arrayTs + m, rows);
chain = ArrayView<std::size_t>(arraySizeT, rows * 2 + 1);
rowStars = ArrayView<std::size_t>(arraySizeT + rows * 2 + 1, rows);
rowPrimes = ArrayView<std::size_t>(arraySizeT + rows * 3 + 1, rows);
columnStars = ArrayView<std::size_t>(arraySizeT + rows * 4 + 1, columns);
mapping = ArrayView<Matching<T> >(arrayMatching, rows);
for (std::size_t mi = 0; mi < m; mi++)
{
costs[mi] = ArrayView<T>(arrayT + mi * n, n);
}
for (std::size_t ri = 0; ri < rows; ri++)
{
matrix[ri] = ArrayView<T>((arrayT + m * n) + ri * columns, columns);
}
return costs;
}
template<typename T>
void MatchingOptimiser<T>::clearCosts(T defaultCost)
{
for (std::size_t i = 0; i < costs.size(); i++)
{
ArrayView<T> row = costs[i];
for (std::size_t j = 0; j < row.size(); j++)
{
row[j] = defaultCost;
}
}
}
template<typename T>
void MatchingOptimiser<T>::prepare()
{
if (transposed)
{
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
matrix[u][v] = costs[v][u];
}
}
}
else
{
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
matrix[u][v] = costs[u][v];
}
}
}
if (maximise)
{
double big = costs[0][0];
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
if (matrix[u][v] > big) big = matrix[u][v];
}
}
for (std::size_t u = 0; u < rows; u++)
{
for (std::size_t v = 0; v < columns; v++)
{
matrix[u][v] = big - matrix[u][v];
}
}
}
for (std::size_t t = 0; t < mapping.size(); t++)
{
mapping[t].u = Unused;
mapping[t].v = Unused;
}
chainLen = 0;
numColumnsCovered = 0;
for (std::size_t t = 0; t < rows; t++)
{
rowStars[t] = Unused;
rowPrimes[t] = Unused;
}
for (std::size_t t = 0; t < columns; t++)
{
columnStars[t] = Unused;
}
numColumnStars = 0;
numRowStars = 0;
numRowPrimes = 0;
rowsCovered.clear();
columnsCovered.clear();
rowPrimesTouched.clear();
}
template<typename T>
void MatchingOptimiser<T>::engageNext(std::size_t pi, std::size_t pj)
{
// InitChain(pi, pj);
chain[0] = pi;
chain[1] = pj;
chainLen = 2;
// TouchPrimedRow(pi);
rowPrimesTouched.add(pi);
for (;;)
{
if (columnStars[pj] != Unused)
{
// the starred zero being displaced is ...
std::size_t qj = pj;
std::size_t qi = columnStars[qj];
// AddStarChain(qi);
chain[chainLen++] = qi;
//if (!rowPrimes.contains(qi))
// throw new InternalError("Unexpected error in Hungarian method: The current row *should* have a primed entry.");
if (!rowPrimesTouched.contains(qi))
{
// the next primed zero in the chain is ...
std::size_t ri = qi;
std::size_t rj = rowPrimes[ri];
// AddPrimeChain(rj);
chain[chainLen++] = rj;
// rowPrimesTouched.set(ri, True);
rowPrimesTouched.add(ri);
pi = ri;
pj = rj;
}
else
break; // break: must break for now, due to local cycle.
}
else
break; // break: there are no more starred zeros in the primed zero's column.
}
// RemoveChainStars();
for (std::size_t c = 1; (c + 1) < chainLen; c += 2)
{
// RemoveStar(chain[c + 1], chain[c]);
std::size_t col = chain[c];
std::size_t row = chain[c + 1];
if (columnStars[col] != Unused) { columnStars[col] = Unused; numColumnStars--; }
if (rowStars[row] != Unused) { rowStars[row] = Unused; numRowStars--; }
}
// ResolveChainPrimes();
for (std::size_t c = 0; (c + 1) < chainLen; c += 2)
{
// AddStar(chain[c], target);
std::size_t row = chain[c];
std::size_t col = chain[c + 1];
if (columnStars[col] == Unused) numColumnStars++;
columnStars[col] = row;
if (rowStars[row] == Unused) numRowStars++;
rowStars[row] = col;
// CoverColumn(col);
numColumnsCovered++;
columnsCovered.add(col);
}
rowsCovered.clear();
rowPrimesTouched.clear();
numRowPrimes = 0;
for (std::size_t c = 0; c < rows; c++)
{
rowPrimes[c] = Unused;
}
// VerifyStars();
for (std::size_t c = 0; c < columns; c++)
{
if ((columnStars[c] != Unused) && !columnsCovered.contains(c))
{
// CoverColumn(c);
numColumnsCovered++;
columnsCovered.add(c);
}
}
}
template<typename T>
bool MatchingOptimiser<T>::findUncoveredZero(std::size_t& pi, std::size_t& pj)
{
for (std::size_t i = 0; i < rows; i++)
{
if (rowsCovered.contains(i)) continue;
for (std::size_t j = 0; j < columns; j++)
{
if (columnsCovered.contains(j)) continue;
// Exact test for 0 is ok due to subtraction performed in Hungarian method
if (matrix[i][j] == Zero)
{
pi = i;
pj = j;
return true;
}
}
}
return false;
}
template<typename T>
T MatchingOptimiser<T>::findSmallestUncovered()
{
T smallest = matrix[0][0];
for (std::size_t i = 0; i < rows; i++)
{
if (rowsCovered.contains(i)) continue;
for (std::size_t j = 0; j < columns; j++)
{
if (columnsCovered.contains(j)) continue;
T value = matrix[i][j];
if (value < smallest) smallest = value;
}
}
return smallest;
}
template<typename T>
void MatchingOptimiser<T>::doNext()
{
for (;;)
{
std::size_t pi, pj;
if (findUncoveredZero(pi, pj)) // populates pi and pj
{
// AddPrime(pi, pj);
numRowPrimes++;
rowPrimes[pi] = pj;
if (rowStars[pi] != Unused)
{
std::size_t j = rowStars[pi];
// UncoverColumn(j);
numColumnsCovered--;
columnsCovered.remove(j);
// CoverRow(pi);
rowsCovered.add(pi);
}
else
{
// We've primed a zero in a starless row.
engageNext(pi, pj);
return;
}
}
else
{
// There were no uncovered zeros, so they must be created.
T smallest = findSmallestUncovered();
for (std::size_t j = 0; j < columns; j++)
{
if (columnsCovered.contains(j)) continue;
for (std::size_t i = 0; i < rows; i++)
{
matrix[i][j] -= smallest;
}
}
for (std::size_t i = 0; i < rows; i++)
{
if (!rowsCovered.contains(i)) continue;
for (std::size_t j = 0; j < columns; j++)
{
matrix[i][j] += smallest;
}
}
}
}
}
template<typename T>
void MatchingOptimiser<T>::extractMapping()
{
for (std::size_t i = 0; i < rows; i++)
{
std::size_t j = rowStars[i];
// RecordResult(i, j);
if (transposed)
{
mapping[i].u = j;
mapping[i].v = i;
mapping[i].score = costs[j][i];
}
else
{
mapping[i].u = i;
mapping[i].v = j;
mapping[i].score = costs[i][j];
}
}
}
template<typename T>
const ArrayView<Matching<T> >& MatchingOptimiser<T>::solve(T& sum, bool excludeNegatives)
{
prepare();
while (numColumnsCovered < rows)
{
doNext();
}
extractMapping();
double localSum = 0.0;
if (excludeNegatives)
{
for (std::size_t i = 0; i < rows; i++)
{
if (mapping[i].score >= 0.0)
{
localSum += mapping[i].score;
}
}
}
else
{
for (std::size_t i = 0; i < rows; i++)
{
localSum += mapping[i].score;
}
}
sum = localSum;
return mapping;
}
}
<|endoftext|> |
<commit_before>
#pragma once
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
#include "utils.hpp"
namespace cinatra
{
class Request
{
public:
Request()
:method_(method_t::UNKNOWN)
{
}
Request(const std::string& url, const std::vector<char>& body,
const std::string& method, const std::string& path,
const CaseMap& query_map, const NcaseMultiMap& header)
:url_(url), body_(body), path_(path),
query_(query_map), header_(header)
{
if (boost::iequals(method, "GET"))
{
method_ = method_t::GET;
}
else if (boost::iequals(method, "PUT"))
{
method_ = method_t::PUT;
}
else if (boost::iequals(method, "POST"))
{
method_ = method_t::POST;
}
else if (boost::iequals(method, "DELETE"))
{
method_ = method_t::DELETE;
}
else if (boost::iequals(method, "TRACE"))
{
method_ = method_t::TRACE;
}
else if (boost::iequals(method, "CONNECT"))
{
method_ = method_t::CONNECT;
}
else if (boost::iequals(method, "HEAD"))
{
method_ = method_t::HEAD;
}
else if (boost::iequals(method, "OPTIONS"))
{
method_ = method_t::OPTIONS;
}
else
{
method_ = method_t::UNKNOWN;
}
}
enum class method_t
{
UNKNOWN,
GET,
PUT,
POST,
DELETE,
TRACE,
CONNECT,
HEAD,
OPTIONS
};
const std::string& url() const { return url_; }
method_t method() const { return method_; }
const std::string& host() const
{
return header_.get_val("host");
}
const std::vector<char>& body() const
{
return body_;
}
const std::string& path() const { return path_; }
const CaseMap& query() const { return query_; }
const NcaseMultiMap& header() const { return header_; }
int content_length() const
{
if (header_.get_count("Content-Length") == 0)
{
return 0;
}
// 这里可以不用担心cast抛异常,要抛异常在解析http header的时候就抛了
return boost::lexical_cast<int>(header_.get_val("Content-Length"));
}
const std::string& cookie() const
{
return header_.get_val("Cookie");
}
private:
std::string url_;
std::vector<char> body_;
method_t method_;
std::string path_;
CaseMap query_;
NcaseMultiMap header_;
};
inline CaseMap query_parser(const std::string& data)
{
return kv_parser<std::string::const_iterator, CaseMap, '=', '&'>(data.begin(), data.end(), false);
}
inline CaseMap body_parser(const std::vector<char>& data)
{
return kv_parser<std::vector<char>::const_iterator, CaseMap, '=', '&'>(data.begin(), data.end(), false);
}
inline CaseMap cookie_parser(const std::string& data)
{
return kv_parser<std::string::const_iterator, CaseMap, '=', ';'>(data.begin(), data.end(), true);
}
}
<commit_msg>添加fixme<commit_after>
#pragma once
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
#include "utils.hpp"
namespace cinatra
{
class Request
{
public:
Request()
:method_(method_t::UNKNOWN)
{
}
Request(const std::string& url, const std::vector<char>& body,
const std::string& method, const std::string& path,
const CaseMap& query_map, const NcaseMultiMap& header)
:url_(url), body_(body), path_(path),
query_(query_map), header_(header)
{
if (boost::iequals(method, "GET"))
{
method_ = method_t::GET;
}
else if (boost::iequals(method, "PUT"))
{
method_ = method_t::PUT;
}
else if (boost::iequals(method, "POST"))
{
method_ = method_t::POST;
}
else if (boost::iequals(method, "DELETE"))
{
method_ = method_t::DELETE;
}
else if (boost::iequals(method, "TRACE"))
{
method_ = method_t::TRACE;
}
else if (boost::iequals(method, "CONNECT"))
{
method_ = method_t::CONNECT;
}
else if (boost::iequals(method, "HEAD"))
{
method_ = method_t::HEAD;
}
else if (boost::iequals(method, "OPTIONS"))
{
method_ = method_t::OPTIONS;
}
else
{
method_ = method_t::UNKNOWN;
}
}
enum class method_t
{
UNKNOWN,
GET,
PUT,
POST,
DELETE,
TRACE,
CONNECT,
HEAD,
OPTIONS
};
const std::string& url() const { return url_; }
method_t method() const { return method_; }
const std::string& host() const
{
return header_.get_val("host");
}
const std::vector<char>& body() const
{
return body_;
}
const std::string& path() const { return path_; }
const CaseMap& query() const { return query_; }
const NcaseMultiMap& header() const { return header_; }
int content_length() const
{
if (header_.get_count("Content-Length") == 0)
{
return 0;
}
// 这里可以不用担心cast抛异常,要抛异常在解析http header的时候就抛了
return boost::lexical_cast<int>(header_.get_val("Content-Length"));
}
const std::string& cookie() const
{
return header_.get_val("Cookie");
}
private:
std::string url_;
std::vector<char> body_;
method_t method_;
std::string path_;
CaseMap query_;
NcaseMultiMap header_;
};
inline CaseMap query_parser(const std::string& data)
{
return kv_parser<std::string::const_iterator, CaseMap, '=', '&'>(data.begin(), data.end(), false);
}
inline CaseMap body_parser(const std::vector<char>& data)
{
return kv_parser<std::vector<char>::const_iterator, CaseMap, '=', '&'>(data.begin(), data.end(), false);
}
//FIXME: 这里还是应该重写,要不cookie的转义字符不好搞啊.
inline CaseMap cookie_parser(const std::string& data)
{
return kv_parser<std::string::const_iterator, CaseMap, '=', ';'>(data.begin(), data.end(), true);
}
}
<|endoftext|> |
<commit_before>
//
// Copyright (c) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CNRS
// Authors: Florent Lamiraux
//
// 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_PROBLEM_HH
# define HPP_CORE_PROBLEM_HH
# include <stdexcept>
# include <hpp/pinocchio/device.hh>
# include <hpp/util/pointer.hh>
# include <hpp/core/config.hh>
# include <hpp/core/steering-method.hh>
# include <hpp/core/container.hh>
# include <hpp/core/parameter.hh>
namespace hpp {
namespace core {
/// \addtogroup path_planning
/// \{
/// Defines a path planning problem for one robot.
/// A path planning problem is defined by
/// \li a robot: instance of class hpp::pinocchio::Device,
/// \li a set of obstacles: a list of hpp::pinocchio::CollisionObject,
/// \li initial and goal configurations,
/// \li a SteeringMethod to handle the robot dynamics,
/// Additional objects are stored in this object:
/// \li a method to validate paths,
/// \li a set of methods to validate configurations. Default methods are
/// collision checking and joint bound checking.
class HPP_CORE_DLLAPI Problem
{
public:
/// Create a path planning problem.
/// \param robot robot associated to the path planning problem.
Problem (DevicePtr_t robot);
virtual ~Problem ();
/// \name Problem definition
/// \{
/// return shared pointer to robot.
const DevicePtr_t& robot () const {
return robot_;
}
/// Get shared pointer to initial configuration.
const ConfigurationPtr_t& initConfig () const
{
return initConf_;
}
/// Set initial configuration.
void initConfig (const ConfigurationPtr_t& inConfig);
/// Set the target
void target (const ProblemTargetPtr_t& target)
{
target_ = target;
}
/// Get the target
const ProblemTargetPtr_t& target () const
{
return target_;
}
/// Get number of goal configuration.
const Configurations_t& goalConfigs () const;
/// Add goal configuration.
void addGoalConfig (const ConfigurationPtr_t& config);
/// Reset the set of goal configurations
void resetGoalConfigs ();
/// \}
/// \name Steering method and distance function
/// \{
/// Set steering method
/// \param sm steering method.
/// If problem contains constraints they are passed to the steering
/// method.
void steeringMethod (const SteeringMethodPtr_t& sm) {
steeringMethod_ = sm;
if (constraints_) steeringMethod_->constraints (constraints_);
}
/// Get steering method
SteeringMethodPtr_t steeringMethod () const {
return steeringMethod_;
}
/// Set distance between configurations
void distance (const DistancePtr_t& distance)
{
distance_ = distance;
}
/// Get distance between configuration
const DistancePtr_t& distance () const
{
return distance_;
}
/// \}
/// \name Configuration validation
/// \{
/// Set configuration validation methods
/// Before starting tos solve a path planning problem, the initial and
/// goal configurations are checked for validity.
void configValidation (const ConfigValidationsPtr_t& configValidations)
{
configValidations_ = configValidations;
}
/// Get configuration validation methods
const ConfigValidationsPtr_t& configValidations () const
{
return configValidations_;
}
/// Reset the ConfigValidations
void resetConfigValidations ();
// Clear the ConfigValidations
void clearConfigValidations ();
/// Add a config validation method
void addConfigValidation (const ConfigValidationPtr_t& configValidation);
/// \name Path validation
/// \{
/// Set path validation method
virtual void pathValidation (const PathValidationPtr_t& pathValidation);
/// Get path validation method
PathValidationPtr_t pathValidation () const
{
return pathValidation_;
}
/// \}
/// \name Configuration shooter
/// \{
/// Set configuration shooter method
void configurationShooter (const ConfigurationShooterPtr_t& configurationShooter);
/// Get path validation method
ConfigurationShooterPtr_t configurationShooter () const
{
return configurationShooter_;
}
/// \}
/// \name Path projector
/// \{
/// Set path projector method
void pathProjector (const PathProjectorPtr_t& pathProjector)
{
pathProjector_ = pathProjector;
}
/// Get path projector method
PathProjectorPtr_t pathProjector () const
{
return pathProjector_;
}
/// \}
/// \name Constraints applicable to the robot
/// \{
/// Set constraint set
/// \param constraints a set of constraints
/// If problem contains a steering method, constraints are passed to
/// the steering method.
void constraints (const ConstraintSetPtr_t& constraints)
{
constraints_ = constraints;
if (steeringMethod_) steeringMethod_->constraints (constraints);
}
///Get constraint set
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// \}
/// Check that problem is well formulated
virtual void checkProblem () const;
/// \name Obstacles
/// \{
/// Add obstacle to the list.
/// \param object a new object.
void addObstacle (const CollisionObjectPtr_t &object);
/// Remove a collision pair between a joint and an obstacle
/// \param the joint that holds the inner objects,
/// \param the obstacle to remove.
void removeObstacleFromJoint (const JointPtr_t& joint,
const CollisionObjectConstPtr_t& obstacle);
/// Build matrix of relative motions between joints
///
/// Loop over constraints in the current constraint set
/// (see Problem::constraints) and for each LockedJoint and each
/// constraints::RelativeTransformation, fill a matrix the column and
/// rows represent joints and the values are the following
/// \li RelativeMotionType::Constrained when the two joints are rigidly
/// fixed by the constraint,
/// \li RelativeMotionType::Parameterized when the two joints are rigidly
/// fixed by the constraint, the relative position is a parameter
/// constant along path, but that can change for different paths,
/// \li RelativeMotionType::Unconstrained when the two joints are not
/// rigidly fixed by the constraint.
///
/// \note the matrix is passed to the current configuration validation
/// instance (Problem::configValidation) and to the current
/// path validation instance (Problem::pathValidation).
void filterCollisionPairs ();
/// Vector of objects considered for collision detection
const ObjectStdVector_t &collisionObstacles() const;
/// Set the vector of objects considered for collision detection
void collisionObstacles (const ObjectStdVector_t &collisionObstacles);
/// \}
/// Get a parameter named name.
///
/// \param name of the parameter.
const Parameter& getParameter (const std::string& name) const
throw (std::invalid_argument)
{
if (parameters.has(name))
return parameters.get(name);
else
return parameterDescription(name).defaultValue();
}
/// Set a parameter named name.
///
/// \param name of the parameter.
/// \param value value of the parameter
/// \throw std::invalid_argument if a parameter exists but has a different
/// type.
void setParameter (const std::string& name, const Parameter& value)
throw (std::invalid_argument);
/// Declare a parameter
/// In shared library, use the following snippet in your cc file:
/// \code{.cpp}
/// HPP_START_PARAMETER_DECLARATION(name)
/// Problem::declareParameter (ParameterDescription (
/// Parameter::FLOAT,
/// "name",
/// "doc",
/// Parameter(value)));
/// HPP_END_PARAMETER_DECLARATION(name)
/// \endcode
static void declareParameter (const ParameterDescription& desc);
/// Get all the parameter descriptions
static const Container<ParameterDescription>& parameterDescriptions ();
/// Access one parameter description
static const ParameterDescription& parameterDescription (const std::string& name);
Container < Parameter > parameters;
private :
/// The robot
DevicePtr_t robot_;
/// Distance between configurations of the robot
DistancePtr_t distance_;
/// Shared pointer to initial configuration.
ConfigurationPtr_t initConf_;
/// Shared pointer to goal configuration.
Configurations_t goalConfigurations_;
/// Shared pointer to problem target
ProblemTargetPtr_t target_;
/// Steering method associated to the problem
SteeringMethodPtr_t steeringMethod_;
/// Configuration validation
ConfigValidationsPtr_t configValidations_;
/// Path validation
PathValidationPtr_t pathValidation_;
/// Path projector
PathProjectorPtr_t pathProjector_;
/// List of obstacles
ObjectStdVector_t collisionObstacles_;
/// Set of constraints applicable to the robot
ConstraintSetPtr_t constraints_;
/// Configuration shooter
ConfigurationShooterPtr_t configurationShooter_;
}; // class Problem
/// \}
} // namespace core
} // namespace hpp
#define HPP_START_PARAMETER_DECLARATION(name) \
struct HPP_CORE_DLLAPI __InitializerClass_##name { \
__InitializerClass_##name () {
#define HPP_END_PARAMETER_DECLARATION(name) \
} \
}; \
extern "C" { \
__InitializerClass_##name __instance_##name; \
}
#endif // HPP_CORE_PROBLEM_HH
<commit_msg>[Problem] Add forgotten declaration of constructor. (#121)<commit_after>
//
// Copyright (c) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CNRS
// Authors: Florent Lamiraux
//
// 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_PROBLEM_HH
# define HPP_CORE_PROBLEM_HH
# include <stdexcept>
# include <hpp/pinocchio/device.hh>
# include <hpp/util/pointer.hh>
# include <hpp/core/config.hh>
# include <hpp/core/steering-method.hh>
# include <hpp/core/container.hh>
# include <hpp/core/parameter.hh>
namespace hpp {
namespace core {
/// \addtogroup path_planning
/// \{
/// Defines a path planning problem for one robot.
/// A path planning problem is defined by
/// \li a robot: instance of class hpp::pinocchio::Device,
/// \li a set of obstacles: a list of hpp::pinocchio::CollisionObject,
/// \li initial and goal configurations,
/// \li a SteeringMethod to handle the robot dynamics,
/// Additional objects are stored in this object:
/// \li a method to validate paths,
/// \li a set of methods to validate configurations. Default methods are
/// collision checking and joint bound checking.
class HPP_CORE_DLLAPI Problem
{
public:
/// Create a path planning problem.
/// \param robot robot associated to the path planning problem.
Problem (DevicePtr_t robot);
/// Constructor without argument
/// \warning do not use this constructor. It is necessary to define
/// std::pairs <Problem, OtherType>.
Problem ();
virtual ~Problem ();
/// \name Problem definition
/// \{
/// return shared pointer to robot.
const DevicePtr_t& robot () const {
return robot_;
}
/// Get shared pointer to initial configuration.
const ConfigurationPtr_t& initConfig () const
{
return initConf_;
}
/// Set initial configuration.
void initConfig (const ConfigurationPtr_t& inConfig);
/// Set the target
void target (const ProblemTargetPtr_t& target)
{
target_ = target;
}
/// Get the target
const ProblemTargetPtr_t& target () const
{
return target_;
}
/// Get number of goal configuration.
const Configurations_t& goalConfigs () const;
/// Add goal configuration.
void addGoalConfig (const ConfigurationPtr_t& config);
/// Reset the set of goal configurations
void resetGoalConfigs ();
/// \}
/// \name Steering method and distance function
/// \{
/// Set steering method
/// \param sm steering method.
/// If problem contains constraints they are passed to the steering
/// method.
void steeringMethod (const SteeringMethodPtr_t& sm) {
steeringMethod_ = sm;
if (constraints_) steeringMethod_->constraints (constraints_);
}
/// Get steering method
SteeringMethodPtr_t steeringMethod () const {
return steeringMethod_;
}
/// Set distance between configurations
void distance (const DistancePtr_t& distance)
{
distance_ = distance;
}
/// Get distance between configuration
const DistancePtr_t& distance () const
{
return distance_;
}
/// \}
/// \name Configuration validation
/// \{
/// Set configuration validation methods
/// Before starting tos solve a path planning problem, the initial and
/// goal configurations are checked for validity.
void configValidation (const ConfigValidationsPtr_t& configValidations)
{
configValidations_ = configValidations;
}
/// Get configuration validation methods
const ConfigValidationsPtr_t& configValidations () const
{
return configValidations_;
}
/// Reset the ConfigValidations
void resetConfigValidations ();
// Clear the ConfigValidations
void clearConfigValidations ();
/// Add a config validation method
void addConfigValidation (const ConfigValidationPtr_t& configValidation);
/// \name Path validation
/// \{
/// Set path validation method
virtual void pathValidation (const PathValidationPtr_t& pathValidation);
/// Get path validation method
PathValidationPtr_t pathValidation () const
{
return pathValidation_;
}
/// \}
/// \name Configuration shooter
/// \{
/// Set configuration shooter method
void configurationShooter (const ConfigurationShooterPtr_t& configurationShooter);
/// Get path validation method
ConfigurationShooterPtr_t configurationShooter () const
{
return configurationShooter_;
}
/// \}
/// \name Path projector
/// \{
/// Set path projector method
void pathProjector (const PathProjectorPtr_t& pathProjector)
{
pathProjector_ = pathProjector;
}
/// Get path projector method
PathProjectorPtr_t pathProjector () const
{
return pathProjector_;
}
/// \}
/// \name Constraints applicable to the robot
/// \{
/// Set constraint set
/// \param constraints a set of constraints
/// If problem contains a steering method, constraints are passed to
/// the steering method.
void constraints (const ConstraintSetPtr_t& constraints)
{
constraints_ = constraints;
if (steeringMethod_) steeringMethod_->constraints (constraints);
}
///Get constraint set
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// \}
/// Check that problem is well formulated
virtual void checkProblem () const;
/// \name Obstacles
/// \{
/// Add obstacle to the list.
/// \param object a new object.
void addObstacle (const CollisionObjectPtr_t &object);
/// Remove a collision pair between a joint and an obstacle
/// \param the joint that holds the inner objects,
/// \param the obstacle to remove.
void removeObstacleFromJoint (const JointPtr_t& joint,
const CollisionObjectConstPtr_t& obstacle);
/// Build matrix of relative motions between joints
///
/// Loop over constraints in the current constraint set
/// (see Problem::constraints) and for each LockedJoint and each
/// constraints::RelativeTransformation, fill a matrix the column and
/// rows represent joints and the values are the following
/// \li RelativeMotionType::Constrained when the two joints are rigidly
/// fixed by the constraint,
/// \li RelativeMotionType::Parameterized when the two joints are rigidly
/// fixed by the constraint, the relative position is a parameter
/// constant along path, but that can change for different paths,
/// \li RelativeMotionType::Unconstrained when the two joints are not
/// rigidly fixed by the constraint.
///
/// \note the matrix is passed to the current configuration validation
/// instance (Problem::configValidation) and to the current
/// path validation instance (Problem::pathValidation).
void filterCollisionPairs ();
/// Vector of objects considered for collision detection
const ObjectStdVector_t &collisionObstacles() const;
/// Set the vector of objects considered for collision detection
void collisionObstacles (const ObjectStdVector_t &collisionObstacles);
/// \}
/// Get a parameter named name.
///
/// \param name of the parameter.
const Parameter& getParameter (const std::string& name) const
throw (std::invalid_argument)
{
if (parameters.has(name))
return parameters.get(name);
else
return parameterDescription(name).defaultValue();
}
/// Set a parameter named name.
///
/// \param name of the parameter.
/// \param value value of the parameter
/// \throw std::invalid_argument if a parameter exists but has a different
/// type.
void setParameter (const std::string& name, const Parameter& value)
throw (std::invalid_argument);
/// Declare a parameter
/// In shared library, use the following snippet in your cc file:
/// \code{.cpp}
/// HPP_START_PARAMETER_DECLARATION(name)
/// Problem::declareParameter (ParameterDescription (
/// Parameter::FLOAT,
/// "name",
/// "doc",
/// Parameter(value)));
/// HPP_END_PARAMETER_DECLARATION(name)
/// \endcode
static void declareParameter (const ParameterDescription& desc);
/// Get all the parameter descriptions
static const Container<ParameterDescription>& parameterDescriptions ();
/// Access one parameter description
static const ParameterDescription& parameterDescription (const std::string& name);
Container < Parameter > parameters;
private :
/// The robot
DevicePtr_t robot_;
/// Distance between configurations of the robot
DistancePtr_t distance_;
/// Shared pointer to initial configuration.
ConfigurationPtr_t initConf_;
/// Shared pointer to goal configuration.
Configurations_t goalConfigurations_;
/// Shared pointer to problem target
ProblemTargetPtr_t target_;
/// Steering method associated to the problem
SteeringMethodPtr_t steeringMethod_;
/// Configuration validation
ConfigValidationsPtr_t configValidations_;
/// Path validation
PathValidationPtr_t pathValidation_;
/// Path projector
PathProjectorPtr_t pathProjector_;
/// List of obstacles
ObjectStdVector_t collisionObstacles_;
/// Set of constraints applicable to the robot
ConstraintSetPtr_t constraints_;
/// Configuration shooter
ConfigurationShooterPtr_t configurationShooter_;
}; // class Problem
/// \}
} // namespace core
} // namespace hpp
#define HPP_START_PARAMETER_DECLARATION(name) \
struct HPP_CORE_DLLAPI __InitializerClass_##name { \
__InitializerClass_##name () {
#define HPP_END_PARAMETER_DECLARATION(name) \
} \
}; \
extern "C" { \
__InitializerClass_##name __instance_##name; \
}
#endif // HPP_CORE_PROBLEM_HH
<|endoftext|> |
<commit_before>/**
** \file libport/contract.hh
** \brief Replacement for cassert.
**/
#ifndef LIBPORT_CONTRACT_HH
# define LIBPORT_CONTRACT_HH
#include "libport/compiler.hh"
ATTRIBUTE_NORETURN void __Terminate (const char*, int, const char*);
# define die(reason) __Terminate (__FILE__, __LINE__, reason)
# define unreached() die ("unreachable code reached")
# ifdef NDEBUG
# define assertion(expr) ((void) 0)
# define iassertion(expr) (expr)
# define precondition(expr) ((void) 0)
# define postcondition(expr) ((void) 0)
# else // NDEBUG
ATTRIBUTE_NORETURN
void __FailedCondition (const char* condType,
const char* condText,
const char* fileName,
int fileLine);
# define __TestCondition(condType,expr) \
((void) ((expr) ? 0 : (__FailedCondition ( #condType, #expr, \
__FILE__, __LINE__ ), 0)))
template<typename T>
inline T __iassert (T expr, const char* expr_str, const char* file, int line)
{
if (expr)
return expr;
__FailedCondition ("Assertion", expr_str, file, line);
}
# define iassertion(expr) \
__iassert ((expr), #expr, __FILE__, __LINE__ )
# define assertion(expr) __TestCondition (Assertion,expr)
# define precondition(expr) __TestCondition (Precondition,expr)
# define postcondition(expr) __TestCondition (Postcondition,expr)
# endif // ! NDEBUG
#endif // !LIBPORT_CONTRACT_HH
<commit_msg>Use references in iassertion to avoid copies<commit_after>/**
** \file libport/contract.hh
** \brief Replacement for cassert.
**/
#ifndef LIBPORT_CONTRACT_HH
# define LIBPORT_CONTRACT_HH
#include "libport/compiler.hh"
ATTRIBUTE_NORETURN void __Terminate (const char*, int, const char*);
# define die(reason) __Terminate (__FILE__, __LINE__, reason)
# define unreached() die ("unreachable code reached")
# ifdef NDEBUG
# define assertion(expr) ((void) 0)
# define iassertion(expr) (expr)
# define precondition(expr) ((void) 0)
# define postcondition(expr) ((void) 0)
# else // NDEBUG
ATTRIBUTE_NORETURN
void __FailedCondition (const char* condType,
const char* condText,
const char* fileName,
int fileLine);
# define __TestCondition(condType,expr) \
((void) ((expr) ? 0 : (__FailedCondition ( #condType, #expr, \
__FILE__, __LINE__ ), 0)))
template<typename T>
inline T&
__iassert (T& expr, const char* expr_str, const char* file, int line)
{
if (expr)
return expr;
__FailedCondition ("Assertion", expr_str, file, line);
}
# define iassertion(expr) \
__iassert ((expr), #expr, __FILE__, __LINE__ )
# define assertion(expr) __TestCondition (Assertion,expr)
# define precondition(expr) __TestCondition (Precondition,expr)
# define postcondition(expr) __TestCondition (Postcondition,expr)
# endif // ! NDEBUG
#endif // !LIBPORT_CONTRACT_HH
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file scope_exit.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Provides a convenient class that executes a lambda on scope exit
//----------------------------------------------------------------------------
// Copyright (c) 2014 Serge Aleynikov <saleyn@gmail.com>
// Created: 2014-07-24
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2014 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_SCOPE_EXIT_HPP_
#define _UTXX_SCOPE_EXIT_HPP_
#if __cplusplus >= 201103L
#include <functional>
#include <utxx/compiler_hints.hpp>
namespace utxx {
/// Call lambda function on exiting scope
template <typename Lambda>
class on_scope_exit {
Lambda m_lambda;
bool m_disable;
on_scope_exit() = delete;
public:
on_scope_exit(const Lambda& a_lambda)
: m_lambda (a_lambda)
, m_disable(false)
{}
on_scope_exit(Lambda&& a_lambda)
: m_lambda(a_lambda)
, m_disable(false)
{
a_lambda = nullptr;
}
/// If disabled the lambda won't be called at scope exit
void disable(bool a_disable = true) { m_disable = a_disable; }
~on_scope_exit() {
if (!m_disable)
m_lambda();
}
};
/// Call functor on exiting scope
class scope_exit : public on_scope_exit<std::function<void()>> {
using base = on_scope_exit<std::function<void()>>;
public:
using base::base;
};
#define UTXX_GLUE2(A,B,C) A##B##C
#define UTXX_GLUE(A,B,C) UTXX_GLUE2(A,B,C)
#define UTXX_SCOPE_EXIT(Fun) \
auto UTXX_GLUE(__on_exit, __LINE__, _fun) = Fun; \
utxx::on_scope_exit<decltype(UTXX_GLUE(__on_exit, __LINE__, _fun))> \
UTXX_GLUE(__on_exit, __LINE__, _var) (UTXX_GLUE(__on_exit, __LINE__, _fun))
} // namespace utxx
#endif
#endif //_UTXX_SCOPE_EXIT_HPP_
<commit_msg>Update scope_exit.hpp<commit_after>//----------------------------------------------------------------------------
/// \file scope_exit.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Provides a convenient class that executes a lambda on scope exit
//----------------------------------------------------------------------------
// Copyright (c) 2014 Serge Aleynikov <saleyn@gmail.com>
// Created: 2014-07-24
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2014 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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
***** END LICENSE BLOCK *****
*/
#pragma once
#if __cplusplus >= 201103L
#include <functional>
#include <utxx/compiler_hints.hpp>
namespace utxx {
/// Call lambda function on exiting scope
template <typename Lambda>
class on_scope_exit {
Lambda m_lambda;
bool m_disable;
on_scope_exit() = delete;
public:
on_scope_exit(const Lambda& a_lambda)
: m_lambda (a_lambda)
, m_disable(false)
{}
on_scope_exit(Lambda&& a_lambda)
: m_lambda(a_lambda)
, m_disable(false)
{
a_lambda = nullptr;
}
/// If disabled the lambda won't be called at scope exit
void disable(bool a_disable = true) { m_disable = a_disable; }
~on_scope_exit() {
if (!m_disable)
m_lambda();
}
};
/// Call functor on exiting scope
class scope_exit : public on_scope_exit<std::function<void()>> {
using base = on_scope_exit<std::function<void()>>;
public:
using base::base;
};
#define UTXX_GLUE2(A,B,C) A##B##C
#define UTXX_GLUE(A,B,C) UTXX_GLUE2(A,B,C)
#define UTXX_SCOPE_EXIT(Fun) \
auto UTXX_GLUE(__on_exit, __LINE__, _fun) = Fun; \
utxx::on_scope_exit<decltype(UTXX_GLUE(__on_exit, __LINE__, _fun))> \
UTXX_GLUE(__on_exit, __LINE__, _var) (UTXX_GLUE(__on_exit, __LINE__, _fun))
} // namespace utxx
#endif
<|endoftext|> |
<commit_before>// Wheels - various C++ utilities
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
// Boolean conjunction meta-function
#ifndef WHEELS_META_ALL_HPP
#define WHEELS_META_ALL_HPP
#include <wheels/meta/invoke.h++>
#include <wheels/meta/bool.h++>
#include <wheels/meta/if.h++>
namespace wheels {
namespace meta {
// Boolean conjunction meta-function
// *Returns*: `True` if all `T::value` are `true`; `False` otherwise.
template <typename... T>
struct all : True {};
template <typename H, typename... T>
struct all<H, T...> : If<H, All<T...>, False> {};
template <typename... T>
using All = Invoke<all<T...>>;
} // namespace meta
} // namespace wheels
#endif // WHEELS_META_ALL_HPP
<commit_msg>Fix bug in all<commit_after>// Wheels - various C++ utilities
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
// Boolean conjunction meta-function
#ifndef WHEELS_META_ALL_HPP
#define WHEELS_META_ALL_HPP
#include <wheels/meta/invoke.h++>
#include <wheels/meta/bool.h++>
#include <wheels/meta/if.h++>
namespace wheels {
namespace meta {
// Boolean conjunction meta-function
// *Returns*: `True` if all `T::value` are `true`; `False` otherwise.
template <typename... T>
struct all : True {};
template <typename H, typename... T>
struct all<H, T...> : If<H, all<T...>, False> {};
template <typename... T>
using All = Invoke<all<T...>>;
} // namespace meta
} // namespace wheels
#endif // WHEELS_META_ALL_HPP
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/stream_pool.h"
#include "absl/memory/memory.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
StreamPool::Ptr StreamPool::BorrowStream(se::StreamExecutor* executor) {
std::unique_ptr<se::Stream> stream;
{
tensorflow::mutex_lock lock(mu_);
if (!streams_.empty()) {
// Re-use an existing stream from the pool.
stream = std::move(streams_.back());
streams_.pop_back();
if (stream->ok()) {
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool reusing existing stream";
} else {
VLOG(1) << stream->DebugStreamPointers()
<< " stream was not ok, StreamPool deleting";
stream = nullptr;
}
}
}
if (!stream) {
// Create a new stream.
stream = absl::make_unique<se::Stream>(executor);
stream->Init();
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool created new stream";
}
// Return the stream wrapped in Ptr, which has our special deleter semantics.
PtrDeleter deleter = {this};
return Ptr(stream.release(), deleter);
}
void StreamPool::ReturnStream(se::Stream* stream) {
if (stream->ok()) {
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool returning ok stream";
tensorflow::mutex_lock lock(mu_);
streams_.emplace_back(stream);
} else {
// If the stream has encountered any errors, all subsequent operations on it
// will fail. So just delete the stream, and rely on new streams to be
// created in the future.
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool deleting !ok stream";
delete stream;
}
}
} // namespace xla
<commit_msg>If the first stream is bad, try again instead of giving up.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/stream_pool.h"
#include "absl/memory/memory.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
StreamPool::Ptr StreamPool::BorrowStream(se::StreamExecutor* executor) {
std::unique_ptr<se::Stream> stream;
{
tensorflow::mutex_lock lock(mu_);
while (!streams_.empty() && !stream) {
// Re-use an existing stream from the pool.
stream = std::move(streams_.back());
streams_.pop_back();
if (stream->ok()) {
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool reusing existing stream";
} else {
VLOG(1) << stream->DebugStreamPointers()
<< " stream was not ok, StreamPool deleting";
stream = nullptr;
}
}
}
if (!stream) {
// Create a new stream.
stream = absl::make_unique<se::Stream>(executor);
stream->Init();
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool created new stream";
}
// Return the stream wrapped in Ptr, which has our special deleter semantics.
PtrDeleter deleter = {this};
return Ptr(stream.release(), deleter);
}
void StreamPool::ReturnStream(se::Stream* stream) {
if (stream->ok()) {
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool returning ok stream";
tensorflow::mutex_lock lock(mu_);
streams_.emplace_back(stream);
} else {
// If the stream has encountered any errors, all subsequent operations on it
// will fail. So just delete the stream, and rely on new streams to be
// created in the future.
VLOG(1) << stream->DebugStreamPointers()
<< " StreamPool deleting !ok stream";
delete stream;
}
}
} // namespace xla
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <random>
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/xent_op.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
static Graph* SparseXent(int batch_size, int num_classes, DataType value_type) {
Graph* g = new Graph(OpRegistry::Global());
Tensor logits(value_type, TensorShape({batch_size, num_classes}));
logits.flat<float>().setRandom();
Tensor labels(DT_INT64, TensorShape({batch_size}));
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, num_classes - 1);
auto labels_t = labels.flat<int64>();
for (int i = 0; i < batch_size; ++i) {
labels_t(i) = dist(gen);
}
test::graph::Binary(g, "SparseSoftmaxCrossEntropyWithLogits",
test::graph::Constant(g, logits),
test::graph::Constant(g, labels));
return g;
}
#define BM_SparseXentDev(BATCH, CLASS, DEVICE, DTType) \
static void BM_SparseXent##_##BATCH##_##CLASS##_##DEVICE_##DTType(int iters) { \
testing::ItemsProcessed(static_cast<int64>(iters) * BATCH * CLASS); \
test::Benchmark(#DEVICE, SparseXent(BATCH, CLASS, DTType)).Run(iters); \
} \
BENCHMARK(BM_SparseXent##_##BATCH##_##CLASS##_##DEVICE_##DTType);
/// The representative tests for ptb_word on GPU
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
BM_SparseXentDev(8, 1000000, gpu, DT_FLOAT);
BM_SparseXentDev(16, 10000, gpu, DT_FLOAT);
BM_SparseXentDev(16, 30000, gpu, DT_FLOAT);
BM_SparseXentDev(16, 100000, gpu, DT_FLOAT);
BM_SparseXentDev(32, 10000, gpu, DT_FLOAT);
BM_SparseXentDev(32, 30000, gpu, DT_FLOAT);
BM_SparseXentDev(32, 100000, gpu, DT_FLOAT);
BM_SparseXentDev(64, 10000, gpu, DT_FLOAT);
BM_SparseXentDev(64, 30000, gpu, DT_FLOAT);
BM_SparseXentDev(64, 100000, gpu, DT_FLOAT);
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// CPU
BM_SparseXentDev(8, 1000000, cpu, DT_FLOAT);
BM_SparseXentDev(16, 10000, cpu, DT_FLOAT);
BM_SparseXentDev(16, 100000, cpu, DT_FLOAT);
BM_SparseXentDev(32, 10000, cpu, DT_FLOAT);
BM_SparseXentDev(32, 100000, cpu, DT_FLOAT);
BM_SparseXentDev(64, 10000, cpu, DT_FLOAT);
BM_SparseXentDev(64, 100000, cpu, DT_FLOAT);
BM_SparseXentDev(8, 1000000, cpu, DT_BFLOAT16);
BM_SparseXentDev(16, 10000, cpu, DT_BFLOAT16);
BM_SparseXentDev(16, 100000, cpu, DT_BFLOAT16);
BM_SparseXentDev(32, 10000, cpu, DT_BFLOAT16);
BM_SparseXentDev(32, 100000, cpu, DT_BFLOAT16);
BM_SparseXentDev(64, 10000, cpu, DT_BFLOAT16);
BM_SparseXentDev(64, 100000, cpu, DT_BFLOAT16);
} // end namespace tensorflow
<commit_msg>Code format<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <random>
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/xent_op.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
static Graph* SparseXent(int batch_size, int num_classes, DataType value_type) {
Graph* g = new Graph(OpRegistry::Global());
Tensor logits(value_type, TensorShape({batch_size, num_classes}));
logits.flat<float>().setRandom();
Tensor labels(DT_INT64, TensorShape({batch_size}));
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, num_classes - 1);
auto labels_t = labels.flat<int64>();
for (int i = 0; i < batch_size; ++i) {
labels_t(i) = dist(gen);
}
test::graph::Binary(g, "SparseSoftmaxCrossEntropyWithLogits",
test::graph::Constant(g, logits),
test::graph::Constant(g, labels));
return g;
}
#define BM_SparseXentDev(BATCH, CLASS, DEVICE, DTType) \
static void BM_SparseXent##_##BATCH##_##CLASS##_##DEVICE_##DTType( \
int iters) { \
testing::ItemsProcessed(static_cast<int64>(iters) * BATCH * CLASS); \
test::Benchmark(#DEVICE, SparseXent(BATCH, CLASS, DTType)).Run(iters); \
} \
BENCHMARK(BM_SparseXent##_##BATCH##_##CLASS##_##DEVICE_##DTType);
/// The representative tests for ptb_word on GPU
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
BM_SparseXentDev(8, 1000000, gpu, DT_FLOAT);
BM_SparseXentDev(16, 10000, gpu, DT_FLOAT);
BM_SparseXentDev(16, 30000, gpu, DT_FLOAT);
BM_SparseXentDev(16, 100000, gpu, DT_FLOAT);
BM_SparseXentDev(32, 10000, gpu, DT_FLOAT);
BM_SparseXentDev(32, 30000, gpu, DT_FLOAT);
BM_SparseXentDev(32, 100000, gpu, DT_FLOAT);
BM_SparseXentDev(64, 10000, gpu, DT_FLOAT);
BM_SparseXentDev(64, 30000, gpu, DT_FLOAT);
BM_SparseXentDev(64, 100000, gpu, DT_FLOAT);
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// CPU
BM_SparseXentDev(8, 1000000, cpu, DT_FLOAT);
BM_SparseXentDev(16, 10000, cpu, DT_FLOAT);
BM_SparseXentDev(16, 100000, cpu, DT_FLOAT);
BM_SparseXentDev(32, 10000, cpu, DT_FLOAT);
BM_SparseXentDev(32, 100000, cpu, DT_FLOAT);
BM_SparseXentDev(64, 10000, cpu, DT_FLOAT);
BM_SparseXentDev(64, 100000, cpu, DT_FLOAT);
BM_SparseXentDev(8, 1000000, cpu, DT_BFLOAT16);
BM_SparseXentDev(16, 10000, cpu, DT_BFLOAT16);
BM_SparseXentDev(16, 100000, cpu, DT_BFLOAT16);
BM_SparseXentDev(32, 10000, cpu, DT_BFLOAT16);
BM_SparseXentDev(32, 100000, cpu, DT_BFLOAT16);
BM_SparseXentDev(64, 10000, cpu, DT_BFLOAT16);
BM_SparseXentDev(64, 100000, cpu, DT_BFLOAT16);
} // end namespace tensorflow
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
struct notlit { // expected-note {{not literal because}}
notlit() {}
};
struct notlit2 {
notlit2() {}
};
// valid declarations
constexpr int i1 = 0;
constexpr int f1() { return 0; }
struct s1 {
constexpr static int mi1 = 0;
const static int mi2;
};
constexpr int s1::mi2 = 0;
// invalid declarations
// not a definition of an object
constexpr extern int i2; // expected-error {{constexpr variable declaration must be a definition}}
// not a literal type
constexpr notlit nl1; // expected-error {{constexpr variable cannot have non-literal type 'const notlit'}}
// function parameters
void f2(constexpr int i) {} // expected-error {{function parameter cannot be constexpr}}
// non-static member
struct s2 {
constexpr int mi1; // expected-error {{non-static data member cannot be constexpr; did you intend to make it const?}}
static constexpr int mi2; // expected-error {{requires an initializer}}
// FIXME: verify that there's no extra suffix in this error. -verify doesn't support anything like that at the moment as far as I know
mutable constexpr int mi3; // expected-error {{non-static data member cannot be constexpr}} expected-error {{'mutable' and 'const' cannot be mixed}}
};
// typedef
typedef constexpr int CI; // expected-error {{typedef cannot be constexpr}}
// tag
constexpr class C1 {}; // expected-error {{class cannot be marked constexpr}}
constexpr struct S1 {}; // expected-error {{struct cannot be marked constexpr}}
constexpr union U1 {}; // expected-error {{union cannot be marked constexpr}}
constexpr enum E1 {}; // expected-error {{enum cannot be marked constexpr}}
template <typename T> constexpr class TC1 {}; // expected-error {{class cannot be marked constexpr}}
template <typename T> constexpr struct TS1 {}; // expected-error {{struct cannot be marked constexpr}}
template <typename T> constexpr union TU1 {}; // expected-error {{union cannot be marked constexpr}}
class C2 {} constexpr; // expected-error {{class cannot be marked constexpr}}
struct S2 {} constexpr; // expected-error {{struct cannot be marked constexpr}}
union U2 {} constexpr; // expected-error {{union cannot be marked constexpr}}
enum E2 {} constexpr; // expected-error {{enum cannot be marked constexpr}}
constexpr class C3 {} c3 = C3();
constexpr struct S3 {} s3 = S3();
constexpr union U3 {} u3 = {};
constexpr enum E3 { V3 } e3 = V3;
class C4 {} constexpr c4 = C4();
struct S4 {} constexpr s4 = S4();
union U4 {} constexpr u4 = {};
enum E4 { V4 } constexpr e4 = V4;
constexpr int; // expected-error {{constexpr can only be used in variable and function declarations}}
// redeclaration mismatch
constexpr int f3(); // expected-note {{previous declaration is here}}
int f3(); // expected-error {{non-constexpr declaration of 'f3' follows constexpr declaration}}
int f4(); // expected-note {{previous declaration is here}}
constexpr int f4(); // expected-error {{constexpr declaration of 'f4' follows non-constexpr declaration}}
template<typename T> constexpr T f5(T);
template<typename T> constexpr T f5(T); // expected-note {{previous}}
template<typename T> T f5(T); // expected-error {{non-constexpr declaration of 'f5' follows constexpr declaration}}
template<typename T> T f6(T); // expected-note {{here}}
template<typename T> constexpr T f6(T); // expected-error {{constexpr declaration of 'f6' follows non-constexpr declaration}}
// destructor
struct ConstexprDtor {
constexpr ~ConstexprDtor() = default; // expected-error {{destructor cannot be marked constexpr}}
};
// template stuff
template <typename T> constexpr T ft(T t) { return t; }
template <typename T> T gt(T t) { return t; }
struct S {
template<typename T> constexpr T f();
template<typename T> T g() const;
};
// explicit specialization can differ in constepxr
template <> notlit ft(notlit nl) { return nl; }
template <> char ft(char c) { return c; } // expected-note {{previous}}
template <> constexpr char ft(char nl); // expected-error {{constexpr declaration of 'ft<char>' follows non-constexpr declaration}}
template <> constexpr int gt(int nl) { return nl; }
template <> notlit S::f() const { return notlit(); }
template <> constexpr int S::g() { return 0; } // expected-note {{previous}}
template <> int S::g() const; // expected-error {{non-constexpr declaration of 'g<int>' follows constexpr declaration}}
// specializations can drop the 'constexpr' but not the implied 'const'.
template <> char S::g() { return 0; } // expected-error {{no function template matches}}
template <> double S::g() const { return 0; } // ok
constexpr int i3 = ft(1);
void test() {
// ignore constexpr when instantiating with non-literal
notlit2 nl2;
(void)ft(nl2);
}
// Examples from the standard:
constexpr int square(int x); // expected-note {{declared here}}
constexpr int bufsz = 1024;
constexpr struct pixel { // expected-error {{struct cannot be marked constexpr}}
int x;
int y;
constexpr pixel(int);
};
constexpr pixel::pixel(int a)
: x(square(a)), y(square(a)) // expected-note {{undefined function 'square' cannot be used in a constant expression}}
{ }
constexpr pixel small(2); // expected-error {{must be initialized by a constant expression}} expected-note {{in call to 'pixel(2)'}}
constexpr int square(int x) {
return x * x;
}
constexpr pixel large(4);
int next(constexpr int x) { // expected-error {{function parameter cannot be constexpr}}
return x + 1;
}
extern constexpr int memsz; // expected-error {{constexpr variable declaration must be a definition}}
<commit_msg>[Sema] Constrain test added in r173873 with expected-error-re<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
struct notlit { // expected-note {{not literal because}}
notlit() {}
};
struct notlit2 {
notlit2() {}
};
// valid declarations
constexpr int i1 = 0;
constexpr int f1() { return 0; }
struct s1 {
constexpr static int mi1 = 0;
const static int mi2;
};
constexpr int s1::mi2 = 0;
// invalid declarations
// not a definition of an object
constexpr extern int i2; // expected-error {{constexpr variable declaration must be a definition}}
// not a literal type
constexpr notlit nl1; // expected-error {{constexpr variable cannot have non-literal type 'const notlit'}}
// function parameters
void f2(constexpr int i) {} // expected-error {{function parameter cannot be constexpr}}
// non-static member
struct s2 {
constexpr int mi1; // expected-error {{non-static data member cannot be constexpr; did you intend to make it const?}}
static constexpr int mi2; // expected-error {{requires an initializer}}
mutable constexpr int mi3 = 3; // expected-error-re {{non-static data member cannot be constexpr$}} expected-error {{'mutable' and 'const' cannot be mixed}}
};
// typedef
typedef constexpr int CI; // expected-error {{typedef cannot be constexpr}}
// tag
constexpr class C1 {}; // expected-error {{class cannot be marked constexpr}}
constexpr struct S1 {}; // expected-error {{struct cannot be marked constexpr}}
constexpr union U1 {}; // expected-error {{union cannot be marked constexpr}}
constexpr enum E1 {}; // expected-error {{enum cannot be marked constexpr}}
template <typename T> constexpr class TC1 {}; // expected-error {{class cannot be marked constexpr}}
template <typename T> constexpr struct TS1 {}; // expected-error {{struct cannot be marked constexpr}}
template <typename T> constexpr union TU1 {}; // expected-error {{union cannot be marked constexpr}}
class C2 {} constexpr; // expected-error {{class cannot be marked constexpr}}
struct S2 {} constexpr; // expected-error {{struct cannot be marked constexpr}}
union U2 {} constexpr; // expected-error {{union cannot be marked constexpr}}
enum E2 {} constexpr; // expected-error {{enum cannot be marked constexpr}}
constexpr class C3 {} c3 = C3();
constexpr struct S3 {} s3 = S3();
constexpr union U3 {} u3 = {};
constexpr enum E3 { V3 } e3 = V3;
class C4 {} constexpr c4 = C4();
struct S4 {} constexpr s4 = S4();
union U4 {} constexpr u4 = {};
enum E4 { V4 } constexpr e4 = V4;
constexpr int; // expected-error {{constexpr can only be used in variable and function declarations}}
// redeclaration mismatch
constexpr int f3(); // expected-note {{previous declaration is here}}
int f3(); // expected-error {{non-constexpr declaration of 'f3' follows constexpr declaration}}
int f4(); // expected-note {{previous declaration is here}}
constexpr int f4(); // expected-error {{constexpr declaration of 'f4' follows non-constexpr declaration}}
template<typename T> constexpr T f5(T);
template<typename T> constexpr T f5(T); // expected-note {{previous}}
template<typename T> T f5(T); // expected-error {{non-constexpr declaration of 'f5' follows constexpr declaration}}
template<typename T> T f6(T); // expected-note {{here}}
template<typename T> constexpr T f6(T); // expected-error {{constexpr declaration of 'f6' follows non-constexpr declaration}}
// destructor
struct ConstexprDtor {
constexpr ~ConstexprDtor() = default; // expected-error {{destructor cannot be marked constexpr}}
};
// template stuff
template <typename T> constexpr T ft(T t) { return t; }
template <typename T> T gt(T t) { return t; }
struct S {
template<typename T> constexpr T f();
template<typename T> T g() const;
};
// explicit specialization can differ in constepxr
template <> notlit ft(notlit nl) { return nl; }
template <> char ft(char c) { return c; } // expected-note {{previous}}
template <> constexpr char ft(char nl); // expected-error {{constexpr declaration of 'ft<char>' follows non-constexpr declaration}}
template <> constexpr int gt(int nl) { return nl; }
template <> notlit S::f() const { return notlit(); }
template <> constexpr int S::g() { return 0; } // expected-note {{previous}}
template <> int S::g() const; // expected-error {{non-constexpr declaration of 'g<int>' follows constexpr declaration}}
// specializations can drop the 'constexpr' but not the implied 'const'.
template <> char S::g() { return 0; } // expected-error {{no function template matches}}
template <> double S::g() const { return 0; } // ok
constexpr int i3 = ft(1);
void test() {
// ignore constexpr when instantiating with non-literal
notlit2 nl2;
(void)ft(nl2);
}
// Examples from the standard:
constexpr int square(int x); // expected-note {{declared here}}
constexpr int bufsz = 1024;
constexpr struct pixel { // expected-error {{struct cannot be marked constexpr}}
int x;
int y;
constexpr pixel(int);
};
constexpr pixel::pixel(int a)
: x(square(a)), y(square(a)) // expected-note {{undefined function 'square' cannot be used in a constant expression}}
{ }
constexpr pixel small(2); // expected-error {{must be initialized by a constant expression}} expected-note {{in call to 'pixel(2)'}}
constexpr int square(int x) {
return x * x;
}
constexpr pixel large(4);
int next(constexpr int x) { // expected-error {{function parameter cannot be constexpr}}
return x + 1;
}
extern constexpr int memsz; // expected-error {{constexpr variable declaration must be a definition}}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <utility>
#include "atom/utility/atom_content_utility_client.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "brave/utility/importer/brave_profile_import_service.h"
#include "chrome/common/importer/profile_import.mojom.h"
#include "chrome/common/resource_usage_reporter.mojom.h"
#include "chrome/utility/extensions/extensions_handler.h"
#include "chrome/utility/utility_message_handler.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/simple_connection_filter.h"
#include "content/public/utility/utility_thread.h"
#include "extensions/features/features.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_message_macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "printing/features/features.h"
#include "services/proxy_resolver/proxy_resolver_service.h"
#include "services/proxy_resolver/public/interfaces/proxy_resolver.mojom.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/common/extensions/chrome_extensions_client.h"
#include "extensions/utility/utility_handler.h"
#endif
#if BUILDFLAG(ENABLE_PRINT_PREVIEW) || \
(BUILDFLAG(ENABLE_BASIC_PRINTING) && defined(OS_WIN))
#include "chrome/utility/printing_handler.h"
#endif
namespace atom {
namespace {
class ResourceUsageReporterImpl : public chrome::mojom::ResourceUsageReporter {
public:
ResourceUsageReporterImpl() {}
~ResourceUsageReporterImpl() override {}
private:
void GetUsageData(const GetUsageDataCallback& callback) override {
chrome::mojom::ResourceUsageDataPtr data =
chrome::mojom::ResourceUsageData::New();
size_t total_heap_size = net::ProxyResolverV8::GetTotalHeapSize();
if (total_heap_size) {
data->reports_v8_stats = true;
data->v8_bytes_allocated = total_heap_size;
data->v8_bytes_used = net::ProxyResolverV8::GetUsedHeapSize();
}
callback.Run(std::move(data));
}
};
void CreateResourceUsageReporter(
mojo::InterfaceRequest<chrome::mojom::ResourceUsageReporter> request) {
mojo::MakeStrongBinding(base::MakeUnique<ResourceUsageReporterImpl>(),
std::move(request));
}
} // namespace
AtomContentUtilityClient::AtomContentUtilityClient()
: utility_process_running_elevated_(false) {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW) || \
(BUILDFLAG(ENABLE_BASIC_PRINTING) && defined(OS_WIN))
handlers_.push_back(base::MakeUnique<printing::PrintingHandler>());
#endif
}
AtomContentUtilityClient::~AtomContentUtilityClient() = default;
void AtomContentUtilityClient::UtilityThreadStarted() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::utility_handler::UtilityThreadStarted();
#endif
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kUtilityProcessRunningElevated))
utility_process_running_elevated_ = true;
content::ServiceManagerConnection* connection =
content::ChildThread::Get()->GetServiceManagerConnection();
// NOTE: Some utility process instances are not connected to the Service
// Manager. Nothing left to do in that case.
if (!connection)
return;
auto registry = base::MakeUnique<service_manager::BinderRegistry>();
// If our process runs with elevated privileges, only add elevated Mojo
// interfaces to the interface registry.
if (!utility_process_running_elevated_) {
registry->AddInterface(base::Bind(CreateResourceUsageReporter),
base::ThreadTaskRunnerHandle::Get());
}
connection->AddConnectionFilter(
base::MakeUnique<content::SimpleConnectionFilter>(std::move(registry)));
}
bool AtomContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (utility_process_running_elevated_)
return false;
for (const auto& handler : handlers_) {
if (handler->OnMessageReceived(message))
return true;
}
return false;
}
void AtomContentUtilityClient::RegisterServices(
AtomContentUtilityClient::StaticServiceMap* services) {
service_manager::EmbeddedServiceInfo proxy_resolver_info;
proxy_resolver_info.task_runner =
content::ChildThread::Get()->GetIOTaskRunner();
proxy_resolver_info.factory =
base::Bind(&proxy_resolver::ProxyResolverService::CreateService);
services->emplace(proxy_resolver::mojom::kProxyResolverServiceName,
proxy_resolver_info);
service_manager::EmbeddedServiceInfo profile_import_info;
profile_import_info.factory =
base::Bind(&BraveProfileImportService::CreateService);
services->emplace(chrome::mojom::kProfileImportServiceName,
profile_import_info);
}
// static
void AtomContentUtilityClient::PreSandboxStartup() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::ExtensionsClient::Set(
extensions::ChromeExtensionsClient::GetInstance());
#endif
}
} // namespace atom
<commit_msg>Use new kNoSandboxAndElevatedPrivileges flag for Windows<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <utility>
#include "atom/utility/atom_content_utility_client.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "brave/utility/importer/brave_profile_import_service.h"
#include "chrome/common/importer/profile_import.mojom.h"
#include "chrome/common/resource_usage_reporter.mojom.h"
#include "chrome/utility/extensions/extensions_handler.h"
#include "chrome/utility/utility_message_handler.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/simple_connection_filter.h"
#include "content/public/utility/utility_thread.h"
#include "extensions/features/features.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_message_macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "printing/features/features.h"
#include "services/proxy_resolver/proxy_resolver_service.h"
#include "services/proxy_resolver/public/interfaces/proxy_resolver.mojom.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "services/service_manager/sandbox/switches.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/common/extensions/chrome_extensions_client.h"
#include "extensions/utility/utility_handler.h"
#endif
#if BUILDFLAG(ENABLE_PRINT_PREVIEW) || \
(BUILDFLAG(ENABLE_BASIC_PRINTING) && defined(OS_WIN))
#include "chrome/utility/printing_handler.h"
#endif
namespace atom {
namespace {
class ResourceUsageReporterImpl : public chrome::mojom::ResourceUsageReporter {
public:
ResourceUsageReporterImpl() {}
~ResourceUsageReporterImpl() override {}
private:
void GetUsageData(const GetUsageDataCallback& callback) override {
chrome::mojom::ResourceUsageDataPtr data =
chrome::mojom::ResourceUsageData::New();
size_t total_heap_size = net::ProxyResolverV8::GetTotalHeapSize();
if (total_heap_size) {
data->reports_v8_stats = true;
data->v8_bytes_allocated = total_heap_size;
data->v8_bytes_used = net::ProxyResolverV8::GetUsedHeapSize();
}
callback.Run(std::move(data));
}
};
void CreateResourceUsageReporter(
mojo::InterfaceRequest<chrome::mojom::ResourceUsageReporter> request) {
mojo::MakeStrongBinding(base::MakeUnique<ResourceUsageReporterImpl>(),
std::move(request));
}
} // namespace
AtomContentUtilityClient::AtomContentUtilityClient()
: utility_process_running_elevated_(false) {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW) || \
(BUILDFLAG(ENABLE_BASIC_PRINTING) && defined(OS_WIN))
handlers_.push_back(base::MakeUnique<printing::PrintingHandler>());
#endif
}
AtomContentUtilityClient::~AtomContentUtilityClient() = default;
void AtomContentUtilityClient::UtilityThreadStarted() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::utility_handler::UtilityThreadStarted();
#endif
#if defined(OS_WIN)
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
utility_process_running_elevated_ = command_line->HasSwitch(
service_manager::switches::kNoSandboxAndElevatedPrivileges);
#endif
content::ServiceManagerConnection* connection =
content::ChildThread::Get()->GetServiceManagerConnection();
// NOTE: Some utility process instances are not connected to the Service
// Manager. Nothing left to do in that case.
if (!connection)
return;
auto registry = base::MakeUnique<service_manager::BinderRegistry>();
// If our process runs with elevated privileges, only add elevated Mojo
// interfaces to the interface registry.
if (!utility_process_running_elevated_) {
registry->AddInterface(base::Bind(CreateResourceUsageReporter),
base::ThreadTaskRunnerHandle::Get());
}
connection->AddConnectionFilter(
base::MakeUnique<content::SimpleConnectionFilter>(std::move(registry)));
}
bool AtomContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (utility_process_running_elevated_)
return false;
for (const auto& handler : handlers_) {
if (handler->OnMessageReceived(message))
return true;
}
return false;
}
void AtomContentUtilityClient::RegisterServices(
AtomContentUtilityClient::StaticServiceMap* services) {
service_manager::EmbeddedServiceInfo proxy_resolver_info;
proxy_resolver_info.task_runner =
content::ChildThread::Get()->GetIOTaskRunner();
proxy_resolver_info.factory =
base::Bind(&proxy_resolver::ProxyResolverService::CreateService);
services->emplace(proxy_resolver::mojom::kProxyResolverServiceName,
proxy_resolver_info);
service_manager::EmbeddedServiceInfo profile_import_info;
profile_import_info.factory =
base::Bind(&BraveProfileImportService::CreateService);
services->emplace(chrome::mojom::kProfileImportServiceName,
profile_import_info);
}
// static
void AtomContentUtilityClient::PreSandboxStartup() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::ExtensionsClient::Set(
extensions::ChromeExtensionsClient::GetInstance());
#endif
}
} // namespace atom
<|endoftext|> |
<commit_before>/* *****************************************************************
*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* *****************************************************************/
#include <ocstack.h>
#include <oic_malloc.h>
#include <OCApi.h>
#include <OCPlatform_impl.h>
#include <oxmjustworks.h>
#include <oxmrandompin.h>
#include <srmutility.h>
#include <OCProvisioningManager.hpp>
#include <gtest/gtest.h>
#define TIMEOUT 5
namespace OCProvisioningTest
{
using namespace OC;
void resultCallback(PMResultList_t *result, int hasError)
{
(void)result;
(void)hasError;
}
TEST(ProvisionInitTest, TestWithEmptyPath)
{
std::string dbPath("");
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
}
TEST(ProvisionInitTest, TestValidPath)
{
std::string dbPath("./dbPath");
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
}
TEST(DiscoveryTest, SecureResource)
{
std::shared_ptr< OC::OCSecureResource > secureResource;
OicUuid_t uuid;
ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverSingleDevice(TIMEOUT, &uuid, secureResource));
}
TEST(DiscoveryTest, SecureResourceZeroTimeout)
{
std::shared_ptr< OC::OCSecureResource > secureResource;
OicUuid_t uuid;
ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverSingleDevice(0, &uuid, secureResource));
}
TEST(DiscoveryTest, UnownedDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverUnownedDevices(TIMEOUT, list));
}
TEST(DiscoveryTest, UnownedDevicesZeroTimeout)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverUnownedDevices(0, list));
}
#ifdef MULTIPLE_OWNER
TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnerEnabledDevices(TIMEOUT, list));
}
TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevicesZeroTimeOut)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnerEnabledDevices(0, list));
}
TEST(MOTDiscoveryTest, MultipleOwnedDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnedDevices(TIMEOUT, list));
}
TEST(MOTDiscoveryTest, MultipleOwnedDevicesZeroTimeOut)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnedDevices(0, list));
}
#endif
TEST(DiscoveryTest, OwnedDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverOwnedDevices(TIMEOUT, list));
}
TEST(DiscoveryTest, OwnedDevicesZeroTimeout)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverOwnedDevices(0, list));
}
TEST(OwnershipTest, OwnershipTransferNullCallback)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doOwnershipTransfer(nullptr));
}
#ifdef MULTIPLE_OWNER
TEST(MOTOwnershipTest, MOTOwnershipTransferNullCallback)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doMultipleOwnershipTransfer(nullptr));
}
TEST(selectMOTMethodTest, selectMOTMethodNullCallback)
{
OCSecureResource device;
const OicSecOxm_t stsecOxm = OIC_PRECONFIG_PIN;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.selectMOTMethod(stsecOxm, nullptr));
}
TEST(changeMOTModeTest, changeMOTModeNullCallback)
{
OCSecureResource device;
const OicSecMomType_t momType = OIC_MULTIPLE_OWNER_ENABLE;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.changeMOTMode(momType, nullptr));
}
TEST(addPreconfigPINTest, addPreconfigPINNullPin)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.addPreconfigPIN(nullptr, 0));
}
TEST(provisionPreconfPinTest, provisionPreconfPinNullCallback)
{
OCSecureResource device;
const char *pin = "test";
size_t PinLength = 4;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPreconfPin(pin, PinLength, nullptr));
}
TEST(isMOTEnabledTest, isMOTEnabledWithoutDeviceInst)
{
OCSecureResource device;
EXPECT_EQ(false, device.isMOTEnabled());
}
TEST(isMOTSupportedTest, isMOTSupportedWithoutDeviceInst)
{
OCSecureResource device;
EXPECT_EQ(false, device.isMOTSupported());
}
TEST(getMOTMethodTest, getMOTMethodNullOxM)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.getMOTMethod(nullptr));
}
#endif
TEST(DeviceInfoTest, DevInfoFromNetwork)
{
std::string dbPath("./dbPath");
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
DeviceList_t owned, unowned;
EXPECT_EQ(OC_STACK_OK, OCSecure::getDevInfoFromNetwork(TIMEOUT,
owned, unowned));
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
}
TEST(SetDisplayPinCBTest, SetDisplayPinCBTestNullCB)
{
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDisplayPinCB(nullptr));
}
TEST(ProvisionAclTest, ProvisionAclTestNullAcl)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, resultCallback));
}
TEST(ProvisionAclTest, ProvisionAclTestNullCallback)
{
OCSecureResource device;
OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionACL(acl, nullptr));
OICFree(acl);
}
TEST(ProvisionAclTest, ProvisionAclTestNullCallbackNUllAcl)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, nullptr));
}
TEST(ProvisionCredTest, ProvisionCredTestNullCallback)
{
OCSecureResource device, dev2;
Credential cred;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionCredentials(cred, dev2, nullptr));
}
TEST(ProvisionPairwiseTest, ProvisionPairwiseTestNullCallback)
{
OCSecureResource device, dev2;
Credential cred;
OicSecAcl_t *acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
OicSecAcl_t *acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPairwiseDevices(cred, acl1,
dev2, acl2, nullptr));
OICFree(acl1);
OICFree(acl2);
}
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
TEST(setDeviceIdSeed, NullParam)
{
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(NULL, 0));
}
TEST(setDeviceIdSeed, InvalidParam)
{
uint8_t seed[1024] = {0};
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, 0));
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
}
TEST(setDeviceIdSeed, ValidValue)
{
uint8_t seed[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
EXPECT_EQ(OC_STACK_OK, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
}
#endif // __WITH_DTLS__ || __WITH_TLS__
}
<commit_msg>iotivity: provisioning: Use .tmp suffix for test file<commit_after>/* *****************************************************************
*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* *****************************************************************/
#include <ocstack.h>
#include <oic_malloc.h>
#include <OCApi.h>
#include <OCPlatform_impl.h>
#include <oxmjustworks.h>
#include <oxmrandompin.h>
#include <srmutility.h>
#include <OCProvisioningManager.hpp>
#include <gtest/gtest.h>
#define TIMEOUT 5
namespace OCProvisioningTest
{
using namespace OC;
void resultCallback(PMResultList_t *result, int hasError)
{
(void)result;
(void)hasError;
}
TEST(ProvisionInitTest, TestWithEmptyPath)
{
std::string dbPath("");
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
}
TEST(ProvisionInitTest, TestValidPath)
{
std::string dbPath("./dbPath.tmp");
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
}
TEST(DiscoveryTest, SecureResource)
{
std::shared_ptr< OC::OCSecureResource > secureResource;
OicUuid_t uuid;
ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverSingleDevice(TIMEOUT, &uuid, secureResource));
}
TEST(DiscoveryTest, SecureResourceZeroTimeout)
{
std::shared_ptr< OC::OCSecureResource > secureResource;
OicUuid_t uuid;
ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverSingleDevice(0, &uuid, secureResource));
}
TEST(DiscoveryTest, UnownedDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverUnownedDevices(TIMEOUT, list));
}
TEST(DiscoveryTest, UnownedDevicesZeroTimeout)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverUnownedDevices(0, list));
}
#ifdef MULTIPLE_OWNER
TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnerEnabledDevices(TIMEOUT, list));
}
TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevicesZeroTimeOut)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnerEnabledDevices(0, list));
}
TEST(MOTDiscoveryTest, MultipleOwnedDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnedDevices(TIMEOUT, list));
}
TEST(MOTDiscoveryTest, MultipleOwnedDevicesZeroTimeOut)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnedDevices(0, list));
}
#endif
TEST(DiscoveryTest, OwnedDevices)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_OK, OCSecure::discoverOwnedDevices(TIMEOUT, list));
}
TEST(DiscoveryTest, OwnedDevicesZeroTimeout)
{
DeviceList_t list;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverOwnedDevices(0, list));
}
TEST(OwnershipTest, OwnershipTransferNullCallback)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doOwnershipTransfer(nullptr));
}
#ifdef MULTIPLE_OWNER
TEST(MOTOwnershipTest, MOTOwnershipTransferNullCallback)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doMultipleOwnershipTransfer(nullptr));
}
TEST(selectMOTMethodTest, selectMOTMethodNullCallback)
{
OCSecureResource device;
const OicSecOxm_t stsecOxm = OIC_PRECONFIG_PIN;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.selectMOTMethod(stsecOxm, nullptr));
}
TEST(changeMOTModeTest, changeMOTModeNullCallback)
{
OCSecureResource device;
const OicSecMomType_t momType = OIC_MULTIPLE_OWNER_ENABLE;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.changeMOTMode(momType, nullptr));
}
TEST(addPreconfigPINTest, addPreconfigPINNullPin)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.addPreconfigPIN(nullptr, 0));
}
TEST(provisionPreconfPinTest, provisionPreconfPinNullCallback)
{
OCSecureResource device;
const char *pin = "test";
size_t PinLength = 4;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPreconfPin(pin, PinLength, nullptr));
}
TEST(isMOTEnabledTest, isMOTEnabledWithoutDeviceInst)
{
OCSecureResource device;
EXPECT_EQ(false, device.isMOTEnabled());
}
TEST(isMOTSupportedTest, isMOTSupportedWithoutDeviceInst)
{
OCSecureResource device;
EXPECT_EQ(false, device.isMOTSupported());
}
TEST(getMOTMethodTest, getMOTMethodNullOxM)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.getMOTMethod(nullptr));
}
#endif
TEST(DeviceInfoTest, DevInfoFromNetwork)
{
std::string dbPath("./dbPath");
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
DeviceList_t owned, unowned;
EXPECT_EQ(OC_STACK_OK, OCSecure::getDevInfoFromNetwork(TIMEOUT,
owned, unowned));
EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
}
TEST(SetDisplayPinCBTest, SetDisplayPinCBTestNullCB)
{
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDisplayPinCB(nullptr));
}
TEST(ProvisionAclTest, ProvisionAclTestNullAcl)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, resultCallback));
}
TEST(ProvisionAclTest, ProvisionAclTestNullCallback)
{
OCSecureResource device;
OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionACL(acl, nullptr));
OICFree(acl);
}
TEST(ProvisionAclTest, ProvisionAclTestNullCallbackNUllAcl)
{
OCSecureResource device;
EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, nullptr));
}
TEST(ProvisionCredTest, ProvisionCredTestNullCallback)
{
OCSecureResource device, dev2;
Credential cred;
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionCredentials(cred, dev2, nullptr));
}
TEST(ProvisionPairwiseTest, ProvisionPairwiseTestNullCallback)
{
OCSecureResource device, dev2;
Credential cred;
OicSecAcl_t *acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
OicSecAcl_t *acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPairwiseDevices(cred, acl1,
dev2, acl2, nullptr));
OICFree(acl1);
OICFree(acl2);
}
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
TEST(setDeviceIdSeed, NullParam)
{
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(NULL, 0));
}
TEST(setDeviceIdSeed, InvalidParam)
{
uint8_t seed[1024] = {0};
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, 0));
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
}
TEST(setDeviceIdSeed, ValidValue)
{
uint8_t seed[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
EXPECT_EQ(OC_STACK_OK, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
}
#endif // __WITH_DTLS__ || __WITH_TLS__
}
<|endoftext|> |
<commit_before>
#include <sstream>
#include "FemusDefault.hpp"
#include "FemusInit.hpp"
#include "MultiLevelMesh.hpp"
#include "MultiLevelProblem.hpp"
#include "LinearImplicitSystem.hpp"
#include "NumericVector.hpp"
#include "WriterEnum.hpp"
#include "VTKWriter.hpp"
using namespace femus;
// So far, we need to be careful
// - how we call the groups in Salome (Group_N_M syntax, with N>1)
// - how we export MED by selecting all groups and meshes
// Moreover, we can see the groups in ParaVIS, but only not simultaneously
void AssembleFracFSI(MultiLevelProblem& ml_prob);
double InitialValue_u(const std::vector < double >& x) {
return 0.;
}
bool SetBoundaryCondition(const std::vector < double >& x, const char name[], double& value, const int faceName, const double time) {
bool dirichlet = true; //dirichlet
value = 0;
// if(!strcmp(name,"u")) {
// if (faceName == 3)
// dirichlet = false;
// }
return dirichlet;
}
int main(int argc,char **args) {
FemusInit init(argc,args,MPI_COMM_WORLD);
std::string med_file = "RectFracWithGroup.med";
std::ostringstream mystream; mystream << "./" << DEFAULT_INPUTDIR << "/" << med_file;
const std::string infile = mystream.str();
//Adimensional
double Lref = 1.;
MultiLevelMesh ml_msh;
ml_msh.ReadCoarseMesh(infile.c_str(),"fifth",Lref);
unsigned numberOfUniformLevels = 1;
unsigned numberOfSelectiveLevels = 0;
ml_msh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
ml_msh.PrintInfo();
ml_msh.SetWriter(XDMF);
ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic");
ml_msh.SetWriter(GMV);
ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic");
ml_msh.SetWriter(VTK);
ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic");
// define the multilevel solution and attach the ml_msh object to it
MultiLevelSolution mlSol(&ml_msh);
// add variables to mlSol
mlSol.AddSolution("u", LAGRANGE, SECOND);
mlSol.Initialize("All"); // initialize all varaibles to zero
mlSol.Initialize("u", InitialValue_u);
mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
mlSol.GenerateBdc("u");
// define the multilevel problem attach the mlSol object to it
MultiLevelProblem mlProb(&mlSol);
// add system in mlProb as a Linear Implicit System
LinearImplicitSystem& system = mlProb.add_system < LinearImplicitSystem > ("FracFSI");
system.AddSolutionToSystemPDE("u");
// attach the assembling function to system
system.SetAssembleFunction(AssembleFracFSI);
// initilaize and solve the system
system.init();
system.solve();
// print solutions
std::vector < std::string > variablesToBePrinted;
variablesToBePrinted.push_back("u");
VTKWriter vtkIO(&mlSol);
vtkIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
return 0;
}
void AssembleFracFSI(MultiLevelProblem& ml_prob) {
// ml_prob is the global object from/to where get/set all the data
// level is the level of the PDE system to be assembled
// levelMax is the Maximum level of the MultiLevelProblem
// assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled
// extract pointers to the several objects that we are going to use
LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem> ("FracFSI"); // pointer to the linear implicit system named "LiftRestr"
const unsigned level = mlPdeSys->GetLevelToAssemble();
const unsigned levelMax = mlPdeSys->GetLevelMax();
const bool assembleMatrix = mlPdeSys->GetAssembleMatrix();
Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object
elem* el = msh->el; // pointer to the elem object in msh (level)
MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object
Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object
LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object
SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level)
NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level)
const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem
unsigned dim2 = (3 * (dim - 1) + !(dim - 1)); // dim2 is the number of second order partial derivatives (1,3,6 depending on the dimension)
const unsigned maxSize = static_cast< unsigned >(ceil(pow(3, dim))); // conservative: based on line3, quad9, hex27
unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation)
//***************************
vector < vector < double > > x(dim); // local coordinates
unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC)
for (unsigned i = 0; i < dim; i++) {
x[i].reserve(maxSize);
}
//***************************
//***************************
double weight; // gauss point weight
//******** Thom *******************
//***************************
vector <double> phi_u; // local test function
vector <double> phi_x_u; // local test function first order partial derivatives
vector <double> phi_xx_u; // local test function second order partial derivatives
phi_u.reserve(maxSize);
phi_x_u.reserve(maxSize * dim);
phi_xx_u.reserve(maxSize * dim2);
unsigned solIndex_u;
solIndex_u = mlSol->GetIndex("u"); // get the position of "u" in the ml_sol object
unsigned solType_u = mlSol->GetSolutionType(solIndex_u); // get the finite element type for "u"
unsigned solPdeIndex_u;
solPdeIndex_u = mlPdeSys->GetSolPdeIndex("u"); // get the position of "Thom" in the pdeSys object
vector < double > sol_u; // local solution
sol_u.reserve(maxSize);
vector< int > l2GMap_u;
l2GMap_u.reserve(maxSize);
//***************************
//***************************
//***************************
//********* WHOLE SET OF VARIABLES ******************
const int solType_max = 2; //biquadratic
const int n_vars = 1;
vector< int > l2GMap_AllVars; // local to global mapping
l2GMap_AllVars.reserve(n_vars*maxSize);
vector< double > Res; // local redidual vector
Res.reserve(n_vars*maxSize);
vector < double > Jac;
Jac.reserve( n_vars*maxSize * n_vars*maxSize);
//***************************
//********** DATA *****************
double T_des = 100.;
double alpha = 10.e5;
double beta = 1.;
double gamma = 1.;
//***************************
if (assembleMatrix) KK->zero();
// element loop: each process loops only on the elements that owns
for (int iel = msh->IS_Mts2Gmt_elem_offset[iproc]; iel < msh->IS_Mts2Gmt_elem_offset[iproc + 1]; iel++) {
unsigned kel = msh->IS_Mts2Gmt_elem[iel]; // mapping between paralell dof and mesh dof
short unsigned kelGeom = el->GetElementType(kel); // element geometry type
//********* GEOMETRY ******************
unsigned nDofx = el->GetElementDofNumber(kel, xType); // number of coordinate element dofs
for (int i = 0; i < dim; i++) x[i].resize(nDofx);
// local storage of coordinates
for (unsigned i = 0; i < nDofx; i++) {
unsigned iNode = el->GetMeshDof(kel, i, xType); // local to global coordinates node
unsigned xDof = msh->GetMetisDof(iNode, xType); // global to global mapping between coordinates node and coordinate dof
for (unsigned jdim = 0; jdim < dim; jdim++) {
x[jdim][i] = (*msh->_coordinate->_Sol[jdim])(xDof); // global extraction and local storage for the element coordinates
}
}
//***************************************
//*********** Thom ****************************
unsigned nDof_u = el->GetElementDofNumber(kel, solType_u); // number of solution element dofs
sol_u .resize(nDof_u);
l2GMap_u.resize(nDof_u);
// local storage of global mapping and solution
for (unsigned i = 0; i < sol_u.size(); i++) {
unsigned iNode = el->GetMeshDof(kel, i, solType_u); // local to global solution node
unsigned solDof_u = msh->GetMetisDof(iNode, solType_u); // global to global mapping between solution node and solution dof
sol_u[i] = (*sol->_Sol[solIndex_u])(solDof_u); // global extraction and local storage for the solution
l2GMap_u[i] = pdeSys->GetKKDof(solIndex_u, solPdeIndex_u, iNode); // global to global mapping between solution node and pdeSys dof
}
//*********** Thom ****************************
//********** ALL VARS *****************
unsigned nDof_AllVars = nDof_u;
const int nDof_max = nDof_u; // AAAAAAAAAAAAAAAAAAAAAAAAAAA TODO COMPUTE MAXIMUM maximum number of element dofs for one scalar variable
Res.resize(nDof_AllVars);
std::fill(Res.begin(), Res.end(), 0.);
Jac.resize(nDof_AllVars * nDof_AllVars);
std::fill(Jac.begin(), Jac.end(), 0.);
l2GMap_AllVars.resize(0);
l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_u.begin(),l2GMap_u.end());
//***************************
if (level == levelMax || !el->GetRefinedElementIndex(kel)) { // do not care about this if now (it is used for the AMR)
// *** Gauss point loop ***
for (unsigned ig = 0; ig < msh->_finiteElement[kelGeom][solType_max]->GetGaussPointNumber(); ig++) {
// *** get gauss point weight, test function and test function partial derivatives ***
// ==== Thom
msh->_finiteElement[kelGeom][solType_u] ->Jacobian(x, ig, weight, phi_u, phi_x_u, phi_xx_u);
//FILLING WITH THE EQUATIONS ===========
// *** phi_i loop ***
for (unsigned i = 0; i < nDof_max; i++) {
double srcTerm = 10.;
// FIRST ROW
Res[0 + i] += weight * (srcTerm*phi_u[i]) ;
if (assembleMatrix) {
// *** phi_j loop ***
for (unsigned j = 0; j < nDof_max; j++) {
double laplace_mat_u = 0.;
for (unsigned kdim = 0; kdim < dim; kdim++) {
laplace_mat_u += (phi_x_u [i * dim + kdim] * phi_x_u [j * dim + kdim]);
}
//DIAG BLOCK
Jac[ 0 * (nDof_u) + i * (nDof_u) + (0 + j) ] += weight * laplace_mat_u;
} // end phi_j loop
} // endif assemble_matrix
} // end phi_i loop
} // end gauss point loop
} // endif single element not refined or fine grid loop
//--------------------------------------------------------------------------------------------------------
// Add the local Matrix/Vector into the global Matrix/Vector
//copy the value of the adept::adoube aRes in double Res and store
RES->add_vector_blocked(Res, l2GMap_AllVars);
if (assembleMatrix) {
//store K in the global matrix KK
KK->add_matrix_blocked(Jac, l2GMap_AllVars, l2GMap_AllVars);
}
} //end element loop for each process
RES->close();
if (assembleMatrix) KK->close();
// ***************** END ASSEMBLY *******************
}<commit_msg>Began flag material reading<commit_after>
#include <sstream>
#include "FemusDefault.hpp"
#include "FemusInit.hpp"
#include "MultiLevelMesh.hpp"
#include "MultiLevelProblem.hpp"
#include "LinearImplicitSystem.hpp"
#include "NumericVector.hpp"
#include "WriterEnum.hpp"
#include "VTKWriter.hpp"
using namespace femus;
// So far, we need to be careful
// - how we call the groups in Salome (Group_N_M syntax, with N>1)
// - how we export MED by selecting all groups and meshes
// Moreover, we can see the groups in ParaVIS, but only not simultaneously
void AssembleFracFSI(MultiLevelProblem& ml_prob);
double InitialValue_u(const std::vector < double >& x) {
return 0.;
}
bool SetBoundaryCondition(const std::vector < double >& x, const char name[], double& value, const int faceName, const double time) {
bool dirichlet = true; //dirichlet
value = 0;
// if(!strcmp(name,"u")) {
// if (faceName == 3)
// dirichlet = false;
// }
return dirichlet;
}
int main(int argc,char **args) {
FemusInit init(argc,args,MPI_COMM_WORLD);
std::string med_file = "RectFracWithGroup.med";
std::ostringstream mystream; mystream << "./" << DEFAULT_INPUTDIR << "/" << med_file;
const std::string infile = mystream.str();
//Adimensional
double Lref = 1.;
MultiLevelMesh ml_msh;
ml_msh.ReadCoarseMesh(infile.c_str(),"fifth",Lref);
unsigned numberOfUniformLevels = 1;
unsigned numberOfSelectiveLevels = 0;
ml_msh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
ml_msh.PrintInfo();
ml_msh.SetWriter(XDMF);
ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic");
ml_msh.SetWriter(GMV);
ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic");
ml_msh.SetWriter(VTK);
ml_msh.GetWriter()->write(DEFAULT_OUTPUTDIR,"biquadratic");
// define the multilevel solution and attach the ml_msh object to it
MultiLevelSolution mlSol(&ml_msh);
// add variables to mlSol
mlSol.AddSolution("u", LAGRANGE, SECOND);
mlSol.Initialize("All"); // initialize all varaibles to zero
mlSol.Initialize("u", InitialValue_u);
mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
mlSol.GenerateBdc("u");
// define the multilevel problem attach the mlSol object to it
MultiLevelProblem mlProb(&mlSol);
// add system in mlProb as a Linear Implicit System
LinearImplicitSystem& system = mlProb.add_system < LinearImplicitSystem > ("FracFSI");
system.AddSolutionToSystemPDE("u");
// attach the assembling function to system
system.SetAssembleFunction(AssembleFracFSI);
// initilaize and solve the system
system.init();
system.solve();
// print solutions
std::vector < std::string > variablesToBePrinted;
variablesToBePrinted.push_back("u");
VTKWriter vtkIO(&mlSol);
vtkIO.write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
return 0;
}
void AssembleFracFSI(MultiLevelProblem& ml_prob) {
// ml_prob is the global object from/to where get/set all the data
// level is the level of the PDE system to be assembled
// levelMax is the Maximum level of the MultiLevelProblem
// assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled
// extract pointers to the several objects that we are going to use
LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem> ("FracFSI"); // pointer to the linear implicit system named "LiftRestr"
const unsigned level = mlPdeSys->GetLevelToAssemble();
const unsigned levelMax = mlPdeSys->GetLevelMax();
const bool assembleMatrix = mlPdeSys->GetAssembleMatrix();
Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object
elem* el = msh->el; // pointer to the elem object in msh (level)
MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object
Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object
LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object
SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level)
NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level)
const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem
unsigned dim2 = (3 * (dim - 1) + !(dim - 1)); // dim2 is the number of second order partial derivatives (1,3,6 depending on the dimension)
const unsigned maxSize = static_cast< unsigned >(ceil(pow(3, dim))); // conservative: based on line3, quad9, hex27
unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation)
//***************************
vector < vector < double > > x(dim); // local coordinates
unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC)
for (unsigned i = 0; i < dim; i++) {
x[i].reserve(maxSize);
}
//***************************
//***************************
double weight; // gauss point weight
//******** Thom *******************
//***************************
vector <double> phi_u; // local test function
vector <double> phi_x_u; // local test function first order partial derivatives
vector <double> phi_xx_u; // local test function second order partial derivatives
phi_u.reserve(maxSize);
phi_x_u.reserve(maxSize * dim);
phi_xx_u.reserve(maxSize * dim2);
unsigned solIndex_u;
solIndex_u = mlSol->GetIndex("u"); // get the position of "u" in the ml_sol object
unsigned solType_u = mlSol->GetSolutionType(solIndex_u); // get the finite element type for "u"
unsigned solPdeIndex_u;
solPdeIndex_u = mlPdeSys->GetSolPdeIndex("u"); // get the position of "Thom" in the pdeSys object
vector < double > sol_u; // local solution
sol_u.reserve(maxSize);
vector< int > l2GMap_u;
l2GMap_u.reserve(maxSize);
//***************************
//***************************
//***************************
//********* WHOLE SET OF VARIABLES ******************
const int solType_max = 2; //biquadratic
const int n_vars = 1;
vector< int > l2GMap_AllVars; // local to global mapping
l2GMap_AllVars.reserve(n_vars*maxSize);
vector< double > Res; // local redidual vector
Res.reserve(n_vars*maxSize);
vector < double > Jac;
Jac.reserve( n_vars*maxSize * n_vars*maxSize);
//***************************
//********** DATA *****************
double T_des = 100.;
double alpha = 10.e5;
double beta = 1.;
double gamma = 1.;
//***************************
if (assembleMatrix) KK->zero();
// element loop: each process loops only on the elements that owns
for (int iel = msh->IS_Mts2Gmt_elem_offset[iproc]; iel < msh->IS_Mts2Gmt_elem_offset[iproc + 1]; iel++) {
unsigned kel = msh->IS_Mts2Gmt_elem[iel]; // mapping between paralell dof and mesh dof
short unsigned kelGeom = el->GetElementType(kel); // element geometry type
int flag_mat = myel->GetElementMaterial(kel);
//********* GEOMETRY ******************
unsigned nDofx = el->GetElementDofNumber(kel, xType); // number of coordinate element dofs
for (int i = 0; i < dim; i++) x[i].resize(nDofx);
// local storage of coordinates
for (unsigned i = 0; i < nDofx; i++) {
unsigned iNode = el->GetMeshDof(kel, i, xType); // local to global coordinates node
unsigned xDof = msh->GetMetisDof(iNode, xType); // global to global mapping between coordinates node and coordinate dof
for (unsigned jdim = 0; jdim < dim; jdim++) {
x[jdim][i] = (*msh->_coordinate->_Sol[jdim])(xDof); // global extraction and local storage for the element coordinates
}
}
//***************************************
//*********** Thom ****************************
unsigned nDof_u = el->GetElementDofNumber(kel, solType_u); // number of solution element dofs
sol_u .resize(nDof_u);
l2GMap_u.resize(nDof_u);
// local storage of global mapping and solution
for (unsigned i = 0; i < sol_u.size(); i++) {
unsigned iNode = el->GetMeshDof(kel, i, solType_u); // local to global solution node
unsigned solDof_u = msh->GetMetisDof(iNode, solType_u); // global to global mapping between solution node and solution dof
sol_u[i] = (*sol->_Sol[solIndex_u])(solDof_u); // global extraction and local storage for the solution
l2GMap_u[i] = pdeSys->GetKKDof(solIndex_u, solPdeIndex_u, iNode); // global to global mapping between solution node and pdeSys dof
}
//*********** Thom ****************************
//********** ALL VARS *****************
unsigned nDof_AllVars = nDof_u;
const int nDof_max = nDof_u; // AAAAAAAAAAAAAAAAAAAAAAAAAAA TODO COMPUTE MAXIMUM maximum number of element dofs for one scalar variable
Res.resize(nDof_AllVars);
std::fill(Res.begin(), Res.end(), 0.);
Jac.resize(nDof_AllVars * nDof_AllVars);
std::fill(Jac.begin(), Jac.end(), 0.);
l2GMap_AllVars.resize(0);
l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_u.begin(),l2GMap_u.end());
//***************************
if (level == levelMax || !el->GetRefinedElementIndex(kel)) { // do not care about this if now (it is used for the AMR)
// *** Gauss point loop ***
for (unsigned ig = 0; ig < msh->_finiteElement[kelGeom][solType_max]->GetGaussPointNumber(); ig++) {
// *** get gauss point weight, test function and test function partial derivatives ***
// ==== Thom
msh->_finiteElement[kelGeom][solType_u] ->Jacobian(x, ig, weight, phi_u, phi_x_u, phi_xx_u);
//FILLING WITH THE EQUATIONS ===========
// *** phi_i loop ***
for (unsigned i = 0; i < nDof_max; i++) {
double srcTerm = 10.;
// FIRST ROW
Res[0 + i] += weight * (srcTerm*phi_u[i]) ;
if (assembleMatrix) {
// *** phi_j loop ***
for (unsigned j = 0; j < nDof_max; j++) {
double laplace_mat_u = 0.;
for (unsigned kdim = 0; kdim < dim; kdim++) {
laplace_mat_u += (phi_x_u [i * dim + kdim] * phi_x_u [j * dim + kdim]);
}
//DIAG BLOCK
Jac[ 0 * (nDof_u) + i * (nDof_u) + (0 + j) ] += weight * laplace_mat_u;
} // end phi_j loop
} // endif assemble_matrix
} // end phi_i loop
} // end gauss point loop
} // endif single element not refined or fine grid loop
//--------------------------------------------------------------------------------------------------------
// Add the local Matrix/Vector into the global Matrix/Vector
//copy the value of the adept::adoube aRes in double Res and store
RES->add_vector_blocked(Res, l2GMap_AllVars);
if (assembleMatrix) {
//store K in the global matrix KK
KK->add_matrix_blocked(Jac, l2GMap_AllVars, l2GMap_AllVars);
}
} //end element loop for each process
RES->close();
if (assembleMatrix) KK->close();
// ***************** END ASSEMBLY *******************
}<|endoftext|> |
<commit_before>#define WEIGHTED 1
#include <cmath>
#include "ligra.h"
#include "index_map.h"
#include "bucket.h"
constexpr uintE TOP_BIT = ((uintE)INT_E_MAX) + 1;
constexpr uintE VAL_MASK = INT_E_MAX;
struct Visit_F {
array_imap<uintE> dists;
Visit_F(array_imap<uintE>& _dists) : dists(_dists) { }
inline Maybe<uintE> update(const uintE& s, const uintE& d, const intE& w) {
uintE oval = dists.s[d];
uintE dist = oval | TOP_BIT, n_dist = (dists.s[s] | TOP_BIT) + w;
if (n_dist < dist) {
if (!(oval & TOP_BIT)) { // First visitor
dists[d] = n_dist;
return Maybe<uintE>(oval);
}
dists[d] = n_dist;
}
return Maybe<uintE>();
}
inline Maybe<uintE> updateAtomic(const uintE& s, const uintE& d, const intE& w) {
uintE oval = dists.s[d];
uintE dist = oval | TOP_BIT;
uintE n_dist = (dists.s[s] | TOP_BIT) + w;
if (n_dist < dist) {
if (!(oval & TOP_BIT) && CAS(&(dists[d]), oval, n_dist)) { // First visitor
return Maybe<uintE>(oval);
}
writeMin(&(dists[d]), n_dist);
}
return Maybe<uintE>();
}
inline bool cond(const uintE& d) const { return true; }
};
template <class vertex>
void DeltaStepping(graph<vertex>& G, uintE src, uintE delta, size_t num_buckets=128) {
auto V = G.V; size_t n = G.n, m = G.m;
auto dists = array_imap<uintE>(n, [&] (size_t i) { return INT_E_MAX; });
dists[src] = 0;
auto get_bkt = [&] (const uintE& dist) -> const uintE {
return (dist == INT_E_MAX) ? UINT_E_MAX : (dist / delta); };
auto get_ring = [&] (const size_t& v) -> const uintE {
auto d = dists[v];
return (d == INT_E_MAX) ? UINT_E_MAX : (d / delta); };
auto b = make_buckets(n, get_ring, increasing, num_buckets);
auto apply_f = [&] (const uintE v, uintE& oldDist) -> void {
uintE newDist = dists.s[v] & VAL_MASK;
dists.s[v] = newDist; // Remove the TOP_BIT in the distance.
// Compute the previous bucket and new bucket for the vertex.
uintE prev_bkt = get_bkt(oldDist), new_bkt = get_bkt(newDist);
bucket_dest dest = b.get_bucket(prev_bkt, new_bkt);
oldDist = dest; // write back
};
auto bkt = b.next_bucket();
while (bkt.id != b.null_bkt) {
auto active = bkt.identifiers;
// The output of the edgeMap is a vertexSubsetData<uintE> where the value
// stored with each vertex is its original distance in this round
auto res = edgeMapData<uintE>(G, active, Visit_F(dists), G.m/20, sparse_no_filter | dense_forward);
vertexMap(res, apply_f);
b.update_buckets(res.get_fn_repr(), res.size());
res.del(); active.del();
bkt = b.next_bucket();
}
}
template <class vertex>
void Compute(graph<vertex>& GA, commandLine P) {
uintE src = P.getOptionLongValue("-src",0);
uintE delta = P.getOptionLongValue("-delta",1);
size_t num_buckets = P.getOptionLongValue("-nb", 128);
if (num_buckets != (1 << pbbs::log2_up(num_buckets))) {
cout << "Please specify a number of buckets that is a power of two" << endl;
exit(-1);
}
cout << "### Application: Delta-Stepping" << endl;
cout << "### Graph: " << P.getArgument(0) << endl;
cout << "### Workers: " << getWorkers() << endl;
cout << "### Buckets: " << num_buckets << endl;
cout << "### n: " << GA.n << endl;
cout << "### m: " << GA.m << endl;
cout << "### delta = " << delta << endl;
DeltaStepping(GA, src, delta, num_buckets);
}
<commit_msg>delta stepping update<commit_after>#define WEIGHTED 1
#include <cmath>
#include "ligra.h"
#include "index_map.h"
#include "bucket.h"
constexpr uintE TOP_BIT = ((uintE)INT_E_MAX) + 1;
constexpr uintE VAL_MASK = INT_E_MAX;
struct Visit_F {
array_imap<uintE> dists;
Visit_F(array_imap<uintE>& _dists) : dists(_dists) { }
inline Maybe<uintE> update(const uintE& s, const uintE& d, const intE& w) {
uintE oval = dists.s[d];
uintE dist = oval | TOP_BIT, n_dist = (dists.s[s] | TOP_BIT) + w;
if (n_dist < dist) {
if (!(oval & TOP_BIT)) { // First visitor
dists[d] = n_dist;
return Maybe<uintE>(oval);
}
dists[d] = n_dist;
}
return Maybe<uintE>();
}
inline Maybe<uintE> updateAtomic(const uintE& s, const uintE& d, const intE& w) {
uintE oval = dists.s[d];
uintE dist = oval | TOP_BIT;
uintE n_dist = (dists.s[s] | TOP_BIT) + w;
if (n_dist < dist) {
if (!(oval & TOP_BIT) && CAS(&(dists[d]), oval, n_dist)) { // First visitor
return Maybe<uintE>(oval);
}
writeMin(&(dists[d]), n_dist);
}
return Maybe<uintE>();
}
inline bool cond(const uintE& d) const { return true; }
};
template <class vertex>
void DeltaStepping(graph<vertex>& G, uintE src, uintE delta, size_t num_buckets=128) {
auto V = G.V; size_t n = G.n, m = G.m;
auto dists = array_imap<uintE>(n, [&] (size_t i) { return INT_E_MAX; });
dists[src] = 0;
auto get_bkt = [&] (const uintE& dist) -> const uintE {
return (dist == INT_E_MAX) ? UINT_E_MAX : (dist / delta); };
auto get_ring = [&] (const size_t& v) -> const uintE {
auto d = dists[v];
return (d == INT_E_MAX) ? UINT_E_MAX : (d / delta); };
auto b = make_buckets(n, get_ring, increasing, num_buckets);
auto apply_f = [&] (const uintE v, uintE& oldDist) -> void {
uintE newDist = dists.s[v] & VAL_MASK;
dists.s[v] = newDist; // Remove the TOP_BIT in the distance.
// Compute the previous bucket and new bucket for the vertex.
uintE prev_bkt = get_bkt(oldDist), new_bkt = get_bkt(newDist);
bucket_dest dest = b.get_bucket(prev_bkt, new_bkt);
oldDist = dest; // write back
};
auto bkt = b.next_bucket();
while (bkt.id != b.null_bkt) {
auto active = bkt.identifiers;
// The output of the edgeMap is a vertexSubsetData<uintE> where the value
// stored with each vertex is its original distance in this round
auto res = edgeMapData<uintE>(G, active, Visit_F(dists), G.m/20, sparse_no_filter | dense_forward);
vertexMap(res, apply_f);
if (res.dense()) {
b.update_buckets(res.get_fn_repr(), n);
} else {
b.update_buckets(res.get_fn_repr(), res.size());
}
res.del(); active.del();
bkt = b.next_bucket();
}
}
template <class vertex>
void Compute(graph<vertex>& GA, commandLine P) {
uintE src = P.getOptionLongValue("-src",0);
uintE delta = P.getOptionLongValue("-delta",1);
size_t num_buckets = P.getOptionLongValue("-nb", 128);
if (num_buckets != (1 << pbbs::log2_up(num_buckets))) {
cout << "Please specify a number of buckets that is a power of two" << endl;
exit(-1);
}
cout << "### Application: Delta-Stepping" << endl;
cout << "### Graph: " << P.getArgument(0) << endl;
cout << "### Workers: " << getWorkers() << endl;
cout << "### Buckets: " << num_buckets << endl;
cout << "### n: " << GA.n << endl;
cout << "### m: " << GA.m << endl;
cout << "### delta = " << delta << endl;
DeltaStepping(GA, src, delta, num_buckets);
}
<|endoftext|> |
<commit_before>/** A general multiagent pathfinding application.
*
* @file multiAgent.cpp
* @package hog2
*
* This file is part of HOG2.
*
* HOG2 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.
*
* HOG2 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 HOG2; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "Common.h"
#include "MultiAgent.h"
#include "AStar.h"
#include "PRAStar.h"
#include "SearchUnit.h"
//#include "SharedAMapGroup.h"
#include "UnitGroup.h"
#include "MapCliqueAbstraction.h"
#include "NodeLimitAbstraction.h"
#include "MapQuadTreeAbstraction.h"
//#include "RadiusAbstraction.h"
#include "MapFlatAbstraction.h"
//#include "ClusterAbstraction.h"
#include "UnitSimulation.h"
#include "EpisodicSimulation.h"
#include "Plot2D.h"
#include "Map2DEnvironment.h"
#include "RandomUnits.h"
#include "AbsMapPatrolUnit.h"
//#include "TemplateAStar.h"
#include "WeightedMap2DEnvironment.h"
bool mouseTracking;
int px1, py1, px2, py2;
int absType = 0;
std::vector<UnitAbsMapSimulation *> unitSims;
//unit *cameraTarget = 0;
Plotting::Plot2D *plot = 0;
Plotting::Line *distLine = 0;
int main(int argc, char* argv[])
{
InstallHandlers();
RunHOGGUI(argc, argv);
}
/**
* This function is used to allocate the unit simulated that you want to run.
* Any parameters or other experimental setup can be done at this time.
*/
void CreateSimulation(int id)
{
Map *map;
// if (gDefaultMap[0] == 0)
// {
//Empty map for now
map = new Map(60, 60);
//MakeMaze(map, 1);
// }
// else
// map = new Map(gDefaultMap);
unitSims.resize(id+1);
//unitSims[id] = new EpisodicSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new MapQuadTreeAbstraction(map, 2)));
//unitSims[id] = new EpisodicSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new NodeLimitAbstraction(map, 8)));
//unitSims[id] = new UnitSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new MapCliqueAbstraction(map)));
//unitSims[id] = new UnitSimulation<xyLoc, tDirection, WeightedMap2DEnvironment>(new WeightedMap2DEnvironment(new MapFlatAbstraction(map)));
unitSims[id] = new UnitSimulation<xyLoc, tDirection, AbsMapEnvironment>(new WeightedMap2DEnvironment(new MapFlatAbstraction(map)));
unitSims[id]->SetStepType(kMinTime);
// unitSim = new UnitSimulation<xyLoc, tDirection, MapEnvironment>(new MapEnvironment(map),
// (OccupancyInterface<xyLoc, tDirection>*)0);
// if (absType == 0)
// unitSim = new unitSimulation(new MapCliqueAbstraction(map));
// else if (absType == 1)
// unitSim = new unitSimulation(new RadiusAbstraction(map, 1));
// else if (absType == 2)
// unitSim = new unitSimulation(new MapQuadTreeAbstraction(map, 2));
// else if (absType == 3)
// unitSim = new unitSimulation(new ClusterAbstraction(map, 8));
//unitSim->setCanCrossDiagonally(true);
//unitSim = new unitSimulation(new MapFlatAbstraction(map));
}
/**
* Allows you to install any keyboard handlers needed for program interaction.
*/
void InstallHandlers()
{
InstallKeyboardHandler(MyDisplayHandler, "Toggle Abstraction", "Toggle display of the ith level of the abstraction", kAnyModifier, '0', '9');
InstallKeyboardHandler(MyDisplayHandler, "Cycle Abs. Display", "Cycle which group abstraction is drawn", kAnyModifier, '\t');
InstallKeyboardHandler(MyDisplayHandler, "Pause Simulation", "Pause simulation execution.", kNoModifier, 'p');
InstallKeyboardHandler(MyDisplayHandler, "Step Simulation", "If the simulation is paused, step forward .1 sec.", kNoModifier, 'o');
InstallKeyboardHandler(MyDisplayHandler, "Step History", "If the simulation is paused, step forward .1 sec in history", kAnyModifier, '}');
InstallKeyboardHandler(MyDisplayHandler, "Step History", "If the simulation is paused, step back .1 sec in history", kAnyModifier, '{');
// InstallKeyboardHandler(MyDisplayHandler, "Step Abs Type", "Increase //abstraction type", kAnyModifier, ']');
// InstallKeyboardHandler(MyDisplayHandler, "Step Abs Type", "Decrease //abstraction type", kAnyModifier, '[');
InstallKeyboardHandler(MyPathfindingKeyHandler, "Patrol Unit", "Deploy patrol unit that patrols between two locations on the map", kNoModifier, 'd');
InstallKeyboardHandler(MyRandomUnitKeyHandler, "Add A* Unit", "Deploys a simple a* unit", kNoModifier, 'a');
// InstallKeyboardHandler(MyRandomUnitKeyHandler, "Add simple Unit", "Deploys a //randomly moving unit", kShiftDown, 'a');
// InstallKeyboardHandler(MyRandomUnitKeyHandler, "Add simple Unit", "Deploys a //right-hand-rule unit", kControlDown, 1);
// InstallCommandLineHandler(MyCLHandler, "-map", "-map filename", "Selects the //default map to be loaded.");
InstallWindowHandler(MyWindowHandler);
InstallMouseClickHandler(MyClickHandler);
}
void MyWindowHandler(unsigned long windowID, tWindowEventType eType)
{
if (eType == kWindowDestroyed)
{
printf("Window %ld destroyed\n", windowID);
RemoveFrameHandler(MyFrameHandler, windowID, 0);
}
else if (eType == kWindowCreated)
{
printf("Window %ld created\n", windowID);
InstallFrameHandler(MyFrameHandler, windowID, 0);
CreateSimulation(windowID);
}
}
void MyFrameHandler(unsigned long windowID, unsigned int viewport, void *)
{
if ((windowID < unitSims.size()) && (unitSims[windowID] == 0))
return;
if (viewport == 0)
{
unitSims[windowID]->StepTime(1.0/30.0);
}
unitSims[windowID]->OpenGLDraw(windowID);
}
int MyCLHandler(char *argument[], int maxNumArgs)
{
if (maxNumArgs <= 1)
return 0;
strncpy(gDefaultMap, argument[1], 1024);
return 2;
}
void MyDisplayHandler(unsigned long windowID, tKeyboardModifier mod, char key)
{
switch (key)
{
case '\t':
if (mod != kShiftDown)
SetActivePort(windowID, (GetActivePort(windowID)+1)%GetNumPorts(windowID));
else
{
SetNumPorts(windowID, 1+(GetNumPorts(windowID)%MAXPORTS));
}
break;
case 'p': unitSims[windowID]->SetPaused(!unitSims[windowID]->GetPaused()); break;
case 'o':
{
if (unitSims[windowID]->GetPaused())
{
unitSims[windowID]->SetPaused(false);
unitSims[windowID]->StepTime(1.0/30.0);
unitSims[windowID]->SetPaused(true);
}
}
break;
// case ']': absType = (absType+1)%3; break;
// case '[': absType = (absType+4)%3; break;
// case '{': unitSim->setPaused(true); unitSim->offsetDisplayTime(-0.5); break;
// case '}': unitSim->offsetDisplayTime(0.5); break;
default:
if (unitSims[windowID])
unitSims[windowID]->GetEnvironment()->GetMapAbstraction()->ToggleDrawAbstraction(((mod == kControlDown)?10:0)+(key-'0'));
break;
}
}
void MyRandomUnitKeyHandler(unsigned long windowID, tKeyboardModifier , char)
{
Map *m = unitSims[windowID]->GetEnvironment()->GetMap();
int x1, y1, x2, y2;
x2 = random()%m->getMapWidth();
y2 = random()%m->getMapHeight();
x1 = random()%m->getMapWidth();
y1 = random()%m->getMapHeight();
SearchUnit *su1 = new SearchUnit(x1, y1, 0, 0);
//SearchUnit *su2 = new SearchUnit(random()%m->getMapWidth(), random()%m->getMapHeight(), su1, new praStar());
SearchUnit *su2 = new SearchUnit(x2, y2, su1, new aStar());
//unitSim->AddUnit(su1);
unitSims[windowID]->AddUnit(su2);
// RandomerUnit *r = new RandomerUnit(random()%m->getMapWidth(), random()%m->getMapHeight());
// int id = unitSim->AddUnit(r);
// xyLoc loc;
// r->GetLocation(loc);
// printf("Added unit %d at (%d, %d)\n", id, loc.x, loc.y);
// int x1, y1, x2, y2;
// unit *u;
// unitSim->getRandomLocation(x1, y1);
// unitSim->getRandomLocation(x2, y2);
// switch (mod)
// {
// case kControlDown: unitSim->addUnit(u=new rhrUnit(x1, y1)); break;
// case kShiftDown: unitSim->addUnit(u=new randomUnit(x1, y1)); break;
// default:
// unit *targ;
// unitSim->addUnit(targ = new unit(x2, y2));
// unitSim->addUnit(u=new SearchUnit(x1, y1, targ, new praStar())); break;
// }
// delete plot;
// plot = new Plotting::Plot2D();
// delete distLine;
// plot->AddLine(distLine = new Plotting::Line("distline"));
// cameraTarget = u;
// u->setSpeed(1.0/4.0);
}
void MyPathfindingKeyHandler(unsigned long windowID, tKeyboardModifier , char)
{
// for (int x = 0; x < ((mod==kShiftDown)?(50):(1)); x++)
// {
//if (unitSims[windowID]->GetUnitGroup(1) == 0)
//{
// unitSims[windowID]->AddUnitGroup(new unitGroup(unitSim));
//unitSims[windowID]->setmapAbstractionDisplay(2);
//}
int xStart=5, yStart=5, xGoal=50, yGoal=50;
xyLoc goal;
goal.x = xGoal;
goal.y = yGoal;
aStar* a = new aStar();
//TemplateAStar<xyLoc, tDirection>* a = new TemplateAStar<xyLoc, tDirection>();
AbsMapPatrolUnit* pUnit = new AbsMapPatrolUnit(xStart,yStart, a);
pUnit->addPatrolLocation(goal);
unitSims[windowID]->AddUnit(pUnit);
//pUnit->setSpeed(0.5);
// int xx1, yy1, xx2, yy2;
// unitSim->getRandomLocation(xx1, yy1);
// unitSim->getRandomLocation(xx2, yy2);
//
// unit *u, *u2 = new unit(xx2, yy2, 0);
//
// praStar *pra = new praStar(); pra->setPartialPathLimit(4);
// //aStar *pra = new aStar();
//
// unitSim->addUnit(u2);
// u = new SearchUnit(xx1, yy1, u2, pra);
// // just set the group of the unit, and it will share a map with those
// // units.
// unitSim->getUnitGroup(1)->addUnit(u);
// unitSim->addUnit(u);
// u->setSpeed(0.5); // time to go 1 distance
// }
}
bool MyClickHandler(unsigned long windowID, int, int, point3d loc, tButtonType button, tMouseEventType mType)
{
return false;
// mouseTracking = false;
// if (button == kRightButton)
// {
// switch (mType)
// {
// case kMouseDown:
// unitSim->GetMap()->getPointFromCoordinate(loc, px1, py1);
// //printf("Mouse down at (%d, %d)\n", px1, py1);
// break;
// case kMouseDrag:
// mouseTracking = true;
// unitSim->GetMap()->getPointFromCoordinate(loc, px2, py2);
// //printf("Mouse tracking at (%d, %d)\n", px2, py2);
// break;
// case kMouseUp:
// {
// if ((px1 == -1) || (px2 == -1))
// break;
// unitSim->GetMap()->getPointFromCoordinate(loc, px2, py2);
// //printf("Mouse up at (%d, %d)\n", px2, py2);
// unit *u, *u2 = new unit(px2, py2, 0);
// //praStar *pra = new praStar(); pra->setPartialPathLimit(4);
// aStar *pra = new aStar();
// unitSim->addUnit(u2);
// u = new SearchUnit(px1, py1, u2, pra);
// unitSim->addUnit(u);
// u->setSpeed(0.5); // time to go 1 distance
// }
// break;
// }
// return true;
// }
// return false;
}
<commit_msg>working version for GenericSearchUnit and TemplateAStar<commit_after>/** A general multiagent pathfinding application.
*
* @file multiAgent.cpp
* @package hog2
*
* This file is part of HOG2.
*
* HOG2 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.
*
* HOG2 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 HOG2; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "Common.h"
#include "MultiAgent.h"
#include "AStar.h"
#include "PRAStar.h"
#include "SearchUnit.h"
//#include "SharedAMapGroup.h"
#include "UnitGroup.h"
#include "MapCliqueAbstraction.h"
#include "NodeLimitAbstraction.h"
#include "MapQuadTreeAbstraction.h"
//#include "RadiusAbstraction.h"
#include "MapFlatAbstraction.h"
//#include "ClusterAbstraction.h"
#include "UnitSimulation.h"
#include "EpisodicSimulation.h"
#include "Plot2D.h"
#include "Map2DEnvironment.h"
#include "RandomUnits.h"
#include "AbsMapPatrolUnit.h"
#include "TemplateAStar.h"
#include "GenericSearchUnit.h"
#include "WeightedMap2DEnvironment.h"
bool mouseTracking;
int px1, py1, px2, py2;
int absType = 0;
std::vector<UnitAbsMapSimulation *> unitSims;
//std::vector<UnitWeightedMapSimulation *> unitSims;
//unit *cameraTarget = 0;
Plotting::Plot2D *plot = 0;
Plotting::Line *distLine = 0;
int main(int argc, char* argv[])
{
InstallHandlers();
RunHOGGUI(argc, argv);
}
/**
* This function is used to allocate the unit simulated that you want to run.
* Any parameters or other experimental setup can be done at this time.
*/
void CreateSimulation(int id)
{
Map *map;
// if (gDefaultMap[0] == 0)
// {
//Empty map for now
map = new Map(60, 60);
//MakeMaze(map, 1);
// }
// else
// map = new Map(gDefaultMap);
unitSims.resize(id+1);
//unitSims[id] = new EpisodicSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new MapQuadTreeAbstraction(map, 2)));
//unitSims[id] = new EpisodicSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new NodeLimitAbstraction(map, 8)));
//unitSims[id] = new UnitSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new MapCliqueAbstraction(map)));
unitSims[id] = new UnitSimulation<xyLoc, tDirection, AbsMapEnvironment>(new AbsMapEnvironment(new MapFlatAbstraction(map)));
//unitSims[id] = new UnitSimulation<xyLoc, tDirection, AbsMapEnvironment>(new WeightedMap2DEnvironment(new MapFlatAbstraction(map)));
//unitSims[id] = new UnitSimulation<xyLoc, tDirection, WeightedMap2DEnvironment>(new WeightedMap2DEnvironment (new MapFlatAbstraction(map)));
unitSims[id]->SetStepType(kMinTime);
// unitSim = new UnitSimulation<xyLoc, tDirection, MapEnvironment>(new MapEnvironment(map),
// (OccupancyInterface<xyLoc, tDirection>*)0);
// if (absType == 0)
// unitSim = new unitSimulation(new MapCliqueAbstraction(map));
// else if (absType == 1)
// unitSim = new unitSimulation(new RadiusAbstraction(map, 1));
// else if (absType == 2)
// unitSim = new unitSimulation(new MapQuadTreeAbstraction(map, 2));
// else if (absType == 3)
// unitSim = new unitSimulation(new ClusterAbstraction(map, 8));
//unitSim->setCanCrossDiagonally(true);
//unitSim = new unitSimulation(new MapFlatAbstraction(map));
}
/**
* Allows you to install any keyboard handlers needed for program interaction.
*/
void InstallHandlers()
{
InstallKeyboardHandler(MyDisplayHandler, "Toggle Abstraction", "Toggle display of the ith level of the abstraction", kAnyModifier, '0', '9');
InstallKeyboardHandler(MyDisplayHandler, "Cycle Abs. Display", "Cycle which group abstraction is drawn", kAnyModifier, '\t');
InstallKeyboardHandler(MyDisplayHandler, "Pause Simulation", "Pause simulation execution.", kNoModifier, 'p');
InstallKeyboardHandler(MyDisplayHandler, "Step Simulation", "If the simulation is paused, step forward .1 sec.", kNoModifier, 'o');
InstallKeyboardHandler(MyDisplayHandler, "Step History", "If the simulation is paused, step forward .1 sec in history", kAnyModifier, '}');
InstallKeyboardHandler(MyDisplayHandler, "Step History", "If the simulation is paused, step back .1 sec in history", kAnyModifier, '{');
// InstallKeyboardHandler(MyDisplayHandler, "Step Abs Type", "Increase //abstraction type", kAnyModifier, ']');
// InstallKeyboardHandler(MyDisplayHandler, "Step Abs Type", "Decrease //abstraction type", kAnyModifier, '[');
InstallKeyboardHandler(MyPathfindingKeyHandler, "Patrol Unit", "Deploy patrol unit that patrols between two locations on the map", kNoModifier, 'd');
InstallKeyboardHandler(MyRandomUnitKeyHandler, "Add A* Unit", "Deploys a simple a* unit", kNoModifier, 'a');
// InstallKeyboardHandler(MyRandomUnitKeyHandler, "Add simple Unit", "Deploys a //randomly moving unit", kShiftDown, 'a');
// InstallKeyboardHandler(MyRandomUnitKeyHandler, "Add simple Unit", "Deploys a //right-hand-rule unit", kControlDown, 1);
// InstallCommandLineHandler(MyCLHandler, "-map", "-map filename", "Selects the //default map to be loaded.");
InstallWindowHandler(MyWindowHandler);
InstallMouseClickHandler(MyClickHandler);
}
void MyWindowHandler(unsigned long windowID, tWindowEventType eType)
{
if (eType == kWindowDestroyed)
{
printf("Window %ld destroyed\n", windowID);
RemoveFrameHandler(MyFrameHandler, windowID, 0);
}
else if (eType == kWindowCreated)
{
printf("Window %ld created\n", windowID);
InstallFrameHandler(MyFrameHandler, windowID, 0);
CreateSimulation(windowID);
}
}
void MyFrameHandler(unsigned long windowID, unsigned int viewport, void *)
{
if ((windowID < unitSims.size()) && (unitSims[windowID] == 0))
return;
if (viewport == 0)
{
unitSims[windowID]->StepTime(1.0/30.0);
}
unitSims[windowID]->OpenGLDraw(windowID);
}
int MyCLHandler(char *argument[], int maxNumArgs)
{
if (maxNumArgs <= 1)
return 0;
strncpy(gDefaultMap, argument[1], 1024);
return 2;
}
void MyDisplayHandler(unsigned long windowID, tKeyboardModifier mod, char key)
{
switch (key)
{
case '\t':
if (mod != kShiftDown)
SetActivePort(windowID, (GetActivePort(windowID)+1)%GetNumPorts(windowID));
else
{
SetNumPorts(windowID, 1+(GetNumPorts(windowID)%MAXPORTS));
}
break;
case 'p': unitSims[windowID]->SetPaused(!unitSims[windowID]->GetPaused()); break;
case 'o':
{
if (unitSims[windowID]->GetPaused())
{
unitSims[windowID]->SetPaused(false);
unitSims[windowID]->StepTime(1.0/30.0);
unitSims[windowID]->SetPaused(true);
}
}
break;
// case ']': absType = (absType+1)%3; break;
// case '[': absType = (absType+4)%3; break;
// case '{': unitSim->setPaused(true); unitSim->offsetDisplayTime(-0.5); break;
// case '}': unitSim->offsetDisplayTime(0.5); break;
default:
if (unitSims[windowID])
unitSims[windowID]->GetEnvironment()->GetMapAbstraction()->ToggleDrawAbstraction(((mod == kControlDown)?10:0)+(key-'0'));
break;
}
}
void MyRandomUnitKeyHandler(unsigned long windowID, tKeyboardModifier , char)
{
/* Map *m = unitSims[windowID]->GetEnvironment()->GetMap();
int x1, y1, x2, y2;
x2 = random()%m->getMapWidth();
y2 = random()%m->getMapHeight();
x1 = random()%m->getMapWidth();
y1 = random()%m->getMapHeight();
SearchUnit *su1 = new SearchUnit(x1, y1, 0, 0);
//SearchUnit *su2 = new SearchUnit(random()%m->getMapWidth(), random()%m->getMapHeight(), su1, new praStar());
SearchUnit *su2 = new SearchUnit(x2, y2, su1, new aStar());
//unitSim->AddUnit(su1);
unitSims[windowID]->AddUnit(su2);*/
// RandomerUnit *r = new RandomerUnit(random()%m->getMapWidth(), random()%m->getMapHeight());
// int id = unitSim->AddUnit(r);
// xyLoc loc;
// r->GetLocation(loc);
// printf("Added unit %d at (%d, %d)\n", id, loc.x, loc.y);
// int x1, y1, x2, y2;
// unit *u;
// unitSim->getRandomLocation(x1, y1);
// unitSim->getRandomLocation(x2, y2);
// switch (mod)
// {
// case kControlDown: unitSim->addUnit(u=new rhrUnit(x1, y1)); break;
// case kShiftDown: unitSim->addUnit(u=new randomUnit(x1, y1)); break;
// default:
// unit *targ;
// unitSim->addUnit(targ = new unit(x2, y2));
// unitSim->addUnit(u=new SearchUnit(x1, y1, targ, new praStar())); break;
// }
// delete plot;
// plot = new Plotting::Plot2D();
// delete distLine;
// plot->AddLine(distLine = new Plotting::Line("distline"));
// cameraTarget = u;
// u->setSpeed(1.0/4.0);
}
void MyPathfindingKeyHandler(unsigned long windowID, tKeyboardModifier , char)
{
// for (int x = 0; x < ((mod==kShiftDown)?(50):(1)); x++)
// {
//if (unitSims[windowID]->GetUnitGroup(1) == 0)
//{
// unitSims[windowID]->AddUnitGroup(new unitGroup(unitSim));
//unitSims[windowID]->setmapAbstractionDisplay(2);
//}
int xStart=5, yStart=5, xGoal=50, yGoal=50;
xyLoc start;
start.x = xStart;
start.y = yStart;
xyLoc goal;
goal.x = xGoal;
goal.y = yGoal;
//aStar* a = new aStar();
TemplateAStar<xyLoc, tDirection>* a = new TemplateAStar<xyLoc, tDirection>();
GenericSearchUnit<xyLoc, tDirection, AbsMapEnvironment>* unit = new GenericSearchUnit<xyLoc, tDirection, AbsMapEnvironment>(start, goal, a);
//AbsMapPatrolUnit* pUnit = new AbsMapPatrolUnit(xStart,yStart, a);
//pUnit->addPatrolLocation(goal);
//Unit<xyLoc, tDirection, WeightedMap2DEnvironment> *pUnit = new Unit<xyLoc, tDirection, WeightedMap2DEnvironment>;
unitSims[windowID]->AddUnit(unit);
//pUnit->setSpeed(0.5);
// int xx1, yy1, xx2, yy2;
// unitSim->getRandomLocation(xx1, yy1);
// unitSim->getRandomLocation(xx2, yy2);
//
// unit *u, *u2 = new unit(xx2, yy2, 0);
//
// praStar *pra = new praStar(); pra->setPartialPathLimit(4);
// //aStar *pra = new aStar();
//
// unitSim->addUnit(u2);
// u = new SearchUnit(xx1, yy1, u2, pra);
// // just set the group of the unit, and it will share a map with those
// // units.
// unitSim->getUnitGroup(1)->addUnit(u);
// unitSim->addUnit(u);
// u->setSpeed(0.5); // time to go 1 distance
// }
}
bool MyClickHandler(unsigned long windowID, int, int, point3d loc, tButtonType button, tMouseEventType mType)
{
return false;
// mouseTracking = false;
// if (button == kRightButton)
// {
// switch (mType)
// {
// case kMouseDown:
// unitSim->GetMap()->getPointFromCoordinate(loc, px1, py1);
// //printf("Mouse down at (%d, %d)\n", px1, py1);
// break;
// case kMouseDrag:
// mouseTracking = true;
// unitSim->GetMap()->getPointFromCoordinate(loc, px2, py2);
// //printf("Mouse tracking at (%d, %d)\n", px2, py2);
// break;
// case kMouseUp:
// {
// if ((px1 == -1) || (px2 == -1))
// break;
// unitSim->GetMap()->getPointFromCoordinate(loc, px2, py2);
// //printf("Mouse up at (%d, %d)\n", px2, py2);
// unit *u, *u2 = new unit(px2, py2, 0);
// //praStar *pra = new praStar(); pra->setPartialPathLimit(4);
// aStar *pra = new aStar();
// unitSim->addUnit(u2);
// u = new SearchUnit(px1, py1, u2, pra);
// unitSim->addUnit(u);
// u->setSpeed(0.5); // time to go 1 distance
// }
// break;
// }
// return true;
// }
// return false;
}
<|endoftext|> |
<commit_before>#include "range_rule.hpp"
RangeRule::RangeRule(const bool withSpecials)
: m_exclude(false), m_dist(33, 127)
{
char *bareRule;
uint16_t length = 0;
if (withSpecials) {
bareRule = " -~";
length = 4;
} else {
bareRule = "a-zA-Z0-9";
length = 10;
}
generateRuleArray(bareRule, length);
delete [] bareRule;
}
RangeRule::RangeRule(const char * const bareRule, const uint16_t length, const bool exclude)
: m_exclude(exclude), m_dist(33, 127)
{
generateRuleArray(bareRule, length);
}
char RangeRule::getChar() {
if (m_rule.size() <= 0) return '\0';
uint16_t value = 0;
do {
value = m_dist(m_rand);
} while (!isValid(value));
return static_cast<char>(value);
}
bool RangeRule::isValid(const uint16_t value) const {
for (auto&& it = m_rule.begin(); it != m_rule.end(); it++) {
if (value == *it) {
return !m_exclude;
}
}
return m_exclude;
}
inline void RangeRule::generateRuleArray(const char * const bareRule, const uint16_t length) {
uint8_t rangeStep = 1;
char first;
for (uint32_t i = 0; i < length; ++i) {
if (rangeStep == 1) {
first = bareRule[i];
rangeStep = 2;
} else if (rangeStep == 2) {
if (bareRule[i] != '-') {
appendChar(first);
first = bareRule[i];
rangeStep = 2;
} else {
rangeStep = 3;
}
} else {
appendRange(first, bareRule[i]);
rangeStep = 1;
}
}
}
inline void RangeRule::appendChar(const char c) {
m_rule.push_back(c);
}
void RangeRule::appendRange(const char first, const char last) {
for (char c = first; c < (last + 1); ++c) {
appendChar(c);
}
}
<commit_msg>Fixes the program hanging on space rule.<commit_after>#include "range_rule.hpp"
#include <iostream>
RangeRule::RangeRule(const bool withSpecials)
: m_exclude(false), m_dist(32, 127)
{
char *bareRule;
uint16_t length = 0;
if (withSpecials) {
bareRule = " -~";
length = 4;
} else {
bareRule = "a-zA-Z0-9";
length = 10;
}
generateRuleArray(bareRule, length);
delete [] bareRule;
}
RangeRule::RangeRule(const char * const bareRule, const uint16_t length, const bool exclude)
: m_exclude(exclude), m_dist(32, 127)
{
generateRuleArray(bareRule, length);
}
char RangeRule::getChar() {
if (m_rule.size() <= 0) return '\0';
uint16_t value = 0;
do {
value = m_dist(m_rand);
} while (!isValid(value));
return static_cast<char>(value);
}
bool RangeRule::isValid(const uint16_t value) const {
for (auto&& it = m_rule.begin(); it != m_rule.end(); it++) {
if (value == *it) {
return !m_exclude;
}
}
return m_exclude;
}
inline void RangeRule::generateRuleArray(const char * const bareRule, const uint16_t length) {
uint8_t rangeStep = 1;
char first;
for (uint32_t i = 0; i < length; ++i) {
if (rangeStep == 1) {
first = bareRule[i];
rangeStep = 2;
} else if (rangeStep == 2) {
if (bareRule[i] != '-') {
appendChar(first);
first = bareRule[i];
rangeStep = 2;
} else {
rangeStep = 3;
}
} else {
appendRange(first, bareRule[i]);
rangeStep = 1;
}
}
}
inline void RangeRule::appendChar(const char c) {
m_rule.push_back(c);
}
void RangeRule::appendRange(const char first, const char last) {
for (char c = first; c < (last + 1); ++c) {
appendChar(c);
}
}
<|endoftext|> |
<commit_before>// Copyright 2013 Sean McKenna
//
// 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.
//
// a ray tracer in C++
// libraries, namespace
#include <thread>
#include <fstream>
#include "library/loadXML.cpp"
#include "library/scene.cpp"
using namespace std;
// scene to load (project #) & whether to debug
const char* xml = "scenes/prj2.xml";
bool printXML = false;
bool zBuffer = false;
// for ray tracing
int w;
int h;
int size;
Color24* img;
float* zImg;
HitInfo objectIntersection(Node &n, Ray r);
// for threading
static const int numThreads = 8;
void rayTracing(int i);
// for camera ray generation
void cameraRayVars();
Point *imageTopLeftV;
Point *dXV;
Point *dYV;
Point firstPixel;
Transformation* c;
Point cameraRay(int pX, int pY);
// ray tracer
int main(){
// load scene: root node, camera, image
loadScene(xml, printXML);
// set variables for ray tracing
w = render.getWidth();
h = render.getHeight();
size = render.getSize();
img = render.getRender();
zImg = render.getZBuffer();
// set variables for generating camera rays
cameraRayVars();
// start ray tracing loop (in parallel with threads)
thread t[numThreads];
for(int i = 0; i < numThreads; i++)
t[i] = thread(rayTracing, i);
// when finished, join all threads back to main
for(int i = 0; i < numThreads; i++)
t[i].join();
// output ray-traced image & z-buffer (if set)
render.save("images/image.ppm");
if(zBuffer){
render.computeZBuffer();
render.saveZBuffer("images/imageZ.ppm");
}
}
// ray tracing loop (for an individual pixel)
void rayTracing(int i){
// initial starting pixel
int pixel = i;
// thread continuation condition
while(pixel < size){
// establish pixel location
int pX = pixel % w;
int pY = pixel / w;
// transform ray into world space
Point rayDir = cameraRay(pX, pY);
Ray *ray = new Ray();
ray->pos = camera.pos;
ray->dir = c->transformFrom(rayDir);
// traverse through scene DOM
// transform rays into model space
// detect ray intersections and return HitInfo
HitInfo h = objectIntersection(rootNode, *ray);
// update z-buffer, if necessary
if(zBuffer)
zImg[pixel] = h.z;
// try and get the hit object & material
Node *n = h.node;
Material *m;
if(n)
m = n->getMaterial();
// if we hit nothing
Color24 c;
if(h.z == FLOAT_MAX){
c.Set(0, 0, 0);
// shade pixel if it has material
}else if(m)
c = Color24(m->shade(*ray, h, lights));
// otherwise, just color it white
else
c.Set(237, 237, 237);
// color the pixel image
img[pixel] = c;
// re-assign next pixel (naive, but works)
pixel += numThreads;
}
}
// create variables for camera ray generation
void cameraRayVars(){
float fov = camera.fov * M_PI / 180.0;
float aspectRatio = (float) w / (float) h;
float imageDistance = 1.0;
float imageTipY = imageDistance * tan(fov / 2.0);
float imageTipX = imageTipY * aspectRatio;
float dX = (2.0 * imageTipX) / (float) w;
float dY = (2.0 * imageTipY) / (float) h;
imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);
dXV = new Point(dX, 0.0, 0.0);
dYV = new Point(0.0, -dY, 0.0);
firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
// set up camera transformation (only need to rotate coordinates)
c = new Transformation();
Matrix *rotate = new cyMatrix3f();
rotate->Set(camera.cross, camera.up, -camera.dir);
c->transform(*rotate);
}
// compute camera rays
Point cameraRay(int pX, int pY){
Point ray = firstPixel + (*dXV * pX) + (*dYV * pY);
ray.Normalize();
return ray;
}
// recursive object intersection through all scene objects for some ray
HitInfo objectIntersection(Node &n, Ray r){
// hit info of closest node
HitInfo h = HitInfo();
// loop on child nodes
int j = 0;
int numChild = n.getNumChild();
while(j < numChild){
// grab child node
Node *child = n.getChild(j);
Object *obj = child->getObject();
// transform rays into model space (or local space)
Ray ray = child->toModelSpace(r);
// for the child, compute ray intersections into hit info
HitInfo hit = HitInfo();
bool objectHit = obj->intersectRay(ray, hit);
hit.setNode(child);
// recursively check this child's descendants for hit info
HitInfo hitDesc = objectIntersection(*child, ray);
// is descendants' hit info closer?
if(hitDesc.z < hit.z){
hit = hitDesc;
objectHit = true;
}
// only store the closest hit info
if(objectHit)
if(hit.z < h.z){
h = hit;
// transform hit info from model space (towards world space)
child->fromModelSpace(h);
}
// loop through all children
j++;
}
// return hit info of closest node
return h;
}
<commit_msg>refactor and clean up the object intersection, or trace ray, function<commit_after>// Copyright 2013 Sean McKenna
//
// 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.
//
// a ray tracer in C++
// libraries, namespace
#include <thread>
#include <fstream>
#include "library/loadXML.cpp"
#include "library/scene.cpp"
using namespace std;
// scene to load (project #) & whether to debug
const char* xml = "scenes/prj2.xml";
bool printXML = false;
bool zBuffer = false;
// for ray tracing
int w;
int h;
int size;
Color24* img;
float* zImg;
bool objectIntersection(Ray r, HitInfo &h, Node &n);
// for threading
static const int numThreads = 8;
void rayTracing(int i);
// for camera ray generation
void cameraRayVars();
Point *imageTopLeftV;
Point *dXV;
Point *dYV;
Point firstPixel;
Transformation* c;
Point cameraRay(int pX, int pY);
// ray tracer
int main(){
// load scene: root node, camera, image
loadScene(xml, printXML);
// set variables for ray tracing
w = render.getWidth();
h = render.getHeight();
size = render.getSize();
img = render.getRender();
zImg = render.getZBuffer();
// set variables for generating camera rays
cameraRayVars();
// start ray tracing loop (in parallel with threads)
thread t[numThreads];
for(int i = 0; i < numThreads; i++)
t[i] = thread(rayTracing, i);
// when finished, join all threads back to main
for(int i = 0; i < numThreads; i++)
t[i].join();
// output ray-traced image & z-buffer (if set)
render.save("images/image.ppm");
if(zBuffer){
render.computeZBuffer();
render.saveZBuffer("images/imageZ.ppm");
}
}
// ray tracing loop (for an individual pixel)
void rayTracing(int i){
// initial starting pixel
int pixel = i;
// thread continuation condition
while(pixel < size){
// establish pixel location
int pX = pixel % w;
int pY = pixel / w;
// transform ray into world space
Point rayDir = cameraRay(pX, pY);
Ray *ray = new Ray();
ray->pos = camera.pos;
ray->dir = c->transformFrom(rayDir);
// traverse through scene DOM
// transform rays into model space
// detect ray intersections and get back HitInfo
HitInfo h = HitInfo();
bool hit = objectIntersection(*ray, h, rootNode);
// update z-buffer, if necessary
if(zBuffer)
zImg[pixel] = h.z;
// try and get the hit object & material
Node *n = h.node;
Material *m;
if(n)
m = n->getMaterial();
// if we hit nothing
Color24 c;
if(!hit){
c.Set(0, 0, 0);
// shade pixel if it has material
}else if(m)
c = Color24(m->shade(*ray, h, lights));
// otherwise, just color it white
else
c.Set(237, 237, 237);
// color the pixel image
img[pixel] = c;
// re-assign next pixel (naive, but works)
pixel += numThreads;
}
}
// create variables for camera ray generation
void cameraRayVars(){
float fov = camera.fov * M_PI / 180.0;
float aspectRatio = (float) w / (float) h;
float imageDistance = 1.0;
float imageTipY = imageDistance * tan(fov / 2.0);
float imageTipX = imageTipY * aspectRatio;
float dX = (2.0 * imageTipX) / (float) w;
float dY = (2.0 * imageTipY) / (float) h;
imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);
dXV = new Point(dX, 0.0, 0.0);
dYV = new Point(0.0, -dY, 0.0);
firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
// set up camera transformation (only need to rotate coordinates)
c = new Transformation();
Matrix *rotate = new cyMatrix3f();
rotate->Set(camera.cross, camera.up, -camera.dir);
c->transform(*rotate);
}
// compute camera rays
Point cameraRay(int pX, int pY){
Point ray = firstPixel + (*dXV * pX) + (*dYV * pY);
ray.Normalize();
return ray;
}
// recursive object intersection through all scene objects for some ray
bool objectIntersection(Ray r, HitInfo &h, Node &n){
// if object gets hit and hit first
bool objectHit;
// grab node's object
Object *obj = n.getObject();
// transform ray into model space (or local space)
Ray ray = n.toModelSpace(r);
// make hit info for node object (if exists)
HitInfo hit = HitInfo();
if(obj){
hit.setNode(&n);
// check if object is hit
objectHit = obj->intersectRay(ray, hit);
}
// check if hit was closer than previous hits
if(objectHit){
if(hit.z < h.z)
h = hit;
// if hit is not closer, don't count as hit
else
objectHit = false;
}
// loop on child nodes
int j = 0;
int numChild = n.getNumChild();
while(j < numChild){
// grab child node
Node *child = n.getChild(j);
// recursively check this child's descendants for hit info
bool childHit = objectIntersection(ray, h, *child);
// if child is hit, make sure we pass that on
if(childHit)
objectHit = true;
// loop through all children
j++;
}
// if object (or a descendant) was hit, transform from model space (to world space)
if(objectHit)
n.fromModelSpace(h);
// return whether there was a hit on object or its descendants
return objectHit;
}
<|endoftext|> |
<commit_before>/* The MIT License
Copyright (c) 2014 Adrian Tan <atks@umich.edu>
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 "bed.h"
/**
* Constructor.
*/
BEDRecord::BEDRecord(kstring_t *s)
{
std::vector<std::string> fields;
split(fields, "\t", s->s);
chrom = fields[0];
str2int32(fields[1], start1);
str2int32(fields[2], end1);
};
/**
* Constructor.
*/
BEDRecord::BEDRecord(std::string& chrom, int32_t start1, int32_t end1)
{
this->chrom = chrom;
this->start1 = start1;
this->end1 = end1;
};
/**
* Prints this BED record to STDERR.
*/
void BEDRecord::print()
{
std::cerr << this->chrom << ":" << this->start1 << "-" <<this->end1 << "\n";
};
/**
* String version of BED record.
*/
std::string BEDRecord::to_string()
{
return this->chrom + ":" + std::to_string(this->start1) + "-" + std::to_string(this->end1);
};<commit_msg>removed std::to_string()<commit_after>/* The MIT License
Copyright (c) 2014 Adrian Tan <atks@umich.edu>
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 "bed.h"
/**
* Constructor.
*/
BEDRecord::BEDRecord(kstring_t *s)
{
std::vector<std::string> fields;
split(fields, "\t", s->s);
chrom = fields[0];
str2int32(fields[1], start1);
str2int32(fields[2], end1);
};
/**
* Constructor.
*/
BEDRecord::BEDRecord(std::string& chrom, int32_t start1, int32_t end1)
{
this->chrom = chrom;
this->start1 = start1;
this->end1 = end1;
};
/**
* Prints this BED record to STDERR.
*/
void BEDRecord::print()
{
std::cerr << this->chrom << ":" << this->start1 << "-" <<this->end1 << "\n";
};
/**
* String version of BED record.
*/
std::string BEDRecord::to_string()
{
kstring_t s = {0,0,0};
kputs(this->chrom.c_str(), &s);
kputc(':', &s);
kputw(this->start1, &s);
kputc('-', &s);
kputw(this->end1, &s);
std::string str = std::string(s.s);
free(s.s);
return str;
};<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael Koval <mkoval@cs.cmu.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstring>
#include <iostream>
#include "dart/common/Console.h"
#include "LocalResource.h"
namespace dart {
namespace common {
//==============================================================================
LocalResource::LocalResource(const std::string& _path)
: mFile(std::fopen(_path.c_str(), "rb"))
{
if(!mFile)
{
dtwarn << "[LocalResource::constructor] Failed opening file '"
<< _path << "' for reading: "
<< std::strerror(errno) << "\n";
}
}
//==============================================================================
LocalResource::~LocalResource()
{
if (!mFile)
return;
if (std::fclose(mFile) == EOF)
{
dtwarn << "[LocalResource::destructor] Failed closing file: "
<< std::strerror(errno) << "\n";
}
}
//==============================================================================
bool LocalResource::isGood() const
{
return !!mFile;
}
//==============================================================================
size_t LocalResource::getSize()
{
if(!mFile)
return 0;
const long offset = std::ftell(mFile);
if(offset == -1L)
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" getting current offset: "
<< std::strerror(errno) << "\n";
return 0;
}
// The SEEK_END option is not required by the C standard. However, it is
// required by POSIX.
if(std::fseek(mFile, 0, SEEK_END) || std::ferror(mFile))
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" seeking to the end of the file: "
<< std::strerror(errno) << "\n";
return 0;
}
const long size = std::ftell(mFile);
if(size == -1L)
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" getting end of file offset: "
<< std::strerror(errno) << "\n";
return 0;
}
if(std::fseek(mFile, offset, SEEK_SET) || std::ferror(mFile))
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" restoring offset: "
<< std::strerror(errno) << "\n";
return 0;
}
return size;
}
//==============================================================================
size_t LocalResource::tell()
{
if(!mFile)
return 0;
const long offset = std::ftell(mFile);
if(offset == -1L)
{
dtwarn << "[LocalResource::tell] Failed getting current offset: "
<< std::strerror(errno) << "\n";
}
// We return -1 to match the beahvior of DefaultIoStream in Assimp.
return offset;
}
//==============================================================================
bool LocalResource::seek(ptrdiff_t _offset, SeekType _mode)
{
int origin;
switch(_mode)
{
case Resource::SEEKTYPE_CUR:
origin = SEEK_CUR;
break;
case Resource::SEEKTYPE_END:
origin = SEEK_END;
break;
case Resource::SEEKTYPE_SET:
origin = SEEK_SET;
break;
default:
dtwarn << "[LocalResource::seek] Invalid origin. Expected"
" SEEKTYPE_CUR, SEEKTYPE_END, or SEEKTYPE_SET.\n";
return false;
}
if (!std::fseek(mFile, _offset, origin) && !std::ferror(mFile))
return true;
else
{
dtwarn << "[LocalResource::seek] Failed seeking: "
<< std::strerror(errno) << "\n";
return false;
}
}
//==============================================================================
size_t LocalResource::read(void *_buffer, size_t _size, size_t _count)
{
if (!mFile)
return 0;
const size_t result = std::fread(_buffer, _size, _count, mFile);
if (std::ferror(mFile))
{
dtwarn << "[LocalResource::read] Failed reading file: "
<< std::strerror(errno) << "\n";
}
return result;
}
} // namespace common
} // namespace dart
<commit_msg>Workaround for ftell bug in Linux<commit_after>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael Koval <mkoval@cs.cmu.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstring>
#include <limits>
#include <iostream>
#include "dart/common/Console.h"
#include "LocalResource.h"
namespace dart {
namespace common {
//==============================================================================
LocalResource::LocalResource(const std::string& _path)
: mFile(std::fopen(_path.c_str(), "rb"))
{
if(!mFile)
{
dtwarn << "[LocalResource::constructor] Failed opening file '"
<< _path << "' for reading: "
<< std::strerror(errno) << "\n";
}
}
//==============================================================================
LocalResource::~LocalResource()
{
if (!mFile)
return;
if (std::fclose(mFile) == EOF)
{
dtwarn << "[LocalResource::destructor] Failed closing file: "
<< std::strerror(errno) << "\n";
}
}
//==============================================================================
bool LocalResource::isGood() const
{
return !!mFile;
}
//==============================================================================
size_t LocalResource::getSize()
{
if(!mFile)
return 0;
const long offset = std::ftell(mFile);
if(offset == -1L)
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" getting current offset: "
<< std::strerror(errno) << "\n";
return 0;
}
// The SEEK_END option is not required by the C standard. However, it is
// required by POSIX.
if(std::fseek(mFile, 0, SEEK_END) || std::ferror(mFile))
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" seeking to the end of the file: "
<< std::strerror(errno) << "\n";
return 0;
}
const long size = std::ftell(mFile);
if(size == -1L)
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" getting end of file offset: "
<< std::strerror(errno) << "\n";
return 0;
}
// fopen, ftell, and fseek produce undefined behavior when called on
// directories. ftell() on Linux libc returns LONG_MAX, unless you are in an
// NFS mount.
//
// See here: http://stackoverflow.com/a/18193383/111426
else if(size == std::numeric_limits<long>::max())
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Computed"
" file size of LONG_MAX. Is this a directory?\n";
return 0;
}
if(std::fseek(mFile, offset, SEEK_SET) || std::ferror(mFile))
{
dtwarn << "[LocalResource::getSize] Unable to compute file size: Failed"
" restoring offset: "
<< std::strerror(errno) << "\n";
return 0;
}
return size;
}
//==============================================================================
size_t LocalResource::tell()
{
if(!mFile)
return 0;
const long offset = std::ftell(mFile);
if(offset == -1L)
{
dtwarn << "[LocalResource::tell] Failed getting current offset: "
<< std::strerror(errno) << "\n";
}
// fopen, ftell, and fseek produce undefined behavior when called on
// directories. ftell() on Linux libc returns LONG_MAX, unless you are in an
// NFS mount.
//
// See here: http://stackoverflow.com/a/18193383/111426
else if(offset == std::numeric_limits<long>::max())
{
dtwarn << "[LocalResource::tell] Failed getting current offset: ftell"
" returned LONG_MAX. Is this a directory?\n";
return -1L;
}
// We return -1 to match the beahvior of DefaultIoStream in Assimp.
return offset;
}
//==============================================================================
bool LocalResource::seek(ptrdiff_t _offset, SeekType _mode)
{
int origin;
switch(_mode)
{
case Resource::SEEKTYPE_CUR:
origin = SEEK_CUR;
break;
case Resource::SEEKTYPE_END:
origin = SEEK_END;
break;
case Resource::SEEKTYPE_SET:
origin = SEEK_SET;
break;
default:
dtwarn << "[LocalResource::seek] Invalid origin. Expected"
" SEEKTYPE_CUR, SEEKTYPE_END, or SEEKTYPE_SET.\n";
return false;
}
if (!std::fseek(mFile, _offset, origin) && !std::ferror(mFile))
return true;
else
{
dtwarn << "[LocalResource::seek] Failed seeking: "
<< std::strerror(errno) << "\n";
return false;
}
}
//==============================================================================
size_t LocalResource::read(void *_buffer, size_t _size, size_t _count)
{
if (!mFile)
return 0;
const size_t result = std::fread(_buffer, _size, _count, mFile);
if (std::ferror(mFile))
{
dtwarn << "[LocalResource::read] Failed reading file: "
<< std::strerror(errno) << "\n";
}
return result;
}
} // namespace common
} // namespace dart
<|endoftext|> |
<commit_before>#include "stdafx.h"
#ifdef _MSC_VER
bool SaveFile(const char *fileName, const uint8_t* buf, int size)
{
bool result = false;
FILE *f = nullptr;
if (fopen_s(&f, fileName, "wb")) {
return false;
}
if (!fwrite(buf, size, 1, f)) {
goto DONE;
}
result = !fclose(f);
f = nullptr;
DONE:
if (f) {
fclose(f);
}
return result;
}
void *LoadFile(const char *fileName, int* size)
{
bool result = false;
FILE *f = nullptr;
int _size;
void *ptr = NULL;
if (fopen_s(&f, fileName, "rb")) {
return nullptr;
}
if (fseek(f, 0, SEEK_END)) {
goto DONE;
}
_size = ftell(f);
if (_size < 0) {
goto DONE;
}
if (fseek(f, 0, SEEK_SET)) {
goto DONE;
}
ptr = calloc(_size + 1, 1);
if (!ptr) {
goto DONE;
}
if (_size > 0) {
if (!fread(ptr, _size, 1, f)) {
goto DONE;
}
}
result = true;
if (size) {
*size = _size;
}
DONE:
if (f) {
fclose(f);
}
if (result){
return ptr;
} else {
if (ptr) {
free(ptr);
}
return nullptr;
}
}
void GoMyDir()
{
char dir[MAX_PATH];
GetModuleFileNameA(GetModuleHandleA(nullptr), dir, MAX_PATH);
char* p = strrchr(dir, '\\');
assert(p);
*p = '\0';
SetCurrentDirectoryA(dir);
SetCurrentDirectoryA("../../pack/assets");
}
#pragma comment(lib, "winmm.lib")
void PlayBgm(const char* fileName)
{
// PlaySoundA(fileName, NULL, SND_ASYNC | SND_LOOP);
mciSendStringA(SPrintf("open \"%s\" type mpegvideo", fileName), NULL, 0, 0);
mciSendStringA(SPrintf("play \"%s\" repeat", fileName), NULL, 0, 0);
}
static UINT StrToType(const char* type)
{
if (!strcmp(type, "okcancel")) {
return MB_OKCANCEL;
} else if (!strcmp(type, "yesno")) {
return MB_YESNO;
}
return MB_OK;
}
static const char* IdToStr(int id)
{
switch (id) {
case IDOK: return "ok";
case IDCANCEL: return "cancel";
case IDYES: return "yes";
case IDNO: return "no";
}
return "unknown";
}
const char* StrMessageBox(const char* txt, const char* type)
{
return IdToStr(MessageBoxA(GetActiveWindow(), txt, "MessageBox", StrToType(type)));
}
namespace Gdiplus {
using std::min;
using std::max;
}
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
bool LoadImageViaGdiPlus(const char* name, IVec2& size, std::vector<uint32_t>& col)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
WCHAR wc[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));
Gdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);
int w = (int)image->GetWidth();
int h = (int)image->GetHeight();
size.x = w;
size.y = h;
Gdiplus::Rect rc(0, 0, w, h);
Gdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;
image->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);
col.resize(w * h);
for (int y = 0; y < h; y++) {
memcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);
for (int x = 0; x < w; x++) {
uint32_t& c = col[y * w + x];
c = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);
}
}
image->UnlockBits(bitmapData);
delete bitmapData;
delete image;
Gdiplus::GdiplusShutdown(gdiplusToken);
return w && h;
}
SRVID LoadTextureViaOS(const char* name, IVec2& size)
{
std::vector<uint32_t> col;
if (!LoadImageViaGdiPlus(name, size, col)) {
return SRVID();
}
return afCreateTexture2D(AFDT_R8G8B8A8_UNORM_SRGB, size, &col[0]);
}
#define IS_HANGUL(c) ( (c) >= 0xAC00 && (c) <= 0xD7A3 )
#define IS_HANGUL2(c) ( ( (c) >= 0x3130 && (c) <= 0x318F ) || IS_HANGUL(c) ) // hangul + jamo
static bool isKorean(int code)
{
return IS_HANGUL2(code) || code < 0x80;
}
static HFONT CreateAsianFont(int code, int height)
{
BOOL isK = isKorean(code);
const char *fontName = isK ? "Gulim" : "MS Gothic";
const DWORD charset = isK ? HANGUL_CHARSET : SHIFTJIS_CHARSET;
return CreateFontA(height, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_MEDIUM, // Font Weight
FALSE, // Italic
FALSE, // Underline
FALSE, // Strikeout
charset, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE | DEFAULT_PITCH, // Family And Pitch
fontName); // Font Name
}
void MakeFontBitmap(const char* fontName, const CharSignature& sig, DIB& dib, CharDesc& cache)
{
bool result = false;
HFONT font = CreateAsianFont(sig.code, sig.fontSize);
assert(font);
dib.Clear();
wchar_t buf[] = { sig.code, '\0' };
HDC hdc = GetDC(nullptr);
assert(hdc);
HFONT oldFont = (HFONT)SelectObject(hdc, font);
const MAT2 mat = { { 0,1 },{ 0,0 },{ 0,0 },{ 0,1 } };
GLYPHMETRICS met;
memset(&met, 0, sizeof(met));
DWORD sizeReq = GetGlyphOutlineW(hdc, (UINT)sig.code, GGO_GRAY8_BITMAP, &met, 0, nullptr, &mat);
if (sizeReq) {
DIB dib3;
afVerify(dib3.Create(met.gmBlackBoxX, met.gmBlackBoxY, 8, 64));
afVerify(dib.Create(met.gmBlackBoxX, met.gmBlackBoxY));
int sizeBuf = dib3.GetByteSize();
if (sizeReq != sizeBuf) {
aflog("FontMan::Build() buf size mismatch! code=%d req=%d dib=%d\n", sig.code, sizeReq, sizeBuf);
int fakeBlackBoxY = met.gmBlackBoxY + 1;
afVerify(dib3.Create(met.gmBlackBoxX, fakeBlackBoxY, 8, 64));
afVerify(dib.Create(met.gmBlackBoxX, fakeBlackBoxY));
int sizeBuf = dib3.GetByteSize();
if (sizeReq != sizeBuf) {
afVerify(false);
} else {
aflog("FontMan::Build() buf size matched by increasing Y, but it is an awful workaround. code=%d req=%d dib=%d\n", sig.code, sizeReq, sizeBuf);
}
}
memset(&met, 0, sizeof(met));
GetGlyphOutlineW(hdc, (UINT)sig.code, GGO_GRAY8_BITMAP, &met, sizeReq, dib3.ReferPixels(), &mat);
// SetTextColor(hdc, RGB(255, 255, 255));
// SetBkColor(hdc, RGB(0, 0, 0));
// TextOutW(hdc, 0, 0, buf, wcslen(buf));
dib3.Blt(dib.GetHDC(), 0, 0, dib3.getW(), dib3.getH());
// dib.Save(SPrintf("../ScreenShot/%04x.bmp", sig.code));
dib.DibToDXFont();
}
SelectObject(hdc, (HGDIOBJ)oldFont);
if (font) {
DeleteObject(font);
}
ReleaseDC(nullptr, hdc);
cache.srcWidth = Vec2((float)met.gmBlackBoxX, (float)met.gmBlackBoxY);
cache.step = (float)met.gmCellIncX;
cache.distDelta = Vec2((float)met.gmptGlyphOrigin.x, (float)-met.gmptGlyphOrigin.y);
}
#endif
<commit_msg>Revert SRGB test.<commit_after>#include "stdafx.h"
#ifdef _MSC_VER
bool SaveFile(const char *fileName, const uint8_t* buf, int size)
{
bool result = false;
FILE *f = nullptr;
if (fopen_s(&f, fileName, "wb")) {
return false;
}
if (!fwrite(buf, size, 1, f)) {
goto DONE;
}
result = !fclose(f);
f = nullptr;
DONE:
if (f) {
fclose(f);
}
return result;
}
void *LoadFile(const char *fileName, int* size)
{
bool result = false;
FILE *f = nullptr;
int _size;
void *ptr = NULL;
if (fopen_s(&f, fileName, "rb")) {
return nullptr;
}
if (fseek(f, 0, SEEK_END)) {
goto DONE;
}
_size = ftell(f);
if (_size < 0) {
goto DONE;
}
if (fseek(f, 0, SEEK_SET)) {
goto DONE;
}
ptr = calloc(_size + 1, 1);
if (!ptr) {
goto DONE;
}
if (_size > 0) {
if (!fread(ptr, _size, 1, f)) {
goto DONE;
}
}
result = true;
if (size) {
*size = _size;
}
DONE:
if (f) {
fclose(f);
}
if (result){
return ptr;
} else {
if (ptr) {
free(ptr);
}
return nullptr;
}
}
void GoMyDir()
{
char dir[MAX_PATH];
GetModuleFileNameA(GetModuleHandleA(nullptr), dir, MAX_PATH);
char* p = strrchr(dir, '\\');
assert(p);
*p = '\0';
SetCurrentDirectoryA(dir);
SetCurrentDirectoryA("../../pack/assets");
}
#pragma comment(lib, "winmm.lib")
void PlayBgm(const char* fileName)
{
// PlaySoundA(fileName, NULL, SND_ASYNC | SND_LOOP);
mciSendStringA(SPrintf("open \"%s\" type mpegvideo", fileName), NULL, 0, 0);
mciSendStringA(SPrintf("play \"%s\" repeat", fileName), NULL, 0, 0);
}
static UINT StrToType(const char* type)
{
if (!strcmp(type, "okcancel")) {
return MB_OKCANCEL;
} else if (!strcmp(type, "yesno")) {
return MB_YESNO;
}
return MB_OK;
}
static const char* IdToStr(int id)
{
switch (id) {
case IDOK: return "ok";
case IDCANCEL: return "cancel";
case IDYES: return "yes";
case IDNO: return "no";
}
return "unknown";
}
const char* StrMessageBox(const char* txt, const char* type)
{
return IdToStr(MessageBoxA(GetActiveWindow(), txt, "MessageBox", StrToType(type)));
}
namespace Gdiplus {
using std::min;
using std::max;
}
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
bool LoadImageViaGdiPlus(const char* name, IVec2& size, std::vector<uint32_t>& col)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
WCHAR wc[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));
Gdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);
int w = (int)image->GetWidth();
int h = (int)image->GetHeight();
size.x = w;
size.y = h;
Gdiplus::Rect rc(0, 0, w, h);
Gdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;
image->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);
col.resize(w * h);
for (int y = 0; y < h; y++) {
memcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);
for (int x = 0; x < w; x++) {
uint32_t& c = col[y * w + x];
c = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);
}
}
image->UnlockBits(bitmapData);
delete bitmapData;
delete image;
Gdiplus::GdiplusShutdown(gdiplusToken);
return w && h;
}
SRVID LoadTextureViaOS(const char* name, IVec2& size)
{
std::vector<uint32_t> col;
if (!LoadImageViaGdiPlus(name, size, col)) {
return SRVID();
}
return afCreateTexture2D(AFDT_R8G8B8A8_UNORM, size, &col[0]);
}
#define IS_HANGUL(c) ( (c) >= 0xAC00 && (c) <= 0xD7A3 )
#define IS_HANGUL2(c) ( ( (c) >= 0x3130 && (c) <= 0x318F ) || IS_HANGUL(c) ) // hangul + jamo
static bool isKorean(int code)
{
return IS_HANGUL2(code) || code < 0x80;
}
static HFONT CreateAsianFont(int code, int height)
{
BOOL isK = isKorean(code);
const char *fontName = isK ? "Gulim" : "MS Gothic";
const DWORD charset = isK ? HANGUL_CHARSET : SHIFTJIS_CHARSET;
return CreateFontA(height, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_MEDIUM, // Font Weight
FALSE, // Italic
FALSE, // Underline
FALSE, // Strikeout
charset, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE | DEFAULT_PITCH, // Family And Pitch
fontName); // Font Name
}
void MakeFontBitmap(const char* fontName, const CharSignature& sig, DIB& dib, CharDesc& cache)
{
bool result = false;
HFONT font = CreateAsianFont(sig.code, sig.fontSize);
assert(font);
dib.Clear();
wchar_t buf[] = { sig.code, '\0' };
HDC hdc = GetDC(nullptr);
assert(hdc);
HFONT oldFont = (HFONT)SelectObject(hdc, font);
const MAT2 mat = { { 0,1 },{ 0,0 },{ 0,0 },{ 0,1 } };
GLYPHMETRICS met;
memset(&met, 0, sizeof(met));
DWORD sizeReq = GetGlyphOutlineW(hdc, (UINT)sig.code, GGO_GRAY8_BITMAP, &met, 0, nullptr, &mat);
if (sizeReq) {
DIB dib3;
afVerify(dib3.Create(met.gmBlackBoxX, met.gmBlackBoxY, 8, 64));
afVerify(dib.Create(met.gmBlackBoxX, met.gmBlackBoxY));
int sizeBuf = dib3.GetByteSize();
if (sizeReq != sizeBuf) {
aflog("FontMan::Build() buf size mismatch! code=%d req=%d dib=%d\n", sig.code, sizeReq, sizeBuf);
int fakeBlackBoxY = met.gmBlackBoxY + 1;
afVerify(dib3.Create(met.gmBlackBoxX, fakeBlackBoxY, 8, 64));
afVerify(dib.Create(met.gmBlackBoxX, fakeBlackBoxY));
int sizeBuf = dib3.GetByteSize();
if (sizeReq != sizeBuf) {
afVerify(false);
} else {
aflog("FontMan::Build() buf size matched by increasing Y, but it is an awful workaround. code=%d req=%d dib=%d\n", sig.code, sizeReq, sizeBuf);
}
}
memset(&met, 0, sizeof(met));
GetGlyphOutlineW(hdc, (UINT)sig.code, GGO_GRAY8_BITMAP, &met, sizeReq, dib3.ReferPixels(), &mat);
// SetTextColor(hdc, RGB(255, 255, 255));
// SetBkColor(hdc, RGB(0, 0, 0));
// TextOutW(hdc, 0, 0, buf, wcslen(buf));
dib3.Blt(dib.GetHDC(), 0, 0, dib3.getW(), dib3.getH());
// dib.Save(SPrintf("../ScreenShot/%04x.bmp", sig.code));
dib.DibToDXFont();
}
SelectObject(hdc, (HGDIOBJ)oldFont);
if (font) {
DeleteObject(font);
}
ReleaseDC(nullptr, hdc);
cache.srcWidth = Vec2((float)met.gmBlackBoxX, (float)met.gmBlackBoxY);
cache.step = (float)met.gmCellIncX;
cache.distDelta = Vec2((float)met.gmptGlyphOrigin.x, (float)-met.gmptGlyphOrigin.y);
}
#endif
<|endoftext|> |
<commit_before>/**********
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. (See <http://www.gnu.org/copyleft/lesser.html>.)
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
**********/
// Copyright (c) 1996-2013, Live Networks, Inc. All rights reserved
// A test program that demonstrates how to stream - via unicast RTP
// - various kinds of file on demand, using a built-in RTSP server.
// main program
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
#include "liveMedia.hh"
#include <GroupsockHelper.hh>
#define EventTime server_EventTime
#include "BasicUsageEnvironment.hh"
#undef EventTime
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "H264VideoOnDemandServerMediaSubsession.h"
#include "shared.h"
#include "config.h"
#include "RandomFramedSource.h"
#include "AlloShared/CubemapFace.h"
#include "AlloServer.h"
#include "concurrent_queue.h"
#include "CubemapFaceSource.h"
//RTPSink* videoSink;
UsageEnvironment* env;
// To make the second and subsequent client for each stream reuse the same
// input stream as the first client (rather than playing the file from the
// start for each client), change the following "False" to "True":
Boolean reuseFirstSource = True;
// To stream *only* MPEG-1 or 2 video "I" frames
// (e.g., to reduce network bandwidth),
// change the following "False" to "True":
Boolean iFramesOnly = False;
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName); // fwd
static char newMatroskaDemuxWatchVariable;
static MatroskaFileServerDemux* demux;
static void onMatroskaDemuxCreation(MatroskaFileServerDemux* newDemux, void* /*clientData*/) {
demux = newDemux;
newMatroskaDemuxWatchVariable = 1;
}
void eventLoop(int port);
void addFaceSubstream();
void startRTSP(int port){
// pthread_t thread;
// return pthread_create(&thread,NULL,eventLoop, NULL);
boost::thread thread1(boost::bind(&eventLoop, port));
}
ServerMediaSession* sms;
EventTriggerId addFaceSubstreamTriggerId;
concurrent_queue<CubemapFace*> faceBuffer;
struct in_addr destinationAddress;
static struct FaceStreamState
{
RTPSink* sink;
CubemapFace* face;
FramedSource* source;
};
void afterPlaying(void* clientData)
{
FaceStreamState* state = (FaceStreamState*)clientData;
*env << "stopped streaming face " << state->face->index << "\n";
state->sink->stopPlaying();
Medium::close(state->source);
// Note that this also closes the input file that this source read from.
delete state;
}
const unsigned short rtpPortNum = 18888;
const unsigned char ttl = 255;
void addFaceSubstream0(void*) {
CubemapFace* face;
while (faceBuffer.try_pop(face))
{
FaceStreamState* state = new FaceStreamState;
state->face = face;
Port rtpPort(rtpPortNum + face->index);
Groupsock rtpGroupsock(*env, destinationAddress, rtpPort, ttl);
rtpGroupsock.multicastSendOnly(); // we're a SSM source
// Create a 'H264 Video RTP' sink from the RTP 'groupsock':
OutPacketBuffer::maxSize = 100000;
state->sink = H264VideoRTPSink::createNew(*env, &rtpGroupsock, 96);
ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink);
//H264VideoOnDemandServerMediaSubsession *subsession = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, face);
sms->addSubsession(subsession);
state->source = H264VideoStreamDiscreteFramer::createNew(*env, CubemapFaceSource::createNew(*env, face));
state->sink->startPlaying(*state->source, afterPlaying, state);
std::cout << "added face " << face->index << std::endl;
}
}
std::vector<H264VideoOnDemandServerMediaSubsession*> faceSubstreams;
void addFaceSubstream()
{
std::list<int> addedFaces;
while (true)
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(cubemap->mutex);
//
for (int i = 0; i < cubemap->count(); i++)
{
if (std::find(addedFaces.begin(), addedFaces.end(), cubemap->getFace(i)->index) == addedFaces.end())
{
faceBuffer.push(cubemap->getFace(i).get());
addedFaces.push_back(cubemap->getFace(i)->index);
}
}
if (!faceBuffer.empty())
{
env->taskScheduler().triggerEvent(addFaceSubstreamTriggerId, NULL);
}
cubemap->newFaceCondition.wait(lock);
}
}
void eventLoop(int port) {
// Begin by setting up our usage environment:
TaskScheduler* scheduler = BasicTaskScheduler::createNew();
env = BasicUsageEnvironment::createNew(*scheduler);
// Create 'groupsocks' for RTP and RTCP:
destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env);
// Note: This is a multicast address. If you wish instead to stream
// using unicast, then you should use the "testOnDemandRTSPServer"
// test program - not this test program - as a model.
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(destinationAddress.s_addr), str, INET_ADDRSTRLEN);
printf("Multicast address: %s\n", str);
UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
// To implement client access control to the RTSP server, do the following:
authDB = new UserAuthenticationDatabase;
authDB->addUserRecord("username1", "password1"); // replace these with real strings
// Repeat the above with each <username>, <password> that you wish to allow
// access to the server.
#endif
// Create the RTSP server:
RTSPServer* rtspServer = RTSPServer::createNew(*env, port, authDB);
//RTSPServer* rtspServer = RTSPServer::createNew(*env, 8555, authDB);
if (rtspServer == NULL) {
*env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
exit(1);
}
char const* descriptionString
= "Session streamed by \"testOnDemandRTSPServer\"";
// Set up each of the possible streams that can be served by the
// RTSP server. Each such stream is implemented using a
// "ServerMediaSession" object, plus one or more
// "ServerMediaSubsession" objects for each audio/video substream.
OutPacketBuffer::maxSize = 4000000;
// A H.264 video elementary stream:
{
char const* streamName = "h264ESVideoTest";
sms = ServerMediaSession::createNew(*env, streamName, streamName,
descriptionString, True);
//H264VideoOnDemandServerMediaSubsession *subsession2 = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, "two");
//videoSink = subsession->createNewRTPSink(groupSock, 96);
//sms->addSubsession(subsession1);
rtspServer->addServerMediaSession(sms);
announceStream(rtspServer, sms, streamName);
}
// Also, attempt to create a HTTP server for RTSP-over-HTTP tunneling.
// Try first with the default HTTP port (80), and then with the alternative HTTP
// port numbers (8000 and 8080).
/*if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) {
*env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n";
} else {
*env << "\n(RTSP-over-HTTP tunneling is not available.)\n";
}*/
/*
// Start the streaming:
*env << "Beginning streaming...\n";
startPlay();
//play(NULL);
usleep(5000000);
printf("done play\n");
*/
addFaceSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstream0);
boost::thread thread2(&addFaceSubstream);
env->taskScheduler().doEventLoop(); // does not return
// return 0; // only to prevent compiler warning
}
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName) {
char* url = rtspServer->rtspURL(sms);
UsageEnvironment& env = rtspServer->envir();
env << "Play this stream using the URL \"" << url << "\"\n";
delete[] url;
}
<commit_msg>Fixed crash<commit_after>/**********
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. (See <http://www.gnu.org/copyleft/lesser.html>.)
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
**********/
// Copyright (c) 1996-2013, Live Networks, Inc. All rights reserved
// A test program that demonstrates how to stream - via unicast RTP
// - various kinds of file on demand, using a built-in RTSP server.
// main program
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
#include "liveMedia.hh"
#include <GroupsockHelper.hh>
#define EventTime server_EventTime
#include "BasicUsageEnvironment.hh"
#undef EventTime
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "H264VideoOnDemandServerMediaSubsession.h"
#include "shared.h"
#include "config.h"
#include "RandomFramedSource.h"
#include "AlloShared/CubemapFace.h"
#include "AlloServer.h"
#include "concurrent_queue.h"
#include "CubemapFaceSource.h"
//RTPSink* videoSink;
UsageEnvironment* env;
// To make the second and subsequent client for each stream reuse the same
// input stream as the first client (rather than playing the file from the
// start for each client), change the following "False" to "True":
Boolean reuseFirstSource = True;
// To stream *only* MPEG-1 or 2 video "I" frames
// (e.g., to reduce network bandwidth),
// change the following "False" to "True":
Boolean iFramesOnly = False;
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName); // fwd
static char newMatroskaDemuxWatchVariable;
static MatroskaFileServerDemux* demux;
static void onMatroskaDemuxCreation(MatroskaFileServerDemux* newDemux, void* /*clientData*/) {
demux = newDemux;
newMatroskaDemuxWatchVariable = 1;
}
void eventLoop(int port);
void addFaceSubstream();
void startRTSP(int port){
// pthread_t thread;
// return pthread_create(&thread,NULL,eventLoop, NULL);
boost::thread thread1(boost::bind(&eventLoop, port));
}
ServerMediaSession* sms;
EventTriggerId addFaceSubstreamTriggerId;
concurrent_queue<CubemapFace*> faceBuffer;
struct in_addr destinationAddress;
static struct FaceStreamState
{
RTPSink* sink;
CubemapFace* face;
FramedSource* source;
};
void afterPlaying(void* clientData)
{
FaceStreamState* state = (FaceStreamState*)clientData;
*env << "stopped streaming face " << state->face->index << "\n";
state->sink->stopPlaying();
Medium::close(state->source);
// Note that this also closes the input file that this source read from.
delete state;
}
const unsigned short rtpPortNum = 18888;
const unsigned char ttl = 255;
void addFaceSubstream0(void*) {
CubemapFace* face;
while (faceBuffer.try_pop(face))
{
FaceStreamState* state = new FaceStreamState;
state->face = face;
Port rtpPort(rtpPortNum + face->index);
Groupsock* rtpGroupsock = new Groupsock(*env, destinationAddress, rtpPort, ttl);
rtpGroupsock->multicastSendOnly(); // we're a SSM source
// Create a 'H264 Video RTP' sink from the RTP 'groupsock':
OutPacketBuffer::maxSize = 100000;
state->sink = H264VideoRTPSink::createNew(*env, rtpGroupsock, 96);
ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink);
//H264VideoOnDemandServerMediaSubsession *subsession = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, face);
sms->addSubsession(subsession);
state->source = H264VideoStreamDiscreteFramer::createNew(*env, CubemapFaceSource::createNew(*env, face));
state->sink->startPlaying(*state->source, afterPlaying, state);
std::cout << "added face " << face->index << std::endl;
}
}
std::vector<H264VideoOnDemandServerMediaSubsession*> faceSubstreams;
void addFaceSubstream()
{
std::list<int> addedFaces;
while (true)
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(cubemap->mutex);
//
for (int i = 0; i < cubemap->count(); i++)
{
if (std::find(addedFaces.begin(), addedFaces.end(), cubemap->getFace(i)->index) == addedFaces.end())
{
faceBuffer.push(cubemap->getFace(i).get());
addedFaces.push_back(cubemap->getFace(i)->index);
}
}
if (!faceBuffer.empty())
{
env->taskScheduler().triggerEvent(addFaceSubstreamTriggerId, NULL);
}
cubemap->newFaceCondition.wait(lock);
}
}
void eventLoop(int port) {
// Begin by setting up our usage environment:
TaskScheduler* scheduler = BasicTaskScheduler::createNew();
env = BasicUsageEnvironment::createNew(*scheduler);
// Create 'groupsocks' for RTP and RTCP:
destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env);
// Note: This is a multicast address. If you wish instead to stream
// using unicast, then you should use the "testOnDemandRTSPServer"
// test program - not this test program - as a model.
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(destinationAddress.s_addr), str, INET_ADDRSTRLEN);
printf("Multicast address: %s\n", str);
UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
// To implement client access control to the RTSP server, do the following:
authDB = new UserAuthenticationDatabase;
authDB->addUserRecord("username1", "password1"); // replace these with real strings
// Repeat the above with each <username>, <password> that you wish to allow
// access to the server.
#endif
// Create the RTSP server:
RTSPServer* rtspServer = RTSPServer::createNew(*env, port, authDB);
//RTSPServer* rtspServer = RTSPServer::createNew(*env, 8555, authDB);
if (rtspServer == NULL) {
*env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
exit(1);
}
char const* descriptionString
= "Session streamed by \"testOnDemandRTSPServer\"";
// Set up each of the possible streams that can be served by the
// RTSP server. Each such stream is implemented using a
// "ServerMediaSession" object, plus one or more
// "ServerMediaSubsession" objects for each audio/video substream.
OutPacketBuffer::maxSize = 4000000;
// A H.264 video elementary stream:
{
char const* streamName = "h264ESVideoTest";
sms = ServerMediaSession::createNew(*env, streamName, streamName,
descriptionString, True);
//H264VideoOnDemandServerMediaSubsession *subsession2 = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, "two");
//videoSink = subsession->createNewRTPSink(groupSock, 96);
//sms->addSubsession(subsession1);
rtspServer->addServerMediaSession(sms);
announceStream(rtspServer, sms, streamName);
}
// Also, attempt to create a HTTP server for RTSP-over-HTTP tunneling.
// Try first with the default HTTP port (80), and then with the alternative HTTP
// port numbers (8000 and 8080).
/*if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) {
*env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n";
} else {
*env << "\n(RTSP-over-HTTP tunneling is not available.)\n";
}*/
/*
// Start the streaming:
*env << "Beginning streaming...\n";
startPlay();
//play(NULL);
usleep(5000000);
printf("done play\n");
*/
addFaceSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstream0);
boost::thread thread2(&addFaceSubstream);
env->taskScheduler().doEventLoop(); // does not return
// return 0; // only to prevent compiler warning
}
static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
char const* streamName) {
char* url = rtspServer->rtspURL(sms);
UsageEnvironment& env = rtspServer->envir();
env << "Play this stream using the URL \"" << url << "\"\n";
delete[] url;
}
<|endoftext|> |
<commit_before>#ifndef BALLSWINDOW_HPP
#define BALLSWINDOW_HPP
#include "ui_BallsWindow.h"
#include <QtGlobal>
#include "config/ProjectConfig.hpp"
#include "model/Meshes.hpp"
#include "model/Uniforms.hpp"
#include "shader/ShaderUniform.hpp"
class QsciLexerGLSL;
class QErrorMessage;
class QFileDialog;
class QSettings;
class QCloseEvent;
namespace balls {
using std::random_device;
using std::default_random_engine;
using std::uniform_real_distribution;
class BallsWindow : public QMainWindow {
Q_OBJECT
public:
explicit BallsWindow(QWidget* parent = 0) noexcept;
~BallsWindow();
config::ProjectConfig getProjectConfig() const noexcept;
public slots:
// void setMesh(const int) noexcept;
void saveProject() noexcept;
void loadProject();
protected /* events */:
void closeEvent(QCloseEvent*) override;
private /* members */:
Ui::BallsWindow ui;
bool _generatorsInitialized;
QSettings* _settings;
private /* UI components/dialogs/etc. */:
QsciLexerGLSL* _vertLexer;
QsciLexerGLSL* _fragLexer;
QsciLexerGLSL* _geomLexer;
QFileDialog* _save;
QFileDialog* _load;
QErrorMessage* _error;
private /* data models */:
Uniforms m_uniforms;
Meshes m_meshes;
private slots:
void _saveProject(const QString&) noexcept;
void _loadProject(const QString&) noexcept;
void loadExample() noexcept;
// void initializeMeshGenerators() noexcept;
void forceShaderUpdate() noexcept;
void reportFatalError(const QString&, const QString&, const int) noexcept;
void reportWarning(const QString&, const QString&) noexcept;
void showAboutQt() noexcept;
// HACK: Must figure out why Qt Designer doesn't see meshManager
void on_meshManager_meshSelected(const Mesh&);
};
}
#endif // BALLSWINDOW_HPP
<commit_msg>Mark BallsWindow::getProjectConfig as deprecated<commit_after>#ifndef BALLSWINDOW_HPP
#define BALLSWINDOW_HPP
#include "ui_BallsWindow.h"
#include <QtGlobal>
#include "config/ProjectConfig.hpp"
#include "model/Meshes.hpp"
#include "model/Uniforms.hpp"
#include "shader/ShaderUniform.hpp"
class QsciLexerGLSL;
class QErrorMessage;
class QFileDialog;
class QSettings;
class QCloseEvent;
namespace balls {
using std::random_device;
using std::default_random_engine;
using std::uniform_real_distribution;
class BallsWindow : public QMainWindow {
Q_OBJECT
public:
explicit BallsWindow(QWidget* parent = 0) noexcept;
~BallsWindow();
Q_DECL_DEPRECATED config::ProjectConfig getProjectConfig() const noexcept;
public slots:
// void setMesh(const int) noexcept;
void saveProject() noexcept;
void loadProject();
protected /* events */:
void closeEvent(QCloseEvent*) override;
private /* members */:
Ui::BallsWindow ui;
bool _generatorsInitialized;
QSettings* _settings;
private /* UI components/dialogs/etc. */:
QsciLexerGLSL* _vertLexer;
QsciLexerGLSL* _fragLexer;
QsciLexerGLSL* _geomLexer;
QFileDialog* _save;
QFileDialog* _load;
QErrorMessage* _error;
private /* data models */:
Uniforms m_uniforms;
Meshes m_meshes;
private slots:
void _saveProject(const QString&) noexcept;
void _loadProject(const QString&) noexcept;
void loadExample() noexcept;
// void initializeMeshGenerators() noexcept;
void forceShaderUpdate() noexcept;
void reportFatalError(const QString&, const QString&, const int) noexcept;
void reportWarning(const QString&, const QString&) noexcept;
void showAboutQt() noexcept;
// HACK: Must figure out why Qt Designer doesn't see meshManager
void on_meshManager_meshSelected(const Mesh&);
};
}
#endif // BALLSWINDOW_HPP
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.