text
stringlengths 54
60.6k
|
---|
<commit_before>#include "client_balancer.hxx"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "pool.hxx"
#include "async.hxx"
#include "balancer.hxx"
#include "failure.hxx"
#include "address_list.hxx"
#include <socket/resolver.h>
#include <socket/util.h>
#include <glib.h>
#include <event.h>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
struct context {
struct balancer *balancer;
enum {
NONE, SUCCESS, TIMEOUT, ERROR,
} result;
SocketDescriptor fd;
GError *error;
};
/*
* client_socket callback
*
*/
static void
my_socket_success(SocketDescriptor &&fd, void *_ctx)
{
struct context *ctx = (struct context *)_ctx;
ctx->result = context::SUCCESS;
ctx->fd = std::move(fd);
balancer_free(ctx->balancer);
}
static void
my_socket_timeout(void *_ctx)
{
struct context *ctx = (struct context *)_ctx;
ctx->result = context::TIMEOUT;
balancer_free(ctx->balancer);
}
static void
my_socket_error(GError *error, void *_ctx)
{
struct context *ctx = (struct context *)_ctx;
ctx->result = context::ERROR;
ctx->error = error;
balancer_free(ctx->balancer);
}
static constexpr ConnectSocketHandler my_socket_handler = {
.success = my_socket_success,
.timeout = my_socket_timeout,
.error = my_socket_error,
};
/*
* main
*
*/
int
main(int argc, char **argv)
{
if (argc <= 1) {
fprintf(stderr, "Usage: run-client-balancer ADDRESS ...\n");
return EXIT_FAILURE;
}
/* initialize */
struct event_base *event_base = event_init();
struct pool *root_pool = pool_new_libc(nullptr, "root");
struct pool *pool = pool_new_linear(root_pool, "test", 8192);
failure_init();
struct context ctx;
ctx.result = context::TIMEOUT;
ctx.balancer = balancer_new(*pool);
AddressList address_list;
address_list.Init();
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
for (int i = 1; i < argc; ++i) {
const char *p = argv[i];
struct addrinfo *ai;
int ret = socket_resolve_host_port(p, 80, &hints, &ai);
if (ret != 0) {
fprintf(stderr, "Failed to resolve '%s': %s\n",
p, gai_strerror(ret));
return EXIT_FAILURE;
}
for (struct addrinfo *j = ai; j != nullptr; j = j->ai_next)
address_list.Add(pool, {ai->ai_addr, ai->ai_addrlen});
freeaddrinfo(ai);
}
/* connect */
struct async_operation_ref async_ref;
client_balancer_connect(pool, ctx.balancer,
false, SocketAddress::Null(),
0, &address_list, 30,
&my_socket_handler, &ctx,
&async_ref);
event_dispatch();
assert(ctx.result != context::NONE);
/* cleanup */
failure_deinit();
pool_unref(pool);
pool_commit();
pool_unref(root_pool);
pool_commit();
pool_recycler_clear();
event_base_free(event_base);
switch (ctx.result) {
case context::NONE:
break;
case context::SUCCESS:
return EXIT_SUCCESS;
case context::TIMEOUT:
fprintf(stderr, "timeout\n");
return EXIT_FAILURE;
case context::ERROR:
fprintf(stderr, "%s\n", ctx.error->message);
g_error_free(ctx.error);
return EXIT_FAILURE;
}
assert(false);
return EXIT_FAILURE;
}
<commit_msg>test/run_client_balancer: rename struct with CamelCase<commit_after>#include "client_balancer.hxx"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "pool.hxx"
#include "async.hxx"
#include "balancer.hxx"
#include "failure.hxx"
#include "address_list.hxx"
#include <socket/resolver.h>
#include <socket/util.h>
#include <glib.h>
#include <event.h>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
struct Context {
struct balancer *balancer;
enum {
NONE, SUCCESS, TIMEOUT, ERROR,
} result = TIMEOUT;
SocketDescriptor fd;
GError *error;
};
/*
* client_socket callback
*
*/
static void
my_socket_success(SocketDescriptor &&fd, void *_ctx)
{
Context *ctx = (Context *)_ctx;
ctx->result = Context::SUCCESS;
ctx->fd = std::move(fd);
balancer_free(ctx->balancer);
}
static void
my_socket_timeout(void *_ctx)
{
Context *ctx = (Context *)_ctx;
ctx->result = Context::TIMEOUT;
balancer_free(ctx->balancer);
}
static void
my_socket_error(GError *error, void *_ctx)
{
Context *ctx = (Context *)_ctx;
ctx->result = Context::ERROR;
ctx->error = error;
balancer_free(ctx->balancer);
}
static constexpr ConnectSocketHandler my_socket_handler = {
.success = my_socket_success,
.timeout = my_socket_timeout,
.error = my_socket_error,
};
/*
* main
*
*/
int
main(int argc, char **argv)
{
if (argc <= 1) {
fprintf(stderr, "Usage: run-client-balancer ADDRESS ...\n");
return EXIT_FAILURE;
}
/* initialize */
struct event_base *event_base = event_init();
struct pool *root_pool = pool_new_libc(nullptr, "root");
struct pool *pool = pool_new_linear(root_pool, "test", 8192);
failure_init();
Context ctx;
ctx.balancer = balancer_new(*pool);
AddressList address_list;
address_list.Init();
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
for (int i = 1; i < argc; ++i) {
const char *p = argv[i];
struct addrinfo *ai;
int ret = socket_resolve_host_port(p, 80, &hints, &ai);
if (ret != 0) {
fprintf(stderr, "Failed to resolve '%s': %s\n",
p, gai_strerror(ret));
return EXIT_FAILURE;
}
for (struct addrinfo *j = ai; j != nullptr; j = j->ai_next)
address_list.Add(pool, {ai->ai_addr, ai->ai_addrlen});
freeaddrinfo(ai);
}
/* connect */
struct async_operation_ref async_ref;
client_balancer_connect(pool, ctx.balancer,
false, SocketAddress::Null(),
0, &address_list, 30,
&my_socket_handler, &ctx,
&async_ref);
event_dispatch();
assert(ctx.result != Context::NONE);
/* cleanup */
failure_deinit();
pool_unref(pool);
pool_commit();
pool_unref(root_pool);
pool_commit();
pool_recycler_clear();
event_base_free(event_base);
switch (ctx.result) {
case Context::NONE:
break;
case Context::SUCCESS:
return EXIT_SUCCESS;
case Context::TIMEOUT:
fprintf(stderr, "timeout\n");
return EXIT_FAILURE;
case Context::ERROR:
fprintf(stderr, "%s\n", ctx.error->message);
g_error_free(ctx.error);
return EXIT_FAILURE;
}
assert(false);
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before><include stdio.h>
<include #stdio.h>
using System;
using userAuth.UITests;
using userAuth.FrameAnchor;
using NUGET.Framework;
project element static[object(slider) {
slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
]]
<commit_msg>Modified file property.cpp<commit_after>
using System;
int a = 100;
if (int a != 600)
{
project element static[object(slider) {
slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
]]
}
<|endoftext|> |
<commit_before>#include "xchainer/python/routines.h"
#include <cstdint>
#include <string>
#include <vector>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/routines/math.h"
#include "xchainer/python/array.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"
namespace xchainer {
namespace python {
namespace internal {
namespace py = pybind11;
namespace {
using xchainer::python::internal::ArrayBodyPtr;
}
void InitXchainerRoutines(pybind11::module& m) {
// creation module functions
m.def("empty",
[](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Empty(ToShape(shape), dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("full",
[](py::tuple shape, Scalar fill_value, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Full(ToShape(shape), fill_value, dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("fill_value"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("full",
[](py::tuple shape, Scalar fill_value, const nonstd::optional<std::string>& device_id) {
return Array::Full(ToShape(shape), fill_value, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("fill_value"),
py::arg("device") = nullptr);
m.def("zeros",
[](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Zeros(ToShape(shape), dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("ones",
[](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Ones(ToShape(shape), dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("empty_like",
[](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
return Array::EmptyLike(Array{a}, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("device") = nullptr);
m.def("full_like",
[](const ArrayBodyPtr& a, Scalar value, const nonstd::optional<std::string>& device_id) {
return Array::FullLike(Array{a}, value, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("fill_value"),
py::arg("device") = nullptr);
m.def("zeros_like",
[](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
return Array::ZerosLike(Array{a}, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("device") = nullptr);
m.def("ones_like",
[](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
return Array::OnesLike(Array{a}, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("device") = nullptr);
m.def("copy", [](const ArrayBodyPtr& a) { return Copy(Array{a}).move_body(); }, py::arg("a"));
// manipulation module functions
m.def("transpose", [](const ArrayBodyPtr& a) { return Transpose(Array{a}).move_body(); }, py::arg("a"));
m.def("reshape",
[](const ArrayBodyPtr& a, py::tuple newshape) { return Reshape(Array{a}, ToShape(newshape)).move_body(); },
py::arg("a"),
py::arg("newshape"));
m.def("reshape",
[](const ArrayBodyPtr& a, const std::vector<int64_t>& newshape) {
return Reshape(Array{a}, {newshape.begin(), newshape.end()}).move_body();
},
py::arg("a"),
py::arg("newshape"));
m.def("broadcast_to",
[](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
py::arg("array"),
py::arg("shape"));
m.def("broadcast_to",
[](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
py::arg("array"),
py::arg("shape"));
// math module functions
m.def("add",
[](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} + Array{x2}).move_body(); },
py::arg("x1"),
py::arg("x2"));
m.def("multiply",
[](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} * Array{x2}).move_body(); },
py::arg("x1"),
py::arg("x2"));
m.def("sum",
[](const ArrayBodyPtr& a, int8_t axis, bool keepdims) { return Sum(Array{a}, std::vector<int8_t>{axis}, keepdims).move_body(); },
py::arg("a"),
py::arg("axis"),
py::arg("keepdims") = false);
m.def("sum",
[](const ArrayBodyPtr& a, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
return Sum(Array{a}, axis, keepdims).move_body();
},
py::arg("a"),
py::arg("axis") = nullptr,
py::arg("keepdims") = false);
}
} // namespace internal
} // namespace python
} // namespace xchainer
<commit_msg>No need of ArrayBodyPtr alias<commit_after>#include "xchainer/python/routines.h"
#include <cstdint>
#include <string>
#include <vector>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/routines/math.h"
#include "xchainer/python/array.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"
namespace xchainer {
namespace python {
namespace internal {
namespace py = pybind11;
void InitXchainerRoutines(pybind11::module& m) {
// creation module functions
m.def("empty",
[](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Empty(ToShape(shape), dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("full",
[](py::tuple shape, Scalar fill_value, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Full(ToShape(shape), fill_value, dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("fill_value"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("full",
[](py::tuple shape, Scalar fill_value, const nonstd::optional<std::string>& device_id) {
return Array::Full(ToShape(shape), fill_value, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("fill_value"),
py::arg("device") = nullptr);
m.def("zeros",
[](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Zeros(ToShape(shape), dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("ones",
[](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
return Array::Ones(ToShape(shape), dtype, GetDevice(device_id)).move_body();
},
py::arg("shape"),
py::arg("dtype"),
py::arg("device") = nullptr);
m.def("empty_like",
[](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
return Array::EmptyLike(Array{a}, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("device") = nullptr);
m.def("full_like",
[](const ArrayBodyPtr& a, Scalar value, const nonstd::optional<std::string>& device_id) {
return Array::FullLike(Array{a}, value, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("fill_value"),
py::arg("device") = nullptr);
m.def("zeros_like",
[](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
return Array::ZerosLike(Array{a}, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("device") = nullptr);
m.def("ones_like",
[](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
return Array::OnesLike(Array{a}, GetDevice(device_id)).move_body();
},
py::arg("a"),
py::arg("device") = nullptr);
m.def("copy", [](const ArrayBodyPtr& a) { return Copy(Array{a}).move_body(); }, py::arg("a"));
// manipulation module functions
m.def("transpose", [](const ArrayBodyPtr& a) { return Transpose(Array{a}).move_body(); }, py::arg("a"));
m.def("reshape",
[](const ArrayBodyPtr& a, py::tuple newshape) { return Reshape(Array{a}, ToShape(newshape)).move_body(); },
py::arg("a"),
py::arg("newshape"));
m.def("reshape",
[](const ArrayBodyPtr& a, const std::vector<int64_t>& newshape) {
return Reshape(Array{a}, {newshape.begin(), newshape.end()}).move_body();
},
py::arg("a"),
py::arg("newshape"));
m.def("broadcast_to",
[](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
py::arg("array"),
py::arg("shape"));
m.def("broadcast_to",
[](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
py::arg("array"),
py::arg("shape"));
// math module functions
m.def("add",
[](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} + Array{x2}).move_body(); },
py::arg("x1"),
py::arg("x2"));
m.def("multiply",
[](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} * Array{x2}).move_body(); },
py::arg("x1"),
py::arg("x2"));
m.def("sum",
[](const ArrayBodyPtr& a, int8_t axis, bool keepdims) { return Sum(Array{a}, std::vector<int8_t>{axis}, keepdims).move_body(); },
py::arg("a"),
py::arg("axis"),
py::arg("keepdims") = false);
m.def("sum",
[](const ArrayBodyPtr& a, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
return Sum(Array{a}, axis, keepdims).move_body();
},
py::arg("a"),
py::arg("axis") = nullptr,
py::arg("keepdims") = false);
}
} // namespace internal
} // namespace python
} // namespace xchainer
<|endoftext|> |
<commit_before>/*
** Author(s):
** - Cedric GESTES <[email protected]>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <gtest/gtest.h>
#include <map>
#include <alcommon-ng/functor/functor.hpp>
#include <alcommon-ng/functor/makefunctor.hpp>
#include <alcommon-ng/tools/dataperftimer.hpp>
static const int gLoopCount = 1000000;
using AL::Messaging::ReturnValue;
using AL::Messaging::ArgumentList;
int fun0() { return 0; }
int fun1(int p0) { return p0; }
int fun2(int p0, int p1) { return p0 + p1; }
int fun3(int p0, int p1, int p2) { return p0 + p1 + p2; }
int fun4(int p0, int p1, int p2, int p3) { return p0 + p1 + p2 + p3; }
int fun5(int p0, int p1, int p2, int p3, int p4) { return p0 + p1 + p2 + p3 + p4; }
int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }
struct Foo {
void voidCall() { return; }
int intStringCall(const std::string &plouf) { return plouf.size(); }
int fun0() { return 0; }
int fun1(int p0) { return p0; }
int fun2(int p0, int p1) { return p0 + p1; }
int fun3(int p0, int p1, int p2) { return p0 + p1 + p2; }
int fun4(int p0, int p1, int p2, int p3) { return p0 + p1 + p2 + p3; }
int fun5(int p0, int p1, int p2, int p3, int p4) { return p0 + p1 + p2 + p3 + p4; }
int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }
};
TEST(TestBind, ArgumentNumber) {
Foo chiche;
//AL::Functor *functor = AL::makeFunctor(&Foo, &Foo::fun0);
//EXPECT_EQ(0, functor->call());
}
TEST(TestBind, VoidCallPerf) {
Foo chiche;
Foo *p = &chiche;
ReturnValue res;
ArgumentList cd;
AL::Test::DataPerfTimer dp;
AL::Functor *functor = AL::makeFunctor(&chiche, &Foo::voidCall);
std::cout << "AL::Functor call" << std::endl;
dp.start(gLoopCount);
for (int i = 0; i < gLoopCount; ++i)
{
functor->call(cd, res);
}
dp.stop();
std::cout << "pointer call" << std::endl;
dp.start(gLoopCount);
for (int i = 0; i < gLoopCount; ++i)
{
p->voidCall();
}
dp.stop();
}
TEST(TestBind, IntStringCallPerf) {
Foo chiche;
Foo *p = &chiche;
ReturnValue res;
AL::Test::DataPerfTimer dp;
std::cout << "AL::Functor call (string with a growing size)" << std::endl;
for (int i = 0; i < 12; ++i)
{
unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
std::string request = std::string(numBytes, 'B');
ArgumentList cd;
AL::Functor *functor = AL::makeFunctor(&chiche, &Foo::intStringCall);
cd.push_back(request);
dp.start(gLoopCount, numBytes);
for (int j = 0; j < gLoopCount; ++j) {
functor->call(cd, res);
}
dp.stop();
}
std::cout << "pointer call (string with a growing size)" << std::endl;
for (int i = 0; i < 12; ++i)
{
unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
std::string request = std::string(numBytes, 'B');
dp.start(gLoopCount, numBytes);
for (int j = 0; j < gLoopCount; ++j) {
p->intStringCall(request);
}
dp.stop();
}
}
<commit_msg>test_bind<commit_after>/*
** Author(s):
** - Cedric GESTES <[email protected]>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <gtest/gtest.h>
#include <map>
#include <alcommon-ng/functor/functor.hpp>
#include <alcommon-ng/functor/makefunctor.hpp>
#include <alcommon-ng/tools/dataperftimer.hpp>
#include <cmath>
static const int gLoopCount = 1000000;
using AL::Messaging::ReturnValue;
using AL::Messaging::ArgumentList;
int fun0() { return 0; }
int fun1(int p0) { return p0; }
int fun2(int p0, int p1) { return p0 + p1; }
int fun3(int p0, int p1, int p2) { return p0 + p1 + p2; }
int fun4(int p0, int p1, int p2, int p3) { return p0 + p1 + p2 + p3; }
int fun5(int p0, int p1, int p2, int p3, int p4) { return p0 + p1 + p2 + p3 + p4; }
int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }
struct Foo {
void voidCall() { return; }
int intStringCall(const std::string &plouf) { return plouf.size(); }
int fun0() { return 0; }
int fun1(int p0) { return p0; }
int fun2(int p0, int p1) { return p0 + p1; }
int fun3(int p0, int p1, int p2) { return p0 + p1 + p2; }
int fun4(int p0, int p1, int p2, int p3) { return p0 + p1 + p2 + p3; }
int fun5(int p0, int p1, int p2, int p3, int p4) { return p0 + p1 + p2 + p3 + p4; }
int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }
};
TEST(TestBind, ArgumentNumber) {
Foo foo;
AL::Functor *functor = AL::makeFunctor(&foo, &Foo::fun0);
//EXPECT_EQ(0, functor->call());
}
TEST(TestBind, VoidCallPerf) {
Foo chiche;
Foo *p = &chiche;
ReturnValue res;
ArgumentList cd;
AL::Test::DataPerfTimer dp;
AL::Functor *functor = AL::makeFunctor(&chiche, &Foo::voidCall);
std::cout << "AL::Functor call" << std::endl;
dp.start(gLoopCount);
for (int i = 0; i < gLoopCount; ++i)
{
functor->call(cd, res);
}
dp.stop();
std::cout << "pointer call" << std::endl;
dp.start(gLoopCount);
for (int i = 0; i < gLoopCount; ++i)
{
p->voidCall();
}
dp.stop();
}
TEST(TestBind, IntStringCallPerf) {
Foo chiche;
Foo *p = &chiche;
ReturnValue res;
AL::Test::DataPerfTimer dp;
std::cout << "AL::Functor call (string with a growing size)" << std::endl;
for (int i = 0; i < 12; ++i)
{
unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
std::string request = std::string(numBytes, 'B');
ArgumentList cd;
AL::Functor *functor = AL::makeFunctor(&chiche, &Foo::intStringCall);
cd.push_back(request);
dp.start(gLoopCount, numBytes);
for (int j = 0; j < gLoopCount; ++j) {
functor->call(cd, res);
}
dp.stop();
}
std::cout << "pointer call (string with a growing size)" << std::endl;
for (int i = 0; i < 12; ++i)
{
unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);
std::string request = std::string(numBytes, 'B');
dp.start(gLoopCount, numBytes);
for (int j = 0; j < gLoopCount; ++j) {
p->intStringCall(request);
}
dp.stop();
}
}
<|endoftext|> |
<commit_before>/*
This file is part of libkdepim.
Copyright (c) 2003 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kconfigwizard.h"
#include <klocale.h>
#include <kdebug.h>
#include <kconfigskeleton.h>
#include <qlistview.h>
#include <qlayout.h>
#include <qtimer.h>
KConfigWizard::KConfigWizard( QWidget *parent,
char *name, bool modal )
: KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
name, modal ),
mPropagator( 0 ), mChangesPage( 0 )
{
init();
}
KConfigWizard::KConfigWizard( KConfigPropagator *propagator, QWidget *parent,
char *name, bool modal )
: KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
name, modal ),
mPropagator( propagator ), mChangesPage( 0 )
{
init();
}
KConfigWizard::~KConfigWizard()
{
delete mPropagator;
}
void KConfigWizard::init()
{
connect( this, SIGNAL( aboutToShowPage( QWidget * ) ),
SLOT( slotAboutToShowPage( QWidget * ) ) );
QTimer::singleShot( 0, this, SLOT( readConfig() ) );
}
void KConfigWizard::setPropagator( KConfigPropagator *p )
{
mPropagator = p;
}
void KConfigWizard::slotAboutToShowPage( QWidget *page )
{
if ( page == mChangesPage ) {
updateChanges();
}
}
QFrame *KConfigWizard::createWizardPage( const QString &title )
{
return addPage( title );
}
void KConfigWizard::setupRulesPage()
{
QFrame *topFrame = addPage( i18n("Rules") );
QVBoxLayout *topLayout = new QVBoxLayout( topFrame );
mRuleView = new QListView( topFrame );
topLayout->addWidget( mRuleView );
mRuleView->addColumn( i18n("Source") );
mRuleView->addColumn( i18n("Target") );
mRuleView->addColumn( i18n("Condition") );
updateRules();
}
void KConfigWizard::updateRules()
{
if ( !mPropagator ) {
kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
return;
}
mRuleView->clear();
KConfigPropagator::Rule::List rules = mPropagator->rules();
KConfigPropagator::Rule::List::ConstIterator it;
for( it = rules.begin(); it != rules.end(); ++it ) {
KConfigPropagator::Rule r = *it;
QString source = r.sourceFile + "/" + r.sourceGroup + "/" +
r.sourceEntry;
QString target = r.targetFile + "/" + r.targetGroup + "/" +
r.targetEntry;
QString condition;
KConfigPropagator::Condition c = r.condition;
if ( c.isValid ) {
condition = c.file + "/" + c.group + "/" + c.key + " = " + c.value;
}
new QListViewItem( mRuleView, source, target, condition );
}
}
void KConfigWizard::setupChangesPage()
{
QFrame *topFrame = addPage( i18n("Changes") );
QVBoxLayout *topLayout = new QVBoxLayout( topFrame );
mChangeView = new QListView( topFrame );
topLayout->addWidget( mChangeView );
mChangeView->addColumn( i18n("Action") );
mChangeView->addColumn( i18n("Option") );
mChangeView->addColumn( i18n("Value") );
mChangesPage = topFrame;
}
void KConfigWizard::updateChanges()
{
kdDebug() << "KConfigWizard::updateChanges()" << endl;
if ( !mPropagator ) {
kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
return;
}
usrWriteConfig();
mPropagator->updateChanges();
mChangeView->clear();
KConfigPropagator::Change::List changes = mPropagator->changes();
KConfigPropagator::Change *c;
for( c = changes.first(); c; c = changes.next() ) {
new QListViewItem( mChangeView, c->title(), c->arg1(), c->arg2() );
}
}
void KConfigWizard::readConfig()
{
kdDebug() << "KConfigWizard::readConfig()" << endl;
usrReadConfig();
}
void KConfigWizard::slotOk()
{
usrWriteConfig();
if ( !mPropagator ) {
kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
return;
} else {
if ( mPropagator->skeleton() ) {
mPropagator->skeleton()->writeConfig();
}
mPropagator->commit();
}
accept();
}
#include "kconfigwizard.moc"
<commit_msg>Add warning about running applications when running the wizard for the first time.<commit_after>/*
This file is part of libkdepim.
Copyright (c) 2003 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kconfigwizard.h"
#include <klocale.h>
#include <kdebug.h>
#include <kconfigskeleton.h>
#include <kmessagebox.h>
#include <kapplication.h>
#include <qlistview.h>
#include <qlayout.h>
#include <qtimer.h>
KConfigWizard::KConfigWizard( QWidget *parent,
char *name, bool modal )
: KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
name, modal ),
mPropagator( 0 ), mChangesPage( 0 )
{
init();
}
KConfigWizard::KConfigWizard( KConfigPropagator *propagator, QWidget *parent,
char *name, bool modal )
: KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
name, modal ),
mPropagator( propagator ), mChangesPage( 0 )
{
init();
}
KConfigWizard::~KConfigWizard()
{
delete mPropagator;
}
void KConfigWizard::init()
{
connect( this, SIGNAL( aboutToShowPage( QWidget * ) ),
SLOT( slotAboutToShowPage( QWidget * ) ) );
QTimer::singleShot( 0, this, SLOT( readConfig() ) );
}
void KConfigWizard::setPropagator( KConfigPropagator *p )
{
mPropagator = p;
}
void KConfigWizard::slotAboutToShowPage( QWidget *page )
{
if ( page == mChangesPage ) {
updateChanges();
}
}
QFrame *KConfigWizard::createWizardPage( const QString &title )
{
return addPage( title );
}
void KConfigWizard::setupRulesPage()
{
QFrame *topFrame = addPage( i18n("Rules") );
QVBoxLayout *topLayout = new QVBoxLayout( topFrame );
mRuleView = new QListView( topFrame );
topLayout->addWidget( mRuleView );
mRuleView->addColumn( i18n("Source") );
mRuleView->addColumn( i18n("Target") );
mRuleView->addColumn( i18n("Condition") );
updateRules();
}
void KConfigWizard::updateRules()
{
if ( !mPropagator ) {
kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
return;
}
mRuleView->clear();
KConfigPropagator::Rule::List rules = mPropagator->rules();
KConfigPropagator::Rule::List::ConstIterator it;
for( it = rules.begin(); it != rules.end(); ++it ) {
KConfigPropagator::Rule r = *it;
QString source = r.sourceFile + "/" + r.sourceGroup + "/" +
r.sourceEntry;
QString target = r.targetFile + "/" + r.targetGroup + "/" +
r.targetEntry;
QString condition;
KConfigPropagator::Condition c = r.condition;
if ( c.isValid ) {
condition = c.file + "/" + c.group + "/" + c.key + " = " + c.value;
}
new QListViewItem( mRuleView, source, target, condition );
}
}
void KConfigWizard::setupChangesPage()
{
QFrame *topFrame = addPage( i18n("Changes") );
QVBoxLayout *topLayout = new QVBoxLayout( topFrame );
mChangeView = new QListView( topFrame );
topLayout->addWidget( mChangeView );
mChangeView->addColumn( i18n("Action") );
mChangeView->addColumn( i18n("Option") );
mChangeView->addColumn( i18n("Value") );
mChangesPage = topFrame;
}
void KConfigWizard::updateChanges()
{
kdDebug() << "KConfigWizard::updateChanges()" << endl;
if ( !mPropagator ) {
kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
return;
}
usrWriteConfig();
mPropagator->updateChanges();
mChangeView->clear();
KConfigPropagator::Change::List changes = mPropagator->changes();
KConfigPropagator::Change *c;
for( c = changes.first(); c; c = changes.next() ) {
new QListViewItem( mChangeView, c->title(), c->arg1(), c->arg2() );
}
}
void KConfigWizard::readConfig()
{
kdDebug() << "KConfigWizard::readConfig()" << endl;
int result = KMessageBox::warningContinueCancel( this,
i18n("Please make sure that the programs which are "
"configured by the wizard don't run in parallel to the wizard. "
"Otherwise changes done by the wizard could be lost."),
i18n("Warning"), i18n("Run wizard now"), "warning_running_instances" );
if ( result != KMessageBox::Continue ) kapp->quit();
usrReadConfig();
}
void KConfigWizard::slotOk()
{
usrWriteConfig();
if ( !mPropagator ) {
kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
return;
} else {
if ( mPropagator->skeleton() ) {
mPropagator->skeleton()->writeConfig();
}
mPropagator->commit();
}
accept();
}
#include "kconfigwizard.moc"
<|endoftext|> |
<commit_before>#include "catch.hpp"
// mapnik vector tile tile class
#include "vector_tile_tile.hpp"
TEST_CASE("Vector tile base class")
{
mapnik::box2d<double> global_extent(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);
SECTION("default constructed")
{
mapnik::vector_tile_impl::tile default_tile(global_extent);
CHECK(default_tile.size() == 0);
CHECK(default_tile.data()[0] == '\0');
CHECK(std::abs(default_tile.scale() - 9783.9396205024) < 0.00001);
std::string str;
default_tile.serialize_to_string(str);
CHECK(str == "");
CHECK(default_tile.is_painted() == false);
CHECK(default_tile.is_empty() == true);
CHECK(default_tile.extent() == global_extent);
CHECK(default_tile.get_buffered_extent() == global_extent);
CHECK(default_tile.tile_size() == 4096);
CHECK(default_tile.get_painted_layers().empty() == true);
CHECK(default_tile.get_empty_layers().empty() == true);
CHECK(default_tile.get_layers().empty() == true);
CHECK(default_tile.get_layers_set().empty() == true);
CHECK(default_tile.has_layer("anything") == false);
vector_tile::Tile t;
t = default_tile.get_tile();
CHECK(t.layers_size() == 0);
}
}
<commit_msg>Add more edge case constructions<commit_after>#include "catch.hpp"
// mapnik vector tile tile class
#include "vector_tile_tile.hpp"
TEST_CASE("Vector tile base class")
{
mapnik::box2d<double> global_extent(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);
SECTION("default constructed")
{
mapnik::vector_tile_impl::tile default_tile(global_extent);
CHECK(default_tile.size() == 0);
CHECK(default_tile.data()[0] == '\0');
CHECK(std::abs(default_tile.scale() - 9783.9396205024) < 0.00001);
std::string str;
default_tile.serialize_to_string(str);
CHECK(str == "");
CHECK(default_tile.is_painted() == false);
CHECK(default_tile.is_empty() == true);
CHECK(default_tile.extent() == global_extent);
CHECK(default_tile.get_buffered_extent() == global_extent);
CHECK(default_tile.tile_size() == 4096);
CHECK(default_tile.get_painted_layers().empty() == true);
CHECK(default_tile.get_empty_layers().empty() == true);
CHECK(default_tile.get_layers().empty() == true);
CHECK(default_tile.get_layers_set().empty() == true);
CHECK(default_tile.has_layer("anything") == false);
vector_tile::Tile t;
t = default_tile.get_tile();
CHECK(t.layers_size() == 0);
}
SECTION("construction with zero tile_size")
{
mapnik::vector_tile_impl::tile zero_size_tile(global_extent, 0);
CHECK(zero_size_tile.tile_size() == 0);
CHECK(std::abs(zero_size_tile.scale() - 40075016.6855780035) < 0.00001);
CHECK(zero_size_tile.get_buffered_extent() == global_extent);
}
SECTION("construction with negative tile_size")
{
mapnik::vector_tile_impl::tile negative_size_tile(global_extent, -1);
CHECK(negative_size_tile.tile_size() == 4294967295);
CHECK(std::abs(negative_size_tile.scale() - 0.0093306919) < 0.0000001);
CHECK(negative_size_tile.get_buffered_extent() == global_extent);
}
SECTION("construction with positive buffer size")
{
mapnik::vector_tile_impl::tile positive_buffer_tile(global_extent, 4096, 10);
mapnik::box2d<double> buffered_extent(-20135347.7389940246939659,-20135347.7389940246939659,20135347.7389940246939659,20135347.7389940246939659);
CHECK(positive_buffer_tile.get_buffered_extent() == buffered_extent);
CHECK(positive_buffer_tile.buffer_size() == 10);
}
SECTION("construction with very negative buffer size")
{
mapnik::vector_tile_impl::tile negative_buffer_tile(global_extent, 4096, -4000);
mapnik::box2d<double> buffered_extent(0.0, 0.0, 0.0, 0.0);
CHECK(negative_buffer_tile.get_buffered_extent() == buffered_extent);
CHECK(negative_buffer_tile.buffer_size() == -4000);
}
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <cstdint>
#include "memory_arena.hpp"
struct alignas(32) SomeType {
int64_t x;
int64_t y;
int64_t z;
};
// Make sure that subsequent allocations that should fit into a single
// chunk are actually allocated sequentially.
TEST_CASE("Sequential memory addresses", "[memory_arena]")
{
MemoryArena<16> arena;
int32_t* a = arena.alloc<int32_t>();
int32_t* b = arena.alloc<int32_t>();
int32_t* c = arena.alloc<int32_t>();
int32_t* d = arena.alloc<int32_t>();
REQUIRE((a+1) == b);
REQUIRE((a+2) == c);
REQUIRE((a+3) == d);
}
// Make sure that types are allocated with proper memory alignment
TEST_CASE("Memory alignment requirements", "[memory_arena]")
{
MemoryArena<128> arena;
arena.alloc<char>();
uintptr_t a = (uintptr_t)(arena.alloc<SomeType>());
uintptr_t b = (uintptr_t)(arena.alloc<SomeType>());
arena.alloc<char>();
arena.alloc<char>();
arena.alloc<char>();
uintptr_t c = (uintptr_t)(arena.alloc<SomeType>());
REQUIRE((a % alignof(SomeType)) == 0);
REQUIRE((b % alignof(SomeType)) == 0);
REQUIRE((c % alignof(SomeType)) == 0);
}<commit_msg>Added more unit tests for MemoryArena.<commit_after>#include "catch.hpp"
#include <cstdint>
#include <vector>
#include <list>
#include "slice.hpp"
#include "memory_arena.hpp"
struct alignas(32) SomeType {
int64_t x;
int64_t y;
int64_t z;
};
// Make sure that subsequent allocations that should fit into a single
// chunk are actually allocated sequentially.
TEST_CASE("Sequential memory addresses", "[memory_arena]")
{
MemoryArena<16> arena;
int32_t* a = arena.alloc<int32_t>();
int32_t* b = arena.alloc<int32_t>();
int32_t* c = arena.alloc<int32_t>();
int32_t* d = arena.alloc<int32_t>();
REQUIRE((a+1) == b);
REQUIRE((a+2) == c);
REQUIRE((a+3) == d);
}
// Make sure alloc() initializes things properly if given a value
TEST_CASE("alloc() init", "[memory_arena]")
{
MemoryArena<> arena;
int32_t* a = arena.alloc<int32_t>(42);
int32_t* b = arena.alloc<int32_t>(64);
REQUIRE((*a) == 42);
REQUIRE((*b) == 64);
}
// Make sure alloc_array() creates a slice of the appropriate length
TEST_CASE("alloc_from_array() length", "[memory_arena]")
{
MemoryArena<> arena;
Slice<int32_t> s = arena.alloc_array<int32_t>(123);
REQUIRE(s.size() == 123);
}
// Make sure alloc_from_iters() initializes things properly
TEST_CASE("alloc_from_iters() init", "[memory_arena]")
{
MemoryArena<64> arena;
std::vector<int32_t> v {1, 0, 2, 9, 3, 8, 4, 7, 5, 6};
std::list<int32_t> l {1, 0, 2, 9, 3, 8, 4, 7, 5, 6};
Slice<int32_t> s1 = arena.alloc_from_iters(v.begin(), v.end());
Slice<int32_t> s2 = arena.alloc_from_iters(l.begin(), l.end());
REQUIRE(v.size() == s1.size());
REQUIRE(l.size() == s2.size());
auto i1 = v.begin();
auto i2 = l.begin();
auto i3 = s1.begin();
auto i4 = s2.begin();
for (size_t i = 0; i < s1.size(); ++i) {
REQUIRE((*i1) == (*i3));
REQUIRE((*i2) == (*i4));
++i1;
++i2;
++i3;
++i4;
}
}
// Make sure that types are allocated with proper memory alignment
TEST_CASE("Memory alignment requirements", "[memory_arena]")
{
MemoryArena<128> arena;
arena.alloc<char>();
uintptr_t a = (uintptr_t)(arena.alloc<SomeType>());
uintptr_t b = (uintptr_t)(arena.alloc<SomeType>());
arena.alloc<char>();
arena.alloc<char>();
arena.alloc<char>();
uintptr_t c = (uintptr_t)(arena.alloc<SomeType>());
REQUIRE((a % alignof(SomeType)) == 0);
REQUIRE((b % alignof(SomeType)) == 0);
REQUIRE((c % alignof(SomeType)) == 0);
}<|endoftext|> |
<commit_before>// Catch
#include <catch.hpp>
#include <helper.hpp>
// Mantella
#include <mantella>
TEST_CASE("quasiRandomSequence: getHaltonSequence", "") {
arma::Mat<double>::fixed<2, 5> expected;
expected = {
0.0, 0.0,
1.0/2.0, 1.0/3.0,
1.0/4.0, 2.0/3.0,
3.0/4.0, 1.0/9.0,
1.0/8.0, 4.0/9.0,
};
compare(mant::getHaltonSequence({2, 3}, {0, 0}, 5), expected);
expected = {
3.0/4.0, 1.0/9.0,
1.0/8.0, 4.0/9.0,
5.0/8.0, 7.0/9.0,
3.0/8.0, 2.0/9.0,
7.0/8.0, 5.0/9.0,
};
compare(mant::getHaltonSequence({2, 3}, {3, 3}, 5), expected);
CHECK_THROWS_AS(mant::getHaltonSequence({1}, {3, 3}, 5), std::logic_error);
CHECK_THROWS_AS(mant::getHaltonSequence({4, 5}, {3}, 6), std::logic_error);
}
TEST_CASE("quasiRandomSequence: getVanDerCorputSequence", "") {
compare(mant::getVanDerCorputSequence(2, 0, 5), {0.0, 1.0/2.0, 1.0/4.0, 3.0/4.0, 1.0/8.0});
compare(mant::getVanDerCorputSequence(3, 3, 5), {1.0/9.0, 4.0/9.0, 7.0/9.0, 2.0/9.0, 5.0/9.0});
}
<commit_msg>test: Reorganised quasiRandomSequence.hpp test cases<commit_after>// Catch
#include <catch.hpp>
#include <helper.hpp>
// Mantella
#include <mantella>
TEST_CASE("quasiRandomSequence: getHaltonSequence(...)", "") {
arma::Mat<double>::fixed<2, 5> expected;
expected = {
0.0, 0.0,
1.0/2.0, 1.0/3.0,
1.0/4.0, 2.0/3.0,
3.0/4.0, 1.0/9.0,
1.0/8.0, 4.0/9.0,
};
compare(mant::getHaltonSequence({2, 3}, {0, 0}, 5), expected);
expected = {
3.0/4.0, 1.0/9.0,
1.0/8.0, 4.0/9.0,
5.0/8.0, 7.0/9.0,
3.0/8.0, 2.0/9.0,
7.0/8.0, 5.0/9.0,
};
compare(mant::getHaltonSequence({2, 3}, {3, 3}, 5), expected);
CHECK_THROWS_AS(mant::getHaltonSequence({1}, {3, 3}, 5), std::logic_error);
CHECK_THROWS_AS(mant::getHaltonSequence({4, 5}, {3}, 6), std::logic_error);
}
TEST_CASE("quasiRandomSequence: getVanDerCorputSequence(...)", "") {
compare(mant::getVanDerCorputSequence(2, 0, 5), {0.0, 1.0/2.0, 1.0/4.0, 3.0/4.0, 1.0/8.0});
compare(mant::getVanDerCorputSequence(3, 3, 5), {1.0/9.0, 4.0/9.0, 7.0/9.0, 2.0/9.0, 5.0/9.0});
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// decimal_functions_sql_test.cpp
//
// Identification: test/sql/decimal_functions_sql_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "sql/testing_sql_util.h"
#include "catalog/catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"
namespace peloton {
namespace test {
class DecimalFunctionsSQLTest : public PelotonTest {};
TEST_F(DecimalFunctionsSQLTest, FloorTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
catalog::Catalog::GetInstance()->Bootstrap();
txn_manager.CommitTransaction(txn);
// Create a t
txn = txn_manager.BeginTransaction();
TestingSQLUtil::ExecuteSQLQuery(
"CREATE TABLE foo(id integer, income decimal);");
// Adding in 2500 random decimal inputs between [-500, 500]
int i;
std::vector<double> inputs;
int lo = -500;
int hi = 500;
int numEntries = 500;
// Setting a seed
std::srand(std::time(0));
for (i = 0; i < numEntries; i++) {
double num = 0.45 + (std::rand() % (hi - lo));
inputs.push_back(num);
std::ostringstream os;
os << "insert into foo values(" << i << ", " << num << ");";
TestingSQLUtil::ExecuteSQLQuery(os.str());
}
EXPECT_EQ(i, numEntries);
txn_manager.CommitTransaction(txn);
// Fetch values from the table
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
std::string testQuery = "select id, floor(income) from foo;";
TestingSQLUtil::ExecuteSQLQuery(testQuery.c_str(), result, tuple_descriptor,
rows_affected, error_message);
for (i = 0; i < numEntries; i++) {
std::string result_id(
TestingSQLUtil::GetResultValueAsString(result, (2 * i)));
std::string result_income(
TestingSQLUtil::GetResultValueAsString(result, (2 * i) + 1));
int id = std::stoi(result_id);
double income = std::stod(result_income);
EXPECT_EQ(id, i);
EXPECT_DOUBLE_EQ(income, floor(inputs[i]));
}
// free the database just created
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} // namespace test
} // namespace peloton
<commit_msg>Added EndTransaction<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// decimal_functions_sql_test.cpp
//
// Identification: test/sql/decimal_functions_sql_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "sql/testing_sql_util.h"
#include "catalog/catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"
namespace peloton {
namespace test {
class DecimalFunctionsSQLTest : public PelotonTest {};
TEST_F(DecimalFunctionsSQLTest, FloorTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
catalog::Catalog::GetInstance()->Bootstrap();
txn_manager.CommitTransaction(txn);
// Create a t
txn = txn_manager.BeginTransaction();
TestingSQLUtil::ExecuteSQLQuery(
"CREATE TABLE foo(id integer, income decimal);");
// Adding in 2500 random decimal inputs between [-500, 500]
int i;
std::vector<double> inputs;
int lo = -500;
int hi = 500;
int numEntries = 500;
// Setting a seed
std::srand(std::time(0));
for (i = 0; i < numEntries; i++) {
double num = 0.45 + (std::rand() % (hi - lo));
inputs.push_back(num);
std::ostringstream os;
os << "insert into foo values(" << i << ", " << num << ");";
TestingSQLUtil::ExecuteSQLQuery(os.str());
}
EXPECT_EQ(i, numEntries);
txn_manager.CommitTransaction(txn);
// Fetch values from the table
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
std::string testQuery = "select id, floor(income) from foo;";
TestingSQLUtil::ExecuteSQLQuery(testQuery.c_str(), result, tuple_descriptor,
rows_affected, error_message);
for (i = 0; i < numEntries; i++) {
std::string result_id(
TestingSQLUtil::GetResultValueAsString(result, (2 * i)));
std::string result_income(
TestingSQLUtil::GetResultValueAsString(result, (2 * i) + 1));
int id = std::stoi(result_id);
double income = std::stod(result_income);
EXPECT_EQ(id, i);
EXPECT_DOUBLE_EQ(income, floor(inputs[i]));
}
// free the database just created
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
txn = txn_manager.EndTransaction();
}
} // namespace test
} // namespace peloton
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#define MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#include <mjolnir/math/Vector.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/LocalInteractionBase.hpp>
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <type_traits>
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
namespace mjolnir
{
namespace test
{
template<typename traitsT, typename Interaction>
typename std::enable_if<
std::is_base_of< LocalInteractionBase<traitsT>, Interaction>::value ||
std::is_base_of<GlobalInteractionBase<traitsT>, Interaction>::value>::type
check_virial_in_force_energy_virial(System<traitsT> ref,
const Interaction& interaction,
const typename traitsT::real_type tol)
{
using coordinate_type = typename traitsT::coordinate_type;
using matrix33_type = typename traitsT::matrix33_type;
for(std::size_t i=0; i<ref.size(); ++i)
{
ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
}
ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);
System<traitsT> sys(ref);
// ------------------------------------------------------------------------
// check virial calculated in calc_force_and_energy
sys.preprocess_forces();
interaction.calc_force_and_energy(sys);
sys.postprocess_forces();
ref.preprocess_forces();
interaction.calc_force_and_virial(ref);
ref.postprocess_forces();
for(std::size_t i=0; i<9; ++i)
{
BOOST_TEST(sys.virial()[i] == ref.virial()[i], boost::test_tools::tolerance(tol));
}
return;
}
template<typename traitsT, typename Interaction>
typename std::enable_if<
! std::is_base_of< LocalInteractionBase<traitsT>, Interaction>::value &&
! std::is_base_of<GlobalInteractionBase<traitsT>, Interaction>::value>::type
check_virial_in_force_energy_virial(System<traitsT>,
const Interaction&,
const typename traitsT::real_type)
{
// ------------------------------------------------------------------------
// does not have virial.
return;
}
// This checks the consistency between `calc_force` and `calc_force_and_energy`.
template<typename traitsT, typename Interaction>
void check_force_energy_virial(System<traitsT> ref,
const Interaction& interaction,
const typename traitsT::real_type tol)
{
using coordinate_type = typename traitsT::coordinate_type;
using matrix33_type = typename traitsT::matrix33_type;
for(std::size_t i=0; i<ref.size(); ++i)
{
ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
}
ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);
System<traitsT> sys(ref);
ref.preprocess_forces();
interaction.calc_force(ref);
ref.postprocess_forces();
const auto ref_ene = interaction.calc_energy(ref);
sys.preprocess_forces();
const auto ene = interaction.calc_force_and_energy(sys);
sys.postprocess_forces();
BOOST_TEST(ref_ene == ene, boost::test_tools::tolerance(tol));
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
BOOST_TEST(math::X(sys.force(idx)) == math::X(ref.force(idx)), boost::test_tools::tolerance(tol));
BOOST_TEST(math::Y(sys.force(idx)) == math::Y(ref.force(idx)), boost::test_tools::tolerance(tol));
BOOST_TEST(math::Z(sys.force(idx)) == math::Z(ref.force(idx)), boost::test_tools::tolerance(tol));
}
check_virial_in_force_energy_virial(sys, interaction, tol);
return;
}
} // test
} // mjolnir
#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP
<commit_msg>fix: calc virial properly in force_energy_virial<commit_after>#ifndef MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#define MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#include <mjolnir/math/Vector.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/LocalInteractionBase.hpp>
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <type_traits>
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
namespace mjolnir
{
namespace test
{
// This checks the consistency between `calc_force` and `calc_force_and_energy`.
template<typename traitsT, typename Interaction>
void check_force_energy_virial(System<traitsT> ref,
const Interaction& interaction,
const typename traitsT::real_type tol)
{
using coordinate_type = typename traitsT::coordinate_type;
using matrix33_type = typename traitsT::matrix33_type;
for(std::size_t i=0; i<ref.size(); ++i)
{
ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
}
ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);
System<traitsT> sys(ref);
ref.preprocess_forces();
interaction.calc_force(ref);
ref.postprocess_forces();
const auto ref_ene = interaction.calc_energy(ref);
sys.preprocess_forces();
const auto ene = interaction.calc_force_virial_energy(sys);
sys.postprocess_forces();
BOOST_TEST(ref_ene == ene, boost::test_tools::tolerance(tol));
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
BOOST_TEST(math::X(sys.force(idx)) == math::X(ref.force(idx)), boost::test_tools::tolerance(tol));
BOOST_TEST(math::Y(sys.force(idx)) == math::Y(ref.force(idx)), boost::test_tools::tolerance(tol));
BOOST_TEST(math::Z(sys.force(idx)) == math::Z(ref.force(idx)), boost::test_tools::tolerance(tol));
}
// external forcefield does not support virial because they depends absolute
// coordinate
if(std::is_base_of< LocalInteractionBase<traitsT>, Interaction>::value ||
std::is_base_of<GlobalInteractionBase<traitsT>, Interaction>::value)
{
for(std::size_t i=0; i<ref.size(); ++i)
{
ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
}
ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);
// calc virial
interaction.calc_force_and_virial(ref);
// compare ref virial with calc_force_energy_virial
for(std::size_t i=0; i<9; ++i)
{
BOOST_TEST(sys.virial()[i] == ref.virial()[i], boost::test_tools::tolerance(tol));
}
}
return;
}
} // test
} // mjolnir
#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP
<|endoftext|> |
<commit_before>#include <itkImageRegionConstIterator.h>
#include <itkPasteImageFilter.h>
#include "rtkTestConfiguration.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
#if !(FAST_TESTS_NO_CHECKS)
typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
ImageIteratorType itRef( ref, ref->GetBufferedRegion() );
typedef double ErrorType;
ErrorType TestError = 0.;
ErrorType EnerError = 0.;
itTest.GoToBegin();
itRef.GoToBegin();
while( !itRef.IsAtEnd() )
{
typename TImage::PixelType TestVal = itTest.Get();
typename TImage::PixelType RefVal = itRef.Get();
TestError += vcl_abs(RefVal - TestVal);
EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
++itTest;
++itRef;
}
// Error per Pixel
ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
// MSE
ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "MSE = " << MSE << std::endl;
// PSNR
ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
std::cout << "PSNR = " << PSNR << "dB" << std::endl;
// QI
ErrorType QI = (2.0-ErrorPerPixel)/2.0;
std::cout << "QI = " << QI << std::endl;
// Checking results
if (ErrorPerPixel > 0.05)
{
std::cerr << "Test Failed, Error per pixel not valid! "
<< ErrorPerPixel << " instead of 0.05." << std::endl;
exit( EXIT_FAILURE);
}
if (PSNR < 22.)
{
std::cerr << "Test Failed, PSNR not valid! "
<< PSNR << " instead of 23" << std::endl;
exit( EXIT_FAILURE);
}
#endif
}
int main(int, char** )
{
const unsigned int Dimension = 3;
typedef float OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#if FAST_TESTS_NO_CHECKS
const unsigned int NumberOfProjectionImages = 3;
#else
const unsigned int NumberOfProjectionImages = 128;
#endif
// Constant image sources
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::PointType origin;
ConstantImageSourceType::SizeType size;
ConstantImageSourceType::SpacingType spacing;
ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();
origin[0] = -63.;
origin[1] = -31.;
origin[2] = -63.;
#if FAST_TESTS_NO_CHECKS
size[0] = 32;
size[1] = 32;
size[2] = 32;
spacing[0] = 8.;
spacing[1] = 8.;
spacing[2] = 8.;
#else
size[0] = 64;
size[1] = 32;
size[2] = 64;
spacing[0] = 2.;
spacing[1] = 2.;
spacing[2] = 2.;
#endif
tomographySource->SetOrigin( origin );
tomographySource->SetSpacing( spacing );
tomographySource->SetSize( size );
tomographySource->SetConstant( 0. );
ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
origin[0] = -254.;
origin[1] = -254.;
origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
size[0] = 32;
size[1] = 32;
size[2] = NumberOfProjectionImages;
spacing[0] = 32.;
spacing[1] = 32.;
spacing[2] = 32.;
#else
size[0] = 128;
size[1] = 128;
size[2] = NumberOfProjectionImages;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
#endif
projectionsSource->SetOrigin( origin );
projectionsSource->SetSpacing( spacing );
projectionsSource->SetSize( size );
projectionsSource->SetConstant( 0. );
ConstantImageSourceType::Pointer oneProjectionSource = ConstantImageSourceType::New();
size[2] = 1;
oneProjectionSource->SetOrigin( origin );
oneProjectionSource->SetSpacing( spacing );
oneProjectionSource->SetSize( size );
oneProjectionSource->SetConstant( 0. );
// Geometry object
typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
GeometryType::Pointer geometry = GeometryType::New();
// Projections
typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
typedef itk::PasteImageFilter <OutputImageType, OutputImageType, OutputImageType > PasteImageFilterType;
OutputImageType::IndexType destinationIndex;
destinationIndex[0] = 0;
destinationIndex[1] = 0;
destinationIndex[2] = 0;
PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();
std::ofstream signalFile("signal.txt");
OutputImageType::Pointer wholeImage = projectionsSource->GetOutput();
for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
{
geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Geometry object
GeometryType::Pointer oneProjGeometry = GeometryType::New();
oneProjGeometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Ellipse 1
REIType::Pointer e1 = REIType::New();
e1->SetInput(oneProjectionSource->GetOutput());
e1->SetGeometry(oneProjGeometry);
e1->SetMultiplicativeConstant(2.);
e1->SetSemiPrincipalAxisX(60.);
e1->SetSemiPrincipalAxisY(60.);
e1->SetSemiPrincipalAxisZ(60.);
e1->SetCenterX(0.);
e1->SetCenterY(0.);
e1->SetCenterZ(0.);
e1->SetRotationAngle(0.);
e1->InPlaceOff();
e1->Update();
// Ellipse 2
REIType::Pointer e2 = REIType::New();
e2->SetInput(e1->GetOutput());
e2->SetGeometry(oneProjGeometry);
e2->SetMultiplicativeConstant(-1.);
e2->SetSemiPrincipalAxisX(8.);
e2->SetSemiPrincipalAxisY(8.);
e2->SetSemiPrincipalAxisZ(8.);
e2->SetCenterX( 4*(vcl_abs( (4+noProj) % 8 - 4.) - 2.) );
e2->SetCenterY(0.);
e2->SetCenterZ(0.);
e2->SetRotationAngle(0.);
e2->Update();
// Adding each projection to volume
pasteFilter->SetSourceImage(e2->GetOutput());
pasteFilter->SetDestinationImage(wholeImage);
pasteFilter->SetSourceRegion(e2->GetOutput()->GetLargestPossibleRegion());
pasteFilter->SetDestinationIndex(destinationIndex);
pasteFilter->Update();
wholeImage = pasteFilter->GetOutput();
destinationIndex[2]++;
// Signal
signalFile << (noProj % 8) / 8. << std::endl;
}
// Create vector field
typedef itk::Vector<float,3> DVFPixelType;
typedef itk::Image< DVFPixelType, 3 > DVFImageType;
typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;
typedef itk::ImageRegionIteratorWithIndex< DeformationType::InputImageType > IteratorType;
DeformationType::InputImageType::Pointer deformationField;
deformationField = DeformationType::InputImageType::New();
DeformationType::InputImageType::IndexType startMotion;
startMotion[0] = 0; // first index on X
startMotion[1] = 0; // first index on Y
startMotion[2] = 0; // first index on Z
startMotion[3] = 0; // first index on t
DeformationType::InputImageType::SizeType sizeMotion;
sizeMotion[0] = 64; // size along X
sizeMotion[1] = 64; // size along Y
sizeMotion[2] = 64; // size along Z
sizeMotion[3] = 2; // size along t
DeformationType::InputImageType::PointType originMotion;
originMotion[0] = (sizeMotion[0]-1)*(-0.5); // size along X
originMotion[1] = (sizeMotion[1]-1)*(-0.5); // size along Y
originMotion[2] = (sizeMotion[2]-1)*(-0.5); // size along Z
originMotion[3] = 0.;
DeformationType::InputImageType::RegionType regionMotion;
regionMotion.SetSize( sizeMotion );
regionMotion.SetIndex( startMotion );
deformationField->SetRegions( regionMotion );
deformationField->SetOrigin(originMotion);
deformationField->Allocate();
// Vector Field initilization
DVFPixelType vec;
vec.Fill(0.);
IteratorType inputIt( deformationField, deformationField->GetLargestPossibleRegion() );
for ( inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt)
{
if(inputIt.GetIndex()[3]==0)
vec[0] = -8.;
else
vec[0] = 8.;
inputIt.Set(vec);
}
// Create cyclic deformation
DeformationType::Pointer def = DeformationType::New();
def->SetInput(deformationField);
typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
WarpBPType::Pointer bp = WarpBPType::New();
bp->SetDeformation(def);
bp->SetGeometry( geometry.GetPointer() );
// FDK reconstruction filtering
#ifdef USE_CUDA
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKType;
#elif USE_OPENCL
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKType;
#else
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
FDKType::Pointer feldkamp = FDKType::New();
feldkamp->SetInput( 0, tomographySource->GetOutput() );
feldkamp->SetInput( 1, wholeImage );
feldkamp->SetGeometry( geometry );
def->SetSignalFilename("signal.txt");
feldkamp.GetPointer()->SetBackProjectionFilter( bp.GetPointer() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() );
// FOV
typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
FOVFilterType::Pointer fov=FOVFilterType::New();
fov->SetInput(0, feldkamp->GetOutput());
fov->SetProjectionsStack( wholeImage.GetPointer() );
fov->SetGeometry( geometry );
TRY_AND_EXIT_ON_ITK_EXCEPTION( fov->Update() );
// Create a reference object (in this case a 3D phantom reference).
// Ellipse 1
typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
DEType::Pointer e1 = DEType::New();
e1->SetInput( tomographySource->GetOutput() );
e1->SetAttenuation(2.);
DEType::VectorType axis(3, 60.);
e1->SetAxis(axis);
DEType::VectorType center(3, 0.);
e1->SetCenter(center);
e1->SetAngle(0.);
e1->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( e1->Update() )
// Ellipse 2
DEType::Pointer e2 = DEType::New();
e2->SetInput(e1->GetOutput());
e2->SetAttenuation(-1.);
DEType::VectorType axis2(3, 8.);
e2->SetAxis(axis2);
DEType::VectorType center2(3, 0.);
e2->SetCenter(center2);
e2->SetAngle(0.);
e2->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( e2->Update() )
CheckImageQuality<OutputImageType>(fov->GetOutput(), e2->GetOutput());
std::cout << "Test PASSED! " << std::endl;
itksys::SystemTools::RemoveFile("signal.txt");
return EXIT_SUCCESS;
}
<commit_msg>Added missing include<commit_after>#include <itkImageRegionConstIterator.h>
#include <itkPasteImageFilter.h>
#include <itksys/SystemTools.hxx>
#include "rtkTestConfiguration.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
#if !(FAST_TESTS_NO_CHECKS)
typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
ImageIteratorType itRef( ref, ref->GetBufferedRegion() );
typedef double ErrorType;
ErrorType TestError = 0.;
ErrorType EnerError = 0.;
itTest.GoToBegin();
itRef.GoToBegin();
while( !itRef.IsAtEnd() )
{
typename TImage::PixelType TestVal = itTest.Get();
typename TImage::PixelType RefVal = itRef.Get();
TestError += vcl_abs(RefVal - TestVal);
EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
++itTest;
++itRef;
}
// Error per Pixel
ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
// MSE
ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
std::cout << "MSE = " << MSE << std::endl;
// PSNR
ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
std::cout << "PSNR = " << PSNR << "dB" << std::endl;
// QI
ErrorType QI = (2.0-ErrorPerPixel)/2.0;
std::cout << "QI = " << QI << std::endl;
// Checking results
if (ErrorPerPixel > 0.05)
{
std::cerr << "Test Failed, Error per pixel not valid! "
<< ErrorPerPixel << " instead of 0.05." << std::endl;
exit( EXIT_FAILURE);
}
if (PSNR < 22.)
{
std::cerr << "Test Failed, PSNR not valid! "
<< PSNR << " instead of 23" << std::endl;
exit( EXIT_FAILURE);
}
#endif
}
int main(int, char** )
{
const unsigned int Dimension = 3;
typedef float OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#if FAST_TESTS_NO_CHECKS
const unsigned int NumberOfProjectionImages = 3;
#else
const unsigned int NumberOfProjectionImages = 128;
#endif
// Constant image sources
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::PointType origin;
ConstantImageSourceType::SizeType size;
ConstantImageSourceType::SpacingType spacing;
ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();
origin[0] = -63.;
origin[1] = -31.;
origin[2] = -63.;
#if FAST_TESTS_NO_CHECKS
size[0] = 32;
size[1] = 32;
size[2] = 32;
spacing[0] = 8.;
spacing[1] = 8.;
spacing[2] = 8.;
#else
size[0] = 64;
size[1] = 32;
size[2] = 64;
spacing[0] = 2.;
spacing[1] = 2.;
spacing[2] = 2.;
#endif
tomographySource->SetOrigin( origin );
tomographySource->SetSpacing( spacing );
tomographySource->SetSize( size );
tomographySource->SetConstant( 0. );
ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
origin[0] = -254.;
origin[1] = -254.;
origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
size[0] = 32;
size[1] = 32;
size[2] = NumberOfProjectionImages;
spacing[0] = 32.;
spacing[1] = 32.;
spacing[2] = 32.;
#else
size[0] = 128;
size[1] = 128;
size[2] = NumberOfProjectionImages;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
#endif
projectionsSource->SetOrigin( origin );
projectionsSource->SetSpacing( spacing );
projectionsSource->SetSize( size );
projectionsSource->SetConstant( 0. );
ConstantImageSourceType::Pointer oneProjectionSource = ConstantImageSourceType::New();
size[2] = 1;
oneProjectionSource->SetOrigin( origin );
oneProjectionSource->SetSpacing( spacing );
oneProjectionSource->SetSize( size );
oneProjectionSource->SetConstant( 0. );
// Geometry object
typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
GeometryType::Pointer geometry = GeometryType::New();
// Projections
typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
typedef itk::PasteImageFilter <OutputImageType, OutputImageType, OutputImageType > PasteImageFilterType;
OutputImageType::IndexType destinationIndex;
destinationIndex[0] = 0;
destinationIndex[1] = 0;
destinationIndex[2] = 0;
PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();
std::ofstream signalFile("signal.txt");
OutputImageType::Pointer wholeImage = projectionsSource->GetOutput();
for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
{
geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Geometry object
GeometryType::Pointer oneProjGeometry = GeometryType::New();
oneProjGeometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);
// Ellipse 1
REIType::Pointer e1 = REIType::New();
e1->SetInput(oneProjectionSource->GetOutput());
e1->SetGeometry(oneProjGeometry);
e1->SetMultiplicativeConstant(2.);
e1->SetSemiPrincipalAxisX(60.);
e1->SetSemiPrincipalAxisY(60.);
e1->SetSemiPrincipalAxisZ(60.);
e1->SetCenterX(0.);
e1->SetCenterY(0.);
e1->SetCenterZ(0.);
e1->SetRotationAngle(0.);
e1->InPlaceOff();
e1->Update();
// Ellipse 2
REIType::Pointer e2 = REIType::New();
e2->SetInput(e1->GetOutput());
e2->SetGeometry(oneProjGeometry);
e2->SetMultiplicativeConstant(-1.);
e2->SetSemiPrincipalAxisX(8.);
e2->SetSemiPrincipalAxisY(8.);
e2->SetSemiPrincipalAxisZ(8.);
e2->SetCenterX( 4*(vcl_abs( (4+noProj) % 8 - 4.) - 2.) );
e2->SetCenterY(0.);
e2->SetCenterZ(0.);
e2->SetRotationAngle(0.);
e2->Update();
// Adding each projection to volume
pasteFilter->SetSourceImage(e2->GetOutput());
pasteFilter->SetDestinationImage(wholeImage);
pasteFilter->SetSourceRegion(e2->GetOutput()->GetLargestPossibleRegion());
pasteFilter->SetDestinationIndex(destinationIndex);
pasteFilter->Update();
wholeImage = pasteFilter->GetOutput();
destinationIndex[2]++;
// Signal
signalFile << (noProj % 8) / 8. << std::endl;
}
// Create vector field
typedef itk::Vector<float,3> DVFPixelType;
typedef itk::Image< DVFPixelType, 3 > DVFImageType;
typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;
typedef itk::ImageRegionIteratorWithIndex< DeformationType::InputImageType > IteratorType;
DeformationType::InputImageType::Pointer deformationField;
deformationField = DeformationType::InputImageType::New();
DeformationType::InputImageType::IndexType startMotion;
startMotion[0] = 0; // first index on X
startMotion[1] = 0; // first index on Y
startMotion[2] = 0; // first index on Z
startMotion[3] = 0; // first index on t
DeformationType::InputImageType::SizeType sizeMotion;
sizeMotion[0] = 64; // size along X
sizeMotion[1] = 64; // size along Y
sizeMotion[2] = 64; // size along Z
sizeMotion[3] = 2; // size along t
DeformationType::InputImageType::PointType originMotion;
originMotion[0] = (sizeMotion[0]-1)*(-0.5); // size along X
originMotion[1] = (sizeMotion[1]-1)*(-0.5); // size along Y
originMotion[2] = (sizeMotion[2]-1)*(-0.5); // size along Z
originMotion[3] = 0.;
DeformationType::InputImageType::RegionType regionMotion;
regionMotion.SetSize( sizeMotion );
regionMotion.SetIndex( startMotion );
deformationField->SetRegions( regionMotion );
deformationField->SetOrigin(originMotion);
deformationField->Allocate();
// Vector Field initilization
DVFPixelType vec;
vec.Fill(0.);
IteratorType inputIt( deformationField, deformationField->GetLargestPossibleRegion() );
for ( inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt)
{
if(inputIt.GetIndex()[3]==0)
vec[0] = -8.;
else
vec[0] = 8.;
inputIt.Set(vec);
}
// Create cyclic deformation
DeformationType::Pointer def = DeformationType::New();
def->SetInput(deformationField);
typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
WarpBPType::Pointer bp = WarpBPType::New();
bp->SetDeformation(def);
bp->SetGeometry( geometry.GetPointer() );
// FDK reconstruction filtering
#ifdef USE_CUDA
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKType;
#elif USE_OPENCL
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKType;
#else
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
FDKType::Pointer feldkamp = FDKType::New();
feldkamp->SetInput( 0, tomographySource->GetOutput() );
feldkamp->SetInput( 1, wholeImage );
feldkamp->SetGeometry( geometry );
def->SetSignalFilename("signal.txt");
feldkamp.GetPointer()->SetBackProjectionFilter( bp.GetPointer() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() );
// FOV
typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
FOVFilterType::Pointer fov=FOVFilterType::New();
fov->SetInput(0, feldkamp->GetOutput());
fov->SetProjectionsStack( wholeImage.GetPointer() );
fov->SetGeometry( geometry );
TRY_AND_EXIT_ON_ITK_EXCEPTION( fov->Update() );
// Create a reference object (in this case a 3D phantom reference).
// Ellipse 1
typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
DEType::Pointer e1 = DEType::New();
e1->SetInput( tomographySource->GetOutput() );
e1->SetAttenuation(2.);
DEType::VectorType axis(3, 60.);
e1->SetAxis(axis);
DEType::VectorType center(3, 0.);
e1->SetCenter(center);
e1->SetAngle(0.);
e1->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( e1->Update() )
// Ellipse 2
DEType::Pointer e2 = DEType::New();
e2->SetInput(e1->GetOutput());
e2->SetAttenuation(-1.);
DEType::VectorType axis2(3, 8.);
e2->SetAxis(axis2);
DEType::VectorType center2(3, 0.);
e2->SetCenter(center2);
e2->SetAngle(0.);
e2->InPlaceOff();
TRY_AND_EXIT_ON_ITK_EXCEPTION( e2->Update() )
CheckImageQuality<OutputImageType>(fov->GetOutput(), e2->GetOutput());
std::cout << "Test PASSED! " << std::endl;
itksys::SystemTools::RemoveFile("signal.txt");
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"
using namespace HTTPP;
using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;
static Connection* gconn = nullptr;
void handler(Connection* connection, Request&&)
{
gconn = connection;
}
BOOST_AUTO_TEST_CASE(cancel_async_operation)
{
HttpClient client;
HttpServer server;
server.start();
server.setSink(&handler);
server.bind("localhost", "8080");
HttpClient::Request request;
request
.url("http://localhost:8080")
.joinUrlPath("test")
.joinUrlPath("kiki", true);
auto handler = client.async_get(
std::move(request),
[](HttpClient::Future&& fut)
{ BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted); });
std::this_thread::sleep_for(std::chrono::seconds(1));
handler.cancelOperation();
std::this_thread::sleep_for(std::chrono::seconds(1));
Connection::releaseFromHandler(gconn);
server.stop();
BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}
static std::atomic_int nb_gconns = { 0 };
static std::vector<Connection*> gconns;
void handler_push(Connection* connection, Request&&)
{
gconns.push_back(connection);
}
BOOST_AUTO_TEST_CASE(delete_pending_connection)
{
HttpServer server;
server.start();
server.setSink(&handler_push);
server.bind("localhost", "8080");
std::atomic_int nb_cb {0};
{
HttpClient client;
HttpClient::Request request;
request.url("http://localhost:8080");
for (int i = 0; i < 1000; ++i)
{
client.async_get(HttpClient::Request{ request },
[&nb_cb](HttpClient::Future&& fut)
{
++nb_cb;
BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
});
}
//std::this_thread::sleep_for(std::chrono::seconds(1));
}
boost::log::core::get()->set_filter
(
boost::log::trivial::severity > boost::log::trivial::error
);
server.stopListeners();
std::for_each(
std::begin(gconns), std::end(gconns), &Connection::releaseFromHandler);
server.stop();
BOOST_CHECK_EQUAL(nb_cb.load(), 1000);
}
BOOST_AUTO_TEST_CASE(delete_pending_connection_google)
{
boost::log::core::get()->set_filter
(
boost::log::trivial::severity >= boost::log::trivial::debug
);
HttpClient client;
HttpClient::Request request;
request.url("http://google.com").followRedirect(true);
for (int i = 0; i < 10; ++i)
{
client.async_get(HttpClient::Request{ request },
[](HttpClient::Future&& fut)
{
BOOST_LOG_TRIVIAL(debug) << "Hello world";
BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
});
}
}
void handler2(Connection* c, Request&&)
{
c->response().setCode(HTTPP::HTTP::HttpCode::Ok);
c->sendResponse();
}
BOOST_AUTO_TEST_CASE(late_cancel)
{
HttpServer server;
server.start();
server.setSink(&handler2);
server.bind("localhost", "8080");
HttpClient client;
HttpClient::Request request;
request.url("http://localhost:8080");
auto handler = client.async_get(std::move(request),
[](HttpClient::Future&& fut)
{
BOOST_LOG_TRIVIAL(debug) << "Response received";
fut.get();
});
std::this_thread::sleep_for(std::chrono::milliseconds(500));
handler.cancelOperation();
BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}
<commit_msg>Add minor check<commit_after>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"
using namespace HTTPP;
using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;
static Connection* gconn = nullptr;
void handler(Connection* connection, Request&&)
{
gconn = connection;
}
BOOST_AUTO_TEST_CASE(cancel_async_operation)
{
HttpClient client;
HttpServer server;
server.start();
server.setSink(&handler);
server.bind("localhost", "8080");
HttpClient::Request request;
request
.url("http://localhost:8080")
.joinUrlPath("test")
.joinUrlPath("kiki", true);
auto handler = client.async_get(
std::move(request),
[](HttpClient::Future&& fut)
{ BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted); });
std::this_thread::sleep_for(std::chrono::seconds(1));
handler.cancelOperation();
std::this_thread::sleep_for(std::chrono::seconds(1));
Connection::releaseFromHandler(gconn);
server.stop();
BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}
static std::atomic_int nb_gconns = { 0 };
static std::vector<Connection*> gconns;
void handler_push(Connection* connection, Request&&)
{
gconns.push_back(connection);
}
BOOST_AUTO_TEST_CASE(delete_pending_connection)
{
HttpServer server;
server.start();
server.setSink(&handler_push);
server.bind("localhost", "8080");
std::atomic_int nb_cb {0};
{
HttpClient client;
HttpClient::Request request;
request.url("http://localhost:8080");
for (int i = 0; i < 1000; ++i)
{
client.async_get(HttpClient::Request{ request },
[&nb_cb](HttpClient::Future&& fut)
{
++nb_cb;
BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
});
}
//std::this_thread::sleep_for(std::chrono::seconds(1));
}
boost::log::core::get()->set_filter
(
boost::log::trivial::severity > boost::log::trivial::error
);
server.stopListeners();
std::for_each(
std::begin(gconns), std::end(gconns), &Connection::releaseFromHandler);
server.stop();
BOOST_CHECK_EQUAL(nb_cb.load(), 1000);
}
BOOST_AUTO_TEST_CASE(delete_pending_connection_google)
{
boost::log::core::get()->set_filter
(
boost::log::trivial::severity >= boost::log::trivial::debug
);
HttpClient client;
HttpClient::Request request;
request.url("http://google.com").followRedirect(true);
for (int i = 0; i < 10; ++i)
{
client.async_get(HttpClient::Request{ request },
[](HttpClient::Future&& fut)
{
BOOST_LOG_TRIVIAL(debug) << "Hello world";
BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
});
}
}
void handler2(Connection* c, Request&&)
{
c->response().setCode(HTTPP::HTTP::HttpCode::Ok);
c->sendResponse();
}
BOOST_AUTO_TEST_CASE(late_cancel)
{
HttpServer server;
server.start();
server.setSink(&handler2);
server.bind("localhost", "8080");
HttpClient client;
HttpClient::Request request;
request.url("http://localhost:8080");
bool ok = false;
auto handler = client.async_get(std::move(request),
[&ok](HttpClient::Future&& fut)
{
ok = true;
BOOST_LOG_TRIVIAL(debug) << "Response received";
fut.get();
});
std::this_thread::sleep_for(std::chrono::milliseconds(500));
BOOST_CHECK(ok);
handler.cancelOperation();
BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_HOOK_HPP
#define VIENNAGRID_STORAGE_HOOK_HPP
#include <iterator>
#include <vector>
#include <map>
#include "viennagrid/meta/typemap.hpp"
#include "viennagrid/storage/forwards.hpp"
namespace viennagrid
{
namespace storage
{
namespace hook
{
template<typename base_container_type, typename view_reference_tag>
struct hook_type
{};
template<typename base_container_type>
struct hook_type<base_container_type, no_hook_tag>
{
typedef viennameta::null_type type;
};
template<typename base_container_type>
struct hook_type<base_container_type, pointer_hook_tag>
{
typedef typename base_container_type::pointer type;
};
template<typename base_container_type>
struct hook_type<base_container_type, iterator_hook_tag>
{
typedef typename base_container_type::iterator type;
};
template<typename base_container_type, typename id_type>
struct hook_type<base_container_type, id_hook_tag<id_type> >
{
typedef id_type type;
};
template<typename base_container_type, typename view_reference_tag>
struct const_hook_type
{};
template<typename base_container_type>
struct const_hook_type<base_container_type, no_hook_tag>
{
typedef const viennameta::null_type type;
};
template<typename base_container_type>
struct const_hook_type<base_container_type, pointer_hook_tag>
{
typedef typename base_container_type::const_pointer type;
};
template<typename base_container_type>
struct const_hook_type<base_container_type, iterator_hook_tag>
{
typedef typename base_container_type::const_iterator type;
};
template<typename base_container_type, typename id_type>
struct const_hook_type<base_container_type, id_hook_tag<id_type> >
{
typedef const id_type type;
};
template<typename container_type, typename hook_tag>
struct iterator_to_hook;
template<typename container_type>
struct iterator_to_hook<container_type, no_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, no_hook_tag>::type hook_type;
template<typename iterator>
static hook_type convert( iterator it ) { return hook_type(); }
};
template<typename container_type>
struct iterator_to_hook<container_type, iterator_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, iterator_hook_tag>::type hook_type;
static hook_type convert( hook_type it ) { return it; }
};
template<typename container_type>
struct iterator_to_hook<container_type, pointer_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, pointer_hook_tag>::type hook_type;
template<typename iterator>
static hook_type convert( iterator it ) { return &* it; }
};
template<typename container_type, typename id_type>
struct iterator_to_hook<container_type, id_hook_tag<id_type> >
{
typedef typename viennagrid::storage::hook::hook_type<container_type, id_hook_tag<id_type> >::type hook_type;
template<typename iterator>
static hook_type convert( iterator it ) { return it->id(); }
};
// template<typename reference_type>
// struct value_type_from_reference_type;
//
// template<typename value_type>
// struct value_type_from_reference_type< value_type * >
// {
// typedef value_type type;
// };
//
// template<typename category, typename value_type, typename distance, typename pointer, typename reference>
// struct value_type_from_reference_type< std::iterator<category, value_type, distance, pointer, reference> >
// {
// typedef value_type type;
// };
// template<typename value_type, typename reference_tag_config>
// struct reference_tag_from_config
// {
// typedef typename viennameta::typemap::result_of::find<reference_tag_config, value_type>::type search_result;
// typedef typename viennameta::typemap::result_of::find<reference_tag_config, viennagrid::storage::default_tag>::type default_reference_tag;
//
// typedef typename viennameta::_if<
// !viennameta::_equal<search_result, viennameta::not_found>::value,
// search_result,
// default_reference_tag
// >::type::second type;
// };
//
// template<typename container_type, typename reference_tag_config>
// struct reference_type_from_config
// {
// typedef typename reference_type<
// container_type,
// typename reference_tag_from_config<typename container_type::iterator, reference_tag_config>::type
// >::type type;
// };
// template<typename iterator_type>
// typename iterator_type::value_type * iterator_to_reference(iterator_type it, pointer_reference_tag)
// { return &* it; }
//
// template<typename iterator_type>
// iterator_type iterator_to_reference(iterator_type it, iterator_reference_tag)
// { return it; }
//
// template<typename iterator_type>
// typename iterator_type::value_type::id_type iterator_to_reference(iterator_type it, id_reference_tag)
// { return it->id(); }
// template<typename dst_reference_type>
// struct reference_converter
// {
// static dst_reference_type convert( dst_reference_type ref )
// {
// return ref;
// }
// };
//
// template<typename value_type>
// struct reference_converter<value_type *>
// {
// template<typename iterator_type>
// static value_type * convert( iterator_type it )
// {
// typedef typename iterator_type::iterator_category tmp;
// return &* it;
// }
// };
}
}
}
#endif<commit_msg>adapted to id_hook_type without id_type<commit_after>#ifndef VIENNAGRID_STORAGE_HOOK_HPP
#define VIENNAGRID_STORAGE_HOOK_HPP
#include <iterator>
#include <vector>
#include <map>
#include "viennagrid/meta/typemap.hpp"
#include "viennagrid/storage/id.hpp"
#include "viennagrid/storage/forwards.hpp"
namespace viennagrid
{
namespace storage
{
namespace hook
{
template<typename base_container_type, typename view_reference_tag>
struct hook_type
{};
template<typename base_container_type>
struct hook_type<base_container_type, no_hook_tag>
{
typedef viennameta::null_type type;
};
template<typename base_container_type>
struct hook_type<base_container_type, pointer_hook_tag>
{
typedef typename base_container_type::pointer type;
};
template<typename base_container_type>
struct hook_type<base_container_type, iterator_hook_tag>
{
typedef typename base_container_type::iterator type;
};
template<typename base_container_type>
struct hook_type<base_container_type, id_hook_tag>
{
typedef typename base_container_type::value_type::id_type type;
};
template<typename base_container_type, typename view_reference_tag>
struct const_hook_type
{};
template<typename base_container_type>
struct const_hook_type<base_container_type, no_hook_tag>
{
typedef const viennameta::null_type type;
};
template<typename base_container_type>
struct const_hook_type<base_container_type, pointer_hook_tag>
{
typedef typename base_container_type::const_pointer type;
};
template<typename base_container_type>
struct const_hook_type<base_container_type, iterator_hook_tag>
{
typedef typename base_container_type::const_iterator type;
};
template<typename base_container_type>
struct const_hook_type<base_container_type, id_hook_tag>
{
typedef const typename base_container_type::value_type::id_type type;
};
template<typename container_type, typename hook_tag>
struct iterator_to_hook;
template<typename container_type>
struct iterator_to_hook<container_type, no_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, no_hook_tag>::type hook_type;
template<typename iterator>
static hook_type convert( iterator it ) { return hook_type(); }
};
template<typename container_type>
struct iterator_to_hook<container_type, iterator_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, iterator_hook_tag>::type hook_type;
static hook_type convert( hook_type it ) { return it; }
};
template<typename container_type>
struct iterator_to_hook<container_type, pointer_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, pointer_hook_tag>::type hook_type;
template<typename iterator>
static hook_type convert( iterator it ) { return &* it; }
};
template<typename container_type>
struct iterator_to_hook<container_type, id_hook_tag>
{
typedef typename viennagrid::storage::hook::hook_type<container_type, id_hook_tag>::type hook_type;
template<typename iterator>
static hook_type convert( iterator it ) { return it->id(); }
};
// template<typename reference_type>
// struct value_type_from_reference_type;
//
// template<typename value_type>
// struct value_type_from_reference_type< value_type * >
// {
// typedef value_type type;
// };
//
// template<typename category, typename value_type, typename distance, typename pointer, typename reference>
// struct value_type_from_reference_type< std::iterator<category, value_type, distance, pointer, reference> >
// {
// typedef value_type type;
// };
// template<typename value_type, typename reference_tag_config>
// struct reference_tag_from_config
// {
// typedef typename viennameta::typemap::result_of::find<reference_tag_config, value_type>::type search_result;
// typedef typename viennameta::typemap::result_of::find<reference_tag_config, viennagrid::storage::default_tag>::type default_reference_tag;
//
// typedef typename viennameta::_if<
// !viennameta::_equal<search_result, viennameta::not_found>::value,
// search_result,
// default_reference_tag
// >::type::second type;
// };
//
// template<typename container_type, typename reference_tag_config>
// struct reference_type_from_config
// {
// typedef typename reference_type<
// container_type,
// typename reference_tag_from_config<typename container_type::iterator, reference_tag_config>::type
// >::type type;
// };
// template<typename iterator_type>
// typename iterator_type::value_type * iterator_to_reference(iterator_type it, pointer_reference_tag)
// { return &* it; }
//
// template<typename iterator_type>
// iterator_type iterator_to_reference(iterator_type it, iterator_reference_tag)
// { return it; }
//
// template<typename iterator_type>
// typename iterator_type::value_type::id_type iterator_to_reference(iterator_type it, id_reference_tag)
// { return it->id(); }
// template<typename dst_reference_type>
// struct reference_converter
// {
// static dst_reference_type convert( dst_reference_type ref )
// {
// return ref;
// }
// };
//
// template<typename value_type>
// struct reference_converter<value_type *>
// {
// template<typename iterator_type>
// static value_type * convert( iterator_type it )
// {
// typedef typename iterator_type::iterator_category tmp;
// return &* it;
// }
// };
}
}
}
#endif<|endoftext|> |
<commit_before>/*
*
* Copyright (C) 2015 Jason Gowan
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <gtest/gtest.h>
#include "simple_constraint_handler.h"
#include <vector>
TEST(SimpleConstraintHandlerTest, canCreate) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
std::vector<dither::dval> tmp;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
}
constraints.push_back(tmp);
dither::SimpleConstraintHandler handler(arr, constraints);
}
TEST(SimpleConstraintHandlerTest, canTestCaseViolateConstraint) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
dither::dval constraint2[] = {-1, 0, 0, 0};
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
std::vector<dither::dval> test_case;
test_case.push_back(0);
test_case.push_back(-1);
test_case.push_back(-1);
test_case.push_back(-1);
dither::SimpleConstraintHandler handler(arr, constraints);
ASSERT_FALSE(handler.violate_constraints(test_case));
test_case[1] = 0;
test_case[2] = 0;
ASSERT_TRUE(handler.violate_constraints(test_case));
test_case[1] = 1;
test_case[3] = 0;
ASSERT_FALSE(handler.violate_constraints(test_case));
}
TEST(SimpleConstraintHandlerTest, canParamsViolateConstraint) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
dither::dval constraint2[] = {-1, 0, 0, 0};
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
std::vector<dither::param> test_case;
dither::param param1;
param1.first = 0;
param1.second = 0;
test_case.push_back(param1);
dither::SimpleConstraintHandler handler(arr, constraints);
ASSERT_FALSE(handler.violate_constraints(test_case));
dither::param param2;
param2.first = 1;
param2.second = 0;
test_case.push_back(param2);
ASSERT_FALSE(handler.violate_constraints(test_case));
dither::param param3;
param3.first = 2;
param3.second = 0;
test_case.push_back(param3);
ASSERT_TRUE(handler.violate_constraints(test_case));
}
TEST(SimpleConstraintHandlerTest, canGroundTestCase) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
dither::dval constraint2[] = {-1, 0, 0, 0};
dither::dval constraint3[] = {0, -1, -1, 0};
dither::dval constraint4[] = {1, -1, -1, 0};
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
std::vector<dither::dval> tmp3;
std::vector<dither::dval> tmp4;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
tmp3.push_back(constraint3[i]);
tmp4.push_back(constraint4[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
constraints.push_back(tmp3);
constraints.push_back(tmp4);
std::vector<dither::dval> test_case;
test_case.push_back(0);
test_case.push_back(-1);
test_case.push_back(-1);
test_case.push_back(-1);
dither::SimpleConstraintHandler handler(arr, constraints);
ASSERT_TRUE(handler.ground(test_case));
std::vector<dither::dval> test_case2;
test_case2.push_back(0);
test_case2.push_back(0);
test_case2.push_back(0);
test_case2.push_back(-1);
ASSERT_FALSE(handler.ground(test_case2));
std::vector<dither::dval> test_case3;
test_case3.push_back(0);
test_case3.push_back(-1);
test_case3.push_back(0);
test_case3.push_back(-1);
// constraint solver should be able to unwind
ASSERT_TRUE(handler.ground(test_case3));
}
TEST(GecodeCompatibilityConstraintTest, canValidateGecodeConstraintOnTestCase) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
std::vector<dither::dval> tmp;
int constraint[] = {-1, 0, 0, -1};
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
}
constraints.push_back(tmp);
dither::SimpleConstraintHandler handler(arr, constraints);
dither::dtest_case dcase(4, -1);
dcase[0] = 0;
ASSERT_FALSE(handler.violate_constraints(dcase));
// test specific to gecode edge case
/* dcase[1] = 20; */
/* ASSERT_TRUE(handler.violate_constraints(dcase)); */
dcase[1] = 0;
dcase[2] = 0;
ASSERT_TRUE(handler.violate_constraints(dcase));
}
TEST(GecodeCompatibilityConstraintTest, canValidateGecodeConstraintOnParams) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
std::vector<dither::dval> tmp;
int constraint[] = {-1, 0, 0, -1};
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
}
constraints.push_back(tmp);
dither::SimpleConstraintHandler handler(arr, constraints);
std::vector<dither::param> params;
dither::param my_param;
my_param.first = 0;
my_param.second = 1;
params.push_back(my_param);
dither::dtest_case dcase(4, -1);
dcase[0] = 0;
ASSERT_FALSE(handler.violate_constraints(params));
// test specific to gecode edge case
/* params.clear(); */
/* my_param.second = 20; */
/* params.push_back(my_param); */
/* ASSERT_TRUE(handler.violate_constraints(params)); */
params.clear();
my_param.first = 1;
my_param.second = 0;
params.push_back(my_param);
my_param.first = 2;
my_param.second = 0;
params.push_back(my_param);
ASSERT_TRUE(handler.violate_constraints(params));
}
TEST(GecodeCompatibilityConstraintTest, canGroundSimpleConstraintOnTestCase) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
std::vector<dither::dval> tmp3;
std::vector<dither::dval> tmp4;
int constraint[] = {-1, 0, 0, -1};
int constraint2[] = {-1, 0, -1, -1};
int constraint3[] = {-1, -1, 0, 0};
int constraint4[] = {-1, -1, 0, 1};
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
tmp3.push_back(constraint3[i]);
tmp4.push_back(constraint4[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
constraints.push_back(tmp3);
constraints.push_back(tmp4);
dither::SimpleConstraintHandler handler(arr, constraints);
dither::dtest_case dcase(4, -1);
dcase[0] = 0;
ASSERT_TRUE(handler.ground(dcase));
ASSERT_EQ(dcase[1], 1);
ASSERT_EQ(dcase[0], 0);
// test specific to gecode edge case
/* std::fill(dcase.begin(), dcase.end(), -1); */
/* dcase[1] = 20; */
/* ASSERT_FALSE(handler.ground(dcase)); */
std::fill(dcase.begin(), dcase.end(), -1);
dcase[1] = 0;
dcase[2] = 0;
ASSERT_FALSE(handler.ground(dcase));
std::fill(dcase.begin(), dcase.end(), -1);
dcase[2] = 0;
dcase[3] = 0;
ASSERT_FALSE(handler.ground(dcase));
}
<commit_msg>create failing test case<commit_after>/*
*
* Copyright (C) 2015 Jason Gowan
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <gtest/gtest.h>
#include "simple_constraint_handler.h"
#include <vector>
TEST(SimpleConstraintHandlerTest, canCreate) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
std::vector<dither::dval> tmp;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
}
constraints.push_back(tmp);
dither::SimpleConstraintHandler handler(arr, constraints);
}
TEST(SimpleConstraintHandlerTest, canTestCaseViolateConstraint) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
dither::dval constraint2[] = {-1, 0, 0, 0};
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
std::vector<dither::dval> test_case;
test_case.push_back(0);
test_case.push_back(-1);
test_case.push_back(-1);
test_case.push_back(-1);
dither::SimpleConstraintHandler handler(arr, constraints);
ASSERT_FALSE(handler.violate_constraints(test_case));
test_case[1] = 0;
test_case[2] = 0;
ASSERT_TRUE(handler.violate_constraints(test_case));
test_case[1] = 1;
test_case[3] = 0;
ASSERT_FALSE(handler.violate_constraints(test_case));
}
TEST(SimpleConstraintHandlerTest, canParamsViolateConstraint) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
dither::dval constraint2[] = {-1, 0, 0, 0};
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
std::vector<dither::param> test_case;
dither::param param1;
param1.first = 0;
param1.second = 0;
test_case.push_back(param1);
dither::SimpleConstraintHandler handler(arr, constraints);
ASSERT_FALSE(handler.violate_constraints(test_case));
dither::param param2;
param2.first = 1;
param2.second = 0;
test_case.push_back(param2);
ASSERT_FALSE(handler.violate_constraints(test_case));
dither::param param3;
param3.first = 2;
param3.second = 0;
test_case.push_back(param3);
ASSERT_TRUE(handler.violate_constraints(test_case));
}
TEST(SimpleConstraintHandlerTest, canGroundTestCase) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
dither::dval constraint[] = {-1, 0, 0, -1};
dither::dval constraint2[] = {-1, 0, 0, 0};
dither::dval constraint3[] = {0, -1, -1, 0};
dither::dval constraint4[] = {1, -1, -1, 0};
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
std::vector<dither::dval> tmp3;
std::vector<dither::dval> tmp4;
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
tmp3.push_back(constraint3[i]);
tmp4.push_back(constraint4[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
constraints.push_back(tmp3);
constraints.push_back(tmp4);
std::vector<dither::dval> test_case;
test_case.push_back(0);
test_case.push_back(-1);
test_case.push_back(-1);
test_case.push_back(-1);
dither::SimpleConstraintHandler handler(arr, constraints);
ASSERT_TRUE(handler.ground(test_case));
std::vector<dither::dval> test_case2;
test_case2.push_back(0);
test_case2.push_back(0);
test_case2.push_back(0);
test_case2.push_back(-1);
ASSERT_FALSE(handler.ground(test_case2));
std::vector<dither::dval> test_case3;
test_case3.push_back(0);
test_case3.push_back(-1);
test_case3.push_back(0);
test_case3.push_back(-1);
// constraint solver should be able to unwind
ASSERT_TRUE(handler.ground(test_case3));
}
TEST(GecodeCompatibilityConstraintTest, canValidateGecodeConstraintOnTestCase) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
std::vector<dither::dval> tmp;
int constraint[] = {-1, 0, 0, -1};
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
}
constraints.push_back(tmp);
dither::SimpleConstraintHandler handler(arr, constraints);
dither::dtest_case dcase(4, -1);
dcase[0] = 0;
ASSERT_FALSE(handler.violate_constraints(dcase));
// test specific to gecode edge case
/* dcase[1] = 20; */
/* ASSERT_TRUE(handler.violate_constraints(dcase)); */
dcase[1] = 0;
dcase[2] = 0;
ASSERT_TRUE(handler.violate_constraints(dcase));
}
TEST(GecodeCompatibilityConstraintTest, canValidateGecodeConstraintOnParams) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
std::vector<std::vector<dither::dval>> constraints;
std::vector<dither::dval> tmp;
int constraint[] = {-1, 0, 0, -1};
for(unsigned int i = 0; i < 4; i++) {
tmp.push_back(constraint[i]);
}
constraints.push_back(tmp);
dither::SimpleConstraintHandler handler(arr, constraints);
std::vector<dither::param> params;
dither::param my_param;
my_param.first = 0;
my_param.second = 1;
params.push_back(my_param);
dither::dtest_case dcase(4, -1);
dcase[0] = 0;
ASSERT_FALSE(handler.violate_constraints(params));
// test specific to gecode edge case
/* params.clear(); */
/* my_param.second = 20; */
/* params.push_back(my_param); */
/* ASSERT_TRUE(handler.violate_constraints(params)); */
params.clear();
my_param.first = 1;
my_param.second = 0;
params.push_back(my_param);
my_param.first = 2;
my_param.second = 0;
params.push_back(my_param);
ASSERT_TRUE(handler.violate_constraints(params));
}
TEST(GecodeCompatibilityConstraintTest, canGroundSimpleConstraintOnTestCase) {
std::vector<dither::dval> arr;
arr.push_back(2);
arr.push_back(2);
arr.push_back(4);
arr.push_back(5);
arr.push_back(1);
std::vector<std::vector<dither::dval>> constraints;
std::vector<dither::dval> tmp;
std::vector<dither::dval> tmp2;
std::vector<dither::dval> tmp3;
std::vector<dither::dval> tmp4;
std::vector<dither::dval> tmp5;
std::vector<dither::dval> tmp6;
int constraint[] = {-1, 0, 0, -1, -1};
int constraint2[] = {-1, 0, -1, -1, -1};
int constraint3[] = {-1, -1, 0, 0, -1};
int constraint4[] = {-1, -1, 0, 1, -1};
int constraint5[] = {-1, -1, 0, -1, 0};
int constraint6[] = {-1, -1, 0, -1, 1};
for(unsigned int i = 0; i < 5; i++) {
tmp.push_back(constraint[i]);
tmp2.push_back(constraint2[i]);
tmp3.push_back(constraint3[i]);
tmp4.push_back(constraint4[i]);
tmp5.push_back(constraint5[i]);
tmp6.push_back(constraint6[i]);
}
constraints.push_back(tmp);
constraints.push_back(tmp2);
constraints.push_back(tmp3);
constraints.push_back(tmp4);
constraints.push_back(tmp5);
constraints.push_back(tmp6);
dither::SimpleConstraintHandler handler(arr, constraints);
dither::dtest_case dcase(5, -1);
dcase[0] = 0;
ASSERT_TRUE(handler.ground(dcase));
ASSERT_EQ(dcase[1], 1);
ASSERT_EQ(dcase[0], 0);
// test specific to gecode edge case
/* std::fill(dcase.begin(), dcase.end(), -1); */
/* dcase[1] = 20; */
/* ASSERT_FALSE(handler.ground(dcase)); */
std::fill(dcase.begin(), dcase.end(), -1);
dcase[1] = 0;
dcase[2] = 0;
ASSERT_FALSE(handler.ground(dcase));
std::fill(dcase.begin(), dcase.end(), -1);
dcase[2] = 0;
dcase[3] = 0;
ASSERT_FALSE(handler.ground(dcase));
std::fill(dcase.begin(), dcase.end(), -1);
dcase[1] = 0;
dcase[4] = 0;
ASSERT_FALSE(handler.ground(dcase));
std::fill(dcase.begin(), dcase.end(), -1);
dcase[3] = 2;
ASSERT_TRUE(handler.ground(dcase));
std::fill(dcase.begin(), dcase.end(), -1);
dcase[4] = 0;
ASSERT_TRUE(handler.ground(dcase));
}
<|endoftext|> |
<commit_before>#include "tests.h"
// Work efficient prefix sum
template <typename F, typename std::enable_if<std::is_floating_point<F>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<F, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
F sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (F)i;
auto diff = std::abs(sum - d[i]);
if(diff > 0.01) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename I, typename std::enable_if<std::is_integral<I>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<I, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
I sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (I)i;
if(d[i] != sum) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename T>
struct prefix_sum_kernel {
protected:
using mode = cl::sycl::access::mode;
using target = cl::sycl::access::target;
// Global memory
cl::sycl::accessor<T, 1> input;
// Local memory
cl::sycl::accessor<T, 1, mode::read_write, target::local> localBlock;
public:
prefix_sum_kernel(cl::sycl::buffer<T>& data, size_t group_size)
: input(data.get_access<mode::read_write>()), localBlock(group_size) {}
void operator()(cl::sycl::nd_item<1> index) {
using namespace cl::sycl;
uint1 GID = 2 * index.get_global_id(0);
uint1 LID = 2 * index.get_local_id(0);
localBlock[LID] = input[GID];
localBlock[LID + 1] = input[GID + 1];
index.barrier(access::fence_space::local);
uint1 N = 2 * index.get_local_size(0);
uint1 first;
uint1 second;
LID /= 2;
// Up-sweep
uint1 offset = 1;
SYCL_WHILE(offset < N)
SYCL_BEGIN{
SYCL_IF(LID % offset == 0)
SYCL_BEGIN{
first = 2 * LID + offset - 1;
second = first + offset;
localBlock[second] = localBlock[first] + localBlock[second];
}
SYCL_END
index.barrier(access::fence_space::local);
offset *= 2;
}
SYCL_END
SYCL_IF(LID == 0)
SYCL_THEN({
localBlock[N - 1] = 0;
})
index.barrier(access::fence_space::local);
// TODO: Need to make this generic
uint1 tmp;
// Down-sweep
offset = N;
SYCL_WHILE(offset > 0)
SYCL_BEGIN{
SYCL_IF(LID % offset == 0)
SYCL_BEGIN{
first = 2 * LID + offset - 1;
second = first + offset;
tmp = localBlock[second];
localBlock[second] = localBlock[first] + tmp;
localBlock[first] = tmp;
}
SYCL_END
index.barrier(access::fence_space::local);
offset /= 2;
}
SYCL_END
LID *= 2;
input[GID] += localBlock[LID];
input[GID + 1] += localBlock[LID + 1];
}
};
bool test9() {
using namespace cl::sycl;
{
queue myQueue;
const auto group_size = myQueue.get_device().get_info<CL_DEVICE_MAX_WORK_GROUP_SIZE>();
const auto size = group_size * 2;
buffer<float> data(size);
// Init
command_group(myQueue, [&]() {
auto d = data.get_access<access::write>();
parallel_for<>(range<1>(size), [=](id<1> index) {
d[index] = index;
});
});
command_group(myQueue, [&]() {
// TODO: Extend for large arrays
parallel_for<>(
nd_range<1>(size / 2, group_size),
prefix_sum_kernel<float>(data, group_size)
);
});
return check_sum(data);
}
return true;
}
<commit_msg>made test9 truly generic.<commit_after>#include "tests.h"
// Work efficient prefix sum
template <typename F, typename std::enable_if<std::is_floating_point<F>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<F, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
F sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (F)i;
auto diff = std::abs(sum - d[i]);
if(diff > 0.01) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename I, typename std::enable_if<std::is_integral<I>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<I, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
I sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (I)i;
if(d[i] != sum) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename T>
struct prefix_sum_kernel {
protected:
using mode = cl::sycl::access::mode;
using target = cl::sycl::access::target;
// Global memory
cl::sycl::accessor<T, 1> input;
// Local memory
cl::sycl::accessor<T, 1, mode::read_write, target::local> localBlock;
public:
prefix_sum_kernel(cl::sycl::buffer<T>& data, size_t group_size)
: input(data.get_access<mode::read_write>()), localBlock(group_size) {}
void operator()(cl::sycl::nd_item<1> index) {
using namespace cl::sycl;
uint1 GID = 2 * index.get_global_id(0);
uint1 LID = 2 * index.get_local_id(0);
localBlock[LID] = input[GID];
localBlock[LID + 1] = input[GID + 1];
index.barrier(access::fence_space::local);
uint1 N = 2 * index.get_local_size(0);
uint1 first;
uint1 second;
LID /= 2;
// Up-sweep
uint1 offset = 1;
SYCL_WHILE(offset < N)
SYCL_BEGIN{
SYCL_IF(LID % offset == 0)
SYCL_BEGIN{
first = 2 * LID + offset - 1;
second = first + offset;
localBlock[second] = localBlock[first] + localBlock[second];
}
SYCL_END
index.barrier(access::fence_space::local);
offset *= 2;
}
SYCL_END
SYCL_IF(LID == 0)
SYCL_THEN({
localBlock[N - 1] = 0;
})
index.barrier(access::fence_space::local);
vec<T, 1> tmp;
// Down-sweep
offset = N;
SYCL_WHILE(offset > 0)
SYCL_BEGIN{
SYCL_IF(LID % offset == 0)
SYCL_BEGIN{
first = 2 * LID + offset - 1;
second = first + offset;
tmp = localBlock[second];
localBlock[second] = localBlock[first] + tmp;
localBlock[first] = tmp;
}
SYCL_END
index.barrier(access::fence_space::local);
offset /= 2;
}
SYCL_END
LID *= 2;
input[GID] += localBlock[LID];
input[GID + 1] += localBlock[LID + 1];
}
};
bool test9() {
using namespace cl::sycl;
{
queue myQueue;
const auto group_size = myQueue.get_device().get_info<CL_DEVICE_MAX_WORK_GROUP_SIZE>();
const auto size = group_size * 2;
using type = double;
buffer<type> data(size);
// Init
command_group(myQueue, [&]() {
auto d = data.get_access<access::write>();
parallel_for<>(range<1>(size), [=](id<1> index) {
d[index] = index;
});
});
command_group(myQueue, [&]() {
// TODO: Extend for large arrays
parallel_for<>(
nd_range<1>(size / 2, group_size),
prefix_sum_kernel<type>(data, group_size)
);
});
return check_sum(data);
}
return true;
}
<|endoftext|> |
<commit_before>#include <QAbstractButton>
#include "KVSettingsDialog.h"
#include "ui_KVSettingsDialog.h"
#include "KVMainWindow.h"
#include "KVDefaults.h"
KVSettingsDialog::KVSettingsDialog(KVMainWindow *parent, Qt::WindowFlags f) :
QDialog(parent, f),
ui(new Ui::KVSettingsDialog)
{
ui->setupUi(this);
ui->translationCheckbox->setChecked(
settings.value("viewerTranslation", kDefaultTranslation).toBool());
ui->proxyCheckbox->setChecked(settings.value("proxy", kDefaultProxy).toBool());
ui->proxyServerEdit->setText(settings.value("proxyServer", kDefaultProxyServer).toString());
ui->proxyPortBox->setValue(settings.value("proxyPort", kDefaultProxyPort).toInt());
ui->proxyUserEdit->setText(settings.value("proxyUser", kDefaultProxyUser).toString());
ui->proxyPassEdit->setText(settings.value("proxyPass", kDefaultProxyPass).toString());
switch(settings.value("proxyType", kDefaultProxyType).toInt())
{
default:
case QNetworkProxy::Socks5Proxy:
ui->socksProxyRadio->setChecked(true);
break;
case QNetworkProxy::HttpProxy:
ui->httpProxyRadio->setChecked(true);
break;
}
connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)),
SLOT(buttonClicked(QAbstractButton*)));
this->adjustSize();
}
KVSettingsDialog::~KVSettingsDialog()
{
}
void KVSettingsDialog::accept()
{
this->setSettings();
QDialog::accept();
}
void KVSettingsDialog::setSettings()
{
settings.setValue("viewerTranslation", ui->translationCheckbox->isChecked());
settings.setValue("proxy", ui->proxyCheckbox->isChecked());
settings.setValue("proxyServer", ui->proxyServerEdit->text());
settings.setValue("proxyPort", ui->proxyPortBox->value());
if(ui->socksProxyRadio->isChecked())
settings.setValue("proxyType", QNetworkProxy::Socks5Proxy);
else if(ui->httpProxyRadio->isChecked())
settings.setValue("proxyType", QNetworkProxy::HttpProxy);
settings.sync();
emit apply();
}
void KVSettingsDialog::buttonClicked(QAbstractButton *button)
{
if(ui->buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole)
setSettings();
}
<commit_msg>Fix the size of the Viewer Settings dialog<commit_after>#include <QAbstractButton>
#include "KVSettingsDialog.h"
#include "ui_KVSettingsDialog.h"
#include "KVMainWindow.h"
#include "KVDefaults.h"
KVSettingsDialog::KVSettingsDialog(KVMainWindow *parent, Qt::WindowFlags f) :
QDialog(parent, f),
ui(new Ui::KVSettingsDialog)
{
ui->setupUi(this);
ui->translationCheckbox->setChecked(
settings.value("viewerTranslation", kDefaultTranslation).toBool());
ui->proxyCheckbox->setChecked(settings.value("proxy", kDefaultProxy).toBool());
ui->proxyServerEdit->setText(settings.value("proxyServer", kDefaultProxyServer).toString());
ui->proxyPortBox->setValue(settings.value("proxyPort", kDefaultProxyPort).toInt());
ui->proxyUserEdit->setText(settings.value("proxyUser", kDefaultProxyUser).toString());
ui->proxyPassEdit->setText(settings.value("proxyPass", kDefaultProxyPass).toString());
switch(settings.value("proxyType", kDefaultProxyType).toInt())
{
default:
case QNetworkProxy::Socks5Proxy:
ui->socksProxyRadio->setChecked(true);
break;
case QNetworkProxy::HttpProxy:
ui->httpProxyRadio->setChecked(true);
break;
}
connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)),
SLOT(buttonClicked(QAbstractButton*)));
this->adjustSize();
this->setFixedSize(this->size());
}
KVSettingsDialog::~KVSettingsDialog()
{
}
void KVSettingsDialog::accept()
{
this->setSettings();
QDialog::accept();
}
void KVSettingsDialog::setSettings()
{
settings.setValue("viewerTranslation", ui->translationCheckbox->isChecked());
settings.setValue("proxy", ui->proxyCheckbox->isChecked());
settings.setValue("proxyServer", ui->proxyServerEdit->text());
settings.setValue("proxyPort", ui->proxyPortBox->value());
if(ui->socksProxyRadio->isChecked())
settings.setValue("proxyType", QNetworkProxy::Socks5Proxy);
else if(ui->httpProxyRadio->isChecked())
settings.setValue("proxyType", QNetworkProxy::HttpProxy);
settings.sync();
emit apply();
}
void KVSettingsDialog::buttonClicked(QAbstractButton *button)
{
if(ui->buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole)
setSettings();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Nickolas Pohilets
//
// This file is a part of the unit test suit for the CppEvents library.
//
// 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 <Cpp/Events/AbstractObjectRef.hpp>
#include "TestClasses.hpp"
#include <gtest/gtest.h>
using Cpp::Private::Events::IsPolymorphic;
////////////////////////////////////////////////////////////////////////////////
// For checking polymorphy special template class is derived from class being tested.
// This potentially may cause compilation problems if some special members of base class are inaccessible.
// This test is designed for detecting these problems. Test is passed if it compiles.
TEST(Test_IsPolymorphic, Compilability)
{
bool const b = IsPolymorphic<ClassWithUndefinedPrivateCtorAndDtor>::value;
(void)b;
}
////////////////////////////////////////////////////////////////////////////////
// Class alignment may possibly cause false detection of polymorphic classes.
// This test is designed for detecting them.
namespace {
template<int n> void doTestAlignmentIssues(ClassOfSize<n> const & x)
{
ASSERT_FALSE(IsPolymorphic< ClassOfSize<n> >::value);
}
template<int n> void testAlignmentIssues(ClassOfSize<n> const & x)
{
doTestAlignmentIssues(x);
testAlignmentIssues(ClassOfSize<n-1>());
}
void testAlignmentIssues(ClassOfSize<0> const & x)
{
doTestAlignmentIssues(x);
}
}
TEST(Test_IsPolymorphic, AlignmentIssues)
{
testAlignmentIssues(ClassOfSize< sizeof(void*) * 2 >());
}
////////////////////////////////////////////////////////////////////////////////
// This test checks classes that are naturally non-polymorphic.
// The TestAlignmentIssues does the same but does it better.
// Thus this test is not much useful but let it be.
TEST(Test_IsPolymorphic, NaturallyNonPolymorphic)
{
ASSERT_FALSE(IsPolymorphic< NonVirtualClass1 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass2_1 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass3_1 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass4_2_3 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass2 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass3 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass4 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass5 >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that all naturally polymorphic classes are detected as polymorphic.
TEST(Test_IsPolymorphic, NaturallyPolymorphic)
{
//This class are naturally polymorphic
ASSERT_TRUE(IsPolymorphic< VirtualByDestructor >::value);
ASSERT_TRUE(IsPolymorphic< VirtualByFunction >::value);
ASSERT_TRUE(IsPolymorphic< VirtualByPureFunction >::value);
ASSERT_TRUE(IsPolymorphic< VirtualBaseClass >::value);
ASSERT_TRUE(IsPolymorphic< VirtualDerivedClass1 >::value);
ASSERT_TRUE(IsPolymorphic< VirtualDerivedClass2 >::value);
ASSERT_TRUE(IsPolymorphic< VirtualCommonDerived >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that classes that have non-virtual hierarchy root and have
// added virtuality later in the hierarchy tree are detected as polymorphic.
TEST(Test_IsPolymorphic, Polymorphized)
{
//This classes
ASSERT_TRUE(IsPolymorphic< ClassThatAddsVirtuality1 >::value);
ASSERT_TRUE(IsPolymorphic< ClassThatAddsVirtuality2 >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass1> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass2_1> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass3_1> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass4_2_3> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass2> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass3> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass4> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass5> >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that classes that use virtual inheritance, but does not
// have any virtual functions are detected as non-polymorphic.
TEST(Test_IsPolymorphic, VirtualInheritanceDoesNotMakeClassesPolymorphic)
{
ASSERT_FALSE(IsPolymorphic< VirtualInhLeft >::value);
ASSERT_FALSE(IsPolymorphic< VirtualInhRight >::value);
ASSERT_FALSE(IsPolymorphic< VirtualInhBottom >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that classes that have virtual functions, but use virtual
// inheritance still are polymorphic.
TEST(Test_IsPolymorphic, VirtualInheritanceDoesNotExcludePolymorphism)
{
ASSERT_TRUE(IsPolymorphic< VirtualInhExtraL >::value);
ASSERT_TRUE(IsPolymorphic< VirtualInhExtraR >::value);
ASSERT_TRUE(IsPolymorphic< VirtualInhExtraX >::value);
}
<commit_msg>-: Fixed: infinite recursion in testAlignmentIssues(ClassOfSize<n> const &) under GCC<commit_after>// Copyright (c) 2010 Nickolas Pohilets
//
// This file is a part of the unit test suit for the CppEvents library.
//
// 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 <Cpp/Events/AbstractObjectRef.hpp>
#include "TestClasses.hpp"
#include <gtest/gtest.h>
using Cpp::Private::Events::IsPolymorphic;
////////////////////////////////////////////////////////////////////////////////
// For checking polymorphy special template class is derived from class being tested.
// This potentially may cause compilation problems if some special members of base class are inaccessible.
// This test is designed for detecting these problems. Test is passed if it compiles.
TEST(Test_IsPolymorphic, Compilability)
{
bool const b = IsPolymorphic<ClassWithUndefinedPrivateCtorAndDtor>::value;
(void)b;
}
////////////////////////////////////////////////////////////////////////////////
// Class alignment may possibly cause false detection of polymorphic classes.
// This test is designed for detecting them.
namespace {
template<int n> void doTestAlignmentIssues(ClassOfSize<n> const & x)
{
ASSERT_FALSE(IsPolymorphic< ClassOfSize<n> >::value);
}
void testAlignmentIssues(ClassOfSize<0> const & x)
{
doTestAlignmentIssues(x);
}
template<int n> void testAlignmentIssues(ClassOfSize<n> const & x)
{
doTestAlignmentIssues(x);
testAlignmentIssues(ClassOfSize<n-1>());
}
}
TEST(Test_IsPolymorphic, AlignmentIssues)
{
testAlignmentIssues(ClassOfSize< sizeof(void*) * 2 >());
}
////////////////////////////////////////////////////////////////////////////////
// This test checks classes that are naturally non-polymorphic.
// The TestAlignmentIssues does the same but does it better.
// Thus this test is not much useful but let it be.
TEST(Test_IsPolymorphic, NaturallyNonPolymorphic)
{
ASSERT_FALSE(IsPolymorphic< NonVirtualClass1 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass2_1 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass3_1 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass4_2_3 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass2 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass3 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass4 >::value);
ASSERT_FALSE(IsPolymorphic< NonVirtualClass5 >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that all naturally polymorphic classes are detected as polymorphic.
TEST(Test_IsPolymorphic, NaturallyPolymorphic)
{
//This class are naturally polymorphic
ASSERT_TRUE(IsPolymorphic< VirtualByDestructor >::value);
ASSERT_TRUE(IsPolymorphic< VirtualByFunction >::value);
ASSERT_TRUE(IsPolymorphic< VirtualByPureFunction >::value);
ASSERT_TRUE(IsPolymorphic< VirtualBaseClass >::value);
ASSERT_TRUE(IsPolymorphic< VirtualDerivedClass1 >::value);
ASSERT_TRUE(IsPolymorphic< VirtualDerivedClass2 >::value);
ASSERT_TRUE(IsPolymorphic< VirtualCommonDerived >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that classes that have non-virtual hierarchy root and have
// added virtuality later in the hierarchy tree are detected as polymorphic.
TEST(Test_IsPolymorphic, Polymorphized)
{
//This classes
ASSERT_TRUE(IsPolymorphic< ClassThatAddsVirtuality1 >::value);
ASSERT_TRUE(IsPolymorphic< ClassThatAddsVirtuality2 >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass1> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass2_1> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass3_1> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass4_2_3> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass2> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass3> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass4> >::value);
ASSERT_TRUE(IsPolymorphic< Virtualizer<NonVirtualClass5> >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that classes that use virtual inheritance, but does not
// have any virtual functions are detected as non-polymorphic.
TEST(Test_IsPolymorphic, VirtualInheritanceDoesNotMakeClassesPolymorphic)
{
ASSERT_FALSE(IsPolymorphic< VirtualInhLeft >::value);
ASSERT_FALSE(IsPolymorphic< VirtualInhRight >::value);
ASSERT_FALSE(IsPolymorphic< VirtualInhBottom >::value);
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that classes that have virtual functions, but use virtual
// inheritance still are polymorphic.
TEST(Test_IsPolymorphic, VirtualInheritanceDoesNotExcludePolymorphism)
{
ASSERT_TRUE(IsPolymorphic< VirtualInhExtraL >::value);
ASSERT_TRUE(IsPolymorphic< VirtualInhExtraR >::value);
ASSERT_TRUE(IsPolymorphic< VirtualInhExtraX >::value);
}
<|endoftext|> |
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif
#include "vvdebugmsg.h"
#include "vvinttypes.h"
#include "vvmulticast.h"
#include "vvsocketmonitor.h"
#ifdef HAVE_NORM
#include <normApi.h>
#include <stdlib.h>
#include <sys/select.h>
#endif
vvMulticast::vvMulticast(const char* addr, const ushort port, const MulticastType type)
: _type(type)
{
#ifdef HAVE_NORM
_instance = NormCreateInstance();
_session = NormCreateSession(_instance, addr, port, NORM_NODE_ANY);
NormSetCongestionControl(_session, true);
if(VV_SENDER == type)
{
NormSessionId sessionId = (NormSessionId)rand();
// TODO: Adjust these numbers depending on the used network topology
NormStartSender(_session, sessionId, 1024*1024, 1400, 64, 16);
NormSetTxSocketBuffer(_session, 512000);
}
else if(VV_RECEIVER == type)
{
NormStartReceiver(_session, 1024*1024);
NormDescriptor normDesc = NormGetDescriptor(_instance);
_normSocket = new vvSocket(normDesc, vvSocket::VV_UDP);
}
#else
(void)addr;
(void)port;
#endif
}
vvMulticast::~vvMulticast()
{
#ifdef HAVE_NORM
if(VV_SENDER == _type)
{
NormStopSender(_session);
}
else if(VV_RECEIVER == _type)
{
NormStopReceiver(_session);
delete _normSocket;
}
NormDestroySession(_session);
NormDestroyInstance(_instance);
#endif
}
ssize_t vvMulticast::write(const uchar* bytes, const uint size, double timeout)
{
vvDebugMsg::msg(3, "vvMulticast::write()");
#ifdef HAVE_NORM
_object = NormDataEnqueue(_session, (char*)bytes, size);
if(NORM_OBJECT_INVALID ==_object)
{
vvDebugMsg::msg(2, "vvMulticast::write(): Norm Object is invalid!");
return false;
}
NormDescriptor normDesc = NormGetDescriptor(_instance);
vvSocketMonitor* monitor = new vvSocketMonitor;
std::vector<vvSocket*> sock;
sock.push_back(new vvSocket(normDesc, vvSocket::VV_UDP));
monitor->setReadFds(sock);
vvSocket* ready;
NormEvent theEvent;
while(true)
{
ready = monitor->wait(&timeout);
if(NULL == ready)
{
vvDebugMsg::msg(2, "vvMulticast::write() error or timeout reached!");
return 0;
}
else
{
NormGetNextEvent(_instance, &theEvent);
switch(theEvent.type)
{
case NORM_CC_ACTIVE:
vvDebugMsg::msg(3, "vvMulticast::write() NORM_CC_ACTIVE: transmission still active");
break;
case NORM_TX_FLUSH_COMPLETED:
case NORM_LOCAL_SENDER_CLOSED:
case NORM_TX_OBJECT_SENT:
vvDebugMsg::msg(3, "vvMulticast::write() NORM_TX_FLUSH_COMPLETED: transfer completed.");
return NormObjectGetSize(theEvent.object) - NormObjectGetBytesPending(theEvent.object);
break;
default:
{
std::string eventmsg = std::string("vvMulticast::write() Norm-Event: ");
eventmsg += theEvent.type;
vvDebugMsg::msg(3, eventmsg.c_str());
break;
}
}
}
}
#else
(void)bytes;
(void)size;
(void)timeout;
return -1;
#endif
}
ssize_t vvMulticast::read(const uint size, uchar*& data, double timeout)
{
vvDebugMsg::msg(3, "vvMulticast::read()");
#ifdef HAVE_NORM
vvSocketMonitor monitor;
std::vector<vvSocket*> sock;
sock.push_back(_normSocket);
monitor.setReadFds(sock);
NormEvent theEvent;
uint bytesReceived = 0;
bool keepGoing = true;
do
{
vvSocket* ready = monitor.wait(&timeout);
if(NULL == ready)
{
vvDebugMsg::msg(2, "vvMulticast::read() error or timeout reached!");
return 0;
}
else
{
NormGetNextEvent(_instance, &theEvent);
switch(theEvent.type)
{
case NORM_RX_OBJECT_UPDATED:
vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_UPDATED: the identified receive object has newly received data content.");
bytesReceived = NormObjectGetSize(theEvent.object) - NormObjectGetBytesPending(theEvent.object);
break;
case NORM_RX_OBJECT_COMPLETED:
vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_COMPLETED: transfer completed.");
bytesReceived = NormObjectGetSize(theEvent.object) - NormObjectGetBytesPending(theEvent.object);
keepGoing = false;
break;
case NORM_RX_OBJECT_ABORTED:
vvDebugMsg::msg(2, "vvMulticast::read() NORM_RX_OBJECT_ABORTED: transfer incomplete!");
return -1;
break;
default:
{
std::string eventmsg = std::string("vvMulticast::read() Norm-Event: ");
eventmsg += theEvent.type;
std::cerr << theEvent.type << std::endl;
vvDebugMsg::msg(3, eventmsg.c_str());
break;
}
}
}
if(bytesReceived >= size) keepGoing = false;
}
while((0.0 < timeout || -1.0 == timeout) && keepGoing);
data = (uchar*)NormDataDetachData(theEvent.object);
return bytesReceived;
#else
(void)size;
(void)data;
(void)timeout;
return -1;
#endif
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>remove debug-code<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif
#include "vvdebugmsg.h"
#include "vvinttypes.h"
#include "vvmulticast.h"
#include "vvsocketmonitor.h"
#ifdef HAVE_NORM
#include <normApi.h>
#include <stdlib.h>
#include <sys/select.h>
#endif
vvMulticast::vvMulticast(const char* addr, const ushort port, const MulticastType type)
: _type(type)
{
#ifdef HAVE_NORM
_instance = NormCreateInstance();
_session = NormCreateSession(_instance, addr, port, NORM_NODE_ANY);
NormSetCongestionControl(_session, true);
if(VV_SENDER == type)
{
NormSessionId sessionId = (NormSessionId)rand();
// TODO: Adjust these numbers depending on the used network topology
NormStartSender(_session, sessionId, 1024*1024, 1400, 64, 16);
NormSetTxSocketBuffer(_session, 512000);
}
else if(VV_RECEIVER == type)
{
NormStartReceiver(_session, 1024*1024);
NormDescriptor normDesc = NormGetDescriptor(_instance);
_normSocket = new vvSocket(normDesc, vvSocket::VV_UDP);
}
#else
(void)addr;
(void)port;
#endif
}
vvMulticast::~vvMulticast()
{
#ifdef HAVE_NORM
if(VV_SENDER == _type)
{
NormStopSender(_session);
}
else if(VV_RECEIVER == _type)
{
NormStopReceiver(_session);
delete _normSocket;
}
NormDestroySession(_session);
NormDestroyInstance(_instance);
#endif
}
ssize_t vvMulticast::write(const uchar* bytes, const uint size, double timeout)
{
vvDebugMsg::msg(3, "vvMulticast::write()");
#ifdef HAVE_NORM
_object = NormDataEnqueue(_session, (char*)bytes, size);
if(NORM_OBJECT_INVALID ==_object)
{
vvDebugMsg::msg(2, "vvMulticast::write(): Norm Object is invalid!");
return false;
}
NormDescriptor normDesc = NormGetDescriptor(_instance);
vvSocketMonitor* monitor = new vvSocketMonitor;
std::vector<vvSocket*> sock;
sock.push_back(new vvSocket(normDesc, vvSocket::VV_UDP));
monitor->setReadFds(sock);
vvSocket* ready;
NormEvent theEvent;
while(true)
{
ready = monitor->wait(&timeout);
if(NULL == ready)
{
vvDebugMsg::msg(2, "vvMulticast::write() error or timeout reached!");
return 0;
}
else
{
NormGetNextEvent(_instance, &theEvent);
switch(theEvent.type)
{
case NORM_CC_ACTIVE:
vvDebugMsg::msg(3, "vvMulticast::write() NORM_CC_ACTIVE: transmission still active");
break;
case NORM_TX_FLUSH_COMPLETED:
case NORM_LOCAL_SENDER_CLOSED:
case NORM_TX_OBJECT_SENT:
vvDebugMsg::msg(3, "vvMulticast::write() NORM_TX_FLUSH_COMPLETED: transfer completed.");
return NormObjectGetSize(theEvent.object) - NormObjectGetBytesPending(theEvent.object);
break;
default:
{
std::string eventmsg = std::string("vvMulticast::write() Norm-Event: ");
eventmsg += theEvent.type;
vvDebugMsg::msg(3, eventmsg.c_str());
break;
}
}
}
}
#else
(void)bytes;
(void)size;
(void)timeout;
return -1;
#endif
}
ssize_t vvMulticast::read(const uint size, uchar*& data, double timeout)
{
vvDebugMsg::msg(3, "vvMulticast::read()");
#ifdef HAVE_NORM
vvSocketMonitor monitor;
std::vector<vvSocket*> sock;
sock.push_back(_normSocket);
monitor.setReadFds(sock);
NormEvent theEvent;
uint bytesReceived = 0;
bool keepGoing = true;
do
{
vvSocket* ready = monitor.wait(&timeout);
if(NULL == ready)
{
vvDebugMsg::msg(2, "vvMulticast::read() error or timeout reached!");
return 0;
}
else
{
NormGetNextEvent(_instance, &theEvent);
switch(theEvent.type)
{
case NORM_RX_OBJECT_UPDATED:
vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_UPDATED: the identified receive object has newly received data content.");
bytesReceived = NormObjectGetSize(theEvent.object) - NormObjectGetBytesPending(theEvent.object);
break;
case NORM_RX_OBJECT_COMPLETED:
vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_COMPLETED: transfer completed.");
bytesReceived = NormObjectGetSize(theEvent.object) - NormObjectGetBytesPending(theEvent.object);
keepGoing = false;
break;
case NORM_RX_OBJECT_ABORTED:
vvDebugMsg::msg(2, "vvMulticast::read() NORM_RX_OBJECT_ABORTED: transfer incomplete!");
return -1;
break;
default:
{
std::string eventmsg = std::string("vvMulticast::read() Norm-Event: ");
eventmsg += theEvent.type;
vvDebugMsg::msg(3, eventmsg.c_str());
break;
}
}
}
if(bytesReceived >= size) keepGoing = false;
}
while((0.0 < timeout || -1.0 == timeout) && keepGoing);
data = (uchar*)NormDataDetachData(theEvent.object);
return bytesReceived;
#else
(void)size;
(void)data;
(void)timeout;
return -1;
#endif
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3226
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3226 to 3227<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3227
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3303
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3303 to 3304<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3304
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3389
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3389 to 3390<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3390
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3186
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3186 to 3187<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3187
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: ManifestImport.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#include <ManifestImport.hxx>
#include <ManifestDefines.hxx>
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star;
using namespace rtl;
using namespace std;
ManifestImport::ManifestImport( vector < Sequence < PropertyValue > > & rNewManVector )
: nNumProperty (0)
, bIgnoreEncryptData ( sal_False )
, rManVector ( rNewManVector )
, sFileEntryElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) )
, sManifestElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) )
, sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) )
, sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) )
, sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) )
, sCdataAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) )
, sMediaTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) )
, sFullPathAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) )
, sSizeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) )
, sSaltAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) )
, sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) )
, sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) )
, sAlgorithmNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) )
, sKeyDerivationNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) )
, sChecksumAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM ) )
, sChecksumTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) )
, sFullPathProperty ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) )
, sMediaTypeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) )
, sIterationCountProperty ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) )
, sSaltProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) )
, sInitialisationVectorProperty ( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) )
, sSizeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) )
, sDigestProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) )
, sWhiteSpace ( RTL_CONSTASCII_USTRINGPARAM ( " " ) )
, sBlowfish ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) )
, sPBKDF2 ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) )
, sChecksumType ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) )
{
}
ManifestImport::~ManifestImport (void )
{
}
void SAL_CALL ManifestImport::startDocument( )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::endDocument( )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
throw(xml::sax::SAXException, uno::RuntimeException)
{
if (aName == sFileEntryElement)
{
aStack.push( e_FileEntry );
aSequence.realloc ( 7 ); // Can have at most 6 entries (currently, will realloc to actual number in endElement)
// Put full-path property first for MBA
aSequence[nNumProperty].Name = sFullPathProperty;
aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sFullPathAttribute );
aSequence[nNumProperty].Name = sMediaTypeProperty;
aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sMediaTypeAttribute );
OUString sSize = xAttribs->getValueByName ( sSizeAttribute );
if (sSize.getLength())
{
sal_Int32 nSize;
nSize = sSize.toInt32();
aSequence[nNumProperty].Name = sSizeProperty;
aSequence[nNumProperty++].Value <<= nSize;
}
}
else if (!aStack.empty())
{
if (aStack.top() == e_FileEntry && aName == sEncryptionDataElement)
{
// If this element exists, then this stream is encrypted and we need
// to store the initialisation vector, salt and iteration count used
aStack.push (e_EncryptionData );
OUString aString = xAttribs->getValueByName ( sChecksumTypeAttribute );
if (aString == sChecksumType && !bIgnoreEncryptData)
{
aString = xAttribs->getValueByName ( sChecksumAttribute );
Sequence < sal_uInt8 > aDecodeBuffer;
Base64Codec::decodeBase64 (aDecodeBuffer, aString);
aSequence[nNumProperty].Name = sDigestProperty;
aSequence[nNumProperty++].Value <<= aDecodeBuffer;
}
}
else if (aStack.top() == e_EncryptionData && aName == sAlgorithmElement)
{
aStack.push (e_Algorithm);
OUString aString = xAttribs->getValueByName ( sAlgorithmNameAttribute );
if (aString == sBlowfish && !bIgnoreEncryptData)
{
aString = xAttribs->getValueByName ( sInitialisationVectorAttribute );
Sequence < sal_uInt8 > aDecodeBuffer;
Base64Codec::decodeBase64 (aDecodeBuffer, aString);
aSequence[nNumProperty].Name = sInitialisationVectorProperty;
aSequence[nNumProperty++].Value <<= aDecodeBuffer;
}
else
// If we don't recognise the algorithm, then the key derivation info
// is useless to us
bIgnoreEncryptData = sal_True;
}
else if (aStack.top() == e_EncryptionData && aName == sKeyDerivationElement)
{
aStack.push (e_KeyDerivation);
OUString aString = xAttribs->getValueByName ( sKeyDerivationNameAttribute );
if ( aString == sPBKDF2 && !bIgnoreEncryptData )
{
aString = xAttribs->getValueByName ( sSaltAttribute );
Sequence < sal_uInt8 > aDecodeBuffer;
Base64Codec::decodeBase64 (aDecodeBuffer, aString);
aSequence[nNumProperty].Name = sSaltProperty;
aSequence[nNumProperty++].Value <<= aDecodeBuffer;
aString = xAttribs->getValueByName ( sIterationCountAttribute );
aSequence[nNumProperty].Name = sIterationCountProperty;
aSequence[nNumProperty++].Value <<= aString.toInt32();
}
else
// If we don't recognise the key derivation technique, then the
// algorithm info is useless to us
bIgnoreEncryptData = sal_True;
}
}
}
void SAL_CALL ManifestImport::endElement( const OUString& /*aName*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
if ( !aStack.empty() )
{
if (aStack.top() == e_FileEntry)
{
aSequence.realloc ( nNumProperty );
bIgnoreEncryptData = sal_False;
rManVector.push_back ( aSequence );
nNumProperty = 0;
}
aStack.pop();
}
}
void SAL_CALL ManifestImport::characters( const OUString& /*aChars*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& /*aWhitespaces*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::processingInstruction( const OUString& /*aTarget*/, const OUString& /*aData*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
<commit_msg>INTEGRATION: CWS jl93 (1.10.58); FILE MERGED 2008/05/06 10:46:23 jl 1.10.58.3: #i86651# wrong order of initialization of members in constructor 2008/05/05 13:28:24 jl 1.10.58.2: RESYNC: (1.10-1.11); FILE MERGED 2008/04/08 15:43:27 mav 1.10.58.1: #i86651# add Version property<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: ManifestImport.cxx,v $
* $Revision: 1.12 $
*
* 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_package.hxx"
#include <ManifestImport.hxx>
#include <ManifestDefines.hxx>
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star;
using namespace rtl;
using namespace std;
ManifestImport::ManifestImport( vector < Sequence < PropertyValue > > & rNewManVector )
: nNumProperty (0)
, bIgnoreEncryptData ( sal_False )
, rManVector ( rNewManVector )
, sFileEntryElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) )
, sManifestElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) )
, sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) )
, sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) )
, sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) )
, sCdataAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) )
, sMediaTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) )
, sVersionAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_VERSION ) )
, sFullPathAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) )
, sSizeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) )
, sSaltAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) )
, sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) )
, sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) )
, sAlgorithmNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) )
, sKeyDerivationNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) )
, sChecksumAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM ) )
, sChecksumTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) )
, sFullPathProperty ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) )
, sMediaTypeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) )
, sVersionProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Version" ) )
, sIterationCountProperty ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) )
, sSaltProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) )
, sInitialisationVectorProperty ( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) )
, sSizeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) )
, sDigestProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) )
, sWhiteSpace ( RTL_CONSTASCII_USTRINGPARAM ( " " ) )
, sBlowfish ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) )
, sPBKDF2 ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) )
, sChecksumType ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) )
{
}
ManifestImport::~ManifestImport (void )
{
}
void SAL_CALL ManifestImport::startDocument( )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::endDocument( )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
throw(xml::sax::SAXException, uno::RuntimeException)
{
if (aName == sFileEntryElement)
{
aStack.push( e_FileEntry );
aSequence.realloc ( PKG_SIZE_ENCR_MNFST );
// Put full-path property first for MBA
aSequence[nNumProperty].Name = sFullPathProperty;
aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sFullPathAttribute );
aSequence[nNumProperty].Name = sMediaTypeProperty;
aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sMediaTypeAttribute );
OUString sVersion = xAttribs->getValueByName ( sVersionAttribute );
if ( sVersion.getLength() )
{
aSequence[nNumProperty].Name = sVersionProperty;
aSequence[nNumProperty++].Value <<= sVersion;
}
OUString sSize = xAttribs->getValueByName ( sSizeAttribute );
if (sSize.getLength())
{
sal_Int32 nSize;
nSize = sSize.toInt32();
aSequence[nNumProperty].Name = sSizeProperty;
aSequence[nNumProperty++].Value <<= nSize;
}
}
else if (!aStack.empty())
{
if (aStack.top() == e_FileEntry && aName == sEncryptionDataElement)
{
// If this element exists, then this stream is encrypted and we need
// to store the initialisation vector, salt and iteration count used
aStack.push (e_EncryptionData );
OUString aString = xAttribs->getValueByName ( sChecksumTypeAttribute );
if (aString == sChecksumType && !bIgnoreEncryptData)
{
aString = xAttribs->getValueByName ( sChecksumAttribute );
Sequence < sal_uInt8 > aDecodeBuffer;
Base64Codec::decodeBase64 (aDecodeBuffer, aString);
aSequence[nNumProperty].Name = sDigestProperty;
aSequence[nNumProperty++].Value <<= aDecodeBuffer;
}
}
else if (aStack.top() == e_EncryptionData && aName == sAlgorithmElement)
{
aStack.push (e_Algorithm);
OUString aString = xAttribs->getValueByName ( sAlgorithmNameAttribute );
if (aString == sBlowfish && !bIgnoreEncryptData)
{
aString = xAttribs->getValueByName ( sInitialisationVectorAttribute );
Sequence < sal_uInt8 > aDecodeBuffer;
Base64Codec::decodeBase64 (aDecodeBuffer, aString);
aSequence[nNumProperty].Name = sInitialisationVectorProperty;
aSequence[nNumProperty++].Value <<= aDecodeBuffer;
}
else
// If we don't recognise the algorithm, then the key derivation info
// is useless to us
bIgnoreEncryptData = sal_True;
}
else if (aStack.top() == e_EncryptionData && aName == sKeyDerivationElement)
{
aStack.push (e_KeyDerivation);
OUString aString = xAttribs->getValueByName ( sKeyDerivationNameAttribute );
if ( aString == sPBKDF2 && !bIgnoreEncryptData )
{
aString = xAttribs->getValueByName ( sSaltAttribute );
Sequence < sal_uInt8 > aDecodeBuffer;
Base64Codec::decodeBase64 (aDecodeBuffer, aString);
aSequence[nNumProperty].Name = sSaltProperty;
aSequence[nNumProperty++].Value <<= aDecodeBuffer;
aString = xAttribs->getValueByName ( sIterationCountAttribute );
aSequence[nNumProperty].Name = sIterationCountProperty;
aSequence[nNumProperty++].Value <<= aString.toInt32();
}
else
// If we don't recognise the key derivation technique, then the
// algorithm info is useless to us
bIgnoreEncryptData = sal_True;
}
}
}
void SAL_CALL ManifestImport::endElement( const OUString& /*aName*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
if ( !aStack.empty() )
{
if (aStack.top() == e_FileEntry)
{
aSequence.realloc ( nNumProperty );
bIgnoreEncryptData = sal_False;
rManVector.push_back ( aSequence );
nNumProperty = 0;
}
aStack.pop();
}
}
void SAL_CALL ManifestImport::characters( const OUString& /*aChars*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& /*aWhitespaces*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::processingInstruction( const OUString& /*aTarget*/, const OUString& /*aData*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ )
throw(xml::sax::SAXException, uno::RuntimeException)
{
}
<|endoftext|> |
<commit_before>/***************************************************************************
connectionstatusplugin.cpp
-------------------
begin : 26th Oct 2002
copyright : (C) 2002-2003 Chris Howells
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; version 2 of the License. *
* *
***************************************************************************/
#include <kdebug.h>
#include <kgenericfactory.h>
#include <qtimer.h>
#include <kprocess.h>
#include "connectionstatusplugin.h"
#include "kopeteaccountmanager.h"
K_EXPORT_COMPONENT_FACTORY(kopete_connectionstatus, KGenericFactory<ConnectionStatusPlugin>);
ConnectionStatusPlugin::ConnectionStatusPlugin(QObject *parent, const char *name, const QStringList& /* args */ ) : KopetePlugin(parent, name)
{
kdDebug(14301) << "ConnectionStatusPlugin::ConnectionStatusPlugin()" << endl;
qtTimer = new QTimer();
connect(qtTimer, SIGNAL(timeout()), this,
SLOT(slotCheckStatus()) );
qtTimer->start(60000);
kpIfconfig = new KProcess;
connect(kpIfconfig, SIGNAL(receivedStdout(KProcess *, char *, int)),
this, SLOT(slotProcessStdout(KProcess *, char *, int)));
m_boolPluginConnected = false;
}
ConnectionStatusPlugin::~ConnectionStatusPlugin()
{
kdDebug(14301) << "ConnectionStatusPlugin::~ConnectionStatusPlugin()" << endl;
delete qtTimer;
delete kpIfconfig;
}
void ConnectionStatusPlugin::slotCheckStatus()
{
/* Use KProcess to run netstat -r. We'll then parse the output of
* netstat -r in slotProcessStdout() to see if it mentions the
* default gateway. If so, we're connected, if not, we're offline */
kdDebug(14301) << "ConnectionStatusPlugin::checkStatus()" << endl;
*kpIfconfig << "netstat" << "-r";
kpIfconfig->start(KProcess::DontCare, KProcess::Stdout);
}
void ConnectionStatusPlugin::slotProcessStdout(KProcess *, char *buffer, int buflen)
{
// Look for a default gateway
kdDebug(14301) << "ConnectionStatusPlugin::slotProcessStdout()" << endl;
QString qsBuffer = QString::fromLatin1(buffer, buflen);
//kdDebug(14301) << qsBuffer << endl;
setConnectedStatus(qsBuffer.contains("default"));
}
void ConnectionStatusPlugin::setConnectedStatus(bool connected)
{
/* We have to handle a few cases here. First is the machine is connected, and the plugin thinks
* we're connected. Then we don't do anything. Next, we can have machine connected, but plugin thinks
* we're disconnected. Also, machine disconnected, plugin disconnected -- we
* don't do anything. Finally, we can have the machine disconnected, and the plugin thinks we're
* connected. This mechanism is required so that we don't keep calling the connect/disconnect functions
* constantly.
*/
kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus()" << endl;
if (connected && !m_boolPluginConnected) // the machine is connected and plugin thinks we're disconnected
{
kdDebug(14301) << "Setting m_boolPluginConnected to true" << endl;
m_boolPluginConnected = true;
kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're connected" << endl;
KopeteAccountManager::manager()->connectAll();
}
else
if (!connected && m_boolPluginConnected) // the machine isn't connected and plugin thinks we're connected
{
kdDebug(14301) << "Setting m_boolPluginConnected to false" << endl;
m_boolPluginConnected = false;
kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're offline" << endl;
KopeteAccountManager::manager()->disconnectAll();
}
}
#include "connectionstatusplugin.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Correct a problem which seems to have been caused by changes to KProcess. Don't accumulate '-r' options eventually meaning that netstat -r -r -r -r -r etc is called.<commit_after>/***************************************************************************
connectionstatusplugin.cpp
-------------------
begin : 26th Oct 2002
copyright : (C) 2002-2003 Chris Howells
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; version 2 of the License. *
* *
***************************************************************************/
#include <kdebug.h>
#include <kgenericfactory.h>
#include <qtimer.h>
#include <kprocess.h>
#include "connectionstatusplugin.h"
#include "kopeteaccountmanager.h"
K_EXPORT_COMPONENT_FACTORY(kopete_connectionstatus, KGenericFactory<ConnectionStatusPlugin>);
ConnectionStatusPlugin::ConnectionStatusPlugin(QObject *parent, const char *name, const QStringList& /* args */ ) : KopetePlugin(parent, name)
{
kdDebug(14301) << "ConnectionStatusPlugin::ConnectionStatusPlugin()" << endl;
qtTimer = new QTimer();
connect(qtTimer, SIGNAL(timeout()), this,
SLOT(slotCheckStatus()) );
qtTimer->start(60000);
kpIfconfig = new KProcess;
*kpIfconfig << "netstat" << "-r";
connect(kpIfconfig, SIGNAL(receivedStdout(KProcess *, char *, int)),
this, SLOT(slotProcessStdout(KProcess *, char *, int)));
m_boolPluginConnected = false;
}
ConnectionStatusPlugin::~ConnectionStatusPlugin()
{
kdDebug(14301) << "ConnectionStatusPlugin::~ConnectionStatusPlugin()" << endl;
delete qtTimer;
delete kpIfconfig;
}
void ConnectionStatusPlugin::slotCheckStatus()
{
/* Use KProcess to run netstat -r. We'll then parse the output of
* netstat -r in slotProcessStdout() to see if it mentions the
* default gateway. If so, we're connected, if not, we're offline */
kdDebug(14301) << "ConnectionStatusPlugin::checkStatus()" << endl;
kpIfconfig->start(KProcess::DontCare, KProcess::Stdout);
}
void ConnectionStatusPlugin::slotProcessStdout(KProcess *, char *buffer, int buflen)
{
// Look for a default gateway
kdDebug(14301) << "ConnectionStatusPlugin::slotProcessStdout()" << endl;
QString qsBuffer = QString::fromLatin1(buffer, buflen);
//kdDebug(14301) << qsBuffer << endl;
setConnectedStatus(qsBuffer.contains("default"));
}
void ConnectionStatusPlugin::setConnectedStatus(bool connected)
{
/* We have to handle a few cases here. First is the machine is connected, and the plugin thinks
* we're connected. Then we don't do anything. Next, we can have machine connected, but plugin thinks
* we're disconnected. Also, machine disconnected, plugin disconnected -- we
* don't do anything. Finally, we can have the machine disconnected, and the plugin thinks we're
* connected. This mechanism is required so that we don't keep calling the connect/disconnect functions
* constantly.
*/
kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus()" << endl;
if (connected && !m_boolPluginConnected) // the machine is connected and plugin thinks we're disconnected
{
kdDebug(14301) << "Setting m_boolPluginConnected to true" << endl;
m_boolPluginConnected = true;
kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're connected" << endl;
KopeteAccountManager::manager()->connectAll();
}
else
if (!connected && m_boolPluginConnected) // the machine isn't connected and plugin thinks we're connected
{
kdDebug(14301) << "Setting m_boolPluginConnected to false" << endl;
m_boolPluginConnected = false;
kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're offline" << endl;
KopeteAccountManager::manager()->disconnectAll();
}
}
#include "connectionstatusplugin.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "formeditorgraphicsview.h"
#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>
#include <qmlanchors.h>
namespace QmlDesigner {
FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
QGraphicsView(parent)
{
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setResizeAnchor(QGraphicsView::AnchorViewCenter);
setCacheMode(QGraphicsView::CacheNone);
// setCacheMode(QGraphicsView::CacheBackground);
setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
setOptimizationFlags(QGraphicsView::DontSavePainterState);
// setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
setRenderHint(QPainter::Antialiasing, false);
setFrameShape(QFrame::NoFrame);
setAutoFillBackground(true);
setBackgroundRole(QPalette::Window);
const int checkerbordSize= 20;
QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
tilePainter.end();
setBackgroundBrush(tilePixmap);
viewport()->setMouseTracking(true);
}
void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
if (event->modifiers().testFlag(Qt::ControlModifier)) {
event->ignore();
} else {
QGraphicsView::wheelEvent(event);
}
}
void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseMoveEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseMoveEvent(mouseEvent);
delete mouseEvent;
}
// Keeps the feedback bubble within screen boundraries
int tx = qMin(width() - 114, qMax(16, event->pos().x() + 50));
int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
m_feedbackOriginPoint = QPoint(tx, ty);
}
void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::keyPressEvent(event);
}
void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
m_rootItemRect = rect;
qDebug() << __FUNCTION__ << m_rootItemRect;
}
QRectF FormEditorGraphicsView::rootItemRect() const
{
return m_rootItemRect;
}
void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseReleaseEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseReleaseEvent(mouseEvent);
delete mouseEvent;
}
m_feedbackOriginPoint = QPoint();
}
void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::leaveEvent(event);
}
static QPixmap createBubblePixmap()
{
QPixmap pixmap(124, 48);
pixmap.fill(Qt::transparent);
QPainter pmPainter(&pixmap);
pmPainter.setRenderHint(QPainter::Antialiasing);
pmPainter.setOpacity(0.85);
pmPainter.translate(0.5, 0.5);
pmPainter.setPen(Qt::NoPen);
pmPainter.setBrush(QColor(0, 0, 0, 40));
pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
gradient.setColorAt(0.0, QColor(70, 70, 70));
gradient.setColorAt(1.0, QColor(10, 10, 10));
pmPainter.setBrush(gradient);
pmPainter.setPen(QColor(60, 60, 60));
pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
pmPainter.setBrush(Qt::NoBrush);
pmPainter.setPen(QColor(255, 255, 255, 140));
pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
pmPainter.end();
return pixmap;
}
void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
if (!m_feedbackNode.isValid())
return;
if (m_feedbackOriginPoint.isNull())
return;
painter->save();
painter->resetTransform();
painter->translate(m_feedbackOriginPoint);
QColor defaultColor(Qt::white);
QColor changeColor("#9999ff");
QFont font;
font.setFamily("Helvetica");
font.setPixelSize(12);
painter->setFont(font);
if (m_bubblePixmap.isNull())
m_bubblePixmap = createBubblePixmap();
painter->drawPixmap(-13, -7, m_bubblePixmap);
if (m_beginXHasExpression) {
if(m_feedbackNode.hasBindingProperty("x"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginX != m_feedbackNode.instanceValue("x"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 13.0), QString("x:"));
painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());
if (m_beginYHasExpression) {
if(m_feedbackNode.hasBindingProperty("y"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginY != m_feedbackNode.instanceValue("y"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 13.0), QString("y:"));
painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());
if (m_beginWidthHasExpression) {
if(m_feedbackNode.hasBindingProperty("width"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginWidth != m_feedbackNode.instanceValue("width"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 29.0), QString("w:"));
painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());
if (m_beginHeightHasExpression) {
if(m_feedbackNode.hasBindingProperty("height"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginHeight != m_feedbackNode.instanceValue("height"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 29.0), QString("h:"));
painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());
if (m_parentNode != m_feedbackNode.instanceParent()) {
painter->setPen(changeColor);
painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));
}
painter->restore();
}
void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
if (node == m_feedbackNode)
return;
m_feedbackNode = node;
if (m_feedbackNode.isValid()) {
m_beginX = m_feedbackNode.instanceValue("x");
m_beginY = m_feedbackNode.instanceValue("y");
m_beginWidth = m_feedbackNode.instanceValue("width");
m_beginHeight = m_feedbackNode.instanceValue("height");
m_parentNode = m_feedbackNode.instanceParent();
m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
} else {
m_beginX = QVariant();
m_beginY = QVariant();
m_beginWidth = QVariant();
m_beginHeight = QVariant();
m_parentNode = QmlObjectNode();
m_beginLeftMargin = QVariant();
m_beginRightMargin = QVariant();
m_beginTopMargin = QVariant();
m_beginBottomMargin = QVariant();
m_beginXHasExpression = false;
m_beginYHasExpression = false;
m_beginWidthHasExpression = false;
m_beginHeightHasExpression = false;
}
}
void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect.intersected(rootItemRect()), backgroundBrush());
// paint rect around editable area
painter->setPen(Qt::black);
painter->drawRect( rootItemRect());
painter->restore();
}
} // namespace QmlDesigner
<commit_msg>QmlDesigner: Fix the formeditor background<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "formeditorgraphicsview.h"
#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>
#include <qmlanchors.h>
namespace QmlDesigner {
FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
QGraphicsView(parent)
{
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setResizeAnchor(QGraphicsView::AnchorViewCenter);
setCacheMode(QGraphicsView::CacheNone);
// setCacheMode(QGraphicsView::CacheBackground);
setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
setOptimizationFlags(QGraphicsView::DontSavePainterState);
// setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
setRenderHint(QPainter::Antialiasing, false);
setFrameShape(QFrame::NoFrame);
setAutoFillBackground(true);
setBackgroundRole(QPalette::Window);
const int checkerbordSize= 20;
QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
tilePainter.end();
setBackgroundBrush(tilePixmap);
viewport()->setMouseTracking(true);
}
void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
if (event->modifiers().testFlag(Qt::ControlModifier)) {
event->ignore();
} else {
QGraphicsView::wheelEvent(event);
}
}
void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseMoveEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseMoveEvent(mouseEvent);
delete mouseEvent;
}
// Keeps the feedback bubble within screen boundraries
int tx = qMin(width() - 114, qMax(16, event->pos().x() + 50));
int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
m_feedbackOriginPoint = QPoint(tx, ty);
}
void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::keyPressEvent(event);
}
void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
m_rootItemRect = rect;
update();
}
QRectF FormEditorGraphicsView::rootItemRect() const
{
return m_rootItemRect;
}
void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseReleaseEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseReleaseEvent(mouseEvent);
delete mouseEvent;
}
m_feedbackOriginPoint = QPoint();
}
void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::leaveEvent(event);
}
static QPixmap createBubblePixmap()
{
QPixmap pixmap(124, 48);
pixmap.fill(Qt::transparent);
QPainter pmPainter(&pixmap);
pmPainter.setRenderHint(QPainter::Antialiasing);
pmPainter.setOpacity(0.85);
pmPainter.translate(0.5, 0.5);
pmPainter.setPen(Qt::NoPen);
pmPainter.setBrush(QColor(0, 0, 0, 40));
pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
gradient.setColorAt(0.0, QColor(70, 70, 70));
gradient.setColorAt(1.0, QColor(10, 10, 10));
pmPainter.setBrush(gradient);
pmPainter.setPen(QColor(60, 60, 60));
pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
pmPainter.setBrush(Qt::NoBrush);
pmPainter.setPen(QColor(255, 255, 255, 140));
pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
pmPainter.end();
return pixmap;
}
void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
if (!m_feedbackNode.isValid())
return;
if (m_feedbackOriginPoint.isNull())
return;
painter->save();
painter->resetTransform();
painter->translate(m_feedbackOriginPoint);
QColor defaultColor(Qt::white);
QColor changeColor("#9999ff");
QFont font;
font.setFamily("Helvetica");
font.setPixelSize(12);
painter->setFont(font);
if (m_bubblePixmap.isNull())
m_bubblePixmap = createBubblePixmap();
painter->drawPixmap(-13, -7, m_bubblePixmap);
if (m_beginXHasExpression) {
if(m_feedbackNode.hasBindingProperty("x"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginX != m_feedbackNode.instanceValue("x"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 13.0), QString("x:"));
painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());
if (m_beginYHasExpression) {
if(m_feedbackNode.hasBindingProperty("y"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginY != m_feedbackNode.instanceValue("y"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 13.0), QString("y:"));
painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());
if (m_beginWidthHasExpression) {
if(m_feedbackNode.hasBindingProperty("width"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginWidth != m_feedbackNode.instanceValue("width"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 29.0), QString("w:"));
painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());
if (m_beginHeightHasExpression) {
if(m_feedbackNode.hasBindingProperty("height"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginHeight != m_feedbackNode.instanceValue("height"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 29.0), QString("h:"));
painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());
if (m_parentNode != m_feedbackNode.instanceParent()) {
painter->setPen(changeColor);
painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));
}
painter->restore();
}
void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
if (node == m_feedbackNode)
return;
m_feedbackNode = node;
if (m_feedbackNode.isValid()) {
m_beginX = m_feedbackNode.instanceValue("x");
m_beginY = m_feedbackNode.instanceValue("y");
m_beginWidth = m_feedbackNode.instanceValue("width");
m_beginHeight = m_feedbackNode.instanceValue("height");
m_parentNode = m_feedbackNode.instanceParent();
m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
} else {
m_beginX = QVariant();
m_beginY = QVariant();
m_beginWidth = QVariant();
m_beginHeight = QVariant();
m_parentNode = QmlObjectNode();
m_beginLeftMargin = QVariant();
m_beginRightMargin = QVariant();
m_beginTopMargin = QVariant();
m_beginBottomMargin = QVariant();
m_beginXHasExpression = false;
m_beginYHasExpression = false;
m_beginWidthHasExpression = false;
m_beginHeightHasExpression = false;
}
}
void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect.intersected(rootItemRect()), backgroundBrush());
// paint rect around editable area
painter->setPen(Qt::black);
painter->drawRect( rootItemRect());
painter->restore();
}
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>#include "pch.h"
#include "utils.h"
#include "ui/dial_button.h"
#include "ui/expanded_tab.h"
#include "utf8.h"
#if defined (WIN32)
#include <Rpc.h>
#elif defined (__ANDROID__) || defined (__EMSCRIPTEN__)
#include <uuidlib/uuid.h>
#else
#include <uuid/uuid.h>
#endif
std::string Utils::generateUUID( )
{
std::string s;
#ifdef WIN32
UUID uuid;
UuidCreate ( &uuid );
unsigned char * str;
UuidToStringA ( &uuid, &str );
s = ( const char* ) str;
RpcStringFreeA ( &str );
#else
uuid_t uuid;
uuid_generate_random ( uuid );
char str[37];
uuid_unparse ( uuid, str );
s = str;
#endif
return s;
}
const wchar_t * Utils::UTF8ToWCS(const char * str)
{
static std::wstring res;
res.clear();
utf8::unchecked::utf8to16(str, str + strlen(str), std::back_inserter(res));
return res.c_str();
}
const char * Utils::WCSToUTF8(const wchar_t * str)
{
static std::string res;
res.clear();
utf8::unchecked::utf16to8(str, str + wcslen(str), std::back_inserter(res));
return res.c_str();
}
const wchar_t * Utils::ANSIToWCS(const char * str)
{
static wchar_t result[2048];
wchar_t * o = result;
while( *str )
*o++ = *str++;
*o = 0;
return result;
}
const char * Utils::format(const char * fmt, ...)
{
static char results[16][2048];
static int resInd = 0;
char * result = results[resInd];
resInd = (resInd + 1) & 15;
va_list args;
va_start(args, fmt);
#ifdef WIN32
_vsnprintf(result, 2048, fmt, args);
#else
vsnprintf(result, 2048, fmt, args);
#endif
va_end(args);
return result;
}
const char * Utils::urlEncode(const char * src)
{
static std::string res[16];
static int resInd = 0;
std::string& result = res[resInd];
resInd = (resInd + 1) & 15;
result.clear();
static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int max = strlen(src);
for (int i = 0; i < max; i++, src++)
{
if (('0' <= *src && *src <= '9') ||
('A' <= *src && *src <= 'Z') ||
('a' <= *src && *src <= 'z') ||
(*src == '~' || *src == '-' || *src == '_' || *src == '.')
)
{
result.push_back(*src);
}
else
{
result.push_back('%');
result.push_back(hexmap[(unsigned char)(*src) >> 4]);
result.push_back(hexmap[*src & 0x0F]);
}
}
return result.c_str();
}
const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, const gameplay::Font * font, float fontSize, float characterSpacing)
{
static std::wstring result;
if (width <= 0.0f)
return L"";
float textw = 0, texth = 0;
font->measureText(text, fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);
if (textw < width)
return text;
result = text;
result.erase(result.end() - 1, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
do
{
result.erase(result.end() - 4, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
font->measureText(result.c_str(), fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);
} while (result.size() > 3 && textw >= width);
return result.c_str();
}
const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, float height, const gameplay::Font * font, float fontSize,
float characterSpacing, float lineSpacing)
{
static std::wstring result;
if (width <= 0.0f || height <= fontSize)
return L"";
gameplay::Rectangle clip(width, height);
gameplay::Rectangle out;
font->measureText(text, clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);
if (out.width < width && out.height < height)
return text;
result = text;
result.erase(result.end() - 1, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
do
{
result.erase(result.end() - 4, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
font->measureText(result.c_str(), clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);
} while (result.size() > 3 && (out.width >= width || out.height >= height));
return result.c_str();
}
void Utils::serializeString(gameplay::Stream * stream, const std::string& str)
{
int32_t size = static_cast<int32_t>(str.size());
stream->write(&size, sizeof(size), 1);
stream->write(str.c_str(), sizeof(char), size);
}
void Utils::deserializeString(gameplay::Stream * stream, std::string * str)
{
int32_t size = 0;
if (stream->read(&size, sizeof(size), 1) != 1)
return;
if (size < 0 || size > 65535)
return; // something wrong with data
char * buf = reinterpret_cast<char *>(alloca(sizeof(char)* (size + 1)));
if (buf)
{
stream->read(buf, sizeof(char), size);
buf[size] = '\0';
if (str)
{
str->clear();
*str = buf;
}
}
}
void Utils::scaleUIControl(gameplay::Control * control, float kx, float ky)
{
if (!control)
return;
// the actual scaling
if (!control->isXPercentage())
control->setX(control->getX() * kx);
if (!control->isYPercentage())
control->setY(control->getY() * ky);
if (!control->isWidthPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_WIDTH) == 0)
control->setWidth(control->getWidth() * kx);
if (!control->isHeightPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_HEIGHT) == 0)
control->setHeight(control->getHeight() * ky);
const gameplay::Theme::Border& border = control->getBorder();
const gameplay::Theme::Margin& margin = control->getMargin();
const gameplay::Theme::Padding& padding = control->getPadding();
control->setBorder(border.top * ky, border.bottom * ky, border.left * kx, border.right * kx);
control->setMargin(margin.top * ky, margin.bottom * ky, margin.left * kx, margin.right * kx);
control->setPadding(padding.top * ky, padding.bottom * ky, padding.left * kx, padding.right * kx);
control->setFontSize(ky * control->getFontSize());
control->setCharacterSpacing(ky * control->getCharacterSpacing());
control->setLineSpacing(ky * control->getLineSpacing());
if (strcmp(control->getTypeName(), "Slider") == 0)
static_cast<gameplay::Slider *>(control)->setScaleFactor(ky);
if (strcmp(control->getTypeName(), "ImageControl") == 0)
{
gameplay::ImageControl * image = static_cast< gameplay::ImageControl * >(control);
const gameplay::Rectangle& dstRegion = image->getRegionDst();
image->setRegionDst(dstRegion.x * kx, dstRegion.y * ky, dstRegion.width * kx, dstRegion.height * ky);
}
if (strcmp(control->getTypeName(), "DialButton") == 0)
{
DialButton * button = static_cast<DialButton *>(control);
button->setHeightCollapsed(ky * button->getHeightCollapsed());
button->setHeightExpanded(ky * button->getHeightExpanded());
}
if (strcmp(control->getTypeName(), "ExpandedTab") == 0)
{
ExpandedTab * tab = static_cast<ExpandedTab * >(control);
tab->setWidthMinimized(kx * tab->getWidthMinimized());
tab->setWidthMaximized(kx * tab->getWidthMaximized());
}
if (strcmp(control->getTypeName(), "RadioButton") == 0)
{
gameplay::RadioButton * button = static_cast<gameplay::RadioButton *>(control);
button->setIconScale(button->getIconScale() * ky);
}
if (strcmp(control->getTypeName(), "CheckBox") == 0)
{
gameplay::CheckBox * button = static_cast<gameplay::CheckBox *>(control);
button->setIconScale(button->getIconScale() * ky);
}
if (control->isContainer())
{
gameplay::Container * container = static_cast<gameplay::Container *>(control);
container->setScrollScale(container->getScrollScale() * ky);
const std::vector< gameplay::Control * >& children = container->getControls();
for (unsigned j = 0; j < children.size(); j++)
scaleUIControl(children[j], kx, ky);
}
}
void Utils::measureChildrenBounds(gameplay::Container * container, float * width, float * height)
{
// Calculate total width and height.
float totalWidth = 0.0f, totalHeight = 0.0f;
const std::vector<gameplay::Control*>& controls = container->getControls();
for (size_t i = 0, count = controls.size(); i < count; ++i)
{
gameplay::Control* control = controls[i];
if (!control->isVisible())
continue;
const gameplay::Rectangle& bounds = control->getBounds();
const gameplay::Theme::Margin& margin = control->getMargin();
float newWidth = bounds.x + bounds.width + margin.right;
if (newWidth > totalWidth)
totalWidth = newWidth;
float newHeight = bounds.y + bounds.height + margin.bottom;
if (newHeight > totalHeight)
totalHeight = newHeight;
}
if (width)
*width = totalWidth;
if (height)
*height = totalHeight;
}<commit_msg>make sure fonts always use integer sizes<commit_after>#include "pch.h"
#include "utils.h"
#include "ui/dial_button.h"
#include "ui/expanded_tab.h"
#include "utf8.h"
#if defined (WIN32)
#include <Rpc.h>
#elif defined (__ANDROID__) || defined (__EMSCRIPTEN__)
#include <uuidlib/uuid.h>
#else
#include <uuid/uuid.h>
#endif
std::string Utils::generateUUID( )
{
std::string s;
#ifdef WIN32
UUID uuid;
UuidCreate ( &uuid );
unsigned char * str;
UuidToStringA ( &uuid, &str );
s = ( const char* ) str;
RpcStringFreeA ( &str );
#else
uuid_t uuid;
uuid_generate_random ( uuid );
char str[37];
uuid_unparse ( uuid, str );
s = str;
#endif
return s;
}
const wchar_t * Utils::UTF8ToWCS(const char * str)
{
static std::wstring res;
res.clear();
utf8::unchecked::utf8to16(str, str + strlen(str), std::back_inserter(res));
return res.c_str();
}
const char * Utils::WCSToUTF8(const wchar_t * str)
{
static std::string res;
res.clear();
utf8::unchecked::utf16to8(str, str + wcslen(str), std::back_inserter(res));
return res.c_str();
}
const wchar_t * Utils::ANSIToWCS(const char * str)
{
static wchar_t result[2048];
wchar_t * o = result;
while( *str )
*o++ = *str++;
*o = 0;
return result;
}
const char * Utils::format(const char * fmt, ...)
{
static char results[16][2048];
static int resInd = 0;
char * result = results[resInd];
resInd = (resInd + 1) & 15;
va_list args;
va_start(args, fmt);
#ifdef WIN32
_vsnprintf(result, 2048, fmt, args);
#else
vsnprintf(result, 2048, fmt, args);
#endif
va_end(args);
return result;
}
const char * Utils::urlEncode(const char * src)
{
static std::string res[16];
static int resInd = 0;
std::string& result = res[resInd];
resInd = (resInd + 1) & 15;
result.clear();
static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int max = strlen(src);
for (int i = 0; i < max; i++, src++)
{
if (('0' <= *src && *src <= '9') ||
('A' <= *src && *src <= 'Z') ||
('a' <= *src && *src <= 'z') ||
(*src == '~' || *src == '-' || *src == '_' || *src == '.')
)
{
result.push_back(*src);
}
else
{
result.push_back('%');
result.push_back(hexmap[(unsigned char)(*src) >> 4]);
result.push_back(hexmap[*src & 0x0F]);
}
}
return result.c_str();
}
const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, const gameplay::Font * font, float fontSize, float characterSpacing)
{
static std::wstring result;
if (width <= 0.0f)
return L"";
float textw = 0, texth = 0;
font->measureText(text, fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);
if (textw < width)
return text;
result = text;
result.erase(result.end() - 1, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
do
{
result.erase(result.end() - 4, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
font->measureText(result.c_str(), fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);
} while (result.size() > 3 && textw >= width);
return result.c_str();
}
const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, float height, const gameplay::Font * font, float fontSize,
float characterSpacing, float lineSpacing)
{
static std::wstring result;
if (width <= 0.0f || height <= fontSize)
return L"";
gameplay::Rectangle clip(width, height);
gameplay::Rectangle out;
font->measureText(text, clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);
if (out.width < width && out.height < height)
return text;
result = text;
result.erase(result.end() - 1, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
do
{
result.erase(result.end() - 4, result.end());
result.push_back('.');
result.push_back('.');
result.push_back('.');
font->measureText(result.c_str(), clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);
} while (result.size() > 3 && (out.width >= width || out.height >= height));
return result.c_str();
}
void Utils::serializeString(gameplay::Stream * stream, const std::string& str)
{
int32_t size = static_cast<int32_t>(str.size());
stream->write(&size, sizeof(size), 1);
stream->write(str.c_str(), sizeof(char), size);
}
void Utils::deserializeString(gameplay::Stream * stream, std::string * str)
{
int32_t size = 0;
if (stream->read(&size, sizeof(size), 1) != 1)
return;
if (size < 0 || size > 65535)
return; // something wrong with data
char * buf = reinterpret_cast<char *>(alloca(sizeof(char)* (size + 1)));
if (buf)
{
stream->read(buf, sizeof(char), size);
buf[size] = '\0';
if (str)
{
str->clear();
*str = buf;
}
}
}
void Utils::scaleUIControl(gameplay::Control * control, float kx, float ky)
{
if (!control)
return;
// the actual scaling
if (!control->isXPercentage())
control->setX(control->getX() * kx);
if (!control->isYPercentage())
control->setY(control->getY() * ky);
if (!control->isWidthPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_WIDTH) == 0)
control->setWidth(control->getWidth() * kx);
if (!control->isHeightPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_HEIGHT) == 0)
control->setHeight(control->getHeight() * ky);
const gameplay::Theme::Border& border = control->getBorder();
const gameplay::Theme::Margin& margin = control->getMargin();
const gameplay::Theme::Padding& padding = control->getPadding();
control->setBorder(border.top * ky, border.bottom * ky, border.left * kx, border.right * kx);
control->setMargin(margin.top * ky, margin.bottom * ky, margin.left * kx, margin.right * kx);
control->setPadding(padding.top * ky, padding.bottom * ky, padding.left * kx, padding.right * kx);
control->setFontSize(roundf(ky * control->getFontSize()));
control->setCharacterSpacing(roundf(ky * control->getCharacterSpacing()));
control->setLineSpacing(roundf(ky * control->getLineSpacing()));
if (strcmp(control->getTypeName(), "Slider") == 0)
static_cast<gameplay::Slider *>(control)->setScaleFactor(ky);
if (strcmp(control->getTypeName(), "ImageControl") == 0)
{
gameplay::ImageControl * image = static_cast< gameplay::ImageControl * >(control);
const gameplay::Rectangle& dstRegion = image->getRegionDst();
image->setRegionDst(dstRegion.x * kx, dstRegion.y * ky, dstRegion.width * kx, dstRegion.height * ky);
}
if (strcmp(control->getTypeName(), "DialButton") == 0)
{
DialButton * button = static_cast<DialButton *>(control);
button->setHeightCollapsed(ky * button->getHeightCollapsed());
button->setHeightExpanded(ky * button->getHeightExpanded());
}
if (strcmp(control->getTypeName(), "ExpandedTab") == 0)
{
ExpandedTab * tab = static_cast<ExpandedTab * >(control);
tab->setWidthMinimized(kx * tab->getWidthMinimized());
tab->setWidthMaximized(kx * tab->getWidthMaximized());
}
if (strcmp(control->getTypeName(), "RadioButton") == 0)
{
gameplay::RadioButton * button = static_cast<gameplay::RadioButton *>(control);
button->setIconScale(button->getIconScale() * ky);
}
if (strcmp(control->getTypeName(), "CheckBox") == 0)
{
gameplay::CheckBox * button = static_cast<gameplay::CheckBox *>(control);
button->setIconScale(button->getIconScale() * ky);
}
if (control->isContainer())
{
gameplay::Container * container = static_cast<gameplay::Container *>(control);
container->setScrollScale(container->getScrollScale() * ky);
const std::vector< gameplay::Control * >& children = container->getControls();
for (unsigned j = 0; j < children.size(); j++)
scaleUIControl(children[j], kx, ky);
}
}
void Utils::measureChildrenBounds(gameplay::Container * container, float * width, float * height)
{
// Calculate total width and height.
float totalWidth = 0.0f, totalHeight = 0.0f;
const std::vector<gameplay::Control*>& controls = container->getControls();
for (size_t i = 0, count = controls.size(); i < count; ++i)
{
gameplay::Control* control = controls[i];
if (!control->isVisible())
continue;
const gameplay::Rectangle& bounds = control->getBounds();
const gameplay::Theme::Margin& margin = control->getMargin();
float newWidth = bounds.x + bounds.width + margin.right;
if (newWidth > totalWidth)
totalWidth = newWidth;
float newHeight = bounds.y + bounds.height + margin.bottom;
if (newHeight > totalHeight)
totalHeight = newHeight;
}
if (width)
*width = totalWidth;
if (height)
*height = totalHeight;
}<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "SwitchOrderLayer.h"
#include "paddle/utils/Stat.h"
namespace paddle {
REGISTER_LAYER(switch_order, SwitchOrderLayer);
bool SwitchOrderLayer::init(const LayerMap& layerMap,
const ParameterMap& parameterMap) {
/* Initialize the basic parent class */
Layer::init(layerMap, parameterMap);
auto& img_conf = config_.inputs(0).image_conf();
size_t inH =
img_conf.has_img_size_y() ? img_conf.img_size_y() : img_conf.img_size();
size_t inW = img_conf.img_size();
size_t inC = img_conf.channels();
inDims_ = TensorShape({0, inC, inH, inW});
outDims_ = TensorShape(4);
auto& reshape_conf = config_.reshape_conf();
for (size_t i = 0; i < reshape_conf.heightaxis_size(); i++) {
heightAxis_.push_back(reshape_conf.heightaxis(i));
}
for (size_t i = 0; i < reshape_conf.widthaxis_size(); i++) {
widthAxis_.push_back(reshape_conf.widthaxis(i));
}
createFunction(nchw2nhwc_, "NCHW2NHWC", FuncConfig());
createFunction(nhwc2nchw_, "NHWC2NCHW", FuncConfig());
return true;
}
void SwitchOrderLayer::setOutDims() {
outDims_.setDim(0, inDims_[0]);
outDims_.setDim(1, inDims_[2]);
outDims_.setDim(2, inDims_[3]);
outDims_.setDim(3, inDims_[1]);
reshapeHeight_ = 1;
for (size_t i = 0; i < heightAxis_.size(); i++) {
reshapeHeight_ *= outDims_[heightAxis_[i]];
}
output_.setFrameHeight(reshapeHeight_);
reshapeWidth_ = 1;
for (size_t i = 0; i < widthAxis_.size(); i++) {
reshapeWidth_ *= outDims_[widthAxis_[i]];
}
output_.setFrameWidth(reshapeWidth_);
}
void SwitchOrderLayer::setInDims() {
MatrixPtr input = inputLayers_[0]->getOutputValue();
size_t batchSize = input->getHeight();
inDims_.setDim(0, batchSize);
int h = inputLayers_[0]->getOutput().getFrameHeight();
if (h != 0) inDims_.setDim(2, h);
int w = inputLayers_[0]->getOutput().getFrameWidth();
if (w != 0) inDims_.setDim(3, w);
int totalCount = input->getElementCnt();
int channels = totalCount / (inDims_[0] * inDims_[2] * inDims_[3]);
if (channels != 0) inDims_.setDim(1, channels);
}
void SwitchOrderLayer::forward(PassType passType) {
Layer::forward(passType);
setInDims();
setOutDims();
resetOutput(outDims_[0], outDims_[1] * outDims_[2] * outDims_[3]);
if (heightAxis_.size() > 0) {
getOutputValue()->reshape(reshapeHeight_, reshapeWidth_);
}
// switch NCHW to NHWC
BufferArgs inputs;
BufferArgs outputs;
inputs.addArg(*getInputValue(0), inDims_);
outputs.addArg(*getOutputValue(), outDims_);
nchw2nhwc_[0]->calc(inputs, outputs);
forwardActivation();
}
void SwitchOrderLayer::backward(const UpdateCallback& callback) {
(void)callback;
backwardActivation();
// switch NHWC to NCHW
BufferArgs inputs;
BufferArgs outputs;
inputs.addArg(*getOutputGrad(), outDims_);
outputs.addArg(*getInputGrad(0), inDims_, ADD_TO);
nhwc2nchw_[0]->calc(inputs, outputs);
}
} // namespace paddle
<commit_msg>Fix SwitchOrderLayer grad bugs by reshape output.grad<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "SwitchOrderLayer.h"
#include "paddle/utils/Stat.h"
namespace paddle {
REGISTER_LAYER(switch_order, SwitchOrderLayer);
bool SwitchOrderLayer::init(const LayerMap& layerMap,
const ParameterMap& parameterMap) {
/* Initialize the basic parent class */
Layer::init(layerMap, parameterMap);
auto& img_conf = config_.inputs(0).image_conf();
size_t inH =
img_conf.has_img_size_y() ? img_conf.img_size_y() : img_conf.img_size();
size_t inW = img_conf.img_size();
size_t inC = img_conf.channels();
inDims_ = TensorShape({0, inC, inH, inW});
outDims_ = TensorShape(4);
auto& reshape_conf = config_.reshape_conf();
for (size_t i = 0; i < reshape_conf.heightaxis_size(); i++) {
heightAxis_.push_back(reshape_conf.heightaxis(i));
}
for (size_t i = 0; i < reshape_conf.widthaxis_size(); i++) {
widthAxis_.push_back(reshape_conf.widthaxis(i));
}
createFunction(nchw2nhwc_, "NCHW2NHWC", FuncConfig());
createFunction(nhwc2nchw_, "NHWC2NCHW", FuncConfig());
return true;
}
void SwitchOrderLayer::setOutDims() {
outDims_.setDim(0, inDims_[0]);
outDims_.setDim(1, inDims_[2]);
outDims_.setDim(2, inDims_[3]);
outDims_.setDim(3, inDims_[1]);
reshapeHeight_ = 1;
for (size_t i = 0; i < heightAxis_.size(); i++) {
reshapeHeight_ *= outDims_[heightAxis_[i]];
}
output_.setFrameHeight(reshapeHeight_);
reshapeWidth_ = 1;
for (size_t i = 0; i < widthAxis_.size(); i++) {
reshapeWidth_ *= outDims_[widthAxis_[i]];
}
output_.setFrameWidth(reshapeWidth_);
}
void SwitchOrderLayer::setInDims() {
MatrixPtr input = inputLayers_[0]->getOutputValue();
size_t batchSize = input->getHeight();
inDims_.setDim(0, batchSize);
int h = inputLayers_[0]->getOutput().getFrameHeight();
if (h != 0) inDims_.setDim(2, h);
int w = inputLayers_[0]->getOutput().getFrameWidth();
if (w != 0) inDims_.setDim(3, w);
int totalCount = input->getElementCnt();
int channels = totalCount / (inDims_[0] * inDims_[2] * inDims_[3]);
if (channels != 0) inDims_.setDim(1, channels);
}
void SwitchOrderLayer::forward(PassType passType) {
Layer::forward(passType);
setInDims();
setOutDims();
resetOutput(outDims_[0], outDims_[1] * outDims_[2] * outDims_[3]);
if (heightAxis_.size() > 0) {
getOutputValue()->reshape(reshapeHeight_, reshapeWidth_);
getOutputGrad()->reshape(reshapeHeight_, reshapeWidth_);
}
// switch NCHW to NHWC
BufferArgs inputs;
BufferArgs outputs;
inputs.addArg(*getInputValue(0), inDims_);
outputs.addArg(*getOutputValue(), outDims_);
nchw2nhwc_[0]->calc(inputs, outputs);
forwardActivation();
}
void SwitchOrderLayer::backward(const UpdateCallback& callback) {
(void)callback;
backwardActivation();
// switch NHWC to NCHW
BufferArgs inputs;
BufferArgs outputs;
inputs.addArg(*getOutputGrad(), outDims_);
outputs.addArg(*getInputGrad(0), inDims_, ADD_TO);
nhwc2nchw_[0]->calc(inputs, outputs);
}
} // namespace paddle
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Retrieves the character map for each of the numeric keys.
*/
// INCLUDE FILES
#include "cpcskeymap.h"
#include <QChar>
#include <QString>
#if defined(USE_ORBIT_KEYMAP)
#include <hbinputkeymap.h>
#include <hbinputkeymapfactory.h>
#endif // #if defined(USE_ORBIT_KEYMAP)
// This macro suppresses log writes
//#define NO_PRED_SEARCH_LOGS
#include "predictivesearchlog.h"
const QChar KSpaceChar = ' ';
// Separator character stored in predictive search table columns
const QChar KSeparatorChar = ' ';
// ============================== MEMBER FUNCTIONS ============================
// ----------------------------------------------------------------------------
// CPcsKeyMap::~CPcsKeyMap
// ----------------------------------------------------------------------------
CPcsKeyMap::~CPcsKeyMap()
{
PRINT(_L("Enter CPcsKeyMap::~CPcsKeyMap"));
PRINT(_L("End CPcsKeyMap::~CPcsKeyMap"));
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::GetMappedStringL
// ----------------------------------------------------------------------------
HBufC* CPcsKeyMap::GetMappedStringL(const TDesC& aSource) const
{
PRINT1(_L("Enter CPcsKeyMap::GetMappedStringL input '%S'"), &aSource);
QString source((QChar*)aSource.Ptr(), aSource.Length());
QString result;
TInt err(KErrNone);
QT_TRYCATCH_ERROR(err, result = GetMappedString(source));
User::LeaveIfError(err);
HBufC* destination = HBufC::NewL(result.length());
destination->Des().Copy(result.utf16());
PRINT1(_L("End CPcsKeyMap::GetMappedStringL result '%S'"), destination);
return destination;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::GetMappedString
// ----------------------------------------------------------------------------
QString CPcsKeyMap::GetMappedString(QString aSource) const
{
#if defined(WRITE_PRED_SEARCH_LOGS)
const int KLogLength = 30;
TBuf<KLogLength> log(aSource.left(KLogLength).utf16());
PRINT1(_L("Enter CPcsKeyMap::GetMappedString input '%S'"), &log);
#endif
QString destination;
TBool skipHashStar = DetermineSpecialCharBehaviour(aSource);
TInt length = aSource.length();
for (int i = 0; i < length; ++i)
{
if (aSource[i] == KSpaceChar)
{
destination.append(KSeparatorChar);
}
else
{
QChar ch(0);
#if defined(USE_ORBIT_KEYMAP)
ch = MappedKeyForChar(aSource[i]);
#else
ch = UseHardcodedKeyMap(aSource[i]);
#endif
if (!ShouldSkipChar(ch, skipHashStar))
{
destination.append(ch);
}
}
}
#if defined(WRITE_PRED_SEARCH_LOGS)
log = destination.left(KLogLength).utf16();
PRINT1(_L("End CPcsKeyMap::GetMappedString result '%S'"), &log);
#endif
return destination;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::GetNumericLimitsL
// In order to speed up the execution, caller should convert search pattern
// with a one call to CPcsKeyMap::GetMappedStringL() and then pass the tokens
// to CPcsKeyMap::GetNumericLimitsL().
// So it is expected that aString contains only certain characters.
// ----------------------------------------------------------------------------
TInt CPcsKeyMap::GetNumericLimits(QString aString,
QString& aLowerLimit,
QString& aUpperLimit) const
{
PRINT(_L("CPcsKeyMap::GetNumericLimits"));
if (aString.length() > iMaxKeysStoredInDb)
{
QString truncated = aString.left(iMaxKeysStoredInDb);
aString = truncated;
}
TInt err = ComputeValue(aString, EFalse, aLowerLimit);
if (err == KErrNone)
{
err = ComputeValue(aString, ETrue, aUpperLimit);
}
PRINT1(_L("End CPcsKeyMap::GetNumericLimits ret=%d"), err);
return err;
}
#if defined(USE_ORBIT_KEYMAP)
// ----------------------------------------------------------------------------
// CPcsKeyMap::Separator
// ----------------------------------------------------------------------------
QChar CPcsKeyMap::Separator() const
{
return KSeparatorChar;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::SetHardcodedCharacters
// Default implementation selects only the current default language.
// ----------------------------------------------------------------------------
QList<HbInputLanguage> CPcsKeyMap::SelectLanguages()
{
QList<HbInputLanguage> languages;
HbInputLanguage inputLanguage(QLocale::system().language());
languages << inputLanguage;
return languages;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::SetHardcodedCharacters
// Default implementation does nothing
// ----------------------------------------------------------------------------
void CPcsKeyMap::SetHardcodedCharacters()
{
}
#endif // #if defined(USE_ORBIT_KEYMAP)
// ----------------------------------------------------------------------------
// CPcsKeyMap::DetermineSpecialCharBehaviour
// Default implementation
// ----------------------------------------------------------------------------
TBool CPcsKeyMap::DetermineSpecialCharBehaviour(QString /*aSource*/) const
{
return EFalse;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ShouldSkipChar
// Default implementation
// ----------------------------------------------------------------------------
TBool CPcsKeyMap::ShouldSkipChar(QChar /*aChar*/, TBool /*aSkipHashStar*/) const
{
return EFalse;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ConstructL
// ----------------------------------------------------------------------------
#if defined(USE_ORBIT_KEYMAP)
void CPcsKeyMap::ConstructL(HbKeyboardType aKeyboardType)
#else
void CPcsKeyMap::ConstructL()
#endif
{
PRINT(_L("Enter CPcsKeyMap::ConstructL"));
#if defined(USE_ORBIT_KEYMAP)
TInt err(KErrNone);
QT_TRYCATCH_ERROR(err,
{
InitKeyMappings();
SetHardcodedCharacters();
ConstructLanguageMappings(aKeyboardType);
});
if (err != KErrNone)
{
PRINT1(_L("CPcsKeyMap::ConstructL exception, err=%d"), err);
User::Leave(err);
}
#endif
PRINT(_L("End CPcsKeyMap::ConstructL"));
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::CPcsKeyMap
// ----------------------------------------------------------------------------
#if defined(USE_ORBIT_KEYMAP)
CPcsKeyMap::CPcsKeyMap(TInt aAmountOfKeys,
QChar aPadChar,
TInt aMaxKeysStoredInDb) :
iKeyMapping(),
iAmountOfKeys(aAmountOfKeys),
iPadChar(aPadChar),
iMaxKeysStoredInDb(aMaxKeysStoredInDb)
{
}
#else // #if defined(USE_ORBIT_KEYMAP)
CPcsKeyMap::CPcsKeyMap(TInt /*aAmountOfKeys*/,
QChar /*aPadChar*/,
TInt aMaxKeysStoredInDb) :
iMaxKeysStoredInDb(aMaxKeysStoredInDb)
{
}
#endif // #if defined(USE_ORBIT_KEYMAP)
#if defined(USE_ORBIT_KEYMAP)
// ----------------------------------------------------------------------------
// CPcsKeyMap::InitKeyMappings
// Put string for each key into iKeyMapping.
// ----------------------------------------------------------------------------
void CPcsKeyMap::InitKeyMappings()
{
PRINT(_L("Enter CPcsKeyMap::InitKeyMappings"));
for (TInt i = 0; i < iAmountOfKeys; ++i)
{
iKeyMapping << QString("");
}
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ConstructLanguageMappings
// Fetch keymap for selected languages.
// Currently QWERTY keymaps do not map digits ('0'..'9') to any key, even with
// HbModifierChrPressed and HbModifierFnPressed modifiers.
// ----------------------------------------------------------------------------
void CPcsKeyMap::ConstructLanguageMappings(HbKeyboardType aKeyboardType)
{
PRINT(_L("Enter CPcsKeyMap::ConstructLanguageMappings"));
#if defined(WRITE_PRED_SEARCH_LOGS)
TInt count(0);
#endif
QList<HbInputLanguage> languages = SelectLanguages();
PRINT1(_L("build keymap from %d language(s)"), languages.count());
TInt languageCount = languages.size();
for (TInt lang = 0; lang < languageCount; ++lang)
{
PRINT2(_L("(%d) handle language %d"), lang, languages[lang].language());
if (IsLanguageSupported(languages[lang].language()))
{
PRINT2(_L("Constructing keymap for lang=%d,var=%d"),
languages[lang].language(),
languages[lang].variant());
// Gets ownership of keymap
const HbKeymap* keymap =
HbKeymapFactory::instance()->keymap(languages[lang],
HbKeymapFactory::NoCaching);
if (keymap)
{
#if defined(WRITE_PRED_SEARCH_LOGS)
count +=
#endif
ReadKeymapCharacters(aKeyboardType, *keymap);
delete keymap;
}
else
{
PRINT(_L("CPcsKeyMap::ContructKeyboardMapping keymap not found"));
}
}
}
#if defined(WRITE_PRED_SEARCH_LOGS)
PRINT1(_L("End CPcsKeyMap::ConstructLanguageMappings keymap has %d chars"), count);
#endif
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::IsLanguageSupported
// ----------------------------------------------------------------------------
TBool CPcsKeyMap::IsLanguageSupported(QLocale::Language aLanguage) const
{
return (aLanguage != QLocale::Japanese && aLanguage != QLocale::Chinese);
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::MappedKeyForChar
// Loop all QStrings of iKeyMapping to find one containing the character.
// If the character is not mapped, use pad character.
// ----------------------------------------------------------------------------
const QChar CPcsKeyMap::MappedKeyForChar(const QChar aChar) const
{
for (TInt index = 0; index < iAmountOfKeys; ++index)
{
if (iKeyMapping[index].contains(aChar))
{
return ArrayIndexToMappedChar(index);
}
}
#if _DEBUG
TUint ch = aChar.unicode();
PRINT2(_L("CPcsKeyMap::MappedKeyForChar no mapping for char '%c' (0x%x)"),
ch, ch);
#endif
return iPadChar;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ReadKeymapCharacters
// ----------------------------------------------------------------------------
TInt CPcsKeyMap::ReadKeymapCharacters(HbKeyboardType aKeyboardType,
const HbKeymap& aKeymap)
{
PRINT(_L("Enter CPcsKeyMap::ReadKeymapCharacters"));
TInt count(0);
for (TInt key = 0; key < iAmountOfKeys; ++key)
{
PRINT1(_L("handle key(enum value %d)"), key); // test
const HbMappedKey* mappedKey = aKeymap.keyForIndex(aKeyboardType, key);
// 12-key: Most languages don't have mapping for EKeyStar, EKeyHash.
// QWERTY: Different languages have different amount of keys,
// so mappedKey can be NULL.
if (mappedKey)
{
const QString lowerCase = mappedKey->characters(HbModifierNone); // "abc2.."
const QString upperCase = mappedKey->characters(HbModifierShiftPressed); // "ABC2.."
const QString charsForKey = lowerCase + upperCase;
// Filter out duplicate characters
for (TInt i = charsForKey.length() - 1; i >= 0 ; --i)
{
QChar ch = charsForKey[i];
if (!iKeyMapping[key].contains(ch) &&
!iHardcodedChars.contains(ch))
{
#if defined(WRITE_PRED_SEARCH_LOGS)
char ascChar = ch.toAscii();
TChar logChar(ArrayIndexToMappedChar(key).unicode());
if (ascChar == 0) // ch can't be represented in ASCII
{
PRINT2(_L("CPcsKeyMap: map key(%c) <-> char=0x%x"),
logChar, ch);
}
else
{
PRINT3(_L("CPcsKeyMap: map key(%c) <-> char='%c'(0x%x)"),
logChar,
ascChar,
ascChar);
}
++count;
#endif // #if defined(WRITE_PRED_SEARCH_LOGS)
iKeyMapping[key] += ch;
}
}
}
}
PRINT(_L("End CPcsKeyMap::ReadKeymapCharacters"));
return count;
}
#endif // #if defined(USE_ORBIT_KEYMAP)
// End of file
<commit_msg>Revert using old Orbit API, so allow compilation on pre-wk32 environment<commit_after>/*
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Retrieves the character map for each of the numeric keys.
*/
// INCLUDE FILES
#include "cpcskeymap.h"
#include <QChar>
#include <QString>
#if defined(USE_ORBIT_KEYMAP)
#include <hbinputkeymap.h>
#include <hbinputkeymapfactory.h>
#endif // #if defined(USE_ORBIT_KEYMAP)
// This macro suppresses log writes
//#define NO_PRED_SEARCH_LOGS
#include "predictivesearchlog.h"
const QChar KSpaceChar = ' ';
// Separator character stored in predictive search table columns
const QChar KSeparatorChar = ' ';
// Code using the new API (wk32 onwards) is put here. Remove old API code
// when wk30 is no longer used.
// #define NEW_KEYMAP_FACTORY_API
// ============================== MEMBER FUNCTIONS ============================
// ----------------------------------------------------------------------------
// CPcsKeyMap::~CPcsKeyMap
// ----------------------------------------------------------------------------
CPcsKeyMap::~CPcsKeyMap()
{
PRINT(_L("Enter CPcsKeyMap::~CPcsKeyMap"));
PRINT(_L("End CPcsKeyMap::~CPcsKeyMap"));
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::GetMappedStringL
// ----------------------------------------------------------------------------
HBufC* CPcsKeyMap::GetMappedStringL(const TDesC& aSource) const
{
PRINT1(_L("Enter CPcsKeyMap::GetMappedStringL input '%S'"), &aSource);
QString source((QChar*)aSource.Ptr(), aSource.Length());
QString result;
TInt err(KErrNone);
QT_TRYCATCH_ERROR(err, result = GetMappedString(source));
User::LeaveIfError(err);
HBufC* destination = HBufC::NewL(result.length());
destination->Des().Copy(result.utf16());
PRINT1(_L("End CPcsKeyMap::GetMappedStringL result '%S'"), destination);
return destination;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::GetMappedString
// ----------------------------------------------------------------------------
QString CPcsKeyMap::GetMappedString(QString aSource) const
{
#if defined(WRITE_PRED_SEARCH_LOGS)
const int KLogLength = 30;
TBuf<KLogLength> log(aSource.left(KLogLength).utf16());
PRINT1(_L("Enter CPcsKeyMap::GetMappedString input '%S'"), &log);
#endif
QString destination;
TBool skipHashStar = DetermineSpecialCharBehaviour(aSource);
TInt length = aSource.length();
for (int i = 0; i < length; ++i)
{
if (aSource[i] == KSpaceChar)
{
destination.append(KSeparatorChar);
}
else
{
QChar ch(0);
#if defined(USE_ORBIT_KEYMAP)
ch = MappedKeyForChar(aSource[i]);
#else
ch = UseHardcodedKeyMap(aSource[i]);
#endif
if (!ShouldSkipChar(ch, skipHashStar))
{
destination.append(ch);
}
}
}
#if defined(WRITE_PRED_SEARCH_LOGS)
log = destination.left(KLogLength).utf16();
PRINT1(_L("End CPcsKeyMap::GetMappedString result '%S'"), &log);
#endif
return destination;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::GetNumericLimitsL
// In order to speed up the execution, caller should convert search pattern
// with a one call to CPcsKeyMap::GetMappedStringL() and then pass the tokens
// to CPcsKeyMap::GetNumericLimitsL().
// So it is expected that aString contains only certain characters.
// ----------------------------------------------------------------------------
TInt CPcsKeyMap::GetNumericLimits(QString aString,
QString& aLowerLimit,
QString& aUpperLimit) const
{
PRINT(_L("CPcsKeyMap::GetNumericLimits"));
if (aString.length() > iMaxKeysStoredInDb)
{
QString truncated = aString.left(iMaxKeysStoredInDb);
aString = truncated;
}
TInt err = ComputeValue(aString, EFalse, aLowerLimit);
if (err == KErrNone)
{
err = ComputeValue(aString, ETrue, aUpperLimit);
}
PRINT1(_L("End CPcsKeyMap::GetNumericLimits ret=%d"), err);
return err;
}
#if defined(USE_ORBIT_KEYMAP)
// ----------------------------------------------------------------------------
// CPcsKeyMap::Separator
// ----------------------------------------------------------------------------
QChar CPcsKeyMap::Separator() const
{
return KSeparatorChar;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::SetHardcodedCharacters
// Default implementation selects only the current default language.
// ----------------------------------------------------------------------------
QList<HbInputLanguage> CPcsKeyMap::SelectLanguages()
{
QList<HbInputLanguage> languages;
HbInputLanguage inputLanguage(QLocale::system().language());
languages << inputLanguage;
return languages;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::SetHardcodedCharacters
// Default implementation does nothing
// ----------------------------------------------------------------------------
void CPcsKeyMap::SetHardcodedCharacters()
{
}
#endif // #if defined(USE_ORBIT_KEYMAP)
// ----------------------------------------------------------------------------
// CPcsKeyMap::DetermineSpecialCharBehaviour
// Default implementation
// ----------------------------------------------------------------------------
TBool CPcsKeyMap::DetermineSpecialCharBehaviour(QString /*aSource*/) const
{
return EFalse;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ShouldSkipChar
// Default implementation
// ----------------------------------------------------------------------------
TBool CPcsKeyMap::ShouldSkipChar(QChar /*aChar*/, TBool /*aSkipHashStar*/) const
{
return EFalse;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ConstructL
// ----------------------------------------------------------------------------
#if defined(USE_ORBIT_KEYMAP)
void CPcsKeyMap::ConstructL(HbKeyboardType aKeyboardType)
#else
void CPcsKeyMap::ConstructL()
#endif
{
PRINT(_L("Enter CPcsKeyMap::ConstructL"));
#if defined(USE_ORBIT_KEYMAP)
TInt err(KErrNone);
QT_TRYCATCH_ERROR(err,
{
InitKeyMappings();
SetHardcodedCharacters();
ConstructLanguageMappings(aKeyboardType);
});
if (err != KErrNone)
{
PRINT1(_L("CPcsKeyMap::ConstructL exception, err=%d"), err);
User::Leave(err);
}
#endif
PRINT(_L("End CPcsKeyMap::ConstructL"));
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::CPcsKeyMap
// ----------------------------------------------------------------------------
#if defined(USE_ORBIT_KEYMAP)
CPcsKeyMap::CPcsKeyMap(TInt aAmountOfKeys,
QChar aPadChar,
TInt aMaxKeysStoredInDb) :
iKeyMapping(),
iAmountOfKeys(aAmountOfKeys),
iPadChar(aPadChar),
iMaxKeysStoredInDb(aMaxKeysStoredInDb)
{
}
#else // #if defined(USE_ORBIT_KEYMAP)
CPcsKeyMap::CPcsKeyMap(TInt /*aAmountOfKeys*/,
QChar /*aPadChar*/,
TInt aMaxKeysStoredInDb) :
iMaxKeysStoredInDb(aMaxKeysStoredInDb)
{
}
#endif // #if defined(USE_ORBIT_KEYMAP)
#if defined(USE_ORBIT_KEYMAP)
// ----------------------------------------------------------------------------
// CPcsKeyMap::InitKeyMappings
// Put string for each key into iKeyMapping.
// ----------------------------------------------------------------------------
void CPcsKeyMap::InitKeyMappings()
{
PRINT(_L("Enter CPcsKeyMap::InitKeyMappings"));
for (TInt i = 0; i < iAmountOfKeys; ++i)
{
iKeyMapping << QString("");
}
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ConstructLanguageMappings
// Fetch keymap for selected languages.
// Currently QWERTY keymaps do not map digits ('0'..'9') to any key, even with
// HbModifierChrPressed and HbModifierFnPressed modifiers.
// ----------------------------------------------------------------------------
void CPcsKeyMap::ConstructLanguageMappings(HbKeyboardType aKeyboardType)
{
PRINT(_L("Enter CPcsKeyMap::ConstructLanguageMappings"));
#if defined(WRITE_PRED_SEARCH_LOGS)
TInt count(0);
#endif
QList<HbInputLanguage> languages = SelectLanguages();
PRINT1(_L("build keymap from %d language(s)"), languages.count());
TInt languageCount = languages.size();
#if !defined(NEW_KEYMAP_FACTORY_API)
// Latest SDKs have so many keymaps contact server runs out of stack.
// So limit the amount of keymaps.
const TInt KMaxKeymapCount = 10;
if (languageCount > KMaxKeymapCount)
{
languageCount = KMaxKeymapCount;
}
#endif
for (TInt lang = 0; lang < languageCount; ++lang)
{
PRINT2(_L("(%d) handle language %d"), lang, languages[lang].language());
if (IsLanguageSupported(languages[lang].language()))
{
PRINT2(_L("Constructing keymap for lang=%d,var=%d"),
languages[lang].language(),
languages[lang].variant());
#if defined(NEW_KEYMAP_FACTORY_API)
// Gets ownership of keymap
const HbKeymap* keymap =
HbKeymapFactory::instance()->keymap(languages[lang],
HbKeymapFactory::NoCaching);
#else
// Does not get ownership of keymap
const HbKeymap* keymap =
HbKeymapFactory::instance()->keymap(languages[lang].language(),
languages[lang].variant());
#endif
if (keymap)
{
#if defined(WRITE_PRED_SEARCH_LOGS)
count +=
#endif
ReadKeymapCharacters(aKeyboardType, *keymap);
#if defined(NEW_KEYMAP_FACTORY_API)
delete keymap;
#endif
}
else
{
PRINT(_L("CPcsKeyMap::ContructKeyboardMapping keymap not found"));
}
}
}
#if defined(WRITE_PRED_SEARCH_LOGS)
PRINT1(_L("End CPcsKeyMap::ConstructLanguageMappings keymap has %d chars"), count);
#endif
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::IsLanguageSupported
// ----------------------------------------------------------------------------
TBool CPcsKeyMap::IsLanguageSupported(QLocale::Language aLanguage) const
{
return (aLanguage != QLocale::Japanese && aLanguage != QLocale::Chinese);
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::MappedKeyForChar
// Loop all QStrings of iKeyMapping to find one containing the character.
// If the character is not mapped, use pad character.
// ----------------------------------------------------------------------------
const QChar CPcsKeyMap::MappedKeyForChar(const QChar aChar) const
{
for (TInt index = 0; index < iAmountOfKeys; ++index)
{
if (iKeyMapping[index].contains(aChar))
{
return ArrayIndexToMappedChar(index);
}
}
#if _DEBUG
TUint ch = aChar.unicode();
PRINT2(_L("CPcsKeyMap::MappedKeyForChar no mapping for char '%c' (0x%x)"),
ch, ch);
#endif
return iPadChar;
}
// ----------------------------------------------------------------------------
// CPcsKeyMap::ReadKeymapCharacters
// ----------------------------------------------------------------------------
TInt CPcsKeyMap::ReadKeymapCharacters(HbKeyboardType aKeyboardType,
const HbKeymap& aKeymap)
{
PRINT(_L("Enter CPcsKeyMap::ReadKeymapCharacters"));
TInt count(0);
for (TInt key = 0; key < iAmountOfKeys; ++key)
{
PRINT1(_L("handle key(enum value %d)"), key); // test
const HbMappedKey* mappedKey = aKeymap.keyForIndex(aKeyboardType, key);
// 12-key: Most languages don't have mapping for EKeyStar, EKeyHash.
// QWERTY: Different languages have different amount of keys,
// so mappedKey can be NULL.
if (mappedKey)
{
const QString lowerCase = mappedKey->characters(HbModifierNone); // "abc2.."
const QString upperCase = mappedKey->characters(HbModifierShiftPressed); // "ABC2.."
const QString charsForKey = lowerCase + upperCase;
// Filter out duplicate characters
for (TInt i = charsForKey.length() - 1; i >= 0 ; --i)
{
QChar ch = charsForKey[i];
if (!iKeyMapping[key].contains(ch) &&
!iHardcodedChars.contains(ch))
{
#if defined(WRITE_PRED_SEARCH_LOGS)
char ascChar = ch.toAscii();
TChar logChar(ArrayIndexToMappedChar(key).unicode());
if (ascChar == 0) // ch can't be represented in ASCII
{
PRINT2(_L("CPcsKeyMap: map key(%c) <-> char=0x%x"),
logChar, ch);
}
else
{
PRINT3(_L("CPcsKeyMap: map key(%c) <-> char='%c'(0x%x)"),
logChar,
ascChar,
ascChar);
}
++count;
#endif // #if defined(WRITE_PRED_SEARCH_LOGS)
iKeyMapping[key] += ch;
}
}
}
}
PRINT(_L("End CPcsKeyMap::ReadKeymapCharacters"));
return count;
}
#endif // #if defined(USE_ORBIT_KEYMAP)
// End of file
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <thrift/conformance/cpp2/AnyRegistry.h>
#include <folly/io/Cursor.h>
#include <thrift/conformance/cpp2/Any.h>
namespace apache::thrift::conformance {
bool AnyRegistry::registerType(const std::type_info& typeInfo, AnyType type) {
return registerTypeImpl(typeInfo, std::move(type)) != nullptr;
}
bool AnyRegistry::registerSerializer(
const std::type_info& type,
const AnySerializer* serializer) {
return registerSerializerImpl(
serializer, ®istry_.at(std::type_index(type)));
}
bool AnyRegistry::registerSerializer(
const std::type_info& type,
std::unique_ptr<AnySerializer> serializer) {
return registerSerializerImpl(
std::move(serializer), ®istry_.at(std::type_index(type)));
}
std::string_view AnyRegistry::getTypeName(const std::type_info& type) const {
const auto* entry = getTypeEntry(type);
if (entry == nullptr) {
return {};
}
return entry->type.get_name();
}
const AnySerializer* AnyRegistry::getSerializer(
const std::type_info& type,
const Protocol& protocol) const {
return getSerializer(getTypeEntry(type), protocol);
}
const AnySerializer* AnyRegistry::getSerializer(
std::string_view name,
const Protocol& protocol) const {
return getSerializer(getTypeEntry(name), protocol);
}
Any AnyRegistry::store(any_ref value, const Protocol& protocol) const {
if (value.type() == typeid(Any)) {
// Use the Any specific overload.
return store(any_cast<const Any&>(value), protocol);
}
const auto* entry = getTypeEntry(value.type());
const auto* serializer = getSerializer(entry, protocol);
if (serializer == nullptr) {
folly::throw_exception<std::bad_any_cast>();
}
folly::IOBufQueue queue(folly::IOBufQueue::cacheChainLength());
// Allocate 16KB at a time; leave some room for the IOBuf overhead
constexpr size_t kDesiredGrowth = (1 << 14) - 64;
serializer->encode(value, folly::io::QueueAppender(&queue, kDesiredGrowth));
Any result;
result.set_type(entry->type.get_name());
if (protocol.isCustom()) {
result.customProtocol_ref() = protocol.custom();
} else {
result.protocol_ref() = protocol.standard();
}
result.data_ref() = queue.moveAsValue();
return result;
}
Any AnyRegistry::store(const Any& value, const Protocol& protocol) const {
if (hasProtocol(value, protocol)) {
return value;
}
return store(load(value), protocol);
}
void AnyRegistry::load(const Any& value, any_ref out) const {
// TODO(afuller): Add support for type_id.
if (!value.type_ref().has_value()) {
folly::throw_exception<std::bad_any_cast>();
}
const auto* entry = getTypeEntry(*value.type_ref());
const auto* serializer = getSerializer(entry, getProtocol(value));
if (serializer == nullptr) {
folly::throw_exception<std::bad_any_cast>();
}
folly::io::Cursor cursor(&*value.data_ref());
serializer->decode(entry->typeInfo, cursor, out);
}
std::any AnyRegistry::load(const Any& value) const {
std::any out;
load(value, out);
return out;
}
auto AnyRegistry::registerTypeImpl(const std::type_info& typeInfo, AnyType type)
-> TypeEntry* {
if (!checkNameAvailability(type)) {
return nullptr;
}
auto result = registry_.emplace(
std::type_index(typeInfo), TypeEntry(typeInfo, std::move(type)));
if (!result.second) {
return nullptr;
}
indexType(&result.first->second);
return &result.first->second;
}
bool AnyRegistry::registerSerializerImpl(
const AnySerializer* serializer,
TypeEntry* entry) {
if (serializer == nullptr) {
return false;
}
return entry->serializers.emplace(serializer->getProtocol(), serializer)
.second;
}
bool AnyRegistry::registerSerializerImpl(
std::unique_ptr<AnySerializer> serializer,
TypeEntry* entry) {
if (!registerSerializerImpl(serializer.get(), entry)) {
return false;
}
ownedSerializers_.emplace_front(std::move(serializer));
return true;
}
bool AnyRegistry::checkNameAvailability(std::string_view name) const {
return !name.empty() && !nameIndex_.contains(name);
}
bool AnyRegistry::checkNameAvailability(const AnyType& type) const {
// Ensure name and all aliases are availabile.
if (!checkNameAvailability(*type.name_ref())) {
return false;
}
for (const auto& alias : *type.aliases_ref()) {
if (!checkNameAvailability(alias)) {
return false;
}
}
return true;
}
void AnyRegistry::indexName(std::string_view name, TypeEntry* entry) {
auto res = nameIndex_.emplace(name, entry);
assert(res.second);
// TODO(afuller): Also index under typeId.
}
void AnyRegistry::indexType(TypeEntry* entry) {
indexName(*entry->type.name_ref(), entry);
for (const auto& alias : *entry->type.aliases_ref()) {
indexName(alias, entry);
}
}
auto AnyRegistry::getTypeEntry(std::string_view name) const
-> const TypeEntry* {
auto itr = nameIndex_.find(name);
if (itr == nameIndex_.end()) {
return nullptr;
}
return itr->second;
}
auto AnyRegistry::getTypeEntry(const std::type_index& index) const
-> const TypeEntry* {
auto itr = registry_.find(index);
if (itr == registry_.end()) {
return nullptr;
}
return &itr->second;
}
const AnySerializer* AnyRegistry::getSerializer(
const TypeEntry* entry,
const Protocol& protocol) const {
if (entry == nullptr) {
return nullptr;
}
auto itr = entry->serializers.find(protocol);
if (itr == entry->serializers.end()) {
return nullptr;
}
return itr->second;
}
} // namespace apache::thrift::conformance
<commit_msg>Fix @mode/opt compile bug<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <thrift/conformance/cpp2/AnyRegistry.h>
#include <folly/CppAttributes.h>
#include <folly/io/Cursor.h>
#include <thrift/conformance/cpp2/Any.h>
namespace apache::thrift::conformance {
bool AnyRegistry::registerType(const std::type_info& typeInfo, AnyType type) {
return registerTypeImpl(typeInfo, std::move(type)) != nullptr;
}
bool AnyRegistry::registerSerializer(
const std::type_info& type,
const AnySerializer* serializer) {
return registerSerializerImpl(
serializer, ®istry_.at(std::type_index(type)));
}
bool AnyRegistry::registerSerializer(
const std::type_info& type,
std::unique_ptr<AnySerializer> serializer) {
return registerSerializerImpl(
std::move(serializer), ®istry_.at(std::type_index(type)));
}
std::string_view AnyRegistry::getTypeName(const std::type_info& type) const {
const auto* entry = getTypeEntry(type);
if (entry == nullptr) {
return {};
}
return entry->type.get_name();
}
const AnySerializer* AnyRegistry::getSerializer(
const std::type_info& type,
const Protocol& protocol) const {
return getSerializer(getTypeEntry(type), protocol);
}
const AnySerializer* AnyRegistry::getSerializer(
std::string_view name,
const Protocol& protocol) const {
return getSerializer(getTypeEntry(name), protocol);
}
Any AnyRegistry::store(any_ref value, const Protocol& protocol) const {
if (value.type() == typeid(Any)) {
// Use the Any specific overload.
return store(any_cast<const Any&>(value), protocol);
}
const auto* entry = getTypeEntry(value.type());
const auto* serializer = getSerializer(entry, protocol);
if (serializer == nullptr) {
folly::throw_exception<std::bad_any_cast>();
}
folly::IOBufQueue queue(folly::IOBufQueue::cacheChainLength());
// Allocate 16KB at a time; leave some room for the IOBuf overhead
constexpr size_t kDesiredGrowth = (1 << 14) - 64;
serializer->encode(value, folly::io::QueueAppender(&queue, kDesiredGrowth));
Any result;
result.set_type(entry->type.get_name());
if (protocol.isCustom()) {
result.customProtocol_ref() = protocol.custom();
} else {
result.protocol_ref() = protocol.standard();
}
result.data_ref() = queue.moveAsValue();
return result;
}
Any AnyRegistry::store(const Any& value, const Protocol& protocol) const {
if (hasProtocol(value, protocol)) {
return value;
}
return store(load(value), protocol);
}
void AnyRegistry::load(const Any& value, any_ref out) const {
// TODO(afuller): Add support for type_id.
if (!value.type_ref().has_value()) {
folly::throw_exception<std::bad_any_cast>();
}
const auto* entry = getTypeEntry(*value.type_ref());
const auto* serializer = getSerializer(entry, getProtocol(value));
if (serializer == nullptr) {
folly::throw_exception<std::bad_any_cast>();
}
folly::io::Cursor cursor(&*value.data_ref());
serializer->decode(entry->typeInfo, cursor, out);
}
std::any AnyRegistry::load(const Any& value) const {
std::any out;
load(value, out);
return out;
}
auto AnyRegistry::registerTypeImpl(const std::type_info& typeInfo, AnyType type)
-> TypeEntry* {
if (!checkNameAvailability(type)) {
return nullptr;
}
auto result = registry_.emplace(
std::type_index(typeInfo), TypeEntry(typeInfo, std::move(type)));
if (!result.second) {
return nullptr;
}
indexType(&result.first->second);
return &result.first->second;
}
bool AnyRegistry::registerSerializerImpl(
const AnySerializer* serializer,
TypeEntry* entry) {
if (serializer == nullptr) {
return false;
}
return entry->serializers.emplace(serializer->getProtocol(), serializer)
.second;
}
bool AnyRegistry::registerSerializerImpl(
std::unique_ptr<AnySerializer> serializer,
TypeEntry* entry) {
if (!registerSerializerImpl(serializer.get(), entry)) {
return false;
}
ownedSerializers_.emplace_front(std::move(serializer));
return true;
}
bool AnyRegistry::checkNameAvailability(std::string_view name) const {
return !name.empty() && !nameIndex_.contains(name);
}
bool AnyRegistry::checkNameAvailability(const AnyType& type) const {
// Ensure name and all aliases are availabile.
if (!checkNameAvailability(*type.name_ref())) {
return false;
}
for (const auto& alias : *type.aliases_ref()) {
if (!checkNameAvailability(alias)) {
return false;
}
}
return true;
}
void AnyRegistry::indexName(std::string_view name, TypeEntry* entry) {
FOLLY_MAYBE_UNUSED auto res = nameIndex_.emplace(name, entry);
assert(res.second);
// TODO(afuller): Also index under typeId.
}
void AnyRegistry::indexType(TypeEntry* entry) {
indexName(*entry->type.name_ref(), entry);
for (const auto& alias : *entry->type.aliases_ref()) {
indexName(alias, entry);
}
}
auto AnyRegistry::getTypeEntry(std::string_view name) const
-> const TypeEntry* {
auto itr = nameIndex_.find(name);
if (itr == nameIndex_.end()) {
return nullptr;
}
return itr->second;
}
auto AnyRegistry::getTypeEntry(const std::type_index& index) const
-> const TypeEntry* {
auto itr = registry_.find(index);
if (itr == registry_.end()) {
return nullptr;
}
return &itr->second;
}
const AnySerializer* AnyRegistry::getSerializer(
const TypeEntry* entry,
const Protocol& protocol) const {
if (entry == nullptr) {
return nullptr;
}
auto itr = entry->serializers.find(protocol);
if (itr == entry->serializers.end()) {
return nullptr;
}
return itr->second;
}
} // namespace apache::thrift::conformance
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <boost/unordered_map.hpp>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <com/sun/star/uno/genfunc.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::__cxxabiv1;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * )
{
}
static OUString toUNOname( char const * p )
{
#if defined BRIDGES_DEBUG
char const * start = p;
#endif
// example: N3com3sun4star4lang24IllegalArgumentExceptionE
OUStringBuffer buf( 64 );
OSL_ASSERT( 'N' == *p );
++p; // skip N
while ('E' != *p)
{
// read chars count
long n = (*p++ - '0');
while ('0' <= *p && '9' >= *p)
{
n *= 10;
n += (*p++ - '0');
}
buf.appendAscii( p, n );
p += n;
if ('E' != *p)
buf.append( '.' );
}
#if defined BRIDGES_DEBUG
OUString ret( buf.makeStringAndClear() );
OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() );
return ret;
#else
return buf.makeStringAndClear();
#endif
}
class RTTI
{
typedef boost::unordered_map< OUString, type_info *, OUStringHash > t_rtti_map;
Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI();
~RTTI();
type_info * getRTTI( typelib_CompoundTypeDescription * );
};
RTTI::RTTI()
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
RTTI::~RTTI()
{
dlclose( m_hApp );
}
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr )
{
type_info * rtti;
OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;
MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );
if (iFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( "_ZTIN" );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
rtti = (type_info *)dlsym( m_hApp, symName.getStr() );
if (rtti)
{
pair< t_rtti_map::iterator, bool > insertion(
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iiFind( m_generatedRttis.find( unoName ) );
if (iiFind == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if defined BRIDGES_DEBUG
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
if (pTypeDescr->pBaseTypeDescription)
{
// ensure availability of base
type_info * base_rtti = getRTTI(
(typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );
rtti = new __si_class_type_info(
strdup( rttiName ), (__class_type_info *)base_rtti );
}
else
{
// this class has no base class
rtti = new __class_type_info( strdup( rttiName ) );
}
pair< t_rtti_map::iterator, bool > insertion(
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" );
}
else // taking already generated rtti
{
rtti = iiFind->second;
}
}
}
else
{
rtti = iFind->second;
}
return rtti;
}
static void deleteException( void * pExc )
{
__cxa_exception const * header = ((__cxa_exception const *)pExc - 1);
typelib_TypeDescription * pTD = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pTD, unoName.pData );
OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" );
if (pTD)
{
::uno_destructData( pExc, pTD, cpp_release );
::typelib_typedescription_release( pTD );
}
}
void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
#if defined BRIDGES_DEBUG
OString cstr(
OUStringToOString(
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> uno exception occurred: %s\n", cstr.getStr() );
#endif
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
{
throw RuntimeException(
OUString("cannot get typedescription for type ") +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ) );
}
pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
// avoiding locked counts
static RTTI * s_rtti = 0;
if (! s_rtti)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_rtti)
{
#ifdef LEAK_STATIC_DATA
s_rtti = new RTTI();
#else
static RTTI rtti_data;
s_rtti = &rtti_data;
#endif
}
}
rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );
TYPELIB_DANGER_RELEASE( pTypeDescr );
OSL_ENSURE( rtti, "### no rtti for throwing exception!" );
if (! rtti)
{
throw RuntimeException(
OUString("no rtti for type ") +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
);
}
}
__cxa_throw( pCppExc, rtti, deleteException );
}
void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )
{
if (! header)
{
RuntimeException aRE( "no exception header!" );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_FAIL( cstr.getStr() );
#endif
return;
}
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
#if defined BRIDGES_DEBUG
OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> c++ exception occurred: %s\n", cstr_unoName.getStr() );
#endif
typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
if (0 == pExcTypeDescr)
{
RuntimeException aRE( OUString("exception type not found: ") + unoName );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_FAIL( cstr.getStr() );
#endif
}
else
{
// construct uno exception any
uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
typelib_typedescription_release( pExcTypeDescr );
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix sparc build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <boost/unordered_map.hpp>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <com/sun/star/uno/genfunc.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::__cxxabiv1;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * )
{
}
static OUString toUNOname( char const * p )
{
#if defined BRIDGES_DEBUG
char const * start = p;
#endif
// example: N3com3sun4star4lang24IllegalArgumentExceptionE
OUStringBuffer buf( 64 );
OSL_ASSERT( 'N' == *p );
++p; // skip N
while ('E' != *p)
{
// read chars count
long n = (*p++ - '0');
while ('0' <= *p && '9' >= *p)
{
n *= 10;
n += (*p++ - '0');
}
buf.appendAscii( p, n );
p += n;
if ('E' != *p)
buf.append( '.' );
}
#if defined BRIDGES_DEBUG
OUString ret( buf.makeStringAndClear() );
OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() );
return ret;
#else
return buf.makeStringAndClear();
#endif
}
class RTTI
{
typedef boost::unordered_map< OUString, type_info *, OUStringHash > t_rtti_map;
Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI();
~RTTI();
type_info * getRTTI( typelib_CompoundTypeDescription * );
};
RTTI::RTTI()
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
RTTI::~RTTI()
{
dlclose( m_hApp );
}
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr )
{
type_info * rtti;
OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;
MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );
if (iFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( "_ZTIN" );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
rtti = (type_info *)dlsym( m_hApp, symName.getStr() );
if (rtti)
{
pair< t_rtti_map::iterator, bool > insertion(
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iiFind( m_generatedRttis.find( unoName ) );
if (iiFind == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if defined BRIDGES_DEBUG
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
if (pTypeDescr->pBaseTypeDescription)
{
// ensure availability of base
type_info * base_rtti = getRTTI(
(typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );
rtti = new __si_class_type_info(
strdup( rttiName ), (__class_type_info *)base_rtti );
}
else
{
// this class has no base class
rtti = new __class_type_info( strdup( rttiName ) );
}
pair< t_rtti_map::iterator, bool > insertion(
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" );
}
else // taking already generated rtti
{
rtti = iiFind->second;
}
}
}
else
{
rtti = iFind->second;
}
return rtti;
}
static void deleteException( void * pExc )
{
__cxa_exception const * header = ((__cxa_exception const *)pExc - 1);
typelib_TypeDescription * pTD = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pTD, unoName.pData );
OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" );
if (pTD)
{
::uno_destructData( pExc, pTD, cpp_release );
::typelib_typedescription_release( pTD );
}
}
void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
#if defined BRIDGES_DEBUG
OString cstr(
OUStringToOString(
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> uno exception occurred: %s\n", cstr.getStr() );
#endif
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
{
throw RuntimeException(
OUString("cannot get typedescription for type ") +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ) );
}
pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
// avoiding locked counts
static RTTI * s_rtti = 0;
if (! s_rtti)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_rtti)
{
#ifdef LEAK_STATIC_DATA
s_rtti = new RTTI();
#else
static RTTI rtti_data;
s_rtti = &rtti_data;
#endif
}
}
rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );
TYPELIB_DANGER_RELEASE( pTypeDescr );
OSL_ENSURE( rtti, "### no rtti for throwing exception!" );
if (! rtti)
{
throw RuntimeException(
OUString("no rtti for type ") +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName )
);
}
}
__cxa_throw( pCppExc, rtti, deleteException );
}
void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )
{
if (! header)
{
RuntimeException aRE( "no exception header!" );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_FAIL( cstr.getStr() );
#endif
return;
}
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
#if defined BRIDGES_DEBUG
OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> c++ exception occurred: %s\n", cstr_unoName.getStr() );
#endif
typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
if (0 == pExcTypeDescr)
{
RuntimeException aRE( OUString("exception type not found: ") + unoName );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_FAIL( cstr.getStr() );
#endif
}
else
{
// construct uno exception any
uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
typelib_typedescription_release( pExcTypeDescr );
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "Action.h"
Action::Action(const int _action):
action(_action)
{}
Action::Execute()
{}
<commit_msg>added comparison operator<commit_after>#include "Action.h"
Action::Action(const int _action):
action(_action)
{}
Action::Execute()
{
//call stored function
}
bool operator==(const Action& a1) const
{
return action==target.action;
}
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_MATH_HH
#define DUNE_STUFF_MATH_HH
#include <vector>
#include <limits>
#include <algorithm>
#include <cstring>
#include <iostream>
#include "static_assert.hh"
#include <boost/static_assert.hpp>
#include <boost/fusion/include/void.hpp>
#include <boost/format.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <dune/common/deprecated.hh>
namespace Stuff {
/** \todo DOCME **/
template <class SomeRangeType, class OtherRangeType >
static double colonProduct( const SomeRangeType& arg1,
const OtherRangeType& arg2 )
{
dune_static_assert( SomeRangeType::cols == SomeRangeType::rows
&& OtherRangeType::cols == OtherRangeType::rows
&& int(OtherRangeType::cols) == int(SomeRangeType::rows), "RangeTypes_dont_fit" );
double ret = 0.0;
// iterators
typedef typename SomeRangeType::ConstRowIterator
ConstRowIteratorType;
typedef typename SomeRangeType::row_type::ConstIterator
ConstIteratorType;
ConstRowIteratorType arg1RowItEnd = arg1.end();
ConstRowIteratorType arg2RowItEnd = arg2.end();
ConstRowIteratorType arg2RowIt = arg2.begin();
for ( ConstRowIteratorType arg1RowIt = arg1.begin();
arg1RowIt != arg1RowItEnd, arg2RowIt != arg2RowItEnd;
++arg1RowIt, ++arg2RowIt ) {
ConstIteratorType row1ItEnd = arg1RowIt->end();
ConstIteratorType row2ItEnd = arg2RowIt->end();
ConstIteratorType row2It = arg2RowIt->begin();
for ( ConstIteratorType row1It = arg1RowIt->begin();
row1It != row1ItEnd, row2It != row2ItEnd;
++row1It, ++row2It ) {
ret += *row1It * *row2It;
}
}
return ret;
}
/**
* \brief dyadic product
*
* Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
* RangeType1 should be fieldmatrix, RangeType2 fieldvector
**/
template <class RangeType1, class RangeType2 >
static RangeType1 dyadicProduct( const RangeType2& arg1,
const RangeType2& arg2 )
{
RangeType1 ret( 0.0 );
typedef typename RangeType1::RowIterator
MatrixRowIteratorType;
typedef typename RangeType2::ConstIterator
ConstVectorIteratorType;
typedef typename RangeType2::Iterator
VectorIteratorType;
MatrixRowIteratorType rItEnd = ret.end();
ConstVectorIteratorType arg1It = arg1.begin();
for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
ConstVectorIteratorType arg2It = arg2.begin();
VectorIteratorType vItEnd = rIt->end();
for ( VectorIteratorType vIt = rIt->begin();
vIt != vItEnd;
++vIt ) {
*vIt = *arg1It * *arg2It;
++arg2It;
}
++arg1It;
}
return ret;
}
/** \brief a vector wrapper for continiously updating min,max,avg of some element type vector
\todo find use? it's only used in minimal as testcase for itself...
**/
template < class ElementType >
class MinMaxAvg {
protected:
typedef MinMaxAvg< ElementType >
ThisType;
typedef std::vector< ElementType >
ElementsVec;
typedef typename ElementsVec::const_iterator
ElementsVecConstIterator;
public:
MinMaxAvg()
{}
template < class stl_container_type >
MinMaxAvg( const stl_container_type& elements )
{
dune_static_assert( (boost::is_same< ElementType, typename stl_container_type::value_type >::value),
"cannot assign mismatching types" );
acc_ = std::for_each( elements.begin(), elements.end(), acc_ );
}
ElementType min () const { return boost::accumulators::min(acc_); }
ElementType max () const { return boost::accumulators::max(acc_); }
ElementType average () const { return boost::accumulators::mean(acc_); }
void DUNE_DEPRECATED push( const ElementType& el ) {
acc_( el );
}
void operator()( const ElementType& el ) {
acc_( el );
}
template < class Stream >
void output( Stream& stream ) {
stream << boost::format( "min: %e\tmax: %e\tavg: %e\n" ) % min() % max() % average();
}
protected:
typedef boost::accumulators::stats<
boost::accumulators::tag::max,
boost::accumulators::tag::min,
boost::accumulators::tag::mean >
StatsType;
boost::accumulators::accumulator_set< ElementType,StatsType > acc_;
MinMaxAvg( const ThisType& other );
};
//! bound \param var in [\param min,\param max]
template <typename T> T clamp(const T var,const T min,const T max)
{
return ( (var < min) ? min : ( var > max ) ? max : var );
}
//! docme
class MovingAverage
{
double avg_;
size_t steps_;
public:
MovingAverage()
:avg_(0.0),steps_(0)
{}
MovingAverage& operator += (double val)
{
avg_ += ( val - avg_ ) / ++steps_;
return *this;
}
operator double () { return avg_; }
};
//! no-branch sign function
long sign(long x) { return long(x!=0) | (long(x>=0)-1); }
} //end namespace Stuff
#endif // DUNE_STUFF_MATH_HH
<commit_msg>fix colonProduct loops<commit_after>#ifndef DUNE_STUFF_MATH_HH
#define DUNE_STUFF_MATH_HH
#include <vector>
#include <limits>
#include <algorithm>
#include <cstring>
#include <iostream>
#include "static_assert.hh"
#include <boost/static_assert.hpp>
#include <boost/fusion/include/void.hpp>
#include <boost/format.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <dune/common/deprecated.hh>
namespace Stuff {
/** \todo DOCME **/
template <class SomeRangeType, class OtherRangeType >
static double colonProduct( const SomeRangeType& arg1,
const OtherRangeType& arg2 )
{
dune_static_assert( SomeRangeType::cols == SomeRangeType::rows
&& OtherRangeType::cols == OtherRangeType::rows
&& int(OtherRangeType::cols) == int(SomeRangeType::rows), "RangeTypes_dont_fit" );
double ret = 0.0;
// iterators
typedef typename SomeRangeType::ConstRowIterator
ConstRowIteratorType;
typedef typename SomeRangeType::row_type::ConstIterator
ConstIteratorType;
ConstRowIteratorType arg1RowItEnd = arg1.end();
ConstRowIteratorType arg2RowItEnd = arg2.end();
ConstRowIteratorType arg2RowIt = arg2.begin();
for ( ConstRowIteratorType arg1RowIt = arg1.begin();
arg1RowIt != arg1RowItEnd && arg2RowIt != arg2RowItEnd;
++arg1RowIt, ++arg2RowIt ) {
ConstIteratorType row1ItEnd = arg1RowIt->end();
ConstIteratorType row2ItEnd = arg2RowIt->end();
ConstIteratorType row2It = arg2RowIt->begin();
for ( ConstIteratorType row1It = arg1RowIt->begin();
row1It != row1ItEnd && row2It != row2ItEnd;
++row1It, ++row2It ) {
ret += *row1It * *row2It;
}
}
return ret;
}
/**
* \brief dyadic product
*
* Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
* RangeType1 should be fieldmatrix, RangeType2 fieldvector
**/
template <class RangeType1, class RangeType2 >
static RangeType1 dyadicProduct( const RangeType2& arg1,
const RangeType2& arg2 )
{
RangeType1 ret( 0.0 );
typedef typename RangeType1::RowIterator
MatrixRowIteratorType;
typedef typename RangeType2::ConstIterator
ConstVectorIteratorType;
typedef typename RangeType2::Iterator
VectorIteratorType;
MatrixRowIteratorType rItEnd = ret.end();
ConstVectorIteratorType arg1It = arg1.begin();
for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
ConstVectorIteratorType arg2It = arg2.begin();
VectorIteratorType vItEnd = rIt->end();
for ( VectorIteratorType vIt = rIt->begin();
vIt != vItEnd;
++vIt ) {
*vIt = *arg1It * *arg2It;
++arg2It;
}
++arg1It;
}
return ret;
}
/** \brief a vector wrapper for continiously updating min,max,avg of some element type vector
\todo find use? it's only used in minimal as testcase for itself...
**/
template < class ElementType >
class MinMaxAvg {
protected:
typedef MinMaxAvg< ElementType >
ThisType;
typedef std::vector< ElementType >
ElementsVec;
typedef typename ElementsVec::const_iterator
ElementsVecConstIterator;
public:
MinMaxAvg()
{}
template < class stl_container_type >
MinMaxAvg( const stl_container_type& elements )
{
dune_static_assert( (boost::is_same< ElementType, typename stl_container_type::value_type >::value),
"cannot assign mismatching types" );
acc_ = std::for_each( elements.begin(), elements.end(), acc_ );
}
ElementType min () const { return boost::accumulators::min(acc_); }
ElementType max () const { return boost::accumulators::max(acc_); }
ElementType average () const { return boost::accumulators::mean(acc_); }
void DUNE_DEPRECATED push( const ElementType& el ) {
acc_( el );
}
void operator()( const ElementType& el ) {
acc_( el );
}
template < class Stream >
void output( Stream& stream ) {
stream << boost::format( "min: %e\tmax: %e\tavg: %e\n" ) % min() % max() % average();
}
protected:
typedef boost::accumulators::stats<
boost::accumulators::tag::max,
boost::accumulators::tag::min,
boost::accumulators::tag::mean >
StatsType;
boost::accumulators::accumulator_set< ElementType,StatsType > acc_;
MinMaxAvg( const ThisType& other );
};
//! bound \param var in [\param min,\param max]
template <typename T> T clamp(const T var,const T min,const T max)
{
return ( (var < min) ? min : ( var > max ) ? max : var );
}
//! docme
class MovingAverage
{
double avg_;
size_t steps_;
public:
MovingAverage()
:avg_(0.0),steps_(0)
{}
MovingAverage& operator += (double val)
{
avg_ += ( val - avg_ ) / ++steps_;
return *this;
}
operator double () { return avg_; }
};
//! no-branch sign function
long sign(long x) { return long(x!=0) | (long(x>=0)-1); }
} //end namespace Stuff
#endif // DUNE_STUFF_MATH_HH
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <drawinglayer/primitive2d/graphicprimitivehelper2d.hxx>
#include <drawinglayer/animation/animationtiming.hxx>
#include <drawinglayer/primitive2d/bitmapprimitive2d.hxx>
#include <drawinglayer/primitive2d/animatedprimitive2d.hxx>
#include <drawinglayer/primitive2d/metafileprimitive2d.hxx>
#include <drawinglayer/primitive2d/transformprimitive2d.hxx>
#include <drawinglayer/primitive2d/maskprimitive2d.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
//////////////////////////////////////////////////////////////////////////////
// helper class for animated graphics
#include <vcl/animate.hxx>
#include <vcl/graph.hxx>
#include <vcl/virdev.hxx>
#include <vcl/svapp.hxx>
#include <vcl/metaact.hxx>
//////////////////////////////////////////////////////////////////////////////
// includes for testing MetafilePrimitive2D::create2DDecomposition
//////////////////////////////////////////////////////////////////////////////
namespace
{
struct animationStep
{
BitmapEx maBitmapEx;
sal_uInt32 mnTime;
};
class animatedBitmapExPreparator
{
::Animation maAnimation;
::std::vector< animationStep > maSteps;
sal_uInt32 generateStepTime(sal_uInt32 nIndex) const;
public:
animatedBitmapExPreparator(const Graphic& rGraphic);
sal_uInt32 count() const { return maSteps.size(); }
sal_uInt32 loopCount() const { return (sal_uInt32)maAnimation.GetLoopCount(); }
sal_uInt32 stepTime(sal_uInt32 a) const { return maSteps[a].mnTime; }
const BitmapEx& stepBitmapEx(sal_uInt32 a) const { return maSteps[a].maBitmapEx; }
};
sal_uInt32 animatedBitmapExPreparator::generateStepTime(sal_uInt32 nIndex) const
{
const AnimationBitmap& rAnimBitmap = maAnimation.Get(sal_uInt16(nIndex));
sal_uInt32 nWaitTime(rAnimBitmap.nWait * 10);
// #115934#
// Take care of special value for MultiPage TIFFs. ATM these shall just
// show their first page. Later we will offer some switching when object
// is selected.
if(ANIMATION_TIMEOUT_ON_CLICK == rAnimBitmap.nWait)
{
// ATM the huge value would block the timer, so
// use a long time to show first page (whole day)
nWaitTime = 100 * 60 * 60 * 24;
}
// Bad trap: There are animated gifs with no set WaitTime (!).
// In that case use a default value.
if(0L == nWaitTime)
{
nWaitTime = 100L;
}
return nWaitTime;
}
animatedBitmapExPreparator::animatedBitmapExPreparator(const Graphic& rGraphic)
: maAnimation(rGraphic.GetAnimation())
{
OSL_ENSURE(GRAPHIC_BITMAP == rGraphic.GetType() && rGraphic.IsAnimated(), "animatedBitmapExPreparator: graphic is not animated (!)");
// #128539# secure access to Animation, looks like there exist animated GIFs out there
// with a step count of zero
if(maAnimation.Count())
{
VirtualDevice aVirtualDevice(*Application::GetDefaultDevice());
VirtualDevice aVirtualDeviceMask(*Application::GetDefaultDevice(), 1L);
// Prepare VirtualDevices and their states
aVirtualDevice.EnableMapMode(sal_False);
aVirtualDeviceMask.EnableMapMode(sal_False);
aVirtualDevice.SetOutputSizePixel(maAnimation.GetDisplaySizePixel());
aVirtualDeviceMask.SetOutputSizePixel(maAnimation.GetDisplaySizePixel());
aVirtualDevice.Erase();
aVirtualDeviceMask.Erase();
for(sal_uInt16 a(0L); a < maAnimation.Count(); a++)
{
animationStep aNextStep;
aNextStep.mnTime = generateStepTime(a);
// prepare step
const AnimationBitmap& rAnimBitmap = maAnimation.Get(sal_uInt16(a));
switch(rAnimBitmap.eDisposal)
{
case DISPOSE_NOT:
{
aVirtualDevice.DrawBitmapEx(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx);
Bitmap aMask = rAnimBitmap.aBmpEx.GetMask();
if(aMask.IsEmpty())
{
const Point aEmpty;
const Rectangle aRect(aEmpty, aVirtualDeviceMask.GetOutputSizePixel());
const Wallpaper aWallpaper(COL_BLACK);
aVirtualDeviceMask.DrawWallpaper(aRect, aWallpaper);
}
else
{
BitmapEx aExpandVisibilityMask = BitmapEx(aMask, aMask);
aVirtualDeviceMask.DrawBitmapEx(rAnimBitmap.aPosPix, aExpandVisibilityMask);
}
break;
}
case DISPOSE_BACK:
{
// #i70772# react on no mask, for primitives, too.
const Bitmap aMask(rAnimBitmap.aBmpEx.GetMask());
const Bitmap aContent(rAnimBitmap.aBmpEx.GetBitmap());
aVirtualDeviceMask.Erase();
aVirtualDevice.DrawBitmap(rAnimBitmap.aPosPix, aContent);
if(aMask.IsEmpty())
{
const Rectangle aRect(rAnimBitmap.aPosPix, aContent.GetSizePixel());
aVirtualDeviceMask.SetFillColor(COL_BLACK);
aVirtualDeviceMask.SetLineColor();
aVirtualDeviceMask.DrawRect(aRect);
}
else
{
aVirtualDeviceMask.DrawBitmap(rAnimBitmap.aPosPix, aMask);
}
break;
}
case DISPOSE_FULL:
{
aVirtualDevice.DrawBitmapEx(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx);
break;
}
case DISPOSE_PREVIOUS :
{
aVirtualDevice.DrawBitmapEx(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx);
aVirtualDeviceMask.DrawBitmap(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx.GetMask());
break;
}
}
// create BitmapEx
Bitmap aMainBitmap = aVirtualDevice.GetBitmap(Point(), aVirtualDevice.GetOutputSizePixel());
#if defined(MACOSX)
AlphaMask aMaskBitmap( aVirtualDeviceMask.GetBitmap( Point(), aVirtualDeviceMask.GetOutputSizePixel()));
#else
Bitmap aMaskBitmap = aVirtualDeviceMask.GetBitmap( Point(), aVirtualDeviceMask.GetOutputSizePixel());
#endif
aNextStep.maBitmapEx = BitmapEx(aMainBitmap, aMaskBitmap);
// add to vector
maSteps.push_back(aNextStep);
}
}
}
} // end of anonymous namespace
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
Primitive2DSequence create2DDecompositionOfGraphic(
const Graphic& rGraphic,
const basegfx::B2DHomMatrix& rTransform)
{
Primitive2DSequence aRetval;
switch(rGraphic.GetType())
{
case GRAPHIC_BITMAP :
{
if(rGraphic.IsAnimated())
{
// prepare animation data
animatedBitmapExPreparator aData(rGraphic);
if(aData.count())
{
// create sub-primitives for animated bitmap and the needed animation loop
animation::AnimationEntryLoop aAnimationLoop(aData.loopCount() ? aData.loopCount() : 0xffff);
Primitive2DSequence aBitmapPrimitives(aData.count());
for(sal_uInt32 a(0); a < aData.count(); a++)
{
animation::AnimationEntryFixed aTime((double)aData.stepTime(a), (double)a / (double)aData.count());
aAnimationLoop.append(aTime);
aBitmapPrimitives[a] = new BitmapPrimitive2D(
aData.stepBitmapEx(a),
rTransform);
}
// prepare animation list
animation::AnimationEntryList aAnimationList;
aAnimationList.append(aAnimationLoop);
// create and add animated switch primitive
aRetval.realloc(1);
aRetval[0] = new AnimatedSwitchPrimitive2D(
aAnimationList,
aBitmapPrimitives,
false);
}
}
else if(rGraphic.getSvgData().get())
{
// embedded Svg fill, create embed transform
const basegfx::B2DRange& rSvgRange(rGraphic.getSvgData()->getRange());
if(basegfx::fTools::more(rSvgRange.getWidth(), 0.0) && basegfx::fTools::more(rSvgRange.getHeight(), 0.0))
{
// translate back to origin, scale to unit coordinates
basegfx::B2DHomMatrix aEmbedSvg(
basegfx::tools::createTranslateB2DHomMatrix(
-rSvgRange.getMinX(),
-rSvgRange.getMinY()));
aEmbedSvg.scale(
1.0 / rSvgRange.getWidth(),
1.0 / rSvgRange.getHeight());
// apply created object transformation
aEmbedSvg = rTransform * aEmbedSvg;
// add Svg primitives embedded
aRetval.realloc(1);
aRetval[0] = new TransformPrimitive2D(
aEmbedSvg,
rGraphic.getSvgData()->getPrimitive2DSequence());
}
}
else
{
aRetval.realloc(1);
aRetval[0] = new BitmapPrimitive2D(
rGraphic.GetBitmapEx(),
rTransform);
}
break;
}
case GRAPHIC_GDIMETAFILE :
{
// create MetafilePrimitive2D
const GDIMetaFile& rMetafile = rGraphic.GetGDIMetaFile();
aRetval.realloc(1);
aRetval[0] = new MetafilePrimitive2D(
rTransform,
rMetafile);
// #i100357# find out if clipping is needed for this primitive. Unfortunately,
// there exist Metafiles who's content is bigger than the proposed PrefSize set
// at them. This is an error, but we need to work around this
const Size aMetaFilePrefSize(rMetafile.GetPrefSize());
const Size aMetaFileRealSize(
const_cast< GDIMetaFile& >(rMetafile).GetBoundRect(
*Application::GetDefaultDevice()).GetSize());
if(aMetaFileRealSize.getWidth() > aMetaFilePrefSize.getWidth()
|| aMetaFileRealSize.getHeight() > aMetaFilePrefSize.getHeight())
{
// clipping needed. Embed to MaskPrimitive2D. Create children and mask polygon
basegfx::B2DPolygon aMaskPolygon(basegfx::tools::createUnitPolygon());
aMaskPolygon.transform(rTransform);
aRetval[0] = new MaskPrimitive2D(
basegfx::B2DPolyPolygon(aMaskPolygon),
aRetval);
}
break;
}
default:
{
// nothing to create
break;
}
}
return aRetval;
}
} // end of namespace primitive2d
} // end of namespace drawinglayer
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#70090: Avoid race in copy vs. modification of aRetval Sequence<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <drawinglayer/primitive2d/graphicprimitivehelper2d.hxx>
#include <drawinglayer/animation/animationtiming.hxx>
#include <drawinglayer/primitive2d/bitmapprimitive2d.hxx>
#include <drawinglayer/primitive2d/animatedprimitive2d.hxx>
#include <drawinglayer/primitive2d/metafileprimitive2d.hxx>
#include <drawinglayer/primitive2d/transformprimitive2d.hxx>
#include <drawinglayer/primitive2d/maskprimitive2d.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
//////////////////////////////////////////////////////////////////////////////
// helper class for animated graphics
#include <vcl/animate.hxx>
#include <vcl/graph.hxx>
#include <vcl/virdev.hxx>
#include <vcl/svapp.hxx>
#include <vcl/metaact.hxx>
//////////////////////////////////////////////////////////////////////////////
// includes for testing MetafilePrimitive2D::create2DDecomposition
//////////////////////////////////////////////////////////////////////////////
namespace
{
struct animationStep
{
BitmapEx maBitmapEx;
sal_uInt32 mnTime;
};
class animatedBitmapExPreparator
{
::Animation maAnimation;
::std::vector< animationStep > maSteps;
sal_uInt32 generateStepTime(sal_uInt32 nIndex) const;
public:
animatedBitmapExPreparator(const Graphic& rGraphic);
sal_uInt32 count() const { return maSteps.size(); }
sal_uInt32 loopCount() const { return (sal_uInt32)maAnimation.GetLoopCount(); }
sal_uInt32 stepTime(sal_uInt32 a) const { return maSteps[a].mnTime; }
const BitmapEx& stepBitmapEx(sal_uInt32 a) const { return maSteps[a].maBitmapEx; }
};
sal_uInt32 animatedBitmapExPreparator::generateStepTime(sal_uInt32 nIndex) const
{
const AnimationBitmap& rAnimBitmap = maAnimation.Get(sal_uInt16(nIndex));
sal_uInt32 nWaitTime(rAnimBitmap.nWait * 10);
// #115934#
// Take care of special value for MultiPage TIFFs. ATM these shall just
// show their first page. Later we will offer some switching when object
// is selected.
if(ANIMATION_TIMEOUT_ON_CLICK == rAnimBitmap.nWait)
{
// ATM the huge value would block the timer, so
// use a long time to show first page (whole day)
nWaitTime = 100 * 60 * 60 * 24;
}
// Bad trap: There are animated gifs with no set WaitTime (!).
// In that case use a default value.
if(0L == nWaitTime)
{
nWaitTime = 100L;
}
return nWaitTime;
}
animatedBitmapExPreparator::animatedBitmapExPreparator(const Graphic& rGraphic)
: maAnimation(rGraphic.GetAnimation())
{
OSL_ENSURE(GRAPHIC_BITMAP == rGraphic.GetType() && rGraphic.IsAnimated(), "animatedBitmapExPreparator: graphic is not animated (!)");
// #128539# secure access to Animation, looks like there exist animated GIFs out there
// with a step count of zero
if(maAnimation.Count())
{
VirtualDevice aVirtualDevice(*Application::GetDefaultDevice());
VirtualDevice aVirtualDeviceMask(*Application::GetDefaultDevice(), 1L);
// Prepare VirtualDevices and their states
aVirtualDevice.EnableMapMode(sal_False);
aVirtualDeviceMask.EnableMapMode(sal_False);
aVirtualDevice.SetOutputSizePixel(maAnimation.GetDisplaySizePixel());
aVirtualDeviceMask.SetOutputSizePixel(maAnimation.GetDisplaySizePixel());
aVirtualDevice.Erase();
aVirtualDeviceMask.Erase();
for(sal_uInt16 a(0L); a < maAnimation.Count(); a++)
{
animationStep aNextStep;
aNextStep.mnTime = generateStepTime(a);
// prepare step
const AnimationBitmap& rAnimBitmap = maAnimation.Get(sal_uInt16(a));
switch(rAnimBitmap.eDisposal)
{
case DISPOSE_NOT:
{
aVirtualDevice.DrawBitmapEx(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx);
Bitmap aMask = rAnimBitmap.aBmpEx.GetMask();
if(aMask.IsEmpty())
{
const Point aEmpty;
const Rectangle aRect(aEmpty, aVirtualDeviceMask.GetOutputSizePixel());
const Wallpaper aWallpaper(COL_BLACK);
aVirtualDeviceMask.DrawWallpaper(aRect, aWallpaper);
}
else
{
BitmapEx aExpandVisibilityMask = BitmapEx(aMask, aMask);
aVirtualDeviceMask.DrawBitmapEx(rAnimBitmap.aPosPix, aExpandVisibilityMask);
}
break;
}
case DISPOSE_BACK:
{
// #i70772# react on no mask, for primitives, too.
const Bitmap aMask(rAnimBitmap.aBmpEx.GetMask());
const Bitmap aContent(rAnimBitmap.aBmpEx.GetBitmap());
aVirtualDeviceMask.Erase();
aVirtualDevice.DrawBitmap(rAnimBitmap.aPosPix, aContent);
if(aMask.IsEmpty())
{
const Rectangle aRect(rAnimBitmap.aPosPix, aContent.GetSizePixel());
aVirtualDeviceMask.SetFillColor(COL_BLACK);
aVirtualDeviceMask.SetLineColor();
aVirtualDeviceMask.DrawRect(aRect);
}
else
{
aVirtualDeviceMask.DrawBitmap(rAnimBitmap.aPosPix, aMask);
}
break;
}
case DISPOSE_FULL:
{
aVirtualDevice.DrawBitmapEx(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx);
break;
}
case DISPOSE_PREVIOUS :
{
aVirtualDevice.DrawBitmapEx(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx);
aVirtualDeviceMask.DrawBitmap(rAnimBitmap.aPosPix, rAnimBitmap.aBmpEx.GetMask());
break;
}
}
// create BitmapEx
Bitmap aMainBitmap = aVirtualDevice.GetBitmap(Point(), aVirtualDevice.GetOutputSizePixel());
#if defined(MACOSX)
AlphaMask aMaskBitmap( aVirtualDeviceMask.GetBitmap( Point(), aVirtualDeviceMask.GetOutputSizePixel()));
#else
Bitmap aMaskBitmap = aVirtualDeviceMask.GetBitmap( Point(), aVirtualDeviceMask.GetOutputSizePixel());
#endif
aNextStep.maBitmapEx = BitmapEx(aMainBitmap, aMaskBitmap);
// add to vector
maSteps.push_back(aNextStep);
}
}
}
} // end of anonymous namespace
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
Primitive2DSequence create2DDecompositionOfGraphic(
const Graphic& rGraphic,
const basegfx::B2DHomMatrix& rTransform)
{
Primitive2DSequence aRetval;
switch(rGraphic.GetType())
{
case GRAPHIC_BITMAP :
{
if(rGraphic.IsAnimated())
{
// prepare animation data
animatedBitmapExPreparator aData(rGraphic);
if(aData.count())
{
// create sub-primitives for animated bitmap and the needed animation loop
animation::AnimationEntryLoop aAnimationLoop(aData.loopCount() ? aData.loopCount() : 0xffff);
Primitive2DSequence aBitmapPrimitives(aData.count());
for(sal_uInt32 a(0); a < aData.count(); a++)
{
animation::AnimationEntryFixed aTime((double)aData.stepTime(a), (double)a / (double)aData.count());
aAnimationLoop.append(aTime);
aBitmapPrimitives[a] = new BitmapPrimitive2D(
aData.stepBitmapEx(a),
rTransform);
}
// prepare animation list
animation::AnimationEntryList aAnimationList;
aAnimationList.append(aAnimationLoop);
// create and add animated switch primitive
aRetval.realloc(1);
aRetval[0] = new AnimatedSwitchPrimitive2D(
aAnimationList,
aBitmapPrimitives,
false);
}
}
else if(rGraphic.getSvgData().get())
{
// embedded Svg fill, create embed transform
const basegfx::B2DRange& rSvgRange(rGraphic.getSvgData()->getRange());
if(basegfx::fTools::more(rSvgRange.getWidth(), 0.0) && basegfx::fTools::more(rSvgRange.getHeight(), 0.0))
{
// translate back to origin, scale to unit coordinates
basegfx::B2DHomMatrix aEmbedSvg(
basegfx::tools::createTranslateB2DHomMatrix(
-rSvgRange.getMinX(),
-rSvgRange.getMinY()));
aEmbedSvg.scale(
1.0 / rSvgRange.getWidth(),
1.0 / rSvgRange.getHeight());
// apply created object transformation
aEmbedSvg = rTransform * aEmbedSvg;
// add Svg primitives embedded
aRetval.realloc(1);
aRetval[0] = new TransformPrimitive2D(
aEmbedSvg,
rGraphic.getSvgData()->getPrimitive2DSequence());
}
}
else
{
aRetval.realloc(1);
aRetval[0] = new BitmapPrimitive2D(
rGraphic.GetBitmapEx(),
rTransform);
}
break;
}
case GRAPHIC_GDIMETAFILE :
{
// create MetafilePrimitive2D
const GDIMetaFile& rMetafile = rGraphic.GetGDIMetaFile();
aRetval.realloc(1);
aRetval[0] = new MetafilePrimitive2D(
rTransform,
rMetafile);
// #i100357# find out if clipping is needed for this primitive. Unfortunately,
// there exist Metafiles who's content is bigger than the proposed PrefSize set
// at them. This is an error, but we need to work around this
const Size aMetaFilePrefSize(rMetafile.GetPrefSize());
const Size aMetaFileRealSize(
const_cast< GDIMetaFile& >(rMetafile).GetBoundRect(
*Application::GetDefaultDevice()).GetSize());
if(aMetaFileRealSize.getWidth() > aMetaFilePrefSize.getWidth()
|| aMetaFileRealSize.getHeight() > aMetaFilePrefSize.getHeight())
{
// clipping needed. Embed to MaskPrimitive2D. Create children and mask polygon
basegfx::B2DPolygon aMaskPolygon(basegfx::tools::createUnitPolygon());
aMaskPolygon.transform(rTransform);
Primitive2DReference mask = new MaskPrimitive2D(
basegfx::B2DPolyPolygon(aMaskPolygon),
aRetval);
aRetval[0] = mask;
}
break;
}
default:
{
// nothing to create
break;
}
}
return aRetval;
}
} // end of namespace primitive2d
} // end of namespace drawinglayer
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "ToolWindowManagerArea.h"
#include "ToolWindowManager.h"
#include <QApplication>
#include <QMouseEvent>
#include <QDebug>
ToolWindowManagerArea::ToolWindowManagerArea(ToolWindowManager *manager, QWidget *parent) :
QTabWidget(parent)
, m_manager(manager)
{
m_dragCanStart = false;
m_tabDragCanStart = false;
m_inTabMoved = false;
setMovable(true);
setTabsClosable(true);
setDocumentMode(true);
tabBar()->installEventFilter(this);
m_manager->m_areas << this;
QObject::connect(tabBar(), &QTabBar::tabMoved, this, &ToolWindowManagerArea::tabMoved);
}
ToolWindowManagerArea::~ToolWindowManagerArea() {
m_manager->m_areas.removeOne(this);
}
void ToolWindowManagerArea::addToolWindow(QWidget *toolWindow) {
addToolWindows(QList<QWidget*>() << toolWindow);
}
void ToolWindowManagerArea::addToolWindows(const QList<QWidget *> &toolWindows) {
int index = 0;
foreach(QWidget* toolWindow, toolWindows) {
index = addTab(toolWindow, toolWindow->windowIcon(), toolWindow->windowTitle());
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
}
}
setCurrentIndex(index);
m_manager->m_lastUsedArea = this;
}
QList<QWidget *> ToolWindowManagerArea::toolWindows() {
QList<QWidget *> result;
for(int i = 0; i < count(); i++) {
result << widget(i);
}
return result;
}
void ToolWindowManagerArea::updateToolWindow(QWidget* toolWindow) {
int index = indexOf(toolWindow);
if(index >= 0) {
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
} else {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(16, 16);
}
tabBar()->setTabText(index, toolWindow->windowTitle());
}
}
void ToolWindowManagerArea::mousePressEvent(QMouseEvent *) {
if (qApp->mouseButtons() == Qt::LeftButton) {
m_dragCanStart = true;
}
}
void ToolWindowManagerArea::mouseReleaseEvent(QMouseEvent *) {
m_dragCanStart = false;
m_manager->updateDragPosition();
}
void ToolWindowManagerArea::mouseMoveEvent(QMouseEvent *) {
check_mouse_move();
}
bool ToolWindowManagerArea::eventFilter(QObject *object, QEvent *event) {
if (object == tabBar()) {
if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::LeftButton) {
int tabIndex = tabBar()->tabAt(static_cast<QMouseEvent*>(event)->pos());
// can start tab drag only if mouse is at some tab, not at empty tabbar space
if (tabIndex >= 0) {
m_tabDragCanStart = true;
if (m_manager->toolWindowProperties(widget(tabIndex)) & ToolWindowManager::DisableDraggableTab) {
setMovable(false);
} else {
setMovable(true);
}
} else {
m_dragCanStart = true;
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_tabDragCanStart = false;
m_dragCanStart = false;
m_manager->updateDragPosition();
} else if (event->type() == QEvent::MouseMove) {
m_manager->updateDragPosition();
if (m_tabDragCanStart) {
if (tabBar()->rect().contains(static_cast<QMouseEvent*>(event)->pos())) {
return false;
}
if (qApp->mouseButtons() != Qt::LeftButton) {
return false;
}
QWidget* toolWindow = currentWidget();
if (!toolWindow || !m_manager->m_toolWindows.contains(toolWindow)) {
return false;
}
m_tabDragCanStart = false;
//stop internal tab drag in QTabBar
QMouseEvent* releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
static_cast<QMouseEvent*>(event)->pos(),
Qt::LeftButton, Qt::LeftButton, 0);
qApp->sendEvent(tabBar(), releaseEvent);
m_manager->startDrag(QList<QWidget*>() << toolWindow);
} else if (m_dragCanStart) {
check_mouse_move();
}
}
}
return QTabWidget::eventFilter(object, event);
}
QVariantMap ToolWindowManagerArea::saveState() {
QVariantMap result;
result["type"] = "area";
result["currentIndex"] = currentIndex();
QStringList objectNames;
for(int i = 0; i < count(); i++) {
QString name = widget(i)->objectName();
if (name.isEmpty()) {
qWarning("cannot save state of tool window without object name");
} else {
objectNames << name;
}
}
result["objectNames"] = objectNames;
return result;
}
void ToolWindowManagerArea::restoreState(const QVariantMap &data) {
foreach(QVariant objectNameValue, data["objectNames"].toList()) {
QString objectName = objectNameValue.toString();
if (objectName.isEmpty()) { continue; }
bool found = false;
foreach(QWidget* toolWindow, m_manager->m_toolWindows) {
if (toolWindow->objectName() == objectName) {
addToolWindow(toolWindow);
found = true;
break;
}
}
if (!found) {
qWarning("tool window with name '%s' not found", objectName.toLocal8Bit().constData());
}
}
setCurrentIndex(data["currentIndex"].toInt());
}
void ToolWindowManagerArea::check_mouse_move() {
m_manager->updateDragPosition();
if (qApp->mouseButtons() == Qt::LeftButton &&
!rect().contains(mapFromGlobal(QCursor::pos())) &&
m_dragCanStart) {
m_dragCanStart = false;
QList<QWidget*> toolWindows;
for(int i = 0; i < count(); i++) {
QWidget* toolWindow = widget(i);
if (!m_manager->m_toolWindows.contains(toolWindow)) {
qWarning("tab widget contains unmanaged widget");
} else {
toolWindows << toolWindow;
}
}
m_manager->startDrag(toolWindows);
}
}
void ToolWindowManagerArea::tabMoved(int from, int to) {
if(m_inTabMoved) return;
QWidget *a = widget(from);
QWidget *b = widget(to);
if(!a || !b) return;
if(m_manager->toolWindowProperties(a) & ToolWindowManager::DisableDraggableTab ||
m_manager->toolWindowProperties(b) & ToolWindowManager::DisableDraggableTab)
{
m_inTabMoved = true;
tabBar()->moveTab(to, from);
m_inTabMoved = false;
}
}
<commit_msg>Serialise area objects as [name, data] pairs, with custom persist data<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "ToolWindowManagerArea.h"
#include "ToolWindowManager.h"
#include <QApplication>
#include <QMouseEvent>
#include <QDebug>
ToolWindowManagerArea::ToolWindowManagerArea(ToolWindowManager *manager, QWidget *parent) :
QTabWidget(parent)
, m_manager(manager)
{
m_dragCanStart = false;
m_tabDragCanStart = false;
m_inTabMoved = false;
setMovable(true);
setTabsClosable(true);
setDocumentMode(true);
tabBar()->installEventFilter(this);
m_manager->m_areas << this;
QObject::connect(tabBar(), &QTabBar::tabMoved, this, &ToolWindowManagerArea::tabMoved);
}
ToolWindowManagerArea::~ToolWindowManagerArea() {
m_manager->m_areas.removeOne(this);
}
void ToolWindowManagerArea::addToolWindow(QWidget *toolWindow) {
addToolWindows(QList<QWidget*>() << toolWindow);
}
void ToolWindowManagerArea::addToolWindows(const QList<QWidget *> &toolWindows) {
int index = 0;
foreach(QWidget* toolWindow, toolWindows) {
index = addTab(toolWindow, toolWindow->windowIcon(), toolWindow->windowTitle());
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
}
}
setCurrentIndex(index);
m_manager->m_lastUsedArea = this;
}
QList<QWidget *> ToolWindowManagerArea::toolWindows() {
QList<QWidget *> result;
for(int i = 0; i < count(); i++) {
result << widget(i);
}
return result;
}
void ToolWindowManagerArea::updateToolWindow(QWidget* toolWindow) {
int index = indexOf(toolWindow);
if(index >= 0) {
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
} else {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(16, 16);
}
tabBar()->setTabText(index, toolWindow->windowTitle());
}
}
void ToolWindowManagerArea::mousePressEvent(QMouseEvent *) {
if (qApp->mouseButtons() == Qt::LeftButton) {
m_dragCanStart = true;
}
}
void ToolWindowManagerArea::mouseReleaseEvent(QMouseEvent *) {
m_dragCanStart = false;
m_manager->updateDragPosition();
}
void ToolWindowManagerArea::mouseMoveEvent(QMouseEvent *) {
check_mouse_move();
}
bool ToolWindowManagerArea::eventFilter(QObject *object, QEvent *event) {
if (object == tabBar()) {
if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::LeftButton) {
int tabIndex = tabBar()->tabAt(static_cast<QMouseEvent*>(event)->pos());
// can start tab drag only if mouse is at some tab, not at empty tabbar space
if (tabIndex >= 0) {
m_tabDragCanStart = true;
if (m_manager->toolWindowProperties(widget(tabIndex)) & ToolWindowManager::DisableDraggableTab) {
setMovable(false);
} else {
setMovable(true);
}
} else {
m_dragCanStart = true;
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_tabDragCanStart = false;
m_dragCanStart = false;
m_manager->updateDragPosition();
} else if (event->type() == QEvent::MouseMove) {
m_manager->updateDragPosition();
if (m_tabDragCanStart) {
if (tabBar()->rect().contains(static_cast<QMouseEvent*>(event)->pos())) {
return false;
}
if (qApp->mouseButtons() != Qt::LeftButton) {
return false;
}
QWidget* toolWindow = currentWidget();
if (!toolWindow || !m_manager->m_toolWindows.contains(toolWindow)) {
return false;
}
m_tabDragCanStart = false;
//stop internal tab drag in QTabBar
QMouseEvent* releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
static_cast<QMouseEvent*>(event)->pos(),
Qt::LeftButton, Qt::LeftButton, 0);
qApp->sendEvent(tabBar(), releaseEvent);
m_manager->startDrag(QList<QWidget*>() << toolWindow);
} else if (m_dragCanStart) {
check_mouse_move();
}
}
}
return QTabWidget::eventFilter(object, event);
}
QVariantMap ToolWindowManagerArea::saveState() {
QVariantMap result;
result["type"] = "area";
result["currentIndex"] = currentIndex();
QVariantList objects;
objects.reserve(count());
for(int i = 0; i < count(); i++) {
QWidget *w = widget(i);
QString name = w->objectName();
if (name.isEmpty()) {
qWarning("cannot save state of tool window without object name");
} else {
QVariantMap objectData;
objectData["name"] = name;
objectData["data"] = w->property("persistData");
objects.push_back(objectData);
}
}
result["objects"] = objects;
return result;
}
void ToolWindowManagerArea::restoreState(const QVariantMap &data) {
foreach(QVariant object, data["objects"].toList()) {
QVariantMap objectData = object.toMap();
if (objectData.isEmpty()) { continue; }
QString objectName = objectData["name"].toString();
if (objectName.isEmpty()) { continue; }
QWidget *t = NULL;
foreach(QWidget* toolWindow, m_manager->m_toolWindows) {
if (toolWindow->objectName() == objectName) {
t = toolWindow;
break;
}
}
if (t) {
t->setProperty("persistData", objectData["data"]);
addToolWindow(t);
} else {
qWarning("tool window with name '%s' not found or created", objectName.toLocal8Bit().constData());
}
}
setCurrentIndex(data["currentIndex"].toInt());
}
void ToolWindowManagerArea::check_mouse_move() {
m_manager->updateDragPosition();
if (qApp->mouseButtons() == Qt::LeftButton &&
!rect().contains(mapFromGlobal(QCursor::pos())) &&
m_dragCanStart) {
m_dragCanStart = false;
QList<QWidget*> toolWindows;
for(int i = 0; i < count(); i++) {
QWidget* toolWindow = widget(i);
if (!m_manager->m_toolWindows.contains(toolWindow)) {
qWarning("tab widget contains unmanaged widget");
} else {
toolWindows << toolWindow;
}
}
m_manager->startDrag(toolWindows);
}
}
void ToolWindowManagerArea::tabMoved(int from, int to) {
if(m_inTabMoved) return;
QWidget *a = widget(from);
QWidget *b = widget(to);
if(!a || !b) return;
if(m_manager->toolWindowProperties(a) & ToolWindowManager::DisableDraggableTab ||
m_manager->toolWindowProperties(b) & ToolWindowManager::DisableDraggableTab)
{
m_inTabMoved = true;
tabBar()->moveTab(to, from);
m_inTabMoved = false;
}
}
<|endoftext|> |
<commit_before>//
// kern_nvhda.cpp
// WhateverGreen
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include "kern_nvhda.hpp"
#include <Headers/kern_util.hpp>
#include <libkern/libkern.h>
#include <IOKit/pci/IOPCIDevice.h>
#include <IOKit/IODeviceTreeSupport.h>
// Workaround for systems with BIOSes that default-disable the HD Audio function on their NVIDIA GPUs.
// We match the device with a higher IOProbeScore than the NVIDIA drivers, use our probe routine to
// enable the HD Audio function, trigger a PCI rescan, and then return a probe failure so that the
// real driver can continue to load.
//
// References:
// https://bugs.freedesktop.org/show_bug.cgi?id=75985
// https://devtalk.nvidia.com/default/topic/1024022/linux/gtx-1060-no-audio-over-hdmi-only-hda-intel-detected-azalia/
// https://github.com/acidanthera/bugtracker/issues/292
OSDefineMetaClassAndStructors(NVHDAEnabler, IOService);
IOService* NVHDAEnabler::probe(IOService *provider, SInt32 *score) {
auto pciDevice = OSDynamicCast(IOPCIDevice, provider);
if (!pciDevice) {
SYSLOG("NVHDAEnabler", "probe: pciDevice is NULL");
return nullptr;
}
uint32_t hdaEnableDword = pciDevice->configRead32(HDAEnableReg);
if (hdaEnableDword & HDAEnableBit) {
DBGLOG("NVHDAEnabler", "probe: HDA enable bit is already set, nothing to do");
return nullptr;
}
DBGLOG("NVHDAEnabler", "probe: reg is 0x%x, setting HDA enable bit", hdaEnableDword);
hdaEnableDword |= HDAEnableBit;
pciDevice->configWrite32(HDAEnableReg, hdaEnableDword);
// Verify with readback
DBGLOG("NVHDAEnabler", "probe: readback: reg is 0x%x", pciDevice->configRead32(HDAEnableReg));
// Find the parent IOPCIBridge
auto parentBridge = OSDynamicCast(IOPCIDevice, pciDevice->getParentEntry(gIODTPlane));
if (!parentBridge) {
DBGLOG("NVHDAEnabler", "probe: Can't find the parent bridge's IOPCIDevice");
return nullptr;
}
DBGLOG("NVHDAEnabler", "probe: Requesting parent bridge rescan");
// Mark this device and the parent bridge as needing scanning, then trigger the rescan.
pciDevice->kernelRequestProbe(kIOPCIProbeOptionNeedsScan);
parentBridge->kernelRequestProbe(kIOPCIProbeOptionNeedsScan | kIOPCIProbeOptionDone);
// This probe must always fail so that the real driver can get a chance to load afterwards.
return nullptr;
}
bool NVHDAEnabler::start(IOService *provider) {
SYSLOG("NVHDAEnabler", "start: shouldn't be called!");
return false;
}
<commit_msg>Fix compiler warning with latest 10.15 SDK<commit_after>//
// kern_nvhda.cpp
// WhateverGreen
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include "kern_nvhda.hpp"
#include <Headers/kern_util.hpp>
#include <libkern/libkern.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winconsistent-missing-override"
#include <IOKit/pci/IOPCIDevice.h>
#pragma clang diagnostic pop
#include <IOKit/IODeviceTreeSupport.h>
// Workaround for systems with BIOSes that default-disable the HD Audio function on their NVIDIA GPUs.
// We match the device with a higher IOProbeScore than the NVIDIA drivers, use our probe routine to
// enable the HD Audio function, trigger a PCI rescan, and then return a probe failure so that the
// real driver can continue to load.
//
// References:
// https://bugs.freedesktop.org/show_bug.cgi?id=75985
// https://devtalk.nvidia.com/default/topic/1024022/linux/gtx-1060-no-audio-over-hdmi-only-hda-intel-detected-azalia/
// https://github.com/acidanthera/bugtracker/issues/292
OSDefineMetaClassAndStructors(NVHDAEnabler, IOService);
IOService* NVHDAEnabler::probe(IOService *provider, SInt32 *score) {
auto pciDevice = OSDynamicCast(IOPCIDevice, provider);
if (!pciDevice) {
SYSLOG("NVHDAEnabler", "probe: pciDevice is NULL");
return nullptr;
}
uint32_t hdaEnableDword = pciDevice->configRead32(HDAEnableReg);
if (hdaEnableDword & HDAEnableBit) {
DBGLOG("NVHDAEnabler", "probe: HDA enable bit is already set, nothing to do");
return nullptr;
}
DBGLOG("NVHDAEnabler", "probe: reg is 0x%x, setting HDA enable bit", hdaEnableDword);
hdaEnableDword |= HDAEnableBit;
pciDevice->configWrite32(HDAEnableReg, hdaEnableDword);
// Verify with readback
DBGLOG("NVHDAEnabler", "probe: readback: reg is 0x%x", pciDevice->configRead32(HDAEnableReg));
// Find the parent IOPCIBridge
auto parentBridge = OSDynamicCast(IOPCIDevice, pciDevice->getParentEntry(gIODTPlane));
if (!parentBridge) {
DBGLOG("NVHDAEnabler", "probe: Can't find the parent bridge's IOPCIDevice");
return nullptr;
}
DBGLOG("NVHDAEnabler", "probe: Requesting parent bridge rescan");
// Mark this device and the parent bridge as needing scanning, then trigger the rescan.
pciDevice->kernelRequestProbe(kIOPCIProbeOptionNeedsScan);
parentBridge->kernelRequestProbe(kIOPCIProbeOptionNeedsScan | kIOPCIProbeOptionDone);
// This probe must always fail so that the real driver can get a chance to load afterwards.
return nullptr;
}
bool NVHDAEnabler::start(IOService *provider) {
SYSLOG("NVHDAEnabler", "start: shouldn't be called!");
return false;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MasterPageObserver.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-07-31 17:25:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "MasterPageObserver.hxx"
#include <algorithm>
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include <hash_map>
#include <set>
#include <vector>
#include <svtools/lstner.hxx>
#ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H
#include <osl/doublecheckedlocking.h>
#endif
#ifndef INCLUDED_OSL_GETGLOBALMUTEX_HXX
#include <osl/getglobalmutex.hxx>
#endif
namespace sd {
class MasterPageObserver::Implementation
: public SfxListener
{
public:
/** The single instance of this class. It is created on demand when
Instance() is called for the first time.
*/
static MasterPageObserver* mpInstance;
/** The master page observer will listen to events of this document and
detect changes of the use of master pages.
*/
void RegisterDocument (SdDrawDocument& rDocument);
/** The master page observer will stop to listen to events of this
document.
*/
void UnregisterDocument (SdDrawDocument& rDocument);
/** Add a listener that is informed of master pages that are newly
assigned to slides or become unassigned.
@param rEventListener
The event listener to call for future events. Call
RemoveEventListener() before the listener is destroyed.
*/
void AddEventListener (const Link& rEventListener);
/** Remove the given listener from the list of listeners.
@param rEventListener
After this method returns the given listener is not called back
from this object. Passing a listener that has not
been registered before is safe and is silently ignored.
*/
void RemoveEventListener (const Link& rEventListener);
/** Return a set of the names of master pages for the given document.
This convenience method exists because this set is part of the
internal data structure and thus takes no time to create.
*/
inline MasterPageObserver::MasterPageNameSet GetMasterPageNames (
SdDrawDocument& rDocument);
private:
::std::vector<Link> maListeners;
struct DrawDocHash {
size_t operator()(SdDrawDocument* argument) const
{ return reinterpret_cast<unsigned long>(argument); }
};
typedef ::std::hash_map<SdDrawDocument*,
MasterPageObserver::MasterPageNameSet,
DrawDocHash>
MasterPageContainer;
MasterPageContainer maUsedMasterPages;
virtual void Notify(
SfxBroadcaster& rBroadcaster,
const SfxHint& rHint);
void AnalyzeUsedMasterPages (SdDrawDocument& rDocument);
void SendEvent (MasterPageObserverEvent& rEvent);
};
MasterPageObserver* MasterPageObserver::Implementation::mpInstance = NULL;
//===== MasterPageObserver ====================================================
MasterPageObserver& MasterPageObserver::Instance (void)
{
if (Implementation::mpInstance == NULL)
{
::osl::GetGlobalMutex aMutexFunctor;
::osl::MutexGuard aGuard (aMutexFunctor());
if (Implementation::mpInstance == NULL)
{
MasterPageObserver* pInstance = new MasterPageObserver ();
SdGlobalResourceContainer::Instance().AddResource (
::std::auto_ptr<SdGlobalResource>(pInstance));
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
Implementation::mpInstance = pInstance;
}
}
else
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
DBG_ASSERT(Implementation::mpInstance!=NULL,
"MasterPageObserver::Instance(): instance is NULL");
return *Implementation::mpInstance;
}
void MasterPageObserver::RegisterDocument (SdDrawDocument& rDocument)
{
mpImpl->RegisterDocument (rDocument);
}
void MasterPageObserver::UnregisterDocument (SdDrawDocument& rDocument)
{
mpImpl->UnregisterDocument (rDocument);
}
void MasterPageObserver::AddEventListener (const Link& rEventListener)
{
mpImpl->AddEventListener (rEventListener);
}
void MasterPageObserver::RemoveEventListener (const Link& rEventListener)
{
mpImpl->RemoveEventListener (rEventListener);
}
MasterPageObserver::MasterPageObserver (void)
: mpImpl (new Implementation())
{}
MasterPageObserver::~MasterPageObserver (void)
{}
MasterPageObserver::MasterPageNameSet MasterPageObserver::GetMasterPageNames (
SdDrawDocument& rDocument)
{
return mpImpl->GetMasterPageNames (rDocument);
}
//===== MasterPageObserver::Implementation ====================================
void MasterPageObserver::Implementation::RegisterDocument (
SdDrawDocument& rDocument)
{
// Gather the names of all the master pages in the given document.
MasterPageContainer::data_type aMasterPageSet;
USHORT nMasterPageCount = rDocument.GetMasterSdPageCount(PK_STANDARD);
for (USHORT nIndex=0; nIndex<nMasterPageCount; nIndex++)
{
SdPage* pMasterPage = rDocument.GetMasterSdPage (nIndex, PK_STANDARD);
if (pMasterPage != NULL)
aMasterPageSet.insert (pMasterPage->GetName());
}
maUsedMasterPages[&rDocument] = aMasterPageSet;
StartListening (rDocument);
}
void MasterPageObserver::Implementation::UnregisterDocument (
SdDrawDocument& rDocument)
{
EndListening (rDocument);
MasterPageContainer::iterator aMasterPageDescriptor(maUsedMasterPages.find(&rDocument));
if(aMasterPageDescriptor != maUsedMasterPages.end())
maUsedMasterPages.erase(aMasterPageDescriptor);
}
void MasterPageObserver::Implementation::AddEventListener (
const Link& rEventListener)
{
if (::std::find (
maListeners.begin(),
maListeners.end(),
rEventListener) == maListeners.end())
{
maListeners.push_back (rEventListener);
// Tell the new listener about all the master pages that are
// currently in use.
typedef ::std::vector<String> StringList;
StringList aNewMasterPages;
StringList aRemovedMasterPages;
MasterPageContainer::iterator aDocumentIterator;
for (aDocumentIterator=maUsedMasterPages.begin();
aDocumentIterator!=maUsedMasterPages.end();
++aDocumentIterator)
{
::std::set<String>::reverse_iterator aNameIterator;
for (aNameIterator=aDocumentIterator->second.rbegin();
aNameIterator!=aDocumentIterator->second.rend();
++aNameIterator)
{
MasterPageObserverEvent aEvent (
MasterPageObserverEvent::ET_MASTER_PAGE_EXISTS,
*aDocumentIterator->first,
*aNameIterator);
SendEvent (aEvent);
}
}
}
}
void MasterPageObserver::Implementation::RemoveEventListener (
const Link& rEventListener)
{
maListeners.erase (
::std::find (
maListeners.begin(),
maListeners.end(),
rEventListener));
}
MasterPageObserver::MasterPageNameSet
MasterPageObserver::Implementation::GetMasterPageNames (
SdDrawDocument& rDocument)
{
MasterPageContainer::iterator aMasterPageDescriptor (
maUsedMasterPages.find(&rDocument));
if (aMasterPageDescriptor != maUsedMasterPages.end())
return aMasterPageDescriptor->second;
else
// Not found so return an empty set.
return MasterPageObserver::MasterPageNameSet();
}
void MasterPageObserver::Implementation::Notify(
SfxBroadcaster& rBroadcaster,
const SfxHint& rHint)
{
if (rHint.ISA(SdrHint))
{
SdrHint& rSdrHint (*PTR_CAST(SdrHint,&rHint));
switch (rSdrHint.GetKind())
{
case HINT_PAGEORDERCHG:
// Process the modified set of pages only when the number of
// standard and notes master pages are equal. This test
// filters out events that are sent in between the insertion
// of a new standard master page and a new notes master
// page.
if (rBroadcaster.ISA(SdDrawDocument))
{
SdDrawDocument& rDocument (
static_cast<SdDrawDocument&>(rBroadcaster));
if (rDocument.GetMasterSdPageCount(PK_STANDARD)
== rDocument.GetMasterSdPageCount(PK_NOTES))
{
AnalyzeUsedMasterPages (rDocument);
}
}
break;
default:
break;
}
}
}
void MasterPageObserver::Implementation::AnalyzeUsedMasterPages (
SdDrawDocument& rDocument)
{
// Create a set of names of the master pages used by the given document.
USHORT nMasterPageCount = rDocument.GetMasterSdPageCount(PK_STANDARD);
::std::set<String> aCurrentMasterPages;
for (USHORT nIndex=0; nIndex<nMasterPageCount; nIndex++)
{
SdPage* pMasterPage = rDocument.GetMasterSdPage (nIndex, PK_STANDARD);
if (pMasterPage != NULL)
aCurrentMasterPages.insert (pMasterPage->GetName());
OSL_TRACE("currently used master page %d is %s",
nIndex,
::rtl::OUStringToOString(pMasterPage->GetName(),
RTL_TEXTENCODING_UTF8).getStr());
}
typedef ::std::vector<String> StringList;
StringList aNewMasterPages;
StringList aRemovedMasterPages;
MasterPageContainer::iterator aOldMasterPagesDescriptor (
maUsedMasterPages.find(&rDocument));
if (aOldMasterPagesDescriptor != maUsedMasterPages.end())
{
StringList::iterator I;
::std::set<String>::iterator J;
int i=0;
for (J=aOldMasterPagesDescriptor->second.begin();
J!=aOldMasterPagesDescriptor->second.end();
++J)
OSL_TRACE("old used master page %d is %s",
i++,
::rtl::OUStringToOString(*J,
RTL_TEXTENCODING_UTF8).getStr());
// Send events about the newly used master pages.
::std::set_difference (
aCurrentMasterPages.begin(),
aCurrentMasterPages.end(),
aOldMasterPagesDescriptor->second.begin(),
aOldMasterPagesDescriptor->second.end(),
::std::back_insert_iterator<StringList>(aNewMasterPages));
for (I=aNewMasterPages.begin(); I!=aNewMasterPages.end(); ++I)
{
OSL_TRACE(" added master page %s",
::rtl::OUStringToOString(*I,
RTL_TEXTENCODING_UTF8).getStr());
MasterPageObserverEvent aEvent (
MasterPageObserverEvent::ET_MASTER_PAGE_ADDED,
rDocument,
*I);
SendEvent (aEvent);
}
// Send events about master pages that are not used any longer.
::std::set_difference (
aOldMasterPagesDescriptor->second.begin(),
aOldMasterPagesDescriptor->second.end(),
aCurrentMasterPages.begin(),
aCurrentMasterPages.end(),
::std::back_insert_iterator<StringList>(aRemovedMasterPages));
for (I=aRemovedMasterPages.begin(); I!=aRemovedMasterPages.end(); ++I)
{
OSL_TRACE(" removed master page %s",
::rtl::OUStringToOString(*I,
RTL_TEXTENCODING_UTF8).getStr());
MasterPageObserverEvent aEvent (
MasterPageObserverEvent::ET_MASTER_PAGE_REMOVED,
rDocument,
*I);
SendEvent (aEvent);
}
// Store the new list of master pages.
aOldMasterPagesDescriptor->second = aCurrentMasterPages;
}
}
void MasterPageObserver::Implementation::SendEvent (
MasterPageObserverEvent& rEvent)
{
::std::vector<Link>::iterator aLink (maListeners.begin());
::std::vector<Link>::iterator aEnd (maListeners.end());
while (aLink!=aEnd)
{
aLink->Call (&rEvent);
++aLink;
}
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.7.166); FILE MERGED 2008/04/01 15:36:09 thb 1.7.166.2: #i85898# Stripping all external header guards 2008/03/31 13:59:02 rt 1.7.166.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: MasterPageObserver.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_sd.hxx"
#include "MasterPageObserver.hxx"
#include <algorithm>
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include <hash_map>
#include <set>
#include <vector>
#include <svtools/lstner.hxx>
#include <osl/doublecheckedlocking.h>
#include <osl/getglobalmutex.hxx>
namespace sd {
class MasterPageObserver::Implementation
: public SfxListener
{
public:
/** The single instance of this class. It is created on demand when
Instance() is called for the first time.
*/
static MasterPageObserver* mpInstance;
/** The master page observer will listen to events of this document and
detect changes of the use of master pages.
*/
void RegisterDocument (SdDrawDocument& rDocument);
/** The master page observer will stop to listen to events of this
document.
*/
void UnregisterDocument (SdDrawDocument& rDocument);
/** Add a listener that is informed of master pages that are newly
assigned to slides or become unassigned.
@param rEventListener
The event listener to call for future events. Call
RemoveEventListener() before the listener is destroyed.
*/
void AddEventListener (const Link& rEventListener);
/** Remove the given listener from the list of listeners.
@param rEventListener
After this method returns the given listener is not called back
from this object. Passing a listener that has not
been registered before is safe and is silently ignored.
*/
void RemoveEventListener (const Link& rEventListener);
/** Return a set of the names of master pages for the given document.
This convenience method exists because this set is part of the
internal data structure and thus takes no time to create.
*/
inline MasterPageObserver::MasterPageNameSet GetMasterPageNames (
SdDrawDocument& rDocument);
private:
::std::vector<Link> maListeners;
struct DrawDocHash {
size_t operator()(SdDrawDocument* argument) const
{ return reinterpret_cast<unsigned long>(argument); }
};
typedef ::std::hash_map<SdDrawDocument*,
MasterPageObserver::MasterPageNameSet,
DrawDocHash>
MasterPageContainer;
MasterPageContainer maUsedMasterPages;
virtual void Notify(
SfxBroadcaster& rBroadcaster,
const SfxHint& rHint);
void AnalyzeUsedMasterPages (SdDrawDocument& rDocument);
void SendEvent (MasterPageObserverEvent& rEvent);
};
MasterPageObserver* MasterPageObserver::Implementation::mpInstance = NULL;
//===== MasterPageObserver ====================================================
MasterPageObserver& MasterPageObserver::Instance (void)
{
if (Implementation::mpInstance == NULL)
{
::osl::GetGlobalMutex aMutexFunctor;
::osl::MutexGuard aGuard (aMutexFunctor());
if (Implementation::mpInstance == NULL)
{
MasterPageObserver* pInstance = new MasterPageObserver ();
SdGlobalResourceContainer::Instance().AddResource (
::std::auto_ptr<SdGlobalResource>(pInstance));
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
Implementation::mpInstance = pInstance;
}
}
else
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
DBG_ASSERT(Implementation::mpInstance!=NULL,
"MasterPageObserver::Instance(): instance is NULL");
return *Implementation::mpInstance;
}
void MasterPageObserver::RegisterDocument (SdDrawDocument& rDocument)
{
mpImpl->RegisterDocument (rDocument);
}
void MasterPageObserver::UnregisterDocument (SdDrawDocument& rDocument)
{
mpImpl->UnregisterDocument (rDocument);
}
void MasterPageObserver::AddEventListener (const Link& rEventListener)
{
mpImpl->AddEventListener (rEventListener);
}
void MasterPageObserver::RemoveEventListener (const Link& rEventListener)
{
mpImpl->RemoveEventListener (rEventListener);
}
MasterPageObserver::MasterPageObserver (void)
: mpImpl (new Implementation())
{}
MasterPageObserver::~MasterPageObserver (void)
{}
MasterPageObserver::MasterPageNameSet MasterPageObserver::GetMasterPageNames (
SdDrawDocument& rDocument)
{
return mpImpl->GetMasterPageNames (rDocument);
}
//===== MasterPageObserver::Implementation ====================================
void MasterPageObserver::Implementation::RegisterDocument (
SdDrawDocument& rDocument)
{
// Gather the names of all the master pages in the given document.
MasterPageContainer::data_type aMasterPageSet;
USHORT nMasterPageCount = rDocument.GetMasterSdPageCount(PK_STANDARD);
for (USHORT nIndex=0; nIndex<nMasterPageCount; nIndex++)
{
SdPage* pMasterPage = rDocument.GetMasterSdPage (nIndex, PK_STANDARD);
if (pMasterPage != NULL)
aMasterPageSet.insert (pMasterPage->GetName());
}
maUsedMasterPages[&rDocument] = aMasterPageSet;
StartListening (rDocument);
}
void MasterPageObserver::Implementation::UnregisterDocument (
SdDrawDocument& rDocument)
{
EndListening (rDocument);
MasterPageContainer::iterator aMasterPageDescriptor(maUsedMasterPages.find(&rDocument));
if(aMasterPageDescriptor != maUsedMasterPages.end())
maUsedMasterPages.erase(aMasterPageDescriptor);
}
void MasterPageObserver::Implementation::AddEventListener (
const Link& rEventListener)
{
if (::std::find (
maListeners.begin(),
maListeners.end(),
rEventListener) == maListeners.end())
{
maListeners.push_back (rEventListener);
// Tell the new listener about all the master pages that are
// currently in use.
typedef ::std::vector<String> StringList;
StringList aNewMasterPages;
StringList aRemovedMasterPages;
MasterPageContainer::iterator aDocumentIterator;
for (aDocumentIterator=maUsedMasterPages.begin();
aDocumentIterator!=maUsedMasterPages.end();
++aDocumentIterator)
{
::std::set<String>::reverse_iterator aNameIterator;
for (aNameIterator=aDocumentIterator->second.rbegin();
aNameIterator!=aDocumentIterator->second.rend();
++aNameIterator)
{
MasterPageObserverEvent aEvent (
MasterPageObserverEvent::ET_MASTER_PAGE_EXISTS,
*aDocumentIterator->first,
*aNameIterator);
SendEvent (aEvent);
}
}
}
}
void MasterPageObserver::Implementation::RemoveEventListener (
const Link& rEventListener)
{
maListeners.erase (
::std::find (
maListeners.begin(),
maListeners.end(),
rEventListener));
}
MasterPageObserver::MasterPageNameSet
MasterPageObserver::Implementation::GetMasterPageNames (
SdDrawDocument& rDocument)
{
MasterPageContainer::iterator aMasterPageDescriptor (
maUsedMasterPages.find(&rDocument));
if (aMasterPageDescriptor != maUsedMasterPages.end())
return aMasterPageDescriptor->second;
else
// Not found so return an empty set.
return MasterPageObserver::MasterPageNameSet();
}
void MasterPageObserver::Implementation::Notify(
SfxBroadcaster& rBroadcaster,
const SfxHint& rHint)
{
if (rHint.ISA(SdrHint))
{
SdrHint& rSdrHint (*PTR_CAST(SdrHint,&rHint));
switch (rSdrHint.GetKind())
{
case HINT_PAGEORDERCHG:
// Process the modified set of pages only when the number of
// standard and notes master pages are equal. This test
// filters out events that are sent in between the insertion
// of a new standard master page and a new notes master
// page.
if (rBroadcaster.ISA(SdDrawDocument))
{
SdDrawDocument& rDocument (
static_cast<SdDrawDocument&>(rBroadcaster));
if (rDocument.GetMasterSdPageCount(PK_STANDARD)
== rDocument.GetMasterSdPageCount(PK_NOTES))
{
AnalyzeUsedMasterPages (rDocument);
}
}
break;
default:
break;
}
}
}
void MasterPageObserver::Implementation::AnalyzeUsedMasterPages (
SdDrawDocument& rDocument)
{
// Create a set of names of the master pages used by the given document.
USHORT nMasterPageCount = rDocument.GetMasterSdPageCount(PK_STANDARD);
::std::set<String> aCurrentMasterPages;
for (USHORT nIndex=0; nIndex<nMasterPageCount; nIndex++)
{
SdPage* pMasterPage = rDocument.GetMasterSdPage (nIndex, PK_STANDARD);
if (pMasterPage != NULL)
aCurrentMasterPages.insert (pMasterPage->GetName());
OSL_TRACE("currently used master page %d is %s",
nIndex,
::rtl::OUStringToOString(pMasterPage->GetName(),
RTL_TEXTENCODING_UTF8).getStr());
}
typedef ::std::vector<String> StringList;
StringList aNewMasterPages;
StringList aRemovedMasterPages;
MasterPageContainer::iterator aOldMasterPagesDescriptor (
maUsedMasterPages.find(&rDocument));
if (aOldMasterPagesDescriptor != maUsedMasterPages.end())
{
StringList::iterator I;
::std::set<String>::iterator J;
int i=0;
for (J=aOldMasterPagesDescriptor->second.begin();
J!=aOldMasterPagesDescriptor->second.end();
++J)
OSL_TRACE("old used master page %d is %s",
i++,
::rtl::OUStringToOString(*J,
RTL_TEXTENCODING_UTF8).getStr());
// Send events about the newly used master pages.
::std::set_difference (
aCurrentMasterPages.begin(),
aCurrentMasterPages.end(),
aOldMasterPagesDescriptor->second.begin(),
aOldMasterPagesDescriptor->second.end(),
::std::back_insert_iterator<StringList>(aNewMasterPages));
for (I=aNewMasterPages.begin(); I!=aNewMasterPages.end(); ++I)
{
OSL_TRACE(" added master page %s",
::rtl::OUStringToOString(*I,
RTL_TEXTENCODING_UTF8).getStr());
MasterPageObserverEvent aEvent (
MasterPageObserverEvent::ET_MASTER_PAGE_ADDED,
rDocument,
*I);
SendEvent (aEvent);
}
// Send events about master pages that are not used any longer.
::std::set_difference (
aOldMasterPagesDescriptor->second.begin(),
aOldMasterPagesDescriptor->second.end(),
aCurrentMasterPages.begin(),
aCurrentMasterPages.end(),
::std::back_insert_iterator<StringList>(aRemovedMasterPages));
for (I=aRemovedMasterPages.begin(); I!=aRemovedMasterPages.end(); ++I)
{
OSL_TRACE(" removed master page %s",
::rtl::OUStringToOString(*I,
RTL_TEXTENCODING_UTF8).getStr());
MasterPageObserverEvent aEvent (
MasterPageObserverEvent::ET_MASTER_PAGE_REMOVED,
rDocument,
*I);
SendEvent (aEvent);
}
// Store the new list of master pages.
aOldMasterPagesDescriptor->second = aCurrentMasterPages;
}
}
void MasterPageObserver::Implementation::SendEvent (
MasterPageObserverEvent& rEvent)
{
::std::vector<Link>::iterator aLink (maListeners.begin());
::std::vector<Link>::iterator aEnd (maListeners.end());
while (aLink!=aEnd)
{
aLink->Call (&rEvent);
++aLink;
}
}
} // end of namespace sd
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include <iostream>
#include "core/driver.h"
#include "core/modmanager.h"
#include "core/value.h"
#include "core/cstring.h"
#include "core/scope.h"
#include "modules/std/std_pkg.h"
#include "modules/db/db_pkg.h"
#include "modules/gui/gui_pkg.h"
#include "core/user.h"
namespace clever {
/// Adds the available packages to be imported
void ModManager::init()
{
addModule("std", new modules::Std);
addModule("db", new modules::Db);
addModule("gui", new modules::Gui);
addModule("_user", m_user = new UserModule);
}
/// Performs shutdown operation
void ModManager::shutdown()
{
std::vector<Type*> typevec;
ModuleMap::const_iterator itm(m_mods.begin()), endm(m_mods.end());
while (itm != endm) {
TypeMap& types = itm->second->getTypes();
TypeMap::const_iterator itt(types.begin()), ite(types.end());
while (itt != ite) {
itt->second->deallocMembers();
typevec.push_back(itt->second);
++itt;
}
clever_delete(itm->second);
++itm;
}
std::for_each(typevec.begin(), typevec.end(), clever_delete<Type>);
}
/// Adds a new module
void ModManager::addModule(const std::string& name, Module* module)
{
if (m_mods.find(name) != m_mods.end()) {
return;
}
m_mods.insert(ModuleMap::value_type(name, module));
module->init();
module->setLoaded();
if (module->hasModules()) {
ModuleMap& mods = module->getModules();
ModuleMap::const_iterator it(mods.begin()), end(mods.end());
while (it != end) {
m_mods.insert(ModuleMap::value_type(it->first, it->second));
++it;
}
}
}
/// Loads an specific module type
void ModManager::loadType(Scope* scope, const std::string& name, Type* type) const
{
Value* tmp = new Value(type, true);
scope->pushValue(CSTRING(name), tmp);
type->init();
}
/// Loads an specific module function
void ModManager::loadFunction(Scope* scope, const std::string& name, Function* func) const
{
Value* fval = new Value();
fval->setObj(CLEVER_FUNC_TYPE, func);
fval->setConst(true);
scope->pushValue(CSTRING(name), fval);
}
void ModManager::loadModuleContent(Scope* scope, Module* module,
size_t kind, const CString* name, const std::string& ns_prefix) const
{
if (!name) {
VarMap& vars = module->getVars();
if (!vars.empty()) {
VarMap::const_iterator it(vars.begin()), end(vars.end());
for (; it != end; ++it) {
const CString* vname = CSTRING(ns_prefix + it->first);
scope->pushValue(vname, it->second);
}
}
}
if (kind & ModManager::FUNCTION) {
FunctionMap& funcs = module->getFunctions();
if (name) {
FunctionMap::const_iterator it(funcs.find(*name));
if (it == funcs.end()) {
std::cerr << "Function `" << *name << "' not found!" << std::endl;
} else {
loadFunction(scope, it->first, it->second);
}
} else {
FunctionMap::const_iterator itf(funcs.begin()), endf(funcs.end());
while (EXPECTED(itf != endf)) {
const std::string& fname = ns_prefix.empty() ?
itf->first : ns_prefix + itf->first;
loadFunction(scope, fname, itf->second);
++itf;
}
}
}
if (kind & ModManager::TYPE) {
TypeMap& types = module->getTypes();
if (name) {
TypeMap::const_iterator it(types.find(*name));
if (it == types.end()) {
std::cerr << "Type `" << *name << "' not found!" << std::endl;
} else {
loadType(scope, it->first, it->second);
}
} else {
TypeMap::const_iterator itt(types.begin()), ite(types.end());
while (EXPECTED(itt != ite)) {
const std::string& tname = ns_prefix.empty() ?
itt->first : ns_prefix + itt->first;
loadType(scope, tname, itt->second);
++itt;
}
}
}
}
/// Loads a module if it is not already loaded
void ModManager::loadModule(Scope* scope, Module* module,
size_t kind, const CString* name) const
{
// Imports the submodule
// e.g. import std; => std:<submodule>:<name>
// e.g. import std.*; => <submodule>:<name>
if ((kind & ModManager::ALL)
&& module->hasModules()) {
ModuleMap& mods = module->getModules();
ModuleMap::const_iterator it(mods.begin()), end(mods.end());
while (it != end) {
if (it->second->isLoaded()) {
++it;
continue;
}
it->second->init();
it->second->setLoaded();
std::string prefix = it->second->getName() + ":";
if (kind & ModManager::NAMESPACE) {
std::replace(prefix.begin(), prefix.end(), '.', ':');
} else {
prefix = prefix.substr(prefix.find_last_of(".")+1);
}
loadModuleContent(scope, it->second, kind, NULL, prefix);
++it;
}
}
if (module->isLoaded()) {
return;
}
module->init();
module->setLoaded();
std::string ns_prefix = "";
if (kind & ModManager::NAMESPACE) {
ns_prefix = module->getName();
size_t found = ns_prefix.find_last_of(".");
if (found != std::string::npos) {
ns_prefix = ns_prefix.substr(ns_prefix.find_last_of(".")+1) + ":";
}
}
loadModuleContent(scope, module, kind, name, ns_prefix);
}
/// Imports an userland module
ast::Node* ModManager::importFile(Scope* scope,
const std::string& module, size_t kind, const CString* name) const
{
std::string mod_name = module;
std::string ns_name = kind & ModManager::NAMESPACE ? module : "";
std::replace(mod_name.begin(), mod_name.end(), '.', '/');
const std::string& fname = m_include_path + mod_name + ".clv";
if (!m_driver->loadFile(fname, ns_name)) {
return m_driver->getCompiler().getAST();
}
return NULL;
}
/// Imports a module
ast::Node* ModManager::importModule(Scope* scope,
const std::string& module, size_t kind, const CString* name) const
{
ModuleMap::const_iterator it(m_mods.find(module));
//std::cout << "imp " << module << std::endl;
if (it == m_mods.end()) {
ast::Node* tree;
if ((tree = importFile(scope, module, kind, name)) == NULL) {
std::cerr << "Module `" << module << "' not found!" << std::endl;
return NULL;
}
return tree;
}
loadModule(scope, it->second, kind, name);
return NULL;
}
} // clever
<commit_msg>- Fixed issue #336<commit_after>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include <iostream>
#include "core/driver.h"
#include "core/modmanager.h"
#include "core/value.h"
#include "core/cstring.h"
#include "core/scope.h"
#include "modules/std/std_pkg.h"
#include "modules/db/db_pkg.h"
#include "modules/gui/gui_pkg.h"
#include "core/user.h"
namespace clever {
/// Adds the available packages to be imported
void ModManager::init()
{
addModule("std", new modules::Std);
addModule("db", new modules::Db);
addModule("gui", new modules::Gui);
addModule("_user", m_user = new UserModule);
}
/// Performs shutdown operation
void ModManager::shutdown()
{
std::vector<Type*> typevec;
ModuleMap::const_iterator itm(m_mods.begin()), endm(m_mods.end());
while (itm != endm) {
TypeMap& types = itm->second->getTypes();
TypeMap::const_iterator itt(types.begin()), ite(types.end());
while (itt != ite) {
itt->second->deallocMembers();
typevec.push_back(itt->second);
++itt;
}
clever_delete(itm->second);
++itm;
}
std::for_each(typevec.begin(), typevec.end(), clever_delete<Type>);
}
/// Adds a new module
void ModManager::addModule(const std::string& name, Module* module)
{
if (m_mods.find(name) != m_mods.end()) {
return;
}
m_mods.insert(ModuleMap::value_type(name, module));
module->init();
module->setLoaded();
if (module->hasModules()) {
ModuleMap& mods = module->getModules();
ModuleMap::const_iterator it(mods.begin()), end(mods.end());
while (it != end) {
m_mods.insert(ModuleMap::value_type(it->first, it->second));
++it;
}
}
}
/// Loads an specific module type
void ModManager::loadType(Scope* scope, const std::string& name, Type* type) const
{
Value* tmp = new Value(type, true);
scope->pushValue(CSTRING(name), tmp);
type->init();
}
/// Loads an specific module function
void ModManager::loadFunction(Scope* scope, const std::string& name, Function* func) const
{
Value* fval = new Value();
fval->setObj(CLEVER_FUNC_TYPE, func);
fval->setConst(true);
scope->pushValue(CSTRING(name), fval);
}
void ModManager::loadModuleContent(Scope* scope, Module* module,
size_t kind, const CString* name, const std::string& ns_prefix) const
{
if (!name) {
VarMap& vars = module->getVars();
if (!vars.empty()) {
VarMap::const_iterator it(vars.begin()), end(vars.end());
for (; it != end; ++it) {
const CString* vname = CSTRING(ns_prefix + it->first);
scope->pushValue(vname, it->second);
}
}
}
if (kind & ModManager::FUNCTION) {
FunctionMap& funcs = module->getFunctions();
if (name) {
FunctionMap::const_iterator it(funcs.find(*name));
if (it == funcs.end()) {
std::cerr << "Function `" << *name << "' not found!" << std::endl;
} else {
loadFunction(scope, it->first, it->second);
}
} else {
FunctionMap::const_iterator itf(funcs.begin()), endf(funcs.end());
while (EXPECTED(itf != endf)) {
const std::string& fname = ns_prefix.empty() ?
itf->first : ns_prefix + itf->first;
loadFunction(scope, fname, itf->second);
++itf;
}
}
}
if (kind & ModManager::TYPE) {
TypeMap& types = module->getTypes();
if (name) {
TypeMap::const_iterator it(types.find(*name));
if (it == types.end()) {
std::cerr << "Type `" << *name << "' not found!" << std::endl;
} else {
loadType(scope, it->first, it->second);
}
} else {
TypeMap::const_iterator itt(types.begin()), ite(types.end());
while (EXPECTED(itt != ite)) {
const std::string& tname = ns_prefix.empty() ?
itt->first : ns_prefix + itt->first;
loadType(scope, tname, itt->second);
++itt;
}
}
}
}
/// Loads a module if it is not already loaded
void ModManager::loadModule(Scope* scope, Module* module,
size_t kind, const CString* name) const
{
// Imports the submodule
// e.g. import std; => std:<submodule>:<name>
// e.g. import std.*; => <submodule>:<name>
if ((kind & ModManager::ALL)
&& module->hasModules()) {
ModuleMap& mods = module->getModules();
ModuleMap::const_iterator it(mods.begin()), end(mods.end());
while (it != end) {
if (it->second->isLoaded()) {
++it;
continue;
}
it->second->init();
it->second->setLoaded();
std::string prefix = it->second->getName() + ":";
if (kind & ModManager::NAMESPACE) {
std::replace(prefix.begin(), prefix.end(), '.', ':');
} else {
prefix = prefix.substr(prefix.find_last_of(".")+1);
}
loadModuleContent(scope, it->second, kind, NULL, prefix);
++it;
}
}
if (module->isLoaded()) {
return;
}
module->init();
module->setLoaded();
std::string ns_prefix = "";
if (kind & ModManager::NAMESPACE) {
ns_prefix = module->getName();
size_t found = ns_prefix.find_last_of(".");
if (found != std::string::npos) {
ns_prefix = ns_prefix.substr(ns_prefix.find_last_of(".")+1) + ":";
}
}
loadModuleContent(scope, module, kind, name, ns_prefix);
}
/// Imports an userland module
ast::Node* ModManager::importFile(Scope* scope,
const std::string& module, size_t kind, const CString* name) const
{
std::string mod_name = module;
std::string ns_name = kind & ModManager::NAMESPACE ? module : "";
std::replace(mod_name.begin(), mod_name.end(), '.', '/');
const std::string& fname = m_include_path + mod_name + ".clv";
if (!m_driver->loadFile(fname, ns_name)) {
return m_driver->getCompiler().getAST();
} else {
CLEVER_EXIT_FATAL();
}
return NULL;
}
/// Imports a module
ast::Node* ModManager::importModule(Scope* scope,
const std::string& module, size_t kind, const CString* name) const
{
ModuleMap::const_iterator it(m_mods.find(module));
//std::cout << "imp " << module << std::endl;
if (it == m_mods.end()) {
ast::Node* tree;
if ((tree = importFile(scope, module, kind, name)) == NULL) {
std::cerr << "Module `" << module << "' not found!" << std::endl;
return NULL;
}
return tree;
}
loadModule(scope, it->second, kind, name);
return NULL;
}
} // clever
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Planet - An atmospheric code for planetary bodies, adapted to Titan
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
//Antioch
#include "antioch/physical_constants.h"
#include "antioch/cmath_shims.h"
//Planet
#include "planet/binary_diffusion.h"
#include "planet/planet_constants.h"
//C++
#include <limits>
#include <string>
#include <iomanip>
template<typename Scalar>
int check(const Scalar &test, const Scalar &ref, const Scalar &tol, const std::string &model)
{
if(Antioch::ant_abs(test - ref)/ref > tol)
{
std::cout << std::scientific << std::setprecision(20)
<< "Error in binary diffusion calculations" << std::endl
<< "model is " << model << std::endl
<< "calculated coefficient = " << test << std::endl
<< "solution = " << ref << std::endl
<< "relative error = " << Antioch::ant_abs(test - ref)/ref << std::endl
<< "tolerance = " << tol << std::endl;
return 1;
}
return 0;
}
template<typename Scalar>
int tester()
{
Scalar p11(0.1783),p12(1.81);
Scalar p21(1.04e-5),p22(1.76);
Scalar p31(5.73e16),p32(0.5);
Planet::BinaryDiffusion<Scalar> N2N2( 0, 0, p11, p12, Planet::DiffusionType::Massman);
Planet::BinaryDiffusion<Scalar> N2CH4( 0, 1, p21, p22, Planet::DiffusionType::Wakeham);
Planet::BinaryDiffusion<Scalar> CH4CH4( 1, 1, p31, p32, Planet::DiffusionType::Wilson);
Scalar T(1500.),P(1e5);
Scalar n = P / (T * Planet::Constants::Universal::kb<Scalar>());
Scalar n2n2 = p11 * Planet::Constants::Convention::P_normal<Scalar>() / P * Antioch::ant_pow(T/Planet::Constants::Convention::T_standard<Scalar>(),p12);
Scalar n2ch4 = p21 * Antioch::ant_pow(T,p22)* Planet::Constants::Convention::P_normal<Scalar>() / P;
Scalar ch4ch4 = p31 * Antioch::ant_pow(T,p32)/n;
Scalar nn = N2N2.binary_coefficient(T,P);
Scalar nc = N2CH4.binary_coefficient(T,P);
Scalar cc = CH4CH4.binary_coefficient(T,P);
int return_flag(0);
const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100.;
return_flag = check(nn,n2n2,tol,"Massman") ||
check(nc,n2ch4,tol,"Wilson") ||
check(cc,ch4ch4,tol,"Wakeham");
return return_flag;
}
int main()
{
return (tester<float>() ||
tester<double>() ||
tester<long double>());
}
<commit_msg>Test on derivatives added<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Planet - An atmospheric code for planetary bodies, adapted to Titan
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
//Antioch
#include "antioch/physical_constants.h"
#include "antioch/cmath_shims.h"
#include "antioch/units.h"
//Planet
#include "planet/binary_diffusion.h"
#include "planet/planet_constants.h"
//C++
#include <limits>
#include <string>
#include <iomanip>
template<typename Scalar>
int check(const Scalar &test, const Scalar &ref, const Scalar &tol, const std::string &model)
{
Scalar dist = (ref < tol)?Antioch::ant_abs(test - ref):
Antioch::ant_abs(test - ref)/ref;
if(dist > tol)
{
std::cout << std::scientific << std::setprecision(20)
<< "Error in binary diffusion calculations" << std::endl
<< "model is " << model << std::endl
<< "calculated coefficient = " << test << std::endl
<< "solution = " << ref << std::endl
<< "relative error = " << Antioch::ant_abs(test - ref)/ref << std::endl
<< "tolerance = " << tol << std::endl;
return 1;
}
return 0;
}
template <typename Scalar>
Scalar Dij(const Scalar & T, const Scalar & P, const Scalar & D01, const Scalar & beta)
{
return D01 * Planet::Constants::Convention::P_normal<Scalar>() / P * Antioch::ant_pow(T/Planet::Constants::Convention::T_standard<Scalar>(),beta);
}
template <typename Scalar>
Scalar dDij_dT(const Scalar & T, const Scalar & P, const Scalar & D01, const Scalar & beta)
{
return Dij(T,P,D01,beta) * (beta - 1.L)/T;
}
template <typename Scalar>
Scalar dDij_dn(const Scalar & T, const Scalar & P, const Scalar & D01, const Scalar & beta)
{
return -Dij(T,P,D01,beta) * (T*Planet::Constants::Universal::kb<Scalar>())/(P*P);
}
template<typename Scalar>
int tester()
{
Scalar p11(0.1783L),p12(1.81L);
Scalar p21(1.04e-5L),p22(1.76L);
Scalar p31(5.73e16L),p32(0.5L);
Planet::BinaryDiffusion<Scalar> N2N2( 0, 0, p11, p12, Planet::DiffusionType::Massman);
Planet::BinaryDiffusion<Scalar> N2CH4( 0, 1, p21, p22, Planet::DiffusionType::Wakeham);
Planet::BinaryDiffusion<Scalar> CH4CH4( 1, 1, p31, p32, Planet::DiffusionType::Wilson);
// on range of temperatures, common pressure of
// measurements is 1 atm
Scalar P(1.L); // in atm
P *= Antioch::Units<Scalar>("atm").get_SI_factor(); // in Pa
int return_flag(0);
const Scalar tol = (std::numeric_limits<Scalar>::epsilon() < 1e-17)?std::numeric_limits<Scalar>::epsilon() * 20.:
std::numeric_limits<Scalar>::epsilon() * 10.;
for(Scalar T = 100.; T < 3500.; T += 100.)
{
Scalar n = P / (T * Planet::Constants::Universal::kb<Scalar>());
Scalar n2n2 = Dij(T,P,p11,p12);
Scalar n2ch4 = p21 * Antioch::ant_pow(T,p22);
Scalar ch4ch4 = p31 * Antioch::ant_pow(T,p32) / n;
Scalar dn2n2_dT = dDij_dT(T,P,p11,p12);
Scalar dn2n2_dn = dDij_dn(T,P,p11,p12);
Scalar dch4ch4_dT = p32 * p31 / n * Antioch::ant_pow(T,p32 - 1.L);
Scalar dch4ch4_dn = - p31 * Antioch::ant_pow(T,p32) / (n * n);
return_flag = check(N2N2.binary_coefficient(T,P),n2n2,tol,"Massman binary coefficient") ||
check(N2CH4.binary_coefficient(T,P),n2ch4,tol,"Wakeham binary coefficient") ||
check(CH4CH4.binary_coefficient(T,P),ch4ch4,tol,"Wilson binary coefficient") ||
check(N2N2.binary_coefficient_deriv_T(T,P),dn2n2_dT,tol,"Massman binary coefficient derived to T") ||
check(CH4CH4.binary_coefficient_deriv_T(T,P),dch4ch4_dT,tol,"Wilson binary coefficient derived to T") ||
check(N2N2.binary_coefficient_deriv_n(T,P,n),dn2n2_dn,tol,"Massman binary coefficient derived to n") ||
check(CH4CH4.binary_coefficient_deriv_n(T,P,n),dch4ch4_dn,tol,"Wilson binary coefficient derived to n") ||
return_flag;
}
// golden values
Scalar T(201.L);
P = 0.53L;
Scalar n = P / (T * Planet::Constants::Universal::kb<Scalar>());
Scalar truth = 1.95654918135100954675984465985829467e4L;
Scalar dtruth_dT = 7.88460117857869518843519489793641134e1L;
Scalar dtruth_dn = -1.0244580436868377275736362395882496e-16L;
return_flag = check(N2N2.binary_coefficient(T,P),truth,tol,"Massman binary coefficient") ||
check(N2N2.binary_coefficient_deriv_T(T,P),dtruth_dT,tol,"Massman binary coefficient derived to T") ||
check(N2N2.binary_coefficient_deriv_n(T,P,n),dtruth_dn,tol,"Massman binary coefficient derived to n") ||
return_flag;
return return_flag;
}
int main()
{
return (tester<float>() ||
tester<double>() ||
tester<long double>());
}
<|endoftext|> |
<commit_before>#include "word.h"
#include "kwic.h"
#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"
void testWordShouldBeLessComparesInternalValue() {
//Arrange
const Word word1("abc");
const Word word2("bcd");
//Assert
ASSERT_LESS(word1, word2);
}
void testWordShouldBeLessComparesCaseInsensitive() {
//Arrange
const Word word1("abc");
const Word word2("BCD");
//Assert
ASSERT_LESS(word1, word2);
}
void testWordShiftLeftPrintsInternalValue() {
//Arrange
std::ostringstream out { };
const Word word("hallo");
//Act
out << word;
//Assert
ASSERT_EQUAL("hallo", out.str());
}
void testConstructWordThrowsInvalidArgumentExceptionForNumber() {
//Assert
ASSERT_THROWS(Word("124abd"), std::invalid_argument);
}
void testConstructWordThrowsInvalidArgumentExceptionForSpecialCharacters() {
//Assert
ASSERT_THROWS(Word("dsl!*%"), std::invalid_argument);
}
void testWordConsistsOfOnlyLetters() {
//Arrange
std::istringstream in { "abc123%" };
Word word { };
//Act
in >> word;
//Assert
ASSERT_EQUAL(std::string { "abc" }, word.value);
}
void testWordIsEmptyIfStreamIsEmpty() {
//Arrange
std::istringstream in { " " };
Word word { };
//Act
in >> word;
//Assert
ASSERT_EQUAL(0, word.value.length());
}
void testWordsAreDelimitedByNonAlphanumericCharacters() {
//Arrange
std::istringstream in { "compl33tely ~ weird !!??!! 4matted in_put" };
Word word1 { }, word2 { }, word3 { }, word4 { }, word5 { }, word6 { };
//Act
in >> word1;
in >> word2;
in >> word3;
in >> word4;
in >> word5;
in >> word6;
//Assert
ASSERT_EQUAL(std::string { "compl" }, word1.value);
ASSERT_EQUAL(std::string { "tely" }, word2.value);
ASSERT_EQUAL(std::string { "weird" }, word3.value);
ASSERT_EQUAL(std::string { "matted" }, word4.value);
ASSERT_EQUAL(std::string { "in" }, word5.value);
ASSERT_EQUAL(std::string { "put" }, word6.value);
}
void testRotateSingleLineReturnsAllMutationsSorted() {
//Arrange
const Word mockWord1("this");
const Word mockWord2("is");
const Word mockWord3("a");
const Word mockWord4("test");
const std::vector<Word> words { Word("this"), Word("is"), Word("a"), Word("test") };
//Act
const auto rotatedWords = rotateWords(words);
auto permuted = std::vector<std::vector<Word>> { };
for (auto word : rotatedWords) {
permuted.push_back(word);
}
//Assert
const std::vector<Word> expected1 { mockWord3, mockWord4, mockWord1, mockWord2 };
ASSERT_EQUAL(expected1, permuted.at(0));
const std::vector<Word> expected2 { mockWord2, mockWord3, mockWord4, mockWord1 };
ASSERT_EQUAL(expected2, permuted.at(1));
const std::vector<Word> expected3 { mockWord4, mockWord1, mockWord2, mockWord3 };
ASSERT_EQUAL(expected3, permuted.at(2));
const std::vector<Word> expected4 { mockWord1, mockWord2, mockWord3, mockWord4 };
ASSERT_EQUAL(expected4, permuted.at(3));
}
void testRotateMultipleLinesReturnsAllMutationsSorted() {
//Arrange
std::istringstream in { "this is a test\n"
"this is another test" };
std::ostringstream out { };
//Act
rotateLines(in, out);
//Assert
ASSERT_EQUAL("a test this is \n"
"another test this is \n"
"is a test this \n"
"is another test this \n"
"test this is a \n"
"test this is another \n"
"this is a test \n"
"this is another test \n", out.str());
}
void testWordRightShiftPutsWordsIntoSentenceUntilEndOfLine() {
//Arrange
std::istringstream in { "this is a test" };
std::vector<Word> sentence { };
//Act
in >> sentence;
//Assert
ASSERT_EQUAL(Word("this"), sentence.at(0));
ASSERT_EQUAL(Word("is"), sentence.at(1));
ASSERT_EQUAL(Word("a"), sentence.at(2));
ASSERT_EQUAL(Word("test"), sentence.at(3));
}
void runAllTests(int argc, char const *argv[]) {
cute::suite s { };
s.push_back(CUTE(testWordConsistsOfOnlyLetters));
s.push_back(CUTE(testWordsAreDelimitedByNonAlphanumericCharacters));
s.push_back(CUTE(testWordIsEmptyIfStreamIsEmpty));
s.push_back(CUTE(testConstructWordThrowsInvalidArgumentExceptionForNumber));
s.push_back(CUTE(testConstructWordThrowsInvalidArgumentExceptionForSpecialCharacters));
s.push_back(CUTE(testWordShiftLeftPrintsInternalValue));
s.push_back(CUTE(testWordShouldBeLessComparesInternalValue));
s.push_back(CUTE(testWordShouldBeLessComparesCaseInsensitive));
s.push_back(CUTE(testRotateSingleLineReturnsAllMutationsSorted));
s.push_back(CUTE(testRotateMultipleLinesReturnsAllMutationsSorted));
s.push_back(CUTE(testWordRightShiftPutsWordsIntoSentenceUntilEndOfLine));
cute::xml_file_opener xmlfile(argc, argv);
cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out);
cute::makeRunner(lis, argc, argv)(s, "AllTests");
}
int main(int argc, char const *argv[]) {
runAllTests(argc, argv);
return 0;
}
<commit_msg>Better names for test<commit_after>#include "word.h"
#include "kwic.h"
#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"
void testWordShouldBeLessComparesInternalValue() {
//Arrange
const Word word1("abc");
const Word word2("bcd");
//Assert
ASSERT_LESS(word1, word2);
}
void testWordShouldBeLessComparesCaseInsensitive() {
//Arrange
const Word word1("abc");
const Word word2("BCD");
//Assert
ASSERT_LESS(word1, word2);
}
void testWordShiftLeftPrintsInternalValue() {
//Arrange
std::ostringstream out { };
const Word word("hallo");
//Act
out << word;
//Assert
ASSERT_EQUAL("hallo", out.str());
}
void testConstructWordThrowsInvalidArgumentExceptionForNumber() {
//Assert
ASSERT_THROWS(Word("124abd"), std::invalid_argument);
}
void testConstructWordThrowsInvalidArgumentExceptionForSpecialCharacters() {
//Assert
ASSERT_THROWS(Word("dsl!*%"), std::invalid_argument);
}
void testWordConsistsOfOnlyLetters() {
//Arrange
std::istringstream in { "abc123%" };
Word word { };
//Act
in >> word;
//Assert
ASSERT_EQUAL(std::string { "abc" }, word.value);
}
void testWordIsEmptyIfStreamIsEmpty() {
//Arrange
std::istringstream in { " " };
Word word { };
//Act
in >> word;
//Assert
ASSERT_EQUAL(0, word.value.length());
}
void testWordsAreDelimitedByNonAlphanumericCharacters() {
//Arrange
std::istringstream in { "compl33tely ~ weird !!??!! 4matted in_put" };
Word word1 { }, word2 { }, word3 { }, word4 { }, word5 { }, word6 { };
//Act
in >> word1;
in >> word2;
in >> word3;
in >> word4;
in >> word5;
in >> word6;
//Assert
ASSERT_EQUAL(std::string { "compl" }, word1.value);
ASSERT_EQUAL(std::string { "tely" }, word2.value);
ASSERT_EQUAL(std::string { "weird" }, word3.value);
ASSERT_EQUAL(std::string { "matted" }, word4.value);
ASSERT_EQUAL(std::string { "in" }, word5.value);
ASSERT_EQUAL(std::string { "put" }, word6.value);
}
void testRotateSingleLineReturnsAllRotationsSorted() {
//Arrange
const Word mockWord1("this");
const Word mockWord2("is");
const Word mockWord3("a");
const Word mockWord4("test");
const std::vector<Word> words { Word("this"), Word("is"), Word("a"), Word("test") };
//Act
const auto rotatedWords = rotateWords(words);
auto permuted = std::vector<std::vector<Word>> { };
for (auto word : rotatedWords) {
permuted.push_back(word);
}
//Assert
const std::vector<Word> expected1 { mockWord3, mockWord4, mockWord1, mockWord2 };
ASSERT_EQUAL(expected1, permuted.at(0));
const std::vector<Word> expected2 { mockWord2, mockWord3, mockWord4, mockWord1 };
ASSERT_EQUAL(expected2, permuted.at(1));
const std::vector<Word> expected3 { mockWord4, mockWord1, mockWord2, mockWord3 };
ASSERT_EQUAL(expected3, permuted.at(2));
const std::vector<Word> expected4 { mockWord1, mockWord2, mockWord3, mockWord4 };
ASSERT_EQUAL(expected4, permuted.at(3));
}
void testRotateMultipleLinesReturnsAllRotationsSorted() {
//Arrange
std::istringstream in { "this is a test\n"
"this is another test" };
std::ostringstream out { };
//Act
rotateLines(in, out);
//Assert
ASSERT_EQUAL("a test this is \n"
"another test this is \n"
"is a test this \n"
"is another test this \n"
"test this is a \n"
"test this is another \n"
"this is a test \n"
"this is another test \n", out.str());
}
void testWordRightShiftPutsWordsIntoSentenceUntilEndOfLine() {
//Arrange
std::istringstream in { "this is a test" };
std::vector<Word> sentence { };
//Act
in >> sentence;
//Assert
ASSERT_EQUAL(Word("this"), sentence.at(0));
ASSERT_EQUAL(Word("is"), sentence.at(1));
ASSERT_EQUAL(Word("a"), sentence.at(2));
ASSERT_EQUAL(Word("test"), sentence.at(3));
}
void runAllTests(int argc, char const *argv[]) {
cute::suite s { };
s.push_back(CUTE(testWordConsistsOfOnlyLetters));
s.push_back(CUTE(testWordsAreDelimitedByNonAlphanumericCharacters));
s.push_back(CUTE(testWordIsEmptyIfStreamIsEmpty));
s.push_back(CUTE(testConstructWordThrowsInvalidArgumentExceptionForNumber));
s.push_back(CUTE(testConstructWordThrowsInvalidArgumentExceptionForSpecialCharacters));
s.push_back(CUTE(testWordShiftLeftPrintsInternalValue));
s.push_back(CUTE(testWordShouldBeLessComparesInternalValue));
s.push_back(CUTE(testWordShouldBeLessComparesCaseInsensitive));
s.push_back(CUTE(testRotateSingleLineReturnsAllRotationsSorted));
s.push_back(CUTE(testRotateMultipleLinesReturnsAllRotationsSorted));
s.push_back(CUTE(testWordRightShiftPutsWordsIntoSentenceUntilEndOfLine));
cute::xml_file_opener xmlfile(argc, argv);
cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out);
cute::makeRunner(lis, argc, argv)(s, "AllTests");
}
int main(int argc, char const *argv[]) {
runAllTests(argc, argv);
return 0;
}
<|endoftext|> |
<commit_before>/*
* RBDecorators.cpp
* golf
*
* Created by Robert Rose on 4/20/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "RBDecorators.h"
#include "RudeDebug.h"
#include "RudeFile.h"
#include "RudeTextureManager.h"
#include "RudeTweaker.h"
bool gRenderDecos = true;
RUDE_TWEAK(RenderDecos, kBool, gRenderDecos);
RBDecoratorInstance::RBDecoratorInstance()
{
m_pos[0] = 0.0f;
m_pos[1] = 0.0f;
m_pos[2] = 0.0f;
}
void RBDecoratorInstance::Set(float x, float y, float z)
{
m_pos[0] = x;
m_pos[1] = y;
m_pos[2] = z;
}
RBDecorator::RBDecorator()
: m_textureid(0)
, m_numInstances(0)
, m_size(16.0f)
, m_texturesize(128)
{
SetSize(16.0f);
}
void RBDecorator::SetTexture(const char *file)
{
m_textureid = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(file);
m_texturesize = RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetHeight();
}
void RBDecorator::SetSize(float size)
{
m_size = size;
float hsize = 0.5f * m_size;
float uvoffset = 1.0f / m_texturesize;
// bottom left
m_verts[0].m_pos[0] = -hsize;
m_verts[0].m_pos[1] = 0;
m_verts[0].m_pos[2] = 0;
m_verts[0].m_uv[0] = 0;
m_verts[0].m_uv[1] = 0;
// bottom right
m_verts[1].m_pos[0] = hsize;
m_verts[1].m_pos[1] = 0;
m_verts[1].m_pos[2] = 0;
m_verts[1].m_uv[0] = 1 - uvoffset;
m_verts[1].m_uv[1] = 0;
// top left
m_verts[2].m_pos[0] = -hsize;
m_verts[2].m_pos[1] = size;
m_verts[2].m_pos[2] = 0;
m_verts[2].m_uv[0] = 0;
m_verts[2].m_uv[1] = 1 - uvoffset;
// top left
m_verts[3].m_pos[0] = -hsize;
m_verts[3].m_pos[1] = size;
m_verts[3].m_pos[2] = 0;
m_verts[3].m_uv[0] = 0;
m_verts[3].m_uv[1] = 1 - uvoffset;
// bottom right
m_verts[4].m_pos[0] = hsize;
m_verts[4].m_pos[1] = 0;
m_verts[4].m_pos[2] = 0;
m_verts[4].m_uv[0] = 1 - uvoffset;
m_verts[4].m_uv[1] = 0;
// top right
m_verts[5].m_pos[0] = hsize;
m_verts[5].m_pos[1] = size;
m_verts[5].m_pos[2] = 0;
m_verts[5].m_uv[0] = 1 - uvoffset;
m_verts[5].m_uv[1] = 1 - uvoffset;
}
bool RBDecorator::AddInstance(float x, float y, float z)
{
if(m_numInstances < kMaxInstances)
{
m_instances[m_numInstances].Set(x, y, z);
m_numInstances++;
return true;
}
else
return false;
}
void RBDecorator::Print()
{
RUDE_REPORT("\nDECORATOR %s %f\n\n", RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetName(), m_size);
for(int i = 0; i < m_numInstances; i++)
{
RUDE_REPORT("%f %f %f\n", m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
}
}
void RBDecorator::Render()
{
glVertexPointer(3, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_pos);
glTexCoordPointer(2, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_uv);
RudeTextureManager::GetInstance()->SetTexture(m_textureid);
float M[16];
for(int i = 0; i < m_numInstances; i++)
{
glPushMatrix();
glTranslatef(m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
glGetFloatv(GL_MODELVIEW_MATRIX, M);
M[0] = 1.0;
M[1] = 0.0f;
M[2] = 0.0f;
M[8] = 0.0f;
M[9] = 0.0f;
M[10] = 1.0f;
/*
for(int i=0; i<3; i+=2 )
for(int j=0; j<3; j++ ) {
if ( i==j )
M[i*4+j] = 1.0;
else
M[i*4+j] = 0.0;
}*/
glLoadMatrixf(M);
glDrawArrays(GL_TRIANGLES, 0, 6);
glPopMatrix();
}
}
RBDecoratorCollection::RBDecoratorCollection()
: m_dropTextureNum(0)
{
}
void RBDecoratorCollection::Load(const char *deco)
{
char filename[512];
sprintf(filename, "%s.deco", deco);
char path[512];
bool found = RudeFileGetFile(filename, path, 512, true);
if(!found)
return;
RUDE_REPORT("RBDecoratorCollection loading %s\n", filename);
FILE *file = fopen(path, "r");
RUDE_ASSERT(file, "Could not open file %s", path);
char buf[256];
char *line = fgets(buf, 256, file);
RBDecorator *curdeco = 0;
while(line)
{
char texturename[256];
float size = 8.0f;
int result = sscanf(line, "DECORATOR %s %f\n", texturename, &size);
if(result == 2)
{
RUDE_REPORT(" DECORATOR: texture=%s size=%f\n", texturename, size);
RBDecorator decorator;
decorator.SetTexture(texturename);
decorator.SetSize(size);
m_decorators.push_back(decorator);
curdeco = &m_decorators[m_decorators.size() - 1];
AddTexture(texturename);
}
else
{
float pos[3];
result = sscanf(line, "%f %f %f\n", &pos[0], &pos[1], &pos[2]);
if(result == 3)
{
RUDE_ASSERT(curdeco, "Failed to parse decorators, DECORATOR not defined");
RUDE_REPORT(" %f %f %f\n", pos[0], pos[1], pos[2]);
bool added = curdeco->AddInstance(pos[0], pos[1], pos[2]);
RUDE_ASSERT(added, "Failed to add decorator instance");
#ifndef NO_DECO_EDITOR
m_droppedDecorators.push_back(btVector3(pos[0], pos[1], pos[2]));
#endif
}
}
line = fgets(buf, 256, file);
}
fclose(file);
}
#ifndef NO_DECO_EDITOR
void RBDecoratorCollection::Drop(const btVector3 &pos, float size)
{
RUDE_ASSERT(m_textureNames.size() > 0, "No decorators have been loaded so there are no textures to drop with");
m_dropTextureNum++;
if(m_dropTextureNum >= m_textureNames.size())
m_dropTextureNum = 0;
// Check to make sure there's no already a decorator at this position
for(unsigned int i = 0; i < m_droppedDecorators.size(); i++)
{
if(m_droppedDecorators[i] == pos)
return;
}
m_droppedDecorators.push_back(pos);
// Check to see if we already have a decorator of the same size and texture
int curTextureID = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(m_textureNames[m_dropTextureNum].c_str());
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
RBDecorator &deco = m_decorators[i];
if(deco.GetTextureID() == curTextureID)
{
if(deco.GetSize() == size)
{
bool added = deco.AddInstance(pos.x(), pos.y(), pos.z());
if(added == false)
{
Print();
RUDE_ASSERT(added, "Failed to add decorator instance");
}
return;
}
}
}
RBDecorator deco;
deco.SetTexture(m_textureNames[m_dropTextureNum].c_str());
deco.SetSize(size);
deco.AddInstance(pos.x(), pos.y(), pos.z());
m_decorators.push_back(deco);
}
#endif
void RBDecoratorCollection::Print()
{
RUDE_REPORT("\n\n# Decorator Collection\n#\n#\n#\n");
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
m_decorators[i].Print();
}
}
void RBDecoratorCollection::Render()
{
unsigned int numdecos = m_decorators.size();
if(numdecos == 0 || gRenderDecos == false)
return;
// set up draw state
RGL.Enable(kBackfaceCull, false);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kColorArray, false);
RGL.EnableClient(kTextureCoordArray, true);
glAlphaFunc(GL_GREATER, 0.5);
glEnable(GL_ALPHA_TEST);
// set up GL matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
float w = RGL.GetHalfWidth();
float h = RGL.GetHalfHeight();
RGL.Frustum(0.0f, 0.0f, w * 2.0f, h * 2.0f, 4.0f, 2500.0f);
btVector3 eye = RGL.GetEye();
btVector3 forward = RGL.GetForward();
btVector3 inup(0, 1, 0);
btVector3 side = inup.cross(forward);
side.normalize();
btVector3 up = forward.cross(side);
float M[] =
{
side.x(), up.x(), forward.x(), 0,
side.y(), up.y(), forward.y(), 0,
side.z(), up.z(), forward.z(), 0,
0, 0, 0, 1
};
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(M);
glTranslatef (-eye.x(), -eye.y(), -eye.z());
for(unsigned int i = 0; i < numdecos; i++)
{
m_decorators[i].Render();
}
// restore GL matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
RGL.LoadIdentity();
// restore draw state
glDisable(GL_ALPHA_TEST);
}
void RBDecoratorCollection::AddTexture(const char *textureName)
{
unsigned int size = m_textureNames.size();
bool found = false;
for(unsigned int i = 0; i < size; i++)
{
if(m_textureNames[i] == std::string(textureName))
found = true;
}
if(!found)
m_textureNames.push_back(std::string(textureName));
}
<commit_msg>set deco render color to white for windows/macos<commit_after>/*
* RBDecorators.cpp
* golf
*
* Created by Robert Rose on 4/20/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "RBDecorators.h"
#include "RudeDebug.h"
#include "RudeFile.h"
#include "RudeTextureManager.h"
#include "RudeTweaker.h"
bool gRenderDecos = true;
RUDE_TWEAK(RenderDecos, kBool, gRenderDecos);
RBDecoratorInstance::RBDecoratorInstance()
{
m_pos[0] = 0.0f;
m_pos[1] = 0.0f;
m_pos[2] = 0.0f;
}
void RBDecoratorInstance::Set(float x, float y, float z)
{
m_pos[0] = x;
m_pos[1] = y;
m_pos[2] = z;
}
RBDecorator::RBDecorator()
: m_textureid(0)
, m_numInstances(0)
, m_size(16.0f)
, m_texturesize(128)
{
SetSize(16.0f);
}
void RBDecorator::SetTexture(const char *file)
{
m_textureid = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(file);
m_texturesize = RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetHeight();
}
void RBDecorator::SetSize(float size)
{
m_size = size;
float hsize = 0.5f * m_size;
float uvoffset = 1.0f / m_texturesize;
// bottom left
m_verts[0].m_pos[0] = -hsize;
m_verts[0].m_pos[1] = 0;
m_verts[0].m_pos[2] = 0;
m_verts[0].m_uv[0] = 0;
m_verts[0].m_uv[1] = 0;
// bottom right
m_verts[1].m_pos[0] = hsize;
m_verts[1].m_pos[1] = 0;
m_verts[1].m_pos[2] = 0;
m_verts[1].m_uv[0] = 1 - uvoffset;
m_verts[1].m_uv[1] = 0;
// top left
m_verts[2].m_pos[0] = -hsize;
m_verts[2].m_pos[1] = size;
m_verts[2].m_pos[2] = 0;
m_verts[2].m_uv[0] = 0;
m_verts[2].m_uv[1] = 1 - uvoffset;
// top left
m_verts[3].m_pos[0] = -hsize;
m_verts[3].m_pos[1] = size;
m_verts[3].m_pos[2] = 0;
m_verts[3].m_uv[0] = 0;
m_verts[3].m_uv[1] = 1 - uvoffset;
// bottom right
m_verts[4].m_pos[0] = hsize;
m_verts[4].m_pos[1] = 0;
m_verts[4].m_pos[2] = 0;
m_verts[4].m_uv[0] = 1 - uvoffset;
m_verts[4].m_uv[1] = 0;
// top right
m_verts[5].m_pos[0] = hsize;
m_verts[5].m_pos[1] = size;
m_verts[5].m_pos[2] = 0;
m_verts[5].m_uv[0] = 1 - uvoffset;
m_verts[5].m_uv[1] = 1 - uvoffset;
}
bool RBDecorator::AddInstance(float x, float y, float z)
{
if(m_numInstances < kMaxInstances)
{
m_instances[m_numInstances].Set(x, y, z);
m_numInstances++;
return true;
}
else
return false;
}
void RBDecorator::Print()
{
RUDE_REPORT("\nDECORATOR %s %f\n\n", RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetName(), m_size);
for(int i = 0; i < m_numInstances; i++)
{
RUDE_REPORT("%f %f %f\n", m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
}
}
void RBDecorator::Render()
{
glVertexPointer(3, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_pos);
glTexCoordPointer(2, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_uv);
RudeTextureManager::GetInstance()->SetTexture(m_textureid);
float M[16];
for(int i = 0; i < m_numInstances; i++)
{
glPushMatrix();
glTranslatef(m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
glGetFloatv(GL_MODELVIEW_MATRIX, M);
M[0] = 1.0;
M[1] = 0.0f;
M[2] = 0.0f;
M[8] = 0.0f;
M[9] = 0.0f;
M[10] = 1.0f;
/*
for(int i=0; i<3; i+=2 )
for(int j=0; j<3; j++ ) {
if ( i==j )
M[i*4+j] = 1.0;
else
M[i*4+j] = 0.0;
}*/
glLoadMatrixf(M);
glDrawArrays(GL_TRIANGLES, 0, 6);
glPopMatrix();
}
}
RBDecoratorCollection::RBDecoratorCollection()
: m_dropTextureNum(0)
{
}
void RBDecoratorCollection::Load(const char *deco)
{
char filename[512];
sprintf(filename, "%s.deco", deco);
char path[512];
bool found = RudeFileGetFile(filename, path, 512, true);
if(!found)
return;
RUDE_REPORT("RBDecoratorCollection loading %s\n", filename);
FILE *file = fopen(path, "r");
RUDE_ASSERT(file, "Could not open file %s", path);
char buf[256];
char *line = fgets(buf, 256, file);
RBDecorator *curdeco = 0;
while(line)
{
char texturename[256];
float size = 8.0f;
int result = sscanf(line, "DECORATOR %s %f\n", texturename, &size);
if(result == 2)
{
RUDE_REPORT(" DECORATOR: texture=%s size=%f\n", texturename, size);
RBDecorator decorator;
decorator.SetTexture(texturename);
decorator.SetSize(size);
m_decorators.push_back(decorator);
curdeco = &m_decorators[m_decorators.size() - 1];
AddTexture(texturename);
}
else
{
float pos[3];
result = sscanf(line, "%f %f %f\n", &pos[0], &pos[1], &pos[2]);
if(result == 3)
{
RUDE_ASSERT(curdeco, "Failed to parse decorators, DECORATOR not defined");
RUDE_REPORT(" %f %f %f\n", pos[0], pos[1], pos[2]);
bool added = curdeco->AddInstance(pos[0], pos[1], pos[2]);
RUDE_ASSERT(added, "Failed to add decorator instance");
#ifndef NO_DECO_EDITOR
m_droppedDecorators.push_back(btVector3(pos[0], pos[1], pos[2]));
#endif
}
}
line = fgets(buf, 256, file);
}
fclose(file);
}
#ifndef NO_DECO_EDITOR
void RBDecoratorCollection::Drop(const btVector3 &pos, float size)
{
RUDE_ASSERT(m_textureNames.size() > 0, "No decorators have been loaded so there are no textures to drop with");
m_dropTextureNum++;
if(m_dropTextureNum >= m_textureNames.size())
m_dropTextureNum = 0;
// Check to make sure there's no already a decorator at this position
for(unsigned int i = 0; i < m_droppedDecorators.size(); i++)
{
if(m_droppedDecorators[i] == pos)
return;
}
m_droppedDecorators.push_back(pos);
// Check to see if we already have a decorator of the same size and texture
int curTextureID = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(m_textureNames[m_dropTextureNum].c_str());
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
RBDecorator &deco = m_decorators[i];
if(deco.GetTextureID() == curTextureID)
{
if(deco.GetSize() == size)
{
bool added = deco.AddInstance(pos.x(), pos.y(), pos.z());
if(added == false)
{
Print();
RUDE_ASSERT(added, "Failed to add decorator instance");
}
return;
}
}
}
RBDecorator deco;
deco.SetTexture(m_textureNames[m_dropTextureNum].c_str());
deco.SetSize(size);
deco.AddInstance(pos.x(), pos.y(), pos.z());
m_decorators.push_back(deco);
}
#endif
void RBDecoratorCollection::Print()
{
RUDE_REPORT("\n\n# Decorator Collection\n#\n#\n#\n");
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
m_decorators[i].Print();
}
}
void RBDecoratorCollection::Render()
{
unsigned int numdecos = m_decorators.size();
if(numdecos == 0 || gRenderDecos == false)
return;
// set up draw state
RGL.Enable(kBackfaceCull, false);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kColorArray, false);
glColor4f(1.0, 1.0, 1.0, 1.0);
RGL.EnableClient(kTextureCoordArray, true);
glAlphaFunc(GL_GREATER, 0.5);
glEnable(GL_ALPHA_TEST);
// set up GL matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
float w = RGL.GetHalfWidth();
float h = RGL.GetHalfHeight();
RGL.Frustum(0.0f, 0.0f, w * 2.0f, h * 2.0f, 4.0f, 2500.0f);
btVector3 eye = RGL.GetEye();
btVector3 forward = RGL.GetForward();
btVector3 inup(0, 1, 0);
btVector3 side = inup.cross(forward);
side.normalize();
btVector3 up = forward.cross(side);
float M[] =
{
side.x(), up.x(), forward.x(), 0,
side.y(), up.y(), forward.y(), 0,
side.z(), up.z(), forward.z(), 0,
0, 0, 0, 1
};
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(M);
glTranslatef (-eye.x(), -eye.y(), -eye.z());
for(unsigned int i = 0; i < numdecos; i++)
{
m_decorators[i].Render();
}
// restore GL matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
RGL.LoadIdentity();
// restore draw state
glDisable(GL_ALPHA_TEST);
}
void RBDecoratorCollection::AddTexture(const char *textureName)
{
unsigned int size = m_textureNames.size();
bool found = false;
for(unsigned int i = 0; i < size; i++)
{
if(m_textureNames[i] == std::string(textureName))
found = true;
}
if(!found)
m_textureNames.push_back(std::string(textureName));
}
<|endoftext|> |
<commit_before>/*
* RBDecorators.cpp
* golf
*
* Created by Robert Rose on 4/20/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "RBDecorators.h"
#include "RudeDebug.h"
#include "RudeFile.h"
#include "RudeTextureManager.h"
#include "RudeTweaker.h"
bool gRenderDecos = true;
RUDE_TWEAK(RenderDecos, kBool, gRenderDecos);
RBDecoratorInstance::RBDecoratorInstance()
{
m_pos[0] = 0.0f;
m_pos[1] = 0.0f;
m_pos[2] = 0.0f;
}
void RBDecoratorInstance::Set(float x, float y, float z)
{
m_pos[0] = x;
m_pos[1] = y;
m_pos[2] = z;
}
RBDecorator::RBDecorator()
: m_textureid(0)
, m_numInstances(0)
, m_size(16.0f)
, m_texturesize(128.0f)
{
SetSize(16.0f);
}
void RBDecorator::SetTexture(const char *file)
{
m_textureid = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(file);
m_texturesize = RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetHeight();
}
void RBDecorator::SetSize(float size)
{
m_size = size;
float hsize = 0.5f * m_size;
float uvoffset = 1.0f / m_texturesize;
// bottom left
m_verts[0].m_pos[0] = -hsize;
m_verts[0].m_pos[1] = 0;
m_verts[0].m_pos[2] = 0;
m_verts[0].m_uv[0] = 0;
m_verts[0].m_uv[1] = 0;
// bottom right
m_verts[1].m_pos[0] = hsize;
m_verts[1].m_pos[1] = 0;
m_verts[1].m_pos[2] = 0;
m_verts[1].m_uv[0] = 1 - uvoffset;
m_verts[1].m_uv[1] = 0;
// top left
m_verts[2].m_pos[0] = -hsize;
m_verts[2].m_pos[1] = size;
m_verts[2].m_pos[2] = 0;
m_verts[2].m_uv[0] = 0;
m_verts[2].m_uv[1] = 1 - uvoffset;
// top left
m_verts[3].m_pos[0] = -hsize;
m_verts[3].m_pos[1] = size;
m_verts[3].m_pos[2] = 0;
m_verts[3].m_uv[0] = 0;
m_verts[3].m_uv[1] = 1 - uvoffset;
// bottom right
m_verts[4].m_pos[0] = hsize;
m_verts[4].m_pos[1] = 0;
m_verts[4].m_pos[2] = 0;
m_verts[4].m_uv[0] = 1 - uvoffset;
m_verts[4].m_uv[1] = 0;
// top right
m_verts[5].m_pos[0] = hsize;
m_verts[5].m_pos[1] = size;
m_verts[5].m_pos[2] = 0;
m_verts[5].m_uv[0] = 1 - uvoffset;
m_verts[5].m_uv[1] = 1 - uvoffset;
}
bool RBDecorator::AddInstance(float x, float y, float z)
{
if(m_numInstances < kMaxInstances)
{
m_instances[m_numInstances].Set(x, y, z);
m_numInstances++;
return true;
}
else
return false;
}
void RBDecorator::Print()
{
RUDE_REPORT("\nDECORATOR %s %f\n\n", RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetName(), m_size);
for(int i = 0; i < m_numInstances; i++)
{
RUDE_REPORT("%f %f %f\n", m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
}
}
void RBDecorator::Render()
{
glVertexPointer(3, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_pos);
glTexCoordPointer(2, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_uv);
RudeTextureManager::GetInstance()->SetTexture(m_textureid);
float M[16];
for(int i = 0; i < m_numInstances; i++)
{
glPushMatrix();
glTranslatef(m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
glGetFloatv(GL_MODELVIEW_MATRIX, M);
M[0] = 1.0;
M[1] = 0.0f;
M[2] = 0.0f;
M[8] = 0.0f;
M[9] = 0.0f;
M[10] = 1.0f;
/*
for(int i=0; i<3; i+=2 )
for(int j=0; j<3; j++ ) {
if ( i==j )
M[i*4+j] = 1.0;
else
M[i*4+j] = 0.0;
}*/
glLoadMatrixf(M);
glDrawArrays(GL_TRIANGLES, 0, 6);
glPopMatrix();
}
}
RBDecoratorCollection::RBDecoratorCollection()
: m_dropTextureNum(0)
{
}
void RBDecoratorCollection::Load(const char *deco)
{
char filename[512];
sprintf(filename, "%s.deco", deco);
char path[512];
bool found = RudeFileGetFile(filename, path, 512, true);
if(!found)
return;
RUDE_REPORT("RBDecoratorCollection loading %s\n", filename);
FILE *file = fopen(path, "r");
RUDE_ASSERT(file, "Could not open file %s", path);
char buf[256];
char *line = fgets(buf, 256, file);
RBDecorator *curdeco = 0;
while(line)
{
char texturename[256];
float size = 8.0f;
int result = sscanf(line, "DECORATOR %s %f\n", texturename, &size);
if(result == 2)
{
RUDE_REPORT(" DECORATOR: texture=%s size=%f\n", texturename, size);
RBDecorator decorator;
decorator.SetTexture(texturename);
decorator.SetSize(size);
m_decorators.push_back(decorator);
curdeco = &m_decorators[m_decorators.size() - 1];
AddTexture(texturename);
}
else
{
float pos[3];
result = sscanf(line, "%f %f %f\n", &pos[0], &pos[1], &pos[2]);
if(result == 3)
{
RUDE_ASSERT(curdeco, "Failed to parse decorators, DECORATOR not defined");
RUDE_REPORT(" %f %f %f\n", pos[0], pos[1], pos[2]);
bool added = curdeco->AddInstance(pos[0], pos[1], pos[2]);
RUDE_ASSERT(added, "Failed to add decorator instance");
#ifndef NO_DECO_EDITOR
m_droppedDecorators.push_back(btVector3(pos[0], pos[1], pos[2]));
#endif
}
}
line = fgets(buf, 256, file);
}
fclose(file);
}
#ifndef NO_DECO_EDITOR
void RBDecoratorCollection::Drop(const btVector3 &pos, float size)
{
RUDE_ASSERT(m_textureNames.size() > 0, "No decorators have been loaded so there are no textures to drop with");
m_dropTextureNum++;
if(m_dropTextureNum >= m_textureNames.size())
m_dropTextureNum = 0;
// Check to make sure there's no already a decorator at this position
for(unsigned int i = 0; i < m_droppedDecorators.size(); i++)
{
if(m_droppedDecorators[i] == pos)
return;
}
m_droppedDecorators.push_back(pos);
// Check to see if we already have a decorator of the same size and texture
int curTextureID = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(m_textureNames[m_dropTextureNum].c_str());
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
RBDecorator &deco = m_decorators[i];
if(deco.GetTextureID() == curTextureID)
{
if(deco.GetSize() == size)
{
bool added = deco.AddInstance(pos.x(), pos.y(), pos.z());
if(added == false)
{
Print();
RUDE_ASSERT(added, "Failed to add decorator instance");
}
return;
}
}
}
RBDecorator deco;
deco.SetTexture(m_textureNames[m_dropTextureNum].c_str());
deco.SetSize(size);
deco.AddInstance(pos.x(), pos.y(), pos.z());
m_decorators.push_back(deco);
}
#endif
void RBDecoratorCollection::Print()
{
RUDE_REPORT("\n\n# Decorator Collection\n#\n#\n#\n");
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
m_decorators[i].Print();
}
}
void RBDecoratorCollection::Render()
{
unsigned int numdecos = m_decorators.size();
if(numdecos == 0 || gRenderDecos == false)
return;
// set up draw state
RGL.Enable(kBackfaceCull, false);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kColorArray, false);
RGL.EnableClient(kTextureCoordArray, true);
glAlphaFunc(GL_GREATER, 0.5);
glEnable(GL_ALPHA_TEST);
// set up GL matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
float w = RGL.GetHalfWidth();
float h = RGL.GetHalfHeight();
RGL.Frustum(0.0f, 0.0f, w * 2.0f, h * 2.0f, 4.0f, 2000.0f);
btVector3 eye = RGL.GetEye();
btVector3 forward = RGL.GetForward();
btVector3 inup(0, 1, 0);
btVector3 side = inup.cross(forward);
side.normalize();
btVector3 up = forward.cross(side);
float M[] =
{
side.x(), up.x(), forward.x(), 0,
side.y(), up.y(), forward.y(), 0,
side.z(), up.z(), forward.z(), 0,
0, 0, 0, 1
};
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(M);
glTranslatef (-eye.x(), -eye.y(), -eye.z());
for(unsigned int i = 0; i < numdecos; i++)
{
m_decorators[i].Render();
}
// restore GL matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
RGL.LoadIdentity();
// restore draw state
glDisable(GL_ALPHA_TEST);
}
void RBDecoratorCollection::AddTexture(const char *textureName)
{
unsigned int size = m_textureNames.size();
bool found = false;
for(int i = 0; i < size; i++)
{
if(m_textureNames[i] == std::string(textureName))
found = true;
}
if(!found)
m_textureNames.push_back(std::string(textureName));
}
<commit_msg>extended decorator far plane out to 2500<commit_after>/*
* RBDecorators.cpp
* golf
*
* Created by Robert Rose on 4/20/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "RBDecorators.h"
#include "RudeDebug.h"
#include "RudeFile.h"
#include "RudeTextureManager.h"
#include "RudeTweaker.h"
bool gRenderDecos = true;
RUDE_TWEAK(RenderDecos, kBool, gRenderDecos);
RBDecoratorInstance::RBDecoratorInstance()
{
m_pos[0] = 0.0f;
m_pos[1] = 0.0f;
m_pos[2] = 0.0f;
}
void RBDecoratorInstance::Set(float x, float y, float z)
{
m_pos[0] = x;
m_pos[1] = y;
m_pos[2] = z;
}
RBDecorator::RBDecorator()
: m_textureid(0)
, m_numInstances(0)
, m_size(16.0f)
, m_texturesize(128.0f)
{
SetSize(16.0f);
}
void RBDecorator::SetTexture(const char *file)
{
m_textureid = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(file);
m_texturesize = RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetHeight();
}
void RBDecorator::SetSize(float size)
{
m_size = size;
float hsize = 0.5f * m_size;
float uvoffset = 1.0f / m_texturesize;
// bottom left
m_verts[0].m_pos[0] = -hsize;
m_verts[0].m_pos[1] = 0;
m_verts[0].m_pos[2] = 0;
m_verts[0].m_uv[0] = 0;
m_verts[0].m_uv[1] = 0;
// bottom right
m_verts[1].m_pos[0] = hsize;
m_verts[1].m_pos[1] = 0;
m_verts[1].m_pos[2] = 0;
m_verts[1].m_uv[0] = 1 - uvoffset;
m_verts[1].m_uv[1] = 0;
// top left
m_verts[2].m_pos[0] = -hsize;
m_verts[2].m_pos[1] = size;
m_verts[2].m_pos[2] = 0;
m_verts[2].m_uv[0] = 0;
m_verts[2].m_uv[1] = 1 - uvoffset;
// top left
m_verts[3].m_pos[0] = -hsize;
m_verts[3].m_pos[1] = size;
m_verts[3].m_pos[2] = 0;
m_verts[3].m_uv[0] = 0;
m_verts[3].m_uv[1] = 1 - uvoffset;
// bottom right
m_verts[4].m_pos[0] = hsize;
m_verts[4].m_pos[1] = 0;
m_verts[4].m_pos[2] = 0;
m_verts[4].m_uv[0] = 1 - uvoffset;
m_verts[4].m_uv[1] = 0;
// top right
m_verts[5].m_pos[0] = hsize;
m_verts[5].m_pos[1] = size;
m_verts[5].m_pos[2] = 0;
m_verts[5].m_uv[0] = 1 - uvoffset;
m_verts[5].m_uv[1] = 1 - uvoffset;
}
bool RBDecorator::AddInstance(float x, float y, float z)
{
if(m_numInstances < kMaxInstances)
{
m_instances[m_numInstances].Set(x, y, z);
m_numInstances++;
return true;
}
else
return false;
}
void RBDecorator::Print()
{
RUDE_REPORT("\nDECORATOR %s %f\n\n", RudeTextureManager::GetInstance()->GetTexture(m_textureid)->GetName(), m_size);
for(int i = 0; i < m_numInstances; i++)
{
RUDE_REPORT("%f %f %f\n", m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
}
}
void RBDecorator::Render()
{
glVertexPointer(3, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_pos);
glTexCoordPointer(2, GL_FLOAT, sizeof(RBDecoratorVert), &m_verts[0].m_uv);
RudeTextureManager::GetInstance()->SetTexture(m_textureid);
float M[16];
for(int i = 0; i < m_numInstances; i++)
{
glPushMatrix();
glTranslatef(m_instances[i].m_pos[0], m_instances[i].m_pos[1], m_instances[i].m_pos[2]);
glGetFloatv(GL_MODELVIEW_MATRIX, M);
M[0] = 1.0;
M[1] = 0.0f;
M[2] = 0.0f;
M[8] = 0.0f;
M[9] = 0.0f;
M[10] = 1.0f;
/*
for(int i=0; i<3; i+=2 )
for(int j=0; j<3; j++ ) {
if ( i==j )
M[i*4+j] = 1.0;
else
M[i*4+j] = 0.0;
}*/
glLoadMatrixf(M);
glDrawArrays(GL_TRIANGLES, 0, 6);
glPopMatrix();
}
}
RBDecoratorCollection::RBDecoratorCollection()
: m_dropTextureNum(0)
{
}
void RBDecoratorCollection::Load(const char *deco)
{
char filename[512];
sprintf(filename, "%s.deco", deco);
char path[512];
bool found = RudeFileGetFile(filename, path, 512, true);
if(!found)
return;
RUDE_REPORT("RBDecoratorCollection loading %s\n", filename);
FILE *file = fopen(path, "r");
RUDE_ASSERT(file, "Could not open file %s", path);
char buf[256];
char *line = fgets(buf, 256, file);
RBDecorator *curdeco = 0;
while(line)
{
char texturename[256];
float size = 8.0f;
int result = sscanf(line, "DECORATOR %s %f\n", texturename, &size);
if(result == 2)
{
RUDE_REPORT(" DECORATOR: texture=%s size=%f\n", texturename, size);
RBDecorator decorator;
decorator.SetTexture(texturename);
decorator.SetSize(size);
m_decorators.push_back(decorator);
curdeco = &m_decorators[m_decorators.size() - 1];
AddTexture(texturename);
}
else
{
float pos[3];
result = sscanf(line, "%f %f %f\n", &pos[0], &pos[1], &pos[2]);
if(result == 3)
{
RUDE_ASSERT(curdeco, "Failed to parse decorators, DECORATOR not defined");
RUDE_REPORT(" %f %f %f\n", pos[0], pos[1], pos[2]);
bool added = curdeco->AddInstance(pos[0], pos[1], pos[2]);
RUDE_ASSERT(added, "Failed to add decorator instance");
#ifndef NO_DECO_EDITOR
m_droppedDecorators.push_back(btVector3(pos[0], pos[1], pos[2]));
#endif
}
}
line = fgets(buf, 256, file);
}
fclose(file);
}
#ifndef NO_DECO_EDITOR
void RBDecoratorCollection::Drop(const btVector3 &pos, float size)
{
RUDE_ASSERT(m_textureNames.size() > 0, "No decorators have been loaded so there are no textures to drop with");
m_dropTextureNum++;
if(m_dropTextureNum >= m_textureNames.size())
m_dropTextureNum = 0;
// Check to make sure there's no already a decorator at this position
for(unsigned int i = 0; i < m_droppedDecorators.size(); i++)
{
if(m_droppedDecorators[i] == pos)
return;
}
m_droppedDecorators.push_back(pos);
// Check to see if we already have a decorator of the same size and texture
int curTextureID = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(m_textureNames[m_dropTextureNum].c_str());
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
RBDecorator &deco = m_decorators[i];
if(deco.GetTextureID() == curTextureID)
{
if(deco.GetSize() == size)
{
bool added = deco.AddInstance(pos.x(), pos.y(), pos.z());
if(added == false)
{
Print();
RUDE_ASSERT(added, "Failed to add decorator instance");
}
return;
}
}
}
RBDecorator deco;
deco.SetTexture(m_textureNames[m_dropTextureNum].c_str());
deco.SetSize(size);
deco.AddInstance(pos.x(), pos.y(), pos.z());
m_decorators.push_back(deco);
}
#endif
void RBDecoratorCollection::Print()
{
RUDE_REPORT("\n\n# Decorator Collection\n#\n#\n#\n");
for(unsigned int i = 0; i < m_decorators.size(); i++)
{
m_decorators[i].Print();
}
}
void RBDecoratorCollection::Render()
{
unsigned int numdecos = m_decorators.size();
if(numdecos == 0 || gRenderDecos == false)
return;
// set up draw state
RGL.Enable(kBackfaceCull, false);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kColorArray, false);
RGL.EnableClient(kTextureCoordArray, true);
glAlphaFunc(GL_GREATER, 0.5);
glEnable(GL_ALPHA_TEST);
// set up GL matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
float w = RGL.GetHalfWidth();
float h = RGL.GetHalfHeight();
RGL.Frustum(0.0f, 0.0f, w * 2.0f, h * 2.0f, 4.0f, 2500.0f);
btVector3 eye = RGL.GetEye();
btVector3 forward = RGL.GetForward();
btVector3 inup(0, 1, 0);
btVector3 side = inup.cross(forward);
side.normalize();
btVector3 up = forward.cross(side);
float M[] =
{
side.x(), up.x(), forward.x(), 0,
side.y(), up.y(), forward.y(), 0,
side.z(), up.z(), forward.z(), 0,
0, 0, 0, 1
};
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(M);
glTranslatef (-eye.x(), -eye.y(), -eye.z());
for(unsigned int i = 0; i < numdecos; i++)
{
m_decorators[i].Render();
}
// restore GL matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
RGL.LoadIdentity();
// restore draw state
glDisable(GL_ALPHA_TEST);
}
void RBDecoratorCollection::AddTexture(const char *textureName)
{
unsigned int size = m_textureNames.size();
bool found = false;
for(int i = 0; i < size; i++)
{
if(m_textureNames[i] == std::string(textureName))
found = true;
}
if(!found)
m_textureNames.push_back(std::string(textureName));
}
<|endoftext|> |
<commit_before>#include<stdio.h>
#include<stdlib.h>
int main()
{
int a;
a = 20161107;
printf_s("%d\n", a);
system("pause");
return(0);
}<commit_msg>Update Source.cpp<commit_after>#include<stdio.h>
#include<stdlib.h>
int main()
{
int b;
b = 20161107;
printf_s("%d\n", b);
system("pause");
return(0);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sortparam.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2008-01-29 15:20: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "sortparam.hxx"
#include "global.hxx"
#include "address.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//------------------------------------------------------------------------
ScSortParam::ScSortParam()
{
Clear();
}
//------------------------------------------------------------------------
ScSortParam::ScSortParam( const ScSortParam& r ) :
nCol1(r.nCol1),nRow1(r.nRow1),nCol2(r.nCol2),nRow2(r.nRow2),
bHasHeader(r.bHasHeader),bByRow(r.bByRow),bCaseSens(r.bCaseSens),
bUserDef(r.bUserDef),nUserIndex(r.nUserIndex),bIncludePattern(r.bIncludePattern),
bInplace(r.bInplace),
nDestTab(r.nDestTab),nDestCol(r.nDestCol),nDestRow(r.nDestRow),
aCollatorLocale( r.aCollatorLocale ), aCollatorAlgorithm( r.aCollatorAlgorithm )
{
for (USHORT i=0; i<MAXSORT; i++)
{
bDoSort[i] = r.bDoSort[i];
nField[i] = r.nField[i];
bAscending[i] = r.bAscending[i];
}
}
//------------------------------------------------------------------------
void ScSortParam::Clear()
{
nCol1=nCol2=nDestCol = 0;
nRow1=nRow2=nDestRow = 0;
nCompatHeader = 2;
nDestTab = 0;
nUserIndex = 0;
bHasHeader=bCaseSens=bUserDef = FALSE;
bByRow=bIncludePattern=bInplace = TRUE;
aCollatorLocale = ::com::sun::star::lang::Locale();
aCollatorAlgorithm.Erase();
for (USHORT i=0; i<MAXSORT; i++)
{
bDoSort[i] = FALSE;
nField[i] = 0;
bAscending[i] = TRUE;
}
}
//------------------------------------------------------------------------
ScSortParam& ScSortParam::operator=( const ScSortParam& r )
{
nCol1 = r.nCol1;
nRow1 = r.nRow1;
nCol2 = r.nCol2;
nRow2 = r.nRow2;
bHasHeader = r.bHasHeader;
bCaseSens = r.bCaseSens;
bByRow = r.bByRow;
bUserDef = r.bUserDef;
nUserIndex = r.nUserIndex;
bIncludePattern = r.bIncludePattern;
bInplace = r.bInplace;
nDestTab = r.nDestTab;
nDestCol = r.nDestCol;
nDestRow = r.nDestRow;
aCollatorLocale = r.aCollatorLocale;
aCollatorAlgorithm = r.aCollatorAlgorithm;
for (USHORT i=0; i<MAXSORT; i++)
{
bDoSort[i] = r.bDoSort[i];
nField[i] = r.nField[i];
bAscending[i] = r.bAscending[i];
}
return *this;
}
//------------------------------------------------------------------------
BOOL ScSortParam::operator==( const ScSortParam& rOther ) const
{
BOOL bEqual = FALSE;
// Anzahl der Sorts gleich?
USHORT nLast = 0;
USHORT nOtherLast = 0;
while ( bDoSort[nLast++] && nLast < MAXSORT );
while ( rOther.bDoSort[nOtherLast++] && nOtherLast < MAXSORT );
nLast--;
nOtherLast--;
if ( (nLast == nOtherLast)
&& (nCol1 == rOther.nCol1)
&& (nRow1 == rOther.nRow1)
&& (nCol2 == rOther.nCol2)
&& (nRow2 == rOther.nRow2)
&& (bHasHeader == rOther.bHasHeader)
&& (bByRow == rOther.bByRow)
&& (bCaseSens == rOther.bCaseSens)
&& (bUserDef == rOther.bUserDef)
&& (nUserIndex == rOther.nUserIndex)
&& (bIncludePattern == rOther.bIncludePattern)
&& (bInplace == rOther.bInplace)
&& (nDestTab == rOther.nDestTab)
&& (nDestCol == rOther.nDestCol)
&& (nDestRow == rOther.nDestRow)
&& (aCollatorLocale.Language == rOther.aCollatorLocale.Language)
&& (aCollatorLocale.Country == rOther.aCollatorLocale.Country)
&& (aCollatorLocale.Variant == rOther.aCollatorLocale.Variant)
&& (aCollatorAlgorithm == rOther.aCollatorAlgorithm)
)
{
bEqual = TRUE;
for ( USHORT i=0; i<=nLast && bEqual; i++ )
{
bEqual = (nField[i] == rOther.nField[i]) && (bAscending[i] == rOther.bAscending[i]);
}
}
return bEqual;
}
//------------------------------------------------------------------------
ScSortParam::ScSortParam( const ScSubTotalParam& rSub, const ScSortParam& rOld ) :
nCol1(rSub.nCol1),nRow1(rSub.nRow1),nCol2(rSub.nCol2),nRow2(rSub.nRow2),
bHasHeader(TRUE),bByRow(TRUE),bCaseSens(rSub.bCaseSens),
bUserDef(rSub.bUserDef),nUserIndex(rSub.nUserIndex),bIncludePattern(rSub.bIncludePattern),
bInplace(TRUE),
nDestTab(0),nDestCol(0),nDestRow(0),
aCollatorLocale( rOld.aCollatorLocale ), aCollatorAlgorithm( rOld.aCollatorAlgorithm )
{
USHORT nNewCount = 0;
USHORT i;
// zuerst die Gruppen aus den Teilergebnissen
if (rSub.bDoSort)
for (i=0; i<MAXSUBTOTAL; i++)
if (rSub.bGroupActive[i])
{
if (nNewCount < MAXSORT)
{
bDoSort[nNewCount] = TRUE;
nField[nNewCount] = rSub.nField[i];
bAscending[nNewCount] = rSub.bAscending;
++nNewCount;
}
}
// dann dahinter die alten Einstellungen
for (i=0; i<MAXSORT; i++)
if (rOld.bDoSort[i])
{
SCCOLROW nThisField = rOld.nField[i];
BOOL bDouble = FALSE;
for (USHORT j=0; j<nNewCount; j++)
if ( nField[j] == nThisField )
bDouble = TRUE;
if (!bDouble) // ein Feld nicht zweimal eintragen
{
if (nNewCount < MAXSORT)
{
bDoSort[nNewCount] = TRUE;
nField[nNewCount] = nThisField;
bAscending[nNewCount] = rOld.bAscending[i];
++nNewCount;
}
}
}
for (i=nNewCount; i<MAXSORT; i++) // Rest loeschen
{
bDoSort[i] = FALSE;
nField[i] = 0;
bAscending[i] = TRUE;
}
}
//------------------------------------------------------------------------
ScSortParam::ScSortParam( const ScQueryParam& rParam, SCCOL nCol ) :
nCol1(nCol),nRow1(rParam.nRow1),nCol2(nCol),nRow2(rParam.nRow2),
bHasHeader(rParam.bHasHeader),bByRow(TRUE),bCaseSens(rParam.bCaseSens),
//! TODO: what about Locale and Algorithm?
bUserDef(FALSE),nUserIndex(0),bIncludePattern(FALSE),
bInplace(TRUE),
nDestTab(0),nDestCol(0),nDestRow(0)
{
bDoSort[0] = TRUE;
nField[0] = nCol;
bAscending[0] = TRUE;
for (USHORT i=1; i<MAXSORT; i++)
{
bDoSort[i] = FALSE;
nField[i] = 0;
bAscending[i] = TRUE;
}
}
//------------------------------------------------------------------------
void ScSortParam::MoveToDest()
{
if (!bInplace)
{
SCsCOL nDifX = ((SCsCOL) nDestCol) - ((SCsCOL) nCol1);
SCsROW nDifY = ((SCsROW) nDestRow) - ((SCsROW) nRow1);
nCol1 = sal::static_int_cast<SCCOL>( nCol1 + nDifX );
nRow1 = sal::static_int_cast<SCROW>( nRow1 + nDifY );
nCol2 = sal::static_int_cast<SCCOL>( nCol2 + nDifX );
nRow2 = sal::static_int_cast<SCROW>( nRow2 + nDifY );
for (USHORT i=0; i<MAXSORT; i++)
if (bByRow)
nField[i] += nDifX;
else
nField[i] += nDifY;
bInplace = TRUE;
}
else
{
DBG_ERROR("MoveToDest, bInplace == TRUE");
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.88); FILE MERGED 2008/04/01 15:29:54 thb 1.7.88.2: #i85898# Stripping all external header guards 2008/03/31 17:13:53 rt 1.7.88.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: sortparam.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_sc.hxx"
#include "sortparam.hxx"
#include "global.hxx"
#include "address.hxx"
#include <tools/debug.hxx>
//------------------------------------------------------------------------
ScSortParam::ScSortParam()
{
Clear();
}
//------------------------------------------------------------------------
ScSortParam::ScSortParam( const ScSortParam& r ) :
nCol1(r.nCol1),nRow1(r.nRow1),nCol2(r.nCol2),nRow2(r.nRow2),
bHasHeader(r.bHasHeader),bByRow(r.bByRow),bCaseSens(r.bCaseSens),
bUserDef(r.bUserDef),nUserIndex(r.nUserIndex),bIncludePattern(r.bIncludePattern),
bInplace(r.bInplace),
nDestTab(r.nDestTab),nDestCol(r.nDestCol),nDestRow(r.nDestRow),
aCollatorLocale( r.aCollatorLocale ), aCollatorAlgorithm( r.aCollatorAlgorithm )
{
for (USHORT i=0; i<MAXSORT; i++)
{
bDoSort[i] = r.bDoSort[i];
nField[i] = r.nField[i];
bAscending[i] = r.bAscending[i];
}
}
//------------------------------------------------------------------------
void ScSortParam::Clear()
{
nCol1=nCol2=nDestCol = 0;
nRow1=nRow2=nDestRow = 0;
nCompatHeader = 2;
nDestTab = 0;
nUserIndex = 0;
bHasHeader=bCaseSens=bUserDef = FALSE;
bByRow=bIncludePattern=bInplace = TRUE;
aCollatorLocale = ::com::sun::star::lang::Locale();
aCollatorAlgorithm.Erase();
for (USHORT i=0; i<MAXSORT; i++)
{
bDoSort[i] = FALSE;
nField[i] = 0;
bAscending[i] = TRUE;
}
}
//------------------------------------------------------------------------
ScSortParam& ScSortParam::operator=( const ScSortParam& r )
{
nCol1 = r.nCol1;
nRow1 = r.nRow1;
nCol2 = r.nCol2;
nRow2 = r.nRow2;
bHasHeader = r.bHasHeader;
bCaseSens = r.bCaseSens;
bByRow = r.bByRow;
bUserDef = r.bUserDef;
nUserIndex = r.nUserIndex;
bIncludePattern = r.bIncludePattern;
bInplace = r.bInplace;
nDestTab = r.nDestTab;
nDestCol = r.nDestCol;
nDestRow = r.nDestRow;
aCollatorLocale = r.aCollatorLocale;
aCollatorAlgorithm = r.aCollatorAlgorithm;
for (USHORT i=0; i<MAXSORT; i++)
{
bDoSort[i] = r.bDoSort[i];
nField[i] = r.nField[i];
bAscending[i] = r.bAscending[i];
}
return *this;
}
//------------------------------------------------------------------------
BOOL ScSortParam::operator==( const ScSortParam& rOther ) const
{
BOOL bEqual = FALSE;
// Anzahl der Sorts gleich?
USHORT nLast = 0;
USHORT nOtherLast = 0;
while ( bDoSort[nLast++] && nLast < MAXSORT );
while ( rOther.bDoSort[nOtherLast++] && nOtherLast < MAXSORT );
nLast--;
nOtherLast--;
if ( (nLast == nOtherLast)
&& (nCol1 == rOther.nCol1)
&& (nRow1 == rOther.nRow1)
&& (nCol2 == rOther.nCol2)
&& (nRow2 == rOther.nRow2)
&& (bHasHeader == rOther.bHasHeader)
&& (bByRow == rOther.bByRow)
&& (bCaseSens == rOther.bCaseSens)
&& (bUserDef == rOther.bUserDef)
&& (nUserIndex == rOther.nUserIndex)
&& (bIncludePattern == rOther.bIncludePattern)
&& (bInplace == rOther.bInplace)
&& (nDestTab == rOther.nDestTab)
&& (nDestCol == rOther.nDestCol)
&& (nDestRow == rOther.nDestRow)
&& (aCollatorLocale.Language == rOther.aCollatorLocale.Language)
&& (aCollatorLocale.Country == rOther.aCollatorLocale.Country)
&& (aCollatorLocale.Variant == rOther.aCollatorLocale.Variant)
&& (aCollatorAlgorithm == rOther.aCollatorAlgorithm)
)
{
bEqual = TRUE;
for ( USHORT i=0; i<=nLast && bEqual; i++ )
{
bEqual = (nField[i] == rOther.nField[i]) && (bAscending[i] == rOther.bAscending[i]);
}
}
return bEqual;
}
//------------------------------------------------------------------------
ScSortParam::ScSortParam( const ScSubTotalParam& rSub, const ScSortParam& rOld ) :
nCol1(rSub.nCol1),nRow1(rSub.nRow1),nCol2(rSub.nCol2),nRow2(rSub.nRow2),
bHasHeader(TRUE),bByRow(TRUE),bCaseSens(rSub.bCaseSens),
bUserDef(rSub.bUserDef),nUserIndex(rSub.nUserIndex),bIncludePattern(rSub.bIncludePattern),
bInplace(TRUE),
nDestTab(0),nDestCol(0),nDestRow(0),
aCollatorLocale( rOld.aCollatorLocale ), aCollatorAlgorithm( rOld.aCollatorAlgorithm )
{
USHORT nNewCount = 0;
USHORT i;
// zuerst die Gruppen aus den Teilergebnissen
if (rSub.bDoSort)
for (i=0; i<MAXSUBTOTAL; i++)
if (rSub.bGroupActive[i])
{
if (nNewCount < MAXSORT)
{
bDoSort[nNewCount] = TRUE;
nField[nNewCount] = rSub.nField[i];
bAscending[nNewCount] = rSub.bAscending;
++nNewCount;
}
}
// dann dahinter die alten Einstellungen
for (i=0; i<MAXSORT; i++)
if (rOld.bDoSort[i])
{
SCCOLROW nThisField = rOld.nField[i];
BOOL bDouble = FALSE;
for (USHORT j=0; j<nNewCount; j++)
if ( nField[j] == nThisField )
bDouble = TRUE;
if (!bDouble) // ein Feld nicht zweimal eintragen
{
if (nNewCount < MAXSORT)
{
bDoSort[nNewCount] = TRUE;
nField[nNewCount] = nThisField;
bAscending[nNewCount] = rOld.bAscending[i];
++nNewCount;
}
}
}
for (i=nNewCount; i<MAXSORT; i++) // Rest loeschen
{
bDoSort[i] = FALSE;
nField[i] = 0;
bAscending[i] = TRUE;
}
}
//------------------------------------------------------------------------
ScSortParam::ScSortParam( const ScQueryParam& rParam, SCCOL nCol ) :
nCol1(nCol),nRow1(rParam.nRow1),nCol2(nCol),nRow2(rParam.nRow2),
bHasHeader(rParam.bHasHeader),bByRow(TRUE),bCaseSens(rParam.bCaseSens),
//! TODO: what about Locale and Algorithm?
bUserDef(FALSE),nUserIndex(0),bIncludePattern(FALSE),
bInplace(TRUE),
nDestTab(0),nDestCol(0),nDestRow(0)
{
bDoSort[0] = TRUE;
nField[0] = nCol;
bAscending[0] = TRUE;
for (USHORT i=1; i<MAXSORT; i++)
{
bDoSort[i] = FALSE;
nField[i] = 0;
bAscending[i] = TRUE;
}
}
//------------------------------------------------------------------------
void ScSortParam::MoveToDest()
{
if (!bInplace)
{
SCsCOL nDifX = ((SCsCOL) nDestCol) - ((SCsCOL) nCol1);
SCsROW nDifY = ((SCsROW) nDestRow) - ((SCsROW) nRow1);
nCol1 = sal::static_int_cast<SCCOL>( nCol1 + nDifX );
nRow1 = sal::static_int_cast<SCROW>( nRow1 + nDifY );
nCol2 = sal::static_int_cast<SCCOL>( nCol2 + nDifX );
nRow2 = sal::static_int_cast<SCROW>( nRow2 + nDifY );
for (USHORT i=0; i<MAXSORT; i++)
if (bByRow)
nField[i] += nDifX;
else
nField[i] += nDifY;
bInplace = TRUE;
}
else
{
DBG_ERROR("MoveToDest, bInplace == TRUE");
}
}
<|endoftext|> |
<commit_before><commit_msg>GPU Calc: Fixed accuracy bug of BitAnd<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "xiname.hxx"
#include "rangenam.hxx"
#include "xistream.hxx"
// for formula compiler
#include "excform.hxx"
// for filter manager
#include "excimp8.hxx"
#include "scextopt.hxx"
#include "document.hxx"
// ============================================================================
// *** Implementation ***
// ============================================================================
XclImpName::XclImpName( XclImpStream& rStrm, sal_uInt16 nXclNameIdx ) :
XclImpRoot( rStrm.GetRoot() ),
mpScData( 0 ),
mcBuiltIn( EXC_BUILTIN_UNKNOWN ),
mnScTab( SCTAB_MAX ),
mbFunction( false ),
mbVBName( false )
{
ExcelToSc& rFmlaConv = GetOldFmlaConverter();
// 1) *** read data from stream *** ---------------------------------------
sal_uInt16 nFlags = 0, nFmlaSize = 0, nExtSheet = EXC_NAME_GLOBAL, nXclTab = EXC_NAME_GLOBAL;
sal_uInt8 nNameLen = 0, nShortCut;
switch( GetBiff() )
{
case EXC_BIFF2:
{
sal_uInt8 nFlagsBiff2;
rStrm >> nFlagsBiff2;
rStrm.Ignore( 1 );
rStrm >> nShortCut >> nNameLen;
nFmlaSize = rStrm.ReaduInt8();
::set_flag( nFlags, EXC_NAME_FUNC, ::get_flag( nFlagsBiff2, EXC_NAME2_FUNC ) );
}
break;
case EXC_BIFF3:
case EXC_BIFF4:
{
rStrm >> nFlags >> nShortCut >> nNameLen >> nFmlaSize;
}
break;
case EXC_BIFF5:
case EXC_BIFF8:
{
rStrm >> nFlags >> nShortCut >> nNameLen >> nFmlaSize >> nExtSheet >> nXclTab;
rStrm.Ignore( 4 );
}
break;
default: DBG_ERROR_BIFF();
}
if( GetBiff() <= EXC_BIFF5 )
maXclName = rStrm.ReadRawByteString( nNameLen );
else
maXclName = rStrm.ReadUniString( nNameLen );
// 2) *** convert sheet index and name *** --------------------------------
// functions and VBA
mbFunction = ::get_flag( nFlags, EXC_NAME_FUNC );
mbVBName = ::get_flag( nFlags, EXC_NAME_VB );
// get built-in name, or convert characters invalid in Calc
bool bBuiltIn = ::get_flag( nFlags, EXC_NAME_BUILTIN );
// special case for BIFF5 filter range - name appears as plain text without built-in flag
if( (GetBiff() == EXC_BIFF5) && (maXclName == XclTools::GetXclBuiltInDefName( EXC_BUILTIN_FILTERDATABASE )) )
{
bBuiltIn = true;
maXclName.Assign( EXC_BUILTIN_FILTERDATABASE );
}
// convert Excel name to Calc name
if( mbVBName )
{
// VB macro name
maScName = maXclName;
}
else if( bBuiltIn )
{
// built-in name
if( maXclName.Len() )
mcBuiltIn = maXclName.GetChar( 0 );
if( mcBuiltIn == '?' ) // NUL character is imported as '?'
mcBuiltIn = '\0';
maScName = XclTools::GetBuiltInDefName( mcBuiltIn );
}
else
{
// any other name
maScName = maXclName;
ScfTools::ConvertToScDefinedName( maScName );
}
rtl::OUString aRealOrigName = maScName;
// add index for local names
if( nXclTab != EXC_NAME_GLOBAL )
{
sal_uInt16 nUsedTab = (GetBiff() == EXC_BIFF8) ? nXclTab : nExtSheet;
// do not rename sheet-local names by default, this breaks VBA scripts
// maScName.Append( '_' ).Append( String::CreateFromInt32( nUsedTab ) );
// TODO: may not work for BIFF5, handle skipped sheets (all BIFF)
mnScTab = static_cast< SCTAB >( nUsedTab - 1 );
}
// 3) *** convert the name definition formula *** -------------------------
rFmlaConv.Reset();
const ScTokenArray* pTokArr = 0; // pointer to token array, owned by rFmlaConv
RangeType nNameType = RT_NAME;
if( ::get_flag( nFlags, EXC_NAME_BIG ) )
{
// special, unsupported name
rFmlaConv.GetDummy( pTokArr );
}
else if( bBuiltIn )
{
SCsTAB const nLocalTab = (nXclTab == EXC_NAME_GLOBAL) ? SCTAB_MAX : (nXclTab - 1);
// --- print ranges or title ranges ---
rStrm.PushPosition();
switch( mcBuiltIn )
{
case EXC_BUILTIN_PRINTAREA:
if( rFmlaConv.Convert( GetPrintAreaBuffer(), rStrm, nFmlaSize, nLocalTab, FT_RangeName ) == ConvOK )
nNameType |= RT_PRINTAREA;
break;
case EXC_BUILTIN_PRINTTITLES:
if( rFmlaConv.Convert( GetTitleAreaBuffer(), rStrm, nFmlaSize, nLocalTab, FT_RangeName ) == ConvOK )
nNameType |= RT_COLHEADER | RT_ROWHEADER;
break;
}
rStrm.PopPosition();
// --- name formula ---
// JEG : double check this. It is clearly false for normal names
// but some of the builtins (sheettitle?) might be able to handle arrays
rFmlaConv.Convert( pTokArr, rStrm, nFmlaSize, false, FT_RangeName );
// --- auto or advanced filter ---
if( (GetBiff() == EXC_BIFF8) && pTokArr && bBuiltIn )
{
ScRange aRange;
if( pTokArr->IsReference( aRange ) )
{
switch( mcBuiltIn )
{
case EXC_BUILTIN_FILTERDATABASE:
GetFilterManager().Insert( &GetOldRoot(), aRange);
break;
case EXC_BUILTIN_CRITERIA:
GetFilterManager().AddAdvancedRange( aRange );
nNameType |= RT_CRITERIA;
break;
case EXC_BUILTIN_EXTRACT:
if( pTokArr->IsValidReference( aRange ) )
GetFilterManager().AddExtractPos( aRange );
break;
}
}
}
}
else if( nFmlaSize > 0 )
{
// regular defined name
rFmlaConv.Convert( pTokArr, rStrm, nFmlaSize, true, FT_RangeName );
}
// 4) *** create a defined name in the Calc document *** ------------------
// do not ignore hidden names (may be regular names created by VBA scripts)
if( pTokArr /*&& (bBuiltIn || !::get_flag( nFlags, EXC_NAME_HIDDEN ))*/ && !mbFunction && !mbVBName )
{
// create the Calc name data
ScRangeData* pData = new ScRangeData( GetDocPtr(), maScName, *pTokArr, ScAddress(), nNameType );
pData->GuessPosition(); // calculate base position for relative refs
pData->SetIndex( nXclNameIdx ); // used as unique identifier in formulas
if (nXclTab == EXC_NAME_GLOBAL)
GetDoc().GetRangeName()->insert(pData);
else
{
ScRangeName* pLocalNames = GetDoc().GetRangeName(mnScTab);
if (pLocalNames)
pLocalNames->insert(pData);
if (GetBiff() == EXC_BIFF8)
{
ScRange aRange;
// discard deleted ranges ( for the moment at least )
if ( pData->IsValidReference( aRange ) )
{
GetExtDocOptions().GetOrCreateTabSettings( nXclTab );
}
}
}
mpScData = pData; // cache for later use
}
}
// ----------------------------------------------------------------------------
XclImpNameManager::XclImpNameManager( const XclImpRoot& rRoot ) :
XclImpRoot( rRoot )
{
}
void XclImpNameManager::ReadName( XclImpStream& rStrm )
{
sal_uLong nCount = maNameList.size();
if( nCount < 0xFFFF )
maNameList.push_back( new XclImpName( rStrm, static_cast< sal_uInt16 >( nCount + 1 ) ) );
}
const XclImpName* XclImpNameManager::FindName( const String& rXclName, SCTAB nScTab ) const
{
const XclImpName* pGlobalName = 0; // a found global name
const XclImpName* pLocalName = 0; // a found local name
for( XclImpNameList::const_iterator itName = maNameList.begin(); itName != maNameList.end() && !pLocalName; ++itName )
{
if( itName->GetXclName() == rXclName )
{
if( itName->GetScTab() == nScTab )
pLocalName = &(*itName);
else if( itName->IsGlobal() )
pGlobalName = &(*itName);
}
}
return pLocalName ? pLocalName : pGlobalName;
}
const XclImpName* XclImpNameManager::GetName( sal_uInt16 nXclNameIdx ) const
{
OSL_ENSURE( nXclNameIdx > 0, "XclImpNameManager::GetName - index must be >0" );
return ( nXclNameIdx >= maNameList.size() ) ? NULL : &(maNameList.at( nXclNameIdx - 1 ));
}
// ============================================================================
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix for fdo#38204: formulas with range names were not imported correctly<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "xiname.hxx"
#include "rangenam.hxx"
#include "xistream.hxx"
// for formula compiler
#include "excform.hxx"
// for filter manager
#include "excimp8.hxx"
#include "scextopt.hxx"
#include "document.hxx"
// ============================================================================
// *** Implementation ***
// ============================================================================
XclImpName::XclImpName( XclImpStream& rStrm, sal_uInt16 nXclNameIdx ) :
XclImpRoot( rStrm.GetRoot() ),
mpScData( 0 ),
mcBuiltIn( EXC_BUILTIN_UNKNOWN ),
mnScTab( SCTAB_MAX ),
mbFunction( false ),
mbVBName( false )
{
ExcelToSc& rFmlaConv = GetOldFmlaConverter();
// 1) *** read data from stream *** ---------------------------------------
sal_uInt16 nFlags = 0, nFmlaSize = 0, nExtSheet = EXC_NAME_GLOBAL, nXclTab = EXC_NAME_GLOBAL;
sal_uInt8 nNameLen = 0, nShortCut;
switch( GetBiff() )
{
case EXC_BIFF2:
{
sal_uInt8 nFlagsBiff2;
rStrm >> nFlagsBiff2;
rStrm.Ignore( 1 );
rStrm >> nShortCut >> nNameLen;
nFmlaSize = rStrm.ReaduInt8();
::set_flag( nFlags, EXC_NAME_FUNC, ::get_flag( nFlagsBiff2, EXC_NAME2_FUNC ) );
}
break;
case EXC_BIFF3:
case EXC_BIFF4:
{
rStrm >> nFlags >> nShortCut >> nNameLen >> nFmlaSize;
}
break;
case EXC_BIFF5:
case EXC_BIFF8:
{
rStrm >> nFlags >> nShortCut >> nNameLen >> nFmlaSize >> nExtSheet >> nXclTab;
rStrm.Ignore( 4 );
}
break;
default: DBG_ERROR_BIFF();
}
if( GetBiff() <= EXC_BIFF5 )
maXclName = rStrm.ReadRawByteString( nNameLen );
else
maXclName = rStrm.ReadUniString( nNameLen );
// 2) *** convert sheet index and name *** --------------------------------
// functions and VBA
mbFunction = ::get_flag( nFlags, EXC_NAME_FUNC );
mbVBName = ::get_flag( nFlags, EXC_NAME_VB );
// get built-in name, or convert characters invalid in Calc
bool bBuiltIn = ::get_flag( nFlags, EXC_NAME_BUILTIN );
// special case for BIFF5 filter range - name appears as plain text without built-in flag
if( (GetBiff() == EXC_BIFF5) && (maXclName == XclTools::GetXclBuiltInDefName( EXC_BUILTIN_FILTERDATABASE )) )
{
bBuiltIn = true;
maXclName.Assign( EXC_BUILTIN_FILTERDATABASE );
}
// convert Excel name to Calc name
if( mbVBName )
{
// VB macro name
maScName = maXclName;
}
else if( bBuiltIn )
{
// built-in name
if( maXclName.Len() )
mcBuiltIn = maXclName.GetChar( 0 );
if( mcBuiltIn == '?' ) // NUL character is imported as '?'
mcBuiltIn = '\0';
maScName = XclTools::GetBuiltInDefName( mcBuiltIn );
}
else
{
// any other name
maScName = maXclName;
ScfTools::ConvertToScDefinedName( maScName );
}
rtl::OUString aRealOrigName = maScName;
// add index for local names
if( nXclTab != EXC_NAME_GLOBAL )
{
sal_uInt16 nUsedTab = (GetBiff() == EXC_BIFF8) ? nXclTab : nExtSheet;
// do not rename sheet-local names by default, this breaks VBA scripts
// maScName.Append( '_' ).Append( String::CreateFromInt32( nUsedTab ) );
// TODO: may not work for BIFF5, handle skipped sheets (all BIFF)
mnScTab = static_cast< SCTAB >( nUsedTab - 1 );
}
// 3) *** convert the name definition formula *** -------------------------
rFmlaConv.Reset();
const ScTokenArray* pTokArr = 0; // pointer to token array, owned by rFmlaConv
RangeType nNameType = RT_NAME;
if( ::get_flag( nFlags, EXC_NAME_BIG ) )
{
// special, unsupported name
rFmlaConv.GetDummy( pTokArr );
}
else if( bBuiltIn )
{
SCsTAB const nLocalTab = (nXclTab == EXC_NAME_GLOBAL) ? SCTAB_MAX : (nXclTab - 1);
// --- print ranges or title ranges ---
rStrm.PushPosition();
switch( mcBuiltIn )
{
case EXC_BUILTIN_PRINTAREA:
if( rFmlaConv.Convert( GetPrintAreaBuffer(), rStrm, nFmlaSize, nLocalTab, FT_RangeName ) == ConvOK )
nNameType |= RT_PRINTAREA;
break;
case EXC_BUILTIN_PRINTTITLES:
if( rFmlaConv.Convert( GetTitleAreaBuffer(), rStrm, nFmlaSize, nLocalTab, FT_RangeName ) == ConvOK )
nNameType |= RT_COLHEADER | RT_ROWHEADER;
break;
}
rStrm.PopPosition();
// --- name formula ---
// JEG : double check this. It is clearly false for normal names
// but some of the builtins (sheettitle?) might be able to handle arrays
rFmlaConv.Convert( pTokArr, rStrm, nFmlaSize, false, FT_RangeName );
// --- auto or advanced filter ---
if( (GetBiff() == EXC_BIFF8) && pTokArr && bBuiltIn )
{
ScRange aRange;
if( pTokArr->IsReference( aRange ) )
{
switch( mcBuiltIn )
{
case EXC_BUILTIN_FILTERDATABASE:
GetFilterManager().Insert( &GetOldRoot(), aRange);
break;
case EXC_BUILTIN_CRITERIA:
GetFilterManager().AddAdvancedRange( aRange );
nNameType |= RT_CRITERIA;
break;
case EXC_BUILTIN_EXTRACT:
if( pTokArr->IsValidReference( aRange ) )
GetFilterManager().AddExtractPos( aRange );
break;
}
}
}
}
else if( nFmlaSize > 0 )
{
// regular defined name
rFmlaConv.Convert( pTokArr, rStrm, nFmlaSize, true, FT_RangeName );
}
// 4) *** create a defined name in the Calc document *** ------------------
// do not ignore hidden names (may be regular names created by VBA scripts)
if( pTokArr /*&& (bBuiltIn || !::get_flag( nFlags, EXC_NAME_HIDDEN ))*/ && !mbFunction && !mbVBName )
{
// create the Calc name data
ScRangeData* pData = new ScRangeData( GetDocPtr(), maScName, *pTokArr, ScAddress(), nNameType );
pData->GuessPosition(); // calculate base position for relative refs
pData->SetIndex( nXclNameIdx ); // used as unique identifier in formulas
if (nXclTab == EXC_NAME_GLOBAL)
GetDoc().GetRangeName()->insert(pData);
else
{
ScRangeName* pLocalNames = GetDoc().GetRangeName(mnScTab);
if (pLocalNames)
pLocalNames->insert(pData);
if (GetBiff() == EXC_BIFF8)
{
ScRange aRange;
// discard deleted ranges ( for the moment at least )
if ( pData->IsValidReference( aRange ) )
{
GetExtDocOptions().GetOrCreateTabSettings( nXclTab );
}
}
}
mpScData = pData; // cache for later use
}
}
// ----------------------------------------------------------------------------
XclImpNameManager::XclImpNameManager( const XclImpRoot& rRoot ) :
XclImpRoot( rRoot )
{
}
void XclImpNameManager::ReadName( XclImpStream& rStrm )
{
sal_uLong nCount = maNameList.size();
if( nCount < 0xFFFF )
maNameList.push_back( new XclImpName( rStrm, static_cast< sal_uInt16 >( nCount + 1 ) ) );
}
const XclImpName* XclImpNameManager::FindName( const String& rXclName, SCTAB nScTab ) const
{
const XclImpName* pGlobalName = 0; // a found global name
const XclImpName* pLocalName = 0; // a found local name
for( XclImpNameList::const_iterator itName = maNameList.begin(); itName != maNameList.end() && !pLocalName; ++itName )
{
if( itName->GetXclName() == rXclName )
{
if( itName->GetScTab() == nScTab )
pLocalName = &(*itName);
else if( itName->IsGlobal() )
pGlobalName = &(*itName);
}
}
return pLocalName ? pLocalName : pGlobalName;
}
const XclImpName* XclImpNameManager::GetName( sal_uInt16 nXclNameIdx ) const
{
OSL_ENSURE( nXclNameIdx > 0, "XclImpNameManager::GetName - index must be >0" );
return ( nXclNameIdx > maNameList.size() ) ? NULL : &(maNameList.at( nXclNameIdx - 1 ));
}
// ============================================================================
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xeescher.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-01-14 12:09:01 $
*
* 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 SC_XEESCHER_HXX
#define SC_XEESCHER_HXX
#ifndef SC_XLESCHER_HXX
#include "xlescher.hxx"
#endif
#include "xcl97rec.hxx"
namespace com { namespace sun { namespace star {
namespace script { struct ScriptEventDescriptor; }
} } }
// ============================================================================
class XclExpTokenArray;
/** Helper to manage controls linked to the sheet. */
class XclExpCtrlLinkHelper : protected XclExpRoot
{
public:
explicit XclExpCtrlLinkHelper( const XclExpRoot& rRoot );
virtual ~XclExpCtrlLinkHelper();
/** Sets the address of the control's linked cell. */
void SetCellLink( const ScAddress& rCellLink );
/** Sets the address of the control's linked source cell range. */
void SetSourceRange( const ScRange& rSrcRange );
protected:
/** Returns the Excel token array of the cell link, or 0, if no link present. */
inline const XclExpTokenArray* GetCellLinkTokArr() const { return mxCellLink.get(); }
/** Returns the Excel token array of the source range, or 0, if no link present. */
inline const XclExpTokenArray* GetSourceRangeTokArr() const { return mxSrcRange.get(); }
/** Returns the number of entries in the source range, or 0, if no source set. */
inline sal_uInt16 GetSourceEntryCount() const { return mnEntryCount; }
/** Writes a formula with special style only valid in OBJ records. */
void WriteFormula( XclExpStream& rStrm, const XclExpTokenArray& rTokArr ) const;
/** Writes a formula subrecord with special style only valid in OBJ records. */
void WriteFormulaSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId, const XclExpTokenArray& rTokArr ) const;
private:
XclExpTokenArrayRef mxCellLink; /// Formula for linked cell.
XclExpTokenArrayRef mxSrcRange; /// Formula for source data range.
sal_uInt16 mnEntryCount; /// Number of entries in source range.
};
// ----------------------------------------------------------------------------
#if EXC_EXP_OCX_CTRL
/** Represents an OBJ record for an OCX form control. */
class XclExpObjOcxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjOcxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel,
const String& rClassName,
sal_uInt32 nStrmStart, sal_uInt32 nStrmSize );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
private:
String maClassName; /// Class name of the control.
sal_uInt32 mnStrmStart; /// Start position in 'Ctls' stream.
sal_uInt32 mnStrmSize; /// Size in 'Ctls' stream.
};
#else
/** Represents an OBJ record for an TBX form control. */
class XclExpObjTbxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjTbxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel );
/** Sets the name of a macro attached to this control.
@return true = The passed event descriptor was valid, macro name has been found. */
bool SetMacroLink( const ::com::sun::star::script::ScriptEventDescriptor& rEvent );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
/** Writes an ftMacro subrecord containing a macro link, or nothing, if no macro present. */
void WriteMacroSubRec( XclExpStream& rStrm );
/** Writes a subrecord containing a cell link, or nothing, if no link present. */
void WriteCellLinkSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId );
/** Writes the ftSbs sub structure containing scrollbar data. */
void WriteSbs( XclExpStream& rStrm );
private:
ScfInt16Vec maMultiSel; /// Indexes of all selected entries in a multi selection.
XclExpTokenArrayRef mxMacroLink; /// Token array containing a link to an attached macro.
sal_Int32 mnHeight; /// Height of the control.
sal_uInt16 mnState; /// Checked/unchecked state.
sal_Int16 mnLineCount; /// Combobox dropdown line count.
sal_Int16 mnSelEntry; /// Selected entry in combobox (1-based).
sal_Int16 mnScrollValue; /// Scrollbar: Current value.
sal_Int16 mnScrollMin; /// Scrollbar: Minimum value.
sal_Int16 mnScrollMax; /// Scrollbar: Maximum value.
sal_Int16 mnScrollStep; /// Scrollbar: Single step.
sal_Int16 mnScrollPage; /// Scrollbar: Page step.
bool mbFlatButton; /// False = 3D button style; True = Flat button style.
bool mbFlatBorder; /// False = 3D border style; True = Flat border style.
bool mbMultiSel; /// true = Multi selection in listbox.
bool mbScrollHor; /// Scrollbar: true = horizontal.
};
#endif
// ============================================================================
/** Represents a NOTE record containing the relevant data of a cell note.
NOTE records differ significantly in various BIFF versions. This class
encapsulates all needed actions for each supported BIFF version.
BIFF5/BIFF7: Stores the note text and generates a single or multiple NOTE
records on saving.
BIFF8: Creates the Escher object containing the drawing information and the
note text.
*/
class XclExpNote : public XclExpRecord
{
public:
/** Constructs a NOTE record from the passed note object and/or the text.
@descr The additional text will be separated from the note text with
an empty line.
@param rScPos The Calc cell address of the note.
@param pScNote The Calc note object. May be 0 to create a note from rAddText only.
@param rAddText Additional text appended to the note text. */
explicit XclExpNote(
const XclExpRoot& rRoot,
const ScAddress& rScPos,
const ScPostIt* pScNote,
const String& rAddText );
/** Writes the NOTE record, if the respective Escher object is present. */
virtual void Save( XclExpStream& rStrm );
private:
/** Writes the body of the NOTE record. */
virtual void WriteBody( XclExpStream& rStrm );
private:
XclExpString maAuthor; /// Name of the author.
ByteString maNoteText; /// Main text of the note (<=BIFF7).
ScAddress maScPos; /// Calc cell address of the note.
sal_uInt16 mnObjId; /// Escher object ID (BIFF8).
bool mbVisible; /// true = permanently visible.
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.192); FILE MERGED 2005/09/05 15:02:50 rt 1.5.192.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xeescher.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:27: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
*
************************************************************************/
#ifndef SC_XEESCHER_HXX
#define SC_XEESCHER_HXX
#ifndef SC_XLESCHER_HXX
#include "xlescher.hxx"
#endif
#include "xcl97rec.hxx"
namespace com { namespace sun { namespace star {
namespace script { struct ScriptEventDescriptor; }
} } }
// ============================================================================
class XclExpTokenArray;
/** Helper to manage controls linked to the sheet. */
class XclExpCtrlLinkHelper : protected XclExpRoot
{
public:
explicit XclExpCtrlLinkHelper( const XclExpRoot& rRoot );
virtual ~XclExpCtrlLinkHelper();
/** Sets the address of the control's linked cell. */
void SetCellLink( const ScAddress& rCellLink );
/** Sets the address of the control's linked source cell range. */
void SetSourceRange( const ScRange& rSrcRange );
protected:
/** Returns the Excel token array of the cell link, or 0, if no link present. */
inline const XclExpTokenArray* GetCellLinkTokArr() const { return mxCellLink.get(); }
/** Returns the Excel token array of the source range, or 0, if no link present. */
inline const XclExpTokenArray* GetSourceRangeTokArr() const { return mxSrcRange.get(); }
/** Returns the number of entries in the source range, or 0, if no source set. */
inline sal_uInt16 GetSourceEntryCount() const { return mnEntryCount; }
/** Writes a formula with special style only valid in OBJ records. */
void WriteFormula( XclExpStream& rStrm, const XclExpTokenArray& rTokArr ) const;
/** Writes a formula subrecord with special style only valid in OBJ records. */
void WriteFormulaSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId, const XclExpTokenArray& rTokArr ) const;
private:
XclExpTokenArrayRef mxCellLink; /// Formula for linked cell.
XclExpTokenArrayRef mxSrcRange; /// Formula for source data range.
sal_uInt16 mnEntryCount; /// Number of entries in source range.
};
// ----------------------------------------------------------------------------
#if EXC_EXP_OCX_CTRL
/** Represents an OBJ record for an OCX form control. */
class XclExpObjOcxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjOcxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel,
const String& rClassName,
sal_uInt32 nStrmStart, sal_uInt32 nStrmSize );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
private:
String maClassName; /// Class name of the control.
sal_uInt32 mnStrmStart; /// Start position in 'Ctls' stream.
sal_uInt32 mnStrmSize; /// Size in 'Ctls' stream.
};
#else
/** Represents an OBJ record for an TBX form control. */
class XclExpObjTbxCtrl : public XclObj, public XclExpCtrlLinkHelper
{
public:
explicit XclExpObjTbxCtrl(
const XclExpRoot& rRoot,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rxShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::awt::XControlModel >& rxCtrlModel );
/** Sets the name of a macro attached to this control.
@return true = The passed event descriptor was valid, macro name has been found. */
bool SetMacroLink( const ::com::sun::star::script::ScriptEventDescriptor& rEvent );
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
/** Writes an ftMacro subrecord containing a macro link, or nothing, if no macro present. */
void WriteMacroSubRec( XclExpStream& rStrm );
/** Writes a subrecord containing a cell link, or nothing, if no link present. */
void WriteCellLinkSubRec( XclExpStream& rStrm, sal_uInt16 nSubRecId );
/** Writes the ftSbs sub structure containing scrollbar data. */
void WriteSbs( XclExpStream& rStrm );
private:
ScfInt16Vec maMultiSel; /// Indexes of all selected entries in a multi selection.
XclExpTokenArrayRef mxMacroLink; /// Token array containing a link to an attached macro.
sal_Int32 mnHeight; /// Height of the control.
sal_uInt16 mnState; /// Checked/unchecked state.
sal_Int16 mnLineCount; /// Combobox dropdown line count.
sal_Int16 mnSelEntry; /// Selected entry in combobox (1-based).
sal_Int16 mnScrollValue; /// Scrollbar: Current value.
sal_Int16 mnScrollMin; /// Scrollbar: Minimum value.
sal_Int16 mnScrollMax; /// Scrollbar: Maximum value.
sal_Int16 mnScrollStep; /// Scrollbar: Single step.
sal_Int16 mnScrollPage; /// Scrollbar: Page step.
bool mbFlatButton; /// False = 3D button style; True = Flat button style.
bool mbFlatBorder; /// False = 3D border style; True = Flat border style.
bool mbMultiSel; /// true = Multi selection in listbox.
bool mbScrollHor; /// Scrollbar: true = horizontal.
};
#endif
// ============================================================================
/** Represents a NOTE record containing the relevant data of a cell note.
NOTE records differ significantly in various BIFF versions. This class
encapsulates all needed actions for each supported BIFF version.
BIFF5/BIFF7: Stores the note text and generates a single or multiple NOTE
records on saving.
BIFF8: Creates the Escher object containing the drawing information and the
note text.
*/
class XclExpNote : public XclExpRecord
{
public:
/** Constructs a NOTE record from the passed note object and/or the text.
@descr The additional text will be separated from the note text with
an empty line.
@param rScPos The Calc cell address of the note.
@param pScNote The Calc note object. May be 0 to create a note from rAddText only.
@param rAddText Additional text appended to the note text. */
explicit XclExpNote(
const XclExpRoot& rRoot,
const ScAddress& rScPos,
const ScPostIt* pScNote,
const String& rAddText );
/** Writes the NOTE record, if the respective Escher object is present. */
virtual void Save( XclExpStream& rStrm );
private:
/** Writes the body of the NOTE record. */
virtual void WriteBody( XclExpStream& rStrm );
private:
XclExpString maAuthor; /// Name of the author.
ByteString maNoteText; /// Main text of the note (<=BIFF7).
ScAddress maScPos; /// Calc cell address of the note.
sal_uInt16 mnObjId; /// Escher object ID (BIFF8).
bool mbVisible; /// true = permanently visible.
};
// ============================================================================
#endif
<|endoftext|> |
<commit_before>/*
BSD 3-Clause License
Copyright (c) 2019-2020, bitsofcotton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_P0_)
template <typename T> class P0 {
public:
typedef SimpleVector<T> Vec;
typedef SimpleVector<complex<T> > VecU;
typedef SimpleMatrix<T> Mat;
typedef SimpleMatrix<complex<T> > MatU;
inline P0();
inline P0(const int& range);
inline ~P0();
inline T next(const Vec& in);
const Mat& lpf(const int& size);
private:
Vec pred;
const MatU& seed(const int& size, const bool& idft);
const Mat& diff(const int& size);
const Vec& nextTaylor(const int& size, const int& step);
const T& Pi() const;
const complex<T>& J() const;
};
template <typename T> inline P0<T>::P0() {
;
}
template <typename T> inline P0<T>::P0(const int& range) {
assert(1 < range);
const auto look(1);
// with convolution meaning, exchange diff and integrate.
const auto& reverse(nextTaylor(range, - look));
pred.resize(reverse.size());
for(int i = 0; i < reverse.size(); i ++)
pred[i] = reverse[reverse.size() - 1 - i];
pred = lpf(range).transpose() * ((pred + nextTaylor(range, look)) / T(2));
}
template <typename T> inline P0<T>::~P0() {
;
}
template <typename T> inline T P0<T>::next(const Vec& in) {
assert(pred.size() == in.size());
return pred.dot(in);
}
template <typename T> const T& P0<T>::Pi() const {
const static auto pi(atan2(T(1), T(1)) * T(4));
return pi;
}
template <typename T> const complex<T>& P0<T>::J() const {
const static auto i(complex<T>(T(0), T(1)));
return i;
}
template <typename T> const typename P0<T>::MatU& P0<T>::seed(const int& size, const bool& f_idft) {
assert(0 < size);
static vector<MatU> dft;
static vector<MatU> idft;
if(dft.size() <= size)
dft.resize(size + 1, MatU());
if(idft.size() <= size)
idft.resize(size + 1, MatU());
if((!f_idft) && dft[size].rows() == size && dft[size].cols() == size)
return dft[size];
if( f_idft && idft[size].rows() == size && idft[size].cols() == size)
return idft[size];
auto& edft( dft[size]);
auto& eidft(idft[size]);
edft.resize(size, size);
eidft.resize(size, size);
for(int i = 0; i < edft.rows(); i ++)
for(int j = 0; j < edft.cols(); j ++) {
const auto theta(- T(2) * Pi() * T(i) * T(j) / T(edft.rows()));
edft(i, j) = complex<T>(cos( theta), sin( theta));
eidft(i, j) = complex<T>(cos(- theta), sin(- theta)) / complex<T>(T(size));
}
if(f_idft)
return eidft;
return edft;
}
template <typename T> const typename P0<T>::Mat& P0<T>::diff(const int& size) {
assert(0 < size);
static vector<Mat> D;
if(D.size() <= size)
D.resize(size + 1, Mat());
if(D[size].rows() == size && D[size].cols() == size)
return D[size];
auto& d(D[size]);
d.resize(size, size);
auto DD(seed(size, false));
DD.row(0) *= complex<T>(T(0));
T nd(0);
T ni(0);
for(int i = 1; i < DD.rows(); i ++) {
const auto phase(- J() * T(2) * Pi() * T(i) / T(DD.rows()));
const auto phase2(complex<T>(T(1)) / phase);
DD.row(i) *= phase;
nd += abs(phase) * abs(phase);
ni += abs(phase2) * abs(phase2);
}
return d = (seed(size, true) * DD).template real<T>() * sqrt(sqrt(T(DD.rows() - 1) / (nd * ni)));
}
template <typename T> const typename P0<T>::Mat& P0<T>::lpf(const int& size) {
assert(0 < size);
static vector<Mat> L;
if(L.size() <= size)
L.resize(size + 1, Mat());
if(L[size].rows() == size && L[size].cols() == size)
return L[size];
auto& l(L[size]);
auto ll(seed(size, false));
for(int i = size / 2; i < size; i ++)
ll.row(i) *= complex<T>(T(0));
return l = (seed(size, true) * ll).template real<T>();
}
template <typename T> const typename P0<T>::Vec& P0<T>::nextTaylor(const int& size, const int& step) {
assert(0 < size && (step == 1 || step == - 1));
static vector<Vec> P;
static vector<Vec> M;
if(P.size() <= size)
P.resize(size + 1, Vec());
if(M.size() <= size)
M.resize(size + 1, Vec());
if(0 < step && P[size].size() == size)
return P[size];
if(step < 0 && M[size].size() == size)
return M[size];
auto& p(P[size]);
auto& m(M[size]);
const auto& D(diff(size));
auto ddm(D);
auto ddp(D);
p.resize(size);
for(int i = 0; i < p.size(); i ++)
p[i] = T(0);
m = p;
p[p.size() - 1] = T(1);
m[0] = T(1);
for(int i = 2; 0 <= i; i ++) {
const auto bp(p);
const auto bm(m);
p += ddp.row(ddp.rows() - 1);
m += ddm.row(0);
if(bm == m && bp == p)
break;
ddp = (D * ddp) * ( T(1) / T(i));
ddm = (D * ddm) * (- T(1) / T(i));
}
if(0 < step)
return p;
return m;
}
#define _P0_
#endif
<commit_msg>fix last up.<commit_after>/*
BSD 3-Clause License
Copyright (c) 2019-2020, bitsofcotton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_P0_)
template <typename T> class P0 {
public:
typedef SimpleVector<T> Vec;
typedef SimpleVector<complex<T> > VecU;
typedef SimpleMatrix<T> Mat;
typedef SimpleMatrix<complex<T> > MatU;
inline P0();
inline P0(const int& range);
inline ~P0();
inline T next(const Vec& in);
const Mat& lpf(const int& size);
private:
Vec pred;
const MatU& seed(const int& size, const bool& idft);
const Mat& diff(const int& size);
const Vec& nextTaylor(const int& size, const int& step);
const T& Pi() const;
const complex<T>& J() const;
};
template <typename T> inline P0<T>::P0() {
;
}
template <typename T> inline P0<T>::P0(const int& range) {
assert(1 < range);
const auto look(1);
// with convolution meaning, exchange diff and integrate.
const auto& reverse(nextTaylor(range, - look));
pred.resize(reverse.size());
for(int i = 0; i < reverse.size(); i ++)
pred[i] = reverse[reverse.size() - 1 - i];
pred = lpf(range).transpose() * ((pred + nextTaylor(range, look)) / T(2));
}
template <typename T> inline P0<T>::~P0() {
;
}
template <typename T> inline T P0<T>::next(const Vec& in) {
assert(pred.size() == in.size());
return pred.dot(in);
}
template <typename T> const T& P0<T>::Pi() const {
const static auto pi(atan2(T(1), T(1)) * T(4));
return pi;
}
template <typename T> const complex<T>& P0<T>::J() const {
const static auto i(complex<T>(T(0), T(1)));
return i;
}
template <typename T> const typename P0<T>::MatU& P0<T>::seed(const int& size, const bool& f_idft) {
assert(0 < size);
static vector<MatU> dft;
static vector<MatU> idft;
if(dft.size() <= size)
dft.resize(size + 1, MatU());
if(idft.size() <= size)
idft.resize(size + 1, MatU());
if((!f_idft) && dft[size].rows() == size && dft[size].cols() == size)
return dft[size];
if( f_idft && idft[size].rows() == size && idft[size].cols() == size)
return idft[size];
auto& edft( dft[size]);
auto& eidft(idft[size]);
edft.resize(size, size);
eidft.resize(size, size);
for(int i = 0; i < edft.rows(); i ++)
for(int j = 0; j < edft.cols(); j ++) {
const auto theta(- T(2) * Pi() * T(i) * T(j) / T(edft.rows()));
edft(i, j) = complex<T>(cos( theta), sin( theta));
eidft(i, j) = complex<T>(cos(- theta), sin(- theta)) / complex<T>(T(size));
}
if(f_idft)
return eidft;
return edft;
}
template <typename T> const typename P0<T>::Mat& P0<T>::diff(const int& size) {
assert(0 < size);
static vector<Mat> D;
if(D.size() <= size)
D.resize(size + 1, Mat());
if(D[size].rows() == size && D[size].cols() == size)
return D[size];
auto& d(D[size]);
d.resize(size, size);
auto DD(seed(size, false));
DD.row(0) *= complex<T>(T(0));
T nd(0);
T ni(0);
for(int i = 1; i < DD.rows(); i ++) {
const auto phase(- J() * T(2) * Pi() * T(i) / T(DD.rows()));
const auto phase2(complex<T>(T(1)) / phase);
DD.row(i) *= phase;
nd += abs(phase) * abs(phase);
ni += abs(phase2) * abs(phase2);
}
return d = (seed(size, true) * DD).template real<T>() * sqrt(sqrt(T(DD.rows() - 1) / (nd * ni)));
}
template <typename T> const typename P0<T>::Mat& P0<T>::lpf(const int& size) {
assert(0 < size);
static vector<Mat> L;
if(L.size() <= size)
L.resize(size + 1, Mat());
if(L[size].rows() == size && L[size].cols() == size)
return L[size];
auto& l(L[size]);
auto ll(seed(size, false));
for(int i = size / 2; i < size; i ++)
ll.row(i) *= complex<T>(T(0));
return l = (seed(size, true) * ll).template real<T>();
}
template <typename T> const typename P0<T>::Vec& P0<T>::nextTaylor(const int& size, const int& step) {
assert(0 < size && (step == 1 || step == - 1));
static vector<Vec> P;
static vector<Vec> M;
if(P.size() <= size)
P.resize(size + 1, Vec());
if(M.size() <= size)
M.resize(size + 1, Vec());
if(0 < step && P[size].size() == size)
return P[size];
if(step < 0 && M[size].size() == size)
return M[size];
auto& p(P[size]);
auto& m(M[size]);
const auto& D(diff(size));
auto ddp( D);
auto ddm(- D);
p.resize(size);
for(int i = 0; i < p.size(); i ++)
p[i] = T(0);
m = p;
p[p.size() - 1] = T(1);
m[0] = T(1);
for(int i = 2; 0 <= i; i ++) {
const auto bp(p);
const auto bm(m);
p += ddp.row(ddp.rows() - 1);
m += ddm.row(0);
if(bm == m && bp == p)
break;
ddp = (D * ddp) * ( T(1) / T(i));
ddm = (D * ddm) * (- T(1) / T(i));
}
if(0 < step)
return p;
return m;
}
#define _P0_
#endif
<|endoftext|> |
<commit_before><commit_msg>sc: refactor ScDrawTextObjectBar::ExecuteAttr<commit_after><|endoftext|> |
<commit_before>int main()
{
//show message
return 0;
}
<commit_msg>Update ex1_1.cpp<commit_after>int main()
{
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: chart2uno.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:53:27 $
*
* 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 "chart2uno.hxx"
#include "miscuno.hxx"
#include "docsh.hxx"
#include "unoguard.hxx"
#include "cell.hxx"
#ifndef _COM_SUN_STAR_BEANS_UNKNOWNPROPERTYEXCEPTION_HDL_
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#endif
SC_SIMPLE_SERVICE_INFO( ScChart2DataProvider, "ScChart2DataProvider",
"com.sun.star.chart2.DataProvider")
SC_SIMPLE_SERVICE_INFO( ScChart2DataSource, "ScChart2DataSource",
"com.sun.star.chart2.DataSource")
SC_SIMPLE_SERVICE_INFO( ScChart2DataSequence, "ScChart2DataSequence",
"com.sun.star.chart2.DataSequence")
using namespace ::com::sun::star;
// DataProvider ==============================================================
ScChart2DataProvider::ScChart2DataProvider( ScDocShell* pDocSh)
: pDocShell( pDocSh)
{
if ( pDocShell )
pDocShell->GetDocument()->AddUnoObject( *this);
}
ScChart2DataProvider::~ScChart2DataProvider()
{
if ( pDocShell )
pDocShell->GetDocument()->RemoveUnoObject( *this);
}
void ScChart2DataProvider::Notify( SfxBroadcaster& rBC, const SfxHint& rHint)
{
if ( rHint.ISA( SfxSimpleHint ) &&
((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocShell = NULL;
}
}
uno::Reference< chart2::XDataSource> SAL_CALL
ScChart2DataProvider::getDataByRangeRepresentation(
const ::rtl::OUString& rRangeRepresentation)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: every call a new object?!? Or create hash of rRangeRepresentation?
if ( pDocShell )
{
ScUnoGuard aGuard;
ScRangeList aRangeList;
USHORT nValid = aRangeList.Parse( rRangeRepresentation,
pDocShell->GetDocument());
if ( (nValid & SCA_VALID) == SCA_VALID )
{
// FIXME: add glue mechanism similar to ScChartArray::GlueState(),
// for now this is a simple join
ScRangeListRef xRanges = new ScRangeList;
for ( ScRangePtr p = aRangeList.First(); p; p = aRangeList.Next())
{
xRanges->Join( *p );
}
return new ScChart2DataSource( pDocShell, xRanges);
}
throw lang::IllegalArgumentException();
}
throw uno::RuntimeException();
return 0;
}
uno::Reference< chart2::XDataSequence> SAL_CALL
ScChart2DataProvider::getDataSequenceByRangeIdentifier(
const ::rtl::OUString& rRangeIdentifier)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: find and return data sequence that matches rRangeIdentifier
throw uno::RuntimeException();
return 0;
}
uno::Reference< chart2::XDataSequence> SAL_CALL
ScChart2DataProvider::replaceRange(
const uno::Reference< chart2::XDataSequence>& rSeq)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
return 0;
}
void SAL_CALL ScChart2DataProvider::addDataChangeListener(
const uno::Reference< chart2::XDataChangeListener>& rListener,
const uno::Reference< chart2::XDataSource>& rData)
throw( uno::RuntimeException)
{
// FIXME: real implementation, reuse ScChartListener
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataProvider::removeDataChangeListener(
const uno::Reference< chart2::XDataChangeListener>& rListener,
const uno::Reference< chart2::XDataSource>& rData)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: real implementation, reuse ScChartListener
throw uno::RuntimeException();
}
// DataSource ================================================================
ScChart2DataSource::ScChart2DataSource( ScDocShell* pDocSh,
const ScRangeListRef& rRangeList)
: pDocShell( pDocSh)
, xRanges( rRangeList)
{
if ( pDocShell )
pDocShell->GetDocument()->AddUnoObject( *this);
}
ScChart2DataSource::~ScChart2DataSource()
{
if ( pDocShell )
pDocShell->GetDocument()->RemoveUnoObject( *this);
}
void ScChart2DataSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint)
{
if ( rHint.ISA( SfxSimpleHint ) &&
((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocShell = NULL;
}
}
uno::Sequence< uno::Reference< chart2::XDataSequence> > SAL_CALL
ScChart2DataSource::getDataSequences() throw ( uno::RuntimeException)
{
ScUnoGuard aGuard;
typedef ::std::vector< chart2::XDataSequence *> tVec;
tVec aVec;
// split into columns - FIXME: different if GlueState() is used
for ( ScRangePtr p = xRanges->First(); p; p = xRanges->Next())
{
for ( SCCOL nCol = p->aStart.Col(); nCol <= p->aEnd.Col(); ++nCol)
{
ScRangeListRef aColRanges = new ScRangeList;
// one single sheet selected assumed for now
aColRanges->Append( ScRange( nCol, p->aStart.Row(),
p->aStart.Tab(), nCol, p->aEnd.Row(),
p->aStart.Tab()));
// TODO: create pure Numerical and Text sequences if possible
aVec.push_back( new ScChart2DataSequence( pDocShell,
aColRanges));
}
}
uno::Sequence< uno::Reference< chart2::XDataSequence> > aSequences(
aVec.size());
uno::Reference< chart2::XDataSequence> * pArr = aSequences.getArray();
sal_Int32 j = 0;
for ( tVec::const_iterator iSeq = aVec.begin(); iSeq != aVec.end();
++iSeq, ++j)
{
pArr[j] = *iSeq;
}
return aSequences;
}
// DataSequence ==============================================================
ScChart2DataSequence::ScChart2DataSequence( ScDocShell* pDocSh,
const ScRangeListRef& rRangeList)
: bHidden( sal_False)
, xRanges( rRangeList)
, pDocShell( pDocSh)
{
if ( pDocShell )
pDocShell->GetDocument()->AddUnoObject( *this);
// FIXME: real implementation of identifier and it's mapping to ranges.
// Reuse ScChartListener?
aIdentifier = ::rtl::OUString::createFromAscii( "ScChart2DataSequence_dummy_ID_");
static sal_Int32 nID = 0;
aIdentifier += ::rtl::OUString::valueOf( ++nID);
}
ScChart2DataSequence::~ScChart2DataSequence()
{
if ( pDocShell )
pDocShell->GetDocument()->RemoveUnoObject( *this);
}
void ScChart2DataSequence::Notify( SfxBroadcaster& rBC, const SfxHint& rHint)
{
if ( rHint.ISA( SfxSimpleHint ) &&
((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocShell = NULL;
}
}
uno::Sequence< uno::Any> SAL_CALL ScChart2DataSequence::getData()
throw ( uno::RuntimeException)
{
if ( !pDocShell)
throw uno::RuntimeException();
ScUnoGuard aGuard;
const ScDocument* pDoc = pDocShell->GetDocument();
sal_Int32 nCount = 0;
ScRangePtr p;
for ( p = xRanges->First(); p; p = xRanges->Next())
{
nCount += sal_Int32(p->aEnd.Col() - p->aStart.Col() + 1) *
(p->aEnd.Row() - p->aStart.Row() + 1) * (p->aEnd.Tab() -
p->aStart.Tab() + 1);
}
uno::Sequence< uno::Any> aSeq( nCount);
uno::Any * pArr = aSeq.getArray();
nCount = 0;
for ( p = xRanges->First(); p; p = xRanges->Next())
{
// TODO: use DocIter?
ScAddress aAdr( p->aStart);
for ( SCTAB nTab = p->aStart.Tab(); nTab <= p->aEnd.Tab(); ++nTab)
{
aAdr.SetTab( nTab);
for ( SCCOL nCol = p->aStart.Col(); nCol <= p->aEnd.Col(); ++nCol)
{
aAdr.SetCol( nCol);
for ( SCROW nRow = p->aStart.Row(); nRow <= p->aEnd.Row();
++nRow)
{
aAdr.SetRow( nRow);
ScBaseCell* pCell = pDoc->GetCell( aAdr);
if ( pCell)
{
switch ( pCell->GetCellType())
{
case CELLTYPE_VALUE:
pArr[nCount] <<= static_cast< ScValueCell*>(
pCell)->GetValue();
break;
case CELLTYPE_FORMULA:
{
ScFormulaCell* pFCell = static_cast<
ScFormulaCell*>( pCell);
USHORT nErr = pFCell->GetErrCode();
if ( !nErr)
{
if ( pFCell->HasValueData())
pArr[nCount] <<= pFCell->GetValue();
else
{
String aStr;
pFCell->GetString( aStr);
pArr[nCount] <<= ::rtl::OUString(
aStr);
}
}
}
default:
{
if ( pCell->HasStringData())
pArr[nCount] <<= ::rtl::OUString(
pCell->GetStringData());
}
}
}
++nCount;
}
}
}
}
return aSeq;
}
::rtl::OUString SAL_CALL ScChart2DataSequence::getSourceIdentifier()
throw ( uno::RuntimeException)
{
return aIdentifier;
}
// DataSequence XPropertySet -------------------------------------------------
uno::Reference< beans::XPropertySetInfo> SAL_CALL
ScChart2DataSequence::getPropertySetInfo() throw( uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
return 0;
}
void SAL_CALL ScChart2DataSequence::setPropertyValue(
const ::rtl::OUString& rPropertyName, const uno::Any& rValue)
throw( beans::UnknownPropertyException,
beans::PropertyVetoException,
lang::IllegalArgumentException,
lang::WrappedTargetException, uno::RuntimeException)
{
if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Role")))
{
if ( !(rValue >>= aRole))
throw lang::IllegalArgumentException();
}
else if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Hidden")))
{
if ( !(rValue >>= bHidden))
throw lang::IllegalArgumentException();
}
else
throw beans::UnknownPropertyException();
// TODO: support optional properties
}
uno::Any SAL_CALL ScChart2DataSequence::getPropertyValue(
const ::rtl::OUString& rPropertyName)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
uno::Any aRet;
if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Role")))
aRet <<= aRole;
else if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Hidden")))
aRet <<= bHidden;
else
throw beans::UnknownPropertyException();
// TODO: support optional properties
return aRet;
}
void SAL_CALL ScChart2DataSequence::addPropertyChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XPropertyChangeListener>& xListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataSequence::removePropertyChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XPropertyChangeListener>& rListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataSequence::addVetoableChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XVetoableChangeListener>& rListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataSequence::removeVetoableChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XVetoableChangeListener>& rListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.450); FILE MERGED 2005/09/05 15:08:49 rt 1.3.450.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: chart2uno.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:43: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
*
************************************************************************/
#include "chart2uno.hxx"
#include "miscuno.hxx"
#include "docsh.hxx"
#include "unoguard.hxx"
#include "cell.hxx"
#ifndef _COM_SUN_STAR_BEANS_UNKNOWNPROPERTYEXCEPTION_HDL_
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#endif
SC_SIMPLE_SERVICE_INFO( ScChart2DataProvider, "ScChart2DataProvider",
"com.sun.star.chart2.DataProvider")
SC_SIMPLE_SERVICE_INFO( ScChart2DataSource, "ScChart2DataSource",
"com.sun.star.chart2.DataSource")
SC_SIMPLE_SERVICE_INFO( ScChart2DataSequence, "ScChart2DataSequence",
"com.sun.star.chart2.DataSequence")
using namespace ::com::sun::star;
// DataProvider ==============================================================
ScChart2DataProvider::ScChart2DataProvider( ScDocShell* pDocSh)
: pDocShell( pDocSh)
{
if ( pDocShell )
pDocShell->GetDocument()->AddUnoObject( *this);
}
ScChart2DataProvider::~ScChart2DataProvider()
{
if ( pDocShell )
pDocShell->GetDocument()->RemoveUnoObject( *this);
}
void ScChart2DataProvider::Notify( SfxBroadcaster& rBC, const SfxHint& rHint)
{
if ( rHint.ISA( SfxSimpleHint ) &&
((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocShell = NULL;
}
}
uno::Reference< chart2::XDataSource> SAL_CALL
ScChart2DataProvider::getDataByRangeRepresentation(
const ::rtl::OUString& rRangeRepresentation)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: every call a new object?!? Or create hash of rRangeRepresentation?
if ( pDocShell )
{
ScUnoGuard aGuard;
ScRangeList aRangeList;
USHORT nValid = aRangeList.Parse( rRangeRepresentation,
pDocShell->GetDocument());
if ( (nValid & SCA_VALID) == SCA_VALID )
{
// FIXME: add glue mechanism similar to ScChartArray::GlueState(),
// for now this is a simple join
ScRangeListRef xRanges = new ScRangeList;
for ( ScRangePtr p = aRangeList.First(); p; p = aRangeList.Next())
{
xRanges->Join( *p );
}
return new ScChart2DataSource( pDocShell, xRanges);
}
throw lang::IllegalArgumentException();
}
throw uno::RuntimeException();
return 0;
}
uno::Reference< chart2::XDataSequence> SAL_CALL
ScChart2DataProvider::getDataSequenceByRangeIdentifier(
const ::rtl::OUString& rRangeIdentifier)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: find and return data sequence that matches rRangeIdentifier
throw uno::RuntimeException();
return 0;
}
uno::Reference< chart2::XDataSequence> SAL_CALL
ScChart2DataProvider::replaceRange(
const uno::Reference< chart2::XDataSequence>& rSeq)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
return 0;
}
void SAL_CALL ScChart2DataProvider::addDataChangeListener(
const uno::Reference< chart2::XDataChangeListener>& rListener,
const uno::Reference< chart2::XDataSource>& rData)
throw( uno::RuntimeException)
{
// FIXME: real implementation, reuse ScChartListener
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataProvider::removeDataChangeListener(
const uno::Reference< chart2::XDataChangeListener>& rListener,
const uno::Reference< chart2::XDataSource>& rData)
throw( lang::IllegalArgumentException, uno::RuntimeException)
{
// FIXME: real implementation, reuse ScChartListener
throw uno::RuntimeException();
}
// DataSource ================================================================
ScChart2DataSource::ScChart2DataSource( ScDocShell* pDocSh,
const ScRangeListRef& rRangeList)
: pDocShell( pDocSh)
, xRanges( rRangeList)
{
if ( pDocShell )
pDocShell->GetDocument()->AddUnoObject( *this);
}
ScChart2DataSource::~ScChart2DataSource()
{
if ( pDocShell )
pDocShell->GetDocument()->RemoveUnoObject( *this);
}
void ScChart2DataSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint)
{
if ( rHint.ISA( SfxSimpleHint ) &&
((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocShell = NULL;
}
}
uno::Sequence< uno::Reference< chart2::XDataSequence> > SAL_CALL
ScChart2DataSource::getDataSequences() throw ( uno::RuntimeException)
{
ScUnoGuard aGuard;
typedef ::std::vector< chart2::XDataSequence *> tVec;
tVec aVec;
// split into columns - FIXME: different if GlueState() is used
for ( ScRangePtr p = xRanges->First(); p; p = xRanges->Next())
{
for ( SCCOL nCol = p->aStart.Col(); nCol <= p->aEnd.Col(); ++nCol)
{
ScRangeListRef aColRanges = new ScRangeList;
// one single sheet selected assumed for now
aColRanges->Append( ScRange( nCol, p->aStart.Row(),
p->aStart.Tab(), nCol, p->aEnd.Row(),
p->aStart.Tab()));
// TODO: create pure Numerical and Text sequences if possible
aVec.push_back( new ScChart2DataSequence( pDocShell,
aColRanges));
}
}
uno::Sequence< uno::Reference< chart2::XDataSequence> > aSequences(
aVec.size());
uno::Reference< chart2::XDataSequence> * pArr = aSequences.getArray();
sal_Int32 j = 0;
for ( tVec::const_iterator iSeq = aVec.begin(); iSeq != aVec.end();
++iSeq, ++j)
{
pArr[j] = *iSeq;
}
return aSequences;
}
// DataSequence ==============================================================
ScChart2DataSequence::ScChart2DataSequence( ScDocShell* pDocSh,
const ScRangeListRef& rRangeList)
: bHidden( sal_False)
, xRanges( rRangeList)
, pDocShell( pDocSh)
{
if ( pDocShell )
pDocShell->GetDocument()->AddUnoObject( *this);
// FIXME: real implementation of identifier and it's mapping to ranges.
// Reuse ScChartListener?
aIdentifier = ::rtl::OUString::createFromAscii( "ScChart2DataSequence_dummy_ID_");
static sal_Int32 nID = 0;
aIdentifier += ::rtl::OUString::valueOf( ++nID);
}
ScChart2DataSequence::~ScChart2DataSequence()
{
if ( pDocShell )
pDocShell->GetDocument()->RemoveUnoObject( *this);
}
void ScChart2DataSequence::Notify( SfxBroadcaster& rBC, const SfxHint& rHint)
{
if ( rHint.ISA( SfxSimpleHint ) &&
((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )
{
pDocShell = NULL;
}
}
uno::Sequence< uno::Any> SAL_CALL ScChart2DataSequence::getData()
throw ( uno::RuntimeException)
{
if ( !pDocShell)
throw uno::RuntimeException();
ScUnoGuard aGuard;
const ScDocument* pDoc = pDocShell->GetDocument();
sal_Int32 nCount = 0;
ScRangePtr p;
for ( p = xRanges->First(); p; p = xRanges->Next())
{
nCount += sal_Int32(p->aEnd.Col() - p->aStart.Col() + 1) *
(p->aEnd.Row() - p->aStart.Row() + 1) * (p->aEnd.Tab() -
p->aStart.Tab() + 1);
}
uno::Sequence< uno::Any> aSeq( nCount);
uno::Any * pArr = aSeq.getArray();
nCount = 0;
for ( p = xRanges->First(); p; p = xRanges->Next())
{
// TODO: use DocIter?
ScAddress aAdr( p->aStart);
for ( SCTAB nTab = p->aStart.Tab(); nTab <= p->aEnd.Tab(); ++nTab)
{
aAdr.SetTab( nTab);
for ( SCCOL nCol = p->aStart.Col(); nCol <= p->aEnd.Col(); ++nCol)
{
aAdr.SetCol( nCol);
for ( SCROW nRow = p->aStart.Row(); nRow <= p->aEnd.Row();
++nRow)
{
aAdr.SetRow( nRow);
ScBaseCell* pCell = pDoc->GetCell( aAdr);
if ( pCell)
{
switch ( pCell->GetCellType())
{
case CELLTYPE_VALUE:
pArr[nCount] <<= static_cast< ScValueCell*>(
pCell)->GetValue();
break;
case CELLTYPE_FORMULA:
{
ScFormulaCell* pFCell = static_cast<
ScFormulaCell*>( pCell);
USHORT nErr = pFCell->GetErrCode();
if ( !nErr)
{
if ( pFCell->HasValueData())
pArr[nCount] <<= pFCell->GetValue();
else
{
String aStr;
pFCell->GetString( aStr);
pArr[nCount] <<= ::rtl::OUString(
aStr);
}
}
}
default:
{
if ( pCell->HasStringData())
pArr[nCount] <<= ::rtl::OUString(
pCell->GetStringData());
}
}
}
++nCount;
}
}
}
}
return aSeq;
}
::rtl::OUString SAL_CALL ScChart2DataSequence::getSourceIdentifier()
throw ( uno::RuntimeException)
{
return aIdentifier;
}
// DataSequence XPropertySet -------------------------------------------------
uno::Reference< beans::XPropertySetInfo> SAL_CALL
ScChart2DataSequence::getPropertySetInfo() throw( uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
return 0;
}
void SAL_CALL ScChart2DataSequence::setPropertyValue(
const ::rtl::OUString& rPropertyName, const uno::Any& rValue)
throw( beans::UnknownPropertyException,
beans::PropertyVetoException,
lang::IllegalArgumentException,
lang::WrappedTargetException, uno::RuntimeException)
{
if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Role")))
{
if ( !(rValue >>= aRole))
throw lang::IllegalArgumentException();
}
else if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Hidden")))
{
if ( !(rValue >>= bHidden))
throw lang::IllegalArgumentException();
}
else
throw beans::UnknownPropertyException();
// TODO: support optional properties
}
uno::Any SAL_CALL ScChart2DataSequence::getPropertyValue(
const ::rtl::OUString& rPropertyName)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
uno::Any aRet;
if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Role")))
aRet <<= aRole;
else if ( rPropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Hidden")))
aRet <<= bHidden;
else
throw beans::UnknownPropertyException();
// TODO: support optional properties
return aRet;
}
void SAL_CALL ScChart2DataSequence::addPropertyChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XPropertyChangeListener>& xListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataSequence::removePropertyChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XPropertyChangeListener>& rListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataSequence::addVetoableChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XVetoableChangeListener>& rListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
void SAL_CALL ScChart2DataSequence::removeVetoableChangeListener(
const ::rtl::OUString& rPropertyName,
const uno::Reference< beans::XVetoableChangeListener>& rListener)
throw( beans::UnknownPropertyException,
lang::WrappedTargetException, uno::RuntimeException)
{
// FIXME: real implementation
throw uno::RuntimeException();
}
<|endoftext|> |
<commit_before>#include "HgTexture.h"
#include <glew.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <vector>
HgTexture::gpuUpdateTextureFunction HgTexture::updateTextureFunc;
AssetManager<HgTexture> HgTexture::imageMap;
HgTexture::TexturePtr HgTexture::acquire(const std::string& path, TextureType type) {
bool isNew = false;
auto ptr = imageMap.get(path, &isNew);
if (ptr == nullptr) {
fprintf(stderr, "Could not open image \"%s\"", path.c_str());
}
if (isNew) {
ptr->setType(type);
}
return std::move( ptr );
}
/*
void HgTexture::release(HgTexture* t) {
if (imageMap.isValid()) { //make sure map hasn't been destroyed (when program exiting)
imageMap.remove(t->m_path);
}
delete t;
}
*/
HgTexture::HgTexture()
{
data = nullptr;
gpuId = 0;
m_type = DIFFUSE;
m_uniqueId = 0;
}
HgTexture::~HgTexture()
{
if (gpuId > 0) glDeleteTextures(1,&gpuId); //FIXME abstract this
SAFE_FREE(data);
}
bool HgTexture::stb_load(FILE* f) {
int x, y, fileChannels;
// stbi_set_flip_vertically_on_load(1);
data = stbi_load_from_file(f, &x, &y, &fileChannels, 0);
m_properties.format = (HgTexture::format)fileChannels;
m_properties.width = x;
m_properties.height = y;
fclose(f);
return data != NULL;
}
struct DDS_PIXELFORMAT {
uint32_t size;
uint32_t flags;
uint32_t fourCC;
uint32_t RGBBitCount;
uint32_t RBitMask;
uint32_t GBitMask;
uint32_t BBitMask;
uint32_t ABitMask;
};
typedef struct {
uint32_t size;
uint32_t flags;
uint32_t height;
uint32_t width;
uint32_t pitchOrLinearSize;
uint32_t depth;
uint32_t mipMapCount;
uint32_t reserved[11];
DDS_PIXELFORMAT ddspf;
uint32_t caps;
uint32_t caps2;
uint32_t caps3;
uint32_t caps4;
uint32_t reserved2;
} DDS_HEADER;
typedef struct {
uint32_t dxgiFormat;
uint32_t resourceDimension;
uint32_t miscFlag;
uint32_t arraySize;
uint32_t miscFlags2;
} DDS_HEADER_DXT10;
#define DDPF_FOURCC 0x4
#define DX10 0x30315844
bool HgTexture::dds_load(FILE* f) {
DDS_HEADER header;
DDS_HEADER_DXT10 dx10Header;
fread(&header, 124, 1, f);
if (header.ddspf.flags == DDPF_FOURCC && header.ddspf.fourCC == DX10)
{
fread(&dx10Header, 20, 1, f);
}
Properties p;
p.height = header.height;
p.width = header.width;
p.mipMapCount = header.mipMapCount;
p.format = (HgTexture::format)header.ddspf.fourCC;
m_properties = p;
const auto linearSize = header.pitchOrLinearSize;
const uint32_t size = p.mipMapCount > 1 ? linearSize * 2 : linearSize;
data = (unsigned char*)malloc(size);
fread(data, 1, size, f);
fclose(f);
return true;
}
bool HgTexture::load(const std::string& path) {
bool r = load_internal(path);
if (r) {
setNeedsGPUUpdate(true);
}
return r;
}
bool HgTexture::load_internal(std::string path) {
std::hash<std::string> hashFunc;
m_uniqueId = hashFunc(path);
char filecode[4];
FILE *f = fopen(path.c_str(), "rb");
if (f == nullptr) {
fprintf(stderr, "Unable to open file \"%s\"", path.c_str());
return false;
}
m_path = std::move(path);
fread(filecode, 1, 4, f);
if (strncmp(filecode, "DDS ", 4) != 0) {
fseek(f, 0, SEEK_SET);
return stb_load(f);
}
return dds_load(f);
}
void HgTexture::sendToGPU()
{
// gpuId = updateTextureFunc(m_width, m_height, m_channels, data);
setNeedsGPUUpdate(false);
gpuId = updateTextureFunc(this);
SAFE_FREE(data);
}
<commit_msg>check for dds magic word first<commit_after>#include "HgTexture.h"
#include <glew.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <vector>
HgTexture::gpuUpdateTextureFunction HgTexture::updateTextureFunc;
AssetManager<HgTexture> HgTexture::imageMap;
HgTexture::TexturePtr HgTexture::acquire(const std::string& path, TextureType type) {
bool isNew = false;
auto ptr = imageMap.get(path, &isNew);
if (ptr == nullptr) {
fprintf(stderr, "Could not open image \"%s\"", path.c_str());
}
if (isNew) {
ptr->setType(type);
}
return std::move( ptr );
}
/*
void HgTexture::release(HgTexture* t) {
if (imageMap.isValid()) { //make sure map hasn't been destroyed (when program exiting)
imageMap.remove(t->m_path);
}
delete t;
}
*/
HgTexture::HgTexture()
{
data = nullptr;
gpuId = 0;
m_type = DIFFUSE;
m_uniqueId = 0;
}
HgTexture::~HgTexture()
{
if (gpuId > 0) glDeleteTextures(1,&gpuId); //FIXME abstract this
SAFE_FREE(data);
}
bool HgTexture::stb_load(FILE* f) {
int x, y, fileChannels;
// stbi_set_flip_vertically_on_load(1);
data = stbi_load_from_file(f, &x, &y, &fileChannels, 0);
m_properties.format = (HgTexture::format)fileChannels;
m_properties.width = x;
m_properties.height = y;
fclose(f);
return data != NULL;
}
struct DDS_PIXELFORMAT {
uint32_t size;
uint32_t flags;
uint32_t fourCC;
uint32_t RGBBitCount;
uint32_t RBitMask;
uint32_t GBitMask;
uint32_t BBitMask;
uint32_t ABitMask;
};
typedef struct {
uint32_t size;
uint32_t flags;
uint32_t height;
uint32_t width;
uint32_t pitchOrLinearSize;
uint32_t depth;
uint32_t mipMapCount;
uint32_t reserved[11];
DDS_PIXELFORMAT ddspf;
uint32_t caps;
uint32_t caps2;
uint32_t caps3;
uint32_t caps4;
uint32_t reserved2;
} DDS_HEADER;
typedef struct {
uint32_t dxgiFormat;
uint32_t resourceDimension;
uint32_t miscFlag;
uint32_t arraySize;
uint32_t miscFlags2;
} DDS_HEADER_DXT10;
#define DDPF_FOURCC 0x4
#define DX10 0x30315844
bool HgTexture::dds_load(FILE* f) {
DDS_HEADER header;
DDS_HEADER_DXT10 dx10Header;
fread(&header, 124, 1, f);
if (header.ddspf.flags == DDPF_FOURCC && header.ddspf.fourCC == DX10)
{
fread(&dx10Header, 20, 1, f);
}
Properties p;
p.height = header.height;
p.width = header.width;
p.mipMapCount = header.mipMapCount;
p.format = (HgTexture::format)header.ddspf.fourCC;
m_properties = p;
const auto linearSize = header.pitchOrLinearSize;
const uint32_t size = p.mipMapCount > 1 ? linearSize * 2 : linearSize;
data = (unsigned char*)malloc(size);
fread(data, 1, size, f);
fclose(f);
return true;
}
bool HgTexture::load(const std::string& path) {
bool r = load_internal(path);
if (r) {
setNeedsGPUUpdate(true);
}
return r;
}
bool HgTexture::load_internal(std::string path) {
std::hash<std::string> hashFunc;
m_uniqueId = hashFunc(path);
char filecode[4];
FILE *f = fopen(path.c_str(), "rb");
if (f == nullptr) {
fprintf(stderr, "Unable to open file \"%s\"", path.c_str());
return false;
}
m_path = std::move(path);
fread(filecode, 1, 4, f);
if (strncmp(filecode, "DDS ", 4) == 0)
{
return dds_load(f);
}
fseek(f, 0, SEEK_SET);
return stb_load(f);
}
void HgTexture::sendToGPU()
{
// gpuId = updateTextureFunc(m_width, m_height, m_channels, data);
setNeedsGPUUpdate(false);
gpuId = updateTextureFunc(this);
SAFE_FREE(data);
}
<|endoftext|> |
<commit_before>/* Copyright 2013 Roman Kurbatov
*
* 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.
*
* This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime
* project. See git revision history for detailed changes. */
#include "trikGuiApplication.h"
#include <QtGui/QKeyEvent>
#include <QtCore/QProcess>
#include <QtWidgets/QWidget>
#include "backgroundWidget.h"
using namespace trikGui;
TrikGuiApplication::TrikGuiApplication(int &argc, char **argv)
: QApplication(argc, argv)
{
connect(&mPowerButtonPressedTimer, &QTimer::timeout, this, &TrikGuiApplication::shutdownSoon);
connect(&mShutdownDelayTimer, &QTimer::timeout, this, &TrikGuiApplication::shutdown);
mPowerButtonPressedTimer.setSingleShot(true);
mShutdownDelayTimer.setSingleShot(true);
}
static bool isTrikPowerOffKey(Qt::Key key) {
return key == Qt::Key_PowerOff || ( key == Qt::Key_W && (QApplication::keyboardModifiers() & Qt::ControlModifier));
}
bool TrikGuiApplication::notify(QObject *receiver, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>(event);
if (isTrikPowerOffKey(static_cast<Qt::Key>(keyEvent->key()))) {
if (keyEvent->isAutoRepeat()) {
// if (!mPowerButtonPressedTimer.isActive()) {
// mPowerButtonPressedTimer.start(2000);
// }
} else {
if (!mPowerButtonPressedTimer.isActive()) {
mPowerButtonPressedTimer.start(2000);
}
mIsShutdownRequested = true;
refreshWidgets(); // refresh display if not auto-repeat
}
static QKeyEvent evntKeyPowerOff(QEvent::KeyPress, Qt::Key_PowerOff, Qt::NoModifier);
event = &evntKeyPowerOff;
}
} else if (event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>(event);
if (isTrikPowerOffKey(static_cast<Qt::Key>(keyEvent->key()))) {
if (!keyEvent->isAutoRepeat()) {
mIsShutdownRequested = false;
// if (mPowerButtonPressedTimer.isActive()) {
// mPowerButtonPressedTimer.stop();
// }
} else {
}
static QKeyEvent evntKeyPowerOff(QEvent::KeyRelease, Qt::Key_PowerOff, Qt::NoModifier);
event = &evntKeyPowerOff;
}
}
return QApplication::notify(receiver, event);
}
void TrikGuiApplication::refreshWidgets()
{
if (dynamic_cast<BackgroundWidget *>(QApplication::activeWindow())) {
for (const auto widget : QApplication::allWidgets()) {
widget->update();
}
}
}
void TrikGuiApplication::shutdown()
{
if(!mIsShutdownRequested) {
setStyleSheet(mSavedStyleSheet);
return;
}
QProcess::startDetached("/sbin/shutdown", {"-h", "-P", "now" });
QCoreApplication::quit();
}
void TrikGuiApplication::shutdownSoon()
{
if(mShutdownDelayTimer.isActive() || !mIsShutdownRequested) {
return;
}
mSavedStyleSheet = styleSheet();
setStyleSheet(mSavedStyleSheet + " QWidget { background-color:red; } ");
mShutdownDelayTimer.start(2000);
}
<commit_msg>Reduce delay before shutdown<commit_after>/* Copyright 2013 Roman Kurbatov
*
* 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.
*
* This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime
* project. See git revision history for detailed changes. */
#include "trikGuiApplication.h"
#include <QtGui/QKeyEvent>
#include <QtCore/QProcess>
#include <QtWidgets/QWidget>
#include "backgroundWidget.h"
using namespace trikGui;
TrikGuiApplication::TrikGuiApplication(int &argc, char **argv)
: QApplication(argc, argv)
{
connect(&mPowerButtonPressedTimer, &QTimer::timeout, this, &TrikGuiApplication::shutdownSoon);
connect(&mShutdownDelayTimer, &QTimer::timeout, this, &TrikGuiApplication::shutdown);
mPowerButtonPressedTimer.setSingleShot(true);
mShutdownDelayTimer.setSingleShot(true);
}
static bool isTrikPowerOffKey(Qt::Key key) {
return key == Qt::Key_PowerOff || ( key == Qt::Key_W && (QApplication::keyboardModifiers() & Qt::ControlModifier));
}
bool TrikGuiApplication::notify(QObject *receiver, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>(event);
if (isTrikPowerOffKey(static_cast<Qt::Key>(keyEvent->key()))) {
if (keyEvent->isAutoRepeat()) {
// if (!mPowerButtonPressedTimer.isActive()) {
// mPowerButtonPressedTimer.start(2000);
// }
} else {
if (!mPowerButtonPressedTimer.isActive()) {
mPowerButtonPressedTimer.start(1500);
}
mIsShutdownRequested = true;
refreshWidgets(); // refresh display if not auto-repeat
}
static QKeyEvent evntKeyPowerOff(QEvent::KeyPress, Qt::Key_PowerOff, Qt::NoModifier);
event = &evntKeyPowerOff;
}
} else if (event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>(event);
if (isTrikPowerOffKey(static_cast<Qt::Key>(keyEvent->key()))) {
if (!keyEvent->isAutoRepeat()) {
mIsShutdownRequested = false;
// if (mPowerButtonPressedTimer.isActive()) {
// mPowerButtonPressedTimer.stop();
// }
} else {
}
static QKeyEvent evntKeyPowerOff(QEvent::KeyRelease, Qt::Key_PowerOff, Qt::NoModifier);
event = &evntKeyPowerOff;
}
}
return QApplication::notify(receiver, event);
}
void TrikGuiApplication::refreshWidgets()
{
if (dynamic_cast<BackgroundWidget *>(QApplication::activeWindow())) {
for (const auto widget : QApplication::allWidgets()) {
widget->update();
}
}
}
void TrikGuiApplication::shutdown()
{
if(!mIsShutdownRequested) {
setStyleSheet(mSavedStyleSheet);
return;
}
QProcess::startDetached("/sbin/shutdown", {"-h", "-P", "now" });
QCoreApplication::quit();
}
void TrikGuiApplication::shutdownSoon()
{
if(mShutdownDelayTimer.isActive() || !mIsShutdownRequested) {
return;
}
mSavedStyleSheet = styleSheet();
setStyleSheet(mSavedStyleSheet + " QWidget { background-color:red; } ");
mShutdownDelayTimer.start(1500);
}
<|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 "chrome/browser/extensions/extension_resource_protocols.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_file_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_file_job.h"
namespace {
class ExtensionResourcesJob : public net::URLRequestFileJob {
public:
ExtensionResourcesJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: net::URLRequestFileJob(request, network_delegate, base::FilePath()),
thread_id_(content::BrowserThread::UI) {
}
virtual void Start() OVERRIDE;
protected:
virtual ~ExtensionResourcesJob() {}
void ResolvePath();
void ResolvePathDone();
private:
content::BrowserThread::ID thread_id_;
};
void ExtensionResourcesJob::Start() {
bool result =
content::BrowserThread::GetCurrentThreadIdentifier(&thread_id_);
CHECK(result) << "Can not get thread id.";
content::BrowserThread::PostTask(
content::BrowserThread::FILE, FROM_HERE,
base::Bind(&ExtensionResourcesJob::ResolvePath, this));
}
void ExtensionResourcesJob::ResolvePath() {
base::FilePath root_path;
PathService::Get(chrome::DIR_RESOURCES_EXTENSION, &root_path);
file_path_ = extension_file_util::ExtensionResourceURLToFilePath(
request()->url(), root_path);
content::BrowserThread::PostTask(
thread_id_, FROM_HERE,
base::Bind(&ExtensionResourcesJob::ResolvePathDone, this));
}
void ExtensionResourcesJob::ResolvePathDone() {
net::URLRequestFileJob::Start();
}
class ExtensionResourceProtocolHandler
: public net::URLRequestJobFactory::ProtocolHandler {
public:
ExtensionResourceProtocolHandler() {}
virtual ~ExtensionResourceProtocolHandler() {}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(ExtensionResourceProtocolHandler);
};
// Creates URLRequestJobs for chrome-extension-resource:// URLs.
net::URLRequestJob*
ExtensionResourceProtocolHandler::MaybeCreateJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
return new ExtensionResourcesJob(request, network_delegate);
}
} // namespace
net::URLRequestJobFactory::ProtocolHandler*
CreateExtensionResourceProtocolHandler() {
return new ExtensionResourceProtocolHandler();
}
<commit_msg>Fix a rare crash in ExtensionResourcesJob::ResolvePath.<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 "chrome/browser/extensions/extension_resource_protocols.h"
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/threading/thread_checker.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_file_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_file_job.h"
namespace {
base::FilePath ResolvePath(const GURL& url) {
base::FilePath root_path;
PathService::Get(chrome::DIR_RESOURCES_EXTENSION, &root_path);
return extension_file_util::ExtensionResourceURLToFilePath(url, root_path);
}
class ExtensionResourcesJob : public net::URLRequestFileJob {
public:
ExtensionResourcesJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: net::URLRequestFileJob(request, network_delegate, base::FilePath()),
weak_ptr_factory_(this) {
}
virtual void Start() OVERRIDE;
protected:
virtual ~ExtensionResourcesJob() {}
void ResolvePathDone(const base::FilePath& resolved_path);
private:
base::WeakPtrFactory<ExtensionResourcesJob> weak_ptr_factory_;
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(ExtensionResourcesJob);
};
void ExtensionResourcesJob::Start() {
DCHECK(thread_checker_.CalledOnValidThread());
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::FILE, FROM_HERE,
base::Bind(&ResolvePath, request()->url()),
base::Bind(&ExtensionResourcesJob::ResolvePathDone,
weak_ptr_factory_.GetWeakPtr()));
}
void ExtensionResourcesJob::ResolvePathDone(
const base::FilePath& resolved_path) {
DCHECK(thread_checker_.CalledOnValidThread());
file_path_ = resolved_path;
net::URLRequestFileJob::Start();
}
class ExtensionResourceProtocolHandler
: public net::URLRequestJobFactory::ProtocolHandler {
public:
ExtensionResourceProtocolHandler() {}
virtual ~ExtensionResourceProtocolHandler() {}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(ExtensionResourceProtocolHandler);
};
// Creates URLRequestJobs for chrome-extension-resource:// URLs.
net::URLRequestJob*
ExtensionResourceProtocolHandler::MaybeCreateJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
return new ExtensionResourcesJob(request, network_delegate);
}
} // namespace
net::URLRequestJobFactory::ProtocolHandler*
CreateExtensionResourceProtocolHandler() {
return new ExtensionResourceProtocolHandler();
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: app.cpp
// Purpose: Implementation of classes for syncodbcquery
// Author: Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
wxIMPLEMENT_APP(App);
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_ABOUT, Frame::OnCommand)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_EXIT, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppDisplayName())
, m_Running(false)
, m_Stopped(false)
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxExMenu* menuView = new wxExMenu();
menuView->AppendBars();
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Query = new wxExSTCWithFrame(this, this);
m_Query->SetLexer("sql");
m_Results = new wxExGrid(this);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
m_Shell->SetFocus();
#if wxUSE_STATUSBAR
std::vector<wxExStatusBarPane> panes;
panes.push_back(wxExStatusBarPane());
panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines")));
SetupStatusBar(panes);
#endif
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, &m_Query->GetFile());
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion(wxExGetVersionInfo().GetVersionOnlyString());
info.SetCopyright(wxExGetVersionInfo().GetCopyright());
info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->GetFile().FileNew(wxExFileName());
m_Query->SetLexer("sql");
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql) | *.sql",
true);
break;
case wxID_SAVE:
m_Query->GetFile().FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this,
&m_Query->GetFile(),
wxGetStockLabel(wxID_SAVEAS),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->GetFile().FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
if (m_otl.Logoff())
{
m_Shell->SetPrompt(">");
}
break;
case ID_DATABASE_OPEN:
if (m_otl.Logon(this))
{
m_Shell->SetPrompt(m_otl.Datasource() + ">");
}
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString input(event.GetString());
if (!input.empty())
{
const wxString query = input.substr(
0,
input.length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnCommandConfigDialog(
wxWindowID dialogid,
int commandid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
m_Shell->ConfigGet();
}
else
{
wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
int col_number,
long flags)
{
if (m_Query->Open(filename, line_number, match, col_number, flags))
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
SetRecentFile(filename.GetFullPath());
}
else
{
return false;
}
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
else
{
const auto rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (text.empty())
{
return;
}
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(long time, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%ld rows processed (%.3f seconds)"),
rpc,
(float)time / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), time);
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), time);
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>added missing commands to event table<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: app.cpp
// Purpose: Implementation of classes for syncodbcquery
// Author: Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
wxIMPLEMENT_APP(App);
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_ABOUT, Frame::OnCommand)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_EXIT, Frame::OnCommand)
EVT_MENU(wxID_NEW, Frame::OnCommand)
EVT_MENU(wxID_OPEN, Frame::OnCommand)
EVT_MENU(wxID_SAVE, Frame::OnCommand)
EVT_MENU(wxID_SAVEAS, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppDisplayName())
, m_Running(false)
, m_Stopped(false)
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxExMenu* menuView = new wxExMenu();
menuView->AppendBars();
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Query = new wxExSTCWithFrame(this, this);
m_Query->SetLexer("sql");
m_Results = new wxExGrid(this);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
m_Shell->SetFocus();
#if wxUSE_STATUSBAR
std::vector<wxExStatusBarPane> panes;
panes.push_back(wxExStatusBarPane());
panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines")));
SetupStatusBar(panes);
#endif
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, &m_Query->GetFile());
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion(wxExGetVersionInfo().GetVersionOnlyString());
info.SetCopyright(wxExGetVersionInfo().GetCopyright());
info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->GetFile().FileNew(wxExFileName());
m_Query->SetLexer("sql");
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql)|*.sql",
true);
break;
case wxID_SAVE:
m_Query->GetFile().FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this,
&m_Query->GetFile(),
wxGetStockLabel(wxID_SAVEAS),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->GetFile().FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
if (m_otl.Logoff())
{
m_Shell->SetPrompt(">");
}
break;
case ID_DATABASE_OPEN:
if (m_otl.Logon(this))
{
m_Shell->SetPrompt(m_otl.Datasource() + ">");
}
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString input(event.GetString());
if (!input.empty())
{
const wxString query = input.substr(
0,
input.length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnCommandConfigDialog(
wxWindowID dialogid,
int commandid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
m_Shell->ConfigGet();
}
else
{
wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
int col_number,
long flags)
{
if (m_Query->Open(filename, line_number, match, col_number, flags))
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
SetRecentFile(filename.GetFullPath());
}
else
{
return false;
}
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
else
{
const auto rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw.Time(), rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (text.empty())
{
return;
}
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(long time, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%ld rows processed (%.3f seconds)"),
rpc,
(float)time / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), time);
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), time);
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|endoftext|> |
<commit_before>#include "wasm-binary.h"
#include "wasm-s-parser.h"
using namespace std;
namespace {
string wast2wasm(string input, bool debug = false) {
wasm::Module wasm;
try {
if (debug) std::cerr << "s-parsing..." << std::endl;
wasm::SExpressionParser parser(const_cast<char*>(input.c_str()));
wasm::Element& root = *parser.root;
if (debug) std::cerr << "w-parsing..." << std::endl;
wasm::SExpressionWasmBuilder builder(wasm, *root[0]);
} catch (wasm::ParseException& p) {
p.dump(std::cerr);
wasm::Fatal() << "error in parsing input";
}
// FIXME: perhaps call validate() here?
if (debug) std::cerr << "binarification..." << std::endl;
wasm::BufferWithRandomAccess buffer(debug);
wasm::WasmBinaryWriter writer(&wasm, buffer, debug);
writer.write();
if (debug) std::cerr << "writing to output..." << std::endl;
ostringstream output;
buffer.writeTo(output);
if (debug) std::cerr << "Done." << std::endl;
return output.str();
}
}
int main(int argc, char **argv) {
cout << wast2wasm("(module (func $test (i64.const 1)))") << endl;
}
<commit_msg>Add C++ skeleton<commit_after>#include "wasm-binary.h"
#include "wasm-s-parser.h"
using namespace std;
namespace {
string wast2wasm(string input, bool debug = false) {
wasm::Module wasm;
try {
if (debug) std::cerr << "s-parsing..." << std::endl;
wasm::SExpressionParser parser(const_cast<char*>(input.c_str()));
wasm::Element& root = *parser.root;
if (debug) std::cerr << "w-parsing..." << std::endl;
wasm::SExpressionWasmBuilder builder(wasm, *root[0]);
} catch (wasm::ParseException& p) {
p.dump(std::cerr);
wasm::Fatal() << "error in parsing input";
}
// FIXME: perhaps call validate() here?
if (debug) std::cerr << "binarification..." << std::endl;
wasm::BufferWithRandomAccess buffer(debug);
wasm::WasmBinaryWriter writer(&wasm, buffer, debug);
writer.write();
if (debug) std::cerr << "writing to output..." << std::endl;
ostringstream output;
buffer.writeTo(output);
if (debug) std::cerr << "Done." << std::endl;
return output.str();
}
string evm2wast(string input) {
// FIXME: do evm magic here
}
string evm2wasm(string input) {
return wast2wasm(evm2wast(input));
}
}
int main(int argc, char **argv) {
cout << wast2wasm("(module (func $test (i64.const 1)))") << endl;
cout << evm2wast("600160020200") << endl;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Modified by ScyllaDB
*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cql3/user_types.hh"
#include "cql3/cql3_type.hh"
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/cxx11/any_of.hpp>
#include <boost/range/algorithm/count.hpp>
#include "types/user.hh"
namespace cql3 {
shared_ptr<column_specification> user_types::field_spec_of(shared_ptr<column_specification> column, size_t field) {
auto&& ut = static_pointer_cast<const user_type_impl>(column->type);
auto&& name = ut->field_name(field);
auto&& sname = sstring(reinterpret_cast<const char*>(name.data()), name.size());
return make_shared<column_specification>(
column->ks_name,
column->cf_name,
make_shared<column_identifier>(column->name->to_string() + "." + sname, true),
ut->field_type(field));
}
user_types::literal::literal(elements_map_type entries)
: _entries(std::move(entries)) {
}
shared_ptr<term> user_types::literal::prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
validate_assignable_to(db, keyspace, receiver);
auto&& ut = static_pointer_cast<const user_type_impl>(receiver->type);
bool all_terminal = true;
std::vector<shared_ptr<term>> values;
values.reserve(_entries.size());
size_t found_values = 0;
for (size_t i = 0; i < ut->size(); ++i) {
auto&& field = column_identifier(to_bytes(ut->field_name(i)), utf8_type);
auto iraw = _entries.find(field);
shared_ptr<term::raw> raw;
if (iraw == _entries.end()) {
raw = cql3::constants::NULL_LITERAL;
} else {
raw = iraw->second;
++found_values;
}
auto&& value = raw->prepare(db, keyspace, field_spec_of(receiver, i));
if (dynamic_cast<non_terminal*>(value.get())) {
all_terminal = false;
}
values.push_back(std::move(value));
}
if (found_values != _entries.size()) {
// We had some field that are not part of the type
for (auto&& id_val : _entries) {
auto&& id = id_val.first;
if (!boost::range::count(ut->field_names(), id.bytes_)) {
throw exceptions::invalid_request_exception(format("Unknown field '{}' in value of user defined type {}", id, ut->get_name_as_string()));
}
}
}
delayed_value value(ut, values);
if (all_terminal) {
return value.bind(query_options::DEFAULT);
} else {
return make_shared(std::move(value));
}
}
void user_types::literal::validate_assignable_to(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
auto&& ut = dynamic_pointer_cast<const user_type_impl>(receiver->type);
if (!ut) {
throw exceptions::invalid_request_exception(format("Invalid user type literal for {} of type {}", receiver->name, receiver->type->as_cql3_type()));
}
for (size_t i = 0; i < ut->size(); i++) {
column_identifier field(to_bytes(ut->field_name(i)), utf8_type);
if (_entries.count(field) == 0) {
continue;
}
shared_ptr<term::raw> value = _entries[field];
auto&& field_spec = field_spec_of(receiver, i);
if (!assignment_testable::is_assignable(value->test_assignment(db, keyspace, field_spec))) {
throw exceptions::invalid_request_exception(format("Invalid user type literal for {}: field {} is not of type {}", receiver->name, field, field_spec->type->as_cql3_type()));
}
}
}
assignment_testable::test_result user_types::literal::test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
try {
validate_assignable_to(db, keyspace, receiver);
return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
} catch (exceptions::invalid_request_exception& e) {
return assignment_testable::test_result::NOT_ASSIGNABLE;
}
}
sstring user_types::literal::assignment_testable_source_context() const {
return to_string();
}
sstring user_types::literal::to_string() const {
auto kv_to_str = [] (auto&& kv) { return format("{}:{}", kv.first, kv.second); };
return format("{{{}}}", ::join(", ", _entries | boost::adaptors::transformed(kv_to_str)));
}
user_types::delayed_value::delayed_value(user_type type, std::vector<shared_ptr<term>> values)
: _type(std::move(type)), _values(std::move(values)) {
}
bool user_types::delayed_value::uses_function(const sstring& ks_name, const sstring& function_name) const {
return boost::algorithm::any_of(_values,
std::bind(&term::uses_function, std::placeholders::_1, std::cref(ks_name), std::cref(function_name)));
}
bool user_types::delayed_value::contains_bind_marker() const {
return boost::algorithm::any_of(_values, std::mem_fn(&term::contains_bind_marker));
}
void user_types::delayed_value::collect_marker_specification(shared_ptr<variable_specifications> bound_names) {
for (auto&& v : _values) {
v->collect_marker_specification(bound_names);
}
}
std::vector<cql3::raw_value> user_types::delayed_value::bind_internal(const query_options& options) {
auto sf = options.get_cql_serialization_format();
std::vector<cql3::raw_value> buffers;
for (size_t i = 0; i < _type->size(); ++i) {
const auto& value = _values[i]->bind_and_get(options);
if (!_type->is_multi_cell() && value.is_unset_value()) {
throw exceptions::invalid_request_exception(format("Invalid unset value for field '{}' of user defined type {}", _type->field_name_as_string(i), _type->get_name_as_string()));
}
buffers.push_back(cql3::raw_value::make_value(value));
// Inside UDT values, we must force the serialization of collections to v3 whatever protocol
// version is in use since we're going to store directly that serialized value.
if (!sf.collection_format_unchanged() && _type->field_type(i)->is_collection() && buffers.back()) {
auto&& ctype = static_pointer_cast<const collection_type_impl>(_type->field_type(i));
buffers.back() = cql3::raw_value::make_value(
ctype->reserialize(sf, cql_serialization_format::latest(), bytes_view(*buffers.back())));
}
}
return buffers;
}
shared_ptr<terminal> user_types::delayed_value::bind(const query_options& options) {
return ::make_shared<constants::value>(cql3::raw_value::make_value((bind_and_get(options))));
}
cql3::raw_value_view user_types::delayed_value::bind_and_get(const query_options& options) {
return options.make_temporary(cql3::raw_value::make_value(user_type_impl::build_value(bind_internal(options))));
}
}
<commit_msg>cql3: remove a dynamic_pointer_cast to user_type_impl.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Modified by ScyllaDB
*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cql3/user_types.hh"
#include "cql3/cql3_type.hh"
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/cxx11/any_of.hpp>
#include <boost/range/algorithm/count.hpp>
#include "types/user.hh"
namespace cql3 {
shared_ptr<column_specification> user_types::field_spec_of(shared_ptr<column_specification> column, size_t field) {
auto&& ut = static_pointer_cast<const user_type_impl>(column->type);
auto&& name = ut->field_name(field);
auto&& sname = sstring(reinterpret_cast<const char*>(name.data()), name.size());
return make_shared<column_specification>(
column->ks_name,
column->cf_name,
make_shared<column_identifier>(column->name->to_string() + "." + sname, true),
ut->field_type(field));
}
user_types::literal::literal(elements_map_type entries)
: _entries(std::move(entries)) {
}
shared_ptr<term> user_types::literal::prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
validate_assignable_to(db, keyspace, receiver);
auto&& ut = static_pointer_cast<const user_type_impl>(receiver->type);
bool all_terminal = true;
std::vector<shared_ptr<term>> values;
values.reserve(_entries.size());
size_t found_values = 0;
for (size_t i = 0; i < ut->size(); ++i) {
auto&& field = column_identifier(to_bytes(ut->field_name(i)), utf8_type);
auto iraw = _entries.find(field);
shared_ptr<term::raw> raw;
if (iraw == _entries.end()) {
raw = cql3::constants::NULL_LITERAL;
} else {
raw = iraw->second;
++found_values;
}
auto&& value = raw->prepare(db, keyspace, field_spec_of(receiver, i));
if (dynamic_cast<non_terminal*>(value.get())) {
all_terminal = false;
}
values.push_back(std::move(value));
}
if (found_values != _entries.size()) {
// We had some field that are not part of the type
for (auto&& id_val : _entries) {
auto&& id = id_val.first;
if (!boost::range::count(ut->field_names(), id.bytes_)) {
throw exceptions::invalid_request_exception(format("Unknown field '{}' in value of user defined type {}", id, ut->get_name_as_string()));
}
}
}
delayed_value value(ut, values);
if (all_terminal) {
return value.bind(query_options::DEFAULT);
} else {
return make_shared(std::move(value));
}
}
void user_types::literal::validate_assignable_to(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
if (!receiver->type->is_user_type()) {
throw exceptions::invalid_request_exception(format("Invalid user type literal for {} of type {}", receiver->name, receiver->type->as_cql3_type()));
}
auto ut = static_pointer_cast<const user_type_impl>(receiver->type);
for (size_t i = 0; i < ut->size(); i++) {
column_identifier field(to_bytes(ut->field_name(i)), utf8_type);
if (_entries.count(field) == 0) {
continue;
}
shared_ptr<term::raw> value = _entries[field];
auto&& field_spec = field_spec_of(receiver, i);
if (!assignment_testable::is_assignable(value->test_assignment(db, keyspace, field_spec))) {
throw exceptions::invalid_request_exception(format("Invalid user type literal for {}: field {} is not of type {}", receiver->name, field, field_spec->type->as_cql3_type()));
}
}
}
assignment_testable::test_result user_types::literal::test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
try {
validate_assignable_to(db, keyspace, receiver);
return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
} catch (exceptions::invalid_request_exception& e) {
return assignment_testable::test_result::NOT_ASSIGNABLE;
}
}
sstring user_types::literal::assignment_testable_source_context() const {
return to_string();
}
sstring user_types::literal::to_string() const {
auto kv_to_str = [] (auto&& kv) { return format("{}:{}", kv.first, kv.second); };
return format("{{{}}}", ::join(", ", _entries | boost::adaptors::transformed(kv_to_str)));
}
user_types::delayed_value::delayed_value(user_type type, std::vector<shared_ptr<term>> values)
: _type(std::move(type)), _values(std::move(values)) {
}
bool user_types::delayed_value::uses_function(const sstring& ks_name, const sstring& function_name) const {
return boost::algorithm::any_of(_values,
std::bind(&term::uses_function, std::placeholders::_1, std::cref(ks_name), std::cref(function_name)));
}
bool user_types::delayed_value::contains_bind_marker() const {
return boost::algorithm::any_of(_values, std::mem_fn(&term::contains_bind_marker));
}
void user_types::delayed_value::collect_marker_specification(shared_ptr<variable_specifications> bound_names) {
for (auto&& v : _values) {
v->collect_marker_specification(bound_names);
}
}
std::vector<cql3::raw_value> user_types::delayed_value::bind_internal(const query_options& options) {
auto sf = options.get_cql_serialization_format();
std::vector<cql3::raw_value> buffers;
for (size_t i = 0; i < _type->size(); ++i) {
const auto& value = _values[i]->bind_and_get(options);
if (!_type->is_multi_cell() && value.is_unset_value()) {
throw exceptions::invalid_request_exception(format("Invalid unset value for field '{}' of user defined type {}", _type->field_name_as_string(i), _type->get_name_as_string()));
}
buffers.push_back(cql3::raw_value::make_value(value));
// Inside UDT values, we must force the serialization of collections to v3 whatever protocol
// version is in use since we're going to store directly that serialized value.
if (!sf.collection_format_unchanged() && _type->field_type(i)->is_collection() && buffers.back()) {
auto&& ctype = static_pointer_cast<const collection_type_impl>(_type->field_type(i));
buffers.back() = cql3::raw_value::make_value(
ctype->reserialize(sf, cql_serialization_format::latest(), bytes_view(*buffers.back())));
}
}
return buffers;
}
shared_ptr<terminal> user_types::delayed_value::bind(const query_options& options) {
return ::make_shared<constants::value>(cql3::raw_value::make_value((bind_and_get(options))));
}
cql3::raw_value_view user_types::delayed_value::bind_and_get(const query_options& options) {
return options.make_temporary(cql3::raw_value::make_value(user_type_impl::build_value(bind_internal(options))));
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// hash_join_test.cpp
//
// Identification: tests/executor/hash_join_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/hash_join_executor.h"
#include "backend/executor/hash_executor.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/executor/nested_loop_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/expression_util.h"
#include "backend/planner/hash_join_plan.h"
#include "backend/planner/hash_plan.h"
#include "backend/planner/merge_join_plan.h"
#include "backend/planner/nested_loop_join_plan.h"
#include "backend/storage/data_table.h"
#include "mock_executor.h"
#include "executor/executor_tests_util.h"
#include "executor/join_tests_util.h"
#include "harness.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
std::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() {
std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;
auto left = expression::TupleValueFactory(0, 1);
auto right = expression::TupleValueFactory(1, 1);
bool reversed = false;
join_clauses.emplace_back(left, right, reversed);
return join_clauses;
}
std::vector<PlanNodeType> join_algorithms = {
PLAN_NODE_TYPE_NESTLOOP,
PLAN_NODE_TYPE_MERGEJOIN,
PLAN_NODE_TYPE_HASHJOIN
};
std::vector<PelotonJoinType> join_types = {
JOIN_TYPE_INNER,
JOIN_TYPE_LEFT,
JOIN_TYPE_RIGHT,
JOIN_TYPE_OUTER
};
void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type);
oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile);
TEST(JoinTests, JoinPredicateTest) {
// Go over all join algorithms
for(auto join_algorithm : join_algorithms) {
std::cout << "JOIN ALGORITHM :: " << PlanNodeTypeToString(join_algorithm) << "\n";
// Go over all join types
for(auto join_type : join_types) {
std::cout << "JOIN TYPE :: " << join_type << "\n";
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type);
}
}
}
void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type) {
//===--------------------------------------------------------------------===//
// Mock table scan executors
//===--------------------------------------------------------------------===//
MockExecutor left_table_scan_executor, right_table_scan_executor;
// Create a table and wrap it in logical tile
size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
size_t left_table_tile_group_count = 3;
size_t right_table_tile_group_count = 2;
// Left table has 3 tile groups
std::unique_ptr<storage::DataTable> left_table(
ExecutorTestsUtil::CreateTable(tile_group_size));
ExecutorTestsUtil::PopulateTable(left_table.get(),
tile_group_size * left_table_tile_group_count,
false,
false, false);
//std::cout << (*left_table);
// Right table has 2 tile groups
std::unique_ptr<storage::DataTable> right_table(
ExecutorTestsUtil::CreateTable(tile_group_size));
ExecutorTestsUtil::PopulateTable(right_table.get(),
tile_group_size * right_table_tile_group_count,
false, false, false);
//std::cout << (*right_table);
// Wrap the input tables with logical tiles
std::unique_ptr<executor::LogicalTile> left_table_logical_tile1(
executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));
std::unique_ptr<executor::LogicalTile> left_table_logical_tile2(
executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));
std::unique_ptr<executor::LogicalTile> left_table_logical_tile3(
executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(2)));
std::unique_ptr<executor::LogicalTile> right_table_logical_tile1(
executor::LogicalTileFactory::WrapTileGroup(
right_table->GetTileGroup(0)));
std::unique_ptr<executor::LogicalTile> right_table_logical_tile2(
executor::LogicalTileFactory::WrapTileGroup(
right_table->GetTileGroup(1)));
// Left scan executor returns logical tiles from the left table
EXPECT_CALL(left_table_scan_executor, DInit())
.WillOnce(Return(true));
EXPECT_CALL(left_table_scan_executor, DExecute())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(left_table_scan_executor, GetOutput())
.WillOnce(Return(left_table_logical_tile1.release()))
.WillOnce(Return(left_table_logical_tile2.release()))
.WillOnce(Return(left_table_logical_tile3.release()));
// Right scan executor returns logical tiles from the right table
EXPECT_CALL(right_table_scan_executor, DInit())
.WillOnce(Return(true));
EXPECT_CALL(right_table_scan_executor, DExecute())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(right_table_scan_executor, GetOutput())
.WillOnce(Return(right_table_logical_tile1.release()))
.WillOnce(Return(right_table_logical_tile2.release()));
//===--------------------------------------------------------------------===//
// Setup join plan nodes and executors and run them
//===--------------------------------------------------------------------===//
oid_t result_tuple_count = 0;
oid_t tuples_with_null = 0;
auto projection = JoinTestsUtil::CreateProjection();
// Construct predicate
expression::AbstractExpression *predicate = JoinTestsUtil::CreateJoinPredicate();
// Differ based on join algorithm
switch(join_algorithm) {
case PLAN_NODE_TYPE_NESTLOOP: {
// Create nested loop join plan node.
planner::NestedLoopJoinPlan nested_loop_join_node(join_type, predicate, projection);
// Run the nested loop join executor
executor::NestedLoopJoinExecutor nested_loop_join_executor(&nested_loop_join_node, nullptr);
// Construct the executor tree
nested_loop_join_executor.AddChild(&left_table_scan_executor);
nested_loop_join_executor.AddChild(&right_table_scan_executor);
// Run the nested loop join executor
EXPECT_TRUE(nested_loop_join_executor.Init());
while(nested_loop_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(nested_loop_join_executor.GetOutput());
if(result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
}
}
}
break;
case PLAN_NODE_TYPE_MERGEJOIN: {
// Create join clauses
std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;
join_clauses = CreateJoinClauses();
// Create merge join plan node
planner::MergeJoinPlan merge_join_node(join_type, predicate, projection, join_clauses);
// Construct the merge join executor
executor::MergeJoinExecutor merge_join_executor(&merge_join_node, nullptr);
// Construct the executor tree
merge_join_executor.AddChild(&left_table_scan_executor);
merge_join_executor.AddChild(&right_table_scan_executor);
// Run the merge join executor
EXPECT_TRUE(merge_join_executor.Init());
while(merge_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(merge_join_executor.GetOutput());
if(result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
//std::cout << (*result_logical_tile);
}
}
}
break;
case PLAN_NODE_TYPE_HASHJOIN: {
// Create hash plan node
expression::AbstractExpression *right_table_attr_1 =
new expression::TupleValueExpression(1, 1);
std::vector<std::unique_ptr<const expression::AbstractExpression> > hash_keys;
hash_keys.emplace_back(right_table_attr_1);
// Create hash plan node
planner::HashPlan hash_plan_node(hash_keys);
// Construct the hash executor
executor::HashExecutor hash_executor(&hash_plan_node, nullptr);
// Create hash join plan node.
planner::HashJoinPlan hash_join_plan_node(join_type, predicate, projection);
// Construct the hash join executor
executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);
// Construct the executor tree
hash_join_executor.AddChild(&left_table_scan_executor);
hash_join_executor.AddChild(&hash_executor);
hash_executor.AddChild(&right_table_scan_executor);
// Run the hash_join_executor
EXPECT_TRUE(hash_join_executor.Init());
while(hash_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(hash_join_executor.GetOutput());
if(result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
//std::cout << (*result_logical_tile);
}
}
}
break;
default:
throw Exception("Unsupported join algorithm : " + std::to_string(join_algorithm));
break;
}
//===--------------------------------------------------------------------===//
// Execute test
//===--------------------------------------------------------------------===//
// Check output
switch(join_type) {
case JOIN_TYPE_INNER:
EXPECT_EQ(result_tuple_count, 2 * tile_group_size);
EXPECT_EQ(tuples_with_null, 0 * tile_group_size);
break;
case JOIN_TYPE_LEFT:
EXPECT_EQ(result_tuple_count, 3 * tile_group_size);
EXPECT_EQ(tuples_with_null, 1 * tile_group_size);
break;
case JOIN_TYPE_RIGHT:
EXPECT_EQ(result_tuple_count, 2 * tile_group_size);
EXPECT_EQ(tuples_with_null, 0 * tile_group_size);
break;
case JOIN_TYPE_OUTER:
EXPECT_EQ(result_tuple_count, 3 * tile_group_size);
EXPECT_EQ(tuples_with_null, 1 * tile_group_size);
break;
default:
throw Exception("Unsupported join type : " + std::to_string(join_type));
break;
}
}
oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile) {
assert(logical_tile);
// Get column count
auto column_count = logical_tile->GetColumnCount();
oid_t tuples_with_null = 0;
// Go over the tile
for (auto logical_tile_itr : *logical_tile) {
const expression::ContainerTuple<executor::LogicalTile> left_tuple(
logical_tile, logical_tile_itr);
// Go over all the fields and check for null values
for(oid_t col_itr = 0; col_itr < column_count; col_itr++) {
auto val = left_tuple.GetValue(col_itr);
if(val.IsNull()) {
tuples_with_null++;
break;
}
}
}
return tuples_with_null;
}
} // namespace test
} // namespace peloton
<commit_msg>Removed code<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// hash_join_test.cpp
//
// Identification: tests/executor/hash_join_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/hash_join_executor.h"
#include "backend/executor/hash_executor.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/executor/nested_loop_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/expression_util.h"
#include "backend/planner/hash_join_plan.h"
#include "backend/planner/hash_plan.h"
#include "backend/planner/merge_join_plan.h"
#include "backend/planner/nested_loop_join_plan.h"
#include "backend/storage/data_table.h"
#include "mock_executor.h"
#include "executor/executor_tests_util.h"
#include "executor/join_tests_util.h"
#include "harness.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
std::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() {
std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;
auto left = expression::TupleValueFactory(0, 1);
auto right = expression::TupleValueFactory(1, 1);
bool reversed = false;
join_clauses.emplace_back(left, right, reversed);
return join_clauses;
}
std::vector<PlanNodeType> join_algorithms = {
PLAN_NODE_TYPE_NESTLOOP,
PLAN_NODE_TYPE_MERGEJOIN
// TODO: Uncomment this to test hash join executor
// PLAN_NODE_TYPE_HASHJOIN
};
std::vector<PelotonJoinType> join_types = {
JOIN_TYPE_INNER,
JOIN_TYPE_LEFT,
JOIN_TYPE_RIGHT,
JOIN_TYPE_OUTER
};
void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type);
oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile);
TEST(JoinTests, JoinPredicateTest) {
// Go over all join algorithms
for(auto join_algorithm : join_algorithms) {
std::cout << "JOIN ALGORITHM :: " << PlanNodeTypeToString(join_algorithm) << "\n";
// Go over all join types
for(auto join_type : join_types) {
std::cout << "JOIN TYPE :: " << join_type << "\n";
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type);
}
}
}
void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type) {
//===--------------------------------------------------------------------===//
// Mock table scan executors
//===--------------------------------------------------------------------===//
MockExecutor left_table_scan_executor, right_table_scan_executor;
// Create a table and wrap it in logical tile
size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
size_t left_table_tile_group_count = 3;
size_t right_table_tile_group_count = 2;
// Left table has 3 tile groups
std::unique_ptr<storage::DataTable> left_table(
ExecutorTestsUtil::CreateTable(tile_group_size));
ExecutorTestsUtil::PopulateTable(left_table.get(),
tile_group_size * left_table_tile_group_count,
false,
false, false);
//std::cout << (*left_table);
// Right table has 2 tile groups
std::unique_ptr<storage::DataTable> right_table(
ExecutorTestsUtil::CreateTable(tile_group_size));
ExecutorTestsUtil::PopulateTable(right_table.get(),
tile_group_size * right_table_tile_group_count,
false, false, false);
//std::cout << (*right_table);
// Wrap the input tables with logical tiles
std::unique_ptr<executor::LogicalTile> left_table_logical_tile1(
executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));
std::unique_ptr<executor::LogicalTile> left_table_logical_tile2(
executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));
std::unique_ptr<executor::LogicalTile> left_table_logical_tile3(
executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(2)));
std::unique_ptr<executor::LogicalTile> right_table_logical_tile1(
executor::LogicalTileFactory::WrapTileGroup(
right_table->GetTileGroup(0)));
std::unique_ptr<executor::LogicalTile> right_table_logical_tile2(
executor::LogicalTileFactory::WrapTileGroup(
right_table->GetTileGroup(1)));
// Left scan executor returns logical tiles from the left table
EXPECT_CALL(left_table_scan_executor, DInit())
.WillOnce(Return(true));
EXPECT_CALL(left_table_scan_executor, DExecute())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(left_table_scan_executor, GetOutput())
.WillOnce(Return(left_table_logical_tile1.release()))
.WillOnce(Return(left_table_logical_tile2.release()))
.WillOnce(Return(left_table_logical_tile3.release()));
// Right scan executor returns logical tiles from the right table
EXPECT_CALL(right_table_scan_executor, DInit())
.WillOnce(Return(true));
EXPECT_CALL(right_table_scan_executor, DExecute())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(right_table_scan_executor, GetOutput())
.WillOnce(Return(right_table_logical_tile1.release()))
.WillOnce(Return(right_table_logical_tile2.release()));
//===--------------------------------------------------------------------===//
// Setup join plan nodes and executors and run them
//===--------------------------------------------------------------------===//
oid_t result_tuple_count = 0;
oid_t tuples_with_null = 0;
auto projection = JoinTestsUtil::CreateProjection();
// Construct predicate
expression::AbstractExpression *predicate = JoinTestsUtil::CreateJoinPredicate();
// Differ based on join algorithm
switch(join_algorithm) {
case PLAN_NODE_TYPE_NESTLOOP: {
// Create nested loop join plan node.
planner::NestedLoopJoinPlan nested_loop_join_node(join_type, predicate, projection);
// Run the nested loop join executor
executor::NestedLoopJoinExecutor nested_loop_join_executor(&nested_loop_join_node, nullptr);
// Construct the executor tree
nested_loop_join_executor.AddChild(&left_table_scan_executor);
nested_loop_join_executor.AddChild(&right_table_scan_executor);
// Run the nested loop join executor
EXPECT_TRUE(nested_loop_join_executor.Init());
while(nested_loop_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(nested_loop_join_executor.GetOutput());
if(result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
}
}
}
break;
case PLAN_NODE_TYPE_MERGEJOIN: {
// Create join clauses
std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;
join_clauses = CreateJoinClauses();
// Create merge join plan node
planner::MergeJoinPlan merge_join_node(join_type, predicate, projection, join_clauses);
// Construct the merge join executor
executor::MergeJoinExecutor merge_join_executor(&merge_join_node, nullptr);
// Construct the executor tree
merge_join_executor.AddChild(&left_table_scan_executor);
merge_join_executor.AddChild(&right_table_scan_executor);
// Run the merge join executor
EXPECT_TRUE(merge_join_executor.Init());
while(merge_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(merge_join_executor.GetOutput());
if(result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
//std::cout << (*result_logical_tile);
}
}
}
break;
case PLAN_NODE_TYPE_HASHJOIN: {
// Create hash plan node
expression::AbstractExpression *right_table_attr_1 =
new expression::TupleValueExpression(1, 1);
std::vector<std::unique_ptr<const expression::AbstractExpression> > hash_keys;
hash_keys.emplace_back(right_table_attr_1);
// Create hash plan node
planner::HashPlan hash_plan_node(hash_keys);
// Construct the hash executor
executor::HashExecutor hash_executor(&hash_plan_node, nullptr);
// Create hash join plan node.
planner::HashJoinPlan hash_join_plan_node(join_type, predicate, projection);
// Construct the hash join executor
executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);
// Construct the executor tree
hash_join_executor.AddChild(&left_table_scan_executor);
hash_join_executor.AddChild(&hash_executor);
hash_executor.AddChild(&right_table_scan_executor);
// Run the hash_join_executor
EXPECT_TRUE(hash_join_executor.Init());
while(hash_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(hash_join_executor.GetOutput());
if(result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
//std::cout << (*result_logical_tile);
}
}
}
break;
default:
throw Exception("Unsupported join algorithm : " + std::to_string(join_algorithm));
break;
}
//===--------------------------------------------------------------------===//
// Execute test
//===--------------------------------------------------------------------===//
// Check output
switch(join_type) {
case JOIN_TYPE_INNER:
EXPECT_EQ(result_tuple_count, 2 * tile_group_size);
EXPECT_EQ(tuples_with_null, 0 * tile_group_size);
break;
case JOIN_TYPE_LEFT:
EXPECT_EQ(result_tuple_count, 3 * tile_group_size);
EXPECT_EQ(tuples_with_null, 1 * tile_group_size);
break;
case JOIN_TYPE_RIGHT:
EXPECT_EQ(result_tuple_count, 2 * tile_group_size);
EXPECT_EQ(tuples_with_null, 0 * tile_group_size);
break;
case JOIN_TYPE_OUTER:
EXPECT_EQ(result_tuple_count, 3 * tile_group_size);
EXPECT_EQ(tuples_with_null, 1 * tile_group_size);
break;
default:
throw Exception("Unsupported join type : " + std::to_string(join_type));
break;
}
}
oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile) {
assert(logical_tile);
// Get column count
auto column_count = logical_tile->GetColumnCount();
oid_t tuples_with_null = 0;
// Go over the tile
for (auto logical_tile_itr : *logical_tile) {
const expression::ContainerTuple<executor::LogicalTile> left_tuple(
logical_tile, logical_tile_itr);
// Go over all the fields and check for null values
for(oid_t col_itr = 0; col_itr < column_count; col_itr++) {
auto val = left_tuple.GetValue(col_itr);
if(val.IsNull()) {
tuples_with_null++;
break;
}
}
}
return tuples_with_null;
}
} // namespace test
} // namespace peloton
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2012 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <libcbio/cbio.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <gtest/gtest.h>
using namespace std;
static const char dbfile[] = "testcase.couch";
class LibcbioTest : public ::testing::Test
{
protected:
LibcbioTest() {}
virtual ~LibcbioTest() {}
virtual void SetUp(void) {
removeDb();
}
virtual void TearDown(void) {
removeDb();
}
protected:
void removeDb(void) {
EXPECT_EQ(0, (remove(dbfile) == -1 && errno != ENOENT));
}
};
class LibcbioOpenTest : public LibcbioTest {};
TEST_F(LibcbioOpenTest, HandleEmptyNameOpenRDONLY)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("", CBIO_OPEN_RDONLY, &handle));
}
TEST_F(LibcbioOpenTest, HandleNullNameOpenRDONLY)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_EINVAL,
cbio_open_handle(NULL, CBIO_OPEN_RDONLY, &handle));
}
TEST_F(LibcbioOpenTest, HandleNonexistentNameOpenRDONLY)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("/this/path/should/not/exist",
CBIO_OPEN_RDONLY, &handle));
}
TEST_F(LibcbioOpenTest, HandleEmptyNameOpenRW)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("", CBIO_OPEN_RW, &handle));
}
TEST_F(LibcbioOpenTest, HandleNullNameOpenRW)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_EINVAL,
cbio_open_handle(NULL, CBIO_OPEN_RW, &handle));
}
TEST_F(LibcbioOpenTest, HandleNonexistentNameOpenRW)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("/this/path/should/not/exist",
CBIO_OPEN_RW, &handle));
}
TEST_F(LibcbioOpenTest, HandleEmptyNameOpenCREATE)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("", CBIO_OPEN_CREATE, &handle));
}
TEST_F(LibcbioOpenTest, HandleNullNameOpenCREATE)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_EINVAL,
cbio_open_handle(NULL, CBIO_OPEN_CREATE, &handle));
}
TEST_F(LibcbioOpenTest, HandleNonexistentNameOpenCREATE)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("/this/path/should/not/exist",
CBIO_OPEN_CREATE, &handle));
}
class LibcbioCreateDatabaseTest : public LibcbioTest {};
TEST_F(LibcbioCreateDatabaseTest, createDatabase)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
}
TEST_F(LibcbioCreateDatabaseTest, reopenDatabaseReadOnly)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_RDONLY, &handle));
cbio_close_handle(handle);
}
TEST_F(LibcbioCreateDatabaseTest, reopenDatabaseReadWrite)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_RW, &handle));
cbio_close_handle(handle);
}
TEST_F(LibcbioCreateDatabaseTest, reopenDatabaseCreate)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
}
class LibcbioDataAccessTest : public LibcbioTest
{
public:
LibcbioDataAccessTest() {
blob = new char[8192];
blobsize = 8192;
}
virtual ~LibcbioDataAccessTest() {
delete []blob;
}
virtual void SetUp(void) {
removeDb();
ASSERT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
}
virtual void TearDown(void) {
cbio_close_handle(handle);
removeDb();
}
protected:
void storeSingleDocument(const string &key, const string &value) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_create_empty_document(handle, &doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_id(doc, key.data(), key.length(), 0));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_value(doc, value.data(),
value.length(), 0));
EXPECT_EQ(CBIO_SUCCESS,
cbio_store_document(handle, doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_commit(handle));
cbio_document_release(doc);
}
void deleteSingleDocument(const string &key) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_create_empty_document(handle, &doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_id(doc, key.data(), key.length(), 0));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_deleted(doc, 1));
EXPECT_EQ(CBIO_SUCCESS,
cbio_store_document(handle, doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_commit(handle));
cbio_document_release(doc);
}
void validateExistingDocument(const string &key, const string &value) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_get_document(handle, key.data(), key.length(), &doc));
const void *ptr;
size_t nbytes;
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_get_value(doc, &ptr, &nbytes));
EXPECT_EQ(value.length(), nbytes);
EXPECT_EQ(0, memcmp(value.data(), ptr, nbytes));
}
void validateNonExistingDocument(const string &key) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_get_document(handle, key.data(), key.length(), &doc));
}
string generateKey(int id) {
stringstream ss;
ss << "mykey-" << id;
return ss.str();
}
libcbio_document_t generateRandomDocument(int id) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_create_empty_document(handle, &doc));
string key = generateKey(id);
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_id(doc, key.data(), key.length(), 1));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_value(doc, blob, random() % blobsize, 0));
return doc;
}
void bulkStoreDocuments(int maxdoc) {
const unsigned int chunksize = 1000;
libcbio_document_t *docs = new libcbio_document_t[chunksize];
int total = 0;
do {
unsigned int currtx = static_cast<unsigned int>(random()) % chunksize;
if (total + currtx > maxdoc) {
currtx = maxdoc - total;
}
for (int ii = 0; ii < currtx; ++ii) {
docs[ii] = generateRandomDocument(total + ii);
}
EXPECT_EQ(CBIO_SUCCESS, cbio_store_documents(handle, docs, currtx));
EXPECT_EQ(CBIO_SUCCESS, cbio_commit(handle));
total += currtx;
for (unsigned int ii = 0; ii < currtx; ++ii) {
cbio_document_release(docs[ii]);
}
} while (total < maxdoc);
for (int ii = 0; ii < maxdoc; ++ii) {
libcbio_document_t doc;
string key = generateKey(ii);
EXPECT_EQ(CBIO_SUCCESS,
cbio_get_document(handle, key.data(), key.length(), &doc));
cbio_document_release(doc);
}
}
char *blob;
size_t blobsize;
libcbio_t handle;
};
TEST_F(LibcbioDataAccessTest, getMiss)
{
validateNonExistingDocument("key");
}
TEST_F(LibcbioDataAccessTest, storeSingleDocument)
{
storeSingleDocument("key", "value");
}
TEST_F(LibcbioDataAccessTest, getHit)
{
storeSingleDocument("key", "value");
validateExistingDocument("key", "value");
}
TEST_F(LibcbioDataAccessTest, deleteNonExistingDocument)
{
string key = "key";
deleteSingleDocument(key);
validateNonExistingDocument(key);
}
TEST_F(LibcbioDataAccessTest, deleteExistingDocument)
{
string key = "key";
string value = "value";
storeSingleDocument(key, value);
validateExistingDocument(key, value);
deleteSingleDocument(key);
validateNonExistingDocument(key);
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_get_document_ex(handle, key.data(), key.length(), &doc));
int deleted;
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_get_deleted(doc, &deleted));
EXPECT_EQ(1, deleted);
cbio_document_release(doc);
}
TEST_F(LibcbioDataAccessTest, testBulkStoreDocuments)
{
bulkStoreDocuments(30000);
}
extern "C" {
static int count_callback(libcbio_t handle,
libcbio_document_t doc,
void *ctx)
{
(void)handle;
(void)doc;
int *count = static_cast<int *>(ctx);
(*count)++;
return 0;
}
}
TEST_F(LibcbioDataAccessTest, testChangesSinceDocuments)
{
uint64_t offset = (uint64_t)cbio_get_header_position(handle);
bulkStoreDocuments(5000);
int total = 0;
EXPECT_EQ(CBIO_SUCCESS,
cbio_changes_since(handle, offset, count_callback,
static_cast<void *>(&total)));
EXPECT_EQ(5000, total);
}
class LibcbioLocalDocumentTest : public LibcbioDataAccessTest
{
};
TEST_F(LibcbioLocalDocumentTest, testStoreLocalDocuments)
{
string key = "_local/hi-there";
string value = "{ foo:true }";
storeSingleDocument(key, value);
validateExistingDocument(key, value);
}
TEST_F(LibcbioLocalDocumentTest, testDeleteLocalDocuments)
{
string key = "_local/hi-there";
deleteSingleDocument(key);
}
TEST_F(LibcbioLocalDocumentTest, testChangesLocalDocuments)
{
uint64_t offset = (uint64_t)cbio_get_header_position(handle);
string key = "_local/hi-there";
string value = "{ foo:true }";
storeSingleDocument(key, value);
validateExistingDocument(key, value);
deleteSingleDocument(key);
validateNonExistingDocument(key);
int total = 0;
EXPECT_EQ(CBIO_SUCCESS,
cbio_changes_since(handle, offset, count_callback,
static_cast<void *>(&total)));
EXPECT_EQ(0, total);
storeSingleDocument("hi", "there");
EXPECT_EQ(CBIO_SUCCESS,
cbio_changes_since(handle, offset, count_callback,
static_cast<void *>(&total)));
EXPECT_EQ(1, total);
}
<commit_msg>Fix warnings reported by gcc about sign comparison<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2012 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <libcbio/cbio.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <gtest/gtest.h>
using namespace std;
static const char dbfile[] = "testcase.couch";
class LibcbioTest : public ::testing::Test
{
protected:
LibcbioTest() {}
virtual ~LibcbioTest() {}
virtual void SetUp(void) {
removeDb();
}
virtual void TearDown(void) {
removeDb();
}
protected:
void removeDb(void) {
EXPECT_EQ(0, (remove(dbfile) == -1 && errno != ENOENT));
}
};
class LibcbioOpenTest : public LibcbioTest {};
TEST_F(LibcbioOpenTest, HandleEmptyNameOpenRDONLY)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("", CBIO_OPEN_RDONLY, &handle));
}
TEST_F(LibcbioOpenTest, HandleNullNameOpenRDONLY)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_EINVAL,
cbio_open_handle(NULL, CBIO_OPEN_RDONLY, &handle));
}
TEST_F(LibcbioOpenTest, HandleNonexistentNameOpenRDONLY)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("/this/path/should/not/exist",
CBIO_OPEN_RDONLY, &handle));
}
TEST_F(LibcbioOpenTest, HandleEmptyNameOpenRW)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("", CBIO_OPEN_RW, &handle));
}
TEST_F(LibcbioOpenTest, HandleNullNameOpenRW)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_EINVAL,
cbio_open_handle(NULL, CBIO_OPEN_RW, &handle));
}
TEST_F(LibcbioOpenTest, HandleNonexistentNameOpenRW)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("/this/path/should/not/exist",
CBIO_OPEN_RW, &handle));
}
TEST_F(LibcbioOpenTest, HandleEmptyNameOpenCREATE)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("", CBIO_OPEN_CREATE, &handle));
}
TEST_F(LibcbioOpenTest, HandleNullNameOpenCREATE)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_EINVAL,
cbio_open_handle(NULL, CBIO_OPEN_CREATE, &handle));
}
TEST_F(LibcbioOpenTest, HandleNonexistentNameOpenCREATE)
{
libcbio_t handle;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_open_handle("/this/path/should/not/exist",
CBIO_OPEN_CREATE, &handle));
}
class LibcbioCreateDatabaseTest : public LibcbioTest {};
TEST_F(LibcbioCreateDatabaseTest, createDatabase)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
}
TEST_F(LibcbioCreateDatabaseTest, reopenDatabaseReadOnly)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_RDONLY, &handle));
cbio_close_handle(handle);
}
TEST_F(LibcbioCreateDatabaseTest, reopenDatabaseReadWrite)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_RW, &handle));
cbio_close_handle(handle);
}
TEST_F(LibcbioCreateDatabaseTest, reopenDatabaseCreate)
{
libcbio_t handle;
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
EXPECT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
cbio_close_handle(handle);
}
class LibcbioDataAccessTest : public LibcbioTest
{
public:
LibcbioDataAccessTest() {
blob = new char[8192];
blobsize = 8192;
}
virtual ~LibcbioDataAccessTest() {
delete []blob;
}
virtual void SetUp(void) {
removeDb();
ASSERT_EQ(CBIO_SUCCESS,
cbio_open_handle(dbfile, CBIO_OPEN_CREATE, &handle));
}
virtual void TearDown(void) {
cbio_close_handle(handle);
removeDb();
}
protected:
void storeSingleDocument(const string &key, const string &value) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_create_empty_document(handle, &doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_id(doc, key.data(), key.length(), 0));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_value(doc, value.data(),
value.length(), 0));
EXPECT_EQ(CBIO_SUCCESS,
cbio_store_document(handle, doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_commit(handle));
cbio_document_release(doc);
}
void deleteSingleDocument(const string &key) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_create_empty_document(handle, &doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_id(doc, key.data(), key.length(), 0));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_deleted(doc, 1));
EXPECT_EQ(CBIO_SUCCESS,
cbio_store_document(handle, doc));
EXPECT_EQ(CBIO_SUCCESS,
cbio_commit(handle));
cbio_document_release(doc);
}
void validateExistingDocument(const string &key, const string &value) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_get_document(handle, key.data(), key.length(), &doc));
const void *ptr;
size_t nbytes;
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_get_value(doc, &ptr, &nbytes));
EXPECT_EQ(value.length(), nbytes);
EXPECT_EQ(0, memcmp(value.data(), ptr, nbytes));
}
void validateNonExistingDocument(const string &key) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_ERROR_ENOENT,
cbio_get_document(handle, key.data(), key.length(), &doc));
}
string generateKey(int id) {
stringstream ss;
ss << "mykey-" << id;
return ss.str();
}
libcbio_document_t generateRandomDocument(int id) {
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_create_empty_document(handle, &doc));
string key = generateKey(id);
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_id(doc, key.data(), key.length(), 1));
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_set_value(doc, blob, random() % blobsize, 0));
return doc;
}
void bulkStoreDocuments(int maxdoc) {
const unsigned int chunksize = 1000;
libcbio_document_t *docs = new libcbio_document_t[chunksize];
int total = 0;
do {
unsigned int currtx = static_cast<unsigned int>(random()) % chunksize;
if (total + (int)currtx > maxdoc) {
currtx = maxdoc - total;
}
for (int ii = 0; ii < (int)currtx; ++ii) {
docs[ii] = generateRandomDocument(total + ii);
}
EXPECT_EQ(CBIO_SUCCESS, cbio_store_documents(handle, docs, currtx));
EXPECT_EQ(CBIO_SUCCESS, cbio_commit(handle));
total += currtx;
for (unsigned int ii = 0; ii < currtx; ++ii) {
cbio_document_release(docs[ii]);
}
} while (total < maxdoc);
for (int ii = 0; ii < maxdoc; ++ii) {
libcbio_document_t doc;
string key = generateKey(ii);
EXPECT_EQ(CBIO_SUCCESS,
cbio_get_document(handle, key.data(), key.length(), &doc));
cbio_document_release(doc);
}
}
char *blob;
size_t blobsize;
libcbio_t handle;
};
TEST_F(LibcbioDataAccessTest, getMiss)
{
validateNonExistingDocument("key");
}
TEST_F(LibcbioDataAccessTest, storeSingleDocument)
{
storeSingleDocument("key", "value");
}
TEST_F(LibcbioDataAccessTest, getHit)
{
storeSingleDocument("key", "value");
validateExistingDocument("key", "value");
}
TEST_F(LibcbioDataAccessTest, deleteNonExistingDocument)
{
string key = "key";
deleteSingleDocument(key);
validateNonExistingDocument(key);
}
TEST_F(LibcbioDataAccessTest, deleteExistingDocument)
{
string key = "key";
string value = "value";
storeSingleDocument(key, value);
validateExistingDocument(key, value);
deleteSingleDocument(key);
validateNonExistingDocument(key);
libcbio_document_t doc;
EXPECT_EQ(CBIO_SUCCESS,
cbio_get_document_ex(handle, key.data(), key.length(), &doc));
int deleted;
EXPECT_EQ(CBIO_SUCCESS,
cbio_document_get_deleted(doc, &deleted));
EXPECT_EQ(1, deleted);
cbio_document_release(doc);
}
TEST_F(LibcbioDataAccessTest, testBulkStoreDocuments)
{
bulkStoreDocuments(30000);
}
extern "C" {
static int count_callback(libcbio_t handle,
libcbio_document_t doc,
void *ctx)
{
(void)handle;
(void)doc;
int *count = static_cast<int *>(ctx);
(*count)++;
return 0;
}
}
TEST_F(LibcbioDataAccessTest, testChangesSinceDocuments)
{
uint64_t offset = (uint64_t)cbio_get_header_position(handle);
bulkStoreDocuments(5000);
int total = 0;
EXPECT_EQ(CBIO_SUCCESS,
cbio_changes_since(handle, offset, count_callback,
static_cast<void *>(&total)));
EXPECT_EQ(5000, total);
}
class LibcbioLocalDocumentTest : public LibcbioDataAccessTest
{
};
TEST_F(LibcbioLocalDocumentTest, testStoreLocalDocuments)
{
string key = "_local/hi-there";
string value = "{ foo:true }";
storeSingleDocument(key, value);
validateExistingDocument(key, value);
}
TEST_F(LibcbioLocalDocumentTest, testDeleteLocalDocuments)
{
string key = "_local/hi-there";
deleteSingleDocument(key);
}
TEST_F(LibcbioLocalDocumentTest, testChangesLocalDocuments)
{
uint64_t offset = (uint64_t)cbio_get_header_position(handle);
string key = "_local/hi-there";
string value = "{ foo:true }";
storeSingleDocument(key, value);
validateExistingDocument(key, value);
deleteSingleDocument(key);
validateNonExistingDocument(key);
int total = 0;
EXPECT_EQ(CBIO_SUCCESS,
cbio_changes_since(handle, offset, count_callback,
static_cast<void *>(&total)));
EXPECT_EQ(0, total);
storeSingleDocument("hi", "there");
EXPECT_EQ(CBIO_SUCCESS,
cbio_changes_since(handle, offset, count_callback,
static_cast<void *>(&total)));
EXPECT_EQ(1, total);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/bind.hh>
#include <libport/lexical-cast.hh>
#include <libport/test.hh>
#include <libport/unistd.h>
#include <libport/thread-pool.hh>
// For atomic increment
#include <boost/interprocess/detail/atomic.hpp>
using boost::interprocess::detail::atomic_inc32;
using boost::interprocess::detail::atomic_read32;
using libport::test_suite;
typedef libport::ThreadPool ThreadPool;
/* Determinism warning: Do not use rand outside main thread!
*/
volatile boost::uint32_t counter;
// Divisor for number of iterations
static boost::uint32_t dfactor = 1;
static void task_sleep_inc(int delay)
{
usleep(delay);
atomic_inc32(&counter);
}
// Just start a bunch of tasks and ensure they are all executed.
// In slowInject, inject slower to trigger the IDLE thread code more often.
static void test_many(bool slowInject)
{
ThreadPool tp(10);
counter = 0;
std::vector<ThreadPool::rTaskLock> v;
for(int i=0; i<10; ++i)
v.push_back(new ThreadPool::TaskLock);
// Start many tasks with random delay and lock
static const boost::uint32_t nTasks = 8000 / dfactor;
for (unsigned i=0; i<nTasks; ++i)
{
ThreadPool::rTaskLock lock;
long delay = rand() % 5000;
if (rand()%100 > 20)
lock = v[rand()%v.size()];
tp.queueTask(boost::bind(&task_sleep_inc, delay), lock);
usleep(rand()%(slowInject?5000:50));
}
// Give it 10s to finish, check regularly.
boost::uint32_t val;
for (int i=0; i<20; ++i)
{
val = atomic_read32(&counter);
if (val == nTasks)
break;
usleep(500000);
}
BOOST_CHECK_EQUAL(nTasks, val);
}
static void test_many_slow()
{
test_many(true);
}
static void test_many_fast()
{
test_many(false);
}
std::vector<unsigned> lockCheck;
boost::uint32_t errors = 0;
static void task_sleep_check_lock(int delay, unsigned lockid, unsigned lockval)
{
lockCheck[lockid] = lockval;
for (int i=0; i<10; ++i)
{
usleep(delay/10);
if (lockCheck[lockid] != lockval)
atomic_inc32(&errors);
lockCheck[lockid] = lockval;
}
atomic_inc32(&counter);
}
// Test that no two tasks with same lock are executed in parallel.
static void test_lock()
{
ThreadPool tp(10);
counter = 0;
std::vector<ThreadPool::rTaskLock> v;
for(int i=0; i<10; ++i)
v.push_back(new ThreadPool::TaskLock);
lockCheck.resize(v.size());
static const boost::uint32_t nTasks = 4000 / (dfactor * ((dfactor!=1)+1));
for (unsigned i=0; i<nTasks; ++i)
{
unsigned lockid = rand()%v.size();
long delay = rand() % 5000;
tp.queueTask(boost::bind(&task_sleep_check_lock, delay, lockid, i),
v[lockid]);
}
boost::uint32_t val;
for (int i=0; i<40; ++i)
{
val = atomic_read32(&counter);
if (val == nTasks)
break;
usleep(500000);
}
BOOST_CHECK_EQUAL(nTasks, val);
BOOST_CHECK_EQUAL(errors, 0);
}
test_suite*
init_test_suite()
{
unsigned int seed = time(0);
if (char * sseed = getenv("RAND_SEED"))
seed = boost::lexical_cast<unsigned int>(sseed);
test_suite* suite = BOOST_TEST_SUITE("libport::ThreadPool test suite");
BOOST_TEST_MESSAGE("Seed is " << seed);
if (running("Wine"))
dfactor = 10;
srand(seed);
suite->add(BOOST_TEST_CASE(test_many_slow));
suite->add(BOOST_TEST_CASE(test_many_fast));
suite->add(BOOST_TEST_CASE(test_lock));
return suite;
}
<commit_msg>test thread-pool: Silence a warning.<commit_after>/*
* Copyright (C) 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/bind.hh>
#include <libport/lexical-cast.hh>
#include <libport/test.hh>
#include <libport/unistd.h>
#include <libport/thread-pool.hh>
// For atomic increment
#include <boost/interprocess/detail/atomic.hpp>
using boost::interprocess::detail::atomic_inc32;
using boost::interprocess::detail::atomic_read32;
using libport::test_suite;
typedef libport::ThreadPool ThreadPool;
/* Determinism warning: Do not use rand outside main thread!
*/
volatile boost::uint32_t counter;
// Divisor for number of iterations
static boost::uint32_t dfactor = 1;
static void task_sleep_inc(int delay)
{
usleep(delay);
atomic_inc32(&counter);
}
// Just start a bunch of tasks and ensure they are all executed.
// In slowInject, inject slower to trigger the IDLE thread code more often.
static void test_many(bool slowInject)
{
ThreadPool tp(10);
counter = 0;
std::vector<ThreadPool::rTaskLock> v;
for(int i=0; i<10; ++i)
v.push_back(new ThreadPool::TaskLock);
// Start many tasks with random delay and lock
static const boost::uint32_t nTasks = 8000 / dfactor;
for (unsigned i=0; i<nTasks; ++i)
{
ThreadPool::rTaskLock lock;
long delay = rand() % 5000;
if (rand()%100 > 20)
lock = v[rand()%v.size()];
tp.queueTask(boost::bind(&task_sleep_inc, delay), lock);
usleep(rand()%(slowInject?5000:50));
}
// Give it 10s to finish, check regularly.
boost::uint32_t val;
for (int i=0; i<20; ++i)
{
val = atomic_read32(&counter);
if (val == nTasks)
break;
usleep(500000);
}
BOOST_CHECK_EQUAL(nTasks, val);
}
static void test_many_slow()
{
test_many(true);
}
static void test_many_fast()
{
test_many(false);
}
std::vector<unsigned> lockCheck;
boost::uint32_t errors = 0;
static void task_sleep_check_lock(int delay, unsigned lockid, unsigned lockval)
{
lockCheck[lockid] = lockval;
for (int i=0; i<10; ++i)
{
usleep(delay/10);
if (lockCheck[lockid] != lockval)
atomic_inc32(&errors);
lockCheck[lockid] = lockval;
}
atomic_inc32(&counter);
}
// Test that no two tasks with same lock are executed in parallel.
static void test_lock()
{
ThreadPool tp(10);
counter = 0;
std::vector<ThreadPool::rTaskLock> v;
for(int i=0; i<10; ++i)
v.push_back(new ThreadPool::TaskLock);
lockCheck.resize(v.size());
static const boost::uint32_t nTasks = 4000 / (dfactor * ((dfactor!=1)+1));
for (unsigned i=0; i<nTasks; ++i)
{
unsigned lockid = rand()%v.size();
long delay = rand() % 5000;
tp.queueTask(boost::bind(&task_sleep_check_lock, delay, lockid, i),
v[lockid]);
}
boost::uint32_t val;
for (int i=0; i<40; ++i)
{
val = atomic_read32(&counter);
if (val == nTasks)
break;
usleep(500000);
}
BOOST_CHECK_EQUAL(nTasks, val);
BOOST_CHECK_EQUAL(errors, 0U);
}
test_suite*
init_test_suite()
{
unsigned int seed = time(0);
if (char * sseed = getenv("RAND_SEED"))
seed = boost::lexical_cast<unsigned int>(sseed);
test_suite* suite = BOOST_TEST_SUITE("libport::ThreadPool test suite");
BOOST_TEST_MESSAGE("Seed is " << seed);
if (running("Wine"))
dfactor = 10;
srand(seed);
suite->add(BOOST_TEST_CASE(test_many_slow));
suite->add(BOOST_TEST_CASE(test_many_fast));
suite->add(BOOST_TEST_CASE(test_lock));
return suite;
}
<|endoftext|> |
<commit_before>#ifdef TREE_HPP
#include <cstddef>
#include <cstdlib>
int compare( const int left, const int right );
template < class T >
Tree< T >::Tree() {
this->root = nullptr;
}
template < class T >
Tree< T >::~Tree() {
destroy( &( this->root ) );
}
template < class T >
void Tree< T >::destroy( Node< T >** node ) {
if( *node != nullptr ) {
destroy( &( *node )->left );
destroy( &( *node )->right );
delete( *node );
node = nullptr;
}
return;
}
template < class T >
std::ostream& Tree< T >::display( std::ostream& out, Node< T >* const node ) const {
if( node != nullptr ) {
display( out, node->left );
out << node->getValue() << ' ';
display( out, node->right );
}
return out;
}
template < class T >
void Tree< T >::insert( const int& key, const T& value ) {
insert( &( this->root ), key, value );
}
template < class T >
void Tree< T >::insert( Node< T >** node, const int& key, const T& value ) {
if( *node == nullptr ) {
*node = new Node< T >( key, value, nullptr, nullptr );
return;
} else if( key < ( *node )->getKey() ) {
insert( &( ( *node )->left ), key, value );
} else if( key > ( *node )->getKey() ) {
insert( &( ( *node )->right ), key, value );
} else {
throw std::runtime_error( "Duplicate key" );
}
}
template < class T >
bool Tree< T >::searchByKey( const int& key ) const {
Node< T >* node = this->root;
while( node != nullptr && key != node->getKey() ) {
if( key < node->getKey() ) {
node = node->left;
} else {
node = node->right;
}
}
return node != nullptr;
}
template < class T >
int Tree< T >::searchByValue( const T& value ) const {
Node< T >* node = searchByValue( this->root, value );
if( node == nullptr ) {
throw std::runtime_error( "No search results found" );
}
return node->getKey();
}
template < class T >
Node< T >* Tree< T >::searchByValue( Node< T >* const node, const T& value ) const {
if( node == nullptr || value == node->getValue() ) {
return node;
}
Node< T >* left = searchByValue( node->left, value );
Node< T >* right = searchByValue( node->right, value );
if( left != nullptr && value == left->getValue() ) {
return left;
} else if( right != nullptr && value == right->getValue() ) {
return right;
} else {
return nullptr;
}
}
template < class T >
void Tree< T >::rotateLeft( Node< T >** root ) {
Node< T >* node = ( *root )->right;
( *root )->right = node->left;
node->left = *root;
*root->height = compare( *root->left->height, *root->right->height ) + 1;
node->height = compare( node->right->height, *root->height ) + 1;
*root = node;
}
template < class T >
void Tree< T >::rotateRight( Node< T >** root ) {
Node< T >* node = ( *root )->left;
( *root )->left = node->right;
node->right = *root;
*root->height = compare( *root->left->height, *root->right->height ) + 1;
node->height = compare( node->left->height, *root->height ) + 1;
*root = node;
}
template < class T >
void Tree< T >::doubleRotateLeft( Node< T >** root ) {
if( *root == nullptr ) {
return;
}
rotateRight( &( *root )->right );
rotateLeft( root );
}
template < class T >
void Tree< T >::doubleRotateRight( Node< T >** root ) {
if( *root == nullptr ) {
return;
}
rotateLeft( &( *root )->left );
rotateRight( root );
}
template < class T >
int Tree< T >::factor( Node< T >* node ) {
if( node->left != nullptr && node->right != nullptr ) {
return abs( node->left->height - node->right->height );
} else if( node->left != nullptr && node->right == nullptr ) {
return abs( node->left->height - 0 );
} else if( node->left == nullptr && node->right != nullptr ) {
return abs( 0 - node->right->height );
} else {
return 0;
}
}
int compare( const int left, const int right ) {
if( left > right ) {
return left;
} else {
return right;
}
}
#endif<commit_msg>Criada função para pegar altura do nó, corrigidas as funções de calcular fator de labanceamento, rotação a direita, rotação a esquerda e fazendo rotação durante a inserção<commit_after>#ifdef TREE_HPP
#include <cstddef>
#include <cstdlib>
int compare( const int left, const int right );
template < class T >
int heightNode( Node< T >* node );
template < class T >
Tree< T >::Tree() {
this->root = nullptr;
}
template < class T >
Tree< T >::~Tree() {
destroy( &( this->root ) );
}
template < class T >
void Tree< T >::destroy( Node< T >** node ) {
if( *node != nullptr ) {
destroy( &( *node )->left );
destroy( &( *node )->right );
delete( *node );
node = nullptr;
}
return;
}
template < class T >
std::ostream& Tree< T >::display( std::ostream& out, Node< T >* const node ) const {
if( node != nullptr ) {
display( out, node->left );
out << node->getValue() << ' ';
display( out, node->right );
}
return out;
}
template < class T >
void Tree< T >::insert( const int& key, const T& value ) {
insert( &( this->root ), key, value );
}
template < class T >
void Tree< T >::insert( Node< T >** node, const int& key, const T& value ) {
if( *node == nullptr ) {
*node = new Node< T >( key, value, nullptr, nullptr );
return;
} else if( key < ( *node )->getKey() ) {
insert( &( ( *node )->left ), key, value );
if( factor( *node ) >= 2 ) {
if( key < ( *node )->left->getKey() ) {
rotateRight( node );
} else {
doubleRotateRight( node );
}
}
} else if( key > ( *node )->getKey() ) {
insert( &( ( *node )->right ), key, value );
if( factor( *node ) >= 2 ) {
if( key > ( *node )->right->getKey() ) {
rotateLeft( node );
} else {
doubleRotateLeft( node );
}
}
} else {
throw std::runtime_error( "Duplicate key" );
}
( *node )->height =
compare( heightNode( ( *node )->left ), heightNode( ( *node )->right ) ) + 1;
}
template < class T >
bool Tree< T >::searchByKey( const int& key ) const {
Node< T >* node = this->root;
while( node != nullptr && key != node->getKey() ) {
if( key < node->getKey() ) {
node = node->left;
} else {
node = node->right;
}
}
return node != nullptr;
}
template < class T >
int Tree< T >::searchByValue( const T& value ) const {
Node< T >* node = searchByValue( this->root, value );
if( node == nullptr ) {
throw std::runtime_error( "No search results found" );
}
return node->getKey();
}
template < class T >
Node< T >* Tree< T >::searchByValue( Node< T >* const node, const T& value ) const {
if( node == nullptr || value == node->getValue() ) {
return node;
}
Node< T >* left = searchByValue( node->left, value );
Node< T >* right = searchByValue( node->right, value );
if( left != nullptr && value == left->getValue() ) {
return left;
} else if( right != nullptr && value == right->getValue() ) {
return right;
} else {
return nullptr;
}
}
template < class T >
void Tree< T >::rotateLeft( Node< T >** root ) {
Node< T >* node = ( *root )->right;
( *root )->right = node->left;
node->left = *root;
( *root )->height =
compare( heightNode( ( *root )->left ), heightNode( ( *root )->right ) ) + 1;
node->height = compare( heightNode( node->right ), ( *root )->height ) + 1;
*root = node;
}
template < class T >
void Tree< T >::rotateRight( Node< T >** root ) {
Node< T >* node = ( *root )->left;
( *root )->left = node->right;
node->right = *root;
( *root )->height =
compare( heightNode( ( *root )->left ), heightNode( ( *root )->right ) ) + 1;
node->height = compare( heightNode( node->left ), ( *root )->height ) + 1;
*root = node;
}
template < class T >
void Tree< T >::doubleRotateLeft( Node< T >** root ) {
if( *root == nullptr ) {
return;
}
rotateRight( &( *root )->right );
rotateLeft( root );
}
template < class T >
void Tree< T >::doubleRotateRight( Node< T >** root ) {
if( *root == nullptr ) {
return;
}
rotateLeft( &( *root )->left );
rotateRight( root );
}
template < class T >
int Tree< T >::factor( Node< T >* node ) {
return abs( heightNode( node->left ) - heightNode( node->right ) );
}
int compare( const int left, const int right ) {
if( left > right ) {
return left;
} else {
return right;
}
}
template < class T >
int heightNode( Node< T >* node ) {
if( node == nullptr ) {
return -1;
} else {
return node->height;
}
}
#endif<|endoftext|> |
<commit_before>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#include "hadesmem/pelib/section_list.hpp"
#include <sstream>
#include <utility>
#define BOOST_TEST_MODULE section_list
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/test/unit_test.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/read.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/config.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/module_list.hpp"
#include "hadesmem/pelib/pe_file.hpp"
#include "hadesmem/pelib/section.hpp"
#include "hadesmem/pelib/nt_headers.hpp"
// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// Boost.Test causes the following warning under Clang:
// error: declaration requires a global constructor
// [-Werror,-Wglobal-constructors]
#if defined(HADESMEM_CLANG)
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif // #if defined(HADESMEM_CLANG)
BOOST_AUTO_TEST_CASE(section_list)
{
hadesmem::Process const process(::GetCurrentProcessId());
hadesmem::PeFile pe_file_1(process, GetModuleHandle(nullptr),
hadesmem::PeFileType::Image);
hadesmem::NtHeaders nt_headers_1(process, pe_file_1);
BOOST_CHECK(nt_headers_1.GetNumberOfSections() >= 1);
hadesmem::Section section_1(process, pe_file_1, 0);
hadesmem::Section section_2(section_1);
BOOST_CHECK_EQUAL(section_1, section_2);
section_1 = section_2;
BOOST_CHECK_EQUAL(section_1, section_2);
hadesmem::Section section_3(std::move(section_2));
BOOST_CHECK_EQUAL(section_3, section_1);
section_2 = std::move(section_3);
BOOST_CHECK_EQUAL(section_1, section_2);
hadesmem::ModuleList modules(process);
for (auto const& mod : modules)
{
// TODO: Also test FileType_Data
hadesmem::PeFile const pe_file(process, mod.GetHandle(),
hadesmem::PeFileType::Data);
hadesmem::NtHeaders const nt_headers(process, pe_file);
WORD const num_sections = nt_headers.GetNumberOfSections();
// Assume every module has at least one section.
// TODO: Better tests.
hadesmem::SectionList sections(process, pe_file);
WORD section_count = 0;
for (auto const& section : sections)
{
section_count += 1;
auto const section_header_raw = hadesmem::Read<IMAGE_SECTION_HEADER>(
process, section.GetBase());
section.SetName(section.GetName());
section.SetVirtualAddress(section.GetVirtualAddress());
section.SetVirtualSize(section.GetVirtualSize());
section.SetSizeOfRawData(section.GetSizeOfRawData());
section.SetPointerToRawData(section.GetPointerToRawData());
section.SetPointerToRelocations(section.GetPointerToRelocations());
section.SetPointerToLinenumbers(section.GetPointerToLinenumbers());
section.SetNumberOfRelocations(section.GetNumberOfRelocations());
section.SetNumberOfLinenumbers(section.GetNumberOfLinenumbers());
section.SetCharacteristics(section.GetCharacteristics());
auto const section_header_raw_new = hadesmem::Read<IMAGE_SECTION_HEADER>(
process, section.GetBase());
BOOST_CHECK_EQUAL(std::memcmp(§ion_header_raw,
§ion_header_raw_new, sizeof(section_header_raw)), 0);
std::stringstream test_str_1;
test_str_1.imbue(std::locale::classic());
test_str_1 << section;
std::stringstream test_str_2;
test_str_2.imbue(std::locale::classic());
test_str_2 << section.GetBase();
BOOST_CHECK_EQUAL(test_str_1.str(), test_str_2.str());
if (mod.GetHandle() != GetModuleHandle(L"ntdll"))
{
hadesmem::PeFile const pe_file_ntdll(process,
GetModuleHandle(L"ntdll"), hadesmem::PeFileType::Image);
hadesmem::Section const section_ntdll(process, pe_file_ntdll, 0);
std::stringstream test_str_3;
test_str_3.imbue(std::locale::classic());
test_str_3 << section_ntdll.GetBase();
BOOST_CHECK_NE(test_str_1.str(), test_str_3.str());
}
}
BOOST_CHECK(section_count == num_sections);
// Assume every module has a '.text' section.
// TODO: Better tests.
auto text_iter = std::find_if(std::begin(sections), std::end(sections),
[] (hadesmem::Section const& section)
{
return section.GetName() == ".text";
});
BOOST_CHECK(text_iter != std::end(sections));
}
}
<commit_msg>* Change test to one that would've caught the previous SectionList bug.<commit_after>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#include "hadesmem/pelib/section_list.hpp"
#include <sstream>
#include <utility>
#define BOOST_TEST_MODULE section_list
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/test/unit_test.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/read.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/config.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/module_list.hpp"
#include "hadesmem/pelib/pe_file.hpp"
#include "hadesmem/pelib/section.hpp"
#include "hadesmem/pelib/nt_headers.hpp"
// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// Boost.Test causes the following warning under Clang:
// error: declaration requires a global constructor
// [-Werror,-Wglobal-constructors]
#if defined(HADESMEM_CLANG)
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif // #if defined(HADESMEM_CLANG)
BOOST_AUTO_TEST_CASE(section_list)
{
hadesmem::Process const process(::GetCurrentProcessId());
hadesmem::PeFile pe_file_1(process, GetModuleHandle(nullptr),
hadesmem::PeFileType::Image);
hadesmem::NtHeaders nt_headers_1(process, pe_file_1);
BOOST_CHECK(nt_headers_1.GetNumberOfSections() >= 1);
hadesmem::Section section_1(process, pe_file_1, 0);
hadesmem::Section section_2(section_1);
BOOST_CHECK_EQUAL(section_1, section_2);
section_1 = section_2;
BOOST_CHECK_EQUAL(section_1, section_2);
hadesmem::Section section_3(std::move(section_2));
BOOST_CHECK_EQUAL(section_3, section_1);
section_2 = std::move(section_3);
BOOST_CHECK_EQUAL(section_1, section_2);
hadesmem::ModuleList modules(process);
for (auto const& mod : modules)
{
// TODO: Also test FileType_Data
hadesmem::PeFile const pe_file(process, mod.GetHandle(),
hadesmem::PeFileType::Data);
hadesmem::NtHeaders const nt_headers(process, pe_file);
WORD const num_sections = nt_headers.GetNumberOfSections();
// Assume every module has at least one section.
// TODO: Better tests.
hadesmem::SectionList sections(process, pe_file);
WORD section_count = 0;
for (auto const& section : sections)
{
section_count += 1;
auto const section_header_raw = hadesmem::Read<IMAGE_SECTION_HEADER>(
process, section.GetBase());
section.SetName(section.GetName());
section.SetVirtualAddress(section.GetVirtualAddress());
section.SetVirtualSize(section.GetVirtualSize());
section.SetSizeOfRawData(section.GetSizeOfRawData());
section.SetPointerToRawData(section.GetPointerToRawData());
section.SetPointerToRelocations(section.GetPointerToRelocations());
section.SetPointerToLinenumbers(section.GetPointerToLinenumbers());
section.SetNumberOfRelocations(section.GetNumberOfRelocations());
section.SetNumberOfLinenumbers(section.GetNumberOfLinenumbers());
section.SetCharacteristics(section.GetCharacteristics());
auto const section_header_raw_new = hadesmem::Read<IMAGE_SECTION_HEADER>(
process, section.GetBase());
BOOST_CHECK_EQUAL(std::memcmp(§ion_header_raw,
§ion_header_raw_new, sizeof(section_header_raw)), 0);
std::stringstream test_str_1;
test_str_1.imbue(std::locale::classic());
test_str_1 << section;
std::stringstream test_str_2;
test_str_2.imbue(std::locale::classic());
test_str_2 << section.GetBase();
BOOST_CHECK_EQUAL(test_str_1.str(), test_str_2.str());
if (mod.GetHandle() != GetModuleHandle(L"ntdll"))
{
hadesmem::PeFile const pe_file_ntdll(process,
GetModuleHandle(L"ntdll"), hadesmem::PeFileType::Image);
hadesmem::Section const section_ntdll(process, pe_file_ntdll, 0);
std::stringstream test_str_3;
test_str_3.imbue(std::locale::classic());
test_str_3 << section_ntdll.GetBase();
BOOST_CHECK_NE(test_str_1.str(), test_str_3.str());
}
}
BOOST_CHECK(section_count == num_sections);
// Assume every module has a '.text' section.
// TODO: Better tests.
auto text_iter = std::find_if(std::begin(sections), std::end(sections),
[] (hadesmem::Section const& section)
{
return section.GetName() == ".data";
});
BOOST_CHECK(text_iter != std::end(sections));
}
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_BOUNDARY_CONDITION
#define MJOLNIR_BOUNDARY_CONDITION
#include <cassert>
namespace mjolnir
{
template<typename realT, typename coordT>
struct UnlimitedBoundary
{
typedef realT real_type;
typedef coordT coordiante_type;
UnlimitedBoundary() = default;
~UnlimitedBoundary() = default;
coordinate_type adjust_direction(coordinate_type dr) const {return dr;}
coordinate_type adjust_position (coordinate_type r ) const {return r;}
};
template<typename realT, typename coordT>
struct CubicPeriodicBoundary
{
public:
typedef realT real_type;
typedef coordT coordiante_type;
public:
CubicPeriodicBoundary() = default;
~CubicPeriodicBoundary() = default;
CubicPeriodicBoundary(const coordinate_type& lw, const coordinate_type& up)
: lower(lw), upper(up), system_size(up-lw), system_size_half(0.5*(up-lw))
{}
coordinate_type adjust_direction(coordinate_type dr) const
{
if(dr[0] < -system_size_half[0]) dr[0] += system_size[0];
else if(dr[0] > system_size_half[0]) dr[0] -= system_size[0];
if(dr[1] < -system_size_half[1]) dr[1] += system_size[1];
else if(dr[1] > system_size_half[1]) dr[1] -= system_size[1];
if(dr[2] < -system_size_half[2]) dr[2] += system_size[2];
else if(dr[2] > system_size_half[2]) dr[2] -= system_size[2];
return dr;
}
coordinate_type adjust_position(coordinate_type pos) const
{
if(pos[0] < lower[0]) pos[0] += system_size_[0];
else if(pos[0] > upper[0]) pos[0] -= system_size_[0];
if(pos[1] < lower[1]) pos[1] += system_size_[1];
else if(pos[1] > upper[1]) pos[1] -= system_size_[1];
if(pos[2] < lower[2]) pos[2] += system_size_[2];
else if(pos[2] > upper[2]) pos[2] -= system_size_[2];
return pos;
}
coordinate_type& lower_bound() {return lower;}
coordinate_type const& lower_bound() const {return lower;}
coordinate_type& upper_bound() {return upper;}
coordinate_type const& upper_bound() const {return upper;}
coordinate_type const& range() const {return system_size;}
private:
coordinate_type lower;
coordinate_type upper;
coordinate_type system_size;
coordinate_type system_size_half;
};
}//mjolnir
#endif /* MJOLNIR_BOUNDARY_CONDITION */
<commit_msg>add noexcept to boundary<commit_after>#ifndef MJOLNIR_BOUNDARY_CONDITION
#define MJOLNIR_BOUNDARY_CONDITION
#include <cassert>
namespace mjolnir
{
template<typename realT, typename coordT>
struct UnlimitedBoundary
{
typedef realT real_type;
typedef coordT coord_type;
UnlimitedBoundary() = default;
~UnlimitedBoundary() = default;
coord_type adjust_direction(coord_type dr) const noexcept {return dr;}
coord_type adjust_position (coord_type r ) const noexcept {return r;}
};
template<typename realT, typename coordT>
struct CubicPeriodicBoundary
{
public:
typedef realT real_type;
typedef coordT coordiante_type;
public:
CubicPeriodicBoundary() = default;
~CubicPeriodicBoundary() = default;
CubicPeriodicBoundary(const coordinate_type& lw, const coordinate_type& up)
: lower(lw), upper(up), system_size(up-lw), system_size_half(0.5*(up-lw))
{}
coordinate_type adjust_direction(coordinate_type dr) const noexcept
{
if(dr[0] < -system_size_half[0]) dr[0] += system_size[0];
else if(dr[0] > system_size_half[0]) dr[0] -= system_size[0];
if(dr[1] < -system_size_half[1]) dr[1] += system_size[1];
else if(dr[1] > system_size_half[1]) dr[1] -= system_size[1];
if(dr[2] < -system_size_half[2]) dr[2] += system_size[2];
else if(dr[2] > system_size_half[2]) dr[2] -= system_size[2];
return dr;
}
coordinate_type adjust_position(coordinate_type pos) const noexcept
{
if(pos[0] < lower[0]) pos[0] += system_size_[0];
else if(pos[0] > upper[0]) pos[0] -= system_size_[0];
if(pos[1] < lower[1]) pos[1] += system_size_[1];
else if(pos[1] > upper[1]) pos[1] -= system_size_[1];
if(pos[2] < lower[2]) pos[2] += system_size_[2];
else if(pos[2] > upper[2]) pos[2] -= system_size_[2];
return pos;
}
coordinate_type& lower_bound() {return lower;}
coordinate_type const& lower_bound() const {return lower;}
coordinate_type& upper_bound() {return upper;}
coordinate_type const& upper_bound() const {return upper;}
coordinate_type const& range() const {return system_size;}
private:
coordinate_type lower;
coordinate_type upper;
coordinate_type system_size;
coordinate_type system_size_half;
};
}//mjolnir
#endif /* MJOLNIR_BOUNDARY_CONDITION */
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libmace
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include "ContextService.h"
#include "AccessLine.h"
#include "MaceKey.h"
#include "HeadEventDispatch.h"
namespace mace{
class __ServiceStackEvent__;
class __ScopedTransition__;
class __ScopedRoutine__;
};
// LocalService is for non-distributed service.
class __LocalTransition__;
class LocalService: public ContextService {
friend class __LocalTransition__;
public:
LocalService(): ContextService()
{
mace::map<mace::MaceAddr ,mace::list<mace::string > > servContext;
loadContextMapping( servContext);
}
protected:
virtual void dispatchDeferredMessages(MaceKey const& dest, mace::string const& message, registration_uid_t const rid ) {}// no messages
virtual void executeDeferredUpcall( mace::Message* const upcall, mace::string& returnValue ) { }
};
class __LocalTransition__{
public:
__LocalTransition__( LocalService* service, int8_t const eventType, mace::string const& targetContextName = "", mace::vector< mace::string > const& snapshotContextNames = mace::vector< mace::string >() ) {
mace::vector< uint32_t > snapshotContextIDs;
mace::__ServiceStackEvent__ sse( eventType, service, targetContextName );
const mace::ContextMapping& currentMapping = service->contextMapping.getSnapshot();
const uint32_t targetContextID = currentMapping.findIDByName( targetContextName );
for_each( snapshotContextNames.begin(), snapshotContextNames.end(), mace::addSnapshotContextID( currentMapping, snapshotContextIDs ) );
mace::AccessLine al( service->instanceUniqueID, targetContextID, currentMapping );
p = new mace::__ScopedTransition__( service, targetContextID );
}
~__LocalTransition__(){
delete p;
}
private:
mace::__ScopedTransition__* p;
};
// InContextService is similar to mace-incontext system
template< class GlobalContextType >
class InContextService: public LocalService {
friend class mace::__ServiceStackEvent__;
public:
InContextService(): LocalService(), globalContext(NULL) { }
private:
GlobalContextType* globalContext;
mace::ContextBaseClass* createContextObject( mace::string const& contextTypeName ){
ASSERT( contextTypeName.empty() );
ASSERT( globalContext == NULL );
globalContext = new GlobalContextType();
return globalContext;
}
};
namespace mace {
// a specialized message type. This message is used for storing information and passed around between threads, therefore it will not do serialization
class LocalMessage: public mace::AsyncEvent_Message, public mace::PrintPrintable{
virtual void print( std::ostream& __out ) const {
__out << "LocalMessage()";
}
virtual void serialize( std::string& str ) const{ } // empty
virtual int deserialize( std::istream& __in ) throw (mace::SerializationException){ return 0;}
};
}
struct __async_req: public mace::LocalMessage{
static const uint8_t messageType =12;
uint8_t getType() const{ return messageType; }
__asyncExtraField& getExtra() { return extra; }
mace::Event& getEvent() { return event; }
mace::Event event;
mace::__asyncExtraField extra;
};
template< class GlobalContextType >
class Test1Service: public InContextService< GlobalContextType > {
public:
Test1Service(): InContextService< GlobalContextType >() { }
void maceInit(){ // access the global context
this->registerInstanceID();
__LocalTransition__ lt( this, mace::Event::STARTEVENT );
__real_maceInit();
}
void maceExit(){ // access the global context
__LocalTransition__ lt( this, mace::Event::ENDEVENT );
__real_maceExit();
}
private:
void __real_maceInit(){
async_test();
}
void __real_maceExit(){
}
void async_test(){
__async_req* req = new __async_req;
this->addEventRequest( req );
}
void test( __async_req* msg){
{
this->__beginRemoteMethod( msg->event );
mace::__ScopedTransition__ (this, msg->extra );
async_test();
}
delete msg;
}
int deserializeMethod( std::istream& is, mace::Message*& eventObject ) {
uint8_t msgNum_s = static_cast<uint8_t>(is.peek() ) ;
switch( msgNum_s ){
case __async_req::messageType: {
eventObject = new __async_req;
return mace::deserialize( is, eventObject );
break;
}
default:
ABORT("message type not found");
}
};
void executeEvent( mace::AsyncEvent_Message* __param ){
mace::Message *msg = static_cast< mace::Message* >( __param ) ;
switch( msg->getType() ){
case __async_req::messageType: {
__async_req* __msg = static_cast< __async_req *>( msg ) ;
test( __msg );
break;
}
}
}
void executeRoutine(mace::Routine_Message* __param, mace::MaceAddr const & source){
}
};
class GlobalContext: public mace::ContextBaseClass{
public:
GlobalContext( const mace::string& contextName="", const uint64_t eventID=0, const uint8_t instanceUniqueID=0, const uint32_t contextID=0 ):
mace::ContextBaseClass( contextName, eventID, instanceUniqueID, contextID ){
}
private:
// declare context variables here
};
int main(int argc, char* argv[]){
mace::Init( argc, argv );
const char *_argv[] = {""};
int _argc = 1;
::boost::unit_test::unit_test_main( &init_unit_test, _argc, const_cast<char**>(_argv) );
mace::Shutdown();
}
BOOST_AUTO_TEST_SUITE( lib_ContextService )
BOOST_AUTO_TEST_CASE( Case1 )
{ // test single services
// test: create start event, async event, timer event, message delivery event, downcall event, upcall event,
// test routines (local)
BOOST_TEST_CHECKPOINT("Constructor");
Test1Service<GlobalContext> service1;
BOOST_TEST_CHECKPOINT("maceInit");
service1.maceInit();
SysUtil::sleep( 10 );
BOOST_TEST_CHECKPOINT("maceExit");
service1.maceExit();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixed a bug in ContextService_test and make it conformant to the current runtime.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libmace
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include "ContextService.h"
#include "AccessLine.h"
#include "MaceKey.h"
#include "HeadEventDispatch.h"
namespace mace{
class __ServiceStackEvent__;
class __ScopedTransition__;
class __ScopedRoutine__;
};
// LocalService is for non-distributed service.
using mace::__CheckTransition__;
class __LocalTransition__;
class LocalService: public ContextService {
friend class __LocalTransition__;
public:
LocalService(): ContextService()
{
mace::map<mace::MaceAddr ,mace::list<mace::string > > servContext;
loadContextMapping( servContext);
}
protected:
virtual void dispatchDeferredMessages(MaceKey const& dest, mace::string const& message, registration_uid_t const rid ) {}// no messages
virtual void executeDeferredUpcall( mace::Message* const upcall, mace::string& returnValue ) { }
};
class __LocalTransition__{
public:
__LocalTransition__( LocalService* service, int8_t const eventType, mace::string const& targetContextName = "", mace::vector< mace::string > const& snapshotContextNames = mace::vector< mace::string >() ) {
mace::vector< uint32_t > snapshotContextIDs;
mace::__ServiceStackEvent__ sse( eventType, service, targetContextName );
const mace::ContextMapping& currentMapping = service->contextMapping.getSnapshot();
const uint32_t targetContextID = currentMapping.findIDByName( targetContextName );
for_each( snapshotContextNames.begin(), snapshotContextNames.end(), mace::addSnapshotContextID( currentMapping, snapshotContextIDs ) );
mace::AccessLine al( service->instanceUniqueID, targetContextID, currentMapping );
p = new mace::__ScopedTransition__( service, targetContextID );
}
~__LocalTransition__(){
delete p;
}
private:
mace::__ScopedTransition__* p;
};
// InContextService is similar to mace-incontext system
template< class GlobalContextType >
class InContextService: public LocalService {
friend class mace::__ServiceStackEvent__;
public:
InContextService(): LocalService(), globalContext(NULL) { }
private:
GlobalContextType* globalContext;
mace::ContextBaseClass* createContextObject( mace::string const& contextTypeName ){
ASSERT( contextTypeName.empty() );
ASSERT( globalContext == NULL );
globalContext = new GlobalContextType();
return globalContext;
}
};
namespace mace {
// a specialized message type. This message is used for storing information and passed around between threads, therefore it will not do serialization
class LocalMessage: public mace::AsyncEvent_Message, public mace::PrintPrintable{
virtual void print( std::ostream& __out ) const {
__out << "LocalMessage()";
}
virtual void serialize( std::string& str ) const{ } // empty
virtual int deserialize( std::istream& __in ) throw (mace::SerializationException){ return 0;}
};
}
struct __async_req: public mace::LocalMessage{
static const uint8_t messageType =12;
uint8_t getType() const{ return messageType; }
__asyncExtraField& getExtra() { return extra; }
mace::Event& getEvent() { return event; }
mace::Event event;
mace::__asyncExtraField extra;
};
template< class GlobalContextType >
class Test1Service: public InContextService< GlobalContextType > {
public:
Test1Service(): InContextService< GlobalContextType >() { }
void maceInit(){ // access the global context
this->registerInstanceID();
//__LocalTransition__ lt( this, mace::Event::STARTEVENT );
__CheckTransition__ cm( this, mace::Event::STARTEVENT, "" );
__real_maceInit();
}
void maceExit(){ // access the global context
//__LocalTransition__ lt( this, mace::Event::ENDEVENT );
__CheckTransition__ cm( this, mace::Event::ENDEVENT, "" );
__real_maceExit();
}
private:
void __real_maceInit(){
async_test();
}
void __real_maceExit(){
}
void async_test(){
__async_req* req = new __async_req;
this->addEventRequest( req );
}
void test( __async_req* msg){
async_test();
}
int deserializeMethod( std::istream& is, mace::Message*& eventObject ) {
uint8_t msgNum_s = static_cast<uint8_t>(is.peek() ) ;
switch( msgNum_s ){
case __async_req::messageType: {
eventObject = new __async_req;
return mace::deserialize( is, eventObject );
break;
}
default:
ABORT("message type not found");
}
};
void executeEvent( mace::AsyncEvent_Message* __param ){
this->__beginRemoteMethod( __param->getEvent() );
mace::__ScopedTransition__ st(this, __param->getExtra() );
mace::Message *msg = static_cast< mace::Message* >( __param ) ;
switch( msg->getType() ){
case __async_req::messageType: {
__async_req* __msg = static_cast< __async_req *>( msg ) ;
test( __msg );
break;
}
}
delete __param;
}
void executeRoutine(mace::Routine_Message* __param, mace::MaceAddr const & source){
}
};
class GlobalContext: public mace::ContextBaseClass{
public:
GlobalContext( const mace::string& contextName="", const uint64_t eventID=0, const uint8_t instanceUniqueID=0, const uint32_t contextID=0 ):
mace::ContextBaseClass( contextName, eventID, instanceUniqueID, contextID ){
}
private:
// declare context variables here
};
int main(int argc, char* argv[]){
mace::Init( argc, argv );
const char *_argv[] = {""};
int _argc = 1;
::boost::unit_test::unit_test_main( &init_unit_test, _argc, const_cast<char**>(_argv) );
mace::Shutdown();
}
BOOST_AUTO_TEST_SUITE( lib_ContextService )
BOOST_AUTO_TEST_CASE( Case1 )
{ // test single services
// test: create start event, async event, timer event, message delivery event, downcall event, upcall event,
// test routines (local)
BOOST_TEST_CHECKPOINT("Constructor");
Test1Service<GlobalContext> service1;
BOOST_TEST_CHECKPOINT("maceInit");
service1.maceInit();
SysUtil::sleep( 10 );
BOOST_TEST_CHECKPOINT("maceExit");
service1.maceExit();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result);
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result);
EXPECT_TRUE(result);
}
// Tests that the APIs in an incognito-enabled extension work properly.
// Flaky, http://crbug.com/42844.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Mark ExtensionApiTest.Incognito as not FLAKY. According to the flakiness dashboard, it has been passing consistently.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result);
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result);
EXPECT_TRUE(result);
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartHTTPServer());
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// TODO(rafaelw,erikkay) disabled due to flakiness
// BUG=22668 (probably the same bug)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<commit_msg>Enable ExtensionApiTest.Toolstrip<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// TODO(rafaelw,erikkay) disabled due to flakiness
// BUG=22668 (probably the same bug)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) {
ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<|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 "chrome/browser/spellchecker/spellcheck_message_filter.h"
#include <algorithm>
#include <functional>
#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_host_metrics.h"
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "chrome/browser/spellchecker/spelling_service_client.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/spellcheck_marker.h"
#include "chrome/common/spellcheck_messages.h"
#include "content/public/browser/render_process_host.h"
#include "net/url_request/url_fetcher.h"
using content::BrowserThread;
SpellCheckMessageFilter::SpellCheckMessageFilter(int render_process_id)
: render_process_id_(render_process_id),
client_(new SpellingServiceClient) {
}
void SpellCheckMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
// IPC messages arrive on IO thread, but spellcheck data lives on UI thread.
// The message filter overrides the thread for these messages because they
// access spellcheck data.
if (message.type() == SpellCheckHostMsg_RequestDictionary::ID ||
message.type() == SpellCheckHostMsg_NotifyChecked::ID ||
message.type() == SpellCheckHostMsg_RespondDocumentMarkers::ID)
*thread = BrowserThread::UI;
#if !defined(OS_MACOSX)
if (message.type() == SpellCheckHostMsg_CallSpellingService::ID)
*thread = BrowserThread::UI;
#endif
}
bool SpellCheckMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(SpellCheckMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_RequestDictionary,
OnSpellCheckerRequestDictionary)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_NotifyChecked,
OnNotifyChecked)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_RespondDocumentMarkers,
OnRespondDocumentMarkers)
#if !defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_CallSpellingService,
OnCallSpellingService)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
SpellCheckMessageFilter::~SpellCheckMessageFilter() {}
void SpellCheckMessageFilter::OnSpellCheckerRequestDictionary() {
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
if (!host)
return; // Teardown.
Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
// The renderer has requested that we initialize its spellchecker. This should
// generally only be called once per session, as after the first call, all
// future renderers will be passed the initialization information on startup
// (or when the dictionary changes in some way).
SpellcheckService* spellcheck_service =
SpellcheckServiceFactory::GetForProfile(profile);
DCHECK(spellcheck_service);
// The spellchecker initialization already started and finished; just send
// it to the renderer.
spellcheck_service->InitForRenderer(host);
// TODO(rlp): Ensure that we do not initialize the hunspell dictionary more
// than once if we get requests from different renderers.
}
void SpellCheckMessageFilter::OnNotifyChecked(const string16& word,
bool misspelled) {
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
if (!host)
return; // Teardown.
// Delegates to SpellCheckHost which tracks the stats of our spellchecker.
Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
SpellcheckService* spellcheck_service =
SpellcheckServiceFactory::GetForProfile(profile);
DCHECK(spellcheck_service);
if (spellcheck_service->GetMetrics())
spellcheck_service->GetMetrics()->RecordCheckedWordStats(word, misspelled);
}
void SpellCheckMessageFilter::OnRespondDocumentMarkers(
const std::vector<uint32>& markers) {
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForRenderProcessId(render_process_id_);
// Spellcheck service may not be available for a renderer process that is
// shutting down.
if (!spellcheck)
return;
spellcheck->GetFeedbackSender()->OnReceiveDocumentMarkers(
render_process_id_, markers);
}
#if !defined(OS_MACOSX)
void SpellCheckMessageFilter::OnCallSpellingService(
int route_id,
int identifier,
const string16& text,
std::vector<SpellCheckMarker> markers) {
DCHECK(!text.empty());
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
// Erase invalid markers (with offsets out of boundaries of text length).
markers.erase(
std::remove_if(
markers.begin(),
markers.end(),
std::not1(SpellCheckMarker::IsValidPredicate(text.length()))),
markers.end());
CallSpellingService(text, route_id, identifier, markers);
}
void SpellCheckMessageFilter::OnTextCheckComplete(
int route_id,
int identifier,
const std::vector<SpellCheckMarker>& markers,
bool success,
const string16& text,
const std::vector<SpellCheckResult>& results) {
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForRenderProcessId(render_process_id_);
DCHECK(spellcheck);
std::vector<SpellCheckResult> results_copy = results;
spellcheck->GetFeedbackSender()->OnSpellcheckResults(
&results_copy, render_process_id_, text, markers);
Send(new SpellCheckMsg_RespondSpellingService(
route_id, identifier, success, text, results_copy));
}
// CallSpellingService always executes the callback OnTextCheckComplete.
// (Which, in turn, sends a SpellCheckMsg_RespondSpellingService)
void SpellCheckMessageFilter::CallSpellingService(
const string16& text,
int route_id,
int identifier,
const std::vector<SpellCheckMarker>& markers) {
Profile* profile = NULL;
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
if (host)
profile = Profile::FromBrowserContext(host->GetBrowserContext());
client_->RequestTextCheck(
profile,
SpellingServiceClient::SPELLCHECK,
text,
base::Bind(&SpellCheckMessageFilter::OnTextCheckComplete,
base::Unretained(this),
route_id,
identifier,
markers));
}
#endif
<commit_msg>Add null checks for handlers in spellcheck_message_filters to avoid crashes when the renderer is shutting down.<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 "chrome/browser/spellchecker/spellcheck_message_filter.h"
#include <algorithm>
#include <functional>
#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_host_metrics.h"
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "chrome/browser/spellchecker/spelling_service_client.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/spellcheck_marker.h"
#include "chrome/common/spellcheck_messages.h"
#include "content/public/browser/render_process_host.h"
#include "net/url_request/url_fetcher.h"
using content::BrowserThread;
SpellCheckMessageFilter::SpellCheckMessageFilter(int render_process_id)
: render_process_id_(render_process_id),
client_(new SpellingServiceClient) {
}
void SpellCheckMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
// IPC messages arrive on IO thread, but spellcheck data lives on UI thread.
// The message filter overrides the thread for these messages because they
// access spellcheck data.
if (message.type() == SpellCheckHostMsg_RequestDictionary::ID ||
message.type() == SpellCheckHostMsg_NotifyChecked::ID ||
message.type() == SpellCheckHostMsg_RespondDocumentMarkers::ID)
*thread = BrowserThread::UI;
#if !defined(OS_MACOSX)
if (message.type() == SpellCheckHostMsg_CallSpellingService::ID)
*thread = BrowserThread::UI;
#endif
}
bool SpellCheckMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(SpellCheckMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_RequestDictionary,
OnSpellCheckerRequestDictionary)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_NotifyChecked,
OnNotifyChecked)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_RespondDocumentMarkers,
OnRespondDocumentMarkers)
#if !defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(SpellCheckHostMsg_CallSpellingService,
OnCallSpellingService)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
SpellCheckMessageFilter::~SpellCheckMessageFilter() {}
void SpellCheckMessageFilter::OnSpellCheckerRequestDictionary() {
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
if (!host)
return; // Teardown.
Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
// The renderer has requested that we initialize its spellchecker. This should
// generally only be called once per session, as after the first call, all
// future renderers will be passed the initialization information on startup
// (or when the dictionary changes in some way).
SpellcheckService* spellcheck_service =
SpellcheckServiceFactory::GetForProfile(profile);
DCHECK(spellcheck_service);
// The spellchecker initialization already started and finished; just send
// it to the renderer.
spellcheck_service->InitForRenderer(host);
// TODO(rlp): Ensure that we do not initialize the hunspell dictionary more
// than once if we get requests from different renderers.
}
void SpellCheckMessageFilter::OnNotifyChecked(const string16& word,
bool misspelled) {
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
if (!host)
return; // Teardown.
// Delegates to SpellCheckHost which tracks the stats of our spellchecker.
Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
SpellcheckService* spellcheck_service =
SpellcheckServiceFactory::GetForProfile(profile);
if (!spellcheck_service)
return;
if (spellcheck_service->GetMetrics())
spellcheck_service->GetMetrics()->RecordCheckedWordStats(word, misspelled);
}
void SpellCheckMessageFilter::OnRespondDocumentMarkers(
const std::vector<uint32>& markers) {
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForRenderProcessId(render_process_id_);
// Spellcheck service may not be available for a renderer process that is
// shutting down.
if (!spellcheck)
return;
spellcheck->GetFeedbackSender()->OnReceiveDocumentMarkers(
render_process_id_, markers);
}
#if !defined(OS_MACOSX)
void SpellCheckMessageFilter::OnCallSpellingService(
int route_id,
int identifier,
const string16& text,
std::vector<SpellCheckMarker> markers) {
DCHECK(!text.empty());
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
// Erase invalid markers (with offsets out of boundaries of text length).
markers.erase(
std::remove_if(
markers.begin(),
markers.end(),
std::not1(SpellCheckMarker::IsValidPredicate(text.length()))),
markers.end());
CallSpellingService(text, route_id, identifier, markers);
}
void SpellCheckMessageFilter::OnTextCheckComplete(
int route_id,
int identifier,
const std::vector<SpellCheckMarker>& markers,
bool success,
const string16& text,
const std::vector<SpellCheckResult>& results) {
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForRenderProcessId(render_process_id_);
if (!spellcheck)
return;
std::vector<SpellCheckResult> results_copy = results;
spellcheck->GetFeedbackSender()->OnSpellcheckResults(
&results_copy, render_process_id_, text, markers);
Send(new SpellCheckMsg_RespondSpellingService(
route_id, identifier, success, text, results_copy));
}
// CallSpellingService always executes the callback OnTextCheckComplete.
// (Which, in turn, sends a SpellCheckMsg_RespondSpellingService)
void SpellCheckMessageFilter::CallSpellingService(
const string16& text,
int route_id,
int identifier,
const std::vector<SpellCheckMarker>& markers) {
Profile* profile = NULL;
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
if (host)
profile = Profile::FromBrowserContext(host->GetBrowserContext());
client_->RequestTextCheck(
profile,
SpellingServiceClient::SPELLCHECK,
text,
base::Bind(&SpellCheckMessageFilter::OnTextCheckComplete,
base::Unretained(this),
route_id,
identifier,
markers));
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/translate_infobars_delegates.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// TranslateInfoBarDelegate: InfoBarDelegate overrides: ------------------------
SkBitmap* TranslateInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_TRANSLATE);
}
bool TranslateInfoBarDelegate::EqualsDelegate(InfoBarDelegate* delegate) const {
TranslateInfoBarDelegate* translate_delegate =
delegate->AsTranslateInfoBarDelegate();
// There can be only 1 translate infobar at any one time.
return (!!translate_delegate);
}
void TranslateInfoBarDelegate::InfoBarClosed() {
delete this;
}
// TranslateInfoBarDelegate: public: -------------------------------------------
void TranslateInfoBarDelegate::ModifyOriginalLanguage(
const std::string& original_language) {
original_language_ = original_language;
// TODO(kuan): Send stats to Google Translate that original language has been
// modified.
}
void TranslateInfoBarDelegate::ModifyTargetLanguage(
const std::string& target_language) {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::GetAvailableOriginalLanguages(
std::vector<std::string>* languages) {
// TODO(kuan): Call backend when it's ready; hardcode a list for now.
languages->push_back("Arabic");
languages->push_back("Bengali");
languages->push_back("Bulgarian");
languages->push_back("Chinese (Simplified Han)");
languages->push_back("Chinese (Traditional Han)");
languages->push_back("Croatian");
languages->push_back("Czech");
languages->push_back("Danish");
languages->push_back("Dutch");
languages->push_back("English");
languages->push_back("Estonian");
languages->push_back("Filipino");
languages->push_back("Finnish");
languages->push_back("French");
languages->push_back("German");
languages->push_back("Greek");
languages->push_back("Hebrew");
languages->push_back("Hindi");
languages->push_back("Hungarian");
languages->push_back("Indonesian");
languages->push_back("Italian");
languages->push_back("Japanese");
languages->push_back("Korean");
languages->push_back("Latvian");
languages->push_back("Lithuanian");
languages->push_back("Norwegian");
languages->push_back("Polish");
languages->push_back("Portuguese");
languages->push_back("Romanian");
languages->push_back("Russian");
languages->push_back("Serbian");
languages->push_back("Slovak");
languages->push_back("Slovenian");
languages->push_back("Spanish");
languages->push_back("Swedish");
languages->push_back("Tamil");
languages->push_back("Thai");
languages->push_back("Turkish");
languages->push_back("Ukrainian");
languages->push_back("Vietnamese");
}
void TranslateInfoBarDelegate::GetAvailableTargetLanguages(
std::vector<std::string>* languages) {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::Translate() {
// TODO(kuan): Call actual Translate method.
/*
Translate(WideToUTF8(original_language()), WideToUTF8(target_language()));
*/
}
bool TranslateInfoBarDelegate::IsLanguageBlacklisted() {
NOTREACHED() << "Subclass should override";
return false;
}
bool TranslateInfoBarDelegate::IsSiteBlacklisted() {
NOTREACHED() << "Subclass should override";
return false;
}
bool TranslateInfoBarDelegate::ShouldAlwaysTranslate() {
NOTREACHED() << "Subclass should override";
return false;
}
void TranslateInfoBarDelegate::ToggleLanguageBlacklist() {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::ToggleSiteBlacklist() {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::ToggleAlwaysTranslate() {
NOTREACHED() << "Subclass should override";
}
// TranslateInfoBarDelegate: protected: ----------------------------------------
TranslateInfoBarDelegate::TranslateInfoBarDelegate(TabContents* tab_contents,
PrefService* user_prefs, const std::string& original_language,
const std::string& target_language)
: InfoBarDelegate(tab_contents),
tab_contents_(tab_contents),
original_language_(original_language),
target_language_(target_language),
prefs_(user_prefs) {
}
// BeforeTranslateInfoBarDelegate: public: -------------------------------------
BeforeTranslateInfoBarDelegate::BeforeTranslateInfoBarDelegate(
TabContents* tab_contents, PrefService* user_prefs, const GURL& url,
const std::string& original_language, const std::string& target_language)
: TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
target_language),
site_(url.HostNoBrackets()),
never_translate_language_(false),
never_translate_site_(false) {
}
bool BeforeTranslateInfoBarDelegate::IsLanguageBlacklisted() {
never_translate_language_ =
prefs_.IsLanguageBlacklisted(original_language());
return never_translate_language_;
}
void BeforeTranslateInfoBarDelegate::ToggleLanguageBlacklist() {
never_translate_language_ = !never_translate_language_;
if (never_translate_language_)
prefs_.BlacklistLanguage(original_language());
else
prefs_.RemoveLanguageFromBlacklist(original_language());
}
bool BeforeTranslateInfoBarDelegate::IsSiteBlacklisted() {
never_translate_site_ = prefs_.IsSiteBlacklisted(site_);
return never_translate_site_;
}
void BeforeTranslateInfoBarDelegate::ToggleSiteBlacklist() {
never_translate_site_ = !never_translate_site_;
if (never_translate_site_)
prefs_.BlacklistSite(site_);
else
prefs_.RemoveSiteFromBlacklist(site_);
}
// AfterTranslateInfoBarDelegate: public: --------------------------------------
AfterTranslateInfoBarDelegate::AfterTranslateInfoBarDelegate(
TabContents* tab_contents, PrefService* user_prefs,
const std::string& original_language, const std::string& target_language)
: TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
target_language),
always_translate_(false) {
}
void AfterTranslateInfoBarDelegate::GetAvailableTargetLanguages(
std::vector<std::string>* languages) {
// TODO(kuan): Call backend when it's ready; hardcode a list for now.
GetAvailableOriginalLanguages(languages);
}
void AfterTranslateInfoBarDelegate::ModifyTargetLanguage(
const std::string& target_language) {
target_language_ = target_language;
}
bool AfterTranslateInfoBarDelegate::ShouldAlwaysTranslate() {
always_translate_ = prefs_.IsLanguagePairWhitelisted(original_language(),
target_language());
return always_translate_;
}
void AfterTranslateInfoBarDelegate::ToggleAlwaysTranslate() {
always_translate_ = !always_translate_;
if (always_translate_)
prefs_.WhitelistLanguagePair(original_language(), target_language());
else
prefs_.RemoveLanguagePairFromWhitelist(original_language(),
target_language());
}
<commit_msg>use stubs for yet-to-be-implemented non-windows translate infobars<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/translate_infobars_delegates.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// TranslateInfoBarDelegate: InfoBarDelegate overrides: ------------------------
SkBitmap* TranslateInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_TRANSLATE);
}
bool TranslateInfoBarDelegate::EqualsDelegate(InfoBarDelegate* delegate) const {
TranslateInfoBarDelegate* translate_delegate =
delegate->AsTranslateInfoBarDelegate();
// There can be only 1 translate infobar at any one time.
return (!!translate_delegate);
}
void TranslateInfoBarDelegate::InfoBarClosed() {
delete this;
}
// TranslateInfoBarDelegate: public: -------------------------------------------
void TranslateInfoBarDelegate::ModifyOriginalLanguage(
const std::string& original_language) {
original_language_ = original_language;
// TODO(kuan): Send stats to Google Translate that original language has been
// modified.
}
void TranslateInfoBarDelegate::ModifyTargetLanguage(
const std::string& target_language) {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::GetAvailableOriginalLanguages(
std::vector<std::string>* languages) {
// TODO(kuan): Call backend when it's ready; hardcode a list for now.
languages->push_back("Arabic");
languages->push_back("Bengali");
languages->push_back("Bulgarian");
languages->push_back("Chinese (Simplified Han)");
languages->push_back("Chinese (Traditional Han)");
languages->push_back("Croatian");
languages->push_back("Czech");
languages->push_back("Danish");
languages->push_back("Dutch");
languages->push_back("English");
languages->push_back("Estonian");
languages->push_back("Filipino");
languages->push_back("Finnish");
languages->push_back("French");
languages->push_back("German");
languages->push_back("Greek");
languages->push_back("Hebrew");
languages->push_back("Hindi");
languages->push_back("Hungarian");
languages->push_back("Indonesian");
languages->push_back("Italian");
languages->push_back("Japanese");
languages->push_back("Korean");
languages->push_back("Latvian");
languages->push_back("Lithuanian");
languages->push_back("Norwegian");
languages->push_back("Polish");
languages->push_back("Portuguese");
languages->push_back("Romanian");
languages->push_back("Russian");
languages->push_back("Serbian");
languages->push_back("Slovak");
languages->push_back("Slovenian");
languages->push_back("Spanish");
languages->push_back("Swedish");
languages->push_back("Tamil");
languages->push_back("Thai");
languages->push_back("Turkish");
languages->push_back("Ukrainian");
languages->push_back("Vietnamese");
}
void TranslateInfoBarDelegate::GetAvailableTargetLanguages(
std::vector<std::string>* languages) {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::Translate() {
// TODO(kuan): Call actual Translate method.
/*
Translate(WideToUTF8(original_language()), WideToUTF8(target_language()));
*/
}
bool TranslateInfoBarDelegate::IsLanguageBlacklisted() {
NOTREACHED() << "Subclass should override";
return false;
}
bool TranslateInfoBarDelegate::IsSiteBlacklisted() {
NOTREACHED() << "Subclass should override";
return false;
}
bool TranslateInfoBarDelegate::ShouldAlwaysTranslate() {
NOTREACHED() << "Subclass should override";
return false;
}
void TranslateInfoBarDelegate::ToggleLanguageBlacklist() {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::ToggleSiteBlacklist() {
NOTREACHED() << "Subclass should override";
}
void TranslateInfoBarDelegate::ToggleAlwaysTranslate() {
NOTREACHED() << "Subclass should override";
}
// TranslateInfoBarDelegate: protected: ----------------------------------------
TranslateInfoBarDelegate::TranslateInfoBarDelegate(TabContents* tab_contents,
PrefService* user_prefs, const std::string& original_language,
const std::string& target_language)
: InfoBarDelegate(tab_contents),
tab_contents_(tab_contents),
original_language_(original_language),
target_language_(target_language),
prefs_(user_prefs) {
}
// BeforeTranslateInfoBarDelegate: public: -------------------------------------
BeforeTranslateInfoBarDelegate::BeforeTranslateInfoBarDelegate(
TabContents* tab_contents, PrefService* user_prefs, const GURL& url,
const std::string& original_language, const std::string& target_language)
: TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
target_language),
site_(url.HostNoBrackets()),
never_translate_language_(false),
never_translate_site_(false) {
}
bool BeforeTranslateInfoBarDelegate::IsLanguageBlacklisted() {
never_translate_language_ =
prefs_.IsLanguageBlacklisted(original_language());
return never_translate_language_;
}
void BeforeTranslateInfoBarDelegate::ToggleLanguageBlacklist() {
never_translate_language_ = !never_translate_language_;
if (never_translate_language_)
prefs_.BlacklistLanguage(original_language());
else
prefs_.RemoveLanguageFromBlacklist(original_language());
}
bool BeforeTranslateInfoBarDelegate::IsSiteBlacklisted() {
never_translate_site_ = prefs_.IsSiteBlacklisted(site_);
return never_translate_site_;
}
void BeforeTranslateInfoBarDelegate::ToggleSiteBlacklist() {
never_translate_site_ = !never_translate_site_;
if (never_translate_site_)
prefs_.BlacklistSite(site_);
else
prefs_.RemoveSiteFromBlacklist(site_);
}
#if !defined(TOOLKIT_VIEWS)
InfoBar* BeforeTranslateInfoBarDelegate::CreateInfoBar() {
NOTIMPLEMENTED();
return NULL;
}
#endif // !TOOLKIT_VIEWS
// AfterTranslateInfoBarDelegate: public: --------------------------------------
AfterTranslateInfoBarDelegate::AfterTranslateInfoBarDelegate(
TabContents* tab_contents, PrefService* user_prefs,
const std::string& original_language, const std::string& target_language)
: TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
target_language),
always_translate_(false) {
}
void AfterTranslateInfoBarDelegate::GetAvailableTargetLanguages(
std::vector<std::string>* languages) {
// TODO(kuan): Call backend when it's ready; hardcode a list for now.
GetAvailableOriginalLanguages(languages);
}
void AfterTranslateInfoBarDelegate::ModifyTargetLanguage(
const std::string& target_language) {
target_language_ = target_language;
}
bool AfterTranslateInfoBarDelegate::ShouldAlwaysTranslate() {
always_translate_ = prefs_.IsLanguagePairWhitelisted(original_language(),
target_language());
return always_translate_;
}
void AfterTranslateInfoBarDelegate::ToggleAlwaysTranslate() {
always_translate_ = !always_translate_;
if (always_translate_)
prefs_.WhitelistLanguagePair(original_language(), target_language());
else
prefs_.RemoveLanguagePairFromWhitelist(original_language(),
target_language());
}
#if !defined(TOOLKIT_VIEWS)
InfoBar* AfterTranslateInfoBarDelegate::CreateInfoBar() {
NOTIMPLEMENTED();
return NULL;
}
#endif // !TOOLKIT_VIEWS
<|endoftext|> |
<commit_before>#include "mocca/net/rpc/Dispatcher.h"
#include "mocca/base/ContainerTools.h"
#include "mocca/base/Error.h"
#include "mocca/base/Memory.h"
#include "mocca/log/LogManager.h"
#include "mocca/net/ConnectionFactorySelector.h"
#include "mocca/net/rpc/JsonKeys.h"
using namespace mocca::net;
Dispatcher::Dispatcher(const std::vector<mocca::net::Endpoint>& endpoints) {
std::vector<std::unique_ptr<mocca::net::IMessageConnectionAcceptor>> acceptors;
for (const auto& ep : endpoints) {
acceptors.push_back(mocca::net::ConnectionFactorySelector::bind(ep));
}
aggregator_ = mocca::make_unique<mocca::net::ConnectionAggregator>(std::move(acceptors));
registerReflection();
}
Dispatcher::~Dispatcher() {
join();
}
void Dispatcher::sendReply(const JsonCpp::Value root, const std::vector<mocca::net::MessagePart>& binary,
std::shared_ptr<const mocca::net::ConnectionID> connectionID) {
JsonCpp::FastWriter writer;
std::string jsonStr = writer.write(root);
mocca::net::Message message;
message.push_back(mocca::net::createMessagePart(jsonStr));
message.insert(end(message), begin(binary), end(binary));
mocca::net::MessageEnvelope envelope(std::move(message), connectionID);
aggregator_->send(std::move(envelope));
}
void Dispatcher::run() {
const auto timeout(std::chrono::milliseconds(100));
while (!isInterrupted()) {
auto envelopeNullable = aggregator_->receive(timeout);
if (!envelopeNullable.isNull()) {
auto envelope = envelopeNullable.release();
auto message = std::move(envelope.message);
try {
JsonCpp::Value root = parseMessage(message);
// sanity checks on request
if (!root.isMember(mocca::net::methodKey())) {
throw Error("Malformatted request: Required field 'method' or 'params' is missing", __FILE__, __LINE__);
}
// find matching method for request
std::string methodName = root[mocca::net::methodKey()].asString();
auto findIt = mocca::findMemberEqual(begin(methods_), end(methods_), &Method::name, methodName);
if (findIt == end(methods_)) {
throw Error("Unknown method '" + methodName + "'", __FILE__, __LINE__);
}
// call method
const auto& method = *findIt;
auto result = method(root[mocca::net::paramsKey()]);
const auto& json = result.first;
const auto& binary = result.second;
// send reply if method returned something
if (!json.empty()) {
JsonCpp::Value reply;
reply[mocca::net::resultKey()] = json;
reply[mocca::net::statusKey()] = mocca::net::successStatus();
sendReply(reply, binary, envelope.connectionID);
}
} catch (const std::runtime_error& err) {
LERROR(err.what());
// in case of an error, send error message back to client
JsonCpp::Value reply;
reply[mocca::net::statusKey()] = mocca::net::errorStatus();
reply[mocca::net::errorKey()] = err.what();
sendReply(reply, {}, envelope.connectionID);
}
}
}
}
JsonCpp::Value Dispatcher::parseMessage(const mocca::net::Message& message) {
JsonCpp::Reader reader;
JsonCpp::Value root;
std::string json(reinterpret_cast<const char*>(message[0]->data()), message[0]->size());
LDEBUG("Request: " << json);
if (!reader.parse(json, root)) {
throw Error("JSON parse error: " + reader.getFormattedErrorMessages(), __FILE__, __LINE__);
}
return root;
}
void Dispatcher::registerMethod(Method method) {
methods_.push_back(std::move(method));
}
void Dispatcher::registerReflection() {
MethodDescription description(mocca::net::describe(), {});
Method method(description, [this](const JsonCpp::Value&) {
JsonCpp::Value result;
int count = 0;
for (const auto& m : methods_) {
result[count++] = MethodDescription::toJson(m.description());
}
return std::make_pair(result, std::vector<mocca::net::MessagePart>());
});
registerMethod(std::move(method));
}<commit_msg>return rpc reply even if it's empty<commit_after>#include "mocca/net/rpc/Dispatcher.h"
#include "mocca/base/ContainerTools.h"
#include "mocca/base/Error.h"
#include "mocca/base/Memory.h"
#include "mocca/log/LogManager.h"
#include "mocca/net/ConnectionFactorySelector.h"
#include "mocca/net/rpc/JsonKeys.h"
using namespace mocca::net;
Dispatcher::Dispatcher(const std::vector<mocca::net::Endpoint>& endpoints) {
std::vector<std::unique_ptr<mocca::net::IMessageConnectionAcceptor>> acceptors;
for (const auto& ep : endpoints) {
acceptors.push_back(mocca::net::ConnectionFactorySelector::bind(ep));
}
aggregator_ = mocca::make_unique<mocca::net::ConnectionAggregator>(std::move(acceptors));
registerReflection();
}
Dispatcher::~Dispatcher() {
join();
}
void Dispatcher::sendReply(const JsonCpp::Value root, const std::vector<mocca::net::MessagePart>& binary,
std::shared_ptr<const mocca::net::ConnectionID> connectionID) {
JsonCpp::FastWriter writer;
std::string jsonStr = writer.write(root);
mocca::net::Message message;
message.push_back(mocca::net::createMessagePart(jsonStr));
message.insert(end(message), begin(binary), end(binary));
mocca::net::MessageEnvelope envelope(std::move(message), connectionID);
aggregator_->send(std::move(envelope));
}
void Dispatcher::run() {
const auto timeout(std::chrono::milliseconds(100));
while (!isInterrupted()) {
auto envelopeNullable = aggregator_->receive(timeout);
if (!envelopeNullable.isNull()) {
auto envelope = envelopeNullable.release();
auto message = std::move(envelope.message);
try {
JsonCpp::Value root = parseMessage(message);
// sanity checks on request
if (!root.isMember(mocca::net::methodKey())) {
throw Error("Malformatted request: Required field 'method' or 'params' is missing", __FILE__, __LINE__);
}
// find matching method for request
std::string methodName = root[mocca::net::methodKey()].asString();
auto findIt = mocca::findMemberEqual(begin(methods_), end(methods_), &Method::name, methodName);
if (findIt == end(methods_)) {
throw Error("Unknown method '" + methodName + "'", __FILE__, __LINE__);
}
// call method
const auto& method = *findIt;
auto result = method(root[mocca::net::paramsKey()]);
const auto& json = result.first;
const auto& binary = result.second;
// send reply if method returned something
JsonCpp::Value reply;
reply[mocca::net::resultKey()] = json;
reply[mocca::net::statusKey()] = mocca::net::successStatus();
sendReply(reply, binary, envelope.connectionID);
} catch (const std::runtime_error& err) {
LERROR(err.what());
// in case of an error, send error message back to client
JsonCpp::Value reply;
reply[mocca::net::statusKey()] = mocca::net::errorStatus();
reply[mocca::net::errorKey()] = err.what();
sendReply(reply, {}, envelope.connectionID);
}
}
}
}
JsonCpp::Value Dispatcher::parseMessage(const mocca::net::Message& message) {
JsonCpp::Reader reader;
JsonCpp::Value root;
std::string json(reinterpret_cast<const char*>(message[0]->data()), message[0]->size());
LDEBUG("Request: " << json);
if (!reader.parse(json, root)) {
throw Error("JSON parse error: " + reader.getFormattedErrorMessages(), __FILE__, __LINE__);
}
return root;
}
void Dispatcher::registerMethod(Method method) {
methods_.push_back(std::move(method));
}
void Dispatcher::registerReflection() {
MethodDescription description(mocca::net::describe(), {});
Method method(description, [this](const JsonCpp::Value&) {
JsonCpp::Value result;
int count = 0;
for (const auto& m : methods_) {
result[count++] = MethodDescription::toJson(m.description());
}
return std::make_pair(result, std::vector<mocca::net::MessagePart>());
});
registerMethod(std::move(method));
}<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_TYPED_ACTOR_HPP
#define CAF_TYPED_ACTOR_HPP
#include "caf/intrusive_ptr.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/replies_to.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/typed_behavior.hpp"
namespace caf {
class actor_addr;
class local_actor;
struct invalid_actor_addr_t;
template <class... Rs>
class typed_event_based_actor;
/**
* Identifies a strongly typed actor.
* @tparam Rs Interface as `replies_to<`...>::with<...> parameter pack.
*/
template <class... Rs>
class typed_actor
: detail::comparable<typed_actor<Rs...>>,
detail::comparable<typed_actor<Rs...>, actor_addr>,
detail::comparable<typed_actor<Rs...>, invalid_actor_addr_t> {
friend class local_actor;
// friend with all possible instantiations
template <class...>
friend class typed_actor;
// allow conversion via actor_cast
template <class T, typename U>
friend T actor_cast(const U&);
public:
template <class... Es>
struct extend {
using type = typed_actor<Rs..., Es...>;
};
/**
* Identifies the behavior type actors of this kind use
* for their behavior stack.
*/
using behavior_type = typed_behavior<Rs...>;
/**
* Identifies pointers to instances of this kind of actor.
*/
using pointer = typed_event_based_actor<Rs...>*;
/**
* Identifies the base class for this kind of actor.
*/
using base = typed_event_based_actor<Rs...>;
typed_actor() = default;
typed_actor(typed_actor&&) = default;
typed_actor(const typed_actor&) = default;
typed_actor& operator=(typed_actor&&) = default;
typed_actor& operator=(const typed_actor&) = default;
template <class... OtherRs>
typed_actor(const typed_actor<OtherRs...>& other) {
set(std::move(other));
}
template <class... OtherRs>
typed_actor& operator=(const typed_actor<OtherRs...>& other) {
set(std::move(other));
return *this;
}
template <class Impl>
typed_actor(intrusive_ptr<Impl> other) {
set(other);
}
abstract_actor* operator->() const {
return m_ptr.get();
}
abstract_actor& operator*() const {
return *m_ptr.get();
}
/**
* Queries the address of the stored actor.
*/
actor_addr address() const {
return m_ptr ? m_ptr->address() : actor_addr{};
}
inline intptr_t compare(const actor_addr& rhs) const {
return address().compare(rhs);
}
inline intptr_t compare(const typed_actor& other) const {
return compare(other.address());
}
inline intptr_t compare(const invalid_actor_addr_t&) const {
return m_ptr ? 1 : 0;
}
static std::set<std::string> message_types() {
return {detail::to_uniform_name<Rs>()...};
}
explicit operator bool() const { return static_cast<bool>(m_ptr); }
inline bool operator!() const { return !m_ptr; }
private:
inline abstract_actor* get() const { return m_ptr.get(); }
typed_actor(abstract_actor* ptr) : m_ptr(ptr) {}
template <class ListA, class ListB>
inline void check_signatures() {
static_assert(detail::tl_is_strict_subset<ListA, ListB>::value,
"'this' must be a strict subset of 'other'");
}
template <class... OtherRs>
inline void set(const typed_actor<OtherRs...>& other) {
check_signatures<detail::type_list<Rs...>, detail::type_list<OtherRs...>>();
m_ptr = other.m_ptr;
}
template <class Impl>
inline void set(intrusive_ptr<Impl>& other) {
check_signatures<detail::type_list<Rs...>, typename Impl::signatures>();
m_ptr = std::move(other);
}
abstract_actor_ptr m_ptr;
};
} // namespace caf
#endif // CAF_TYPED_ACTOR_HPP
<commit_msg>Fix doxygen documentation<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_TYPED_ACTOR_HPP
#define CAF_TYPED_ACTOR_HPP
#include "caf/intrusive_ptr.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/replies_to.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/typed_behavior.hpp"
namespace caf {
class actor_addr;
class local_actor;
struct invalid_actor_addr_t;
template <class... Rs>
class typed_event_based_actor;
/**
* Identifies a strongly typed actor.
* @tparam Rs Interface as `replies_to<...>::with<...>` parameter pack.
*/
template <class... Rs>
class typed_actor
: detail::comparable<typed_actor<Rs...>>,
detail::comparable<typed_actor<Rs...>, actor_addr>,
detail::comparable<typed_actor<Rs...>, invalid_actor_addr_t> {
friend class local_actor;
// friend with all possible instantiations
template <class...>
friend class typed_actor;
// allow conversion via actor_cast
template <class T, typename U>
friend T actor_cast(const U&);
public:
template <class... Es>
struct extend {
using type = typed_actor<Rs..., Es...>;
};
/**
* Identifies the behavior type actors of this kind use
* for their behavior stack.
*/
using behavior_type = typed_behavior<Rs...>;
/**
* Identifies pointers to instances of this kind of actor.
*/
using pointer = typed_event_based_actor<Rs...>*;
/**
* Identifies the base class for this kind of actor.
*/
using base = typed_event_based_actor<Rs...>;
typed_actor() = default;
typed_actor(typed_actor&&) = default;
typed_actor(const typed_actor&) = default;
typed_actor& operator=(typed_actor&&) = default;
typed_actor& operator=(const typed_actor&) = default;
template <class... OtherRs>
typed_actor(const typed_actor<OtherRs...>& other) {
set(std::move(other));
}
template <class... OtherRs>
typed_actor& operator=(const typed_actor<OtherRs...>& other) {
set(std::move(other));
return *this;
}
template <class Impl>
typed_actor(intrusive_ptr<Impl> other) {
set(other);
}
abstract_actor* operator->() const {
return m_ptr.get();
}
abstract_actor& operator*() const {
return *m_ptr.get();
}
/**
* Queries the address of the stored actor.
*/
actor_addr address() const {
return m_ptr ? m_ptr->address() : actor_addr{};
}
inline intptr_t compare(const actor_addr& rhs) const {
return address().compare(rhs);
}
inline intptr_t compare(const typed_actor& other) const {
return compare(other.address());
}
inline intptr_t compare(const invalid_actor_addr_t&) const {
return m_ptr ? 1 : 0;
}
static std::set<std::string> message_types() {
return {detail::to_uniform_name<Rs>()...};
}
explicit operator bool() const { return static_cast<bool>(m_ptr); }
inline bool operator!() const { return !m_ptr; }
private:
inline abstract_actor* get() const { return m_ptr.get(); }
typed_actor(abstract_actor* ptr) : m_ptr(ptr) {}
template <class ListA, class ListB>
inline void check_signatures() {
static_assert(detail::tl_is_strict_subset<ListA, ListB>::value,
"'this' must be a strict subset of 'other'");
}
template <class... OtherRs>
inline void set(const typed_actor<OtherRs...>& other) {
check_signatures<detail::type_list<Rs...>, detail::type_list<OtherRs...>>();
m_ptr = other.m_ptr;
}
template <class Impl>
inline void set(intrusive_ptr<Impl>& other) {
check_signatures<detail::type_list<Rs...>, typename Impl::signatures>();
m_ptr = std::move(other);
}
abstract_actor_ptr m_ptr;
};
} // namespace caf
#endif // CAF_TYPED_ACTOR_HPP
<|endoftext|> |
<commit_before>/*
* libcpu: translate_singlestep.cpp
*
* This translates a single instruction and hooks up all
* basic blocks (branch target, taken, non-taken, ...)
* so that execution will always exit after the instruction.
*/
#include "llvm/BasicBlock.h"
#include "libcpu.h"
#include "libcpu_llvm.h"
#include "disasm.h"
#include "tag.h"
#include "basicblock.h"
#include "translate.h"
//////////////////////////////////////////////////////////////////////
// single stepping
//////////////////////////////////////////////////////////////////////
BasicBlock *
create_singlestep_return_basicblock(cpu_t *cpu, addr_t new_pc, BasicBlock *bb_ret)
{
BasicBlock *bb_branch = create_basicblock(cpu, new_pc, cpu->cur_func, BB_TYPE_NORMAL);
emit_store_pc_return(cpu, bb_branch, new_pc, bb_ret);
return bb_branch;
}
BasicBlock *
cpu_translate_singlestep(cpu_t *cpu, BasicBlock *bb_ret, BasicBlock *bb_trap)
{
addr_t new_pc;
tag_t tag;
BasicBlock *cur_bb = NULL, *bb_target = NULL, *bb_next = NULL, *bb_cont = NULL;
addr_t next_pc, pc = cpu->f.get_pc(cpu, cpu->rf.grf);
cur_bb = BasicBlock::Create(_CTX(), "instruction", cpu->cur_func, 0);
if (LOGGING)
disasm_instr(cpu, pc);
cpu->f.tag_instr(cpu, pc, &tag, &new_pc, &next_pc);
/* get target basic block */
if ((tag & TAG_RET) || (new_pc == NEW_PC_NONE)) /* translate_instr() will set PC */
bb_target = bb_ret;
else if (tag & (TAG_CALL|TAG_BRANCH))
bb_target = create_singlestep_return_basicblock(cpu, new_pc, bb_ret);
/* get not-taken & conditional basic block */
if (tag & TAG_CONDITIONAL)
bb_next = create_singlestep_return_basicblock(cpu, next_pc, bb_ret);
bb_cont = translate_instr(cpu, pc, tag, bb_target, bb_trap, bb_next, cur_bb);
/* If it's not a branch, append "store PC & return" to basic block */
if (bb_cont)
emit_store_pc_return(cpu, bb_cont, next_pc, bb_ret);
return cur_bb;
}
<commit_msg>fix build<commit_after>/*
* libcpu: translate_singlestep.cpp
*
* This translates a single instruction and hooks up all
* basic blocks (branch target, taken, non-taken, ...)
* so that execution will always exit after the instruction.
*/
#include "llvm/IR/BasicBlock.h"
#include "libcpu.h"
#include "libcpu_llvm.h"
#include "disasm.h"
#include "tag.h"
#include "basicblock.h"
#include "translate.h"
//////////////////////////////////////////////////////////////////////
// single stepping
//////////////////////////////////////////////////////////////////////
BasicBlock *
create_singlestep_return_basicblock(cpu_t *cpu, addr_t new_pc, BasicBlock *bb_ret)
{
BasicBlock *bb_branch = create_basicblock(cpu, new_pc, cpu->cur_func, BB_TYPE_NORMAL);
emit_store_pc_return(cpu, bb_branch, new_pc, bb_ret);
return bb_branch;
}
BasicBlock *
cpu_translate_singlestep(cpu_t *cpu, BasicBlock *bb_ret, BasicBlock *bb_trap)
{
addr_t new_pc;
tag_t tag;
BasicBlock *cur_bb = NULL, *bb_target = NULL, *bb_next = NULL, *bb_cont = NULL;
addr_t next_pc, pc = cpu->f.get_pc(cpu, cpu->rf.grf);
cur_bb = BasicBlock::Create(_CTX(), "instruction", cpu->cur_func, 0);
if (LOGGING)
disasm_instr(cpu, pc);
cpu->f.tag_instr(cpu, pc, &tag, &new_pc, &next_pc);
/* get target basic block */
if ((tag & TAG_RET) || (new_pc == NEW_PC_NONE)) /* translate_instr() will set PC */
bb_target = bb_ret;
else if (tag & (TAG_CALL|TAG_BRANCH))
bb_target = create_singlestep_return_basicblock(cpu, new_pc, bb_ret);
/* get not-taken & conditional basic block */
if (tag & TAG_CONDITIONAL)
bb_next = create_singlestep_return_basicblock(cpu, next_pc, bb_ret);
bb_cont = translate_instr(cpu, pc, tag, bb_target, bb_trap, bb_next, cur_bb);
/* If it's not a branch, append "store PC & return" to basic block */
if (bb_cont)
emit_store_pc_return(cpu, bb_cont, next_pc, bb_ret);
return cur_bb;
}
<|endoftext|> |
<commit_before>/*
kopetexsl.cpp - Kopete XSL Routines
Copyright (c) 2003 by Jason Keirstead <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <libxslt/transform.h>
#include <libxml/parser.h>
#include <kdebug.h>
#include <kopetexsl.h>
#include <qregexp.h>
#include <qsignal.h>
//#define XSL_DEBUG 1
extern int xmlLoadExtDtdDefaultValue;
const QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString )
{
KopeteXSLThread mThread( xmlString, xslString );
mThread.start();
mThread.wait();
return mThread.result();
}
void KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString,
QObject *target, const char* slotCompleted )
{
KopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString, target, slotCompleted );
mThread->start();
}
bool KopeteXSL::isValid( const QString &xslString )
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xslDoc = NULL;
bool retVal = false;
// Convert QString into a C string
QCString xslCString = xslString.utf8();
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
retVal = true;
xsltFreeStylesheet(style_sheet);
}
else
{
xmlFreeDoc(xslDoc);
}
}
return retVal;
}
KopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted )
{
m_xml = xmlString;
m_xsl = xslString;
m_target = target;
m_slotCompleted = slotCompleted;
}
void KopeteXSLThread::run()
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xmlDoc, xslDoc, resultDoc;
//Init Stuff
xmlLoadExtDtdDefaultValue = 0;
xmlSubstituteEntitiesDefault(1);
// Convert QString into a C string
QCString xmlCString = m_xml.utf8();
QCString xslCString = m_xsl.utf8();
// Read XML docs in from memory
xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xmlDoc != NULL )
{
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
resultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL);
if( resultDoc != NULL )
{
//Save the result into the QString
xmlChar *mem;
int size;
xmlDocDumpMemory( resultDoc, &mem, &size );
m_resultString = QString::fromUtf8( QCString( (char*)mem, size + 1 ) );
delete mem;
xmlFreeDoc(resultDoc);
}
else
{
kdDebug() << "Transformed document is null!!!" << endl;
}
xsltFreeStylesheet(style_sheet);
}
else
{
kdDebug() << "Document is not valid XSL!!!" << endl;
xmlFreeDoc(xslDoc);
}
}
else
{
kdDebug() << "XSL Document could not be parsed!!!" << endl;
}
xmlFreeDoc(xmlDoc);
}
else
{
kdDebug() << "XML Document could not be parsed!!!" << endl;
}
//Signal completion
if( m_target && m_slotCompleted )
{
QSignal completeSignal( m_target );
completeSignal.connect( m_target, m_slotCompleted );
completeSignal.setValue( m_resultString );
completeSignal.activate();
delete this;
}
}
QString KopeteXSL::unescape( const QString &xml )
{
QString data = xml;
data.replace( QRegExp( QString::fromLatin1( "\"\"" ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( ">" ) ), QString::fromLatin1( ">" ) );
data.replace( QRegExp( QString::fromLatin1( "<" ) ), QString::fromLatin1( "<" ) );
data.replace( QRegExp( QString::fromLatin1( """ ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( "&" ) ), QString::fromLatin1( "&" ) );
return data;
}
<commit_msg>fix compile<commit_after>/*
kopetexsl.cpp - Kopete XSL Routines
Copyright (c) 2003 by Jason Keirstead <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxml/parser.h>
#include <kdebug.h>
#include <kopetexsl.h>
#include <qregexp.h>
#include <qsignal.h>
//#define XSL_DEBUG 1
extern int xmlLoadExtDtdDefaultValue;
const QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString )
{
KopeteXSLThread mThread( xmlString, xslString );
mThread.start();
mThread.wait();
return mThread.result();
}
void KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString,
QObject *target, const char* slotCompleted )
{
KopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString, target, slotCompleted );
mThread->start();
}
bool KopeteXSL::isValid( const QString &xslString )
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xslDoc = NULL;
bool retVal = false;
// Convert QString into a C string
QCString xslCString = xslString.utf8();
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
retVal = true;
xsltFreeStylesheet(style_sheet);
}
else
{
xmlFreeDoc(xslDoc);
}
}
return retVal;
}
KopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted )
{
m_xml = xmlString;
m_xsl = xslString;
m_target = target;
m_slotCompleted = slotCompleted;
}
void KopeteXSLThread::run()
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xmlDoc, xslDoc, resultDoc;
//Init Stuff
xmlLoadExtDtdDefaultValue = 0;
xmlSubstituteEntitiesDefault(1);
// Convert QString into a C string
QCString xmlCString = m_xml.utf8();
QCString xslCString = m_xsl.utf8();
// Read XML docs in from memory
xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xmlDoc != NULL )
{
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
resultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL);
if( resultDoc != NULL )
{
//Save the result into the QString
xmlChar *mem;
int size;
xmlDocDumpMemory( resultDoc, &mem, &size );
m_resultString = QString::fromUtf8( QCString( (char*)mem, size + 1 ) );
delete mem;
xmlFreeDoc(resultDoc);
}
else
{
kdDebug() << "Transformed document is null!!!" << endl;
}
xsltFreeStylesheet(style_sheet);
}
else
{
kdDebug() << "Document is not valid XSL!!!" << endl;
xmlFreeDoc(xslDoc);
}
}
else
{
kdDebug() << "XSL Document could not be parsed!!!" << endl;
}
xmlFreeDoc(xmlDoc);
}
else
{
kdDebug() << "XML Document could not be parsed!!!" << endl;
}
//Signal completion
if( m_target && m_slotCompleted )
{
QSignal completeSignal( m_target );
completeSignal.connect( m_target, m_slotCompleted );
completeSignal.setValue( m_resultString );
completeSignal.activate();
delete this;
}
}
QString KopeteXSL::unescape( const QString &xml )
{
QString data = xml;
data.replace( QRegExp( QString::fromLatin1( "\"\"" ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( ">" ) ), QString::fromLatin1( ">" ) );
data.replace( QRegExp( QString::fromLatin1( "<" ) ), QString::fromLatin1( "<" ) );
data.replace( QRegExp( QString::fromLatin1( """ ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( "&" ) ), QString::fromLatin1( "&" ) );
return data;
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "proxy.h"
namespace ti
{
Proxy::Proxy(const std::string& _hostname,
const std::string& _port,
const std::string& _username,
const std::string& _password)
: hostname(_hostname),
port(_port),
username(_username),
password(_password)
{
/**
* @tiapi(method=True,name=Titanium.Network.Proxy.getHostName,since=0.4) Returns the hostname of a Proxy object
* @tiresult(for=Titanium.Network.Proxy.getHostName, type=string) the hostname of the Proxy object
*/
this->SetMethod("getHostName",&Proxy::getHostName);
/**
* @tiapi(method=True,name=Titanium.Network.Proxy.getPort,since=0.4) Returns the port of a Proxy object
* @tiresult(for=Titanium.Network.Proxy.getPort, type=string) the port of the Proxy object
*/
this->SetMethod("getPort",&Proxy::getPort);
/**
* @tiapi(method=True,name=Titanium.Network.Proxy.getUserName,since=0.4) Returns the username of a Proxy object
* @tiresult(for=Titanium.Network.Proxy.getUserName, type=string) the username of the Proxy object
*/
this->SetMethod("getUserName",&Proxy::getUserName);
/**
* @tiapi(method=True,name=Titanium.Network.Proxy.getPassword,since=0.4) Returns the password of a Proxy object
* @tiresult(for=Titanium.Network.Proxy.getPassword, type=string) the password of the Proxy object
*/
this->SetMethod("getPassword",&Proxy::getPassword);
}
Proxy::~Proxy()
{
}
void Proxy::getHostName(const ValueList& args, SharedValue result)
{
result->SetString(this->hostname.c_str());
}
void Proxy::getPort(const ValueList& args, SharedValue result)
{
result->SetString(this->port.c_str());
}
void Proxy::getUserName(const ValueList& args, SharedValue result)
{
result->SetString(this->username.c_str());
}
void Proxy::getPassword(const ValueList& args, SharedValue result)
{
result->SetString(this->password.c_str());
}
}
<commit_msg>Additional fixes for the API coverage documentation<commit_after>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "proxy.h"
namespace ti
{
Proxy::Proxy(const std::string& _hostname,
const std::string& _port,
const std::string& _username,
const std::string& _password)
: hostname(_hostname),
port(_port),
username(_username),
password(_password)
{
/**
* @tiapi(method=True,name=Network.Proxy.getHostName,since=0.4) Returns the hostname of a Proxy object
* @tiresult(for=Network.Proxy.getHostName, type=string) the hostname of the Proxy object
*/
this->SetMethod("getHostName",&Proxy::getHostName);
/**
* @tiapi(method=True,name=Network.Proxy.getPort,since=0.4) Returns the port of a Proxy object
* @tiresult(for=Network.Proxy.getPort, type=string) the port of the Proxy object
*/
this->SetMethod("getPort",&Proxy::getPort);
/**
* @tiapi(method=True,name=Network.Proxy.getUserName,since=0.4) Returns the username of a Proxy object
* @tiresult(for=Network.Proxy.getUserName, type=string) the username of the Proxy object
*/
this->SetMethod("getUserName",&Proxy::getUserName);
/**
* @tiapi(method=True,name=Network.Proxy.getPassword,since=0.4) Returns the password of a Proxy object
* @tiresult(for=Network.Proxy.getPassword, type=string) the password of the Proxy object
*/
this->SetMethod("getPassword",&Proxy::getPassword);
}
Proxy::~Proxy()
{
}
void Proxy::getHostName(const ValueList& args, SharedValue result)
{
result->SetString(this->hostname.c_str());
}
void Proxy::getPort(const ValueList& args, SharedValue result)
{
result->SetString(this->port.c_str());
}
void Proxy::getUserName(const ValueList& args, SharedValue result)
{
result->SetString(this->username.c_str());
}
void Proxy::getPassword(const ValueList& args, SharedValue result)
{
result->SetString(this->password.c_str());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006 Justin Karneges
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// this code assumes the following ioctls work:
// SIOCGIFCONF - get list of devices
// SIOCGIFFLAGS - get flags about a device
// gateway detection currently only works on linux
#include "irisnetplugin.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <errno.h>
// for solaris
#ifndef SIOCGIFCONF
# include<sys/sockio.h>
#endif
class UnixIface
{
public:
QString name;
bool loopback;
QHostAddress address;
};
class UnixGateway
{
public:
QString ifaceName;
QHostAddress address;
};
static QList<UnixIface> get_sioc_ifaces()
{
QList<UnixIface> out;
int tmpsock = socket(AF_INET, SOCK_DGRAM, 0);
if(tmpsock < 0)
return out;
struct ifconf ifc;
int lastlen = 0;
QByteArray buf(100 * sizeof(struct ifreq), 0); // guess
while(1)
{
ifc.ifc_len = buf.size();
ifc.ifc_buf = buf.data();
if(ioctl(tmpsock, SIOCGIFCONF, &ifc) < 0)
{
if(errno != EINVAL || lastlen != 0)
return out;
}
else
{
// if it didn't grow since last time, then
// there's no overflow
if(ifc.ifc_len == lastlen)
break;
lastlen = ifc.ifc_len;
}
buf.resize(buf.size() + 10 * sizeof(struct ifreq));
}
buf.resize(lastlen);
int itemsize;
for(int at = 0; at < buf.size(); at += itemsize)
{
struct ifreq *ifr = (struct ifreq *)(buf.data() + at);
int sockaddr_len;
if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET)
sockaddr_len = sizeof(struct sockaddr_in);
else if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET6)
sockaddr_len = sizeof(struct sockaddr_in6);
else
sockaddr_len = sizeof(struct sockaddr);
// set this asap so the next iteration is possible
itemsize = sizeof(ifr->ifr_name) + sockaddr_len;
// skip if the family is 0 (sometimes you get empty entries)
if(ifr->ifr_addr.sa_family == 0)
continue;
// make a copy of this item to do additional ioctls on
struct ifreq ifrcopy = *ifr;
// grab the flags
if(ioctl(tmpsock, SIOCGIFFLAGS, &ifrcopy) < 0)
continue;
// device must be up and not loopback
if(!(ifrcopy.ifr_flags & IFF_UP))
continue;
UnixIface i;
i.name = QString::fromLatin1(ifr->ifr_name);
i.loopback = (ifrcopy.ifr_flags & IFF_LOOPBACK) ? true : false;
i.address.setAddress(&ifr->ifr_addr);
out += i;
}
// don't need this anymore
close(tmpsock);
return out;
}
#ifdef Q_OS_LINUX
static QStringList read_proc_as_lines(const char *procfile)
{
QStringList out;
FILE *f = fopen(procfile, "r");
if(!f)
return out;
QByteArray buf;
while(!feof(f))
{
// max read on a proc is 4K
QByteArray block(4096, 0);
int ret = fread(block.data(), 1, block.size(), f);
if(ret <= 0)
break;
block.resize(ret);
buf += block;
}
fclose(f);
QString str = QString::fromLocal8Bit(buf);
out = str.split('\n', QString::SkipEmptyParts);
return out;
}
static QHostAddress linux_ipv6_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 32)
return out;
quint8 raw[16];
for(int n = 0; n < 16; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
raw[n] = (quint8)x;
}
out.setAddress(raw);
return out;
}
static QHostAddress linux_ipv4_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 8)
return out;
quint32 raw;
unsigned char *rawp = (unsigned char *)&raw;
for(int n = 0; n < 4; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
rawp[n] = (unsigned char )x;
}
out.setAddress(raw);
return out;
}
static QList<UnixIface> get_linux_ipv6_ifaces()
{
QList<UnixIface> out;
QStringList lines = read_proc_as_lines("/proc/net/if_inet6");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 6)
continue;
QString name = parts[5];
if(name.isEmpty())
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[0]);
if(addr.isNull())
continue;
QString scopestr = parts[3];
bool ok;
unsigned int scope = parts[3].toInt(&ok, 16);
if(!ok)
continue;
// IPV6_ADDR_LOOPBACK 0x0010U
// IPV6_ADDR_SCOPE_MASK 0x00f0U
bool loopback = false;
if((scope & 0x00f0U) == 0x0010U)
loopback = true;
UnixIface i;
i.name = name;
i.loopback = loopback;
i.address = addr;
out += i;
}
return out;
}
static QList<UnixGateway> get_linux_gateways()
{
QList<UnixGateway> out;
QStringList lines = read_proc_as_lines("/proc/net/route");
// skip the first line, so we start at 1
for(int n = 1; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10) // net-tools does 10, but why not 11?
continue;
QHostAddress addr = linux_ipv4_to_qaddr(parts[2]);
if(addr.isNull())
continue;
int iflags = parts[3].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[0];
g.address = addr;
out += g;
}
lines = read_proc_as_lines("/proc/net/ipv6_route");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10)
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[4]);
if(addr.isNull())
continue;
int iflags = parts[8].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[9];
g.address = addr;
out += g;
}
return out;
}
#endif
static QList<UnixIface> get_unix_ifaces()
{
QList<UnixIface> out = get_sioc_ifaces();
#ifdef Q_OS_LINUX
out += get_linux_ipv6_ifaces();
#endif
return out;
}
static QList<UnixGateway> get_unix_gateways()
{
// support other platforms here
QList<UnixGateway> out;
#ifdef Q_OS_LINUX
out = get_linux_gateways();
#endif
return out;
}
namespace XMPP {
class UnixNet : public NetInterfaceProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::NetInterfaceProvider)
public:
QList<Info> info;
QTimer t;
UnixNet() : t(this)
{
connect(&t, SIGNAL(timeout()), SLOT(check()));
}
void start()
{
t.start(5000);
poll();
}
QList<Info> interfaces() const
{
return info;
}
void poll()
{
QList<Info> ifaces;
QList<UnixIface> list = get_unix_ifaces();
for(int n = 0; n < list.count(); ++n)
{
// see if we have it already
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == list[n].name)
{
lookup = k;
break;
}
}
// don't have it? make it
if(lookup == -1)
{
Info i;
i.id = list[n].name;
i.name = list[n].name;
i.isLoopback = list[n].loopback;
i.addresses += list[n].address;
ifaces += i;
}
// otherwise, tack on the address
else
ifaces[lookup].addresses += list[n].address;
}
QList<UnixGateway> glist = get_unix_gateways();
for(int n = 0; n < glist.count(); ++n)
{
// look up the interface
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == glist[n].ifaceName)
{
lookup = k;
break;
}
}
if(lookup == -1)
break;
ifaces[lookup].gateway = glist[n].address;
}
info = ifaces;
}
public slots:
void check()
{
poll();
emit updated();
}
};
class UnixNetProvider : public IrisNetProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::IrisNetProvider)
public:
virtual NetInterfaceProvider *createNetInterfaceProvider()
{
return new UnixNet;
}
};
IrisNetProvider *irisnet_createUnixNetProvider()
{
return new UnixNetProvider;
}
}
#include "netinterface_unix.moc"
<commit_msg>SVN_SILENT compile<commit_after>/*
* Copyright (C) 2006 Justin Karneges
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// this code assumes the following ioctls work:
// SIOCGIFCONF - get list of devices
// SIOCGIFFLAGS - get flags about a device
// gateway detection currently only works on linux
#include "irisnetplugin.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
// for solaris
#ifndef SIOCGIFCONF
# include<sys/sockio.h>
#endif
class UnixIface
{
public:
QString name;
bool loopback;
QHostAddress address;
};
class UnixGateway
{
public:
QString ifaceName;
QHostAddress address;
};
static QList<UnixIface> get_sioc_ifaces()
{
QList<UnixIface> out;
int tmpsock = socket(AF_INET, SOCK_DGRAM, 0);
if(tmpsock < 0)
return out;
struct ifconf ifc;
int lastlen = 0;
QByteArray buf(100 * sizeof(struct ifreq), 0); // guess
while(1)
{
ifc.ifc_len = buf.size();
ifc.ifc_buf = buf.data();
if(ioctl(tmpsock, SIOCGIFCONF, &ifc) < 0)
{
if(errno != EINVAL || lastlen != 0)
return out;
}
else
{
// if it didn't grow since last time, then
// there's no overflow
if(ifc.ifc_len == lastlen)
break;
lastlen = ifc.ifc_len;
}
buf.resize(buf.size() + 10 * sizeof(struct ifreq));
}
buf.resize(lastlen);
int itemsize;
for(int at = 0; at < buf.size(); at += itemsize)
{
struct ifreq *ifr = (struct ifreq *)(buf.data() + at);
int sockaddr_len;
if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET)
sockaddr_len = sizeof(struct sockaddr_in);
else if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET6)
sockaddr_len = sizeof(struct sockaddr_in6);
else
sockaddr_len = sizeof(struct sockaddr);
// set this asap so the next iteration is possible
itemsize = sizeof(ifr->ifr_name) + sockaddr_len;
// skip if the family is 0 (sometimes you get empty entries)
if(ifr->ifr_addr.sa_family == 0)
continue;
// make a copy of this item to do additional ioctls on
struct ifreq ifrcopy = *ifr;
// grab the flags
if(ioctl(tmpsock, SIOCGIFFLAGS, &ifrcopy) < 0)
continue;
// device must be up and not loopback
if(!(ifrcopy.ifr_flags & IFF_UP))
continue;
UnixIface i;
i.name = QString::fromLatin1(ifr->ifr_name);
i.loopback = (ifrcopy.ifr_flags & IFF_LOOPBACK) ? true : false;
i.address.setAddress(&ifr->ifr_addr);
out += i;
}
// don't need this anymore
close(tmpsock);
return out;
}
#ifdef Q_OS_LINUX
static QStringList read_proc_as_lines(const char *procfile)
{
QStringList out;
FILE *f = fopen(procfile, "r");
if(!f)
return out;
QByteArray buf;
while(!feof(f))
{
// max read on a proc is 4K
QByteArray block(4096, 0);
int ret = fread(block.data(), 1, block.size(), f);
if(ret <= 0)
break;
block.resize(ret);
buf += block;
}
fclose(f);
QString str = QString::fromLocal8Bit(buf);
out = str.split('\n', QString::SkipEmptyParts);
return out;
}
static QHostAddress linux_ipv6_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 32)
return out;
quint8 raw[16];
for(int n = 0; n < 16; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
raw[n] = (quint8)x;
}
out.setAddress(raw);
return out;
}
static QHostAddress linux_ipv4_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 8)
return out;
quint32 raw;
unsigned char *rawp = (unsigned char *)&raw;
for(int n = 0; n < 4; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
rawp[n] = (unsigned char )x;
}
out.setAddress(raw);
return out;
}
static QList<UnixIface> get_linux_ipv6_ifaces()
{
QList<UnixIface> out;
QStringList lines = read_proc_as_lines("/proc/net/if_inet6");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 6)
continue;
QString name = parts[5];
if(name.isEmpty())
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[0]);
if(addr.isNull())
continue;
QString scopestr = parts[3];
bool ok;
unsigned int scope = parts[3].toInt(&ok, 16);
if(!ok)
continue;
// IPV6_ADDR_LOOPBACK 0x0010U
// IPV6_ADDR_SCOPE_MASK 0x00f0U
bool loopback = false;
if((scope & 0x00f0U) == 0x0010U)
loopback = true;
UnixIface i;
i.name = name;
i.loopback = loopback;
i.address = addr;
out += i;
}
return out;
}
static QList<UnixGateway> get_linux_gateways()
{
QList<UnixGateway> out;
QStringList lines = read_proc_as_lines("/proc/net/route");
// skip the first line, so we start at 1
for(int n = 1; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10) // net-tools does 10, but why not 11?
continue;
QHostAddress addr = linux_ipv4_to_qaddr(parts[2]);
if(addr.isNull())
continue;
int iflags = parts[3].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[0];
g.address = addr;
out += g;
}
lines = read_proc_as_lines("/proc/net/ipv6_route");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10)
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[4]);
if(addr.isNull())
continue;
int iflags = parts[8].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[9];
g.address = addr;
out += g;
}
return out;
}
#endif
static QList<UnixIface> get_unix_ifaces()
{
QList<UnixIface> out = get_sioc_ifaces();
#ifdef Q_OS_LINUX
out += get_linux_ipv6_ifaces();
#endif
return out;
}
static QList<UnixGateway> get_unix_gateways()
{
// support other platforms here
QList<UnixGateway> out;
#ifdef Q_OS_LINUX
out = get_linux_gateways();
#endif
return out;
}
namespace XMPP {
class UnixNet : public NetInterfaceProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::NetInterfaceProvider)
public:
QList<Info> info;
QTimer t;
UnixNet() : t(this)
{
connect(&t, SIGNAL(timeout()), SLOT(check()));
}
void start()
{
t.start(5000);
poll();
}
QList<Info> interfaces() const
{
return info;
}
void poll()
{
QList<Info> ifaces;
QList<UnixIface> list = get_unix_ifaces();
for(int n = 0; n < list.count(); ++n)
{
// see if we have it already
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == list[n].name)
{
lookup = k;
break;
}
}
// don't have it? make it
if(lookup == -1)
{
Info i;
i.id = list[n].name;
i.name = list[n].name;
i.isLoopback = list[n].loopback;
i.addresses += list[n].address;
ifaces += i;
}
// otherwise, tack on the address
else
ifaces[lookup].addresses += list[n].address;
}
QList<UnixGateway> glist = get_unix_gateways();
for(int n = 0; n < glist.count(); ++n)
{
// look up the interface
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == glist[n].ifaceName)
{
lookup = k;
break;
}
}
if(lookup == -1)
break;
ifaces[lookup].gateway = glist[n].address;
}
info = ifaces;
}
public slots:
void check()
{
poll();
emit updated();
}
};
class UnixNetProvider : public IrisNetProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::IrisNetProvider)
public:
virtual NetInterfaceProvider *createNetInterfaceProvider()
{
return new UnixNet;
}
};
IrisNetProvider *irisnet_createUnixNetProvider()
{
return new UnixNetProvider;
}
}
#include "netinterface_unix.moc"
<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
JITObjTypeSpecFldInfo::JITObjTypeSpecFldInfo(ObjTypeSpecFldIDL * data) :
m_data(*data)
{
CompileAssert(sizeof(ObjTypeSpecFldIDL) == sizeof(JITObjTypeSpecFldInfo));
}
bool
JITObjTypeSpecFldInfo::UsesAuxSlot() const
{
return GetFlags().usesAuxSlot;
}
bool
JITObjTypeSpecFldInfo::UsesAccessor() const
{
return GetFlags().usesAccessor;
}
bool
JITObjTypeSpecFldInfo::IsRootObjectNonConfigurableFieldLoad() const
{
return GetFlags().isRootObjectNonConfigurableFieldLoad;
}
bool
JITObjTypeSpecFldInfo::HasEquivalentTypeSet() const
{
return m_data.typeSet != nullptr;
}
bool
JITObjTypeSpecFldInfo::DoesntHaveEquivalence() const
{
return GetFlags().doesntHaveEquivalence;
}
bool
JITObjTypeSpecFldInfo::IsPoly() const
{
return GetFlags().isPolymorphic;
}
bool
JITObjTypeSpecFldInfo::IsMono() const
{
return !IsPoly();
}
bool
JITObjTypeSpecFldInfo::IsBuiltIn() const
{
return GetFlags().isBuiltIn;
}
bool
JITObjTypeSpecFldInfo::IsLoadedFromProto() const
{
return GetFlags().isLoadedFromProto;
}
bool
JITObjTypeSpecFldInfo::HasFixedValue() const
{
return GetFlags().hasFixedValue;
}
bool
JITObjTypeSpecFldInfo::IsBeingStored() const
{
return GetFlags().isBeingStored;
}
bool
JITObjTypeSpecFldInfo::IsBeingAdded() const
{
return GetFlags().isBeingAdded;
}
bool
JITObjTypeSpecFldInfo::IsRootObjectNonConfigurableField() const
{
return GetFlags().isRootObjectNonConfigurableField;
}
bool
JITObjTypeSpecFldInfo::HasInitialType() const
{
return IsMono() && !IsLoadedFromProto() && m_data.initialType != nullptr;
}
bool
JITObjTypeSpecFldInfo::IsMonoObjTypeSpecCandidate() const
{
return IsMono();
}
bool
JITObjTypeSpecFldInfo::IsPolyObjTypeSpecCandidate() const
{
return IsPoly();
}
Js::TypeId
JITObjTypeSpecFldInfo::GetTypeId() const
{
Assert(m_data.typeId != Js::TypeIds_Limit);
return (Js::TypeId)m_data.typeId;
}
Js::TypeId
JITObjTypeSpecFldInfo::GetTypeId(uint i) const
{
Assert(IsPoly());
return (Js::TypeId)m_data.fixedFieldInfoArray[i].type->typeId;
}
Js::PropertyId
JITObjTypeSpecFldInfo::GetPropertyId() const
{
return (Js::PropertyId)m_data.propertyId;
}
uint16
JITObjTypeSpecFldInfo::GetSlotIndex() const
{
return m_data.slotIndex;
}
uint16
JITObjTypeSpecFldInfo::GetFixedFieldCount() const
{
return m_data.fixedFieldCount;
}
uint
JITObjTypeSpecFldInfo::GetObjTypeSpecFldId() const
{
return m_data.id;
}
intptr_t
JITObjTypeSpecFldInfo::GetProtoObject() const
{
return m_data.protoObjectAddr;
}
intptr_t
JITObjTypeSpecFldInfo::GetFieldValue(uint i) const
{
Assert(IsPoly());
return m_data.fixedFieldInfoArray[i].fieldValue;
}
intptr_t
JITObjTypeSpecFldInfo::GetPropertyGuardValueAddr() const
{
return m_data.propertyGuardValueAddr;
}
intptr_t
JITObjTypeSpecFldInfo::GetFieldValueAsFixedDataIfAvailable() const
{
Assert(HasFixedValue() && GetFixedFieldCount() == 1);
return m_data.fixedFieldInfoArray[0].fieldValue;
}
JITTimeConstructorCache *
JITObjTypeSpecFldInfo::GetCtorCache() const
{
return (JITTimeConstructorCache*)m_data.ctorCache;
}
Js::EquivalentTypeSet *
JITObjTypeSpecFldInfo::GetEquivalentTypeSet() const
{
return (Js::EquivalentTypeSet *)m_data.typeSet;
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetType() const
{
Assert(IsMono());
return JITTypeHolder((JITType *)m_data.fixedFieldInfoArray[0].type);
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetType(uint i) const
{
Assert(IsPoly());
return JITTypeHolder((JITType *)m_data.fixedFieldInfoArray[i].type);
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetInitialType() const
{
return JITTypeHolder((JITType *)m_data.initialType);
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetFirstEquivalentType() const
{
Assert(HasEquivalentTypeSet());
return JITTypeHolder(GetEquivalentTypeSet()->GetFirstType());
}
void
JITObjTypeSpecFldInfo::SetIsBeingStored(bool value)
{
((Js::ObjTypeSpecFldInfoFlags*)&m_data.flags)->isBeingStored = value;
}
JITTimeFixedField *
JITObjTypeSpecFldInfo::GetFixedFieldIfAvailableAsFixedFunction()
{
Assert(HasFixedValue());
Assert(IsMono() || (IsPoly() && !DoesntHaveEquivalence()));
Assert(m_data.fixedFieldInfoArray);
if (m_data.fixedFieldInfoArray[0].funcInfoAddr != 0)
{
return (JITTimeFixedField *)&m_data.fixedFieldInfoArray[0];
}
return nullptr;
}
JITTimeFixedField *
JITObjTypeSpecFldInfo::GetFixedFieldIfAvailableAsFixedFunction(uint i)
{
Assert(HasFixedValue());
Assert(IsPoly());
if (m_data.fixedFieldCount > 0 && m_data.fixedFieldInfoArray[i].funcInfoAddr != 0)
{
return (JITTimeFixedField *)&m_data.fixedFieldInfoArray[i];
}
return nullptr;
}
JITTimeFixedField *
JITObjTypeSpecFldInfo::GetFixedFieldInfoArray()
{
return (JITTimeFixedField*)m_data.fixedFieldInfoArray;
}
/* static */
void
JITObjTypeSpecFldInfo::BuildObjTypeSpecFldInfoArray(
__in ArenaAllocator * alloc,
__in Js::ObjTypeSpecFldInfo ** objTypeSpecInfo,
__in uint arrayLength,
_Inout_updates_(arrayLength) ObjTypeSpecFldIDL * jitData)
{
for (uint i = 0; i < arrayLength; ++i)
{
if (objTypeSpecInfo[i] == nullptr)
{
continue;
}
jitData[i].inUse = TRUE;
if (objTypeSpecInfo[i]->IsLoadedFromProto())
{
jitData[i].protoObjectAddr = (intptr_t)objTypeSpecInfo[i]->GetProtoObject();
}
jitData[i].propertyGuardValueAddr = (intptr_t)objTypeSpecInfo[i]->GetPropertyGuard()->GetAddressOfValue();
jitData[i].propertyId = objTypeSpecInfo[i]->GetPropertyId();
jitData[i].typeId = objTypeSpecInfo[i]->GetTypeId();
jitData[i].id = objTypeSpecInfo[i]->GetObjTypeSpecFldId();
jitData[i].flags = objTypeSpecInfo[i]->GetFlags();
jitData[i].slotIndex = objTypeSpecInfo[i]->GetSlotIndex();
jitData[i].fixedFieldCount = objTypeSpecInfo[i]->GetFixedFieldCount();
if (objTypeSpecInfo[i]->HasInitialType())
{
jitData[i].initialType = AnewStructZ(alloc, TypeIDL);
JITType::BuildFromJsType(objTypeSpecInfo[i]->GetInitialType(), (JITType*)jitData[i].initialType);
}
if (objTypeSpecInfo[i]->GetCtorCache() != nullptr)
{
jitData[i].ctorCache = objTypeSpecInfo[i]->GetCtorCache()->GetData();
}
CompileAssert(sizeof(Js::EquivalentTypeSet) == sizeof(EquivalentTypeSetIDL));
Js::EquivalentTypeSet * equivTypeSet = objTypeSpecInfo[i]->GetEquivalentTypeSet();
if (equivTypeSet != nullptr)
{
jitData[i].typeSet = (EquivalentTypeSetIDL*)equivTypeSet;
}
jitData[i].fixedFieldInfoArraySize = jitData[i].fixedFieldCount;
if (jitData[i].fixedFieldInfoArraySize == 0)
{
jitData[i].fixedFieldInfoArraySize = 1;
}
jitData[i].fixedFieldInfoArray = AnewArrayZ(alloc, FixedFieldIDL, jitData[i].fixedFieldInfoArraySize);
Js::FixedFieldInfo * ffInfo = objTypeSpecInfo[i]->GetFixedFieldInfoArray();
for (uint16 j = 0; j < jitData[i].fixedFieldInfoArraySize; ++j)
{
jitData[i].fixedFieldInfoArray[j].fieldValue = (intptr_t)ffInfo[j].fieldValue;
jitData[i].fixedFieldInfoArray[j].nextHasSameFixedField = ffInfo[j].nextHasSameFixedField;
if (ffInfo[j].fieldValue != nullptr && Js::JavascriptFunction::Is(ffInfo[j].fieldValue))
{
Js::JavascriptFunction * funcObj = Js::JavascriptFunction::FromVar(ffInfo[j].fieldValue);
jitData[i].fixedFieldInfoArray[j].valueType = ValueType::FromObject(funcObj).GetRawData();
jitData[i].fixedFieldInfoArray[j].funcInfoAddr = (intptr_t)funcObj->GetFunctionInfo();
jitData[i].fixedFieldInfoArray[j].isClassCtor = funcObj->GetFunctionInfo()->IsConstructor();
jitData[i].fixedFieldInfoArray[j].localFuncId = (intptr_t)funcObj->GetFunctionInfo()->GetLocalFunctionId();
if (Js::ScriptFunction::Is(ffInfo[j].fieldValue))
{
jitData[i].fixedFieldInfoArray[j].environmentAddr = (intptr_t)Js::ScriptFunction::FromVar(funcObj)->GetEnvironment();
}
}
if (ffInfo[j].type != nullptr)
{
jitData[i].fixedFieldInfoArray[j].type = AnewStructZ(alloc, TypeIDL);
// TODO: OOP JIT, maybe type should be out of line? might not save anything on x64 though
JITType::BuildFromJsType(ffInfo[j].type, (JITType*)jitData[i].fixedFieldInfoArray[j].type);
}
}
}
}
Js::ObjTypeSpecFldInfoFlags
JITObjTypeSpecFldInfo::GetFlags() const
{
return (Js::ObjTypeSpecFldInfoFlags)m_data.flags;
}
<commit_msg>fix condition for fixed class ctors<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
JITObjTypeSpecFldInfo::JITObjTypeSpecFldInfo(ObjTypeSpecFldIDL * data) :
m_data(*data)
{
CompileAssert(sizeof(ObjTypeSpecFldIDL) == sizeof(JITObjTypeSpecFldInfo));
}
bool
JITObjTypeSpecFldInfo::UsesAuxSlot() const
{
return GetFlags().usesAuxSlot;
}
bool
JITObjTypeSpecFldInfo::UsesAccessor() const
{
return GetFlags().usesAccessor;
}
bool
JITObjTypeSpecFldInfo::IsRootObjectNonConfigurableFieldLoad() const
{
return GetFlags().isRootObjectNonConfigurableFieldLoad;
}
bool
JITObjTypeSpecFldInfo::HasEquivalentTypeSet() const
{
return m_data.typeSet != nullptr;
}
bool
JITObjTypeSpecFldInfo::DoesntHaveEquivalence() const
{
return GetFlags().doesntHaveEquivalence;
}
bool
JITObjTypeSpecFldInfo::IsPoly() const
{
return GetFlags().isPolymorphic;
}
bool
JITObjTypeSpecFldInfo::IsMono() const
{
return !IsPoly();
}
bool
JITObjTypeSpecFldInfo::IsBuiltIn() const
{
return GetFlags().isBuiltIn;
}
bool
JITObjTypeSpecFldInfo::IsLoadedFromProto() const
{
return GetFlags().isLoadedFromProto;
}
bool
JITObjTypeSpecFldInfo::HasFixedValue() const
{
return GetFlags().hasFixedValue;
}
bool
JITObjTypeSpecFldInfo::IsBeingStored() const
{
return GetFlags().isBeingStored;
}
bool
JITObjTypeSpecFldInfo::IsBeingAdded() const
{
return GetFlags().isBeingAdded;
}
bool
JITObjTypeSpecFldInfo::IsRootObjectNonConfigurableField() const
{
return GetFlags().isRootObjectNonConfigurableField;
}
bool
JITObjTypeSpecFldInfo::HasInitialType() const
{
return IsMono() && !IsLoadedFromProto() && m_data.initialType != nullptr;
}
bool
JITObjTypeSpecFldInfo::IsMonoObjTypeSpecCandidate() const
{
return IsMono();
}
bool
JITObjTypeSpecFldInfo::IsPolyObjTypeSpecCandidate() const
{
return IsPoly();
}
Js::TypeId
JITObjTypeSpecFldInfo::GetTypeId() const
{
Assert(m_data.typeId != Js::TypeIds_Limit);
return (Js::TypeId)m_data.typeId;
}
Js::TypeId
JITObjTypeSpecFldInfo::GetTypeId(uint i) const
{
Assert(IsPoly());
return (Js::TypeId)m_data.fixedFieldInfoArray[i].type->typeId;
}
Js::PropertyId
JITObjTypeSpecFldInfo::GetPropertyId() const
{
return (Js::PropertyId)m_data.propertyId;
}
uint16
JITObjTypeSpecFldInfo::GetSlotIndex() const
{
return m_data.slotIndex;
}
uint16
JITObjTypeSpecFldInfo::GetFixedFieldCount() const
{
return m_data.fixedFieldCount;
}
uint
JITObjTypeSpecFldInfo::GetObjTypeSpecFldId() const
{
return m_data.id;
}
intptr_t
JITObjTypeSpecFldInfo::GetProtoObject() const
{
return m_data.protoObjectAddr;
}
intptr_t
JITObjTypeSpecFldInfo::GetFieldValue(uint i) const
{
Assert(IsPoly());
return m_data.fixedFieldInfoArray[i].fieldValue;
}
intptr_t
JITObjTypeSpecFldInfo::GetPropertyGuardValueAddr() const
{
return m_data.propertyGuardValueAddr;
}
intptr_t
JITObjTypeSpecFldInfo::GetFieldValueAsFixedDataIfAvailable() const
{
Assert(HasFixedValue() && GetFixedFieldCount() == 1);
return m_data.fixedFieldInfoArray[0].fieldValue;
}
JITTimeConstructorCache *
JITObjTypeSpecFldInfo::GetCtorCache() const
{
return (JITTimeConstructorCache*)m_data.ctorCache;
}
Js::EquivalentTypeSet *
JITObjTypeSpecFldInfo::GetEquivalentTypeSet() const
{
return (Js::EquivalentTypeSet *)m_data.typeSet;
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetType() const
{
Assert(IsMono());
return JITTypeHolder((JITType *)m_data.fixedFieldInfoArray[0].type);
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetType(uint i) const
{
Assert(IsPoly());
return JITTypeHolder((JITType *)m_data.fixedFieldInfoArray[i].type);
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetInitialType() const
{
return JITTypeHolder((JITType *)m_data.initialType);
}
JITTypeHolder
JITObjTypeSpecFldInfo::GetFirstEquivalentType() const
{
Assert(HasEquivalentTypeSet());
return JITTypeHolder(GetEquivalentTypeSet()->GetFirstType());
}
void
JITObjTypeSpecFldInfo::SetIsBeingStored(bool value)
{
((Js::ObjTypeSpecFldInfoFlags*)&m_data.flags)->isBeingStored = value;
}
JITTimeFixedField *
JITObjTypeSpecFldInfo::GetFixedFieldIfAvailableAsFixedFunction()
{
Assert(HasFixedValue());
Assert(IsMono() || (IsPoly() && !DoesntHaveEquivalence()));
Assert(m_data.fixedFieldInfoArray);
if (m_data.fixedFieldInfoArray[0].funcInfoAddr != 0)
{
return (JITTimeFixedField *)&m_data.fixedFieldInfoArray[0];
}
return nullptr;
}
JITTimeFixedField *
JITObjTypeSpecFldInfo::GetFixedFieldIfAvailableAsFixedFunction(uint i)
{
Assert(HasFixedValue());
Assert(IsPoly());
if (m_data.fixedFieldCount > 0 && m_data.fixedFieldInfoArray[i].funcInfoAddr != 0)
{
return (JITTimeFixedField *)&m_data.fixedFieldInfoArray[i];
}
return nullptr;
}
JITTimeFixedField *
JITObjTypeSpecFldInfo::GetFixedFieldInfoArray()
{
return (JITTimeFixedField*)m_data.fixedFieldInfoArray;
}
/* static */
void
JITObjTypeSpecFldInfo::BuildObjTypeSpecFldInfoArray(
__in ArenaAllocator * alloc,
__in Js::ObjTypeSpecFldInfo ** objTypeSpecInfo,
__in uint arrayLength,
_Inout_updates_(arrayLength) ObjTypeSpecFldIDL * jitData)
{
for (uint i = 0; i < arrayLength; ++i)
{
if (objTypeSpecInfo[i] == nullptr)
{
continue;
}
jitData[i].inUse = TRUE;
if (objTypeSpecInfo[i]->IsLoadedFromProto())
{
jitData[i].protoObjectAddr = (intptr_t)objTypeSpecInfo[i]->GetProtoObject();
}
jitData[i].propertyGuardValueAddr = (intptr_t)objTypeSpecInfo[i]->GetPropertyGuard()->GetAddressOfValue();
jitData[i].propertyId = objTypeSpecInfo[i]->GetPropertyId();
jitData[i].typeId = objTypeSpecInfo[i]->GetTypeId();
jitData[i].id = objTypeSpecInfo[i]->GetObjTypeSpecFldId();
jitData[i].flags = objTypeSpecInfo[i]->GetFlags();
jitData[i].slotIndex = objTypeSpecInfo[i]->GetSlotIndex();
jitData[i].fixedFieldCount = objTypeSpecInfo[i]->GetFixedFieldCount();
if (objTypeSpecInfo[i]->HasInitialType())
{
jitData[i].initialType = AnewStructZ(alloc, TypeIDL);
JITType::BuildFromJsType(objTypeSpecInfo[i]->GetInitialType(), (JITType*)jitData[i].initialType);
}
if (objTypeSpecInfo[i]->GetCtorCache() != nullptr)
{
jitData[i].ctorCache = objTypeSpecInfo[i]->GetCtorCache()->GetData();
}
CompileAssert(sizeof(Js::EquivalentTypeSet) == sizeof(EquivalentTypeSetIDL));
Js::EquivalentTypeSet * equivTypeSet = objTypeSpecInfo[i]->GetEquivalentTypeSet();
if (equivTypeSet != nullptr)
{
jitData[i].typeSet = (EquivalentTypeSetIDL*)equivTypeSet;
}
jitData[i].fixedFieldInfoArraySize = jitData[i].fixedFieldCount;
if (jitData[i].fixedFieldInfoArraySize == 0)
{
jitData[i].fixedFieldInfoArraySize = 1;
}
jitData[i].fixedFieldInfoArray = AnewArrayZ(alloc, FixedFieldIDL, jitData[i].fixedFieldInfoArraySize);
Js::FixedFieldInfo * ffInfo = objTypeSpecInfo[i]->GetFixedFieldInfoArray();
for (uint16 j = 0; j < jitData[i].fixedFieldInfoArraySize; ++j)
{
jitData[i].fixedFieldInfoArray[j].fieldValue = (intptr_t)ffInfo[j].fieldValue;
jitData[i].fixedFieldInfoArray[j].nextHasSameFixedField = ffInfo[j].nextHasSameFixedField;
if (ffInfo[j].fieldValue != nullptr && Js::JavascriptFunction::Is(ffInfo[j].fieldValue))
{
Js::JavascriptFunction * funcObj = Js::JavascriptFunction::FromVar(ffInfo[j].fieldValue);
jitData[i].fixedFieldInfoArray[j].valueType = ValueType::FromObject(funcObj).GetRawData();
jitData[i].fixedFieldInfoArray[j].funcInfoAddr = (intptr_t)funcObj->GetFunctionInfo();
jitData[i].fixedFieldInfoArray[j].isClassCtor = funcObj->GetFunctionInfo()->IsClassConstructor();
jitData[i].fixedFieldInfoArray[j].localFuncId = (intptr_t)funcObj->GetFunctionInfo()->GetLocalFunctionId();
if (Js::ScriptFunction::Is(ffInfo[j].fieldValue))
{
jitData[i].fixedFieldInfoArray[j].environmentAddr = (intptr_t)Js::ScriptFunction::FromVar(funcObj)->GetEnvironment();
}
}
if (ffInfo[j].type != nullptr)
{
jitData[i].fixedFieldInfoArray[j].type = AnewStructZ(alloc, TypeIDL);
// TODO: OOP JIT, maybe type should be out of line? might not save anything on x64 though
JITType::BuildFromJsType(ffInfo[j].type, (JITType*)jitData[i].fixedFieldInfoArray[j].type);
}
}
}
}
Js::ObjTypeSpecFldInfoFlags
JITObjTypeSpecFldInfo::GetFlags() const
{
return (Js::ObjTypeSpecFldInfoFlags)m_data.flags;
}
<|endoftext|> |
<commit_before>//===-- Intercept.cpp - System function interception routines -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// If a function call occurs to an external function, the JIT is designed to use
// the dynamic loader interface to find a function to call. This is useful for
// calling system calls and library functions that are not available in LLVM.
// Some system calls, however, need to be handled specially. For this reason,
// we intercept some of them here and use our own stubs to handle them.
//
//===----------------------------------------------------------------------===//
#include "JIT.h"
#include "llvm/System/DynamicLibrary.h"
#include "llvm/Config/config.h"
using namespace llvm;
// AtExitHandlers - List of functions to call when the program exits,
// registered with the atexit() library function.
static std::vector<void (*)()> AtExitHandlers;
/// runAtExitHandlers - Run any functions registered by the program's
/// calls to atexit(3), which we intercept and store in
/// AtExitHandlers.
///
static void runAtExitHandlers() {
while (!AtExitHandlers.empty()) {
void (*Fn)() = AtExitHandlers.back();
AtExitHandlers.pop_back();
Fn();
}
}
//===----------------------------------------------------------------------===//
// Function stubs that are invoked instead of certain library calls
//===----------------------------------------------------------------------===//
// Force the following functions to be linked in to anything that uses the
// JIT. This is a hack designed to work around the all-too-clever Glibc
// strategy of making these functions work differently when inlined vs. when
// not inlined, and hiding their real definitions in a separate archive file
// that the dynamic linker can't see. For more info, search for
// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
#if defined(__linux__)
#if defined(HAVE_SYS_STAT_H)
#include <sys/stat.h>
#endif
void *FunctionPointers[] = {
(void *)(intptr_t) stat,
(void *)(intptr_t) fstat,
(void *)(intptr_t) lstat,
(void *)(intptr_t) stat64,
(void *)(intptr_t) fstat64,
(void *)(intptr_t) lstat64,
(void *)(intptr_t) atexit,
(void *)(intptr_t) mknod
};
#endif // __linux__
// jit_exit - Used to intercept the "exit" library call.
static void jit_exit(int Status) {
runAtExitHandlers(); // Run atexit handlers...
exit(Status);
}
// jit_atexit - Used to intercept the "atexit" library call.
static int jit_atexit(void (*Fn)(void)) {
AtExitHandlers.push_back(Fn); // Take note of atexit handler...
return 0; // Always successful
}
//===----------------------------------------------------------------------===//
//
/// getPointerToNamedFunction - This method returns the address of the specified
/// function by using the dynamic loader interface. As such it is only useful
/// for resolving library symbols, not code generated symbols.
///
void *JIT::getPointerToNamedFunction(const std::string &Name) {
// Check to see if this is one of the functions we want to intercept. Note,
// we cast to intptr_t here to silence a -pedantic warning that complains
// about casting a function pointer to a normal pointer.
if (Name == "exit") return (void*)(intptr_t)&jit_exit;
if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
const char *NameStr = Name.c_str();
// If this is an asm specifier, skip the sentinal.
if (NameStr[0] == 1) ++NameStr;
// If it's an external function, look it up in the process image...
void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
if (Ptr) return Ptr;
// If it wasn't found and if it starts with an underscore ('_') character, and
// has an asm specifier, try again without the underscore.
if (Name[0] == 1 && NameStr[0] == '_') {
Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
if (Ptr) return Ptr;
}
// darwin/ppc adds $LDBLStub suffixes to various symbols like printf. These
// are references to hidden visibility symbols that dlsym cannot resolve. If
// we have one of these, strip off $LDBLStub and try again.
#if defined(__APPLE__) && defined(__ppc__)
if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0)
return getPointerToNamedFunction(std::string(Name.begin(),
Name.end()-9));
#endif
/// If a LazyFunctionCreator is installed, use it to get/create the function.
if (LazyFunctionCreator)
if (void *RP = LazyFunctionCreator(Name))
return RP;
cerr << "ERROR: Program used external function '" << Name
<< "' which could not be resolved!\n";
abort();
return 0;
}
<commit_msg>Make this actually work on systems that support ppc long double.<commit_after>//===-- Intercept.cpp - System function interception routines -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// If a function call occurs to an external function, the JIT is designed to use
// the dynamic loader interface to find a function to call. This is useful for
// calling system calls and library functions that are not available in LLVM.
// Some system calls, however, need to be handled specially. For this reason,
// we intercept some of them here and use our own stubs to handle them.
//
//===----------------------------------------------------------------------===//
#include "JIT.h"
#include "llvm/System/DynamicLibrary.h"
#include "llvm/Config/config.h"
using namespace llvm;
// AtExitHandlers - List of functions to call when the program exits,
// registered with the atexit() library function.
static std::vector<void (*)()> AtExitHandlers;
/// runAtExitHandlers - Run any functions registered by the program's
/// calls to atexit(3), which we intercept and store in
/// AtExitHandlers.
///
static void runAtExitHandlers() {
while (!AtExitHandlers.empty()) {
void (*Fn)() = AtExitHandlers.back();
AtExitHandlers.pop_back();
Fn();
}
}
//===----------------------------------------------------------------------===//
// Function stubs that are invoked instead of certain library calls
//===----------------------------------------------------------------------===//
// Force the following functions to be linked in to anything that uses the
// JIT. This is a hack designed to work around the all-too-clever Glibc
// strategy of making these functions work differently when inlined vs. when
// not inlined, and hiding their real definitions in a separate archive file
// that the dynamic linker can't see. For more info, search for
// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
#if defined(__linux__)
#if defined(HAVE_SYS_STAT_H)
#include <sys/stat.h>
#endif
void *FunctionPointers[] = {
(void *)(intptr_t) stat,
(void *)(intptr_t) fstat,
(void *)(intptr_t) lstat,
(void *)(intptr_t) stat64,
(void *)(intptr_t) fstat64,
(void *)(intptr_t) lstat64,
(void *)(intptr_t) atexit,
(void *)(intptr_t) mknod
};
#endif // __linux__
// jit_exit - Used to intercept the "exit" library call.
static void jit_exit(int Status) {
runAtExitHandlers(); // Run atexit handlers...
exit(Status);
}
// jit_atexit - Used to intercept the "atexit" library call.
static int jit_atexit(void (*Fn)(void)) {
AtExitHandlers.push_back(Fn); // Take note of atexit handler...
return 0; // Always successful
}
//===----------------------------------------------------------------------===//
//
/// getPointerToNamedFunction - This method returns the address of the specified
/// function by using the dynamic loader interface. As such it is only useful
/// for resolving library symbols, not code generated symbols.
///
void *JIT::getPointerToNamedFunction(const std::string &Name) {
// Check to see if this is one of the functions we want to intercept. Note,
// we cast to intptr_t here to silence a -pedantic warning that complains
// about casting a function pointer to a normal pointer.
if (Name == "exit") return (void*)(intptr_t)&jit_exit;
if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
const char *NameStr = Name.c_str();
// If this is an asm specifier, skip the sentinal.
if (NameStr[0] == 1) ++NameStr;
// If it's an external function, look it up in the process image...
void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
if (Ptr) return Ptr;
// If it wasn't found and if it starts with an underscore ('_') character, and
// has an asm specifier, try again without the underscore.
if (Name[0] == 1 && NameStr[0] == '_') {
Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
if (Ptr) return Ptr;
}
// darwin/ppc adds $LDBLStub suffixes to various symbols like printf. These
// are references to hidden visibility symbols that dlsym cannot resolve. If
// we have one of these, strip off $LDBLStub and try again.
#if defined(__APPLE__) && defined(__ppc__)
if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
// First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
// This mirrors logic in libSystemStubs.a.
std::string Prefix = std::string(Name.begin(), Name.end()-9);
if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128"))
return Ptr;
return getPointerToNamedFunction(Prefix);
}
#endif
/// If a LazyFunctionCreator is installed, use it to get/create the function.
if (LazyFunctionCreator)
if (void *RP = LazyFunctionCreator(Name))
return RP;
cerr << "ERROR: Program used external function '" << Name
<< "' which could not be resolved!\n";
abort();
return 0;
}
<|endoftext|> |
<commit_before>/**
* \file TypedBaseFilter.hxx
*/
#include <ATK/Core/TypedBaseFilter.h>
#include <ATK/Core/Utilities.h>
#include <complex>
#include <cstdint>
#include <iostream>
#include <type_traits>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
#if USE_SIMD
#include <simdpp/simd.h>
#endif
namespace
{
typedef boost::mpl::vector<std::int16_t, std::int32_t, int64_t, float, double, std::complex<float>, std::complex<double> > ConversionTypes;
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::mpl::empty<Vector>::type, void>::type
convert_scalar_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
throw std::runtime_error("Cannot convert types for these filters");
}
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::is_arithmetic<typename boost::mpl::front<Vector>::type>::type, typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type>::type
convert_scalar_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
convert_scalar_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
}
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::is_arithmetic<typename boost::mpl::front<Vector>::type>::type, typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type>::type
convert_scalar_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
if(type != 0)
{
convert_scalar_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
}
else
{
typedef typename boost::mpl::front<Vector>::type InputOriginalType;
InputOriginalType* original_input_array = static_cast<ATK::TypedBaseFilter<InputOriginalType>*>(filter)->get_output_array(port);
ATK::ConversionUtilities<InputOriginalType, DataType>::convert_array(original_input_array, converted_input, size);
}
}
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::mpl::empty<Vector>::type, void>::type
convert_complex_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
throw std::runtime_error("Can't convert types");
}
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type
convert_complex_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
assert(type >= 0);
if (type != 0)
{
convert_complex_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
}
else
{
typedef typename boost::mpl::front<Vector>::type InputOriginalType;
InputOriginalType* original_input_array = static_cast<ATK::TypedBaseFilter<InputOriginalType>*>(filter)->get_output_array(port);
ATK::ConversionUtilities<InputOriginalType, DataType>::convert_array(original_input_array, converted_input, size);
}
}
/// Conversion function for arithmetic types
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::is_arithmetic<DataType>::type, void>::type convert_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
convert_scalar_array<Vector, DataType>(filter, port, converted_input, size, type);
}
/// Conversion function for other types not contained in ConversionTypes (no conversion in that case, just copy)
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::is_arithmetic<DataType>::type, typename boost::disable_if<typename boost::mpl::contains<Vector, DataType>::type, void>::type>::type convert_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
assert(dynamic_cast<ATK::OutputArrayInterface<DataType>*>(filter));
// For SIMD, you shouldn't call this, but adapt input/output delays so that there is no copy from one filter to another.
DataType* original_input_array = dynamic_cast<ATK::TypedBaseFilter<DataType>*>(filter)->get_output_array(port);
ATK::ConversionUtilities<DataType, DataType>::convert_array(original_input_array, converted_input, size);
}
/// Conversion function for std::complex contained in ConversionTypes
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::is_arithmetic<DataType>::type, typename boost::enable_if<typename boost::mpl::contains<Vector, DataType>::type, void>::type>::type convert_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
convert_complex_array<Vector, DataType>(filter, port, converted_input, size, type);
}
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::mpl::contains<Vector, DataType>::type, int>::type get_type()
{
return boost::mpl::distance<boost::mpl::begin<ConversionTypes>::type, typename boost::mpl::find<ConversionTypes, DataType>::type >::value;
}
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::mpl::contains<Vector, DataType>::type, int>::type get_type()
{
return -1;
}
}
namespace ATK
{
template<typename DataType>
OutputArrayInterface<DataType>::~OutputArrayInterface()
{
}
template<typename DataType_, typename DataType__>
TypedBaseFilter<DataType_, DataType__>::TypedBaseFilter(std::size_t nb_input_ports, std::size_t nb_output_ports)
:Parent(nb_input_ports, nb_output_ports), converted_inputs_delay(nb_input_ports), converted_inputs(nb_input_ports, nullptr), converted_inputs_size(nb_input_ports, 0), converted_in_delays(nb_input_ports, 0), direct_filters(nb_input_ports, nullptr), outputs_delay(nb_output_ports), outputs(nb_output_ports, nullptr), outputs_size(nb_output_ports, 0), out_delays(nb_output_ports, 0), default_input(nb_input_ports, TypeTraits<DataType_>::Zero()), default_output(nb_output_ports, TypeTraits<DataType__>::Zero())
{
}
template<typename DataType_, typename DataType__>
TypedBaseFilter<DataType_, DataType__>::TypedBaseFilter(TypedBaseFilter&& other)
: Parent(std::move(other)), converted_inputs_delay(std::move(other.converted_inputs_delay)), converted_inputs(std::move(other.converted_inputs)), converted_inputs_size(std::move(other.converted_inputs_size)), converted_in_delays(std::move(other.converted_in_delays)), direct_filters(std::move(other.direct_filters)), outputs_delay(std::move(other.outputs_delay)), outputs(std::move(other.outputs)), outputs_size(std::move(other.outputs_size)), default_input(std::move(other.default_input)), default_output(std::move(other.default_output))
{
}
template<typename DataType_, typename DataType__>
TypedBaseFilter<DataType_, DataType__>::~TypedBaseFilter()
{
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::set_nb_input_ports(std::size_t nb_ports)
{
if(nb_ports == nb_input_ports)
return;
Parent::set_nb_input_ports(nb_ports);
converted_inputs_delay = std::vector<AlignedVector>(nb_ports);
converted_inputs.assign(nb_ports, nullptr);
converted_inputs_size.assign(nb_ports, 0);
converted_in_delays.assign(nb_ports, 0);
direct_filters.assign(nb_ports, nullptr);
default_input.assign(nb_ports, TypeTraits<DataTypeInput>::Zero());
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::set_nb_output_ports(std::size_t nb_ports)
{
if(nb_ports == nb_output_ports)
return;
Parent::set_nb_output_ports(nb_ports);
outputs_delay = std::vector<AlignedOutVector>(nb_ports);
outputs.assign(nb_ports, nullptr);
outputs_size.assign(nb_ports, 0);
out_delays.assign(nb_ports, 0);
default_output.assign(nb_ports, TypeTraits<DataTypeOutput>::Zero());
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::process_impl(std::size_t size) const
{
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::prepare_process(std::size_t size)
{
convert_inputs(size);
}
template<typename DataType_, typename DataType__>
int TypedBaseFilter<DataType_, DataType__>::get_type() const
{
return ::get_type<ConversionTypes, DataType__>();
}
template<typename DataType_, typename DataType__>
DataType__* TypedBaseFilter<DataType_, DataType__>::get_output_array(std::size_t port) const
{
return outputs[port];
}
template<typename DataType_, typename DataType__>
std::size_t TypedBaseFilter<DataType_, DataType__>::get_output_array_size() const
{
return outputs_size.front();
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::convert_inputs(std::size_t size)
{
for(unsigned int i = 0; i < nb_input_ports; ++i)
{
// if the input delay is smaller than the preceding filter output delay, we may have overlap
// if the types are identical and if the type is not -1 (an unknown type)
// if we have overlap, don't copy anything at all
if((input_delay <= connections[i].second->get_output_delay()) && (direct_filters[i] != nullptr))
{
converted_inputs[i] = direct_filters[i]->get_output_array(connections[i].first);
converted_inputs_size[i] = size;
converted_in_delays[i] = input_delay;
continue;
}
auto input_size = converted_inputs_size[i];
auto in_delay = converted_in_delays[i];
if(input_size < size || in_delay < input_delay)
{
// TODO Properly align the beginning of the data, not depending on input delay
AlignedVector temp(input_delay + size, TypeTraits<DataTypeInput>::Zero());
if(input_size == 0)
{
for(unsigned int j = 0; j < input_delay; ++j)
{
temp[j] = default_input[i];
}
}
else
{
const auto input_ptr = converted_inputs[i];
for(int j = 0; j < static_cast<int>(input_delay); ++j)
{
temp[j] = input_ptr[last_size + j - input_delay];
}
}
converted_inputs_delay[i] = std::move(temp);
converted_inputs[i] = converted_inputs_delay[i].data() + input_delay;
converted_inputs_size[i] = size;
converted_in_delays[i] = input_delay;
}
else
{
auto my_last_size = static_cast<int64_t>(last_size) * input_sampling_rate / output_sampling_rate;
const auto input_ptr = converted_inputs[i];
for(int j = 0; j < static_cast<int>(input_delay); ++j)
{
input_ptr[j - input_delay] = input_ptr[my_last_size + j - input_delay];
}
}
convert_array<ConversionTypes, DataTypeInput>(connections[i].second, connections[i].first, converted_inputs[i], size, connections[i].second->get_type());
}
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::prepare_outputs(std::size_t size)
{
for(unsigned int i = 0; i < nb_output_ports; ++i)
{
auto output_size = outputs_size[i];
auto out_delay = out_delays[i];
if(output_size < size || out_delay < output_delay)
{
// TODO Properly align the beginning of the data, not depending on output delay
AlignedOutVector temp(output_delay + size, TypeTraits<DataTypeOutput>::Zero());
if(output_size == 0)
{
for(unsigned int j = 0; j < output_delay; ++j)
{
temp[j] = default_output[i];
}
}
else
{
const auto output_ptr = outputs[i];
for(int j = 0; j < static_cast<int>(output_delay); ++j)
{
temp[j] = output_ptr[last_size + j - output_delay];
}
}
outputs_delay[i] = std::move(temp);
outputs[i] = outputs_delay[i].data() + output_delay;
outputs_size[i] = size;
}
else
{
const auto output_ptr = outputs[i];
for(int j = 0; j < static_cast<int>(output_delay); ++j)
{
output_ptr[j - output_delay] = output_ptr[last_size + j - output_delay];
}
}
}
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::full_setup()
{
// Reset input arrays
converted_inputs_delay = std::vector<AlignedVector>(nb_input_ports);
converted_inputs.assign(nb_input_ports, nullptr);
converted_inputs_size.assign(nb_input_ports, 0);
converted_in_delays.assign(nb_input_ports, 0);
// Reset output arrays
outputs_delay = std::vector<AlignedOutVector>(nb_output_ports);
outputs.assign(nb_output_ports, nullptr);
outputs_size.assign(nb_output_ports, 0);
out_delays.assign(nb_output_ports, 0);
Parent::full_setup();
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::set_input_port(std::size_t input_port, BaseFilter* filter, std::size_t output_port)
{
Parent::set_input_port(input_port, filter, output_port);
converted_inputs_size[input_port] = 0;
converted_in_delays[input_port] = 0;
direct_filters[input_port] = dynamic_cast<OutputArrayInterface<DataType_>*>(filter);
}
}
<commit_msg>Fix temporary copy as well as output_delay save<commit_after>/**
* \file TypedBaseFilter.hxx
*/
#include <ATK/Core/TypedBaseFilter.h>
#include <ATK/Core/Utilities.h>
#include <complex>
#include <cstdint>
#include <iostream>
#include <type_traits>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
#if USE_SIMD
#include <simdpp/simd.h>
#endif
namespace
{
typedef boost::mpl::vector<std::int16_t, std::int32_t, int64_t, float, double, std::complex<float>, std::complex<double> > ConversionTypes;
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::mpl::empty<Vector>::type, void>::type
convert_scalar_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
throw std::runtime_error("Cannot convert types for these filters");
}
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::is_arithmetic<typename boost::mpl::front<Vector>::type>::type, typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type>::type
convert_scalar_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
convert_scalar_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
}
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::is_arithmetic<typename boost::mpl::front<Vector>::type>::type, typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type>::type
convert_scalar_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
if(type != 0)
{
convert_scalar_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
}
else
{
typedef typename boost::mpl::front<Vector>::type InputOriginalType;
InputOriginalType* original_input_array = static_cast<ATK::TypedBaseFilter<InputOriginalType>*>(filter)->get_output_array(port);
ATK::ConversionUtilities<InputOriginalType, DataType>::convert_array(original_input_array, converted_input, size);
}
}
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::mpl::empty<Vector>::type, void>::type
convert_complex_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
throw std::runtime_error("Can't convert types");
}
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type
convert_complex_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
assert(type >= 0);
if (type != 0)
{
convert_complex_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
}
else
{
typedef typename boost::mpl::front<Vector>::type InputOriginalType;
InputOriginalType* original_input_array = static_cast<ATK::TypedBaseFilter<InputOriginalType>*>(filter)->get_output_array(port);
ATK::ConversionUtilities<InputOriginalType, DataType>::convert_array(original_input_array, converted_input, size);
}
}
/// Conversion function for arithmetic types
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::is_arithmetic<DataType>::type, void>::type convert_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
convert_scalar_array<Vector, DataType>(filter, port, converted_input, size, type);
}
/// Conversion function for other types not contained in ConversionTypes (no conversion in that case, just copy)
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::is_arithmetic<DataType>::type, typename boost::disable_if<typename boost::mpl::contains<Vector, DataType>::type, void>::type>::type convert_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
assert(dynamic_cast<ATK::OutputArrayInterface<DataType>*>(filter));
// For SIMD, you shouldn't call this, but adapt input/output delays so that there is no copy from one filter to another.
DataType* original_input_array = dynamic_cast<ATK::TypedBaseFilter<DataType>*>(filter)->get_output_array(port);
ATK::ConversionUtilities<DataType, DataType>::convert_array(original_input_array, converted_input, size);
}
/// Conversion function for std::complex contained in ConversionTypes
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::is_arithmetic<DataType>::type, typename boost::enable_if<typename boost::mpl::contains<Vector, DataType>::type, void>::type>::type convert_array(ATK::BaseFilter* filter, unsigned int port, DataType* converted_input, std::size_t size, int type)
{
convert_complex_array<Vector, DataType>(filter, port, converted_input, size, type);
}
template<typename Vector, typename DataType>
typename boost::enable_if<typename boost::mpl::contains<Vector, DataType>::type, int>::type get_type()
{
return boost::mpl::distance<boost::mpl::begin<ConversionTypes>::type, typename boost::mpl::find<ConversionTypes, DataType>::type >::value;
}
template<typename Vector, typename DataType>
typename boost::disable_if<typename boost::mpl::contains<Vector, DataType>::type, int>::type get_type()
{
return -1;
}
}
namespace ATK
{
template<typename DataType>
OutputArrayInterface<DataType>::~OutputArrayInterface()
{
}
template<typename DataType_, typename DataType__>
TypedBaseFilter<DataType_, DataType__>::TypedBaseFilter(std::size_t nb_input_ports, std::size_t nb_output_ports)
:Parent(nb_input_ports, nb_output_ports), converted_inputs_delay(nb_input_ports), converted_inputs(nb_input_ports, nullptr), converted_inputs_size(nb_input_ports, 0), converted_in_delays(nb_input_ports, 0), direct_filters(nb_input_ports, nullptr), outputs_delay(nb_output_ports), outputs(nb_output_ports, nullptr), outputs_size(nb_output_ports, 0), out_delays(nb_output_ports, 0), default_input(nb_input_ports, TypeTraits<DataType_>::Zero()), default_output(nb_output_ports, TypeTraits<DataType__>::Zero())
{
}
template<typename DataType_, typename DataType__>
TypedBaseFilter<DataType_, DataType__>::TypedBaseFilter(TypedBaseFilter&& other)
: Parent(std::move(other)), converted_inputs_delay(std::move(other.converted_inputs_delay)), converted_inputs(std::move(other.converted_inputs)), converted_inputs_size(std::move(other.converted_inputs_size)), converted_in_delays(std::move(other.converted_in_delays)), direct_filters(std::move(other.direct_filters)), outputs_delay(std::move(other.outputs_delay)), outputs(std::move(other.outputs)), outputs_size(std::move(other.outputs_size)), default_input(std::move(other.default_input)), default_output(std::move(other.default_output))
{
}
template<typename DataType_, typename DataType__>
TypedBaseFilter<DataType_, DataType__>::~TypedBaseFilter()
{
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::set_nb_input_ports(std::size_t nb_ports)
{
if(nb_ports == nb_input_ports)
return;
Parent::set_nb_input_ports(nb_ports);
converted_inputs_delay = std::vector<AlignedVector>(nb_ports);
converted_inputs.assign(nb_ports, nullptr);
converted_inputs_size.assign(nb_ports, 0);
converted_in_delays.assign(nb_ports, 0);
direct_filters.assign(nb_ports, nullptr);
default_input.assign(nb_ports, TypeTraits<DataTypeInput>::Zero());
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::set_nb_output_ports(std::size_t nb_ports)
{
if(nb_ports == nb_output_ports)
return;
Parent::set_nb_output_ports(nb_ports);
outputs_delay = std::vector<AlignedOutVector>(nb_ports);
outputs.assign(nb_ports, nullptr);
outputs_size.assign(nb_ports, 0);
out_delays.assign(nb_ports, 0);
default_output.assign(nb_ports, TypeTraits<DataTypeOutput>::Zero());
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::process_impl(std::size_t size) const
{
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::prepare_process(std::size_t size)
{
convert_inputs(size);
}
template<typename DataType_, typename DataType__>
int TypedBaseFilter<DataType_, DataType__>::get_type() const
{
return ::get_type<ConversionTypes, DataType__>();
}
template<typename DataType_, typename DataType__>
DataType__* TypedBaseFilter<DataType_, DataType__>::get_output_array(std::size_t port) const
{
return outputs[port];
}
template<typename DataType_, typename DataType__>
std::size_t TypedBaseFilter<DataType_, DataType__>::get_output_array_size() const
{
return outputs_size.front();
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::convert_inputs(std::size_t size)
{
for(unsigned int i = 0; i < nb_input_ports; ++i)
{
// if the input delay is smaller than the preceding filter output delay, we may have overlap
// if the types are identical and if the type is not -1 (an unknown type)
// if we have overlap, don't copy anything at all
if((input_delay <= connections[i].second->get_output_delay()) && (direct_filters[i] != nullptr))
{
converted_inputs[i] = direct_filters[i]->get_output_array(connections[i].first);
converted_inputs_size[i] = size;
converted_in_delays[i] = input_delay;
continue;
}
auto input_size = converted_inputs_size[i];
auto in_delay = converted_in_delays[i];
if(input_size < size || in_delay < input_delay)
{
// TODO Properly align the beginning of the data, not depending on input delay
AlignedVector temp(input_delay + size, TypeTraits<DataTypeInput>::Zero());
if(input_size == 0)
{
for(unsigned int j = 0; j < input_delay; ++j)
{
temp[j] = default_input[i];
}
}
else
{
const auto input_ptr = converted_inputs[i];
for(int j = 0; j < static_cast<int>(in_delay); ++j)
{
temp[j] = input_ptr[last_size + j - in_delay];
}
}
converted_inputs_delay[i] = std::move(temp);
converted_inputs[i] = converted_inputs_delay[i].data() + input_delay;
converted_inputs_size[i] = size;
converted_in_delays[i] = input_delay;
}
else
{
auto my_last_size = static_cast<int64_t>(last_size) * input_sampling_rate / output_sampling_rate;
const auto input_ptr = converted_inputs[i];
for(int j = 0; j < static_cast<int>(input_delay); ++j)
{
input_ptr[j - input_delay] = input_ptr[my_last_size + j - input_delay];
}
}
convert_array<ConversionTypes, DataTypeInput>(connections[i].second, connections[i].first, converted_inputs[i], size, connections[i].second->get_type());
}
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::prepare_outputs(std::size_t size)
{
for(unsigned int i = 0; i < nb_output_ports; ++i)
{
auto output_size = outputs_size[i];
auto out_delay = out_delays[i];
if(output_size < size || out_delay < output_delay)
{
// TODO Properly align the beginning of the data, not depending on output delay
AlignedOutVector temp(output_delay + size, TypeTraits<DataTypeOutput>::Zero());
if(output_size == 0)
{
for(unsigned int j = 0; j < output_delay; ++j)
{
temp[j] = default_output[i];
}
}
else
{
const auto output_ptr = outputs[i];
for(int j = 0; j < static_cast<int>(out_delay); ++j)
{
temp[j] = output_ptr[last_size + j - out_delay];
}
}
outputs_delay[i] = std::move(temp);
outputs[i] = outputs_delay[i].data() + output_delay;
outputs_size[i] = size;
out_delays[i] = output_delay;
}
else
{
const auto output_ptr = outputs[i];
for(int j = 0; j < static_cast<int>(output_delay); ++j)
{
output_ptr[j - output_delay] = output_ptr[last_size + j - output_delay];
}
}
}
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::full_setup()
{
// Reset input arrays
converted_inputs_delay = std::vector<AlignedVector>(nb_input_ports);
converted_inputs.assign(nb_input_ports, nullptr);
converted_inputs_size.assign(nb_input_ports, 0);
converted_in_delays.assign(nb_input_ports, 0);
// Reset output arrays
outputs_delay = std::vector<AlignedOutVector>(nb_output_ports);
outputs.assign(nb_output_ports, nullptr);
outputs_size.assign(nb_output_ports, 0);
out_delays.assign(nb_output_ports, 0);
Parent::full_setup();
}
template<typename DataType_, typename DataType__>
void TypedBaseFilter<DataType_, DataType__>::set_input_port(std::size_t input_port, BaseFilter* filter, std::size_t output_port)
{
Parent::set_input_port(input_port, filter, output_port);
converted_inputs_size[input_port] = 0;
converted_in_delays[input_port] = 0;
direct_filters[input_port] = dynamic_cast<OutputArrayInterface<DataType_>*>(filter);
}
}
<|endoftext|> |
<commit_before>#include "game.hpp"
#define SCORE_MAX 3
// helper functions
static void
draw();
static void
resetBall();
// game state functions
static void
menuTitle();
static void
gameSetup();
static void
gameMain();
static void
menuWin();
static void
menuLose();
void (*gameTick)(){ &menuTitle };
Ball ball;
Player player;
Computer computer;
void
draw()
{
// cool border around the screen
arduboy.drawRect(0, 0, WIDTH, HEIGHT, WHITE);
// dotted line in the middle
for (uint8_t i{ 2 }; i < HEIGHT; i += 8)
{
arduboy.drawFastVLine(WIDTH / 2, i, 4, WHITE);
}
// scores
arduboy.setCursor(WIDTH/2 - 12, 2);
arduboy.print(player.score);
arduboy.setCursor(WIDTH/2 + 3, 2);
arduboy.print(computer.score);
// objects
ball.draw();
player.draw();
computer.draw();
}
void
resetBall()
{
ball.x = WIDTH / 2;
ball.y = HEIGHT / 2;
ball.dx = 1;
ball.dy = 1;
}
void
menuTitle()
{
arduboy.setCursor(0, 0);
arduboy.print(F("Press A to\nstart"));
if (arduboy.pressed(A_BUTTON))
{
gameTick = &gameSetup;
}
}
void
gameSetup()
{
arduboy.initRandomSeed();
resetBall();
player.x = 9;
player.y = 24; // i thought of something funnier than 24...
player.score = 0;
computer.x = WIDTH - PADDLE_WIDTH - 9;
computer.y = 25; // twenyfiiive!
computer.score = 0;
draw();
arduboy.display();
delay(1000);
gameTick = &gameMain;
}
void
gameMain()
{
draw();
ball.move();
// check if someone scored
if (ball.x >= WIDTH - BALL_SIZE)
{
sound.tone(POINT_FREQ, POINT_DUR);
if (++player.score >= SCORE_MAX)
{
gameTick = &menuWin;
return;
}
else
{
resetBall();
}
}
else if (ball.x < 1)
{
sound.tone(POINT_FREQ, POINT_DUR);
if (++computer.score >= SCORE_MAX)
{
gameTick = &menuLose;
return;
}
else
{
resetBall();
}
}
ball.bounce();
player.move();
computer.move();
}
void
menuWin()
{
arduboy.setCursor(0, 0);
arduboy.print(F("You win!\nPress A to\nrestart"));
if (arduboy.pressed(A_BUTTON))
{
gameTick = &gameSetup;
}
}
void
menuLose()
{
arduboy.setCursor(0, 0);
arduboy.print(F("You lost!\nPress A to\nrestart"));
if (arduboy.pressed(A_BUTTON))
{
gameTick = &gameSetup;
}
}
<commit_msg>Add pause state<commit_after>#include "game.hpp"
#define SCORE_MAX 3
// helper functions
static void
draw();
static void
resetBall();
// game state functions
static void
menuTitle();
static void
gameSetup();
static void
gameMain();
static void
gamePause();
static void
menuWin();
static void
menuLose();
void (*gameTick)(){ &menuTitle };
Ball ball;
Player player;
Computer computer;
void
draw()
{
// cool border around the screen
arduboy.drawRect(0, 0, WIDTH, HEIGHT, WHITE);
// dotted line in the middle
for (uint8_t i{ 2 }; i < HEIGHT; i += 8)
{
arduboy.drawFastVLine(WIDTH / 2, i, 4, WHITE);
}
// scores
arduboy.setCursor(WIDTH/2 - 12, 2);
arduboy.print(player.score);
arduboy.setCursor(WIDTH/2 + 3, 2);
arduboy.print(computer.score);
// objects
ball.draw();
player.draw();
computer.draw();
}
void
resetBall()
{
ball.x = WIDTH / 2;
ball.y = HEIGHT / 2;
ball.dx = 1;
ball.dy = 1;
}
void
menuTitle()
{
arduboy.setCursor(0, 0);
arduboy.print(F("Press A to\nstart"));
if (arduboy.pressed(A_BUTTON))
{
gameTick = &gameSetup;
}
}
void
gameSetup()
{
arduboy.initRandomSeed();
resetBall();
player.x = 9;
player.y = 24; // i thought of something funnier than 24...
player.score = 0;
computer.x = WIDTH - PADDLE_WIDTH - 9;
computer.y = 25; // twenyfiiive!
computer.score = 0;
draw();
arduboy.display();
delay(1000);
gameTick = &gameMain;
}
void
gameMain()
{
draw();
// pause the game if needed
if (arduboy.justPressed(A_BUTTON))
{
gameTick = &gamePause;
return;
}
ball.move();
// check if someone scored
if (ball.x >= WIDTH - BALL_SIZE)
{
sound.tone(POINT_FREQ, POINT_DUR);
if (++player.score >= SCORE_MAX)
{
gameTick = &menuWin;
return;
}
else
{
resetBall();
}
}
else if (ball.x < 1)
{
sound.tone(POINT_FREQ, POINT_DUR);
if (++computer.score >= SCORE_MAX)
{
gameTick = &menuLose;
return;
}
else
{
resetBall();
}
}
ball.bounce();
player.move();
computer.move();
}
void
gamePause()
{
draw();
// resume the game if needed
if (arduboy.justPressed(A_BUTTON))
{
gameTick = &gameMain;
}
}
void
menuWin()
{
arduboy.setCursor(0, 0);
arduboy.print(F("You win!\nPress A to\nrestart"));
if (arduboy.pressed(A_BUTTON))
{
gameTick = &gameSetup;
}
}
void
menuLose()
{
arduboy.setCursor(0, 0);
arduboy.print(F("You lost!\nPress A to\nrestart"));
if (arduboy.pressed(A_BUTTON))
{
gameTick = &gameSetup;
}
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include "util/coordinate_calculation.hpp"
#include <osrm/coordinate.hpp>
#include <cmath>
using namespace osrm;
using namespace osrm::util;
// Regression test for bug captured in #1347
BOOST_AUTO_TEST_CASE(regression_test_1347)
{
Coordinate u(FloatLongitude(-100), FloatLatitude(10));
Coordinate v(FloatLongitude(-100.002), FloatLatitude(10.001));
Coordinate q(FloatLongitude(-100.001), FloatLatitude(10.002));
double d1 = coordinate_calculation::perpendicularDistance(u, v, q);
double ratio;
Coordinate nearest_location;
double d2 = coordinate_calculation::perpendicularDistance(u, v, q, nearest_location, ratio);
BOOST_CHECK_LE(std::abs(d1 - d2), 0.01);
}
<commit_msg>Add tests for coordinate transformation<commit_after>#include <boost/test/unit_test.hpp>
#include "util/coordinate_calculation.hpp"
#include <osrm/coordinate.hpp>
#include <cmath>
using namespace osrm;
using namespace osrm::util;
// Regression test for bug captured in #1347
BOOST_AUTO_TEST_CASE(regression_test_1347)
{
Coordinate u(FloatLongitude(-100), FloatLatitude(10));
Coordinate v(FloatLongitude(-100.002), FloatLatitude(10.001));
Coordinate q(FloatLongitude(-100.001), FloatLatitude(10.002));
double d1 = coordinate_calculation::perpendicularDistance(u, v, q);
double ratio;
Coordinate nearest_location;
double d2 = coordinate_calculation::perpendicularDistance(u, v, q, nearest_location, ratio);
BOOST_CHECK_LE(std::abs(d1 - d2), 0.01);
}
BOOST_AUTO_TEST_CASE(lon_to_pixel)
{
using namespace coordinate_calculation;
BOOST_CHECK_CLOSE(7.416042 * mercator::DEGREE_TO_PX, 825550.019142, 0.1);
BOOST_CHECK_CLOSE(7.415892 * mercator::DEGREE_TO_PX, 825533.321218, 0.1);
BOOST_CHECK_CLOSE(7.416016 * mercator::DEGREE_TO_PX, 825547.124835, 0.1);
BOOST_CHECK_CLOSE(7.41577 * mercator::DEGREE_TO_PX, 825519.74024, 0.1);
BOOST_CHECK_CLOSE(7.415808 * mercator::DEGREE_TO_PX, 825523.970381, 0.1);
}
BOOST_AUTO_TEST_CASE(lat_to_pixel)
{
using namespace coordinate_calculation;
BOOST_CHECK_CLOSE(mercator::latToY(util::FloatLatitude(43.733947)) * mercator::DEGREE_TO_PX,
5424361.75863, 0.1);
BOOST_CHECK_CLOSE(mercator::latToY(util::FloatLatitude(43.733799)) * mercator::DEGREE_TO_PX,
5424338.95731, 0.1);
BOOST_CHECK_CLOSE(mercator::latToY(util::FloatLatitude(43.733922)) * mercator::DEGREE_TO_PX,
5424357.90705, 0.1);
BOOST_CHECK_CLOSE(mercator::latToY(util::FloatLatitude(43.733697)) * mercator::DEGREE_TO_PX,
5424323.24293, 0.1);
BOOST_CHECK_CLOSE(mercator::latToY(util::FloatLatitude(43.733729)) * mercator::DEGREE_TO_PX,
5424328.17293, 0.1);
}
BOOST_AUTO_TEST_CASE(xyz_to_wgs84)
{
using namespace coordinate_calculation;
double minx_1;
double miny_1;
double maxx_1;
double maxy_1;
mercator::xyzToWSG84(2, 2, 1, minx_1, miny_1, maxx_1, maxy_1);
BOOST_CHECK_CLOSE(minx_1, 180, 0.0001);
BOOST_CHECK_CLOSE(miny_1, -89.786, 0.0001);
BOOST_CHECK_CLOSE(maxx_1, 360, 0.0001);
BOOST_CHECK_CLOSE(maxy_1, -85.0511, 0.0001);
double minx_2;
double miny_2;
double maxx_2;
double maxy_2;
mercator::xyzToWSG84(100, 0, 13, minx_2, miny_2, maxx_2, maxy_2);
BOOST_CHECK_CLOSE(minx_2, -175.6054, 0.0001);
BOOST_CHECK_CLOSE(miny_2, 85.0473, 0.0001);
BOOST_CHECK_CLOSE(maxx_2, -175.5615, 0.0001);
BOOST_CHECK_CLOSE(maxy_2, 85.0511, 0.0001);
}
BOOST_AUTO_TEST_CASE(xyz_to_mercator)
{
using namespace coordinate_calculation;
double minx;
double miny;
double maxx;
double maxy;
mercator::xyzToMercator(100, 0, 13, minx, miny, maxx, maxy);
BOOST_CHECK_CLOSE(minx, -19548311.361764118075, 0.0001);
BOOST_CHECK_CLOSE(miny, 20032616.372979003936, 0.0001);
BOOST_CHECK_CLOSE(maxx, -19543419.391953866929, 0.0001);
BOOST_CHECK_CLOSE(maxy, 20037508.342789277434, 0.0001);
}
<|endoftext|> |
<commit_before>/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#include <nan.h>
#include <stdint.h>
using namespace Nan; // NOLINT(build/namespaces)
NAN_METHOD(ReadU8) {
TypedArrayContents<uint8_t> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());
for (size_t i=0; i<data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_METHOD(ReadI32) {
TypedArrayContents<int32_t> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());
for (size_t i=0; i<data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_METHOD(ReadFloat) {
TypedArrayContents<float> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());\
for (size_t i=0; i<data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_METHOD(ReadDouble) {
TypedArrayContents<double> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());
for (size_t i=0; i<data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, ReadU8);
NAN_EXPORT(target, ReadI32);
NAN_EXPORT(target, ReadFloat);
NAN_EXPORT(target, ReadDouble);
}
NODE_MODULE(typedarrays, Init)
<commit_msg>typedarrays.cpp: Missing spaces around < [whitespace/operators] [3]<commit_after>/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#include <nan.h>
#include <stdint.h>
using namespace Nan; // NOLINT(build/namespaces)
NAN_METHOD(ReadU8) {
TypedArrayContents<uint8_t> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());
for (size_t i=0; i < data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_METHOD(ReadI32) {
TypedArrayContents<int32_t> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());
for (size_t i=0; i < data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_METHOD(ReadFloat) {
TypedArrayContents<float> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());\
for (size_t i=0; i < data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_METHOD(ReadDouble) {
TypedArrayContents<double> data(info[0]);
v8::Local<v8::Array> result = New<v8::Array>(data.length());
for (size_t i=0; i < data.length(); i++) {
Set(result, i, New<v8::Number>((*data)[i]));
}
info.GetReturnValue().Set(result);
}
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, ReadU8);
NAN_EXPORT(target, ReadI32);
NAN_EXPORT(target, ReadFloat);
NAN_EXPORT(target, ReadDouble);
}
NODE_MODULE(typedarrays, Init)
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <accessibility/standard/vclxaccessibletabpagewindow.hxx>
#include <toolkit/helper/convert.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/tabpage.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
using namespace ::comphelper;
// ----------------------------------------------------
// class VCLXAccessibleTabPageWindow
// ----------------------------------------------------
VCLXAccessibleTabPageWindow::VCLXAccessibleTabPageWindow( VCLXWindow* pVCLXWindow )
:VCLXAccessibleComponent( pVCLXWindow )
{
m_pTabPage = static_cast< TabPage* >( GetWindow() );
m_pTabControl = 0;
m_nPageId = 0;
if ( m_pTabPage )
{
Window* pParent = m_pTabPage->GetAccessibleParentWindow();
if ( pParent && pParent->GetType() == WINDOW_TABCONTROL )
{
m_pTabControl = static_cast< TabControl* >( pParent );
if ( m_pTabControl )
{
for ( sal_uInt16 i = 0, nCount = m_pTabControl->GetPageCount(); i < nCount; ++i )
{
sal_uInt16 nPageId = m_pTabControl->GetPageId( i );
if ( m_pTabControl->GetTabPage( nPageId ) == m_pTabPage )
m_nPageId = nPageId;
}
}
}
}
}
// -----------------------------------------------------------------------------
VCLXAccessibleTabPageWindow::~VCLXAccessibleTabPageWindow()
{
}
// -----------------------------------------------------------------------------
// OCommonAccessibleComponent
// -----------------------------------------------------------------------------
awt::Rectangle VCLXAccessibleTabPageWindow::implGetBounds() throw (RuntimeException)
{
awt::Rectangle aBounds( 0, 0, 0, 0 );
if ( m_pTabControl )
{
Rectangle aPageRect = m_pTabControl->GetTabBounds( m_nPageId );
if ( m_pTabPage )
{
Rectangle aRect = Rectangle( m_pTabPage->GetPosPixel(), m_pTabPage->GetSizePixel() );
aRect.Move( -aPageRect.Left(), -aPageRect.Top() );
aBounds = AWTRectangle( aRect );
}
}
return aBounds;
}
// -----------------------------------------------------------------------------
// XComponent
// -----------------------------------------------------------------------------
void VCLXAccessibleTabPageWindow::disposing()
{
VCLXAccessibleComponent::disposing();
m_pTabControl = NULL;
m_pTabPage = NULL;
}
// -----------------------------------------------------------------------------
// XAccessibleContext
// -----------------------------------------------------------------------------
Reference< XAccessible > VCLXAccessibleTabPageWindow::getAccessibleParent( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Reference< XAccessible > xParent;
if ( m_pTabControl )
{
Reference< XAccessible > xAcc( m_pTabControl->GetAccessible() );
if ( xAcc.is() )
{
Reference< XAccessibleContext > xCont( xAcc->getAccessibleContext() );
if ( xCont.is() )
xParent = xCont->getAccessibleChild( m_pTabControl->GetPagePos( m_nPageId ) );
}
}
return xParent;
}
// -----------------------------------------------------------------------------
sal_Int32 VCLXAccessibleTabPageWindow::getAccessibleIndexInParent( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
return 0;
}
// -----------------------------------------------------------------------------
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>VCLXAccessibleTabPageWindow: unhandled IndexOutOfBoundsException<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <accessibility/standard/vclxaccessibletabpagewindow.hxx>
#include <toolkit/helper/convert.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/tabpage.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
using namespace ::comphelper;
// ----------------------------------------------------
// class VCLXAccessibleTabPageWindow
// ----------------------------------------------------
VCLXAccessibleTabPageWindow::VCLXAccessibleTabPageWindow( VCLXWindow* pVCLXWindow )
:VCLXAccessibleComponent( pVCLXWindow )
{
m_pTabPage = static_cast< TabPage* >( GetWindow() );
m_pTabControl = 0;
m_nPageId = 0;
if ( m_pTabPage )
{
Window* pParent = m_pTabPage->GetAccessibleParentWindow();
if ( pParent && pParent->GetType() == WINDOW_TABCONTROL )
{
m_pTabControl = static_cast< TabControl* >( pParent );
if ( m_pTabControl )
{
for ( sal_uInt16 i = 0, nCount = m_pTabControl->GetPageCount(); i < nCount; ++i )
{
sal_uInt16 nPageId = m_pTabControl->GetPageId( i );
if ( m_pTabControl->GetTabPage( nPageId ) == m_pTabPage )
m_nPageId = nPageId;
}
}
}
}
}
// -----------------------------------------------------------------------------
VCLXAccessibleTabPageWindow::~VCLXAccessibleTabPageWindow()
{
}
// -----------------------------------------------------------------------------
// OCommonAccessibleComponent
// -----------------------------------------------------------------------------
awt::Rectangle VCLXAccessibleTabPageWindow::implGetBounds() throw (RuntimeException)
{
awt::Rectangle aBounds( 0, 0, 0, 0 );
if ( m_pTabControl )
{
Rectangle aPageRect = m_pTabControl->GetTabBounds( m_nPageId );
if ( m_pTabPage )
{
Rectangle aRect = Rectangle( m_pTabPage->GetPosPixel(), m_pTabPage->GetSizePixel() );
aRect.Move( -aPageRect.Left(), -aPageRect.Top() );
aBounds = AWTRectangle( aRect );
}
}
return aBounds;
}
// -----------------------------------------------------------------------------
// XComponent
// -----------------------------------------------------------------------------
void VCLXAccessibleTabPageWindow::disposing()
{
VCLXAccessibleComponent::disposing();
m_pTabControl = NULL;
m_pTabPage = NULL;
}
// -----------------------------------------------------------------------------
// XAccessibleContext
// -----------------------------------------------------------------------------
Reference< XAccessible > VCLXAccessibleTabPageWindow::getAccessibleParent( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Reference< XAccessible > xParent;
if ( m_pTabControl )
{
Reference< XAccessible > xAcc( m_pTabControl->GetAccessible() );
if ( xAcc.is() )
{
Reference< XAccessibleContext > xCont( xAcc->getAccessibleContext() );
if ( xCont.is() )
{
sal_uInt16 const nPagePos(m_pTabControl->GetPagePos(m_nPageId));
SAL_WARN_IF(TAB_PAGE_NOTFOUND == nPagePos, "accessibility",
"getAccessibleParent(): no tab page");
if (TAB_PAGE_NOTFOUND != nPagePos)
{
xParent = xCont->getAccessibleChild(nPagePos);
}
}
}
}
return xParent;
}
// -----------------------------------------------------------------------------
sal_Int32 VCLXAccessibleTabPageWindow::getAccessibleIndexInParent( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
return 0;
}
// -----------------------------------------------------------------------------
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#ifndef LOCK_FREE_QUEUE_HPP
#define LOCK_FREE_QUEUE_HPP
#include <atomic>
#include <utility>
namespace ctl {
/// Thread safe and lock free FIFO queue.
/** Note: implementation is from:
http://www.drdobbs.com/parallel/writing-lock-free-code-a-corrected-queue/210604448
**/
template<typename T>
class lock_free_queue {
struct node {
node() : next(nullptr) {}
template<typename U>
node(U&& t) : data(std::forward<U>(t)), next(nullptr) {}
T data;
node* next;
};
node* first_;
std::atomic<node*> dummy_, last_;
public :
lock_free_queue() {
// Always keep a dummy separator between head and tail
first_ = last_ = dummy_ = new node();
}
~lock_free_queue() {
// Clear the whole queue
while (first_ != nullptr) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
}
lock_free_queue(const lock_free_queue& q) = delete;
lock_free_queue& operator = (const lock_free_queue& q) = delete;
/// Push a new element at the back of the queue.
/** Called by the 'producer' thread only.
**/
template<typename U>
void push(U&& t) {
// Add the new item to the queue
(*last_).next = new node(std::forward<U>(t));
last_ = (*last_).next;
// Clear consumed items
while (first_ != dummy_) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
}
/// Pop an element from the front of the queue.
/** Called by the 'consumer' thread only.
**/
bool pop(T& t) {
// Return false if queue is empty
if (dummy_!= last_) {
// Consume the value
t = std::move((*dummy_).next->data);
dummy_ = (*dummy_).next;
return true;
} else {
return false;
}
}
/// Check if this queue is empty.
/** Called by the 'consumer' thread only.
**/
bool empty() const {
return dummy_ == last_;
}
/// Delete all elements from the queue.
/** This method should not be used in concurrent situations
**/
void clear() {
while (first_ != dummy_) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
first_ = dummy_.load();
while (first_->next != nullptr) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
last_ = dummy_ = first_;
}
};
}
#endif
<commit_msg>Added lock_free_queue::size().<commit_after>#ifndef LOCK_FREE_QUEUE_HPP
#define LOCK_FREE_QUEUE_HPP
#include <atomic>
#include <utility>
namespace ctl {
/// Thread safe and lock free FIFO queue.
/** Note: implementation is from:
http://www.drdobbs.com/parallel/writing-lock-free-code-a-corrected-queue/210604448
**/
template<typename T>
class lock_free_queue {
struct node {
node() : next(nullptr) {}
template<typename U>
node(U&& t) : data(std::forward<U>(t)), next(nullptr) {}
T data;
node* next;
};
// Modified and read by 'procuder' only
node* first_;
// Modified and read by 'consumer', read by 'producer'
std::atomic<node*> dummy_;
// Modified and read by 'procuder', read by 'consumer'
std::atomic<node*> last_;
public :
lock_free_queue() {
// Always keep a dummy separator between head and tail
first_ = last_ = dummy_ = new node();
}
~lock_free_queue() {
// Clear the whole queue
while (first_ != nullptr) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
}
lock_free_queue(const lock_free_queue& q) = delete;
lock_free_queue& operator = (const lock_free_queue& q) = delete;
/// Push a new element at the back of the queue.
/** Called by the 'producer' thread only.
**/
template<typename U>
void push(U&& t) {
// Add the new item to the queue
(*last_).next = new node(std::forward<U>(t));
last_ = (*last_).next;
// Clear consumed items
while (first_ != dummy_) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
}
/// Pop an element from the front of the queue.
/** Called by the 'consumer' thread only.
**/
bool pop(T& t) {
// Return false if queue is empty
if (dummy_ != last_) {
// Consume the value
t = std::move((*dummy_).next->data);
dummy_ = (*dummy_).next;
return true;
} else {
return false;
}
}
/// Compute the current number of elements in the queue.
/** Called by the 'consumer' thread only.
Note that the true size may actually be larger than the returned value if the
'producer' thread pushes new elements while the size is computed.
**/
std::size_t size() const {
node* tmp = dummy_.load();
node* end = last_.load();
std::size_t n = 0;
while (tmp != end) {
tmp = tmp->next;
++n;
}
return n;
}
/// Check if this queue is empty.
/** Called by the 'consumer' thread only.
**/
bool empty() const {
return dummy_ == last_;
}
/// Delete all elements from the queue.
/** This method should not be used in concurrent situations
**/
void clear() {
while (first_ != dummy_) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
first_ = dummy_.load();
while (first_->next != nullptr) {
node* temp = first_;
first_ = temp->next;
delete temp;
}
last_ = dummy_ = first_;
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Android File Transfer for Linux: MTP client for android devices
* Copyright (C) 2015 Vladimir Menshakov
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <usb/Device.h>
#include <usb/Exception.h>
#include <mtp/usb/TimeoutException.h>
#include <mtp/ByteArray.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <sys/time.h>
#include "linux/usbdevice_fs.h"
#define IOCTL(...) do { int r = ioctl(__VA_ARGS__); if (r < 0) throw Exception("ioctl(" #__VA_ARGS__ ")"); } while(false)
namespace mtp { namespace usb
{
Device::InterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber)
{
IOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber);
}
Device::InterfaceToken::~InterfaceToken()
{
ioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber);
}
Device::Device(int fd): _fd(fd)
{
IOCTL(_fd, USBDEVFS_GET_CAPABILITIES, &_capabilities);
}
Device::~Device()
{
close(_fd);
}
int Device::GetConfiguration() const
{
return 0;
}
void Device::SetConfiguration(int idx)
{
fprintf(stderr, "SetConfiguration(%d): not implemented", idx);
}
void * Device::Reap(int timeout)
{
timeval started = {};
if (gettimeofday(&started, NULL) == -1)
throw usb::Exception("gettimeofday");
pollfd fd = {};
fd.fd = _fd;
fd.events = POLLOUT;
int r = poll(&fd, 1, timeout);
timeval now = {};
if (gettimeofday(&now, NULL) == -1)
throw usb::Exception("gettimeofday");
if (r < 0)
throw Exception("poll");
if (r == 0)
{
int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000;
fprintf(stderr, "%d ms since the last poll call\n", ms);
throw TimeoutException("timeout reaping usb urb");
}
usbdevfs_urb *urb;
r = ioctl(_fd, USBDEVFS_REAPURBNDELAY, &urb);
if (r == 0)
return urb;
else
throw Exception("ioctl");
}
void Device::ReapSingleUrb(void *urb, int timeout)
{
void * reapUrb = Reap(timeout);
if (urb != reapUrb)
{
fprintf(stderr, "reaping unknown urb, usb bus conflict: %p %p\n", urb, reapUrb);
std::terminate();
}
}
void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)
{
size_t transferSize = ep->GetMaxPacketSize() * 1024;
ByteArray data(transferSize);
size_t r;
bool continuation = false;
do
{
r = inputStream->Read(data.data(), data.size());
//HexDump("write", ByteArray(data.data(), data.data() + r));
usbdevfs_urb urb = {};
urb.type = USBDEVFS_URB_TYPE_BULK;
urb.endpoint = ep->GetAddress();
urb.buffer = const_cast<u8 *>(data.data());
urb.buffer_length = r;
if (continuation)
urb.flags |= USBDEVFS_URB_BULK_CONTINUATION;
else
continuation = true;
IOCTL(_fd, USBDEVFS_SUBMITURB, &urb);
try
{
ReapSingleUrb(&urb, timeout);
}
catch(const std::exception &ex)
{
int r = ioctl(_fd, USBDEVFS_DISCARDURB, &urb);
if (r != 0)
std::terminate();
fprintf(stderr, "exception %s: discard = %d\n", ex.what(), r);
throw;
}
}
while(r == transferSize);
}
void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)
{
ByteArray data(ep->GetMaxPacketSize() * 1024);
usbdevfs_urb urb = {};
bool continuation = false;
do
{
urb.type = USBDEVFS_URB_TYPE_BULK;
urb.endpoint = ep->GetAddress();
urb.buffer = data.data();
urb.buffer_length = data.size();
if (continuation)
urb.flags |= USBDEVFS_URB_BULK_CONTINUATION;
else
continuation = true;
IOCTL(_fd, USBDEVFS_SUBMITURB, &urb);
try
{
ReapSingleUrb(&urb, timeout);
}
catch(const std::exception &ex)
{
int r = ioctl(_fd, USBDEVFS_DISCARDURB, &urb);
if (r != 0)
std::terminate();
fprintf(stderr, "exception %s: discard = %d\n", ex.what(), r);
throw;
}
//HexDump("read", ByteArray(data.data(), data.data() + urb.actual_length));
outputStream->Write(data.data(), urb.actual_length);
}
while(urb.actual_length == (int)data.size());
}
}}<commit_msg>lock device file descriptor to avoid conflicts<commit_after>/*
* Android File Transfer for Linux: MTP client for android devices
* Copyright (C) 2015 Vladimir Menshakov
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <usb/Device.h>
#include <usb/Exception.h>
#include <mtp/usb/TimeoutException.h>
#include <mtp/ByteArray.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <sys/time.h>
#include "linux/usbdevice_fs.h"
#define IOCTL(...) do { int r = ioctl(__VA_ARGS__); if (r < 0) throw Exception("ioctl(" #__VA_ARGS__ ")"); } while(false)
namespace mtp { namespace usb
{
Device::InterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber)
{
IOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber);
}
Device::InterfaceToken::~InterfaceToken()
{
ioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber);
}
Device::Device(int fd): _fd(fd)
{
IOCTL(_fd, USBDEVFS_GET_CAPABILITIES, &_capabilities);
int r = lockf(_fd, F_TLOCK, 0);
if (r == -1)
throw Exception("device is used by another process");
}
Device::~Device()
{
lockf(_fd, F_ULOCK, 0);
close(_fd);
}
int Device::GetConfiguration() const
{
return 0;
}
void Device::SetConfiguration(int idx)
{
fprintf(stderr, "SetConfiguration(%d): not implemented", idx);
}
void * Device::Reap(int timeout)
{
timeval started = {};
if (gettimeofday(&started, NULL) == -1)
throw usb::Exception("gettimeofday");
pollfd fd = {};
fd.fd = _fd;
fd.events = POLLOUT;
int r = poll(&fd, 1, timeout);
timeval now = {};
if (gettimeofday(&now, NULL) == -1)
throw usb::Exception("gettimeofday");
if (r < 0)
throw Exception("poll");
if (r == 0)
{
int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000;
fprintf(stderr, "%d ms since the last poll call\n", ms);
throw TimeoutException("timeout reaping usb urb");
}
usbdevfs_urb *urb;
r = ioctl(_fd, USBDEVFS_REAPURBNDELAY, &urb);
if (r == 0)
return urb;
else
throw Exception("ioctl");
}
void Device::ReapSingleUrb(void *urb, int timeout)
{
void * reapUrb = Reap(timeout);
if (urb != reapUrb)
{
fprintf(stderr, "reaping unknown urb, usb bus conflict: %p %p\n", urb, reapUrb);
std::terminate();
}
}
void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)
{
size_t transferSize = ep->GetMaxPacketSize() * 1024;
ByteArray data(transferSize);
size_t r;
bool continuation = false;
do
{
r = inputStream->Read(data.data(), data.size());
//HexDump("write", ByteArray(data.data(), data.data() + r));
usbdevfs_urb urb = {};
urb.type = USBDEVFS_URB_TYPE_BULK;
urb.endpoint = ep->GetAddress();
urb.buffer = const_cast<u8 *>(data.data());
urb.buffer_length = r;
if (continuation)
urb.flags |= USBDEVFS_URB_BULK_CONTINUATION;
else
continuation = true;
IOCTL(_fd, USBDEVFS_SUBMITURB, &urb);
try
{
ReapSingleUrb(&urb, timeout);
}
catch(const std::exception &ex)
{
int r = ioctl(_fd, USBDEVFS_DISCARDURB, &urb);
if (r != 0)
std::terminate();
fprintf(stderr, "exception %s: discard = %d\n", ex.what(), r);
throw;
}
}
while(r == transferSize);
}
void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)
{
ByteArray data(ep->GetMaxPacketSize() * 1024);
usbdevfs_urb urb = {};
bool continuation = false;
do
{
urb.type = USBDEVFS_URB_TYPE_BULK;
urb.endpoint = ep->GetAddress();
urb.buffer = data.data();
urb.buffer_length = data.size();
if (continuation)
urb.flags |= USBDEVFS_URB_BULK_CONTINUATION;
else
continuation = true;
IOCTL(_fd, USBDEVFS_SUBMITURB, &urb);
try
{
ReapSingleUrb(&urb, timeout);
}
catch(const std::exception &ex)
{
int r = ioctl(_fd, USBDEVFS_DISCARDURB, &urb);
if (r != 0)
std::terminate();
fprintf(stderr, "exception %s: discard = %d\n", ex.what(), r);
throw;
}
//HexDump("read", ByteArray(data.data(), data.data() + urb.actual_length));
outputStream->Write(data.data(), urb.actual_length);
}
while(urb.actual_length == (int)data.size());
}
}}<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "medialibrary/IMediaLibrary.h"
#include "test/common/NoopCallback.h"
#include "test/common/util.h"
#include "compat/Mutex.h"
#include "compat/ConditionVariable.h"
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <unistd.h>
#include <cassert>
class TestCb : public mock::NoopCallback
{
public:
TestCb()
: m_isDiscoveryCompleted( false )
, m_isParsingCompleted( false )
, m_isIdle( false )
, m_error( false )
{
}
bool waitForCompletion()
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_cond.wait( lock, [this](){
return (m_isDiscoveryCompleted == true &&
m_isParsingCompleted == true &&
m_isIdle == true) || m_error;
});
return m_error == false;
}
private:
virtual void onDiscoveryStarted() override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isDiscoveryCompleted = false;
m_isParsingCompleted = false;
}
m_cond.notify_all();
}
virtual void onDiscoveryCompleted() override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isDiscoveryCompleted = true;
}
m_cond.notify_all();
}
virtual void onDiscoveryFailed( const std::string& ) override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_error = true;
}
m_cond.notify_all();
}
virtual void onParsingStatsUpdated( uint32_t done, uint32_t scheduled ) override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isParsingCompleted = (done == scheduled);
}
m_cond.notify_all();
}
virtual void onBackgroundTasksIdleChanged(bool isIdle) override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isIdle = isIdle;
}
m_cond.notify_all();
}
private:
compat::ConditionVariable m_cond;
compat::Mutex m_mutex;
bool m_isDiscoveryCompleted;
bool m_isParsingCompleted;
bool m_isIdle;
bool m_error;
};
int main( int argc, char** argv )
{
if ( argc < 2 )
{
std::cerr << "usage: " << argv[0] << " <entrypoint> [nb_runs] [-q]" << std::endl;
return 1;
}
auto mlDir = getTempPath( "discoverer_test" );
auto dbPath = mlDir + "/test.db";
auto nbRuns = 1;
auto quiet = false;
for ( auto i = 2; i < argc; ++i )
{
if ( !strcmp( argv[i], "-q" ) )
quiet = true;
else
nbRuns = atoi( argv[i] );
}
unlink( dbPath.c_str() );
auto testCb = std::make_unique<TestCb>();
std::unique_ptr<medialibrary::IMediaLibrary> ml{
NewMediaLibrary( dbPath.c_str(), mlDir.c_str(), false )
};
ml->setVerbosity( quiet == true ? medialibrary::LogLevel::Error :
medialibrary::LogLevel::Debug );
ml->initialize( testCb.get() );
auto res = ml->setDiscoverNetworkEnabled( true );
assert( res );
for ( auto i = 0; i < nbRuns; ++i )
{
ml->discover( argv[1] );
res = testCb->waitForCompletion();
if ( res == false )
return 1;
if ( i < nbRuns - 1 )
ml->forceRescan();
}
return 0;
}
<commit_msg>test: discoverer: Allow a local path to be provided<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "medialibrary/IMediaLibrary.h"
#include "test/common/NoopCallback.h"
#include "test/common/util.h"
#include "compat/Mutex.h"
#include "compat/ConditionVariable.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "medialibrary/filesystem/Errors.h"
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <unistd.h>
#include <cassert>
class TestCb : public mock::NoopCallback
{
public:
TestCb()
: m_isDiscoveryCompleted( false )
, m_isParsingCompleted( false )
, m_isIdle( false )
, m_error( false )
{
}
bool waitForCompletion()
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_cond.wait( lock, [this](){
return (m_isDiscoveryCompleted == true &&
m_isParsingCompleted == true &&
m_isIdle == true) || m_error;
});
return m_error == false;
}
private:
virtual void onDiscoveryStarted() override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isDiscoveryCompleted = false;
m_isParsingCompleted = false;
}
m_cond.notify_all();
}
virtual void onDiscoveryCompleted() override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isDiscoveryCompleted = true;
}
m_cond.notify_all();
}
virtual void onDiscoveryFailed( const std::string& ) override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_error = true;
}
m_cond.notify_all();
}
virtual void onParsingStatsUpdated( uint32_t done, uint32_t scheduled ) override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isParsingCompleted = (done == scheduled);
}
m_cond.notify_all();
}
virtual void onBackgroundTasksIdleChanged(bool isIdle) override
{
{
std::lock_guard<compat::Mutex> lock( m_mutex );
m_isIdle = isIdle;
}
m_cond.notify_all();
}
private:
compat::ConditionVariable m_cond;
compat::Mutex m_mutex;
bool m_isDiscoveryCompleted;
bool m_isParsingCompleted;
bool m_isIdle;
bool m_error;
};
int main( int argc, char** argv )
{
if ( argc < 2 )
{
std::cerr << "usage: " << argv[0] << " <entrypoint> [nb_runs] [-q]" << std::endl;
return 1;
}
auto mlDir = getTempPath( "discoverer_test" );
auto dbPath = mlDir + "/test.db";
auto nbRuns = 1;
auto quiet = false;
for ( auto i = 2; i < argc; ++i )
{
if ( !strcmp( argv[i], "-q" ) )
quiet = true;
else
nbRuns = atoi( argv[i] );
}
std::string target;
try
{
utils::url::scheme( argv[1] );
target = argv[1];
}
catch ( const medialibrary::fs::errors::UnhandledScheme& )
{
target = utils::file::toMrl( argv[1] );
}
unlink( dbPath.c_str() );
auto testCb = std::make_unique<TestCb>();
std::unique_ptr<medialibrary::IMediaLibrary> ml{
NewMediaLibrary( dbPath.c_str(), mlDir.c_str(), false )
};
ml->setVerbosity( quiet == true ? medialibrary::LogLevel::Error :
medialibrary::LogLevel::Debug );
ml->initialize( testCb.get() );
auto res = ml->setDiscoverNetworkEnabled( true );
assert( res );
for ( auto i = 0; i < nbRuns; ++i )
{
ml->discover( target );
res = testCb->waitForCompletion();
if ( res == false )
return 1;
if ( i < nbRuns - 1 )
ml->forceRescan();
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 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-CHROMIUM file.
#include "browser/permission_manager.h"
#include "base/callback.h"
#include "content/public/browser/permission_type.h"
namespace brightray {
PermissionManager::PermissionManager() {
}
PermissionManager::~PermissionManager() {
}
void PermissionManager::RequestPermission(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
int request_id,
const GURL& requesting_origin,
bool user_gesture,
const base::Callback<void(content::PermissionStatus)>& callback) {
callback.Run(content::PERMISSION_STATUS_GRANTED);
}
void PermissionManager::CancelPermissionRequest(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
int request_id,
const GURL& requesting_origin) {
}
void PermissionManager::ResetPermission(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
content::PermissionStatus PermissionManager::GetPermissionStatus(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
return content::PERMISSION_STATUS_GRANTED;
}
void PermissionManager::RegisterPermissionUsage(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
int PermissionManager::SubscribePermissionStatusChange(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin,
const base::Callback<void(content::PermissionStatus)>& callback) {
return -1;
}
void PermissionManager::UnsubscribePermissionStatusChange(int subscription_id) {
}
} // namespace brightray
<commit_msg>Grant ChildProcessSecurityPolicy for MIDI from PermissionManager<commit_after>// Copyright (c) 2015 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-CHROMIUM file.
#include "browser/permission_manager.h"
#include "base/callback.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
namespace brightray {
PermissionManager::PermissionManager() {
}
PermissionManager::~PermissionManager() {
}
void PermissionManager::RequestPermission(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
int request_id,
const GURL& requesting_origin,
bool user_gesture,
const base::Callback<void(content::PermissionStatus)>& callback) {
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()->
GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
}
callback.Run(content::PERMISSION_STATUS_GRANTED);
}
void PermissionManager::CancelPermissionRequest(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
int request_id,
const GURL& requesting_origin) {
}
void PermissionManager::ResetPermission(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
content::PermissionStatus PermissionManager::GetPermissionStatus(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
return content::PERMISSION_STATUS_GRANTED;
}
void PermissionManager::RegisterPermissionUsage(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
int PermissionManager::SubscribePermissionStatusChange(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin,
const base::Callback<void(content::PermissionStatus)>& callback) {
return -1;
}
void PermissionManager::UnsubscribePermissionStatusChange(int subscription_id) {
}
} // namespace brightray
<|endoftext|> |
<commit_before>#include "iostream"
#include "cstdlib"
#include "optional"
using namespace std;
/*
LinkedList
- Estrutura fundamental, pois todos os outros partem dele
- Tamanho variavel**
- Um nó aponta para o proximo, se o nó for o "primeiro" o mesmo é NULL
*/
template<class T>
struct Node{
T value;
Node *next;
};
template<class T>
class LinkedList{
private:
Node<T> *head;
int deepSearch(Node<T> *actualNode, int actualSize = 0){
if(actualNode == NULL)
return actualSize;
deepSearch(actualNode->next, ++actualSize);
}
std::optional<T> recursiveElementSearch(Node<T> *actualNode, int objectiveLevel, int actualLevel = 0){
if(actualNode == NULL)
return {};
if(actualLevel == objectiveLevel)
return actualNode->value;
return recursiveElementSearch(actualNode->next, objectiveLevel, ++actualLevel);
}
public:
LinkedList(){
head = NULL;
}
void push(int value){
Node<T> *n = new Node<T>();
n->value = value;
n->next = head;
head = n;
}
std::optional<T> pop(){
if(head == NULL)
return {};
Node<T> *n = head;
int ret = n->value;
head = head->next;
delete n;
return ret;
}
std::optional<T> peek(){
return head == NULL ? {} : head->value;
}
std::optional<T> at(int index){
if(auto element = recursiveElementSearch(head, index))
return *element;
return {};
}
bool any(){
return head == NULL ? false : true;
}
int size(){
return deepSearch(head);
}
};
int main(){
LinkedList<int> list;
cout << list.any() << endl;
list.push(12);
list.push(55);
list.push(16);
cout << list.any() << endl;
cout << list.at(3).value_or(0) << endl;
cout << list.pop().value_or(0) << endl;
cout << list.pop().value_or(0) << endl;
cout << list.pop().value_or(0) << endl;
}
<commit_msg>array<commit_after>#include "iostream"
#include "cstdlib"
#include "optional"
using namespace std;
/*
LinkedList
- Estrutura fundamental, pois todos os outros partem dele
- Tamanho variavel**
- Um nó aponta para o proximo, se o nó for o "primeiro" o mesmo é NULL
*/
template<class T>
struct Node{
T value;
Node *next;
};
template<class T>
class LinkedList{
private:
Node<T> *head;
int deep_search(Node<T> *actualNode, int actualSize = 0){
if(actualNode == NULL)
return actualSize;
deep_search(actualNode->next, ++actualSize);
}
std::optional<T> recursive_element_search(Node<T> *actualNode, int objectiveLevel, int actualLevel = 0){
if(actualNode == NULL)
return {};
if(actualLevel == objectiveLevel)
return actualNode->value;
return recursive_element_search(actualNode->next, objectiveLevel, ++actualLevel);
}
void fill_array(Node<T> *actualNode, T *array, int actualIndex = 0){
if(actualNode == NULL)
return;
array[actualIndex] = actualNode->value;
fill_array(actualNode->next, array, ++actualIndex);
}
public:
LinkedList(){
head = NULL;
}
void push_back(int value){
Node<T> *n = new Node<T>();
n->value = value;
n->next = head;
head = n;
}
std::optional<T> pop_back(){
if(head == NULL)
return {};
Node<T> *n = head;
int ret = n->value;
head = head->next;
delete n;
return ret;
}
std::optional<T> peek_back(){
if(head == NULL)
return {};
return head->value;
}
std::optional<T> at(int index){
if(auto element = recursive_element_search(head, index))
return *element;
return {};
}
bool any(){
return head == NULL ? false : true;
}
int size(){
return deep_search(head);
}
T* to_array(){
T *array = new T[size()];
fill_array(head, array);
return array;
}
};
int main(){
LinkedList<int> list;
cout << list.any() << endl;
list.push_back(12);
list.push_back(55);
list.push_back(16);
cout << list.any() << endl;
cout << list.at(3).value_or(0) << endl;
cout << list.pop_back().value_or(0) << endl;
cout << list.pop_back().value_or(0) << endl;
cout << list.pop_back().value_or(0) << endl;
}
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for most recent version including documentation.
//
// File : $RCSfile$
//
// Version : $Id$
//
// Description : tests floating point comparison algorithms
// ***************************************************************************
// Boost.Test
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_result.hpp>
#include <boost/test/floating_point_comparison.hpp>
using namespace boost::unit_test_framework;
// STL
#include <iostream>
//____________________________________________________________________________//
#define CHECK_TOOL_USAGE( tool_usage, check ) \
{ \
boost::test_toolbox::output_test_stream output; \
\
unit_test_log::instance().set_log_stream( output ); \
{ unit_test_result_saver saver; \
tool_usage; \
} \
unit_test_log::instance().set_log_stream( std::cout ); \
BOOST_CHECK( check ); \
}
//____________________________________________________________________________//
#if !defined(__BORLANDC__)
#define CHECK_PATTERN( msg, shift ) \
(boost::wrap_stringstream().ref() << __FILE__ << "(" << __LINE__ << "): " << msg).str()
#else
#define CHECK_PATTERN( msg, shift ) \
(boost::wrap_stringstream().ref() << __FILE__ << "(" << (__LINE__-shift) << "): " << msg).str()
#endif
//____________________________________________________________________________//
template<typename FPT>
void
test_BOOST_CHECK_CLOSE( FPT ) {
#undef TEST_CASE_NAME
#define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_CLOSE_all" << "\"" <<
unit_test_log::instance().set_log_threshold_level( log_messages );
BOOST_MESSAGE( "testing BOOST_CHECK_CLOSE for " << typeid(FPT).name() );
#define BOOST_CHECK_CLOSE_SHOULD_PASS( first, second, e ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
epsilon = static_cast<FPT>(e); \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, epsilon ), \
output.is_empty() \
)
#define BOOST_CHECK_CLOSE_SHOULD_PASS_N( first, second, num ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, (num) ), \
output.is_empty() \
)
#define BOOST_CHECK_CLOSE_SHOULD_FAIL( first, second, e ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
epsilon = static_cast<FPT>(e); \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, epsilon ), \
output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
<< fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
)
#define BOOST_CHECK_CLOSE_SHOULD_FAIL_N( first, second, num ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
epsilon = num * std::numeric_limits<FPT>::epsilon()/2; \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, num ), \
output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
<< fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
)
FPT fp1, fp2, epsilon, tmp;
BOOST_CHECK_CLOSE_SHOULD_PASS( 1, 1, 0 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-20, 1e-7 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-30, 1e-7 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, -1e-10, 1e-3 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, 0.123457, 1e-6 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 0.123456, 0.123457, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, -0.123457, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 1.23456e28, 1.23457e28, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.23456e-10, 1.23457e-11, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.111e-10, 1.112e-10, 0.0008999 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.112e-10, 1.111e-10, 0.0008999 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 1 , 1.0001, 1.1e-4 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 1.0002, 1.0001, 1.1e-4 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1 , 1.0002, 1.1e-4 );
BOOST_CHECK_CLOSE_SHOULD_PASS_N( 1, 1+std::numeric_limits<FPT>::epsilon() / 2, 1 );
tmp = static_cast<FPT>(1e-10);
BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp+tmp, 2e-10, 1+2 );
tmp = static_cast<FPT>(3.1);
BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp, 9.61, 1+2 );
tmp = 11;
tmp /= 10;
BOOST_CHECK_CLOSE_SHOULD_PASS_N( (tmp*tmp-tmp), 11./100, 1+3 );
BOOST_CHECK_CLOSE_SHOULD_FAIL_N( 100*(tmp*tmp-tmp), 11, 3 );
tmp = static_cast<FPT>(1e15+1e-10);
BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp+tmp*tmp, 2e30+2e-20+4e5, 3+5 );
fp1 = static_cast<FPT>(1.0001);
fp2 = static_cast<FPT>(1001.1001);
tmp = static_cast<FPT>(1.0001);
for( int i=0; i < 1000; i++ )
fp1 = fp1 + tmp;
CHECK_TOOL_USAGE(
BOOST_CHECK_CLOSE( fp1, fp2, 1000 ),
output.is_empty()
);
}
void
test_BOOST_CHECK_CLOSE_all() {
test_BOOST_CHECK_CLOSE<float>( (float)0 );
test_BOOST_CHECK_CLOSE<double>( (double)0 );
test_BOOST_CHECK_CLOSE<long double>( (long double)0 );
double fp1 = 1.00000001;
double fp2 = 1.00000002;
double epsilon = 1e-8;
CHECK_TOOL_USAGE(
BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
output.is_empty()
);
CHECK_TOOL_USAGE(
BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),
output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed ["
<< fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 3 ) )
);
fp1 = 1.23456e-10;
fp2 = 1.23457e-10;
epsilon = 8.1e-6;
CHECK_TOOL_USAGE(
BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
output.is_empty()
);
CHECK_TOOL_USAGE(
BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon ), 2, ( fp1, fp2 ) ),
output.is_equal( CHECK_PATTERN(
"error in " TEST_CASE_NAME ": test close_at_tolerance<double>( epsilon )(fp1, fp2) "
"failed for (" << fp1 << ", " << fp2 << ")\n", 4 ) )
);
}
//____________________________________________________________________________//
test_suite*
init_unit_test_suite( int /*argc*/, char* /*argv*/[] ) {
test_suite* test = BOOST_TEST_SUITE("FP compare test");
test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_CLOSE_all ) );
return test;
}
//____________________________________________________________________________//
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.1 2003/02/13 08:47:11 rogeeff
// *** empty log message ***
//
// ***************************************************************************
// EOF
<commit_msg>cwpro8 fix<commit_after>// (C) Copyright Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for most recent version including documentation.
//
// File : $RCSfile$
//
// Version : $Id$
//
// Description : tests floating point comparison algorithms
// ***************************************************************************
// Boost.Test
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_result.hpp>
using namespace boost::unit_test_framework;
// STL
#include <iostream>
//____________________________________________________________________________//
#define CHECK_TOOL_USAGE( tool_usage, check ) \
{ \
boost::test_toolbox::output_test_stream output; \
\
unit_test_log::instance().set_log_stream( output ); \
{ unit_test_result_saver saver; \
tool_usage; \
} \
unit_test_log::instance().set_log_stream( std::cout ); \
BOOST_CHECK( check ); \
}
//____________________________________________________________________________//
#if !defined(__BORLANDC__)
#define CHECK_PATTERN( msg, shift ) \
(boost::wrap_stringstream().ref() << __FILE__ << "(" << __LINE__ << "): " << msg).str()
#else
#define CHECK_PATTERN( msg, shift ) \
(boost::wrap_stringstream().ref() << __FILE__ << "(" << (__LINE__-shift) << "): " << msg).str()
#endif
//____________________________________________________________________________//
template<typename FPT>
void
test_BOOST_CHECK_CLOSE( FPT ) {
#undef TEST_CASE_NAME
#define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_CLOSE_all" << "\"" <<
unit_test_log::instance().set_log_threshold_level( log_messages );
BOOST_MESSAGE( "testing BOOST_CHECK_CLOSE for " << typeid(FPT).name() );
#define BOOST_CHECK_CLOSE_SHOULD_PASS( first, second, e ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
epsilon = static_cast<FPT>(e); \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, epsilon ), \
output.is_empty() \
)
#define BOOST_CHECK_CLOSE_SHOULD_PASS_N( first, second, num ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, (num) ), \
output.is_empty() \
)
#define BOOST_CHECK_CLOSE_SHOULD_FAIL( first, second, e ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
epsilon = static_cast<FPT>(e); \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, epsilon ), \
output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
<< fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
)
#define BOOST_CHECK_CLOSE_SHOULD_FAIL_N( first, second, num ) \
fp1 = static_cast<FPT>(first); \
fp2 = static_cast<FPT>(second); \
epsilon = num * std::numeric_limits<FPT>::epsilon()/2; \
\
CHECK_TOOL_USAGE( \
BOOST_CHECK_CLOSE( fp1, fp2, num ), \
output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
<< fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
)
FPT fp1, fp2, epsilon, tmp;
BOOST_CHECK_CLOSE_SHOULD_PASS( 1, 1, 0 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-20, 1e-7 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-30, 1e-7 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, -1e-10, 1e-3 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, 0.123457, 1e-6 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 0.123456, 0.123457, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, -0.123457, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 1.23456e28, 1.23457e28, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.23456e-10, 1.23457e-11, 1e-5 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.111e-10, 1.112e-10, 0.0008999 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.112e-10, 1.111e-10, 0.0008999 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 1 , 1.0001, 1.1e-4 );
BOOST_CHECK_CLOSE_SHOULD_PASS( 1.0002, 1.0001, 1.1e-4 );
BOOST_CHECK_CLOSE_SHOULD_FAIL( 1 , 1.0002, 1.1e-4 );
BOOST_CHECK_CLOSE_SHOULD_PASS_N( 1, 1+std::numeric_limits<FPT>::epsilon() / 2, 1 );
tmp = static_cast<FPT>(1e-10);
BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp+tmp, 2e-10, 1+2 );
tmp = static_cast<FPT>(3.1);
BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp, 9.61, 1+2 );
tmp = 11;
tmp /= 10;
BOOST_CHECK_CLOSE_SHOULD_PASS_N( (tmp*tmp-tmp), 11./100, 1+3 );
BOOST_CHECK_CLOSE_SHOULD_FAIL_N( 100*(tmp*tmp-tmp), 11, 3 );
tmp = static_cast<FPT>(1e15+1e-10);
BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp+tmp*tmp, 2e30+2e-20+4e5, 3+5 );
fp1 = static_cast<FPT>(1.0001);
fp2 = static_cast<FPT>(1001.1001);
tmp = static_cast<FPT>(1.0001);
for( int i=0; i < 1000; i++ )
fp1 = fp1 + tmp;
CHECK_TOOL_USAGE(
BOOST_CHECK_CLOSE( fp1, fp2, 1000 ),
output.is_empty()
);
}
void
test_BOOST_CHECK_CLOSE_all() {
test_BOOST_CHECK_CLOSE<float>( (float)0 );
test_BOOST_CHECK_CLOSE<double>( (double)0 );
test_BOOST_CHECK_CLOSE<long double>( (long double)0 );
double fp1 = 1.00000001;
double fp2 = 1.00000002;
double epsilon = 1e-8;
CHECK_TOOL_USAGE(
BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
output.is_empty()
);
CHECK_TOOL_USAGE(
BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),
output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed ["
<< fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 3 ) )
);
fp1 = 1.23456e-10;
fp2 = 1.23457e-10;
epsilon = 8.1e-6;
CHECK_TOOL_USAGE(
BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
output.is_empty()
);
CHECK_TOOL_USAGE(
BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon ), 2, ( fp1, fp2 ) ),
output.is_equal( CHECK_PATTERN(
"error in " TEST_CASE_NAME ": test close_at_tolerance<double>( epsilon )(fp1, fp2) "
"failed for (" << fp1 << ", " << fp2 << ")\n", 4 ) )
);
}
//____________________________________________________________________________//
test_suite*
init_unit_test_suite( int /*argc*/, char* /*argv*/[] ) {
test_suite* test = BOOST_TEST_SUITE("FP compare test");
test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_CLOSE_all ) );
return test;
}
//____________________________________________________________________________//
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.2 2003/02/15 21:53:39 rogeeff
// cwpro8 fix
//
// Revision 1.1 2003/02/13 08:47:11 rogeeff
// *** empty log message ***
//
// ***************************************************************************
// EOF
<|endoftext|> |
<commit_before><commit_msg>Disable OCSP until we have fixed the crash in OCSP code. As a result our EV checks must fail because EV requires revocation checking. (We aren't downloading CRLs yet.)<commit_after><|endoftext|> |
<commit_before><commit_msg><commit_after><|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/type_traits.h"
#include "base/basictypes.h"
#include <gtest/gtest.h>
namespace base {
namespace {
struct AStruct {};
class AClass {};
union AUnion {};
enum AnEnum { AN_ENUM_APPLE, AN_ENUM_BANANA, AN_ENUM_CARROT };
struct BStruct {
int x;
};
class BClass {
int ALLOW_UNUSED _x;
};
class Parent {};
class Child : public Parent {};
// is_empty<Type>
COMPILE_ASSERT(is_empty<AStruct>::value, IsEmpty);
COMPILE_ASSERT(is_empty<AClass>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BStruct>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BClass>::value, IsEmpty);
// is_pointer<Type>
COMPILE_ASSERT(!is_pointer<int>::value, IsPointer);
COMPILE_ASSERT(!is_pointer<int&>::value, IsPointer);
COMPILE_ASSERT(is_pointer<int*>::value, IsPointer);
COMPILE_ASSERT(is_pointer<const int*>::value, IsPointer);
// is_array<Type>
COMPILE_ASSERT(!is_array<int>::value, IsArray);
COMPILE_ASSERT(!is_array<int*>::value, IsArray);
COMPILE_ASSERT(!is_array<int(*)[3]>::value, IsArray);
COMPILE_ASSERT(is_array<int[]>::value, IsArray);
COMPILE_ASSERT(is_array<const int[]>::value, IsArray);
COMPILE_ASSERT(is_array<int[3]>::value, IsArray);
// is_non_const_reference<Type>
COMPILE_ASSERT(!is_non_const_reference<int>::value, IsNonConstReference);
COMPILE_ASSERT(!is_non_const_reference<const int&>::value, IsNonConstReference);
COMPILE_ASSERT(is_non_const_reference<int&>::value, IsNonConstReference);
// is_convertible<From, To>
// Extra parens needed to make preprocessor macro parsing happy. Otherwise,
// it sees the equivalent of:
//
// (is_convertible < Child), (Parent > ::value)
//
// Silly C++.
COMPILE_ASSERT( (is_convertible<Child, Parent>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, Child>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, AStruct>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int, double>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int*, void*>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<void*, int*>::value), IsConvertible);
// Array types are an easy corner case. Make sure to test that
// it does indeed compile.
COMPILE_ASSERT(!(is_convertible<int[10], double>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<double, int[10]>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int[10], int*>::value), IsConvertible);
// is_same<Type1, Type2>
COMPILE_ASSERT(!(is_same<Child, Parent>::value), IsSame);
COMPILE_ASSERT(!(is_same<Parent, Child>::value), IsSame);
COMPILE_ASSERT( (is_same<Parent, Parent>::value), IsSame);
COMPILE_ASSERT( (is_same<int*, int*>::value), IsSame);
COMPILE_ASSERT( (is_same<int, int>::value), IsSame);
COMPILE_ASSERT( (is_same<void, void>::value), IsSame);
COMPILE_ASSERT(!(is_same<int, double>::value), IsSame);
// is_class<Type>
COMPILE_ASSERT(is_class<AStruct>::value, IsClass);
COMPILE_ASSERT(is_class<AClass>::value, IsClass);
COMPILE_ASSERT(is_class<AUnion>::value, IsClass);
COMPILE_ASSERT(!is_class<AnEnum>::value, IsClass);
COMPILE_ASSERT(!is_class<int>::value, IsClass);
COMPILE_ASSERT(!is_class<char*>::value, IsClass);
COMPILE_ASSERT(!is_class<int&>::value, IsClass);
COMPILE_ASSERT(!is_class<char[3]>::value, IsClass);
// NOTE(gejun): Not work in gcc 3.4 yet.
#if !defined(__GNUC__) || __GNUC__ >= 4
COMPILE_ASSERT((is_enum<AnEnum>::value), IsEnum);
#endif
COMPILE_ASSERT(!(is_enum<AClass>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AStruct>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AUnion>::value), IsEnum);
COMPILE_ASSERT(!is_member_function_pointer<int>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int*>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<void*>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct*>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)()>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)(int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int) const>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int) const>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int) const>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int, int) const>::value,
IsMemberFunctionPointer);
// False because we don't have a specialization for 5 params yet.
COMPILE_ASSERT(!is_member_function_pointer<
int (AStruct::*)(int, int, int, int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<
int (AStruct::*)(int, int, int, int, int) const>::value,
IsMemberFunctionPointer);
// add_const
COMPILE_ASSERT((is_same<add_const<int>::type, const int>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<long>::type, const long>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<std::string>::type, const std::string>::value),
AddConst);
COMPILE_ASSERT((is_same<add_const<const int>::type, const int>::value),
AddConst);
COMPILE_ASSERT((is_same<add_const<const long>::type, const long>::value),
AddConst);
COMPILE_ASSERT((is_same<add_const<const std::string>::type,
const std::string>::value), AddConst);
// add_volatile
COMPILE_ASSERT((is_same<add_volatile<int>::type, volatile int>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<long>::type, volatile long>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<std::string>::type,
volatile std::string>::value), AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile int>::type, volatile int>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile long>::type, volatile long>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile std::string>::type,
volatile std::string>::value), AddVolatile);
// add_reference
COMPILE_ASSERT((is_same<add_reference<int>::type, int&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<long>::type, long&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string>::type, std::string&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<int&>::type, int&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<long&>::type, long&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string&>::type,
std::string&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<const int&>::type, const int&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<const long&>::type, const long&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<const std::string&>::type,
const std::string&>::value), AddReference);
// add_cr_non_integral
COMPILE_ASSERT((is_same<add_cr_non_integral<int>::type, int>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<long>::type, long>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<std::string>::type,
const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int>::type, const int&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long>::type, const long&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string>::type,
const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int&>::type, const int&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long&>::type, const long&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string&>::type,
const std::string&>::value), AddCrNonIntegral);
// remove_const
COMPILE_ASSERT((is_same<remove_const<const int>::type, int>::value),
RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const long>::type, long>::value),
RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const std::string>::type,
std::string>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<int>::type, int>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<long>::type, long>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<std::string>::type, std::string>::value),
RemoveConst);
// remove_reference
COMPILE_ASSERT((is_same<remove_reference<int&>::type, int>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long&>::type, long>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string&>::type,
std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const int&>::type, const int>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const long&>::type, const long>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const std::string&>::type,
const std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<int>::type, int>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long>::type, long>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string>::type, std::string>::value),
RemoveReference);
} // namespace
} // namespace base
<commit_msg>Patch a minor fix to test/type_traits_unittest.cc from svn<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/type_traits.h"
#include "base/basictypes.h"
#include <gtest/gtest.h>
namespace base {
namespace {
struct AStruct {};
class AClass {};
union AUnion {};
enum AnEnum { AN_ENUM_APPLE, AN_ENUM_BANANA, AN_ENUM_CARROT };
struct BStruct {
int x;
};
class BClass {
#if defined(__clang__)
int ALLOW_UNUSED _x;
#else
int _x;
#endif
};
class Parent {};
class Child : public Parent {};
// is_empty<Type>
COMPILE_ASSERT(is_empty<AStruct>::value, IsEmpty);
COMPILE_ASSERT(is_empty<AClass>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BStruct>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BClass>::value, IsEmpty);
// is_pointer<Type>
COMPILE_ASSERT(!is_pointer<int>::value, IsPointer);
COMPILE_ASSERT(!is_pointer<int&>::value, IsPointer);
COMPILE_ASSERT(is_pointer<int*>::value, IsPointer);
COMPILE_ASSERT(is_pointer<const int*>::value, IsPointer);
// is_array<Type>
COMPILE_ASSERT(!is_array<int>::value, IsArray);
COMPILE_ASSERT(!is_array<int*>::value, IsArray);
COMPILE_ASSERT(!is_array<int(*)[3]>::value, IsArray);
COMPILE_ASSERT(is_array<int[]>::value, IsArray);
COMPILE_ASSERT(is_array<const int[]>::value, IsArray);
COMPILE_ASSERT(is_array<int[3]>::value, IsArray);
// is_non_const_reference<Type>
COMPILE_ASSERT(!is_non_const_reference<int>::value, IsNonConstReference);
COMPILE_ASSERT(!is_non_const_reference<const int&>::value, IsNonConstReference);
COMPILE_ASSERT(is_non_const_reference<int&>::value, IsNonConstReference);
// is_convertible<From, To>
// Extra parens needed to make preprocessor macro parsing happy. Otherwise,
// it sees the equivalent of:
//
// (is_convertible < Child), (Parent > ::value)
//
// Silly C++.
COMPILE_ASSERT( (is_convertible<Child, Parent>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, Child>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, AStruct>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int, double>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int*, void*>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<void*, int*>::value), IsConvertible);
// Array types are an easy corner case. Make sure to test that
// it does indeed compile.
COMPILE_ASSERT(!(is_convertible<int[10], double>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<double, int[10]>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int[10], int*>::value), IsConvertible);
// is_same<Type1, Type2>
COMPILE_ASSERT(!(is_same<Child, Parent>::value), IsSame);
COMPILE_ASSERT(!(is_same<Parent, Child>::value), IsSame);
COMPILE_ASSERT( (is_same<Parent, Parent>::value), IsSame);
COMPILE_ASSERT( (is_same<int*, int*>::value), IsSame);
COMPILE_ASSERT( (is_same<int, int>::value), IsSame);
COMPILE_ASSERT( (is_same<void, void>::value), IsSame);
COMPILE_ASSERT(!(is_same<int, double>::value), IsSame);
// is_class<Type>
COMPILE_ASSERT(is_class<AStruct>::value, IsClass);
COMPILE_ASSERT(is_class<AClass>::value, IsClass);
COMPILE_ASSERT(is_class<AUnion>::value, IsClass);
COMPILE_ASSERT(!is_class<AnEnum>::value, IsClass);
COMPILE_ASSERT(!is_class<int>::value, IsClass);
COMPILE_ASSERT(!is_class<char*>::value, IsClass);
COMPILE_ASSERT(!is_class<int&>::value, IsClass);
COMPILE_ASSERT(!is_class<char[3]>::value, IsClass);
// NOTE(gejun): Not work in gcc 3.4 yet.
#if !defined(__GNUC__) || __GNUC__ >= 4
COMPILE_ASSERT((is_enum<AnEnum>::value), IsEnum);
#endif
COMPILE_ASSERT(!(is_enum<AClass>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AStruct>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AUnion>::value), IsEnum);
COMPILE_ASSERT(!is_member_function_pointer<int>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int*>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<void*>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct*>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)()>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)(int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int) const>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int) const>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int) const>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
int (AStruct::*)(int, int, int, int) const>::value,
IsMemberFunctionPointer);
// False because we don't have a specialization for 5 params yet.
COMPILE_ASSERT(!is_member_function_pointer<
int (AStruct::*)(int, int, int, int, int)>::value,
IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<
int (AStruct::*)(int, int, int, int, int) const>::value,
IsMemberFunctionPointer);
// add_const
COMPILE_ASSERT((is_same<add_const<int>::type, const int>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<long>::type, const long>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<std::string>::type, const std::string>::value),
AddConst);
COMPILE_ASSERT((is_same<add_const<const int>::type, const int>::value),
AddConst);
COMPILE_ASSERT((is_same<add_const<const long>::type, const long>::value),
AddConst);
COMPILE_ASSERT((is_same<add_const<const std::string>::type,
const std::string>::value), AddConst);
// add_volatile
COMPILE_ASSERT((is_same<add_volatile<int>::type, volatile int>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<long>::type, volatile long>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<std::string>::type,
volatile std::string>::value), AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile int>::type, volatile int>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile long>::type, volatile long>::value),
AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile std::string>::type,
volatile std::string>::value), AddVolatile);
// add_reference
COMPILE_ASSERT((is_same<add_reference<int>::type, int&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<long>::type, long&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string>::type, std::string&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<int&>::type, int&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<long&>::type, long&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string&>::type,
std::string&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<const int&>::type, const int&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<const long&>::type, const long&>::value),
AddReference);
COMPILE_ASSERT((is_same<add_reference<const std::string&>::type,
const std::string&>::value), AddReference);
// add_cr_non_integral
COMPILE_ASSERT((is_same<add_cr_non_integral<int>::type, int>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<long>::type, long>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<std::string>::type,
const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int>::type, const int&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long>::type, const long&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string>::type,
const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int&>::type, const int&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long&>::type, const long&>::value),
AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string&>::type,
const std::string&>::value), AddCrNonIntegral);
// remove_const
COMPILE_ASSERT((is_same<remove_const<const int>::type, int>::value),
RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const long>::type, long>::value),
RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const std::string>::type,
std::string>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<int>::type, int>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<long>::type, long>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<std::string>::type, std::string>::value),
RemoveConst);
// remove_reference
COMPILE_ASSERT((is_same<remove_reference<int&>::type, int>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long&>::type, long>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string&>::type,
std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const int&>::type, const int>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const long&>::type, const long>::value),
RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const std::string&>::type,
const std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<int>::type, int>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long>::type, long>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string>::type, std::string>::value),
RemoveReference);
} // namespace
} // namespace base
<|endoftext|> |
<commit_before>#ifndef SIGNALSRLATCH_HPP_INCLUDED
#define SIGNALSRLATCH_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"
//!
//! @file SignalSRlatch.hpp
//! @author Petter Krus <[email protected]>
//! @date Fri 28 Jun 2013 13:01:40
//! @brief S-R latch
//! @ingroup SignalComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalFFBDcomponents.nb*/
using namespace hopsan;
class SignalSRlatch : public ComponentSignal
{
private:
int mNstep;
//==This code has been autogenerated using Compgen==
//inputVariables
double setCond;
double resetCond;
//outputVariables
double Qstate;
double notQstate;
//InitialExpressions variables
double oldQstate;
double oldSetCond;
double oldResetCond;
//Expressions variables
double DsetCond;
double DresetCond;
//Delay declarations
//==This code has been autogenerated using Compgen==
//inputVariables pointers
double *mpsetCond;
double *mpresetCond;
//inputParameters pointers
//outputVariables pointers
double *mpQstate;
double *mpnotQstate;
EquationSystemSolver *mpSolver;
public:
static Component *Creator()
{
return new SignalSRlatch();
}
void configure()
{
//==This code has been autogenerated using Compgen==
mNstep=9;
//Add ports to the component
//Add inputVariables to the component
addInputVariable("setCond","On condition","",0.,&mpsetCond);
addInputVariable("resetCond","off condition","",0.,&mpresetCond);
//Add inputParammeters to the component
//Add outputVariables to the component
addOutputVariable("Qstate","Logical state","",0.,&mpQstate);
addOutputVariable("notQstate","Logical inverse of \
state","",0.,&mpnotQstate);
//==This code has been autogenerated using Compgen==
//Add constantParameters
}
void initialize()
{
//Read port variable pointers from nodes
//Read variables from nodes
//Read inputVariables from nodes
setCond = (*mpsetCond);
resetCond = (*mpresetCond);
//Read inputParameters from nodes
//Read outputVariables from nodes
Qstate = (*mpQstate);
notQstate = (*mpnotQstate);
//==This code has been autogenerated using Compgen==
//InitialExpressions
oldQstate = Qstate;
oldSetCond = setCond;
oldResetCond = resetCond;
//Initialize delays
}
void simulateOneTimestep()
{
//Read variables from nodes
//Read inputVariables from nodes
setCond = (*mpsetCond);
resetCond = (*mpresetCond);
//LocalExpressions
//Expressions
DsetCond = onPositive(-oldSetCond + setCond);
DresetCond = onPositive(-oldResetCond + resetCond);
Qstate = -0.5 - onPositive(-0.5 + DresetCond) + onPositive(-0.5 + \
DsetCond) + onPositive(-0.5 + oldQstate);
oldQstate = Qstate;
notQstate = 1 - Qstate;
//Calculate the delayed parts
//Write new values to nodes
//outputVariables
(*mpQstate)=Qstate;
(*mpnotQstate)=notQstate;
//Update the delayed variabels
}
void deconfigure()
{
delete mpSolver;
}
};
#endif // SIGNALSRLATCH_HPP_INCLUDED
<commit_msg>Behaviour corrected<commit_after>#ifndef SIGNALSRLATCH_HPP_INCLUDED
#define SIGNALSRLATCH_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"
//!
//! @file SignalSRlatch.hpp
//! @author Petter Krus <[email protected]>
//! @date Wed 16 Oct 2013 09:59:45
//! @brief S-R latch
//! @ingroup SignalComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalFFBDcomponents.nb*/
using namespace hopsan;
class SignalSRlatch : public ComponentSignal
{
private:
int mNstep;
//==This code has been autogenerated using Compgen==
//inputVariables
double setCond;
double resetCond;
//outputVariables
double Qstate;
double notQstate;
//InitialExpressions variables
double oldQstate;
double oldSetCond;
double oldResetCond;
//Expressions variables
double DsetCond;
double DresetCond;
//Delay declarations
//==This code has been autogenerated using Compgen==
//inputVariables pointers
double *mpsetCond;
double *mpresetCond;
//inputParameters pointers
//outputVariables pointers
double *mpQstate;
double *mpnotQstate;
EquationSystemSolver *mpSolver;
public:
static Component *Creator()
{
return new SignalSRlatch();
}
void configure()
{
//==This code has been autogenerated using Compgen==
mNstep=9;
//Add ports to the component
//Add inputVariables to the component
addInputVariable("setCond","On condition","",0.,&mpsetCond);
addInputVariable("resetCond","off condition","",0.,&mpresetCond);
//Add inputParammeters to the component
//Add outputVariables to the component
addOutputVariable("Qstate","Logical state","",0.,&mpQstate);
addOutputVariable("notQstate","Logical inverse of \
state","",0.,&mpnotQstate);
//==This code has been autogenerated using Compgen==
//Add constantParameters
}
void initialize()
{
//Read port variable pointers from nodes
//Read variables from nodes
//Read inputVariables from nodes
setCond = (*mpsetCond);
resetCond = (*mpresetCond);
//Read inputParameters from nodes
//Read outputVariables from nodes
Qstate = (*mpQstate);
notQstate = (*mpnotQstate);
//==This code has been autogenerated using Compgen==
//InitialExpressions
oldQstate = Qstate;
oldSetCond = setCond;
oldResetCond = resetCond;
//Initialize delays
}
void simulateOneTimestep()
{
//Read variables from nodes
//Read inputVariables from nodes
setCond = (*mpsetCond);
resetCond = (*mpresetCond);
//LocalExpressions
//Expressions
DsetCond = onPositive(-oldSetCond + setCond);
DresetCond = onPositive(-oldResetCond + resetCond);
Qstate = limit(-2*onPositive(-0.5 + DresetCond) + 2*onPositive(-0.5 \
+ DsetCond) + 2*onPositive(-0.5 + oldQstate),0,1);
oldQstate = Qstate;
notQstate = 1 - Qstate;
//Calculate the delayed parts
//Write new values to nodes
//outputVariables
(*mpQstate)=Qstate;
(*mpnotQstate)=notQstate;
//Update the delayed variabels
}
void deconfigure()
{
delete mpSolver;
}
};
#endif // SIGNALSRLATCH_HPP_INCLUDED
<|endoftext|> |
<commit_before>#ifndef SLIC3RXS
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <initializer_list>
#include <memory>
#include <regex>
#include "PrintConfig.hpp"
#include "ConfigBase.hpp"
namespace Slic3r {
/// Exception class for invalid (but correct type) option values.
/// Thrown by validate()
class InvalidOptionValue : public std::runtime_error {
public:
InvalidOptionValue(const char* v) : runtime_error(v) {}
InvalidOptionValue(const std::string v) : runtime_error(v.c_str()) {}
};
/// Exception class to handle config options that don't exist.
class InvalidConfigOption : public std::runtime_error {};
/// Exception class for type mismatches
class InvalidOptionType : public std::runtime_error {
public:
InvalidOptionType(const char* v) : runtime_error(v) {}
InvalidOptionType(const std::string v) : runtime_error(v.c_str()) {}
};
class Config;
using config_ptr = std::shared_ptr<Config>;
class Config {
public:
/// Factory method to construct a Config with all default values loaded.
static std::shared_ptr<Config> new_from_defaults();
/// Factory method to construct a Config with specific default values loaded.
static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init);
/// Factory method to construct a Config with specific default values loaded.
static std::shared_ptr<Config> new_from_defaults(t_config_option_keys init);
/// Factory method to construct a Config from CLI options.
static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]);
/// Factory method to construct a Config from an ini file.
static std::shared_ptr<Config> new_from_ini(const std::string& inifile);
/// Write a windows-style opt=value ini file with categories from the configuration store.
void write_ini(const std::string& file) const;
/// Parse a windows-style opt=value ini file with categories and load the configuration store.
void read_ini(const std::string& file);
/// Template function to retrieve and cast in hopefully a slightly nicer
/// format than longwinded dynamic_cast<>
template <class T>
T& get(const t_config_option_key& opt_key, bool create=false) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return *(dynamic_cast<T*>(this->_config.optptr(opt_key, create)));
}
double getFloat(const t_config_option_key& opt_key, bool create=false) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getFloat();
}
int getInt(const t_config_option_key& opt_key, bool create=false) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getInt();
}
std::string getString(const t_config_option_key& opt_key, bool create=false) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getString();
}
/// Template function to dynamic cast and leave it in pointer form.
template <class T>
T* get_ptr(const t_config_option_key& opt_key, bool create=false) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return dynamic_cast<T*>(this->_config.optptr(opt_key, create));
}
/// Function to parse value from a string to whatever opt_key is.
void set(const t_config_option_key& opt_key, const std::string& value);
/// Function to parse value from an integer to whatever opt_key is, if
/// opt_key is a numeric type. This will throw an exception and do
/// nothing if called with an incorrect type.
void set(const t_config_option_key& opt_key, const int value);
/// Function to parse value from an integer to whatever opt_key is, if
/// opt_key is a numeric type. This will throw an exception and do
/// nothing if called with an incorrect type.
void set(const t_config_option_key& opt_key, const double value);
/// Method to validate the different configuration options.
/// It will throw InvalidConfigOption exceptions on failure.
bool validate();
const DynamicPrintConfig& config() const { return _config; }
bool empty() const { return _config.empty(); }
/// Pass-through of apply()
void apply(const config_ptr& other) { _config.apply(other->config()); }
void apply(const Slic3r::Config& other) { _config.apply(other.config()); }
Config();
private:
std::regex _cli_pattern {"=(.+)$"};
std::smatch _match_info {};
/// Underlying configuration store.
DynamicPrintConfig _config {};
};
bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);
bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);
} // namespace Slic3r
#endif // CONFIG_HPP
#endif // SLIC3RXS
<commit_msg>Default to pulling from defaults with get() functions.<commit_after>#ifndef SLIC3RXS
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <initializer_list>
#include <memory>
#include <regex>
#include "PrintConfig.hpp"
#include "ConfigBase.hpp"
namespace Slic3r {
/// Exception class for invalid (but correct type) option values.
/// Thrown by validate()
class InvalidOptionValue : public std::runtime_error {
public:
InvalidOptionValue(const char* v) : runtime_error(v) {}
InvalidOptionValue(const std::string v) : runtime_error(v.c_str()) {}
};
/// Exception class to handle config options that don't exist.
class InvalidConfigOption : public std::runtime_error {};
/// Exception class for type mismatches
class InvalidOptionType : public std::runtime_error {
public:
InvalidOptionType(const char* v) : runtime_error(v) {}
InvalidOptionType(const std::string v) : runtime_error(v.c_str()) {}
};
class Config;
using config_ptr = std::shared_ptr<Config>;
class Config {
public:
/// Factory method to construct a Config with all default values loaded.
static std::shared_ptr<Config> new_from_defaults();
/// Factory method to construct a Config with specific default values loaded.
static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init);
/// Factory method to construct a Config with specific default values loaded.
static std::shared_ptr<Config> new_from_defaults(t_config_option_keys init);
/// Factory method to construct a Config from CLI options.
static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]);
/// Factory method to construct a Config from an ini file.
static std::shared_ptr<Config> new_from_ini(const std::string& inifile);
/// Write a windows-style opt=value ini file with categories from the configuration store.
void write_ini(const std::string& file) const;
/// Parse a windows-style opt=value ini file with categories and load the configuration store.
void read_ini(const std::string& file);
double getFloat(const t_config_option_key& opt_key, bool create=true) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getFloat();
}
int getInt(const t_config_option_key& opt_key, bool create=true) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getInt();
}
std::string getString(const t_config_option_key& opt_key, bool create=true) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getString();
}
/// Template function to dynamic cast and leave it in pointer form.
template <class T>
T* get_ptr(const t_config_option_key& opt_key, bool create=true) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return dynamic_cast<T*>(this->_config.optptr(opt_key, create));
}
/// Template function to retrieve and cast in hopefully a slightly nicer
/// format than longwinded dynamic_cast<>
template <class T>
T& get(const t_config_option_key& opt_key, bool create=true) {
if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
return *(dynamic_cast<T*>(this->_config.optptr(opt_key, create)));
}
/// Function to parse value from a string to whatever opt_key is.
void set(const t_config_option_key& opt_key, const std::string& value);
/// Function to parse value from an integer to whatever opt_key is, if
/// opt_key is a numeric type. This will throw an exception and do
/// nothing if called with an incorrect type.
void set(const t_config_option_key& opt_key, const int value);
/// Function to parse value from an integer to whatever opt_key is, if
/// opt_key is a numeric type. This will throw an exception and do
/// nothing if called with an incorrect type.
void set(const t_config_option_key& opt_key, const double value);
/// Method to validate the different configuration options.
/// It will throw InvalidConfigOption exceptions on failure.
bool validate();
const DynamicPrintConfig& config() const { return _config; }
bool empty() const { return _config.empty(); }
/// Pass-through of apply()
void apply(const config_ptr& other) { _config.apply(other->config()); }
void apply(const Slic3r::Config& other) { _config.apply(other.config()); }
Config();
private:
std::regex _cli_pattern {"=(.+)$"};
std::smatch _match_info {};
/// Underlying configuration store.
DynamicPrintConfig _config {};
};
bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);
bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);
} // namespace Slic3r
#endif // CONFIG_HPP
#endif // SLIC3RXS
<|endoftext|> |
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/execution/executor/new_executor_traits/is_simple_executor.hpp>
#include <agency/execution/executor/new_executor_traits/is_bulk_executor.hpp>
namespace agency
{
template<class T>
using new_is_executor = agency::detail::disjunction<
is_simple_executor<T>,
is_bulk_executor<T>
>;
namespace detail
{
// a fake Concept to use with __AGENCY_REQUIRES
template<class T>
constexpr bool Executor()
{
return is_executor<T>();
}
} // end detail
} // end agency
<commit_msg>Fix the implementation of detail::Executor()<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/execution/executor/new_executor_traits/is_simple_executor.hpp>
#include <agency/execution/executor/new_executor_traits/is_bulk_executor.hpp>
namespace agency
{
template<class T>
using new_is_executor = agency::detail::disjunction<
is_simple_executor<T>,
is_bulk_executor<T>
>;
namespace detail
{
// a fake Concept to use with __AGENCY_REQUIRES
template<class T>
constexpr bool Executor()
{
return new_is_executor<T>();
}
} // end detail
} // end agency
<|endoftext|> |
<commit_before>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "Serialization\JsObjectsSerialization.h"
#include "Async/JavascriptAsyncMethodCallback.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
const CefString CefAppUnmanagedWrapper::kPromiseCreatorFunction = "cefsharp_CreatePromise";
const CefString CefAppUnmanagedWrapper::kPromiseCreatorScript = ""
"function cefsharp_CreatePromise() {"
" var object = {};"
" var promise = new Promise(function(resolve, reject) {"
" object.resolve = resolve;object.reject = reject;"
" });"
" return{ p: promise, res : object.resolve, rej: object.reject};"
"}";
CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
{
return this;
};
// CefRenderProcessHandler
void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
auto wrapper = gcnew CefBrowserWrapper(browser);
_onBrowserCreated->Invoke(wrapper);
//Multiple CefBrowserWrappers created when opening popups
_browserWrappers->TryAdd(browser->GetIdentifier(), wrapper);
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
CefBrowserWrapper^ wrapper;
if (_browserWrappers->TryRemove(browser->GetIdentifier(), wrapper))
{
_onBrowserDestroyed->Invoke(wrapper);
delete wrapper;
}
};
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (!Object::ReferenceEquals(_javascriptRootObject, nullptr) || !Object::ReferenceEquals(_javascriptAsyncRootObject, nullptr))
{
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
auto frameId = frame->GetIdentifier();
if (rootObjectWrappers->ContainsKey(frameId))
{
LOG(WARNING) << "A context has been created for the same browser / frame without context released called previously";
}
else
{
auto rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), browserWrapper->BrowserProcess);
rootObject->Bind(_javascriptRootObject, _javascriptAsyncRootObject, context->GetGlobal());
rootObjectWrappers->TryAdd(frameId, rootObject);
}
}
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
JavascriptRootObjectWrapper^ wrapper;
if (rootObjectWrappers->TryRemove(frame->GetIdentifier(), wrapper))
{
delete wrapper;
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
if (name == kJavascriptCallbackDestroyRequest ||
name == kJavascriptRootObjectRequest ||
name == kJavascriptAsyncMethodCallResponse)
{
//If we can't find the browser wrapper then we'll just
//ignore this as it's likely already been disposed of
return true;
}
CefString responseName;
if (name == kEvaluateJavascriptRequest)
{
responseName = kEvaluateJavascriptResponse;
}
else if (name == kJavascriptCallbackRequest)
{
responseName = kJavascriptCallbackResponse;
}
else
{
//TODO: Should be throw an exception here? It's likely that only a CefSharp developer would see this
// when they added a new message and havn't yet implemented the render process functionality.
throw gcnew Exception("Unsupported message type");
}
auto callbackId = GetInt64(argList, 1);
auto response = CefProcessMessage::Create(responseName);
auto responseArgList = response->GetArgumentList();
auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());
//success: false
responseArgList->SetBool(0, false);
SetInt64(callbackId, responseArgList, 1);
responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
browser->SendProcessMessage(sourceProcessId, response);
return true;
}
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool success;
CefRefPtr<CefV8Value> result;
CefString errorMessage;
CefRefPtr<CefProcessMessage> response;
//both messages have the frameId stored at 0 and callbackId stored at index 1
auto frameId = GetInt64(argList, 0);
int64 callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
auto callbackRegistry = rootObjectWrapper == nullptr ? nullptr : rootObjectWrapper->CallbackRegistry;
if (callbackRegistry == nullptr)
{
success = false;
errorMessage = StringUtils::ToNative("Frame " + frameId + " is no longer available, most likely the Frame has been Disposed.");
}
else if (name == kEvaluateJavascriptRequest)
{
auto script = argList->GetString(2);
response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
if (context.get() && context->Enter())
{
try
{
CefRefPtr<CefV8Exception> exception;
success = context->Eval(script, result, exception);
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
errorMessage = exception->GetMessage();
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
else
{
errorMessage = "Unable to Get Frame matching Id";
}
}
else
{
auto jsCallbackId = GetInt64(argList, 2);
auto parameterList = argList->GetList(3);
CefV8ValueList params;
for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
{
params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
}
response = CefProcessMessage::Create(kJavascriptCallbackResponse);
auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
auto context = callbackWrapper->GetContext();
auto value = callbackWrapper->GetValue();
if (context.get() && context->Enter())
{
try
{
result = value->ExecuteFunction(nullptr, params);
success = result.get() != nullptr;
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
auto exception = value->GetException();
if (exception.get())
{
errorMessage = exception->GetMessage();
}
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
if (response.get())
{
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(callbackId, responseArgList, 1);
if (!success)
{
responseArgList->SetString(2, errorMessage);
}
browser->SendProcessMessage(sourceProcessId, response);
}
handled = true;
}
else if (name == kJavascriptCallbackDestroyRequest)
{
auto jsCallbackId = GetInt64(argList, 0);
auto frameId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr && rootObjectWrapper->CallbackRegistry != nullptr)
{
rootObjectWrapper->CallbackRegistry->Deregister(jsCallbackId);
}
handled = true;
}
else if (name == kJavascriptRootObjectRequest)
{
_javascriptAsyncRootObject = DeserializeJsRootObject(argList, 0);
_javascriptRootObject = DeserializeJsRootObject(argList, 1);
handled = true;
}
else if (name == kJavascriptAsyncMethodCallResponse)
{
auto frameId = GetInt64(argList, 0);
auto callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr)
{
JavascriptAsyncMethodCallback^ callback;
if (rootObjectWrapper->TryGetAndRemoveMethodCallback(callbackId, callback))
{
auto success = argList->GetBool(2);
if (success)
{
callback->Success(DeserializeV8Object(argList, 3));
}
else
{
callback->Fail(argList->GetString(3));
}
//dispose
delete callback;
}
}
handled = true;
}
return handled;
};
void CefAppUnmanagedWrapper::OnRenderThreadCreated(CefRefPtr<CefListValue> extraInfo)
{
auto extensionList = extraInfo->GetList(0);
for (size_t i = 0; i < extensionList->GetSize(); i++)
{
auto extension = extensionList->GetList(i);
auto ext = gcnew CefExtension(StringUtils::ToClr(extension->GetString(0)), StringUtils::ToClr(extension->GetString(1)));
_extensions->Add(ext);
}
}
void CefAppUnmanagedWrapper::OnWebKitInitialized()
{
//we need to do this because the builtin Promise object is not accesible
CefRegisterExtension("cefsharp/promisecreator", kPromiseCreatorScript, NULL);
for each(CefExtension^ extension in _extensions->AsReadOnly())
{
//only support extensions without handlers now
CefRegisterExtension(StringUtils::ToNative(extension->Name), StringUtils::ToNative(extension->JavascriptCode), NULL);
}
}
void CefAppUnmanagedWrapper::OnRegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar)
{
for each (CefCustomScheme^ scheme in _schemes->AsReadOnly())
{
registrar->AddCustomScheme(StringUtils::ToNative(scheme->SchemeName), scheme->IsStandard, scheme->IsLocal, scheme->IsDisplayIsolated);
}
}
}<commit_msg>create a root object even if no objects have been registered but only bind the root object if objects are available<commit_after>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "Serialization\JsObjectsSerialization.h"
#include "Async/JavascriptAsyncMethodCallback.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
const CefString CefAppUnmanagedWrapper::kPromiseCreatorFunction = "cefsharp_CreatePromise";
const CefString CefAppUnmanagedWrapper::kPromiseCreatorScript = ""
"function cefsharp_CreatePromise() {"
" var object = {};"
" var promise = new Promise(function(resolve, reject) {"
" object.resolve = resolve;object.reject = reject;"
" });"
" return{ p: promise, res : object.resolve, rej: object.reject};"
"}";
CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
{
return this;
};
// CefRenderProcessHandler
void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
auto wrapper = gcnew CefBrowserWrapper(browser);
_onBrowserCreated->Invoke(wrapper);
//Multiple CefBrowserWrappers created when opening popups
_browserWrappers->TryAdd(browser->GetIdentifier(), wrapper);
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
CefBrowserWrapper^ wrapper;
if (_browserWrappers->TryRemove(browser->GetIdentifier(), wrapper))
{
_onBrowserDestroyed->Invoke(wrapper);
delete wrapper;
}
};
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
auto frameId = frame->GetIdentifier();
if (rootObjectWrappers->ContainsKey(frameId))
{
LOG(WARNING) << "A context has been created for the same browser / frame without context released called previously";
}
else
{
auto rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), browserWrapper->BrowserProcess);
if (!Object::ReferenceEquals(_javascriptRootObject, nullptr) || !Object::ReferenceEquals(_javascriptAsyncRootObject, nullptr))
{
rootObject->Bind(_javascriptRootObject, _javascriptAsyncRootObject, context->GetGlobal());
}
rootObjectWrappers->TryAdd(frameId, rootObject);
}
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
JavascriptRootObjectWrapper^ wrapper;
if (rootObjectWrappers->TryRemove(frame->GetIdentifier(), wrapper))
{
delete wrapper;
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
if (name == kJavascriptCallbackDestroyRequest ||
name == kJavascriptRootObjectRequest ||
name == kJavascriptAsyncMethodCallResponse)
{
//If we can't find the browser wrapper then we'll just
//ignore this as it's likely already been disposed of
return true;
}
CefString responseName;
if (name == kEvaluateJavascriptRequest)
{
responseName = kEvaluateJavascriptResponse;
}
else if (name == kJavascriptCallbackRequest)
{
responseName = kJavascriptCallbackResponse;
}
else
{
//TODO: Should be throw an exception here? It's likely that only a CefSharp developer would see this
// when they added a new message and havn't yet implemented the render process functionality.
throw gcnew Exception("Unsupported message type");
}
auto callbackId = GetInt64(argList, 1);
auto response = CefProcessMessage::Create(responseName);
auto responseArgList = response->GetArgumentList();
auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());
//success: false
responseArgList->SetBool(0, false);
SetInt64(callbackId, responseArgList, 1);
responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
browser->SendProcessMessage(sourceProcessId, response);
return true;
}
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool success;
CefRefPtr<CefV8Value> result;
CefString errorMessage;
CefRefPtr<CefProcessMessage> response;
//both messages have the frameId stored at 0 and callbackId stored at index 1
auto frameId = GetInt64(argList, 0);
int64 callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
auto callbackRegistry = rootObjectWrapper == nullptr ? nullptr : rootObjectWrapper->CallbackRegistry;
if (callbackRegistry == nullptr)
{
success = false;
errorMessage = StringUtils::ToNative("Frame " + frameId + " is no longer available, most likely the Frame has been Disposed.");
}
else if (name == kEvaluateJavascriptRequest)
{
auto script = argList->GetString(2);
response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
if (context.get() && context->Enter())
{
try
{
CefRefPtr<CefV8Exception> exception;
success = context->Eval(script, result, exception);
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
errorMessage = exception->GetMessage();
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
else
{
errorMessage = "Unable to Get Frame matching Id";
}
}
else
{
auto jsCallbackId = GetInt64(argList, 2);
auto parameterList = argList->GetList(3);
CefV8ValueList params;
for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
{
params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
}
response = CefProcessMessage::Create(kJavascriptCallbackResponse);
auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
auto context = callbackWrapper->GetContext();
auto value = callbackWrapper->GetValue();
if (context.get() && context->Enter())
{
try
{
result = value->ExecuteFunction(nullptr, params);
success = result.get() != nullptr;
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
auto exception = value->GetException();
if (exception.get())
{
errorMessage = exception->GetMessage();
}
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
if (response.get())
{
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(callbackId, responseArgList, 1);
if (!success)
{
responseArgList->SetString(2, errorMessage);
}
browser->SendProcessMessage(sourceProcessId, response);
}
handled = true;
}
else if (name == kJavascriptCallbackDestroyRequest)
{
auto jsCallbackId = GetInt64(argList, 0);
auto frameId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr && rootObjectWrapper->CallbackRegistry != nullptr)
{
rootObjectWrapper->CallbackRegistry->Deregister(jsCallbackId);
}
handled = true;
}
else if (name == kJavascriptRootObjectRequest)
{
_javascriptAsyncRootObject = DeserializeJsRootObject(argList, 0);
_javascriptRootObject = DeserializeJsRootObject(argList, 1);
handled = true;
}
else if (name == kJavascriptAsyncMethodCallResponse)
{
auto frameId = GetInt64(argList, 0);
auto callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr)
{
JavascriptAsyncMethodCallback^ callback;
if (rootObjectWrapper->TryGetAndRemoveMethodCallback(callbackId, callback))
{
auto success = argList->GetBool(2);
if (success)
{
callback->Success(DeserializeV8Object(argList, 3));
}
else
{
callback->Fail(argList->GetString(3));
}
//dispose
delete callback;
}
}
handled = true;
}
return handled;
};
void CefAppUnmanagedWrapper::OnRenderThreadCreated(CefRefPtr<CefListValue> extraInfo)
{
auto extensionList = extraInfo->GetList(0);
for (size_t i = 0; i < extensionList->GetSize(); i++)
{
auto extension = extensionList->GetList(i);
auto ext = gcnew CefExtension(StringUtils::ToClr(extension->GetString(0)), StringUtils::ToClr(extension->GetString(1)));
_extensions->Add(ext);
}
}
void CefAppUnmanagedWrapper::OnWebKitInitialized()
{
//we need to do this because the builtin Promise object is not accesible
CefRegisterExtension("cefsharp/promisecreator", kPromiseCreatorScript, NULL);
for each(CefExtension^ extension in _extensions->AsReadOnly())
{
//only support extensions without handlers now
CefRegisterExtension(StringUtils::ToNative(extension->Name), StringUtils::ToNative(extension->JavascriptCode), NULL);
}
}
void CefAppUnmanagedWrapper::OnRegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar)
{
for each (CefCustomScheme^ scheme in _schemes->AsReadOnly())
{
registrar->AddCustomScheme(StringUtils::ToNative(scheme->SchemeName), scheme->IsStandard, scheme->IsLocal, scheme->IsDisplayIsolated);
}
}
}<|endoftext|> |
<commit_before>// @(#)root/thread:$Id$
// Author: Enric Tejedor, CERN 12/09/2016
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class ROOT::TTreeProcessorMT
\ingroup Parallelism
\brief A class to process the entries of a TTree in parallel.
By means of its Process method, ROOT::TTreeProcessorMT provides a way to process the
entries of a TTree in parallel. When invoking TTreeProcessor::Process, the user
passes a function whose only parameter is a TTreeReader. The function iterates
on a subrange of entries by using that TTreeReader.
The implementation of ROOT::TTreeProcessorMT parallelizes the processing of the subranges,
each corresponding to a cluster in the TTree. This is possible thanks to the use
of a ROOT::TThreadedObject, so that each thread works with its own TFile and TTree
objects.
*/
#include "TROOT.h"
#include "ROOT/TTreeProcessorMT.hxx"
#include "ROOT/TThreadExecutor.hxx"
using namespace ROOT;
namespace ROOT {
namespace Internal {
////////////////////////////////////////////////////////////////////////
/// Return a vector of cluster boundaries for the given tree and files.
ClustersAndEntries
MakeClusters(const std::string &treeName, const std::vector<std::string> &fileNames)
{
// Note that as a side-effect of opening all files that are going to be used in the
// analysis once, all necessary streamers will be loaded into memory.
TDirectory::TContext c;
std::vector<std::vector<EntryCluster>> clustersPerFile;
std::vector<Long64_t> entriesPerFile;
const auto nFileNames = fileNames.size();
Long64_t offset = 0ll;
for (auto i = 0u; i < nFileNames; ++i) {
std::unique_ptr<TFile> f(TFile::Open(fileNames[i].c_str())); // need TFile::Open to load plugins if need be
TTree *t = nullptr; // not a leak, t will be deleted by f
f->GetObject(treeName.c_str(), t);
auto clusterIter = t->GetClusterIterator(0);
Long64_t start = 0ll, end = 0ll;
const Long64_t entries = t->GetEntries();
// Iterate over the clusters in the current file
std::vector<EntryCluster> clusters;
while ((start = clusterIter()) < entries) {
end = clusterIter.GetNextEntry();
// Add the current file's offset to start and end to make them (chain) global
clusters.emplace_back(EntryCluster{start + offset, end + offset});
}
offset += entries;
clustersPerFile.emplace_back(std::move(clusters));
entriesPerFile.emplace_back(entries);
}
return std::make_pair(std::move(clustersPerFile), std::move(entriesPerFile));
}
////////////////////////////////////////////////////////////////////////
/// Return a vector containing the number of entries of each file of each friend TChain
std::vector<std::vector<Long64_t>> GetFriendEntries(const std::vector<std::pair<std::string, std::string>> &friendNames,
const std::vector<std::vector<std::string>> &friendFileNames)
{
std::vector<std::vector<Long64_t>> friendEntries;
const auto nFriends = friendNames.size();
for (auto i = 0u; i < nFriends; ++i) {
std::vector<Long64_t> nEntries;
const auto &thisFriendName = friendNames[i].first;
const auto &thisFriendFiles = friendFileNames[i];
for (const auto &fname : thisFriendFiles) {
std::unique_ptr<TFile> f(TFile::Open(fname.c_str()));
TTree *t = nullptr; // owned by TFile
f->GetObject(thisFriendName.c_str(), t);
nEntries.emplace_back(t->GetEntries());
}
friendEntries.emplace_back(std::move(nEntries));
}
return friendEntries;
}
}
}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a file name.
/// \param[in] filename Name of the file containing the tree to process.
/// \param[in] treename Name of the tree to process. If not provided,
/// the implementation will automatically search for a
/// tree in the file.
TTreeProcessorMT::TTreeProcessorMT(std::string_view filename, std::string_view treename) : treeView(filename, treename) {}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a collection of file names.
/// \param[in] filenames Collection of the names of the files containing the tree to process.
/// \param[in] treename Name of the tree to process. If not provided,
/// the implementation will automatically search for a
/// tree in the collection of files.
TTreeProcessorMT::TTreeProcessorMT(const std::vector<std::string_view> &filenames, std::string_view treename) : treeView(filenames, treename) {}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a TTree.
/// \param[in] tree Tree or chain of files containing the tree to process.
TTreeProcessorMT::TTreeProcessorMT(TTree &tree) : treeView(tree) {}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a TTree and a TEntryList.
/// \param[in] tree Tree or chain of files containing the tree to process.
/// \param[in] entries List of entry numbers to process.
TTreeProcessorMT::TTreeProcessorMT(TTree &tree, TEntryList &entries) : treeView(tree, entries) {}
//////////////////////////////////////////////////////////////////////////////
/// Process the entries of a TTree in parallel. The user-provided function
/// receives a TTreeReader which can be used to iterate on a subrange of
/// entries
/// ~~~{.cpp}
/// TTreeProcessorMT::Process([](TTreeReader& readerSubRange) {
/// // Select branches to read
/// while (readerSubRange.next()) {
/// // Use content of current entry
/// }
/// });
/// ~~~
/// The user needs to be aware that each of the subranges can potentially
/// be processed in parallel. This means that the code of the user function
/// should be thread safe.
///
/// \param[in] func User-defined function that processes a subrange of entries
void TTreeProcessorMT::Process(std::function<void(TTreeReader &)> func)
{
// Enable this IMT use case (activate its locks)
Internal::TParTreeProcessingRAII ptpRAII;
// If an entry list or friend trees are present, we need to generate clusters with global entry numbers,
// so we do it here for all files.
const bool hasFriends = !treeView->GetFriendNames().empty();
const bool hasEntryList = treeView->GetEntryList().GetN() > 0;
const bool shouldRetrieveAllClusters = hasFriends || hasEntryList;
const auto clustersAndEntries = shouldRetrieveAllClusters
? ROOT::Internal::MakeClusters(treeView->GetTreeName(), treeView->GetFileNames())
: ROOT::Internal::ClustersAndEntries{};
const auto &clusters = clustersAndEntries.first;
const auto &entries = clustersAndEntries.second;
// Retrieve number of entries for each file for each friend tree
const auto friendEntries =
hasFriends ? ROOT::Internal::GetFriendEntries(treeView->GetFriendNames(), treeView->GetFriendFileNames())
: std::vector<std::vector<Long64_t>>{};
TThreadExecutor pool;
// Parent task, spawns tasks that process each of the entry clusters for each input file
using ROOT::Internal::EntryCluster;
auto processFile = [&](std::size_t fileIdx) {
// If cluster information is already present, build TChains with all input files and use global entry numbers
// Otherwise get cluster information only for the file we need to process and use local entry numbers
const bool shouldUseGlobalEntries = hasFriends || hasEntryList;
// theseFiles contains either all files or just the single file to process
const auto &theseFiles = shouldUseGlobalEntries ? treeView->GetFileNames()
: std::vector<std::string>({treeView->GetFileNames()[fileIdx]});
// Evaluate clusters (with local entry numbers) and number of entries for this file, if needed
const auto theseClustersAndEntries = shouldUseGlobalEntries
? Internal::ClustersAndEntries{}
: Internal::MakeClusters(treeView->GetTreeName(), theseFiles);
// All clusters for the file to process, either with global or local entry numbers
const auto &thisFileClusters = shouldUseGlobalEntries ? clusters[fileIdx] : theseClustersAndEntries.first[0];
// Either all number of entries or just the ones for this file
const auto &theseEntries =
shouldUseGlobalEntries ? entries : std::vector<Long64_t>({theseClustersAndEntries.second[0]});
auto processCluster = [&](const ROOT::Internal::EntryCluster &c) {
// This task will operate with the tree that contains start
treeView->PushTaskFirstEntry(c.start);
std::unique_ptr<TTreeReader> reader;
std::unique_ptr<TEntryList> elist;
std::tie(reader, elist) = treeView->GetTreeReader(c.start, c.end, theseFiles, theseEntries, friendEntries);
func(*reader);
// In case of task interleaving, we need to load here the tree of the parent task
treeView->PopTaskFirstEntry();
};
pool.Foreach(processCluster, thisFileClusters);
};
std::vector<std::size_t> fileIdxs(treeView->GetFileNames().size());
std::iota(fileIdxs.begin(), fileIdxs.end(), 0u);
pool.Foreach(processFile, fileIdxs);
}
<commit_msg>[TREEPROCMT][NFC] Use Internal:: instead of ROOT::Internal<commit_after>// @(#)root/thread:$Id$
// Author: Enric Tejedor, CERN 12/09/2016
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class ROOT::TTreeProcessorMT
\ingroup Parallelism
\brief A class to process the entries of a TTree in parallel.
By means of its Process method, ROOT::TTreeProcessorMT provides a way to process the
entries of a TTree in parallel. When invoking TTreeProcessor::Process, the user
passes a function whose only parameter is a TTreeReader. The function iterates
on a subrange of entries by using that TTreeReader.
The implementation of ROOT::TTreeProcessorMT parallelizes the processing of the subranges,
each corresponding to a cluster in the TTree. This is possible thanks to the use
of a ROOT::TThreadedObject, so that each thread works with its own TFile and TTree
objects.
*/
#include "TROOT.h"
#include "ROOT/TTreeProcessorMT.hxx"
#include "ROOT/TThreadExecutor.hxx"
using namespace ROOT;
namespace ROOT {
namespace Internal {
////////////////////////////////////////////////////////////////////////
/// Return a vector of cluster boundaries for the given tree and files.
ClustersAndEntries
MakeClusters(const std::string &treeName, const std::vector<std::string> &fileNames)
{
// Note that as a side-effect of opening all files that are going to be used in the
// analysis once, all necessary streamers will be loaded into memory.
TDirectory::TContext c;
std::vector<std::vector<EntryCluster>> clustersPerFile;
std::vector<Long64_t> entriesPerFile;
const auto nFileNames = fileNames.size();
Long64_t offset = 0ll;
for (auto i = 0u; i < nFileNames; ++i) {
std::unique_ptr<TFile> f(TFile::Open(fileNames[i].c_str())); // need TFile::Open to load plugins if need be
TTree *t = nullptr; // not a leak, t will be deleted by f
f->GetObject(treeName.c_str(), t);
auto clusterIter = t->GetClusterIterator(0);
Long64_t start = 0ll, end = 0ll;
const Long64_t entries = t->GetEntries();
// Iterate over the clusters in the current file
std::vector<EntryCluster> clusters;
while ((start = clusterIter()) < entries) {
end = clusterIter.GetNextEntry();
// Add the current file's offset to start and end to make them (chain) global
clusters.emplace_back(EntryCluster{start + offset, end + offset});
}
offset += entries;
clustersPerFile.emplace_back(std::move(clusters));
entriesPerFile.emplace_back(entries);
}
return std::make_pair(std::move(clustersPerFile), std::move(entriesPerFile));
}
////////////////////////////////////////////////////////////////////////
/// Return a vector containing the number of entries of each file of each friend TChain
std::vector<std::vector<Long64_t>> GetFriendEntries(const std::vector<std::pair<std::string, std::string>> &friendNames,
const std::vector<std::vector<std::string>> &friendFileNames)
{
std::vector<std::vector<Long64_t>> friendEntries;
const auto nFriends = friendNames.size();
for (auto i = 0u; i < nFriends; ++i) {
std::vector<Long64_t> nEntries;
const auto &thisFriendName = friendNames[i].first;
const auto &thisFriendFiles = friendFileNames[i];
for (const auto &fname : thisFriendFiles) {
std::unique_ptr<TFile> f(TFile::Open(fname.c_str()));
TTree *t = nullptr; // owned by TFile
f->GetObject(thisFriendName.c_str(), t);
nEntries.emplace_back(t->GetEntries());
}
friendEntries.emplace_back(std::move(nEntries));
}
return friendEntries;
}
}
}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a file name.
/// \param[in] filename Name of the file containing the tree to process.
/// \param[in] treename Name of the tree to process. If not provided,
/// the implementation will automatically search for a
/// tree in the file.
TTreeProcessorMT::TTreeProcessorMT(std::string_view filename, std::string_view treename) : treeView(filename, treename) {}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a collection of file names.
/// \param[in] filenames Collection of the names of the files containing the tree to process.
/// \param[in] treename Name of the tree to process. If not provided,
/// the implementation will automatically search for a
/// tree in the collection of files.
TTreeProcessorMT::TTreeProcessorMT(const std::vector<std::string_view> &filenames, std::string_view treename) : treeView(filenames, treename) {}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a TTree.
/// \param[in] tree Tree or chain of files containing the tree to process.
TTreeProcessorMT::TTreeProcessorMT(TTree &tree) : treeView(tree) {}
////////////////////////////////////////////////////////////////////////
/// Constructor based on a TTree and a TEntryList.
/// \param[in] tree Tree or chain of files containing the tree to process.
/// \param[in] entries List of entry numbers to process.
TTreeProcessorMT::TTreeProcessorMT(TTree &tree, TEntryList &entries) : treeView(tree, entries) {}
//////////////////////////////////////////////////////////////////////////////
/// Process the entries of a TTree in parallel. The user-provided function
/// receives a TTreeReader which can be used to iterate on a subrange of
/// entries
/// ~~~{.cpp}
/// TTreeProcessorMT::Process([](TTreeReader& readerSubRange) {
/// // Select branches to read
/// while (readerSubRange.next()) {
/// // Use content of current entry
/// }
/// });
/// ~~~
/// The user needs to be aware that each of the subranges can potentially
/// be processed in parallel. This means that the code of the user function
/// should be thread safe.
///
/// \param[in] func User-defined function that processes a subrange of entries
void TTreeProcessorMT::Process(std::function<void(TTreeReader &)> func)
{
// Enable this IMT use case (activate its locks)
Internal::TParTreeProcessingRAII ptpRAII;
// If an entry list or friend trees are present, we need to generate clusters with global entry numbers,
// so we do it here for all files.
const bool hasFriends = !treeView->GetFriendNames().empty();
const bool hasEntryList = treeView->GetEntryList().GetN() > 0;
const bool shouldRetrieveAllClusters = hasFriends || hasEntryList;
const auto clustersAndEntries = shouldRetrieveAllClusters
? Internal::MakeClusters(treeView->GetTreeName(), treeView->GetFileNames())
: Internal::ClustersAndEntries{};
const auto &clusters = clustersAndEntries.first;
const auto &entries = clustersAndEntries.second;
// Retrieve number of entries for each file for each friend tree
const auto friendEntries =
hasFriends ? Internal::GetFriendEntries(treeView->GetFriendNames(), treeView->GetFriendFileNames())
: std::vector<std::vector<Long64_t>>{};
TThreadExecutor pool;
// Parent task, spawns tasks that process each of the entry clusters for each input file
using Internal::EntryCluster;
auto processFile = [&](std::size_t fileIdx) {
// If cluster information is already present, build TChains with all input files and use global entry numbers
// Otherwise get cluster information only for the file we need to process and use local entry numbers
const bool shouldUseGlobalEntries = hasFriends || hasEntryList;
// theseFiles contains either all files or just the single file to process
const auto &theseFiles = shouldUseGlobalEntries ? treeView->GetFileNames()
: std::vector<std::string>({treeView->GetFileNames()[fileIdx]});
// Evaluate clusters (with local entry numbers) and number of entries for this file, if needed
const auto theseClustersAndEntries = shouldUseGlobalEntries
? Internal::ClustersAndEntries{}
: Internal::MakeClusters(treeView->GetTreeName(), theseFiles);
// All clusters for the file to process, either with global or local entry numbers
const auto &thisFileClusters = shouldUseGlobalEntries ? clusters[fileIdx] : theseClustersAndEntries.first[0];
// Either all number of entries or just the ones for this file
const auto &theseEntries =
shouldUseGlobalEntries ? entries : std::vector<Long64_t>({theseClustersAndEntries.second[0]});
auto processCluster = [&](const Internal::EntryCluster &c) {
// This task will operate with the tree that contains start
treeView->PushTaskFirstEntry(c.start);
std::unique_ptr<TTreeReader> reader;
std::unique_ptr<TEntryList> elist;
std::tie(reader, elist) = treeView->GetTreeReader(c.start, c.end, theseFiles, theseEntries, friendEntries);
func(*reader);
// In case of task interleaving, we need to load here the tree of the parent task
treeView->PopTaskFirstEntry();
};
pool.Foreach(processCluster, thisFileClusters);
};
std::vector<std::size_t> fileIdxs(treeView->GetFileNames().size());
std::iota(fileIdxs.begin(), fileIdxs.end(), 0u);
pool.Foreach(processFile, fileIdxs);
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* MPIAggregator.cpp
*
* Created on: Feb 20, 2018
* Author: William F Godoy [email protected]
*/
#include "MPIAggregator.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace aggregator
{
MPIAggregator::MPIAggregator() : m_Comm(MPI_COMM_NULL) {}
MPIAggregator::~MPIAggregator()
{
if (m_IsActive)
{
helper::CheckMPIReturn(MPI_Comm_free(&m_Comm),
"freeing aggregators comm in MPIAggregator "
"destructor, not recommended");
}
}
void MPIAggregator::Init(const size_t subStreams, MPI_Comm parentComm) {}
void MPIAggregator::SwapBuffers(const int step) noexcept {}
void MPIAggregator::ResetBuffers() noexcept {}
format::Buffer &MPIAggregator::GetConsumerBuffer(format::Buffer &buffer)
{
return buffer;
}
void MPIAggregator::Close()
{
if (m_IsActive)
{
helper::CheckMPIReturn(MPI_Comm_free(&m_Comm),
"freeing aggregators comm at Close\n");
m_IsActive = false;
}
}
// PROTECTED
void MPIAggregator::InitComm(const size_t subStreams, MPI_Comm parentComm)
{
int parentRank;
int parentSize;
MPI_Comm_rank(parentComm, &parentRank);
MPI_Comm_size(parentComm, &parentSize);
const size_t processes = static_cast<size_t>(parentSize);
size_t stride = processes / subStreams + 1;
const size_t remainder = processes % subStreams;
size_t consumer = 0;
for (auto s = 0; s < subStreams; ++s)
{
if (s >= remainder)
{
stride = processes / subStreams;
}
if (static_cast<size_t>(parentRank) >= consumer &&
static_cast<size_t>(parentRank) < consumer + stride)
{
helper::CheckMPIReturn(
MPI_Comm_split(parentComm, static_cast<int>(consumer),
parentRank, &m_Comm),
"creating aggregators comm with split at Open");
m_ConsumerRank = static_cast<int>(consumer);
m_SubStreamIndex = static_cast<size_t>(s);
}
consumer += stride;
}
MPI_Comm_rank(m_Comm, &m_Rank);
MPI_Comm_size(m_Comm, &m_Size);
if (m_Rank != 0)
{
m_IsConsumer = false;
}
m_IsActive = true;
m_SubStreams = subStreams;
}
void MPIAggregator::HandshakeRank(const int rank)
{
int message = -1;
if (m_Rank == rank)
{
message = m_Rank;
}
helper::CheckMPIReturn(MPI_Bcast(&message, 1, MPI_INT, rank, m_Comm),
"handshake with aggregator rank 0 at Open");
}
} // end namespace aggregator
} // end namespace adios2
<commit_msg>aggregator: Simplify substream assignment logic<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* MPIAggregator.cpp
*
* Created on: Feb 20, 2018
* Author: William F Godoy [email protected]
*/
#include "MPIAggregator.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace aggregator
{
MPIAggregator::MPIAggregator() : m_Comm(MPI_COMM_NULL) {}
MPIAggregator::~MPIAggregator()
{
if (m_IsActive)
{
helper::CheckMPIReturn(MPI_Comm_free(&m_Comm),
"freeing aggregators comm in MPIAggregator "
"destructor, not recommended");
}
}
void MPIAggregator::Init(const size_t subStreams, MPI_Comm parentComm) {}
void MPIAggregator::SwapBuffers(const int step) noexcept {}
void MPIAggregator::ResetBuffers() noexcept {}
format::Buffer &MPIAggregator::GetConsumerBuffer(format::Buffer &buffer)
{
return buffer;
}
void MPIAggregator::Close()
{
if (m_IsActive)
{
helper::CheckMPIReturn(MPI_Comm_free(&m_Comm),
"freeing aggregators comm at Close\n");
m_IsActive = false;
}
}
// PROTECTED
void MPIAggregator::InitComm(const size_t subStreams, MPI_Comm parentComm)
{
int parentRank;
int parentSize;
MPI_Comm_rank(parentComm, &parentRank);
MPI_Comm_size(parentComm, &parentSize);
const size_t process = static_cast<size_t>(parentRank);
const size_t processes = static_cast<size_t>(parentSize);
// Divide the processes into S=subStreams groups.
const size_t q = processes / subStreams;
const size_t r = processes % subStreams;
// Groups [0,r) have size q+1. Groups [r,S) have size q.
const size_t first_in_small_groups = r * (q + 1);
// Within each group the first process becomes its consumer.
if (process >= first_in_small_groups)
{
m_SubStreamIndex = r + (process - first_in_small_groups) / q;
m_ConsumerRank = static_cast<int>(first_in_small_groups +
(m_SubStreamIndex - r) * q);
}
else
{
m_SubStreamIndex = process / (q + 1);
m_ConsumerRank = static_cast<int>(m_SubStreamIndex * (q + 1));
}
helper::CheckMPIReturn(
MPI_Comm_split(parentComm, m_ConsumerRank, parentRank, &m_Comm),
"creating aggregators comm with split at Open");
MPI_Comm_rank(m_Comm, &m_Rank);
MPI_Comm_size(m_Comm, &m_Size);
if (m_Rank != 0)
{
m_IsConsumer = false;
}
m_IsActive = true;
m_SubStreams = subStreams;
}
void MPIAggregator::HandshakeRank(const int rank)
{
int message = -1;
if (m_Rank == rank)
{
message = m_Rank;
}
helper::CheckMPIReturn(MPI_Bcast(&message, 1, MPI_INT, rank, m_Comm),
"handshake with aggregator rank 0 at Open");
}
} // end namespace aggregator
} // end namespace adios2
<|endoftext|> |
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include <boost/python.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <fstream>
#include "PPPMForceCompute.h"
#ifdef ENABLE_CUDA
#include "PPPMForceComputeGPU.h"
#endif
#include "NeighborListBinned.h"
#include "Initializers.h"
#include <math.h>
using namespace std;
using namespace boost;
using namespace boost::python;
/*! \file pppm_force_test.cc
\brief Implements unit tests for PPPMForceCompute and PPPMForceComputeGPU and descendants
\ingroup unit_tests
*/
//! Name the unit test module
#define BOOST_TEST_MODULE PPPMTest
#include "boost_utf_configure.h"
//! Typedef'd PPPMForceCompute factory
typedef boost::function<shared_ptr<PPPMForceCompute> (shared_ptr<SystemDefinition> sysdef,
shared_ptr<NeighborList> nlist,
shared_ptr<ParticleGroup> group)> pppmforce_creator;
//! Test the ability of the lj force compute to actually calucate forces
void pppm_force_particle_test(pppmforce_creator pppm_creator, boost::shared_ptr<ExecutionConfiguration> exec_conf)
{
// this is a 2-particle of charge 1 and -1
// due to the complexity of FFTs, the correct resutls are not analytically computed
// but instead taken from a known working implementation of the PPPM method
// The box lengths and grid points are different in each direction
shared_ptr<SystemDefinition> sysdef_2(new SystemDefinition(2, BoxDim(6.0, 10.0, 14.0), 1, 0, 0, 0, 0, exec_conf));
shared_ptr<ParticleData> pdata_2 = sysdef_2->getParticleData();
pdata_2->setFlags(~PDataFlags(0));
shared_ptr<NeighborList> nlist_2(new NeighborList(sysdef_2, Scalar(1.0), Scalar(1.0)));
shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(sysdef_2, 0, 1));
shared_ptr<ParticleGroup> group_all(new ParticleGroup(sysdef_2, selector_all));
{
ArrayHandle<Scalar4> h_pos(pdata_2->getPositions(), access_location::host, access_mode::readwrite);
ArrayHandle<Scalar> h_charge(pdata_2->getCharges(), access_location::host, access_mode::readwrite);
h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 1.0;
h_charge.data[0] = 1.0;
h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 2.0;
h_charge.data[1] = -1.0;
}
shared_ptr<PPPMForceCompute> fc_2 = pppm_creator(sysdef_2, nlist_2, group_all);
// first test: setup a sigma of 1.0 so that all forces will be 0
int Nx = 10;
int Ny = 15;
int Nz = 24;
int order = 5;
Scalar kappa = 1.0;
Scalar rcut = 1.0;
Scalar volume = 6.0*10.0*14.0;
fc_2->setParams(Nx, Ny, Nz, order, kappa, rcut);
// compute the forces
fc_2->compute(0);
ArrayHandle<Scalar4> h_force(fc_2->getForceArray(), access_location::host, access_mode::read);
ArrayHandle<Scalar> h_virial(fc_2->getVirialArray(), access_location::host, access_mode::read);
unsigned int pitch = fc_2->getVirialArray().getPitch();
MY_BOOST_CHECK_CLOSE(h_force.data[0].x, 0.151335f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[0].y, 0.172246f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[0].z, 0.179186f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[0].w, -0.576491f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[0*pitch]/volume, -0.000180413f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[1*pitch]/volume, -0.000180153f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[2*pitch]/volume, -0.000180394f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[3*pitch]/volume, -0.000211184f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[4*pitch]/volume, -0.000204873f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[5*pitch]/volume, -0.000219209f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[1].x, -0.151335f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[1].y, -0.172246f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[1].z, -0.179186f, tol_small);
MY_BOOST_CHECK_SMALL(h_force.data[1].w, tol_small);
MY_BOOST_CHECK_SMALL(h_virial.data[0*pitch+1]
+h_virial.data[3*pitch+1]
+h_virial.data[5*pitch+1], tol_small);
}
//! PPPMForceCompute creator for unit tests
shared_ptr<PPPMForceCompute> base_class_pppm_creator(shared_ptr<SystemDefinition> sysdef,
shared_ptr<NeighborList> nlist,
shared_ptr<ParticleGroup> group)
{
return shared_ptr<PPPMForceCompute>(new PPPMForceCompute(sysdef, nlist, group));
}
#ifdef ENABLE_CUDA
//! PPPMForceComputeGPU creator for unit tests
shared_ptr<PPPMForceCompute> gpu_pppm_creator(shared_ptr<SystemDefinition> sysdef,
shared_ptr<NeighborList> nlist,
shared_ptr<ParticleGroup> group)
{
nlist->setStorageMode(NeighborList::full);
return shared_ptr<PPPMForceComputeGPU> (new PPPMForceComputeGPU(sysdef, nlist, group));
}
#endif
//! boost test case for particle test on CPU
BOOST_AUTO_TEST_CASE( PPPMForceCompute_basic )
{
pppmforce_creator pppm_creator = bind(base_class_pppm_creator, _1, _2, _3);
pppm_force_particle_test(pppm_creator, boost::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::CPU)));
}
#ifdef ENABLE_CUDA
//! boost test case for bond forces on the GPU
BOOST_AUTO_TEST_CASE( PPPMForceComputeGPU_basic )
{
pppmforce_creator pppm_creator = bind(gpu_pppm_creator, _1, _2, _3);
pppm_force_particle_test(pppm_creator, boost::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::GPU)));
}
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>Added unit test for charge.pppm with triclinic<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include <boost/python.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <fstream>
#include "PPPMForceCompute.h"
#ifdef ENABLE_CUDA
#include "PPPMForceComputeGPU.h"
#endif
#include "NeighborListBinned.h"
#include "Initializers.h"
#include <math.h>
using namespace std;
using namespace boost;
using namespace boost::python;
/*! \file pppm_force_test.cc
\brief Implements unit tests for PPPMForceCompute and PPPMForceComputeGPU and descendants
\ingroup unit_tests
*/
//! Name the unit test module
#define BOOST_TEST_MODULE PPPMTest
#include "boost_utf_configure.h"
//! Typedef'd PPPMForceCompute factory
typedef boost::function<shared_ptr<PPPMForceCompute> (shared_ptr<SystemDefinition> sysdef,
shared_ptr<NeighborList> nlist,
shared_ptr<ParticleGroup> group)> pppmforce_creator;
//! Test the ability of the lj force compute to actually calucate forces
void pppm_force_particle_test(pppmforce_creator pppm_creator, boost::shared_ptr<ExecutionConfiguration> exec_conf)
{
// this is a 2-particle of charge 1 and -1
// due to the complexity of FFTs, the correct resutls are not analytically computed
// but instead taken from a known working implementation of the PPPM method
// The box lengths and grid points are different in each direction
shared_ptr<SystemDefinition> sysdef_2(new SystemDefinition(2, BoxDim(6.0, 10.0, 14.0), 1, 0, 0, 0, 0, exec_conf));
shared_ptr<ParticleData> pdata_2 = sysdef_2->getParticleData();
pdata_2->setFlags(~PDataFlags(0));
shared_ptr<NeighborList> nlist_2(new NeighborList(sysdef_2, Scalar(1.0), Scalar(1.0)));
shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(sysdef_2, 0, 1));
shared_ptr<ParticleGroup> group_all(new ParticleGroup(sysdef_2, selector_all));
{
ArrayHandle<Scalar4> h_pos(pdata_2->getPositions(), access_location::host, access_mode::readwrite);
ArrayHandle<Scalar> h_charge(pdata_2->getCharges(), access_location::host, access_mode::readwrite);
h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 1.0;
h_charge.data[0] = 1.0;
h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 2.0;
h_charge.data[1] = -1.0;
}
shared_ptr<PPPMForceCompute> fc_2 = pppm_creator(sysdef_2, nlist_2, group_all);
// first test: setup a sigma of 1.0 so that all forces will be 0
int Nx = 10;
int Ny = 15;
int Nz = 24;
int order = 5;
Scalar kappa = 1.0;
Scalar rcut = 1.0;
Scalar volume = 6.0*10.0*14.0;
fc_2->setParams(Nx, Ny, Nz, order, kappa, rcut);
// compute the forces
fc_2->compute(0);
ArrayHandle<Scalar4> h_force(fc_2->getForceArray(), access_location::host, access_mode::read);
ArrayHandle<Scalar> h_virial(fc_2->getVirialArray(), access_location::host, access_mode::read);
unsigned int pitch = fc_2->getVirialArray().getPitch();
MY_BOOST_CHECK_CLOSE(h_force.data[0].x, 0.151335f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[0].y, 0.172246f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[0].z, 0.179186f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[0].w, -0.576491f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[0*pitch]/volume, -0.000180413f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[1*pitch]/volume, -0.000180153f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[2*pitch]/volume, -0.000180394f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[3*pitch]/volume, -0.000211184f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[4*pitch]/volume, -0.000204873f, tol_small);
MY_BOOST_CHECK_CLOSE(h_virial.data[5*pitch]/volume, -0.000219209f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[1].x, -0.151335f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[1].y, -0.172246f, tol_small);
MY_BOOST_CHECK_CLOSE(h_force.data[1].z, -0.179186f, tol_small);
MY_BOOST_CHECK_SMALL(h_force.data[1].w, tol_small);
MY_BOOST_CHECK_SMALL(h_virial.data[0*pitch+1]
+h_virial.data[3*pitch+1]
+h_virial.data[5*pitch+1], tol_small);
}
//! Test the ability of the lj force compute to actually calucate forces
void pppm_force_particle_test_triclinic(pppmforce_creator pppm_creator, boost::shared_ptr<ExecutionConfiguration> exec_conf)
{
// this is a 2-particle of charge 1 and -1
// due to the complexity of FFTs, the correct resutls are not analytically computed
// but instead taken from a known working implementation of the PPPM method (LAMMPS ewald/disp
// with lj/long/coul/long at RMS error = 6.14724e-06)
// The box lengths and grid points are different in each direction
// set up triclinic box
Scalar tilt(0.5);
shared_ptr<SystemDefinition> sysdef_2(new SystemDefinition(2, BoxDim(10.0,tilt,tilt,tilt), 1, 0, 0, 0, 0, exec_conf));
shared_ptr<ParticleData> pdata_2 = sysdef_2->getParticleData();
pdata_2->setFlags(~PDataFlags(0));
shared_ptr<NeighborList> nlist_2(new NeighborList(sysdef_2, Scalar(1.0), Scalar(1.0)));
shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(sysdef_2, 0, 1));
shared_ptr<ParticleGroup> group_all(new ParticleGroup(sysdef_2, selector_all));
{
ArrayHandle<Scalar4> h_pos(pdata_2->getPositions(), access_location::host, access_mode::readwrite);
ArrayHandle<Scalar> h_charge(pdata_2->getCharges(), access_location::host, access_mode::readwrite);
h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 0.0;
h_charge.data[0] = 1.0;
h_pos.data[1].x = 3.0; h_pos.data[1].y = 3.0; h_pos.data[1].z = 3.0;
h_charge.data[1] = -1.0;
}
shared_ptr<PPPMForceCompute> fc_2 = pppm_creator(sysdef_2, nlist_2, group_all);
int Nx = 128;
int Ny = 128;
int Nz = 128;
int order = 3;
Scalar kappa = 1.519768; // this value is calculated by charge.pppm
Scalar rcut = 2.0;
Scalar volume = 10.0*10.0*10.0;
fc_2->setParams(Nx, Ny, Nz, order, kappa, rcut);
// compute the forces
fc_2->compute(0);
ArrayHandle<Scalar4> h_force(fc_2->getForceArray(), access_location::host, access_mode::read);
ArrayHandle<Scalar> h_virial(fc_2->getVirialArray(), access_location::host, access_mode::read);
unsigned int pitch = fc_2->getVirialArray().getPitch();
Scalar rough_tol = 0.02;
Scalar rough_tol_2 = 1.0;
MY_BOOST_CHECK_CLOSE(h_force.data[0].x, 0.00904953, rough_tol);
MY_BOOST_CHECK_CLOSE(h_force.data[0].y, 0.0101797, rough_tol);
MY_BOOST_CHECK_CLOSE(h_force.data[0].z, 0.0124804, rough_tol);
MY_BOOST_CHECK_CLOSE(h_force.data[0].w, -0.2441, rough_tol);
MY_BOOST_CHECK_CLOSE(h_virial.data[0*pitch]/volume, -5.7313404e-05, rough_tol_2);
MY_BOOST_CHECK_CLOSE(h_virial.data[1*pitch]/volume, -4.5494677e-05, rough_tol_2);
MY_BOOST_CHECK_CLOSE(h_virial.data[2*pitch]/volume, -3.9889249e-05, rough_tol_2);
MY_BOOST_CHECK_CLOSE(h_virial.data[3*pitch]/volume, -7.8745142e-05, rough_tol_2);
MY_BOOST_CHECK_CLOSE(h_virial.data[4*pitch]/volume, -4.8501155e-05, rough_tol_2);
MY_BOOST_CHECK_CLOSE(h_virial.data[5*pitch]/volume, -0.00010732774, rough_tol_2);
MY_BOOST_CHECK_CLOSE(h_force.data[1].x, -0.00904953, rough_tol);
MY_BOOST_CHECK_CLOSE(h_force.data[1].y, -0.0101797, rough_tol);
MY_BOOST_CHECK_CLOSE(h_force.data[1].z, -0.0124804, rough_tol);
MY_BOOST_CHECK_SMALL(h_force.data[1].w, rough_tol);
MY_BOOST_CHECK_SMALL(h_virial.data[0*pitch+1], rough_tol);
MY_BOOST_CHECK_SMALL(h_virial.data[1*pitch+1], rough_tol);
MY_BOOST_CHECK_SMALL(h_virial.data[2*pitch+1], rough_tol);
MY_BOOST_CHECK_SMALL(h_virial.data[3*pitch+1], rough_tol);
MY_BOOST_CHECK_SMALL(h_virial.data[4*pitch+1], rough_tol);
MY_BOOST_CHECK_SMALL(h_virial.data[5*pitch+1], rough_tol);
}
//! PPPMForceCompute creator for unit tests
shared_ptr<PPPMForceCompute> base_class_pppm_creator(shared_ptr<SystemDefinition> sysdef,
shared_ptr<NeighborList> nlist,
shared_ptr<ParticleGroup> group)
{
return shared_ptr<PPPMForceCompute>(new PPPMForceCompute(sysdef, nlist, group));
}
#ifdef ENABLE_CUDA
//! PPPMForceComputeGPU creator for unit tests
shared_ptr<PPPMForceCompute> gpu_pppm_creator(shared_ptr<SystemDefinition> sysdef,
shared_ptr<NeighborList> nlist,
shared_ptr<ParticleGroup> group)
{
nlist->setStorageMode(NeighborList::full);
return shared_ptr<PPPMForceComputeGPU> (new PPPMForceComputeGPU(sysdef, nlist, group));
}
#endif
//! boost test case for particle test on CPU
BOOST_AUTO_TEST_CASE( PPPMForceCompute_basic )
{
pppmforce_creator pppm_creator = bind(base_class_pppm_creator, _1, _2, _3);
pppm_force_particle_test(pppm_creator, boost::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::CPU)));
}
//! boost test case for particle test on CPU
BOOST_AUTO_TEST_CASE( PPPMForceCompute_triclinic )
{
pppmforce_creator pppm_creator = bind(base_class_pppm_creator, _1, _2, _3);
pppm_force_particle_test_triclinic(pppm_creator, boost::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::CPU)));
}
#
#ifdef ENABLE_CUDA
//! boost test case for bond forces on the GPU
BOOST_AUTO_TEST_CASE( PPPMForceComputeGPU_basic )
{
pppmforce_creator pppm_creator = bind(gpu_pppm_creator, _1, _2, _3);
pppm_force_particle_test(pppm_creator, boost::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::GPU)));
}
BOOST_AUTO_TEST_CASE( PPPMForceComputeGPU_triclinic )
{
pppmforce_creator pppm_creator = bind(gpu_pppm_creator, _1, _2, _3);
pppm_force_particle_test_triclinic(pppm_creator, boost::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::GPU)));
}
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|> |
<commit_before>//################################################
// This code file
// defines Measure class used to track properties
// (e.g. peak, min, duration) of specified state variable.
//
// Copyright (C) 2015 Thomas J. Hund.
// Updated 07/2015
// Email [email protected]
//#################################################
#include "measure_kernel.h"
//#############################################################
// Measure class constructor and destructor
//#############################################################
MeasureKernel::MeasureKernel(string varname, double percrepol)
{
peak=-100.0;
min=100.0;
vartakeoff=-100.0;
repol = -25.0;
amp = 70.0;
maxderiv=0.0;
maxderiv2nd=0.0;
cl=0.0;
told = -10000.0;
mint = 0.0;
maxt = 0.0;
varold = 100.0;
derivold = 0.0;
minflag = false;
maxflag = false;
ampflag = false;
ddrflag = false;
derivt2 = 0.0;
derivt1 = 0.0;
derivt = 0.0;
deriv2ndt = 0.0;
durflag = false;
this->percrepol = percrepol;
returnflag = 0;
this->varname = varname;
this->mkmap();
};
MeasureKernel::MeasureKernel(const MeasureKernel& toCopy) {
this->copy(toCopy);
};
MeasureKernel::MeasureKernel( MeasureKernel&& toCopy) {
this->copy(toCopy);
};
MeasureKernel& MeasureKernel::operator=(const MeasureKernel& toCopy) {
this->copy(toCopy);
return *this;
};
MeasureKernel::~MeasureKernel()
{
};
set<string> MeasureKernel::getVariables() {
set<string> toReturn;
map<string,double*>::iterator it;
for(it = varmap.begin(); it != varmap.end(); it++) {
toReturn.insert(it->first);
}
return toReturn;
}
map<string,double> MeasureKernel::getVariablesMap() {
map<string,double> toReturn;
for(map<string,double*>::iterator it = varmap.begin(); it != varmap.end(); it++) {
toReturn.insert(std::pair<string,double>(it->first, *it->second));
}
return toReturn;
}
void MeasureKernel::copy(const MeasureKernel& toCopy) {
std::map<string, double*>::iterator it;
peak= toCopy.peak;
min= toCopy.min;
vartakeoff= toCopy.vartakeoff;
repol = toCopy.repol;
amp = toCopy.amp;
maxderiv= toCopy.maxderiv;
maxderiv2nd= toCopy.maxderiv2nd;
cl= toCopy.cl;
told = toCopy.told;
mint = toCopy.mint;
maxt = toCopy.maxt;
varold = toCopy.varold;
derivold = toCopy.derivold;
minflag = toCopy.minflag;
maxflag = toCopy.maxflag;
ampflag = toCopy.ampflag;
ddrflag = toCopy.ddrflag;
derivt2 = toCopy.derivt2;
derivt1 = toCopy.derivt1;
derivt = toCopy.derivt;
deriv2ndt = toCopy.deriv2ndt;
durflag = toCopy.durflag;
percrepol = toCopy.percrepol;
returnflag = toCopy.returnflag;
dur = toCopy.dur;
varname = toCopy.varname;
this->mkmap();
};
//################################################################
// Function to track properties (e.g. peak, min, duration) of
// specified state variable and return status flag to calling fxn.
//################################################################
bool MeasureKernel::measure(double time, double var)
{
double deriv,deriv2nd;
returnflag = false; //default for return...set to 1 when props ready for output
deriv=(var-varold)/(time-told);
deriv2nd=(deriv-derivold)/(time-told);
if(deriv>maxderiv){ // Track value and time of max 1st deriv
maxderiv=deriv;
derivt=time;
}
if(deriv2nd>.02&&var>(0.01*abs(min)+min)&&!ddrflag){ // Track 2nd deriv for SAN ddr
vartakeoff=var;
deriv2ndt=time;
ddr=(vartakeoff-min)/(time-mint);
ddrflag=true;
}
if(minflag&&var>peak){ // Track value and time of peak
peak=var;
maxt=time;
}
else if((peak-min)>0.3*abs(min)) // Assumes true max is more than 30% greater than the min.
maxflag=true;
if(var<min){ // Track value and time of min
min=var;
mint=time;
}
else
minflag=true;
if(var>repol&&!durflag){ // t1 for dur calculation = first time var crosses repol.
durtime1=time; // will depend on percrepol - default is 50 but can be changed.
durflag=true;
}
if(maxflag&&minflag&&!ampflag){
amp=peak-min;
ampflag = true;
cl=derivt-derivt1;
derivt2=derivt1;
derivt1=derivt;
repol = (1-percrepol*0.01)*amp+min;
}
if(durflag&&var<repol){
dur=time-durtime1;
durflag=false;
returnflag = true; // lets calling fxn know that it is time to output and reset.
}
told=time;
varold=var;
derivold=deriv;
return (returnflag);
};
void MeasureKernel::reset()
{
for(auto var: this->varmap) {
this->lastMap[var.first] = *var.second;
}
peak=-100.0;
min=100.0;
maxderiv=0.0;
maxderiv2nd=0.0;
told = 0.0;
minflag = 0;
maxflag = 0;
ampflag = 0;
ddrflag = 0;
};
void MeasureKernel::setPercrepol(double val) {
this->percrepol = val;
}
double MeasureKernel::getPercrepol() const {
return this->percrepol;
}
void MeasureKernel::restoreLast() {
for(auto var: lastMap) {
*this->varmap[var.first] = var.second;
}
}
void MeasureKernel::mkmap() {
varmap["cl"]=&cl;
varmap["peak"]=&peak;
varmap["min"]=&min;
varmap["amp"]=&
varmap["ddr"]=&ddr;
varmap["maxderiv"]=&maxderiv;
varmap["dur"]=&dur;
varmap["durtime1"]=&durtime1;
varmap["vartakeoff"]=&vartakeoff;
varmap["mint"]=&mint;
varmap["derivt"]=&derivt;
varmap["deriv2ndt"]=&deriv2ndt;
}
<commit_msg>peak is now the abs of value<commit_after>//################################################
// This code file
// defines Measure class used to track properties
// (e.g. peak, min, duration) of specified state variable.
//
// Copyright (C) 2015 Thomas J. Hund.
// Updated 07/2015
// Email [email protected]
//#################################################
#include "measure_kernel.h"
//#############################################################
// Measure class constructor and destructor
//#############################################################
MeasureKernel::MeasureKernel(string varname, double percrepol)
{
peak=-100.0;
min=100.0;
vartakeoff=-100.0;
repol = -25.0;
amp = 70.0;
maxderiv=0.0;
maxderiv2nd=0.0;
cl=0.0;
told = -10000.0;
mint = 0.0;
maxt = 0.0;
varold = 100.0;
derivold = 0.0;
minflag = false;
maxflag = false;
ampflag = false;
ddrflag = false;
derivt2 = 0.0;
derivt1 = 0.0;
derivt = 0.0;
deriv2ndt = 0.0;
durflag = false;
this->percrepol = percrepol;
returnflag = 0;
this->varname = varname;
this->mkmap();
};
MeasureKernel::MeasureKernel(const MeasureKernel& toCopy) {
this->copy(toCopy);
};
MeasureKernel::MeasureKernel( MeasureKernel&& toCopy) {
this->copy(toCopy);
};
MeasureKernel& MeasureKernel::operator=(const MeasureKernel& toCopy) {
this->copy(toCopy);
return *this;
};
MeasureKernel::~MeasureKernel()
{
};
set<string> MeasureKernel::getVariables() {
set<string> toReturn;
map<string,double*>::iterator it;
for(it = varmap.begin(); it != varmap.end(); it++) {
toReturn.insert(it->first);
}
return toReturn;
}
map<string,double> MeasureKernel::getVariablesMap() {
map<string,double> toReturn;
for(map<string,double*>::iterator it = varmap.begin(); it != varmap.end(); it++) {
toReturn.insert(std::pair<string,double>(it->first, *it->second));
}
return toReturn;
}
void MeasureKernel::copy(const MeasureKernel& toCopy) {
std::map<string, double*>::iterator it;
peak= toCopy.peak;
min= toCopy.min;
vartakeoff= toCopy.vartakeoff;
repol = toCopy.repol;
amp = toCopy.amp;
maxderiv= toCopy.maxderiv;
maxderiv2nd= toCopy.maxderiv2nd;
cl= toCopy.cl;
told = toCopy.told;
mint = toCopy.mint;
maxt = toCopy.maxt;
varold = toCopy.varold;
derivold = toCopy.derivold;
minflag = toCopy.minflag;
maxflag = toCopy.maxflag;
ampflag = toCopy.ampflag;
ddrflag = toCopy.ddrflag;
derivt2 = toCopy.derivt2;
derivt1 = toCopy.derivt1;
derivt = toCopy.derivt;
deriv2ndt = toCopy.deriv2ndt;
durflag = toCopy.durflag;
percrepol = toCopy.percrepol;
returnflag = toCopy.returnflag;
dur = toCopy.dur;
varname = toCopy.varname;
this->mkmap();
};
//################################################################
// Function to track properties (e.g. peak, min, duration) of
// specified state variable and return status flag to calling fxn.
//################################################################
bool MeasureKernel::measure(double time, double var)
{
double deriv,deriv2nd;
returnflag = false; //default for return...set to 1 when props ready for output
deriv=(var-varold)/(time-told);
deriv2nd=(deriv-derivold)/(time-told);
if(deriv>maxderiv){ // Track value and time of max 1st deriv
maxderiv=deriv;
derivt=time;
}
if(deriv2nd>.02&&var>(0.01*abs(min)+min)&&!ddrflag){ // Track 2nd deriv for SAN ddr
vartakeoff=var;
deriv2ndt=time;
ddr=(vartakeoff-min)/(time-mint);
ddrflag=true;
}
if(minflag&&abs(var)>peak){ // Track value and time of peak
peak=var;
maxt=time;
}
else if((peak-min)>0.3*abs(min)) // Assumes true max is more than 30% greater than the min.
maxflag=true;
if(var<min){ // Track value and time of min
min=var;
mint=time;
}
else
minflag=true;
if(var>repol&&!durflag){ // t1 for dur calculation = first time var crosses repol.
durtime1=time; // will depend on percrepol - default is 50 but can be changed.
durflag=true;
}
if(maxflag&&minflag&&!ampflag){
amp=peak-min;
ampflag = true;
cl=derivt-derivt1;
derivt2=derivt1;
derivt1=derivt;
repol = (1-percrepol*0.01)*amp+min;
}
if(durflag&&var<repol){
dur=time-durtime1;
durflag=false;
returnflag = true; // lets calling fxn know that it is time to output and reset.
}
told=time;
varold=var;
derivold=deriv;
return (returnflag);
};
void MeasureKernel::reset()
{
for(auto var: this->varmap) {
this->lastMap[var.first] = *var.second;
}
peak=-100.0;
min=100.0;
maxderiv=0.0;
maxderiv2nd=0.0;
told = 0.0;
minflag = 0;
maxflag = 0;
ampflag = 0;
ddrflag = 0;
};
void MeasureKernel::setPercrepol(double val) {
this->percrepol = val;
}
double MeasureKernel::getPercrepol() const {
return this->percrepol;
}
void MeasureKernel::restoreLast() {
for(auto var: lastMap) {
*this->varmap[var.first] = var.second;
}
}
void MeasureKernel::mkmap() {
varmap["cl"]=&cl;
varmap["peak"]=&peak;
varmap["min"]=&min;
varmap["amp"]=&
varmap["ddr"]=&ddr;
varmap["maxderiv"]=&maxderiv;
varmap["dur"]=&dur;
varmap["durtime1"]=&durtime1;
varmap["vartakeoff"]=&vartakeoff;
varmap["mint"]=&mint;
varmap["derivt"]=&derivt;
varmap["deriv2ndt"]=&deriv2ndt;
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX
#define OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX
#include <exception>
#include <set>
#include <vector>
#include <queue>
#include "opengm/graphicalmodel/graphicalmodel.hxx"
#include "opengm/graphicalmodel/space/discretespace.hxx"
#include "opengm/functions/view.hxx"
#include "opengm/functions/view_fix_variables_function.hxx"
#include "opengm/functions/constant.hxx"
#include <opengm/utilities/metaprogramming.hxx>
namespace opengm {
/// \brief GraphicalModelManipulator
///
/// Invariant: Order of the variables in the modified subgraphs is the same as in the original graph
///
/// \ingroup graphical_models
template<class GM>
class GraphicalModelManipulator
{
public:
typedef GM OGM;
typedef typename GM::SpaceType OSpaceType;
typedef typename GM::IndexType IndexType;
typedef typename GM::LabelType LabelType;
typedef typename GM::ValueType ValueType;
typedef typename opengm::DiscreteSpace<IndexType, LabelType> MSpaceType;
typedef typename meta::TypeListGenerator< ViewFixVariablesFunction<GM>, ViewFunction<GM>, ConstantFunction<ValueType, IndexType, LabelType> >::type MFunctionTypeList;
typedef GraphicalModel<ValueType, typename GM::OperatorType, MFunctionTypeList, MSpaceType> MGM;
GraphicalModelManipulator(GM& gm);
//BuildModels
void buildModifiedModel();
void buildModifiedSubModels();
//Get Models
const OGM& getOriginalModel() const;
const MGM& getModifiedModel() const;
const MGM& getModifiedSubModel(size_t) const;
//GetInfo
size_t numberOfSubmodels() const;
void modifiedState2OriginalState(const std::vector<LabelType>&, std::vector<LabelType>&) const;
void modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >&, std::vector<LabelType>&) const;
bool isLocked() const;
//Manipulation
void fixVariable(const typename GM::IndexType, const typename GM::LabelType);
void freeVariable(const typename GM::IndexType);
void freeAllVariables();
void unlock();
void lock();
private:
void expand(IndexType, IndexType, std::vector<bool>&);
//General Members
const OGM& gm_; // original model
bool locked_; // if true no more manipulation is allowed
std::vector<bool> fixVariable_; // flag if variables are fixed
std::vector<LabelType> fixVariableLabel_; // label of fixed variables (otherwise undefined)
//Modified Model
bool validModel_; // true if modified model is valid
MGM mgm_; // modified model
//Modified SubModels
bool validSubModels_; // true if themodified submodels are valid
std::vector<MGM> submodels_; // modified submodels
std::vector<IndexType> var2subProblem_; // subproblem of variable (for fixed variables undefined)
};
template<class GM>
GraphicalModelManipulator<GM>::GraphicalModelManipulator(GM& gm)
: gm_(gm), locked_(false), validModel_(false), validSubModels_(false),
fixVariable_(std::vector<bool>(gm.numberOfVariables(),false)),
fixVariableLabel_(std::vector<LabelType>(gm.numberOfVariables(),0)),
var2subProblem_(std::vector<LabelType>(gm.numberOfVariables(),0))
{
return;
}
/// \brief return the original graphical model
template<class GM>
inline const typename GraphicalModelManipulator<GM>::OGM &
GraphicalModelManipulator<GM>::getOriginalModel() const
{
return gm_;
}
/// \brief return the modified graphical model
template<class GM>
inline const typename GraphicalModelManipulator<GM>::MGM &
GraphicalModelManipulator<GM>::getModifiedModel() const
{
OPENGM_ASSERT(isLocked() && validModel_);
return mgm_;
}
/// \brief return the i-th modified sub graphical model
template<class GM>
inline const typename GraphicalModelManipulator<GM>::MGM &
GraphicalModelManipulator<GM>::getModifiedSubModel(size_t i) const
{
OPENGM_ASSERT(isLocked() && validSubModels_);
OPENGM_ASSERT(i < submodels_.size());
return submodels_[i];
}
/// \brief return the number of submodels
template<class GM>
size_t GraphicalModelManipulator<GM>::numberOfSubmodels() const
{
OPENGM_ASSERT(isLocked());
return submodels_.size();
}
/// \brief unlock model
template<class GM>
void GraphicalModelManipulator<GM>::unlock()
{
locked_=false;
validSubModels_=false;
validModel_=false;
submodels_.clear();
freeAllVariables();
}
/// \brief lock model
template<class GM>
void GraphicalModelManipulator<GM>::lock()
{
locked_=true;
}
/// \brief return true if model is locked
template<class GM>
bool GraphicalModelManipulator<GM>::isLocked() const
{
return locked_;
}
/// \brief fix label for variable
template<class GM>
void GraphicalModelManipulator<GM>::fixVariable(const typename GM::IndexType var, const typename GM::LabelType l)
{
OPENGM_ASSERT(!isLocked());
if(!isLocked()){
fixVariable_[var]=true;
fixVariableLabel_[var]=l;
}
}
/// \brief remove fixed label for variable
template<class GM>
void GraphicalModelManipulator<GM>::freeVariable(const typename GM::IndexType var)
{
OPENGM_ASSERT(!isLocked());
if(!isLocked()){
fixVariable_[var]=false;
}
}
/// \brief remove fixed label for all variable
template<class GM>
void GraphicalModelManipulator<GM>::freeAllVariables()
{
OPENGM_ASSERT(!isLocked())
if(!isLocked()){
for(IndexType var=0; var<fixVariable_.size(); ++var)
fixVariable_[var]=false;
}
}
/// \brief transforming label of the modified to the labeling of the original problem
template<class GM>
void GraphicalModelManipulator<GM>::modifiedState2OriginalState(const std::vector<LabelType>& ml, std::vector<LabelType>& ol) const
{
OPENGM_ASSERT(isLocked());
OPENGM_ASSERT(ml.size()==mgm_.numberOfVariables());
if(isLocked() && ml.size()==mgm_.numberOfVariables()){
ol.resize(gm_.numberOfVariables());
size_t c = 0;
for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
if(fixVariable_[var]){
ol[var] = fixVariableLabel_[var];
}else{
ol[var] = ml[c++];
}
}
}
}
/// \brief transforming label of the modified subproblems to the labeling of the original problem
template<class GM>
void GraphicalModelManipulator<GM>::modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >& subconf, std::vector<LabelType>& conf) const
{
conf.resize(gm_.numberOfVariables());
std::vector<IndexType> varCount(submodels_.size(),0);
for(IndexType i=0;i<submodels_.size(); ++i){
OPENGM_ASSERT(submodels_[i].numberOfVariables()==subconf[i].size());
}
for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
if(fixVariable_[var]){
conf[var] = fixVariableLabel_[var];
}else{
const IndexType sp=var2subProblem_[var];
conf[var] = subconf[sp][varCount[sp]++];
}
}
}
/// \brief build modified model
template<class GM>
void
GraphicalModelManipulator<GM>::buildModifiedModel()
{
locked_ = true;
validModel_ = true;
IndexType numberOfVariables = 0;
std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
for(IndexType var=0; var<gm_.numberOfVariables();++var){
if(fixVariable_[var]==false){
varMap[var] = numberOfVariables++;
}
}
std::vector<LabelType> shape(numberOfVariables,0);
for(IndexType var=0; var<gm_.numberOfVariables();++var){
if(fixVariable_[var]==false){
shape[varMap[var]] = gm_.numberOfLabels(var);
}
}
MSpaceType space(shape.begin(),shape.end());
mgm_ = MGM(space);
std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
std::vector<IndexType> MVars;
ValueType constant;
GM::OperatorType::neutral(constant);
for(IndexType f=0; f<gm_.numberOfFactors();++f){
fixedVars.resize(0);
MVars.resize(0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
const IndexType var = gm_[f].variableIndex(i);
if(fixVariable_[var]){
fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
}else{
MVars.push_back(varMap[var]);
}
}
if(fixedVars.size()==0){//non fixed
const ViewFunction<GM> func(gm_[f]);
mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
}else if(fixedVars.size()==gm_[f].numberOfVariables()){//all fixed
std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
}
GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
}else{
const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
}
}
{
LabelType temp;
ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.begin());
}
}
/// \brief build modified sub-models
template<class GM>
void
GraphicalModelManipulator<GM>::buildModifiedSubModels()
{
locked_ = true;
validSubModels_ = true;
//Find Connected Components
std::vector<bool> closedVar = fixVariable_;
IndexType numberOfSubproblems = 0;
for(IndexType var=0 ; var<gm_.numberOfVariables(); ++var){
if(closedVar[var])
continue;
else{
expand(var, numberOfSubproblems, closedVar);
}
++numberOfSubproblems;
}
submodels_.resize(numberOfSubproblems);
std::vector<IndexType> numberOfVariables(numberOfSubproblems,0);
std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
for(IndexType var=0; var<gm_.numberOfVariables();++var){
if(fixVariable_[var]==false){
varMap[var] = numberOfVariables[var2subProblem_[var]]++;
}
}
std::vector<std::vector<LabelType> > shape(numberOfSubproblems);
for (size_t i=0; i<numberOfSubproblems; ++i){
shape[i] = std::vector<LabelType>(numberOfVariables[i],0);
}
for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
if(fixVariable_[var]==false){
shape[var2subProblem_[var]][varMap[var]] = gm_.numberOfLabels(var);
}
}
for (size_t i=0; i<numberOfSubproblems; ++i){
MSpaceType space(shape[i].begin(),shape[i].end());
submodels_[i] = MGM(space);
}
std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
std::vector<IndexType> MVars;
ValueType constant;
GM::OperatorType::neutral(constant);
for(IndexType f=0; f<gm_.numberOfFactors();++f){
IndexType subproblem = 0;
fixedVars.resize(0);
MVars.resize(0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
const IndexType var = gm_[f].variableIndex(i);
if(fixVariable_[var]){
fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
}else{
MVars.push_back(varMap[var]);
subproblem = var2subProblem_[var];
}
}
if(MVars.size()==0){ //constant, all fixed
std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
}
GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
}
else if(fixedVars.size()==0){//non fixed
const ViewFunction<GM> func(gm_[f]);
submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
}else{
const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
}
}
{
LabelType temp;
ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
submodels_[0].addFactor( submodels_[0].addFunction(func),MVars.begin(), MVars.begin());
}
}
////////////////////
// Private Methods
////////////////////
template<class GM>
void
GraphicalModelManipulator<GM>::expand(IndexType var, IndexType CCN, std::vector<bool>& closedVar)
{
if(closedVar[var])
return;
else{
closedVar[var] = true;
var2subProblem_[var] = CCN;
for( typename GM::ConstFactorIterator itf = gm_.factorsOfVariableBegin(var); itf!=gm_.factorsOfVariableEnd(var); ++itf){
for( typename GM::ConstVariableIterator itv = gm_.variablesOfFactorBegin(*itf); itv!=gm_.variablesOfFactorEnd(*itf);++itv){
expand(*itv, CCN, closedVar);
}
}
}
}
} //namespace opengm
#endif // #ifndef OPENGM_GRAPHICALMODEL_HXX
<commit_msg>fixed minor bug in constructor... a const GM & gm should be passed instead of GM &gm<commit_after>#pragma once
#ifndef OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX
#define OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX
#include <exception>
#include <set>
#include <vector>
#include <queue>
#include "opengm/graphicalmodel/graphicalmodel.hxx"
#include "opengm/graphicalmodel/space/discretespace.hxx"
#include "opengm/functions/view.hxx"
#include "opengm/functions/view_fix_variables_function.hxx"
#include "opengm/functions/constant.hxx"
#include <opengm/utilities/metaprogramming.hxx>
namespace opengm {
/// \brief GraphicalModelManipulator
///
/// Invariant: Order of the variables in the modified subgraphs is the same as in the original graph
///
/// \ingroup graphical_models
template<class GM>
class GraphicalModelManipulator
{
public:
typedef GM OGM;
typedef typename GM::SpaceType OSpaceType;
typedef typename GM::IndexType IndexType;
typedef typename GM::LabelType LabelType;
typedef typename GM::ValueType ValueType;
typedef typename opengm::DiscreteSpace<IndexType, LabelType> MSpaceType;
typedef typename meta::TypeListGenerator< ViewFixVariablesFunction<GM>, ViewFunction<GM>, ConstantFunction<ValueType, IndexType, LabelType> >::type MFunctionTypeList;
typedef GraphicalModel<ValueType, typename GM::OperatorType, MFunctionTypeList, MSpaceType> MGM;
GraphicalModelManipulator(const GM& gm);
//BuildModels
void buildModifiedModel();
void buildModifiedSubModels();
//Get Models
const OGM& getOriginalModel() const;
const MGM& getModifiedModel() const;
const MGM& getModifiedSubModel(size_t) const;
//GetInfo
size_t numberOfSubmodels() const;
void modifiedState2OriginalState(const std::vector<LabelType>&, std::vector<LabelType>&) const;
void modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >&, std::vector<LabelType>&) const;
bool isLocked() const;
//Manipulation
void fixVariable(const typename GM::IndexType, const typename GM::LabelType);
void freeVariable(const typename GM::IndexType);
void freeAllVariables();
void unlock();
void lock();
private:
void expand(IndexType, IndexType, std::vector<bool>&);
//General Members
const OGM& gm_; // original model
bool locked_; // if true no more manipulation is allowed
std::vector<bool> fixVariable_; // flag if variables are fixed
std::vector<LabelType> fixVariableLabel_; // label of fixed variables (otherwise undefined)
//Modified Model
bool validModel_; // true if modified model is valid
MGM mgm_; // modified model
//Modified SubModels
bool validSubModels_; // true if themodified submodels are valid
std::vector<MGM> submodels_; // modified submodels
std::vector<IndexType> var2subProblem_; // subproblem of variable (for fixed variables undefined)
};
template<class GM>
GraphicalModelManipulator<GM>::GraphicalModelManipulator(const GM& gm)
: gm_(gm), locked_(false), validModel_(false), validSubModels_(false),
fixVariable_(std::vector<bool>(gm.numberOfVariables(),false)),
fixVariableLabel_(std::vector<LabelType>(gm.numberOfVariables(),0)),
var2subProblem_(std::vector<LabelType>(gm.numberOfVariables(),0))
{
return;
}
/// \brief return the original graphical model
template<class GM>
inline const typename GraphicalModelManipulator<GM>::OGM &
GraphicalModelManipulator<GM>::getOriginalModel() const
{
return gm_;
}
/// \brief return the modified graphical model
template<class GM>
inline const typename GraphicalModelManipulator<GM>::MGM &
GraphicalModelManipulator<GM>::getModifiedModel() const
{
OPENGM_ASSERT(isLocked() && validModel_);
return mgm_;
}
/// \brief return the i-th modified sub graphical model
template<class GM>
inline const typename GraphicalModelManipulator<GM>::MGM &
GraphicalModelManipulator<GM>::getModifiedSubModel(size_t i) const
{
OPENGM_ASSERT(isLocked() && validSubModels_);
OPENGM_ASSERT(i < submodels_.size());
return submodels_[i];
}
/// \brief return the number of submodels
template<class GM>
size_t GraphicalModelManipulator<GM>::numberOfSubmodels() const
{
OPENGM_ASSERT(isLocked());
return submodels_.size();
}
/// \brief unlock model
template<class GM>
void GraphicalModelManipulator<GM>::unlock()
{
locked_=false;
validSubModels_=false;
validModel_=false;
submodels_.clear();
freeAllVariables();
}
/// \brief lock model
template<class GM>
void GraphicalModelManipulator<GM>::lock()
{
locked_=true;
}
/// \brief return true if model is locked
template<class GM>
bool GraphicalModelManipulator<GM>::isLocked() const
{
return locked_;
}
/// \brief fix label for variable
template<class GM>
void GraphicalModelManipulator<GM>::fixVariable(const typename GM::IndexType var, const typename GM::LabelType l)
{
OPENGM_ASSERT(!isLocked());
if(!isLocked()){
fixVariable_[var]=true;
fixVariableLabel_[var]=l;
}
}
/// \brief remove fixed label for variable
template<class GM>
void GraphicalModelManipulator<GM>::freeVariable(const typename GM::IndexType var)
{
OPENGM_ASSERT(!isLocked());
if(!isLocked()){
fixVariable_[var]=false;
}
}
/// \brief remove fixed label for all variable
template<class GM>
void GraphicalModelManipulator<GM>::freeAllVariables()
{
OPENGM_ASSERT(!isLocked())
if(!isLocked()){
for(IndexType var=0; var<fixVariable_.size(); ++var)
fixVariable_[var]=false;
}
}
/// \brief transforming label of the modified to the labeling of the original problem
template<class GM>
void GraphicalModelManipulator<GM>::modifiedState2OriginalState(const std::vector<LabelType>& ml, std::vector<LabelType>& ol) const
{
OPENGM_ASSERT(isLocked());
OPENGM_ASSERT(ml.size()==mgm_.numberOfVariables());
if(isLocked() && ml.size()==mgm_.numberOfVariables()){
ol.resize(gm_.numberOfVariables());
size_t c = 0;
for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
if(fixVariable_[var]){
ol[var] = fixVariableLabel_[var];
}else{
ol[var] = ml[c++];
}
}
}
}
/// \brief transforming label of the modified subproblems to the labeling of the original problem
template<class GM>
void GraphicalModelManipulator<GM>::modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >& subconf, std::vector<LabelType>& conf) const
{
conf.resize(gm_.numberOfVariables());
std::vector<IndexType> varCount(submodels_.size(),0);
for(IndexType i=0;i<submodels_.size(); ++i){
OPENGM_ASSERT(submodels_[i].numberOfVariables()==subconf[i].size());
}
for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
if(fixVariable_[var]){
conf[var] = fixVariableLabel_[var];
}else{
const IndexType sp=var2subProblem_[var];
conf[var] = subconf[sp][varCount[sp]++];
}
}
}
/// \brief build modified model
template<class GM>
void
GraphicalModelManipulator<GM>::buildModifiedModel()
{
locked_ = true;
validModel_ = true;
IndexType numberOfVariables = 0;
std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
for(IndexType var=0; var<gm_.numberOfVariables();++var){
if(fixVariable_[var]==false){
varMap[var] = numberOfVariables++;
}
}
std::vector<LabelType> shape(numberOfVariables,0);
for(IndexType var=0; var<gm_.numberOfVariables();++var){
if(fixVariable_[var]==false){
shape[varMap[var]] = gm_.numberOfLabels(var);
}
}
MSpaceType space(shape.begin(),shape.end());
mgm_ = MGM(space);
std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
std::vector<IndexType> MVars;
ValueType constant;
GM::OperatorType::neutral(constant);
for(IndexType f=0; f<gm_.numberOfFactors();++f){
fixedVars.resize(0);
MVars.resize(0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
const IndexType var = gm_[f].variableIndex(i);
if(fixVariable_[var]){
fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
}else{
MVars.push_back(varMap[var]);
}
}
if(fixedVars.size()==0){//non fixed
const ViewFunction<GM> func(gm_[f]);
mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
}else if(fixedVars.size()==gm_[f].numberOfVariables()){//all fixed
std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
}
GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
}else{
const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
}
}
{
LabelType temp;
ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.begin());
}
}
/// \brief build modified sub-models
template<class GM>
void
GraphicalModelManipulator<GM>::buildModifiedSubModels()
{
locked_ = true;
validSubModels_ = true;
//Find Connected Components
std::vector<bool> closedVar = fixVariable_;
IndexType numberOfSubproblems = 0;
for(IndexType var=0 ; var<gm_.numberOfVariables(); ++var){
if(closedVar[var])
continue;
else{
expand(var, numberOfSubproblems, closedVar);
}
++numberOfSubproblems;
}
submodels_.resize(numberOfSubproblems);
std::vector<IndexType> numberOfVariables(numberOfSubproblems,0);
std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
for(IndexType var=0; var<gm_.numberOfVariables();++var){
if(fixVariable_[var]==false){
varMap[var] = numberOfVariables[var2subProblem_[var]]++;
}
}
std::vector<std::vector<LabelType> > shape(numberOfSubproblems);
for (size_t i=0; i<numberOfSubproblems; ++i){
shape[i] = std::vector<LabelType>(numberOfVariables[i],0);
}
for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
if(fixVariable_[var]==false){
shape[var2subProblem_[var]][varMap[var]] = gm_.numberOfLabels(var);
}
}
for (size_t i=0; i<numberOfSubproblems; ++i){
MSpaceType space(shape[i].begin(),shape[i].end());
submodels_[i] = MGM(space);
}
std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
std::vector<IndexType> MVars;
ValueType constant;
GM::OperatorType::neutral(constant);
for(IndexType f=0; f<gm_.numberOfFactors();++f){
IndexType subproblem = 0;
fixedVars.resize(0);
MVars.resize(0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
const IndexType var = gm_[f].variableIndex(i);
if(fixVariable_[var]){
fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
}else{
MVars.push_back(varMap[var]);
subproblem = var2subProblem_[var];
}
}
if(MVars.size()==0){ //constant, all fixed
std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
}
GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
}
else if(fixedVars.size()==0){//non fixed
const ViewFunction<GM> func(gm_[f]);
submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
}else{
const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
}
}
{
LabelType temp;
ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
submodels_[0].addFactor( submodels_[0].addFunction(func),MVars.begin(), MVars.begin());
}
}
////////////////////
// Private Methods
////////////////////
template<class GM>
void
GraphicalModelManipulator<GM>::expand(IndexType var, IndexType CCN, std::vector<bool>& closedVar)
{
if(closedVar[var])
return;
else{
closedVar[var] = true;
var2subProblem_[var] = CCN;
for( typename GM::ConstFactorIterator itf = gm_.factorsOfVariableBegin(var); itf!=gm_.factorsOfVariableEnd(var); ++itf){
for( typename GM::ConstVariableIterator itv = gm_.variablesOfFactorBegin(*itf); itv!=gm_.variablesOfFactorEnd(*itf);++itv){
expand(*itv, CCN, closedVar);
}
}
}
}
} //namespace opengm
#endif // #ifndef OPENGM_GRAPHICALMODEL_HXX
<|endoftext|> |
<commit_before>/*
============================================================================
Author : Alexey Tikhvinsky
Copyright : Copyright (C) 2011 Rhomobile (http://www.rhomobile.com).
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
============================================================================
*/
#include <android/native_activity.h>
#include "rhodes/JNIRhodes.h"
RHO_GLOBAL void delete_files_in_folder(const char *szFolderPath)
{
// JNIEnv *env = jnienv();
// jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
// if (!cls) return;
// jmethodID mid = getJNIClassStaticMethod(env, cls, "deleteFilesInFolder", "(Ljava/lang/String;)V");
// if (!mid) return;
// jhstring objFolderPath = rho_cast<jhstring>(szFolderPath);
// env->CallStaticVoidMethod(cls, mid, objFolderPath.get());
}
RHO_GLOBAL rho::String rho_sysimpl_get_phone_id()
{
return "";
}
RHO_GLOBAL void rho_free_callbackdata(void* pData)
{
}
RHO_GLOBAL int rho_net_ping_network(const char* szHost)
{
return 1;
}
<commit_msg>Rhosync-client-Java: fix build.<commit_after>/*
============================================================================
Author : Alexey Tikhvinsky
Copyright : Copyright (C) 2011 Rhomobile (http://www.rhomobile.com).
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
============================================================================
*/
#include <android/native_activity.h>
#include "rhodes/JNIRhodes.h"
RHO_GLOBAL void delete_files_in_folder(const char *szFolderPath)
{
// JNIEnv *env = jnienv();
// jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
// if (!cls) return;
// jmethodID mid = getJNIClassStaticMethod(env, cls, "deleteFilesInFolder", "(Ljava/lang/String;)V");
// if (!mid) return;
// jhstring objFolderPath = rho_cast<jhstring>(szFolderPath);
// env->CallStaticVoidMethod(cls, mid, objFolderPath.get());
}
rho::String rho_sysimpl_get_phone_id()
{
return "";
}
RHO_GLOBAL void rho_free_callbackdata(void* pData)
{
}
RHO_GLOBAL int rho_net_ping_network(const char* szHost)
{
return 1;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Steinwurf ApS nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <gtest/gtest.h>
#include <sak/buffer.hpp>
TEST(TestBuffer, construct)
{
sak::buffer b;
EXPECT_EQ(0U, b.size());
}
TEST(TestBuffer, resize)
{
sak::buffer b;
b.resize(100);
EXPECT_EQ(100U, b.size());
}
TEST(TestBuffer, resize_and_copy)
{
sak::buffer b1;
b1.resize(100);
EXPECT_EQ(100U, b1.size());
sak::buffer b2 = b1;
EXPECT_EQ(100U, b2.size());
}
TEST(TestBuffer, append_to_empty_with_size)
{
std::vector<uint8_t> data(32);
EXPECT_EQ(32U, data.size());
sak::buffer b;
EXPECT_EQ(0U, b.size());
b.append(&data[0], static_cast<uint32_t>(data.size()));
EXPECT_EQ(data.size(), b.size());
}
TEST(TestBuffer, append_to_empty_with_pointers)
{
std::vector<uint8_t> data(32);
EXPECT_EQ(32U, data.size());
sak::buffer b;
EXPECT_EQ(b.size(), 0U);
b.append(&data[0], &data[0] + data.size());
EXPECT_EQ(b.size(), data.size());
}
TEST(TestBuffer, append_to_empty_with_storage)
{
std::vector<uint8_t> data(32);
EXPECT_EQ(32U, data.size());
sak::buffer b;
EXPECT_EQ(b.size(), 0U);
b.append(sak::storage(data));
EXPECT_EQ(b.size(), data.size());
}
TEST(TestBuffer, append_to_initialized)
{
{
sak::buffer b(10);
EXPECT_EQ(b.size(), 0U);
std::vector<uint8_t> data(32, 'x');
EXPECT_EQ(32U, data.size());
b.append(&data[0], static_cast<uint32_t>(data.size()));
EXPECT_EQ(b.size(), data.size());
}
{
sak::buffer b(10);
EXPECT_EQ(b.size(), 0U);
std::vector<uint8_t> data(32, 'x');
EXPECT_EQ(32U, data.size());
b.append(&data[0], &data[0] + data.size());
EXPECT_EQ(b.size(), data.size());
}
{
sak::buffer b(10);
EXPECT_EQ(b.size(), 0U);
std::vector<uint8_t> data(32, 'x');
EXPECT_EQ(32U, data.size());
b.append(sak::storage(data));
EXPECT_EQ(b.size(), data.size());
}
}
TEST(TestBuffer, resize_and_clear)
{
sak::buffer b(100);
EXPECT_EQ(0U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.resize(10);
EXPECT_EQ(10U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.resize(101);
EXPECT_EQ(101U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.clear();
EXPECT_EQ(0U, b.size());
b.resize(0);
EXPECT_EQ(0U, b.size());
b.resize(102);
EXPECT_EQ(102U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.resize(0);
EXPECT_EQ(0U, b.size());
b.clear();
EXPECT_EQ(0U, b.size());
}
<commit_msg>Re-order vector constructors<commit_after>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Steinwurf ApS nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <gtest/gtest.h>
#include <sak/buffer.hpp>
TEST(TestBuffer, construct)
{
sak::buffer b;
EXPECT_EQ(0U, b.size());
}
TEST(TestBuffer, resize)
{
sak::buffer b;
b.resize(100);
EXPECT_EQ(100U, b.size());
}
TEST(TestBuffer, resize_and_copy)
{
sak::buffer b1;
b1.resize(100);
EXPECT_EQ(100U, b1.size());
sak::buffer b2 = b1;
EXPECT_EQ(100U, b2.size());
}
TEST(TestBuffer, append_to_empty_with_size)
{
std::vector<uint8_t> data(32);
EXPECT_EQ(32U, data.size());
sak::buffer b;
EXPECT_EQ(0U, b.size());
b.append(&data[0], static_cast<uint32_t>(data.size()));
EXPECT_EQ(data.size(), b.size());
}
TEST(TestBuffer, append_to_empty_with_pointers)
{
std::vector<uint8_t> data(32);
EXPECT_EQ(32U, data.size());
sak::buffer b;
EXPECT_EQ(b.size(), 0U);
b.append(&data[0], &data[0] + data.size());
EXPECT_EQ(b.size(), data.size());
}
TEST(TestBuffer, append_to_empty_with_storage)
{
std::vector<uint8_t> data(32);
EXPECT_EQ(32U, data.size());
sak::buffer b;
EXPECT_EQ(b.size(), 0U);
b.append(sak::storage(data));
EXPECT_EQ(b.size(), data.size());
}
TEST(TestBuffer, append_to_initialized)
{
{
std::vector<uint8_t> data(32, 'x');
EXPECT_EQ(32U, data.size());
sak::buffer b(10);
EXPECT_EQ(b.size(), 0U);
b.append(&data[0], static_cast<uint32_t>(data.size()));
EXPECT_EQ(b.size(), data.size());
}
{
std::vector<uint8_t> data(32, 'x');
EXPECT_EQ(32U, data.size());
sak::buffer b(10);
EXPECT_EQ(b.size(), 0U);
b.append(&data[0], &data[0] + data.size());
EXPECT_EQ(b.size(), data.size());
}
{
std::vector<uint8_t> data(32, 'x');
EXPECT_EQ(32U, data.size());
sak::buffer b(10);
EXPECT_EQ(b.size(), 0U);
b.append(sak::storage(data));
EXPECT_EQ(b.size(), data.size());
}
}
TEST(TestBuffer, resize_and_clear)
{
sak::buffer b(100);
EXPECT_EQ(0U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.resize(10);
EXPECT_EQ(10U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.resize(101);
EXPECT_EQ(101U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.clear();
EXPECT_EQ(0U, b.size());
b.resize(0);
EXPECT_EQ(0U, b.size());
b.resize(102);
EXPECT_EQ(102U, b.size());
std::fill_n(b.data(), b.size(), 'x');
b.resize(0);
EXPECT_EQ(0U, b.size());
b.clear();
EXPECT_EQ(0U, b.size());
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.