text
stringlengths 54
60.6k
|
---|
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_clique/cco_max_clique.hh>
#include <max_clique/cco_base.hh>
#include <max_clique/print_incumbent.hh>
#include <graph/template_voodoo.hh>
#include <graph/merge_cliques.hh>
#include <algorithm>
#include <thread>
#include <mutex>
using namespace parasols;
namespace
{
template <CCOPermutations perm_, CCOInference inference_, CCOMerge merge_, unsigned size_, typename VertexType_>
struct CCO : CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >
{
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::CCOBase;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::original_graph;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::graph;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::params;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::expand;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::order;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::colour_class_order;
MaxCliqueResult result;
std::list<std::set<int> > previouses;
auto run() -> MaxCliqueResult
{
result.size = params.initial_bound;
std::vector<unsigned> c;
c.reserve(graph.size());
FixedBitSet<size_> p; // potential additions
p.resize(graph.size());
p.set_all();
std::vector<int> positions;
positions.reserve(graph.size());
positions.push_back(0);
// initial colouring
std::array<VertexType_, size_ * bits_per_word> initial_p_order;
std::array<VertexType_, size_ * bits_per_word> initial_colours;
colour_class_order(SelectColourClassOrderOverload<perm_>(), p, initial_p_order, initial_colours);
result.initial_colour_bound = initial_colours[graph.size() - 1];
// go!
expand(c, p, initial_p_order, initial_colours, positions);
// hack for enumerate
if (params.enumerate)
result.size = result.members.size();
return result;
}
auto increment_nodes() -> void
{
++result.nodes;
}
auto recurse(
std::vector<unsigned> & c, // current candidate clique
FixedBitSet<size_> & p,
const std::array<VertexType_, size_ * bits_per_word> & p_order,
const std::array<VertexType_, size_ * bits_per_word> & colours,
std::vector<int> & position
) -> bool
{
expand(c, p, p_order, colours, position);
return true;
}
auto potential_new_best(
const std::vector<unsigned> & c,
const std::vector<int> & position) -> void
{
switch (merge_) {
case CCOMerge::None:
if (c.size() > result.size) {
if (params.enumerate) {
++result.result_count;
result.size = c.size() - 1;
}
else
result.size = c.size();
result.members.clear();
for (auto & v : c)
result.members.insert(order[v]);
print_incumbent(params, c.size(), position);
}
break;
case CCOMerge::Previous:
{
std::set<int> new_members;
for (auto & v : c)
new_members.insert(order[v]);
auto merged = merge_cliques(original_graph, result.members, new_members);
if (merged.size() > result.size) {
result.members = merged;
result.size = result.members.size();
print_incumbent(params, result.size, position);
}
}
break;
case CCOMerge::All:
{
std::set<int> new_members;
for (auto & v : c)
new_members.insert(order[v]);
for (auto & p : previouses) {
auto merged = merge_cliques(original_graph, p, new_members);
if (merged.size() > result.size) {
result.members = merged;
result.size = result.members.size();
previouses.push_back(result.members);
print_incumbent(params, result.size, position);
}
}
previouses.push_back(result.members);
print_position(params, "previouses is now " + std::to_string(previouses.size()), position);
}
break;
}
}
auto get_best_anywhere_value() -> unsigned
{
return result.size;
}
auto get_skip(unsigned, int &, bool &) -> void
{
}
};
}
template <CCOPermutations perm_, CCOInference inference_, CCOMerge merge_>
auto parasols::cco_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult
{
return select_graph_size<ApplyPermInferenceMerge<CCO, perm_, inference_, merge_>::template Type, MaxCliqueResult>(
AllGraphSizes(), graph, params);
}
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::None, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::None, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::None, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::None, CCOMerge::Previous>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::None, CCOMerge::Previous>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::None, CCOMerge::Previous>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::None, CCOMerge::All>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::None, CCOMerge::All>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::None, CCOMerge::All>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::GlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::GlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::GlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::LazyGlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::LazyGlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::LazyGlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
<commit_msg>Fix merge all<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_clique/cco_max_clique.hh>
#include <max_clique/cco_base.hh>
#include <max_clique/print_incumbent.hh>
#include <graph/template_voodoo.hh>
#include <graph/merge_cliques.hh>
#include <algorithm>
#include <thread>
#include <mutex>
using namespace parasols;
namespace
{
template <CCOPermutations perm_, CCOInference inference_, CCOMerge merge_, unsigned size_, typename VertexType_>
struct CCO : CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >
{
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::CCOBase;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::original_graph;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::graph;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::params;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::expand;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::order;
using CCOBase<perm_, inference_, merge_, size_, VertexType_, CCO<perm_, inference_, merge_, size_, VertexType_> >::colour_class_order;
MaxCliqueResult result;
std::list<std::set<int> > previouses;
auto run() -> MaxCliqueResult
{
result.size = params.initial_bound;
std::vector<unsigned> c;
c.reserve(graph.size());
FixedBitSet<size_> p; // potential additions
p.resize(graph.size());
p.set_all();
std::vector<int> positions;
positions.reserve(graph.size());
positions.push_back(0);
// initial colouring
std::array<VertexType_, size_ * bits_per_word> initial_p_order;
std::array<VertexType_, size_ * bits_per_word> initial_colours;
colour_class_order(SelectColourClassOrderOverload<perm_>(), p, initial_p_order, initial_colours);
result.initial_colour_bound = initial_colours[graph.size() - 1];
// go!
expand(c, p, initial_p_order, initial_colours, positions);
// hack for enumerate
if (params.enumerate)
result.size = result.members.size();
return result;
}
auto increment_nodes() -> void
{
++result.nodes;
}
auto recurse(
std::vector<unsigned> & c, // current candidate clique
FixedBitSet<size_> & p,
const std::array<VertexType_, size_ * bits_per_word> & p_order,
const std::array<VertexType_, size_ * bits_per_word> & colours,
std::vector<int> & position
) -> bool
{
expand(c, p, p_order, colours, position);
return true;
}
auto potential_new_best(
const std::vector<unsigned> & c,
const std::vector<int> & position) -> void
{
switch (merge_) {
case CCOMerge::None:
if (c.size() > result.size) {
if (params.enumerate) {
++result.result_count;
result.size = c.size() - 1;
}
else
result.size = c.size();
result.members.clear();
for (auto & v : c)
result.members.insert(order[v]);
print_incumbent(params, c.size(), position);
}
break;
case CCOMerge::Previous:
{
std::set<int> new_members;
for (auto & v : c)
new_members.insert(order[v]);
auto merged = merge_cliques(original_graph, result.members, new_members);
if (merged.size() > result.size) {
result.members = merged;
result.size = result.members.size();
print_incumbent(params, result.size, position);
}
}
break;
case CCOMerge::All:
{
std::set<int> new_members;
for (auto & v : c)
new_members.insert(order[v]);
if (previouses.empty()) {
result.members = new_members;
result.size = result.members.size();
previouses.push_back(result.members);
print_incumbent(params, result.size, position);
}
else
for (auto & p : previouses) {
auto merged = merge_cliques(original_graph, p, new_members);
if (merged.size() > result.size) {
result.members = merged;
result.size = result.members.size();
previouses.push_back(result.members);
print_incumbent(params, result.size, position);
}
}
previouses.push_back(result.members);
print_position(params, "previouses is now " + std::to_string(previouses.size()), position);
}
break;
}
}
auto get_best_anywhere_value() -> unsigned
{
return result.size;
}
auto get_skip(unsigned, int &, bool &) -> void
{
}
};
}
template <CCOPermutations perm_, CCOInference inference_, CCOMerge merge_>
auto parasols::cco_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult
{
return select_graph_size<ApplyPermInferenceMerge<CCO, perm_, inference_, merge_>::template Type, MaxCliqueResult>(
AllGraphSizes(), graph, params);
}
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::None, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::None, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::None, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::None, CCOMerge::Previous>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::None, CCOMerge::Previous>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::None, CCOMerge::Previous>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::None, CCOMerge::All>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::None, CCOMerge::All>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::None, CCOMerge::All>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::GlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::GlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::GlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::None, CCOInference::LazyGlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Defer1, CCOInference::LazyGlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::cco_max_clique<CCOPermutations::Sort, CCOInference::LazyGlobalDomination, CCOMerge::None>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
<|endoftext|> |
<commit_before>// Copyright 2016 Google 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 "cpu_instructions/x86/cleanup_instruction_set_properties.h"
#include <unordered_map>
#include "strings/string.h"
#include "cpu_instructions/base/cleanup_instruction_set.h"
#include "glog/logging.h"
#include "util/gtl/map_util.h"
namespace cpu_instructions {
namespace x86 {
namespace {
using ::cpu_instructions::util::OkStatus;
using ::cpu_instructions::util::Status;
const std::unordered_map<string, string>& GetMissingCpuFlags() {
static const std::unordered_map<string, string>* const kMissingFlags =
new std::unordered_map<string, string>({
{"CLFLUSH", "CLFSH"}, {"CLFLUSHOPT", "CLFLUSHOPT"},
});
return *kMissingFlags;
}
} // namespace
Status AddMissingCpuFlags(InstructionSetProto* instruction_set) {
CHECK(instruction_set != nullptr);
for (auto& instruction : *instruction_set->mutable_instructions()) {
const string* const feature_name = FindOrNull(
GetMissingCpuFlags(), instruction.vendor_syntax().mnemonic());
if (feature_name) {
// Be warned if they fix it someday. If this triggers, just remove the
// rule.
CHECK_NE(*feature_name, instruction.feature_name())
<< instruction.vendor_syntax().mnemonic();
instruction.set_feature_name(*feature_name);
}
}
return OkStatus();
}
REGISTER_INSTRUCTION_SET_TRANSFORM(AddMissingCpuFlags, 1000);
namespace {
// Returns the list of protection modes for priviledged instructions.
const std::unordered_map<string, int>& GetProtectionModes() {
static const std::unordered_map<string, int>* const kProtectionModes =
new std::unordered_map<string, int>({
// -----------------------
// Restricted operations.
{"CLAC", 0},
{"CLI", 0},
{"CLTS", 0},
{"HLT", 0},
{"INVD", 0},
{"INVPCID", 0},
{"LGDT", 0},
{"LIDT", 0},
{"LLDT", 0},
{"LMSW", 0},
{"LTR", 0},
{"MWAIT", 0},
// The instruction is not marked as priviledged in its doc, but SWAPGR
// later states that "The IA32_KERNEL_GS_BASE MSR itself is only
// accessible using RDMSR/WRMSR instructions. Those instructions are
// only accessible at privilege level 0."
{"RDMSR", 0},
{"STAC", 0},
{"STD", 0}, // Not 100% sure, it looks like the SDM is wrong.
{"STI", 0},
{"SWAPGR", 0},
{"SWAPGS", 0},
{"WBINVD", 0},
{"WRMSR", 0},
{"XRSTORS", 0},
{"XRSTORS64", 0},
// -----------------------
// Input/output.
// For now assume the worst case: IOPL == 0.
{"IN", 0},
{"INS", 0},
{"INSB", 0},
{"INSW", 0},
{"INSD", 0},
{"OUT", 0},
{"OUTS", 0},
{"OUTSB", 0},
{"OUTSD", 0},
{"OUTSW", 0},
// -----------------------
// SMM mode.
// For now assume that everything that needs to execute in SMM mode
// requires CPL 0.
{"RSM", 0},
});
return *kProtectionModes;
}
} // namespace
Status AddProtectionModes(InstructionSetProto* instruction_set) {
CHECK(instruction_set != nullptr);
for (auto& instruction : *instruction_set->mutable_instructions()) {
const int* mode = FindOrNull(GetProtectionModes(),
instruction.vendor_syntax().mnemonic());
if (mode) {
instruction.set_protection_mode(*mode);
}
}
return OkStatus();
}
REGISTER_INSTRUCTION_SET_TRANSFORM(AddProtectionModes, 1000);
} // namespace x86
} // namespace cpu_instructions
<commit_msg>RDPMC can run at CPL0.<commit_after>// Copyright 2016 Google 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 "cpu_instructions/x86/cleanup_instruction_set_properties.h"
#include <unordered_map>
#include "strings/string.h"
#include "cpu_instructions/base/cleanup_instruction_set.h"
#include "glog/logging.h"
#include "util/gtl/map_util.h"
namespace cpu_instructions {
namespace x86 {
namespace {
using ::cpu_instructions::util::OkStatus;
using ::cpu_instructions::util::Status;
const std::unordered_map<string, string>& GetMissingCpuFlags() {
static const std::unordered_map<string, string>* const kMissingFlags =
new std::unordered_map<string, string>({
{"CLFLUSH", "CLFSH"}, {"CLFLUSHOPT", "CLFLUSHOPT"},
});
return *kMissingFlags;
}
} // namespace
Status AddMissingCpuFlags(InstructionSetProto* instruction_set) {
CHECK(instruction_set != nullptr);
for (auto& instruction : *instruction_set->mutable_instructions()) {
const string* const feature_name = FindOrNull(
GetMissingCpuFlags(), instruction.vendor_syntax().mnemonic());
if (feature_name) {
// Be warned if they fix it someday. If this triggers, just remove the
// rule.
CHECK_NE(*feature_name, instruction.feature_name())
<< instruction.vendor_syntax().mnemonic();
instruction.set_feature_name(*feature_name);
}
}
return OkStatus();
}
REGISTER_INSTRUCTION_SET_TRANSFORM(AddMissingCpuFlags, 1000);
namespace {
// Returns the list of protection modes for priviledged instructions.
const std::unordered_map<string, int>& GetProtectionModes() {
static const std::unordered_map<string, int>* const kProtectionModes =
new std::unordered_map<string, int>({
// -----------------------
// Restricted operations.
{"CLAC", 0},
{"CLI", 0},
{"CLTS", 0},
{"HLT", 0},
{"INVD", 0},
{"INVPCID", 0},
{"LGDT", 0},
{"LIDT", 0},
{"LLDT", 0},
{"LMSW", 0},
{"LTR", 0},
{"MWAIT", 0},
// The instruction is not marked as priviledged in its doc, but SWAPGR
// later states that "The IA32_KERNEL_GS_BASE MSR itself is only
// accessible using RDMSR/WRMSR instructions. Those instructions are
// only accessible at privilege level 0."
{"RDMSR", 0},
{"RDPMC", 0},
{"STAC", 0},
{"STD", 0}, // Not 100% sure, it looks like the SDM is wrong.
{"STI", 0},
{"SWAPGR", 0},
{"SWAPGS", 0},
{"WBINVD", 0},
{"WRMSR", 0},
{"XRSTORS", 0},
{"XRSTORS64", 0},
// -----------------------
// Input/output.
// For now assume the worst case: IOPL == 0.
{"IN", 0},
{"INS", 0},
{"INSB", 0},
{"INSW", 0},
{"INSD", 0},
{"OUT", 0},
{"OUTS", 0},
{"OUTSB", 0},
{"OUTSD", 0},
{"OUTSW", 0},
// -----------------------
// SMM mode.
// For now assume that everything that needs to execute in SMM mode
// requires CPL 0.
{"RSM", 0},
});
return *kProtectionModes;
}
} // namespace
Status AddProtectionModes(InstructionSetProto* instruction_set) {
CHECK(instruction_set != nullptr);
for (auto& instruction : *instruction_set->mutable_instructions()) {
const int* mode = FindOrNull(GetProtectionModes(),
instruction.vendor_syntax().mnemonic());
if (mode) {
instruction.set_protection_mode(*mode);
}
}
return OkStatus();
}
REGISTER_INSTRUCTION_SET_TRANSFORM(AddProtectionModes, 1000);
} // namespace x86
} // namespace cpu_instructions
<|endoftext|> |
<commit_before>
// INCLUDES
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include "atTCPNetworkInterface.h++"
atTCPNetworkInterface::atTCPNetworkInterface(char * address, short port)
{
char hostname[MAXHOSTNAMELEN];
struct hostent * host;
// Open the socket
if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
notify(AT_ERROR, "Unable to open socket for communication.\n");
// Get information about this host and initialize the read name field
gethostname(hostname, sizeof(hostname));
host = gethostbyname(hostname);
read_name.sin_family = AF_INET;
memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
read_name.sin_port = htons(port);
// Get information about remote host and initialize the write name field
host = gethostbyname(address);
write_name.sin_family = AF_INET;
memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
write_name.sin_port = htons(port);
// Initialize remaining instance variables
num_client_sockets = 0;
}
atTCPNetworkInterface::~atTCPNetworkInterface()
{
// Close the socket
close(socket_value);
}
void atTCPNetworkInterface::allowConnections(int backlog)
{
// Bind to the port
if (bind(socket_value, (struct sockaddr *) &read_name,
sizeof(read_name)) < 0)
{
notify(AT_ERROR, "Unable to bind to the port.\n");
}
// Notify our willingness to accept connections and give a backlog limit
listen(socket_value, backlog);
}
int atTCPNetworkInterface::acceptConnection()
{
int newSocket;
struct sockaddr_in connectingName;
socklen_t connectingNameLength;
// Try to accept a connection
connectingNameLength = sizeof(connectingName);
newSocket = accept(socket_value, (struct sockaddr *) &connectingName,
&connectingNameLength);
// If we had an error and it wasn't that we would block on a non-blocking
// socket (a blocking socket shouldn't generate an EWOULDBLOCK error), then
// notify the user; otherwise, store the socket and return an ID to the user
if (newSocket == -1)
{
if (errno != EWOULDBLOCK)
notify(AT_ERROR, "Could not accept a connection.\n");
return -1;
}
else
{
client_sockets[num_client_sockets] = newSocket;
num_client_sockets++;
return num_client_sockets - 1;
}
}
void atTCPNetworkInterface::enableBlockingOnClient(int clientID)
{
int statusFlags;
// Get the current flags on the socket (return an error if we fail)
if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 )
notify(AT_ERROR, "Unable to get status of socket.\n");
else
{
// Now set the flags back while removing the non-blocking bit
if (fcntl(client_sockets[clientID], F_SETFL,
statusFlags & (~FNONBLOCK)) < 0)
{
// Report an error if we fail
notify(AT_ERROR, "Unable to disable blocking on socket.\n");
}
}
}
void atTCPNetworkInterface::disableBlockingOnClient(int clientID)
{
int statusFlags;
// Get the current flags on the socket (return an error if we fail)
if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 )
notify(AT_ERROR, "Unable to get status of socket.\n");
else
{
// Now set the flags back while adding the non-blocking bit (report any
// errors we get if we fail)
if (fcntl(client_sockets[clientID], F_SETFL, statusFlags | FNONBLOCK) < 0)
notify(AT_ERROR, "Unable to disable blocking on socket.\n");
}
}
int atTCPNetworkInterface::makeConnection()
{
int statusFlags;
int keepTrying;
struct sockaddr_in connectingName;
// Get flags on our current socket (so we can put them on new sockets if
// needed)
if ( (statusFlags = fcntl(socket_value, F_GETFL)) < 0 )
notify(AT_ERROR, "Unable to get status of socket.\n");
keepTrying = 1;
while (keepTrying == 1)
{
// Try to connect
connectingName = write_name;
if (connect(socket_value, (struct sockaddr *) &connectingName,
sizeof(connectingName)) != -1)
{
// We connected so signal the loop to end
keepTrying = 0;
}
else
{
// We didn't connect so close the socket
close(socket_value);
socket_value = -1;
// If we are not in blocking mode, tell the loop to stop (we give up);
// Otherwise, tell the user the info that we failed this time and
// re-open the socket
if ( (fcntl(socket_value, F_GETFL) & FNONBLOCK) != 0 )
keepTrying = 0;
else
{
notify(AT_INFO, "Failed to connect to server. Trying again.\n");
// Re-open the socket
if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
notify(AT_ERROR, "Unable to open socket for communication.\n");
// Put flags from previous socket on this new socket
if (fcntl(socket_value, F_SETFL, statusFlags) < 0)
notify(AT_ERROR, "Unable to disable blocking on socket.\n");
}
}
}
// Tell the user whether or not we succeeded to connect
if (socket_value == -1)
return -1;
else
return 0;
}
int atTCPNetworkInterface::read(u_char * buffer, u_long len)
{
struct sockaddr_in fromAddress;
socklen_t fromAddressLength;
int packetLength;
// Get a packet
fromAddressLength = sizeof(fromAddress);
packetLength = recvfrom(socket_value, buffer, len, MSG_WAITALL,
(struct sockaddr *) &fromAddress,
&fromAddressLength);
// Tell user how many bytes we read (-1 means an error)
return packetLength;
}
int atTCPNetworkInterface::read(int clientID, u_char * buffer, u_long len)
{
struct sockaddr_in fromAddress;
socklen_t fromAddressLength;
int packetLength;
// Get a packet
fromAddressLength = sizeof(fromAddress);
packetLength = recvfrom(client_sockets[clientID], buffer, len, MSG_WAITALL,
(struct sockaddr *) &fromAddress,
&fromAddressLength);
// Tell user how many bytes we read (-1 means an error)
return packetLength;
}
int atTCPNetworkInterface::write(u_char * buffer, u_long len)
{
int lengthWritten;
// Write the packet
lengthWritten = sendto(socket_value, buffer, len, 0,
(struct sockaddr *) &write_name, write_name_length);
// Tell user how many bytes we wrote (-1 if error)
return lengthWritten;
}
int atTCPNetworkInterface::write(int clientID, u_char * buffer, u_long len)
{
int lengthWritten;
// Write the packet
lengthWritten = sendto(client_sockets[clientID], buffer, len, 0,
(struct sockaddr *) &write_name, write_name_length);
// Tell user how many bytes we wrote (-1 if error)
return lengthWritten;
}
<commit_msg>Fixed missing constructor.<commit_after>
// INCLUDES
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include "atTCPNetworkInterface.h++"
atTCPNetworkInterface::atTCPNetworkInterface(char * address, short port)
{
char hostname[MAXHOSTNAMELEN];
struct hostent * host;
// Open the socket
if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
notify(AT_ERROR, "Unable to open socket for communication.\n");
// Get information about this host and initialize the read name field
gethostname(hostname, sizeof(hostname));
host = gethostbyname(hostname);
read_name.sin_family = AF_INET;
memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
read_name.sin_port = htons(port);
// Get information about remote host and initialize the write name field
host = gethostbyname(address);
write_name.sin_family = AF_INET;
memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
write_name.sin_port = htons(port);
// Initialize remaining instance variables
num_client_sockets = 0;
}
atTCPNetworkInterface::atTCPNetworkInterface(short port)
{
char hostname[MAXHOSTNAMELEN];
struct hostent * host;
// Open the socket
if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
notify(AT_ERROR, "Unable to open socket for communication.\n");
// Get information about this host and initialize the read name field
gethostname(hostname, sizeof(hostname));
host = gethostbyname(hostname);
read_name.sin_family = AF_INET;
memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
read_name.sin_port = htons(port);
// Get information about remote host and initialize the write name field
write_name.sin_family = AF_INET;
memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
write_name.sin_port = htons(port);
// Initialize remaining instance variables
num_client_sockets = 0;
}
atTCPNetworkInterface::~atTCPNetworkInterface()
{
// Close the socket
close(socket_value);
}
void atTCPNetworkInterface::allowConnections(int backlog)
{
// Bind to the port
if (bind(socket_value, (struct sockaddr *) &read_name,
sizeof(read_name)) < 0)
{
notify(AT_ERROR, "Unable to bind to the port.\n");
}
// Notify our willingness to accept connections and give a backlog limit
listen(socket_value, backlog);
}
int atTCPNetworkInterface::acceptConnection()
{
int newSocket;
struct sockaddr_in connectingName;
socklen_t connectingNameLength;
// Try to accept a connection
connectingNameLength = sizeof(connectingName);
newSocket = accept(socket_value, (struct sockaddr *) &connectingName,
&connectingNameLength);
// If we had an error and it wasn't that we would block on a non-blocking
// socket (a blocking socket shouldn't generate an EWOULDBLOCK error), then
// notify the user; otherwise, store the socket and return an ID to the user
if (newSocket == -1)
{
if (errno != EWOULDBLOCK)
notify(AT_ERROR, "Could not accept a connection.\n");
return -1;
}
else
{
client_sockets[num_client_sockets] = newSocket;
num_client_sockets++;
return num_client_sockets - 1;
}
}
void atTCPNetworkInterface::enableBlockingOnClient(int clientID)
{
int statusFlags;
// Get the current flags on the socket (return an error if we fail)
if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 )
notify(AT_ERROR, "Unable to get status of socket.\n");
else
{
// Now set the flags back while removing the non-blocking bit
if (fcntl(client_sockets[clientID], F_SETFL,
statusFlags & (~FNONBLOCK)) < 0)
{
// Report an error if we fail
notify(AT_ERROR, "Unable to disable blocking on socket.\n");
}
}
}
void atTCPNetworkInterface::disableBlockingOnClient(int clientID)
{
int statusFlags;
// Get the current flags on the socket (return an error if we fail)
if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 )
notify(AT_ERROR, "Unable to get status of socket.\n");
else
{
// Now set the flags back while adding the non-blocking bit (report any
// errors we get if we fail)
if (fcntl(client_sockets[clientID], F_SETFL, statusFlags | FNONBLOCK) < 0)
notify(AT_ERROR, "Unable to disable blocking on socket.\n");
}
}
int atTCPNetworkInterface::makeConnection()
{
int statusFlags;
int keepTrying;
struct sockaddr_in connectingName;
// Get flags on our current socket (so we can put them on new sockets if
// needed)
if ( (statusFlags = fcntl(socket_value, F_GETFL)) < 0 )
notify(AT_ERROR, "Unable to get status of socket.\n");
keepTrying = 1;
while (keepTrying == 1)
{
// Try to connect
connectingName = write_name;
if (connect(socket_value, (struct sockaddr *) &connectingName,
sizeof(connectingName)) != -1)
{
// We connected so signal the loop to end
keepTrying = 0;
}
else
{
// We didn't connect so close the socket
close(socket_value);
socket_value = -1;
// If we are not in blocking mode, tell the loop to stop (we give up);
// Otherwise, tell the user the info that we failed this time and
// re-open the socket
if ( (fcntl(socket_value, F_GETFL) & FNONBLOCK) != 0 )
keepTrying = 0;
else
{
notify(AT_INFO, "Failed to connect to server. Trying again.\n");
// Re-open the socket
if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
notify(AT_ERROR, "Unable to open socket for communication.\n");
// Put flags from previous socket on this new socket
if (fcntl(socket_value, F_SETFL, statusFlags) < 0)
notify(AT_ERROR, "Unable to disable blocking on socket.\n");
}
}
}
// Tell the user whether or not we succeeded to connect
if (socket_value == -1)
return -1;
else
return 0;
}
int atTCPNetworkInterface::read(u_char * buffer, u_long len)
{
struct sockaddr_in fromAddress;
socklen_t fromAddressLength;
int packetLength;
// Get a packet
fromAddressLength = sizeof(fromAddress);
packetLength = recvfrom(socket_value, buffer, len, MSG_WAITALL,
(struct sockaddr *) &fromAddress,
&fromAddressLength);
// Tell user how many bytes we read (-1 means an error)
return packetLength;
}
int atTCPNetworkInterface::read(int clientID, u_char * buffer, u_long len)
{
struct sockaddr_in fromAddress;
socklen_t fromAddressLength;
int packetLength;
// Get a packet
fromAddressLength = sizeof(fromAddress);
packetLength = recvfrom(client_sockets[clientID], buffer, len, MSG_WAITALL,
(struct sockaddr *) &fromAddress,
&fromAddressLength);
// Tell user how many bytes we read (-1 means an error)
return packetLength;
}
int atTCPNetworkInterface::write(u_char * buffer, u_long len)
{
int lengthWritten;
// Write the packet
lengthWritten = sendto(socket_value, buffer, len, 0,
(struct sockaddr *) &write_name, write_name_length);
// Tell user how many bytes we wrote (-1 if error)
return lengthWritten;
}
int atTCPNetworkInterface::write(int clientID, u_char * buffer, u_long len)
{
int lengthWritten;
// Write the packet
lengthWritten = sendto(client_sockets[clientID], buffer, len, 0,
(struct sockaddr *) &write_name, write_name_length);
// Tell user how many bytes we wrote (-1 if error)
return lengthWritten;
}
<|endoftext|> |
<commit_before>#include <iostream>
int main(void) {
int apple = 9;
auto lambda_capture_value = [apple] () { return apple; };
auto lambda_capture_reference = [&apple] () { return apple; };
apple = 0;
std::cout << "apple = " << apple
<< ", lambda_capture_value return value = " << lambda_capture_value()
<< ", lambda_capture_reference return value = " << lambda_capture_reference()
<< std::endl;
return 0;
}
<commit_msg>cpp update<commit_after>#include <iostream>
int main(void) {
int apple = 9;
auto lambda_capture_value = [apple] () { return apple; };
auto lambda_capture_reference = [&apple] () { return apple; };
auto lambda_auto_capture_value = [=] () { return apple; }
auto lambda_auto_capture_reference = [&] () { return apple; }
apple = 0;
std::cout << "apple = " << apple
<< ", lambda_capture_value return value = " << lambda_capture_value()
<< ", lambda_capture_reference return value = " << lambda_capture_reference()
<< ", lambda_auto_capture_value return value = " << lambda_auto_capture_value()
<< ", lambda_auto_capture_reference return value = " << lambda_auto_capture_reference()
<< std::endl;
return 0;
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "MemoryUsageReporter.h"
#include "MemoryUtils.h"
MemoryUsageReporter::MemoryUsageReporter(const MooseObject * moose_object)
: _mur_communicator(moose_object->comm()),
_my_rank(_mur_communicator.rank()),
_nrank(_mur_communicator.size()),
_hardware_id(_nrank)
{
// get total available ram
_memory_total = MemoryUtils::getTotalRAM();
if (!_memory_total)
mooseWarning("Unable to query hardware memory size in ", moose_object->name());
// gather all per node memory to processor zero
std::vector<unsigned long long> memory_totals(_nrank);
_mur_communicator.gather(0, _memory_total, memory_totals);
sharedMemoryRanksBySplitCommunicator();
// validate and store per node memory
if (_my_rank == 0)
for (std::size_t i = 0; i < _nrank; ++i)
{
auto id = _hardware_id[i];
if (id == _hardware_memory_total.size())
{
_hardware_memory_total.resize(id + 1);
_hardware_memory_total[id] = memory_totals[i];
}
else if (_hardware_memory_total[id] != memory_totals[i])
mooseWarning("Inconsistent total memory reported by ranks on the same hardware node in ",
moose_object->name());
}
}
void
MemoryUsageReporter::sharedMemoryRanksBySplitCommunicator()
{
// figure out which ranks share memory
processor_id_type world_rank = 0;
#ifdef LIBMESH_HAVE_MPI
// create a split communicator among shared memory ranks
MPI_Comm shmem_raw_comm;
MPI_Comm_split_type(
_mur_communicator.get(), MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &shmem_raw_comm);
Parallel::Communicator shmem_comm(shmem_raw_comm);
// broadcast the world rank of the sub group root
world_rank = _my_rank;
shmem_comm.broadcast(world_rank, 0);
#endif
std::vector<processor_id_type> world_ranks(_nrank);
_mur_communicator.gather(0, world_rank, world_ranks);
// assign a contiguous unique numerical id to each shared memory group on processor zero
unsigned int id = 0;
processor_id_type last = world_ranks[0];
if (_my_rank == 0)
for (std::size_t i = 0; i < _nrank; ++i)
{
if (world_ranks[i] != last)
{
last = world_ranks[i];
id++;
}
_hardware_id[i] = id;
}
}
void
MemoryUsageReporter::sharedMemoryRanksByProcessorname()
{
// get processor names and assign a unique number to each piece of hardware
std::string processor_name = MemoryUtils::getMPIProcessorName();
// gather all names at processor zero
std::vector<std::string> processor_names(_nrank);
_mur_communicator.gather(0, processor_name, processor_names);
// assign a unique numerical id to them on processor zero
unsigned int id = 0;
if (_my_rank == 0)
{
// map to assign an id to each processor name string
std::map<std::string, unsigned int> hardware_id_map;
for (std::size_t i = 0; i < _nrank; ++i)
{
// generate or look up unique ID for the current processor name
auto it = hardware_id_map.lower_bound(processor_names[i]);
if (it == hardware_id_map.end() || it->first != processor_names[i])
it = hardware_id_map.emplace_hint(it, processor_names[i], id++);
_hardware_id[i] = it->second;
}
}
}
<commit_msg>Free the comm in MemoryUsageReporter<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "MemoryUsageReporter.h"
#include "MemoryUtils.h"
MemoryUsageReporter::MemoryUsageReporter(const MooseObject * moose_object)
: _mur_communicator(moose_object->comm()),
_my_rank(_mur_communicator.rank()),
_nrank(_mur_communicator.size()),
_hardware_id(_nrank)
{
// get total available ram
_memory_total = MemoryUtils::getTotalRAM();
if (!_memory_total)
mooseWarning("Unable to query hardware memory size in ", moose_object->name());
// gather all per node memory to processor zero
std::vector<unsigned long long> memory_totals(_nrank);
_mur_communicator.gather(0, _memory_total, memory_totals);
sharedMemoryRanksBySplitCommunicator();
// validate and store per node memory
if (_my_rank == 0)
for (std::size_t i = 0; i < _nrank; ++i)
{
auto id = _hardware_id[i];
if (id == _hardware_memory_total.size())
{
_hardware_memory_total.resize(id + 1);
_hardware_memory_total[id] = memory_totals[i];
}
else if (_hardware_memory_total[id] != memory_totals[i])
mooseWarning("Inconsistent total memory reported by ranks on the same hardware node in ",
moose_object->name());
}
}
void
MemoryUsageReporter::sharedMemoryRanksBySplitCommunicator()
{
// figure out which ranks share memory
processor_id_type world_rank = 0;
#ifdef LIBMESH_HAVE_MPI
// create a split communicator among shared memory ranks
MPI_Comm shmem_raw_comm;
MPI_Comm_split_type(
_mur_communicator.get(), MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &shmem_raw_comm);
Parallel::Communicator shmem_comm(shmem_raw_comm);
// broadcast the world rank of the sub group root
world_rank = _my_rank;
shmem_comm.broadcast(world_rank, 0);
MPI_Comm_free(&shmem_raw_comm);
#endif
std::vector<processor_id_type> world_ranks(_nrank);
_mur_communicator.gather(0, world_rank, world_ranks);
// assign a contiguous unique numerical id to each shared memory group on processor zero
unsigned int id = 0;
processor_id_type last = world_ranks[0];
if (_my_rank == 0)
for (std::size_t i = 0; i < _nrank; ++i)
{
if (world_ranks[i] != last)
{
last = world_ranks[i];
id++;
}
_hardware_id[i] = id;
}
}
void
MemoryUsageReporter::sharedMemoryRanksByProcessorname()
{
// get processor names and assign a unique number to each piece of hardware
std::string processor_name = MemoryUtils::getMPIProcessorName();
// gather all names at processor zero
std::vector<std::string> processor_names(_nrank);
_mur_communicator.gather(0, processor_name, processor_names);
// assign a unique numerical id to them on processor zero
unsigned int id = 0;
if (_my_rank == 0)
{
// map to assign an id to each processor name string
std::map<std::string, unsigned int> hardware_id_map;
for (std::size_t i = 0; i < _nrank; ++i)
{
// generate or look up unique ID for the current processor name
auto it = hardware_id_map.lower_bound(processor_names[i]);
if (it == hardware_id_map.end() || it->first != processor_names[i])
it = hardware_id_map.emplace_hint(it, processor_names[i], id++);
_hardware_id[i] = it->second;
}
}
}
<|endoftext|> |
<commit_before>#ifndef TYPES_H
#define TYPES_H
/*
Defines a set of types for use on the hl-side.
*/
#include"objects.hpp"
class GenericTraverser {
public:
virtual void traverse(Object::ref&) =0;
virtual ~GenericTraverser();
};
/*-----------------------------------------------------------------------------
Generic
-----------------------------------------------------------------------------*/
class Generic {
public:
virtual void traverse_references(GenericTraverser* gt) {
/*default to having no references to traverse*/
}
/*some objects have extra allocated space at their ends
(e.g. Closure).
This virtual function returns the total size of the class
plus extra allocated space.
*/
virtual size_t real_size(void) const =0;
/*hash functions for table-ident and table-is*/
virtual size_t hash_ident(void) const {
return reinterpret_cast<size_t>(this);
}
virtual size_t hash_is(void) const {
return reinterpret_cast<size_t>(this);
}
/*broken hearts for GC*/
virtual void break_heart(Object::ref) =0;
/*dtor*/
virtual ~Generic() { }
};
template<class T>
class GenericDerived : class Generic {
public:
virtual size_t real_size(void) {
return sizeof(T);
}
virtual void break_heart(Generic* to) {
Generic* gp = this;
gp->~Generic();
new((void*) gp) BrokenHeartFor<T>(to);
};
};
void throw_OverBrokenHeart(Generic*);
class BrokenHeart : class Generic {
public:
Generic* to;
virtual bool break_heart(Generic* to) {
/*already broken - don't break too much!*/
throw_OverBrokenHeart(to);
}
};
template<class T>
class BrokenHeartFor : class BrokenHeart {
public:
virtual bool real_size(void) {
return sizeof(T);
}
};
#endif //TYPES_H
<commit_msg>inc/types.hpp: reorganized, corrected major syntax errors, added generic-derived for variadic<commit_after>#ifndef TYPES_H
#define TYPES_H
/*
Defines a set of types for use on the hl-side.
*/
#include"objects.hpp"
class GenericTraverser {
public:
virtual void traverse(Object::ref&) =0;
virtual ~GenericTraverser();
};
/*-----------------------------------------------------------------------------
Generic
-----------------------------------------------------------------------------*/
class Generic {
public:
virtual void traverse_references(GenericTraverser* gt) {
/*default to having no references to traverse*/
/*example for Cons:
gt->traverse(a);
gt->traverse(d);
*/
}
/*some objects have extra allocated space at their ends
(e.g. Closure).
This virtual function returns the total size of the class
plus extra allocated space.
*/
virtual size_t real_size(void) const =0;
/*hash functions for table-ident and table-is*/
virtual size_t hash_ident(void) const {
return reinterpret_cast<size_t>(this);
}
virtual size_t hash_is(void) const {
return reinterpret_cast<size_t>(this);
}
/*broken hearts for GC*/
virtual void break_heart(Object::ref) =0;
/*dtor*/
virtual ~Generic() { }
};
/*-----------------------------------------------------------------------------
Broken Heart tags
-----------------------------------------------------------------------------*/
void throw_OverBrokenHeart(Generic*);
class BrokenHeart : public Generic {
public:
Generic* to;
virtual bool break_heart(Generic* to) {
/*already broken - don't break too much!*/
throw_OverBrokenHeart(to);
}
BrokenHeart(Object::ref nto) : to(nto) { }
};
template<class T>
class BrokenHeartFor : public BrokenHeart {
public:
virtual bool real_size(void) const {
return sizeof(T);
}
explicit BrokenHeartFor<T>(Object::ref x) : BrokenHeart(x) { }
};
template<class T>
class BrokenHeartForVariadic : public BrokenHeart {
private:
size_t sz;
public:
virtual bool real_size(void) const {
return sizeof(T) + sz * sizeof(Object::ref);
}
BrokenHeartForVariadic<T>(Object::ref x, size_t nsz)
: BrokenHeart(x), sz(nsz) { }
};
/*-----------------------------------------------------------------------------
Base classes for Generic-derived objects
-----------------------------------------------------------------------------*/
template<class T>
class GenericDerived : public Generic {
public:
virtual size_t real_size(void) const {
return sizeof(T);
}
virtual void break_heart(Generic* to) {
Generic* gp = this;
gp->~Generic();
new((void*) gp) BrokenHeartFor<T>(to);
};
};
/*This class implements a variable-size object by informing the
memory system to reserve extra space.
*/
template<class T>
class GenericDerivedVariadic : public Generic {
GenericDerivedVariadic<T>(); // disallowed!
protected:
/*number of extra Object::ref's*/
size_t sz;
/*used by the derived classes to get access to
the variadic data at the end of the object.
*/
Object::ref& index(size_t i) {
void* vp = this;
char* cp = (char*) vp;
cp = cp + sizeof(T);
Object::ref* op = (void*) cp;
return op[i];
}
GenericDerivedVariadic<T>(size_t nsz) : sz(nsz) {
/*clear the extra references*/
for(size_t i; i < nsz; ++i) {
index(i) = Object::nil();
}
}
public:
virtual size_t real_size(void) const {
return sizeof(T) + sz * sizeof(Object::ref);
}
virtual void break_heart(Object::ref to) {
Generic* gp = this;
size_t nsz = sz; //save this before dtoring!
gp->~Generic();
new((void*) gp) BrokenHeartForVariadic<T>(to, nsz);
}
};
#endif //TYPES_H
<|endoftext|> |
<commit_before>/***********************************************************************************
**
** FileManager.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "FileManager.h"
#include "../Wisp/WispApplication.h"
CFileManager g_FileManager;
//----------------------------------------------------------------------------------
CFileManager::CFileManager()
: m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0)
{
}
//----------------------------------------------------------------------------------
CFileManager::~CFileManager()
{
}
//----------------------------------------------------------------------------------
bool CFileManager::Load()
{
if (!g_FileManager.UseUOP)
{
if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul")))
return false;
else if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul")))
return false;
else if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul")))
return false;
else if (!m_ArtMul.Load(g_App.FilePath("art.mul")))
return false;
else if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul")))
return false;
else if (!m_SoundMul.Load(g_App.FilePath("sound.mul")))
return false;
}
else
{
if (!m_artLegacyMUL.Load(g_App.FilePath("artLegacyMUL.uop")))
return false;
if (!m_gumpartLegacyMUL.Load(g_App.FilePath("gumpartLegacyMUL.uop")))
return false;
if (!m_soundLegacyMUL.Load(g_App.FilePath("soundLegacyMUL.uop")))
return false;
if (!m_tileart.Load(g_App.FilePath("tileart.uop")))
return false;
if (!m_string_dictionary.Load(g_App.FilePath("string_dictionary.uop")))
return false;
if (!m_MultiCollection.Load(g_App.FilePath("MultiCollection.uop")))
return false;
if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop")))
return false;
if (!m_MainMisc.Load(g_App.FilePath("MainMisc.uop")))
return false;
IFOR(i, 1, 5)
{
if (!m_AnimationFrame[i].Load(g_App.FilePath("AnimationFrame%i.uop", i)))
return false;
}
}
if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx")))
return false;
if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul")))
return false;
else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx")))
return false;
else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx")))
return false;
else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle")))
return false;
else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul")))
return false;
else if (!m_SpeechMul.Load(g_App.FilePath("speech.mul")))
return false;
else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul")))
return false;
else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul")))
return false;
else if (!m_HuesMul.Load(g_App.FilePath("hues.mul")))
return false;
else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul")))
return false;
else if (!m_LightMul.Load(g_App.FilePath("light.mul")))
return false;
else if (!m_MultiMul.Load(g_App.FilePath("multi.mul")))
return false;
else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul")))
return false;
else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul")))
return false;
else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul")))
return false;
else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul")))
return false;
else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul")))
return false;
m_LangcodeIff.Load(g_App.FilePath("Langcode.iff"));
IFOR(i, 0, 6)
{
if (g_FileManager.UseUOP && i > 1 || !g_FileManager.UseUOP && i > 0)
{
if (!m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i)))
return false;
if (!m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i)))
return false;
}
if (g_FileManager.UseUOP)
{
if (!m_MapUOP[i].Load(g_App.FilePath("map%iLegacyMUL.uop", i)))
return false;
if (i == 0 || i == 1 || i == 2 || i == 5)
{
if (!m_MapXUOP[i].Load(g_App.FilePath("map%ixLegacyMUL.uop", i)))
return false;
}
}
else
{
m_MapMul[i].Load(g_App.FilePath("map%i.mul", i));
}
m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i));
m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i));
m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i));
}
IFOR(i, 0, 20)
{
string s;
if (i)
s = g_App.FilePath("unifont%i.mul", i);
else
s = g_App.FilePath("unifont.mul");
if (!m_UnifontMul[i].Load(s))
break;
m_UnicodeFontsCount++;
}
if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul")))
m_UseVerdata = false;
return true;
}
//----------------------------------------------------------------------------------
void CFileManager::Unload()
{
if (!g_FileManager.UseUOP)
{
m_ArtIdx.Unload();
m_GumpIdx.Unload();
m_SoundIdx.Unload();
m_ArtMul.Unload();
m_GumpMul.Unload();
m_SoundMul.Unload();
}
else
{
m_artLegacyMUL.Unload();
m_gumpartLegacyMUL.Unload();
m_soundLegacyMUL.Unload();
m_tileart.Unload();
m_string_dictionary.Unload();
m_MultiCollection.Unload();
m_AnimationSequence.Unload();
m_MainMisc.Unload();
IFOR(i, 1, 5)
{
m_AnimationFrame[i].Unload();
}
}
m_LightIdx.Unload();
m_MultiIdx.Unload();
m_SkillsIdx.Unload();
m_MultiMap.Unload();
m_TextureIdx.Unload();
m_SpeechMul.Unload();
m_AnimdataMul.Unload();
m_HuesMul.Unload();
m_FontsMul.Unload();
m_LightMul.Unload();
m_MultiMul.Unload();
m_PaletteMul.Unload();
m_RadarcolMul.Unload();
m_SkillsMul.Unload();
m_TextureMul.Unload();
m_TiledataMul.Unload();
m_LangcodeIff.Unload();
IFOR(i, 0, 6)
{
m_AnimIdx[i].Unload();
m_AnimMul[i].Unload();
if (g_FileManager.UseUOP)
{
m_MapUOP[i].Unload();
m_MapXUOP[i].Unload();
}
else
m_MapMul[i].Unload();
m_StaticIdx[i].Unload();
m_StaticMul[i].Unload();
m_FacetMul[i].Unload();
}
IFOR(i, 0, 20)
m_UnifontMul[i].Unload();
m_VerdataMul.Unload();
}
//----------------------------------------------------------------------------------<commit_msg>Выключил ммапинг AnimationFrame из-за нехватки памяти.<commit_after>/***********************************************************************************
**
** FileManager.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "FileManager.h"
#include "../Wisp/WispApplication.h"
CFileManager g_FileManager;
//----------------------------------------------------------------------------------
CFileManager::CFileManager()
: m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0)
{
}
//----------------------------------------------------------------------------------
CFileManager::~CFileManager()
{
}
//----------------------------------------------------------------------------------
bool CFileManager::Load()
{
if (!g_FileManager.UseUOP)
{
if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul")))
return false;
else if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul")))
return false;
else if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul")))
return false;
else if (!m_ArtMul.Load(g_App.FilePath("art.mul")))
return false;
else if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul")))
return false;
else if (!m_SoundMul.Load(g_App.FilePath("sound.mul")))
return false;
}
else
{
if (!m_artLegacyMUL.Load(g_App.FilePath("artLegacyMUL.uop")))
return false;
if (!m_gumpartLegacyMUL.Load(g_App.FilePath("gumpartLegacyMUL.uop")))
return false;
if (!m_soundLegacyMUL.Load(g_App.FilePath("soundLegacyMUL.uop")))
return false;
if (!m_tileart.Load(g_App.FilePath("tileart.uop")))
return false;
if (!m_string_dictionary.Load(g_App.FilePath("string_dictionary.uop")))
return false;
if (!m_MultiCollection.Load(g_App.FilePath("MultiCollection.uop")))
return false;
if (!m_AnimationSequence.Load(g_App.FilePath("AnimationSequence.uop")))
return false;
if (!m_MainMisc.Load(g_App.FilePath("MainMisc.uop")))
return false;
/*IFOR(i, 1, 5)
{
if (!m_AnimationFrame[i].Load(g_App.FilePath("AnimationFrame%i.uop", i)))
return false;
}*/
}
if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx")))
return false;
if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul")))
return false;
else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx")))
return false;
else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx")))
return false;
else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle")))
return false;
else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul")))
return false;
else if (!m_SpeechMul.Load(g_App.FilePath("speech.mul")))
return false;
else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul")))
return false;
else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul")))
return false;
else if (!m_HuesMul.Load(g_App.FilePath("hues.mul")))
return false;
else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul")))
return false;
else if (!m_LightMul.Load(g_App.FilePath("light.mul")))
return false;
else if (!m_MultiMul.Load(g_App.FilePath("multi.mul")))
return false;
else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul")))
return false;
else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul")))
return false;
else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul")))
return false;
else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul")))
return false;
else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul")))
return false;
m_LangcodeIff.Load(g_App.FilePath("Langcode.iff"));
IFOR(i, 0, 6)
{
if (g_FileManager.UseUOP && i > 1 || !g_FileManager.UseUOP && i > 0)
{
if (!m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i)))
return false;
if (!m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i)))
return false;
}
if (g_FileManager.UseUOP)
{
if (!m_MapUOP[i].Load(g_App.FilePath("map%iLegacyMUL.uop", i)))
return false;
if (i == 0 || i == 1 || i == 2 || i == 5)
{
if (!m_MapXUOP[i].Load(g_App.FilePath("map%ixLegacyMUL.uop", i)))
return false;
}
}
else
{
m_MapMul[i].Load(g_App.FilePath("map%i.mul", i));
}
m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i));
m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i));
m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i));
}
IFOR(i, 0, 20)
{
string s;
if (i)
s = g_App.FilePath("unifont%i.mul", i);
else
s = g_App.FilePath("unifont.mul");
if (!m_UnifontMul[i].Load(s))
break;
m_UnicodeFontsCount++;
}
if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul")))
m_UseVerdata = false;
return true;
}
//----------------------------------------------------------------------------------
void CFileManager::Unload()
{
if (!g_FileManager.UseUOP)
{
m_ArtIdx.Unload();
m_GumpIdx.Unload();
m_SoundIdx.Unload();
m_ArtMul.Unload();
m_GumpMul.Unload();
m_SoundMul.Unload();
}
else
{
m_artLegacyMUL.Unload();
m_gumpartLegacyMUL.Unload();
m_soundLegacyMUL.Unload();
m_tileart.Unload();
m_string_dictionary.Unload();
m_MultiCollection.Unload();
m_AnimationSequence.Unload();
m_MainMisc.Unload();
IFOR(i, 1, 5)
{
m_AnimationFrame[i].Unload();
}
}
m_LightIdx.Unload();
m_MultiIdx.Unload();
m_SkillsIdx.Unload();
m_MultiMap.Unload();
m_TextureIdx.Unload();
m_SpeechMul.Unload();
m_AnimdataMul.Unload();
m_HuesMul.Unload();
m_FontsMul.Unload();
m_LightMul.Unload();
m_MultiMul.Unload();
m_PaletteMul.Unload();
m_RadarcolMul.Unload();
m_SkillsMul.Unload();
m_TextureMul.Unload();
m_TiledataMul.Unload();
m_LangcodeIff.Unload();
IFOR(i, 0, 6)
{
m_AnimIdx[i].Unload();
m_AnimMul[i].Unload();
if (g_FileManager.UseUOP)
{
m_MapUOP[i].Unload();
m_MapXUOP[i].Unload();
}
else
m_MapMul[i].Unload();
m_StaticIdx[i].Unload();
m_StaticMul[i].Unload();
m_FacetMul[i].Unload();
}
IFOR(i, 0, 20)
m_UnifontMul[i].Unload();
m_VerdataMul.Unload();
}
//----------------------------------------------------------------------------------<|endoftext|> |
<commit_before>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm_kahan.h"
#include "ghost/tsmttsm_kahan_gen.h"
#include <map>
using namespace std;
static bool operator<(const ghost_tsmttsm_kahan_parameters_t &a, const ghost_tsmttsm_kahan_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,0)) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,0));
}
static map<ghost_tsmttsm_kahan_parameters_t, ghost_tsmttsm_kahan_kernel_t> ghost_tsmttsm_kahan_kernels;
ghost_error_t ghost_tsmttsm_kahan_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror)
{
if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (reduce != GHOST_GEMM_ALL_REDUCE) {
if (printerror) {
ERROR_LOG("Only Allreduce supported currently!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm_kahan(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret;
if ((ret = ghost_tsmttsm_kahan_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) {
return ret;
}
if (ghost_tsmttsm_kahan_kernels.empty()) {
#include "tsmttsm_kahan.def"
}
ghost_tsmttsm_kahan_parameters_t p;
ghost_tsmttsm_kahan_kernel_t kernel = NULL;
p.impl = GHOST_IMPLEMENTATION_PLAIN;
p.dt = x->traits.datatype;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
kernel = ghost_tsmttsm_kahan_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kahan_kernels[p];
}
kernel = ghost_tsmttsm_kahan_kernels[p];
if (!kernel) {
INFO_LOG("Could not find Kahan-TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols);
return GHOST_ERR_INVALID_ARG;
//return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);
}
ret = kernel(x,v,w,alpha,beta,conjv);
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.xcols = p.wcols;
tsmttsm_perfargs.vcols = p.vcols;
tsmttsm_perfargs.vrows = v->context->gnrows;
tsmttsm_perfargs.dt = x->traits.datatype;
ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<commit_msg>fallback to GEMM<commit_after>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm_kahan.h"
#include "ghost/tsmttsm_kahan_gen.h"
#include <map>
using namespace std;
static bool operator<(const ghost_tsmttsm_kahan_parameters_t &a, const ghost_tsmttsm_kahan_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,0)) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,0));
}
static map<ghost_tsmttsm_kahan_parameters_t, ghost_tsmttsm_kahan_kernel_t> ghost_tsmttsm_kahan_kernels;
ghost_error_t ghost_tsmttsm_kahan_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror)
{
if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.location != GHOST_LOCATION_HOST || v->traits.location != GHOST_LOCATION_HOST || w->traits.location != GHOST_LOCATION_HOST) {
if (printerror) {
ERROR_LOG("TSMTTSM only implemented for host densemats!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (reduce != GHOST_GEMM_ALL_REDUCE) {
if (printerror) {
ERROR_LOG("Only Allreduce supported currently!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm_kahan(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret;
if ((ret = ghost_tsmttsm_kahan_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) {
INFO_LOG("TSMTTSM-Kahan cannot be applied. Checking whether (non-Kahan) GEMM is fine!");
if ((ret = ghost_gemm_valid(x,v,"T",w,"N",alpha,beta,reduce,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) {
ERROR_LOG("GEMM cannot be applied!");
return ret;
} else {
return ghost_gemm(x,v,"T",w,"N",alpha,beta,reduce,GHOST_GEMM_NOT_SPECIAL);
}
}
if (ghost_tsmttsm_kahan_kernels.empty()) {
#include "tsmttsm_kahan.def"
}
ghost_tsmttsm_kahan_parameters_t p;
ghost_tsmttsm_kahan_kernel_t kernel = NULL;
p.impl = GHOST_IMPLEMENTATION_PLAIN;
p.dt = x->traits.datatype;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
kernel = ghost_tsmttsm_kahan_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kahan_kernels[p];
}
kernel = ghost_tsmttsm_kahan_kernels[p];
if (!kernel) {
INFO_LOG("Could not find Kahan-TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols);
return GHOST_ERR_INVALID_ARG;
//return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);
}
ret = kernel(x,v,w,alpha,beta,conjv);
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.xcols = p.wcols;
tsmttsm_perfargs.vcols = p.vcols;
tsmttsm_perfargs.vrows = v->context->gnrows;
tsmttsm_perfargs.dt = x->traits.datatype;
ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/////////////////////////////////////////////////////////////////////////
//
// Todo
// . Currently supported by sdl, wxGTK and x11. Check if other guis need mapping.
// . Tables look-up should be optimised.
//
#include "bochs.h"
// Table of bochs "BX_KEY_*" symbols
// the table must be in BX_KEY_* order
char *bx_key_symbol[BX_KEY_NBKEYS] = {
"BX_KEY_CTRL_L", "BX_KEY_SHIFT_L", "BX_KEY_F1",
"BX_KEY_F2", "BX_KEY_F3", "BX_KEY_F4",
"BX_KEY_F5", "BX_KEY_F6", "BX_KEY_F7",
"BX_KEY_F8", "BX_KEY_F9", "BX_KEY_F10",
"BX_KEY_F11", "BX_KEY_F12", "BX_KEY_CTRL_R",
"BX_KEY_SHIFT_R", "BX_KEY_CAPS_LOCK", "BX_KEY_NUM_LOCK",
"BX_KEY_ALT_L", "BX_KEY_ALT_R", "BX_KEY_A",
"BX_KEY_B", "BX_KEY_C", "BX_KEY_D",
"BX_KEY_E", "BX_KEY_F", "BX_KEY_G",
"BX_KEY_H", "BX_KEY_I", "BX_KEY_J",
"BX_KEY_K", "BX_KEY_L", "BX_KEY_M",
"BX_KEY_N", "BX_KEY_O", "BX_KEY_P",
"BX_KEY_Q", "BX_KEY_R", "BX_KEY_S",
"BX_KEY_T", "BX_KEY_U", "BX_KEY_V",
"BX_KEY_W", "BX_KEY_X", "BX_KEY_Y",
"BX_KEY_Z", "BX_KEY_0", "BX_KEY_1",
"BX_KEY_2", "BX_KEY_3", "BX_KEY_4",
"BX_KEY_5", "BX_KEY_6", "BX_KEY_7",
"BX_KEY_8", "BX_KEY_9", "BX_KEY_ESC",
"BX_KEY_SPACE", "BX_KEY_SINGLE_QUOTE", "BX_KEY_COMMA",
"BX_KEY_PERIOD", "BX_KEY_SLASH", "BX_KEY_SEMICOLON",
"BX_KEY_EQUALS", "BX_KEY_LEFT_BRACKET", "BX_KEY_BACKSLASH",
"BX_KEY_RIGHT_BRACKET", "BX_KEY_MINUS", "BX_KEY_GRAVE",
"BX_KEY_BACKSPACE", "BX_KEY_ENTER", "BX_KEY_TAB",
"BX_KEY_LEFT_BACKSLASH", "BX_KEY_PRINT", "BX_KEY_SCRL_LOCK",
"BX_KEY_PAUSE", "BX_KEY_INSERT", "BX_KEY_DELETE",
"BX_KEY_HOME", "BX_KEY_END", "BX_KEY_PAGE_UP",
"BX_KEY_PAGE_DOWN", "BX_KEY_KP_ADD", "BX_KEY_KP_SUBTRACT",
"BX_KEY_KP_END", "BX_KEY_KP_DOWN", "BX_KEY_KP_PAGE_DOWN",
"BX_KEY_KP_LEFT", "BX_KEY_KP_RIGHT", "BX_KEY_KP_HOME",
"BX_KEY_KP_UP", "BX_KEY_KP_PAGE_UP", "BX_KEY_KP_INSERT",
"BX_KEY_KP_DELETE", "BX_KEY_KP_5", "BX_KEY_UP",
"BX_KEY_DOWN", "BX_KEY_LEFT", "BX_KEY_RIGHT",
"BX_KEY_KP_ENTER", "BX_KEY_KP_MULTIPLY", "BX_KEY_KP_DIVIDE",
"BX_KEY_WIN_L", "BX_KEY_WIN_R", "BX_KEY_MENU",
"BX_KEY_ALT_SYSREQ", "BX_KEY_CTRL_BREAK", "BX_KEY_INT_BACK",
"BX_KEY_INT_FORWARD", "BX_KEY_INT_STOP", "BX_KEY_INT_MAIL",
"BX_KEY_INT_SEARCH", "BX_KEY_INT_FAV", "BX_KEY_INT_HOME",
"BX_KEY_POWER_MYCOMP", "BX_KEY_POWER_CALC", "BX_KEY_POWER_SLEEP",
"BX_KEY_POWER_POWER", "BX_KEY_POWER_WAKE",
};
bx_keymap_c bx_keymap;
#define LOG_THIS bx_keymap.
bx_keymap_c::bx_keymap_c(void)
{
put("KMAP");
keymapCount = 0;
keymapTable = (BXKeyEntry *)NULL;
}
bx_keymap_c::~bx_keymap_c(void)
{
if(keymapTable != NULL) {
free(keymapTable);
keymapTable = (BXKeyEntry *)NULL;
}
keymapCount = 0;
}
void
bx_keymap_c::loadKeymap(Bit32u stringToSymbol(const char*))
{
if(bx_options.keyboard.OuseMapping->get()) {
loadKeymap(stringToSymbol,bx_options.keyboard.Okeymap->getptr());
}
}
bx_bool
bx_keymap_c::isKeymapLoaded ()
{
return (keymapCount > 0);
}
///////////////////
// I'll add these to the keymap object in a minute.
static unsigned char *lineptr = NULL;
static int lineCount;
static void
init_parse ()
{
lineCount = 0;
}
static void
init_parse_line (char *line_to_parse)
{
// chop off newline
lineptr = (unsigned char *)line_to_parse;
char *nl;
if( (nl = strchr(line_to_parse,'\n')) != NULL) {
*nl = 0;
}
}
static Bit32s
get_next_word (char *output)
{
char *copyp = output;
// find first nonspace
while (*lineptr && isspace (*lineptr))
lineptr++;
if (!*lineptr)
return -1; // nothing but spaces until end of line
if (*lineptr == '#')
return -1; // nothing but a comment
// copy nonspaces into the output
while (*lineptr && !isspace (*lineptr))
*copyp++ = *lineptr++;
*copyp=0; // null terminate the copy
// there must be at least one nonspace, since that's why we stopped the
// first loop!
BX_ASSERT (copyp != output);
return 0;
}
static Bit32s
get_next_keymap_line (FILE *fp, char *bxsym, char *modsym, Bit32s *ascii, char *hostsym)
{
char line[256];
char buf[256];
line[0] = 0;
while (1) {
lineCount++;
if (!fgets(line, sizeof(line)-1, fp)) return -1; // EOF
init_parse_line (line);
if (get_next_word (bxsym) >= 0) {
modsym[0] = 0;
char *p;
if ((p = strchr (bxsym, '+')) != NULL) {
*p = 0; // truncate bxsym.
p++; // move one char beyond the +
strcpy (modsym, p); // copy the rest to modsym
}
if (get_next_word (buf) < 0) {
BX_PANIC (("keymap line %d: expected 3 columns", lineCount));
return -1;
}
if (buf[0] == '\'' && buf[2] == '\'' && buf[3]==0) {
*ascii = (Bit8u) buf[1];
} else if (!strcmp(buf, "space")) {
*ascii = ' ';
} else if (!strcmp(buf, "return")) {
*ascii = '\n';
} else if (!strcmp(buf, "tab")) {
*ascii = '\t';
} else if (!strcmp(buf, "backslash")) {
*ascii = '\\';
} else if (!strcmp(buf, "apostrophe")) {
*ascii = '\'';
} else if (!strcmp(buf, "none")) {
*ascii = -1;
} else {
BX_PANIC (("keymap line %d: ascii equivalent is \"%s\" but it must be char constant like 'x', or one of space,tab,return,none", lineCount, buf));
}
if (get_next_word (hostsym) < 0) {
BX_PANIC (("keymap line %d: expected 3 columns", lineCount));
return -1;
}
return 0;
}
// no words on this line, keep reading.
}
}
void
bx_keymap_c::loadKeymap(Bit32u stringToSymbol(const char*), const char* filename)
{
FILE *keymapFile;
char baseSym[256], modSym[256], hostSym[256];
Bit32s ascii;
Bit32u baseKey, modKey, hostKey;
struct stat status;
if (stat(filename, &status)) {
BX_PANIC(("Can not stat keymap file '%s'.",filename));
}
if (!(S_ISREG(status.st_mode))) {
BX_PANIC(("Keymap file '%s' is not a file",filename));
}
if((keymapFile = fopen(filename,"r"))==NULL) {
BX_PANIC(("Can not open keymap file '%s'.",filename));
}
BX_INFO(("Loading keymap from '%s'",filename));
init_parse ();
// Read keymap file one line at a time
while(1) {
if (get_next_keymap_line (keymapFile,
baseSym, modSym, &ascii, hostSym) < 0) { break; }
// convert X_KEY_* symbols to values
baseKey = convertStringToBXKey(baseSym);
modKey = convertStringToBXKey(modSym);
hostKey = 0;
if (stringToSymbol != NULL)
hostKey = stringToSymbol(hostSym);
BX_DEBUG (("baseKey='%s' (%d), modSym='%s' (%d), ascii=%d, guisym='%s' (%d)", baseSym, baseKey, modSym, modKey, ascii, hostSym, hostKey));
// Check if data is valid
if( baseKey==BX_KEYMAP_UNKNOWN ) {
BX_PANIC (("line %d: unknown BX_KEY constant '%s'",lineCount,baseSym));
continue;
}
if( hostKey==BX_KEYMAP_UNKNOWN ) {
BX_PANIC (("line %d: unknown host key name '%s'",lineCount,hostSym));
continue;
}
keymapTable=(BXKeyEntry*)realloc(keymapTable,(keymapCount+1) * sizeof(BXKeyEntry));
if(keymapTable==NULL)
BX_PANIC(("Can not allocate memory for keymap table."));
keymapTable[keymapCount].baseKey=baseKey;
keymapTable[keymapCount].modKey=modKey;
keymapTable[keymapCount].ascii=ascii;
keymapTable[keymapCount].hostKey=hostKey;
keymapCount++;
}
BX_INFO(("Loaded %d symbols",keymapCount));
fclose(keymapFile);
}
Bit32u
bx_keymap_c::convertStringToBXKey(const char* string)
{
Bit16u i;
// We look through the bx_key_symbol table to find the searched string
for (i=0; i<BX_KEY_NBKEYS; i++) {
if (strcmp(string,bx_key_symbol[i])==0) {
return i;
}
}
// Key is not known
return BX_KEYMAP_UNKNOWN;
}
BXKeyEntry *
bx_keymap_c::findHostKey(Bit32u key)
{
Bit16u i;
// We look through the keymap table to find the searched key
for (i=0; i<keymapCount; i++) {
if (keymapTable[i].hostKey == key) {
BX_DEBUG (("key 0x%02x matches hostKey for entry #%d", key, i));
return &keymapTable[i];
}
}
BX_DEBUG (("key %02x matches no entries", key));
// Return default
return NULL;
}
BXKeyEntry *
bx_keymap_c::findAsciiChar(Bit8u ch)
{
Bit16u i;
BX_DEBUG (("findAsciiChar (0x%02x)", ch));
// We look through the keymap table to find the searched key
for (i=0; i<keymapCount; i++) {
if (keymapTable[i].ascii == ch) {
BX_DEBUG (("key %02x matches ascii for entry #%d", ch, i));
return &keymapTable[i];
}
}
BX_DEBUG (("key 0x%02x matches no entries", ch));
// Return default
return NULL;
}
char *
bx_keymap_c::getBXKeyName(Bit32u key)
{
return bx_key_symbol[key & 0x7fffffff];
}
<commit_msg>- panic message for unknown key symbols improved<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/////////////////////////////////////////////////////////////////////////
//
// Todo
// . Currently supported by sdl, wxGTK and x11. Check if other guis need mapping.
// . Tables look-up should be optimised.
//
#include "bochs.h"
// Table of bochs "BX_KEY_*" symbols
// the table must be in BX_KEY_* order
char *bx_key_symbol[BX_KEY_NBKEYS] = {
"BX_KEY_CTRL_L", "BX_KEY_SHIFT_L", "BX_KEY_F1",
"BX_KEY_F2", "BX_KEY_F3", "BX_KEY_F4",
"BX_KEY_F5", "BX_KEY_F6", "BX_KEY_F7",
"BX_KEY_F8", "BX_KEY_F9", "BX_KEY_F10",
"BX_KEY_F11", "BX_KEY_F12", "BX_KEY_CTRL_R",
"BX_KEY_SHIFT_R", "BX_KEY_CAPS_LOCK", "BX_KEY_NUM_LOCK",
"BX_KEY_ALT_L", "BX_KEY_ALT_R", "BX_KEY_A",
"BX_KEY_B", "BX_KEY_C", "BX_KEY_D",
"BX_KEY_E", "BX_KEY_F", "BX_KEY_G",
"BX_KEY_H", "BX_KEY_I", "BX_KEY_J",
"BX_KEY_K", "BX_KEY_L", "BX_KEY_M",
"BX_KEY_N", "BX_KEY_O", "BX_KEY_P",
"BX_KEY_Q", "BX_KEY_R", "BX_KEY_S",
"BX_KEY_T", "BX_KEY_U", "BX_KEY_V",
"BX_KEY_W", "BX_KEY_X", "BX_KEY_Y",
"BX_KEY_Z", "BX_KEY_0", "BX_KEY_1",
"BX_KEY_2", "BX_KEY_3", "BX_KEY_4",
"BX_KEY_5", "BX_KEY_6", "BX_KEY_7",
"BX_KEY_8", "BX_KEY_9", "BX_KEY_ESC",
"BX_KEY_SPACE", "BX_KEY_SINGLE_QUOTE", "BX_KEY_COMMA",
"BX_KEY_PERIOD", "BX_KEY_SLASH", "BX_KEY_SEMICOLON",
"BX_KEY_EQUALS", "BX_KEY_LEFT_BRACKET", "BX_KEY_BACKSLASH",
"BX_KEY_RIGHT_BRACKET", "BX_KEY_MINUS", "BX_KEY_GRAVE",
"BX_KEY_BACKSPACE", "BX_KEY_ENTER", "BX_KEY_TAB",
"BX_KEY_LEFT_BACKSLASH", "BX_KEY_PRINT", "BX_KEY_SCRL_LOCK",
"BX_KEY_PAUSE", "BX_KEY_INSERT", "BX_KEY_DELETE",
"BX_KEY_HOME", "BX_KEY_END", "BX_KEY_PAGE_UP",
"BX_KEY_PAGE_DOWN", "BX_KEY_KP_ADD", "BX_KEY_KP_SUBTRACT",
"BX_KEY_KP_END", "BX_KEY_KP_DOWN", "BX_KEY_KP_PAGE_DOWN",
"BX_KEY_KP_LEFT", "BX_KEY_KP_RIGHT", "BX_KEY_KP_HOME",
"BX_KEY_KP_UP", "BX_KEY_KP_PAGE_UP", "BX_KEY_KP_INSERT",
"BX_KEY_KP_DELETE", "BX_KEY_KP_5", "BX_KEY_UP",
"BX_KEY_DOWN", "BX_KEY_LEFT", "BX_KEY_RIGHT",
"BX_KEY_KP_ENTER", "BX_KEY_KP_MULTIPLY", "BX_KEY_KP_DIVIDE",
"BX_KEY_WIN_L", "BX_KEY_WIN_R", "BX_KEY_MENU",
"BX_KEY_ALT_SYSREQ", "BX_KEY_CTRL_BREAK", "BX_KEY_INT_BACK",
"BX_KEY_INT_FORWARD", "BX_KEY_INT_STOP", "BX_KEY_INT_MAIL",
"BX_KEY_INT_SEARCH", "BX_KEY_INT_FAV", "BX_KEY_INT_HOME",
"BX_KEY_POWER_MYCOMP", "BX_KEY_POWER_CALC", "BX_KEY_POWER_SLEEP",
"BX_KEY_POWER_POWER", "BX_KEY_POWER_WAKE",
};
bx_keymap_c bx_keymap;
#define LOG_THIS bx_keymap.
bx_keymap_c::bx_keymap_c(void)
{
put("KMAP");
keymapCount = 0;
keymapTable = (BXKeyEntry *)NULL;
}
bx_keymap_c::~bx_keymap_c(void)
{
if(keymapTable != NULL) {
free(keymapTable);
keymapTable = (BXKeyEntry *)NULL;
}
keymapCount = 0;
}
void
bx_keymap_c::loadKeymap(Bit32u stringToSymbol(const char*))
{
if(bx_options.keyboard.OuseMapping->get()) {
loadKeymap(stringToSymbol,bx_options.keyboard.Okeymap->getptr());
}
}
bx_bool
bx_keymap_c::isKeymapLoaded ()
{
return (keymapCount > 0);
}
///////////////////
// I'll add these to the keymap object in a minute.
static unsigned char *lineptr = NULL;
static int lineCount;
static void
init_parse ()
{
lineCount = 0;
}
static void
init_parse_line (char *line_to_parse)
{
// chop off newline
lineptr = (unsigned char *)line_to_parse;
char *nl;
if( (nl = strchr(line_to_parse,'\n')) != NULL) {
*nl = 0;
}
}
static Bit32s
get_next_word (char *output)
{
char *copyp = output;
// find first nonspace
while (*lineptr && isspace (*lineptr))
lineptr++;
if (!*lineptr)
return -1; // nothing but spaces until end of line
if (*lineptr == '#')
return -1; // nothing but a comment
// copy nonspaces into the output
while (*lineptr && !isspace (*lineptr))
*copyp++ = *lineptr++;
*copyp=0; // null terminate the copy
// there must be at least one nonspace, since that's why we stopped the
// first loop!
BX_ASSERT (copyp != output);
return 0;
}
static Bit32s
get_next_keymap_line (FILE *fp, char *bxsym, char *modsym, Bit32s *ascii, char *hostsym)
{
char line[256];
char buf[256];
line[0] = 0;
while (1) {
lineCount++;
if (!fgets(line, sizeof(line)-1, fp)) return -1; // EOF
init_parse_line (line);
if (get_next_word (bxsym) >= 0) {
modsym[0] = 0;
char *p;
if ((p = strchr (bxsym, '+')) != NULL) {
*p = 0; // truncate bxsym.
p++; // move one char beyond the +
strcpy (modsym, p); // copy the rest to modsym
}
if (get_next_word (buf) < 0) {
BX_PANIC (("keymap line %d: expected 3 columns", lineCount));
return -1;
}
if (buf[0] == '\'' && buf[2] == '\'' && buf[3]==0) {
*ascii = (Bit8u) buf[1];
} else if (!strcmp(buf, "space")) {
*ascii = ' ';
} else if (!strcmp(buf, "return")) {
*ascii = '\n';
} else if (!strcmp(buf, "tab")) {
*ascii = '\t';
} else if (!strcmp(buf, "backslash")) {
*ascii = '\\';
} else if (!strcmp(buf, "apostrophe")) {
*ascii = '\'';
} else if (!strcmp(buf, "none")) {
*ascii = -1;
} else {
BX_PANIC (("keymap line %d: ascii equivalent is \"%s\" but it must be char constant like 'x', or one of space,tab,return,none", lineCount, buf));
}
if (get_next_word (hostsym) < 0) {
BX_PANIC (("keymap line %d: expected 3 columns", lineCount));
return -1;
}
return 0;
}
// no words on this line, keep reading.
}
}
void
bx_keymap_c::loadKeymap(Bit32u stringToSymbol(const char*), const char* filename)
{
FILE *keymapFile;
char baseSym[256], modSym[256], hostSym[256];
Bit32s ascii;
Bit32u baseKey, modKey, hostKey;
struct stat status;
if (stat(filename, &status)) {
BX_PANIC(("Can not stat keymap file '%s'.",filename));
}
if (!(S_ISREG(status.st_mode))) {
BX_PANIC(("Keymap file '%s' is not a file",filename));
}
if((keymapFile = fopen(filename,"r"))==NULL) {
BX_PANIC(("Can not open keymap file '%s'.",filename));
}
BX_INFO(("Loading keymap from '%s'",filename));
init_parse ();
// Read keymap file one line at a time
while(1) {
if (get_next_keymap_line (keymapFile,
baseSym, modSym, &ascii, hostSym) < 0) { break; }
// convert X_KEY_* symbols to values
baseKey = convertStringToBXKey(baseSym);
modKey = convertStringToBXKey(modSym);
hostKey = 0;
if (stringToSymbol != NULL)
hostKey = stringToSymbol(hostSym);
BX_DEBUG (("baseKey='%s' (%d), modSym='%s' (%d), ascii=%d, guisym='%s' (%d)", baseSym, baseKey, modSym, modKey, ascii, hostSym, hostKey));
// Check if data is valid
if( baseKey==BX_KEYMAP_UNKNOWN ) {
BX_PANIC (("line %d: unknown BX_KEY constant '%s'",lineCount,baseSym));
continue;
}
if( hostKey==BX_KEYMAP_UNKNOWN ) {
BX_PANIC (("line %d: unknown host key name '%s' (wrong keymap ?)",lineCount,hostSym));
continue;
}
keymapTable=(BXKeyEntry*)realloc(keymapTable,(keymapCount+1) * sizeof(BXKeyEntry));
if(keymapTable==NULL)
BX_PANIC(("Can not allocate memory for keymap table."));
keymapTable[keymapCount].baseKey=baseKey;
keymapTable[keymapCount].modKey=modKey;
keymapTable[keymapCount].ascii=ascii;
keymapTable[keymapCount].hostKey=hostKey;
keymapCount++;
}
BX_INFO(("Loaded %d symbols",keymapCount));
fclose(keymapFile);
}
Bit32u
bx_keymap_c::convertStringToBXKey(const char* string)
{
Bit16u i;
// We look through the bx_key_symbol table to find the searched string
for (i=0; i<BX_KEY_NBKEYS; i++) {
if (strcmp(string,bx_key_symbol[i])==0) {
return i;
}
}
// Key is not known
return BX_KEYMAP_UNKNOWN;
}
BXKeyEntry *
bx_keymap_c::findHostKey(Bit32u key)
{
Bit16u i;
// We look through the keymap table to find the searched key
for (i=0; i<keymapCount; i++) {
if (keymapTable[i].hostKey == key) {
BX_DEBUG (("key 0x%02x matches hostKey for entry #%d", key, i));
return &keymapTable[i];
}
}
BX_DEBUG (("key %02x matches no entries", key));
// Return default
return NULL;
}
BXKeyEntry *
bx_keymap_c::findAsciiChar(Bit8u ch)
{
Bit16u i;
BX_DEBUG (("findAsciiChar (0x%02x)", ch));
// We look through the keymap table to find the searched key
for (i=0; i<keymapCount; i++) {
if (keymapTable[i].ascii == ch) {
BX_DEBUG (("key %02x matches ascii for entry #%d", ch, i));
return &keymapTable[i];
}
}
BX_DEBUG (("key 0x%02x matches no entries", ch));
// Return default
return NULL;
}
char *
bx_keymap_c::getBXKeyName(Bit32u key)
{
return bx_key_symbol[key & 0x7fffffff];
}
<|endoftext|> |
<commit_before>#include <enumerate.hpp>
#include "test_helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include <utility>
#include <sstream>
namespace Catch {
template <typename A, typename B>
std::string toString( const std::pair<A, B>& p) {
std::ostringstream oss;
oss << '{' << p.first << ", " << p.second << '}';
return oss.str();
}
}
#include "catch.hpp"
using Vec = std::vector<std::pair<std::size_t, char>>;
using iter::enumerate;
using itertest::BasicIterable;
using itertest::SolidInt;
TEST_CASE("Basic Function", "[enumerate]") {
std::string str = "abc";
auto e = enumerate(str);
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'a'}, {1, 'b'}, {2, 'c'}};
REQUIRE( v == vc );
}
TEST_CASE("Empty", "[enumerate]") {
std::string emp{};
auto e = enumerate(emp);
Vec v(std::begin(e), std::end(e));
REQUIRE( v.empty() );
}
TEST_CASE("Modifications through enumerate affect container", "[enumerate]") {
std::vector<int> v{1, 2, 3, 4};
std::vector<int> vc(v.size(), -1);
for (auto&& p : enumerate(v)){
p.second = -1;
}
REQUIRE( v == vc );
}
TEST_CASE("Static array works", "[enumerate]") {
char arr[] = {'w', 'x', 'y'};
SECTION("Conversion to vector") {
auto e = enumerate(arr);
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'w'}, {1, 'x'}, {2, 'y'}};
REQUIRE( v == vc );
}
SECTION("Modification through enumerate") {
for (auto&& p : enumerate(arr)) {
p.second = 'z';
}
std::vector<char> v(std::begin(arr), std::end(arr));
decltype(v) vc(v.size(), 'z');
REQUIRE( v == vc );
}
}
TEST_CASE("initializer_list works", "[enumerate]") {
auto e = enumerate({'a', 'b', 'c'});
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'a'}, {1, 'b'}, {2, 'c'}};
REQUIRE( v == vc );
}
TEST_CASE("binds reference when it should", "[enumerate]") {
BasicIterable<char> bi{'x', 'y', 'z'};
auto e = enumerate(bi);
(void)e;
REQUIRE_FALSE( bi.was_moved_from() );
}
TEST_CASE("moves rvalues into enumerable object", "[enumerate]") {
BasicIterable<char> bi{'x', 'y', 'z'};
auto e = enumerate(std::move(bi));
REQUIRE( bi.was_moved_from());
(void)e;
}
TEST_CASE("Doesn't move or copy elements of iterable", "[enumerate]") {
constexpr SolidInt arr[] = {6, 7, 8};
for (auto&& i : enumerate(arr)) {
(void)i;
}
}
<commit_msg>adds enumerate test with const sequence<commit_after>#include <enumerate.hpp>
#include "test_helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include <utility>
#include <sstream>
namespace Catch {
template <typename A, typename B>
std::string toString( const std::pair<A, B>& p) {
std::ostringstream oss;
oss << '{' << p.first << ", " << p.second << '}';
return oss.str();
}
}
#include "catch.hpp"
using Vec = std::vector<std::pair<std::size_t, char>>;
using iter::enumerate;
using itertest::BasicIterable;
using itertest::SolidInt;
TEST_CASE("Basic Function", "[enumerate]") {
std::string str = "abc";
auto e = enumerate(str);
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'a'}, {1, 'b'}, {2, 'c'}};
REQUIRE( v == vc );
}
TEST_CASE("Empty", "[enumerate]") {
std::string emp{};
auto e = enumerate(emp);
Vec v(std::begin(e), std::end(e));
REQUIRE( v.empty() );
}
TEST_CASE("Modifications through enumerate affect container", "[enumerate]") {
std::vector<int> v{1, 2, 3, 4};
std::vector<int> vc(v.size(), -1);
for (auto&& p : enumerate(v)){
p.second = -1;
}
REQUIRE( v == vc );
}
TEST_CASE("Static array works", "[enumerate]") {
char arr[] = {'w', 'x', 'y'};
SECTION("Conversion to vector") {
auto e = enumerate(arr);
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'w'}, {1, 'x'}, {2, 'y'}};
REQUIRE( v == vc );
}
SECTION("Modification through enumerate") {
for (auto&& p : enumerate(arr)) {
p.second = 'z';
}
std::vector<char> v(std::begin(arr), std::end(arr));
decltype(v) vc(v.size(), 'z');
REQUIRE( v == vc );
}
}
TEST_CASE("initializer_list works", "[enumerate]") {
auto e = enumerate({'a', 'b', 'c'});
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'a'}, {1, 'b'}, {2, 'c'}};
REQUIRE( v == vc );
}
TEST_CASE("binds reference when it should", "[enumerate]") {
BasicIterable<char> bi{'x', 'y', 'z'};
auto e = enumerate(bi);
(void)e;
REQUIRE_FALSE( bi.was_moved_from() );
}
TEST_CASE("moves rvalues into enumerable object", "[enumerate]") {
BasicIterable<char> bi{'x', 'y', 'z'};
auto e = enumerate(std::move(bi));
REQUIRE( bi.was_moved_from());
(void)e;
}
TEST_CASE("Works with const iterable", "[enumerate]") {
const std::string s{"ace"};
auto e = enumerate(s);
Vec v(std::begin(e), std::end(e));
Vec vc{{0, 'a'}, {1, 'c'}, {2, 'e'}};
REQUIRE( v == vc );
}
TEST_CASE("Doesn't move or copy elements of iterable", "[enumerate]") {
constexpr SolidInt arr[] = {6, 7, 8};
for (auto&& i : enumerate(arr)) {
(void)i;
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of the LibreOffice project.
*
* Based on LLVM/Clang.
*
* This file is distributed under the University of Illinois Open Source
* License. See LICENSE.TXT for details.
*
*/
#include "pluginhandler.hxx"
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/Lex/PPCallbacks.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
/*
This source file manages all plugin actions. It is not necessary to modify this
file when adding new actions.
*/
namespace loplugin
{
struct PluginData
{
Plugin* (*create)( CompilerInstance&, Rewriter& );
Plugin* object;
const char* optionName;
bool isRewriter;
};
const int MAX_PLUGINS = 100;
static PluginData plugins[ MAX_PLUGINS ];
static int pluginCount = 0;
static bool pluginObjectsCreated = false;
PluginHandler::PluginHandler( CompilerInstance& compiler, const vector< string >& args )
: compiler( compiler )
, rewriter( compiler.getSourceManager(), compiler.getLangOpts())
, scope( "mainfile" )
{
bool wasPlugin = false;
for( vector< string >::const_iterator it = args.begin();
it != args.end();
++it )
{
if( it->size() >= 2 && (*it)[ 0 ] == '-' && (*it)[ 1 ] == '-' )
handleOption( it->substr( 2 ));
else
{
createPlugin( *it );
wasPlugin = true;
}
}
if( !wasPlugin )
createPlugin( "" ); // = all non-rewriters
pluginObjectsCreated = true;
}
PluginHandler::~PluginHandler()
{
for( int i = 0;
i < pluginCount;
++i )
if( plugins[ i ].object != NULL )
{
// PPCallbacks is owned by preprocessor object, don't delete those
if( dynamic_cast< PPCallbacks* >( plugins[ i ].object ) == NULL )
delete plugins[ i ].object;
}
}
void PluginHandler::handleOption( const string& option )
{
if( option.substr( 0, 6 ) == "scope=" )
{
scope = option.substr( 6 );
if( scope == "mainfile" || scope == "all" )
; // ok
else
{
struct stat st;
if( stat(( SRCDIR "/" + scope ).c_str(), &st ) != 0 || !S_ISDIR( st.st_mode ))
report( DiagnosticsEngine::Fatal, "unknown scope %0 (no such module directory)" ) << scope;
}
}
else
report( DiagnosticsEngine::Fatal, "unknown option %0" ) << option;
}
void PluginHandler::createPlugin( const string& name )
{
for( int i = 0;
i < pluginCount;
++i )
{
if( name.empty()) // no plugin given -> create non-writer plugins
{
if( !plugins[ i ].isRewriter )
plugins[ i ].object = plugins[ i ].create( compiler, rewriter );
}
else if( plugins[ i ].optionName == name )
{
plugins[ i ].object = plugins[ i ].create( compiler, rewriter );
return;
}
}
if( !name.empty())
report( DiagnosticsEngine::Fatal, "unknown plugin tool %0" ) << name;
}
void PluginHandler::registerPlugin( Plugin* (*create)( CompilerInstance&, Rewriter& ), const char* optionName, bool isRewriter )
{
assert( !pluginObjectsCreated );
assert( pluginCount < MAX_PLUGINS );
plugins[ pluginCount ].create = create;
plugins[ pluginCount ].object = NULL;
plugins[ pluginCount ].optionName = optionName;
plugins[ pluginCount ].isRewriter = isRewriter;
++pluginCount;
}
DiagnosticBuilder PluginHandler::report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc )
{
return Plugin::report( level, message, compiler, loc );
}
void PluginHandler::HandleTranslationUnit( ASTContext& context )
{
if( context.getDiagnostics().hasErrorOccurred())
return;
for( int i = 0;
i < pluginCount;
++i )
{
if( plugins[ i ].object != NULL )
plugins[ i ].object->run();
}
for( Rewriter::buffer_iterator it = rewriter.buffer_begin();
it != rewriter.buffer_end();
++it )
{
const FileEntry* e = context.getSourceManager().getFileEntryForID( it->first );
/* Check where the file actually is, and warn about cases where modification
most probably doesn't matter (generated files in workdir).
The order here is important, as OUTDIR and WORKDIR are often in SRCDIR/BUILDDIR,
and BUILDDIR is sometimes in SRCDIR. */
string modifyFile;
const char* pathWarning = NULL;
bool skip = false;
if( strncmp( e->getName(), OUTDIR "/", strlen( OUTDIR "/" )) == 0 )
{
/* Try to find a matching file for a file in solver/ (include files
are usually included from there rather than from the source dir) if possible. */
if( strncmp( e->getName(), OUTDIR "/inc/", strlen( OUTDIR ) + strlen( "/inc/" )) == 0 )
{
string filename( e->getName());
int modulePos = strlen( OUTDIR ) + strlen( "/inc/" );
size_t moduleEnd = filename.find( '/', modulePos );
if( moduleEnd != string::npos )
{
modifyFile = SRCDIR "/" + filename.substr( modulePos, moduleEnd - modulePos )
+ "/inc/" + filename.substr( modulePos );
}
}
if( modifyFile.empty())
pathWarning = "modified source in solver/ : %0";
}
else if( strncmp( e->getName(), WORKDIR "/", strlen( WORKDIR "/" )) == 0 )
pathWarning = "modified source in workdir/ : %0";
else if( strcmp( SRCDIR, BUILDDIR ) != 0 && strncmp( e->getName(), BUILDDIR "/", strlen( BUILDDIR "/" )) == 0 )
pathWarning = "modified source in build dir : %0";
else if( strncmp( e->getName(), SRCDIR "/", strlen( SRCDIR "/" )) == 0 )
; // ok
else
{
pathWarning = "modified source in unknown location, not modifying : %0";
skip = true;
}
if( modifyFile.empty())
modifyFile = e->getName();
// Check whether the modified file is in the wanted scope (done after path checking above), so
// that files mapped from OUTDIR to SRCDIR are included.
if( scope == "mainfile" )
{
if( it->first != context.getSourceManager().getMainFileID())
continue;
}
else if( scope == "all" )
; // ok
else // scope is module
{
if( strncmp( modifyFile.c_str(), ( SRCDIR "/" + scope + "/" ).c_str(), ( SRCDIR "/" + scope + "/" ).size()) != 0 )
continue;
}
// Warn only now, so that files not in scope do not cause warnings.
if( pathWarning != NULL )
report( DiagnosticsEngine::Warning, pathWarning ) << e->getName();
if( skip )
continue;
char* filename = new char[ modifyFile.length() + 100 ];
sprintf( filename, "%s.new.%d", modifyFile.c_str(), getpid());
string error;
bool ok = false;
raw_fd_ostream ostream( filename, error );
if( error.empty())
{
it->second.write( ostream );
ostream.close();
if( !ostream.has_error() && rename( filename, modifyFile.c_str()) == 0 )
ok = true;
}
ostream.clear_error();
unlink( filename );
if( !ok )
report( DiagnosticsEngine::Error, "cannot write modified source to %0 (%1)" ) << modifyFile << error;
delete[] filename;
}
}
ASTConsumer* LibreOfficeAction::CreateASTConsumer( CompilerInstance& Compiler, StringRef )
{
return new PluginHandler( Compiler, _args );
}
bool LibreOfficeAction::ParseArgs( const CompilerInstance&, const vector< string >& args )
{
_args = args;
return true;
}
static FrontendPluginRegistry::Add< loplugin::LibreOfficeAction > X( "loplugin", "LibreOffice compile check plugin" );
} // namespace
<commit_msg>Adapt UPDATE_FILES=<module> to headers being moved to include/<commit_after>/*
* This file is part of the LibreOffice project.
*
* Based on LLVM/Clang.
*
* This file is distributed under the University of Illinois Open Source
* License. See LICENSE.TXT for details.
*
*/
#include "pluginhandler.hxx"
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/Lex/PPCallbacks.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
/*
This source file manages all plugin actions. It is not necessary to modify this
file when adding new actions.
*/
namespace
{
bool isPrefix( const string& prefix, const string& full)
{
return full.compare(0, prefix.size(), prefix) == 0;
}
}
namespace loplugin
{
struct PluginData
{
Plugin* (*create)( CompilerInstance&, Rewriter& );
Plugin* object;
const char* optionName;
bool isRewriter;
};
const int MAX_PLUGINS = 100;
static PluginData plugins[ MAX_PLUGINS ];
static int pluginCount = 0;
static bool pluginObjectsCreated = false;
PluginHandler::PluginHandler( CompilerInstance& compiler, const vector< string >& args )
: compiler( compiler )
, rewriter( compiler.getSourceManager(), compiler.getLangOpts())
, scope( "mainfile" )
{
bool wasPlugin = false;
for( vector< string >::const_iterator it = args.begin();
it != args.end();
++it )
{
if( it->size() >= 2 && (*it)[ 0 ] == '-' && (*it)[ 1 ] == '-' )
handleOption( it->substr( 2 ));
else
{
createPlugin( *it );
wasPlugin = true;
}
}
if( !wasPlugin )
createPlugin( "" ); // = all non-rewriters
pluginObjectsCreated = true;
}
PluginHandler::~PluginHandler()
{
for( int i = 0;
i < pluginCount;
++i )
if( plugins[ i ].object != NULL )
{
// PPCallbacks is owned by preprocessor object, don't delete those
if( dynamic_cast< PPCallbacks* >( plugins[ i ].object ) == NULL )
delete plugins[ i ].object;
}
}
void PluginHandler::handleOption( const string& option )
{
if( option.substr( 0, 6 ) == "scope=" )
{
scope = option.substr( 6 );
if( scope == "mainfile" || scope == "all" )
; // ok
else
{
struct stat st;
if( stat(( SRCDIR "/" + scope ).c_str(), &st ) != 0 || !S_ISDIR( st.st_mode ))
report( DiagnosticsEngine::Fatal, "unknown scope %0 (no such module directory)" ) << scope;
}
}
else
report( DiagnosticsEngine::Fatal, "unknown option %0" ) << option;
}
void PluginHandler::createPlugin( const string& name )
{
for( int i = 0;
i < pluginCount;
++i )
{
if( name.empty()) // no plugin given -> create non-writer plugins
{
if( !plugins[ i ].isRewriter )
plugins[ i ].object = plugins[ i ].create( compiler, rewriter );
}
else if( plugins[ i ].optionName == name )
{
plugins[ i ].object = plugins[ i ].create( compiler, rewriter );
return;
}
}
if( !name.empty())
report( DiagnosticsEngine::Fatal, "unknown plugin tool %0" ) << name;
}
void PluginHandler::registerPlugin( Plugin* (*create)( CompilerInstance&, Rewriter& ), const char* optionName, bool isRewriter )
{
assert( !pluginObjectsCreated );
assert( pluginCount < MAX_PLUGINS );
plugins[ pluginCount ].create = create;
plugins[ pluginCount ].object = NULL;
plugins[ pluginCount ].optionName = optionName;
plugins[ pluginCount ].isRewriter = isRewriter;
++pluginCount;
}
DiagnosticBuilder PluginHandler::report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc )
{
return Plugin::report( level, message, compiler, loc );
}
void PluginHandler::HandleTranslationUnit( ASTContext& context )
{
if( context.getDiagnostics().hasErrorOccurred())
return;
for( int i = 0;
i < pluginCount;
++i )
{
if( plugins[ i ].object != NULL )
plugins[ i ].object->run();
}
for( Rewriter::buffer_iterator it = rewriter.buffer_begin();
it != rewriter.buffer_end();
++it )
{
const FileEntry* e = context.getSourceManager().getFileEntryForID( it->first );
/* Check where the file actually is, and warn about cases where modification
most probably doesn't matter (generated files in workdir).
The order here is important, as OUTDIR and WORKDIR are often in SRCDIR/BUILDDIR,
and BUILDDIR is sometimes in SRCDIR. */
string modifyFile;
const char* pathWarning = NULL;
bool skip = false;
if( strncmp( e->getName(), OUTDIR "/", strlen( OUTDIR "/" )) == 0 )
{
/* Try to find a matching file for a file in solver/ (include files
are usually included from there rather than from the source dir) if possible. */
if( strncmp( e->getName(), OUTDIR "/inc/", strlen( OUTDIR ) + strlen( "/inc/" )) == 0 )
{
string filename( e->getName());
int modulePos = strlen( OUTDIR ) + strlen( "/inc/" );
size_t moduleEnd = filename.find( '/', modulePos );
if( moduleEnd != string::npos )
{
modifyFile = SRCDIR "/" + filename.substr( modulePos, moduleEnd - modulePos )
+ "/inc/" + filename.substr( modulePos );
}
}
if( modifyFile.empty())
pathWarning = "modified source in solver/ : %0";
}
else if( strncmp( e->getName(), WORKDIR "/", strlen( WORKDIR "/" )) == 0 )
pathWarning = "modified source in workdir/ : %0";
else if( strcmp( SRCDIR, BUILDDIR ) != 0 && strncmp( e->getName(), BUILDDIR "/", strlen( BUILDDIR "/" )) == 0 )
pathWarning = "modified source in build dir : %0";
else if( strncmp( e->getName(), SRCDIR "/", strlen( SRCDIR "/" )) == 0 )
; // ok
else
{
pathWarning = "modified source in unknown location, not modifying : %0";
skip = true;
}
if( modifyFile.empty())
modifyFile = e->getName();
// Check whether the modified file is in the wanted scope (done after path checking above), so
// that files mapped from OUTDIR to SRCDIR are included.
if( scope == "mainfile" )
{
if( it->first != context.getSourceManager().getMainFileID())
continue;
}
else if( scope == "all" )
; // ok
else // scope is module
{
if( !( isPrefix( SRCDIR "/" + scope + "/", modifyFile ) || isPrefix( SRCDIR "/include/" + scope + "/", modifyFile ) ) )
continue;
}
// Warn only now, so that files not in scope do not cause warnings.
if( pathWarning != NULL )
report( DiagnosticsEngine::Warning, pathWarning ) << e->getName();
if( skip )
continue;
char* filename = new char[ modifyFile.length() + 100 ];
sprintf( filename, "%s.new.%d", modifyFile.c_str(), getpid());
string error;
bool ok = false;
raw_fd_ostream ostream( filename, error );
if( error.empty())
{
it->second.write( ostream );
ostream.close();
if( !ostream.has_error() && rename( filename, modifyFile.c_str()) == 0 )
ok = true;
}
ostream.clear_error();
unlink( filename );
if( !ok )
report( DiagnosticsEngine::Error, "cannot write modified source to %0 (%1)" ) << modifyFile << error;
delete[] filename;
}
}
ASTConsumer* LibreOfficeAction::CreateASTConsumer( CompilerInstance& Compiler, StringRef )
{
return new PluginHandler( Compiler, _args );
}
bool LibreOfficeAction::ParseArgs( const CompilerInstance&, const vector< string >& args )
{
_args = args;
return true;
}
static FrontendPluginRegistry::Add< loplugin::LibreOfficeAction > X( "loplugin", "LibreOffice compile check plugin" );
} // namespace
<|endoftext|> |
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2014, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "LPlugins.h"
#include <LuminaUtils.h>
LPlugins::LPlugins(){
LoadPanelPlugins();
LoadDesktopPlugins();
LoadMenuPlugins();
LoadColorItems();
}
LPlugins::~LPlugins(){
}
//Plugin lists
QStringList LPlugins::panelPlugins(){
QStringList pan = PANEL.keys();
pan.sort();
return pan;
}
QStringList LPlugins::desktopPlugins(){
QStringList desk = DESKTOP.keys();
desk.sort();
return desk;
}
QStringList LPlugins::menuPlugins(){
QStringList men = MENU.keys();
men.sort();
return men;
}
QStringList LPlugins::colorItems(){
return COLORS.keys();
}
//Information on individual plugins
LPI LPlugins::panelPluginInfo(QString plug){
if(PANEL.contains(plug)){ return PANEL[plug]; }
else{ return LPI(); }
}
LPI LPlugins::desktopPluginInfo(QString plug){
if(DESKTOP.contains(plug)){ return DESKTOP[plug]; }
else{ return LPI(); }
}
LPI LPlugins::menuPluginInfo(QString plug){
if(MENU.contains(plug)){ return MENU[plug]; }
else{ return LPI(); }
}
LPI LPlugins::colorInfo(QString item){
if(COLORS.contains(item)){ return COLORS[item]; }
else{ return LPI(); }
}
//===================
// PLUGINS
//===================
void LPlugins::LoadPanelPlugins(){
PANEL.clear();
//User Button
LPI info;
info.name = QObject::tr("User Button");
info.description = QObject::tr("This is the main system access button for the user (applications, directories, settings, log out).");
info.ID = "userbutton";
info.icon = "user-identity";
PANEL.insert(info.ID, info);
//Application Menu
info = LPI(); //clear it
info.name = QObject::tr("Application Menu");
info.description = QObject::tr("This provides instant-access to application that are installed on the system.");
info.ID = "appmenu";
info.icon = "format-list-unordered";
PANEL.insert(info.ID, info);
//Desktop Bar
info = LPI(); //clear it
info.name = QObject::tr("Desktop Bar");
info.description = QObject::tr("This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.");
info.ID = "desktopbar";
info.icon = "user-desktop";
PANEL.insert(info.ID, info);
//Spacer
info = LPI(); //clear it
info.name = QObject::tr("Spacer");
info.description = QObject::tr("Invisible spacer to separate plugins.");
info.ID = "spacer";
info.icon = "transform-move";
PANEL.insert(info.ID, info);
//Line
info = LPI(); //clear it
info.name = QObject::tr("Line");
info.description = QObject::tr("Simple line to provide visual separation between items.");
info.ID = "line";
info.icon = "insert-horizontal-rule";
PANEL.insert(info.ID, info);
//Desktop Switcher
info = LPI(); //clear it
info.name = QObject::tr("Workspace Switcher");
info.description = QObject::tr("Controls for switching between the various virtual desktops.");
info.ID = "desktopswitcher";
info.icon = "preferences-desktop-display-color";
PANEL.insert(info.ID, info);
//Battery
info = LPI(); //clear it
info.name = QObject::tr("Battery Monitor");
info.description = QObject::tr("Keep track of your battery status.");
info.ID = "battery";
info.icon = "battery-charging";
PANEL.insert(info.ID, info);
//Clock
info = LPI(); //clear it
info.name = QObject::tr("Time/Date");
info.description = QObject::tr("View the current time and date.");
info.ID = "clock";
info.icon = "preferences-system-time";
PANEL.insert(info.ID, info);
//System Dachboard plugin
info = LPI(); //clear it
info.name = QObject::tr("System Dashboard");
info.description = QObject::tr("View or change system settings (audio volume, screen brightness, battery life, virtual desktops).");
info.ID = "systemdashboard";
info.icon = "dashboard-show";
PANEL.insert(info.ID, info);
//Task Manager
info = LPI(); //clear it
info.name = QObject::tr("Task Manager");
info.description = QObject::tr("View and control any running application windows (every application has a button)");
info.ID = "taskmanager";
info.icon = "preferences-system-windows";
PANEL.insert(info.ID, info);
//Task Manager
info = LPI(); //clear it
info.name = QObject::tr("Task Manager (No Groups)");
info.description = QObject::tr("View and control any running application windows (every window has a button)");
info.ID = "taskmanager-nogroups";
info.icon = "preferences-system-windows";
PANEL.insert(info.ID, info);
//System Tray
info = LPI(); //clear it
info.name = QObject::tr("System Tray");
info.description = QObject::tr("Display area for dockable system applications");
info.ID = "systemtray";
info.icon = "preferences-system-windows-actions";
PANEL.insert(info.ID, info);
//Home Button
info = LPI(); //clear it
info.name = QObject::tr("Show Desktop");
info.description = QObject::tr("Hide all open windows and show the desktop");
info.ID = "homebutton";
info.icon = "user-desktop";
PANEL.insert(info.ID, info);
//Start Menu
info = LPI(); //clear it
info.name = QObject::tr("Start Menu");
info.description = QObject::tr("Unified system access and application launch menu.");
info.ID = "systemstart";
info.icon = "Lumina-DE";
PANEL.insert(info.ID, info);
//Application Launcher
info = LPI(); //clear it
info.name = QObject::tr("Application Launcher");
info.description = QObject::tr("Pin an application shortcut directly to the panel");
info.ID = "applauncher";
info.icon = "quickopen";
PANEL.insert(info.ID, info);
}
void LPlugins::LoadDesktopPlugins(){
DESKTOP.clear();
//Calendar Plugin
LPI info;
info.name = QObject::tr("Calendar");
info.description = QObject::tr("Display a calendar on the desktop");
info.ID = "calendar";
info.icon = "view-calendar";
DESKTOP.insert(info.ID, info);
//Application Launcher Plugin
info = LPI(); //clear it
info.name = QObject::tr("Application Launcher");
info.description = QObject::tr("Desktop button for launching an application");
info.ID = "applauncher";
info.icon = "quickopen";
DESKTOP.insert(info.ID, info);
//Desktop View Plugin
info = LPI(); //clear it
info.name = QObject::tr("Desktop Icons View");
info.description = QObject::tr("Area for automatically showing desktop icons");
info.ID = "desktopview";
info.icon = "preferences-desktop-icons";
DESKTOP.insert(info.ID, info);
//Notepad Plugin
info = LPI(); //clear it
info.name = QObject::tr("Note Pad");
info.description = QObject::tr("Keep simple text notes on your desktop");
info.ID = "notepad";
info.icon = "text-enriched";
DESKTOP.insert(info.ID, info);
//Audio Player Plugin
info = LPI(); //clear it
info.name = QObject::tr("Audio Player");
info.description = QObject::tr("Play through lists of audio files");
info.ID = "audioplayer";
info.icon = "media-playback-start";
DESKTOP.insert(info.ID, info);
//System Monitor Plugin
info = LPI(); //clear it
info.name = QObject::tr("System Monitor");
info.description = QObject::tr("Keep track of system statistics such as CPU/Memory usage and CPU temperatures.");
info.ID = "systemmonitor";
info.icon = "cpu";
DESKTOP.insert(info.ID, info);
//Available QtQuick scripts
/*QStringList quickID = LUtils::listQuickPlugins();
for(int i=0; i<quickID.length(); i++){
QStringList quickinfo = LUtils::infoQuickPlugin(quickID[i]); //Returns: [name, description, icon]
if(quickinfo.length() < 3){ continue; } //invalid file (unreadable/other)
info = LPI();
info.name = quickinfo[0];
info.description = quickinfo[1];
info.ID = "quick-"+quickID[i]; //the "quick-" prefix is required for the desktop plugin syntax
info.icon = quickinfo[2];
DESKTOP.insert(info.ID, info);
}*/
}
void LPlugins::LoadMenuPlugins(){
MENU.clear();
//Terminal
LPI info;
info.name = QObject::tr("Terminal");
info.description = QObject::tr("Start the default system terminal.");
info.ID = "terminal";
info.icon = "utilities-terminal";
MENU.insert(info.ID, info);
//File Manager
info = LPI(); //clear it
info.name = QObject::tr("File Manager");
info.description = QObject::tr("Browse the system with the default file manager.");
info.ID = "filemanager";
info.icon = "Insight-FileManager";
MENU.insert(info.ID, info);
//Applications
info = LPI(); //clear it
info.name = QObject::tr("Applications");
info.description = QObject::tr("Show the system applications menu.");
info.ID = "applications";
info.icon = "system-run";
MENU.insert(info.ID, info);
//Line seperator
info = LPI(); //clear it
info.name = QObject::tr("Separator");
info.description = QObject::tr("Static horizontal line.");
info.ID = "line";
info.icon = "insert-horizontal-rule";
MENU.insert(info.ID, info);
//Settings
info = LPI(); //clear it
info.name = QObject::tr("Settings");
info.description = QObject::tr("Show the desktop settings menu.");
info.ID = "settings";
info.icon = "configure";
MENU.insert(info.ID, info);
//Window List
info = LPI(); //clear it
info.name = QObject::tr("Window List");
info.description = QObject::tr("List the open application windows");
info.ID = "windowlist";
info.icon = "preferences-system-windows";
MENU.insert(info.ID, info);
//Custom Apps
info = LPI(); //clear it
info.name = QObject::tr("Custom App");
info.description = QObject::tr("Start a custom application");
info.ID = "app";
info.icon = "application-x-desktop";
MENU.insert(info.ID, info);
}
void LPlugins::LoadColorItems(){
COLORS.clear();
//Text Color
LPI info;
info.name = QObject::tr("Text");
info.description = QObject::tr("Color to use for all visible text.");
info.ID = "TEXTCOLOR";
COLORS.insert(info.ID, info);
//Text Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Text (Disabled)");
info.description = QObject::tr("Text color for disabled or inactive items.");
info.ID = "TEXTDISABLECOLOR";
COLORS.insert(info.ID, info);
//Text Color (Highlighted)
info = LPI(); //clear it
info.name = QObject::tr("Text (Highlighted)");
info.description = QObject::tr("Text color when selection is highlighted.");
info.ID = "TEXTHIGHLIGHTCOLOR";
COLORS.insert(info.ID, info);
//Base Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Base Window Color");
info.description = QObject::tr("Main background color for the window/dialog.");
info.ID = "BASECOLOR";
COLORS.insert(info.ID, info);
//Base Color (Alternate)
info = LPI(); //clear it
info.name = QObject::tr("Base Window Color (Alternate)");
info.description = QObject::tr("Main background color for widgets that list or display collections of items.");
info.ID = "ALTBASECOLOR";
COLORS.insert(info.ID, info);
//Primary Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Primary Color");
info.description = QObject::tr("Dominant color for the theme.");
info.ID = "PRIMARYCOLOR";
COLORS.insert(info.ID, info);
//Primary Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Primary Color (Disabled)");
info.description = QObject::tr("Dominant color for the theme (more subdued).");
info.ID = "PRIMARYDISABLECOLOR";
COLORS.insert(info.ID, info);
//Secondary Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Secondary Color");
info.description = QObject::tr("Alternate color for the theme.");
info.ID = "SECONDARYCOLOR";
COLORS.insert(info.ID, info);
//Secondary Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Secondary Color (Disabled)");
info.description = QObject::tr("Alternate color for the theme (more subdued).");
info.ID = "SECONDARYDISABLECOLOR";
COLORS.insert(info.ID, info);
//Accent Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Accent Color");
info.description = QObject::tr("Color used for borders or other accents.");
info.ID = "ACCENTCOLOR";
COLORS.insert(info.ID, info);
//Accent Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Accent Color (Disabled)");
info.description = QObject::tr("Color used for borders or other accents (more subdued).");
info.ID = "ACCENTDISABLECOLOR";
COLORS.insert(info.ID, info);
//Highlight Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Highlight Color");
info.description = QObject::tr("Color used for highlighting an item.");
info.ID = "HIGHLIGHTCOLOR";
COLORS.insert(info.ID, info);
//Highlight Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Highlight Color (Disabled)");
info.description = QObject::tr("Color used for highlighting an item (more subdued).");
info.ID = "HIGHLIGHTDISABLECOLOR";
COLORS.insert(info.ID, info);
}<commit_msg>Add the new RSS reader to the known plugins in lumina-config.<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2014, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "LPlugins.h"
#include <LuminaUtils.h>
LPlugins::LPlugins(){
LoadPanelPlugins();
LoadDesktopPlugins();
LoadMenuPlugins();
LoadColorItems();
}
LPlugins::~LPlugins(){
}
//Plugin lists
QStringList LPlugins::panelPlugins(){
QStringList pan = PANEL.keys();
pan.sort();
return pan;
}
QStringList LPlugins::desktopPlugins(){
QStringList desk = DESKTOP.keys();
desk.sort();
return desk;
}
QStringList LPlugins::menuPlugins(){
QStringList men = MENU.keys();
men.sort();
return men;
}
QStringList LPlugins::colorItems(){
return COLORS.keys();
}
//Information on individual plugins
LPI LPlugins::panelPluginInfo(QString plug){
if(PANEL.contains(plug)){ return PANEL[plug]; }
else{ return LPI(); }
}
LPI LPlugins::desktopPluginInfo(QString plug){
if(DESKTOP.contains(plug)){ return DESKTOP[plug]; }
else{ return LPI(); }
}
LPI LPlugins::menuPluginInfo(QString plug){
if(MENU.contains(plug)){ return MENU[plug]; }
else{ return LPI(); }
}
LPI LPlugins::colorInfo(QString item){
if(COLORS.contains(item)){ return COLORS[item]; }
else{ return LPI(); }
}
//===================
// PLUGINS
//===================
void LPlugins::LoadPanelPlugins(){
PANEL.clear();
//User Button
LPI info;
info.name = QObject::tr("User Button");
info.description = QObject::tr("This is the main system access button for the user (applications, directories, settings, log out).");
info.ID = "userbutton";
info.icon = "user-identity";
PANEL.insert(info.ID, info);
//Application Menu
info = LPI(); //clear it
info.name = QObject::tr("Application Menu");
info.description = QObject::tr("This provides instant-access to application that are installed on the system.");
info.ID = "appmenu";
info.icon = "format-list-unordered";
PANEL.insert(info.ID, info);
//Desktop Bar
info = LPI(); //clear it
info.name = QObject::tr("Desktop Bar");
info.description = QObject::tr("This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.");
info.ID = "desktopbar";
info.icon = "user-desktop";
PANEL.insert(info.ID, info);
//Spacer
info = LPI(); //clear it
info.name = QObject::tr("Spacer");
info.description = QObject::tr("Invisible spacer to separate plugins.");
info.ID = "spacer";
info.icon = "transform-move";
PANEL.insert(info.ID, info);
//Line
info = LPI(); //clear it
info.name = QObject::tr("Line");
info.description = QObject::tr("Simple line to provide visual separation between items.");
info.ID = "line";
info.icon = "insert-horizontal-rule";
PANEL.insert(info.ID, info);
//Desktop Switcher
info = LPI(); //clear it
info.name = QObject::tr("Workspace Switcher");
info.description = QObject::tr("Controls for switching between the various virtual desktops.");
info.ID = "desktopswitcher";
info.icon = "preferences-desktop-display-color";
PANEL.insert(info.ID, info);
//Battery
info = LPI(); //clear it
info.name = QObject::tr("Battery Monitor");
info.description = QObject::tr("Keep track of your battery status.");
info.ID = "battery";
info.icon = "battery-charging";
PANEL.insert(info.ID, info);
//Clock
info = LPI(); //clear it
info.name = QObject::tr("Time/Date");
info.description = QObject::tr("View the current time and date.");
info.ID = "clock";
info.icon = "preferences-system-time";
PANEL.insert(info.ID, info);
//System Dachboard plugin
info = LPI(); //clear it
info.name = QObject::tr("System Dashboard");
info.description = QObject::tr("View or change system settings (audio volume, screen brightness, battery life, virtual desktops).");
info.ID = "systemdashboard";
info.icon = "dashboard-show";
PANEL.insert(info.ID, info);
//Task Manager
info = LPI(); //clear it
info.name = QObject::tr("Task Manager");
info.description = QObject::tr("View and control any running application windows (every application has a button)");
info.ID = "taskmanager";
info.icon = "preferences-system-windows";
PANEL.insert(info.ID, info);
//Task Manager
info = LPI(); //clear it
info.name = QObject::tr("Task Manager (No Groups)");
info.description = QObject::tr("View and control any running application windows (every window has a button)");
info.ID = "taskmanager-nogroups";
info.icon = "preferences-system-windows";
PANEL.insert(info.ID, info);
//System Tray
info = LPI(); //clear it
info.name = QObject::tr("System Tray");
info.description = QObject::tr("Display area for dockable system applications");
info.ID = "systemtray";
info.icon = "preferences-system-windows-actions";
PANEL.insert(info.ID, info);
//Home Button
info = LPI(); //clear it
info.name = QObject::tr("Show Desktop");
info.description = QObject::tr("Hide all open windows and show the desktop");
info.ID = "homebutton";
info.icon = "user-desktop";
PANEL.insert(info.ID, info);
//Start Menu
info = LPI(); //clear it
info.name = QObject::tr("Start Menu");
info.description = QObject::tr("Unified system access and application launch menu.");
info.ID = "systemstart";
info.icon = "Lumina-DE";
PANEL.insert(info.ID, info);
//Application Launcher
info = LPI(); //clear it
info.name = QObject::tr("Application Launcher");
info.description = QObject::tr("Pin an application shortcut directly to the panel");
info.ID = "applauncher";
info.icon = "quickopen";
PANEL.insert(info.ID, info);
}
void LPlugins::LoadDesktopPlugins(){
DESKTOP.clear();
//Calendar Plugin
LPI info;
info.name = QObject::tr("Calendar");
info.description = QObject::tr("Display a calendar on the desktop");
info.ID = "calendar";
info.icon = "view-calendar";
DESKTOP.insert(info.ID, info);
//Application Launcher Plugin
info = LPI(); //clear it
info.name = QObject::tr("Application Launcher");
info.description = QObject::tr("Desktop button for launching an application");
info.ID = "applauncher";
info.icon = "quickopen";
DESKTOP.insert(info.ID, info);
//Desktop View Plugin
info = LPI(); //clear it
info.name = QObject::tr("Desktop Icons View");
info.description = QObject::tr("Area for automatically showing desktop icons");
info.ID = "desktopview";
info.icon = "preferences-desktop-icons";
DESKTOP.insert(info.ID, info);
//Notepad Plugin
info = LPI(); //clear it
info.name = QObject::tr("Note Pad");
info.description = QObject::tr("Keep simple text notes on your desktop");
info.ID = "notepad";
info.icon = "text-enriched";
DESKTOP.insert(info.ID, info);
//Audio Player Plugin
info = LPI(); //clear it
info.name = QObject::tr("Audio Player");
info.description = QObject::tr("Play through lists of audio files");
info.ID = "audioplayer";
info.icon = "media-playback-start";
DESKTOP.insert(info.ID, info);
//System Monitor Plugin
info = LPI(); //clear it
info.name = QObject::tr("System Monitor");
info.description = QObject::tr("Keep track of system statistics such as CPU/Memory usage and CPU temperatures.");
info.ID = "systemmonitor";
info.icon = "cpu";
DESKTOP.insert(info.ID, info);
//RSS Reader Plugin
info = LPI(); //clear it
info.name = QObject::tr("RSS Reader");
info.description = QObject::tr("Monitor RSS Feeds (Requires internet connection)");
info.ID = "rssfeeder";
info.icon = "application-rss+xml";
DESKTOP.insert(info.ID, info);
//Available QtQuick scripts
/*QStringList quickID = LUtils::listQuickPlugins();
for(int i=0; i<quickID.length(); i++){
QStringList quickinfo = LUtils::infoQuickPlugin(quickID[i]); //Returns: [name, description, icon]
if(quickinfo.length() < 3){ continue; } //invalid file (unreadable/other)
info = LPI();
info.name = quickinfo[0];
info.description = quickinfo[1];
info.ID = "quick-"+quickID[i]; //the "quick-" prefix is required for the desktop plugin syntax
info.icon = quickinfo[2];
DESKTOP.insert(info.ID, info);
}*/
}
void LPlugins::LoadMenuPlugins(){
MENU.clear();
//Terminal
LPI info;
info.name = QObject::tr("Terminal");
info.description = QObject::tr("Start the default system terminal.");
info.ID = "terminal";
info.icon = "utilities-terminal";
MENU.insert(info.ID, info);
//File Manager
info = LPI(); //clear it
info.name = QObject::tr("File Manager");
info.description = QObject::tr("Browse the system with the default file manager.");
info.ID = "filemanager";
info.icon = "Insight-FileManager";
MENU.insert(info.ID, info);
//Applications
info = LPI(); //clear it
info.name = QObject::tr("Applications");
info.description = QObject::tr("Show the system applications menu.");
info.ID = "applications";
info.icon = "system-run";
MENU.insert(info.ID, info);
//Line seperator
info = LPI(); //clear it
info.name = QObject::tr("Separator");
info.description = QObject::tr("Static horizontal line.");
info.ID = "line";
info.icon = "insert-horizontal-rule";
MENU.insert(info.ID, info);
//Settings
info = LPI(); //clear it
info.name = QObject::tr("Settings");
info.description = QObject::tr("Show the desktop settings menu.");
info.ID = "settings";
info.icon = "configure";
MENU.insert(info.ID, info);
//Window List
info = LPI(); //clear it
info.name = QObject::tr("Window List");
info.description = QObject::tr("List the open application windows");
info.ID = "windowlist";
info.icon = "preferences-system-windows";
MENU.insert(info.ID, info);
//Custom Apps
info = LPI(); //clear it
info.name = QObject::tr("Custom App");
info.description = QObject::tr("Start a custom application");
info.ID = "app";
info.icon = "application-x-desktop";
MENU.insert(info.ID, info);
}
void LPlugins::LoadColorItems(){
COLORS.clear();
//Text Color
LPI info;
info.name = QObject::tr("Text");
info.description = QObject::tr("Color to use for all visible text.");
info.ID = "TEXTCOLOR";
COLORS.insert(info.ID, info);
//Text Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Text (Disabled)");
info.description = QObject::tr("Text color for disabled or inactive items.");
info.ID = "TEXTDISABLECOLOR";
COLORS.insert(info.ID, info);
//Text Color (Highlighted)
info = LPI(); //clear it
info.name = QObject::tr("Text (Highlighted)");
info.description = QObject::tr("Text color when selection is highlighted.");
info.ID = "TEXTHIGHLIGHTCOLOR";
COLORS.insert(info.ID, info);
//Base Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Base Window Color");
info.description = QObject::tr("Main background color for the window/dialog.");
info.ID = "BASECOLOR";
COLORS.insert(info.ID, info);
//Base Color (Alternate)
info = LPI(); //clear it
info.name = QObject::tr("Base Window Color (Alternate)");
info.description = QObject::tr("Main background color for widgets that list or display collections of items.");
info.ID = "ALTBASECOLOR";
COLORS.insert(info.ID, info);
//Primary Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Primary Color");
info.description = QObject::tr("Dominant color for the theme.");
info.ID = "PRIMARYCOLOR";
COLORS.insert(info.ID, info);
//Primary Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Primary Color (Disabled)");
info.description = QObject::tr("Dominant color for the theme (more subdued).");
info.ID = "PRIMARYDISABLECOLOR";
COLORS.insert(info.ID, info);
//Secondary Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Secondary Color");
info.description = QObject::tr("Alternate color for the theme.");
info.ID = "SECONDARYCOLOR";
COLORS.insert(info.ID, info);
//Secondary Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Secondary Color (Disabled)");
info.description = QObject::tr("Alternate color for the theme (more subdued).");
info.ID = "SECONDARYDISABLECOLOR";
COLORS.insert(info.ID, info);
//Accent Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Accent Color");
info.description = QObject::tr("Color used for borders or other accents.");
info.ID = "ACCENTCOLOR";
COLORS.insert(info.ID, info);
//Accent Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Accent Color (Disabled)");
info.description = QObject::tr("Color used for borders or other accents (more subdued).");
info.ID = "ACCENTDISABLECOLOR";
COLORS.insert(info.ID, info);
//Highlight Color (Normal)
info = LPI(); //clear it
info.name = QObject::tr("Highlight Color");
info.description = QObject::tr("Color used for highlighting an item.");
info.ID = "HIGHLIGHTCOLOR";
COLORS.insert(info.ID, info);
//Highlight Color (Disabled)
info = LPI(); //clear it
info.name = QObject::tr("Highlight Color (Disabled)");
info.description = QObject::tr("Color used for highlighting an item (more subdued).");
info.ID = "HIGHLIGHTDISABLECOLOR";
COLORS.insert(info.ID, info);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// \file h5_handler.cc
/// \brief main program source.
///
/// \author Muqun Yang ([email protected])
/// \author Hyo-Kyung Lee <[email protected]>
///
/// Copyright (C) 2007 HDF Group, Inc.
///
/// Copyright (C) 1999 National Center for Supercomputing Applications.
/// All rights reserved.
////////////////////////////////////////////////////////////////////////////////
// #define DODS_DEBUG
#include "h5_handler.h"
/// The default CGI version of handler.
const static string cgi_version = "3.0";
/// An external object that handles NASA EOS HDF5 files for grid generation
/// and meta data parsing.
extern H5EOS eos;
///////////////////////////////////////////////////////////////////////////////
/// \fn main(int argc, char *argv[])
/// main function for HDF5 data handler.
/// This function processes options and generates the corresponding DAP outputs requested by the user.
/// @param argc number of arguments
/// @param argv command line arguments for options
/// @return 0 if success
/// @return 1 if error
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
DBG(cerr << "Starting the HDF handler." << endl);
try {
DODSFilter df(argc, argv);
if (df.get_cgi_version() == "")
df.set_cgi_version(cgi_version);
// Handle the version info as a special case since there's no need to
// open the hdf5 file. This makes it possible to move the file open
// and close code out of the individual case statements.
// jhrg 02/04/04
if (df.get_response() == DODSFilter::Version_Response) {
df.send_version_info();
return 0;
}
hid_t file1 = get_fileid(df.get_dataset_name().c_str());
if (file1 < 0)
throw Error(no_such_file, string("Could not open hdf5 file: ")
+ df.get_dataset_name());
// Check if it is EOS file.
DBG(cerr << "checking EOS file" << endl);
if(eos.check_eos(file1)){
DBG(cerr << "eos file is detected" << endl);
eos.set_dimension_array();
}
else{
DBG(cerr << "eos file is not detected" << endl);
}
switch (df.get_response()) {
case DODSFilter::DAS_Response:{
DAS das;
find_gloattr(file1, das);
depth_first(file1, "/", das);
df.send_das(das);
break;
}
case DODSFilter::DDS_Response:{
DAS das;
HDF5TypeFactory factory;
DDS dds(&factory);
ConstraintEvaluator ce;
depth_first(file1, "/", dds,
df.get_dataset_name().c_str());
DBG(cerr << ">df.send_dds()" << endl);
df.send_dds(dds, ce, true);
break;
}
case DODSFilter::DataDDS_Response:{
HDF5TypeFactory factory;
DDS dds(&factory);
ConstraintEvaluator ce;
DAS das;
depth_first(file1, "/", dds,
df.get_dataset_name().c_str());
df.send_data(dds, ce, stdout);
break;
}
case DODSFilter::DDX_Response:{
HDF5TypeFactory factory;
DDS dds(&factory);
ConstraintEvaluator ce;
DAS das;
depth_first(file1, "/", dds,
df.get_dataset_name().c_str());
find_gloattr(file1, das);
dds.transfer_attributes(&das);
df.send_ddx(dds, ce, stdout);
break;
}
case DODSFilter::Version_Response:{
df.send_version_info();
break;
}
default:
df.print_usage(); // Throws Error
}
if (H5Fclose(file1) < 0)
throw Error(unknown_error,
string("Could not close the HDF5 file: ")
+ df.get_dataset_name());
}
catch(Error & e) {
string s;
s = string("h5_handler: ") + e.get_error_message() + "\n";
ErrMsgT(s);
set_mime_text(stdout, dods_error, cgi_version);
e.print(stdout);
return 1;
}
catch(...) {
string s("h5_handler: Unknown exception");
ErrMsgT(s);
Error e(unknown_error, s);
set_mime_text(stdout, dods_error, cgi_version);
e.print(stdout);
return 1;
}
DBG(cerr << "HDF5 server exitied successfully." << endl);
return 0;
}
// $Log$
<commit_msg>Attributes were not being added to the dds when requesting the ddx response. Fixed this. M h5_handler.cc<commit_after>////////////////////////////////////////////////////////////////////////////////
/// \file h5_handler.cc
/// \brief main program source.
///
/// \author Muqun Yang ([email protected])
/// \author Hyo-Kyung Lee <[email protected]>
///
/// Copyright (C) 2007 HDF Group, Inc.
///
/// Copyright (C) 1999 National Center for Supercomputing Applications.
/// All rights reserved.
////////////////////////////////////////////////////////////////////////////////
// #define DODS_DEBUG
#include "h5_handler.h"
/// The default CGI version of handler.
const static string cgi_version = "3.0";
/// An external object that handles NASA EOS HDF5 files for grid generation
/// and meta data parsing.
extern H5EOS eos;
///////////////////////////////////////////////////////////////////////////////
/// \fn main(int argc, char *argv[])
/// main function for HDF5 data handler.
/// This function processes options and generates the corresponding DAP outputs requested by the user.
/// @param argc number of arguments
/// @param argv command line arguments for options
/// @return 0 if success
/// @return 1 if error
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
DBG(cerr << "Starting the HDF handler." << endl);
try {
DODSFilter df(argc, argv);
if (df.get_cgi_version() == "")
df.set_cgi_version(cgi_version);
// Handle the version info as a special case since there's no need to
// open the hdf5 file. This makes it possible to move the file open
// and close code out of the individual case statements.
// jhrg 02/04/04
if (df.get_response() == DODSFilter::Version_Response) {
df.send_version_info();
return 0;
}
hid_t file1 = get_fileid(df.get_dataset_name().c_str());
if (file1 < 0)
throw Error(no_such_file, string("Could not open hdf5 file: ")
+ df.get_dataset_name());
// Check if it is EOS file.
DBG(cerr << "checking EOS file" << endl);
if(eos.check_eos(file1)){
DBG(cerr << "eos file is detected" << endl);
eos.set_dimension_array();
}
else{
DBG(cerr << "eos file is not detected" << endl);
}
switch (df.get_response()) {
case DODSFilter::DAS_Response:{
DAS das;
find_gloattr(file1, das);
depth_first(file1, "/", das);
df.send_das(das);
break;
}
case DODSFilter::DDS_Response:{
DAS das;
HDF5TypeFactory factory;
DDS dds(&factory);
ConstraintEvaluator ce;
depth_first(file1, "/", dds,
df.get_dataset_name().c_str());
DBG(cerr << ">df.send_dds()" << endl);
df.send_dds(dds, ce, true);
break;
}
case DODSFilter::DataDDS_Response:{
HDF5TypeFactory factory;
DDS dds(&factory);
ConstraintEvaluator ce;
DAS das;
depth_first(file1, "/", dds,
df.get_dataset_name().c_str());
df.send_data(dds, ce, stdout);
break;
}
case DODSFilter::DDX_Response:{
HDF5TypeFactory factory;
DDS dds(&factory);
ConstraintEvaluator ce;
DAS das;
depth_first(file1, "/", dds,
df.get_dataset_name().c_str());
find_gloattr(file1, das);
depth_first(file1, "/", das);
dds.transfer_attributes(&das);
df.send_ddx(dds, ce, stdout);
break;
}
case DODSFilter::Version_Response:{
df.send_version_info();
break;
}
default:
df.print_usage(); // Throws Error
}
if (H5Fclose(file1) < 0)
throw Error(unknown_error,
string("Could not close the HDF5 file: ")
+ df.get_dataset_name());
}
catch(Error & e) {
string s;
s = string("h5_handler: ") + e.get_error_message() + "\n";
ErrMsgT(s);
set_mime_text(stdout, dods_error, cgi_version);
e.print(stdout);
return 1;
}
catch(...) {
string s("h5_handler: Unknown exception");
ErrMsgT(s);
Error e(unknown_error, s);
set_mime_text(stdout, dods_error, cgi_version);
e.print(stdout);
return 1;
}
DBG(cerr << "HDF5 server exitied successfully." << endl);
return 0;
}
// $Log$
<|endoftext|> |
<commit_before>
// Bindings
#include "CPyCppyy.h"
#include "PyROOTPythonize.h"
#include "CPPInstance.h"
#include "ProxyWrappers.h"
#include "Converters.h"
#include "Utility.h"
// ROOT
#include "TClass.h"
#include "TTree.h"
#include "TBranch.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TLeaf.h"
#include "TLeafElement.h"
#include "TLeafObject.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
using namespace CPyCppyy;
static TClass *OP2TCLASS(CPPInstance *pyobj)
{
return TClass::GetClass(Cppyy::GetFinalName(pyobj->ObjectIsA()).c_str());
}
// Allow access to branches/leaves as if they were data members
PyObject *GetAttr(CPPInstance *self, PyObject *pyname)
{
const char *name1 = CPyCppyy_PyUnicode_AsString(pyname);
if (!name1)
return 0;
// get hold of actual tree
TTree *tree = (TTree *)OP2TCLASS(self)->DynamicCast(TTree::Class(), self->GetObject());
if (!tree) {
PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
return 0;
}
// deal with possible aliasing
const char *name = tree->GetAlias(name1);
if (!name)
name = name1;
// search for branch first (typical for objects)
TBranch *branch = tree->GetBranch(name);
if (!branch) {
// for benefit of naming of sub-branches, the actual name may have a trailing '.'
branch = tree->GetBranch((std::string(name) + '.').c_str());
}
if (branch) {
// found a branched object, wrap its address for the object it represents
// for partial return of a split object
if (branch->InheritsFrom(TBranchElement::Class())) {
TBranchElement *be = (TBranchElement *)branch;
if (be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID())) {
Long_t offset = ((TStreamerElement *)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
return BindCppObjectNoCast(be->GetObject() + offset, Cppyy::GetScope(be->GetCurrentClass()->GetName()));
}
}
// for return of a full object
if (branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class()) {
TClass *klass = TClass::GetClass(branch->GetClassName());
if (klass && branch->GetAddress())
return BindCppObjectNoCast(*(void **)branch->GetAddress(), Cppyy::GetScope(branch->GetClassName()));
// try leaf, otherwise indicate failure by returning a typed null-object
TObjArray *leaves = branch->GetListOfLeaves();
if (klass && !tree->GetLeaf(name) && !(leaves->GetSize() && (leaves->First() == leaves->Last())))
return BindCppObjectNoCast(NULL, Cppyy::GetScope(branch->GetClassName()));
}
}
// if not, try leaf
TLeaf *leaf = tree->GetLeaf(name);
if (branch && !leaf) {
leaf = branch->GetLeaf(name);
if (!leaf) {
TObjArray *leaves = branch->GetListOfLeaves();
if (leaves->GetSize() && (leaves->First() == leaves->Last())) {
// i.e., if unambiguously only this one
leaf = (TLeaf *)leaves->At(0);
}
}
}
if (leaf) {
// found a leaf, extract value and wrap
if (1 < leaf->GetLenStatic() || leaf->GetLeafCount()) {
// array types
std::string typeName = leaf->GetTypeName();
Converter *pcnv = CreateConverter(typeName + '*', leaf->GetNdata());
void *address = 0;
if (leaf->GetBranch())
address = (void *)leaf->GetBranch()->GetAddress();
if (!address)
address = (void *)leaf->GetValuePointer();
PyObject *value = pcnv->FromMemory(&address);
delete pcnv;
return value;
} else if (leaf->GetValuePointer()) {
// value types
Converter *pcnv = CreateConverter(leaf->GetTypeName());
PyObject *value = 0;
if (leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class())
value = pcnv->FromMemory((void *)*(void **)leaf->GetValuePointer());
else
value = pcnv->FromMemory((void *)leaf->GetValuePointer());
delete pcnv;
return value;
}
}
// confused
PyErr_Format(PyExc_AttributeError, "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name);
return 0;
}
// Public function
PyObject *PyROOT::PythonizeTTree(PyObject *, PyObject *args)
{
PyObject *pyclass = PyTuple_GetItem(args, 0);
Utility::AddToClass(pyclass, "__getattr__", (PyCFunction)GetAttr, METH_O);
Py_RETURN_NONE;
}
<commit_msg>Follow ROOT naming convention<commit_after>
// Bindings
#include "CPyCppyy.h"
#include "PyROOTPythonize.h"
#include "CPPInstance.h"
#include "ProxyWrappers.h"
#include "Converters.h"
#include "Utility.h"
// ROOT
#include "TClass.h"
#include "TTree.h"
#include "TBranch.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TLeaf.h"
#include "TLeafElement.h"
#include "TLeafObject.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
using namespace CPyCppyy;
static TClass *GetClass(CPPInstance *pyobj)
{
return TClass::GetClass(Cppyy::GetFinalName(pyobj->ObjectIsA()).c_str());
}
// Allow access to branches/leaves as if they were data members
PyObject *GetAttr(CPPInstance *self, PyObject *pyname)
{
const char *name1 = CPyCppyy_PyUnicode_AsString(pyname);
if (!name1)
return 0;
// get hold of actual tree
TTree *tree = (TTree *)GetClass(self)->DynamicCast(TTree::Class(), self->GetObject());
if (!tree) {
PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
return 0;
}
// deal with possible aliasing
const char *name = tree->GetAlias(name1);
if (!name)
name = name1;
// search for branch first (typical for objects)
TBranch *branch = tree->GetBranch(name);
if (!branch) {
// for benefit of naming of sub-branches, the actual name may have a trailing '.'
branch = tree->GetBranch((std::string(name) + '.').c_str());
}
if (branch) {
// found a branched object, wrap its address for the object it represents
// for partial return of a split object
if (branch->InheritsFrom(TBranchElement::Class())) {
TBranchElement *be = (TBranchElement *)branch;
if (be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID())) {
Long_t offset = ((TStreamerElement *)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
return BindCppObjectNoCast(be->GetObject() + offset, Cppyy::GetScope(be->GetCurrentClass()->GetName()));
}
}
// for return of a full object
if (branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class()) {
TClass *klass = TClass::GetClass(branch->GetClassName());
if (klass && branch->GetAddress())
return BindCppObjectNoCast(*(void **)branch->GetAddress(), Cppyy::GetScope(branch->GetClassName()));
// try leaf, otherwise indicate failure by returning a typed null-object
TObjArray *leaves = branch->GetListOfLeaves();
if (klass && !tree->GetLeaf(name) && !(leaves->GetSize() && (leaves->First() == leaves->Last())))
return BindCppObjectNoCast(NULL, Cppyy::GetScope(branch->GetClassName()));
}
}
// if not, try leaf
TLeaf *leaf = tree->GetLeaf(name);
if (branch && !leaf) {
leaf = branch->GetLeaf(name);
if (!leaf) {
TObjArray *leaves = branch->GetListOfLeaves();
if (leaves->GetSize() && (leaves->First() == leaves->Last())) {
// i.e., if unambiguously only this one
leaf = (TLeaf *)leaves->At(0);
}
}
}
if (leaf) {
// found a leaf, extract value and wrap
if (1 < leaf->GetLenStatic() || leaf->GetLeafCount()) {
// array types
std::string typeName = leaf->GetTypeName();
Converter *pcnv = CreateConverter(typeName + '*', leaf->GetNdata());
void *address = 0;
if (leaf->GetBranch())
address = (void *)leaf->GetBranch()->GetAddress();
if (!address)
address = (void *)leaf->GetValuePointer();
PyObject *value = pcnv->FromMemory(&address);
delete pcnv;
return value;
} else if (leaf->GetValuePointer()) {
// value types
Converter *pcnv = CreateConverter(leaf->GetTypeName());
PyObject *value = 0;
if (leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class())
value = pcnv->FromMemory((void *)*(void **)leaf->GetValuePointer());
else
value = pcnv->FromMemory((void *)leaf->GetValuePointer());
delete pcnv;
return value;
}
}
// confused
PyErr_Format(PyExc_AttributeError, "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name);
return 0;
}
// Public function
PyObject *PyROOT::PythonizeTTree(PyObject *, PyObject *args)
{
PyObject *pyclass = PyTuple_GetItem(args, 0);
Utility::AddToClass(pyclass, "__getattr__", (PyCFunction)GetAttr, METH_O);
Py_RETURN_NONE;
}
<|endoftext|> |
<commit_before>#include "Audio3DSample.h"
#include "Grid.h"
#include "SamplesGame.h"
#if defined(ADD_SAMPLE)
ADD_SAMPLE("Media", "Audio 3D", Audio3DSample, 1);
#endif
static const unsigned int MOVE_FORWARD = 1;
static const unsigned int MOVE_BACKWARD = 2;
static const unsigned int MOVE_LEFT = 4;
static const unsigned int MOVE_RIGHT = 8;
static const unsigned int MOVE_UP = 16;
static const unsigned int MOVE_DOWN = 32;
static const float MOVE_SPEED = 15.0f;
static const float UP_DOWN_SPEED = 10.0f;
Audio3DSample::Audio3DSample()
: _font(NULL), _scene(NULL), _cubeNode(NULL), _gamepad(NULL), _moveFlags(0), _prevX(0), _prevY(0), _buttonPressed(false)
{
}
void Audio3DSample::initialize()
{
setMultiTouch(true);
_font = Font::create("res/ui/arial.gpb");
// Load game scene from file
_scene = Scene::load("res/common/box.gpb");
// Get light node
Node* lightNode = _scene->findNode("directionalLight1");
Light* light = lightNode->getLight();
lightNode->setRotation(Vector3(1, 0, 0), -MATH_DEG_TO_RAD(45));
// Initialize box model
Node* boxNode = _scene->findNode("box");
Model* boxModel = dynamic_cast<Model*>(boxNode->getDrawable());
Material* boxMaterial = boxModel->setMaterial("res/common/box.material#lambert1");
boxMaterial->getParameter("u_directionalLightColor[0]")->setValue(light->getColor());
boxMaterial->getParameter("u_directionalLightDirection[0]")->setValue(lightNode->getForwardVectorView());
// Remove the cube from the scene but keep a reference to it.
_cubeNode = boxNode;
_cubeNode->addRef();
_scene->removeNode(_cubeNode);
loadGrid(_scene);
// Initialize cameraa
Vector3 cameraPosition(5, 5, 1);
if (Camera* camera = _scene->getActiveCamera())
{
camera->getNode()->getTranslation(&cameraPosition);
}
_fpCamera.initialize();
_fpCamera.setPosition(cameraPosition);
_scene->addNode(_fpCamera.getRootNode());
_scene->setActiveCamera(_fpCamera.getCamera());
_gamepad = getGamepad(0);
// This is needed because the virtual gamepad is shared between all samples.
// SamplesGame always ensures the virtual gamepad is disabled when a sample is exited.
if (_gamepad && _gamepad->isVirtual())
_gamepad->getForm()->setEnabled(true);
}
void Audio3DSample::finalize()
{
SAFE_RELEASE(_scene);
SAFE_RELEASE(_font);
SAFE_RELEASE(_cubeNode);
for (std::map<std::string, Node*>::iterator it = _audioNodes.begin(); it != _audioNodes.end(); ++it)
{
it->second->release();
}
_audioNodes.clear();
}
void Audio3DSample::update(float elapsedTime)
{
float time = (float)elapsedTime / 1000.0f;
Vector2 move;
if (_moveFlags != 0)
{
// Forward motion
if (_moveFlags & MOVE_FORWARD)
{
move.y = 1;
}
else if (_moveFlags & MOVE_BACKWARD)
{
move.y = -1;
}
// Strafing
if (_moveFlags & MOVE_LEFT)
{
move.x = 1;
}
else if (_moveFlags & MOVE_RIGHT)
{
move.x = -1;
}
move.normalize();
// Up and down
if (_moveFlags & MOVE_UP)
{
_fpCamera.moveUp(time * UP_DOWN_SPEED);
}
else if (_moveFlags & MOVE_DOWN)
{
_fpCamera.moveDown(time * UP_DOWN_SPEED);
}
}
else if (_gamepad->getJoystickCount() > 0)
{
_gamepad->getJoystickValues(0, &move);
move.x = -move.x;
}
if (_gamepad->getJoystickCount() > 1)
{
Vector2 joy2;
_gamepad->getJoystickValues(1, &joy2);
_fpCamera.rotate(MATH_DEG_TO_RAD(joy2.x * 2.0f), MATH_DEG_TO_RAD(joy2.y * 2.0f));
}
if (!move.isZero())
{
move.scale(time * MOVE_SPEED);
_fpCamera.moveForward(move.y);
_fpCamera.moveLeft(move.x);
}
if (!_buttonPressed && _gamepad->isButtonDown(Gamepad::BUTTON_A))
{
addSound("footsteps.wav");
}
_buttonPressed = _gamepad->isButtonDown(Gamepad::BUTTON_A);
}
void Audio3DSample::render(float elapsedTime)
{
// Clear the color and depth buffers
clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0);
// Visit all the nodes in the scene for drawing
_scene->visit(this, &Audio3DSample::drawScene);
drawDebugText(5, 20, 18);
_gamepad->draw();
drawFrameRate(_font, Vector4(0, 0.5f, 1, 1), 5, 1, getFrameRate());
}
bool Audio3DSample::drawScene(Node* node)
{
Drawable* drawable = node->getDrawable();
if (drawable)
drawable->draw();
return true;
}
void Audio3DSample::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
switch (evt)
{
case Touch::TOUCH_PRESS:
{
if (x < 75 && y < 50)
{
// Toggle Vsync if the user touches the top left corner
setVsync(!isVsync());
}
_prevX = x;
_prevY = y;
break;
}
case Touch::TOUCH_RELEASE:
{
_prevX = 0;
_prevY = 0;
break;
}
case Touch::TOUCH_MOVE:
{
int deltaX = x - _prevX;
int deltaY = y - _prevY;
_prevX = x;
_prevY = y;
float pitch = -MATH_DEG_TO_RAD(deltaY * 0.5f);
float yaw = MATH_DEG_TO_RAD(deltaX * 0.5f);
_fpCamera.rotate(yaw, pitch);
break;
}
};
}
void Audio3DSample::keyEvent(Keyboard::KeyEvent evt, int key)
{
if (evt == Keyboard::KEY_PRESS)
{
switch (key)
{
case Keyboard::KEY_W:
_moveFlags |= MOVE_FORWARD;
break;
case Keyboard::KEY_S:
_moveFlags |= MOVE_BACKWARD;
break;
case Keyboard::KEY_A:
_moveFlags |= MOVE_LEFT;
break;
case Keyboard::KEY_D:
_moveFlags |= MOVE_RIGHT;
break;
case Keyboard::KEY_Q:
_moveFlags |= MOVE_DOWN;
break;
case Keyboard::KEY_E:
_moveFlags |= MOVE_UP;
break;
case Keyboard::KEY_PG_UP:
_fpCamera.rotate(0, MATH_PIOVER4);
break;
case Keyboard::KEY_PG_DOWN:
_fpCamera.rotate(0, -MATH_PIOVER4);
break;
case Keyboard::KEY_ONE:
case Keyboard::KEY_SPACE:
addSound("footsteps.wav");
break;
}
}
else if (evt == Keyboard::KEY_RELEASE)
{
switch (key)
{
case Keyboard::KEY_W:
_moveFlags &= ~MOVE_FORWARD;
break;
case Keyboard::KEY_S:
_moveFlags &= ~MOVE_BACKWARD;
break;
case Keyboard::KEY_A:
_moveFlags &= ~MOVE_LEFT;
break;
case Keyboard::KEY_D:
_moveFlags &= ~MOVE_RIGHT;
break;
case Keyboard::KEY_Q:
_moveFlags &= ~MOVE_DOWN;
break;
case Keyboard::KEY_E:
_moveFlags &= ~MOVE_UP;
break;
}
}
}
bool Audio3DSample::mouseEvent(Mouse::MouseEvent evt, int x, int y, float wheelDelta)
{
switch (evt)
{
case Mouse::MOUSE_WHEEL:
_fpCamera.moveForward(wheelDelta * MOVE_SPEED / 2.0f );
return true;
}
return false;
}
void Audio3DSample::addSound(const std::string& file)
{
std::string path("res/common/");
path.append(file);
Node* node = NULL;
std::map<std::string, Node*>::iterator it = _audioNodes.find(path);
if (it != _audioNodes.end())
{
node = it->second->clone();
}
else
{
AudioSource* audioSource = AudioSource::create(path.c_str());
assert(audioSource);
audioSource->setLooped(true);
node = _cubeNode->clone();
node->setId(file.c_str());
node->setAudioSource(audioSource);
audioSource->release();
_audioNodes[path] = node;
node->addRef();
}
assert(node);
Node* cameraNode = _scene->getActiveCamera()->getNode();
// Position the sound infront of the user
node->setTranslation(cameraNode->getTranslationWorld());
Vector3 dir = cameraNode->getForwardVectorWorld().normalize();
dir.scale(2);
node->translate(dir);
_scene->addNode(node);
node->getAudioSource()->play();
node->release();
}
void Audio3DSample::drawDebugText(int x, int y, unsigned int fontSize)
{
_font->start();
static const int V_SPACE = 16;
AudioListener* audioListener = AudioListener::getInstance();
drawVector3("Position", audioListener->getPosition(), x, y);
drawVector3("Forward", audioListener->getOrientationForward(), x, y += fontSize);
drawVector3("Orientation", audioListener->getOrientationUp(), x, y += fontSize);
drawVector3("Velocity", audioListener->getVelocity(), x, y += fontSize);
_font->finish();
}
void Audio3DSample::drawVector3(const char* str, const Vector3& vector, int x, int y)
{
wchar_t buffer[255];
swprintf(buffer, 255, L"%s: (%f, %f, %f)", str, vector.x, vector.y, vector.z);
_font->drawText(buffer, x, y, Vector4::one(), _font->getSize());
}
void Audio3DSample::loadGrid(Scene* scene)
{
assert(scene);
Model* gridModel = createGridModel();
assert(gridModel);
gridModel->setMaterial("res/common/grid.material");
Node* node = scene->addNode("grid");
node->setDrawable(gridModel);
SAFE_RELEASE(gridModel);
}
void Audio3DSample::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad)
{
switch(evt)
{
case Gamepad::CONNECTED_EVENT:
case Gamepad::DISCONNECTED_EVENT:
_gamepad = getGamepad(0);
// This is needed because the virtual gamepad is shared between all samples.
// SamplesGame always ensures the virtual gamepad is disabled when a sample is exited.
if (_gamepad && _gamepad->isVirtual())
_gamepad->getForm()->setEnabled(true);
break;
}
}<commit_msg>fixed incorrect usage of %s format string<commit_after>#include "Audio3DSample.h"
#include "Grid.h"
#include "SamplesGame.h"
#if defined(ADD_SAMPLE)
ADD_SAMPLE("Media", "Audio 3D", Audio3DSample, 1);
#endif
static const unsigned int MOVE_FORWARD = 1;
static const unsigned int MOVE_BACKWARD = 2;
static const unsigned int MOVE_LEFT = 4;
static const unsigned int MOVE_RIGHT = 8;
static const unsigned int MOVE_UP = 16;
static const unsigned int MOVE_DOWN = 32;
static const float MOVE_SPEED = 15.0f;
static const float UP_DOWN_SPEED = 10.0f;
Audio3DSample::Audio3DSample()
: _font(NULL), _scene(NULL), _cubeNode(NULL), _gamepad(NULL), _moveFlags(0), _prevX(0), _prevY(0), _buttonPressed(false)
{
}
void Audio3DSample::initialize()
{
setMultiTouch(true);
_font = Font::create("res/ui/arial.gpb");
// Load game scene from file
_scene = Scene::load("res/common/box.gpb");
// Get light node
Node* lightNode = _scene->findNode("directionalLight1");
Light* light = lightNode->getLight();
lightNode->setRotation(Vector3(1, 0, 0), -MATH_DEG_TO_RAD(45));
// Initialize box model
Node* boxNode = _scene->findNode("box");
Model* boxModel = dynamic_cast<Model*>(boxNode->getDrawable());
Material* boxMaterial = boxModel->setMaterial("res/common/box.material#lambert1");
boxMaterial->getParameter("u_directionalLightColor[0]")->setValue(light->getColor());
boxMaterial->getParameter("u_directionalLightDirection[0]")->setValue(lightNode->getForwardVectorView());
// Remove the cube from the scene but keep a reference to it.
_cubeNode = boxNode;
_cubeNode->addRef();
_scene->removeNode(_cubeNode);
loadGrid(_scene);
// Initialize cameraa
Vector3 cameraPosition(5, 5, 1);
if (Camera* camera = _scene->getActiveCamera())
{
camera->getNode()->getTranslation(&cameraPosition);
}
_fpCamera.initialize();
_fpCamera.setPosition(cameraPosition);
_scene->addNode(_fpCamera.getRootNode());
_scene->setActiveCamera(_fpCamera.getCamera());
_gamepad = getGamepad(0);
// This is needed because the virtual gamepad is shared between all samples.
// SamplesGame always ensures the virtual gamepad is disabled when a sample is exited.
if (_gamepad && _gamepad->isVirtual())
_gamepad->getForm()->setEnabled(true);
}
void Audio3DSample::finalize()
{
SAFE_RELEASE(_scene);
SAFE_RELEASE(_font);
SAFE_RELEASE(_cubeNode);
for (std::map<std::string, Node*>::iterator it = _audioNodes.begin(); it != _audioNodes.end(); ++it)
{
it->second->release();
}
_audioNodes.clear();
}
void Audio3DSample::update(float elapsedTime)
{
float time = (float)elapsedTime / 1000.0f;
Vector2 move;
if (_moveFlags != 0)
{
// Forward motion
if (_moveFlags & MOVE_FORWARD)
{
move.y = 1;
}
else if (_moveFlags & MOVE_BACKWARD)
{
move.y = -1;
}
// Strafing
if (_moveFlags & MOVE_LEFT)
{
move.x = 1;
}
else if (_moveFlags & MOVE_RIGHT)
{
move.x = -1;
}
move.normalize();
// Up and down
if (_moveFlags & MOVE_UP)
{
_fpCamera.moveUp(time * UP_DOWN_SPEED);
}
else if (_moveFlags & MOVE_DOWN)
{
_fpCamera.moveDown(time * UP_DOWN_SPEED);
}
}
else if (_gamepad->getJoystickCount() > 0)
{
_gamepad->getJoystickValues(0, &move);
move.x = -move.x;
}
if (_gamepad->getJoystickCount() > 1)
{
Vector2 joy2;
_gamepad->getJoystickValues(1, &joy2);
_fpCamera.rotate(MATH_DEG_TO_RAD(joy2.x * 2.0f), MATH_DEG_TO_RAD(joy2.y * 2.0f));
}
if (!move.isZero())
{
move.scale(time * MOVE_SPEED);
_fpCamera.moveForward(move.y);
_fpCamera.moveLeft(move.x);
}
if (!_buttonPressed && _gamepad->isButtonDown(Gamepad::BUTTON_A))
{
addSound("footsteps.wav");
}
_buttonPressed = _gamepad->isButtonDown(Gamepad::BUTTON_A);
}
void Audio3DSample::render(float elapsedTime)
{
// Clear the color and depth buffers
clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0);
// Visit all the nodes in the scene for drawing
_scene->visit(this, &Audio3DSample::drawScene);
drawDebugText(5, 20, 18);
_gamepad->draw();
drawFrameRate(_font, Vector4(0, 0.5f, 1, 1), 5, 1, getFrameRate());
}
bool Audio3DSample::drawScene(Node* node)
{
Drawable* drawable = node->getDrawable();
if (drawable)
drawable->draw();
return true;
}
void Audio3DSample::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
switch (evt)
{
case Touch::TOUCH_PRESS:
{
if (x < 75 && y < 50)
{
// Toggle Vsync if the user touches the top left corner
setVsync(!isVsync());
}
_prevX = x;
_prevY = y;
break;
}
case Touch::TOUCH_RELEASE:
{
_prevX = 0;
_prevY = 0;
break;
}
case Touch::TOUCH_MOVE:
{
int deltaX = x - _prevX;
int deltaY = y - _prevY;
_prevX = x;
_prevY = y;
float pitch = -MATH_DEG_TO_RAD(deltaY * 0.5f);
float yaw = MATH_DEG_TO_RAD(deltaX * 0.5f);
_fpCamera.rotate(yaw, pitch);
break;
}
};
}
void Audio3DSample::keyEvent(Keyboard::KeyEvent evt, int key)
{
if (evt == Keyboard::KEY_PRESS)
{
switch (key)
{
case Keyboard::KEY_W:
_moveFlags |= MOVE_FORWARD;
break;
case Keyboard::KEY_S:
_moveFlags |= MOVE_BACKWARD;
break;
case Keyboard::KEY_A:
_moveFlags |= MOVE_LEFT;
break;
case Keyboard::KEY_D:
_moveFlags |= MOVE_RIGHT;
break;
case Keyboard::KEY_Q:
_moveFlags |= MOVE_DOWN;
break;
case Keyboard::KEY_E:
_moveFlags |= MOVE_UP;
break;
case Keyboard::KEY_PG_UP:
_fpCamera.rotate(0, MATH_PIOVER4);
break;
case Keyboard::KEY_PG_DOWN:
_fpCamera.rotate(0, -MATH_PIOVER4);
break;
case Keyboard::KEY_ONE:
case Keyboard::KEY_SPACE:
addSound("footsteps.wav");
break;
}
}
else if (evt == Keyboard::KEY_RELEASE)
{
switch (key)
{
case Keyboard::KEY_W:
_moveFlags &= ~MOVE_FORWARD;
break;
case Keyboard::KEY_S:
_moveFlags &= ~MOVE_BACKWARD;
break;
case Keyboard::KEY_A:
_moveFlags &= ~MOVE_LEFT;
break;
case Keyboard::KEY_D:
_moveFlags &= ~MOVE_RIGHT;
break;
case Keyboard::KEY_Q:
_moveFlags &= ~MOVE_DOWN;
break;
case Keyboard::KEY_E:
_moveFlags &= ~MOVE_UP;
break;
}
}
}
bool Audio3DSample::mouseEvent(Mouse::MouseEvent evt, int x, int y, float wheelDelta)
{
switch (evt)
{
case Mouse::MOUSE_WHEEL:
_fpCamera.moveForward(wheelDelta * MOVE_SPEED / 2.0f );
return true;
}
return false;
}
void Audio3DSample::addSound(const std::string& file)
{
std::string path("res/common/");
path.append(file);
Node* node = NULL;
std::map<std::string, Node*>::iterator it = _audioNodes.find(path);
if (it != _audioNodes.end())
{
node = it->second->clone();
}
else
{
AudioSource* audioSource = AudioSource::create(path.c_str());
assert(audioSource);
audioSource->setLooped(true);
node = _cubeNode->clone();
node->setId(file.c_str());
node->setAudioSource(audioSource);
audioSource->release();
_audioNodes[path] = node;
node->addRef();
}
assert(node);
Node* cameraNode = _scene->getActiveCamera()->getNode();
// Position the sound infront of the user
node->setTranslation(cameraNode->getTranslationWorld());
Vector3 dir = cameraNode->getForwardVectorWorld().normalize();
dir.scale(2);
node->translate(dir);
_scene->addNode(node);
node->getAudioSource()->play();
node->release();
}
void Audio3DSample::drawDebugText(int x, int y, unsigned int fontSize)
{
_font->start();
static const int V_SPACE = 16;
AudioListener* audioListener = AudioListener::getInstance();
drawVector3("Position", audioListener->getPosition(), x, y);
drawVector3("Forward", audioListener->getOrientationForward(), x, y += fontSize);
drawVector3("Orientation", audioListener->getOrientationUp(), x, y += fontSize);
drawVector3("Velocity", audioListener->getVelocity(), x, y += fontSize);
_font->finish();
}
void Audio3DSample::drawVector3(const char* str, const Vector3& vector, int x, int y)
{
wchar_t buffer[255];
swprintf(buffer, 255, L"%S: (%f, %f, %f)", str, vector.x, vector.y, vector.z);
_font->drawText(buffer, x, y, Vector4::one(), _font->getSize());
}
void Audio3DSample::loadGrid(Scene* scene)
{
assert(scene);
Model* gridModel = createGridModel();
assert(gridModel);
gridModel->setMaterial("res/common/grid.material");
Node* node = scene->addNode("grid");
node->setDrawable(gridModel);
SAFE_RELEASE(gridModel);
}
void Audio3DSample::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad)
{
switch(evt)
{
case Gamepad::CONNECTED_EVENT:
case Gamepad::DISCONNECTED_EVENT:
_gamepad = getGamepad(0);
// This is needed because the virtual gamepad is shared between all samples.
// SamplesGame always ensures the virtual gamepad is disabled when a sample is exited.
if (_gamepad && _gamepad->isVirtual())
_gamepad->getForm()->setEnabled(true);
break;
}
}<|endoftext|> |
<commit_before>#include "common.h"
#define GL_GLEXT_PROTOTYPES
#include "GLES/gl.h"
#include "GLES2/gl2.h"
#include <cstdlib> // EXIT_SUCCESS, etc
#include <cstdint> // uint8_t, etc
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "lodepng.h"
#include "json.hpp"
using json = nlohmann::json;
#define COMPILE_ERROR_EXIT_CODE (101)
#define LINK_ERROR_EXIT_CODE (102)
#define RENDER_ERROR_EXIT_CODE (103)
#define CHANNELS (4)
#define DELAY (2)
const float vertices[] = {
-1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f
};
const GLubyte indices[] = {
0, 1, 2,
2, 3, 0
};
const char* vertex_shader_wo_version =
"attribute vec2 vert2d;\n"
"void main(void) {\n"
" gl_Position = vec4(vert2d, 0.0, 1.0);\n"
"}";
bool readFile(const std::string& fileName, std::string& contentsOut) {
std::ifstream ifs(fileName.c_str());
if(!ifs) {
std::cerr << "File " << fileName << " not found" << std::endl;
return false;
}
std::stringstream ss;
ss << ifs.rdbuf();
contentsOut = ss.str();
return true;
}
void printProgramError(GLuint program) {
GLint length = 0;
glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);
// The maxLength includes the NULL character
std::vector<GLchar> errorLog((size_t) length, 0);
glGetShaderInfoLog(program, length, &length, &errorLog[0]);
if(length > 0) {
std::string s(&errorLog[0]);
std::cout << s << std::endl;
}
}
int checkForGLError(const char loc[]) {
GLenum res = glGetError();
if(res != GL_NO_ERROR) {
std::cerr << loc << ": glGetError: " << std::hex << res << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
#define CHECK_ERROR(loc) \
do { \
if(checkForGLError(loc) == EXIT_FAILURE) { \
return EXIT_FAILURE; \
} \
} while(false)
int render(
EGLDisplay display,
EGLSurface surface,
int width,
int height,
bool animate,
int numFrames,
bool& saved,
const std::string& output,
GLint resolutionLocation,
GLint timeLocation) {
glViewport(0, 0, width, height);
CHECK_ERROR("After glViewport");
if(resolutionLocation != -1) {
glUniform2f(resolutionLocation, width, height);
CHECK_ERROR("After glUniform2f");
}
if(animate && timeLocation != -1 && numFrames > DELAY) {
glUniform1f(timeLocation, numFrames / 10.0f);
CHECK_ERROR("After glUniform1f");
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
CHECK_ERROR("After glClearColor");
glClear(GL_COLOR_BUFFER_BIT);
CHECK_ERROR("After glClear");
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);
CHECK_ERROR("After glDrawElements");
glFlush();
CHECK_ERROR("After glFlush");
eglSwapBuffers(display, surface);
CHECK_ERROR("After swapBuffers");
return EXIT_SUCCESS;
}
int setUniformsFromJSON(const std::string& jsonFilename, const GLuint& program) {
std::string jsonContent;
if (!readFile(jsonFilename, jsonContent)) {
return EXIT_FAILURE;
}
json j = json::parse(jsonContent);
for (json::iterator it = j.begin(); it != j.end(); ++it) {
std::string uniformName = it.key();
json uniformInfo = it.value();
// Check presence of func and args entries
if (uniformInfo.find("func") == uniformInfo.end()) {
std::cerr << "Error: malformed JSON: no \"func\" entry for uniform: " << uniformName << std::endl;
return EXIT_FAILURE;
}
if (uniformInfo.find("args") == uniformInfo.end()) {
std::cerr << "Error: malformed JSON: no \"args\" entry for uniform: " << uniformName << std::endl;
return EXIT_FAILURE;
}
// Get uniform location
GLint uniformLocation = glGetUniformLocation(program, uniformName.c_str());
CHECK_ERROR("After glGetUniformLocation");
if (uniformLocation == -1) {
std::cerr << "Warning: Cannot find uniform named: " << uniformName << std::endl;
continue;
}
// Dispatch to matching init function
std::string uniformFunc = uniformInfo["func"];
json args = uniformInfo["args"];
// TODO: check that args has the good number of fields and type
if (uniformFunc == "glUniform1f") {
glUniform1f(uniformLocation, args[0]);
} else if (uniformFunc == "glUniform2f") {
glUniform2f(uniformLocation, args[0], args[1]);
} else if (uniformFunc == "glUniform3f") {
glUniform3f(uniformLocation, args[0], args[1], args[2]);
} else if (uniformFunc == "glUniform4f") {
glUniform4f(uniformLocation, args[0], args[1], args[2], args[3]);
}
else if (uniformFunc == "glUniform1i") {
glUniform1i(uniformLocation, args[0]);
} else if (uniformFunc == "glUniform2i") {
glUniform2i(uniformLocation, args[0], args[1]);
} else if (uniformFunc == "glUniform3i") {
glUniform3i(uniformLocation, args[0], args[1], args[2]);
} else if (uniformFunc == "glUniform4i") {
glUniform4i(uniformLocation, args[0], args[1], args[2], args[3]);
}
else {
std::cerr << "Error: unknown uniform init func: " << uniformFunc << std::endl;
return EXIT_FAILURE;
}
CHECK_ERROR("After uniform initialisation");
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[]) {
EGLDisplay display = 0;
EGLConfig config = 0;
EGLContext context = 0;
EGLSurface surface = 0;
const int width = 640;
const int height = 480;
bool res = init_gl(
width,
height,
display,
config,
context,
surface
);
if(!res) {
return EXIT_FAILURE;
}
bool persist = false;
bool animate = false;
bool exit_compile = false;
bool exit_linking = false;
std::string output("output.png");
std::string vertex_shader;
std::string fragment_shader;
for(int i = 1; i < argc; i++) {
std::string curr_arg = std::string(argv[i]);
if(!curr_arg.compare(0, 2, "--")) {
if(curr_arg == "--persist") {
persist = true;
continue;
}
else if(curr_arg == "--animate") {
animate = true;
continue;
}
else if(curr_arg == "--exit_compile") {
exit_compile = true;
continue;
}
else if(curr_arg == "--exit_linking") {
exit_linking = true;
continue;
}
else if(curr_arg == "--output") {
output = argv[++i];
continue;
}
else if(curr_arg == "--vertex") {
vertex_shader = argv[++i];
continue;
}
std::cerr << "Unknown argument " << curr_arg << std::endl;
continue;
}
if (fragment_shader.length() == 0) {
fragment_shader = curr_arg;
} else {
std::cerr << "Ignoring extra argument " << curr_arg << std::endl;
}
}
if(fragment_shader.length() == 0) {
std::cerr << "Requires fragment shader argument!" << std::endl;
return EXIT_FAILURE;
}
GLuint program = glCreateProgram();
int compileOk = 0;
const char* temp;
std::string fragContents;
if(!readFile(fragment_shader, fragContents)) {
return EXIT_FAILURE;
}
temp = fragContents.c_str();
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &temp, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compileOk);
if (!compileOk) {
std::cerr << "Error compiling fragment shader." << std::endl;
printProgramError(program);
return COMPILE_ERROR_EXIT_CODE;
}
std::cerr << "Fragment shader compiled successfully." << std::endl;
if (exit_compile) {
std::cout << "Exiting after fragment shader compilation." << std::endl;
return EXIT_SUCCESS;
}
glAttachShader(program, fragmentShader);
std::string vertexContents;
if(vertex_shader.length() == 0) {
// Use embedded vertex shader.
std::stringstream ss;
size_t i = fragContents.find('\n');
if(i != std::string::npos && fragContents[0] == '#') {
ss << fragContents.substr(0,i);
ss << "\n";
} else {
std::cerr << "Warning: Could not find #version string of fragment shader." << std::endl;
}
ss << vertex_shader_wo_version;
vertexContents = ss.str();
} else {
if(!readFile(vertex_shader, vertexContents)) {
return EXIT_FAILURE;
}
}
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
temp = vertexContents.c_str();
glShaderSource(vertexShader, 1, &temp, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compileOk);
if (!compileOk) {
std::cerr << "Error compiling vertex shader." << std::endl;
printProgramError(program);
return EXIT_FAILURE;
}
std::cerr << "Vertex shader compiled successfully." << std::endl;
glAttachShader(program, vertexShader);
std::cerr << "Linking program." << std::endl;
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &compileOk);
if (!compileOk) {
std::cerr << "Error in linking program." << std::endl;
printProgramError(program);
return LINK_ERROR_EXIT_CODE;
}
std::cerr << "Program linked successfully." << std::endl;
if (exit_linking) {
std::cout << "Exiting after program linking." << std::endl;
return EXIT_SUCCESS;
}
GLint posAttribLocationAttempt = glGetAttribLocation(program, "vert2d");
if(posAttribLocationAttempt == -1) {
std::cerr << "Error getting vert2d attribute location." << std::endl;
return EXIT_FAILURE;
}
GLuint posAttribLocation = (GLuint) posAttribLocationAttempt;
glEnableVertexAttribArray(posAttribLocation);
glUseProgram(program);
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint indicesBuffer;
glGenBuffers(1, &indicesBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
GLint injectionSwitchLocation = glGetUniformLocation(program, "injectionSwitch");
GLint timeLocation = glGetUniformLocation(program, "time");
GLint mouseLocation = glGetUniformLocation(program, "mouse");
GLint resolutionLocation = glGetUniformLocation(program, "resolution");
if(injectionSwitchLocation != -1) {
glUniform2f(injectionSwitchLocation, 0.0f, 1.0f);
}
if(mouseLocation != -1) {
glUniform2f(mouseLocation, 0.0f, 0.0f);
}
if(timeLocation != -1) {
glUniform1f(timeLocation, 0.0f);
}
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(posAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
std::string jsonFilename(fragment_shader);
jsonFilename.replace(jsonFilename.end()-4, jsonFilename.end(), "json");
int result = setUniformsFromJSON(jsonFilename, program);
if(result != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
std::cerr << "Uniforms set successfully." << std::endl;
int numFrames = 0;
bool saved = false;
result = render(
display,
surface,
width,
height,
animate,
numFrames,
saved,
output,
resolutionLocation,
timeLocation);
if(result != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
// ++numFrames;
// if(numFrames == DELAY && !saved) {
std::cerr << "Capturing frame." << std::endl;
saved = true;
unsigned uwidth = (unsigned int) width;
unsigned uheight = (unsigned int) height;
std::vector<std::uint8_t> data(uwidth * uheight * CHANNELS);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
CHECK_ERROR("After glReadPixels");
std::vector<std::uint8_t> flipped_data(uwidth * uheight * CHANNELS);
for (unsigned int h = 0; h < uheight ; h++)
for (unsigned int col = 0; col < uwidth * CHANNELS; col++)
flipped_data[h * uwidth * CHANNELS + col] =
data[(uheight - h - 1) * uwidth * CHANNELS + col];
unsigned png_error = lodepng::encode(output, flipped_data, uwidth, uheight);
if (png_error) {
std::cerr << "Error producing PNG file: " << lodepng_error_text(png_error) << std::endl;
return EXIT_FAILURE;
}
if (!persist) {
return EXIT_SUCCESS;
}
// }
return EXIT_SUCCESS;
}
<commit_msg>Add support for glUniformXfv and glUniformXiv<commit_after>#include "common.h"
#define GL_GLEXT_PROTOTYPES
#include "GLES/gl.h"
#include "GLES2/gl2.h"
#include <cstdlib> // EXIT_SUCCESS, etc
#include <cstdint> // uint8_t, etc
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "lodepng.h"
#include "json.hpp"
using json = nlohmann::json;
#define COMPILE_ERROR_EXIT_CODE (101)
#define LINK_ERROR_EXIT_CODE (102)
#define RENDER_ERROR_EXIT_CODE (103)
#define CHANNELS (4)
#define DELAY (2)
const float vertices[] = {
-1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f
};
const GLubyte indices[] = {
0, 1, 2,
2, 3, 0
};
const char* vertex_shader_wo_version =
"attribute vec2 vert2d;\n"
"void main(void) {\n"
" gl_Position = vec4(vert2d, 0.0, 1.0);\n"
"}";
bool readFile(const std::string& fileName, std::string& contentsOut) {
std::ifstream ifs(fileName.c_str());
if(!ifs) {
std::cerr << "File " << fileName << " not found" << std::endl;
return false;
}
std::stringstream ss;
ss << ifs.rdbuf();
contentsOut = ss.str();
return true;
}
void printProgramError(GLuint program) {
GLint length = 0;
glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);
// The maxLength includes the NULL character
std::vector<GLchar> errorLog((size_t) length, 0);
glGetShaderInfoLog(program, length, &length, &errorLog[0]);
if(length > 0) {
std::string s(&errorLog[0]);
std::cout << s << std::endl;
}
}
int checkForGLError(const char loc[]) {
GLenum res = glGetError();
if(res != GL_NO_ERROR) {
std::cerr << loc << ": glGetError: " << std::hex << res << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
#define CHECK_ERROR(loc) \
do { \
if(checkForGLError(loc) == EXIT_FAILURE) { \
return EXIT_FAILURE; \
} \
} while(false)
int render(
EGLDisplay display,
EGLSurface surface,
int width,
int height,
bool animate,
int numFrames,
bool& saved,
const std::string& output,
GLint resolutionLocation,
GLint timeLocation) {
glViewport(0, 0, width, height);
CHECK_ERROR("After glViewport");
if(resolutionLocation != -1) {
glUniform2f(resolutionLocation, width, height);
CHECK_ERROR("After glUniform2f");
}
if(animate && timeLocation != -1 && numFrames > DELAY) {
glUniform1f(timeLocation, numFrames / 10.0f);
CHECK_ERROR("After glUniform1f");
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
CHECK_ERROR("After glClearColor");
glClear(GL_COLOR_BUFFER_BIT);
CHECK_ERROR("After glClear");
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);
CHECK_ERROR("After glDrawElements");
glFlush();
CHECK_ERROR("After glFlush");
eglSwapBuffers(display, surface);
CHECK_ERROR("After swapBuffers");
return EXIT_SUCCESS;
}
template<typename T>
T *getArray(const json& j) {
T *a = new T[j.size()];
for (int i = 0; i < j.size(); i++) {
a[i] = j[i];
}
return a;
}
#define GLUNIFORM_ARRAYINIT(funcname, uniformloc, gltype, jsonarray) \
gltype *a = getArray<gltype>(jsonarray.size()); \
funcname(uniformloc, jsonarray.size(), a); \
delete [] a
int setUniformsFromJSON(const std::string& jsonFilename, const GLuint& program) {
std::string jsonContent;
if (!readFile(jsonFilename, jsonContent)) {
return EXIT_FAILURE;
}
json j = json::parse(jsonContent);
for (json::iterator it = j.begin(); it != j.end(); ++it) {
std::string uniformName = it.key();
json uniformInfo = it.value();
// Check presence of func and args entries
if (uniformInfo.find("func") == uniformInfo.end()) {
std::cerr << "Error: malformed JSON: no \"func\" entry for uniform: " << uniformName << std::endl;
return EXIT_FAILURE;
}
if (uniformInfo.find("args") == uniformInfo.end()) {
std::cerr << "Error: malformed JSON: no \"args\" entry for uniform: " << uniformName << std::endl;
return EXIT_FAILURE;
}
// Get uniform location
GLint uniformLocation = glGetUniformLocation(program, uniformName.c_str());
CHECK_ERROR("After glGetUniformLocation");
if (uniformLocation == -1) {
std::cerr << "Warning: Cannot find uniform named: " << uniformName << std::endl;
continue;
}
// Dispatch to matching init function
std::string uniformFunc = uniformInfo["func"];
json args = uniformInfo["args"];
// TODO: check that args has the good number of fields and type
if (uniformFunc == "glUniform1f") {
glUniform1f(uniformLocation, args[0]);
} else if (uniformFunc == "glUniform2f") {
glUniform2f(uniformLocation, args[0], args[1]);
} else if (uniformFunc == "glUniform3f") {
glUniform3f(uniformLocation, args[0], args[1], args[2]);
} else if (uniformFunc == "glUniform4f") {
glUniform4f(uniformLocation, args[0], args[1], args[2], args[3]);
}
else if (uniformFunc == "glUniform1i") {
glUniform1i(uniformLocation, args[0]);
} else if (uniformFunc == "glUniform2i") {
glUniform2i(uniformLocation, args[0], args[1]);
} else if (uniformFunc == "glUniform3i") {
glUniform3i(uniformLocation, args[0], args[1], args[2]);
} else if (uniformFunc == "glUniform4i") {
glUniform4i(uniformLocation, args[0], args[1], args[2], args[3]);
}
// Note: no "glUniformXui" variant in OpenGL ES
// else if (uniformFunc == "glUniform1ui") {
// glUniform1ui(uniformLocation, args[0]);
// } else if (uniformFunc == "glUniform2ui") {
// glUniform2ui(uniformLocation, args[0], args[1]);
// } else if (uniformFunc == "glUniform3ui") {
// glUniform3ui(uniformLocation, args[0], args[1], args[2]);
// } else if (uniformFunc == "glUniform4ui") {
// glUniform4ui(uniformLocation, args[0], args[1], args[2], args[3]);
// }
else if (uniformFunc == "glUniform1fv") {
GLUNIFORM_ARRAYINIT(glUniform1fv, uniformLocation, GLfloat, args);
} else if (uniformFunc == "glUniform2fv") {
GLUNIFORM_ARRAYINIT(glUniform2fv, uniformLocation, GLfloat, args);
} else if (uniformFunc == "glUniform3fv") {
GLUNIFORM_ARRAYINIT(glUniform3fv, uniformLocation, GLfloat, args);
} else if (uniformFunc == "glUniform4fv") {
GLUNIFORM_ARRAYINIT(glUniform4fv, uniformLocation, GLfloat, args);
}
else if (uniformFunc == "glUniform1iv") {
GLUNIFORM_ARRAYINIT(glUniform1iv, uniformLocation, GLint, args);
} else if (uniformFunc == "glUniform2iv") {
GLUNIFORM_ARRAYINIT(glUniform2iv, uniformLocation, GLint, args);
} else if (uniformFunc == "glUniform3iv") {
GLUNIFORM_ARRAYINIT(glUniform3iv, uniformLocation, GLint, args);
} else if (uniformFunc == "glUniform4iv") {
GLUNIFORM_ARRAYINIT(glUniform4iv, uniformLocation, GLint, args);
}
else {
std::cerr << "Error: unknown uniform init func: " << uniformFunc << std::endl;
return EXIT_FAILURE;
}
CHECK_ERROR("After uniform initialisation");
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[]) {
EGLDisplay display = 0;
EGLConfig config = 0;
EGLContext context = 0;
EGLSurface surface = 0;
const int width = 640;
const int height = 480;
bool res = init_gl(
width,
height,
display,
config,
context,
surface
);
if(!res) {
return EXIT_FAILURE;
}
bool persist = false;
bool animate = false;
bool exit_compile = false;
bool exit_linking = false;
std::string output("output.png");
std::string vertex_shader;
std::string fragment_shader;
for(int i = 1; i < argc; i++) {
std::string curr_arg = std::string(argv[i]);
if(!curr_arg.compare(0, 2, "--")) {
if(curr_arg == "--persist") {
persist = true;
continue;
}
else if(curr_arg == "--animate") {
animate = true;
continue;
}
else if(curr_arg == "--exit_compile") {
exit_compile = true;
continue;
}
else if(curr_arg == "--exit_linking") {
exit_linking = true;
continue;
}
else if(curr_arg == "--output") {
output = argv[++i];
continue;
}
else if(curr_arg == "--vertex") {
vertex_shader = argv[++i];
continue;
}
std::cerr << "Unknown argument " << curr_arg << std::endl;
continue;
}
if (fragment_shader.length() == 0) {
fragment_shader = curr_arg;
} else {
std::cerr << "Ignoring extra argument " << curr_arg << std::endl;
}
}
if(fragment_shader.length() == 0) {
std::cerr << "Requires fragment shader argument!" << std::endl;
return EXIT_FAILURE;
}
GLuint program = glCreateProgram();
int compileOk = 0;
const char* temp;
std::string fragContents;
if(!readFile(fragment_shader, fragContents)) {
return EXIT_FAILURE;
}
temp = fragContents.c_str();
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &temp, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compileOk);
if (!compileOk) {
std::cerr << "Error compiling fragment shader." << std::endl;
printProgramError(program);
return COMPILE_ERROR_EXIT_CODE;
}
std::cerr << "Fragment shader compiled successfully." << std::endl;
if (exit_compile) {
std::cout << "Exiting after fragment shader compilation." << std::endl;
return EXIT_SUCCESS;
}
glAttachShader(program, fragmentShader);
std::string vertexContents;
if(vertex_shader.length() == 0) {
// Use embedded vertex shader.
std::stringstream ss;
size_t i = fragContents.find('\n');
if(i != std::string::npos && fragContents[0] == '#') {
ss << fragContents.substr(0,i);
ss << "\n";
} else {
std::cerr << "Warning: Could not find #version string of fragment shader." << std::endl;
}
ss << vertex_shader_wo_version;
vertexContents = ss.str();
} else {
if(!readFile(vertex_shader, vertexContents)) {
return EXIT_FAILURE;
}
}
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
temp = vertexContents.c_str();
glShaderSource(vertexShader, 1, &temp, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compileOk);
if (!compileOk) {
std::cerr << "Error compiling vertex shader." << std::endl;
printProgramError(program);
return EXIT_FAILURE;
}
std::cerr << "Vertex shader compiled successfully." << std::endl;
glAttachShader(program, vertexShader);
std::cerr << "Linking program." << std::endl;
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &compileOk);
if (!compileOk) {
std::cerr << "Error in linking program." << std::endl;
printProgramError(program);
return LINK_ERROR_EXIT_CODE;
}
std::cerr << "Program linked successfully." << std::endl;
if (exit_linking) {
std::cout << "Exiting after program linking." << std::endl;
return EXIT_SUCCESS;
}
GLint posAttribLocationAttempt = glGetAttribLocation(program, "vert2d");
if(posAttribLocationAttempt == -1) {
std::cerr << "Error getting vert2d attribute location." << std::endl;
return EXIT_FAILURE;
}
GLuint posAttribLocation = (GLuint) posAttribLocationAttempt;
glEnableVertexAttribArray(posAttribLocation);
glUseProgram(program);
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint indicesBuffer;
glGenBuffers(1, &indicesBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
GLint injectionSwitchLocation = glGetUniformLocation(program, "injectionSwitch");
GLint timeLocation = glGetUniformLocation(program, "time");
GLint mouseLocation = glGetUniformLocation(program, "mouse");
GLint resolutionLocation = glGetUniformLocation(program, "resolution");
if(injectionSwitchLocation != -1) {
glUniform2f(injectionSwitchLocation, 0.0f, 1.0f);
}
if(mouseLocation != -1) {
glUniform2f(mouseLocation, 0.0f, 0.0f);
}
if(timeLocation != -1) {
glUniform1f(timeLocation, 0.0f);
}
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(posAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
std::string jsonFilename(fragment_shader);
jsonFilename.replace(jsonFilename.end()-4, jsonFilename.end(), "json");
int result = setUniformsFromJSON(jsonFilename, program);
if(result != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
std::cerr << "Uniforms set successfully." << std::endl;
int numFrames = 0;
bool saved = false;
result = render(
display,
surface,
width,
height,
animate,
numFrames,
saved,
output,
resolutionLocation,
timeLocation);
if(result != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
// ++numFrames;
// if(numFrames == DELAY && !saved) {
std::cerr << "Capturing frame." << std::endl;
saved = true;
unsigned uwidth = (unsigned int) width;
unsigned uheight = (unsigned int) height;
std::vector<std::uint8_t> data(uwidth * uheight * CHANNELS);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
CHECK_ERROR("After glReadPixels");
std::vector<std::uint8_t> flipped_data(uwidth * uheight * CHANNELS);
for (unsigned int h = 0; h < uheight ; h++)
for (unsigned int col = 0; col < uwidth * CHANNELS; col++)
flipped_data[h * uwidth * CHANNELS + col] =
data[(uheight - h - 1) * uwidth * CHANNELS + col];
unsigned png_error = lodepng::encode(output, flipped_data, uwidth, uheight);
if (png_error) {
std::cerr << "Error producing PNG file: " << lodepng_error_text(png_error) << std::endl;
return EXIT_FAILURE;
}
if (!persist) {
return EXIT_SUCCESS;
}
// }
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file point_set.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__FILTER__GAUSSIAN__POINT_SET_HPP
#define FL__FILTER__GAUSSIAN__POINT_SET_HPP
#include <map>
#include <cmath>
#include <type_traits>
#include <Eigen/Dense>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/exception/exception.hpp>
#include <fl/filter/filter_interface.hpp>
/** \cond internal */
/**
* Checks dimensions
*/
#define INLINE_CHECK_POINT_SET_DIMENSIONS() \
assert(points_.cols() == int(weights_.size())); \
if (points_.rows() == 0) \
{ \
fl_throw(ZeroDimensionException("PointSet")); \
} \
if (points_.cols() == 0) \
{ \
fl_throw(Exception("PointSet contains no points.")); \
}
/**
* Checks for index out of bounds and valid dimensions
*/
#define INLINE_CHECK_POINT_SET_BOUNDS(i) \
if (i >= int(weights_.size())) \
{ \
fl_throw(OutOfBoundsException(i, weights_.size())); \
} \
INLINE_CHECK_POINT_SET_DIMENSIONS();
/** \endcond */
namespace fl
{
// Forward declaration
template <typename Point, int Points_> class PointSet;
/**
* Trait struct of a PointSet
*/
template <typename Point_, int Points_>
struct Traits<PointSet<Point_, Points_>>
{
/**
* \brief Point type
*/
typedef Point_ Point;
/**
* \brief Number of points for fixed-size set
*/
enum
{
/**
* \brief Number of points which provided by the PointSet.
*
* If the number of points is unknown and there for dynamic, then
* NumberOfPoints is set to Eigen::Dynamic
*/
NumberOfPoints = IsFixed<Points_>() ? Points_ : Eigen::Dynamic
};
/**
* \brief Weight harbors the weights of a point. For each of the first two
* moments there is a separate weight.
*
*
* Generally a single weight suffices. However, some transforms utilize
* different weights for each moment to select a set of points representing
* the underlying moments.
*/
struct Weight
{
/**
* First moment (mean) point weight
*/
double w_mean;
/**
* Second centered moment (covariance) point weight
*/
double w_cov;
};
/**
* \brief Point container type
*
* \details
* The point container type has a fixed-size dimension of a point
* and the number of the points is statically known.
*/
typedef Eigen::Matrix<
typename Point::Scalar,
Point::RowsAtCompileTime,
Points_
> PointMatrix;
/**
* \brief WeightVector
*/
typedef Eigen::Matrix<
typename Point::Scalar,
Points_,
1
> WeightVector;
/**
* \brief Weight list of all points
*/
typedef Eigen::Array<Weight, Points_, 1> Weights;
};
/**
* \class PointSet
*
* \ingroup nonlinear_gaussian_filter
*
* PointSet represents a container of fixed-size or dynamic-size points each
* paired with a set of weights. PointSet has two degree-of-freedoms. The first
* is the dimension of the points. The second is the number of points within the
* set. Each of the parameter can either be fixed at compile time or left
* unspecified. That is, the parameter is set to Eigen::Dynamic.
*
* \tparam Point Gaussian variable type
* \tparam Points_ Number of points representing the gaussian
*/
template <typename Point_, int Points_ = -1>
class PointSet
{
private:
/** Typdef of \c This for #from_traits(TypeName) helper */
typedef PointSet<Point_, Points_> This;
public:
typedef from_traits(Point);
typedef from_traits(PointMatrix);
typedef from_traits(Weight);
typedef from_traits(Weights);
typedef from_traits(WeightVector);
public:
/**
* Creates a PointSet
*
* \param points_count Number of points representing the Gaussian
* \param dimension Sample space dimension
*/
PointSet(int dimension,
int points_count = ToDimension<Points_>())
: points_(dimension, points_count),
weights_(points_count, 1)
{
assert(points_count >= 0);
static_assert(Points_ >= Eigen::Dynamic, "Invalid point count");
points_.setZero();
double weight = (points_count > 0) ? 1./double(points_count) : 0;
weights_.fill(Weight{weight, weight});
}
/**
* Creates a PointSet
*/
PointSet()
{
points_.setZero();
double weight = (weights_.size() > 0) ? 1./double(weights_.size()) : 0;
weights_.fill(Weight{weight, weight});
}
/**
* \brief Overridable default destructor
*/
virtual ~PointSet() { }
/**
* Resizes a dynamic-size PointSet
*
* \param Points_ Number of points
*
* \throws ResizingFixedSizeEntityException
*/
void resize(int points_count)
{
if (int(weights_.size()) == points_count &&
int(points_.cols()) == points_count) return;
if (IsFixed<Points_>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(weights_.size(),
points_count,
"poit set Gaussian"));
}
points_.setZero(points_.rows(), points_count);
weights_.resize(points_count, 1);
const double weight = (points_count > 0)? 1. / double(points_count) : 0;
for (int i = 0; i < points_count; ++i)
{
weights_(i).w_mean = weight;
weights_(i).w_cov = weight;
}
// std::fill(weights_.begin(), weights_.end(), Weight{weight, weight});
}
/**
* Resizes a dynamic-size PointSet
*
* \param Points_ Number of points
*
* \throws ResizingFixedSizeEntityException
*/
void resize(int dim, int points_count)
{
if (dim == dimension() && points_count == count_points()) return;
points_.setZero(dim, points_count);
weights_.resize(points_count, 1);
const double weight = (points_count > 0)? 1. / double(points_count) : 0;
for (int i = 0; i < points_count; ++i)
{
weights_(i).w_mean = weight;
weights_(i).w_cov = weight;
}
}
/**
* Sets the new dimension for dynamic-size points (not to confuse
* with the number of points)
*
* \param dim Dimension of each point
*/
void dimension(int dim)
{
points_.resize(dim, count_points());
}
/**
* \return Dimension of containing points
*/
int dimension() const
{
return points_.rows();
}
/**
* \return The number of points
*/
int count_points() const
{
return points_.cols();
}
/**
* \return read only access on i-th point
*
* \param i Index of requested point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
Point point(int i) const
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
return points_.col(i);
}
auto operator[](int i) -> decltype(PointMatrix().col(i))
{
return points_.col(i);
}
/**
* \return weight of i-th point assuming both weights are the same
*
* \param i Index of requested point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
double weight(int i)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
return weights_(i).w_mean;
}
/**
* \return weights of i-th point
*
* \param i Index of requested point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
const Weight& weights(int i) const
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
return weights_(i);
}
/**
* \return Point matrix (read only)
*/
const PointMatrix& points() const noexcept
{
return points_;
}
/**
* \return Point matrix
*/
PointMatrix& points()
{
return points_;
}
/**
* \return point weights vector
*/
const Weights& weights() const noexcept
{
return weights_;
}
/**
* \return Returns the weights for the mean of the points as a vector
*/
WeightVector mean_weights_vector() const noexcept
{
const int point_count = count_points();
WeightVector weight_vec(point_count);
for (int i = 0; i < point_count; ++i)
{
weight_vec(i) = weights_(i).w_mean;
}
return weight_vec;
}
/**
* \return Returns the weights for the covariance of the points as a vector
*/
WeightVector covariance_weights_vector() const noexcept
{
const int point_count = count_points();
WeightVector weight_vec(point_count);
for (int i = 0; i < point_count; ++i)
{
weight_vec(i) = weights_(i).w_cov;
}
return weight_vec;
}
/**
* Sets the given point matrix
*/
void points(const PointMatrix& point_matrix)
{
points_ = point_matrix;
}
/**
* Sets a given point at position i
*
* \param i Index of point
* \param p The new point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
points_.col(i) = p;
}
/**
* Sets a given point at position i along with its weights
*
* \param i Index of point
* \param p The new point
* \param w Point weights. The weights determinaing the first two
* moments are the same
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p, double w)
{
point(i, p, Weight{w, w});
}
/**
* Sets a given point at position i along with its weights
*
* \param i Index of point
* \param p The new point
* \param w_mean point weight used to compute the first moment
* \param w_cov point weight used to compute the second centered moment
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p, double w_mean , double w_cov)
{
point(i, p, Weight{w_mean, w_cov});
}
/**
* Sets a given point at given position i along with its weights
*
* \param i Index of point
* \param p The new point
* \param weights point weights
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p, Weight weights)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
points_.col(i) = p;
weights_(i) = weights;
}
/**
* Sets a given weight of a point at position i
*
* \param i Index of point
* \param w Point weights. The weights determinaing the first two
* moments are the same
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void weight(int i, double w)
{
weight(i, Weight{w, w});
}
/**
* Sets given weights of a point at position i
*
* \param i Index of point
* \param w_mean point weight used to compute the first moment
* \param w_cov point weight used to compute the second centered moment
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void weight(int i, double w_mean , double w_cov)
{
weight(i, Weight{w_mean, w_cov});
}
/**
* Sets given weights of a point at position i
*
* \param i Index of point
* \param weights point weights
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void weight(int i, Weight weights)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
weights_(i) = weights;
}
/**
* \return Centered points matrix.
*
* Creates a PointMatrix populated with zero mean points
*
* \throws ZeroDimensionException
* \throws Exception
*/
PointMatrix centered_points() const
{
INLINE_CHECK_POINT_SET_DIMENSIONS();
PointMatrix centered(points_.rows(), points_.cols());
const Point weighted_mean = mean();
const int point_count = points_.cols();
for (int i = 0; i < point_count; ++i)
{
centered.col(i) = points_.col(i) - weighted_mean;
}
return centered;
}
Point center()
{
const Point weighted_mean = mean();
const int point_count = points_.cols();
for (int i = 0; i < point_count; ++i)
{
points_.col(i) -= weighted_mean;
}
return weighted_mean;
}
/**
* \return The weighted mean of all points
*
* \throws ZeroDimensionException
* \throws Exception
*/
Point mean() const
{
INLINE_CHECK_POINT_SET_DIMENSIONS();
Point weighted_mean;
weighted_mean.setZero(points_.rows());
const int point_count = points_.cols();
for (int i = 0; i < point_count; ++i)
{
weighted_mean += weights_(i).w_mean * points_.col(i);
}
return weighted_mean;
}
protected:
/**
* \brief point container
*/
PointMatrix points_;
/**
* \brief weight container
*/
Weights weights_;
};
}
#endif
<commit_msg>Doc updates<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file point_set.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__FILTER__GAUSSIAN__POINT_SET_HPP
#define FL__FILTER__GAUSSIAN__POINT_SET_HPP
#include <map>
#include <cmath>
#include <type_traits>
#include <Eigen/Dense>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/exception/exception.hpp>
#include <fl/filter/filter_interface.hpp>
/** \cond internal */
/**
* Checks dimensions
*/
#define INLINE_CHECK_POINT_SET_DIMENSIONS() \
assert(points_.cols() == int(weights_.size())); \
if (points_.rows() == 0) \
{ \
fl_throw(ZeroDimensionException("PointSet")); \
} \
if (points_.cols() == 0) \
{ \
fl_throw(Exception("PointSet contains no points.")); \
}
/**
* Checks for index out of bounds and valid dimensions
*/
#define INLINE_CHECK_POINT_SET_BOUNDS(i) \
if (i >= int(weights_.size())) \
{ \
fl_throw(OutOfBoundsException(i, weights_.size())); \
} \
INLINE_CHECK_POINT_SET_DIMENSIONS();
/** \endcond */
namespace fl
{
// Forward declaration
template <typename Point, int Points_> class PointSet;
/**
* Trait struct of a PointSet
*/
template <typename Point_, int Points_>
struct Traits<PointSet<Point_, Points_>>
{
/**
* \brief Point type
*/
typedef Point_ Point;
/**
* \brief Number of points for fixed-size set
*/
enum
{
/**
* \brief Number of points which provided by the PointSet.
*
* If the number of points is unknown and there for dynamic, then
* NumberOfPoints is set to Eigen::Dynamic
*/
NumberOfPoints = IsFixed<Points_>() ? Points_ : Eigen::Dynamic
};
/**
* \brief Weight harbors the weights of a point. For each of the first two
* moments there is a separate weight.
*
*
* Generally a single weight suffices. However, some transforms utilize
* different weights for each moment to select a set of points representing
* the underlying moments.
*/
struct Weight
{
/**
* First moment (mean) point weight
*/
double w_mean;
/**
* Second centered moment (covariance) point weight
*/
double w_cov;
};
/**
* \brief Point container type
*
* \details
* The point container type has a fixed-size dimension of a point
* and the number of the points is statically known.
*/
typedef Eigen::Matrix<
typename Point::Scalar,
Point::RowsAtCompileTime,
Points_
> PointMatrix;
/**
* \brief WeightVector
*/
typedef Eigen::Matrix<
typename Point::Scalar,
Points_,
1
> WeightVector;
/**
* \brief Weight list of all points
*/
typedef Eigen::Array<Weight, Points_, 1> Weights;
};
/**
* \ingroup nonlinear_gaussian_filter
*
* \brief PointSet represents a container of fixed-size or dynamic-size points each
* paired with a set of weights.
*
* PointSet has two degree-of-freedoms. The first
* is the dimension of the points. The second is the number of points within the
* set. Each of the parameter can either be fixed at compile time or left
* unspecified. That is, the parameter is set to Eigen::Dynamic.
*
* \tparam Point Gaussian variable type
* \tparam Points_ Number of points representing the gaussian
*/
template <typename Point_, int Points_ = -1>
class PointSet
{
private:
/** \brief Typdef of \c This for #from_traits(TypeName) helper */
typedef PointSet<Point_, Points_> This;
public:
typedef from_traits(Point);
typedef from_traits(PointMatrix);
typedef from_traits(Weight);
typedef from_traits(Weights);
typedef from_traits(WeightVector);
public:
/**
* \brief Creates a PointSet
*
* \param points_count Number of points representing the Gaussian
* \param dimension Sample space dimension
*/
PointSet(int dimension,
int points_count = ToDimension<Points_>())
: points_(dimension, points_count),
weights_(points_count, 1)
{
assert(points_count >= 0);
static_assert(Points_ >= Eigen::Dynamic, "Invalid point count");
points_.setZero();
double weight = (points_count > 0) ? 1./double(points_count) : 0;
weights_.fill(Weight{weight, weight});
}
/**
* \brief Creates a PointSet
*/
PointSet()
{
points_.setZero();
double weight = (weights_.size() > 0) ? 1./double(weights_.size()) : 0;
weights_.fill(Weight{weight, weight});
}
/**
* \brief Overridable default destructor
*/
virtual ~PointSet() { }
/**
* \brief Resizes a dynamic-size PointSet
*
* \param Points_ Number of points
*
* \throws ResizingFixedSizeEntityException
*/
void resize(int points_count)
{
if (int(weights_.size()) == points_count &&
int(points_.cols()) == points_count) return;
if (IsFixed<Points_>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(weights_.size(),
points_count,
"poit set Gaussian"));
}
points_.setZero(points_.rows(), points_count);
weights_.resize(points_count, 1);
const double weight = (points_count > 0)? 1. / double(points_count) : 0;
for (int i = 0; i < points_count; ++i)
{
weights_(i).w_mean = weight;
weights_(i).w_cov = weight;
}
// std::fill(weights_.begin(), weights_.end(), Weight{weight, weight});
}
/**
* \brief Resizes a dynamic-size PointSet
*
* \param Points_ Number of points
*
* \throws ResizingFixedSizeEntityException
*/
void resize(int dim, int points_count)
{
if (dim == dimension() && points_count == count_points()) return;
points_.setZero(dim, points_count);
weights_.resize(points_count, 1);
const double weight = (points_count > 0)? 1. / double(points_count) : 0;
for (int i = 0; i < points_count; ++i)
{
weights_(i).w_mean = weight;
weights_(i).w_cov = weight;
}
}
/**
* \brief Sets the new dimension for dynamic-size points (not to confuse
* with the number of points)
*
* \param dim Dimension of each point
*/
void dimension(int dim)
{
points_.resize(dim, count_points());
}
/**
* \return Dimension of containing points
*/
int dimension() const
{
return points_.rows();
}
/**
* \brief The number of points
*/
int count_points() const
{
return points_.cols();
}
/**
* \brief Read only access on i-th point
*
* \param i Index of requested point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
Point point(int i) const
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
return points_.col(i);
}
auto operator[](int i) -> decltype(PointMatrix().col(i))
{
return points_.col(i);
}
/**
* \brief weight of i-th point assuming both weights are the same
*
* \param i Index of requested point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
double weight(int i)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
return weights_(i).w_mean;
}
/**
* \brief weights of i-th point
*
* \param i Index of requested point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
const Weight& weights(int i) const
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
return weights_(i);
}
/**
* \brief Point matrix (read only)
*/
const PointMatrix& points() const noexcept
{
return points_;
}
/**
* \brief Point matrix
*/
PointMatrix& points()
{
return points_;
}
/**
* \brief point weights vector
*/
const Weights& weights() const noexcept
{
return weights_;
}
/**
* \brief Returns the weights for the mean of the points as a vector
*/
WeightVector mean_weights_vector() const noexcept
{
const int point_count = count_points();
WeightVector weight_vec(point_count);
for (int i = 0; i < point_count; ++i)
{
weight_vec(i) = weights_(i).w_mean;
}
return weight_vec;
}
/**
* \brief Returns the weights for the covariance of the points as a vector
*/
WeightVector covariance_weights_vector() const noexcept
{
const int point_count = count_points();
WeightVector weight_vec(point_count);
for (int i = 0; i < point_count; ++i)
{
weight_vec(i) = weights_(i).w_cov;
}
return weight_vec;
}
/**
* \brief Sets the given point matrix
*/
void points(const PointMatrix& point_matrix)
{
points_ = point_matrix;
}
/**
* \brief Sets a given point at position i
*
* \param i Index of point
* \param p The new point
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
points_.col(i) = p;
}
/**
* \brief Sets a given point at position i along with its weights
*
* \param i Index of point
* \param p The new point
* \param w Point weights. The weights determinaing the first two
* moments are the same
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p, double w)
{
point(i, p, Weight{w, w});
}
/**
* \brief Sets a given point at position i along with its weights
*
* \param i Index of point
* \param p The new point
* \param w_mean point weight used to compute the first moment
* \param w_cov point weight used to compute the second centered moment
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p, double w_mean , double w_cov)
{
point(i, p, Weight{w_mean, w_cov});
}
/**
* \brief Sets a given point at given position i along with its weights
*
* \param i Index of point
* \param p The new point
* \param weights point weights
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void point(int i, Point p, Weight weights)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
points_.col(i) = p;
weights_(i) = weights;
}
/**
* \brief Sets a given weight of a point at position i
*
* \param i Index of point
* \param w Point weights. The weights determinaing the first two
* moments are the same
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void weight(int i, double w)
{
weight(i, Weight{w, w});
}
/**
* \brief Sets given weights of a point at position i
*
* \param i Index of point
* \param w_mean point weight used to compute the first moment
* \param w_cov point weight used to compute the second centered moment
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void weight(int i, double w_mean , double w_cov)
{
weight(i, Weight{w_mean, w_cov});
}
/**
* Sets given weights of a point at position i
*
* \param i Index of point
* \param weights point weights
*
* \throws OutOfBoundsException
* \throws ZeroDimensionException
*/
void weight(int i, Weight weights)
{
INLINE_CHECK_POINT_SET_BOUNDS(i);
weights_(i) = weights;
}
/**
* \brief Creates a PointMatrix populated with zero mean points
*
* \return Centered points matrix.
*
* \throws ZeroDimensionException
* \throws Exception
*/
PointMatrix centered_points() const
{
INLINE_CHECK_POINT_SET_DIMENSIONS();
PointMatrix centered(points_.rows(), points_.cols());
const Point weighted_mean = mean();
const int point_count = points_.cols();
for (int i = 0; i < point_count; ++i)
{
centered.col(i) = points_.col(i) - weighted_mean;
}
return centered;
}
/**
* \brief Centers all points and returns the mean over all points.
*
* Computes the weighted mean of all points and subtracts the mean from all
* points. Finally returns the weighted mean
*
* \return Weighted mean
*/
Point center()
{
const Point weighted_mean = mean();
const int point_count = points_.cols();
for (int i = 0; i < point_count; ++i)
{
points_.col(i) -= weighted_mean;
}
return weighted_mean;
}
/**
* \brief Returns the weighted mean of all points
*
* \throws ZeroDimensionException
* \throws Exception
*/
Point mean() const
{
INLINE_CHECK_POINT_SET_DIMENSIONS();
Point weighted_mean;
weighted_mean.setZero(points_.rows());
const int point_count = points_.cols();
for (int i = 0; i < point_count; ++i)
{
weighted_mean += weights_(i).w_mean * points_.col(i);
}
return weighted_mean;
}
protected:
/**
* \brief point container
*/
PointMatrix points_;
/**
* \brief weight container
*/
Weights weights_;
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: except.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mh $ $Date: 2002-10-02 11:41:21 $
*
* 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 <stdio.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <hash_map>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <bridges/cpp_uno/bridge.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
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 ) SAL_THROW( () )
{
#ifdef 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( (sal_Unicode)'.' );
}
#ifdef 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 hash_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() SAL_THROW( () );
~RTTI() SAL_THROW( () );
type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );
};
//__________________________________________________________________________________________________
RTTI::RTTI() SAL_THROW( () )
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
//__________________________________________________________________________________________________
RTTI::~RTTI() SAL_THROW( () )
{
dlclose( m_hApp );
}
//__________________________________________________________________________________________________
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )
{
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( RTL_CONSTASCII_STRINGPARAM("_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 iFind( m_generatedRttis.find( unoName ) );
if (iFind == 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;
#ifdef 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 = iFind->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 )
{
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
terminate();
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)
terminate();
}
__cxa_throw( pCppExc, rtti, deleteException );
}
//==================================================================================================
void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno )
{
OSL_ENSURE( header, "### no exception header!!!" );
if (! header)
terminate();
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" );
if (! pExcTypeDescr)
terminate();
// construct uno exception any
::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
::typelib_typedescription_release( pExcTypeDescr );
}
}
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.3.36); FILE MERGED 2003/04/09 10:15:35 kso 1.3.36.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
*
* $RCSfile: except.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-15 16:26:17 $
*
* 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 <stdio.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <hash_map>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <bridges/cpp_uno/bridge.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
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 ) SAL_THROW( () )
{
#if OSL_DEBUG_LEVEL > 1
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( (sal_Unicode)'.' );
}
#if OSL_DEBUG_LEVEL > 1
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 hash_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() SAL_THROW( () );
~RTTI() SAL_THROW( () );
type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );
};
//__________________________________________________________________________________________________
RTTI::RTTI() SAL_THROW( () )
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
//__________________________________________________________________________________________________
RTTI::~RTTI() SAL_THROW( () )
{
dlclose( m_hApp );
}
//__________________________________________________________________________________________________
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )
{
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( RTL_CONSTASCII_STRINGPARAM("_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 iFind( m_generatedRttis.find( unoName ) );
if (iFind == 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 OSL_DEBUG_LEVEL > 1
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 = iFind->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 )
{
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
terminate();
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)
terminate();
}
__cxa_throw( pCppExc, rtti, deleteException );
}
//==================================================================================================
void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno )
{
OSL_ENSURE( header, "### no exception header!!!" );
if (! header)
terminate();
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" );
if (! pExcTypeDescr)
terminate();
// construct uno exception any
::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
::typelib_typedescription_release( pExcTypeDescr );
}
}
<|endoftext|> |
<commit_before>// An Homage to Vera Molnar's "An Homange to Durer"
SquareSize = [[Square Size]]
gridHeight = [[Grid Height]]
gridWidth = [[Grid Width]]
columnCounter = [[shiftCounter]]
rowCounter = [[rowCounter]]
if(columnCounter < [[gridWidth]]) {
drawVeraLines([[columnCounter]], [[rowCounter]])
columnCounter++;
} else if ([[rowCounter]] < [[gridHeight]]) {
columnCounter = 0;
rowCounter++;
} else {
rowCounter = 0;
columnCounter = 0;
}<commit_msg>Fix typo in pseudocode comment<commit_after>// An homage to Vera Molnar's "Hommage a Durer"
SquareSize = [[Square Size]]
gridHeight = [[Grid Height]]
gridWidth = [[Grid Width]]
columnCounter = [[shiftCounter]]
rowCounter = [[rowCounter]]
if(columnCounter < [[gridWidth]]) {
drawVeraLines([[columnCounter]], [[rowCounter]])
columnCounter++;
} else if ([[rowCounter]] < [[gridHeight]]) {
columnCounter = 0;
rowCounter++;
} else {
rowCounter = 0;
columnCounter = 0;
}<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH
#define DUNE_STUFF_FUNCTION_EXPRESSION_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <sstream>
#include <vector>
#ifdef HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/exceptions.hh>
#ifdef HAVE_DUNE_FEM
#include <dune/fem/function/common/function.hh>
#include <dune/fem/space/common/functionspace.hh>
#endif // HAVE_DUNE_FEM
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include "expression/mathexpr.hh"
#include "interface.hh"
namespace Dune {
namespace Stuff {
namespace Function {
/**
\brief Provides a function which evaluates a given mathematical expression at runtime.
Given a mathematical expression as a string, a domain \f$ K_d^{m \geq 1} \f$ and a range \f$ K_r^{n \geq 1}
\f$ this function represents the map
\f{eqnarray}
f:K_d^m \to K_r^n\\
x = (x_1, \dots, x_m)' \mapsto (f_1(x), \dots f_n(x))',
\f}
where \f$ K_d \f$ is the DomainType and \f$ K_r \f$ is the RangeType, usually a power of \f$ \mathcal{R} \f$.
The name of the variable as well as the \f$ n \f$ expressions of \f$f_1, \dots, f_n\f$ have to be given in a
Dune::ParameterTree in the following form:
\code variable: x
expression.0: 2*x[0]
expression.1: sin(x[1])*x[0]\endcode
There have to exist at least \f$n\f$ expressions; the entries of the variable are indexed by \f$[i]\f$ for
\f$ 0 \leq i \leq m - 1 \f$.
**/
template< class DomainFieldImp, int maxDimDomain, class RangeFieldImp, int maxDimRange >
class Expression
: public Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange >
{
public:
typedef DomainFieldImp DomainFieldType;
typedef RangeFieldImp RangeFieldType;
typedef Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > BaseType;
typedef Expression< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > ThisType;
// static const std::string id()
// {
// return BaseType::id() + ".expression";
// }
Expression(const std::string _variable, const std::string _expression)
{
const std::vector< std::string > expressions(1, _expression);
setup(_variable, expressions);
} // Expression(const std::string variable, const std::string expression)
Expression(const std::string _variable, const std::vector< std::string > _expressions)
{
setup(_variable, _expressions);
} // Expression(const std::string variable, const std::vector< std::string >& expressions)
Expression(const ThisType& other)
{
setup(other.variable(), other.expression());
} // Expression(const ThisType& other)
static ThisType createFromParamTree(const Dune::ParameterTree& paramTree)
{
const Dune::Stuff::Common::ExtendedParameterTree extendedParamtree(paramTree);
// get variable
if (!extendedParamtree.hasKey("variable"))
DUNE_THROW(Dune::RangeError, "\nError: missing key 'variable'!");
const std::string variable = extendedParamtree.get("variable", "not_meaningful_default_value");
// get expressions
if (!extendedParamtree.hasKey("expression"))
DUNE_THROW(Dune::RangeError, "\nError: missing key or vector 'expression'!");
const std::vector< std::string > expressions
= extendedParamtree.getVector< std::string >("expression", "not_meaningful_default_value");
// create and return
return ThisType(variable, expressions);
} // static ThisType createFromParamTree(const Stuff::Common::ExtendedParameterTree& paramTree)
ThisType& operator=(const ThisType& other)
{
if (this != &other) {
cleanup();
setup(other.variable(), other.expression());
}
return this;
} // ThisType& operator=(const ThisType& other)
~Expression()
{
cleanup();
} // ~Expression()
std::string variable() const
{
return variable_;
}
const std::vector< std::string > expression() const
{
return expressions_;
}
unsigned int dimRange() const
{
return actualDimRange_;
}
//! needed for Interface
virtual void evaluate(const Dune::FieldVector< DomainFieldImp, maxDimDomain >& arg, Dune::FieldVector< RangeFieldImp, maxDimRange >& ret) const
{
// ensure right dimensions
assert(arg.size() <= maxDimDomain);
assert(ret.size() <= dimRange());
// arg
for (typename Dune::FieldVector< DomainFieldImp, maxDimDomain >::size_type i = 0; i < arg.size(); ++i) {
*(arg_[i]) = arg[i];
}
// ret
for (typename Dune::FieldVector< RangeFieldImp, maxDimRange >::size_type i = 0; i < ret.size(); ++i) {
ret[i] = op_[i]->Val();
}
}
template< class DomainVectorType, class RangeVectorType >
void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const
{
// ensure right dimensions
assert(arg.size() <= maxDimDomain);
assert(ret.size() <= dimRange());
// arg
for (typename Dune::DenseVector< DomainVectorType >::size_type i = 0; i < arg.size(); ++i) {
*(arg_[i]) = arg[i];
}
// ret
for (typename Dune::DenseVector< RangeVectorType >::size_type i = 0; i < ret.size(); ++i) {
ret[i] = op_[i]->Val();
}
}
#ifdef HAVE_EIGEN
void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const
{
// ensure right dimensions
assert(arg.size() <= maxDimDomain);
assert(ret.size() <= dimRange());
// arg
for (int i = 0; i < arg.size(); ++ i) {
*(arg_[i]) = arg(i);
}
// ret
for (int i = 0; i < ret.size(); ++ i) {
ret(i) = op_[i]->Val();
}
}
#endif // HAVE_EIGEN
private:
void setup(const std::string& _variable, const std::vector< std::string >& _expressions)
{
assert(maxDimDomain > 0);
assert(maxDimRange > 0);
// set expressions
if (_expressions.size() < 1)
DUNE_THROW(Dune::InvalidStateException,"\nError: Given 'expressions'-vector is empty!");
actualDimRange_ = _expressions.size();
expressions_ = _expressions;
// set variable (i.e. "x")
variable_ = _variable;
// fill variables (i.e. "x[0]", "x[1]", ...)
for (int i = 0; i < maxDimDomain; ++i) {
std::stringstream variableStream;
variableStream << variable_ << "[" << i << "]";
variables_.push_back(variableStream.str());
}
// create epressions
for (unsigned int i = 0; i < maxDimDomain; ++i) {
arg_[i] = new DomainFieldType(0.0);
var_arg_[i] = new RVar(variables_[i].c_str(), arg_[i]);
vararray_[i] = var_arg_[i];
}
for (unsigned int i = 0; i < dimRange(); ++ i) {
op_[i] = new ROperation(expressions_[i].c_str(), maxDimDomain, vararray_);
}
} // void setup(const std::string& variable, const std::vector< std::string >& expressions)
void cleanup()
{
for (unsigned int i = 0; i < dimRange(); ++i) {
delete op_[i];
}
for (unsigned int i = 0; i < maxDimDomain; ++i) {
delete var_arg_[i];
delete arg_[i];
}
} // void cleanup()
std::string variable_;
std::vector< std::string > variables_;
std::vector< std::string > expressions_;
unsigned int actualDimRange_;
mutable DomainFieldType* arg_[maxDimDomain];
RVar* var_arg_[maxDimDomain];
RVar* vararray_[maxDimDomain];
ROperation* op_[maxDimRange];
}; // class Expression
} // namespace Function
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTION_EXPRESSION_HH
<commit_msg>[function.expression] removed id(), added report()<commit_after>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH
#define DUNE_STUFF_FUNCTION_EXPRESSION_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <sstream>
#include <vector>
#ifdef HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/exceptions.hh>
#ifdef HAVE_DUNE_FEM
#include <dune/fem/function/common/function.hh>
#include <dune/fem/space/common/functionspace.hh>
#endif // HAVE_DUNE_FEM
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include "expression/mathexpr.hh"
#include "interface.hh"
namespace Dune {
namespace Stuff {
namespace Function {
/**
\brief Provides a function which evaluates a given mathematical expression at runtime.
Given a mathematical expression as a string, a domain \f$ K_d^{m \geq 1} \f$ and a range \f$ K_r^{n \geq 1}
\f$ this function represents the map
\f{eqnarray}
f:K_d^m \to K_r^n\\
x = (x_1, \dots, x_m)' \mapsto (f_1(x), \dots f_n(x))',
\f}
where \f$ K_d \f$ is the DomainType and \f$ K_r \f$ is the RangeType, usually a power of \f$ \mathcal{R} \f$.
The name of the variable as well as the \f$ n \f$ expressions of \f$f_1, \dots, f_n\f$ have to be given in a
Dune::ParameterTree in the following form:
\code variable: x
expression.0: 2*x[0]
expression.1: sin(x[1])*x[0]\endcode
There have to exist at least \f$n\f$ expressions; the entries of the variable are indexed by \f$[i]\f$ for
\f$ 0 \leq i \leq m - 1 \f$.
**/
template< class DomainFieldImp, int maxDimDomain, class RangeFieldImp, int maxDimRange >
class Expression
: public Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange >
{
public:
typedef DomainFieldImp DomainFieldType;
typedef RangeFieldImp RangeFieldType;
typedef Interface< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > BaseType;
typedef Expression< DomainFieldImp, maxDimDomain, RangeFieldImp, maxDimRange > ThisType;
Expression(const std::string _variable, const std::string _expression)
{
const std::vector< std::string > expressions(1, _expression);
setup(_variable, expressions);
} // Expression(const std::string variable, const std::string expression)
Expression(const std::string _variable, const std::vector< std::string > _expressions)
{
setup(_variable, _expressions);
} // Expression(const std::string variable, const std::vector< std::string >& expressions)
Expression(const ThisType& other)
{
setup(other.variable(), other.expression());
} // Expression(const ThisType& other)
static ThisType createFromParamTree(const Dune::ParameterTree& paramTree)
{
const Dune::Stuff::Common::ExtendedParameterTree extendedParamtree(paramTree);
// get variable
if (!extendedParamtree.hasKey("variable"))
DUNE_THROW(Dune::RangeError, "\nError: missing key 'variable'!");
const std::string variable = extendedParamtree.get("variable", "not_meaningful_default_value");
// get expressions
if (!extendedParamtree.hasKey("expression"))
DUNE_THROW(Dune::RangeError, "\nError: missing key or vector 'expression'!");
const std::vector< std::string > expressions
= extendedParamtree.getVector< std::string >("expression", "not_meaningful_default_value");
// create and return
return ThisType(variable, expressions);
} // static ThisType createFromParamTree(const Stuff::Common::ExtendedParameterTree& paramTree)
ThisType& operator=(const ThisType& other)
{
if (this != &other) {
cleanup();
setup(other.variable(), other.expression());
}
return this;
} // ThisType& operator=(const ThisType& other)
~Expression()
{
cleanup();
} // ~Expression()
void report(const std::string name = "stuff.function.expression",
std::ostream& stream = std::cout,
const std::string& prefix = "") const
{
const std::string tmp = name + "(" + variable() + ") = ";
stream << prefix << tmp;
if (expression().size() == 1)
stream << expression()[0] << std::endl;
else {
stream << "[ " << expression()[0] << ";" << std::endl;
const std::string whitespace = Dune::Stuff::Common::whitespaceify(tmp + "[ ");
for (unsigned int i = 1; i < expression().size() - 1; ++i)
stream << prefix << whitespace << expression()[i] << ";" << std::endl;
stream << prefix << whitespace << expression()[expression().size() -1] << " ]" << std::endl;
}
} // void report(const std::string, std::ostream&, const std::string&) const
std::string variable() const
{
return variable_;
}
const std::vector< std::string > expression() const
{
return expressions_;
}
unsigned int dimRange() const
{
return actualDimRange_;
}
//! needed for Interface
virtual void evaluate(const Dune::FieldVector< DomainFieldImp, maxDimDomain >& arg, Dune::FieldVector< RangeFieldImp, maxDimRange >& ret) const
{
// ensure right dimensions
assert(arg.size() <= maxDimDomain);
assert(ret.size() <= dimRange());
// arg
for (typename Dune::FieldVector< DomainFieldImp, maxDimDomain >::size_type i = 0; i < arg.size(); ++i) {
*(arg_[i]) = arg[i];
}
// ret
for (typename Dune::FieldVector< RangeFieldImp, maxDimRange >::size_type i = 0; i < ret.size(); ++i) {
ret[i] = op_[i]->Val();
}
}
template< class DomainVectorType, class RangeVectorType >
void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const
{
// ensure right dimensions
assert(arg.size() <= maxDimDomain);
assert(ret.size() <= dimRange());
// arg
for (typename Dune::DenseVector< DomainVectorType >::size_type i = 0; i < arg.size(); ++i) {
*(arg_[i]) = arg[i];
}
// ret
for (typename Dune::DenseVector< RangeVectorType >::size_type i = 0; i < ret.size(); ++i) {
ret[i] = op_[i]->Val();
}
}
#ifdef HAVE_EIGEN
/**
* \attention ret is resized to size dimRange()!
*/
void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const
{
// ensure right dimensions
assert(arg.size() <= maxDimDomain);
ret.resize(dimRange());
// arg
for (int i = 0; i < arg.size(); ++ i) {
*(arg_[i]) = arg(i);
}
// ret
for (int i = 0; i < ret.size(); ++ i) {
ret(i) = op_[i]->Val();
}
} // void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const
#endif // HAVE_EIGEN
private:
void setup(const std::string& _variable, const std::vector< std::string >& _expressions)
{
assert(maxDimDomain > 0);
assert(maxDimRange > 0);
// set expressions
if (_expressions.size() < 1)
DUNE_THROW(Dune::InvalidStateException,"\nError: Given 'expressions'-vector is empty!");
actualDimRange_ = _expressions.size();
expressions_ = _expressions;
// set variable (i.e. "x")
variable_ = _variable;
// fill variables (i.e. "x[0]", "x[1]", ...)
for (int i = 0; i < maxDimDomain; ++i) {
std::stringstream variableStream;
variableStream << variable_ << "[" << i << "]";
variables_.push_back(variableStream.str());
}
// create epressions
for (unsigned int i = 0; i < maxDimDomain; ++i) {
arg_[i] = new DomainFieldType(0.0);
var_arg_[i] = new RVar(variables_[i].c_str(), arg_[i]);
vararray_[i] = var_arg_[i];
}
for (unsigned int i = 0; i < dimRange(); ++ i) {
op_[i] = new ROperation(expressions_[i].c_str(), maxDimDomain, vararray_);
}
} // void setup(const std::string& variable, const std::vector< std::string >& expressions)
void cleanup()
{
for (unsigned int i = 0; i < dimRange(); ++i) {
delete op_[i];
}
for (unsigned int i = 0; i < maxDimDomain; ++i) {
delete var_arg_[i];
delete arg_[i];
}
} // void cleanup()
std::string variable_;
std::vector< std::string > variables_;
std::vector< std::string > expressions_;
unsigned int actualDimRange_;
mutable DomainFieldType* arg_[maxDimDomain];
RVar* var_arg_[maxDimDomain];
RVar* vararray_[maxDimDomain];
ROperation* op_[maxDimRange];
}; // class Expression
} // namespace Function
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTION_EXPRESSION_HH
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_GRID_WALKER_WRAPPER_HH
#define DUNE_STUFF_GRID_WALKER_WRAPPER_HH
#include "functors.hh"
namespace Dune {
namespace Stuff {
namespace Grid {
namespace internal {
template <class GridViewType>
class Codim0Object
: public Functor::Codim0< GridViewType >
{
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
~Codim0Object() {}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
};
template<class GridViewType, class Codim0FunctorType>
class Codim0FunctorWrapper
: public Codim0Object<GridViewType>
{
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor,
const ApplyOn::WhichEntity< GridViewType >* where)
: wrapped_functor_(wrapped_functor)
, where_(where)
{}
virtual ~Codim0FunctorWrapper() {}
virtual void prepare() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.prepare();
}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(grid_view, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
wrapped_functor_.apply_local(entity);
}
virtual void finalize() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.finalize();
}
private:
Codim0FunctorType& wrapped_functor_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
}; // class Codim0FunctorWrapper
template <class GridViewType>
class Codim1Object
: public Functor::Codim1< GridViewType >
{
typedef typename GridViewType::Intersection IntersectionType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
~Codim1Object() {}
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
};
template<class GridViewType, class Codim1FunctorType>
class Codim1FunctorWrapper
: public Codim1Object<GridViewType>
{
typedef typename GridViewType::Intersection IntersectionType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor,
const ApplyOn::WhichIntersection< GridViewType >* where)
: wrapped_functor_(wrapped_functor)
, where_(where)
{}
virtual void prepare() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.prepare();
}
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(grid_view, intersection);
}
virtual void apply_local(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) DS_OVERRIDE DS_FINAL
{
wrapped_functor_.apply_local(intersection, inside_entity, outside_entity);
}
virtual void finalize() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.finalize();
}
private:
Codim1FunctorType& wrapped_functor_;
std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > where_;
}; // class Codim1FunctorWrapper
template<class GridViewType, class WalkerType>
class WalkerWrapper
: public Codim0Object<GridViewType>
, public Codim1Object<GridViewType>
{
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef typename GridViewType::Intersection IntersectionType;
public:
WalkerWrapper(WalkerType& grid_walker,
const ApplyOn::WhichEntity< GridViewType >* which_entities)
: grid_walker_(grid_walker)
, which_entities_(which_entities)
, which_intersections_(new ApplyOn::AllIntersections< GridViewType >())
{}
WalkerWrapper(WalkerType& grid_walker,
const ApplyOn::WhichIntersection< GridViewType >* which_intersections)
: grid_walker_(grid_walker)
, which_entities_(new ApplyOn::AllEntities< GridViewType >())
, which_intersections_(which_intersections)
{}
virtual ~WalkerWrapper() {}
virtual void prepare() DS_OVERRIDE DS_FINAL
{
grid_walker_.prepare();
}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return which_entities_->apply_on(grid_view, entity) && grid_walker_.apply_on(entity);
}
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
{
return which_intersections_->apply_on(grid_view, intersection) && grid_walker_.apply_on(intersection);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
grid_walker_.apply_local(entity);
}
virtual void apply_local(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) DS_OVERRIDE DS_FINAL
{
grid_walker_.apply_local(intersection, inside_entity, outside_entity);
}
virtual void finalize() DS_OVERRIDE DS_FINAL
{
grid_walker_.finalize();
}
private:
WalkerType& grid_walker_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > which_entities_;
std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > which_intersections_;
}; // class WalkerWrapper
template<class GridViewType >
class Codim0LambdaWrapper
: public Codim0Object< GridViewType >
{
typedef Codim0Object< GridViewType > BaseType;
public:
typedef typename BaseType::EntityType EntityType;
typedef std::function< void(const EntityType&) > LambdaType;
Codim0LambdaWrapper(LambdaType lambda, const ApplyOn::WhichEntity< GridViewType >* where)
: lambda_(lambda)
, where_(where)
{}
virtual ~Codim0LambdaWrapper() {}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(grid_view, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
lambda_(entity);
}
private:
LambdaType lambda_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
}; // class Codim0LambdaWrapper
} // namespace internal
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_GRID_WALKER_WRAPPER_HH
<commit_msg>[grid.walker.wrapper] use correct type<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_GRID_WALKER_WRAPPER_HH
#define DUNE_STUFF_GRID_WALKER_WRAPPER_HH
#include "functors.hh"
namespace Dune {
namespace Stuff {
namespace Grid {
namespace internal {
template <class GridViewType>
class Codim0Object
: public Functor::Codim0< GridViewType >
{
typedef Functor::Codim0< GridViewType > BaseType;
public:
typedef typename BaseType::EntityType EntityType;
~Codim0Object() {}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
};
template<class GridViewType, class Codim0FunctorType>
class Codim0FunctorWrapper
: public Codim0Object<GridViewType>
{
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor,
const ApplyOn::WhichEntity< GridViewType >* where)
: wrapped_functor_(wrapped_functor)
, where_(where)
{}
virtual ~Codim0FunctorWrapper() {}
virtual void prepare() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.prepare();
}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(grid_view, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
wrapped_functor_.apply_local(entity);
}
virtual void finalize() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.finalize();
}
private:
Codim0FunctorType& wrapped_functor_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
}; // class Codim0FunctorWrapper
template <class GridViewType>
class Codim1Object
: public Functor::Codim1< GridViewType >
{
typedef typename GridViewType::Intersection IntersectionType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
~Codim1Object() {}
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
};
template<class GridViewType, class Codim1FunctorType>
class Codim1FunctorWrapper
: public Codim1Object<GridViewType>
{
typedef typename GridViewType::Intersection IntersectionType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
public:
Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor,
const ApplyOn::WhichIntersection< GridViewType >* where)
: wrapped_functor_(wrapped_functor)
, where_(where)
{}
virtual void prepare() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.prepare();
}
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(grid_view, intersection);
}
virtual void apply_local(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) DS_OVERRIDE DS_FINAL
{
wrapped_functor_.apply_local(intersection, inside_entity, outside_entity);
}
virtual void finalize() DS_OVERRIDE DS_FINAL
{
wrapped_functor_.finalize();
}
private:
Codim1FunctorType& wrapped_functor_;
std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > where_;
}; // class Codim1FunctorWrapper
template<class GridViewType, class WalkerType>
class WalkerWrapper
: public Codim0Object<GridViewType>
, public Codim1Object<GridViewType>
{
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef typename GridViewType::Intersection IntersectionType;
public:
WalkerWrapper(WalkerType& grid_walker,
const ApplyOn::WhichEntity< GridViewType >* which_entities)
: grid_walker_(grid_walker)
, which_entities_(which_entities)
, which_intersections_(new ApplyOn::AllIntersections< GridViewType >())
{}
WalkerWrapper(WalkerType& grid_walker,
const ApplyOn::WhichIntersection< GridViewType >* which_intersections)
: grid_walker_(grid_walker)
, which_entities_(new ApplyOn::AllEntities< GridViewType >())
, which_intersections_(which_intersections)
{}
virtual ~WalkerWrapper() {}
virtual void prepare() DS_OVERRIDE DS_FINAL
{
grid_walker_.prepare();
}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return which_entities_->apply_on(grid_view, entity) && grid_walker_.apply_on(entity);
}
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
{
return which_intersections_->apply_on(grid_view, intersection) && grid_walker_.apply_on(intersection);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
grid_walker_.apply_local(entity);
}
virtual void apply_local(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) DS_OVERRIDE DS_FINAL
{
grid_walker_.apply_local(intersection, inside_entity, outside_entity);
}
virtual void finalize() DS_OVERRIDE DS_FINAL
{
grid_walker_.finalize();
}
private:
WalkerType& grid_walker_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > which_entities_;
std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > which_intersections_;
}; // class WalkerWrapper
template<class GridViewType >
class Codim0LambdaWrapper
: public Codim0Object< GridViewType >
{
typedef Codim0Object< GridViewType > BaseType;
public:
typedef typename BaseType::EntityType EntityType;
typedef std::function< void(const EntityType&) > LambdaType;
Codim0LambdaWrapper(LambdaType lambda, const ApplyOn::WhichEntity< GridViewType >* where)
: lambda_(lambda)
, where_(where)
{}
virtual ~Codim0LambdaWrapper() {}
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(grid_view, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
lambda_(entity);
}
private:
LambdaType lambda_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
}; // class Codim0LambdaWrapper
} // namespace internal
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_GRID_WALKER_WRAPPER_HH
<|endoftext|> |
<commit_before><commit_msg>Add a CHECK() around the SharedMemory ftruncate() call to finger it as a crash culprit.<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_basic.hxx"
#include "app.hxx"
#include "basic.hrc"
#include "appwin.hxx"
#include "status.hxx"
#include <vcl/decoview.hxx>
StatusLine::StatusLine( BasicFrame* p )
: TaskBar( p )
, pFrame( p )
{
// initialize TaskToolBox
TaskToolBox* pTempTaskToolBox = GetTaskToolBox();
pTempTaskToolBox->SetActivateTaskHdl( LINK( this, StatusLine, ActivateTask ) );
// initialize TaskStatusBar
TaskStatusBar* pTempStatusBar = GetStatusBar();
long nCharWidth = GetTextWidth( '0' ); // We state: All numbers has the same width
pTempStatusBar->InsertItem( ST_MESSAGE, GetTextWidth( 'X' ) * 20, SIB_LEFT | SIB_IN | SIB_AUTOSIZE );
pTempStatusBar->InsertItem( ST_LINE, 5*nCharWidth );
pTempStatusBar->InsertItem( ST_PROF, GetTextWidth( 'X' ) * 10 );
pTempStatusBar->InsertStatusField();
Show();
}
void StatusLine::Message( const String& s )
{
GetStatusBar()->SetItemText( ST_MESSAGE, s );
}
void StatusLine::Pos( const String& s )
{
GetStatusBar()->SetItemText( ST_LINE, s );
}
void StatusLine::SetProfileName( const String& s )
{
GetStatusBar()->SetItemText( ST_PROF, s );
}
IMPL_LINK( StatusLine, ActivateTask, TaskToolBox*, pTTB )
{
sal_uInt16 nFirstWinPos=0;
MenuBar* pMenu = pFrame->GetMenuBar();
PopupMenu* pWinMenu = pMenu->GetPopupMenu( RID_APPWINDOW );
while ( pWinMenu->GetItemId( nFirstWinPos ) < RID_WIN_FILE1 && nFirstWinPos < pWinMenu->GetItemCount() )
nFirstWinPos++;
nFirstWinPos += pTTB->GetItemPos( pTTB->GetCurItemId() ) / 2;
sal_uInt16 x;
x = pTTB->GetItemPos( pTTB->GetCurItemId() );
x = pWinMenu->GetItemId( nFirstWinPos );
x = pWinMenu->GetItemCount();
AppWin* pWin = pFrame->FindWin( pWinMenu->GetItemText( pWinMenu->GetItemId( nFirstWinPos ) ).EraseAllChars( L'~' ) );
if ( pWin )
{
pWin->Minimize( sal_False );
pWin->ToTop();
}
return 0;
}
void StatusLine::LoadTaskToolBox()
{
sal_uInt16 nFirstWinPos=0;
MenuBar* pMenu = pFrame->GetMenuBar();
PopupMenu* pWinMenu = pMenu->GetPopupMenu( RID_APPWINDOW );
while ( pWinMenu->GetItemId( nFirstWinPos ) < RID_WIN_FILE1 && nFirstWinPos < pWinMenu->GetItemCount() )
nFirstWinPos++;
TaskToolBox* pTaskToolBox = GetTaskToolBox();
pTaskToolBox->StartUpdateTask();
while ( nFirstWinPos < pWinMenu->GetItemCount() )
{ // There are windows
Window* pWin = pFrame->FindWin( pWinMenu->GetItemId( nFirstWinPos ) );
if ( pWin )
pTaskToolBox->UpdateTask( Image(), pWin->GetText(), pWin == pFrame->pList->back() && !( pFrame->pList->back()->GetWinState() & TT_WIN_STATE_HIDE ) );
nFirstWinPos++;
}
pTaskToolBox->EndUpdateTask();
Resize();
Invalidate();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>these statements have no effect, looks like debugging code<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_basic.hxx"
#include "app.hxx"
#include "basic.hrc"
#include "appwin.hxx"
#include "status.hxx"
#include <vcl/decoview.hxx>
StatusLine::StatusLine( BasicFrame* p )
: TaskBar( p )
, pFrame( p )
{
// initialize TaskToolBox
TaskToolBox* pTempTaskToolBox = GetTaskToolBox();
pTempTaskToolBox->SetActivateTaskHdl( LINK( this, StatusLine, ActivateTask ) );
// initialize TaskStatusBar
TaskStatusBar* pTempStatusBar = GetStatusBar();
long nCharWidth = GetTextWidth( '0' ); // We state: All numbers has the same width
pTempStatusBar->InsertItem( ST_MESSAGE, GetTextWidth( 'X' ) * 20, SIB_LEFT | SIB_IN | SIB_AUTOSIZE );
pTempStatusBar->InsertItem( ST_LINE, 5*nCharWidth );
pTempStatusBar->InsertItem( ST_PROF, GetTextWidth( 'X' ) * 10 );
pTempStatusBar->InsertStatusField();
Show();
}
void StatusLine::Message( const String& s )
{
GetStatusBar()->SetItemText( ST_MESSAGE, s );
}
void StatusLine::Pos( const String& s )
{
GetStatusBar()->SetItemText( ST_LINE, s );
}
void StatusLine::SetProfileName( const String& s )
{
GetStatusBar()->SetItemText( ST_PROF, s );
}
IMPL_LINK( StatusLine, ActivateTask, TaskToolBox*, pTTB )
{
sal_uInt16 nFirstWinPos=0;
MenuBar* pMenu = pFrame->GetMenuBar();
PopupMenu* pWinMenu = pMenu->GetPopupMenu( RID_APPWINDOW );
while ( pWinMenu->GetItemId( nFirstWinPos ) < RID_WIN_FILE1 && nFirstWinPos < pWinMenu->GetItemCount() )
nFirstWinPos++;
nFirstWinPos += pTTB->GetItemPos( pTTB->GetCurItemId() ) / 2;
AppWin* pWin = pFrame->FindWin( pWinMenu->GetItemText( pWinMenu->GetItemId( nFirstWinPos ) ).EraseAllChars( L'~' ) );
if ( pWin )
{
pWin->Minimize( sal_False );
pWin->ToTop();
}
return 0;
}
void StatusLine::LoadTaskToolBox()
{
sal_uInt16 nFirstWinPos=0;
MenuBar* pMenu = pFrame->GetMenuBar();
PopupMenu* pWinMenu = pMenu->GetPopupMenu( RID_APPWINDOW );
while ( pWinMenu->GetItemId( nFirstWinPos ) < RID_WIN_FILE1 && nFirstWinPos < pWinMenu->GetItemCount() )
nFirstWinPos++;
TaskToolBox* pTaskToolBox = GetTaskToolBox();
pTaskToolBox->StartUpdateTask();
while ( nFirstWinPos < pWinMenu->GetItemCount() )
{ // There are windows
Window* pWin = pFrame->FindWin( pWinMenu->GetItemId( nFirstWinPos ) );
if ( pWin )
pTaskToolBox->UpdateTask( Image(), pWin->GetText(), pWin == pFrame->pList->back() && !( pFrame->pList->back()->GetWinState() & TT_WIN_STATE_HIDE ) );
nFirstWinPos++;
}
pTaskToolBox->EndUpdateTask();
Resize();
Invalidate();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE ftEdgeTest
#include <boost/test/unit_test.hpp>
#include <fstream>
#include "GoTools/utils/Point.h"
#include "GoTools/geometry/Utils.h"
#include "GoTools/geometry/ObjectHeader.h"
#include "GoTools/geometry/Circle.h"
#include "GoTools/compositemodel/Vertex.h"
#include "GoTools/compositemodel/ftEdge.h"
using namespace std;
using namespace Go;
BOOST_AUTO_TEST_CASE(ConstructFromCircle)
{
ifstream in("data/ftEdge.dat");
BOOST_CHECK_MESSAGE(!in.bad(), "Input file not found or file corrupt");
ObjectHeader header;
shared_ptr<Circle> circle(new Circle);
Point pt1(3);
Point pt2(3);
int index = 0;
while (!in.eof()) {
cout << "index: " << index << endl;
// Circle
header.read(in);
circle->read(in);
// Vertices
pt1.read(in);
shared_ptr<Vertex> v1(new Vertex(pt1));
pt2.read(in);
shared_ptr<Vertex> v2(new Vertex(pt2));
// ftEdge
ftEdge edge(circle, v1, v2);
// Test vertices
shared_ptr<Vertex> va, vb;
edge.getVertices(va, vb);
double eps = 1.0e-6;
double dist1 = (v1->getVertexPoint() - va->getVertexPoint()).length();
double dist2 = (v2->getVertexPoint() - vb->getVertexPoint()).length();
bool verticesOK = (dist1 < eps) && (dist2 < eps);
BOOST_CHECK(verticesOK);
// Test if not reversed
bool isNotReversed = !edge.isReversed();
BOOST_CHECK(isNotReversed);
// Test parameter interval
double parlen = edge.tMax() - edge.tMin();
bool lessthan2pi = (parlen <= 2.0 * M_PI);
BOOST_CHECK(lessthan2pi);
Utils::eatwhite(in);
++index;
}
}
<commit_msg>Test tweaks.<commit_after>#define BOOST_TEST_MODULE ftEdgeTest
#include <boost/test/unit_test.hpp>
#include <fstream>
#include "GoTools/utils/Point.h"
#include "GoTools/geometry/Utils.h"
#include "GoTools/geometry/ObjectHeader.h"
#include "GoTools/geometry/Circle.h"
#include "GoTools/compositemodel/Vertex.h"
#include "GoTools/compositemodel/ftEdge.h"
using namespace std;
using namespace Go;
BOOST_AUTO_TEST_CASE(ConstructFromCircle)
{
ifstream in("data/ftEdge.dat");
BOOST_CHECK_MESSAGE(!in.bad(), "Input file not found or file corrupt");
ObjectHeader header;
shared_ptr<Circle> circle(new Circle);
Point pt1(3);
Point pt2(3);
int index = 0;
while (!in.eof()) {
cout << "index: " << index << endl;
// Circle
header.read(in);
circle->read(in);
// Vertices
pt1.read(in);
shared_ptr<Vertex> v1(new Vertex(pt1));
pt2.read(in);
shared_ptr<Vertex> v2(new Vertex(pt2));
// ftEdge
ftEdge edge(circle, v1, v2);
// Test vertices
shared_ptr<Vertex> va, vb;
edge.getVertices(va, vb);
double eps = 1.0e-6;
double dist1 = (v1->getVertexPoint() - va->getVertexPoint()).length();
double dist2 = (v2->getVertexPoint() - vb->getVertexPoint()).length();
bool verticesOK = (dist1 < eps) && (dist2 < eps);
BOOST_CHECK(verticesOK);
// Test if not reversed
bool isNotReversed = !edge.isReversed();
BOOST_CHECK(isNotReversed);
// Test parameter interval
double parlen = edge.tMax() - edge.tMin();
bool lessthan2pi = (parlen <= 2.0 * M_PI);
BOOST_CHECK(lessthan2pi);
Utils::eatwhite(in);
++index;
}
}
<|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_processes_api.h"
#include "base/callback.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_processes_api_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
namespace keys = extension_processes_api_constants;
DictionaryValue* CreateProcessValue(int process_id,
const std::string& type,
double cpu,
int64 net,
int64 pr_mem,
int64 sh_mem) {
DictionaryValue* result = new DictionaryValue();
result->SetInteger(keys::kIdKey, process_id);
result->SetString(keys::kTypeKey, type);
result->SetDouble(keys::kCpuKey, cpu);
result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
result->SetDouble(keys::kSharedMemoryKey, static_cast<double>(sh_mem));
return result;
}
ExtensionProcessesEventRouter* ExtensionProcessesEventRouter::GetInstance() {
return Singleton<ExtensionProcessesEventRouter>::get();
}
ExtensionProcessesEventRouter::ExtensionProcessesEventRouter() {
model_ = TaskManager::GetInstance()->model();
model_->AddObserver(this);
}
ExtensionProcessesEventRouter::~ExtensionProcessesEventRouter() {
model_->RemoveObserver(this);
}
void ExtensionProcessesEventRouter::ObserveProfile(Profile* profile) {
profiles_.insert(profile);
}
void ExtensionProcessesEventRouter::ListenerAdded() {
model_->StartUpdating();
}
void ExtensionProcessesEventRouter::ListenerRemoved() {
model_->StopUpdating();
}
void ExtensionProcessesEventRouter::OnItemsChanged(int start, int length) {
if (model_) {
ListValue args;
DictionaryValue* processes = new DictionaryValue();
for (int i = start; i < start + length; i++) {
if (model_->IsResourceFirstInGroup(i)) {
int id = model_->GetProcessId(i);
// Determine process type
std::string type = keys::kProcessTypeOther;
TaskManager::Resource::Type resource_type = model_->GetResourceType(i);
switch (resource_type) {
case TaskManager::Resource::BROWSER:
type = keys::kProcessTypeBrowser;
break;
case TaskManager::Resource::RENDERER:
type = keys::kProcessTypeRenderer;
break;
case TaskManager::Resource::EXTENSION:
type = keys::kProcessTypeExtension;
break;
case TaskManager::Resource::NOTIFICATION:
type = keys::kProcessTypeNotification;
break;
case TaskManager::Resource::PLUGIN:
type = keys::kProcessTypePlugin;
break;
case TaskManager::Resource::WORKER:
type = keys::kProcessTypeWorker;
break;
case TaskManager::Resource::NACL:
type = keys::kProcessTypeNacl;
break;
case TaskManager::Resource::UTILITY:
type = keys::kProcessTypeUtility;
break;
case TaskManager::Resource::GPU:
type = keys::kProcessTypeGPU;
break;
case TaskManager::Resource::PROFILE_IMPORT:
case TaskManager::Resource::ZYGOTE:
case TaskManager::Resource::SANDBOX_HELPER:
case TaskManager::Resource::UNKNOWN:
type = keys::kProcessTypeOther;
break;
default:
NOTREACHED() << "Unknown resource type.";
}
// Get process metrics as numbers
double cpu = model_->GetCPUUsage(i);
// TODO(creis): Network is actually reported per-resource (tab),
// not per-process. We should aggregate it here.
int64 net = model_->GetNetworkUsage(i);
size_t mem;
int64 pr_mem = model_->GetPrivateMemory(i, &mem) ?
static_cast<int64>(mem) : -1;
int64 sh_mem = model_->GetSharedMemory(i, &mem) ?
static_cast<int64>(mem) : -1;
// Store each process indexed by the string version of its id
processes->Set(base::IntToString(id),
CreateProcessValue(id, type, cpu, net, pr_mem, sh_mem));
}
}
args.Append(processes);
std::string json_args;
base::JSONWriter::Write(&args, &json_args);
// Notify each profile that is interested.
for (ProfileSet::iterator it = profiles_.begin();
it != profiles_.end(); it++) {
Profile* profile = *it;
DispatchEvent(profile, keys::kOnUpdated, json_args);
}
}
}
void ExtensionProcessesEventRouter::DispatchEvent(Profile* profile,
const char* event_name,
const std::string& json_args) {
if (profile && profile->GetExtensionEventRouter()) {
profile->GetExtensionEventRouter()->DispatchEventToRenderers(
event_name, json_args, NULL, GURL());
}
}
bool GetProcessIdForTabFunction::RunImpl() {
int tab_id;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
TabContentsWrapper* contents = NULL;
int tab_index = -1;
if (!ExtensionTabUtil::GetTabById(tab_id, profile(), include_incognito(),
NULL, NULL, &contents, &tab_index)) {
error_ = ExtensionErrorUtils::FormatErrorMessage(
extension_tabs_module_constants::kTabNotFoundError,
base::IntToString(tab_id));
return false;
}
// Return the process ID of the tab as an integer.
int id = base::GetProcId(contents->web_contents()->
GetRenderProcessHost()->GetHandle());
result_.reset(Value::CreateIntegerValue(id));
return true;
}
<commit_msg>ifdef'd out more references to TaskManager<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_processes_api.h"
#include "base/callback.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_processes_api_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
namespace keys = extension_processes_api_constants;
DictionaryValue* CreateProcessValue(int process_id,
const std::string& type,
double cpu,
int64 net,
int64 pr_mem,
int64 sh_mem) {
DictionaryValue* result = new DictionaryValue();
result->SetInteger(keys::kIdKey, process_id);
result->SetString(keys::kTypeKey, type);
result->SetDouble(keys::kCpuKey, cpu);
result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
result->SetDouble(keys::kSharedMemoryKey, static_cast<double>(sh_mem));
return result;
}
ExtensionProcessesEventRouter* ExtensionProcessesEventRouter::GetInstance() {
return Singleton<ExtensionProcessesEventRouter>::get();
}
ExtensionProcessesEventRouter::ExtensionProcessesEventRouter() {
#if defined(ENABLE_TASK_MANAGER)
model_ = TaskManager::GetInstance()->model();
model_->AddObserver(this);
#endif // defined(ENABLE_TASK_MANAGER)
}
ExtensionProcessesEventRouter::~ExtensionProcessesEventRouter() {
#if defined(ENABLE_TASK_MANAGER)
model_->RemoveObserver(this);
#endif // defined(ENABLE_TASK_MANAGER)
}
void ExtensionProcessesEventRouter::ObserveProfile(Profile* profile) {
profiles_.insert(profile);
}
void ExtensionProcessesEventRouter::ListenerAdded() {
#if defined(ENABLE_TASK_MANAGER)
model_->StartUpdating();
#endif // defined(ENABLE_TASK_MANAGER)
}
void ExtensionProcessesEventRouter::ListenerRemoved() {
#if defined(ENABLE_TASK_MANAGER)
model_->StopUpdating();
#endif // defined(ENABLE_TASK_MANAGER)
}
void ExtensionProcessesEventRouter::OnItemsChanged(int start, int length) {
#if defined(ENABLE_TASK_MANAGER)
if (model_) {
ListValue args;
DictionaryValue* processes = new DictionaryValue();
for (int i = start; i < start + length; i++) {
if (model_->IsResourceFirstInGroup(i)) {
int id = model_->GetProcessId(i);
// Determine process type
std::string type = keys::kProcessTypeOther;
TaskManager::Resource::Type resource_type = model_->GetResourceType(i);
switch (resource_type) {
case TaskManager::Resource::BROWSER:
type = keys::kProcessTypeBrowser;
break;
case TaskManager::Resource::RENDERER:
type = keys::kProcessTypeRenderer;
break;
case TaskManager::Resource::EXTENSION:
type = keys::kProcessTypeExtension;
break;
case TaskManager::Resource::NOTIFICATION:
type = keys::kProcessTypeNotification;
break;
case TaskManager::Resource::PLUGIN:
type = keys::kProcessTypePlugin;
break;
case TaskManager::Resource::WORKER:
type = keys::kProcessTypeWorker;
break;
case TaskManager::Resource::NACL:
type = keys::kProcessTypeNacl;
break;
case TaskManager::Resource::UTILITY:
type = keys::kProcessTypeUtility;
break;
case TaskManager::Resource::GPU:
type = keys::kProcessTypeGPU;
break;
case TaskManager::Resource::PROFILE_IMPORT:
case TaskManager::Resource::ZYGOTE:
case TaskManager::Resource::SANDBOX_HELPER:
case TaskManager::Resource::UNKNOWN:
type = keys::kProcessTypeOther;
break;
default:
NOTREACHED() << "Unknown resource type.";
}
// Get process metrics as numbers
double cpu = model_->GetCPUUsage(i);
// TODO(creis): Network is actually reported per-resource (tab),
// not per-process. We should aggregate it here.
int64 net = model_->GetNetworkUsage(i);
size_t mem;
int64 pr_mem = model_->GetPrivateMemory(i, &mem) ?
static_cast<int64>(mem) : -1;
int64 sh_mem = model_->GetSharedMemory(i, &mem) ?
static_cast<int64>(mem) : -1;
// Store each process indexed by the string version of its id
processes->Set(base::IntToString(id),
CreateProcessValue(id, type, cpu, net, pr_mem, sh_mem));
}
}
args.Append(processes);
std::string json_args;
base::JSONWriter::Write(&args, &json_args);
// Notify each profile that is interested.
for (ProfileSet::iterator it = profiles_.begin();
it != profiles_.end(); it++) {
Profile* profile = *it;
DispatchEvent(profile, keys::kOnUpdated, json_args);
}
}
#endif // defined(ENABLE_TASK_MANAGER)
}
void ExtensionProcessesEventRouter::DispatchEvent(Profile* profile,
const char* event_name,
const std::string& json_args) {
if (profile && profile->GetExtensionEventRouter()) {
profile->GetExtensionEventRouter()->DispatchEventToRenderers(
event_name, json_args, NULL, GURL());
}
}
bool GetProcessIdForTabFunction::RunImpl() {
int tab_id;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));
TabContentsWrapper* contents = NULL;
int tab_index = -1;
if (!ExtensionTabUtil::GetTabById(tab_id, profile(), include_incognito(),
NULL, NULL, &contents, &tab_index)) {
error_ = ExtensionErrorUtils::FormatErrorMessage(
extension_tabs_module_constants::kTabNotFoundError,
base::IntToString(tab_id));
return false;
}
// Return the process ID of the tab as an integer.
int id = base::GetProcId(contents->web_contents()->
GetRenderProcessHost()->GetHandle());
result_.reset(Value::CreateIntegerValue(id));
return true;
}
<|endoftext|> |
<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>
#include "Sensor.h"
#include "I2C.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"
#include <vector>
#include <iostream>
#include <wiringPi.h> //compile with -lwiringPi
using namespace std;
vector<Sensor*> sensors; //Vector of the sensors
vector<Light*> lights; //Vector of the lights
vector<int> values; //Vector of the values from the sensors
vector<int> active;
Camera& cam; //Pointer to the camera
int sumActive(int active[]) {
int sum=0;
for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
sum+=active[i];
return sum;
}
void setCam(bool b);
void init();
int main() {
while(1) {
for(int i=0;i<sensors.capacity();i++) // For every sensor
if(sensors[i]->Check()) { // Call their check function
active[i]=1; // And if the check is positive (returns true).
//TODO ENABLE LIGHTS
} else active[i]=0;
if(sumActive(active)==0) {
cout<<"uhoh"<<endl;
// Guard.sendAlert();
}
for(i=0;i<lights.capacity();i++) // For every light
lights[i]->Check(); // Check if timer expired yet
}
}
/*Init for the main*/
void init() {
wiringPiSetupGpio();
Light x(22);
I2CCom i2c(I2CLOC); //the i2c to communicate with sensors
MotionSensor s1(0x05,i2c);
Log log(LOG);
PressureSensor s2(0x06, i2c, log);
sensors.push_back(&s1);
sensors.push_back(&s2);
lights.push_back(&x);
active.resize(sensors.sizeof);
values.resize(sensors.sizeof);
}
/*Sets the camera*/
void setCam(bool b){
cam.setCamera(b);
}
<commit_msg>added attributes & checkAnomaly function<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>
#include "Sensor.h"
#include "I2C.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"
#include <vector>
#include <iostream>
#include <wiringPi.h> //compile with -lwiringPi
using namespace std;
vector<Sensor*> sensors; //Vector of the sensors
vector<Light*> lights; //Vector of the lights
vector<int> values; //Vector of the values from the sensors
vector<int> active;
Camera& cam; //Pointer to the camera
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
int sumActive(int active[]) {
int sum=0;
for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
sum+=active[i];
return sum;
}
void checkAnomaly();
void checkCam();
void init();
int main() {
while(1) {
for(int i=0;i<sensors.capacity();i++) // For every sensor
if(sensors[i]->Check()) { // Call their check function
active[i]=1; // And if the check is positive (returns true).
//TODO ENABLE LIGHTS
} else active[i]=0;
if(sumActive(active)==0) {
cout<<"uhoh"<<endl;
// Guard.sendAlert();
}
for(i=0;i<lights.capacity();i++) // For every light
lights[i]->Check(); // Check if timer expired yet
}
}
/*Init for the main*/
void init() {
wiringPiSetupGpio();
Light x(22);
I2CCom i2c(I2CLOC); //the i2c to communicate with sensors
MotionSensor s1(0x05,i2c);
Log log(LOG);
PressureSensor s2(0x06, i2c, log);
sensors.push_back(&s1);
sensors.push_back(&s2);
lights.push_back(&x);
active.resize(sensors.sizeof);
values.resize(sensors.sizeof);
}
/*Sets the camera*/
void checkCam(){
if(day) {
cam.setCamera(true);
} else if(anamoly) {
cam.setCamera(true);
} else {
cam.setCamera(false);
}
}
void checkAnomaly(){
int pressureValue = values[2];
if(pressureValue > 20 && value < 150) {
anomaly = true;
}
if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
//Do nothing, maybe verify if person really is sleeping
}
if(pressureValue > 200) {
sleep = true;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/test/automation/javascript_execution_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Tests the DOMAutomation framework for manipulating DOMElements within
// browser tests.
class DOMAutomationTest : public InProcessBrowserTest {
public:
DOMAutomationTest() {
EnableDOMAutomation();
JavaScriptExecutionController::set_timeout(30000);
}
GURL GetTestURL(const char* path) {
std::string url_path = "files/dom_automation/";
url_path.append(path);
return test_server()->GetURL(url_path);
}
};
typedef DOMElementProxy::By By;
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindByXPath) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_div = main_doc->FindElement(By::XPath("//div"));
ASSERT_TRUE(first_div);
ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//div"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::XPath("//nosuchtag")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::XPath("//nosuchtag"), &elements));
elements.clear();
ASSERT_EQ(0u, elements.size());
// Find with invalid xpath.
ASSERT_FALSE(main_doc->FindElement(By::XPath("'invalid'")));
ASSERT_FALSE(main_doc->FindElement(By::XPath(" / / ")));
ASSERT_FALSE(main_doc->FindElements(By::XPath("'invalid'"), &elements));
ASSERT_FALSE(main_doc->FindElements(By::XPath(" / / "), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::XPath("/html/body/span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::XPath("./span"));
}
ASSERT_EQ(3, nested_count);
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_myclass =
main_doc->FindElement(By::Selectors(".myclass"));
ASSERT_TRUE(first_myclass);
ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors(".myclass"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("#nosuchid")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Selectors("#nosuchid"), &elements));
ASSERT_EQ(0u, elements.size());
// Find with invalid selectors.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("1#2")));
ASSERT_FALSE(main_doc->FindElements(By::Selectors("1#2"), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Selectors("span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Selectors("span"));
}
ASSERT_EQ(3, nested_count);
}
#if defined(OS_WIN)
// http://crbug.com/72745
#define MAYBE_FindByText FLAKY_FindByText
#else
#define MAYBE_FindByText FindByText
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_text = main_doc->FindElement(By::Text("div_text"));
ASSERT_TRUE(first_text);
ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Text("div_text"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Text("nosuchtext")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Text("nosuchtext"), &elements));
ASSERT_EQ(0u, elements.size());
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Text("span_text"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Text("span_text"));
}
ASSERT_EQ(3, nested_count);
// Find only visible text.
DOMElementProxyRef shown_td = main_doc->FindElement(By::Text("table_text"));
ASSERT_TRUE(shown_td);
ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches("shown"));
// Find text in inputs.
ASSERT_TRUE(main_doc->FindElement(By::Text("textarea_text")));
ASSERT_TRUE(main_doc->FindElement(By::Text("input_text")));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef div =
main_doc->WaitFor1VisibleElement(By::Selectors("div"));
ASSERT_TRUE(div.get());
ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches("div_inner"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors("img")));
std::vector<DOMElementProxyRef> img_elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors("img"), &img_elements));
ASSERT_EQ(0u, img_elements.size());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(anchor.get());
ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(
"href", "http://www.google.com"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("frames/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Get both frame elements.
std::vector<DOMElementProxyRef> frame_elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//frame"), &frame_elements));
ASSERT_EQ(2u, frame_elements.size());
// Get both frames, checking their contents are correct.
DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();
DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();
ASSERT_TRUE(frame1 && frame2);
DOMElementProxyRef frame_div =
frame1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 1"));
frame_div = frame2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 2"));
// Get both inner iframes, checking their contents are correct.
DOMElementProxyRef iframe1 =
frame1->GetDocumentFromFrame("0");
DOMElementProxyRef iframe2 =
frame2->GetDocumentFromFrame("0");
ASSERT_TRUE(iframe1 && iframe2);
frame_div = iframe1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 1"));
frame_div = iframe2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 2"));
// Get nested frame.
ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame("0", "0").get());
ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame("1", "0").get());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("events/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Click link and make sure text changes.
DOMElementProxyRef link = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(link && link->Click());
ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches("clicked"));
// Click input button and make sure textfield changes.
DOMElementProxyRef button = main_doc->FindElement(By::Selectors("#button"));
DOMElementProxyRef textfield =
main_doc->FindElement(By::Selectors("#textfield"));
ASSERT_TRUE(textfield && button && button->Click());
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("clicked"));
// Type in the textfield.
ASSERT_TRUE(textfield->SetText("test"));
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("test"));
// Type in the textarea.
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea && textarea->Type("test"));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches("textareatest"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("string_escape/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea);
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L"\u00FF")));
const wchar_t* set_and_expect_strings[] = {
L"\u00FF and \u00FF",
L"\n \t \\",
L"' \""
};
for (size_t i = 0; i < 3; i++) {
ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(
WideToUTF8(set_and_expect_strings[i])));
}
}
} // namespace
<commit_msg>Re-mark DOMAutomationTest.FindByXPath as FLAKY on Windows.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/test/automation/javascript_execution_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Tests the DOMAutomation framework for manipulating DOMElements within
// browser tests.
class DOMAutomationTest : public InProcessBrowserTest {
public:
DOMAutomationTest() {
EnableDOMAutomation();
JavaScriptExecutionController::set_timeout(30000);
}
GURL GetTestURL(const char* path) {
std::string url_path = "files/dom_automation/";
url_path.append(path);
return test_server()->GetURL(url_path);
}
};
typedef DOMElementProxy::By By;
#if defined(OS_WIN)
// See http://crbug.com/61636
#define MAYBE_FindByXPath FLAKY_FindByXPath
#else
#define MAYBE_FindByXPath FindByXPath
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByXPath) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_div = main_doc->FindElement(By::XPath("//div"));
ASSERT_TRUE(first_div);
ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//div"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::XPath("//nosuchtag")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::XPath("//nosuchtag"), &elements));
elements.clear();
ASSERT_EQ(0u, elements.size());
// Find with invalid xpath.
ASSERT_FALSE(main_doc->FindElement(By::XPath("'invalid'")));
ASSERT_FALSE(main_doc->FindElement(By::XPath(" / / ")));
ASSERT_FALSE(main_doc->FindElements(By::XPath("'invalid'"), &elements));
ASSERT_FALSE(main_doc->FindElements(By::XPath(" / / "), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::XPath("/html/body/span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::XPath("./span"));
}
ASSERT_EQ(3, nested_count);
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_myclass =
main_doc->FindElement(By::Selectors(".myclass"));
ASSERT_TRUE(first_myclass);
ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors(".myclass"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("#nosuchid")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Selectors("#nosuchid"), &elements));
ASSERT_EQ(0u, elements.size());
// Find with invalid selectors.
ASSERT_FALSE(main_doc->FindElement(By::Selectors("1#2")));
ASSERT_FALSE(main_doc->FindElements(By::Selectors("1#2"), &elements));
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Selectors("span"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Selectors("span"));
}
ASSERT_EQ(3, nested_count);
}
#if defined(OS_WIN)
// http://crbug.com/72745
#define MAYBE_FindByText FLAKY_FindByText
#else
#define MAYBE_FindByText FindByText
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("find_elements/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Find first element.
DOMElementProxyRef first_text = main_doc->FindElement(By::Text("div_text"));
ASSERT_TRUE(first_text);
ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches("0"));
// Find many elements.
std::vector<DOMElementProxyRef> elements;
ASSERT_TRUE(main_doc->FindElements(By::Text("div_text"), &elements));
ASSERT_EQ(2u, elements.size());
for (size_t i = 0; i < elements.size(); i++) {
ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
base::UintToString(i)));
}
// Find 0 elements.
ASSERT_FALSE(main_doc->FindElement(By::Text("nosuchtext")));
elements.clear();
ASSERT_TRUE(main_doc->FindElements(By::Text("nosuchtext"), &elements));
ASSERT_EQ(0u, elements.size());
// Find nested elements.
int nested_count = 0;
std::string span_name;
DOMElementProxyRef node = main_doc->FindElement(By::Text("span_text"));
while (node) {
nested_count++;
span_name.append("span");
ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
node = node->FindElement(By::Text("span_text"));
}
ASSERT_EQ(3, nested_count);
// Find only visible text.
DOMElementProxyRef shown_td = main_doc->FindElement(By::Text("table_text"));
ASSERT_TRUE(shown_td);
ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches("shown"));
// Find text in inputs.
ASSERT_TRUE(main_doc->FindElement(By::Text("textarea_text")));
ASSERT_TRUE(main_doc->FindElement(By::Text("input_text")));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef div =
main_doc->WaitFor1VisibleElement(By::Selectors("div"));
ASSERT_TRUE(div.get());
ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches("div_inner"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors("img")));
std::vector<DOMElementProxyRef> img_elements;
ASSERT_TRUE(main_doc->FindElements(By::Selectors("img"), &img_elements));
ASSERT_EQ(0u, img_elements.size());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(anchor.get());
ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(
"href", "http://www.google.com"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("frames/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Get both frame elements.
std::vector<DOMElementProxyRef> frame_elements;
ASSERT_TRUE(main_doc->FindElements(By::XPath("//frame"), &frame_elements));
ASSERT_EQ(2u, frame_elements.size());
// Get both frames, checking their contents are correct.
DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();
DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();
ASSERT_TRUE(frame1 && frame2);
DOMElementProxyRef frame_div =
frame1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 1"));
frame_div = frame2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 2"));
// Get both inner iframes, checking their contents are correct.
DOMElementProxyRef iframe1 =
frame1->GetDocumentFromFrame("0");
DOMElementProxyRef iframe2 =
frame2->GetDocumentFromFrame("0");
ASSERT_TRUE(iframe1 && iframe2);
frame_div = iframe1->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 1"));
frame_div = iframe2->FindElement(By::XPath("/html/body/div"));
ASSERT_TRUE(frame_div);
ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 2"));
// Get nested frame.
ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame("0", "0").get());
ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame("1", "0").get());
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(), GetTestURL("events/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
// Click link and make sure text changes.
DOMElementProxyRef link = main_doc->FindElement(By::Selectors("a"));
ASSERT_TRUE(link && link->Click());
ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches("clicked"));
// Click input button and make sure textfield changes.
DOMElementProxyRef button = main_doc->FindElement(By::Selectors("#button"));
DOMElementProxyRef textfield =
main_doc->FindElement(By::Selectors("#textfield"));
ASSERT_TRUE(textfield && button && button->Click());
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("clicked"));
// Type in the textfield.
ASSERT_TRUE(textfield->SetText("test"));
ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("test"));
// Type in the textarea.
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea && textarea->Type("test"));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches("textareatest"));
}
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {
ASSERT_TRUE(test_server()->Start());
ui_test_utils::NavigateToURL(browser(),
GetTestURL("string_escape/test.html"));
DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());
DOMElementProxyRef textarea =
main_doc->FindElement(By::Selectors("textarea"));
ASSERT_TRUE(textarea);
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L"\u00FF")));
const wchar_t* set_and_expect_strings[] = {
L"\u00FF and \u00FF",
L"\n \t \\",
L"' \""
};
for (size_t i = 0; i < 3; i++) {
ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));
ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(
WideToUTF8(set_and_expect_strings[i])));
}
}
} // namespace
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "recommender_base.hpp"
using std::make_pair;
using std::pair;
using std::string;
using std::vector;
namespace jubatus {
namespace core {
namespace recommender {
class recommender_impl : public recommender_base {
public:
recommender_impl()
: recommender_base() {
// make mock
orig_.set("r1", "a1", 1.0);
orig_.set("r1", "a2", 1.0);
orig_.set("r2", "b1", 1.0);
orig_.set("r2", "b2", 1.0);
orig_.set("r3", "a1", 1.0);
orig_.set("r3", "b1", 1.0);
}
void similar_row(
const common::sfv_t& query,
vector<pair<string, float> >& ids,
size_t ret_num) const {
ids.clear();
ids.push_back(make_pair("r1", 2.0));
ids.push_back(make_pair("r3", 1.0));
}
void neighbor_row(
const common::sfv_t& query,
vector<pair<string, float> >& ids,
size_t ret_num) const {
ids.clear();
ids.push_back(make_pair("r1", 1.0));
ids.push_back(make_pair("r3", 2.0));
}
void clear() {
}
void clear_row(const string& id) {
}
void update_row(const string& id, const sfv_diff_t& diff) {
}
void get_all_row_ids(vector<string>& ids) const {
ids.clear();
ids.push_back("r1");
ids.push_back("r2");
ids.push_back("r3");
}
string type() const {
return string("recommender_impl");
}
framework::mixable* get_mixable() const {}
void pack(framework::packer&) const {
}
void unpack(msgpack::object) {
}
};
TEST(recommender_base, complete_row) {
recommender_impl r;
common::sfv_t q;
common::sfv_t ret;
r.complete_row(q, ret);
ASSERT_EQ(3u, ret.size());
EXPECT_EQ("a1", ret[0].first);
EXPECT_EQ("a2", ret[1].first);
EXPECT_EQ("b1", ret[2].first);
}
TEST(recommender_base, get_all_row_ids) {
vector<string> ids;
recommender_impl r;
r.get_all_row_ids(ids);
ASSERT_EQ(3u, ids.size());
sort(ids.begin(), ids.end());
EXPECT_EQ("r1", ids[0]);
EXPECT_EQ("r2", ids[1]);
EXPECT_EQ("r3", ids[2]);
}
TEST(recommender_base, decode_row) {
recommender_impl r;
common::sfv_t v;
r.decode_row("r1", v);
ASSERT_EQ(2u, v.size());
EXPECT_EQ("a1", v[0].first);
EXPECT_EQ(1.0, v[0].second);
EXPECT_EQ("a2", v[1].first);
EXPECT_EQ(1.0, v[1].second);
r.decode_row("r", v);
ASSERT_TRUE(v.empty());
}
TEST(recommender_base, calc_l2norm) {
recommender_impl r;
common::sfv_t q;
q.push_back(make_pair("a1", 1.0));
q.push_back(make_pair("a2", 2.0));
q.push_back(make_pair("a3", 3.0));
EXPECT_FLOAT_EQ(std::sqrt(1.0 + 4.0 + 9.0), r.calc_l2norm(q));
}
TEST(recommender_base, calc_similality) {
recommender_impl r;
common::sfv_t q1;
common::sfv_t q2;
q1.push_back(make_pair("c1", 1.0));
q1.push_back(make_pair("c2", 2.0));
q1.push_back(make_pair("c3", 3.0));
q2.push_back(make_pair("c4", 2.0));
q2.push_back(make_pair("c3", 3.0));
q2.push_back(make_pair("c2", 3.0));
EXPECT_FLOAT_EQ(
(2.0 * 3.0 + 3.0 * 3.0) / r.calc_l2norm(q1) / r.calc_l2norm(q2),
r.calc_similality(q1, q2));
}
} // namespace recommender
} // namespace core
} // namespace jubatus
<commit_msg>Fix recommender_base_test for libc++.<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "recommender_base.hpp"
using std::make_pair;
using std::pair;
using std::string;
using std::vector;
namespace jubatus {
namespace core {
namespace recommender {
class recommender_impl : public recommender_base {
public:
recommender_impl()
: recommender_base() {
// make mock
orig_.set("r1", "a1", 1.0);
orig_.set("r1", "a2", 1.0);
orig_.set("r2", "b1", 1.0);
orig_.set("r2", "b2", 1.0);
orig_.set("r3", "a1", 1.0);
orig_.set("r3", "b1", 1.0);
}
void similar_row(
const common::sfv_t& query,
vector<pair<string, float> >& ids,
size_t ret_num) const {
ids.clear();
ids.push_back(make_pair("r1", 2.0));
ids.push_back(make_pair("r3", 1.0));
}
void neighbor_row(
const common::sfv_t& query,
vector<pair<string, float> >& ids,
size_t ret_num) const {
ids.clear();
ids.push_back(make_pair("r1", 1.0));
ids.push_back(make_pair("r3", 2.0));
}
void clear() {
}
void clear_row(const string& id) {
}
void update_row(const string& id, const sfv_diff_t& diff) {
}
void get_all_row_ids(vector<string>& ids) const {
ids.clear();
ids.push_back("r1");
ids.push_back("r2");
ids.push_back("r3");
}
string type() const {
return string("recommender_impl");
}
framework::mixable* get_mixable() const {}
void pack(framework::packer&) const {
}
void unpack(msgpack::object) {
}
};
TEST(recommender_base, complete_row) {
recommender_impl r;
common::sfv_t q;
common::sfv_t ret;
r.complete_row(q, ret);
ASSERT_EQ(3u, ret.size());
EXPECT_EQ("a1", ret[0].first);
EXPECT_EQ("a2", ret[1].first);
EXPECT_EQ("b1", ret[2].first);
}
TEST(recommender_base, get_all_row_ids) {
vector<string> ids;
recommender_impl r;
r.get_all_row_ids(ids);
ASSERT_EQ(3u, ids.size());
sort(ids.begin(), ids.end());
EXPECT_EQ("r1", ids[0]);
EXPECT_EQ("r2", ids[1]);
EXPECT_EQ("r3", ids[2]);
}
TEST(recommender_base, decode_row) {
recommender_impl r;
common::sfv_t v;
r.decode_row("r1", v);
ASSERT_EQ(2u, v.size());
std::sort(v.begin(), v.end());
EXPECT_EQ("a1", v[0].first);
EXPECT_EQ(1.0, v[0].second);
EXPECT_EQ("a2", v[1].first);
EXPECT_EQ(1.0, v[1].second);
r.decode_row("r", v);
ASSERT_TRUE(v.empty());
}
TEST(recommender_base, calc_l2norm) {
recommender_impl r;
common::sfv_t q;
q.push_back(make_pair("a1", 1.0));
q.push_back(make_pair("a2", 2.0));
q.push_back(make_pair("a3", 3.0));
EXPECT_FLOAT_EQ(std::sqrt(1.0 + 4.0 + 9.0), r.calc_l2norm(q));
}
TEST(recommender_base, calc_similality) {
recommender_impl r;
common::sfv_t q1;
common::sfv_t q2;
q1.push_back(make_pair("c1", 1.0));
q1.push_back(make_pair("c2", 2.0));
q1.push_back(make_pair("c3", 3.0));
q2.push_back(make_pair("c4", 2.0));
q2.push_back(make_pair("c3", 3.0));
q2.push_back(make_pair("c2", 3.0));
EXPECT_FLOAT_EQ(
(2.0 * 3.0 + 3.0 * 3.0) / r.calc_l2norm(q1) / r.calc_l2norm(q2),
r.calc_similality(q1, q2));
}
} // namespace recommender
} // namespace core
} // namespace jubatus
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <libtorrent/session.hpp>
using namespace boost::python;
using namespace libtorrent;
void bind_session_settings()
{
class_<session_settings>("session_settings")
.def_readwrite("user_agent", &session_settings::user_agent)
.def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
.def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
.def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
.def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
.def_readwrite("piece_timeout", &session_settings::piece_timeout)
.def_readwrite("request_timeout", &session_settings::request_timeout)
.def_readwrite("request_queue_time", &session_settings::request_queue_time)
.def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
.def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
.def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
.def_readwrite("peer_timeout", &session_settings::peer_timeout)
.def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
.def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
.def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
.def_readwrite("file_pool_size", &session_settings::file_pool_size)
.def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
.def_readwrite("max_failcount", &session_settings::max_failcount)
.def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
.def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
.def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
.def_readwrite("connection_speed", &session_settings::connection_speed)
.def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
.def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
.def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
.def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
.def_readwrite("optimistic_unchoke_interval", &session_settings::optimistic_unchoke_interval)
.def_readwrite("num_want", &session_settings::num_want)
.def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
.def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
.def_readwrite("max_queued_disk_bytes", &session_settings::max_queued_disk_bytes)
.def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
.def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
.def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
.def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
.def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
.def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
.def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
.def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
.def_readwrite("cache_size", &session_settings::cache_size)
.def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
.def_readwrite("cache_expiry", &session_settings::cache_expiry)
.def_readwrite("use_read_cache", &session_settings::use_read_cache)
.def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
.def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
.def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
.def_readwrite("coalesce_writes", &session_settings::coalesce_writes)
.def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
.def_readwrite("peer_tos", &session_settings::peer_tos)
.def_readwrite("active_downloads", &session_settings::active_downloads)
.def_readwrite("active_seeds", &session_settings::active_seeds)
.def_readwrite("active_limit", &session_settings::active_limit)
.def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
.def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
.def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
.def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
.def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
.def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
.def_readwrite("peer_turnover", &session_settings::peer_turnover)
.def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
.def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
.def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
.def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
.def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
.def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
.def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
.def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
.def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
.def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
.def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
.def_readwrite("announce_to_all_tiers", &session_settings::announce_to_all_tiers)
.def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
.def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
.def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
.def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
.def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
.def_readwrite("max_rejects", &session_settings::max_rejects)
.def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
.def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
.def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
.def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
.def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
.def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
.def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
.def_readwrite("optimistic_disk_retry", &session_settings::optimistic_disk_retry)
.def_readwrite("disable_hash_checks", &session_settings::disable_hash_checks)
.def_readwrite("allow_reordered_disk_operations", &session_settings::allow_reordered_disk_operations)
.def_readwrite("allow_i2p_mixed", &session_settings::allow_i2p_mixed)
.def_readwrite("max_suggest_pieces", &session_settings::max_suggest_pieces)
.def_readwrite("drop_skipped_requests", &session_settings::drop_skipped_requests)
.def_readwrite("low_prio_disk", &session_settings::low_prio_disk)
.def_readwrite("local_service_announce_interval", &session_settings::local_service_announce_interval)
.def_readwrite("udp_tracker_token_expiry", &session_settings::udp_tracker_token_expiry)
.def_readwrite("volatile_read_cache", &session_settings::volatile_read_cache)
.def_readwrite("guided_read_cache", &guided_read_cache)
;
enum_<proxy_settings::proxy_type>("proxy_type")
.value("none", proxy_settings::none)
.value("socks4", proxy_settings::socks4)
.value("socks5", proxy_settings::socks5)
.value("socks5_pw", proxy_settings::socks5_pw)
.value("http", proxy_settings::http)
.value("http_pw", proxy_settings::http_pw)
;
enum_<session_settings::disk_cache_algo_t>("disk_cache_algo_t")
.value("lru", session_settings::lru)
.value("largest_contiguous", session_settings::largest_contiguous)
;
enum_<session_settings::io_buffer_mode_t>("io_buffer_mode_t")
.value("enable_os_cache", session_settings::enable_os_cache)
.value("disable_os_cache_for_aligned_files", session_settings::disable_os_cache_for_aligned_files)
.value("disable_os_cache", session_settings::disable_os_cache)
;
class_<proxy_settings>("proxy_settings")
.def_readwrite("hostname", &proxy_settings::hostname)
.def_readwrite("port", &proxy_settings::port)
.def_readwrite("password", &proxy_settings::password)
.def_readwrite("username", &proxy_settings::username)
.def_readwrite("type", &proxy_settings::type)
;
#ifndef TORRENT_DISABLE_DHT
class_<dht_settings>("dht_settings")
.def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
.def_readwrite("search_branching", &dht_settings::search_branching)
.def_readwrite("service_port", &dht_settings::service_port)
.def_readwrite("max_fail_count", &dht_settings::max_fail_count)
;
#endif
#ifndef TORRENT_DISABLE_ENCRYPTION
enum_<pe_settings::enc_policy>("enc_policy")
.value("forced", pe_settings::forced)
.value("enabled", pe_settings::enabled)
.value("disabled", pe_settings::disabled)
;
enum_<pe_settings::enc_level>("enc_level")
.value("rc4", pe_settings::rc4)
.value("plaintext", pe_settings::plaintext)
.value("both", pe_settings::both)
;
class_<pe_settings>("pe_settings")
.def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
.def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
.def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
.def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
;
#endif
}
<commit_msg>fixed python binding<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <libtorrent/session.hpp>
using namespace boost::python;
using namespace libtorrent;
void bind_session_settings()
{
class_<session_settings>("session_settings")
.def_readwrite("user_agent", &session_settings::user_agent)
.def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
.def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
.def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
.def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
.def_readwrite("piece_timeout", &session_settings::piece_timeout)
.def_readwrite("request_timeout", &session_settings::request_timeout)
.def_readwrite("request_queue_time", &session_settings::request_queue_time)
.def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
.def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
.def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
.def_readwrite("peer_timeout", &session_settings::peer_timeout)
.def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
.def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
.def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
.def_readwrite("file_pool_size", &session_settings::file_pool_size)
.def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
.def_readwrite("max_failcount", &session_settings::max_failcount)
.def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
.def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
.def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
.def_readwrite("connection_speed", &session_settings::connection_speed)
.def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
.def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
.def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
.def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
.def_readwrite("optimistic_unchoke_interval", &session_settings::optimistic_unchoke_interval)
.def_readwrite("num_want", &session_settings::num_want)
.def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
.def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
.def_readwrite("max_queued_disk_bytes", &session_settings::max_queued_disk_bytes)
.def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
.def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
.def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
.def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
.def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
.def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
.def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
.def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
.def_readwrite("cache_size", &session_settings::cache_size)
.def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
.def_readwrite("cache_expiry", &session_settings::cache_expiry)
.def_readwrite("use_read_cache", &session_settings::use_read_cache)
.def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
.def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
.def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
.def_readwrite("coalesce_writes", &session_settings::coalesce_writes)
.def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
.def_readwrite("peer_tos", &session_settings::peer_tos)
.def_readwrite("active_downloads", &session_settings::active_downloads)
.def_readwrite("active_seeds", &session_settings::active_seeds)
.def_readwrite("active_limit", &session_settings::active_limit)
.def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
.def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
.def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
.def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
.def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
.def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
.def_readwrite("peer_turnover", &session_settings::peer_turnover)
.def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
.def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
.def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
.def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
.def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
.def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
.def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
.def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
.def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
.def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
.def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
.def_readwrite("announce_to_all_tiers", &session_settings::announce_to_all_tiers)
.def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
.def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
.def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
.def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
.def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
.def_readwrite("max_rejects", &session_settings::max_rejects)
.def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
.def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
.def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
.def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
.def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
.def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
.def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
.def_readwrite("optimistic_disk_retry", &session_settings::optimistic_disk_retry)
.def_readwrite("disable_hash_checks", &session_settings::disable_hash_checks)
.def_readwrite("allow_reordered_disk_operations", &session_settings::allow_reordered_disk_operations)
.def_readwrite("allow_i2p_mixed", &session_settings::allow_i2p_mixed)
.def_readwrite("max_suggest_pieces", &session_settings::max_suggest_pieces)
.def_readwrite("drop_skipped_requests", &session_settings::drop_skipped_requests)
.def_readwrite("low_prio_disk", &session_settings::low_prio_disk)
.def_readwrite("local_service_announce_interval", &session_settings::local_service_announce_interval)
.def_readwrite("udp_tracker_token_expiry", &session_settings::udp_tracker_token_expiry)
.def_readwrite("volatile_read_cache", &session_settings::volatile_read_cache)
.def_readwrite("guided_read_cache", &session_settings::guided_read_cache)
;
enum_<proxy_settings::proxy_type>("proxy_type")
.value("none", proxy_settings::none)
.value("socks4", proxy_settings::socks4)
.value("socks5", proxy_settings::socks5)
.value("socks5_pw", proxy_settings::socks5_pw)
.value("http", proxy_settings::http)
.value("http_pw", proxy_settings::http_pw)
;
enum_<session_settings::disk_cache_algo_t>("disk_cache_algo_t")
.value("lru", session_settings::lru)
.value("largest_contiguous", session_settings::largest_contiguous)
;
enum_<session_settings::io_buffer_mode_t>("io_buffer_mode_t")
.value("enable_os_cache", session_settings::enable_os_cache)
.value("disable_os_cache_for_aligned_files", session_settings::disable_os_cache_for_aligned_files)
.value("disable_os_cache", session_settings::disable_os_cache)
;
class_<proxy_settings>("proxy_settings")
.def_readwrite("hostname", &proxy_settings::hostname)
.def_readwrite("port", &proxy_settings::port)
.def_readwrite("password", &proxy_settings::password)
.def_readwrite("username", &proxy_settings::username)
.def_readwrite("type", &proxy_settings::type)
;
#ifndef TORRENT_DISABLE_DHT
class_<dht_settings>("dht_settings")
.def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
.def_readwrite("search_branching", &dht_settings::search_branching)
.def_readwrite("service_port", &dht_settings::service_port)
.def_readwrite("max_fail_count", &dht_settings::max_fail_count)
;
#endif
#ifndef TORRENT_DISABLE_ENCRYPTION
enum_<pe_settings::enc_policy>("enc_policy")
.value("forced", pe_settings::forced)
.value("enabled", pe_settings::enabled)
.value("disabled", pe_settings::disabled)
;
enum_<pe_settings::enc_level>("enc_level")
.value("rc4", pe_settings::rc4)
.value("plaintext", pe_settings::plaintext)
.value("both", pe_settings::both)
;
class_<pe_settings>("pe_settings")
.def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
.def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
.def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
.def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
;
#endif
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOpenGLGeometryBuffer.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :
OpenGLGeometryBufferBase(owner),
d_shader(owner.getShaderStandard()),
d_shaderPosLoc(owner.getShaderStandardPositionLoc()),
d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),
d_shaderColourLoc(owner.getShaderStandardColourLoc()),
d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),
d_glStateChanger(owner.getOpenGLStateChanger()),
d_bufferSize(0)
{
initialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
deinitialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
CEGUI::Rectf viewPort = d_owner->getActiveViewPort();
d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
static_cast<GLint>(d_clipRect.getWidth()),
static_cast<GLint>(d_clipRect.getHeight()));
// apply the transformations we need to use.
if (!d_matrixValid)
updateMatrix();
// Send ModelViewProjection matrix to shader
glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));
// activate desired blending mode
d_owner->setupRenderingBlendMode(d_blendMode);
// Bind our vao
d_glStateChanger->bindVertexArray(d_verticesVAO);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
size_t pos = 0;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
// draw the batches
BatchList::const_iterator i = d_batches.begin();
for ( ; i != d_batches.end(); ++i)
{
const BatchInfo& currentBatch = *i;
if (currentBatch.clip)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
glBindTexture(GL_TEXTURE_2D, currentBatch.texture);
// draw the geometry
const unsigned int numVertices = currentBatch.vertexCount;
glDrawArrays(GL_TRIANGLES, pos, numVertices);
pos += numVertices;
}
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,
uint vertex_count)
{
OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
OpenGLGeometryBufferBase::reset();
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseOpenGLBuffers()
{
glGenVertexArrays(1, &d_verticesVAO);
glBindVertexArray(d_verticesVAO);
// Generate and bind position vbo
glGenBuffers(1, &d_verticesVBO);
glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);
d_shader->bind();
GLsizei stride = 9 * sizeof(GL_FLOAT);
glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);
glEnableVertexAttribArray(d_shaderTexCoordLoc);
glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(d_shaderColourLoc);
glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(d_shaderPosLoc);
d_shader->unbind();
// Unbind Vertex Attribute Array (VAO)
glBindVertexArray(0);
// Unbind array and element array buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
glDeleteVertexArrays(1, &d_verticesVAO);
glDeleteBuffers(1, &d_verticesVBO);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
bool needNewBuffer = false;
unsigned int vertexCount = d_vertices.size();
if(d_bufferSize < vertexCount)
{
needNewBuffer = true;
d_bufferSize = vertexCount;
}
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
GLsizei dataSize = d_bufferSize * sizeof(GLVertex);
if(needNewBuffer)
{
glBufferData(GL_ARRAY_BUFFER, dataSize, d_vertices.data(), GL_DYNAMIC_DRAW);
}
else
{
glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, d_vertices.data());
}
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>FIX: Don't use std::vector::data since it only exists for C++11<commit_after>/***********************************************************************
filename: CEGUIOpenGLGeometryBuffer.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :
OpenGLGeometryBufferBase(owner),
d_shader(owner.getShaderStandard()),
d_shaderPosLoc(owner.getShaderStandardPositionLoc()),
d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),
d_shaderColourLoc(owner.getShaderStandardColourLoc()),
d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),
d_glStateChanger(owner.getOpenGLStateChanger()),
d_bufferSize(0)
{
initialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
deinitialiseOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
CEGUI::Rectf viewPort = d_owner->getActiveViewPort();
d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
static_cast<GLint>(d_clipRect.getWidth()),
static_cast<GLint>(d_clipRect.getHeight()));
// apply the transformations we need to use.
if (!d_matrixValid)
updateMatrix();
// Send ModelViewProjection matrix to shader
glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));
// activate desired blending mode
d_owner->setupRenderingBlendMode(d_blendMode);
// Bind our vao
d_glStateChanger->bindVertexArray(d_verticesVAO);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
size_t pos = 0;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
// draw the batches
BatchList::const_iterator i = d_batches.begin();
for ( ; i != d_batches.end(); ++i)
{
const BatchInfo& currentBatch = *i;
if (currentBatch.clip)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
glBindTexture(GL_TEXTURE_2D, currentBatch.texture);
// draw the geometry
const unsigned int numVertices = currentBatch.vertexCount;
glDrawArrays(GL_TRIANGLES, pos, numVertices);
pos += numVertices;
}
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,
uint vertex_count)
{
OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
OpenGLGeometryBufferBase::reset();
updateOpenGLBuffers();
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseOpenGLBuffers()
{
glGenVertexArrays(1, &d_verticesVAO);
glBindVertexArray(d_verticesVAO);
// Generate and bind position vbo
glGenBuffers(1, &d_verticesVBO);
glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);
d_shader->bind();
GLsizei stride = 9 * sizeof(GL_FLOAT);
glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);
glEnableVertexAttribArray(d_shaderTexCoordLoc);
glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(d_shaderColourLoc);
glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(d_shaderPosLoc);
d_shader->unbind();
// Unbind Vertex Attribute Array (VAO)
glBindVertexArray(0);
// Unbind array and element array buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
glDeleteVertexArrays(1, &d_verticesVAO);
glDeleteBuffers(1, &d_verticesVBO);
}
//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
bool needNewBuffer = false;
unsigned int vertexCount = d_vertices.size();
if(d_bufferSize < vertexCount)
{
needNewBuffer = true;
d_bufferSize = vertexCount;
}
d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);
GLsizei dataSize = d_bufferSize * sizeof(GLVertex);
if(needNewBuffer)
{
glBufferData(GL_ARRAY_BUFFER, dataSize, &d_vertices.front(), GL_DYNAMIC_DRAW);
}
else
{
glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, &d_vertices.front());
}
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#ifndef VEXCL_UTIL_HPP
#define VEXCL_UTIL_HPP
/*
The MIT License
Copyright (c) 2012-2013 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/util.hpp
* \author Denis Demidov <[email protected]>
* \brief OpenCL general utilities.
*/
#ifdef WIN32
# pragma warning(push)
# pragma warning(disable : 4267 4290)
# define NOMINMAX
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <climits>
#include <stdexcept>
#include <limits>
#include <boost/config.hpp>
#include <boost/type_traits/is_same.hpp>
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <CL/cl.hpp>
#include <vexcl/types.hpp>
typedef unsigned int uint;
typedef unsigned char uchar;
namespace vex {
/// Convert typename to string.
template <class T> inline std::string type_name() {
throw std::logic_error("Trying to use an undefined type in a kernel.");
}
/// Declares a type as CL native, allows using it as a literal.
template <class T> struct is_cl_native : std::false_type {};
#define STRINGIFY(type) \
template <> inline std::string type_name<cl_##type>() { return #type; } \
template <> struct is_cl_native<cl_##type> : std::true_type {};
// enable use of OpenCL vector types as literals
#define CL_VEC_TYPE(type, len) \
template <> inline std::string type_name<cl_##type##len>() { return #type #len; } \
template <> struct is_cl_native<cl_##type##len> : std::true_type {};
#define CL_TYPES(type) \
STRINGIFY(type); \
CL_VEC_TYPE(type, 2); \
CL_VEC_TYPE(type, 4); \
CL_VEC_TYPE(type, 8); \
CL_VEC_TYPE(type, 16);
CL_TYPES(float);
CL_TYPES(double);
CL_TYPES(char); CL_TYPES(uchar);
CL_TYPES(short); CL_TYPES(ushort);
CL_TYPES(int); CL_TYPES(uint);
CL_TYPES(long); CL_TYPES(ulong);
#undef CL_TYPES
#undef CL_VEC_TYPE
#undef STRINGIFY
#if defined(__clang__) && defined(__APPLE__)
template <> inline std::string type_name<size_t>() {
return std::numeric_limits<std::size_t>::max() ==
std::numeric_limits<uint>::max() ? "uint" : "ulong";
}
template <> struct is_cl_native<size_t> : std::true_type {};
#endif
const std::string standard_kernel_header = std::string(
"#if defined(cl_khr_fp64)\n"
"# pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
"#elif defined(cl_amd_fp64)\n"
"# pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
"#endif\n"
);
/// \cond INTERNAL
/// Binary operations with their traits.
namespace binop {
enum kind {
Add,
Subtract,
Multiply,
Divide,
Remainder,
Greater,
Less,
GreaterEqual,
LessEqual,
Equal,
NotEqual,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
LogicalAnd,
LogicalOr,
RightShift,
LeftShift
};
template <kind> struct traits {};
#define BOP_TRAITS(kind, op, nm) \
template <> struct traits<kind> { \
static std::string oper() { return op; } \
static std::string name() { return nm; } \
};
BOP_TRAITS(Add, "+", "Add_")
BOP_TRAITS(Subtract, "-", "Sub_")
BOP_TRAITS(Multiply, "*", "Mul_")
BOP_TRAITS(Divide, "/", "Div_")
BOP_TRAITS(Remainder, "%", "Mod_")
BOP_TRAITS(Greater, ">", "Gtr_")
BOP_TRAITS(Less, "<", "Lss_")
BOP_TRAITS(GreaterEqual, ">=", "Geq_")
BOP_TRAITS(LessEqual, "<=", "Leq_")
BOP_TRAITS(Equal, "==", "Equ_")
BOP_TRAITS(NotEqual, "!=", "Neq_")
BOP_TRAITS(BitwiseAnd, "&", "BAnd_")
BOP_TRAITS(BitwiseOr, "|", "BOr_")
BOP_TRAITS(BitwiseXor, "^", "BXor_")
BOP_TRAITS(LogicalAnd, "&&", "LAnd_")
BOP_TRAITS(LogicalOr, "||", "LOr_")
BOP_TRAITS(RightShift, ">>", "Rsh_")
BOP_TRAITS(LeftShift, "<<", "Lsh_")
#undef BOP_TRAITS
}
/// \endcond
/// Return next power of 2.
inline size_t nextpow2(size_t x) {
--x;
x |= x >> 1U;
x |= x >> 2U;
x |= x >> 4U;
x |= x >> 8U;
x |= x >> 16U;
return ++x;
}
/// Align n to the next multiple of m.
inline size_t alignup(size_t n, size_t m = 16U) {
return n % m ? n - n % m + m : n;
}
/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I == std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &, Function &)
{ }
/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I < std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &v, Function &f)
{
f( std::get<I>(v) );
for_each<I + 1>(v, f);
}
/// Create and build a program from source string.
inline cl::Program build_sources(
const cl::Context &context, const std::string &source
)
{
cl::Program program(context, cl::Program::Sources(
1, std::make_pair(source.c_str(), source.size())
));
auto device = context.getInfo<CL_CONTEXT_DEVICES>();
try {
program.build(device);
} catch(const cl::Error&) {
std::cerr << source
<< std::endl
<< program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
<< std::endl;
throw;
}
return program;
}
/// Get maximum possible workgroup size for given kernel.
inline uint kernel_workgroup_size(
const cl::Kernel &kernel,
const cl::Device &device
)
{
size_t wgsz = 1024U;
uint dev_wgsz = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
while(wgsz > dev_wgsz) wgsz /= 2;
return wgsz;
}
/// Shortcut for q.getInfo<CL_QUEUE_CONTEXT>()
inline cl::Context qctx(const cl::CommandQueue& q) {
cl::Context ctx;
q.getInfo(CL_QUEUE_CONTEXT, &ctx);
return ctx;
}
/// Shortcut for q.getInfo<CL_QUEUE_DEVICE>()
inline cl::Device qdev(const cl::CommandQueue& q) {
cl::Device dev;
q.getInfo(CL_QUEUE_DEVICE, &dev);
return dev;
}
struct column_owner {
const std::vector<size_t> ∂
column_owner(const std::vector<size_t> &part) : part(part) {}
size_t operator()(size_t c) const {
return std::upper_bound(part.begin(), part.end(), c)
- part.begin() - 1;
}
};
} // namespace vex
/// Output description of an OpenCL error to a stream.
inline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {
os << e.what() << "(";
switch (e.err()) {
case 0:
os << "Success";
break;
case -1:
os << "Device not found";
break;
case -2:
os << "Device not available";
break;
case -3:
os << "Compiler not available";
break;
case -4:
os << "Mem object allocation failure";
break;
case -5:
os << "Out of resources";
break;
case -6:
os << "Out of host memory";
break;
case -7:
os << "Profiling info not available";
break;
case -8:
os << "Mem copy overlap";
break;
case -9:
os << "Image format mismatch";
break;
case -10:
os << "Image format not supported";
break;
case -11:
os << "Build program failure";
break;
case -12:
os << "Map failure";
break;
case -13:
os << "Misaligned sub buffer offset";
break;
case -14:
os << "Exec status error for events in wait list";
break;
case -30:
os << "Invalid value";
break;
case -31:
os << "Invalid device type";
break;
case -32:
os << "Invalid platform";
break;
case -33:
os << "Invalid device";
break;
case -34:
os << "Invalid context";
break;
case -35:
os << "Invalid queue properties";
break;
case -36:
os << "Invalid command queue";
break;
case -37:
os << "Invalid host ptr";
break;
case -38:
os << "Invalid mem object";
break;
case -39:
os << "Invalid image format descriptor";
break;
case -40:
os << "Invalid image size";
break;
case -41:
os << "Invalid sampler";
break;
case -42:
os << "Invalid binary";
break;
case -43:
os << "Invalid build options";
break;
case -44:
os << "Invalid program";
break;
case -45:
os << "Invalid program executable";
break;
case -46:
os << "Invalid kernel name";
break;
case -47:
os << "Invalid kernel definition";
break;
case -48:
os << "Invalid kernel";
break;
case -49:
os << "Invalid arg index";
break;
case -50:
os << "Invalid arg value";
break;
case -51:
os << "Invalid arg size";
break;
case -52:
os << "Invalid kernel args";
break;
case -53:
os << "Invalid work dimension";
break;
case -54:
os << "Invalid work group size";
break;
case -55:
os << "Invalid work item size";
break;
case -56:
os << "Invalid global offset";
break;
case -57:
os << "Invalid event wait list";
break;
case -58:
os << "Invalid event";
break;
case -59:
os << "Invalid operation";
break;
case -60:
os << "Invalid gl object";
break;
case -61:
os << "Invalid buffer size";
break;
case -62:
os << "Invalid mip level";
break;
case -63:
os << "Invalid global work size";
break;
case -64:
os << "Invalid property";
break;
default:
os << "Unknown error";
break;
}
return os << ")";
}
#ifdef WIN32
# pragma warning(pop)
#endif
// vim: et
#endif
<commit_msg>Add ptrdiff_t specialization for Apple's clang<commit_after>#ifndef VEXCL_UTIL_HPP
#define VEXCL_UTIL_HPP
/*
The MIT License
Copyright (c) 2012-2013 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/util.hpp
* \author Denis Demidov <[email protected]>
* \brief OpenCL general utilities.
*/
#ifdef WIN32
# pragma warning(push)
# pragma warning(disable : 4267 4290)
# define NOMINMAX
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <climits>
#include <stdexcept>
#include <limits>
#include <boost/config.hpp>
#include <boost/type_traits/is_same.hpp>
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <CL/cl.hpp>
#include <vexcl/types.hpp>
typedef unsigned int uint;
typedef unsigned char uchar;
namespace vex {
/// Convert typename to string.
template <class T> inline std::string type_name() {
throw std::logic_error("Trying to use an undefined type in a kernel.");
}
/// Declares a type as CL native, allows using it as a literal.
template <class T> struct is_cl_native : std::false_type {};
#define STRINGIFY(type) \
template <> inline std::string type_name<cl_##type>() { return #type; } \
template <> struct is_cl_native<cl_##type> : std::true_type {};
// enable use of OpenCL vector types as literals
#define CL_VEC_TYPE(type, len) \
template <> inline std::string type_name<cl_##type##len>() { return #type #len; } \
template <> struct is_cl_native<cl_##type##len> : std::true_type {};
#define CL_TYPES(type) \
STRINGIFY(type); \
CL_VEC_TYPE(type, 2); \
CL_VEC_TYPE(type, 4); \
CL_VEC_TYPE(type, 8); \
CL_VEC_TYPE(type, 16);
CL_TYPES(float);
CL_TYPES(double);
CL_TYPES(char); CL_TYPES(uchar);
CL_TYPES(short); CL_TYPES(ushort);
CL_TYPES(int); CL_TYPES(uint);
CL_TYPES(long); CL_TYPES(ulong);
#undef CL_TYPES
#undef CL_VEC_TYPE
#undef STRINGIFY
#if defined(__clang__) && defined(__APPLE__)
template <> inline std::string type_name<size_t>() {
return std::numeric_limits<std::size_t>::max() ==
std::numeric_limits<uint>::max() ? "uint" : "ulong";
}
template <> struct is_cl_native<size_t> : std::true_type {};
template <> inline std::string type_name<ptrdiff_t>() {
return std::numeric_limits<std::ptrdiff_t>::max() ==
std::numeric_limits<int>::max() ? "int" : "long";
}
template <> struct is_cl_native<ptrdiff_t> : std::true_type {};
#endif
const std::string standard_kernel_header = std::string(
"#if defined(cl_khr_fp64)\n"
"# pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
"#elif defined(cl_amd_fp64)\n"
"# pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
"#endif\n"
);
/// \cond INTERNAL
/// Binary operations with their traits.
namespace binop {
enum kind {
Add,
Subtract,
Multiply,
Divide,
Remainder,
Greater,
Less,
GreaterEqual,
LessEqual,
Equal,
NotEqual,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
LogicalAnd,
LogicalOr,
RightShift,
LeftShift
};
template <kind> struct traits {};
#define BOP_TRAITS(kind, op, nm) \
template <> struct traits<kind> { \
static std::string oper() { return op; } \
static std::string name() { return nm; } \
};
BOP_TRAITS(Add, "+", "Add_")
BOP_TRAITS(Subtract, "-", "Sub_")
BOP_TRAITS(Multiply, "*", "Mul_")
BOP_TRAITS(Divide, "/", "Div_")
BOP_TRAITS(Remainder, "%", "Mod_")
BOP_TRAITS(Greater, ">", "Gtr_")
BOP_TRAITS(Less, "<", "Lss_")
BOP_TRAITS(GreaterEqual, ">=", "Geq_")
BOP_TRAITS(LessEqual, "<=", "Leq_")
BOP_TRAITS(Equal, "==", "Equ_")
BOP_TRAITS(NotEqual, "!=", "Neq_")
BOP_TRAITS(BitwiseAnd, "&", "BAnd_")
BOP_TRAITS(BitwiseOr, "|", "BOr_")
BOP_TRAITS(BitwiseXor, "^", "BXor_")
BOP_TRAITS(LogicalAnd, "&&", "LAnd_")
BOP_TRAITS(LogicalOr, "||", "LOr_")
BOP_TRAITS(RightShift, ">>", "Rsh_")
BOP_TRAITS(LeftShift, "<<", "Lsh_")
#undef BOP_TRAITS
}
/// \endcond
/// Return next power of 2.
inline size_t nextpow2(size_t x) {
--x;
x |= x >> 1U;
x |= x >> 2U;
x |= x >> 4U;
x |= x >> 8U;
x |= x >> 16U;
return ++x;
}
/// Align n to the next multiple of m.
inline size_t alignup(size_t n, size_t m = 16U) {
return n % m ? n - n % m + m : n;
}
/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I == std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &, Function &)
{ }
/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I < std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &v, Function &f)
{
f( std::get<I>(v) );
for_each<I + 1>(v, f);
}
/// Create and build a program from source string.
inline cl::Program build_sources(
const cl::Context &context, const std::string &source
)
{
cl::Program program(context, cl::Program::Sources(
1, std::make_pair(source.c_str(), source.size())
));
auto device = context.getInfo<CL_CONTEXT_DEVICES>();
try {
program.build(device);
} catch(const cl::Error&) {
std::cerr << source
<< std::endl
<< program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
<< std::endl;
throw;
}
return program;
}
/// Get maximum possible workgroup size for given kernel.
inline uint kernel_workgroup_size(
const cl::Kernel &kernel,
const cl::Device &device
)
{
size_t wgsz = 1024U;
uint dev_wgsz = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
while(wgsz > dev_wgsz) wgsz /= 2;
return wgsz;
}
/// Shortcut for q.getInfo<CL_QUEUE_CONTEXT>()
inline cl::Context qctx(const cl::CommandQueue& q) {
cl::Context ctx;
q.getInfo(CL_QUEUE_CONTEXT, &ctx);
return ctx;
}
/// Shortcut for q.getInfo<CL_QUEUE_DEVICE>()
inline cl::Device qdev(const cl::CommandQueue& q) {
cl::Device dev;
q.getInfo(CL_QUEUE_DEVICE, &dev);
return dev;
}
struct column_owner {
const std::vector<size_t> ∂
column_owner(const std::vector<size_t> &part) : part(part) {}
size_t operator()(size_t c) const {
return std::upper_bound(part.begin(), part.end(), c)
- part.begin() - 1;
}
};
} // namespace vex
/// Output description of an OpenCL error to a stream.
inline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {
os << e.what() << "(";
switch (e.err()) {
case 0:
os << "Success";
break;
case -1:
os << "Device not found";
break;
case -2:
os << "Device not available";
break;
case -3:
os << "Compiler not available";
break;
case -4:
os << "Mem object allocation failure";
break;
case -5:
os << "Out of resources";
break;
case -6:
os << "Out of host memory";
break;
case -7:
os << "Profiling info not available";
break;
case -8:
os << "Mem copy overlap";
break;
case -9:
os << "Image format mismatch";
break;
case -10:
os << "Image format not supported";
break;
case -11:
os << "Build program failure";
break;
case -12:
os << "Map failure";
break;
case -13:
os << "Misaligned sub buffer offset";
break;
case -14:
os << "Exec status error for events in wait list";
break;
case -30:
os << "Invalid value";
break;
case -31:
os << "Invalid device type";
break;
case -32:
os << "Invalid platform";
break;
case -33:
os << "Invalid device";
break;
case -34:
os << "Invalid context";
break;
case -35:
os << "Invalid queue properties";
break;
case -36:
os << "Invalid command queue";
break;
case -37:
os << "Invalid host ptr";
break;
case -38:
os << "Invalid mem object";
break;
case -39:
os << "Invalid image format descriptor";
break;
case -40:
os << "Invalid image size";
break;
case -41:
os << "Invalid sampler";
break;
case -42:
os << "Invalid binary";
break;
case -43:
os << "Invalid build options";
break;
case -44:
os << "Invalid program";
break;
case -45:
os << "Invalid program executable";
break;
case -46:
os << "Invalid kernel name";
break;
case -47:
os << "Invalid kernel definition";
break;
case -48:
os << "Invalid kernel";
break;
case -49:
os << "Invalid arg index";
break;
case -50:
os << "Invalid arg value";
break;
case -51:
os << "Invalid arg size";
break;
case -52:
os << "Invalid kernel args";
break;
case -53:
os << "Invalid work dimension";
break;
case -54:
os << "Invalid work group size";
break;
case -55:
os << "Invalid work item size";
break;
case -56:
os << "Invalid global offset";
break;
case -57:
os << "Invalid event wait list";
break;
case -58:
os << "Invalid event";
break;
case -59:
os << "Invalid operation";
break;
case -60:
os << "Invalid gl object";
break;
case -61:
os << "Invalid buffer size";
break;
case -62:
os << "Invalid mip level";
break;
case -63:
os << "Invalid global work size";
break;
case -64:
os << "Invalid property";
break;
default:
os << "Unknown error";
break;
}
return os << ")";
}
#ifdef WIN32
# pragma warning(pop)
#endif
// vim: et
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon ([email protected])
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_light.cpp implementation of the GLC_Light class.
#include <QtDebug>
#include "glc_light.h"
#include "glc_openglexception.h"
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light()
:GLC_Object("Light")
, m_LightID(GL_LIGHT1) // Default Light ID
, m_ListID(0) // By default display list ID= 0
, m_ListIsValid(false) // By default display list is not valid
, m_AmbientColor() // Ambient color will be set in the constructor
, m_DiffuseColor(Qt::white) // By default diffuse color is set to white
, m_SpecularColor(Qt::white) // By default specular color is set to white
, m_Position()
{
//! \todo modify class to support multi light
m_AmbientColor.setRgbF(0.2, 0.2, 0.2, 1.0); // By default light's color is dark grey
}
GLC_Light::GLC_Light(const QColor& color)
:GLC_Object("Light")
, m_LightID(GL_LIGHT1) // Default Light ID
, m_ListID(0) // By default display list ID= 0
, m_ListIsValid(false) // By default display list is not valid
, m_AmbientColor(color) // the ambiant color of the light
, m_DiffuseColor(Qt::white) // By default diffuse color is set to white
, m_SpecularColor(Qt::white) // By default specular color is set to white
, m_Position()
{
//! \todo modify class to support multi light
}
GLC_Light::~GLC_Light(void)
{
deleteList();
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Set the lihgt position by a 4D vector
void GLC_Light::setPosition(const GLC_Vector4d &vectPos)
{
m_Position= vectPos;
m_ListIsValid = false;
}
// Set the lihgt position by a 3 GLfloat
void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
m_Position.setX(x);
m_Position.setY(y);
m_Position.setZ(z);
m_ListIsValid = false;
}
// Set light's ambiant color by a QColor
void GLC_Light::setAmbientColor(const QColor& color)
{
m_AmbientColor= color;
m_ListIsValid = false;
}
// Set light's diffuse color by a QColor
void GLC_Light::setDiffuseColor(const QColor& color)
{
m_DiffuseColor= color;
m_ListIsValid = false;
}
// Set light's specular color by a QColor
void GLC_Light::setSpecularColor(const QColor& color)
{
m_SpecularColor= color;
m_ListIsValid = false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Create light's OpenGL list
void GLC_Light::creationList(GLenum Mode)
{
if(!m_ListID) // OpenGL list not created
{
m_ListID= glGenLists(1);
if (!m_ListID) // OpenGL List Id not get
{
glDraw();
qDebug("GLC_Lumiere::CreationListe Display list not create");
}
}
// OpenGL list creation and execution
glNewList(m_ListID, Mode);
// Light execution
glDraw();
glEndList();
// Indicateur de la validit de la liste
m_ListIsValid= true;
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Light::CreationList ", error);
throw(OpenGlException);
}
}
// Execute OpenGL light
void GLC_Light::glExecute(GLenum Mode)
{
// Object Name
glLoadName(getID());
if (!m_ListIsValid)
{
// OpenGL list is not valid
creationList(Mode);
}
else
{
glCallList(m_ListID);
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Light::GlExecute ", error);
throw(OpenGlException);
}
}
// OpenGL light set up
void GLC_Light::glDraw(void)
{
// Color
GLfloat setArray[4]= {static_cast<GLfloat>(m_AmbientColor.redF()),
static_cast<GLfloat>(m_AmbientColor.greenF()),
static_cast<GLfloat>(m_AmbientColor.blueF()),
static_cast<GLfloat>(m_AmbientColor.alphaF())};
glLightfv(m_LightID, GL_AMBIENT, setArray); // Setup The Ambient Light
setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
glLightfv(m_LightID, GL_DIFFUSE, setArray); // Setup The Diffuse Light
setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
glLightfv(m_LightID, GL_SPECULAR, setArray); // Setup The specular Light
// Position
setArray[0]= static_cast<GLfloat>(m_Position.getX());
setArray[1]= static_cast<GLfloat>(m_Position.getY());
setArray[2]= static_cast<GLfloat>(m_Position.getZ());
setArray[3]= static_cast<GLfloat>(m_Position.getW());
glLightfv(m_LightID, GL_POSITION, setArray); // Position The Light
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Light::GlDraw ", error);
throw(OpenGlException);
}
}
//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
// Delete OpenGL Display list
void GLC_Light::deleteList(void)
{
//! if the list is valid, the list is deleted
if (glIsList(m_ListID))
{
glDeleteLists(m_ListID, 1);
}
}
<commit_msg>modification off the default light color<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon ([email protected])
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_light.cpp implementation of the GLC_Light class.
#include <QtDebug>
#include "glc_light.h"
#include "glc_openglexception.h"
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light()
:GLC_Object("Light")
, m_LightID(GL_LIGHT1) // Default Light ID
, m_ListID(0) // By default display list ID= 0
, m_ListIsValid(false) // By default display list is not valid
, m_AmbientColor(Qt::black) // By default diffuse color is set to black
, m_DiffuseColor(Qt::white) // By default diffuse color is set to white
, m_SpecularColor(Qt::white) // By default specular color is set to white
, m_Position()
{
//! \todo modify class to support multi light
}
GLC_Light::GLC_Light(const QColor& color)
:GLC_Object("Light")
, m_LightID(GL_LIGHT1) // Default Light ID
, m_ListID(0) // By default display list ID= 0
, m_ListIsValid(false) // By default display list is not valid
, m_AmbientColor(Qt::black) // By default diffuse color is set to black
, m_DiffuseColor(color) // Diffuse color is set to color
, m_SpecularColor(Qt::white) // By default specular color is set to white
, m_Position()
{
//! \todo modify class to support multi light
}
GLC_Light::~GLC_Light(void)
{
deleteList();
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Set the lihgt position by a 4D vector
void GLC_Light::setPosition(const GLC_Vector4d &vectPos)
{
m_Position= vectPos;
m_ListIsValid = false;
}
// Set the lihgt position by a 3 GLfloat
void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
m_Position.setX(x);
m_Position.setY(y);
m_Position.setZ(z);
m_ListIsValid = false;
}
// Set light's ambiant color by a QColor
void GLC_Light::setAmbientColor(const QColor& color)
{
m_AmbientColor= color;
m_ListIsValid = false;
}
// Set light's diffuse color by a QColor
void GLC_Light::setDiffuseColor(const QColor& color)
{
m_DiffuseColor= color;
m_ListIsValid = false;
}
// Set light's specular color by a QColor
void GLC_Light::setSpecularColor(const QColor& color)
{
m_SpecularColor= color;
m_ListIsValid = false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Create light's OpenGL list
void GLC_Light::creationList(GLenum Mode)
{
if(!m_ListID) // OpenGL list not created
{
m_ListID= glGenLists(1);
if (!m_ListID) // OpenGL List Id not get
{
glDraw();
qDebug("GLC_Lumiere::CreationListe Display list not create");
}
}
// OpenGL list creation and execution
glNewList(m_ListID, Mode);
// Light execution
glDraw();
glEndList();
// Indicateur de la validit de la liste
m_ListIsValid= true;
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Light::CreationList ", error);
throw(OpenGlException);
}
}
// Execute OpenGL light
void GLC_Light::glExecute(GLenum Mode)
{
// Object Name
glLoadName(getID());
if (!m_ListIsValid)
{
// OpenGL list is not valid
creationList(Mode);
}
else
{
glCallList(m_ListID);
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Light::GlExecute ", error);
throw(OpenGlException);
}
}
// OpenGL light set up
void GLC_Light::glDraw(void)
{
// Color
GLfloat setArray[4]= {static_cast<GLfloat>(m_AmbientColor.redF()),
static_cast<GLfloat>(m_AmbientColor.greenF()),
static_cast<GLfloat>(m_AmbientColor.blueF()),
static_cast<GLfloat>(m_AmbientColor.alphaF())};
glLightfv(m_LightID, GL_AMBIENT, setArray); // Setup The Ambient Light
setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
glLightfv(m_LightID, GL_DIFFUSE, setArray); // Setup The Diffuse Light
setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
glLightfv(m_LightID, GL_SPECULAR, setArray); // Setup The specular Light
// Position
setArray[0]= static_cast<GLfloat>(m_Position.getX());
setArray[1]= static_cast<GLfloat>(m_Position.getY());
setArray[2]= static_cast<GLfloat>(m_Position.getZ());
setArray[3]= static_cast<GLfloat>(m_Position.getW());
glLightfv(m_LightID, GL_POSITION, setArray); // Position The Light
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Light::GlDraw ", error);
throw(OpenGlException);
}
}
//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
// Delete OpenGL Display list
void GLC_Light::deleteList(void)
{
//! if the list is valid, the list is deleted
if (glIsList(m_ListID))
{
glDeleteLists(m_ListID, 1);
}
}
<|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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<commit_msg>Marking ExtensionApiTest, Infobars as DISABLED on everything but Windows.<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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/safe_browsing_database.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_impl.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_bloom.h"
#include "googleurl/src/gurl.h"
// Filename suffix for the bloom filter.
static const wchar_t kBloomFilterFile[] = L" Filter";
// Factory method.
SafeBrowsingDatabase* SafeBrowsingDatabase::Create() {
return new SafeBrowsingDatabaseImpl;
}
bool SafeBrowsingDatabase::NeedToCheckUrl(const GURL& url) {
if (!bloom_filter_.get())
return true;
IncrementBloomFilterReadCount();
std::vector<std::string> hosts;
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
if (hosts.size() == 0)
return false; // Could be about:blank.
SBPrefix host_key;
if (url.HostIsIPAddress()) {
base::SHA256HashString(url.host() + "/", &host_key, sizeof(SBPrefix));
if (bloom_filter_->Exists(host_key))
return true;
} else {
base::SHA256HashString(hosts[0] + "/", &host_key, sizeof(SBPrefix));
if (bloom_filter_->Exists(host_key))
return true;
if (hosts.size() > 1) {
base::SHA256HashString(hosts[1] + "/", &host_key, sizeof(SBPrefix));
if (bloom_filter_->Exists(host_key))
return true;
}
}
return false;
}
std::wstring SafeBrowsingDatabase::BloomFilterFilename(
const std::wstring& db_filename) {
return db_filename + kBloomFilterFile;
}
void SafeBrowsingDatabase::LoadBloomFilter() {
DCHECK(!bloom_filter_filename_.empty());
int64 size_64;
if (!file_util::GetFileSize(bloom_filter_filename_, &size_64) ||
size_64 == 0) {
BuildBloomFilter();
return;
}
int size = static_cast<int>(size_64);
char* data = new char[size];
CHECK(data);
Time before = Time::Now();
file_util::ReadFile(bloom_filter_filename_, data, size);
SB_DLOG(INFO) << "SafeBrowsingDatabase read bloom filter in " <<
(Time::Now() - before).InMilliseconds() << " ms";
bloom_filter_.reset(new BloomFilter(data, size));
}
void SafeBrowsingDatabase::DeleteBloomFilter() {
file_util::Delete(bloom_filter_filename_, false);
}
void SafeBrowsingDatabase::WriteBloomFilter() {
if (!bloom_filter_.get())
return;
Time before = Time::Now();
file_util::WriteFile(bloom_filter_filename_,
bloom_filter_->data(),
bloom_filter_->size());
SB_DLOG(INFO) << "SafeBrowsingDatabase wrote bloom filter in " <<
(Time::Now() - before).InMilliseconds() << " ms";
}
<commit_msg>Provide an option to turn on the new SafeBrowsing storage system via a command line flag ("--new-safe-browsing").<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/safe_browsing_database.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_impl.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_bloom.h"
#include "chrome/common/chrome_switches.h"
#include "googleurl/src/gurl.h"
// Filename suffix for the bloom filter.
static const wchar_t kBloomFilterFile[] = L" Filter";
// Factory method.
SafeBrowsingDatabase* SafeBrowsingDatabase::Create() {
if (CommandLine().HasSwitch(switches::kUseNewSafeBrowsing))
return new SafeBrowsingDatabaseBloom;
return new SafeBrowsingDatabaseImpl;
}
bool SafeBrowsingDatabase::NeedToCheckUrl(const GURL& url) {
if (!bloom_filter_.get())
return true;
IncrementBloomFilterReadCount();
std::vector<std::string> hosts;
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
if (hosts.size() == 0)
return false; // Could be about:blank.
SBPrefix host_key;
if (url.HostIsIPAddress()) {
base::SHA256HashString(url.host() + "/", &host_key, sizeof(SBPrefix));
if (bloom_filter_->Exists(host_key))
return true;
} else {
base::SHA256HashString(hosts[0] + "/", &host_key, sizeof(SBPrefix));
if (bloom_filter_->Exists(host_key))
return true;
if (hosts.size() > 1) {
base::SHA256HashString(hosts[1] + "/", &host_key, sizeof(SBPrefix));
if (bloom_filter_->Exists(host_key))
return true;
}
}
return false;
}
std::wstring SafeBrowsingDatabase::BloomFilterFilename(
const std::wstring& db_filename) {
return db_filename + kBloomFilterFile;
}
void SafeBrowsingDatabase::LoadBloomFilter() {
DCHECK(!bloom_filter_filename_.empty());
int64 size_64;
if (!file_util::GetFileSize(bloom_filter_filename_, &size_64) ||
size_64 == 0) {
BuildBloomFilter();
return;
}
int size = static_cast<int>(size_64);
char* data = new char[size];
CHECK(data);
Time before = Time::Now();
file_util::ReadFile(bloom_filter_filename_, data, size);
SB_DLOG(INFO) << "SafeBrowsingDatabase read bloom filter in " <<
(Time::Now() - before).InMilliseconds() << " ms";
bloom_filter_.reset(new BloomFilter(data, size));
}
void SafeBrowsingDatabase::DeleteBloomFilter() {
file_util::Delete(bloom_filter_filename_, false);
}
void SafeBrowsingDatabase::WriteBloomFilter() {
if (!bloom_filter_.get())
return;
Time before = Time::Now();
file_util::WriteFile(bloom_filter_filename_,
bloom_filter_->data(),
bloom_filter_->size());
SB_DLOG(INFO) << "SafeBrowsingDatabase wrote bloom filter in " <<
(Time::Now() - before).InMilliseconds() << " ms";
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
hipError_t hipMalloc(void** ptr, size_t sizeBytes)
{
HIP_INIT_API(ptr, sizeBytes);
amd::Context* context = as_amd(g_currentCtx);
if (sizeBytes == 0) {
*ptr = nullptr;
return hipSuccess;
}
else if (!is_valid(context) || !ptr) {
return hipErrorInvalidValue;
}
auto deviceHandle = as_amd(g_deviceArray[0]);
if ((deviceHandle->info().maxMemAllocSize_ < size)) {
return hipErrorOutOfMemory;
}
amd::Memory* mem = new (*context) amd::Buffer(*context, 0, sizeBytes);
if (!mem) {
return hipErrorOutOfMemory;
}
if (!mem->create(nullptr)) {
return hipErrorMemoryAllocation;
}
*ptr = reinterpret_cast<void*>(as_cl(mem));
return hipSuccess;
}
hipError_t hipFree(void* ptr)
{
if (!is_valid(reinterpret_cast<cl_mem>(ptr))) {
return hipErrorInvalidValue;
}
as_amd(reinterpret_cast<cl_mem>(ptr))->release();
return hipSuccess;
}
<commit_msg>P4 to Git Change 1516173 by skudchad@skudchad_rocm on 2018/02/14 15:02:45<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
hipError_t hipMalloc(void** ptr, size_t sizeBytes)
{
HIP_INIT_API(ptr, sizeBytes);
amd::Context* context = as_amd(g_currentCtx);
if (sizeBytes == 0) {
*ptr = nullptr;
return hipSuccess;
}
else if (!is_valid(context) || !ptr) {
return hipErrorInvalidValue;
}
auto deviceHandle = as_amd(g_deviceArray[0]);
if ((deviceHandle->info().maxMemAllocSize_ < size)) {
return hipErrorOutOfMemory;
}
amd::Memory* mem = new (*context) amd::Buffer(*context, 0, sizeBytes);
if (!mem) {
return hipErrorOutOfMemory;
}
if (!mem->create(nullptr)) {
return hipErrorMemoryAllocation;
}
*ptr = reinterpret_cast<void*>(as_cl(mem));
return hipSuccess;
}
hipError_t hipFree(void* ptr)
{
if (!is_valid(reinterpret_cast<cl_mem>(ptr))) {
return hipErrorInvalidValue;
}
as_amd(reinterpret_cast<cl_mem>(ptr))->release();
return hipSuccess;
}
hipError_t hipMemcpy(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind)
{
HIP_INIT_API(dst, src, sizeBytes, kind);
amd::Context* context = as_amd(g_currentCtx);
amd::Device* device = context->devices()[0];
// FIXME : Do we create a queue here or create at init and just reuse
amd::HostQueue* queue = new amd::HostQueue(*context, *device, 0,
amd::CommandQueue::RealTimeDisabled,
amd::CommandQueue::Priority::Normal);
if (!queue) {
return hipErrorOutOfMemory;
}
amd::Buffer* srcBuffer = as_amd(reinterpret_cast<cl_mem>(const_cast<void*>(src)))->asBuffer();
amd::Buffer* dstBuffer = as_amd(reinterpret_cast<cl_mem>(const_cast<void*>(dst)))->asBuffer();
amd::Command* command;
amd::Command::EventWaitList waitList;
switch (kind) {
case hipMemcpyDeviceToHost:
command = new amd::ReadMemoryCommand(*queue, CL_COMMAND_READ_BUFFER, waitList,
srcBuffer, 0, sizeBytes, dst);
break;
case hipMemcpyHostToDevice:
command = new amd::WriteMemoryCommand(*queue, CL_COMMAND_WRITE_BUFFER, waitList,
dstBuffer, 0, sizeBytes, src);
break;
default:
assert(!"Shouldn't reach here");
break;
}
if (!command) {
return hipErrorOutOfMemory;
}
// Make sure we have memory for the command execution
if (CL_SUCCESS != command->validateMemory()) {
delete command;
return hipErrorMemoryAllocation;
}
command->enqueue();
command->awaitCompletion();
command->release();
queue->release();
return hipSuccess;
}
<|endoftext|> |
<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_HTTP_ENUMS_HPP_
#define POSEIDON_HTTP_ENUMS_HPP_
#include "../fwd.hpp"
namespace poseidon {
// These are HTTP version numbers.
// At the moment only 1.0 and 1.1 are supported.
enum HTTP_Version : uint16_t
{
http_version_0_0 = 0,
http_version_1_0 = 0x0100, // HTTP/1.0
http_version_1_1 = 0x0101, // HTTP/1.1
};
// Converts an HTTP version to a string such as `HTTP/1.1`.
ROCKET_CONST_FUNCTION
const char*
format_http_version(HTTP_Version ver)
noexcept;
// Parses a version number from plain text.
// `http_version_0_0` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Version
parse_http_version(const char* bptr, const char* eptr)
noexcept;
// These are HTTP methods a.k.a. verbs.
enum HTTP_Method : uint8_t
{
http_method_null = 0,
http_method_get = 1,
http_method_head = 2,
http_method_post = 3,
http_method_put = 4,
http_method_delete = 5,
http_method_connect = 6,
http_method_options = 7,
http_method_trace = 8,
};
// Converts an HTTP method to a string such as `GET`.
// If the method is invalid, the invalid string `NULL` is returned.
ROCKET_CONST_FUNCTION
const char*
format_http_method(HTTP_Method method)
noexcept;
// Parses a method from plain text.
// `http_method_null` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Method
parse_http_method(const char* bptr, const char* eptr)
noexcept;
// These are HTTP status codes.
// This list is not exhaustive. Custom values may be used.
enum HTTP_Status : uint16_t
{
http_status_null = 0, // Null
http_status_class_information = 100,
http_status_continue = 100, // Continue
http_status_switching_protocol = 101, // Switching Protocol
http_status_processing = 102, // Processing
http_status_early_hints = 103, // Early Hints
http_status_class_success = 200,
http_status_ok = 200, // OK
http_status_created = 201, // Created
http_status_accepted = 202, // Accepted
http_status_nonauthoritative = 203, // Non-authoritative Information
http_status_no_content = 204, // No Content
http_status_reset_content = 205, // Reset Content
http_status_partial_content = 206, // Partial Content
http_status_multistatus = 207, // Multi-status
http_status_already_reported = 208, // Already Reported
http_status_im_used = 226, // IM Used
http_status_connection_established = 299, // Connection Established [x]
http_status_class_redirection = 300,
http_status_multiple_choice = 300, // Multiple Choice
http_status_moved_permanently = 301, // Moved Permanently
http_status_found = 302, // Found
http_status_see_other = 303, // See Other
http_status_not_modified = 304, // Not Modified
http_status_use_proxy = 305, // Use Proxy
http_status_temporary_redirect = 307, // Temporary Redirect
http_status_permanent_redirect = 308, // Permanent Redirect
http_status_class_client_error = 400,
http_status_bad_request = 400, // Bad Request
http_status_unauthorized = 401, // Unauthorized
http_status_forbidden = 403, // Forbidden
http_status_not_found = 404, // Not Found
http_status_method_not_allowed = 405, // Method Not Allowed
http_status_not_acceptable = 406, // Not Acceptable
http_status_proxy_unauthorized = 407, // Proxy Authentication Required
http_status_request_timeout = 408, // Request Timeout
http_status_conflict = 409, // Conflict
http_status_gone = 410, // Gone
http_status_length_required = 411, // Length Required
http_status_precondition_failed = 412, // Precondition Failed
http_status_payload_too_large = 413, // Payload Too Large
http_status_uri_too_long = 414, // URI Too Long
http_status_unsupported_media_type = 415, // Unsupported Media Type
http_status_range_not_satisfiable = 416, // Range Not Satisfiable
http_status_expectation_failed = 417, // Expectation Failed
http_status_misdirected_request = 421, // Misdirected Request
http_status_unprocessable_entity = 422, // Unprocessable Entity
http_status_locked = 423, // Locked
http_status_failed_dependency = 424, // Failed Dependency
http_status_too_early = 425, // Too Early
http_status_upgrade_required = 426, // Upgrade Required
http_status_precondition_required = 428, // Precondition Required
http_status_too_many_requests = 429, // Too Many Requests
http_status_headers_too_large = 431, // Request Header Fields Too Large
http_status_class_server_error = 500,
http_status_internal_server_error = 500, // Internal Server Error
http_status_not_implemented = 501, // Not Implemented
http_status_bad_gateway = 502, // Bad Gateway
http_status_service_unavailable = 503, // Service Unavailable
http_status_gateway_timeout = 504, // Gateway Timeout
http_status_version_not_supported = 505, // HTTP Version Not Supported
http_status_insufficient_storage = 507, // Insufficient Storage
http_status_loop_detected = 508, // Loop Detected
http_status_not_extended = 510, // Not Extended
http_status_network_unauthorized = 511, // Network Authentication Required
};
// Converts an HTTP status code to a string such as `Bad Request`.
// If the status code is unknown, `Unknown Status` is returned.
ROCKET_CONST_FUNCTION
const char*
describe_http_status(HTTP_Status stat)
noexcept;
// Classifies a status code.
constexpr
HTTP_Status
classify_http_status(HTTP_Status stat)
noexcept
{ return static_cast<HTTP_Status>(static_cast<uint32_t>(stat) / 100 * 100); }
// These are values for `Connection:` headers.
enum HTTP_Connection : uint8_t
{
http_connection_keep_alive = 0,
http_connection_close = 1,
http_connection_upgrade = 2, // special value for pending upgrades
http_connection_tunnel = 3, // special value for CONNECT method
http_connection_websocket = 4, // WebSocket
};
// These are WebSocket opcodes.
// This list is exhaustive according to RFC 6455.
enum WebSocket_Opcode : uint8_t
{
websocket_opcode_class_data = 0b0000,
websocket_opcode_continuation = 0b0000,
websocket_opcode_text = 0b0001,
websocket_opcode_binary = 0b0010,
websocket_opcode_class_control = 0b1000,
websocket_opcode_close = 0b1000,
websocket_opcode_ping = 0b1001,
websocket_opcode_pong = 0b1010,
};
// Classifies an opcode.
constexpr
WebSocket_Opcode
classify_websocket_opcode(WebSocket_Opcode opcode)
noexcept
{ return static_cast<WebSocket_Opcode>(opcode & 0b1000); }
// These are WebSocket status codes.
// This list is not exhaustive. Custom values may be used.
enum WebSocket_Status : uint16_t
{
websocket_status_null = 0,
websocket_status_class_rfc6455 = 1000,
websocket_status_normal_closure = 1000,
websocket_status_going_away = 1001,
websocket_status_protocol_error = 1002,
websocket_status_not_acceptable = 1003,
websocket_status_no_status = 1005, // reserved
websocket_status_abnormal = 1006, // reserved
websocket_status_data_error = 1007,
websocket_status_forbidden = 1008,
websocket_status_too_large = 1009,
websocket_status_extension_required = 1010, // reserved
websocket_status_server_error = 1011,
websocket_status_tls_error = 1015, // reserved
websocket_status_class_iana = 3000,
websocket_status_class_private_use = 4000,
};
// Classifies a status code.
constexpr
WebSocket_Status
classify_websocket_status(WebSocket_Status stat)
noexcept
{
uint32_t cls = static_cast<uint32_t>(stat) / 1000 * 1000;
return (cls == 2000) ? websocket_status_class_rfc6455
: static_cast<WebSocket_Status>(cls);
}
} // namespace poseidon
#endif
<commit_msg>http/enums: Update `HTTP_Connection`<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_HTTP_ENUMS_HPP_
#define POSEIDON_HTTP_ENUMS_HPP_
#include "../fwd.hpp"
namespace poseidon {
// These are HTTP version numbers.
// At the moment only 1.0 and 1.1 are supported.
enum HTTP_Version : uint16_t
{
http_version_0_0 = 0,
http_version_1_0 = 0x0100, // HTTP/1.0
http_version_1_1 = 0x0101, // HTTP/1.1
};
// Converts an HTTP version to a string such as `HTTP/1.1`.
ROCKET_CONST_FUNCTION
const char*
format_http_version(HTTP_Version ver)
noexcept;
// Parses a version number from plain text.
// `http_version_0_0` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Version
parse_http_version(const char* bptr, const char* eptr)
noexcept;
// These are HTTP methods a.k.a. verbs.
enum HTTP_Method : uint8_t
{
http_method_null = 0,
http_method_get = 1,
http_method_head = 2,
http_method_post = 3,
http_method_put = 4,
http_method_delete = 5,
http_method_connect = 6,
http_method_options = 7,
http_method_trace = 8,
};
// Converts an HTTP method to a string such as `GET`.
// If the method is invalid, the invalid string `NULL` is returned.
ROCKET_CONST_FUNCTION
const char*
format_http_method(HTTP_Method method)
noexcept;
// Parses a method from plain text.
// `http_method_null` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Method
parse_http_method(const char* bptr, const char* eptr)
noexcept;
// These are HTTP status codes.
// This list is not exhaustive. Custom values may be used.
enum HTTP_Status : uint16_t
{
http_status_null = 0, // Null
http_status_class_information = 100,
http_status_continue = 100, // Continue
http_status_switching_protocol = 101, // Switching Protocol
http_status_processing = 102, // Processing
http_status_early_hints = 103, // Early Hints
http_status_class_success = 200,
http_status_ok = 200, // OK
http_status_created = 201, // Created
http_status_accepted = 202, // Accepted
http_status_nonauthoritative = 203, // Non-authoritative Information
http_status_no_content = 204, // No Content
http_status_reset_content = 205, // Reset Content
http_status_partial_content = 206, // Partial Content
http_status_multistatus = 207, // Multi-status
http_status_already_reported = 208, // Already Reported
http_status_im_used = 226, // IM Used
http_status_connection_established = 299, // Connection Established [x]
http_status_class_redirection = 300,
http_status_multiple_choice = 300, // Multiple Choice
http_status_moved_permanently = 301, // Moved Permanently
http_status_found = 302, // Found
http_status_see_other = 303, // See Other
http_status_not_modified = 304, // Not Modified
http_status_use_proxy = 305, // Use Proxy
http_status_temporary_redirect = 307, // Temporary Redirect
http_status_permanent_redirect = 308, // Permanent Redirect
http_status_class_client_error = 400,
http_status_bad_request = 400, // Bad Request
http_status_unauthorized = 401, // Unauthorized
http_status_forbidden = 403, // Forbidden
http_status_not_found = 404, // Not Found
http_status_method_not_allowed = 405, // Method Not Allowed
http_status_not_acceptable = 406, // Not Acceptable
http_status_proxy_unauthorized = 407, // Proxy Authentication Required
http_status_request_timeout = 408, // Request Timeout
http_status_conflict = 409, // Conflict
http_status_gone = 410, // Gone
http_status_length_required = 411, // Length Required
http_status_precondition_failed = 412, // Precondition Failed
http_status_payload_too_large = 413, // Payload Too Large
http_status_uri_too_long = 414, // URI Too Long
http_status_unsupported_media_type = 415, // Unsupported Media Type
http_status_range_not_satisfiable = 416, // Range Not Satisfiable
http_status_expectation_failed = 417, // Expectation Failed
http_status_misdirected_request = 421, // Misdirected Request
http_status_unprocessable_entity = 422, // Unprocessable Entity
http_status_locked = 423, // Locked
http_status_failed_dependency = 424, // Failed Dependency
http_status_too_early = 425, // Too Early
http_status_upgrade_required = 426, // Upgrade Required
http_status_precondition_required = 428, // Precondition Required
http_status_too_many_requests = 429, // Too Many Requests
http_status_headers_too_large = 431, // Request Header Fields Too Large
http_status_class_server_error = 500,
http_status_internal_server_error = 500, // Internal Server Error
http_status_not_implemented = 501, // Not Implemented
http_status_bad_gateway = 502, // Bad Gateway
http_status_service_unavailable = 503, // Service Unavailable
http_status_gateway_timeout = 504, // Gateway Timeout
http_status_version_not_supported = 505, // HTTP Version Not Supported
http_status_insufficient_storage = 507, // Insufficient Storage
http_status_loop_detected = 508, // Loop Detected
http_status_not_extended = 510, // Not Extended
http_status_network_unauthorized = 511, // Network Authentication Required
};
// Converts an HTTP status code to a string such as `Bad Request`.
// If the status code is unknown, `Unknown Status` is returned.
ROCKET_CONST_FUNCTION
const char*
describe_http_status(HTTP_Status stat)
noexcept;
// Classifies a status code.
constexpr
HTTP_Status
classify_http_status(HTTP_Status stat)
noexcept
{ return static_cast<HTTP_Status>(static_cast<uint32_t>(stat) / 100 * 100); }
// These were designed for various options in the `Connection:` header, but
// now they denote [ method + connection + upgrade ] combinations.
enum HTTP_Connection : uint8_t
{
http_connection_keep_alive = 0,
http_connection_connect = 1, // special value for CONNECT method
http_connection_head = 2, // special value for HEAD method
http_connection_close = 3,
http_connection_upgrade = 4, // special value for pending upgrades
http_connection_websocket = 5, // WebSocket
};
// These are WebSocket opcodes.
// This list is exhaustive according to RFC 6455.
enum WebSocket_Opcode : uint8_t
{
websocket_opcode_class_data = 0b0000,
websocket_opcode_continuation = 0b0000,
websocket_opcode_text = 0b0001,
websocket_opcode_binary = 0b0010,
websocket_opcode_class_control = 0b1000,
websocket_opcode_close = 0b1000,
websocket_opcode_ping = 0b1001,
websocket_opcode_pong = 0b1010,
};
// Classifies an opcode.
constexpr
WebSocket_Opcode
classify_websocket_opcode(WebSocket_Opcode opcode)
noexcept
{ return static_cast<WebSocket_Opcode>(opcode & 0b1000); }
// These are WebSocket status codes.
// This list is not exhaustive. Custom values may be used.
enum WebSocket_Status : uint16_t
{
websocket_status_null = 0,
websocket_status_class_rfc6455 = 1000,
websocket_status_normal_closure = 1000,
websocket_status_going_away = 1001,
websocket_status_protocol_error = 1002,
websocket_status_not_acceptable = 1003,
websocket_status_no_status = 1005, // reserved
websocket_status_abnormal = 1006, // reserved
websocket_status_data_error = 1007,
websocket_status_forbidden = 1008,
websocket_status_too_large = 1009,
websocket_status_extension_required = 1010, // reserved
websocket_status_server_error = 1011,
websocket_status_tls_error = 1015, // reserved
websocket_status_class_iana = 3000,
websocket_status_class_private_use = 4000,
};
// Classifies a status code.
constexpr
WebSocket_Status
classify_websocket_status(WebSocket_Status stat)
noexcept
{
uint32_t cls = static_cast<uint32_t>(stat) / 1000 * 1000;
return (cls == 2000) ? websocket_status_class_rfc6455
: static_cast<WebSocket_Status>(cls);
}
} // namespace poseidon
#endif
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, John Haddon. All rights reserved.
// Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include <fstream>
#include "boost/filesystem.hpp"
#include "IECorePython/ScopedGILLock.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/Wrapper.h"
#include "Gaffer/ApplicationRoot.h"
#include "Gaffer/CompoundPlug.h"
#include "Gaffer/Preferences.h"
#include "GafferBindings/ApplicationRootBinding.h"
#include "GafferBindings/Serialisation.h"
#include "GafferBindings/ValuePlugBinding.h"
using namespace boost::python;
using namespace GafferBindings;
using namespace Gaffer;
class ApplicationRootWrapper : public ApplicationRoot, public IECorePython::Wrapper<ApplicationRoot>
{
public :
ApplicationRootWrapper( PyObject *self, const std::string &name = staticTypeName() )
: ApplicationRoot( name ), IECorePython::Wrapper<ApplicationRoot>( self, this )
{
}
virtual void savePreferences( const std::string &fileName ) const
{
IECorePython::ScopedGILLock gilLock;
// serialise everything
Serialisation s( preferences(), "application.root()[\"preferences\"]" );
// make the directory for the preferences file if it doesn't exist yet
boost::filesystem::path path( fileName );
path.remove_filename();
boost::filesystem::create_directories( path );
// then make the file and write the serialisation into it
std::ofstream f;
f.open( fileName.c_str() );
if( !f.is_open() )
{
throw IECore::Exception( "Unable to open file \"" + fileName + "\"" );
}
f << "# This file was automatically generated by Gaffer.\n";
f << "# Do not edit this file - it will be overwritten.\n\n";
f << s.result() << std::endl;
if( !f.good() )
{
throw IECore::Exception( "Error while writing file \"" + fileName + "\"" );
}
}
};
IE_CORE_DECLAREPTR( ApplicationRootWrapper )
static IECore::ObjectPtr getClipboardContents( ApplicationRoot &a )
{
IECore::ConstObjectPtr o = a.getClipboardContents();
if( o )
{
return o->copy();
}
return 0;
}
void GafferBindings::bindApplicationRoot()
{
IECorePython::RunTimeTypedClass<ApplicationRoot, ApplicationRootWrapperPtr>()
.def( init<>() )
.def( init<const std::string &>() )
.def( "getClipboardContents", &getClipboardContents )
.def( "setClipboardContents", &ApplicationRoot::setClipboardContents )
.def( "savePreferences", (void (ApplicationRoot::*)()const)&ApplicationRoot::savePreferences )
.def( "savePreferences", (void (ApplicationRoot::*)( const std::string & )const)&ApplicationRoot::savePreferences )
.def( "preferencesLocation", &ApplicationRoot::preferencesLocation )
;
}
<commit_msg>Removing unused include.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, John Haddon. All rights reserved.
// Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include <fstream>
#include "boost/filesystem.hpp"
#include "IECorePython/ScopedGILLock.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/Wrapper.h"
#include "Gaffer/ApplicationRoot.h"
#include "Gaffer/CompoundPlug.h"
#include "Gaffer/Preferences.h"
#include "GafferBindings/ApplicationRootBinding.h"
#include "GafferBindings/Serialisation.h"
using namespace boost::python;
using namespace GafferBindings;
using namespace Gaffer;
class ApplicationRootWrapper : public ApplicationRoot, public IECorePython::Wrapper<ApplicationRoot>
{
public :
ApplicationRootWrapper( PyObject *self, const std::string &name = staticTypeName() )
: ApplicationRoot( name ), IECorePython::Wrapper<ApplicationRoot>( self, this )
{
}
virtual void savePreferences( const std::string &fileName ) const
{
IECorePython::ScopedGILLock gilLock;
// serialise everything
Serialisation s( preferences(), "application.root()[\"preferences\"]" );
// make the directory for the preferences file if it doesn't exist yet
boost::filesystem::path path( fileName );
path.remove_filename();
boost::filesystem::create_directories( path );
// then make the file and write the serialisation into it
std::ofstream f;
f.open( fileName.c_str() );
if( !f.is_open() )
{
throw IECore::Exception( "Unable to open file \"" + fileName + "\"" );
}
f << "# This file was automatically generated by Gaffer.\n";
f << "# Do not edit this file - it will be overwritten.\n\n";
f << s.result() << std::endl;
if( !f.good() )
{
throw IECore::Exception( "Error while writing file \"" + fileName + "\"" );
}
}
};
IE_CORE_DECLAREPTR( ApplicationRootWrapper )
static IECore::ObjectPtr getClipboardContents( ApplicationRoot &a )
{
IECore::ConstObjectPtr o = a.getClipboardContents();
if( o )
{
return o->copy();
}
return 0;
}
void GafferBindings::bindApplicationRoot()
{
IECorePython::RunTimeTypedClass<ApplicationRoot, ApplicationRootWrapperPtr>()
.def( init<>() )
.def( init<const std::string &>() )
.def( "getClipboardContents", &getClipboardContents )
.def( "setClipboardContents", &ApplicationRoot::setClipboardContents )
.def( "savePreferences", (void (ApplicationRoot::*)()const)&ApplicationRoot::savePreferences )
.def( "savePreferences", (void (ApplicationRoot::*)( const std::string & )const)&ApplicationRoot::savePreferences )
.def( "preferencesLocation", &ApplicationRoot::preferencesLocation )
;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "movetool.h"
#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"
#include "resizehandleitem.h"
#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QAction>
#include <QDebug>
namespace QmlDesigner {
MoveTool::MoveTool(FormEditorView *editorView)
: AbstractFormEditorTool(editorView),
m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
m_bindingIndicator(editorView->scene()->manipulatorLayerItem())
{
m_selectionIndicator.setCursor(Qt::SizeAllCursor);
}
MoveTool::~MoveTool()
{
}
void MoveTool::clear()
{
m_moveManipulator.clear();
m_movingItems.clear();
m_selectionIndicator.clear();
m_resizeIndicator.clear();
m_anchorIndicator.clear();
m_bindingIndicator.clear();
AbstractFormEditorTool::clear();
}
void MoveTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
if (itemList.isEmpty())
return;
m_movingItems = movingItems(items());
if (m_movingItems.isEmpty())
return;
m_moveManipulator.setItems(m_movingItems);
m_moveManipulator.begin(event->scenePos());
}
AbstractFormEditorTool::mousePressEvent(itemList, event);
}
void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
if (m_moveManipulator.isActive()) {
if (m_movingItems.isEmpty())
return;
// m_selectionIndicator.hide();
m_resizeIndicator.hide();
m_anchorIndicator.hide();
m_bindingIndicator.hide();
FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems);
if (containerItem && view()->currentState().isBaseState()) {
if (containerItem != m_movingItems.first()->parentItem()
&& event->modifiers().testFlag(Qt::ShiftModifier)) {
m_moveManipulator.reparentTo(containerItem);
}
}
m_moveManipulator.update(event->scenePos(), generateUseSnapping(event->modifiers()));
}
}
void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent * /*event*/)
{
if (itemList.isEmpty()) {
view()->changeToSelectionTool();
return;
}
ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
if (resizeHandle) {
view()->changeToResizeTool();
return;
}
if (!topSelectedItemIsMovable(itemList)) {
view()->changeToSelectionTool();
return;
}
}
void MoveTool::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
case Qt::Key_AltGr:
event->setAccepted(false);
return;
}
double moveStep = 1.0;
if (event->modifiers().testFlag(Qt::ShiftModifier))
moveStep = 10.0;
if (!event->isAutoRepeat()) {
QList<FormEditorItem*> movableItems(movingItems(items()));
if (movableItems.isEmpty())
return;
m_moveManipulator.setItems(movableItems);
// m_selectionIndicator.hide();
m_resizeIndicator.hide();
m_anchorIndicator.hide();
m_bindingIndicator.hide();
m_moveManipulator.beginRewriterTransaction();
}
switch (event->key()) {
case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break;
case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break;
case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break;
case Qt::Key_Down: m_moveManipulator.moveBy(0.0, moveStep); break;
}
if (event->key() == Qt::Key_Escape && !m_movingItems.isEmpty()) {
event->accept();
view()->changeToSelectionTool();
}
}
void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent)
{
switch (keyEvent->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
case Qt::Key_AltGr:
keyEvent->setAccepted(false);
return;
}
if (!keyEvent->isAutoRepeat()) {
m_moveManipulator.beginRewriterTransaction();
m_moveManipulator.clear();
// m_selectionIndicator.show();
m_resizeIndicator.show();
m_anchorIndicator.show();
m_bindingIndicator.show();
}
}
void MoveTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{
}
void MoveTool::dragMoveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{
}
void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
if (m_moveManipulator.isActive()) {
if (m_movingItems.isEmpty())
return;
m_moveManipulator.end(generateUseSnapping(event->modifiers()));
m_selectionIndicator.show();
m_resizeIndicator.show();
m_anchorIndicator.show();
m_bindingIndicator.show();
m_movingItems.clear();
}
AbstractFormEditorTool::mouseReleaseEvent(itemList, event);
}
void MoveTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event)
{
AbstractFormEditorTool::mouseDoubleClickEvent(itemList, event);
}
void MoveTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItemList)
{
foreach (FormEditorItem* removedItem, removedItemList)
m_movingItems.removeOne(removedItem);
}
void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.setItems(movingItems(itemList));
m_resizeIndicator.setItems(itemList);
m_anchorIndicator.setItems(itemList);
m_bindingIndicator.setItems(itemList);
updateMoveManipulator();
}
void MoveTool::instancesCompleted(const QList<FormEditorItem*> & /*itemList*/)
{
}
void MoveTool::instancesParentChanged(const QList<FormEditorItem *> &itemList)
{
m_moveManipulator.synchronizeInstanceParent(itemList);
}
void MoveTool::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}
bool MoveTool::haveSameParent(const QList<FormEditorItem*> &itemList)
{
if (itemList.isEmpty())
return false;
QGraphicsItem *firstParent = itemList.first()->parentItem();
foreach (FormEditorItem* item, itemList)
{
if (firstParent != item->parentItem())
return false;
}
return true;
}
bool MoveTool::isAncestorOfAllItems(FormEditorItem* maybeAncestorItem,
const QList<FormEditorItem*> &itemList)
{
foreach (FormEditorItem* item, itemList)
{
if (!maybeAncestorItem->isAncestorOf(item) && item != maybeAncestorItem)
return false;
}
return true;
}
FormEditorItem* MoveTool::ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList)
{
if (itemList.isEmpty())
return 0;
foreach (FormEditorItem* item, itemList)
{
if (isAncestorOfAllItems(item, itemList))
return item;
}
return 0;
}
void MoveTool::updateMoveManipulator()
{
if (m_moveManipulator.isActive())
return;
}
void MoveTool::beginWithPoint(const QPointF &beginPoint)
{
m_movingItems = movingItems(items());
if (m_movingItems.isEmpty())
return;
m_moveManipulator.setItems(m_movingItems);
m_moveManipulator.begin(beginPoint);
}
static bool isNotAncestorOfItemInList(FormEditorItem *formEditorItem, const QList<FormEditorItem*> &itemList)
{
foreach (FormEditorItem *item, itemList) {
if (item
&& item->qmlItemNode().isValid()
&& item->qmlItemNode().isAncestorOf(formEditorItem->qmlItemNode()))
return false;
}
return true;
}
FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &itemUnderMouseList,
const QList<FormEditorItem*> &selectedItemList)
{
Q_ASSERT(!selectedItemList.isEmpty());
foreach (QGraphicsItem* item, itemUnderMouseList) {
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
if (formEditorItem
&& !selectedItemList.contains(formEditorItem)
&& isNotAncestorOfItemInList(formEditorItem, selectedItemList))
return formEditorItem;
}
return 0;
}
QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList)
{
QList<FormEditorItem*> filteredItemList(itemList);
QMutableListIterator<FormEditorItem*> listIterator(filteredItemList);
while (listIterator.hasNext()) {
FormEditorItem *item = listIterator.next();
if (!item->qmlItemNode().isValid()
|| !item->qmlItemNode().instanceIsMovable()
|| !item->qmlItemNode().modelIsMovable()
|| item->qmlItemNode().instanceIsInLayoutable())
listIterator.remove();
}
return filteredItemList;
}
QList<FormEditorItem*> MoveTool::movingItems(const QList<FormEditorItem*> &selectedItemList)
{
QList<FormEditorItem*> filteredItemList = movalbeItems(selectedItemList);
FormEditorItem* ancestorItem = ancestorIfOtherItemsAreChild(filteredItemList);
if (ancestorItem != 0 && ancestorItem->qmlItemNode().isRootNode()) {
// view()->changeToSelectionTool();
return QList<FormEditorItem*>();
}
if (ancestorItem != 0 && ancestorItem->parentItem() != 0) {
QList<FormEditorItem*> ancestorItemList;
ancestorItemList.append(ancestorItem);
return ancestorItemList;
}
if (!haveSameParent(filteredItemList)) {
// view()->changeToSelectionTool();
return QList<FormEditorItem*>();
}
return filteredItemList;
}
void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.updateItems(itemList);
m_resizeIndicator.updateItems(itemList);
m_anchorIndicator.updateItems(itemList);
m_bindingIndicator.updateItems(itemList);
}
}
<commit_msg>QmlDesigner.FormEditor: using FormEditorItem::isContainer in MoveTool<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "movetool.h"
#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"
#include "resizehandleitem.h"
#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QAction>
#include <QDebug>
namespace QmlDesigner {
MoveTool::MoveTool(FormEditorView *editorView)
: AbstractFormEditorTool(editorView),
m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
m_bindingIndicator(editorView->scene()->manipulatorLayerItem())
{
m_selectionIndicator.setCursor(Qt::SizeAllCursor);
}
MoveTool::~MoveTool()
{
}
void MoveTool::clear()
{
m_moveManipulator.clear();
m_movingItems.clear();
m_selectionIndicator.clear();
m_resizeIndicator.clear();
m_anchorIndicator.clear();
m_bindingIndicator.clear();
AbstractFormEditorTool::clear();
}
void MoveTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
if (itemList.isEmpty())
return;
m_movingItems = movingItems(items());
if (m_movingItems.isEmpty())
return;
m_moveManipulator.setItems(m_movingItems);
m_moveManipulator.begin(event->scenePos());
}
AbstractFormEditorTool::mousePressEvent(itemList, event);
}
void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
if (m_moveManipulator.isActive()) {
if (m_movingItems.isEmpty())
return;
// m_selectionIndicator.hide();
m_resizeIndicator.hide();
m_anchorIndicator.hide();
m_bindingIndicator.hide();
FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems);
if (containerItem && view()->currentState().isBaseState()) {
if (containerItem != m_movingItems.first()->parentItem()
&& event->modifiers().testFlag(Qt::ShiftModifier)) {
m_moveManipulator.reparentTo(containerItem);
}
}
m_moveManipulator.update(event->scenePos(), generateUseSnapping(event->modifiers()));
}
}
void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent * /*event*/)
{
if (itemList.isEmpty()) {
view()->changeToSelectionTool();
return;
}
ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
if (resizeHandle) {
view()->changeToResizeTool();
return;
}
if (!topSelectedItemIsMovable(itemList)) {
view()->changeToSelectionTool();
return;
}
}
void MoveTool::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
case Qt::Key_AltGr:
event->setAccepted(false);
return;
}
double moveStep = 1.0;
if (event->modifiers().testFlag(Qt::ShiftModifier))
moveStep = 10.0;
if (!event->isAutoRepeat()) {
QList<FormEditorItem*> movableItems(movingItems(items()));
if (movableItems.isEmpty())
return;
m_moveManipulator.setItems(movableItems);
// m_selectionIndicator.hide();
m_resizeIndicator.hide();
m_anchorIndicator.hide();
m_bindingIndicator.hide();
m_moveManipulator.beginRewriterTransaction();
}
switch (event->key()) {
case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break;
case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break;
case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break;
case Qt::Key_Down: m_moveManipulator.moveBy(0.0, moveStep); break;
}
if (event->key() == Qt::Key_Escape && !m_movingItems.isEmpty()) {
event->accept();
view()->changeToSelectionTool();
}
}
void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent)
{
switch (keyEvent->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
case Qt::Key_AltGr:
keyEvent->setAccepted(false);
return;
}
if (!keyEvent->isAutoRepeat()) {
m_moveManipulator.beginRewriterTransaction();
m_moveManipulator.clear();
// m_selectionIndicator.show();
m_resizeIndicator.show();
m_anchorIndicator.show();
m_bindingIndicator.show();
}
}
void MoveTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{
}
void MoveTool::dragMoveEvent(QGraphicsSceneDragDropEvent * /*event*/)
{
}
void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
if (m_moveManipulator.isActive()) {
if (m_movingItems.isEmpty())
return;
m_moveManipulator.end(generateUseSnapping(event->modifiers()));
m_selectionIndicator.show();
m_resizeIndicator.show();
m_anchorIndicator.show();
m_bindingIndicator.show();
m_movingItems.clear();
}
AbstractFormEditorTool::mouseReleaseEvent(itemList, event);
}
void MoveTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event)
{
AbstractFormEditorTool::mouseDoubleClickEvent(itemList, event);
}
void MoveTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItemList)
{
foreach (FormEditorItem* removedItem, removedItemList)
m_movingItems.removeOne(removedItem);
}
void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.setItems(movingItems(itemList));
m_resizeIndicator.setItems(itemList);
m_anchorIndicator.setItems(itemList);
m_bindingIndicator.setItems(itemList);
updateMoveManipulator();
}
void MoveTool::instancesCompleted(const QList<FormEditorItem*> & /*itemList*/)
{
}
void MoveTool::instancesParentChanged(const QList<FormEditorItem *> &itemList)
{
m_moveManipulator.synchronizeInstanceParent(itemList);
}
void MoveTool::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}
bool MoveTool::haveSameParent(const QList<FormEditorItem*> &itemList)
{
if (itemList.isEmpty())
return false;
QGraphicsItem *firstParent = itemList.first()->parentItem();
foreach (FormEditorItem* item, itemList)
{
if (firstParent != item->parentItem())
return false;
}
return true;
}
bool MoveTool::isAncestorOfAllItems(FormEditorItem* maybeAncestorItem,
const QList<FormEditorItem*> &itemList)
{
foreach (FormEditorItem* item, itemList)
{
if (!maybeAncestorItem->isAncestorOf(item) && item != maybeAncestorItem)
return false;
}
return true;
}
FormEditorItem* MoveTool::ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList)
{
if (itemList.isEmpty())
return 0;
foreach (FormEditorItem* item, itemList)
{
if (isAncestorOfAllItems(item, itemList))
return item;
}
return 0;
}
void MoveTool::updateMoveManipulator()
{
if (m_moveManipulator.isActive())
return;
}
void MoveTool::beginWithPoint(const QPointF &beginPoint)
{
m_movingItems = movingItems(items());
if (m_movingItems.isEmpty())
return;
m_moveManipulator.setItems(m_movingItems);
m_moveManipulator.begin(beginPoint);
}
static bool isNotAncestorOfItemInList(FormEditorItem *formEditorItem, const QList<FormEditorItem*> &itemList)
{
foreach (FormEditorItem *item, itemList) {
if (item
&& item->qmlItemNode().isValid()
&& item->qmlItemNode().isAncestorOf(formEditorItem->qmlItemNode()))
return false;
}
return true;
}
FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &itemUnderMouseList,
const QList<FormEditorItem*> &selectedItemList)
{
Q_ASSERT(!selectedItemList.isEmpty());
foreach (QGraphicsItem* item, itemUnderMouseList) {
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
if (formEditorItem
&& !selectedItemList.contains(formEditorItem)
&& isNotAncestorOfItemInList(formEditorItem, selectedItemList)
&& formEditorItem->isContainer())
return formEditorItem;
}
return 0;
}
QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList)
{
QList<FormEditorItem*> filteredItemList(itemList);
QMutableListIterator<FormEditorItem*> listIterator(filteredItemList);
while (listIterator.hasNext()) {
FormEditorItem *item = listIterator.next();
if (!item->qmlItemNode().isValid()
|| !item->qmlItemNode().instanceIsMovable()
|| !item->qmlItemNode().modelIsMovable()
|| item->qmlItemNode().instanceIsInLayoutable())
listIterator.remove();
}
return filteredItemList;
}
QList<FormEditorItem*> MoveTool::movingItems(const QList<FormEditorItem*> &selectedItemList)
{
QList<FormEditorItem*> filteredItemList = movalbeItems(selectedItemList);
FormEditorItem* ancestorItem = ancestorIfOtherItemsAreChild(filteredItemList);
if (ancestorItem != 0 && ancestorItem->qmlItemNode().isRootNode()) {
// view()->changeToSelectionTool();
return QList<FormEditorItem*>();
}
if (ancestorItem != 0 && ancestorItem->parentItem() != 0) {
QList<FormEditorItem*> ancestorItemList;
ancestorItemList.append(ancestorItem);
return ancestorItemList;
}
if (!haveSameParent(filteredItemList)) {
// view()->changeToSelectionTool();
return QList<FormEditorItem*>();
}
return filteredItemList;
}
void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.updateItems(itemList);
m_resizeIndicator.updateItems(itemList);
m_anchorIndicator.updateItems(itemList);
m_bindingIndicator.updateItems(itemList);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsPageObjectViewContact.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:36:35 $
*
* 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 "view/SlsPageObjectViewContact.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"
#include <svx/svdopage.hxx>
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
using namespace ::sdr::contact;
namespace sd { namespace slidesorter { namespace view {
PageObjectViewContact::PageObjectViewContact (
SdrPageObj& rPageObj,
model::PageDescriptor& rDescriptor)
: ViewContactOfPageObj (rPageObj),
mbIsValid(true),
mrDescriptor(rDescriptor)
{
}
PageObjectViewContact::~PageObjectViewContact (void)
{
}
ViewObjectContact&
PageObjectViewContact::CreateObjectSpecificViewObjectContact(
ObjectContact& rObjectContact)
{
ViewObjectContact* pResult
= mrDescriptor.GetPageObjectFactory().CreateViewObjectContact (
rObjectContact,
*this);
DBG_ASSERT (pResult!=NULL,
"PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
return *pResult;
}
const SdrPage* PageObjectViewContact::GetPage (void) const
{
if (mbIsValid)
return GetReferencedPage();
else
return NULL;
}
void PageObjectViewContact::CalcPaintRectangle (void)
{
ViewContactOfPageObj::CalcPaintRectangle();
if (mbIsValid)
{
maPageObjectBoundingBox = maPaintRectangle;
SvBorder aBorder (mrDescriptor.GetModelBorder());
maPaintRectangle.Left() -= aBorder.Left();
maPaintRectangle.Right() += aBorder.Right();
maPaintRectangle.Top() -= aBorder.Top();
maPaintRectangle.Bottom() += aBorder.Bottom();
}
}
Rectangle PageObjectViewContact::GetPageRectangle (void)
{
return GetPageObj().GetCurrentBoundRect();
}
Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
return maPageObjectBoundingBox;
}
SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
return ViewContactOfPageObj::GetPageObj();
}
void PageObjectViewContact::PrepareDelete (void)
{
mbIsValid = false;
}
} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS components1 (1.4.148); FILE MERGED 2006/11/21 16:23:20 af 1.4.148.3: RESYNC: (1.5-1.6); FILE MERGED 2006/09/25 17:26:33 af 1.4.148.2: RESYNC: (1.4-1.5); FILE MERGED 2006/08/22 11:49:35 af 1.4.148.1: #i68075# Added ActionChanged() method.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsPageObjectViewContact.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2007-04-03 16:19:16 $
*
* 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 "view/SlsPageObjectViewContact.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"
#include <svx/svdopage.hxx>
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
using namespace ::sdr::contact;
namespace sd { namespace slidesorter { namespace view {
PageObjectViewContact::PageObjectViewContact (
SdrPageObj& rPageObj,
model::PageDescriptor& rDescriptor)
: ViewContactOfPageObj (rPageObj),
mbIsValid(true),
mrDescriptor(rDescriptor)
{
}
PageObjectViewContact::~PageObjectViewContact (void)
{
}
ViewObjectContact&
PageObjectViewContact::CreateObjectSpecificViewObjectContact(
ObjectContact& rObjectContact)
{
ViewObjectContact* pResult
= mrDescriptor.GetPageObjectFactory().CreateViewObjectContact (
rObjectContact,
*this);
DBG_ASSERT (pResult!=NULL,
"PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
return *pResult;
}
const SdrPage* PageObjectViewContact::GetPage (void) const
{
if (mbIsValid)
return GetReferencedPage();
else
return NULL;
}
void PageObjectViewContact::CalcPaintRectangle (void)
{
ViewContactOfPageObj::CalcPaintRectangle();
if (mbIsValid)
{
maPageObjectBoundingBox = maPaintRectangle;
SvBorder aBorder (mrDescriptor.GetModelBorder());
maPaintRectangle.Left() -= aBorder.Left();
maPaintRectangle.Right() += aBorder.Right();
maPaintRectangle.Top() -= aBorder.Top();
maPaintRectangle.Bottom() += aBorder.Bottom();
}
}
Rectangle PageObjectViewContact::GetPageRectangle (void)
{
return GetPageObj().GetCurrentBoundRect();
}
void PageObjectViewContact::ActionChanged (void)
{
ViewContactOfPageObj::ActionChanged();
}
Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
return maPageObjectBoundingBox;
}
SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
return ViewContactOfPageObj::GetPageObj();
}
void PageObjectViewContact::PrepareDelete (void)
{
mbIsValid = false;
}
} } } // end of namespace ::sd::slidesorter::view
<|endoftext|> |
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#include "player_sys.sqf"
class playerSettings {
idd = playersys_DIALOG;
movingEnable = true;
enableSimulation = true;
onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'";
class controlsBackground {
class MainBG : w_RscPicture {
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
moving = true;
x = 0.0; y = 0.1;
w = .745; h = 0.65;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.45,0.005,0,1)";
x = 0;
y = 0.1;
w = 0.745;
h = 0.05;
};
class MainTitle : w_RscText {
idc = -1;
text = "Player Menu";
sizeEx = 0.04;
shadow = 2;
x = 0.260; y = 0.1;
w = 0.3; h = 0.05;
};
class waterIcon : w_RscPicture {
idc = -1;
text = "client\icons\energydrink.paa";
x = 0.022; y = 0.2;
w = 0.04 / (4/3); h = 0.04;
};
class foodIcon : w_RscPicture {
idc = -1;
text = "client\icons\cannedfood.paa";
x = 0.022; y = 0.26;
w = 0.04 / (4/3); h = 0.04;
};
class moneyIcon : w_RscPicture {
idc = -1;
text = "client\icons\money.paa";
x = 0.022; y = 0.32;
w = 0.04 / (4/3); h = 0.04;
};
class serverLogo : w_RscPicture {
idc = -1;
text = "mapconfig\logo.paa";
x = 0.225; y = 0.20;
w = 0.32 / (4/3); h = 0.32;
};
class waterText : w_RscText {
idc = water_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.193;
w = 0.3; h = 0.05;
};
class foodText : w_RscText {
idc = food_text;
sizeEx = 0.03;
text = "";
x = 0.06; y = 0.254;
w = 0.3; h = 0.05;
};
class moneyText : w_RscText {
idc = money_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.313;
w = 0.3; h = 0.05;
};
class distanceText : w_RscText {
idc = view_range_text;
text = "View range:";
sizeEx = 0.025;
x = 0.03; y = 0.40;
w = 0.3; h = 0.02;
};
class uptimeText : w_RscText {
idc = uptime_text;
text = "";
sizeEx = 0.030;
x = 0.52; y = 0.69;
w = 0.225; h = 0.03;
};
};
class controls {
class itemList : w_Rsclist {
idc = item_list;
x = 0.49; y = 0.185;
w = 0.235; h = 0.325;
};
class DropButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.610; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class UseButton : w_RscButton {
idc = -1;
text = "Use";
onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.489; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class moneyInput: w_RscCombo {
idc = money_value;
x = 0.610; y = 0.618;
w = .116; h = .030;
};
class DropcButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'";
x = 0.489; y = 0.60;
w = 0.116; h = 0.033 * safezoneH;
};
class CloseButton : w_RscButton {
idc = close_button;
text = "Close";
onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'";
x = 0.02; y = 0.66;
w = 0.125; h = 0.033 * safezoneH;
};
class GroupsButton : w_RscButton {
idc = groupButton;
text = "Group Management";
onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
x = 0.158; y = 0.66;
w = 0.225; h = 0.033 * safezoneH;
};
class btnDistanceNear : w_RscButton {
idc = -1;
text = "Low";
onButtonClick = "setViewDistance 1000; setObjectViewDistance 1200; setTerrainGrid 27;";
x = 0.02; y = 0.43;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceMedium : w_RscButton {
idc = -1;
text = "Medium";
onButtonClick = "setViewDistance 1500; setObjectViewDistance 1500; setTerrainGrid 25;";
x = 0.02; y = 0.5;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceFar : w_RscButton {
idc = -1;
text = "High";
onButtonClick = "setViewDistance 2500; setObjectViewDistance 2500; setTerrainGrid 12.5;";
x = 0.02; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
class TOParmaInfoButton : w_RscButton { //btnDistanceEffects
idc = -1;
text = "Server Info";
onButtonClick = "[] execVM 'addons\TOParmaInfo\loadTOParmaInfo.sqf'";
x = 0.158; y = 0.57;
w = 0.225; h = 0.033 * safezoneH;
};
};
};
<commit_msg>Testing<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#include "player_sys.sqf"
class playerSettings {
idd = playersys_DIALOG;
movingEnable = true;
enableSimulation = true;
onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'";
class controlsBackground {
class MainBG : w_RscPicture {
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
moving = true;
x = 0.0; y = 0.1;
w = .745; h = 0.65;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.45,0.005,0,1)";
x = 0;
y = 0.1;
w = 0.745;
h = 0.05;
};
class MainTitle : w_RscText {
idc = -1;
text = "Player Menu";
sizeEx = 0.04;
shadow = 2;
x = 0.260; y = 0.1;
w = 0.3; h = 0.05;
};
class waterIcon : w_RscPicture {
idc = -1;
text = "client\icons\energydrink.paa";
x = 0.022; y = 0.2;
w = 0.04 / (4/3); h = 0.04;
};
class foodIcon : w_RscPicture {
idc = -1;
text = "client\icons\cannedfood.paa";
x = 0.022; y = 0.26;
w = 0.04 / (4/3); h = 0.04;
};
class moneyIcon : w_RscPicture {
idc = -1;
text = "client\icons\money.paa";
x = 0.022; y = 0.32;
w = 0.04 / (4/3); h = 0.04;
};
class serverLogo : w_RscPicture {
idc = -1;
text = "mapconfig\logo.paa";
x = 0.225; y = 0.20;
w = 0.32 / (4/3); h = 0.32;
};
class waterText : w_RscText {
idc = water_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.193;
w = 0.3; h = 0.05;
};
class foodText : w_RscText {
idc = food_text;
sizeEx = 0.03;
text = "";
x = 0.06; y = 0.254;
w = 0.3; h = 0.05;
};
class moneyText : w_RscText {
idc = money_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.313;
w = 0.3; h = 0.05;
};
class distanceText : w_RscText {
idc = view_range_text;
text = "View range:";
sizeEx = 0.025;
x = 0.03; y = 0.40;
w = 0.3; h = 0.02;
};
class uptimeText : w_RscText {
idc = uptime_text;
text = "";
sizeEx = 0.030;
x = 0.52; y = 0.69;
w = 0.225; h = 0.03;
};
};
class controls {
class itemList : w_Rsclist {
idc = item_list;
x = 0.49; y = 0.185;
w = 0.235; h = 0.325;
};
class DropButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.610; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class UseButton : w_RscButton {
idc = -1;
text = "Use";
onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.489; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class moneyInput: w_RscCombo {
idc = money_value;
x = 0.610; y = 0.618;
w = .116; h = .030;
};
class DropcButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'";
x = 0.489; y = 0.60;
w = 0.116; h = 0.033 * safezoneH;
};
class CloseButton : w_RscButton {
idc = close_button;
text = "Close";
onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'";
x = 0.02; y = 0.66;
w = 0.125; h = 0.033 * safezoneH;
};
class GroupsButton : w_RscButton {
idc = groupButton;
text = "Group Management";
onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
x = 0.158; y = 0.66;
w = 0.225; h = 0.033 * safezoneH;
};
class btnDistanceNear : w_RscButton {
idc = -1;
text = "Low";
onButtonClick = "setViewDistance 1000; setObjectViewDistance 1200; setTerrainGrid 27;";
x = 0.02; y = 0.43;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceMedium : w_RscButton {
idc = -1;
text = "Medium";
onButtonClick = "setViewDistance 1500; setObjectViewDistance 1500; setTerrainGrid 25;";
x = 0.02; y = 0.5;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceFar : w_RscButton {
idc = -1;
text = "High";
onButtonClick = "setViewDistance 2500; setObjectViewDistance 2500; setTerrainGrid 12.5;";
x = 0.02; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
class TOParmaInfoButton : w_RscButton { //btnDistanceEffects
idc = -1;
text = "Server Info";
onButtonClick = "[] execVM 'addons\TOParmaInfo\loadTOParmaInfo.sqf'";
x = 0.158; y = 0.57;
w = 0.225; h = 0.033 * safezoneH;
};
/* class showStat : w_RscButton {
idc = -1;
text = "Show Stats";
onButtonClick = "[] execVM 'addons\statusBar\statusbar.sqf'";
x = 0.158; y = 0.5;
w = 0.225; h = 0.033 * safezoneH;
}; */
};
};
<|endoftext|> |
<commit_before>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "polygon.h"
#include "linearAlg2D.h" // pointLiesOnTheRightOfLine
#include "../debug.h"
namespace cura
{
bool PolygonRef::shorterThan(int64_t check_length) const
{
const PolygonRef& polygon = *this;
const Point* p0 = &polygon.back();
for (const Point& p1 : polygon)
{
check_length += vSize(*p0 - p1);
if (check_length >= check_length)
{
return false;
}
p0 = &p1;
}
return true;
}
bool PolygonRef::inside(Point p, bool border_result)
{
PolygonRef thiss = *this;
if (size() < 1)
{
return false;
}
int crossings = 0;
Point p0 = back();
for(unsigned int n=0; n<size(); n++)
{
Point p1 = thiss[n];
// no tests unless the segment p0-p1 is at least partly at, or to right of, p.X
short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
if (comp == 1)
{
crossings++;
}
else if (comp == 0)
{
return border_result;
}
p0 = p1;
}
return (crossings % 2) == 1;
}
bool Polygons::inside(Point p, bool border_result) const
{
const Polygons& thiss = *this;
if (size() < 1)
{
return false;
}
int crossings = 0;
for (const ClipperLib::Path& poly : thiss)
{
Point p0 = poly.back();
for (const Point& p1 : poly)
{
short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
if (comp == 1)
{
crossings++;
}
else if (comp == 0)
{
return border_result;
}
p0 = p1;
}
}
return (crossings % 2) == 1;
}
unsigned int Polygons::findInside(Point p, bool border_result)
{
Polygons& thiss = *this;
if (size() < 1)
{
return false;
}
int64_t min_x[size()];
std::fill_n(min_x, size(), std::numeric_limits<int64_t>::max()); // initialize with int.max
int crossings[size()];
std::fill_n(crossings, size(), 0); // initialize with zeros
for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
{
PolygonRef poly = thiss[poly_idx];
Point p0 = poly.back();
for(Point& p1 : poly)
{
short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
if (comp == 1)
{
crossings[poly_idx]++;
int64_t x;
if (p1.Y == p0.Y)
{
x = p0.X;
}
else
{
x = p0.X + (p1.X-p0.X) * (p.Y-p0.Y) / (p1.Y-p0.Y);
}
if (x < min_x[poly_idx])
{
min_x[poly_idx] = x;
}
}
else if (border_result && comp == 0)
{
return poly_idx;
}
p0 = p1;
}
}
int64_t min_x_uneven = std::numeric_limits<int64_t>::max();
unsigned int ret = NO_INDEX;
unsigned int n_unevens = 0;
for (unsigned int array_idx = 0; array_idx < size(); array_idx++)
{
if (crossings[array_idx] % 2 == 1)
{
n_unevens++;
if (min_x[array_idx] < min_x_uneven)
{
min_x_uneven = min_x[array_idx];
ret = array_idx;
}
}
}
if (n_unevens % 2 == 0) { ret = NO_INDEX; }
return ret;
}
void PolygonRef::simplify(int smallest_line_segment_squared, int allowed_error_distance_squared){
PolygonRef& thiss = *this;
if (size() <= 2)
{
clear();
return;
}
{ // remove segments smaller than allowed_error_distance
// this is neccesary in order to avoid the case where a long segment is followed by a lot of small segments would get simplified to a long segment going to the wrong end point
// ....... _ _______
// | / |
// | would become / instead of |
// | / |
Point* last = &thiss.back();
unsigned int writing_idx = 0;
for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
{
Point& here = thiss[poly_idx];
if (vSize2(*last - here) < smallest_line_segment_squared)
{
// don't add the point
}
else
{
thiss[writing_idx] = here;
writing_idx++;
last = &here;
}
}
path->erase(path->begin() + writing_idx , path->end());
}
if (size() < 3)
{
clear();
return;
}
Point* last = &thiss[0];
unsigned int writing_idx = 1;
for (unsigned int poly_idx = 1; poly_idx < size(); poly_idx++)
{
Point& here = thiss[poly_idx];
if ( vSize2(here-*last) < allowed_error_distance_squared )
{
// don't add the point to the result
continue;
}
Point& next = thiss[(poly_idx+1) % size()];
char here_is_beyond_line = 0;
int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next, &here_is_beyond_line);
if (here_is_beyond_line == 0 && error2 < allowed_error_distance_squared)
{// don't add the point to the result
} else
{
thiss[writing_idx] = here;
writing_idx++;
last = &here;
}
}
path->erase(path->begin() + writing_idx , path->end());
if (size() < 3)
{
clear();
return;
}
{ // handle the line segments spanning the vector end and begin
Point* last = &thiss.back();
Point& here = thiss[0];
if ( vSize2(here-*last) < allowed_error_distance_squared )
{
remove(0);
}
Point& next = thiss[1];
int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next);
if (error2 < allowed_error_distance_squared)
{
remove(0);
} else
{
// leave it in
}
}
if (size() < 3)
{
clear();
return;
}
}
std::vector<PolygonsPart> Polygons::splitIntoParts(bool unionAll) const
{
std::vector<PolygonsPart> ret;
ClipperLib::Clipper clipper(clipper_init);
ClipperLib::PolyTree resultPolyTree;
clipper.AddPaths(paths, ClipperLib::ptSubject, true);
if (unionAll)
clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
else
clipper.Execute(ClipperLib::ctUnion, resultPolyTree);
splitIntoParts_processPolyTreeNode(&resultPolyTree, ret);
return ret;
}
void Polygons::splitIntoParts_processPolyTreeNode(ClipperLib::PolyNode* node, std::vector<PolygonsPart>& ret) const
{
for(int n=0; n<node->ChildCount(); n++)
{
ClipperLib::PolyNode* child = node->Childs[n];
PolygonsPart part;
part.add(child->Contour);
for(int i=0; i<child->ChildCount(); i++)
{
part.add(child->Childs[i]->Contour);
splitIntoParts_processPolyTreeNode(child->Childs[i], ret);
}
ret.push_back(part);
}
}
unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
PartsView& partsView = *this;
for (unsigned int part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++)
{
std::vector<unsigned int>& partView = partsView[part_idx_now];
if (partView.size() == 0) { continue; }
std::vector<unsigned int>::iterator result = std::find(partView.begin(), partView.end(), poly_idx);
if (result != partView.end())
{
if (boundary_poly_idx) { *boundary_poly_idx = partView[0]; }
return part_idx_now;
}
}
return NO_INDEX;
}
PolygonsPart PartsView::assemblePart(unsigned int part_idx)
{
PartsView& partsView = *this;
PolygonsPart ret;
if (part_idx != NO_INDEX)
{
for (unsigned int poly_idx_ff : partsView[part_idx])
{
ret.add(polygons[poly_idx_ff]);
}
}
return ret;
}
PolygonsPart PartsView::assemblePartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
PolygonsPart ret;
unsigned int part_idx = getPartContaining(poly_idx, boundary_poly_idx);
if (part_idx != NO_INDEX)
{
return assemblePart(part_idx);
}
return ret;
}
PartsView Polygons::splitIntoPartsView(bool unionAll)
{
Polygons reordered;
PartsView partsView(*this);
ClipperLib::Clipper clipper(clipper_init);
ClipperLib::PolyTree resultPolyTree;
clipper.AddPaths(paths, ClipperLib::ptSubject, true);
if (unionAll)
clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
else
clipper.Execute(ClipperLib::ctUnion, resultPolyTree);
splitIntoPartsView_processPolyTreeNode(partsView, reordered, &resultPolyTree);
(*this) = reordered;
return partsView;
}
void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Polygons& reordered, ClipperLib::PolyNode* node) const
{
for(int n=0; n<node->ChildCount(); n++)
{
ClipperLib::PolyNode* child = node->Childs[n];
partsView.emplace_back();
unsigned int pos = partsView.size() - 1;
partsView[pos].push_back(reordered.size());
reordered.add(child->Contour);
for(int i = 0; i < child->ChildCount(); i++)
{
partsView[pos].push_back(reordered.size());
reordered.add(child->Childs[i]->Contour);
splitIntoPartsView_processPolyTreeNode(partsView, reordered, child->Childs[i]);
}
}
}
}//namespace cura
<commit_msg>Compare in PolygonRef::shorterThan is strange.<commit_after>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "polygon.h"
#include "linearAlg2D.h" // pointLiesOnTheRightOfLine
#include "../debug.h"
namespace cura
{
bool PolygonRef::shorterThan(int64_t check_length) const
{
const PolygonRef& polygon = *this;
const Point* p0 = &polygon.back();
int64_t length = 0;
for (const Point& p1 : polygon)
{
length += vSize(*p0 - p1);
if (length >= check_length)
{
return false;
}
p0 = &p1;
}
return true;
}
bool PolygonRef::inside(Point p, bool border_result)
{
PolygonRef thiss = *this;
if (size() < 1)
{
return false;
}
int crossings = 0;
Point p0 = back();
for(unsigned int n=0; n<size(); n++)
{
Point p1 = thiss[n];
// no tests unless the segment p0-p1 is at least partly at, or to right of, p.X
short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
if (comp == 1)
{
crossings++;
}
else if (comp == 0)
{
return border_result;
}
p0 = p1;
}
return (crossings % 2) == 1;
}
bool Polygons::inside(Point p, bool border_result) const
{
const Polygons& thiss = *this;
if (size() < 1)
{
return false;
}
int crossings = 0;
for (const ClipperLib::Path& poly : thiss)
{
Point p0 = poly.back();
for (const Point& p1 : poly)
{
short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
if (comp == 1)
{
crossings++;
}
else if (comp == 0)
{
return border_result;
}
p0 = p1;
}
}
return (crossings % 2) == 1;
}
unsigned int Polygons::findInside(Point p, bool border_result)
{
Polygons& thiss = *this;
if (size() < 1)
{
return false;
}
int64_t min_x[size()];
std::fill_n(min_x, size(), std::numeric_limits<int64_t>::max()); // initialize with int.max
int crossings[size()];
std::fill_n(crossings, size(), 0); // initialize with zeros
for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
{
PolygonRef poly = thiss[poly_idx];
Point p0 = poly.back();
for(Point& p1 : poly)
{
short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1);
if (comp == 1)
{
crossings[poly_idx]++;
int64_t x;
if (p1.Y == p0.Y)
{
x = p0.X;
}
else
{
x = p0.X + (p1.X-p0.X) * (p.Y-p0.Y) / (p1.Y-p0.Y);
}
if (x < min_x[poly_idx])
{
min_x[poly_idx] = x;
}
}
else if (border_result && comp == 0)
{
return poly_idx;
}
p0 = p1;
}
}
int64_t min_x_uneven = std::numeric_limits<int64_t>::max();
unsigned int ret = NO_INDEX;
unsigned int n_unevens = 0;
for (unsigned int array_idx = 0; array_idx < size(); array_idx++)
{
if (crossings[array_idx] % 2 == 1)
{
n_unevens++;
if (min_x[array_idx] < min_x_uneven)
{
min_x_uneven = min_x[array_idx];
ret = array_idx;
}
}
}
if (n_unevens % 2 == 0) { ret = NO_INDEX; }
return ret;
}
void PolygonRef::simplify(int smallest_line_segment_squared, int allowed_error_distance_squared){
PolygonRef& thiss = *this;
if (size() <= 2)
{
clear();
return;
}
{ // remove segments smaller than allowed_error_distance
// this is neccesary in order to avoid the case where a long segment is followed by a lot of small segments would get simplified to a long segment going to the wrong end point
// ....... _ _______
// | / |
// | would become / instead of |
// | / |
Point* last = &thiss.back();
unsigned int writing_idx = 0;
for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++)
{
Point& here = thiss[poly_idx];
if (vSize2(*last - here) < smallest_line_segment_squared)
{
// don't add the point
}
else
{
thiss[writing_idx] = here;
writing_idx++;
last = &here;
}
}
path->erase(path->begin() + writing_idx , path->end());
}
if (size() < 3)
{
clear();
return;
}
Point* last = &thiss[0];
unsigned int writing_idx = 1;
for (unsigned int poly_idx = 1; poly_idx < size(); poly_idx++)
{
Point& here = thiss[poly_idx];
if ( vSize2(here-*last) < allowed_error_distance_squared )
{
// don't add the point to the result
continue;
}
Point& next = thiss[(poly_idx+1) % size()];
char here_is_beyond_line = 0;
int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next, &here_is_beyond_line);
if (here_is_beyond_line == 0 && error2 < allowed_error_distance_squared)
{// don't add the point to the result
} else
{
thiss[writing_idx] = here;
writing_idx++;
last = &here;
}
}
path->erase(path->begin() + writing_idx , path->end());
if (size() < 3)
{
clear();
return;
}
{ // handle the line segments spanning the vector end and begin
Point* last = &thiss.back();
Point& here = thiss[0];
if ( vSize2(here-*last) < allowed_error_distance_squared )
{
remove(0);
}
Point& next = thiss[1];
int64_t error2 = LinearAlg2D::getDist2FromLineSegment(*last, here, next);
if (error2 < allowed_error_distance_squared)
{
remove(0);
} else
{
// leave it in
}
}
if (size() < 3)
{
clear();
return;
}
}
std::vector<PolygonsPart> Polygons::splitIntoParts(bool unionAll) const
{
std::vector<PolygonsPart> ret;
ClipperLib::Clipper clipper(clipper_init);
ClipperLib::PolyTree resultPolyTree;
clipper.AddPaths(paths, ClipperLib::ptSubject, true);
if (unionAll)
clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
else
clipper.Execute(ClipperLib::ctUnion, resultPolyTree);
splitIntoParts_processPolyTreeNode(&resultPolyTree, ret);
return ret;
}
void Polygons::splitIntoParts_processPolyTreeNode(ClipperLib::PolyNode* node, std::vector<PolygonsPart>& ret) const
{
for(int n=0; n<node->ChildCount(); n++)
{
ClipperLib::PolyNode* child = node->Childs[n];
PolygonsPart part;
part.add(child->Contour);
for(int i=0; i<child->ChildCount(); i++)
{
part.add(child->Childs[i]->Contour);
splitIntoParts_processPolyTreeNode(child->Childs[i], ret);
}
ret.push_back(part);
}
}
unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
PartsView& partsView = *this;
for (unsigned int part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++)
{
std::vector<unsigned int>& partView = partsView[part_idx_now];
if (partView.size() == 0) { continue; }
std::vector<unsigned int>::iterator result = std::find(partView.begin(), partView.end(), poly_idx);
if (result != partView.end())
{
if (boundary_poly_idx) { *boundary_poly_idx = partView[0]; }
return part_idx_now;
}
}
return NO_INDEX;
}
PolygonsPart PartsView::assemblePart(unsigned int part_idx)
{
PartsView& partsView = *this;
PolygonsPart ret;
if (part_idx != NO_INDEX)
{
for (unsigned int poly_idx_ff : partsView[part_idx])
{
ret.add(polygons[poly_idx_ff]);
}
}
return ret;
}
PolygonsPart PartsView::assemblePartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx)
{
PolygonsPart ret;
unsigned int part_idx = getPartContaining(poly_idx, boundary_poly_idx);
if (part_idx != NO_INDEX)
{
return assemblePart(part_idx);
}
return ret;
}
PartsView Polygons::splitIntoPartsView(bool unionAll)
{
Polygons reordered;
PartsView partsView(*this);
ClipperLib::Clipper clipper(clipper_init);
ClipperLib::PolyTree resultPolyTree;
clipper.AddPaths(paths, ClipperLib::ptSubject, true);
if (unionAll)
clipper.Execute(ClipperLib::ctUnion, resultPolyTree, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
else
clipper.Execute(ClipperLib::ctUnion, resultPolyTree);
splitIntoPartsView_processPolyTreeNode(partsView, reordered, &resultPolyTree);
(*this) = reordered;
return partsView;
}
void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Polygons& reordered, ClipperLib::PolyNode* node) const
{
for(int n=0; n<node->ChildCount(); n++)
{
ClipperLib::PolyNode* child = node->Childs[n];
partsView.emplace_back();
unsigned int pos = partsView.size() - 1;
partsView[pos].push_back(reordered.size());
reordered.add(child->Contour);
for(int i = 0; i < child->ChildCount(); i++)
{
partsView[pos].push_back(reordered.size());
reordered.add(child->Childs[i]->Contour);
splitIntoPartsView_processPolyTreeNode(partsView, reordered, child->Childs[i]);
}
}
}
}//namespace cura
<|endoftext|> |
<commit_before>/*
Usage: seq_sample N IN.fastq OUT.fastq
Samples N reads from IN.fastq and writes them to OUT.fastq without
duplicates.
*/
#include <fstream>
#include <iostream>
#include <set>
#include <seqan/basic.h>
#include <seqan/file.h>
#include <seqan/misc/misc_random.h>
#include <seqan/sequence.h>
#include <seqan/store.h>
using namespace seqan;
template <
typename TStream,
typename TSeq >
void dumpWrapped(
TStream &out,
TSeq &seq)
{
unsigned size = length(seq);
unsigned i;
for (i = 0; i + 60 < size; i += 60)
out << infix(seq, i, i + 60) << std::endl;
out << infix(seq, i, size) << std::endl;
}
template <typename TStream, typename TStringSetSpec, typename TStringSetSpec2>
void write(TStream & stream,
StringSet<String<Dna5Q>, TStringSetSpec> const & sequences,
StringSet<CharString, TStringSetSpec2> const & seqIds,
Fastq const &) {
typedef StringSet<String<Dna5Q>, TStringSetSpec> TStringSet;
typedef typename Position<TStringSet>::Type TPosition;
CharString qualBuffer;
for (TPosition i = 0; i < length(sequences); ++i) {
stream << "@" << seqIds[i] << std::endl;
stream << sequences[i] << std::endl;
stream << "+" << seqIds[i] << std::endl;
resize(qualBuffer, length(sequences[i]), Exact());
for (TPosition j = 0; j < length(sequences[i]); ++j) {
qualBuffer[j] = getQualityValue(sequences[i][j]) + '!';
}
stream << qualBuffer << std::endl;
}
}
int main(int argc, char **argv) {
if (argc != 4) {
std::cerr << "ERROR: Wrong number of parameters!" << std::endl;
std::cerr << "USAGE: seq_sample N IN.fastq OUT.fastq" << std::endl;
return 1;
}
// TODO(holtgrew): Actually, we want to seed this!
// const unsigned SEED = 42;
mtRandInit();
unsigned n = atoi(argv[1]);
// Load reads using the fragment store.
FragmentStore<> fragStore;
if (!loadReads(fragStore, argv[2])) return 1;
// The factor 10 is arbitrarily chosen to make sure the generation
// is sufficiently fast.
if (length(fragStore.readSeqStore) < 10 * n) {
std::cerr << "Number of reads in file should be >= 10*n" << std::endl;
return 1;
}
// Randomly build the resulting string set.
// Pick ids to select.
std::set<unsigned> selectedIds;
while (length(selectedIds) < n) {
unsigned x = mtRand() % length(fragStore.readSeqStore);
selectedIds.insert(x);
}
// Actually build result.
StringSet<String<Dna5Q> > resultSeqs;
reserve(resultSeqs, n);
StringSet<CharString> resultIds;
reserve(resultIds, n);
for (std::set<unsigned>::const_iterator it = selectedIds.begin(); it != selectedIds.end(); ++it) {
appendValue(resultSeqs, fragStore.readSeqStore[*it]);
appendValue(resultIds, fragStore.readNameStore[*it]);
}
// Write out the result.
if (CharString("-") == argv[3]) {
write(std::cout, resultSeqs, resultIds, Fastq());
} else {
std::fstream fstrm(argv[3], std::ios_base::out);
if (not fstrm.is_open()) {
std::cerr << "Could not open out file \"" << argv[3] << "\"" << std::endl;
return 1;
}
write(fstrm, resultSeqs, resultIds, Fastq());
}
return 0;
}
<commit_msg>New seq_sample app.<commit_after>/*
Usage: seq_sample N IN.fastq OUT.fastq
seq_sample N IN.1.fastq IN.2.fastq OUT.1.fastq OUT.2.fastq
Samples N reads from IN.fastq and writes them to OUT.fastq without
duplicates, alternatively from mate-paired reads.
*/
#include <fstream>
#include <iostream>
#include <set>
#include <seqan/basic.h>
#include <seqan/file.h>
#include <seqan/misc/misc_random.h>
#include <seqan/sequence.h>
#include <seqan/store.h>
using namespace seqan;
template <typename TStream, typename TStringSetSpec, typename TStringSetSpec2>
void write(TStream & stream,
StringSet<String<Dna5Q>, TStringSetSpec> const & sequences,
StringSet<CharString, TStringSetSpec2> const & seqIds,
Fastq const &) {
typedef StringSet<String<Dna5Q>, TStringSetSpec> TStringSet;
typedef typename Position<TStringSet>::Type TPosition;
CharString qualBuffer;
for (TPosition i = 0; i < length(sequences); ++i) {
stream << "@" << seqIds[i] << std::endl;
stream << sequences[i] << std::endl;
stream << "+" << seqIds[i] << std::endl;
resize(qualBuffer, length(sequences[i]), Exact());
for (TPosition j = 0; j < length(sequences[i]); ++j) {
qualBuffer[j] = getQualityValue(sequences[i][j]) + '!';
}
stream << qualBuffer << std::endl;
}
}
int main(int argc, char **argv) {
if (argc != 4 && argc != 6) {
std::cerr << "ERROR: Wrong number of parameters!" << std::endl;
std::cerr << "USAGE: seq_sample N IN.fastq OUT.fastq" << std::endl;
std::cerr << " seq_sample N IN.1.fastq IN.2.fastq OUT.1.fastq OUT.2.fastq" << std::endl;
return 1;
}
// TODO(holtgrew): Actually, we want to seed this!
const unsigned SEED = 42;
mtRandInit(SEED);
unsigned n = atoi(argv[1]);
// Load reads using the fragment store.
FragmentStore<> fragStore;
bool hasMatePairs = (argc == 6);
unsigned matePairFactor = hasMatePairs ? 2 : 1;
if (!hasMatePairs) {
if (!loadReads(fragStore, argv[2])) return 1;
} else {
if (!loadReads(fragStore, argv[2], argv[3])) return 1;
}
unsigned matePairCount = length(fragStore.readSeqStore) / matePairFactor;
// The factor 10 is arbitrarily chosen to make sure the generation
// is sufficiently fast.
if (matePairCount < 10 * n) {
std::cerr << "Number of reads/mate pairs in file/s should be >= 10*n" << std::endl;
return 1;
}
// Randomly build the resulting string set.
// Pick ids to select.
std::set<unsigned> selectedIds;
while (length(selectedIds) < n) {
unsigned x = mtRand() % matePairCount;
selectedIds.insert(x);
}
// Actually build result.
StringSet<String<Dna5Q> > resultSeqsL, resultSeqsR;
StringSet<CharString> resultIdsL, resultIdsR;
reserve(resultSeqsL, n);
reserve(resultIdsL, n);
if (hasMatePairs) {
reserve(resultIdsR, n);
reserve(resultSeqsR, n);
}
for (std::set<unsigned>::const_iterator it = selectedIds.begin(); it != selectedIds.end(); ++it) {
if (!hasMatePairs) {
appendValue(resultSeqsL, fragStore.readSeqStore[*it]);
appendValue(resultIdsL, fragStore.readNameStore[*it]);
} else {
appendValue(resultSeqsL, fragStore.readSeqStore[2 * (*it)]);
appendValue(resultIdsL, fragStore.readNameStore[2 * (*it)]);
appendValue(resultSeqsR, fragStore.readSeqStore[2 * (*it) + 1]);
appendValue(resultIdsR, fragStore.readNameStore[2 * (*it) + 1]);
}
}
// Write out the result.
if (!hasMatePairs) {
if (CharString("-") == argv[3]) {
write(std::cout, resultSeqsL, resultIdsL, Fastq());
} else {
std::fstream fstrm(argv[3], std::ios_base::out);
if (not fstrm.is_open()) {
std::cerr << "Could not open out file \"" << argv[3] << "\"" << std::endl;
return 1;
}
write(fstrm, resultSeqsL, resultIdsL, Fastq());
}
} else {
if (CharString("-") == argv[4]) {
write(std::cout, resultSeqsL, resultIdsL, Fastq());
} else {
std::fstream fstrm(argv[4], std::ios_base::out);
if (not fstrm.is_open()) {
std::cerr << "Could not open out file \"" << argv[4] << "\"" << std::endl;
return 1;
}
write(fstrm, resultSeqsL, resultIdsL, Fastq());
}
if (CharString("-") == argv[5]) {
write(std::cout, resultSeqsR, resultIdsR, Fastq());
} else {
std::fstream fstrm(argv[5], std::ios_base::out);
if (not fstrm.is_open()) {
std::cerr << "Could not open out file \"" << argv[5] << "\"" << std::endl;
return 1;
}
write(fstrm, resultSeqsR, resultIdsR, Fastq());
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <mantella_bits/samplesSelection/bestNeighbourhoodSamplesSelection.hpp>
namespace mant {
void BestNeighbourhoodSamplesSelection::selectImplementation() {
arma::Col<double> bestParameter;
double bestObjectiveValue = std::numeric_limits<double>::infinity();
for (const auto& sample : samples_) {
if(sample.second < bestObjectiveValue) {
bestParameter = sample.first;
bestObjectiveValue = sample.second;
}
}
arma::Col<double> distances(samples_.size());
arma::uword n = 0;
for (const auto& sample : samples_) {
distances(++n) = arma::norm(bestParameter - sample.first);
}
for (const auto& i : static_cast<arma::Col<arma::uword>>(static_cast<arma::Col<arma::uword>>(arma::sort_index(distances)).head(numberOfSelectedSamples_))) {
const auto& selectedSample = std::next(std::begin(samples_), i);
selectedSamples_.insert({selectedSample->first, selectedSample->second});
}
}
std::string BestNeighbourhoodSamplesSelection::toString() const {
return "nearest_to_best_samples_selection";
}
}<commit_msg>Fixed toString<commit_after>#include <mantella_bits/samplesSelection/bestNeighbourhoodSamplesSelection.hpp>
namespace mant {
void BestNeighbourhoodSamplesSelection::selectImplementation() {
arma::Col<double> bestParameter;
double bestObjectiveValue = std::numeric_limits<double>::infinity();
for (const auto& sample : samples_) {
if(sample.second < bestObjectiveValue) {
bestParameter = sample.first;
bestObjectiveValue = sample.second;
}
}
arma::Col<double> distances(samples_.size());
arma::uword n = 0;
for (const auto& sample : samples_) {
distances(++n) = arma::norm(bestParameter - sample.first);
}
for (const auto& i : static_cast<arma::Col<arma::uword>>(static_cast<arma::Col<arma::uword>>(arma::sort_index(distances)).head(numberOfSelectedSamples_))) {
const auto& selectedSample = std::next(std::begin(samples_), i);
selectedSamples_.insert({selectedSample->first, selectedSample->second});
}
}
std::string BestNeighbourhoodSamplesSelection::toString() const {
return "best_neighbourhood_samples_selection";
}
}<|endoftext|> |
<commit_before>#ifndef VG_VARIANT_ADDER_HPP
#define VG_VARIANT_ADDER_HPP
/** \file
* variant_adder.hpp: defines a tool class used for adding variants from VCF
* files into existing graphs.
*/
#include "vcf_buffer.hpp"
#include "path_index.hpp"
#include "vg.hpp"
#include "progressive.hpp"
#include "name_mapper.hpp"
#include "graph_synchronizer.hpp"
namespace vg {
using namespace std;
/**
* A tool class for adding variants to a VG graph. Integrated NameMapper
* provides name translation for the VCF contigs.
*/
class VariantAdder : public NameMapper, public Progressive {
public:
/**
* Make a new VariantAdder to add variants to the given graph. Modifies the
* graph in place.
*/
VariantAdder(VG& graph);
/**
* Add in the variants from the given non-null VCF file. The file must be
* freshly opened. The variants in the file must be sorted.
*
* May be called from multiple threads. Synchronizes internally on the
* graph.
*/
void add_variants(vcflib::VariantCallFile* vcf);
/// How wide of a range in bases should we look for nearby variants in?
size_t variant_range = 50;
/// How much additional context should we try and add outside the radius of
/// our group of variants we actually find?
size_t flank_range = 20;
/// Should we accept and ignore VCF contigs that we can't find in the graph?
bool ignore_missing_contigs = false;
protected:
/// The graph we are modifying
VG& graph;
/// We keep a GraphSynchronizer so we can have multiple threads working on
/// different parts of the same graph.
GraphSynchronizer sync;
/// We cache the set of valid path names, so we can detect/skip missing ones
/// without locking the graph.
set<string> path_names;
/**
* Get all the unique combinations of variant alts represented by actual
* haplotypes. Arbitrarily phases unphased variants.
*
* Can (and should) take a WindowedVcfBuffer that owns the variants, and
* from which cached pre-parsed genotypes can be extracted.
*
* Returns a set of vectors or one number per variant, giving the alt number
* (starting with 0 for reference) that appears on the haplotype.
*
* TODO: ought to just take a collection of pre-barsed genotypes, but in an
* efficient way (a vector of pointers to vectors of sample genotypes?)
*/
set<vector<int>> get_unique_haplotypes(const vector<vcflib::Variant*>& variants, WindowedVcfBuffer* cache = nullptr) const;
/**
* Convert a haplotype on a list of variants into a string. The string will
* run from the start of the first variant through the end of the last
* variant.
*/
string haplotype_to_string(const vector<int>& haplotype, const vector<vcflib::Variant*>& variants);
/**
* Get the radius of the variant around its center: the amount of sequence
* that needs to be pulled out to make sure you have the ref and all the
* alts, if they exist. This is just going to be twice the longest of the
* ref and the alts.
*/
static size_t get_radius(const vcflib::Variant& variant);
/**
* Get the center position of the given variant.
*/
static size_t get_center(const vcflib::Variant& variant);
/**
* Get the center and radius around that center needed to extract everything
* that might be involved in a group of variants.
*/
static pair<size_t, size_t> get_center_and_radius(const vector<vcflib::Variant*>& variants);
};
}
#endif
<commit_msg>Up context<commit_after>#ifndef VG_VARIANT_ADDER_HPP
#define VG_VARIANT_ADDER_HPP
/** \file
* variant_adder.hpp: defines a tool class used for adding variants from VCF
* files into existing graphs.
*/
#include "vcf_buffer.hpp"
#include "path_index.hpp"
#include "vg.hpp"
#include "progressive.hpp"
#include "name_mapper.hpp"
#include "graph_synchronizer.hpp"
namespace vg {
using namespace std;
/**
* A tool class for adding variants to a VG graph. Integrated NameMapper
* provides name translation for the VCF contigs.
*/
class VariantAdder : public NameMapper, public Progressive {
public:
/**
* Make a new VariantAdder to add variants to the given graph. Modifies the
* graph in place.
*/
VariantAdder(VG& graph);
/**
* Add in the variants from the given non-null VCF file. The file must be
* freshly opened. The variants in the file must be sorted.
*
* May be called from multiple threads. Synchronizes internally on the
* graph.
*/
void add_variants(vcflib::VariantCallFile* vcf);
/// How wide of a range in bases should we look for nearby variants in?
size_t variant_range = 50;
/// How much additional context should we try and add outside the radius of
/// our group of variants we actually find?
size_t flank_range = 100;
/// Should we accept and ignore VCF contigs that we can't find in the graph?
bool ignore_missing_contigs = false;
protected:
/// The graph we are modifying
VG& graph;
/// We keep a GraphSynchronizer so we can have multiple threads working on
/// different parts of the same graph.
GraphSynchronizer sync;
/// We cache the set of valid path names, so we can detect/skip missing ones
/// without locking the graph.
set<string> path_names;
/**
* Get all the unique combinations of variant alts represented by actual
* haplotypes. Arbitrarily phases unphased variants.
*
* Can (and should) take a WindowedVcfBuffer that owns the variants, and
* from which cached pre-parsed genotypes can be extracted.
*
* Returns a set of vectors or one number per variant, giving the alt number
* (starting with 0 for reference) that appears on the haplotype.
*
* TODO: ought to just take a collection of pre-barsed genotypes, but in an
* efficient way (a vector of pointers to vectors of sample genotypes?)
*/
set<vector<int>> get_unique_haplotypes(const vector<vcflib::Variant*>& variants, WindowedVcfBuffer* cache = nullptr) const;
/**
* Convert a haplotype on a list of variants into a string. The string will
* run from the start of the first variant through the end of the last
* variant.
*/
string haplotype_to_string(const vector<int>& haplotype, const vector<vcflib::Variant*>& variants);
/**
* Get the radius of the variant around its center: the amount of sequence
* that needs to be pulled out to make sure you have the ref and all the
* alts, if they exist. This is just going to be twice the longest of the
* ref and the alts.
*/
static size_t get_radius(const vcflib::Variant& variant);
/**
* Get the center position of the given variant.
*/
static size_t get_center(const vcflib::Variant& variant);
/**
* Get the center and radius around that center needed to extract everything
* that might be involved in a group of variants.
*/
static pair<size_t, size_t> get_center_and_radius(const vector<vcflib::Variant*>& variants);
};
}
#endif
<|endoftext|> |
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
// std includes
#include <vector>
// dune-common includes
#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace Assembler {
namespace System {
template <class AnsatzFunctionSpaceImp, class TestFunctionSpaceImp = AnsatzFunctionSpaceImp>
class Constrained
{
public:
typedef AnsatzFunctionSpaceImp AnsatzFunctionSpaceType;
typedef TestFunctionSpaceImp TestFunctionSpaceType;
typedef Constrained<AnsatzFunctionSpaceImp, TestFunctionSpaceImp> ThisType;
//! constructor
Constrained(const AnsatzFunctionSpaceType& ansatzSpace, const TestFunctionSpaceType& testSpace)
: ansatzSpace_(ansatzSpace)
, testSpace_(testSpace)
{
}
//! constructor
Constrained(const AnsatzFunctionSpaceType& ansatzSpace)
: ansatzSpace_(ansatzSpace)
, testSpace_(ansatzSpace)
{
}
const AnsatzFunctionSpaceType& ansatzSpace()
{
return ansatzSpace_;
}
const TestFunctionSpaceType& testSpace()
{
return testSpace_;
}
template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
void assemble(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
{
assembleSystem(localMatrixAssembler, systemMatrix, localVectorAssembler, systemVector);
applyConstraints(systemMatrix, systemVector);
} // void assemble()
template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
void assembleSystem(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
{
// some types
typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
typedef typename GridPartType::template Codim<0>::EntityType EntityType;
typedef typename AnsatzFunctionSpaceType::RangeFieldType RangeFieldType;
typedef Dune::DynamicMatrix<RangeFieldType> LocalMatrixType;
typedef Dune::DynamicVector<RangeFieldType> LocalVectorType;
// common tmp storage for all entities
std::vector<unsigned int> numberTmpMatrices = localMatrixAssembler.numTmpObjectsRequired();
std::vector<LocalMatrixType> tmpLocalAssemblerMatrices(
numberTmpMatrices[0],
LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<LocalMatrixType> tmpLocalOperatorMatrices(
numberTmpMatrices[1],
LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<std::vector<LocalMatrixType>> tmpLocalMatricesContainer;
tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);
tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);
std::vector<unsigned int> numberTmpVectors = localVectorAssembler.numTmpObjectsRequired();
std::vector<LocalVectorType> tmpLocalAssemblerVectors(
numberTmpVectors[0], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<LocalVectorType> tmpLocalFunctionalVectors(
numberTmpVectors[1], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<std::vector<LocalVectorType>> tmpLocalVectorsContainer;
tmpLocalVectorsContainer.push_back(tmpLocalAssemblerVectors);
tmpLocalVectorsContainer.push_back(tmpLocalFunctionalVectors);
// walk the grid to assemble
for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
entityIterator != ansatzSpace_.gridPart().template end<0>();
++entityIterator) {
const EntityType& entity = *entityIterator;
localMatrixAssembler.assembleLocal(ansatzSpace_, testSpace_, entity, systemMatrix, tmpLocalMatricesContainer);
localVectorAssembler.assembleLocal(testSpace_, entity, systemVector, tmpLocalVectorsContainer);
} // walk the grid to assemble
} // void assembleSystem()
template <class MatrixType, class VectorType>
void applyConstraints(MatrixType& matrix, VectorType& vector) const
{
typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
typedef typename GridPartType::template Codim<0>::EntityType EntityType;
typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType;
typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType;
// walk the grid to apply constraints
const ConstraintsType& constraints = ansatzSpace_.constraints();
for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
entityIterator != ansatzSpace_.gridPart().template end<0>();
++entityIterator) {
const EntityType& entity = *entityIterator;
const LocalConstraintsType& localConstraints = constraints.local(entity);
applyLocalMatrixConstraints(localConstraints, matrix);
applyLocalVectorConstraints(localConstraints, vector);
} // walk the grid to apply constraints
} // void applyConstraints()
private:
ThisType& operator=(const ThisType&);
Constrained(const ThisType&);
template <class LocalConstraintsType, class MatrixType>
void applyLocalMatrixConstraints(const LocalConstraintsType& localConstraints, MatrixType& matrix) const
{
for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
for (unsigned int j = 0; j < localConstraints.columnDofsSize(); ++j) {
matrix.set(localConstraints.rowDofs(i), localConstraints.columnDofs(j), localConstraints.localMatrix(i, j));
}
}
} // end applyLocalMatrixConstraints
template <class LocalConstraintsType, class VectorType>
void applyLocalVectorConstraints(const LocalConstraintsType& localConstraints, VectorType& vector) const
{
for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
vector.set(localConstraints.rowDofs(i), 0.0);
}
} // end applyLocalVectorConstraints
const AnsatzFunctionSpaceType& ansatzSpace_;
const TestFunctionSpaceType& testSpace_;
}; // end class Constrained
} // end namespace System
} // end namespace Assembler
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
<commit_msg>[assembler.system.constrained] some cleanup<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
// std includes
#include <vector>
// dune-common includes
#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace Assembler {
namespace System {
template <class AnsatzFunctionSpaceImp, class TestFunctionSpaceImp = AnsatzFunctionSpaceImp>
class Constrained
{
public:
typedef AnsatzFunctionSpaceImp AnsatzFunctionSpaceType;
typedef TestFunctionSpaceImp TestFunctionSpaceType;
typedef Constrained<AnsatzFunctionSpaceImp, TestFunctionSpaceImp> ThisType;
//! constructor
Constrained(const AnsatzFunctionSpaceType& ansatzSpace, const TestFunctionSpaceType& testSpace)
: ansatzSpace_(ansatzSpace)
, testSpace_(testSpace)
{
}
//! constructor
Constrained(const AnsatzFunctionSpaceType& ansatzSpace)
: ansatzSpace_(ansatzSpace)
, testSpace_(ansatzSpace)
{
}
const AnsatzFunctionSpaceType& ansatzSpace()
{
return ansatzSpace_;
}
const TestFunctionSpaceType& testSpace()
{
return testSpace_;
}
template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
void assemble(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
{
assembleSystem(localMatrixAssembler, systemMatrix, localVectorAssembler, systemVector);
applyConstraints(systemMatrix, systemVector);
} // void assemble()
template <class LocalMatrixAssemblerType, class MatrixType, class LocalVectorAssemblerType, class VectorType>
void assembleSystem(const LocalMatrixAssemblerType& localMatrixAssembler, MatrixType& systemMatrix,
const LocalVectorAssemblerType& localVectorAssembler, VectorType& systemVector) const
{
// some types
typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
typedef typename GridPartType::template Codim<0>::EntityType EntityType;
typedef typename AnsatzFunctionSpaceType::RangeFieldType RangeFieldType;
typedef Dune::DynamicMatrix<RangeFieldType> LocalMatrixType;
typedef Dune::DynamicVector<RangeFieldType> LocalVectorType;
// common tmp storage for all entities
std::vector<unsigned int> numberTmpMatrices = localMatrixAssembler.numTmpObjectsRequired();
std::vector<LocalMatrixType> tmpLocalAssemblerMatrices(
numberTmpMatrices[0],
LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<LocalMatrixType> tmpLocalOperatorMatrices(
numberTmpMatrices[1],
LocalMatrixType(ansatzSpace_.map().maxLocalSize(), testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<std::vector<LocalMatrixType>> tmpLocalMatricesContainer;
tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);
tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);
std::vector<unsigned int> numberTmpVectors = localVectorAssembler.numTmpObjectsRequired();
std::vector<LocalVectorType> tmpLocalAssemblerVectors(
numberTmpVectors[0], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<LocalVectorType> tmpLocalFunctionalVectors(
numberTmpVectors[1], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0.0)));
std::vector<std::vector<LocalVectorType>> tmpLocalVectorsContainer;
tmpLocalVectorsContainer.push_back(tmpLocalAssemblerVectors);
tmpLocalVectorsContainer.push_back(tmpLocalFunctionalVectors);
// walk the grid to assemble
for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
entityIterator != ansatzSpace_.gridPart().template end<0>();
++entityIterator) {
const EntityType& entity = *entityIterator;
localMatrixAssembler.assembleLocal(ansatzSpace_, testSpace_, entity, systemMatrix, tmpLocalMatricesContainer);
localVectorAssembler.assembleLocal(testSpace_, entity, systemVector, tmpLocalVectorsContainer);
} // walk the grid to assemble
} // void assembleSystem()
template <class MatrixType, class VectorType>
void applyConstraints(MatrixType& matrix, VectorType& vector) const
{
typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType;
typedef typename GridPartType::template Codim<0>::IteratorType EntityIteratorType;
typedef typename GridPartType::template Codim<0>::EntityType EntityType;
typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType;
typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType;
// walk the grid to apply constraints
const ConstraintsType& constraints = ansatzSpace_.constraints();
for (EntityIteratorType entityIterator = ansatzSpace_.gridPart().template begin<0>();
entityIterator != ansatzSpace_.gridPart().template end<0>();
++entityIterator) {
const EntityType& entity = *entityIterator;
const LocalConstraintsType& localConstraints = constraints.local(entity);
applyLocalMatrixConstraints(localConstraints, matrix);
applyLocalVectorConstraints(localConstraints, vector);
} // walk the grid to apply constraints
} // void applyConstraints()
private:
ThisType& operator=(const ThisType&);
Constrained(const ThisType&);
template <class LocalConstraintsType, class MatrixType>
void applyLocalMatrixConstraints(const LocalConstraintsType& localConstraints, MatrixType& matrix) const
{
for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
const unsigned int rowDof = localConstraints.rowDofs(i);
for (unsigned int j = 0; j < localConstraints.columnDofsSize(); ++j) {
matrix.set(rowDof, localConstraints.columnDofs(j), localConstraints.localMatrix(i, j));
}
}
} // end applyLocalMatrixConstraints
template <class LocalConstraintsType, class VectorType>
void applyLocalVectorConstraints(const LocalConstraintsType& localConstraints, VectorType& vector) const
{
for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) {
vector.set(localConstraints.rowDofs(i), 0.0);
}
} // end applyLocalVectorConstraints
const AnsatzFunctionSpaceType& ansatzSpace_;
const TestFunctionSpaceType& testSpace_;
}; // end class Constrained
} // end namespace System
} // end namespace Assembler
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_AFFINE_HH
<|endoftext|> |
<commit_before>// This macro plays a recorded ROOT session showing how to perform various
// interactive graphical editing operations. The initial graphics setup
// was created using the following root commands:
/*
t = new TRecorder();
t->Start("graphedit_playback.root");
gStyle->SetPalette(1);
TCanvas *c2 = new TCanvas("c2","c2",0,0,700,500);
TH2F* h2 = new TH2F("h2","Random 2D Gaussian",40,-4,4,40,-4,4);
h2->SetDirectory(0);
TRandom r;
for (int i=0;i<50000;i++) h2->Fill(r.Gaus(),r.Gaus());
h2->Draw();
gPad->Update();
TCanvas *c1 = new TCanvas("c1","c1",0,0,700,500);
TH1F* h1 = new TH1F("h1","Random 1D Gaussian",100,-4,4);
h1->SetDirectory(0);
h1->FillRandom("gaus",10000);
h1->Draw();
gPad->Update();
// Here the following "sketch" was done.
t->Stop();
*/
// Note: The previous commands should be copy/pasted into a ROOT session, not
// executed as a macro.
//
// The interactive editing shows:
// - Object editing using object editors
// - Direct editing on the graphics canvas
// - Saving PS and bitmap files.
// - Saving as a .C file: C++ code corresponding to the modifications
// is saved.
//
// The sketch of the recorded actions is:
//
// On the canvas c1:
// Open View/Editor
// Select histogram
// Change fill style
// Change fill color
// Move stat box
// Change fill color
// Move title
// Change fill color using wheel color
// Select Y axis
// Change axis title
// Select X axis
// Change axis title
// Select histogram
// Go in binning
// Change range
// Move range
// On the canvas menu set grid Y
// On the canvas menu set grid X
// On the canvas menu set log Y
// Increase the range
// Close View/Editor
// Open the Tool Bar
// Create a text "Comment"
// Create an arrow
// Change the arrow size
// Close the Tool Bar
// Save as PS file
// Save as C file
// Close c1
// On the canvas c2:
// Open View/Editor
// Select histogram
// Select COL
// Select Palette
// Move Stats
// Select Overflows
// Select histogram
// Select 3D
// Select SURF1
// Rotate Surface
// Go in binning
// Change X range
// Change Y range
// Close View/Editor
// Save as GIF file
// Save as C file
// Close c2
Int_t file_size(char *filename)
{
FileStat_t fs;
gSystem->GetPathInfo(filename, fs);
return (Int_t)fs.fSize;
}
void graph_edit_playback()
{
r = new TRecorder();
r->Replay("http://root.cern.ch/files/graphedit_playback.root",kFALSE);
// wait for the recorder to finish the replay
while (r->GetState() == TRecorder::kReplaying) {
gSystem->ProcessEvents();
gSystem->Sleep(1);
}
Int_t c1_ps_Ref = 11592 , c1_ps_Err = 500;
Int_t c1_C_Ref = 4729 , c1_C_Err = 100;
Int_t c2_gif_Ref = 21184 , c2_gif_Err = 100;
Int_t c2_C_Ref = 35471 , c2_C_Err = 100;
Int_t c1_ps = file_size("c1.ps");
Int_t c1_C = file_size("c1.C");
Int_t c2_gif = file_size("c2.gif");
Int_t c2_C = file_size("c2.C");
cout << "**********************************************************************" <<endl;
cout << "* Report of graph_edit_playback.C *" <<endl;
cout << "**********************************************************************" <<endl;
if (TMath::Abs(c1_ps_Ref-c1_ps) <= c1_ps_Err) {
cout << "Canvas c1: PS output............................................... OK" <<endl;
} else {
cout << "Canvas c1: PS output........................................... FAILED" <<endl;
}
if (TMath::Abs(c1_C_Ref-c1_C) <= c1_C_Err) {
cout << " C output................................................ OK" <<endl;
} else {
cout << " C output............................................ FAILED" <<endl;
}
if (TMath::Abs(c2_gif_Ref-c2_gif) <= c2_gif_Err) {
cout << "Canvas c2: GIF output.............................................. OK" <<endl;
} else {
cout << "Canvas c2: GIF output.......................................... FAILED" <<endl;
}
if (TMath::Abs(c2_C_Ref-c2_C) <= c2_C_Err) {
cout << " C output................................................ OK" <<endl;
} else {
cout << " C output............................................ FAILED" <<endl;
}
cout << "**********************************************************************" <<endl;
}
<commit_msg>- Do the replay with the cursor "ON".<commit_after>// This macro plays a recorded ROOT session showing how to perform various
// interactive graphical editing operations. The initial graphics setup
// was created using the following root commands:
/*
t = new TRecorder();
t->Start("graphedit_playback.root");
gStyle->SetPalette(1);
TCanvas *c2 = new TCanvas("c2","c2",0,0,700,500);
TH2F* h2 = new TH2F("h2","Random 2D Gaussian",40,-4,4,40,-4,4);
h2->SetDirectory(0);
TRandom r;
for (int i=0;i<50000;i++) h2->Fill(r.Gaus(),r.Gaus());
h2->Draw();
gPad->Update();
TCanvas *c1 = new TCanvas("c1","c1",0,0,700,500);
TH1F* h1 = new TH1F("h1","Random 1D Gaussian",100,-4,4);
h1->SetDirectory(0);
h1->FillRandom("gaus",10000);
h1->Draw();
gPad->Update();
// Here the following "sketch" was done.
t->Stop();
*/
// Note: The previous commands should be copy/pasted into a ROOT session, not
// executed as a macro.
//
// The interactive editing shows:
// - Object editing using object editors
// - Direct editing on the graphics canvas
// - Saving PS and bitmap files.
// - Saving as a .C file: C++ code corresponding to the modifications
// is saved.
//
// The sketch of the recorded actions is:
//
// On the canvas c1:
// Open View/Editor
// Select histogram
// Change fill style
// Change fill color
// Move stat box
// Change fill color
// Move title
// Change fill color using wheel color
// Select Y axis
// Change axis title
// Select X axis
// Change axis title
// Select histogram
// Go in binning
// Change range
// Move range
// On the canvas menu set grid Y
// On the canvas menu set grid X
// On the canvas menu set log Y
// Increase the range
// Close View/Editor
// Open the Tool Bar
// Create a text "Comment"
// Create an arrow
// Change the arrow size
// Close the Tool Bar
// Save as PS file
// Save as C file
// Close c1
// On the canvas c2:
// Open View/Editor
// Select histogram
// Select COL
// Select Palette
// Move Stats
// Select Overflows
// Select histogram
// Select 3D
// Select SURF1
// Rotate Surface
// Go in binning
// Change X range
// Change Y range
// Close View/Editor
// Save as GIF file
// Save as C file
// Close c2
Int_t file_size(char *filename)
{
FileStat_t fs;
gSystem->GetPathInfo(filename, fs);
return (Int_t)fs.fSize;
}
void graph_edit_playback()
{
r = new TRecorder();
r->Replay("http://root.cern.ch/files/graphedit_playback.root");
// wait for the recorder to finish the replay
while (r->GetState() == TRecorder::kReplaying) {
gSystem->ProcessEvents();
gSystem->Sleep(1);
}
Int_t c1_ps_Ref = 11592 , c1_ps_Err = 500;
Int_t c1_C_Ref = 4729 , c1_C_Err = 100;
Int_t c2_gif_Ref = 21184 , c2_gif_Err = 100;
Int_t c2_C_Ref = 35471 , c2_C_Err = 100;
Int_t c1_ps = file_size("c1.ps");
Int_t c1_C = file_size("c1.C");
Int_t c2_gif = file_size("c2.gif");
Int_t c2_C = file_size("c2.C");
cout << "**********************************************************************" <<endl;
cout << "* Report of graph_edit_playback.C *" <<endl;
cout << "**********************************************************************" <<endl;
if (TMath::Abs(c1_ps_Ref-c1_ps) <= c1_ps_Err) {
cout << "Canvas c1: PS output............................................... OK" <<endl;
} else {
cout << "Canvas c1: PS output........................................... FAILED" <<endl;
}
if (TMath::Abs(c1_C_Ref-c1_C) <= c1_C_Err) {
cout << " C output................................................ OK" <<endl;
} else {
cout << " C output............................................ FAILED" <<endl;
}
if (TMath::Abs(c2_gif_Ref-c2_gif) <= c2_gif_Err) {
cout << "Canvas c2: GIF output.............................................. OK" <<endl;
} else {
cout << "Canvas c2: GIF output.......................................... FAILED" <<endl;
}
if (TMath::Abs(c2_C_Ref-c2_C) <= c2_C_Err) {
cout << " C output................................................ OK" <<endl;
} else {
cout << " C output............................................ FAILED" <<endl;
}
cout << "**********************************************************************" <<endl;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: webdavprovider.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kso $ $Date: 2001-11-26 09:45:37 $
*
* 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 _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX
#include <hash_set>
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif
#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX
#include "PropertyMap.hxx"
#endif
namespace webdav_ucp {
//=========================================================================
// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
"com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38
// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
"vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH 19
#define HTTP_URL_SCHEME "http"
#define HTTP_URL_SCHEME_LENGTH 4
#define HTTPS_URL_SCHEME "https"
#define HTTPS_URL_SCHEME_LENGTH 5
#define FTP_URL_SCHEME "ftp"
#define HTTP_CONTENT_TYPE \
"application/" HTTP_URL_SCHEME "-content"
#define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
"application/" WEBDAV_URL_SCHEME "-collection"
//=========================================================================
class ContentProvider : public ::ucb::ContentProviderImplHelper
{
rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
PropertyMap * m_pProps;
public:
ContentProvider( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
virtual ~ContentProvider();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
XSERVICEINFO_DECL()
// XContentProvider
virtual ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContent > SAL_CALL
queryContent( const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >& Identifier )
throw( ::com::sun::star::ucb::IllegalIdentifierException,
::com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Additional interfaces
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Non-interface methods.
//////////////////////////////////////////////////////////////////////
rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
{ return m_xDAVSessionFactory; }
bool getProperty( const ::rtl::OUString & rPropName,
::com::sun::star::beans::Property & rProp,
bool bStrict = false );
};
}
#endif
<commit_msg>INTEGRATION: CWS ooo20040704 (1.6.180); FILE MERGED 2004/06/28 14:35:47 cmc 1.6.180.1: #i30801# allow using system libs if possible<commit_after>/*************************************************************************
*
* $RCSfile: webdavprovider.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2004-09-08 17:07:13 $
*
* 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 _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif
#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX
#include "PropertyMap.hxx"
#endif
namespace webdav_ucp {
//=========================================================================
// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
"com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38
// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
"vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH 19
#define HTTP_URL_SCHEME "http"
#define HTTP_URL_SCHEME_LENGTH 4
#define HTTPS_URL_SCHEME "https"
#define HTTPS_URL_SCHEME_LENGTH 5
#define FTP_URL_SCHEME "ftp"
#define HTTP_CONTENT_TYPE \
"application/" HTTP_URL_SCHEME "-content"
#define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
"application/" WEBDAV_URL_SCHEME "-collection"
//=========================================================================
class ContentProvider : public ::ucb::ContentProviderImplHelper
{
rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
PropertyMap * m_pProps;
public:
ContentProvider( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
virtual ~ContentProvider();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
XSERVICEINFO_DECL()
// XContentProvider
virtual ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContent > SAL_CALL
queryContent( const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >& Identifier )
throw( ::com::sun::star::ucb::IllegalIdentifierException,
::com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Additional interfaces
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Non-interface methods.
//////////////////////////////////////////////////////////////////////
rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
{ return m_xDAVSessionFactory; }
bool getProperty( const ::rtl::OUString & rPropName,
::com::sun::star::beans::Property & rProp,
bool bStrict = false );
};
}
#endif
<|endoftext|> |
<commit_before><commit_msg>This syntax is C++11 only.<commit_after><|endoftext|> |
<commit_before>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Cell.h"
#include "CellImpl.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "TaskScheduler.h"
#include "temple_of_ahnqiraj.h"
enum Spells
{
// Ouro
SPELL_SWEEP = 26103,
SPELL_SAND_BLAST = 26102,
SPELL_GROUND_RUPTURE = 26100,
SPELL_BERSERK = 26615,
SPELL_BOULDER = 26616,
SPELL_OURO_SUBMERGE_VISUAL = 26063,
SPELL_SUMMON_SANDWORM_BASE = 26133,
// Misc - Mounds, Ouro Spawner
SPELL_BIRTH = 26586,
SPELL_DIRTMOUND_PASSIVE = 26092,
SPELL_SUMMON_OURO = 26061,
SPELL_SUMMON_OURO_MOUNDS = 26058,
SPELL_QUAKE = 26093,
SPELL_SUMMON_SCARABS = 26060,
SPELL_SUMMON_OURO_AURA = 26642,
SPELL_DREAM_FOG = 24780
};
enum Misc
{
GROUP_EMERGED = 0,
GROUP_PHASE_TRANSITION = 1,
NPC_DIRT_MOUND = 15712,
GO_SANDWORM_BASE = 180795,
DATA_OURO_HEALTH = 0
};
struct npc_ouro_spawner : public ScriptedAI
{
npc_ouro_spawner(Creature* creature) : ScriptedAI(creature)
{
Reset();
}
bool hasSummoned;
void Reset() override
{
hasSummoned = false;
DoCastSelf(SPELL_DIRTMOUND_PASSIVE);
}
void MoveInLineOfSight(Unit* who) override
{
// Spawn Ouro on LoS check
if (!hasSummoned && who->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(who, 40.0f) && !who->ToPlayer()->IsGameMaster())
{
DoCastSelf(SPELL_SUMMON_OURO);
hasSummoned = true;
}
ScriptedAI::MoveInLineOfSight(who);
}
void JustSummoned(Creature* creature) override
{
// Despawn when Ouro is spawned
if (creature->GetEntry() == NPC_OURO)
{
creature->SetInCombatWithZone();
me->DespawnOrUnsummon();
}
}
};
struct boss_ouro : public BossAI
{
boss_ouro(Creature* creature) : BossAI(creature, DATA_OURO)
{
SetCombatMovement(false);
me->SetControlled(true, UNIT_STATE_ROOT);
_scheduler.SetValidator([this] { return !me->HasUnitState(UNIT_STATE_CASTING); });
}
void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType, SpellSchoolMask) override
{
if (me->HealthBelowPctDamaged(20, damage) && !_enraged)
{
DoCastSelf(SPELL_BERSERK, true);
_enraged = true;
_scheduler.CancelGroup(GROUP_PHASE_TRANSITION);
_scheduler.Schedule(1s, [this](TaskContext context)
{
if (!IsPlayerWithinMeleeRange())
DoSpellAttackToRandomTargetIfReady(SPELL_BOULDER);
context.Repeat();
})
.Schedule(20s, [this](TaskContext context)
{
DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true);
context.Repeat();
});
}
}
void Submerge()
{
me->AttackStop();
me->SetReactState(REACT_PASSIVE);
me->SetUnitFlag(UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
_submergeMelee = 0;
_submerged = true;
DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL);
_scheduler.CancelGroup(GROUP_EMERGED);
_scheduler.CancelGroup(GROUP_PHASE_TRANSITION);
if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 10.f))
{
base->Use(me);
base->DespawnOrUnsummon(6s);
}
DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true);
// According to sniffs, Ouro uses his mounds to respawn. The health management could be a little scuffed.
std::list<Creature*> ouroMounds;
me->GetCreatureListWithEntryInGrid(ouroMounds, NPC_DIRT_MOUND, 200.f);
if (!ouroMounds.empty()) // This can't be possible, but just to be sure.
{
if (Creature* mound = Acore::Containers::SelectRandomContainerElement(ouroMounds))
{
mound->AddAura(SPELL_SUMMON_OURO_AURA, mound);
mound->AI()->SetData(DATA_OURO_HEALTH, me->GetHealth());
}
}
me->DespawnOrUnsummon(1000);
}
void CastGroundRupture()
{
std::list<WorldObject*> targets;
Acore::AllWorldObjectsInRange checker(me, 10.0f);
Acore::WorldObjectListSearcher<Acore::AllWorldObjectsInRange> searcher(me, targets, checker);
Cell::VisitAllObjects(me, searcher, 10.0f);
for (WorldObject* target : targets)
{
if (Unit* unitTarget = target->ToUnit())
{
if (unitTarget->IsHostileTo(me))
DoCast(unitTarget, SPELL_GROUND_RUPTURE, true);
}
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override
{
if (spellInfo->Id == SPELL_SAND_BLAST && target)
me->GetThreatMgr().modifyThreatPercent(target, 100);
}
void Emerge()
{
DoCastSelf(SPELL_BIRTH);
DoCastSelf(SPELL_SUMMON_SANDWORM_BASE, true);
me->SetReactState(REACT_AGGRESSIVE);
CastGroundRupture();
_scheduler
.Schedule(20s, GROUP_EMERGED, [this](TaskContext context)
{
DoCastVictim(SPELL_SAND_BLAST);
context.Repeat();
})
.Schedule(22s, GROUP_EMERGED, [this](TaskContext context)
{
DoCastVictim(SPELL_SWEEP);
context.Repeat();
})
.Schedule(90s, GROUP_PHASE_TRANSITION, [this](TaskContext /*context*/)
{
Submerge();
})
.Schedule(3s, GROUP_PHASE_TRANSITION, [this](TaskContext context)
{
if (!IsPlayerWithinMeleeRange() && !_submerged)
{
if (_submergeMelee < 10)
{
_submergeMelee++;
}
else
{
if (!_enraged)
Submerge();
_submergeMelee = 0;
}
}
else
{
_submergeMelee = 0;
}
if (!_submerged)
context.Repeat(1s);
});
}
void Reset() override
{
instance->SetBossState(DATA_OURO, NOT_STARTED);
_scheduler.CancelAll();
_submergeMelee = 0;
_submerged = false;
_enraged = false;
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL);
me->DespawnOrUnsummon(1000);
instance->SetBossState(DATA_OURO, FAIL);
if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f))
base->DespawnOrUnsummon();
}
void EnterCombat(Unit* who) override
{
Emerge();
BossAI::EnterCombat(who);
}
void UpdateAI(uint32 diff) override
{
//Return since we have no target
if (!UpdateVictim())
return;
_scheduler.Update(diff, [this]
{
DoMeleeAttackIfReady();
});
}
protected:
TaskScheduler _scheduler;
bool _enraged;
uint8 _submergeMelee;
bool _submerged;
bool IsPlayerWithinMeleeRange() const
{
return me->IsWithinMeleeRange(me->GetVictim());
}
};
struct npc_dirt_mound : ScriptedAI
{
npc_dirt_mound(Creature* creature) : ScriptedAI(creature)
{
_instance = creature->GetInstanceScript();
}
void JustSummoned(Creature* creature) override
{
if (creature->GetEntry() == NPC_OURO)
{
creature->SetInCombatWithZone();
creature->SetHealth(_ouroHealth);
}
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_OURO_HEALTH)
_ouroHealth = data;
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
_scheduler.Schedule(30s, [this](TaskContext /*context*/)
{
DoCastSelf(SPELL_SUMMON_SCARABS, true);
me->DespawnOrUnsummon(1000);
})
.Schedule(100ms, [this](TaskContext context)
{
ChaseNewTarget();
context.Repeat(5s, 10s);
});
}
void ChaseNewTarget()
{
DoResetThreat();
if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 200.f, true))
{
me->AddThreat(target, 1000000.f);
AttackStart(target);
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
_scheduler.Update(diff);
}
void Reset() override
{
DoCastSelf(SPELL_DIRTMOUND_PASSIVE, true);
DoCastSelf(SPELL_DREAM_FOG, true);
DoCastSelf(SPELL_QUAKE, true);
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
if (_instance)
{
_instance->SetBossState(DATA_OURO, FAIL);
}
if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f))
base->DespawnOrUnsummon();
me->DespawnOrUnsummon();
}
protected:
TaskScheduler _scheduler;
uint32 _ouroHealth;
InstanceScript* _instance;
};
void AddSC_boss_ouro()
{
RegisterTempleOfAhnQirajCreatureAI(npc_ouro_spawner);
RegisterTempleOfAhnQirajCreatureAI(boss_ouro);
RegisterTempleOfAhnQirajCreatureAI(npc_dirt_mound);
}
<commit_msg>fix(Scripts/TempleOfAhnQiraj): Reduce player damage req for Ouro (#13065)<commit_after>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Cell.h"
#include "CellImpl.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "TaskScheduler.h"
#include "temple_of_ahnqiraj.h"
enum Spells
{
// Ouro
SPELL_SWEEP = 26103,
SPELL_SAND_BLAST = 26102,
SPELL_GROUND_RUPTURE = 26100,
SPELL_BERSERK = 26615,
SPELL_BOULDER = 26616,
SPELL_OURO_SUBMERGE_VISUAL = 26063,
SPELL_SUMMON_SANDWORM_BASE = 26133,
// Misc - Mounds, Ouro Spawner
SPELL_BIRTH = 26586,
SPELL_DIRTMOUND_PASSIVE = 26092,
SPELL_SUMMON_OURO = 26061,
SPELL_SUMMON_OURO_MOUNDS = 26058,
SPELL_QUAKE = 26093,
SPELL_SUMMON_SCARABS = 26060,
SPELL_SUMMON_OURO_AURA = 26642,
SPELL_DREAM_FOG = 24780
};
enum Misc
{
GROUP_EMERGED = 0,
GROUP_PHASE_TRANSITION = 1,
NPC_DIRT_MOUND = 15712,
GO_SANDWORM_BASE = 180795,
DATA_OURO_HEALTH = 0
};
struct npc_ouro_spawner : public ScriptedAI
{
npc_ouro_spawner(Creature* creature) : ScriptedAI(creature)
{
Reset();
}
bool hasSummoned;
void Reset() override
{
hasSummoned = false;
DoCastSelf(SPELL_DIRTMOUND_PASSIVE);
}
void MoveInLineOfSight(Unit* who) override
{
// Spawn Ouro on LoS check
if (!hasSummoned && who->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(who, 40.0f) && !who->ToPlayer()->IsGameMaster())
{
DoCastSelf(SPELL_SUMMON_OURO);
hasSummoned = true;
}
ScriptedAI::MoveInLineOfSight(who);
}
void JustSummoned(Creature* creature) override
{
// Despawn when Ouro is spawned
if (creature->GetEntry() == NPC_OURO)
{
creature->SetInCombatWithZone();
me->DespawnOrUnsummon();
}
}
};
struct boss_ouro : public BossAI
{
boss_ouro(Creature* creature) : BossAI(creature, DATA_OURO)
{
SetCombatMovement(false);
me->SetControlled(true, UNIT_STATE_ROOT);
_scheduler.SetValidator([this] { return !me->HasUnitState(UNIT_STATE_CASTING); });
}
void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType, SpellSchoolMask) override
{
if (me->HealthBelowPctDamaged(20, damage) && !_enraged)
{
DoCastSelf(SPELL_BERSERK, true);
_enraged = true;
_scheduler.CancelGroup(GROUP_PHASE_TRANSITION);
_scheduler.Schedule(1s, [this](TaskContext context)
{
if (!IsPlayerWithinMeleeRange())
DoSpellAttackToRandomTargetIfReady(SPELL_BOULDER);
context.Repeat();
})
.Schedule(20s, [this](TaskContext context)
{
DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true);
context.Repeat();
});
}
}
void Submerge()
{
me->AttackStop();
me->SetReactState(REACT_PASSIVE);
me->SetUnitFlag(UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
_submergeMelee = 0;
_submerged = true;
DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL);
_scheduler.CancelGroup(GROUP_EMERGED);
_scheduler.CancelGroup(GROUP_PHASE_TRANSITION);
if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 10.f))
{
base->Use(me);
base->DespawnOrUnsummon(6s);
}
DoCastSelf(SPELL_SUMMON_OURO_MOUNDS, true);
// According to sniffs, Ouro uses his mounds to respawn. The health management could be a little scuffed.
std::list<Creature*> ouroMounds;
me->GetCreatureListWithEntryInGrid(ouroMounds, NPC_DIRT_MOUND, 200.f);
if (!ouroMounds.empty()) // This can't be possible, but just to be sure.
{
if (Creature* mound = Acore::Containers::SelectRandomContainerElement(ouroMounds))
{
mound->AddAura(SPELL_SUMMON_OURO_AURA, mound);
mound->AI()->SetData(DATA_OURO_HEALTH, me->GetHealth());
}
}
me->DespawnOrUnsummon(1000);
}
void CastGroundRupture()
{
std::list<WorldObject*> targets;
Acore::AllWorldObjectsInRange checker(me, 10.0f);
Acore::WorldObjectListSearcher<Acore::AllWorldObjectsInRange> searcher(me, targets, checker);
Cell::VisitAllObjects(me, searcher, 10.0f);
for (WorldObject* target : targets)
{
if (Unit* unitTarget = target->ToUnit())
{
if (unitTarget->IsHostileTo(me))
DoCast(unitTarget, SPELL_GROUND_RUPTURE, true);
}
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override
{
if (spellInfo->Id == SPELL_SAND_BLAST && target)
me->GetThreatMgr().modifyThreatPercent(target, 100);
}
void Emerge()
{
DoCastSelf(SPELL_BIRTH);
DoCastSelf(SPELL_SUMMON_SANDWORM_BASE, true);
me->SetReactState(REACT_AGGRESSIVE);
CastGroundRupture();
_scheduler
.Schedule(20s, GROUP_EMERGED, [this](TaskContext context)
{
DoCastVictim(SPELL_SAND_BLAST);
context.Repeat();
})
.Schedule(22s, GROUP_EMERGED, [this](TaskContext context)
{
DoCastVictim(SPELL_SWEEP);
context.Repeat();
})
.Schedule(90s, GROUP_PHASE_TRANSITION, [this](TaskContext /*context*/)
{
Submerge();
})
.Schedule(3s, GROUP_PHASE_TRANSITION, [this](TaskContext context)
{
if (!IsPlayerWithinMeleeRange() && !_submerged)
{
if (_submergeMelee < 10)
{
_submergeMelee++;
}
else
{
if (!_enraged)
Submerge();
_submergeMelee = 0;
}
}
else
{
_submergeMelee = 0;
}
if (!_submerged)
context.Repeat(1s);
});
}
void Reset() override
{
instance->SetBossState(DATA_OURO, NOT_STARTED);
_scheduler.CancelAll();
_submergeMelee = 0;
_submerged = false;
_enraged = false;
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
DoCastSelf(SPELL_OURO_SUBMERGE_VISUAL);
me->DespawnOrUnsummon(1000);
instance->SetBossState(DATA_OURO, FAIL);
if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f))
base->DespawnOrUnsummon();
}
void EnterCombat(Unit* who) override
{
Emerge();
BossAI::EnterCombat(who);
}
void UpdateAI(uint32 diff) override
{
//Return since we have no target
if (!UpdateVictim())
return;
_scheduler.Update(diff, [this]
{
DoMeleeAttackIfReady();
});
}
protected:
TaskScheduler _scheduler;
bool _enraged;
uint8 _submergeMelee;
bool _submerged;
bool IsPlayerWithinMeleeRange() const
{
return me->IsWithinMeleeRange(me->GetVictim());
}
};
struct npc_dirt_mound : ScriptedAI
{
npc_dirt_mound(Creature* creature) : ScriptedAI(creature)
{
_instance = creature->GetInstanceScript();
}
void JustSummoned(Creature* creature) override
{
if (creature->GetEntry() == NPC_OURO)
{
creature->SetInCombatWithZone();
creature->SetHealth(_ouroHealth);
creature->LowerPlayerDamageReq(creature->GetMaxHealth() - creature->GetHealth());
}
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_OURO_HEALTH)
_ouroHealth = data;
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
_scheduler.Schedule(30s, [this](TaskContext /*context*/)
{
DoCastSelf(SPELL_SUMMON_SCARABS, true);
me->DespawnOrUnsummon(1000);
})
.Schedule(100ms, [this](TaskContext context)
{
ChaseNewTarget();
context.Repeat(5s, 10s);
});
}
void ChaseNewTarget()
{
DoResetThreat();
if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 200.f, true))
{
me->AddThreat(target, 1000000.f);
AttackStart(target);
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
_scheduler.Update(diff);
}
void Reset() override
{
DoCastSelf(SPELL_DIRTMOUND_PASSIVE, true);
DoCastSelf(SPELL_DREAM_FOG, true);
DoCastSelf(SPELL_QUAKE, true);
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
if (_instance)
{
_instance->SetBossState(DATA_OURO, FAIL);
}
if (GameObject* base = me->FindNearestGameObject(GO_SANDWORM_BASE, 200.f))
base->DespawnOrUnsummon();
me->DespawnOrUnsummon();
}
protected:
TaskScheduler _scheduler;
uint32 _ouroHealth;
InstanceScript* _instance;
};
void AddSC_boss_ouro()
{
RegisterTempleOfAhnQirajCreatureAI(npc_ouro_spawner);
RegisterTempleOfAhnQirajCreatureAI(boss_ouro);
RegisterTempleOfAhnQirajCreatureAI(npc_dirt_mound);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: null_spritecanvas.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2006-12-13 14:45:40 $
*
* 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 _NULLCANVAS_SPRITECANVAS_HXX_
#define _NULLCANVAS_SPRITECANVAS_HXX_
#include <rtl/ref.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceName.hpp>
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/XGraphicDevice.hpp>
#include <com/sun/star/rendering/XBufferController.hpp>
#include <com/sun/star/rendering/XColorSpace.hpp>
#include <com/sun/star/rendering/XParametricPolyPolygon2DFactory.hpp>
#include <cppuhelper/compbase9.hxx>
#include <comphelper/uno3.hxx>
#include <canvas/base/spritecanvasbase.hxx>
#include <canvas/base/basemutexhelper.hxx>
#include <canvas/base/windowgraphicdevicebase.hxx>
#include "null_spritecanvashelper.hxx"
#include "null_devicehelper.hxx"
#include "null_usagecounter.hxx"
namespace nullcanvas
{
typedef ::cppu::WeakComponentImplHelper9< ::com::sun::star::rendering::XSpriteCanvas,
::com::sun::star::rendering::XIntegerBitmap,
::com::sun::star::rendering::XGraphicDevice,
::com::sun::star::rendering::XParametricPolyPolygon2DFactory,
::com::sun::star::rendering::XBufferController,
::com::sun::star::rendering::XColorSpace,
::com::sun::star::awt::XWindowListener,
::com::sun::star::beans::XPropertySet,
::com::sun::star::lang::XServiceName > WindowGraphicDeviceBase_Base;
typedef ::canvas::WindowGraphicDeviceBase< ::canvas::BaseMutexHelper< WindowGraphicDeviceBase_Base >,
DeviceHelper,
::osl::MutexGuard,
::cppu::OWeakObject > SpriteCanvasBase_Base;
/** Mixin SpriteSurface
Have to mixin the SpriteSurface before deriving from
::canvas::SpriteCanvasBase, as this template should already
implement some of those interface methods.
The reason why this appears kinda convoluted is the fact that
we cannot specify non-IDL types as WeakComponentImplHelperN
template args, and furthermore, don't want to derive
::canvas::SpriteCanvasBase directly from
::canvas::SpriteSurface (because derivees of
::canvas::SpriteCanvasBase have to explicitely forward the
XInterface methods (e.g. via DECLARE_UNO3_AGG_DEFAULTS)
anyway). Basically, ::canvas::CanvasCustomSpriteBase should
remain a base class that provides implementation, not to
enforce any specific interface on its derivees.
*/
class SpriteCanvasBaseSpriteSurface_Base : public SpriteCanvasBase_Base,
public ::canvas::SpriteSurface
{
};
typedef ::canvas::SpriteCanvasBase< SpriteCanvasBaseSpriteSurface_Base,
SpriteCanvasHelper,
::osl::MutexGuard,
::cppu::OWeakObject > SpriteCanvasBaseT;
/** Product of this component's factory.
The SpriteCanvas object combines the actual Window canvas with
the XGraphicDevice interface. This is because there's a
one-to-one relation between them, anyway, since each window
can have exactly one canvas and one associated
XGraphicDevice. And to avoid messing around with circular
references, this is implemented as one single object.
*/
class SpriteCanvas : public SpriteCanvasBaseT,
private UsageCounter< SpriteCanvas >
{
public:
SpriteCanvas( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Any >& aArguments,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext >& rxContext );
void initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );
#if defined __SUNPRO_CC
using SpriteCanvasBaseT::disposing;
#endif
/// Dispose all internal references
virtual void SAL_CALL disposing();
// Forwarding the XComponent implementation to the
// cppu::ImplHelper templated base
// Classname Base doing refcounting Base implementing the XComponent interface
// | | |
// V V V
DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS( SpriteCanvas, WindowGraphicDeviceBase_Base, ::cppu::WeakComponentImplHelperBase );
// XBufferController (partial)
virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
// XSpriteCanvas (partial)
virtual sal_Bool SAL_CALL updateScreen( sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
// XServiceName
virtual ::rtl::OUString SAL_CALL getServiceName( ) throw (::com::sun::star::uno::RuntimeException);
private:
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxComponentContext;
};
typedef ::rtl::Reference< SpriteCanvas > SpriteCanvasRef;
typedef ::rtl::Reference< SpriteCanvas > DeviceRef;
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008/03/28 16:35:09 rt 1.3.80.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: null_spritecanvas.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _NULLCANVAS_SPRITECANVAS_HXX_
#define _NULLCANVAS_SPRITECANVAS_HXX_
#include <rtl/ref.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceName.hpp>
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/XGraphicDevice.hpp>
#include <com/sun/star/rendering/XBufferController.hpp>
#include <com/sun/star/rendering/XColorSpace.hpp>
#include <com/sun/star/rendering/XParametricPolyPolygon2DFactory.hpp>
#include <cppuhelper/compbase9.hxx>
#include <comphelper/uno3.hxx>
#include <canvas/base/spritecanvasbase.hxx>
#include <canvas/base/basemutexhelper.hxx>
#include <canvas/base/windowgraphicdevicebase.hxx>
#include "null_spritecanvashelper.hxx"
#include "null_devicehelper.hxx"
#include "null_usagecounter.hxx"
namespace nullcanvas
{
typedef ::cppu::WeakComponentImplHelper9< ::com::sun::star::rendering::XSpriteCanvas,
::com::sun::star::rendering::XIntegerBitmap,
::com::sun::star::rendering::XGraphicDevice,
::com::sun::star::rendering::XParametricPolyPolygon2DFactory,
::com::sun::star::rendering::XBufferController,
::com::sun::star::rendering::XColorSpace,
::com::sun::star::awt::XWindowListener,
::com::sun::star::beans::XPropertySet,
::com::sun::star::lang::XServiceName > WindowGraphicDeviceBase_Base;
typedef ::canvas::WindowGraphicDeviceBase< ::canvas::BaseMutexHelper< WindowGraphicDeviceBase_Base >,
DeviceHelper,
::osl::MutexGuard,
::cppu::OWeakObject > SpriteCanvasBase_Base;
/** Mixin SpriteSurface
Have to mixin the SpriteSurface before deriving from
::canvas::SpriteCanvasBase, as this template should already
implement some of those interface methods.
The reason why this appears kinda convoluted is the fact that
we cannot specify non-IDL types as WeakComponentImplHelperN
template args, and furthermore, don't want to derive
::canvas::SpriteCanvasBase directly from
::canvas::SpriteSurface (because derivees of
::canvas::SpriteCanvasBase have to explicitely forward the
XInterface methods (e.g. via DECLARE_UNO3_AGG_DEFAULTS)
anyway). Basically, ::canvas::CanvasCustomSpriteBase should
remain a base class that provides implementation, not to
enforce any specific interface on its derivees.
*/
class SpriteCanvasBaseSpriteSurface_Base : public SpriteCanvasBase_Base,
public ::canvas::SpriteSurface
{
};
typedef ::canvas::SpriteCanvasBase< SpriteCanvasBaseSpriteSurface_Base,
SpriteCanvasHelper,
::osl::MutexGuard,
::cppu::OWeakObject > SpriteCanvasBaseT;
/** Product of this component's factory.
The SpriteCanvas object combines the actual Window canvas with
the XGraphicDevice interface. This is because there's a
one-to-one relation between them, anyway, since each window
can have exactly one canvas and one associated
XGraphicDevice. And to avoid messing around with circular
references, this is implemented as one single object.
*/
class SpriteCanvas : public SpriteCanvasBaseT,
private UsageCounter< SpriteCanvas >
{
public:
SpriteCanvas( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Any >& aArguments,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext >& rxContext );
void initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );
#if defined __SUNPRO_CC
using SpriteCanvasBaseT::disposing;
#endif
/// Dispose all internal references
virtual void SAL_CALL disposing();
// Forwarding the XComponent implementation to the
// cppu::ImplHelper templated base
// Classname Base doing refcounting Base implementing the XComponent interface
// | | |
// V V V
DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS( SpriteCanvas, WindowGraphicDeviceBase_Base, ::cppu::WeakComponentImplHelperBase );
// XBufferController (partial)
virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
// XSpriteCanvas (partial)
virtual sal_Bool SAL_CALL updateScreen( sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
// XServiceName
virtual ::rtl::OUString SAL_CALL getServiceName( ) throw (::com::sun::star::uno::RuntimeException);
private:
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxComponentContext;
};
typedef ::rtl::Reference< SpriteCanvas > SpriteCanvasRef;
typedef ::rtl::Reference< SpriteCanvas > DeviceRef;
}
#endif
<|endoftext|> |
<commit_before>/*
* BCJR Decoding, Memoryless Modulation, and Filtering come from Tarik BENADDI (Toulouse INP)
*/
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include "../../../Decoder/decoder_functions.h"
#include "Modulator_GSM_BCJR.hpp"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BCJR tools //////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Q>
struct negative_inf
{
static Q get() { return -std::numeric_limits<Q>::max(); }
};
template <>
struct negative_inf <short>
{
static short get() { return -(1 << (sizeof(short) * 8 -2)); }
};
template <>
struct negative_inf <signed char>
{
static signed char get() { return -63; }
};
template <typename Q, proto_max<Q> MAX>
struct BCJR_normalize
{
// Adrien comment's: I think that the normalisation is useless in floating point arithmetic
static void apply(Q *metrics, const int &i, const int &n_states)
{
// normalization
auto norm_val = negative_inf<signed char>::get();
for (auto j = 0; j < n_states; j++)
norm_val = MAX(norm_val, metrics[j]);
for (auto j = 0; j < n_states; j++)
metrics[j] -= norm_val;
}
};
template <proto_max<signed char> MAX>
struct BCJR_normalize <signed char,MAX>
{
static void apply(signed char *metrics, const int &i, const int &n_states)
{
// normalization & saturation
auto norm_val = negative_inf<signed char>::get();
for (auto j = 0; j < n_states; j++)
norm_val = MAX(norm_val, metrics[j]);
for (auto j = 0; j < n_states; j++)
metrics[j] = saturate<signed char>(metrics[j] - norm_val, -63, +63);
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Q, proto_max<Q> MAX>
Modulator_GSM_BCJR<Q,MAX>
::Modulator_GSM_BCJR(const int frame_size,
const int n_states,
const int m_order,
const int n_bits_per_symb,
const int n_prev_branches,
const std::vector<int> binary_symbols,
const std::vector<int> trellis,
const std::vector<int> anti_trellis)
: frame_size (frame_size ),
n_states (n_states ),
m_order (m_order ),
n_bits_per_symb(n_bits_per_symb),
n_prev_branches(n_prev_branches),
binary_symbols(binary_symbols),
trellis (trellis ),
anti_trellis (anti_trellis ),
symb_apriori_prob(frame_size * m_order ),
gamma (frame_size * n_states * m_order ),
alpha (frame_size * n_states ),
beta (frame_size * n_states ),
proba_msg_symb (frame_size * m_order, 0),
proba_msg_bits (frame_size * 2 , 0)
{
}
template <typename Q, proto_max<Q> MAX>
Modulator_GSM_BCJR<Q,MAX>
::~Modulator_GSM_BCJR()
{
}
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::decode(const mipp::vector<Q> &Lch_N, mipp::vector<Q> &Le_N)
{
std::fill(this->symb_apriori_prob.begin(), this->symb_apriori_prob.end(), 0);
compute_alpha_beta_gamma(Lch_N);
symboles_probas ( );
bits_probas ( );
compute_ext (Le_N );
}
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::decode(const mipp::vector<Q> &Lch_N, const mipp::vector<Q> &Ldec_N, mipp::vector<Q> &Le_N)
{
LLR_to_logsymb_proba (Ldec_N );
compute_alpha_beta_gamma(Lch_N );
symboles_probas ( );
bits_probas ( );
compute_ext (Ldec_N, Le_N);
}
// retrieve log symbols probability from LLR
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::LLR_to_logsymb_proba(const mipp::vector<Q> &Ldec_N)
{
std::fill(this->symb_apriori_prob.begin(), this->symb_apriori_prob.end(), 0);
for (auto i = 0; i < (int) this->symb_apriori_prob.size() / m_order; i++)
for (auto j = 0; j < this->m_order; j++)
for (auto k = 0; k < this->n_bits_per_symb; k++)
{
const auto symbol = this->binary_symbols[k * this->m_order +j];
const auto sign = 1 - (symbol + symbol);
this->symb_apriori_prob[i * this->m_order +j] += (Q)sign * Ldec_N[i * this->n_bits_per_symb +k] * 0.5;
}
}
// compute gamma, alpha and beta, heart of the processing
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::compute_alpha_beta_gamma(const mipp::vector<Q> &Lch_N)
{
// alpha and beta initialization
std::fill(this->alpha.begin(), this->alpha.end(), negative_inf<Q>::get());
std::fill(this->beta .begin(), this->beta .end(), negative_inf<Q>::get());
this->alpha[0 ] = 0;
this->beta [(this->frame_size -1) * this->n_states] = 0;
// other way to initialize beta: does not support the fixed point mode because of the log function call
// this is usefull when we don't use the tail bits in the turbo demodulation
// auto beta_final_equi_proba = 1.0 / this->n_states;
for (auto i = 0; i < this->n_states; i++)
// this->beta[(this->frame_size -1) * n_states +i] = std::log(beta_final_equi_proba);
this->beta[(this->frame_size -1) * n_states +i] = 0;
// compute gamma
for (auto i = 0; i < this->frame_size; i++)
for (auto j = 0; j < this->n_states; j++)
for (auto k = 0; k < this->m_order; k++)
this->gamma[(k * n_states +j) * this->frame_size +i] =
Lch_N[this->trellis[(k + this->m_order) * this->n_states +j] * this->frame_size +i] + // info from the channel
this->symb_apriori_prob[i * this->m_order +k]; // info from the decoder
// compute alpha and beta
for (auto i = 1; i < this->frame_size; i++)
{
for (auto j = 0; j < this->n_states; j++)
{
const auto original_state = this->anti_trellis.data() + j * this->n_prev_branches;
const auto input_symb = this->anti_trellis.data() + (this->n_states +j) * this->n_prev_branches;
// compute the alpha nodes
for (auto k = 0; k < this->n_prev_branches; k++)
this->alpha [(i -0) * this->n_states +j] =
MAX(this->alpha[(i -0) * this->n_states +j],
this->alpha[(i -1) * this->n_states + original_state[k]] +
this->gamma[(input_symb[k] * this->n_states + original_state[k]) * this->frame_size +i -1]);
// compute the beta nodes
for (auto k = 0; k < this->m_order; k++)
this->beta [(this->frame_size - (i +1)) * this->n_states +j] =
MAX(this->beta [(this->frame_size - (i +1)) * this->n_states +j],
this->beta [(this->frame_size - (i +0)) * this->n_states + this->trellis[k * this->n_states +j]] +
this->gamma[(k * this->n_states +j) * this->frame_size + this->frame_size -i]);
}
// normalize alpha and beta vectors (not impact on the decoding performances)
BCJR_normalize<Q,MAX>::apply(&this->alpha[ (i +0) * this->n_states], i, this->n_states);
BCJR_normalize<Q,MAX>::apply(&this->beta [(this->frame_size - (i +1)) * this->n_states], i, this->n_states);
}
}
// from alpha, beta, and gamma computes new symbol probability
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::symboles_probas()
{
// initialize proba_msg_symb
for (auto i = 0; i < this->frame_size; i++)
for (auto j = 0; j < this->m_order; j++)
proba_msg_symb[i * this->m_order +j] = negative_inf<Q>::get();
for (auto i = 0; i < this->frame_size; i++)
for (auto j = 0; j < this->m_order; j++)
for (auto k = 0; k < this->n_states; k++)
proba_msg_symb [ i * this->m_order +j] =
MAX(proba_msg_symb[ i * this->m_order +j],
this->alpha [ i * this->n_states +k] +
this->beta [ i * this->n_states + this->trellis[j * this->n_states +k]] +
this->gamma [(j * this->n_states +k) * this->frame_size +i]);
}
// from symbol probabilities, computes bit probabilities
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::bits_probas()
{
// initialize proba_msg_bits
std::fill(proba_msg_bits.begin(), proba_msg_bits.end(), negative_inf<Q>::get());
for (auto i = 0; i < this->frame_size; i++)
{
const auto ii = i * this->n_bits_per_symb;
for (auto j = 0; j < n_bits_per_symb; j++)
for (auto k = 0; k < this->m_order; k++)
{
const auto symbol = binary_symbols[j * this->m_order +k];
// bit 0
if (symbol == 0)
proba_msg_bits[(ii +j) * 2 +0] = MAX(proba_msg_bits[(ii +j) * 2 +0],
proba_msg_symb[i * this->m_order +k]);
// bit 1
else if (symbol == 1)
proba_msg_bits[(ii +j) * 2 +1] = MAX(proba_msg_bits[(ii +j) * 2 +1],
proba_msg_symb[i * this->m_order +k]);
}
}
}
// extrinsic information processing from bit probabilities
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::compute_ext(mipp::vector<Q> &Le_N)
{
const auto loop_size = (int)Le_N.size() * 2;
for (auto i = 0; i < loop_size; i += 2)
// processing aposteriori and substracting a priori to directly obtain extrinsic
Le_N[i / 2] = proba_msg_bits[i] - proba_msg_bits[i +1];
}
// extrinsic information processing from bit probabilities and CPM a priori LLR
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::compute_ext(const mipp::vector<Q> &Ldec_N,
mipp::vector<Q> &Le_N)
{
const auto loop_size = (int)Le_N.size() * 2;
for (auto i = 0; i < loop_size; i += 2)
// processing aposteriori and substracting a priori to directly obtain extrinsic
Le_N[i / 2] = proba_msg_bits[i] - (proba_msg_bits[i +1] + Ldec_N[i / 2]);
}<commit_msg>Typo-Bug Corrected.<commit_after>/*
* BCJR Decoding, Memoryless Modulation, and Filtering come from Tarik BENADDI (Toulouse INP)
*/
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include "../../../Decoder/decoder_functions.h"
#include "Modulator_GSM_BCJR.hpp"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BCJR tools //////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Q>
struct negative_inf
{
static Q get() { return -std::numeric_limits<Q>::max(); }
};
template <>
struct negative_inf <short>
{
static short get() { return -(1 << (sizeof(short) * 8 -2)); }
};
template <>
struct negative_inf <signed char>
{
static signed char get() { return -63; }
};
template <typename Q, proto_max<Q> MAX>
struct BCJR_normalize
{
// Adrien comment's: I think that the normalisation is useless in floating point arithmetic
static void apply(Q *metrics, const int &i, const int &n_states)
{
// normalization
auto norm_val = negative_inf<Q>::get();
for (auto j = 0; j < n_states; j++)
norm_val = MAX(norm_val, metrics[j]);
for (auto j = 0; j < n_states; j++)
metrics[j] -= norm_val;
}
};
template <proto_max<signed char> MAX>
struct BCJR_normalize <signed char,MAX>
{
static void apply(signed char *metrics, const int &i, const int &n_states)
{
// normalization & saturation
auto norm_val = negative_inf<signed char>::get();
for (auto j = 0; j < n_states; j++)
norm_val = MAX(norm_val, metrics[j]);
for (auto j = 0; j < n_states; j++)
metrics[j] = saturate<signed char>(metrics[j] - norm_val, -63, +63);
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Q, proto_max<Q> MAX>
Modulator_GSM_BCJR<Q,MAX>
::Modulator_GSM_BCJR(const int frame_size,
const int n_states,
const int m_order,
const int n_bits_per_symb,
const int n_prev_branches,
const std::vector<int> binary_symbols,
const std::vector<int> trellis,
const std::vector<int> anti_trellis)
: frame_size (frame_size ),
n_states (n_states ),
m_order (m_order ),
n_bits_per_symb(n_bits_per_symb),
n_prev_branches(n_prev_branches),
binary_symbols(binary_symbols),
trellis (trellis ),
anti_trellis (anti_trellis ),
symb_apriori_prob(frame_size * m_order ),
gamma (frame_size * n_states * m_order ),
alpha (frame_size * n_states ),
beta (frame_size * n_states ),
proba_msg_symb (frame_size * m_order, 0),
proba_msg_bits (frame_size * 2 , 0)
{
}
template <typename Q, proto_max<Q> MAX>
Modulator_GSM_BCJR<Q,MAX>
::~Modulator_GSM_BCJR()
{
}
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::decode(const mipp::vector<Q> &Lch_N, mipp::vector<Q> &Le_N)
{
std::fill(this->symb_apriori_prob.begin(), this->symb_apriori_prob.end(), 0);
compute_alpha_beta_gamma(Lch_N);
symboles_probas ( );
bits_probas ( );
compute_ext (Le_N );
}
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::decode(const mipp::vector<Q> &Lch_N, const mipp::vector<Q> &Ldec_N, mipp::vector<Q> &Le_N)
{
LLR_to_logsymb_proba (Ldec_N );
compute_alpha_beta_gamma(Lch_N );
symboles_probas ( );
bits_probas ( );
compute_ext (Ldec_N, Le_N);
}
// retrieve log symbols probability from LLR
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::LLR_to_logsymb_proba(const mipp::vector<Q> &Ldec_N)
{
std::fill(this->symb_apriori_prob.begin(), this->symb_apriori_prob.end(), 0);
for (auto i = 0; i < (int) this->symb_apriori_prob.size() / m_order; i++)
for (auto j = 0; j < this->m_order; j++)
for (auto k = 0; k < this->n_bits_per_symb; k++)
{
const auto symbol = this->binary_symbols[k * this->m_order +j];
const auto sign = 1 - (symbol + symbol);
this->symb_apriori_prob[i * this->m_order +j] += (Q)sign * Ldec_N[i * this->n_bits_per_symb +k] * 0.5;
}
}
// compute gamma, alpha and beta, heart of the processing
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::compute_alpha_beta_gamma(const mipp::vector<Q> &Lch_N)
{
// alpha and beta initialization
std::fill(this->alpha.begin(), this->alpha.end(), negative_inf<Q>::get());
std::fill(this->beta .begin(), this->beta .end(), negative_inf<Q>::get());
this->alpha[0 ] = 0;
this->beta [(this->frame_size -1) * this->n_states] = 0;
// other way to initialize beta: does not support the fixed point mode because of the log function call
// this is usefull when we don't use the tail bits in the turbo demodulation
// auto beta_final_equi_proba = 1.0 / this->n_states;
for (auto i = 0; i < this->n_states; i++)
// this->beta[(this->frame_size -1) * n_states +i] = std::log(beta_final_equi_proba);
this->beta[(this->frame_size -1) * n_states +i] = 0;
// compute gamma
for (auto i = 0; i < this->frame_size; i++)
for (auto j = 0; j < this->n_states; j++)
for (auto k = 0; k < this->m_order; k++)
this->gamma[(k * n_states +j) * this->frame_size +i] =
Lch_N[this->trellis[(k + this->m_order) * this->n_states +j] * this->frame_size +i] + // info from the channel
this->symb_apriori_prob[i * this->m_order +k]; // info from the decoder
// compute alpha and beta
for (auto i = 1; i < this->frame_size; i++)
{
for (auto j = 0; j < this->n_states; j++)
{
const auto original_state = this->anti_trellis.data() + j * this->n_prev_branches;
const auto input_symb = this->anti_trellis.data() + (this->n_states +j) * this->n_prev_branches;
// compute the alpha nodes
for (auto k = 0; k < this->n_prev_branches; k++)
this->alpha [(i -0) * this->n_states +j] =
MAX(this->alpha[(i -0) * this->n_states +j],
this->alpha[(i -1) * this->n_states + original_state[k]] +
this->gamma[(input_symb[k] * this->n_states + original_state[k]) * this->frame_size +i -1]);
// compute the beta nodes
for (auto k = 0; k < this->m_order; k++)
this->beta [(this->frame_size - (i +1)) * this->n_states +j] =
MAX(this->beta [(this->frame_size - (i +1)) * this->n_states +j],
this->beta [(this->frame_size - (i +0)) * this->n_states + this->trellis[k * this->n_states +j]] +
this->gamma[(k * this->n_states +j) * this->frame_size + this->frame_size -i]);
}
// normalize alpha and beta vectors (not impact on the decoding performances)
BCJR_normalize<Q,MAX>::apply(&this->alpha[ (i +0) * this->n_states], i, this->n_states);
BCJR_normalize<Q,MAX>::apply(&this->beta [(this->frame_size - (i +1)) * this->n_states], i, this->n_states);
}
}
// from alpha, beta, and gamma computes new symbol probability
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::symboles_probas()
{
// initialize proba_msg_symb
for (auto i = 0; i < this->frame_size; i++)
for (auto j = 0; j < this->m_order; j++)
proba_msg_symb[i * this->m_order +j] = negative_inf<Q>::get();
for (auto i = 0; i < this->frame_size; i++)
for (auto j = 0; j < this->m_order; j++)
for (auto k = 0; k < this->n_states; k++)
proba_msg_symb [ i * this->m_order +j] =
MAX(proba_msg_symb[ i * this->m_order +j],
this->alpha [ i * this->n_states +k] +
this->beta [ i * this->n_states + this->trellis[j * this->n_states +k]] +
this->gamma [(j * this->n_states +k) * this->frame_size +i]);
}
// from symbol probabilities, computes bit probabilities
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::bits_probas()
{
// initialize proba_msg_bits
std::fill(proba_msg_bits.begin(), proba_msg_bits.end(), negative_inf<Q>::get());
for (auto i = 0; i < this->frame_size; i++)
{
const auto ii = i * this->n_bits_per_symb;
for (auto j = 0; j < n_bits_per_symb; j++)
for (auto k = 0; k < this->m_order; k++)
{
const auto symbol = binary_symbols[j * this->m_order +k];
// bit 0
if (symbol == 0)
proba_msg_bits[(ii +j) * 2 +0] = MAX(proba_msg_bits[(ii +j) * 2 +0],
proba_msg_symb[i * this->m_order +k]);
// bit 1
else if (symbol == 1)
proba_msg_bits[(ii +j) * 2 +1] = MAX(proba_msg_bits[(ii +j) * 2 +1],
proba_msg_symb[i * this->m_order +k]);
}
}
}
// extrinsic information processing from bit probabilities
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::compute_ext(mipp::vector<Q> &Le_N)
{
const auto loop_size = (int)Le_N.size() * 2;
for (auto i = 0; i < loop_size; i += 2)
// processing aposteriori and substracting a priori to directly obtain extrinsic
Le_N[i / 2] = proba_msg_bits[i] - proba_msg_bits[i +1];
}
// extrinsic information processing from bit probabilities and CPM a priori LLR
template <typename Q, proto_max<Q> MAX>
void Modulator_GSM_BCJR<Q,MAX>
::compute_ext(const mipp::vector<Q> &Ldec_N,
mipp::vector<Q> &Le_N)
{
const auto loop_size = (int)Le_N.size() * 2;
for (auto i = 0; i < loop_size; i += 2)
// processing aposteriori and substracting a priori to directly obtain extrinsic
Le_N[i / 2] = proba_msg_bits[i] - (proba_msg_bits[i +1] + Ldec_N[i / 2]);
}<|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.
#include <list>
#include <vector>
#include <glog/logging.h>
#include <stout/hashmap.hpp>
#include <stout/json.hpp>
#include <stout/os.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/subprocess.hpp>
#include <mesos/docker/spec.hpp>
#include "common/status_utils.hpp"
#include "slave/containerizer/mesos/provisioner/docker/metadata_manager.hpp"
#include "slave/containerizer/mesos/provisioner/docker/store.hpp"
#include "slave/containerizer/mesos/provisioner/docker/paths.hpp"
#include "slave/containerizer/mesos/provisioner/docker/puller.hpp"
using namespace process;
namespace spec = docker::spec;
using std::list;
using std::pair;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace slave {
namespace docker {
class StoreProcess : public Process<StoreProcess>
{
public:
StoreProcess(
const Flags& _flags,
const Owned<MetadataManager>& _metadataManager,
const Owned<Puller>& _puller)
: flags(_flags),
metadataManager(_metadataManager),
puller(_puller) {}
~StoreProcess() {}
Future<Nothing> recover();
Future<ImageInfo> get(const mesos::Image& image);
private:
Future<Image> _get(
const spec::ImageReference& reference,
const Option<Image>& image);
Future<ImageInfo> __get(const Image& image);
Future<vector<string>> moveLayers(
const list<pair<string, string>>& layerPaths);
Future<Image> storeImage(
const spec::ImageReference& reference,
const vector<string>& layerIds);
Future<Nothing> moveLayer(
const pair<string, string>& layerPath);
const Flags flags;
Owned<MetadataManager> metadataManager;
Owned<Puller> puller;
hashmap<string, Owned<Promise<Image>>> pulling;
};
Try<Owned<slave::Store>> Store::create(const Flags& flags)
{
Try<Owned<Puller>> puller = Puller::create(flags);
if (puller.isError()) {
return Error("Failed to create Docker puller: " + puller.error());
}
Try<Owned<slave::Store>> store = Store::create(flags, puller.get());
if (store.isError()) {
return Error("Failed to create Docker store: " + store.error());
}
return store.get();
}
Try<Owned<slave::Store>> Store::create(
const Flags& flags,
const Owned<Puller>& puller)
{
Try<Nothing> mkdir = os::mkdir(flags.docker_store_dir);
if (mkdir.isError()) {
return Error("Failed to create Docker store directory: " +
mkdir.error());
}
mkdir = os::mkdir(paths::getStagingDir(flags.docker_store_dir));
if (mkdir.isError()) {
return Error("Failed to create Docker store staging directory: " +
mkdir.error());
}
Try<Owned<MetadataManager>> metadataManager = MetadataManager::create(flags);
if (metadataManager.isError()) {
return Error(metadataManager.error());
}
Owned<StoreProcess> process(
new StoreProcess(flags, metadataManager.get(), puller));
return Owned<slave::Store>(new Store(process));
}
Store::Store(const Owned<StoreProcess>& _process) : process(_process)
{
spawn(CHECK_NOTNULL(process.get()));
}
Store::~Store()
{
terminate(process.get());
wait(process.get());
}
Future<Nothing> Store::recover()
{
return dispatch(process.get(), &StoreProcess::recover);
}
Future<ImageInfo> Store::get(const mesos::Image& image)
{
return dispatch(process.get(), &StoreProcess::get, image);
}
Future<ImageInfo> StoreProcess::get(const mesos::Image& image)
{
if (image.type() != mesos::Image::DOCKER) {
return Failure("Docker provisioner store only supports Docker images");
}
Try<spec::ImageReference> reference =
spec::parseImageReference(image.docker().name());
if (reference.isError()) {
return Failure("Failed to parse docker image '" + image.docker().name() +
"': " + reference.error());
}
return metadataManager->get(reference.get())
.then(defer(self(), &Self::_get, reference.get(), lambda::_1))
.then(defer(self(), &Self::__get, lambda::_1));
}
Future<Image> StoreProcess::_get(
const spec::ImageReference& reference,
const Option<Image>& image)
{
if (image.isSome()) {
return image.get();
}
Try<string> staging =
os::mkdtemp(paths::getStagingTempDir(flags.docker_store_dir));
if (staging.isError()) {
return Failure("Failed to create a staging directory");
}
const string imageReference = stringify(reference);
if (!pulling.contains(imageReference)) {
Owned<Promise<Image>> promise(new Promise<Image>());
Future<Image> future = puller->pull(reference, Path(staging.get()))
.then(defer(self(), &Self::moveLayers, lambda::_1))
.then(defer(self(), &Self::storeImage, reference, lambda::_1))
.onAny(defer(self(), [this, imageReference](const Future<Image>&) {
pulling.erase(imageReference);
}))
.onAny([staging, imageReference]() {
Try<Nothing> rmdir = os::rmdir(staging.get());
if (rmdir.isError()) {
LOG(WARNING) << "Failed to remove staging directory: "
<< rmdir.error();
}
});
promise->associate(future);
pulling[imageReference] = promise;
return promise->future();
}
return pulling[imageReference]->future();
}
Future<ImageInfo> StoreProcess::__get(const Image& image)
{
CHECK_LT(0, image.layer_ids_size());
vector<string> layerDirectories;
foreach (const string& layer, image.layer_ids()) {
layerDirectories.push_back(
paths::getImageLayerRootfsPath(
flags.docker_store_dir, layer));
}
// Read the manifest from the last layer because all runtime config
// are merged at the leaf already.
Try<string> manifest = os::read(
paths::getImageLayerManifestPath(
flags.docker_store_dir,
image.layer_ids(image.layer_ids_size() - 1)));
if (manifest.isError()) {
return Failure("Failed to read manifest: " + manifest.error());
}
Try<::docker::spec::v1::ImageManifest> v1 =
::docker::spec::v1::parse(manifest.get());
if (v1.isError()) {
return Failure("Failed to parse docker v1 manifest: " + v1.error());
}
return ImageInfo{layerDirectories, v1.get()};
}
Future<Nothing> StoreProcess::recover()
{
return metadataManager->recover();
}
Future<vector<string>> StoreProcess::moveLayers(
const list<pair<string, string>>& layerPaths)
{
list<Future<Nothing>> futures;
foreach (const auto& layerPath, layerPaths) {
futures.push_back(moveLayer(layerPath));
}
return collect(futures)
.then([layerPaths]() {
vector<string> layerIds;
foreach (const auto& layerPath, layerPaths) {
layerIds.push_back(layerPath.first);
}
return layerIds;
});
}
Future<Image> StoreProcess::storeImage(
const spec::ImageReference& reference,
const vector<string>& layerIds)
{
return metadataManager->put(reference, layerIds);
}
Future<Nothing> StoreProcess::moveLayer(
const pair<string, string>& layerPath)
{
if (!os::exists(layerPath.second)) {
return Failure("Unable to find layer '" + layerPath.first + "' in '" +
layerPath.second + "'");
}
const string imageLayerPath =
paths::getImageLayerPath(flags.docker_store_dir, layerPath.first);
// If image layer path exists, we should remove it and make an empty
// directory, because os::rename can only have empty or non-existed
// directory as destination.
if (os::exists(imageLayerPath)) {
Try<Nothing> rmdir = os::rmdir(imageLayerPath);
if (rmdir.isError()) {
return Failure("Failed to remove existing layer: " + rmdir.error());
}
}
Try<Nothing> mkdir = os::mkdir(imageLayerPath);
if (mkdir.isError()) {
return Failure("Failed to create layer path in store for id '" +
layerPath.first + "': " + mkdir.error());
}
Try<Nothing> status = os::rename(
layerPath.second,
imageLayerPath);
if (status.isError()) {
return Failure("Failed to move layer '" + layerPath.first +
"' to store directory: " + status.error());
}
return Nothing();
}
} // namespace docker {
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Added a NOTE in docker store about caching.<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.
#include <list>
#include <vector>
#include <glog/logging.h>
#include <stout/hashmap.hpp>
#include <stout/json.hpp>
#include <stout/os.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/subprocess.hpp>
#include <mesos/docker/spec.hpp>
#include "common/status_utils.hpp"
#include "slave/containerizer/mesos/provisioner/docker/metadata_manager.hpp"
#include "slave/containerizer/mesos/provisioner/docker/store.hpp"
#include "slave/containerizer/mesos/provisioner/docker/paths.hpp"
#include "slave/containerizer/mesos/provisioner/docker/puller.hpp"
using namespace process;
namespace spec = docker::spec;
using std::list;
using std::pair;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace slave {
namespace docker {
class StoreProcess : public Process<StoreProcess>
{
public:
StoreProcess(
const Flags& _flags,
const Owned<MetadataManager>& _metadataManager,
const Owned<Puller>& _puller)
: flags(_flags),
metadataManager(_metadataManager),
puller(_puller) {}
~StoreProcess() {}
Future<Nothing> recover();
Future<ImageInfo> get(const mesos::Image& image);
private:
Future<Image> _get(
const spec::ImageReference& reference,
const Option<Image>& image);
Future<ImageInfo> __get(const Image& image);
Future<vector<string>> moveLayers(
const list<pair<string, string>>& layerPaths);
Future<Image> storeImage(
const spec::ImageReference& reference,
const vector<string>& layerIds);
Future<Nothing> moveLayer(
const pair<string, string>& layerPath);
const Flags flags;
Owned<MetadataManager> metadataManager;
Owned<Puller> puller;
hashmap<string, Owned<Promise<Image>>> pulling;
};
Try<Owned<slave::Store>> Store::create(const Flags& flags)
{
Try<Owned<Puller>> puller = Puller::create(flags);
if (puller.isError()) {
return Error("Failed to create Docker puller: " + puller.error());
}
Try<Owned<slave::Store>> store = Store::create(flags, puller.get());
if (store.isError()) {
return Error("Failed to create Docker store: " + store.error());
}
return store.get();
}
Try<Owned<slave::Store>> Store::create(
const Flags& flags,
const Owned<Puller>& puller)
{
Try<Nothing> mkdir = os::mkdir(flags.docker_store_dir);
if (mkdir.isError()) {
return Error("Failed to create Docker store directory: " +
mkdir.error());
}
mkdir = os::mkdir(paths::getStagingDir(flags.docker_store_dir));
if (mkdir.isError()) {
return Error("Failed to create Docker store staging directory: " +
mkdir.error());
}
Try<Owned<MetadataManager>> metadataManager = MetadataManager::create(flags);
if (metadataManager.isError()) {
return Error(metadataManager.error());
}
Owned<StoreProcess> process(
new StoreProcess(flags, metadataManager.get(), puller));
return Owned<slave::Store>(new Store(process));
}
Store::Store(const Owned<StoreProcess>& _process) : process(_process)
{
spawn(CHECK_NOTNULL(process.get()));
}
Store::~Store()
{
terminate(process.get());
wait(process.get());
}
Future<Nothing> Store::recover()
{
return dispatch(process.get(), &StoreProcess::recover);
}
Future<ImageInfo> Store::get(const mesos::Image& image)
{
return dispatch(process.get(), &StoreProcess::get, image);
}
Future<ImageInfo> StoreProcess::get(const mesos::Image& image)
{
if (image.type() != mesos::Image::DOCKER) {
return Failure("Docker provisioner store only supports Docker images");
}
Try<spec::ImageReference> reference =
spec::parseImageReference(image.docker().name());
if (reference.isError()) {
return Failure("Failed to parse docker image '" + image.docker().name() +
"': " + reference.error());
}
return metadataManager->get(reference.get())
.then(defer(self(), &Self::_get, reference.get(), lambda::_1))
.then(defer(self(), &Self::__get, lambda::_1));
}
Future<Image> StoreProcess::_get(
const spec::ImageReference& reference,
const Option<Image>& image)
{
// NOTE: Here, we assume that image layers are not removed without
// first removing the metadata in the metadata manager first.
// Otherwise, the image we return here might miss some layers. At
// the time we introduce cache eviction, we also want to avoid the
// situation where a layer was returned to the provisioner but is
// later evicted.
if (image.isSome()) {
return image.get();
}
Try<string> staging =
os::mkdtemp(paths::getStagingTempDir(flags.docker_store_dir));
if (staging.isError()) {
return Failure("Failed to create a staging directory");
}
const string imageReference = stringify(reference);
if (!pulling.contains(imageReference)) {
Owned<Promise<Image>> promise(new Promise<Image>());
Future<Image> future = puller->pull(reference, Path(staging.get()))
.then(defer(self(), &Self::moveLayers, lambda::_1))
.then(defer(self(), &Self::storeImage, reference, lambda::_1))
.onAny(defer(self(), [this, imageReference](const Future<Image>&) {
pulling.erase(imageReference);
}))
.onAny([staging, imageReference]() {
Try<Nothing> rmdir = os::rmdir(staging.get());
if (rmdir.isError()) {
LOG(WARNING) << "Failed to remove staging directory: "
<< rmdir.error();
}
});
promise->associate(future);
pulling[imageReference] = promise;
return promise->future();
}
return pulling[imageReference]->future();
}
Future<ImageInfo> StoreProcess::__get(const Image& image)
{
CHECK_LT(0, image.layer_ids_size());
vector<string> layerDirectories;
foreach (const string& layer, image.layer_ids()) {
layerDirectories.push_back(
paths::getImageLayerRootfsPath(
flags.docker_store_dir, layer));
}
// Read the manifest from the last layer because all runtime config
// are merged at the leaf already.
Try<string> manifest = os::read(
paths::getImageLayerManifestPath(
flags.docker_store_dir,
image.layer_ids(image.layer_ids_size() - 1)));
if (manifest.isError()) {
return Failure("Failed to read manifest: " + manifest.error());
}
Try<::docker::spec::v1::ImageManifest> v1 =
::docker::spec::v1::parse(manifest.get());
if (v1.isError()) {
return Failure("Failed to parse docker v1 manifest: " + v1.error());
}
return ImageInfo{layerDirectories, v1.get()};
}
Future<Nothing> StoreProcess::recover()
{
return metadataManager->recover();
}
Future<vector<string>> StoreProcess::moveLayers(
const list<pair<string, string>>& layerPaths)
{
list<Future<Nothing>> futures;
foreach (const auto& layerPath, layerPaths) {
futures.push_back(moveLayer(layerPath));
}
return collect(futures)
.then([layerPaths]() {
vector<string> layerIds;
foreach (const auto& layerPath, layerPaths) {
layerIds.push_back(layerPath.first);
}
return layerIds;
});
}
Future<Image> StoreProcess::storeImage(
const spec::ImageReference& reference,
const vector<string>& layerIds)
{
return metadataManager->put(reference, layerIds);
}
Future<Nothing> StoreProcess::moveLayer(
const pair<string, string>& layerPath)
{
if (!os::exists(layerPath.second)) {
return Failure("Unable to find layer '" + layerPath.first + "' in '" +
layerPath.second + "'");
}
const string imageLayerPath =
paths::getImageLayerPath(flags.docker_store_dir, layerPath.first);
// If image layer path exists, we should remove it and make an empty
// directory, because os::rename can only have empty or non-existed
// directory as destination.
if (os::exists(imageLayerPath)) {
Try<Nothing> rmdir = os::rmdir(imageLayerPath);
if (rmdir.isError()) {
return Failure("Failed to remove existing layer: " + rmdir.error());
}
}
Try<Nothing> mkdir = os::mkdir(imageLayerPath);
if (mkdir.isError()) {
return Failure("Failed to create layer path in store for id '" +
layerPath.first + "': " + mkdir.error());
}
Try<Nothing> status = os::rename(
layerPath.second,
imageLayerPath);
if (status.isError()) {
return Failure("Failed to move layer '" + layerPath.first +
"' to store directory: " + status.error());
}
return Nothing();
}
} // namespace docker {
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclarationName.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/Lookup.h"
using namespace clang;
namespace cling {
namespace utils {
Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) {
ASTContext& Ctx = S->getASTContext();
if (!Ty->isPointerType())
Ty = Ctx.getPointerType(Ty);
TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty);
const llvm::APInt Addr(8 * sizeof(void *), Ptr);
Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy,
SourceLocation());
Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(),
Result).take();
assert(Result && "Cannot create CStyleCastPtrExpr");
return Result;
}
QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx,
QualType QT,
const llvm::SmallSet<const Type*, 4>& TypesToSkip){
// If there are no constains - use the standard desugaring.
if (!TypesToSkip.size())
return QT.getDesugaredType(Ctx);
while(isa<TypedefType>(QT.getTypePtr())) {
if (!TypesToSkip.count(QT.getTypePtr()))
QT = QT.getSingleStepDesugaredType(Ctx);
else
return QT;
}
// In case of template specializations iterate over the arguments and
// desugar them as well.
if(const TemplateSpecializationType* TST
= dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) {
bool mightHaveChanged = false;
llvm::SmallVector<TemplateArgument, 4> desArgs;
for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
I != E; ++I) {
QualType SubTy = I->getAsType();
if (SubTy.isNull())
continue;
// Check if the type needs more desugaring and recurse.
if (isa<TypedefType>(SubTy) || isa<TemplateSpecializationType>(SubTy)) {
mightHaveChanged = true;
desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx,
SubTy,
TypesToSkip)));
else
desArgs.push_back(*I);
}
// If desugaring happened allocate new type in the AST.
if (mightHaveChanged) {
QualType Result
= Ctx.getTemplateSpecializationType(TST->getTemplateName(),
desArgs.data(),
desArgs.size(),
TST->getCanonicalTypeInternal());
return Result;
}
}
return QT;
}
NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name,
DeclContext* Within) {
DeclarationName DName = &S->Context.Idents.get(Name);
LookupResult R(*S, DName, SourceLocation(),
Sema::LookupNestedNameSpecifierName);
if (!Within)
S->LookupName(R, S->TUScope);
else
S->LookupQualifiedName(R, Within);
if (R.empty())
return 0;
R.resolveKind();
return dyn_cast<NamespaceDecl>(R.getFoundDecl());
}
NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) {
DeclarationName DName = &S->Context.Idents.get(Name);
LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName,
Sema::ForRedeclaration);
if (!Within)
S->LookupName(R, S->TUScope);
else
S->LookupQualifiedName(R, Within);
if (R.empty())
return 0;
R.resolveKind();
return R.getFoundDecl();
}
} // end namespace utils
} // end namespace cling
<commit_msg>Fix typo<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclarationName.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/Lookup.h"
using namespace clang;
namespace cling {
namespace utils {
Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) {
ASTContext& Ctx = S->getASTContext();
if (!Ty->isPointerType())
Ty = Ctx.getPointerType(Ty);
TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty);
const llvm::APInt Addr(8 * sizeof(void *), Ptr);
Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy,
SourceLocation());
Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(),
Result).take();
assert(Result && "Cannot create CStyleCastPtrExpr");
return Result;
}
QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx,
QualType QT,
const llvm::SmallSet<const Type*, 4>& TypesToSkip){
// If there are no constains - use the standard desugaring.
if (!TypesToSkip.size())
return QT.getDesugaredType(Ctx);
while(isa<TypedefType>(QT.getTypePtr())) {
if (!TypesToSkip.count(QT.getTypePtr()))
QT = QT.getSingleStepDesugaredType(Ctx);
else
return QT;
}
// In case of template specializations iterate over the arguments and
// desugar them as well.
if(const TemplateSpecializationType* TST
= dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) {
bool mightHaveChanged = false;
llvm::SmallVector<TemplateArgument, 4> desArgs;
for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
I != E; ++I) {
QualType SubTy = I->getAsType();
if (SubTy.isNull())
continue;
// Check if the type needs more desugaring and recurse.
if (isa<TypedefType>(SubTy) || isa<TemplateSpecializationType>(SubTy)) {
mightHaveChanged = true;
desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx,
SubTy,
TypesToSkip)));
} else
desArgs.push_back(*I);
}
// If desugaring happened allocate new type in the AST.
if (mightHaveChanged) {
QualType Result
= Ctx.getTemplateSpecializationType(TST->getTemplateName(),
desArgs.data(),
desArgs.size(),
TST->getCanonicalTypeInternal());
return Result;
}
}
return QT;
}
NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name,
DeclContext* Within) {
DeclarationName DName = &S->Context.Idents.get(Name);
LookupResult R(*S, DName, SourceLocation(),
Sema::LookupNestedNameSpecifierName);
if (!Within)
S->LookupName(R, S->TUScope);
else
S->LookupQualifiedName(R, Within);
if (R.empty())
return 0;
R.resolveKind();
return dyn_cast<NamespaceDecl>(R.getFoundDecl());
}
NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) {
DeclarationName DName = &S->Context.Idents.get(Name);
LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName,
Sema::ForRedeclaration);
if (!Within)
S->LookupName(R, S->TUScope);
else
S->LookupQualifiedName(R, Within);
if (R.empty())
return 0;
R.resolveKind();
return R.getFoundDecl();
}
} // end namespace utils
} // end namespace cling
<|endoftext|> |
<commit_before>/**
* @version GrPPI v0.3
* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.
* @license GNU/GPL, see LICENSE.txt
* 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 have received a copy of the GNU General Public License in LICENSE.txt
* also available in <http://www.gnu.org/licenses/gpl.html>.
*
* See COPYRIGHT.txt for copyright notices and details.
*/
#include <atomic>
#include <utility>
#include <experimental/optional>
#include <gtest/gtest.h>
#include "farm.h"
#include "pipeline.h"
#include "dyn/dynamic_execution.h"
#include "supported_executions.h"
using namespace std;
using namespace grppi;
template <typename T>
using optional = std::experimental::optional<T>;
template <typename T>
class farm_pipeline_test : public ::testing::Test {
public:
T execution_;
dynamic_execution dyn_execution_{execution_};
// Variables
std::atomic<int> output;
// Vectors
vector<int> v{};
vector<int> v2{};
vector<int> v3{};
vector<int> w{};
// entry counter
int idx_in = 0;
int idx_out = 0;
// Invocation counter
std::atomic<int> invocations_in{0};
std::atomic<int> invocations_op{0};
std::atomic<int> invocations_op2{0};
std::atomic<int> invocations_sk{0};
void setup_empty() {}
template <typename E>
void run_empty(const E & e) {
grppi::pipeline(e,
[this]() -> optional<int>{
invocations_in++;
return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x;
},
[this](int x) {
invocations_op2++;
return x;
}
)
),
[](int x) {}
);
}
void check_empty() {
EXPECT_EQ(1, invocations_in); // Functor in was invoked once
EXPECT_EQ(0, invocations_op); // Functor op was not invoked
EXPECT_EQ(0, invocations_op2); // Functor op2 was not invoked
}
void setup_empty_sink() {}
template <typename E>
void run_empty_sink(const E & e) {
grppi::pipeline (e,
[this]() -> optional<int>{
invocations_in++;
return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x;
},
[this](int x) {
invocations_op2++;
return x;
}
)
),
[this](int x) {
this->invocations_sk++;
}
);
}
void check_empty_sink() {
EXPECT_EQ(1, invocations_in);
EXPECT_EQ(0, invocations_op);
EXPECT_EQ(0, invocations_op2);
EXPECT_EQ(0, invocations_sk);
}
void setup_empty_ary() {}
template <typename E>
void run_empty_ary(const E & e) {
grppi::pipeline(e,
[this]() -> optional<tuple<int,int,int>> {
invocations_in++;
return {};
},
grppi::farm(2,
grppi::pipeline(
[this](tuple<int,int,int> x) {
invocations_op++;
return x;
},
[this](tuple<int,int,int> x) {
invocations_op2++;
return x;
})
),
[&](tuple<int,int,int> x){
invocations_sk++;
}
);
}
void check_empty_ary() {
EXPECT_EQ(1, invocations_in);
EXPECT_EQ(0, invocations_op);
EXPECT_EQ(0, invocations_op2);
EXPECT_EQ(0, invocations_sk);
}
void setup_single_sink() {
v = vector<int>{42};
w = vector<int>{99};
}
template <typename E>
void run_single_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<int> {
invocations_in++;
if (idx_in < v.size() ) {
idx_in++;
return v[idx_in-1];
}
else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x*2;
},
[this](int x) {
invocations_op2++;
return x*2;
}
)
),
[this](int x) {
invocations_sk++;
w[idx_out] = x;
idx_out++;
}
);
}
void check_single_sink() {
EXPECT_EQ(2, invocations_in); // Functor in was invoked once
EXPECT_EQ(1, this->invocations_op); // one invocation of function op
EXPECT_EQ(1, this->invocations_op2); // one invocation of function op
EXPECT_EQ(1, this->invocations_sk); // one invocation of function sk
EXPECT_EQ(168, this->w[0]);
}
void setup_single_ary_sink() {
v = vector<int>{11};
v2 = vector<int>{22};
v3 = vector<int>{33};
w = vector<int>{99};
}
template <typename E>
void run_single_ary_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<tuple<int,int,int>> {
invocations_in++;
if (idx_in < v.size()) {
idx_in++;
return make_tuple(v[idx_in-1], v2[idx_in-1], v3[idx_in-1]);
}
else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](tuple<int,int,int> x) {
invocations_op++;
return get<0>(x) + get<1>(x) + get<2>(x);;
},
[this](int x){
invocations_op2++;
return x*2;
}
)
),
[this](int x) {
invocations_sk++;
w[idx_out] = x;
idx_out++;
});
}
void check_single_ary_sink() {
EXPECT_EQ(2, invocations_in); // Functor in was invoked twice
EXPECT_EQ(1, this->invocations_op); // one invocation of function op
EXPECT_EQ(1, this->invocations_op2); // one invocation of function op
EXPECT_EQ(1, this->invocations_sk); // one invocation of function sk
EXPECT_EQ(132, this->w[0]);
}
void setup_multiple_sink() {
v = vector<int>{1,2,3,4,5};
output = 0;
}
template <typename E>
void run_multiple_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<int> {
invocations_in++;
if (idx_in < v.size()) {
idx_in++;
return v[idx_in-1];
} else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x * 2;
},
[this](int x) {
invocations_op2++;
return x * 2;
}
)
),
[this](int x) {
invocations_sk++;
output +=x;
}
);
}
void check_multiple_sink() {
EXPECT_EQ(6, this->invocations_in); // six invocations of function in
EXPECT_EQ(5, this->invocations_op); // five invocations of function op
EXPECT_EQ(5, this->invocations_op2); // five invocations of function sk
EXPECT_EQ(5, this->invocations_sk); // five invocations of function sk
EXPECT_EQ(60, this->output);
}
void setup_multiple_ary_sink() {
v = vector<int>{1,2,3,4,5};
v2 = vector<int>{2,4,6,8,10};
v3 = vector<int>{10,10,10,10,10};
output = 0;
}
template <typename E>
void run_multiple_ary_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<tuple<int,int,int>> {
invocations_in++;
if (idx_in < v.size()) {
idx_in++;
return make_tuple(v[idx_in-1], v2[idx_in-1], v3[idx_in-1]);
}
else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](tuple<int,int,int> x) {
invocations_op++;
return get<0>(x) + get<1>(x) + get<2>(x);
},
[this](int x){
invocations_op2++;
return x*2;
}
)
),
[this](int x) {
invocations_sk++;
output += x;
});
}
void check_multiple_ary_sink() {
EXPECT_EQ(6, this->invocations_in); // six invocations of function in
EXPECT_EQ(5, this->invocations_op); // five invocations of function op
EXPECT_EQ(5, this->invocations_op2); // five invocations of function op
EXPECT_EQ(5, this->invocations_sk); // five invocations of function sk
EXPECT_EQ(190, this->output);
}
};
// Test for execution policies defined in supported_executions.h
TYPED_TEST_CASE(farm_pipeline_test, executions);
TYPED_TEST(farm_pipeline_test, static_empty)
{
this->setup_empty();
this->run_empty(this->execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, dyn_empty)
{
this->setup_empty();
this->run_empty(this->dyn_execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, static_empty_sink)
{
this->setup_empty_sink();
this->run_empty_sink(this->execution_);
this->check_empty_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_empty_sink)
{
this->setup_empty_sink();
this->run_empty_sink(this->dyn_execution_);
this->check_empty_sink();
}
TYPED_TEST(farm_pipeline_test, static_empty_ary)
{
this->setup_empty();
this->run_empty_ary(this->execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, dyn_empty_ary)
{
this->setup_empty();
this->run_empty_ary(this->dyn_execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, static_single_sink)
{
this->setup_single_sink();
this->run_single_sink(this->execution_);
this->check_single_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_single_sink)
{
this->setup_single_sink();
this->run_single_sink(this->dyn_execution_);
this->check_single_sink();
}
TYPED_TEST(farm_pipeline_test, static_single_ary_sink)
{
this->setup_single_ary_sink();
this->run_single_ary_sink(this->dyn_execution_);
this->check_single_ary_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_single_ary_sink)
{
this->setup_single_ary_sink();
this->run_single_ary_sink(this->dyn_execution_);
this->check_single_ary_sink();
}
TYPED_TEST(farm_pipeline_test, static_multiple_sink)
{
this->setup_multiple_sink();
this->run_multiple_sink(this->execution_);
this->check_multiple_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_multiple_sink)
{
this->setup_multiple_sink();
this->run_multiple_sink(this->dyn_execution_);
this->check_multiple_sink();
}
TYPED_TEST(farm_pipeline_test, static_multiple_ary_sink)
{
this->setup_multiple_ary_sink();
this->run_multiple_ary_sink(this->execution_);
this->check_multiple_ary_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_multiple_ary_sink)
{
this->setup_multiple_ary_sink();
this->run_multiple_ary_sink(this->dyn_execution_);
this->check_multiple_ary_sink();
}
<commit_msg>Unit test farm+pipeline with no ff execution until it is implemented<commit_after>/**
* @version GrPPI v0.3
* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.
* @license GNU/GPL, see LICENSE.txt
* 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 have received a copy of the GNU General Public License in LICENSE.txt
* also available in <http://www.gnu.org/licenses/gpl.html>.
*
* See COPYRIGHT.txt for copyright notices and details.
*/
#include <atomic>
#include <utility>
#include <experimental/optional>
#include <gtest/gtest.h>
#include "farm.h"
#include "pipeline.h"
#include "dyn/dynamic_execution.h"
#include "supported_executions.h"
using namespace std;
using namespace grppi;
template <typename T>
using optional = std::experimental::optional<T>;
template <typename T>
class farm_pipeline_test : public ::testing::Test {
public:
T execution_;
dynamic_execution dyn_execution_{execution_};
// Variables
std::atomic<int> output;
// Vectors
vector<int> v{};
vector<int> v2{};
vector<int> v3{};
vector<int> w{};
// entry counter
int idx_in = 0;
int idx_out = 0;
// Invocation counter
std::atomic<int> invocations_in{0};
std::atomic<int> invocations_op{0};
std::atomic<int> invocations_op2{0};
std::atomic<int> invocations_sk{0};
void setup_empty() {}
template <typename E>
void run_empty(const E & e) {
grppi::pipeline(e,
[this]() -> optional<int>{
invocations_in++;
return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x;
},
[this](int x) {
invocations_op2++;
return x;
}
)
),
[](int x) {}
);
}
void check_empty() {
EXPECT_EQ(1, invocations_in); // Functor in was invoked once
EXPECT_EQ(0, invocations_op); // Functor op was not invoked
EXPECT_EQ(0, invocations_op2); // Functor op2 was not invoked
}
void setup_empty_sink() {}
template <typename E>
void run_empty_sink(const E & e) {
grppi::pipeline (e,
[this]() -> optional<int>{
invocations_in++;
return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x;
},
[this](int x) {
invocations_op2++;
return x;
}
)
),
[this](int x) {
this->invocations_sk++;
}
);
}
void check_empty_sink() {
EXPECT_EQ(1, invocations_in);
EXPECT_EQ(0, invocations_op);
EXPECT_EQ(0, invocations_op2);
EXPECT_EQ(0, invocations_sk);
}
void setup_empty_ary() {}
template <typename E>
void run_empty_ary(const E & e) {
grppi::pipeline(e,
[this]() -> optional<tuple<int,int,int>> {
invocations_in++;
return {};
},
grppi::farm(2,
grppi::pipeline(
[this](tuple<int,int,int> x) {
invocations_op++;
return x;
},
[this](tuple<int,int,int> x) {
invocations_op2++;
return x;
})
),
[&](tuple<int,int,int> x){
invocations_sk++;
}
);
}
void check_empty_ary() {
EXPECT_EQ(1, invocations_in);
EXPECT_EQ(0, invocations_op);
EXPECT_EQ(0, invocations_op2);
EXPECT_EQ(0, invocations_sk);
}
void setup_single_sink() {
v = vector<int>{42};
w = vector<int>{99};
}
template <typename E>
void run_single_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<int> {
invocations_in++;
if (idx_in < v.size() ) {
idx_in++;
return v[idx_in-1];
}
else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x*2;
},
[this](int x) {
invocations_op2++;
return x*2;
}
)
),
[this](int x) {
invocations_sk++;
w[idx_out] = x;
idx_out++;
}
);
}
void check_single_sink() {
EXPECT_EQ(2, invocations_in); // Functor in was invoked once
EXPECT_EQ(1, this->invocations_op); // one invocation of function op
EXPECT_EQ(1, this->invocations_op2); // one invocation of function op
EXPECT_EQ(1, this->invocations_sk); // one invocation of function sk
EXPECT_EQ(168, this->w[0]);
}
void setup_single_ary_sink() {
v = vector<int>{11};
v2 = vector<int>{22};
v3 = vector<int>{33};
w = vector<int>{99};
}
template <typename E>
void run_single_ary_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<tuple<int,int,int>> {
invocations_in++;
if (idx_in < v.size()) {
idx_in++;
return make_tuple(v[idx_in-1], v2[idx_in-1], v3[idx_in-1]);
}
else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](tuple<int,int,int> x) {
invocations_op++;
return get<0>(x) + get<1>(x) + get<2>(x);;
},
[this](int x){
invocations_op2++;
return x*2;
}
)
),
[this](int x) {
invocations_sk++;
w[idx_out] = x;
idx_out++;
});
}
void check_single_ary_sink() {
EXPECT_EQ(2, invocations_in); // Functor in was invoked twice
EXPECT_EQ(1, this->invocations_op); // one invocation of function op
EXPECT_EQ(1, this->invocations_op2); // one invocation of function op
EXPECT_EQ(1, this->invocations_sk); // one invocation of function sk
EXPECT_EQ(132, this->w[0]);
}
void setup_multiple_sink() {
v = vector<int>{1,2,3,4,5};
output = 0;
}
template <typename E>
void run_multiple_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<int> {
invocations_in++;
if (idx_in < v.size()) {
idx_in++;
return v[idx_in-1];
} else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](int x) {
invocations_op++;
return x * 2;
},
[this](int x) {
invocations_op2++;
return x * 2;
}
)
),
[this](int x) {
invocations_sk++;
output +=x;
}
);
}
void check_multiple_sink() {
EXPECT_EQ(6, this->invocations_in); // six invocations of function in
EXPECT_EQ(5, this->invocations_op); // five invocations of function op
EXPECT_EQ(5, this->invocations_op2); // five invocations of function sk
EXPECT_EQ(5, this->invocations_sk); // five invocations of function sk
EXPECT_EQ(60, this->output);
}
void setup_multiple_ary_sink() {
v = vector<int>{1,2,3,4,5};
v2 = vector<int>{2,4,6,8,10};
v3 = vector<int>{10,10,10,10,10};
output = 0;
}
template <typename E>
void run_multiple_ary_sink(const E & e) {
grppi::pipeline(e,
[this]() -> optional<tuple<int,int,int>> {
invocations_in++;
if (idx_in < v.size()) {
idx_in++;
return make_tuple(v[idx_in-1], v2[idx_in-1], v3[idx_in-1]);
}
else return {};
},
grppi::farm(2,
grppi::pipeline(
[this](tuple<int,int,int> x) {
invocations_op++;
return get<0>(x) + get<1>(x) + get<2>(x);
},
[this](int x){
invocations_op2++;
return x*2;
}
)
),
[this](int x) {
invocations_sk++;
output += x;
});
}
void check_multiple_ary_sink() {
EXPECT_EQ(6, this->invocations_in); // six invocations of function in
EXPECT_EQ(5, this->invocations_op); // five invocations of function op
EXPECT_EQ(5, this->invocations_op2); // five invocations of function op
EXPECT_EQ(5, this->invocations_sk); // five invocations of function sk
EXPECT_EQ(190, this->output);
}
};
// Test for execution policies defined in supported_executions.h
TYPED_TEST_CASE(farm_pipeline_test, executions_noff);
TYPED_TEST(farm_pipeline_test, static_empty)
{
this->setup_empty();
this->run_empty(this->execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, dyn_empty)
{
this->setup_empty();
this->run_empty(this->dyn_execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, static_empty_sink)
{
this->setup_empty_sink();
this->run_empty_sink(this->execution_);
this->check_empty_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_empty_sink)
{
this->setup_empty_sink();
this->run_empty_sink(this->dyn_execution_);
this->check_empty_sink();
}
TYPED_TEST(farm_pipeline_test, static_empty_ary)
{
this->setup_empty();
this->run_empty_ary(this->execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, dyn_empty_ary)
{
this->setup_empty();
this->run_empty_ary(this->dyn_execution_);
this->check_empty();
}
TYPED_TEST(farm_pipeline_test, static_single_sink)
{
this->setup_single_sink();
this->run_single_sink(this->execution_);
this->check_single_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_single_sink)
{
this->setup_single_sink();
this->run_single_sink(this->dyn_execution_);
this->check_single_sink();
}
TYPED_TEST(farm_pipeline_test, static_single_ary_sink)
{
this->setup_single_ary_sink();
this->run_single_ary_sink(this->dyn_execution_);
this->check_single_ary_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_single_ary_sink)
{
this->setup_single_ary_sink();
this->run_single_ary_sink(this->dyn_execution_);
this->check_single_ary_sink();
}
TYPED_TEST(farm_pipeline_test, static_multiple_sink)
{
this->setup_multiple_sink();
this->run_multiple_sink(this->execution_);
this->check_multiple_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_multiple_sink)
{
this->setup_multiple_sink();
this->run_multiple_sink(this->dyn_execution_);
this->check_multiple_sink();
}
TYPED_TEST(farm_pipeline_test, static_multiple_ary_sink)
{
this->setup_multiple_ary_sink();
this->run_multiple_ary_sink(this->execution_);
this->check_multiple_ary_sink();
}
TYPED_TEST(farm_pipeline_test, dyn_multiple_ary_sink)
{
this->setup_multiple_ary_sink();
this->run_multiple_ary_sink(this->dyn_execution_);
this->check_multiple_ary_sink();
}
<|endoftext|> |
<commit_before>#include <my-class.h>
/*! \namespace MyNamespace
\brief This is a small namespace thought for the examle.
This is a namespace. A small litte namespace. It doesn't need any detailed documentation,
because it's so small. But also, because nobody will every use it.
But hey, don't be sad. That's, what an example is for. Just showcasing useful stuff.
*/
/*! \class MyClass
\brief This is a small class thought for the examle.
This is a class. A small litte class. It doesn't need any detailed documentation,
because it's so small. But also, because nobody will every use it.
But hey, don't be sad. That's, what an example is for. Just showcasing useful stuff.
*/
namespace MyNamespace
{
/*!
\brief This is a small function thought for the examle.
This is a function. A small litte function. It doesn't need any detailed documentation,
because it's so small. But also, because nobody will every use it.
But hey, don't be sad. That's, what an example is for. Just showcasing useful stuff.
*/
int MyClass::myFunction(int x) const
{
return myVar - x + 42;
}
}
<commit_msg>fixed example docu<commit_after>#include <my-class.h>
/*! \namespace MyNamespace
\brief This is a small namespace thought for the examle.
This is a namespace. A small litte namespace. It doesn't need any detailed documentation,
because it's so small. But also, because nobody will every use it.
But hey, don't be sad. That's, what an example is for. Just showcasing useful stuff.
*/
/*! \class MyNamespace::MyClass
\brief This is a small class thought for the examle.
This is a class. A small litte class. It doesn't need any detailed documentation,
because it's so small. But also, because nobody will every use it.
But hey, don't be sad. That's, what an example is for. Just showcasing useful stuff.
*/
namespace MyNamespace
{
/*!
\brief This is a small function thought for the examle.
This is a function. A small litte function. It doesn't need any detailed documentation,
because it's so small. But also, because nobody will every use it.
But hey, don't be sad. That's, what an example is for. Just showcasing useful stuff.
*/
int MyClass::myFunction(int x) const
{
return myVar - x + 42;
}
}
<|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_unotools.hxx"
#include <rtl/ustrbuf.hxx>
#include <tools/inetdef.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/bootstrap.hxx>
#include <unotools/docinfohelper.hxx>
using namespace ::com::sun::star;
namespace utl
{
::rtl::OUString DocInfoHelper::GetGeneratorString()
{
rtl::OUStringBuffer aResult;
// First product: branded name + version
// version is <product_versions>_<product_extension>$<platform>
utl::ConfigManager& rMgr = utl::ConfigManager::GetConfigManager();
// plain product name
rtl::OUString aValue;
uno::Any aAny = rMgr.GetDirectConfigProperty(
utl::ConfigManager::PRODUCTNAME);
if ( (aAny >>= aValue) && aValue.getLength() )
{
aResult.append( aValue.replace( ' ', '_' ) );
aResult.append( (sal_Unicode)'/' );
aAny = rMgr.GetDirectConfigProperty(
utl::ConfigManager::PRODUCTVERSION);
if ( (aAny >>= aValue) && aValue.getLength() )
{
aResult.append( aValue.replace( ' ', '_' ) );
aAny = rMgr.GetDirectConfigProperty(
utl::ConfigManager::PRODUCTEXTENSION);
if ( (aAny >>= aValue) && aValue.getLength() )
{
aResult.append( (sal_Unicode)'_' );
aResult.append( aValue.replace( ' ', '_' ) );
}
}
aResult.append( (sal_Unicode)'$' );
aResult.append( ::rtl::OUString::createFromAscii(
TOOLS_INETDEF_OS ).replace( ' ', '_' ) );
aResult.append( (sal_Unicode)' ' );
}
// second product: OpenOffice.org_project/<build_information>
// build_information has '(' and '[' encoded as '$', ')' and ']' ignored
// and ':' replaced by '-'
{
aResult.appendAscii( "OpenOffice.org_project/" );
::rtl::OUString aDefault;
::rtl::OUString aBuildId( Bootstrap::getBuildIdData( aDefault ) );
for( sal_Int32 i=0; i < aBuildId.getLength(); i++ )
{
sal_Unicode c = aBuildId[i];
switch( c )
{
case '(':
case '[':
aResult.append( (sal_Unicode)'$' );
break;
case ')':
case ']':
break;
case ':':
aResult.append( (sal_Unicode)'-' );
break;
default:
aResult.append( c );
break;
}
}
}
return aResult.makeStringAndClear();
}
} // end of namespace utl
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Change ODF creator to LibreOffice<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_unotools.hxx"
#include <rtl/ustrbuf.hxx>
#include <tools/inetdef.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/bootstrap.hxx>
#include <unotools/docinfohelper.hxx>
using namespace ::com::sun::star;
namespace utl
{
::rtl::OUString DocInfoHelper::GetGeneratorString()
{
rtl::OUStringBuffer aResult;
// First product: branded name + version
// version is <product_versions>_<product_extension>$<platform>
utl::ConfigManager& rMgr = utl::ConfigManager::GetConfigManager();
// plain product name
rtl::OUString aValue;
uno::Any aAny = rMgr.GetDirectConfigProperty(
utl::ConfigManager::PRODUCTNAME);
if ( (aAny >>= aValue) && aValue.getLength() )
{
aResult.append( aValue.replace( ' ', '_' ) );
aResult.append( (sal_Unicode)'/' );
aAny = rMgr.GetDirectConfigProperty(
utl::ConfigManager::PRODUCTVERSION);
if ( (aAny >>= aValue) && aValue.getLength() )
{
aResult.append( aValue.replace( ' ', '_' ) );
aAny = rMgr.GetDirectConfigProperty(
utl::ConfigManager::PRODUCTEXTENSION);
if ( (aAny >>= aValue) && aValue.getLength() )
{
aResult.append( (sal_Unicode)'_' );
aResult.append( aValue.replace( ' ', '_' ) );
}
}
aResult.append( (sal_Unicode)'$' );
aResult.append( ::rtl::OUString::createFromAscii(
TOOLS_INETDEF_OS ).replace( ' ', '_' ) );
aResult.append( (sal_Unicode)' ' );
}
// second product: LibreOffice_project/<build_information>
// build_information has '(' and '[' encoded as '$', ')' and ']' ignored
// and ':' replaced by '-'
{
aResult.appendAscii( "LibreOffice_project/" );
::rtl::OUString aDefault;
::rtl::OUString aBuildId( Bootstrap::getBuildIdData( aDefault ) );
for( sal_Int32 i=0; i < aBuildId.getLength(); i++ )
{
sal_Unicode c = aBuildId[i];
switch( c )
{
case '(':
case '[':
aResult.append( (sal_Unicode)'$' );
break;
case ')':
case ']':
break;
case ':':
aResult.append( (sal_Unicode)'-' );
break;
default:
aResult.append( c );
break;
}
}
}
return aResult.makeStringAndClear();
}
} // end of namespace utl
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#ifndef RBX_OBJECTS_HPP
#define RBX_OBJECTS_HPP
#include "vm.hpp"
#include "object.hpp"
#include "type_info.hpp"
#include <iostream>
#include "builtin/immediates.hpp" // TODO: remove me!
namespace rubinius {
class Numeric : public Object {
public:
static const object_type type = NumericType;
class Info : public TypeInfo {
public:
Info(object_type type) : TypeInfo(type) { }
};
};
class Integer : public Numeric {
public:
static const object_type type = IntegerType;
native_int n2i();
class Info : public TypeInfo {
public:
Info(object_type type) : TypeInfo(type) { }
};
};
}
namespace rubinius {
class NormalObject : public Object {
public:
const static size_t fields = 1;
const static object_type type = ObjectType;
OBJECT instance_variables;
class Info : public TypeInfo {
public:
Info(object_type type) : TypeInfo(type) { }
virtual void mark(OBJECT t, ObjectMark& mark);
};
};
template <>
static inline NormalObject* as<NormalObject>(OBJECT obj) {
return (NormalObject*)obj;
}
};
#endif
<commit_msg>Removed immediates from objects.hpp<commit_after>#ifndef RBX_OBJECTS_HPP
#define RBX_OBJECTS_HPP
#include "vm.hpp"
#include "object.hpp"
#include "type_info.hpp"
#include <iostream>
namespace rubinius {
class Numeric : public Object {
public:
static const object_type type = NumericType;
class Info : public TypeInfo {
public:
Info(object_type type) : TypeInfo(type) { }
};
};
class Integer : public Numeric {
public:
static const object_type type = IntegerType;
native_int n2i();
class Info : public TypeInfo {
public:
Info(object_type type) : TypeInfo(type) { }
};
};
}
namespace rubinius {
class NormalObject : public Object {
public:
const static size_t fields = 1;
const static object_type type = ObjectType;
OBJECT instance_variables;
class Info : public TypeInfo {
public:
Info(object_type type) : TypeInfo(type) { }
virtual void mark(OBJECT t, ObjectMark& mark);
};
};
template <>
static inline NormalObject* as<NormalObject>(OBJECT obj) {
return (NormalObject*)obj;
}
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: directview.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: jb $ $Date: 2002-03-28 08:14:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License") You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include "directview.hxx"
#ifndef CONFIGMGR_VIEWBEHAVIORFACTORY_HXX_
#include "viewfactory.hxx"
#endif
#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_
#include "setnodeimpl.hxx"
#endif
#ifndef CONFIGMGR_SETNODEACCESS_HXX
#include "setnodeaccess.hxx"
#endif
namespace configmgr
{
namespace view
{
//-----------------------------------------------------------------------------
void DirectViewStrategy::implMarkNondefault(SetNode const& _aSetNode)
{
data::SetNodeAccess aSetAccess = _aSetNode.getAccess();
OSL_ASSERT(aSetAccess.isValid());
sharable::SetNode* pNode = this->getDataForUpdate(aSetAccess);
OSL_ASSERT(pNode);
pNode->info.markAsDefault(false);
}
//-----------------------------------------------------------------------------
bool DirectViewStrategy::doHasChanges(Node const& ) const
{
return false;
}
//-----------------------------------------------------------------------------
void DirectViewStrategy::doMarkChanged(Node const& )
{
// do nothing
}
//-----------------------------------------------------------------------------
node::Attributes DirectViewStrategy::doAdjustAttributes(node::Attributes const& _aAttributes) const
{
node::Attributes aAttributes = _aAttributes;
aAttributes.bFinalized |= !aAttributes.bWritable;
aAttributes.bWritable = true;
return aAttributes;
}
//-----------------------------------------------------------------------------
configuration::ValueMemberNode DirectViewStrategy::doGetValueMember(GroupNode const& _aNode, Name const& _aName, bool _bForUpdate) const
{
return ViewStrategy::doGetValueMember(_aNode,_aName,_bForUpdate);
}
//-----------------------------------------------------------------------------
void DirectViewStrategy::doInsertElement(SetNode const& _aNode, Name const& _aName, SetNodeEntry const& _aNewEntry)
{
// move to this memory segment
// should already be direct (as any free-floating one)
//implMakeElement(aNewEntry)
SetNodeElement aNewElement = implMakeElement(_aNode, _aNewEntry );
// _aNewEntry.tree()->rebuild(this, _aNode.accessor());
_aNode.get_impl()->insertElement(_aName, aNewElement);
aNewElement->attachTo( _aNode.getAccess(), _aName );
implMarkNondefault( _aNode );
}
//-----------------------------------------------------------------------------
void DirectViewStrategy::doRemoveElement(SetNode const& _aNode, Name const& _aName)
{
SetNodeElement aOldElement = _aNode.get_impl()->removeElement(_aName);
aOldElement->detachFrom( _aNode.getAccess(), _aName);
implMarkNondefault( _aNode );
}
//-----------------------------------------------------------------------------
extern NodeFactory& getDirectAccessFactory();
NodeFactory& DirectViewStrategy::doGetNodeFactory()
{
return getDirectAccessFactory();
}
//-----------------------------------------------------------------------------
ViewStrategyRef createDirectAccessStrategy(data::TreeSegment const & _aTreeSegment)
{
return new DirectViewStrategy(_aTreeSegment);
}
//-----------------------------------------------------------------------------
}
}
<commit_msg>INTEGRATION: CWS cfg01 (1.2.24); FILE MERGED 2003/03/13 15:25:50 jb 1.2.24.2: #107404# Further clean up of node::Attributes interface 2003/02/17 15:58:08 ssmith 1.2.24.1: #107404# refactoring code to support encapsulation<commit_after>/*************************************************************************
*
* $RCSfile: directview.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-01 13:40:04 $
*
* 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 <stdio.h>
#include "directview.hxx"
#ifndef CONFIGMGR_VIEWBEHAVIORFACTORY_HXX_
#include "viewfactory.hxx"
#endif
#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_
#include "setnodeimpl.hxx"
#endif
#ifndef CONFIGMGR_SETNODEACCESS_HXX
#include "setnodeaccess.hxx"
#endif
namespace configmgr
{
namespace view
{
//-----------------------------------------------------------------------------
void DirectViewStrategy::implMarkNondefault(SetNode const& _aSetNode)
{
data::SetNodeAccess aSetAccess = _aSetNode.getAccess();
OSL_ASSERT(aSetAccess.isValid());
sharable::SetNode* pNode = this->getDataForUpdate(aSetAccess);
OSL_ASSERT(pNode);
pNode->info.markAsDefault(false);
}
//-----------------------------------------------------------------------------
bool DirectViewStrategy::doHasChanges(Node const& ) const
{
return false;
}
//-----------------------------------------------------------------------------
void DirectViewStrategy::doMarkChanged(Node const& )
{
// do nothing
}
//-----------------------------------------------------------------------------
node::Attributes DirectViewStrategy::doAdjustAttributes(node::Attributes const& _aAttributes) const
{
node::Attributes aAttributes = _aAttributes;
if (aAttributes.isReadonly())
aAttributes.setAccess(node::accessFinal);
return aAttributes;
}
//-----------------------------------------------------------------------------
configuration::ValueMemberNode DirectViewStrategy::doGetValueMember(GroupNode const& _aNode, Name const& _aName, bool _bForUpdate) const
{
return ViewStrategy::doGetValueMember(_aNode,_aName,_bForUpdate);
}
//-----------------------------------------------------------------------------
void DirectViewStrategy::doInsertElement(SetNode const& _aNode, Name const& _aName, SetNodeEntry const& _aNewEntry)
{
// move to this memory segment
// should already be direct (as any free-floating one)
//implMakeElement(aNewEntry)
SetNodeElement aNewElement = implMakeElement(_aNode, _aNewEntry );
// _aNewEntry.tree()->rebuild(this, _aNode.accessor());
_aNode.get_impl()->insertElement(_aName, aNewElement);
aNewElement->attachTo( _aNode.getAccess(), _aName );
implMarkNondefault( _aNode );
}
//-----------------------------------------------------------------------------
void DirectViewStrategy::doRemoveElement(SetNode const& _aNode, Name const& _aName)
{
SetNodeElement aOldElement = _aNode.get_impl()->removeElement(_aName);
aOldElement->detachFrom( _aNode.getAccess(), _aName);
implMarkNondefault( _aNode );
}
//-----------------------------------------------------------------------------
extern NodeFactory& getDirectAccessFactory();
NodeFactory& DirectViewStrategy::doGetNodeFactory()
{
return getDirectAccessFactory();
}
//-----------------------------------------------------------------------------
ViewStrategyRef createDirectAccessStrategy(data::TreeSegment const & _aTreeSegment)
{
return new DirectViewStrategy(_aTreeSegment);
}
//-----------------------------------------------------------------------------
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: propertyids.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: oj $ $Date: 2000-10-24 15:13:05 $
*
* 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 _CONNECTIVITY_PROPERTYIDS_HXX_
#define _CONNECTIVITY_PROPERTYIDS_HXX_
// this define has to be set to split the names into different dll's or so's
// every dll has his own set of property names
#ifndef CONNECTIVITY_PROPERTY_NAME_SPACE
#pragma warning("CONNECTIVITY_PROPERTY_NAME_SPACE not set")
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
namespace connectivity
{
namespace dbtools
{
extern const sal_Char* getPROPERTY_QUERYTIMEOUT();
extern const sal_Char* getPROPERTY_MAXFIELDSIZE();
extern const sal_Char* getPROPERTY_MAXROWS();
extern const sal_Char* getPROPERTY_CURSORNAME();
extern const sal_Char* getPROPERTY_RESULTSETCONCURRENCY();
extern const sal_Char* getPROPERTY_RESULTSETTYPE();
extern const sal_Char* getPROPERTY_FETCHDIRECTION();
extern const sal_Char* getPROPERTY_FETCHSIZE();
extern const sal_Char* getPROPERTY_ESCAPEPROCESSING();
extern const sal_Char* getPROPERTY_USEBOOKMARKS();
extern const sal_Char* getPROPERTY_NAME();
extern const sal_Char* getPROPERTY_TYPE();
extern const sal_Char* getPROPERTY_TYPENAME();
extern const sal_Char* getPROPERTY_PRECISION();
extern const sal_Char* getPROPERTY_SCALE();
extern const sal_Char* getPROPERTY_ISNULLABLE();
extern const sal_Char* getPROPERTY_ISAUTOINCREMENT();
extern const sal_Char* getPROPERTY_ISROWVERSION();
extern const sal_Char* getPROPERTY_DESCRIPTION();
extern const sal_Char* getPROPERTY_DEFAULTVALUE();
extern const sal_Char* getPROPERTY_REFERENCEDTABLE();
extern const sal_Char* getPROPERTY_UPDATERULE();
extern const sal_Char* getPROPERTY_DELETERULE();
extern const sal_Char* getPROPERTY_CATALOG();
extern const sal_Char* getPROPERTY_ISUNIQUE();
extern const sal_Char* getPROPERTY_ISPRIMARYKEYINDEX();
extern const sal_Char* getPROPERTY_ISCLUSTERED();
extern const sal_Char* getPROPERTY_ISASCENDING();
extern const sal_Char* getPROPERTY_SCHEMANAME();
extern const sal_Char* getPROPERTY_CATALOGNAME();
extern const sal_Char* getPROPERTY_COMMAND();
extern const sal_Char* getPROPERTY_CHECKOPTION();
extern const sal_Char* getPROPERTY_PASSWORD();
extern const sal_Char* getPROPERTY_REFERENCEDCOLUMN();
extern const sal_Char* getSTAT_INVALID_INDEX();
extern const sal_Char* getPROPERTY_FUNCTION();
extern const sal_Char* getPROPERTY_TABLENAME();
extern const sal_Char* getPROPERTY_REALNAME();
extern const sal_Char* getPROPERTY_DBASEPRECISIONCHANGED();
extern const sal_Char* getPROPERTY_ISCURRENCY();
extern const sal_Char* getPROPERTY_ISBOOKMARKABLE();
// ====================================================
// error messages
// ====================================================
extern const sal_Char* getERRORMSG_SEQUENCE();
extern const sal_Char* getSQLSTATE_SEQUENCE();
}
}
namespace connectivity
{
namespace CONNECTIVITY_PROPERTY_NAME_SPACE
{
typedef const sal_Char* (*PVFN)();
struct UStringDescription
{
const sal_Char* pZeroTerminatedName;
sal_Int32 nLength;
UStringDescription(PVFN _fCharFkt);
operator ::rtl::OUString() const { return ::rtl::OUString(pZeroTerminatedName,nLength,RTL_TEXTENCODING_ASCII_US); }
~UStringDescription();
private:
UStringDescription();
};
#define DECLARE_CONSTASCII_USTRING(name,nsp) \
extern connectivity::nsp::UStringDescription name;
DECLARE_CONSTASCII_USTRING(PROPERTY_CURSORNAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_RESULTSETCONCURRENCY,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_RESULTSETTYPE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_FETCHDIRECTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_FETCHSIZE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_QUERYTIMEOUT,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_MAXFIELDSIZE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_MAXROWS,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ESCAPEPROCESSING,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_USEBOOKMARKS,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_NAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_TYPE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_TYPENAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_PRECISION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_SCALE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISNULLABLE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISAUTOINCREMENT,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISROWVERSION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DESCRIPTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DEFAULTVALUE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_REFERENCEDTABLE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_UPDATERULE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DELETERULE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_CATALOG,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISUNIQUE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISPRIMARYKEYINDEX,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISCLUSTERED,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISASCENDING,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_SCHEMANAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_CATALOGNAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_COMMAND,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_CHECKOPTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_PASSWORD,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_REFERENCEDCOLUMN,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_FUNCTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_TABLENAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_REALNAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DBASEPRECISIONCHANGED,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISCURRENCY,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISBOOKMARKABLE,CONNECTIVITY_PROPERTY_NAME_SPACE)
// error msg
DECLARE_CONSTASCII_USTRING(STAT_INVALID_INDEX,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(ERRORMSG_SEQUENCE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(SQLSTATE_SEQUENCE,CONNECTIVITY_PROPERTY_NAME_SPACE);
}
}
//------------------------------------------------------------------------------
#define DECL_PROP1IMPL(varname, type) \
pProperties[nPos++] = ::com::sun::star::beans::Property(connectivity::CONNECTIVITY_PROPERTY_NAME_SPACE::PROPERTY_##varname, PROPERTY_ID_##varname, ::getCppuType(reinterpret_cast< type*>(NULL)),
//------------------------------------------------------------------------------
#define DECL_PROP0(varname, type) \
DECL_PROP1IMPL(varname, type) 0)
//------------------------------------------------------------------------------
#define DECL_BOOL_PROP1IMPL(varname) \
pProperties[nPos++] = ::com::sun::star::beans::Property(connectivity::CONNECTIVITY_PROPERTY_NAME_SPACE::PROPERTY_##varname, PROPERTY_ID_##varname, ::getBooleanCppuType(),
//------------------------------------------------------------------------------
#define DECL_BOOL_PROP0(varname) \
DECL_BOOL_PROP1IMPL(varname) 0)
#define PROPERTY_ID_QUERYTIMEOUT 1
#define PROPERTY_ID_MAXFIELDSIZE 2
#define PROPERTY_ID_MAXROWS 3
#define PROPERTY_ID_CURSORNAME 4
#define PROPERTY_ID_RESULTSETCONCURRENCY 5
#define PROPERTY_ID_RESULTSETTYPE 6
#define PROPERTY_ID_FETCHDIRECTION 7
#define PROPERTY_ID_FETCHSIZE 8
#define PROPERTY_ID_ESCAPEPROCESSING 9
#define PROPERTY_ID_USEBOOKMARKS 10
// Column
#define PROPERTY_ID_NAME 11
#define PROPERTY_ID_TYPE 12
#define PROPERTY_ID_TYPENAME 13
#define PROPERTY_ID_PRECISION 14
#define PROPERTY_ID_SCALE 15
#define PROPERTY_ID_ISNULLABLE 16
#define PROPERTY_ID_ISAUTOINCREMENT 17
#define PROPERTY_ID_ISROWVERSION 18
#define PROPERTY_ID_DESCRIPTION 19
#define PROPERTY_ID_DEFAULTVALUE 20
#define PROPERTY_ID_REFERENCEDTABLE 21
#define PROPERTY_ID_UPDATERULE 22
#define PROPERTY_ID_DELETERULE 23
#define PROPERTY_ID_CATALOG 24
#define PROPERTY_ID_ISUNIQUE 25
#define PROPERTY_ID_ISPRIMARYKEYINDEX 26
#define PROPERTY_ID_ISCLUSTERED 27
#define PROPERTY_ID_ISASCENDING 28
#define PROPERTY_ID_SCHEMANAME 29
#define PROPERTY_ID_CATALOGNAME 30
#define PROPERTY_ID_COMMAND 31
#define PROPERTY_ID_CHECKOPTION 32
#define PROPERTY_ID_PASSWORD 33
#define PROPERTY_ID_REFERENCEDCOLUMN 34
#define PROPERTY_ID_FUNCTION 35
#define PROPERTY_ID_TABLENAME 36
#define PROPERTY_ID_REALNAME 37
#define PROPERTY_ID_DBASEPRECISIONCHANGED 38
#define PROPERTY_ID_ISCURRENCY 39
#define PROPERTY_ID_ISBOOKMARKABLE 40
#endif // _CONNECTIVITY_PROPERTYIDS_HXX_
<commit_msg>#65293#: typo<commit_after>/*************************************************************************
*
* $RCSfile: propertyids.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2000-10-31 11:04:19 $
*
* 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 _CONNECTIVITY_PROPERTYIDS_HXX_
#define _CONNECTIVITY_PROPERTYIDS_HXX_
// this define has to be set to split the names into different dll's or so's
// every dll has his own set of property names
#ifndef CONNECTIVITY_PROPERTY_NAME_SPACE
#pragma warning("CONNECTIVITY_PROPERTY_NAME_SPACE not set")
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
namespace connectivity
{
namespace dbtools
{
extern const sal_Char* getPROPERTY_QUERYTIMEOUT();
extern const sal_Char* getPROPERTY_MAXFIELDSIZE();
extern const sal_Char* getPROPERTY_MAXROWS();
extern const sal_Char* getPROPERTY_CURSORNAME();
extern const sal_Char* getPROPERTY_RESULTSETCONCURRENCY();
extern const sal_Char* getPROPERTY_RESULTSETTYPE();
extern const sal_Char* getPROPERTY_FETCHDIRECTION();
extern const sal_Char* getPROPERTY_FETCHSIZE();
extern const sal_Char* getPROPERTY_ESCAPEPROCESSING();
extern const sal_Char* getPROPERTY_USEBOOKMARKS();
extern const sal_Char* getPROPERTY_NAME();
extern const sal_Char* getPROPERTY_TYPE();
extern const sal_Char* getPROPERTY_TYPENAME();
extern const sal_Char* getPROPERTY_PRECISION();
extern const sal_Char* getPROPERTY_SCALE();
extern const sal_Char* getPROPERTY_ISNULLABLE();
extern const sal_Char* getPROPERTY_ISAUTOINCREMENT();
extern const sal_Char* getPROPERTY_ISROWVERSION();
extern const sal_Char* getPROPERTY_DESCRIPTION();
extern const sal_Char* getPROPERTY_DEFAULTVALUE();
extern const sal_Char* getPROPERTY_REFERENCEDTABLE();
extern const sal_Char* getPROPERTY_UPDATERULE();
extern const sal_Char* getPROPERTY_DELETERULE();
extern const sal_Char* getPROPERTY_CATALOG();
extern const sal_Char* getPROPERTY_ISUNIQUE();
extern const sal_Char* getPROPERTY_ISPRIMARYKEYINDEX();
extern const sal_Char* getPROPERTY_ISCLUSTERED();
extern const sal_Char* getPROPERTY_ISASCENDING();
extern const sal_Char* getPROPERTY_SCHEMANAME();
extern const sal_Char* getPROPERTY_CATALOGNAME();
extern const sal_Char* getPROPERTY_COMMAND();
extern const sal_Char* getPROPERTY_CHECKOPTION();
extern const sal_Char* getPROPERTY_PASSWORD();
extern const sal_Char* getPROPERTY_REFERENCEDCOLUMN();
extern const sal_Char* getSTAT_INVALID_INDEX();
extern const sal_Char* getPROPERTY_FUNCTION();
extern const sal_Char* getPROPERTY_TABLENAME();
extern const sal_Char* getPROPERTY_REALNAME();
extern const sal_Char* getPROPERTY_DBASEPRECISIONCHANGED();
extern const sal_Char* getPROPERTY_ISCURRENCY();
extern const sal_Char* getPROPERTY_ISBOOKMARKABLE();
// ====================================================
// error messages
// ====================================================
extern const sal_Char* getERRORMSG_SEQUENCE();
extern const sal_Char* getSQLSTATE_SEQUENCE();
}
}
namespace connectivity
{
namespace CONNECTIVITY_PROPERTY_NAME_SPACE
{
typedef const sal_Char* (*PVFN)();
struct UStringDescription
{
const sal_Char* pZeroTerminatedName;
sal_Int32 nLength;
UStringDescription(PVFN _fCharFkt);
operator ::rtl::OUString() const { return ::rtl::OUString(pZeroTerminatedName,nLength,RTL_TEXTENCODING_ASCII_US); }
~UStringDescription();
private:
UStringDescription();
};
#define DECLARE_CONSTASCII_USTRING(name,nsp) \
extern connectivity::nsp::UStringDescription name;
DECLARE_CONSTASCII_USTRING(PROPERTY_CURSORNAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_RESULTSETCONCURRENCY,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_RESULTSETTYPE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_FETCHDIRECTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_FETCHSIZE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_QUERYTIMEOUT,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_MAXFIELDSIZE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_MAXROWS,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ESCAPEPROCESSING,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_USEBOOKMARKS,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_NAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_TYPE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_TYPENAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_PRECISION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_SCALE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISNULLABLE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISAUTOINCREMENT,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISROWVERSION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DESCRIPTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DEFAULTVALUE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_REFERENCEDTABLE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_UPDATERULE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DELETERULE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_CATALOG,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISUNIQUE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISPRIMARYKEYINDEX,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISCLUSTERED,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISASCENDING,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_SCHEMANAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_CATALOGNAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_COMMAND,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_CHECKOPTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_PASSWORD,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_REFERENCEDCOLUMN,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_FUNCTION,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_TABLENAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_REALNAME,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_DBASEPRECISIONCHANGED,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISCURRENCY,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(PROPERTY_ISBOOKMARKABLE,CONNECTIVITY_PROPERTY_NAME_SPACE)
// error msg
DECLARE_CONSTASCII_USTRING(STAT_INVALID_INDEX,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(ERRORMSG_SEQUENCE,CONNECTIVITY_PROPERTY_NAME_SPACE)
DECLARE_CONSTASCII_USTRING(SQLSTATE_SEQUENCE,CONNECTIVITY_PROPERTY_NAME_SPACE)
}
}
//------------------------------------------------------------------------------
#define DECL_PROP1IMPL(varname, type) \
pProperties[nPos++] = ::com::sun::star::beans::Property(connectivity::CONNECTIVITY_PROPERTY_NAME_SPACE::PROPERTY_##varname, PROPERTY_ID_##varname, ::getCppuType(reinterpret_cast< type*>(NULL)),
//------------------------------------------------------------------------------
#define DECL_PROP0(varname, type) \
DECL_PROP1IMPL(varname, type) 0)
//------------------------------------------------------------------------------
#define DECL_BOOL_PROP1IMPL(varname) \
pProperties[nPos++] = ::com::sun::star::beans::Property(connectivity::CONNECTIVITY_PROPERTY_NAME_SPACE::PROPERTY_##varname, PROPERTY_ID_##varname, ::getBooleanCppuType(),
//------------------------------------------------------------------------------
#define DECL_BOOL_PROP0(varname) \
DECL_BOOL_PROP1IMPL(varname) 0)
#define PROPERTY_ID_QUERYTIMEOUT 1
#define PROPERTY_ID_MAXFIELDSIZE 2
#define PROPERTY_ID_MAXROWS 3
#define PROPERTY_ID_CURSORNAME 4
#define PROPERTY_ID_RESULTSETCONCURRENCY 5
#define PROPERTY_ID_RESULTSETTYPE 6
#define PROPERTY_ID_FETCHDIRECTION 7
#define PROPERTY_ID_FETCHSIZE 8
#define PROPERTY_ID_ESCAPEPROCESSING 9
#define PROPERTY_ID_USEBOOKMARKS 10
// Column
#define PROPERTY_ID_NAME 11
#define PROPERTY_ID_TYPE 12
#define PROPERTY_ID_TYPENAME 13
#define PROPERTY_ID_PRECISION 14
#define PROPERTY_ID_SCALE 15
#define PROPERTY_ID_ISNULLABLE 16
#define PROPERTY_ID_ISAUTOINCREMENT 17
#define PROPERTY_ID_ISROWVERSION 18
#define PROPERTY_ID_DESCRIPTION 19
#define PROPERTY_ID_DEFAULTVALUE 20
#define PROPERTY_ID_REFERENCEDTABLE 21
#define PROPERTY_ID_UPDATERULE 22
#define PROPERTY_ID_DELETERULE 23
#define PROPERTY_ID_CATALOG 24
#define PROPERTY_ID_ISUNIQUE 25
#define PROPERTY_ID_ISPRIMARYKEYINDEX 26
#define PROPERTY_ID_ISCLUSTERED 27
#define PROPERTY_ID_ISASCENDING 28
#define PROPERTY_ID_SCHEMANAME 29
#define PROPERTY_ID_CATALOGNAME 30
#define PROPERTY_ID_COMMAND 31
#define PROPERTY_ID_CHECKOPTION 32
#define PROPERTY_ID_PASSWORD 33
#define PROPERTY_ID_REFERENCEDCOLUMN 34
#define PROPERTY_ID_FUNCTION 35
#define PROPERTY_ID_TABLENAME 36
#define PROPERTY_ID_REALNAME 37
#define PROPERTY_ID_DBASEPRECISIONCHANGED 38
#define PROPERTY_ID_ISCURRENCY 39
#define PROPERTY_ID_ISBOOKMARKABLE 40
#endif // _CONNECTIVITY_PROPERTYIDS_HXX_
<|endoftext|> |
<commit_before>#ifndef SAVE_STATE_H
# define SAVE_STATE_H
# pragma once
struct statebuf
{
void* sp;
void* bp;
void* label;
};
#if defined(__GNUC__)
static inline bool __attribute__((always_inline)) savestate(
statebuf& ssb) noexcept
{
bool r;
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile (
"movl %%esp, %0\n\t" // store sp
"movl %%ebp, %1\n\t" // store bp
"movl $1f, %2\n\t" // store label
"movb $0, %3\n\t" // return false
"jmp 2f\n\t"
"1:"
"movb $1, %3\n\t" // return true
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "memory"
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile (
"movq %%rsp, %0\n\t" // store sp
"movq %%rbp, %1\n\t" // store bp
"movq $1f, %2\n\t" // store label
"movb $0, %3\n\t" // return false
"jmp 2f\n\t"
"1:"
"movb $1, %3\n\t" // return true
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "memory"
);
#elif defined(__aarch64__)
asm volatile (
"mov x7, sp\n\t"
"str x7, %0\n\t" // store sp
"str fp, %1\n\t" // store fp
"ldr x7, =1f\n\t" // load label into x3
"str x7, %2\n\t" // store x3 into label
"mov %3, #0\n\t" // store 0 into result
"b 2f\n\t"
"1:"
"mov %3, #1\n\t" // store 1 into result
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "x7", "memory"
);
#elif defined(__arm__) && defined(__ARM_ARCH_7__)
asm volatile (
"str sp, %0\n\t" // store sp
"str r7, %1\n\t" // store fp
"ldr r3, =1f\n\t" // load label into r3
"str r3, %2\n\t" // store r3 into label
"mov %3, $0\n\t" // store 0 into result
"b 2f\n\t"
"1:"
"mov %3, $1\n\t" // store 1 into result
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "r3", "memory"
);
#elif defined(__arm__)
asm volatile (
"str sp, %0\n\t" // store sp
"str fp, %1\n\t" // store fp
"ldr r3, =1f\n\t" // load label into r3
"str r3, %2\n\t" // store r3 into label
"mov %3, $0\n\t" // store 0 into result
"b 2f\n\t"
"1:"
"mov %3, $1\n\t" // store 1 into result
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "r3", "memory"
);
#endif
return r;
}
#elif defined(_MSC_VER)
__forceinline bool savestate(statebuf& ssb) noexcept
{
bool r;
__asm {
mov ebx, ssb
mov [ebx]ssb.sp, esp
mov [ebx]ssb.bp, ebp
mov [ebx]ssb.label, offset _1f
mov r, 0x0
jmp _2f
_1f:
mov r, 0x1
_2f:
}
return r;
}
#else
# error "unsupported compiler"
#endif
#if defined(__GNUC__)
#if defined(i386) || defined(__i386) || defined(__i386__)
#define restorestate(SSB) \
asm volatile ( \
"movl %0, %%esp\n\t" \
"movl %1, %%ebp\n\t" \
"jmp *%2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
#define restorestate(SSB) \
asm volatile ( \
"movq %0, %%rsp\n\t" \
"movq %1, %%rbp\n\t" \
"jmp *%2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__aarch64__)
#define restorestate(SSB) \
asm volatile ( \
"mov sp, %0\n\t" \
"mov fp, %1\n\t" \
"ret %2" \
: \
: "r" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__arm__) && defined(__ARM_ARCH_7__)
#define restorestate(SSB) \
asm volatile ( \
"ldr sp, %0\n\t" \
"mov r7, %1\n\t" \
"mov pc, %2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__arm__)
#define restorestate(SSB) \
asm volatile ( \
"ldr sp, %0\n\t" \
"mov fp, %1\n\t" \
"mov pc, %2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#else
# error "unsupported architecture"
#endif
#elif defined(_MSC_VER)
#define restorestate(SSB) \
__asm mov ebx, this \
__asm add ebx, [SSB] \
__asm mov esp, [ebx]SSB.sp\
__asm mov ebp, [ebx]SSB.bp\
__asm jmp [ebx]SSB.label
#else
# error "unsupported compiler"
#endif
#endif // SAVE_STATE_H
<commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H
# define SAVE_STATE_H
# pragma once
struct statebuf
{
void* sp;
void* bp;
void* label;
};
#if defined(__GNUC__)
static inline bool __attribute__((always_inline)) savestate(
statebuf& ssb) noexcept
{
bool r;
#if defined(i386) || defined(__i386) || defined(__i386__)
asm volatile (
"movl %%esp, %0\n\t" // store sp
"movl %%ebp, %1\n\t" // store bp
"movl $1f, %2\n\t" // store label
"movb $0, %3\n\t" // return false
"jmp 2f\n\t"
"1:"
"movb $1, %3\n\t" // return true
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "memory"
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
asm volatile (
"movq %%rsp, %0\n\t" // store sp
"movq %%rbp, %1\n\t" // store bp
"movq $1f, %2\n\t" // store label
"movb $0, %3\n\t" // return false
"jmp 2f\n\t"
"1:"
"movb $1, %3\n\t" // return true
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "memory"
);
#elif defined(__aarch64__)
asm volatile (
"mov x7, sp\n\t"
"str x7, %0\n\t" // store sp
"str fp, %1\n\t" // store fp
"ldr x7, =1f\n\t" // load label into x3
"str x7, %2\n\t" // store x3 into label
"mov %3, #0\n\t" // store 0 into result
"b 2f\n\t"
"1:"
"mov %3, #1\n\t" // store 1 into result
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "x7", "memory"
);
#elif defined(__arm__) && defined(__ARM_ARCH_7__)
asm volatile (
"str sp, %0\n\t" // store sp
"str r7, %1\n\t" // store fp
"ldr r3, =1f\n\t" // load label into r3
"str r3, %2\n\t" // store r3 into label
"mov %3, $0\n\t" // store 0 into result
"b 2f\n\t"
"1:"
"mov %3, $1\n\t" // store 1 into result
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "r3", "memory"
);
#elif defined(__arm__)
asm volatile (
"str sp, %0\n\t" // store sp
"str fp, %1\n\t" // store fp
"ldr r3, =1f\n\t" // load label into r3
"str r3, %2\n\t" // store r3 into label
"mov %3, $0\n\t" // store 0 into result
"b 2f\n\t"
"1:"
"mov %3, $1\n\t" // store 1 into result
"2:"
: "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r)
:
: "r3", "memory"
);
#endif
return r;
}
#elif defined(_MSC_VER)
__forceinline bool savestate(statebuf& ssb) noexcept
{
bool r;
__asm {
mov ebx, ssb
mov [ebx]ssb.sp, esp
mov [ebx]ssb.bp, ebp
mov [ebx]ssb.label, offset _1f
mov r, 0x0
jmp _2f
_1f:
mov r, 0x1
_2f:
}
return r;
}
#else
# error "unsupported compiler"
#endif
#if defined(__GNUC__)
#if defined(i386) || defined(__i386) || defined(__i386__)
#define restorestate(SSB) \
asm volatile ( \
"movl %0, %%esp\n\t" \
"movl %1, %%ebp\n\t" \
"jmp *%2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
#define restorestate(SSB) \
asm volatile ( \
"movq %0, %%rsp\n\t" \
"movq %1, %%rbp\n\t" \
"jmp *%2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__aarch64__)
#define restorestate(SSB) \
asm volatile ( \
"mov sp, %0\n\t" \
"mov fp, %1\n\t" \
"ret %2" \
: \
: "r" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__arm__) && defined(__ARM_ARCH_7__)
#define restorestate(SSB) \
asm volatile ( \
"ldr sp, %0\n\t" \
"mov r7, %1\n\t" \
"mov pc, %2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#elif defined(__arm__)
#define restorestate(SSB) \
asm volatile ( \
"ldr sp, %0\n\t" \
"mov fp, %1\n\t" \
"mov pc, %2" \
: \
: "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\
);
#else
# error "unsupported architecture"
#endif
#elif defined(_MSC_VER)
#define restorestate(SSB) \
__asm mov ebx, this \
__asm add ebx, [SSB] \
__asm mov esp, [ebx]SSB.sp\
__asm mov ebp, [ebx]SSB.bp\
__asm jmp [ebx]SSB.label
#else
# error "unsupported compiler"
#endif
#endif // SAVE_STATE_H
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cr_html.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-19 20:04:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <fstream>
#include "cr_html.hxx"
#include "xmltree.hxx"
#include "../support/syshelp.hxx"
char C_sHtmlFileHeader1[] =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n"
"<HTML>\n"
"<HEAD>\n"
" <TITLE>";
char C_sHtmlFileHeader2[] =
"</TITLE>\n"
" <META NAME=\"GENERATOR\" CONTENT=\"xml2cmp\">\n"
"</HEAD>\n"
"<BODY BGCOLOR=\"#ffffff\">\n<P><BR></P>";
char C_sHtmlFileFoot[] = "</BODY>\n</HTML>\n";
HtmlCreator::HtmlCreator( const char * i_pOutputFileName,
const XmlElement & i_rDocument,
const Simstr & i_sIDL_BaseDirectory )
: aFile(i_pOutputFileName, std::ios::out
#ifdef WNT
| std::ios::binary
#endif
),
rDocument(i_rDocument),
sIdl_BaseDirectory(i_sIDL_BaseDirectory)
{
if ( !aFile )
{
std::cerr << "Error: " << i_pOutputFileName << " could not be created." << std::endl;
exit(0);
}
}
HtmlCreator::~HtmlCreator()
{
aFile.close();
}
void
HtmlCreator::Run()
{
WriteStr( C_sHtmlFileHeader1 );
WriteStr( "ModuleDescription" );
WriteStr( C_sHtmlFileHeader2 );
rDocument.Write2Html(*this);
WriteStr( "<P><BR><BR></P>\n" );
WriteStr( C_sHtmlFileFoot );
}
void
HtmlCreator::StartTable()
{
WriteStr( "<P><BR></P>\n" );
WriteStr(
"<TABLE WIDTH=95% BORDER=1 CELLSPACING=0 CELLPADDING=4>\n"
" <TBODY>\n" );
}
void
HtmlCreator::FinishTable()
{
WriteStr( " </TBODY>\n"
"</TABLE>\n\n" );
}
void
HtmlCreator::StartBigCell( const char * i_sTitle )
{
WriteStr( "<TR><TD COLSPAN=2>\n"
"<H4><BR>" );
WriteStr( i_sTitle );
WriteStr( "</H4>\n" );
}
void
HtmlCreator::FinishBigCell()
{
WriteStr( "</TD><TR>\n" );
}
void
HtmlCreator::Write_SglTextElement( const SglTextElement & i_rElement,
bool i_bStrong )
{
StartRow();
WriteElementName( i_rElement.Name(), i_bStrong );
StartCell( "77%");
if (i_bStrong)
{
WriteStr( "<H4><A NAME=\"" );
unsigned nLen = strlen(i_rElement.Data());
if ( i_rElement.IsReversedName())
{
const char * pEnd = strchr(i_rElement.Data(), ' ');
nLen = pEnd - i_rElement.Data();
}
aFile.write( i_rElement.Data(), nLen );
WriteStr( "\">" );
}
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(),
i_bStrong ? lt_nolink : i_rElement.LinkType() );
if (i_bStrong)
WriteStr( "</A></H4>" );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_MultiTextElement( const MultipleTextElement & i_rElement )
{
StartRow();
WriteElementName( i_rElement.Name(), false );
StartCell( "77%");
unsigned i_max = i_rElement.Size();
for ( unsigned i = 0; i < i_max; ++i )
{
if (i > 0)
WriteStr( "<BR>\n" );
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(i), i_rElement.LinkType() );
} // end for
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_SglText( const Simstr & i_sName,
const Simstr & i_sValue )
{
StartRow();
WriteElementName( i_sName, false );
StartCell( "77%");
WriteStr( i_sValue );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_ReferenceDocu( const Simstr & i_sName,
const Simstr & i_sRef,
const Simstr & i_sRole,
const Simstr & i_sTitle )
{
StartRow();
StartCell( "23%" );
WriteStr(i_sName);
FinishCell();
StartCell( "77%" );
if ( !i_sRef.is_empty() )
{
WriteStr("<A href=\"");
WriteStr(i_sRef);
WriteStr("\">");
if ( !i_sTitle.is_empty() )
WriteStr( i_sTitle );
else
WriteStr(i_sRef);
WriteStr("</A><BR>\n");
}
else if ( !i_sTitle.is_empty() )
{
WriteStr("Title: ");
WriteStr( i_sTitle );
WriteStr("<BR>\n");
}
if ( !i_sRole.is_empty() )
{
WriteStr("Role: ");
WriteStr( i_sRole );
}
FinishCell();
FinishRow();
}
void
HtmlCreator::PrintH1( const char * i_pText)
{
static const char sH1a[] = "<H1 ALIGN=CENTER>";
static const char sH1e[] = "</H1>";
WriteStr(sH1a);
WriteStr(i_pText);
WriteStr(sH1e);
}
void
HtmlCreator::StartRow()
{
WriteStr( " <TR VALIGN=TOP>\n" );
}
void
HtmlCreator::FinishRow()
{
WriteStr( " </TR>\n" );
}
void
HtmlCreator::StartCell( const char * i_pWidth)
{
WriteStr( " <TD WIDTH=" );
WriteStr( i_pWidth );
WriteStr( ">\n <P>" );
}
void
HtmlCreator::FinishCell()
{
WriteStr( "</P>\n </TD>\n" );
}
void
HtmlCreator::WriteElementName( const Simstr & i_sName,
bool i_bStrong )
{
StartCell( "23%" );
if (i_bStrong)
WriteStr( "<H4>" );
WriteStr(i_sName);
if (i_bStrong)
WriteStr( "</H4>" );
FinishCell();
}
<commit_msg>INTEGRATION: CWS obo05 (1.8.2); FILE MERGED 2006/06/27 13:15:59 obo 1.8.2.1: #i53611# port for .net 2005<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cr_html.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2006-09-25 13:26:08 $
*
* 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 <fstream>
#include "cr_html.hxx"
#include "xmltree.hxx"
#include "../support/syshelp.hxx"
char C_sHtmlFileHeader1[] =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n"
"<HTML>\n"
"<HEAD>\n"
" <TITLE>";
char C_sHtmlFileHeader2[] =
"</TITLE>\n"
" <META NAME=\"GENERATOR\" CONTENT=\"xml2cmp\">\n"
"</HEAD>\n"
"<BODY BGCOLOR=\"#ffffff\">\n<P><BR></P>";
char C_sHtmlFileFoot[] = "</BODY>\n</HTML>\n";
HtmlCreator::HtmlCreator( const char * i_pOutputFileName,
const XmlElement & i_rDocument,
const Simstr & i_sIDL_BaseDirectory )
: aFile(i_pOutputFileName, std::ios::out
#ifdef WNT
| std::ios::binary
#endif
),
rDocument(i_rDocument),
sIdl_BaseDirectory(i_sIDL_BaseDirectory)
{
if ( !aFile )
{
std::cerr << "Error: " << i_pOutputFileName << " could not be created." << std::endl;
exit(0);
}
}
HtmlCreator::~HtmlCreator()
{
aFile.close();
}
void
HtmlCreator::Run()
{
WriteStr( C_sHtmlFileHeader1 );
WriteStr( "ModuleDescription" );
WriteStr( C_sHtmlFileHeader2 );
rDocument.Write2Html(*this);
WriteStr( "<P><BR><BR></P>\n" );
WriteStr( C_sHtmlFileFoot );
}
void
HtmlCreator::StartTable()
{
WriteStr( "<P><BR></P>\n" );
WriteStr(
"<TABLE WIDTH=95% BORDER=1 CELLSPACING=0 CELLPADDING=4>\n"
" <TBODY>\n" );
}
void
HtmlCreator::FinishTable()
{
WriteStr( " </TBODY>\n"
"</TABLE>\n\n" );
}
void
HtmlCreator::StartBigCell( const char * i_sTitle )
{
WriteStr( "<TR><TD COLSPAN=2>\n"
"<H4><BR>" );
WriteStr( i_sTitle );
WriteStr( "</H4>\n" );
}
void
HtmlCreator::FinishBigCell()
{
WriteStr( "</TD><TR>\n" );
}
void
HtmlCreator::Write_SglTextElement( const SglTextElement & i_rElement,
bool i_bStrong )
{
StartRow();
WriteElementName( i_rElement.Name(), i_bStrong );
StartCell( "77%");
if (i_bStrong)
{
WriteStr( "<H4><A NAME=\"" );
unsigned nLen = strlen(i_rElement.Data());
if ( i_rElement.IsReversedName())
{
const char * pEnd = strchr(i_rElement.Data(), ' ');
nLen = (unsigned)( pEnd - i_rElement.Data() );
}
aFile.write( i_rElement.Data(), (int) nLen );
WriteStr( "\">" );
}
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(),
i_bStrong ? lt_nolink : i_rElement.LinkType() );
if (i_bStrong)
WriteStr( "</A></H4>" );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_MultiTextElement( const MultipleTextElement & i_rElement )
{
StartRow();
WriteElementName( i_rElement.Name(), false );
StartCell( "77%");
unsigned i_max = i_rElement.Size();
for ( unsigned i = 0; i < i_max; ++i )
{
if (i > 0)
WriteStr( "<BR>\n" );
WriteName( aFile, sIdl_BaseDirectory, i_rElement.Data(i), i_rElement.LinkType() );
} // end for
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_SglText( const Simstr & i_sName,
const Simstr & i_sValue )
{
StartRow();
WriteElementName( i_sName, false );
StartCell( "77%");
WriteStr( i_sValue );
FinishCell();
FinishRow();
}
void
HtmlCreator::Write_ReferenceDocu( const Simstr & i_sName,
const Simstr & i_sRef,
const Simstr & i_sRole,
const Simstr & i_sTitle )
{
StartRow();
StartCell( "23%" );
WriteStr(i_sName);
FinishCell();
StartCell( "77%" );
if ( !i_sRef.is_empty() )
{
WriteStr("<A href=\"");
WriteStr(i_sRef);
WriteStr("\">");
if ( !i_sTitle.is_empty() )
WriteStr( i_sTitle );
else
WriteStr(i_sRef);
WriteStr("</A><BR>\n");
}
else if ( !i_sTitle.is_empty() )
{
WriteStr("Title: ");
WriteStr( i_sTitle );
WriteStr("<BR>\n");
}
if ( !i_sRole.is_empty() )
{
WriteStr("Role: ");
WriteStr( i_sRole );
}
FinishCell();
FinishRow();
}
void
HtmlCreator::PrintH1( const char * i_pText)
{
static const char sH1a[] = "<H1 ALIGN=CENTER>";
static const char sH1e[] = "</H1>";
WriteStr(sH1a);
WriteStr(i_pText);
WriteStr(sH1e);
}
void
HtmlCreator::StartRow()
{
WriteStr( " <TR VALIGN=TOP>\n" );
}
void
HtmlCreator::FinishRow()
{
WriteStr( " </TR>\n" );
}
void
HtmlCreator::StartCell( const char * i_pWidth)
{
WriteStr( " <TD WIDTH=" );
WriteStr( i_pWidth );
WriteStr( ">\n <P>" );
}
void
HtmlCreator::FinishCell()
{
WriteStr( "</P>\n </TD>\n" );
}
void
HtmlCreator::WriteElementName( const Simstr & i_sName,
bool i_bStrong )
{
StartCell( "23%" );
if (i_bStrong)
WriteStr( "<H4>" );
WriteStr(i_sName);
if (i_bStrong)
WriteStr( "</H4>" );
FinishCell();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlmetae.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 13:33:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLMETAE_HXX
#define _XMLOFF_XMLMETAE_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFO_HPP_
#include <com/sun/star/document/XDocumentInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
namespace com { namespace sun { namespace star { namespace frame {
class XModel;
} } } }
class Time;
class SvXMLNamespaceMap;
class SvXMLAttributeList;
class SvXMLExport;
class XMLOFF_DLLPUBLIC SfxXMLMetaExport
{
private:
SvXMLExport& rExport;
::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo> xDocInfo;
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet> xInfoProp;
::com::sun::star::lang::Locale aLocale;
::com::sun::star::uno::Sequence<
::com::sun::star::beans::NamedValue> aDocStatistic;
SAL_DLLPRIVATE void SimpleStringElement(
const ::rtl::OUString& rPropertyName, sal_uInt16 nNamespace,
enum ::xmloff::token::XMLTokenEnum eElementName );
SAL_DLLPRIVATE void SimpleDateTimeElement(
const ::rtl::OUString& rPropertyName, sal_uInt16 nNamespace,
enum ::xmloff::token::XMLTokenEnum eElementName );
public:
SfxXMLMetaExport( SvXMLExport& rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel>& rDocModel );
SfxXMLMetaExport( SvXMLExport& rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo>& rDocInfo );
virtual ~SfxXMLMetaExport();
// core API
void Export();
static ::rtl::OUString GetISODateTimeString(
const ::com::sun::star::util::DateTime& rDateTime );
};
#endif // _XMLOFF_XMLMETAE_HXX
<commit_msg>INTEGRATION: CWS custommeta (1.2.132); FILE MERGED 2007/12/18 15:53:49 mst 1.2.132.2: - xmloff/inc/xmloff/xmlmetae.hxx, xmloff/source/meta/xmlmetae.cxx, xmloff/source/meta/xmlversion.cxx: + remove class SfxXMLMetaExport; replaced by SvXMLMetaExport + SvXMLMetaExport::_Export replaces SfxXMLMetaExport::Export, uses XDocumentProperties instead of XDocumentInfo 2007/12/07 18:51:47 mst 1.2.132.1: refactoring to use XDocumentProperties instead of XDocumentInfo on document export: - xmloff/inc/xmloff/xmlexp.hxx, xmloff/source/core/xmlexp.cxx: + turn lcl_GetProductName into static method SvXMLExport::GetProductName + updating of Generator string is now done in _ExportMeta - xmloff/inc/MetaExportComponent.hxx, source/meta/MetaExportComponent.cxx: + use XDocumentProperties instead of XDocumentInfo + override _ExportMeta - xmloff/inc/xmloff/xmlmetae.hxx, source/meta/xmlmetae.cxx: + new class SvXMLMetaExport, to eventually replace SfxXMLMetaExport + move lcl_GetProductName to xmlexp.cxx<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlmetae.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2008-02-26 13:30:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLMETAE_HXX
#define _XMLOFF_XMLMETAE_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#include <cppuhelper/implbase1.hxx>
#include <xmloff/xmltoken.hxx>
#include <vector>
#include <com/sun/star/beans/StringPair.hpp>
#include <com/sun/star/util/DateTime.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>
class SvXMLExport;
/** export meta data from an <type>XDocumentProperties</type> instance.
<p>
This class will start the export at the office:meta element,
not at the root element. This means that when <method>Export</method>
is called here, the document root element must already be written, but
office:meta must <em>not</em> be written.
</p>
*/
class XMLOFF_DLLPUBLIC SvXMLMetaExport : public ::cppu::WeakImplHelper1<
::com::sun::star::xml::sax::XDocumentHandler >
{
private:
SvXMLExport& mrExport;
::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentProperties> mxDocProps;
/// counts levels of the xml document. necessary for special handling.
int m_level;
/// preserved namespaces. necessary because we do not write the root node.
std::vector< ::com::sun::star::beans::StringPair > m_preservedNSs;
SAL_DLLPRIVATE void SimpleStringElement(
const ::rtl::OUString& rText, sal_uInt16 nNamespace,
enum ::xmloff::token::XMLTokenEnum eElementName );
SAL_DLLPRIVATE void SimpleDateTimeElement(
const ::com::sun::star::util::DateTime & rDate, sal_uInt16 nNamespace,
enum ::xmloff::token::XMLTokenEnum eElementName );
/// currently unused; for exporting via the XDocumentProperties interface
SAL_DLLPRIVATE void _Export();
public:
SvXMLMetaExport( SvXMLExport& i_rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentProperties>& i_rDocProps);
virtual ~SvXMLMetaExport();
/// export via XSAXWriter interface, with fallback to _Export
void Export();
static ::rtl::OUString GetISODateTimeString(
const ::com::sun::star::util::DateTime& rDateTime );
// ::com::sun::star::xml::sax::XDocumentHandler:
virtual void SAL_CALL startDocument()
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL endDocument()
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL startElement(const ::rtl::OUString & i_rName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & i_xAttribs)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL endElement(const ::rtl::OUString & i_rName)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL characters(const ::rtl::OUString & i_rChars)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL ignorableWhitespace(
const ::rtl::OUString & i_rWhitespaces)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL processingInstruction(
const ::rtl::OUString & i_rTarget, const ::rtl::OUString & i_rData)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
virtual void SAL_CALL setDocumentLocator(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XLocator > & i_xLocator)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::xml::sax::SAXException);
};
#endif // _XMLOFF_XMLMETAE_HXX
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: PlaneSrc.cc
Language: C++
Date: 5/15/94
Version: 1.12
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkPlaneSource.hh"
#include "vtkFloatPoints.hh"
#include "vtkFloatNormals.hh"
#include "vtkFloatTCoords.hh"
#include "vtkMath.hh"
static vtkMath math;
// Description:
// Construct plane perpendicular to z-axis, resolution 1x1, width and height 1.0,
// and centered at the origin.
vtkPlaneSource::vtkPlaneSource()
{
this->XResolution = 1;
this->YResolution = 1;
this->Origin[0] = this->Origin[1] = -0.5;
this->Origin[2] = 0.0;
this->Point1[0] = 0.5;
this->Point1[1] = -0.5;
this->Point1[2] = 0.0;
this->Point2[0] = -0.5;
this->Point2[1] = 0.5;
this->Point2[2] = 0.0;
this->Normal[2] = 1.0;
this->Normal[0] = this->Normal[1] = 0.0;
}
// Description:
// Set the number of x-y subdivisions in the plane.
void vtkPlaneSource::SetResolution(const int xR, const int yR)
{
if ( xR != this->XResolution || yR != this->YResolution )
{
this->XResolution = xR;
this->YResolution = yR;
this->XResolution = (this->XResolution > 0 ? this->XResolution : 1);
this->YResolution = (this->YResolution > 0 ? this->YResolution : 1);
this->Modified();
}
}
void vtkPlaneSource::Execute()
{
float x[3], tc[2], v1[3], v2[3];
int pts[4];
int i, j, ii;
int numPts;
int numPolys;
vtkFloatPoints *newPoints;
vtkFloatNormals *newNormals;
vtkFloatTCoords *newTCoords;
vtkCellArray *newPolys;
vtkPolyData *output = this->GetOutput();
// Check input
for ( i=0; i < 3; i++ )
{
v1[i] = this->Point1[i] - this->Origin[i];
v2[i] = this->Point2[i] - this->Origin[i];
}
if ( !this->UpdateNormal(v1,v2) ) return;
//
// Set things up; allocate memory
//
numPts = (this->XResolution+1) * (this->YResolution+1);
numPolys = this->XResolution * this->YResolution;
newPoints = new vtkFloatPoints(numPts);
newNormals = new vtkFloatNormals(numPts);
newTCoords = new vtkFloatTCoords(numPts,2);
newPolys = new vtkCellArray;
newPolys->Allocate(newPolys->EstimateSize(numPolys,4));
//
// Generate points and point data
//
for (numPts=0, i=0; i<(this->YResolution+1); i++)
{
tc[1] = (float) i / this->YResolution;
for (j=0; j<(this->XResolution+1); j++)
{
tc[0] = (float) j / this->XResolution;
for ( ii=0; ii < 3; ii++)
{
x[ii] = this->Origin[ii] + tc[0]*v1[ii] + tc[1]*v2[ii];
}
newPoints->InsertPoint(numPts,x);
newTCoords->InsertTCoord(numPts,tc);
newNormals->InsertNormal(numPts++,this->Normal);
}
}
//
// Generate polygon connectivity
//
for (i=0; i<this->YResolution; i++)
{
for (j=0; j<this->XResolution; j++)
{
pts[0] = j + i*(this->XResolution+1);
pts[1] = pts[0] + 1;
pts[2] = pts[0] + this->XResolution + 2;
pts[3] = pts[0] + this->XResolution + 1;
newPolys->InsertNextCell(4,pts);
}
}
//
// Update ourselves and release memory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
output->SetPolys(newPolys);
newPolys->Delete();
}
// Description:
// Set the normal to the plane. Will modify the Origin, Point1, and Point2
// instance variables are necessary (i.e., rotate the plane around its center).
void vtkPlaneSource::SetNormal(float N[3])
{
float n[3], v1[3], v2[3], center[3];
float rotVector[3];
int i;
// compute plane axes
for ( i=0; i < 3; i++)
{
n[i] = N[i];
v1[i] = (this->Point1[i] - this->Origin[i]) / 2.0;
v2[i] = (this->Point2[i] - this->Origin[i]) / 2.0;
center[i] = this->Origin[i] + v1[i] + v2[i];
}
//make sure input is decent
if ( math.Normalize(n) == 0.0 )
{
vtkErrorMacro(<<"Specified zero normal");
return;
}
if ( !this->UpdateNormal(v1,v2) ) return;
//compute rotation vector
math.Cross(this->Normal,n,rotVector);
if ( math.Normalize(rotVector) == 0.0 ) return; //no rotation
// determine components of rotation around the three axes
}
// Description:
// Set the normal to the plane. Will modify the Origin, Point1, and Point2
// instance variables are necessary (i.e., rotate the plane around its center).
void vtkPlaneSource::SetNormal(float nx, float ny, float nz)
{
float n[3];
n[0] = nx; n[1] = ny; n[2] = nz;
this->SetNormal(n);
}
// Description:
// Translate the plane in the direction of the normal by the distance specified.
// Negative values move the plane in the opposite direction.
void vtkPlaneSource::Push(float distance)
{
if ( distance == 0.0 ) return;
for ( int i=0; i < 3; i++ )
{
this->Origin[i] += distance * this->Normal[i];
this->Point1[i] += distance * this->Normal[i];
this->Point2[i] += distance * this->Normal[i];
}
this->Modified();
}
// Protected method updates normals from two axes.
int vtkPlaneSource::UpdateNormal(float v1[3], float v2[3])
{
math.Cross(v1,v2,this->Normal);
if ( math.Normalize(this->Normal) == 0.0 )
{
vtkErrorMacro(<<"Bad plane coordinate system");
return 0;
}
else
{
return 1;
}
}
void vtkPlaneSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolySource::PrintSelf(os,indent);
os << indent << "X Resolution: " << this->XResolution << "\n";
os << indent << "Y Resolution: " << this->YResolution << "\n";
os << indent << "Origin: (" << this->Origin[0] << ", "
<< this->Origin[1] << ", "
<< this->Origin[2] << ")\n";
os << indent << "Point 1: (" << this->Point1[0] << ", "
<< this->Point1[1] << ", "
<< this->Point1[2] << ")\n";
os << indent << "Point 2: (" << this->Point2[0] << ", "
<< this->Point2[1] << ", "
<< this->Point2[2] << ")\n";
os << indent << "Normal: (" << this->Normal[0] << ", "
<< this->Normal[1] << ", "
<< this->Normal[2] << ")\n";
}
<commit_msg>ENH: Got Normal and Center working.<commit_after>/*=========================================================================
Program: Visualization Library
Module: vtkPlaneSource.cc
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute
this software and its documentation for any purpose, provided
that existing copyright notices are retained in all copies and that this
notice is included verbatim in any distributions. Additionally, the
authors grant permission to modify this software and its documentation for
any purpose, provided that such modifications are not distributed without
the explicit consent of the authors and that existing copyright notices are
retained in all copies.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
=========================================================================*/
#include "vtkPlaneSource.hh"
#include "vtkFloatPoints.hh"
#include "vtkFloatNormals.hh"
#include "vtkFloatTCoords.hh"
#include "vtkMath.hh"
#include "vtkTransform.hh"
static vtkMath math;
// Description:
// Construct plane perpendicular to z-axis, resolution 1x1, width and height 1.0,
// and centered at the origin.
vtkPlaneSource::vtkPlaneSource()
{
this->XResolution = 1;
this->YResolution = 1;
this->Origin[0] = this->Origin[1] = -0.5;
this->Origin[2] = 0.0;
this->Point1[0] = 0.5;
this->Point1[1] = -0.5;
this->Point1[2] = 0.0;
this->Point2[0] = -0.5;
this->Point2[1] = 0.5;
this->Point2[2] = 0.0;
this->Normal[2] = 1.0;
this->Normal[0] = this->Normal[1] = 0.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
}
// Description:
// Set the number of x-y subdivisions in the plane.
void vtkPlaneSource::SetResolution(const int xR, const int yR)
{
if ( xR != this->XResolution || yR != this->YResolution )
{
this->XResolution = xR;
this->YResolution = yR;
this->XResolution = (this->XResolution > 0 ? this->XResolution : 1);
this->YResolution = (this->YResolution > 0 ? this->YResolution : 1);
this->Modified();
}
}
void vtkPlaneSource::Execute()
{
float x[3], tc[2], v1[3], v2[3];
int pts[4];
int i, j, ii;
int numPts;
int numPolys;
vtkFloatPoints *newPoints;
vtkFloatNormals *newNormals;
vtkFloatTCoords *newTCoords;
vtkCellArray *newPolys;
vtkPolyData *output = this->GetOutput();
// Check input
for ( i=0; i < 3; i++ )
{
v1[i] = this->Point1[i] - this->Origin[i];
v2[i] = this->Point2[i] - this->Origin[i];
}
if ( !this->UpdatePlane(v1,v2) ) return;
//
// Set things up; allocate memory
//
numPts = (this->XResolution+1) * (this->YResolution+1);
numPolys = this->XResolution * this->YResolution;
newPoints = new vtkFloatPoints(numPts);
newNormals = new vtkFloatNormals(numPts);
newTCoords = new vtkFloatTCoords(numPts,2);
newPolys = new vtkCellArray;
newPolys->Allocate(newPolys->EstimateSize(numPolys,4));
//
// Generate points and point data
//
for (numPts=0, i=0; i<(this->YResolution+1); i++)
{
tc[1] = (float) i / this->YResolution;
for (j=0; j<(this->XResolution+1); j++)
{
tc[0] = (float) j / this->XResolution;
for ( ii=0; ii < 3; ii++)
{
x[ii] = this->Origin[ii] + tc[0]*v1[ii] + tc[1]*v2[ii];
}
newPoints->InsertPoint(numPts,x);
newTCoords->InsertTCoord(numPts,tc);
newNormals->InsertNormal(numPts++,this->Normal);
}
}
//
// Generate polygon connectivity
//
for (i=0; i<this->YResolution; i++)
{
for (j=0; j<this->XResolution; j++)
{
pts[0] = j + i*(this->XResolution+1);
pts[1] = pts[0] + 1;
pts[2] = pts[0] + this->XResolution + 2;
pts[3] = pts[0] + this->XResolution + 1;
newPolys->InsertNextCell(4,pts);
}
}
//
// Update ourselves and release memory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
output->SetPolys(newPolys);
newPolys->Delete();
}
// Description:
// Set the normal to the plane. Will modify the Origin, Point1, and Point2
// instance variables as necessary (i.e., rotate the plane around its center).
void vtkPlaneSource::SetNormal(float N[3])
{
float n[3], v1[3], v2[3], p[4];
float rotVector[3], theta;
int i;
vtkTransform transform;
// compute plane axes
for ( i=0; i < 3; i++)
{
n[i] = N[i];
v1[i] = this->Point1[i] - this->Origin[i];
v2[i] = this->Point2[i] - this->Origin[i];
}
//make sure input is decent
if ( math.Normalize(n) == 0.0 )
{
vtkErrorMacro(<<"Specified zero normal");
return;
}
if ( !this->UpdatePlane(v1,v2) ) return;
//compute rotation vector
math.Cross(this->Normal,n,rotVector);
if ( math.Normalize(rotVector) == 0.0 ) return; //no rotation
theta = acos((double)math.Dot(this->Normal,n)) / math.DegreesToRadians();
// create rotation matrix
transform.PostMultiply();
transform.Translate(-this->Center[0],-this->Center[1],-this->Center[2]);
transform.RotateWXYZ(theta,rotVector[0],rotVector[1],rotVector[2]);
transform.Translate(this->Center[0],this->Center[1],this->Center[2]);
// transform the three defining points
transform.SetPoint(this->Origin[0],this->Origin[1],this->Origin[2],1.0);
transform.GetPoint(p);
for (i=0; i < 3; i++) this->Origin[i] = p[i] / p[3];
transform.SetPoint(this->Point1[0],this->Point1[1],this->Point1[2],1.0);
transform.GetPoint(p);
for (i=0; i < 3; i++) this->Point1[i] = p[i] / p[3];
transform.SetPoint(this->Point2[0],this->Point2[1],this->Point2[2],1.0);
transform.GetPoint(p);
for (i=0; i < 3; i++) this->Point2[i] = p[i] / p[3];
this->Modified();
}
// Description:
// Set the normal to the plane. Will modify the Origin, Point1, and Point2
// instance variables as necessary (i.e., rotate the plane around its center).
void vtkPlaneSource::SetNormal(float nx, float ny, float nz)
{
float n[3];
n[0] = nx; n[1] = ny; n[2] = nz;
this->SetNormal(n);
}
// Description:
// Set the center of the plane. Will modify the Origin, Point1, and Point2
// instance variables as necessary (i.e., translate the plane).
void vtkPlaneSource::SetCenter(float center[3])
{
if ( this->Center[0] == center[0] && this->Center[1] == center[1] &&
this->Center[2] == center[2] )
{
return; //no change
}
else
{
float d;
for ( int i=0; i < 3; i++ )
{
d = center[i] - this->Center[i];
this->Center[i] = center[i];
this->Origin[i] += d;
this->Point1[i] += d;
this->Point2[i] += d;
}
this->Modified();
}
}
// Description:
// Set the center of the plane. Will modify the Origin, Point1, and Point2
// instance variables as necessary (i.e., translate the plane).
void vtkPlaneSource::SetCenter(float x, float y, float z)
{
float center[3];
center[0] = x; center[1] = y; center[2] = z;
this->SetCenter(center);
}
// Description:
// Translate the plane in the direction of the normal by the distance specified.
// Negative values move the plane in the opposite direction.
void vtkPlaneSource::Push(float distance)
{
if ( distance == 0.0 ) return;
for ( int i=0; i < 3; i++ )
{
this->Origin[i] += distance * this->Normal[i];
this->Point1[i] += distance * this->Normal[i];
this->Point2[i] += distance * this->Normal[i];
}
this->Modified();
}
// Protected method updates normals and plane center from two axes.
int vtkPlaneSource::UpdatePlane(float v1[3], float v2[3])
{
// set plane center
for ( int i=0; i < 3; i++ )
{
this->Center[i] = this->Origin[i] + 0.5*(v1[i] + v2[i]);
}
// set plane normal
math.Cross(v1,v2,this->Normal);
if ( math.Normalize(this->Normal) == 0.0 )
{
vtkErrorMacro(<<"Bad plane coordinate system");
return 0;
}
else
{
return 1;
}
}
void vtkPlaneSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolySource::PrintSelf(os,indent);
os << indent << "X Resolution: " << this->XResolution << "\n";
os << indent << "Y Resolution: " << this->YResolution << "\n";
os << indent << "Origin: (" << this->Origin[0] << ", "
<< this->Origin[1] << ", "
<< this->Origin[2] << ")\n";
os << indent << "Point 1: (" << this->Point1[0] << ", "
<< this->Point1[1] << ", "
<< this->Point1[2] << ")\n";
os << indent << "Point 2: (" << this->Point2[0] << ", "
<< this->Point2[1] << ", "
<< this->Point2[2] << ")\n";
os << indent << "Normal: (" << this->Normal[0] << ", "
<< this->Normal[1] << ", "
<< this->Normal[2] << ")\n";
os << indent << "Center: (" << this->Center[0] << ", "
<< this->Center[1] << ", "
<< this->Center[2] << ")\n";
}
<|endoftext|> |
<commit_before>#include <assert.h>
#include <stdio.h>
#include "../ClipperUtils.hpp"
#include "../Geometry.hpp"
#include "../Layer.hpp"
#include "../Print.hpp"
#include "../PrintConfig.hpp"
#include "../Surface.hpp"
#include "FillBase.hpp"
namespace Slic3r {
// Generate infills for Slic3r::Layer::Region.
// The Slic3r::Layer::Region at this point of time may contain
// surfaces of various types (internal/bridge/top/bottom/solid).
// The infills are generated on the groups of surfaces with a compatible type.
// Returns an array of Slic3r::ExtrusionPath::Collection objects containing the infills generaed now
// and the thin fills generated by generate_perimeters().
void make_fill(LayerRegion &layerm, ExtrusionEntityCollection &out)
{
// Slic3r::debugf "Filling layer %d:\n", $layerm->layer->id;
double fill_density = layerm.region()->config.fill_density;
Flow infill_flow = layerm.flow(frInfill);
Flow solid_infill_flow = layerm.flow(frSolidInfill);
Flow top_solid_infill_flow = layerm.flow(frTopSolidInfill);
Surfaces surfaces;
// merge adjacent surfaces
// in case of bridge surfaces, the ones with defined angle will be attached to the ones
// without any angle (shouldn't this logic be moved to process_external_surfaces()?)
{
SurfacesPtr surfaces_with_bridge_angle;
surfaces_with_bridge_angle.reserve(layerm.fill_surfaces.surfaces.size());
for (Surfaces::iterator it = layerm.fill_surfaces.surfaces.begin(); it != layerm.fill_surfaces.surfaces.end(); ++ it)
if (it->bridge_angle >= 0)
surfaces_with_bridge_angle.push_back(&(*it));
// group surfaces by distinct properties (equal surface_type, thickness, thickness_layers, bridge_angle)
// group is of type Slic3r::SurfaceCollection
//FIXME: Use some smart heuristics to merge similar surfaces to eliminate tiny regions.
std::vector<SurfacesPtr> groups;
layerm.fill_surfaces.group(&groups);
// merge compatible groups (we can generate continuous infill for them)
{
// cache flow widths and patterns used for all solid groups
// (we'll use them for comparing compatible groups)
std::vector<char> is_solid(groups.size(), false);
std::vector<float> fw(groups.size(), 0.f);
std::vector<int> pattern(groups.size(), -1);
for (size_t i = 0; i < groups.size(); ++ i) {
// we can only merge solid non-bridge surfaces, so discard
// non-solid surfaces
const Surface &surface = *groups[i].front();
if (surface.is_solid() && (!surface.is_bridge() || layerm.layer()->id() == 0)) {
is_solid[i] = true;
fw[i] = (surface.surface_type == stTop) ? top_solid_infill_flow.width : solid_infill_flow.width;
pattern[i] = surface.is_external() ? layerm.region()->config.external_fill_pattern.value : ipRectilinear;
}
}
// loop through solid groups
for (size_t i = 0; i < groups.size(); ++ i) {
if (is_solid[i]) {
// find compatible groups and append them to this one
for (size_t j = i + 1; j < groups.size(); ++ j) {
if (is_solid[j] && fw[i] == fw[j] && pattern[i] == pattern[j]) {
// groups are compatible, merge them
groups[i].insert(groups[i].end(), groups[j].begin(), groups[j].end());
groups.erase(groups.begin() + j);
is_solid.erase(is_solid.begin() + j);
fw.erase(fw.begin() + j);
pattern.erase(pattern.begin() + j);
}
}
}
}
}
// Give priority to bridges. Process the bridges in the first round, the rest of the surfaces in the 2nd round.
for (size_t round = 0; round < 2; ++ round) {
for (std::vector<SurfacesPtr>::iterator it_group = groups.begin(); it_group != groups.end(); ++ it_group) {
const SurfacesPtr &group = *it_group;
bool is_bridge = group.front()->bridge_angle >= 0;
if (is_bridge != (round == 0))
continue;
// Make a union of polygons defining the infiill regions of a group, use a safety offset.
Polygons union_p = union_(to_polygons(*it_group), true);
// Subtract surfaces having a defined bridge_angle from any other, use a safety offset.
if (! surfaces_with_bridge_angle.empty() && it_group->front()->bridge_angle < 0)
union_p = diff(union_p, to_polygons(surfaces_with_bridge_angle), true);
// subtract any other surface already processed
//FIXME Vojtech: Because the bridge surfaces came first, they are subtracted twice!
ExPolygons union_expolys = diff_ex(union_p, to_polygons(surfaces), true);
for (ExPolygons::const_iterator it_expoly = union_expolys.begin(); it_expoly != union_expolys.end(); ++ it_expoly)
surfaces.push_back(Surface(*it_group->front(), *it_expoly));
}
}
}
// we need to detect any narrow surfaces that might collapse
// when adding spacing below
// such narrow surfaces are often generated in sloping walls
// by bridge_over_infill() and combine_infill() as a result of the
// subtraction of the combinable area from the layer infill area,
// which leaves small areas near the perimeters
// we are going to grow such regions by overlapping them with the void (if any)
// TODO: detect and investigate whether there could be narrow regions without
// any void neighbors
{
coord_t distance_between_surfaces = std::max(
std::max(infill_flow.scaled_spacing(), solid_infill_flow.scaled_spacing()),
top_solid_infill_flow.scaled_spacing());
Polygons surfaces_polygons = to_polygons(surfaces);
Polygons collapsed = diff(
surfaces_polygons,
offset2(surfaces_polygons, -distance_between_surfaces/2, +distance_between_surfaces/2),
true);
Polygons to_subtract;
to_subtract.reserve(collapsed.size() + number_polygons(surfaces));
for (Surfaces::const_iterator it_surface = surfaces.begin(); it_surface != surfaces.end(); ++ it_surface)
if (it_surface->surface_type == stInternalVoid)
polygons_append(to_subtract, *it_surface);
polygons_append(to_subtract, collapsed);
surfaces_append(
surfaces,
intersection_ex(
offset(collapsed, distance_between_surfaces),
to_subtract,
true),
stInternalSolid);
}
if (0) {
// require "Slic3r/SVG.pm";
// Slic3r::SVG::output("fill_" . $layerm->print_z . ".svg",
// expolygons => [ map $_->expolygon, grep !$_->is_solid, @surfaces ],
// red_expolygons => [ map $_->expolygon, grep $_->is_solid, @surfaces ],
// );
}
for (Surfaces::const_iterator surface_it = surfaces.begin(); surface_it != surfaces.end(); ++ surface_it) {
const Surface &surface = *surface_it;
if (surface.surface_type == stInternalVoid)
continue;
InfillPattern fill_pattern = layerm.region()->config.fill_pattern.value;
double density = fill_density;
FlowRole role = (surface.surface_type == stTop) ? frTopSolidInfill :
(surface.is_solid() ? frSolidInfill : frInfill);
bool is_bridge = layerm.layer()->id() > 0 && surface.is_bridge();
if (surface.is_solid()) {
density = 100;
fill_pattern = (surface.is_external() && ! is_bridge) ?
layerm.region()->config.external_fill_pattern.value :
ipRectilinear;
} else if (density <= 0)
continue;
// get filler object
std::auto_ptr<Fill> f = std::auto_ptr<Fill>(Fill::new_from_type(fill_pattern));
f->set_bounding_box(layerm.layer()->object()->bounding_box());
// calculate the actual flow we'll be using for this infill
coordf_t h = (surface.thickness == -1) ? layerm.layer()->height : surface.thickness;
Flow flow = layerm.region()->flow(
role,
h,
is_bridge || f->use_bridge_flow(), // bridge flow?
layerm.layer()->id() == 0, // first layer?
-1, // auto width
*layerm.layer()->object()
);
// calculate flow spacing for infill pattern generation
bool using_internal_flow = false;
if (! surface.is_solid() && ! is_bridge) {
// it's internal infill, so we can calculate a generic flow spacing
// for all layers, for avoiding the ugly effect of
// misaligned infill on first layer because of different extrusion width and
// layer height
Flow internal_flow = layerm.region()->flow(
frInfill,
layerm.layer()->object()->config.layer_height.value, // TODO: handle infill_every_layers?
false, // no bridge
false, // no first layer
-1, // auto width
*layerm.layer()->object()
);
f->spacing = internal_flow.spacing();
using_internal_flow = 1;
} else {
f->spacing = flow.spacing();
}
double link_max_length = 0.;
if (! is_bridge) {
link_max_length = layerm.region()->config.get_abs_value(surface.is_external() ? "external_fill_link_max_length" : "fill_link_max_length", flow.spacing());
// printf("flow spacing: %f, is_external: %d, link_max_length: %lf\n", flow.spacing(), int(surface.is_external()), link_max_length);
}
f->layer_id = layerm.layer()->id();
f->z = layerm.layer()->print_z;
f->angle = Geometry::deg2rad(layerm.region()->config.fill_angle.value);
// Maximum length of the perimeter segment linking two infill lines.
f->link_max_length = scale_(link_max_length);
// Used by the concentric infill pattern to clip the loops to create extrusion paths.
f->loop_clipping = scale_(flow.nozzle_diameter) * LOOP_CLIPPING_LENGTH_OVER_NOZZLE_DIAMETER;
// f->layer_height = h;
// apply half spacing using this flow's own spacing and generate infill
FillParams params;
params.density = 0.01 * density;
params.dont_adjust = true;
Polylines polylines = f->fill_surface(&surface, params);
if (polylines.empty())
continue;
// calculate actual flow from spacing (which might have been adjusted by the infill
// pattern generator)
if (using_internal_flow) {
// if we used the internal flow we're not doing a solid infill
// so we can safely ignore the slight variation that might have
// been applied to $f->flow_spacing
} else {
flow = Flow::new_from_spacing(f->spacing, flow.nozzle_diameter, h, is_bridge || f->use_bridge_flow());
}
// save into layer
{
ExtrusionRole role = is_bridge ? erBridgeInfill :
(surface.is_solid() ? ((surface.surface_type == stTop) ? erTopSolidInfill : erSolidInfill) : erInternalInfill);
ExtrusionEntityCollection &collection = *(new ExtrusionEntityCollection());
out.entities.push_back(&collection);
// Only concentric fills are not sorted.
collection.no_sort = f->no_sort();
for (Polylines::iterator it = polylines.begin(); it != polylines.end(); ++ it) {
ExtrusionPath *path = new ExtrusionPath(role);
collection.entities.push_back(path);
path->polyline.points.swap(it->points);
path->mm3_per_mm = flow.mm3_per_mm();
path->width = flow.width,
path->height = flow.height;
}
}
}
// add thin fill regions
// thin_fills are of C++ Slic3r::ExtrusionEntityCollection, perl type Slic3r::ExtrusionPath::Collection
// Unpacks the collection, creates multiple collections per path.
// The path type could be ExtrusionPath, ExtrusionLoop or ExtrusionEntityCollection.
// Why the paths are unpacked?
for (ExtrusionEntitiesPtr::iterator thin_fill = layerm.thin_fills.entities.begin(); thin_fill != layerm.thin_fills.entities.end(); ++ thin_fill) {
#if 0
out.entities.push_back((*thin_fill)->clone());
assert(dynamic_cast<ExtrusionEntityCollection*>(out.entities.back()) != NULL);
#else
ExtrusionEntityCollection &collection = *(new ExtrusionEntityCollection());
out.entities.push_back(&collection);
collection.entities.push_back((*thin_fill)->clone());
#endif
}
}
} // namespace Slic3r
<commit_msg>Missing #include <memory><commit_after>#include <assert.h>
#include <stdio.h>
#include <memory>
#include "../ClipperUtils.hpp"
#include "../Geometry.hpp"
#include "../Layer.hpp"
#include "../Print.hpp"
#include "../PrintConfig.hpp"
#include "../Surface.hpp"
#include "FillBase.hpp"
namespace Slic3r {
// Generate infills for Slic3r::Layer::Region.
// The Slic3r::Layer::Region at this point of time may contain
// surfaces of various types (internal/bridge/top/bottom/solid).
// The infills are generated on the groups of surfaces with a compatible type.
// Returns an array of Slic3r::ExtrusionPath::Collection objects containing the infills generaed now
// and the thin fills generated by generate_perimeters().
void make_fill(LayerRegion &layerm, ExtrusionEntityCollection &out)
{
// Slic3r::debugf "Filling layer %d:\n", $layerm->layer->id;
double fill_density = layerm.region()->config.fill_density;
Flow infill_flow = layerm.flow(frInfill);
Flow solid_infill_flow = layerm.flow(frSolidInfill);
Flow top_solid_infill_flow = layerm.flow(frTopSolidInfill);
Surfaces surfaces;
// merge adjacent surfaces
// in case of bridge surfaces, the ones with defined angle will be attached to the ones
// without any angle (shouldn't this logic be moved to process_external_surfaces()?)
{
SurfacesPtr surfaces_with_bridge_angle;
surfaces_with_bridge_angle.reserve(layerm.fill_surfaces.surfaces.size());
for (Surfaces::iterator it = layerm.fill_surfaces.surfaces.begin(); it != layerm.fill_surfaces.surfaces.end(); ++ it)
if (it->bridge_angle >= 0)
surfaces_with_bridge_angle.push_back(&(*it));
// group surfaces by distinct properties (equal surface_type, thickness, thickness_layers, bridge_angle)
// group is of type Slic3r::SurfaceCollection
//FIXME: Use some smart heuristics to merge similar surfaces to eliminate tiny regions.
std::vector<SurfacesPtr> groups;
layerm.fill_surfaces.group(&groups);
// merge compatible groups (we can generate continuous infill for them)
{
// cache flow widths and patterns used for all solid groups
// (we'll use them for comparing compatible groups)
std::vector<char> is_solid(groups.size(), false);
std::vector<float> fw(groups.size(), 0.f);
std::vector<int> pattern(groups.size(), -1);
for (size_t i = 0; i < groups.size(); ++ i) {
// we can only merge solid non-bridge surfaces, so discard
// non-solid surfaces
const Surface &surface = *groups[i].front();
if (surface.is_solid() && (!surface.is_bridge() || layerm.layer()->id() == 0)) {
is_solid[i] = true;
fw[i] = (surface.surface_type == stTop) ? top_solid_infill_flow.width : solid_infill_flow.width;
pattern[i] = surface.is_external() ? layerm.region()->config.external_fill_pattern.value : ipRectilinear;
}
}
// loop through solid groups
for (size_t i = 0; i < groups.size(); ++ i) {
if (is_solid[i]) {
// find compatible groups and append them to this one
for (size_t j = i + 1; j < groups.size(); ++ j) {
if (is_solid[j] && fw[i] == fw[j] && pattern[i] == pattern[j]) {
// groups are compatible, merge them
groups[i].insert(groups[i].end(), groups[j].begin(), groups[j].end());
groups.erase(groups.begin() + j);
is_solid.erase(is_solid.begin() + j);
fw.erase(fw.begin() + j);
pattern.erase(pattern.begin() + j);
}
}
}
}
}
// Give priority to bridges. Process the bridges in the first round, the rest of the surfaces in the 2nd round.
for (size_t round = 0; round < 2; ++ round) {
for (std::vector<SurfacesPtr>::iterator it_group = groups.begin(); it_group != groups.end(); ++ it_group) {
const SurfacesPtr &group = *it_group;
bool is_bridge = group.front()->bridge_angle >= 0;
if (is_bridge != (round == 0))
continue;
// Make a union of polygons defining the infiill regions of a group, use a safety offset.
Polygons union_p = union_(to_polygons(*it_group), true);
// Subtract surfaces having a defined bridge_angle from any other, use a safety offset.
if (! surfaces_with_bridge_angle.empty() && it_group->front()->bridge_angle < 0)
union_p = diff(union_p, to_polygons(surfaces_with_bridge_angle), true);
// subtract any other surface already processed
//FIXME Vojtech: Because the bridge surfaces came first, they are subtracted twice!
ExPolygons union_expolys = diff_ex(union_p, to_polygons(surfaces), true);
for (ExPolygons::const_iterator it_expoly = union_expolys.begin(); it_expoly != union_expolys.end(); ++ it_expoly)
surfaces.push_back(Surface(*it_group->front(), *it_expoly));
}
}
}
// we need to detect any narrow surfaces that might collapse
// when adding spacing below
// such narrow surfaces are often generated in sloping walls
// by bridge_over_infill() and combine_infill() as a result of the
// subtraction of the combinable area from the layer infill area,
// which leaves small areas near the perimeters
// we are going to grow such regions by overlapping them with the void (if any)
// TODO: detect and investigate whether there could be narrow regions without
// any void neighbors
{
coord_t distance_between_surfaces = std::max(
std::max(infill_flow.scaled_spacing(), solid_infill_flow.scaled_spacing()),
top_solid_infill_flow.scaled_spacing());
Polygons surfaces_polygons = to_polygons(surfaces);
Polygons collapsed = diff(
surfaces_polygons,
offset2(surfaces_polygons, -distance_between_surfaces/2, +distance_between_surfaces/2),
true);
Polygons to_subtract;
to_subtract.reserve(collapsed.size() + number_polygons(surfaces));
for (Surfaces::const_iterator it_surface = surfaces.begin(); it_surface != surfaces.end(); ++ it_surface)
if (it_surface->surface_type == stInternalVoid)
polygons_append(to_subtract, *it_surface);
polygons_append(to_subtract, collapsed);
surfaces_append(
surfaces,
intersection_ex(
offset(collapsed, distance_between_surfaces),
to_subtract,
true),
stInternalSolid);
}
if (0) {
// require "Slic3r/SVG.pm";
// Slic3r::SVG::output("fill_" . $layerm->print_z . ".svg",
// expolygons => [ map $_->expolygon, grep !$_->is_solid, @surfaces ],
// red_expolygons => [ map $_->expolygon, grep $_->is_solid, @surfaces ],
// );
}
for (Surfaces::const_iterator surface_it = surfaces.begin(); surface_it != surfaces.end(); ++ surface_it) {
const Surface &surface = *surface_it;
if (surface.surface_type == stInternalVoid)
continue;
InfillPattern fill_pattern = layerm.region()->config.fill_pattern.value;
double density = fill_density;
FlowRole role = (surface.surface_type == stTop) ? frTopSolidInfill :
(surface.is_solid() ? frSolidInfill : frInfill);
bool is_bridge = layerm.layer()->id() > 0 && surface.is_bridge();
if (surface.is_solid()) {
density = 100;
fill_pattern = (surface.is_external() && ! is_bridge) ?
layerm.region()->config.external_fill_pattern.value :
ipRectilinear;
} else if (density <= 0)
continue;
// get filler object
std::auto_ptr<Fill> f = std::auto_ptr<Fill>(Fill::new_from_type(fill_pattern));
f->set_bounding_box(layerm.layer()->object()->bounding_box());
// calculate the actual flow we'll be using for this infill
coordf_t h = (surface.thickness == -1) ? layerm.layer()->height : surface.thickness;
Flow flow = layerm.region()->flow(
role,
h,
is_bridge || f->use_bridge_flow(), // bridge flow?
layerm.layer()->id() == 0, // first layer?
-1, // auto width
*layerm.layer()->object()
);
// calculate flow spacing for infill pattern generation
bool using_internal_flow = false;
if (! surface.is_solid() && ! is_bridge) {
// it's internal infill, so we can calculate a generic flow spacing
// for all layers, for avoiding the ugly effect of
// misaligned infill on first layer because of different extrusion width and
// layer height
Flow internal_flow = layerm.region()->flow(
frInfill,
layerm.layer()->object()->config.layer_height.value, // TODO: handle infill_every_layers?
false, // no bridge
false, // no first layer
-1, // auto width
*layerm.layer()->object()
);
f->spacing = internal_flow.spacing();
using_internal_flow = 1;
} else {
f->spacing = flow.spacing();
}
double link_max_length = 0.;
if (! is_bridge) {
link_max_length = layerm.region()->config.get_abs_value(surface.is_external() ? "external_fill_link_max_length" : "fill_link_max_length", flow.spacing());
// printf("flow spacing: %f, is_external: %d, link_max_length: %lf\n", flow.spacing(), int(surface.is_external()), link_max_length);
}
f->layer_id = layerm.layer()->id();
f->z = layerm.layer()->print_z;
f->angle = Geometry::deg2rad(layerm.region()->config.fill_angle.value);
// Maximum length of the perimeter segment linking two infill lines.
f->link_max_length = scale_(link_max_length);
// Used by the concentric infill pattern to clip the loops to create extrusion paths.
f->loop_clipping = scale_(flow.nozzle_diameter) * LOOP_CLIPPING_LENGTH_OVER_NOZZLE_DIAMETER;
// f->layer_height = h;
// apply half spacing using this flow's own spacing and generate infill
FillParams params;
params.density = 0.01 * density;
params.dont_adjust = true;
Polylines polylines = f->fill_surface(&surface, params);
if (polylines.empty())
continue;
// calculate actual flow from spacing (which might have been adjusted by the infill
// pattern generator)
if (using_internal_flow) {
// if we used the internal flow we're not doing a solid infill
// so we can safely ignore the slight variation that might have
// been applied to $f->flow_spacing
} else {
flow = Flow::new_from_spacing(f->spacing, flow.nozzle_diameter, h, is_bridge || f->use_bridge_flow());
}
// save into layer
{
ExtrusionRole role = is_bridge ? erBridgeInfill :
(surface.is_solid() ? ((surface.surface_type == stTop) ? erTopSolidInfill : erSolidInfill) : erInternalInfill);
ExtrusionEntityCollection &collection = *(new ExtrusionEntityCollection());
out.entities.push_back(&collection);
// Only concentric fills are not sorted.
collection.no_sort = f->no_sort();
for (Polylines::iterator it = polylines.begin(); it != polylines.end(); ++ it) {
ExtrusionPath *path = new ExtrusionPath(role);
collection.entities.push_back(path);
path->polyline.points.swap(it->points);
path->mm3_per_mm = flow.mm3_per_mm();
path->width = flow.width,
path->height = flow.height;
}
}
}
// add thin fill regions
// thin_fills are of C++ Slic3r::ExtrusionEntityCollection, perl type Slic3r::ExtrusionPath::Collection
// Unpacks the collection, creates multiple collections per path.
// The path type could be ExtrusionPath, ExtrusionLoop or ExtrusionEntityCollection.
// Why the paths are unpacked?
for (ExtrusionEntitiesPtr::iterator thin_fill = layerm.thin_fills.entities.begin(); thin_fill != layerm.thin_fills.entities.end(); ++ thin_fill) {
#if 0
out.entities.push_back((*thin_fill)->clone());
assert(dynamic_cast<ExtrusionEntityCollection*>(out.entities.back()) != NULL);
#else
ExtrusionEntityCollection &collection = *(new ExtrusionEntityCollection());
out.entities.push_back(&collection);
collection.entities.push_back((*thin_fill)->clone());
#endif
}
}
} // namespace Slic3r
<|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 <stdio.h>
#include <stdlib.h>
#include <cassert>
#include "ppapi/c/ppb_gamepad.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/size.h"
#include "ppapi/cpp/var.h"
#include "ppapi/utility/completion_callback_factory.h"
#ifdef WIN32
#undef min
#undef max
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif
class GamepadInstance : public pp::Instance {
public:
explicit GamepadInstance(PP_Instance instance);
virtual ~GamepadInstance();
// Update the graphics context to the new size, and regenerate |pixel_buffer_|
// to fit the new size as well.
virtual void DidChangeView(const pp::View& view);
// Flushes its contents of |pixel_buffer_| to the 2D graphics context.
void Paint();
int width() const {
return pixel_buffer_ ? pixel_buffer_->size().width() : 0;
}
int height() const {
return pixel_buffer_ ? pixel_buffer_->size().height() : 0;
}
// Indicate whether a flush is pending. This can only be called from the
// main thread; it is not thread safe.
bool flush_pending() const { return flush_pending_; }
void set_flush_pending(bool flag) { flush_pending_ = flag; }
private:
// Create and initialize the 2D context used for drawing.
void CreateContext(const pp::Size& size);
// Destroy the 2D drawing context.
void DestroyContext();
// Push the pixels to the browser, then attempt to flush the 2D context. If
// there is a pending flush on the 2D context, then update the pixels only
// and do not flush.
void FlushPixelBuffer();
void FlushCallback(int32_t result);
bool IsContextValid() const { return graphics_2d_context_ != NULL; }
pp::CompletionCallbackFactory<GamepadInstance> callback_factory_;
pp::Graphics2D* graphics_2d_context_;
pp::ImageData* pixel_buffer_;
const PPB_Gamepad* gamepad_;
bool flush_pending_;
};
GamepadInstance::GamepadInstance(PP_Instance instance)
: pp::Instance(instance),
callback_factory_(this),
graphics_2d_context_(NULL),
pixel_buffer_(NULL),
flush_pending_(false) {
pp::Module* module = pp::Module::Get();
assert(module);
gamepad_ = static_cast<const PPB_Gamepad*>(
module->GetBrowserInterface(PPB_GAMEPAD_INTERFACE));
assert(gamepad_);
}
GamepadInstance::~GamepadInstance() {
DestroyContext();
delete pixel_buffer_;
}
void GamepadInstance::DidChangeView(const pp::View& view) {
pp::Rect position = view.GetRect();
if (position.size().width() == width() &&
position.size().height() == height())
return; // Size didn't change, no need to update anything.
// Create a new device context with the new size.
DestroyContext();
CreateContext(position.size());
// Delete the old pixel buffer and create a new one.
delete pixel_buffer_;
pixel_buffer_ = NULL;
if (graphics_2d_context_ != NULL) {
pixel_buffer_ = new pp::ImageData(this,
PP_IMAGEDATAFORMAT_BGRA_PREMUL,
graphics_2d_context_->size(),
false);
}
Paint();
}
void FillRect(pp::ImageData* image,
int left,
int top,
int width,
int height,
uint32_t color) {
for (int y = std::max(0, top);
y < std::min(image->size().height() - 1, top + height);
y++) {
for (int x = std::max(0, left);
x < std::min(image->size().width() - 1, left + width);
x++)
*image->GetAddr32(pp::Point(x, y)) = color;
}
}
void GamepadInstance::Paint() {
// Clear the background.
FillRect(pixel_buffer_, 0, 0, width(), height(), 0xfff0f0f0);
// Get current gamepad data.
PP_GamepadsSampleData gamepad_data;
gamepad_->Sample(pp_instance(), &gamepad_data);
// Draw the current state for each connected gamepad.
for (size_t p = 0; p < gamepad_data.length; ++p) {
int width2 = width() / gamepad_data.length / 2;
int height2 = height() / 2;
int offset = width2 * 2 * p;
PP_GamepadSampleData& pad = gamepad_data.items[p];
if (!pad.connected)
continue;
// Draw axes.
for (size_t i = 0; i < pad.axes_length; i += 2) {
int x = static_cast<int>(pad.axes[i + 0] * width2 + width2) + offset;
int y = static_cast<int>(pad.axes[i + 1] * height2 + height2);
uint32_t box_bgra = 0x80000000; // Alpha 50%.
FillRect(pixel_buffer_, x - 3, y - 3, 7, 7, box_bgra);
}
// Draw buttons.
for (size_t i = 0; i < pad.buttons_length; ++i) {
float button_val = pad.buttons[i];
uint32_t colour = static_cast<uint32_t>((button_val * 192) + 63) << 24;
int x = i * 8 + 10 + offset;
int y = 10;
FillRect(pixel_buffer_, x - 3, y - 3, 7, 7, colour);
}
}
// Output to the screen.
FlushPixelBuffer();
}
void GamepadInstance::CreateContext(const pp::Size& size) {
if (IsContextValid())
return;
graphics_2d_context_ = new pp::Graphics2D(this, size, false);
if (!BindGraphics(*graphics_2d_context_)) {
printf("Couldn't bind the device context\n");
}
}
void GamepadInstance::DestroyContext() {
if (!IsContextValid())
return;
delete graphics_2d_context_;
graphics_2d_context_ = NULL;
}
void GamepadInstance::FlushPixelBuffer() {
if (!IsContextValid())
return;
// Note that the pixel lock is held while the buffer is copied into the
// device context and then flushed.
graphics_2d_context_->PaintImageData(*pixel_buffer_, pp::Point());
if (flush_pending())
return;
set_flush_pending(true);
graphics_2d_context_->Flush(
callback_factory_.NewCallback(&GamepadInstance::FlushCallback));
}
void GamepadInstance::FlushCallback(int32_t result) {
set_flush_pending(false);
Paint();
}
class GamepadModule : public pp::Module {
public:
GamepadModule() : pp::Module() {}
virtual ~GamepadModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new GamepadInstance(instance);
}
};
namespace pp {
Module* CreateModule() { return new GamepadModule(); }
} // namespace pp
<commit_msg>[NaCl SDK] Fix gamepad example for msvc 2013<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 <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cassert>
#include "ppapi/c/ppb_gamepad.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/size.h"
#include "ppapi/cpp/var.h"
#include "ppapi/utility/completion_callback_factory.h"
#ifdef WIN32
#undef min
#undef max
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif
class GamepadInstance : public pp::Instance {
public:
explicit GamepadInstance(PP_Instance instance);
virtual ~GamepadInstance();
// Update the graphics context to the new size, and regenerate |pixel_buffer_|
// to fit the new size as well.
virtual void DidChangeView(const pp::View& view);
// Flushes its contents of |pixel_buffer_| to the 2D graphics context.
void Paint();
int width() const {
return pixel_buffer_ ? pixel_buffer_->size().width() : 0;
}
int height() const {
return pixel_buffer_ ? pixel_buffer_->size().height() : 0;
}
// Indicate whether a flush is pending. This can only be called from the
// main thread; it is not thread safe.
bool flush_pending() const { return flush_pending_; }
void set_flush_pending(bool flag) { flush_pending_ = flag; }
private:
// Create and initialize the 2D context used for drawing.
void CreateContext(const pp::Size& size);
// Destroy the 2D drawing context.
void DestroyContext();
// Push the pixels to the browser, then attempt to flush the 2D context. If
// there is a pending flush on the 2D context, then update the pixels only
// and do not flush.
void FlushPixelBuffer();
void FlushCallback(int32_t result);
bool IsContextValid() const { return graphics_2d_context_ != NULL; }
pp::CompletionCallbackFactory<GamepadInstance> callback_factory_;
pp::Graphics2D* graphics_2d_context_;
pp::ImageData* pixel_buffer_;
const PPB_Gamepad* gamepad_;
bool flush_pending_;
};
GamepadInstance::GamepadInstance(PP_Instance instance)
: pp::Instance(instance),
callback_factory_(this),
graphics_2d_context_(NULL),
pixel_buffer_(NULL),
flush_pending_(false) {
pp::Module* module = pp::Module::Get();
assert(module);
gamepad_ = static_cast<const PPB_Gamepad*>(
module->GetBrowserInterface(PPB_GAMEPAD_INTERFACE));
assert(gamepad_);
}
GamepadInstance::~GamepadInstance() {
DestroyContext();
delete pixel_buffer_;
}
void GamepadInstance::DidChangeView(const pp::View& view) {
pp::Rect position = view.GetRect();
if (position.size().width() == width() &&
position.size().height() == height())
return; // Size didn't change, no need to update anything.
// Create a new device context with the new size.
DestroyContext();
CreateContext(position.size());
// Delete the old pixel buffer and create a new one.
delete pixel_buffer_;
pixel_buffer_ = NULL;
if (graphics_2d_context_ != NULL) {
pixel_buffer_ = new pp::ImageData(this,
PP_IMAGEDATAFORMAT_BGRA_PREMUL,
graphics_2d_context_->size(),
false);
}
Paint();
}
void FillRect(pp::ImageData* image,
int left,
int top,
int width,
int height,
uint32_t color) {
for (int y = std::max(0, top);
y < std::min(image->size().height() - 1, top + height);
y++) {
for (int x = std::max(0, left);
x < std::min(image->size().width() - 1, left + width);
x++)
*image->GetAddr32(pp::Point(x, y)) = color;
}
}
void GamepadInstance::Paint() {
// Clear the background.
FillRect(pixel_buffer_, 0, 0, width(), height(), 0xfff0f0f0);
// Get current gamepad data.
PP_GamepadsSampleData gamepad_data;
gamepad_->Sample(pp_instance(), &gamepad_data);
// Draw the current state for each connected gamepad.
for (size_t p = 0; p < gamepad_data.length; ++p) {
int width2 = width() / gamepad_data.length / 2;
int height2 = height() / 2;
int offset = width2 * 2 * p;
PP_GamepadSampleData& pad = gamepad_data.items[p];
if (!pad.connected)
continue;
// Draw axes.
for (size_t i = 0; i < pad.axes_length; i += 2) {
int x = static_cast<int>(pad.axes[i + 0] * width2 + width2) + offset;
int y = static_cast<int>(pad.axes[i + 1] * height2 + height2);
uint32_t box_bgra = 0x80000000; // Alpha 50%.
FillRect(pixel_buffer_, x - 3, y - 3, 7, 7, box_bgra);
}
// Draw buttons.
for (size_t i = 0; i < pad.buttons_length; ++i) {
float button_val = pad.buttons[i];
uint32_t colour = static_cast<uint32_t>((button_val * 192) + 63) << 24;
int x = i * 8 + 10 + offset;
int y = 10;
FillRect(pixel_buffer_, x - 3, y - 3, 7, 7, colour);
}
}
// Output to the screen.
FlushPixelBuffer();
}
void GamepadInstance::CreateContext(const pp::Size& size) {
if (IsContextValid())
return;
graphics_2d_context_ = new pp::Graphics2D(this, size, false);
if (!BindGraphics(*graphics_2d_context_)) {
printf("Couldn't bind the device context\n");
}
}
void GamepadInstance::DestroyContext() {
if (!IsContextValid())
return;
delete graphics_2d_context_;
graphics_2d_context_ = NULL;
}
void GamepadInstance::FlushPixelBuffer() {
if (!IsContextValid())
return;
// Note that the pixel lock is held while the buffer is copied into the
// device context and then flushed.
graphics_2d_context_->PaintImageData(*pixel_buffer_, pp::Point());
if (flush_pending())
return;
set_flush_pending(true);
graphics_2d_context_->Flush(
callback_factory_.NewCallback(&GamepadInstance::FlushCallback));
}
void GamepadInstance::FlushCallback(int32_t result) {
set_flush_pending(false);
Paint();
}
class GamepadModule : public pp::Module {
public:
GamepadModule() : pp::Module() {}
virtual ~GamepadModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new GamepadInstance(instance);
}
};
namespace pp {
Module* CreateModule() { return new GamepadModule(); }
} // namespace pp
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/accelerator_handler.h"
#include <bitset>
#include <gtk/gtk.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "views/accelerator.h"
#include "views/events/event.h"
#include "views/focus/focus_manager.h"
#include "views/touchui/touch_factory.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace views {
namespace {
RootView* FindRootViewForGdkWindow(GdkWindow* gdk_window) {
gpointer data = NULL;
gdk_window_get_user_data(gdk_window, &data);
GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);
if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {
DLOG(WARNING) << "no GtkWidget found for that GdkWindow";
return NULL;
}
WidgetGtk* widget_gtk = WidgetGtk::GetViewForNative(gtk_widget);
if (!widget_gtk) {
DLOG(WARNING) << "no WidgetGtk found for that GtkWidget";
return NULL;
}
return widget_gtk->GetRootView();
}
#if defined(HAVE_XINPUT2)
bool X2EventIsTouchEvent(XEvent* xev) {
// TODO(sad): Determine if the captured event is a touch-event.
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Is the event coming from a touch device?
return TouchFactory::GetInstance()->IsTouchDevice(
static_cast<XIDeviceEvent*>(cookie->data)->sourceid);
}
default:
return false;
}
}
#endif // HAVE_XINPUT2
} // namespace
#if defined(HAVE_XINPUT2)
bool DispatchX2Event(RootView* root, XEvent* xev) {
XGenericEventCookie* cookie = &xev->xcookie;
bool touch_event = false;
if (X2EventIsTouchEvent(xev)) {
// Hide the cursor when a touch event comes in.
TouchFactory::GetInstance()->SetCursorVisible(false, false);
touch_event = true;
// Create a TouchEvent, and send it off to |root|. If the event
// is processed by |root|, then return. Otherwise let it fall through so it
// can be used (if desired) as a mouse event.
TouchEvent touch(xev);
if (root->OnTouchEvent(touch) != views::View::TOUCH_STATUS_UNKNOWN)
return true;
}
switch (cookie->evtype) {
case XI_KeyPress:
case XI_KeyRelease: {
// TODO(sad): We don't capture XInput2 events from keyboard yet.
break;
}
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Scrolling the wheel generates press/release events with button id's 4
// and 5. In case of a wheelscroll, we do not want to show the cursor.
XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(cookie->data);
if (xievent->detail == 4 || xievent->detail == 5) {
Event::FromNativeEvent2 from_native;
return root->OnMouseWheel(MouseWheelEvent(xev, from_native));
}
MouseEvent mouseev(xev);
if (!touch_event) {
// Show the cursor, and decide whether or not the cursor should be
// automatically hidden after a certain time of inactivity.
int button_flags = mouseev.flags() & (ui::EF_RIGHT_BUTTON_DOWN |
ui::EF_MIDDLE_BUTTON_DOWN | ui::EF_LEFT_BUTTON_DOWN);
bool start_timer = false;
switch (cookie->evtype) {
case XI_ButtonPress:
start_timer = false;
break;
case XI_ButtonRelease:
// For a release, start the timer if this was only button pressed
// that is being released.
if (button_flags == ui::EF_RIGHT_BUTTON_DOWN ||
button_flags == ui::EF_LEFT_BUTTON_DOWN ||
button_flags == ui::EF_MIDDLE_BUTTON_DOWN)
start_timer = true;
break;
case XI_Motion:
start_timer = !button_flags;
break;
}
TouchFactory::GetInstance()->SetCursorVisible(true, start_timer);
}
// Dispatch the event.
switch (cookie->evtype) {
case XI_ButtonPress:
return root->OnMousePressed(mouseev);
case XI_ButtonRelease:
root->OnMouseReleased(mouseev, false);
return true;
case XI_Motion: {
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
}
}
}
return false;
}
#endif // HAVE_XINPUT2
bool DispatchXEvent(XEvent* xev) {
GdkDisplay* gdisp = gdk_display_get_default();
XID xwindow = xev->xany.window;
#if defined(HAVE_XINPUT2)
if (xev->type == GenericEvent) {
XGenericEventCookie* cookie = &xev->xcookie;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
xwindow = xiev->event;
}
#endif
GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);
if (RootView* root = FindRootViewForGdkWindow(gwind)) {
switch (xev->type) {
case KeyPress:
case KeyRelease: {
Event::FromNativeEvent2 from_native;
KeyEvent keyev(xev, from_native);
return root->ProcessKeyEvent(keyev);
}
case ButtonPress:
case ButtonRelease: {
if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {
// Scrolling the wheel triggers button press/release events.
Event::FromNativeEvent2 from_native;
return root->OnMouseWheel(MouseWheelEvent(xev, from_native));
} else {
MouseEvent mouseev(xev);
if (xev->type == ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true; // Assume the event has been processed to make sure we
// don't process it twice.
}
}
}
case MotionNotify: {
MouseEvent mouseev(xev);
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
#if defined(HAVE_XINPUT2)
case GenericEvent: {
return DispatchX2Event(root, xev);
}
#endif
}
}
return false;
}
#if defined(HAVE_XINPUT2)
void SetTouchDeviceList(std::vector<unsigned int>& devices) {
TouchFactory::GetInstance()->SetTouchDeviceList(devices);
}
#endif
AcceleratorHandler::AcceleratorHandler() {}
bool AcceleratorHandler::Dispatch(GdkEvent* event) {
gtk_main_do_event(event);
return true;
}
base::MessagePumpGlibXDispatcher::DispatchStatus
AcceleratorHandler::DispatchX(XEvent* xev) {
return DispatchXEvent(xev) ?
base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :
base::MessagePumpGlibXDispatcher::EVENT_IGNORED;
}
} // namespace views
<commit_msg>touchui: Fix building on a buildbot.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/accelerator_handler.h"
#include <bitset>
#include <gtk/gtk.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "views/accelerator.h"
#include "views/events/event.h"
#include "views/focus/focus_manager.h"
#include "views/touchui/touch_factory.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace views {
namespace {
RootView* FindRootViewForGdkWindow(GdkWindow* gdk_window) {
gpointer data = NULL;
gdk_window_get_user_data(gdk_window, &data);
GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);
if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {
DLOG(WARNING) << "no GtkWidget found for that GdkWindow";
return NULL;
}
WidgetGtk* widget_gtk = WidgetGtk::GetViewForNative(gtk_widget);
if (!widget_gtk) {
DLOG(WARNING) << "no WidgetGtk found for that GtkWidget";
return NULL;
}
return widget_gtk->GetRootView();
}
#if defined(HAVE_XINPUT2)
bool X2EventIsTouchEvent(XEvent* xev) {
// TODO(sad): Determine if the captured event is a touch-event.
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Is the event coming from a touch device?
return TouchFactory::GetInstance()->IsTouchDevice(
static_cast<XIDeviceEvent*>(cookie->data)->sourceid);
}
default:
return false;
}
}
#endif // HAVE_XINPUT2
} // namespace
#if defined(HAVE_XINPUT2)
bool DispatchX2Event(RootView* root, XEvent* xev) {
XGenericEventCookie* cookie = &xev->xcookie;
bool touch_event = false;
if (X2EventIsTouchEvent(xev)) {
// Hide the cursor when a touch event comes in.
TouchFactory::GetInstance()->SetCursorVisible(false, false);
touch_event = true;
// Create a TouchEvent, and send it off to |root|. If the event
// is processed by |root|, then return. Otherwise let it fall through so it
// can be used (if desired) as a mouse event.
TouchEvent touch(xev);
if (root->OnTouchEvent(touch) != views::View::TOUCH_STATUS_UNKNOWN)
return true;
}
switch (cookie->evtype) {
case XI_KeyPress:
case XI_KeyRelease: {
// TODO(sad): We don't capture XInput2 events from keyboard yet.
break;
}
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Scrolling the wheel generates press/release events with button id's 4
// and 5. In case of a wheelscroll, we do not want to show the cursor.
XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(cookie->data);
if (xievent->detail == 4 || xievent->detail == 5) {
Event::FromNativeEvent2 from_native;
MouseWheelEvent wheelev(xev, from_native);
return root->OnMouseWheel(wheelev);
}
MouseEvent mouseev(xev);
if (!touch_event) {
// Show the cursor, and decide whether or not the cursor should be
// automatically hidden after a certain time of inactivity.
int button_flags = mouseev.flags() & (ui::EF_RIGHT_BUTTON_DOWN |
ui::EF_MIDDLE_BUTTON_DOWN | ui::EF_LEFT_BUTTON_DOWN);
bool start_timer = false;
switch (cookie->evtype) {
case XI_ButtonPress:
start_timer = false;
break;
case XI_ButtonRelease:
// For a release, start the timer if this was only button pressed
// that is being released.
if (button_flags == ui::EF_RIGHT_BUTTON_DOWN ||
button_flags == ui::EF_LEFT_BUTTON_DOWN ||
button_flags == ui::EF_MIDDLE_BUTTON_DOWN)
start_timer = true;
break;
case XI_Motion:
start_timer = !button_flags;
break;
}
TouchFactory::GetInstance()->SetCursorVisible(true, start_timer);
}
// Dispatch the event.
switch (cookie->evtype) {
case XI_ButtonPress:
return root->OnMousePressed(mouseev);
case XI_ButtonRelease:
root->OnMouseReleased(mouseev, false);
return true;
case XI_Motion: {
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
}
}
}
return false;
}
#endif // HAVE_XINPUT2
bool DispatchXEvent(XEvent* xev) {
GdkDisplay* gdisp = gdk_display_get_default();
XID xwindow = xev->xany.window;
#if defined(HAVE_XINPUT2)
if (xev->type == GenericEvent) {
XGenericEventCookie* cookie = &xev->xcookie;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
xwindow = xiev->event;
}
#endif
GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);
if (RootView* root = FindRootViewForGdkWindow(gwind)) {
switch (xev->type) {
case KeyPress:
case KeyRelease: {
Event::FromNativeEvent2 from_native;
KeyEvent keyev(xev, from_native);
return root->ProcessKeyEvent(keyev);
}
case ButtonPress:
case ButtonRelease: {
if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {
// Scrolling the wheel triggers button press/release events.
Event::FromNativeEvent2 from_native;
MouseWheelEvent wheelev(xev, from_native);
return root->OnMouseWheel(wheelev);
} else {
MouseEvent mouseev(xev);
if (xev->type == ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true; // Assume the event has been processed to make sure we
// don't process it twice.
}
}
}
case MotionNotify: {
MouseEvent mouseev(xev);
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
#if defined(HAVE_XINPUT2)
case GenericEvent: {
return DispatchX2Event(root, xev);
}
#endif
}
}
return false;
}
#if defined(HAVE_XINPUT2)
void SetTouchDeviceList(std::vector<unsigned int>& devices) {
TouchFactory::GetInstance()->SetTouchDeviceList(devices);
}
#endif
AcceleratorHandler::AcceleratorHandler() {}
bool AcceleratorHandler::Dispatch(GdkEvent* event) {
gtk_main_do_event(event);
return true;
}
base::MessagePumpGlibXDispatcher::DispatchStatus
AcceleratorHandler::DispatchX(XEvent* xev) {
return DispatchXEvent(xev) ?
base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :
base::MessagePumpGlibXDispatcher::EVENT_IGNORED;
}
} // namespace views
<|endoftext|> |
<commit_before>/*************************************************************************/
/* view_panner.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "view_panner.h"
#include "core/input/input.h"
#include "core/input/shortcut.h"
#include "core/os/keyboard.h"
bool ViewPanner::gui_input(const Ref<InputEvent> &p_event, Rect2 p_canvas_rect) {
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
Vector2i scroll_vec = Vector2((mb->get_button_index() == MouseButton::WHEEL_RIGHT) - (mb->get_button_index() == MouseButton::WHEEL_LEFT), (mb->get_button_index() == MouseButton::WHEEL_DOWN) - (mb->get_button_index() == MouseButton::WHEEL_UP));
if (scroll_vec != Vector2()) {
if (control_scheme == SCROLL_PANS) {
if (mb->is_ctrl_pressed()) {
scroll_vec.y *= mb->get_factor();
callback_helper(zoom_callback, varray(scroll_vec, mb->get_position(), mb->is_alt_pressed()));
return true;
} else {
Vector2 panning;
if (mb->is_shift_pressed()) {
panning.x += mb->get_factor() * scroll_vec.y;
panning.y += mb->get_factor() * scroll_vec.x;
} else {
panning.y += mb->get_factor() * scroll_vec.y;
panning.x += mb->get_factor() * scroll_vec.x;
}
callback_helper(scroll_callback, varray(panning, mb->is_alt_pressed()));
return true;
}
} else {
if (mb->is_ctrl_pressed()) {
Vector2 panning;
if (mb->is_shift_pressed()) {
panning.x += mb->get_factor() * scroll_vec.y;
panning.y += mb->get_factor() * scroll_vec.x;
} else {
panning.y += mb->get_factor() * scroll_vec.y;
panning.x += mb->get_factor() * scroll_vec.x;
}
callback_helper(scroll_callback, varray(panning, mb->is_alt_pressed()));
return true;
} else if (!mb->is_shift_pressed()) {
scroll_vec.y *= mb->get_factor();
callback_helper(zoom_callback, varray(scroll_vec, mb->get_position(), mb->is_alt_pressed()));
return true;
}
}
}
// Alt is not used for button presses, so ignore it.
if (mb->is_alt_pressed()) {
return false;
}
bool is_drag_event = mb->get_button_index() == MouseButton::MIDDLE ||
(enable_rmb && mb->get_button_index() == MouseButton::RIGHT) ||
(!simple_panning_enabled && mb->get_button_index() == MouseButton::LEFT && is_panning()) ||
(force_drag && mb->get_button_index() == MouseButton::LEFT);
if (is_drag_event) {
if (mb->is_pressed()) {
is_dragging = true;
} else {
is_dragging = false;
}
return mb->get_button_index() != MouseButton::LEFT || mb->is_pressed(); // Don't consume LMB release events (it fixes some selection problems).
}
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid()) {
if (is_dragging) {
if (p_canvas_rect != Rect2()) {
callback_helper(pan_callback, varray(Input::get_singleton()->warp_mouse_motion(mm, p_canvas_rect)));
} else {
callback_helper(pan_callback, varray(mm->get_relative()));
}
return true;
}
}
Ref<InputEventKey> k = p_event;
if (k.is_valid()) {
if (pan_view_shortcut.is_valid() && pan_view_shortcut->matches_event(k)) {
pan_key_pressed = k->is_pressed();
if (simple_panning_enabled || (Input::get_singleton()->get_mouse_button_mask() & MouseButton::LEFT) != MouseButton::NONE) {
is_dragging = pan_key_pressed;
}
return true;
}
}
return false;
}
void ViewPanner::release_pan_key() {
pan_key_pressed = false;
is_dragging = false;
}
void ViewPanner::callback_helper(Callable p_callback, Vector<Variant> p_args) {
const Variant **argptr = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
for (int i = 0; i < p_args.size(); i++) {
argptr[i] = &p_args[i];
}
Variant result;
Callable::CallError ce;
p_callback.call(argptr, p_args.size(), result, ce);
}
void ViewPanner::set_callbacks(Callable p_scroll_callback, Callable p_pan_callback, Callable p_zoom_callback) {
scroll_callback = p_scroll_callback;
pan_callback = p_pan_callback;
zoom_callback = p_zoom_callback;
}
void ViewPanner::set_control_scheme(ControlScheme p_scheme) {
control_scheme = p_scheme;
}
void ViewPanner::set_enable_rmb(bool p_enable) {
enable_rmb = p_enable;
}
void ViewPanner::set_pan_shortcut(Ref<Shortcut> p_shortcut) {
pan_view_shortcut = p_shortcut;
pan_key_pressed = false;
}
void ViewPanner::set_simple_panning_enabled(bool p_enabled) {
simple_panning_enabled = p_enabled;
}
void ViewPanner::setup(ControlScheme p_scheme, Ref<Shortcut> p_shortcut, bool p_simple_panning) {
set_control_scheme(p_scheme);
set_pan_shortcut(p_shortcut);
set_simple_panning_enabled(p_simple_panning);
}
bool ViewPanner::is_panning() const {
return is_dragging || pan_key_pressed;
}
void ViewPanner::set_force_drag(bool p_force) {
force_drag = p_force;
}
ViewPanner::ViewPanner() {
Array inputs;
inputs.append(InputEventKey::create_reference(Key::SPACE));
pan_view_shortcut.instantiate();
pan_view_shortcut->set_events(inputs);
}
<commit_msg>Fix that slow mouse wheel scroll has no zoom effect on 2D editor<commit_after>/*************************************************************************/
/* view_panner.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "view_panner.h"
#include "core/input/input.h"
#include "core/input/shortcut.h"
#include "core/os/keyboard.h"
bool ViewPanner::gui_input(const Ref<InputEvent> &p_event, Rect2 p_canvas_rect) {
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
Vector2 scroll_vec = Vector2((mb->get_button_index() == MouseButton::WHEEL_RIGHT) - (mb->get_button_index() == MouseButton::WHEEL_LEFT), (mb->get_button_index() == MouseButton::WHEEL_DOWN) - (mb->get_button_index() == MouseButton::WHEEL_UP));
if (scroll_vec != Vector2()) {
if (control_scheme == SCROLL_PANS) {
if (mb->is_ctrl_pressed()) {
scroll_vec.y *= mb->get_factor();
callback_helper(zoom_callback, varray(scroll_vec, mb->get_position(), mb->is_alt_pressed()));
return true;
} else {
Vector2 panning;
if (mb->is_shift_pressed()) {
panning.x += mb->get_factor() * scroll_vec.y;
panning.y += mb->get_factor() * scroll_vec.x;
} else {
panning.y += mb->get_factor() * scroll_vec.y;
panning.x += mb->get_factor() * scroll_vec.x;
}
callback_helper(scroll_callback, varray(panning, mb->is_alt_pressed()));
return true;
}
} else {
if (mb->is_ctrl_pressed()) {
Vector2 panning;
if (mb->is_shift_pressed()) {
panning.x += mb->get_factor() * scroll_vec.y;
panning.y += mb->get_factor() * scroll_vec.x;
} else {
panning.y += mb->get_factor() * scroll_vec.y;
panning.x += mb->get_factor() * scroll_vec.x;
}
callback_helper(scroll_callback, varray(panning, mb->is_alt_pressed()));
return true;
} else if (!mb->is_shift_pressed()) {
scroll_vec.y *= mb->get_factor();
callback_helper(zoom_callback, varray(scroll_vec, mb->get_position(), mb->is_alt_pressed()));
return true;
}
}
}
// Alt is not used for button presses, so ignore it.
if (mb->is_alt_pressed()) {
return false;
}
bool is_drag_event = mb->get_button_index() == MouseButton::MIDDLE ||
(enable_rmb && mb->get_button_index() == MouseButton::RIGHT) ||
(!simple_panning_enabled && mb->get_button_index() == MouseButton::LEFT && is_panning()) ||
(force_drag && mb->get_button_index() == MouseButton::LEFT);
if (is_drag_event) {
if (mb->is_pressed()) {
is_dragging = true;
} else {
is_dragging = false;
}
return mb->get_button_index() != MouseButton::LEFT || mb->is_pressed(); // Don't consume LMB release events (it fixes some selection problems).
}
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid()) {
if (is_dragging) {
if (p_canvas_rect != Rect2()) {
callback_helper(pan_callback, varray(Input::get_singleton()->warp_mouse_motion(mm, p_canvas_rect)));
} else {
callback_helper(pan_callback, varray(mm->get_relative()));
}
return true;
}
}
Ref<InputEventKey> k = p_event;
if (k.is_valid()) {
if (pan_view_shortcut.is_valid() && pan_view_shortcut->matches_event(k)) {
pan_key_pressed = k->is_pressed();
if (simple_panning_enabled || (Input::get_singleton()->get_mouse_button_mask() & MouseButton::LEFT) != MouseButton::NONE) {
is_dragging = pan_key_pressed;
}
return true;
}
}
return false;
}
void ViewPanner::release_pan_key() {
pan_key_pressed = false;
is_dragging = false;
}
void ViewPanner::callback_helper(Callable p_callback, Vector<Variant> p_args) {
const Variant **argptr = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
for (int i = 0; i < p_args.size(); i++) {
argptr[i] = &p_args[i];
}
Variant result;
Callable::CallError ce;
p_callback.call(argptr, p_args.size(), result, ce);
}
void ViewPanner::set_callbacks(Callable p_scroll_callback, Callable p_pan_callback, Callable p_zoom_callback) {
scroll_callback = p_scroll_callback;
pan_callback = p_pan_callback;
zoom_callback = p_zoom_callback;
}
void ViewPanner::set_control_scheme(ControlScheme p_scheme) {
control_scheme = p_scheme;
}
void ViewPanner::set_enable_rmb(bool p_enable) {
enable_rmb = p_enable;
}
void ViewPanner::set_pan_shortcut(Ref<Shortcut> p_shortcut) {
pan_view_shortcut = p_shortcut;
pan_key_pressed = false;
}
void ViewPanner::set_simple_panning_enabled(bool p_enabled) {
simple_panning_enabled = p_enabled;
}
void ViewPanner::setup(ControlScheme p_scheme, Ref<Shortcut> p_shortcut, bool p_simple_panning) {
set_control_scheme(p_scheme);
set_pan_shortcut(p_shortcut);
set_simple_panning_enabled(p_simple_panning);
}
bool ViewPanner::is_panning() const {
return is_dragging || pan_key_pressed;
}
void ViewPanner::set_force_drag(bool p_force) {
force_drag = p_force;
}
ViewPanner::ViewPanner() {
Array inputs;
inputs.append(InputEventKey::create_reference(Key::SPACE));
pan_view_shortcut.instantiate();
pan_view_shortcut->set_events(inputs);
}
<|endoftext|> |
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/steadystate/CSteadyStateTask.cpp,v $
$Revision: 1.62 $
$Name: $
$Author: shoops $
$Date: 2006/04/27 01:31:49 $
End CVS Header */
// Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
/**
* CSteadyStateTask class.
*
* This class implements a steady state task which is comprised of a
* of a problem and a method. Additionally calls to the reporting
* methods are done when initialized.
*
* Created for Copasi by Stefan Hoops 2002
*/
#include "copasi.h"
#include "CSteadyStateTask.h"
#include "CSteadyStateProblem.h"
#include "CSteadyStateMethod.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "model/CMetabNameInterface.h"
#include "report/CKeyFactory.h"
#include "report/CReport.h"
#define XXXX_Reporting
CSteadyStateTask::CSteadyStateTask(const CCopasiContainer * pParent):
CCopasiTask(CCopasiTask::steadyState, pParent),
mpSteadyState(NULL),
mJacobian(),
mJacobianX(),
mEigenValues("Eigenvalues of Jacobian", this),
mEigenValuesX("Eigenvalues of reduced system Jacobian", this)
{
mpProblem = new CSteadyStateProblem(this);
mpMethod =
CSteadyStateMethod::createSteadyStateMethod(CCopasiMethod::Newton);
this->add(mpMethod, true);
//mpMethod->setObjectParent(this);
//((CSteadyStateMethod *) mpMethod)->setProblem((CSteadyStateProblem *) mpProblem);
}
CSteadyStateTask::CSteadyStateTask(const CSteadyStateTask & src,
const CCopasiContainer * pParent):
CCopasiTask(src, pParent),
mpSteadyState(src.mpSteadyState),
mJacobian(src.mJacobian),
mJacobianX(src.mJacobianX),
mEigenValues(src.mEigenValues, this),
mEigenValuesX(src.mEigenValuesX, this)
{
mpProblem =
new CSteadyStateProblem(* (CSteadyStateProblem *) src.mpProblem, this);
mpMethod =
CSteadyStateMethod::createSteadyStateMethod(src.mpMethod->getSubType());
this->add(mpMethod, true);
//mpMethod->setObjectParent(this);
//((CSteadyStateMethod *) mpMethod)->setProblem((CSteadyStateProblem *) mpProblem);
}
CSteadyStateTask::~CSteadyStateTask()
{
pdelete(mpSteadyState);
}
void CSteadyStateTask::cleanup()
{}
void CSteadyStateTask::print(std::ostream * ostream) const {(*ostream) << (*this);}
void CSteadyStateTask::load(CReadConfig & configBuffer)
{
configBuffer.getVariable("SteadyState", "bool", &mScheduled,
CReadConfig::LOOP);
((CSteadyStateProblem *) mpProblem)->load(configBuffer);
((CSteadyStateMethod *) mpMethod)->load(configBuffer);
}
//CState * CSteadyStateTask::getState()
//{return mpSteadyState;}
const CState * CSteadyStateTask::getState() const
{return mpSteadyState;}
const CMatrix< C_FLOAT64 > & CSteadyStateTask::getJacobian() const
{return mJacobian;}
const CMatrix< C_FLOAT64 > & CSteadyStateTask::getJacobianReduced() const
{return mJacobianX;}
const CEigen & CSteadyStateTask::getEigenValues() const
{
return mEigenValues;
}
const CEigen & CSteadyStateTask::getEigenValuesReduced() const
{
return mEigenValuesX;
}
bool CSteadyStateTask::initialize(const OutputFlag & of,
std::ostream * pOstream)
{
assert(mpProblem && mpMethod);
if (!mpMethod->isValidProblem(mpProblem)) return false;
bool success = true;
success &= CCopasiTask::initialize(of, pOstream);
//init states
if (!mpProblem->getModel()) return false;
pdelete(mpSteadyState);
mpSteadyState = new CState(mpProblem->getModel()->getInitialState());
mCalculateReducedSystem = (mpProblem->getModel()->getNumDependentMetabs() != 0);
//init jacobians
unsigned C_INT32 size = mpSteadyState->getNumIndependent();
mJacobianX.resize(size, size);
size += mpSteadyState->getNumDependent();
mJacobian.resize(size, size);
CSteadyStateProblem* pProblem =
dynamic_cast<CSteadyStateProblem *>(mpProblem);
assert(pProblem);
success &= pProblem->initialize();
CSteadyStateMethod* pMethod =
dynamic_cast<CSteadyStateMethod *>(mpMethod);
assert(pMethod);
success &= pMethod->initialize(pProblem);
return success;
}
bool CSteadyStateTask::process(const bool & useInitialValues)
{
if (useInitialValues)
{
mpProblem->getModel()->applyInitialValues();
}
*mpSteadyState = mpProblem->getModel()->getState();
CSteadyStateMethod* pMethod =
dynamic_cast<CSteadyStateMethod *>(mpMethod);
assert(pMethod);
output(COutputInterface::BEFORE);
mResult = pMethod->process(mpSteadyState,
mJacobian,
mJacobianX,
mEigenValues,
mEigenValuesX,
mpCallBack);
output(COutputInterface::AFTER);
return (mResult != CSteadyStateMethod::notFound);
}
bool CSteadyStateTask::restore()
{
bool success = CCopasiTask::restore();
if (mUpdateModel)
{
CModel * pModel = mpProblem->getModel();
pModel->setState(*mpSteadyState);
pModel->applyAssignments();
pModel->setInitialState(pModel->getState());
}
return success;
}
std::ostream &operator<<(std::ostream &os, const CSteadyStateTask &A)
{
switch (A.getResult())
{
case CSteadyStateMethod::found:
os << "A steady state with given resolution was found." << std::endl;
break;
case CSteadyStateMethod::notFound:
os << "No steady state with given resolution was found!" << std::endl;
os << "(below are the last unsuccessful trial values)" << std::endl;
break;
case CSteadyStateMethod::foundEquilibrium:
os << "An equilibrium steady state (zero fluxes) was found." << std::endl;
break;
case CSteadyStateMethod::foundNegative:
os << "An invalid steady state (negative concentrations) was found." << std::endl;
}
os << std::endl;
// Update all necessary values.
CState * pState = const_cast<CState *>(A.getState());
if (!pState) return os;
CModel * pModel = A.mpProblem->getModel();
if (!pModel) return os;
pModel->setState(*pState);
pModel->applyAssignments();
pModel->refreshRates();
pModel->setTransitionTimes();
// Metabolite Info: Name, Concentration, Concentration Rate, Particle Number, Particle Rate, Transition Time
const CCopasiVector<CMetab> & Metabolites = pModel->getMetabolites();
const CMetab * pMetab;
unsigned C_INT32 i, imax = Metabolites.size();
os << "Metabolite" << "\t";
os << "Concentration (" << pModel->getConcentrationUnitName() << ")" << "\t";
os << "Concentration Rate (" << pModel->getConcentrationRateUnitName() << ")" << "\t";
os << "Particle Number" << "\t";
os << "Particle Number Rate (1/" << pModel->getTimeUnitName() << ")" << "\t";
os << "Transition Time (" << pModel->getTimeUnitName() << ")" << std::endl;
for (i = 0; i < imax; ++i)
{
pMetab = Metabolites[i];
os << CMetabNameInterface::getDisplayName(pModel, *pMetab) << "\t";
os << pMetab->getConcentration() << "\t";
os << pMetab->getConcentrationRate() << "\t";
os << pMetab->getValue() << "\t";
os << pMetab->getRate() << "\t";
os << pMetab->getTransitionTime() << std::endl;
}
os << std::endl;
// Reaction Info: Name, Flux, Particle Flux
const CCopasiVector<CReaction>& Reactions = pModel->getReactions();
const CReaction * pReaction;
imax = Reactions.size();
os << "Reaction" << "\t";
os << "Flux (" << pModel->getQuantityRateUnitName() << ")" << "\t";
os << "Particle Flux (1/" << pModel->getTimeUnitName() << ")" << std::endl;
for (i = 0; i < imax; ++i)
{
pReaction = Reactions[i];
os << pReaction->getObjectName() << "\t";
os << pReaction->getFlux() << "\t";
os << pReaction->getParticleFlux() << std::endl;
}
os << std::endl;
// if Jacobian Requested
// Jacobian
// Jacobian Reduced System
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isJacobianRequested())
{
os << "Jacobian of the Complete System" << std::endl;
os << A.mJacobian << std::endl;
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isStabilityAnalysisRequested())
{
os << "Eigenvalues\treal\timaginary" << std::endl;
imax = A.mEigenValues.getR().size();
for (i = 0; i < imax; i++)
os << "\t" << A.mEigenValues.getR()[i] << "\t" << A.mEigenValues.getI()[i] << std::endl;
os << std::endl;
}
os << "Jacobian of the Reduced System" << std::endl;
os << A.mJacobianX << std::endl;
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isStabilityAnalysisRequested())
{
os << "Eigenvalues\treal\timaginary" << std::endl;
imax = A.mEigenValuesX.getR().size();
for (i = 0; i < imax; i++)
os << "\t" << A.mEigenValuesX.getR()[i] << "\t" << A.mEigenValuesX.getI()[i] << std::endl;
os << std::endl;
}
}
// if Stability Analysis Requested
// Stability Analysis Reduced System
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isStabilityAnalysisRequested())
{
os << "Stability Analysis of the Reduced System" << std::endl;
os << A.mEigenValuesX << std::endl;
}
return os;
}
<commit_msg>Fixed Bug 694. Steady-state calculation may never update the initial time as this calculation is only valid for autonomous models.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/steadystate/CSteadyStateTask.cpp,v $
$Revision: 1.63 $
$Name: $
$Author: shoops $
$Date: 2006/11/03 19:49:49 $
End CVS Header */
// Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
/**
* CSteadyStateTask class.
*
* This class implements a steady state task which is comprised of a
* of a problem and a method. Additionally calls to the reporting
* methods are done when initialized.
*
* Created for Copasi by Stefan Hoops 2002
*/
#include "copasi.h"
#include "CSteadyStateTask.h"
#include "CSteadyStateProblem.h"
#include "CSteadyStateMethod.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "model/CMetabNameInterface.h"
#include "report/CKeyFactory.h"
#include "report/CReport.h"
#define XXXX_Reporting
CSteadyStateTask::CSteadyStateTask(const CCopasiContainer * pParent):
CCopasiTask(CCopasiTask::steadyState, pParent),
mpSteadyState(NULL),
mJacobian(),
mJacobianX(),
mEigenValues("Eigenvalues of Jacobian", this),
mEigenValuesX("Eigenvalues of reduced system Jacobian", this)
{
mpProblem = new CSteadyStateProblem(this);
mpMethod =
CSteadyStateMethod::createSteadyStateMethod(CCopasiMethod::Newton);
this->add(mpMethod, true);
//mpMethod->setObjectParent(this);
//((CSteadyStateMethod *) mpMethod)->setProblem((CSteadyStateProblem *) mpProblem);
}
CSteadyStateTask::CSteadyStateTask(const CSteadyStateTask & src,
const CCopasiContainer * pParent):
CCopasiTask(src, pParent),
mpSteadyState(src.mpSteadyState),
mJacobian(src.mJacobian),
mJacobianX(src.mJacobianX),
mEigenValues(src.mEigenValues, this),
mEigenValuesX(src.mEigenValuesX, this)
{
mpProblem =
new CSteadyStateProblem(* (CSteadyStateProblem *) src.mpProblem, this);
mpMethod =
CSteadyStateMethod::createSteadyStateMethod(src.mpMethod->getSubType());
this->add(mpMethod, true);
//mpMethod->setObjectParent(this);
//((CSteadyStateMethod *) mpMethod)->setProblem((CSteadyStateProblem *) mpProblem);
}
CSteadyStateTask::~CSteadyStateTask()
{
pdelete(mpSteadyState);
}
void CSteadyStateTask::cleanup()
{}
void CSteadyStateTask::print(std::ostream * ostream) const {(*ostream) << (*this);}
void CSteadyStateTask::load(CReadConfig & configBuffer)
{
configBuffer.getVariable("SteadyState", "bool", &mScheduled,
CReadConfig::LOOP);
((CSteadyStateProblem *) mpProblem)->load(configBuffer);
((CSteadyStateMethod *) mpMethod)->load(configBuffer);
}
//CState * CSteadyStateTask::getState()
//{return mpSteadyState;}
const CState * CSteadyStateTask::getState() const
{return mpSteadyState;}
const CMatrix< C_FLOAT64 > & CSteadyStateTask::getJacobian() const
{return mJacobian;}
const CMatrix< C_FLOAT64 > & CSteadyStateTask::getJacobianReduced() const
{return mJacobianX;}
const CEigen & CSteadyStateTask::getEigenValues() const
{
return mEigenValues;
}
const CEigen & CSteadyStateTask::getEigenValuesReduced() const
{
return mEigenValuesX;
}
bool CSteadyStateTask::initialize(const OutputFlag & of,
std::ostream * pOstream)
{
assert(mpProblem && mpMethod);
if (!mpMethod->isValidProblem(mpProblem)) return false;
bool success = true;
success &= CCopasiTask::initialize(of, pOstream);
//init states
if (!mpProblem->getModel()) return false;
pdelete(mpSteadyState);
mpSteadyState = new CState(mpProblem->getModel()->getInitialState());
mCalculateReducedSystem = (mpProblem->getModel()->getNumDependentMetabs() != 0);
//init jacobians
unsigned C_INT32 size = mpSteadyState->getNumIndependent();
mJacobianX.resize(size, size);
size += mpSteadyState->getNumDependent();
mJacobian.resize(size, size);
CSteadyStateProblem* pProblem =
dynamic_cast<CSteadyStateProblem *>(mpProblem);
assert(pProblem);
success &= pProblem->initialize();
CSteadyStateMethod* pMethod =
dynamic_cast<CSteadyStateMethod *>(mpMethod);
assert(pMethod);
success &= pMethod->initialize(pProblem);
return success;
}
bool CSteadyStateTask::process(const bool & useInitialValues)
{
if (useInitialValues)
{
mpProblem->getModel()->applyInitialValues();
}
*mpSteadyState = mpProblem->getModel()->getState();
// A steady-state makes only sense in an autonomous model,
// i.e., the time of the steady-state must not be changed
// during simulation.
C_FLOAT64 InitialTime = mpSteadyState->getTime();
CSteadyStateMethod* pMethod =
dynamic_cast<CSteadyStateMethod *>(mpMethod);
assert(pMethod);
output(COutputInterface::BEFORE);
mResult = pMethod->process(mpSteadyState,
mJacobian,
mJacobianX,
mEigenValues,
mEigenValuesX,
mpCallBack);
// Reset the time.
mpSteadyState->setTime(InitialTime);
output(COutputInterface::AFTER);
return (mResult != CSteadyStateMethod::notFound);
}
bool CSteadyStateTask::restore()
{
bool success = CCopasiTask::restore();
if (mUpdateModel)
{
CModel * pModel = mpProblem->getModel();
pModel->setState(*mpSteadyState);
pModel->applyAssignments();
pModel->setInitialState(pModel->getState());
}
return success;
}
std::ostream &operator<<(std::ostream &os, const CSteadyStateTask &A)
{
switch (A.getResult())
{
case CSteadyStateMethod::found:
os << "A steady state with given resolution was found." << std::endl;
break;
case CSteadyStateMethod::notFound:
os << "No steady state with given resolution was found!" << std::endl;
os << "(below are the last unsuccessful trial values)" << std::endl;
break;
case CSteadyStateMethod::foundEquilibrium:
os << "An equilibrium steady state (zero fluxes) was found." << std::endl;
break;
case CSteadyStateMethod::foundNegative:
os << "An invalid steady state (negative concentrations) was found." << std::endl;
}
os << std::endl;
// Update all necessary values.
CState * pState = const_cast<CState *>(A.getState());
if (!pState) return os;
CModel * pModel = A.mpProblem->getModel();
if (!pModel) return os;
pModel->setState(*pState);
pModel->applyAssignments();
pModel->refreshRates();
pModel->setTransitionTimes();
// Metabolite Info: Name, Concentration, Concentration Rate, Particle Number, Particle Rate, Transition Time
const CCopasiVector<CMetab> & Metabolites = pModel->getMetabolites();
const CMetab * pMetab;
unsigned C_INT32 i, imax = Metabolites.size();
os << "Metabolite" << "\t";
os << "Concentration (" << pModel->getConcentrationUnitName() << ")" << "\t";
os << "Concentration Rate (" << pModel->getConcentrationRateUnitName() << ")" << "\t";
os << "Particle Number" << "\t";
os << "Particle Number Rate (1/" << pModel->getTimeUnitName() << ")" << "\t";
os << "Transition Time (" << pModel->getTimeUnitName() << ")" << std::endl;
for (i = 0; i < imax; ++i)
{
pMetab = Metabolites[i];
os << CMetabNameInterface::getDisplayName(pModel, *pMetab) << "\t";
os << pMetab->getConcentration() << "\t";
os << pMetab->getConcentrationRate() << "\t";
os << pMetab->getValue() << "\t";
os << pMetab->getRate() << "\t";
os << pMetab->getTransitionTime() << std::endl;
}
os << std::endl;
// Reaction Info: Name, Flux, Particle Flux
const CCopasiVector<CReaction>& Reactions = pModel->getReactions();
const CReaction * pReaction;
imax = Reactions.size();
os << "Reaction" << "\t";
os << "Flux (" << pModel->getQuantityRateUnitName() << ")" << "\t";
os << "Particle Flux (1/" << pModel->getTimeUnitName() << ")" << std::endl;
for (i = 0; i < imax; ++i)
{
pReaction = Reactions[i];
os << pReaction->getObjectName() << "\t";
os << pReaction->getFlux() << "\t";
os << pReaction->getParticleFlux() << std::endl;
}
os << std::endl;
// if Jacobian Requested
// Jacobian
// Jacobian Reduced System
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isJacobianRequested())
{
os << "Jacobian of the Complete System" << std::endl;
os << A.mJacobian << std::endl;
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isStabilityAnalysisRequested())
{
os << "Eigenvalues\treal\timaginary" << std::endl;
imax = A.mEigenValues.getR().size();
for (i = 0; i < imax; i++)
os << "\t" << A.mEigenValues.getR()[i] << "\t" << A.mEigenValues.getI()[i] << std::endl;
os << std::endl;
}
os << "Jacobian of the Reduced System" << std::endl;
os << A.mJacobianX << std::endl;
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isStabilityAnalysisRequested())
{
os << "Eigenvalues\treal\timaginary" << std::endl;
imax = A.mEigenValuesX.getR().size();
for (i = 0; i < imax; i++)
os << "\t" << A.mEigenValuesX.getR()[i] << "\t" << A.mEigenValuesX.getI()[i] << std::endl;
os << std::endl;
}
}
// if Stability Analysis Requested
// Stability Analysis Reduced System
if (static_cast<CSteadyStateProblem *>(A.mpProblem)->isStabilityAnalysisRequested())
{
os << "Stability Analysis of the Reduced System" << std::endl;
os << A.mEigenValuesX << std::endl;
}
return os;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qnamespace.h>
#include "qqmlaccessible.h"
#ifndef QT_NO_ACCESSIBILITY
QT_BEGIN_NAMESPACE
QString Q_GUI_EXPORT qTextBeforeOffsetFromString(int offset, QAccessible2::BoundaryType boundaryType,
int *startOffset, int *endOffset, const QString& text);
QString Q_GUI_EXPORT qTextAtOffsetFromString(int offset, QAccessible2::BoundaryType boundaryType,
int *startOffset, int *endOffset, const QString& text);
QString Q_GUI_EXPORT qTextAfterOffsetFromString(int offset, QAccessible2::BoundaryType boundaryType,
int *startOffset, int *endOffset, const QString& text);
QQmlAccessible::QQmlAccessible(QObject *object)
:QAccessibleObject(object)
{
}
void *QQmlAccessible::interface_cast(QAccessible::InterfaceType t)
{
if (t == QAccessible::ActionInterface)
return static_cast<QAccessibleActionInterface*>(this);
return QAccessibleObject::interface_cast(t);
}
QQmlAccessible::~QQmlAccessible()
{
}
QAccessibleInterface *QQmlAccessible::childAt(int x, int y) const
{
// Note that this function will disregard stacking order.
// (QAccessibleQuickView::childAt() does this correctly and more efficient)
// If the item clips its children, we can return early if the coordinate is outside its rect
if (clipsChildren()) {
if (!rect().contains(x, y))
return 0;
}
for (int i = childCount() - 1; i >= 0; --i) {
QAccessibleInterface *childIface = child(i);
if (childIface && !childIface->state().invisible) {
if (childIface->rect().contains(x, y))
return childIface;
}
delete childIface;
}
return 0;
}
QAccessible::State QQmlAccessible::state() const
{
QAccessible::State state;
//QRect viewRect(QPoint(0, 0), m_implementation->size());
//QRect itemRect(m_item->scenePos().toPoint(), m_item->boundingRect().size().toSize());
QRect viewRect_ = viewRect();
QRect itemRect = rect();
// qDebug() << "viewRect" << viewRect << "itemRect" << itemRect;
// error case:
if (viewRect_.isNull() || itemRect.isNull()) {
state.invisible = true;
}
if (!viewRect_.intersects(itemRect)) {
state.offscreen = true;
// state.invisible = true; // no set at this point to ease development
}
if (!object()->property("visible").toBool() || qFuzzyIsNull(object()->property("opacity").toDouble())) {
state.invisible = true;
}
if ((role() == QAccessible::CheckBox || role() == QAccessible::RadioButton) && object()->property("checked").toBool()) {
state.checked = true;
}
if (role() == QAccessible::EditableText)
state.focusable = true;
//qDebug() << "state?" << m_item->property("state").toString() << m_item->property("status").toString() << m_item->property("visible").toString();
return state;
}
QStringList QQmlAccessible::actionNames() const
{
QStringList actions;
switch (role()) {
case QAccessible::PushButton:
actions << QAccessibleActionInterface::pressAction();
break;
case QAccessible::RadioButton:
case QAccessible::CheckBox:
actions << QAccessibleActionInterface::checkAction()
<< QAccessibleActionInterface::uncheckAction()
<< QAccessibleActionInterface::pressAction();
break;
case QAccessible::Slider:
case QAccessible::SpinBox:
case QAccessible::ScrollBar:
actions << QAccessibleActionInterface::increaseAction()
<< QAccessibleActionInterface::decreaseAction();
break;
default:
break;
}
return actions;
}
void QQmlAccessible::doAction(const QString &actionName)
{
// Look for and call the accessible[actionName]Action() function on the item.
// This allows for overriding the default action handling.
const QByteArray functionName = "accessible" + actionName.toLatin1() + "Action()";
if (object()->metaObject()->indexOfMethod(functionName) != -1) {
QMetaObject::invokeMethod(object(), functionName, Q_ARG(QString, actionName));
return;
}
// Role-specific default action handling follows. Items are excepted to provide
// properties according to role conventions. These will then be read and/or updated
// by the accessibility system.
// Checkable roles : checked
// Value-based roles : (via the value interface: value, minimumValue, maximumValue), stepSize
switch (role()) {
case QAccessible::RadioButton:
case QAccessible::CheckBox: {
QVariant checked = object()->property("checked");
if (checked.isValid()) {
if (actionName == QAccessibleActionInterface::pressAction()) {
object()->setProperty("checked", QVariant(!checked.toBool()));
} else if (actionName == QAccessibleActionInterface::checkAction()) {
object()->setProperty("checked", QVariant(true));
} else if (actionName == QAccessibleActionInterface::uncheckAction()) {
object()->setProperty("checked", QVariant(false));
}
}
break;
}
case QAccessible::Slider:
case QAccessible::SpinBox:
case QAccessible::Dial:
case QAccessible::ScrollBar: {
if (actionName != QAccessibleActionInterface::increaseAction() &&
actionName != QAccessibleActionInterface::decreaseAction())
break;
// Update the value using QAccessibleValueInterface, respecting
// the minimum and maximum value (if set). Also check for and
// use the "stepSize" property on the item
if (QAccessibleValueInterface *valueIface = valueInterface()) {
QVariant valueV = valueIface->currentValue();
qreal newValue = valueV.toInt();
QVariant stepSizeV = object()->property("stepSize");
qreal stepSize = stepSizeV.isValid() ? stepSizeV.toReal() : qreal(1.0);
if (actionName == QAccessibleActionInterface::increaseAction()) {
newValue += stepSize;
} else {
newValue -= stepSize;
}
QVariant minimumValueV = valueIface->minimumValue();
if (minimumValueV.isValid()) {
newValue = qMax(newValue, minimumValueV.toReal());
}
QVariant maximumValueV = valueIface->maximumValue();
if (maximumValueV.isValid()) {
newValue = qMin(newValue, maximumValueV.toReal());
}
valueIface->setCurrentValue(QVariant(newValue));
}
break;
}
default:
break;
}
}
QStringList QQmlAccessible::keyBindingsForAction(const QString &actionName) const
{
Q_UNUSED(actionName)
return QStringList();
}
QT_END_NAMESPACE
#endif // QT_NO_ACCESSIBILITY
<commit_msg>Fix doAction with custom functions.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qnamespace.h>
#include "qqmlaccessible.h"
#ifndef QT_NO_ACCESSIBILITY
QT_BEGIN_NAMESPACE
QString Q_GUI_EXPORT qTextBeforeOffsetFromString(int offset, QAccessible2::BoundaryType boundaryType,
int *startOffset, int *endOffset, const QString& text);
QString Q_GUI_EXPORT qTextAtOffsetFromString(int offset, QAccessible2::BoundaryType boundaryType,
int *startOffset, int *endOffset, const QString& text);
QString Q_GUI_EXPORT qTextAfterOffsetFromString(int offset, QAccessible2::BoundaryType boundaryType,
int *startOffset, int *endOffset, const QString& text);
QQmlAccessible::QQmlAccessible(QObject *object)
:QAccessibleObject(object)
{
}
void *QQmlAccessible::interface_cast(QAccessible::InterfaceType t)
{
if (t == QAccessible::ActionInterface)
return static_cast<QAccessibleActionInterface*>(this);
return QAccessibleObject::interface_cast(t);
}
QQmlAccessible::~QQmlAccessible()
{
}
QAccessibleInterface *QQmlAccessible::childAt(int x, int y) const
{
// Note that this function will disregard stacking order.
// (QAccessibleQuickView::childAt() does this correctly and more efficient)
// If the item clips its children, we can return early if the coordinate is outside its rect
if (clipsChildren()) {
if (!rect().contains(x, y))
return 0;
}
for (int i = childCount() - 1; i >= 0; --i) {
QAccessibleInterface *childIface = child(i);
if (childIface && !childIface->state().invisible) {
if (childIface->rect().contains(x, y))
return childIface;
}
delete childIface;
}
return 0;
}
QAccessible::State QQmlAccessible::state() const
{
QAccessible::State state;
//QRect viewRect(QPoint(0, 0), m_implementation->size());
//QRect itemRect(m_item->scenePos().toPoint(), m_item->boundingRect().size().toSize());
QRect viewRect_ = viewRect();
QRect itemRect = rect();
// qDebug() << "viewRect" << viewRect << "itemRect" << itemRect;
// error case:
if (viewRect_.isNull() || itemRect.isNull()) {
state.invisible = true;
}
if (!viewRect_.intersects(itemRect)) {
state.offscreen = true;
// state.invisible = true; // no set at this point to ease development
}
if (!object()->property("visible").toBool() || qFuzzyIsNull(object()->property("opacity").toDouble())) {
state.invisible = true;
}
if ((role() == QAccessible::CheckBox || role() == QAccessible::RadioButton) && object()->property("checked").toBool()) {
state.checked = true;
}
if (role() == QAccessible::EditableText)
state.focusable = true;
//qDebug() << "state?" << m_item->property("state").toString() << m_item->property("status").toString() << m_item->property("visible").toString();
return state;
}
QStringList QQmlAccessible::actionNames() const
{
QStringList actions;
switch (role()) {
case QAccessible::PushButton:
actions << QAccessibleActionInterface::pressAction();
break;
case QAccessible::RadioButton:
case QAccessible::CheckBox:
actions << QAccessibleActionInterface::checkAction()
<< QAccessibleActionInterface::uncheckAction()
<< QAccessibleActionInterface::pressAction();
break;
case QAccessible::Slider:
case QAccessible::SpinBox:
case QAccessible::ScrollBar:
actions << QAccessibleActionInterface::increaseAction()
<< QAccessibleActionInterface::decreaseAction();
break;
default:
break;
}
return actions;
}
void QQmlAccessible::doAction(const QString &actionName)
{
// Look for and call the accessible[actionName]Action() function on the item.
// This allows for overriding the default action handling.
const QByteArray functionName = "accessible" + actionName.toLatin1() + "Action";
if (object()->metaObject()->indexOfMethod(functionName + "()") != -1) {
QMetaObject::invokeMethod(object(), functionName);
return;
}
// Role-specific default action handling follows. Items are excepted to provide
// properties according to role conventions. These will then be read and/or updated
// by the accessibility system.
// Checkable roles : checked
// Value-based roles : (via the value interface: value, minimumValue, maximumValue), stepSize
switch (role()) {
case QAccessible::RadioButton:
case QAccessible::CheckBox: {
QVariant checked = object()->property("checked");
if (checked.isValid()) {
if (actionName == QAccessibleActionInterface::pressAction()) {
object()->setProperty("checked", QVariant(!checked.toBool()));
} else if (actionName == QAccessibleActionInterface::checkAction()) {
object()->setProperty("checked", QVariant(true));
} else if (actionName == QAccessibleActionInterface::uncheckAction()) {
object()->setProperty("checked", QVariant(false));
}
}
break;
}
case QAccessible::Slider:
case QAccessible::SpinBox:
case QAccessible::Dial:
case QAccessible::ScrollBar: {
if (actionName != QAccessibleActionInterface::increaseAction() &&
actionName != QAccessibleActionInterface::decreaseAction())
break;
// Update the value using QAccessibleValueInterface, respecting
// the minimum and maximum value (if set). Also check for and
// use the "stepSize" property on the item
if (QAccessibleValueInterface *valueIface = valueInterface()) {
QVariant valueV = valueIface->currentValue();
qreal newValue = valueV.toInt();
QVariant stepSizeV = object()->property("stepSize");
qreal stepSize = stepSizeV.isValid() ? stepSizeV.toReal() : qreal(1.0);
if (actionName == QAccessibleActionInterface::increaseAction()) {
newValue += stepSize;
} else {
newValue -= stepSize;
}
QVariant minimumValueV = valueIface->minimumValue();
if (minimumValueV.isValid()) {
newValue = qMax(newValue, minimumValueV.toReal());
}
QVariant maximumValueV = valueIface->maximumValue();
if (maximumValueV.isValid()) {
newValue = qMin(newValue, maximumValueV.toReal());
}
valueIface->setCurrentValue(QVariant(newValue));
}
break;
}
default:
break;
}
}
QStringList QQmlAccessible::keyBindingsForAction(const QString &actionName) const
{
Q_UNUSED(actionName)
return QStringList();
}
QT_END_NAMESPACE
#endif // QT_NO_ACCESSIBILITY
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 LINK/2012 <[email protected]>
* Licensed under the MIT License, see LICENSE at top level directory.
*
*/
#include <stdinc.hpp>
#include "../data_traits.hpp"
using namespace modloader;
using std::set;
using std::string;
namespace datalib
{
template<>
struct data_info<udata<modelname>> : data_info<modelname>
{
static const bool ignore = true;
};
}
// Traits for pedgrp.dat and cargrp.dat
struct xxxgrp_traits : public data_traits
{
static const bool has_sections = false;
static const bool per_line_section = false;
//
using key_type = std::pair<int, size_t>; // grpindex, model_hash
using value_type = data_slice<either<set<modelname>, udata<modelname>>>;
key_type key_from_value(const value_type&)
{
return std::make_pair(grpindex++, 0);
}
template<typename StoreType, typename TData>
static bool setbyline(StoreType& store, TData& data, const gta3::section_info* section, const std::string& line)
{
if(gvm.IsVC())
{
// VC uses '//' at the end of the line.
// The game doesn't even reach the point of reading this char (it only reads 16 tokens),
// but our method to avoid it is erasing.
size_t comment_pos = line.find("//");
if(comment_pos != line.npos)
{
std::string fixed_line = line;
fixed_line.erase(comment_pos);
return data_traits::setbyline(store, data, section, fixed_line);
}
}
return data_traits::setbyline(store, data, section, line);
}
// Before the merging process transform the set of models into individual models in each key of the container
// This allows merging of individual entries in a group not just the entire group container itself
template<class StoreType>
static bool premerge(StoreType& store)
{
StoreType::container_type newcontainer;
// Builds the new container, which contains a single model instead of the set of models
std::for_each(store.container().begin(), store.container().end(), [&](StoreType::pair_type& pair)
{
auto& set = *get<std::set<modelname>>(&pair.second.get<0>());
for(auto& model : set)
{
newcontainer.emplace(
key_type(pair.first.first, hash_model(model)),
value_type(make_udata<modelname>(model)));
}
});
store.container() = std::move(newcontainer);
return true;
}
// Now, before writing the content to the merged file we should reverse the transformation we did in premerge.
// So this time we should take each model with the same group in the key and put in a set
template<class StoreType, class MergedList, class FuncDoWrite>
static bool prewrite(MergedList list, FuncDoWrite dowrite)
{
std::map<key_type, value_type> grp_content;
std::for_each(list.begin(), list.end(), [&](MergedList::value_type& pair)
{
auto& model = get(*get<udata<modelname>>(&pair.second.get().get<0>()));
auto key = key_type(pair.first.get().first, 0);
// If the key still doesn't exist, make it to be have it's mapped type to be a set of models
if(grp_content.count(key) == 0)
{
grp_content.emplace(key, value_type(set<modelname>()));
}
get<set<modelname>>(&grp_content[key].get<0>())->emplace(model);
});
list.clear();
for(auto& x : grp_content)
list.emplace_back(std::cref(x.first), std::ref(x.second));
return dowrite(list);
}
public: // traits data
int grpindex = 0; // Line index we are going tho for groups
template<class Archive>
void serialize(Archive& archive)
{ archive(this->grpindex); }
};
struct cargrp_traits : public xxxgrp_traits
{
struct dtraits : modloader::dtraits::OpenFile
{
static const char* what() { return "car groups"; }
static const char* datafile() { return "cargrp.dat"; }
};
using detour_type = modloader::OpenFileDetour<0x5BD1BB, dtraits>;
};
struct pedgrp_traits : public xxxgrp_traits
{
struct dtraits : modloader::dtraits::OpenFile
{
static const char* what() { return "ped groups"; }
static const char* datafile() { return "pedgrp.dat"; }
};
using detour_type = modloader::OpenFileDetour<0x5BCFFB, dtraits>;
};
template<class Traits>
using xxxgrp_store = gta3::data_store<Traits, std::map<
typename Traits::key_type, typename Traits::value_type
>>;
template<class Traits>
static void initialise(DataPlugin* plugin_ptr, std::function<void()> refresher)
{
using store_type = xxxgrp_store<Traits>;
plugin_ptr->AddMerger<store_type>(Traits::dtraits::datafile(), true, false, false, reinstall_since_load, refresher);
}
static auto xinit = initializer([](DataPlugin* plugin_ptr)
{
if(true) initialise<pedgrp_traits>(plugin_ptr, gdir_refresh(injector::cstd<void()>::call<0x5BCFE0>));
if(gvm.IsSA()) initialise<cargrp_traits>(plugin_ptr, gdir_refresh(injector::cstd<void()>::call<0x5BD1A0>));
});
<commit_msg>Fix pedgrp merger for III/VC<commit_after>/*
* Copyright (C) 2015 LINK/2012 <[email protected]>
* Licensed under the MIT License, see LICENSE at top level directory.
*
*/
#include <stdinc.hpp>
#include "../data_traits.hpp"
using namespace modloader;
using std::set;
using std::vector;
using std::string;
namespace datalib
{
template<>
struct data_info<udata<modelname>> : data_info<modelname>
{
static const bool ignore = true;
};
}
// Traits for pedgrp.dat and cargrp.dat
struct xxxgrp_traits : public data_traits
{
static const bool has_sections = false;
static const bool per_line_section = false;
//
using key_type = std::pair<int, size_t>; // grpindex, model_hash
using value_type = data_slice<either<vector<modelname>, udata<modelname>>>;
key_type key_from_value(const value_type&)
{
return std::make_pair(grpindex++, 0);
}
template<typename StoreType, typename TData>
static bool setbyline(StoreType& store, TData& data, const gta3::section_info* section, const std::string& line)
{
if(gvm.IsVC())
{
// VC uses '//' at the end of the line.
// The game doesn't even reach the point of reading this char (it only reads 16 tokens),
// but our method to avoid it is erasing.
size_t comment_pos = line.find("//");
if(comment_pos != line.npos)
{
std::string fixed_line = line;
fixed_line.erase(comment_pos);
return data_traits::setbyline(store, data, section, fixed_line);
}
}
return data_traits::setbyline(store, data, section, line);
}
// (SA-only, III/VC grps aren't variable length)
// Before the merging process transform the set of models into individual models in each key of the container
// This allows merging of individual entries in a group not just the entire group container itself
template<class StoreType>
static bool premerge(StoreType& store)
{
if(gvm.IsSA())
{
StoreType::container_type newcontainer;
// Builds the new container, which contains a single model instead of the set of models
std::for_each(store.container().begin(), store.container().end(), [&](StoreType::pair_type& pair)
{
auto& vec = *get<std::vector<modelname>>(&pair.second.get<0>());
for(auto& model : vec)
{
// the key will make the vector unique, no need to do a find.
newcontainer.emplace(
key_type(pair.first.first, hash_model(model)),
value_type(make_udata<modelname>(model)));
}
});
store.container() = std::move(newcontainer);
}
return true;
}
// (SA-only, III/VC grps aren't variable length)
// Now, before writing the content to the merged file we should reverse the transformation we did in premerge.
// So this time we should take each model with the same group in the key and put in a set
template<class StoreType, class MergedList, class FuncDoWrite>
static bool prewrite(MergedList list, FuncDoWrite dowrite)
{
if(gvm.IsSA())
{
std::map<key_type, value_type> grp_content;
std::for_each(list.begin(), list.end(), [&](MergedList::value_type& pair)
{
auto& model = get(*get<udata<modelname>>(&pair.second.get().get<0>()));
auto key = key_type(pair.first.get().first, 0);
// If the key still doesn't exist, make it to be have it's mapped type to be a set of models
if(grp_content.count(key) == 0)
{
grp_content.emplace(key, value_type(vector<modelname>()));
}
get<vector<modelname>>(&grp_content[key].get<0>())->emplace_back(model);
});
list.clear();
for(auto& x : grp_content)
list.emplace_back(std::cref(x.first), std::ref(x.second));
}
return dowrite(list);
}
public: // traits data
int grpindex = 0; // Line index we are going tho for groups
template<class Archive>
void serialize(Archive& archive)
{ archive(this->grpindex); }
};
struct cargrp_traits : public xxxgrp_traits
{
struct dtraits : modloader::dtraits::OpenFile
{
static const char* what() { return "car groups"; }
static const char* datafile() { return "cargrp.dat"; }
};
using detour_type = modloader::OpenFileDetour<0x5BD1BB, dtraits>;
};
struct pedgrp_traits : public xxxgrp_traits
{
struct dtraits : modloader::dtraits::OpenFile
{
static const char* what() { return "ped groups"; }
static const char* datafile() { return "pedgrp.dat"; }
};
using detour_type = modloader::OpenFileDetour<0x5BCFFB, dtraits>;
};
template<class Traits>
using xxxgrp_store = gta3::data_store<Traits, std::map<
typename Traits::key_type, typename Traits::value_type
>>;
template<class Traits>
static void initialise(DataPlugin* plugin_ptr, std::function<void()> refresher)
{
using store_type = xxxgrp_store<Traits>;
plugin_ptr->AddMerger<store_type>(Traits::dtraits::datafile(), true, false, false, reinstall_since_load, refresher);
}
static auto xinit = initializer([](DataPlugin* plugin_ptr)
{
if(true) initialise<pedgrp_traits>(plugin_ptr, gdir_refresh(injector::cstd<void()>::call<0x5BCFE0>));
if(gvm.IsSA()) initialise<cargrp_traits>(plugin_ptr, gdir_refresh(injector::cstd<void()>::call<0x5BD1A0>));
});
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "img_search_snippet.h"
#include "websearch.h"
#include "query_context.h"
#include "img_query_context.h"
#include "miscutil.h"
#include "mem_utils.h"
#include "encode.h"
#include "urlmatch.h"
#include <assert.h>
#if defined(PROTOBUF) && defined(TC)
#include "query_capture_configuration.h"
#endif
using sp::miscutil;
using sp::encode;
using sp::urlmatch;
namespace seeks_plugins
{
img_search_snippet::img_search_snippet()
:search_snippet()
#ifdef FEATURE_OPENCV2
,_surf_keypoints(NULL),_surf_descriptors(NULL),_surf_storage(NULL)
#endif
, _cached_image(NULL)
{
_doc_type = IMAGE;
}
img_search_snippet::img_search_snippet(const short &rank)
:search_snippet(rank)
#ifdef FEATURE_OPENCV2
,_surf_keypoints(NULL),_surf_descriptors(NULL)
#endif
, _cached_image(NULL)
{
_doc_type = IMAGE;
#ifdef FEATURE_OPENCV2
_surf_storage = cvCreateMemStorage(0);
#endif
}
img_search_snippet::~img_search_snippet()
{
if (_cached_image)
delete _cached_image;
#ifdef FEATURE_OPENCV2
if (_surf_keypoints)
cvClearSeq(_surf_keypoints);
if (_surf_descriptors)
cvClearSeq(_surf_descriptors);
if (_surf_storage)
cvReleaseMemStorage(&_surf_storage);
#endif
}
std::string img_search_snippet::to_html_with_highlight(std::vector<std::string> &words,
const std::string &base_url_str,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
// check for URL redirection for capture & personalization of results.
bool prs = true;
const char *pers = miscutil::lookup(parameters,"prs");
if (!pers)
prs = websearch::_wconfig->_personalization;
else
{
if (strcasecmp(pers,"on") == 0)
prs = true;
else if (strcasecmp(pers,"off") == 0)
prs = false;
else prs = websearch::_wconfig->_personalization;
}
std::string url = _url;
#if defined(PROTOBUF) && defined(TC)
if (prs && websearch::_qc_plugin && websearch::_qc_plugin_activated
&& query_capture_configuration::_config
&& query_capture_configuration::_config->_mode_intercept == "redirect")
{
char *url_enc = encode::url_encode(url.c_str());
url = base_url_str + "/qc_redir?q=" + _qc->_url_enc_query + "&url=" + std::string(url_enc);
free(url_enc);
}
#endif
std::string se_icon = "<span class=\"search_engine icon\" title=\"setitle\"><a href=\"" + base_url_str + "/search_img?q=" + _qc->_url_enc_query + "&page=1&expansion=1&action=expand&engines=seeng\"> </a></span>";
std::string html_content = "<li class=\"search_snippet search_snippet_img\">";
html_content += "<h3><a href=\"";
html_content += url + "\"><img src=\"";
html_content += _cached;
html_content += "\"></a><div>";
const char *title_enc = encode::html_encode(_title.c_str());
html_content += title_enc;
free_const(title_enc);
if (_img_engine.to_ulong()&SE_GOOGLE_IMG)
{
std::string ggle_se_icon = se_icon;
miscutil::replace_in_string(ggle_se_icon,"icon","search_engine_google");
miscutil::replace_in_string(ggle_se_icon,"setitle","Google");
miscutil::replace_in_string(ggle_se_icon,"seeng","google");
html_content += ggle_se_icon;
}
if (_img_engine.to_ulong()&SE_BING_IMG)
{
std::string bing_se_icon = se_icon;
miscutil::replace_in_string(bing_se_icon,"icon","search_engine_bing");
miscutil::replace_in_string(bing_se_icon,"setitle","Bing");
miscutil::replace_in_string(bing_se_icon,"seeng","bing");
html_content += bing_se_icon;
}
if (_img_engine.to_ulong()&SE_FLICKR)
{
std::string flickr_se_icon = se_icon;
miscutil::replace_in_string(flickr_se_icon,"icon","search_engine_flickr");
miscutil::replace_in_string(flickr_se_icon,"setitle","Flickr");
miscutil::replace_in_string(flickr_se_icon,"seeng","flickr");
html_content += flickr_se_icon;
}
if (_img_engine.to_ulong()&SE_WCOMMONS)
{
std::string wcommons_se_icon = se_icon;
miscutil::replace_in_string(wcommons_se_icon,"icon","search_engine_wcommons");
miscutil::replace_in_string(wcommons_se_icon,"setitle","Wikimedia Commons");
miscutil::replace_in_string(wcommons_se_icon,"seeng","wcommons");
html_content += wcommons_se_icon;
}
if (_img_engine.to_ulong()&SE_YAHOO_IMG)
{
std::string yahoo_se_icon = se_icon;
miscutil::replace_in_string(yahoo_se_icon,"icon","search_engine_yahoo");
miscutil::replace_in_string(yahoo_se_icon,"setitle","yahoo");
miscutil::replace_in_string(yahoo_se_icon,"seeng","yahoo");
html_content += yahoo_se_icon;
}
// XXX: personalization icon kind of look ugly with image snippets...
/* if (_personalized)
{
html_content += "<h3 class=\"personalized_result personalized\" title=\"personalized result\">";
}
else */
html_content += "</div></h3>";
const char *cite_enc = NULL;
if (!_cite.empty())
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_cite,cite_host,cite_path);
cite_enc = encode::html_encode(cite_host.c_str());
}
else
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_url,cite_host,cite_path);
cite_enc = encode::html_encode(cite_host.c_str());
}
std::string cite_enc_str = std::string(cite_enc);
if (cite_enc_str.size()>4 && cite_enc_str.substr(0,4)=="www.") //TODO: tolower.
cite_enc_str = cite_enc_str.substr(4);
free_const(cite_enc);
html_content += "<cite>";
html_content += cite_enc_str;
html_content += "</cite><br>";
if (!_cached.empty())
{
char *enc_cached = encode::html_encode(_cached.c_str());
miscutil::chomp(enc_cached);
html_content += "<a class=\"search_cache\" href=\"";
html_content += enc_cached;
html_content += "\">Cached</a>";
free_const(enc_cached);
}
#ifdef FEATURE_OPENCV2
if (!_sim_back)
{
set_similarity_link(parameters);
html_content += "<a class=\"search_cache\" href=\"";
}
else
{
set_back_similarity_link(parameters);
html_content += "<a class=\"search_similarity\" href=\"";
}
html_content += base_url_str + _sim_link;
if (!_sim_back)
html_content += "\">Similar</a>";
else html_content += "\">Back</a>";
#endif
html_content += "</li>\n";
return html_content;
}
std::string img_search_snippet::to_json(const bool &thumbs,
const std::vector<std::string> &query_words)
{
std::string json_str;
json_str += "{";
json_str += "\"id\":" + miscutil::to_string(_id) + ",";
std::string title = _title;
miscutil::replace_in_string(title,"\"","\\\"");
json_str += "\"title\":\"" + title + "\",";
std::string url = _url;
miscutil::replace_in_string(url,"\"","\\\"");
json_str += "\"url\":\"" + url + "\",";
std::string summary = _summary_noenc;
miscutil::replace_in_string(summary,"\"","\\\"");
json_str += "\"summary\":\"" + summary + "\",";
json_str += "\"seeks_meta\":" + miscutil::to_string(_meta_rank) + ",";
json_str += "\"seeks_score\":" + miscutil::to_string(_seeks_rank) + ",";
double rank = _rank / static_cast<double>(_img_engine.count());
json_str += "\"rank\":" + miscutil::to_string(rank) + ",";
json_str += "\"cite\":\"";
if (!_cite.empty())
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_cite,cite_host,cite_path);
json_str += cite_host + "\",";
}
else
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_url,cite_host,cite_path);
json_str += cite_host + "\",";
}
if (!_cached.empty())
{
std::string cached = _cached;
miscutil::replace_in_string(cached,"\"","\\\"");
json_str += "\"cached\":\"" + _cached + "\","; // XXX: cached might be malformed without preprocessing.
}
json_str += "\"engines\":[";
std::string json_str_eng = "";
if (_img_engine.to_ulong()&SE_GOOGLE_IMG)
json_str_eng += "\"google\"";
if (_img_engine.to_ulong()&SE_BING_IMG)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"bing\"";
}
if (_img_engine.to_ulong()&SE_FLICKR)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"flickr\"";
}
if (_img_engine.to_ulong()&SE_WCOMMONS)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"wcommons\"";
}
if (_img_engine.to_ulong()&SE_YAHOO_IMG)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"yahoo\"";
}
json_str += json_str_eng + "]";
json_str += ",\"type\":\"" + get_doc_type_str() + "\"";
json_str += ",\"personalized\":\"";
if (_personalized)
json_str += "yes";
else json_str += "no";
json_str += "\"";
if (!_date.empty())
json_str += ",\"date\":\"" + _date + "\"";
json_str += "}";
return json_str;
}
bool img_search_snippet::is_se_enabled(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
std::bitset<IMG_NSEs> se_enabled;
img_query_context::fillup_img_engines(parameters,se_enabled);
std::bitset<IMG_NSEs> band = _img_engine & se_enabled;
return (band.count() != 0);
}
void img_search_snippet::set_similarity_link(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
const char *engines = miscutil::lookup(parameters,"engines");
std::string sfsearch = "on";
if (!static_cast<img_query_context*>(_qc)->_safesearch)
sfsearch = "off";
_sim_link = "/search_img?q=" + _qc->_url_enc_query
+ "&page=1&expansion=" + miscutil::to_string(_qc->_page_expansion)
+ "&action=similarity&safesearch=" + sfsearch
+ "&id=" + miscutil::to_string(_id) + "&engines=";
if (engines)
_sim_link += std::string(engines);
_sim_back = false;
}
void img_search_snippet::set_back_similarity_link(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
const char *engines = miscutil::lookup(parameters,"engines");
std::string sfsearch = "on";
if (!static_cast<img_query_context*>(_qc)->_safesearch)
sfsearch = "off";
_sim_link = "/search_img?q=" + _qc->_url_enc_query
+ "&page=1&expansion=" + miscutil::to_string(_qc->_page_expansion)
+ "&action=expand&safesearch=" + sfsearch + "&engines=";
if (engines)
_sim_link += std::string(engines);
_sim_back = true;
}
void img_search_snippet::merge_img_snippets(img_search_snippet *s1,
const img_search_snippet *s2)
{
search_snippet::merge_snippets(s1,s2);
std::bitset<IMG_NSEs> setest = s1->_img_engine;
setest &= s2->_img_engine;
if (setest.count()>0)
return;
s1->_img_engine |= s2->_img_engine;
if (!s1->_cached_image && s2->_cached_image)
s1->_cached_image = new std::string(*s2->_cached_image);
/// seeks rank.
s1->_seeks_rank = s1->_img_engine.count();
// XXX: hack, on English queries, Bing & Yahoo are the same engine,
// therefore the rank must be tweaked accordingly in this special case.
if (s1->_qc->_auto_lang == "en"
&& (s1->_img_engine.to_ulong()&SE_YAHOO_IMG)
&& (s1->_img_engine.to_ulong()&SE_BING_IMG))
s1->_seeks_rank--;
}
} /* end of namespace. */
<commit_msg>fixed search engines icon URL rendering bug in image statuc UI<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "img_search_snippet.h"
#include "websearch.h"
#include "query_context.h"
#include "img_query_context.h"
#include "miscutil.h"
#include "mem_utils.h"
#include "encode.h"
#include "urlmatch.h"
#include <assert.h>
#if defined(PROTOBUF) && defined(TC)
#include "query_capture_configuration.h"
#endif
using sp::miscutil;
using sp::encode;
using sp::urlmatch;
namespace seeks_plugins
{
img_search_snippet::img_search_snippet()
:search_snippet()
#ifdef FEATURE_OPENCV2
,_surf_keypoints(NULL),_surf_descriptors(NULL),_surf_storage(NULL)
#endif
, _cached_image(NULL)
{
_doc_type = IMAGE;
}
img_search_snippet::img_search_snippet(const short &rank)
:search_snippet(rank)
#ifdef FEATURE_OPENCV2
,_surf_keypoints(NULL),_surf_descriptors(NULL)
#endif
, _cached_image(NULL)
{
_doc_type = IMAGE;
#ifdef FEATURE_OPENCV2
_surf_storage = cvCreateMemStorage(0);
#endif
}
img_search_snippet::~img_search_snippet()
{
if (_cached_image)
delete _cached_image;
#ifdef FEATURE_OPENCV2
if (_surf_keypoints)
cvClearSeq(_surf_keypoints);
if (_surf_descriptors)
cvClearSeq(_surf_descriptors);
if (_surf_storage)
cvReleaseMemStorage(&_surf_storage);
#endif
}
std::string img_search_snippet::to_html_with_highlight(std::vector<std::string> &words,
const std::string &base_url_str,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
// check for URL redirection for capture & personalization of results.
bool prs = true;
const char *pers = miscutil::lookup(parameters,"prs");
if (!pers)
prs = websearch::_wconfig->_personalization;
else
{
if (strcasecmp(pers,"on") == 0)
prs = true;
else if (strcasecmp(pers,"off") == 0)
prs = false;
else prs = websearch::_wconfig->_personalization;
}
std::string url = _url;
#if defined(PROTOBUF) && defined(TC)
if (prs && websearch::_qc_plugin && websearch::_qc_plugin_activated
&& query_capture_configuration::_config
&& query_capture_configuration::_config->_mode_intercept == "redirect")
{
char *url_enc = encode::url_encode(url.c_str());
url = base_url_str + "/qc_redir?q=" + _qc->_url_enc_query + "&url=" + std::string(url_enc);
free(url_enc);
}
#endif
std::string se_icon = "<span class=\"search_engine icon\" title=\"setitle\"><a href=\"" + base_url_str + "/search_img?q=@query@&page=1&expansion=1&action=expand&engines=seeng\"> </a></span>";
std::string html_content = "<li class=\"search_snippet search_snippet_img\">";
html_content += "<h3><a href=\"";
html_content += url + "\"><img src=\"";
html_content += _cached;
html_content += "\"></a><div>";
const char *title_enc = encode::html_encode(_title.c_str());
html_content += title_enc;
free_const(title_enc);
if (_img_engine.to_ulong()&SE_GOOGLE_IMG)
{
std::string ggle_se_icon = se_icon;
miscutil::replace_in_string(ggle_se_icon,"icon","search_engine_google");
miscutil::replace_in_string(ggle_se_icon,"setitle","Google");
miscutil::replace_in_string(ggle_se_icon,"seeng","google");
miscutil::replace_in_string(ggle_se_icon,"@query@",_qc->_url_enc_query);
html_content += ggle_se_icon;
}
if (_img_engine.to_ulong()&SE_BING_IMG)
{
std::string bing_se_icon = se_icon;
miscutil::replace_in_string(bing_se_icon,"icon","search_engine_bing");
miscutil::replace_in_string(bing_se_icon,"setitle","Bing");
miscutil::replace_in_string(bing_se_icon,"seeng","bing");
miscutil::replace_in_string(bing_se_icon,"@query@",_qc->_url_enc_query);
html_content += bing_se_icon;
}
if (_img_engine.to_ulong()&SE_FLICKR)
{
std::string flickr_se_icon = se_icon;
miscutil::replace_in_string(flickr_se_icon,"icon","search_engine_flickr");
miscutil::replace_in_string(flickr_se_icon,"setitle","Flickr");
miscutil::replace_in_string(flickr_se_icon,"seeng","flickr");
miscutil::replace_in_string(flickr_se_icon,"@query@",_qc->_url_enc_query);
html_content += flickr_se_icon;
}
if (_img_engine.to_ulong()&SE_WCOMMONS)
{
std::string wcommons_se_icon = se_icon;
miscutil::replace_in_string(wcommons_se_icon,"icon","search_engine_wcommons");
miscutil::replace_in_string(wcommons_se_icon,"setitle","Wikimedia Commons");
miscutil::replace_in_string(wcommons_se_icon,"seeng","wcommons");
miscutil::replace_in_string(wcommons_se_icon,"@query@",_qc->_url_enc_query);
html_content += wcommons_se_icon;
}
if (_img_engine.to_ulong()&SE_YAHOO_IMG)
{
std::string yahoo_se_icon = se_icon;
miscutil::replace_in_string(yahoo_se_icon,"icon","search_engine_yahoo");
miscutil::replace_in_string(yahoo_se_icon,"setitle","yahoo");
miscutil::replace_in_string(yahoo_se_icon,"seeng","yahoo");
miscutil::replace_in_string(yahoo_se_icon,"@query@",_qc->_url_enc_query);
html_content += yahoo_se_icon;
}
// XXX: personalization icon kind of look ugly with image snippets...
/* if (_personalized)
{
html_content += "<h3 class=\"personalized_result personalized\" title=\"personalized result\">";
}
else */
html_content += "</div></h3>";
const char *cite_enc = NULL;
if (!_cite.empty())
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_cite,cite_host,cite_path);
cite_enc = encode::html_encode(cite_host.c_str());
}
else
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_url,cite_host,cite_path);
cite_enc = encode::html_encode(cite_host.c_str());
}
std::string cite_enc_str = std::string(cite_enc);
if (cite_enc_str.size()>4 && cite_enc_str.substr(0,4)=="www.") //TODO: tolower.
cite_enc_str = cite_enc_str.substr(4);
free_const(cite_enc);
html_content += "<cite>";
html_content += cite_enc_str;
html_content += "</cite><br>";
if (!_cached.empty())
{
char *enc_cached = encode::html_encode(_cached.c_str());
miscutil::chomp(enc_cached);
html_content += "<a class=\"search_cache\" href=\"";
html_content += enc_cached;
html_content += "\">Cached</a>";
free_const(enc_cached);
}
#ifdef FEATURE_OPENCV2
if (!_sim_back)
{
set_similarity_link(parameters);
html_content += "<a class=\"search_cache\" href=\"";
}
else
{
set_back_similarity_link(parameters);
html_content += "<a class=\"search_similarity\" href=\"";
}
html_content += base_url_str + _sim_link;
if (!_sim_back)
html_content += "\">Similar</a>";
else html_content += "\">Back</a>";
#endif
html_content += "</li>\n";
return html_content;
}
std::string img_search_snippet::to_json(const bool &thumbs,
const std::vector<std::string> &query_words)
{
std::string json_str;
json_str += "{";
json_str += "\"id\":" + miscutil::to_string(_id) + ",";
std::string title = _title;
miscutil::replace_in_string(title,"\"","\\\"");
json_str += "\"title\":\"" + title + "\",";
std::string url = _url;
miscutil::replace_in_string(url,"\"","\\\"");
json_str += "\"url\":\"" + url + "\",";
std::string summary = _summary_noenc;
miscutil::replace_in_string(summary,"\"","\\\"");
json_str += "\"summary\":\"" + summary + "\",";
json_str += "\"seeks_meta\":" + miscutil::to_string(_meta_rank) + ",";
json_str += "\"seeks_score\":" + miscutil::to_string(_seeks_rank) + ",";
double rank = _rank / static_cast<double>(_img_engine.count());
json_str += "\"rank\":" + miscutil::to_string(rank) + ",";
json_str += "\"cite\":\"";
if (!_cite.empty())
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_cite,cite_host,cite_path);
json_str += cite_host + "\",";
}
else
{
std::string cite_host;
std::string cite_path;
urlmatch::parse_url_host_and_path(_url,cite_host,cite_path);
json_str += cite_host + "\",";
}
if (!_cached.empty())
{
std::string cached = _cached;
miscutil::replace_in_string(cached,"\"","\\\"");
json_str += "\"cached\":\"" + _cached + "\","; // XXX: cached might be malformed without preprocessing.
}
json_str += "\"engines\":[";
std::string json_str_eng = "";
if (_img_engine.to_ulong()&SE_GOOGLE_IMG)
json_str_eng += "\"google\"";
if (_img_engine.to_ulong()&SE_BING_IMG)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"bing\"";
}
if (_img_engine.to_ulong()&SE_FLICKR)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"flickr\"";
}
if (_img_engine.to_ulong()&SE_WCOMMONS)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"wcommons\"";
}
if (_img_engine.to_ulong()&SE_YAHOO_IMG)
{
if (!json_str_eng.empty())
json_str_eng += ",";
json_str_eng += "\"yahoo\"";
}
json_str += json_str_eng + "]";
json_str += ",\"type\":\"" + get_doc_type_str() + "\"";
json_str += ",\"personalized\":\"";
if (_personalized)
json_str += "yes";
else json_str += "no";
json_str += "\"";
if (!_date.empty())
json_str += ",\"date\":\"" + _date + "\"";
json_str += "}";
return json_str;
}
bool img_search_snippet::is_se_enabled(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
std::bitset<IMG_NSEs> se_enabled;
img_query_context::fillup_img_engines(parameters,se_enabled);
std::bitset<IMG_NSEs> band = _img_engine & se_enabled;
return (band.count() != 0);
}
void img_search_snippet::set_similarity_link(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
const char *engines = miscutil::lookup(parameters,"engines");
std::string sfsearch = "on";
if (!static_cast<img_query_context*>(_qc)->_safesearch)
sfsearch = "off";
_sim_link = "/search_img?q=" + _qc->_url_enc_query
+ "&page=1&expansion=" + miscutil::to_string(_qc->_page_expansion)
+ "&action=similarity&safesearch=" + sfsearch
+ "&id=" + miscutil::to_string(_id) + "&engines=";
if (engines)
_sim_link += std::string(engines);
_sim_back = false;
}
void img_search_snippet::set_back_similarity_link(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
const char *engines = miscutil::lookup(parameters,"engines");
std::string sfsearch = "on";
if (!static_cast<img_query_context*>(_qc)->_safesearch)
sfsearch = "off";
_sim_link = "/search_img?q=" + _qc->_url_enc_query
+ "&page=1&expansion=" + miscutil::to_string(_qc->_page_expansion)
+ "&action=expand&safesearch=" + sfsearch + "&engines=";
if (engines)
_sim_link += std::string(engines);
_sim_back = true;
}
void img_search_snippet::merge_img_snippets(img_search_snippet *s1,
const img_search_snippet *s2)
{
search_snippet::merge_snippets(s1,s2);
std::bitset<IMG_NSEs> setest = s1->_img_engine;
setest &= s2->_img_engine;
if (setest.count()>0)
return;
s1->_img_engine |= s2->_img_engine;
if (!s1->_cached_image && s2->_cached_image)
s1->_cached_image = new std::string(*s2->_cached_image);
/// seeks rank.
s1->_seeks_rank = s1->_img_engine.count();
// XXX: hack, on English queries, Bing & Yahoo are the same engine,
// therefore the rank must be tweaked accordingly in this special case.
if (s1->_qc->_auto_lang == "en"
&& (s1->_img_engine.to_ulong()&SE_YAHOO_IMG)
&& (s1->_img_engine.to_ulong()&SE_BING_IMG))
s1->_seeks_rank--;
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>//==============================================================================
// Computer engine class
//==============================================================================
#include "computerengine.h"
#include "computerparser.h"
//==============================================================================
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
//==============================================================================
#include <QDebug>
//==============================================================================
namespace OpenCOR {
namespace Computer {
//==============================================================================
ComputerEngine::ComputerEngine() :
mError(QString()),
mExternalFunctions(ComputerExternalFunctions())
{
// Create a module
static int counter = 0;
mModule = new llvm::Module(QString("Module #%1").arg(QString::number(++counter)).toLatin1().constData(),
llvm::getGlobalContext());
// Initialise the native target, so not only can we then create a JIT
// execution engine, but more importantly its data layout will match that of
// our target platform...
llvm::InitializeNativeTarget();
// Create a JIT execution engine
mExecutionEngine = llvm::ExecutionEngine::createJIT(mModule);
// Create a parser
mParser = new ComputerParser();
}
//==============================================================================
ComputerEngine::~ComputerEngine()
{
// Delete some internal objects
delete mParser;
delete mExecutionEngine;
// Note: we must NOT delete mModule, since it gets deleted when deleting
// mExecutionEngine...
}
//==============================================================================
llvm::Module * ComputerEngine::module()
{
// Return the computer engine's module
return mModule;
}
//==============================================================================
llvm::ExecutionEngine * ComputerEngine::executionEngine()
{
// Return the computer engine's execution engine
return mExecutionEngine;
}
//==============================================================================
ComputerError ComputerEngine::error()
{
// Return the computer engine's error
return mError;
}
//==============================================================================
ComputerErrors ComputerEngine::parserErrors()
{
// Return the computer engine's parser's errors
return mParser->errors();
}
//==============================================================================
llvm::Function * ComputerEngine::addFunction(const QString &pFunction)
{
qDebug("---------------------------------------");
qDebug("Compilation of...");
qDebug();
qDebug(pFunction.toLatin1().constData());
// Parse the function
ComputerFunction function = mParser->parseFunction(pFunction);
if (function.isValid()) {
// Output the function's details
qDebug("---------------------------------------");
qDebug("Function details:");
if (function.type() == ComputerFunction::Void)
qDebug(" Type: void");
else
qDebug(" Type: double");
qDebug(QString(" Name: %1").arg(function.name()).toLatin1().constData());
qDebug(QString(" Nb of params: %1").arg(QString::number(function.parameters().count())).toLatin1().constData());
if (!function.parameters().isEmpty())
foreach (const QString ¶meter, function.parameters())
qDebug(QString(" - %1").arg(parameter).toLatin1().constData());
if (function.type() == ComputerFunction::Double)
qDebug(QString(" Return value: %1").arg(function.returnValue()).toLatin1().constData());
// The function was properly parsed, so check that we don't already
// have a function with the same name in our module
if (mModule->getFunction(function.name().toLatin1().constData())) {
// A function with the same name already exists, so...
mError = ComputerError(tr("there is already a function called '%1'").arg(function.name()));
return 0;
}
// No function with the same already exists, so we can try to compile
// the function
if (!compileFunction(function))
// The function couldn't be compiled, so...
return 0;
// Return the function's IR code
return function.irCode();
} else {
// The function wasn't properly parsed, so...
return 0;
}
}
//==============================================================================
bool ComputerEngine::compileFunction(ComputerFunction &pFunction)
{
// Generate some LLVM assembly code based on the contents of the function
static QString indent = QString(" ");
QString assemblyCode = QString();
// Declare any external function which we need and in case they are not
// already declared
foreach (const ComputerExternalFunction &externalFunction,
pFunction.externalFunctions())
if (!mExternalFunctions.contains(externalFunction)) {
// The function's external function hasn't already been declared, so
// declare it
assemblyCode += QString("declare double @%1").arg(externalFunction.name());
QString parameters = QString();
for (int i = 0, iMax = externalFunction.nbOfParameters(); i < iMax; ++i) {
// Add a separator first if we already have 1+ parameters
if (!parameters.isEmpty())
parameters += ", ";
// Add the parameter definition
parameters += "double";
}
assemblyCode += "("+parameters+") nounwind readnone\n";
// Add the extenral function to the computer engine's list of
// external functions
mExternalFunctions.append(externalFunction);
}
if (!assemblyCode.isEmpty())
assemblyCode += "\n";
// Define the function
assemblyCode += "define";
// Type of function
if (pFunction.type() == ComputerFunction::Void)
assemblyCode += " void";
else
assemblyCode += " double";
// Name of the function
assemblyCode += " @"+pFunction.name();
// Parameters of the function
QString parameters = QString();
foreach (const QString ¶meter, pFunction.parameters()) {
// Add a separator first if we already have 1+ parameters
if (!parameters.isEmpty())
parameters += ", ";
// Add the parameter definition
parameters += "double* nocapture %%"+parameter;
}
assemblyCode += "("+parameters+")";
// Additional information for the function definition
assemblyCode += " nounwind uwtable {\n";
// Mathematical statements
bool tbaaMetadataNeeded = false;
//---GRY--- TO BE DONE...
// Return statement
if (pFunction.type() == ComputerFunction::Void)
assemblyCode += indent+"ret void\n";
else
assemblyCode += indent+"ret double "+pFunction.returnValue()+"\n";
// End the function
assemblyCode += "}";
// Add the TBAA metadata, if neeeded
if (tbaaMetadataNeeded) {
assemblyCode += "\n\n";
assemblyCode += "!0 = metadata !{metadata !\"double\", metadata !1}\n";
assemblyCode += "!1 = metadata !{metadata !\"omnipotent char\", metadata !2}\n";
assemblyCode += "!2 = metadata !{metadata !\"Simple C/C++ TBAA\", null}";
}
// Now that we are done generating some LLVM assembly code for the function,
// we can parse that code and have LLVM generate some IR code that will get
// automatically added to our module
//assemblyCode = "declare double @sin(double)\n";
//assemblyCode += "\n";
//assemblyCode += "define void @test(double* %%data) {\n";
//assemblyCode += " %%1 = getelementptr inbounds double* %%data, i64 0\n";
//assemblyCode += " store double 1.230000e+02, double* %%1, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%2 = getelementptr inbounds double* %%data, i64 2\n";
//assemblyCode += " store double 1.230000e+02, double* %%2, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%3 = getelementptr inbounds double* %%data, i64 4\n";
//assemblyCode += " store double 1.230000e+02, double* %%3, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%4 = load double* %%data, align 8\n";
//assemblyCode += " %%5 = tail call double @sin(double %%4)\n";
//assemblyCode += " %%6 = getelementptr inbounds double* %%data, i64 1\n";
//assemblyCode += " store double %%5, double* %%6, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%7 = getelementptr inbounds double* %%data, i64 2\n";
//assemblyCode += " %%8 = load double* %%7, align 8\n";
//assemblyCode += " %%9 = tail call double @sin(double %%8) nounwind readnone\n";
//assemblyCode += " %%10 = getelementptr inbounds double* %%data, i64 3\n";
//assemblyCode += " store double %%9, double* %%10, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%11 = getelementptr inbounds double* %%data, i64 4\n";
//assemblyCode += " %%12 = load double* %%11, align 8\n";
//assemblyCode += " %%13 = tail call double @sin(double %%12) nounwind readnone\n";
//assemblyCode += " %%14 = getelementptr inbounds double* %%data, i64 5\n";
//assemblyCode += " store double %%13, double* %%14, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " ret void\n";
//assemblyCode += "}";
qDebug(QString(" LLVM assembly:\n%1").arg(assemblyCode).toLatin1().constData());
QString originalAssemblyCode = QString(assemblyCode);
// Note: the above is required since we must replace '%' with '\%' prior to
// having LLVM parse the assembly code, yet we need to keep a trace of
// the original assembly code (in case the parsing goes wrong), so...
llvm::SMDiagnostic parseError;
llvm::ParseAssemblyString(assemblyCode.replace("%%", "\%").toLatin1().constData(),
mModule, parseError, llvm::getGlobalContext());
if (parseError.getMessage().size())
mError = ComputerError(tr("the LLVM assembly code could not be parsed: %1").arg(QString::fromStdString(parseError.getMessage()).remove("error: ")),
parseError.getLineNo(), parseError.getColumnNo(),
originalAssemblyCode);
// Try to retrieve the function which assembly code we have just parsed
llvm::Function *function = mModule->getFunction(pFunction.name().toLatin1().constData());
if (function) {
// The function could be retrieved, but it should be removed in case an
// error of sorts occurred during the compilation
if (!mError.isEmpty()) {
// An error occurred during the compilation of the function, so...
function->eraseFromParent();
return false;
}
// Set the function's IR code
pFunction.setIrCode(function);
// Everything went fine, so...
return true;
} else {
// The function couldn't be retrieved, so add an error but only if no
// error occurred during the compilation
if (mError.isEmpty())
mError = ComputerError(tr("the function '%1' could not be found").arg(pFunction.name()));
return false;
}
}
//==============================================================================
} // namespace Computer
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Minor editing.<commit_after>//==============================================================================
// Computer engine class
//==============================================================================
#include "computerengine.h"
#include "computerparser.h"
//==============================================================================
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
//==============================================================================
#include <QDebug>
//==============================================================================
namespace OpenCOR {
namespace Computer {
//==============================================================================
ComputerEngine::ComputerEngine() :
mError(QString()),
mExternalFunctions(ComputerExternalFunctions())
{
// Create a module
static int counter = 0;
mModule = new llvm::Module(QString("Module #%1").arg(QString::number(++counter)).toLatin1().constData(),
llvm::getGlobalContext());
// Initialise the native target, so not only can we then create a JIT
// execution engine, but more importantly its data layout will match that of
// our target platform...
llvm::InitializeNativeTarget();
// Create a JIT execution engine
mExecutionEngine = llvm::ExecutionEngine::createJIT(mModule);
// Create a parser
mParser = new ComputerParser();
}
//==============================================================================
ComputerEngine::~ComputerEngine()
{
// Delete some internal objects
delete mParser;
delete mExecutionEngine;
// Note: we must NOT delete mModule, since it gets deleted when deleting
// mExecutionEngine...
}
//==============================================================================
llvm::Module * ComputerEngine::module()
{
// Return the computer engine's module
return mModule;
}
//==============================================================================
llvm::ExecutionEngine * ComputerEngine::executionEngine()
{
// Return the computer engine's execution engine
return mExecutionEngine;
}
//==============================================================================
ComputerError ComputerEngine::error()
{
// Return the computer engine's error
return mError;
}
//==============================================================================
ComputerErrors ComputerEngine::parserErrors()
{
// Return the computer engine's parser's errors
return mParser->errors();
}
//==============================================================================
llvm::Function * ComputerEngine::addFunction(const QString &pFunction)
{
qDebug("---------------------------------------");
qDebug("Compilation of...");
qDebug();
qDebug(pFunction.toLatin1().constData());
// Parse the function
ComputerFunction function = mParser->parseFunction(pFunction);
if (function.isValid()) {
// Output the function's details
qDebug("---------------------------------------");
qDebug("Function details:");
if (function.type() == ComputerFunction::Void)
qDebug(" Type: void");
else
qDebug(" Type: double");
qDebug(QString(" Name: %1").arg(function.name()).toLatin1().constData());
qDebug(QString(" Nb of params: %1").arg(QString::number(function.parameters().count())).toLatin1().constData());
if (!function.parameters().isEmpty())
foreach (const QString ¶meter, function.parameters())
qDebug(QString(" - %1").arg(parameter).toLatin1().constData());
if (function.type() == ComputerFunction::Double)
qDebug(QString(" Return value: %1").arg(function.returnValue()).toLatin1().constData());
// The function was properly parsed, so check that we don't already have
// a function with the same name in our module
if (mModule->getFunction(function.name().toLatin1().constData())) {
// A function with the same name already exists, so...
mError = ComputerError(tr("there is already a function called '%1'").arg(function.name()));
return 0;
}
// No function with the same name already exists, so we can try to
// compile the function
if (!compileFunction(function))
// The function couldn't be compiled, so...
return 0;
// Return the function's IR code
return function.irCode();
} else {
// The function wasn't properly parsed, so...
return 0;
}
}
//==============================================================================
bool ComputerEngine::compileFunction(ComputerFunction &pFunction)
{
// Generate some LLVM assembly code based on the contents of the function
static QString indent = QString(" ");
QString assemblyCode = QString();
// Declare any external function which we need and which are not already
// declared
foreach (const ComputerExternalFunction &externalFunction,
pFunction.externalFunctions())
if (!mExternalFunctions.contains(externalFunction)) {
// The function's external function hasn't already been declared, so
// declare it
assemblyCode += QString("declare double @%1").arg(externalFunction.name());
QString parameters = QString();
for (int i = 0, iMax = externalFunction.nbOfParameters(); i < iMax; ++i) {
// Add a separator first if we already have 1+ parameters
if (!parameters.isEmpty())
parameters += ", ";
// Add the parameter definition
parameters += "double";
}
assemblyCode += "("+parameters+") nounwind readnone\n";
// Add the extenral function to the computer engine's list of
// external functions
mExternalFunctions.append(externalFunction);
}
if (!assemblyCode.isEmpty())
assemblyCode += "\n";
// Define the function
assemblyCode += "define";
// Type of function
if (pFunction.type() == ComputerFunction::Void)
assemblyCode += " void";
else
assemblyCode += " double";
// Name of the function
assemblyCode += " @"+pFunction.name();
// Parameters of the function
QString parameters = QString();
foreach (const QString ¶meter, pFunction.parameters()) {
// Add a separator first if we already have 1+ parameters
if (!parameters.isEmpty())
parameters += ", ";
// Add the parameter definition
parameters += "double* nocapture %%"+parameter;
}
assemblyCode += "("+parameters+")";
// Additional information for the function definition
assemblyCode += " nounwind uwtable {\n";
// Mathematical statements
bool tbaaMetadataNeeded = false;
//---GRY--- TO BE DONE...
// Return statement
if (pFunction.type() == ComputerFunction::Void)
assemblyCode += indent+"ret void\n";
else
assemblyCode += indent+"ret double "+pFunction.returnValue()+"\n";
// End the function
assemblyCode += "}";
// Add the TBAA metadata, if neeeded
if (tbaaMetadataNeeded) {
assemblyCode += "\n\n";
assemblyCode += "!0 = metadata !{metadata !\"double\", metadata !1}\n";
assemblyCode += "!1 = metadata !{metadata !\"omnipotent char\", metadata !2}\n";
assemblyCode += "!2 = metadata !{metadata !\"Simple C/C++ TBAA\", null}";
}
// Now that we are done generating some LLVM assembly code for the function,
// we can parse that code and have LLVM generate some IR code that will get
// automatically added to our module
//assemblyCode = "declare double @sin(double)\n";
//assemblyCode += "\n";
//assemblyCode += "define void @test(double* %%data) {\n";
//assemblyCode += " %%1 = getelementptr inbounds double* %%data, i64 0\n";
//assemblyCode += " store double 1.230000e+02, double* %%1, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%2 = getelementptr inbounds double* %%data, i64 2\n";
//assemblyCode += " store double 1.230000e+02, double* %%2, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%3 = getelementptr inbounds double* %%data, i64 4\n";
//assemblyCode += " store double 1.230000e+02, double* %%3, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%4 = load double* %%data, align 8\n";
//assemblyCode += " %%5 = tail call double @sin(double %%4)\n";
//assemblyCode += " %%6 = getelementptr inbounds double* %%data, i64 1\n";
//assemblyCode += " store double %%5, double* %%6, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%7 = getelementptr inbounds double* %%data, i64 2\n";
//assemblyCode += " %%8 = load double* %%7, align 8\n";
//assemblyCode += " %%9 = tail call double @sin(double %%8) nounwind readnone\n";
//assemblyCode += " %%10 = getelementptr inbounds double* %%data, i64 3\n";
//assemblyCode += " store double %%9, double* %%10, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " %%11 = getelementptr inbounds double* %%data, i64 4\n";
//assemblyCode += " %%12 = load double* %%11, align 8\n";
//assemblyCode += " %%13 = tail call double @sin(double %%12) nounwind readnone\n";
//assemblyCode += " %%14 = getelementptr inbounds double* %%data, i64 5\n";
//assemblyCode += " store double %%13, double* %%14, align 8\n";
//assemblyCode += "\n";
//assemblyCode += " ret void\n";
//assemblyCode += "}";
qDebug(QString(" LLVM assembly:\n%1").arg(assemblyCode).toLatin1().constData());
QString originalAssemblyCode = QString(assemblyCode);
// Note: the above is required since we must replace '%' with '\%' prior to
// having LLVM parse the assembly code, yet we need to keep a trace of
// the original assembly code (in case the parsing goes wrong), so...
llvm::SMDiagnostic parseError;
llvm::ParseAssemblyString(assemblyCode.replace("%%", "\%").toLatin1().constData(),
mModule, parseError, llvm::getGlobalContext());
if (parseError.getMessage().size())
mError = ComputerError(tr("the LLVM assembly code could not be parsed: %1").arg(QString::fromStdString(parseError.getMessage()).remove("error: ")),
parseError.getLineNo(), parseError.getColumnNo(),
originalAssemblyCode);
// Note: we must not exit straightaway since LLVM may have generated
// some IR code, so we first need to check whether part of the
// function has already been generated and, if so, remove it...
// Try to retrieve the function which assembly code we have just parsed
llvm::Function *function = mModule->getFunction(pFunction.name().toLatin1().constData());
if (function) {
// The function could be retrieved, but it should be removed in case an
// error of sorts occurred during the parsing of the assembly code
if (!mError.isEmpty()) {
// An error occurred during the parsing of the assembly code, so
// remove the function
function->eraseFromParent();
return false;
}
// Set the function's IR code
pFunction.setIrCode(function);
// Everything went fine, so...
return true;
} else {
// The function couldn't be retrieved, so add an error but only if no
// error occurred during the parsing of the assembly code
if (mError.isEmpty())
mError = ComputerError(tr("the function '%1' could not be found").arg(pFunction.name()));
return false;
}
}
//==============================================================================
} // namespace Computer
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/**
* projectM -- Milkdrop-esque visualisation SDK
* Copyright (C)2003-2004 projectM Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* See 'LICENSE.txt' included within this release
*
*/
#include <math.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <iostream>
#ifdef WIN32
#include <shlwapi.h>
#include <SDL_opengl.h>
#define DLL_EXPORT __declspec(dllexport)
#else
#include <SDL2/SDL_opengl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#define DLL_EXPORT
#endif
#include <projectM.hpp>
#include <sdk/IPcmVisualizer.h>
#include <sdk/IPlugin.h>
#include "Utility.h"
#include "EventMapper.h"
#define MAX_FPS 30LL
#define MILLIS_PER_FRAME (1000LL / MAX_FPS)
#ifndef WIN32
#define COMPILE_AS_EXE
#endif
using namespace std::chrono;
static projectM* pm = nullptr;
static std::atomic<bool> quit(false);
static std::atomic<bool> thread(false);
static std::mutex pcmMutex, threadMutex;
static std::condition_variable threadCondition;
#ifndef WIN32
static const int MAX_SAMPLES = 1024;
static const char* PCM_PIPE = "/tmp/musikcube_pcm.pipe";
static void pipeReadProc() {
float samples[MAX_SAMPLES];
int count = 0;
while (!quit.load()) {
mkfifo(PCM_PIPE, 0666);
std::cerr << "pipeReadProc: opening pipe...\n";
int pipeFd = open(PCM_PIPE, O_RDONLY);
std::cerr << "pipeReadProc: open returned\n";
if (pipeFd > 0) {
std::cerr << "pipeReadProc: pipe stream opened fd=" << pipeFd << "\n";
bool pipeOpen = true;
while (pipeFd > 0) {
int count = read(pipeFd, (void *)&samples, MAX_SAMPLES * sizeof(float));
if (count > 0) {
std::unique_lock<std::mutex> lock(pcmMutex);
if (pm) {
pm->pcm()->addPCMfloat(samples, count / sizeof(float));
}
}
else {
close(pipeFd);
pipeFd = 0;
}
}
}
} /* while (!quit) */
std::cerr << "pipeReadProc: done\n";
}
#endif
static void windowProc() {
SDL_Event event;
SDL_GLContext glContext = nullptr;
SDL_Window* screen = nullptr;
projectMEvent evt;
projectMKeycode key;
projectMModifier mod;
long long start, end;
bool recreate = true;
bool fullscreen = false;
int width = 784;
int height = 784;
int flags = 0;
int x = SDL_WINDOWPOS_UNDEFINED;
int y = SDL_WINDOWPOS_UNDEFINED;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
goto cleanup;
}
while (!quit.load()) {
auto start = system_clock::now();
if (recreate) {
if (glContext) {
SDL_GL_DeleteContext(glContext);
}
if (screen) {
SDL_DestroyWindow(screen);
}
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
if (fullscreen) {
flags = SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN;
}
else {
flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
}
screen = SDL_CreateWindow(
"projectM", x, y, width, height, flags);
glContext = SDL_GL_CreateContext(screen);
if (!pm) {
std::string configFn = GetProjectMDataDirectory() + "\\config.inp";
pm = new projectM(configFn);
pm->projectM_resetGL(width, height);
}
recreate = false;
}
while (SDL_PollEvent(&event)) {
evt = sdl2pmEvent(event);
key = sdl2pmKeycode(event.key.keysym.sym);
mod = sdl2pmModifier(event.key.keysym.mod);
if (event.type == SDL_WINDOWEVENT) {
if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
quit.store(true);
continue;
}
}
if (evt == PROJECTM_KEYDOWN) {
if (event.key.keysym.sym == SDLK_SPACE) {
/* hack: spacebar locks. */
pm->key_handler(evt, PROJECTM_K_l, mod);
}
else if (key == PROJECTM_K_f) {
if (!fullscreen) {
SDL_GetWindowPosition(screen, &x, &y);
SDL_GetWindowSize(screen, &width, &height);
}
fullscreen = !fullscreen;
recreate = true;
}
else if (key == PROJECTM_K_ESCAPE) {
quit.store(true);
continue;
}
else {
pm->key_handler(evt, key, mod);
}
}
else if (evt == PROJECTM_VIDEORESIZE) {
SDL_GetWindowSize(screen, &width, &height);
pm->projectM_resetGL(width, height);
pm->projectM_resetTextures();
}
}
{
std::unique_lock<std::mutex> lock(pcmMutex);
pm->renderFrame();
}
SDL_GL_SwapWindow(screen);
auto end = system_clock::now();
auto delta = duration_cast<milliseconds>(end - start);
long long waitTime = MILLIS_PER_FRAME - (delta.count());
if (waitTime > 0) {
util::sleep(waitTime);
}
}
{
std::unique_lock<std::mutex> lock(pcmMutex);
delete pm;
pm = nullptr;
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(screen);
SDL_Quit();
cleanup:
thread.store(false);
{
std::unique_lock<std::mutex> lock(threadMutex);
threadCondition.notify_all();
}
}
#ifdef COMPILE_AS_EXE
int main(int argc, char *argv[]) {
SetProjectMDataDirectory(util::getModuleDirectory());
#ifndef WIN32
std::thread background(pipeReadProc);
background.detach();
#endif
quit.store(false);
thread.store(true);
windowProc();
return 0;
}
#else
#ifdef WIN32
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) {
if (reason == DLL_PROCESS_ATTACH) {
SetProjectMDataDirectory(util::getModuleDirectory(hModule));
}
return true;
}
#endif
#endif
#ifdef WIN32
class Visualizer : public musik::core::audio::IPcmVisualizer {
public:
virtual const char* Name() {
return "projectM IPcmVisualizer";
};
virtual const char* Version() {
return "0.1";
};
virtual const char* Author() {
return "clangen";
};
virtual void Destroy() {
this->Hide();
delete this;
}
virtual void Write(musik::core::audio::IBuffer* buffer) {
if (Visible()) {
std::unique_lock<std::mutex> lock(pcmMutex);
if (pm) {
pm->pcm()->addPCMfloat(buffer->BufferPointer(), buffer->Samples());
}
}
}
virtual void Show() {
if (!Visible()) {
quit.store(false);
thread.store(true);
std::thread background(windowProc);
background.detach();
}
}
virtual void Hide() {
if (Visible()) {
quit.store(true);
while (thread.load()) {
std::unique_lock<std::mutex> lock(threadMutex);
threadCondition.wait(lock);
}
}
}
virtual bool Visible() {
return thread.load();
}
};
extern "C" DLL_EXPORT musik::core::IPlugin* GetPlugin() {
return new Visualizer();
}
extern "C" DLL_EXPORT musik::core::audio::IPcmVisualizer* GetPcmVisualizer() {
return new Visualizer();
}
#endif
<commit_msg>Tweaked the Win32 visualizer name to match *Nix<commit_after>/**
* projectM -- Milkdrop-esque visualisation SDK
* Copyright (C)2003-2004 projectM Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* See 'LICENSE.txt' included within this release
*
*/
#include <math.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <iostream>
#ifdef WIN32
#include <shlwapi.h>
#include <SDL_opengl.h>
#define DLL_EXPORT __declspec(dllexport)
#else
#include <SDL2/SDL_opengl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#define DLL_EXPORT
#endif
#include <projectM.hpp>
#include <sdk/IPcmVisualizer.h>
#include <sdk/IPlugin.h>
#include "Utility.h"
#include "EventMapper.h"
#define MAX_FPS 30LL
#define MILLIS_PER_FRAME (1000LL / MAX_FPS)
#ifndef WIN32
#define COMPILE_AS_EXE
#endif
using namespace std::chrono;
static projectM* pm = nullptr;
static std::atomic<bool> quit(false);
static std::atomic<bool> thread(false);
static std::mutex pcmMutex, threadMutex;
static std::condition_variable threadCondition;
#ifndef WIN32
static const int MAX_SAMPLES = 1024;
static const char* PCM_PIPE = "/tmp/musikcube_pcm.pipe";
static void pipeReadProc() {
float samples[MAX_SAMPLES];
int count = 0;
while (!quit.load()) {
mkfifo(PCM_PIPE, 0666);
std::cerr << "pipeReadProc: opening pipe...\n";
int pipeFd = open(PCM_PIPE, O_RDONLY);
std::cerr << "pipeReadProc: open returned\n";
if (pipeFd > 0) {
std::cerr << "pipeReadProc: pipe stream opened fd=" << pipeFd << "\n";
bool pipeOpen = true;
while (pipeFd > 0) {
int count = read(pipeFd, (void *)&samples, MAX_SAMPLES * sizeof(float));
if (count > 0) {
std::unique_lock<std::mutex> lock(pcmMutex);
if (pm) {
pm->pcm()->addPCMfloat(samples, count / sizeof(float));
}
}
else {
close(pipeFd);
pipeFd = 0;
}
}
}
} /* while (!quit) */
std::cerr << "pipeReadProc: done\n";
}
#endif
static void windowProc() {
SDL_Event event;
SDL_GLContext glContext = nullptr;
SDL_Window* screen = nullptr;
projectMEvent evt;
projectMKeycode key;
projectMModifier mod;
long long start, end;
bool recreate = true;
bool fullscreen = false;
int width = 784;
int height = 784;
int flags = 0;
int x = SDL_WINDOWPOS_UNDEFINED;
int y = SDL_WINDOWPOS_UNDEFINED;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
goto cleanup;
}
while (!quit.load()) {
auto start = system_clock::now();
if (recreate) {
if (glContext) {
SDL_GL_DeleteContext(glContext);
}
if (screen) {
SDL_DestroyWindow(screen);
}
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
if (fullscreen) {
flags = SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN;
}
else {
flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
}
screen = SDL_CreateWindow(
"projectM", x, y, width, height, flags);
glContext = SDL_GL_CreateContext(screen);
if (!pm) {
std::string configFn = GetProjectMDataDirectory() + "\\config.inp";
pm = new projectM(configFn);
pm->projectM_resetGL(width, height);
}
recreate = false;
}
while (SDL_PollEvent(&event)) {
evt = sdl2pmEvent(event);
key = sdl2pmKeycode(event.key.keysym.sym);
mod = sdl2pmModifier(event.key.keysym.mod);
if (event.type == SDL_WINDOWEVENT) {
if (event.window.event == SDL_WINDOWEVENT_CLOSE) {
quit.store(true);
continue;
}
}
if (evt == PROJECTM_KEYDOWN) {
if (event.key.keysym.sym == SDLK_SPACE) {
/* hack: spacebar locks. */
pm->key_handler(evt, PROJECTM_K_l, mod);
}
else if (key == PROJECTM_K_f) {
if (!fullscreen) {
SDL_GetWindowPosition(screen, &x, &y);
SDL_GetWindowSize(screen, &width, &height);
}
fullscreen = !fullscreen;
recreate = true;
}
else if (key == PROJECTM_K_ESCAPE) {
quit.store(true);
continue;
}
else {
pm->key_handler(evt, key, mod);
}
}
else if (evt == PROJECTM_VIDEORESIZE) {
SDL_GetWindowSize(screen, &width, &height);
pm->projectM_resetGL(width, height);
pm->projectM_resetTextures();
}
}
{
std::unique_lock<std::mutex> lock(pcmMutex);
pm->renderFrame();
}
SDL_GL_SwapWindow(screen);
auto end = system_clock::now();
auto delta = duration_cast<milliseconds>(end - start);
long long waitTime = MILLIS_PER_FRAME - (delta.count());
if (waitTime > 0) {
util::sleep(waitTime);
}
}
{
std::unique_lock<std::mutex> lock(pcmMutex);
delete pm;
pm = nullptr;
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(screen);
SDL_Quit();
cleanup:
thread.store(false);
{
std::unique_lock<std::mutex> lock(threadMutex);
threadCondition.notify_all();
}
}
#ifdef COMPILE_AS_EXE
int main(int argc, char *argv[]) {
SetProjectMDataDirectory(util::getModuleDirectory());
#ifndef WIN32
std::thread background(pipeReadProc);
background.detach();
#endif
quit.store(false);
thread.store(true);
windowProc();
return 0;
}
#else
#ifdef WIN32
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) {
if (reason == DLL_PROCESS_ATTACH) {
SetProjectMDataDirectory(util::getModuleDirectory(hModule));
}
return true;
}
#endif
#endif
#ifdef WIN32
class Visualizer : public musik::core::audio::IPcmVisualizer {
public:
virtual const char* Name() {
return "projectM";
};
virtual const char* Version() {
return "0.1";
};
virtual const char* Author() {
return "clangen";
};
virtual void Destroy() {
this->Hide();
delete this;
}
virtual void Write(musik::core::audio::IBuffer* buffer) {
if (Visible()) {
std::unique_lock<std::mutex> lock(pcmMutex);
if (pm) {
pm->pcm()->addPCMfloat(buffer->BufferPointer(), buffer->Samples());
}
}
}
virtual void Show() {
if (!Visible()) {
quit.store(false);
thread.store(true);
std::thread background(windowProc);
background.detach();
}
}
virtual void Hide() {
if (Visible()) {
quit.store(true);
while (thread.load()) {
std::unique_lock<std::mutex> lock(threadMutex);
threadCondition.wait(lock);
}
}
}
virtual bool Visible() {
return thread.load();
}
};
extern "C" DLL_EXPORT musik::core::IPlugin* GetPlugin() {
return new Visualizer();
}
extern "C" DLL_EXPORT musik::core::audio::IPcmVisualizer* GetPcmVisualizer() {
return new Visualizer();
}
#endif
<|endoftext|> |
<commit_before><commit_msg>remove unnecessary stuff<commit_after><|endoftext|> |
<commit_before><commit_msg>Reverting 19447.<commit_after><|endoftext|> |
<commit_before><commit_msg>Make function definition order (.cc) match function declaration order (.h). No code changes.<commit_after><|endoftext|> |
<commit_before><commit_msg>Revert thakis's changes to download_file.cc from r17595.<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix bookmark util crash<commit_after><|endoftext|> |
<commit_before><commit_msg>Show bookmark manager on Linux when menu shortcut is pressed (ctrl-shift-b).<commit_after><|endoftext|> |
<commit_before><commit_msg>Add test for history HTML escaping issue.<commit_after><|endoftext|> |
<commit_before>#include "stan/math/functions/log_rising_factorial.hpp"
#include <gtest/gtest.h>
TEST(MathFunctions, log_rising_factorial) {
using stan::math::log_rising_factorial;
EXPECT_FLOAT_EQ(std::log(120.0), log_rising_factorial(4.0,3));
EXPECT_FLOAT_EQ(std::log(360.0), log_rising_factorial(3.0,4));
EXPECT_THROW(log_rising_factorial(-1, 4),std::domain_error);
}
<commit_msg>added NaN test for log_rising_factorial<commit_after>#include <stan/math/functions/log_rising_factorial.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, log_rising_factorial) {
using stan::math::log_rising_factorial;
EXPECT_FLOAT_EQ(std::log(120.0), log_rising_factorial(4.0,3));
EXPECT_FLOAT_EQ(std::log(360.0), log_rising_factorial(3.0,4));
EXPECT_THROW(log_rising_factorial(-1, 4),std::domain_error);
}
TEST(MathFunctions, log_rising_factorial_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::log_rising_factorial(nan, 3));
}
<|endoftext|> |
<commit_before>#include "common.h"
#include "PlayerController.h"
#include "EventManager.h"
#include "PositionComponent.h"
#include "OrientationComponent.h"
#include "BoundingComponent.h"
#include "ModelComponent.h"
void PlayerController::Init() {
const std::vector<Triangle> triangles = {
std::make_tuple(Point3(-0.375, -0.85, 0.25), Point3( 0.375, -0.85, 0.25), Point3(-0.375, 0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, 0.25), Point3( 0.375, 0.85, 0.25), Point3(-0.375, 0.85, 0.25)),
std::make_tuple(Point3(-0.375, 0.85, 0.25), Point3( 0.375, 0.85, 0.25), Point3(-0.375, 0.85, -0.25)),
std::make_tuple(Point3( 0.375, 0.85, 0.25), Point3( 0.375, 0.85, -0.25), Point3(-0.375, 0.85, -0.25)),
std::make_tuple(Point3(-0.375, 0.85, -0.25), Point3( 0.375, 0.85, -0.25), Point3(-0.375, -0.85, -0.25)),
std::make_tuple(Point3( 0.375, 0.85, -0.25), Point3( 0.375, -0.85, -0.25), Point3(-0.375, -0.85, -0.25)),
std::make_tuple(Point3(-0.375, -0.85, -0.25), Point3( 0.375, -0.85, -0.25), Point3(-0.375, -0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, -0.25), Point3( 0.375, -0.85, 0.25), Point3(-0.375, -0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, 0.25), Point3( 0.375, -0.85, -0.25), Point3( 0.375, 0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, -0.25), Point3( 0.375, 0.85, -0.25), Point3( 0.375, 0.85, 0.25)),
std::make_tuple(Point3(-0.375, -0.85, -0.25), Point3(-0.375, -0.85, 0.25), Point3(-0.375, 0.85, -0.25)),
std::make_tuple(Point3(-0.375, -0.85, 0.25), Point3(-0.375, 0.85, 0.25), Point3(-0.375, 0.85, -0.25))
};
object = engine->AddObject();
engine->AddComponent<PositionComponent>(object);
engine->AddComponent<OrientationComponent>(object);
engine->AddComponent<BoundingComponent>(object, Point3(-0.375f, -0.85f, -0.25f), Point3(0.75f, 1.7f, 0.5f));
engine->AddComponent<ModelComponent>(object, triangles);
InitObject();
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownBounds = engine->GetComponent<BoundingComponent>(object);
/* gravity */
ownPos->position.Derivative(1) = Point3(0, -9.8f, 0);
/* collision detection and response */
engine->systems.Get<EventManager>()->ListenFor("integrator", "ticked", [this, ownPos, ownBounds] (Arg delta) {
auto &prev = ownPos->position.GetPrevious();
auto &curr = *ownPos->position;
auto &vel = *ownPos->position.Derivative();
Point3 normal;
float entryTime = 0.0f;
auto pair = engine->objects.right.equal_range(&typeid(BoundingComponent));
/* loop until all collisions have been resolved */
while(entryTime != 1.0f) {
auto tickVel = vel * delta.float_;
entryTime = 1.0f;
/* find collision with soonest entry time */
for(auto it = pair.first; it != pair.second; ++it) {
auto id = it->get_left();
/* don't check for collisions with self */
if(id == object) { continue; }
auto objPos = engine->GetComponent<PositionComponent>(id);
if(objPos != nullptr) {
auto objBounds = engine->GetComponent<BoundingComponent>(id);
if(objBounds != nullptr) {
auto r = ownBounds->box.AABBSwept(objBounds->box, std::make_tuple(prev, curr, tickVel), *objPos->position);
if(std::get<0>(r) < entryTime) { std::tie(entryTime, normal) = r; }
}
}
}
/* respond to collision */
if(entryTime < 1.0f) {
/* project previous position to point of entry of collision */
prev += tickVel * entryTime;
/* project position onto surface by subtracting surface-to-end vector */
curr -= normal * glm::dot(tickVel, normal);
/* project velocity onto surface too
* y is given a bounce factor of 0.125
*/
vel -= normal * glm::dot(Point3(vel.x, vel.y * 1.125f, vel.z), normal);
}
}
});
}
void PlayerController::Update(DeltaTicks &dt) {
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownOrient = engine->GetComponent<OrientationComponent>(object);
auto rel = glm::normalize(Point4((moveLeft ? -1 : 0) + (moveRight ? 1 : 0), 0, (moveForward ? -1 : 0) + (moveBackward ? 1 : 0), 1));
auto abs = (glm::inverse(ownOrient->orientation) * rel) * 4.0f; /* 4 meters per second */
/* TODO: footstep spread is between 0.5m and 1m */
ownPos->position.Derivative()->x = abs.x;
//pos->position.Derivative()->y = abs.y;
ownPos->position.Derivative()->z = abs.z;
}
<commit_msg>Decrease movement speed slightly<commit_after>#include "common.h"
#include "PlayerController.h"
#include "EventManager.h"
#include "PositionComponent.h"
#include "OrientationComponent.h"
#include "BoundingComponent.h"
#include "ModelComponent.h"
void PlayerController::Init() {
const std::vector<Triangle> triangles = {
std::make_tuple(Point3(-0.375, -0.85, 0.25), Point3( 0.375, -0.85, 0.25), Point3(-0.375, 0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, 0.25), Point3( 0.375, 0.85, 0.25), Point3(-0.375, 0.85, 0.25)),
std::make_tuple(Point3(-0.375, 0.85, 0.25), Point3( 0.375, 0.85, 0.25), Point3(-0.375, 0.85, -0.25)),
std::make_tuple(Point3( 0.375, 0.85, 0.25), Point3( 0.375, 0.85, -0.25), Point3(-0.375, 0.85, -0.25)),
std::make_tuple(Point3(-0.375, 0.85, -0.25), Point3( 0.375, 0.85, -0.25), Point3(-0.375, -0.85, -0.25)),
std::make_tuple(Point3( 0.375, 0.85, -0.25), Point3( 0.375, -0.85, -0.25), Point3(-0.375, -0.85, -0.25)),
std::make_tuple(Point3(-0.375, -0.85, -0.25), Point3( 0.375, -0.85, -0.25), Point3(-0.375, -0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, -0.25), Point3( 0.375, -0.85, 0.25), Point3(-0.375, -0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, 0.25), Point3( 0.375, -0.85, -0.25), Point3( 0.375, 0.85, 0.25)),
std::make_tuple(Point3( 0.375, -0.85, -0.25), Point3( 0.375, 0.85, -0.25), Point3( 0.375, 0.85, 0.25)),
std::make_tuple(Point3(-0.375, -0.85, -0.25), Point3(-0.375, -0.85, 0.25), Point3(-0.375, 0.85, -0.25)),
std::make_tuple(Point3(-0.375, -0.85, 0.25), Point3(-0.375, 0.85, 0.25), Point3(-0.375, 0.85, -0.25))
};
object = engine->AddObject();
engine->AddComponent<PositionComponent>(object);
engine->AddComponent<OrientationComponent>(object);
engine->AddComponent<BoundingComponent>(object, Point3(-0.375f, -0.85f, -0.25f), Point3(0.75f, 1.7f, 0.5f));
engine->AddComponent<ModelComponent>(object, triangles);
InitObject();
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownBounds = engine->GetComponent<BoundingComponent>(object);
/* gravity */
ownPos->position.Derivative(1) = Point3(0, -9.8f, 0);
/* collision detection and response */
engine->systems.Get<EventManager>()->ListenFor("integrator", "ticked", [this, ownPos, ownBounds] (Arg delta) {
auto &prev = ownPos->position.GetPrevious();
auto &curr = *ownPos->position;
auto &vel = *ownPos->position.Derivative();
Point3 normal;
float entryTime = 0.0f;
auto pair = engine->objects.right.equal_range(&typeid(BoundingComponent));
/* loop until all collisions have been resolved */
while(entryTime != 1.0f) {
auto tickVel = vel * delta.float_;
entryTime = 1.0f;
/* find collision with soonest entry time */
for(auto it = pair.first; it != pair.second; ++it) {
auto id = it->get_left();
/* don't check for collisions with self */
if(id == object) { continue; }
auto objPos = engine->GetComponent<PositionComponent>(id);
if(objPos != nullptr) {
auto objBounds = engine->GetComponent<BoundingComponent>(id);
if(objBounds != nullptr) {
auto r = ownBounds->box.AABBSwept(objBounds->box, std::make_tuple(prev, curr, tickVel), *objPos->position);
if(std::get<0>(r) < entryTime) { std::tie(entryTime, normal) = r; }
}
}
}
/* respond to collision */
if(entryTime < 1.0f) {
/* project previous position to point of entry of collision */
prev += tickVel * entryTime;
/* project position onto surface by subtracting surface-to-end vector */
curr -= normal * glm::dot(tickVel, normal);
/* project velocity onto surface too
* y is given a bounce factor of 0.125
*/
vel -= normal * glm::dot(Point3(vel.x, vel.y * 1.125f, vel.z), normal);
}
}
});
}
void PlayerController::Update(DeltaTicks &dt) {
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownOrient = engine->GetComponent<OrientationComponent>(object);
auto rel = glm::normalize(Point4((moveLeft ? -1 : 0) + (moveRight ? 1 : 0), 0, (moveForward ? -1 : 0) + (moveBackward ? 1 : 0), 1));
auto abs = (glm::inverse(ownOrient->orientation) * rel) * 3.5f; /* 4 meters per second */
ownPos->position.Derivative()->x = abs.x;
//pos->position.Derivative()->y = abs.y;
ownPos->position.Derivative()->z = abs.z;
}
<|endoftext|> |
<commit_before>//
// C++ Implementation: localbero
//
// Description:
//
//
// Author: FThauer FHammer <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "localbero.h"
using namespace std;
LocalBeRo::LocalBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS)
: BeRoInterface(), myHand(hi), myBeRoID(gS), myID(id), dealerPosition(dP), smallBlindPosition(0), dealerPositionId(dP), smallBlindPositionId(0), bigBlindPositionId(0), smallBlind(sB), highestSet(false), minimumRaise(2*sB), firstRun(true), firstRound(true), firstHeadsUpRound(true), currentPlayersTurnId(0), firstRoundLastPlayersTurnId(0), logBoardCardsDone(false)
{
currentPlayersTurnIt = myHand->getRunningPlayerList()->begin();
lastPlayersTurnIt = myHand->getRunningPlayerList()->begin();
PlayerListConstIterator it_c;
// determine bigBlindPosition
for(it_c=myHand->getActivePlayerList()->begin(); it_c!=myHand->getActivePlayerList()->end(); it_c++) {
if((*it_c)->getMyButton() == BUTTON_BIG_BLIND) {
bigBlindPositionId = (*it_c)->getMyUniqueID();
break;
}
}
assert(it_c!=myHand->getActivePlayerList()->end());
// determine smallBlindPosition
for(it_c=myHand->getActivePlayerList()->begin(); it_c!=myHand->getActivePlayerList()->end(); it_c++) {
if((*it_c)->getMyButton() == BUTTON_SMALL_BLIND) {
smallBlindPositionId = (*it_c)->getMyUniqueID();
break;
}
}
assert(it_c!=myHand->getActivePlayerList()->end());
// int i;
//SmallBlind-Position ermitteln
// for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// if (myHand->getPlayerArray()[i]->getMyButton() == 2) smallBlindPosition = i;
// }
}
LocalBeRo::~LocalBeRo()
{
}
void LocalBeRo::nextPlayer() {
// myHand->getPlayerArray()[playersTurn]->action();
// cout << "playerID in nextPlayer(): " << (*currentPlayersTurnIt)->getMyID() << endl;
PlayerListConstIterator currentPlayersTurnConstIt = myHand->getRunningPlayerIt(currentPlayersTurnId);
assert( currentPlayersTurnConstIt != myHand->getRunningPlayerList()->end() );
(*currentPlayersTurnConstIt)->action();
}
void LocalBeRo::run() {
int i;
PlayerListIterator it;
if (firstRun) {
// determine smallBlindPosition
PlayerListIterator smallBlindPositionIt;
for(smallBlindPositionIt=myHand->getActivePlayerList()->begin(); smallBlindPositionIt!=myHand->getActivePlayerList()->end(); smallBlindPositionIt++) {
if((*smallBlindPositionIt)->getMyButton() == BUTTON_SMALL_BLIND) break;
}
// determine running player before smallBlind (for heads up: determine dealer/smallblind)
PlayerListIterator it_1, it_2;
size_t i;
// running player before smallBlind
if(myHand->getActivePlayerList()->size() > 2) {
it_1 = smallBlindPositionIt;
for(i=0; i<myHand->getActivePlayerList()->size(); i++) {
if(it_1 == myHand->getActivePlayerList()->begin()) it_1 = myHand->getActivePlayerList()->end();
it_1--;
it_2 = find(myHand->getRunningPlayerList()->begin(), myHand->getRunningPlayerList()->end(), *it_1);
// running player found
if(it_2 != myHand->getRunningPlayerList()->end()) {
lastPlayersTurnIt = it_2;
break;
}
}
}
// heads up: bigBlind begins -> dealer/smallBlind is running player before bigBlind
else {
it_1 = find(myHand->getRunningPlayerList()->begin(), myHand->getRunningPlayerList()->end(), *smallBlindPositionIt);
if( it_1 == myHand->getRunningPlayerList()->end() ) {
cout << "ERROR - lastPlayersTurnIt-detection in localBeRo" << endl;
}
// smallBlind found
else {
lastPlayersTurnIt = it_1;
}
}
currentPlayersTurnIt = lastPlayersTurnIt;
myHand->getGuiInterface()->dealBeRoCards(myBeRoID);
firstRun = false;
}
else {
//log the turned cards
if(!logBoardCardsDone) {
int tempBoardCardsArray[5];
myHand->getBoard()->getMyCards(tempBoardCardsArray);
switch(myBeRoID) {
case GAME_STATE_FLOP: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2]);
break;
case GAME_STATE_TURN: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3]);
break;
case GAME_STATE_RIVER: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3], tempBoardCardsArray[4]);
break;
default: { cout << "ERROR in localbero.cpp - wrong myBeRoID" << endl;}
}
logBoardCardsDone = true;
}
bool allHighestSet = true;
// prfe, ob alle Sets gleich sind ( falls nicht, dann allHighestSet = 0 )
// for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// if(myHand->getPlayerArray()[i]->getMyActiveStatus() && myHand->getPlayerArray()[i]->getMyAction() != 1 && myHand->getPlayerArray()[i]->getMyAction() != 6) {
// if(highestSet != myHand->getPlayerArray()[i]->getMySet()) { allHighestSet=0; }
// }
// }
// test if all running players have same sets (else allHighestSet = false)
for(it=myHand->getRunningPlayerList()->begin(); it!=myHand->getRunningPlayerList()->end(); it++) {
if(highestSet != (*it)->getMySet()) {
allHighestSet = false;
}
}
// prfen, ob aktuelle bero wirklich dran ist
if(!firstRound && allHighestSet) {
// aktuelle bero nicht dran, weil alle Sets gleich sind
//also gehe in naechste bero
myHand->setActualRound(myBeRoID+1);
//Action loeschen und ActionButtons refresh
// for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// if(myHand->getPlayerArray()[i]->getMyAction() != 1 && myHand->getPlayerArray()[i]->getMyAction() != 6) myHand->getPlayerArray()[i]->setMyAction(0);
// }
//Action loeschen und ActionButtons refresh
for(it=myHand->getRunningPlayerList()->begin(); it!=myHand->getRunningPlayerList()->end(); it++) {
(*it)->setMyAction(PLAYER_ACTION_NONE);
}
//Sets in den Pot verschieben und Sets = 0 und Pot-refresh
myHand->getBoard()->collectSets();
myHand->getBoard()->collectPot();
myHand->getGuiInterface()->refreshPot();
myHand->getGuiInterface()->refreshSet();
myHand->getGuiInterface()->refreshCash();
for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { myHand->getGuiInterface()->refreshAction(i,PLAYER_ACTION_NONE); }
myHand->switchRounds();
}
else {
// aktuelle bero ist wirklich dran
// Anzahl der effektiv gespielten Runden (des human player) erhöhen
if(myHand->getPlayerArray()[0]->getMyActiveStatus() && myHand->getPlayerArray()[0]->getMyAction() != 1) {
myHand->setBettingRoundsPlayed(myBeRoID);
}
//// !!!!!!!!!!!!!!!!1!!!! very buggy, rule breaking -> TODO !!!!!!!!!!!!11!!!!!!!! //////////////
//// headsup:
//// preflop: dealer is small blind and begins
//// flop, trun, river: big blind begins
//// !!!!!!!!! attention: exception if player failed before !!!!!!!!
// if( !(myHand->getActualQuantityPlayers() < 3 && firstHeadsUpRound == 1) || myHand->getPlayerArray()[playersTurn]->getMyActiveStatus() == 0 ) {
// not first round in heads up (for headsup dealer is smallblind so it is dealers turn)
// naechsten Spieler ermitteln
// int i;
// for(i=0; (i<MAX_NUMBER_OF_PLAYERS && ((myHand->getPlayerArray()[playersTurn]->getMyActiveStatus()) == 0 || (myHand->getPlayerArray()[playersTurn]->getMyAction())==1 || (myHand->getPlayerArray()[playersTurn]->getMyAction())==6)) || i==0; i++) {
// playersTurn = (playersTurn+1)%(MAX_NUMBER_OF_PLAYERS);
// }
// firstHeadsUpRound = 0;
// determine next running player
currentPlayersTurnIt++;
if(currentPlayersTurnIt == myHand->getRunningPlayerList()->end()) currentPlayersTurnIt = myHand->getRunningPlayerList()->begin();
// }
// else { firstHeadsUpRound = 0; }
////// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ////////////////
//Spieler-Position vor SmallBlind-Position ermitteln
// int activePlayerBeforeSmallBlind = smallBlindPosition;
// for(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(myHand->getPlayerArray()[activePlayerBeforeSmallBlind]->getMyActiveStatus()) || (myHand->getPlayerArray()[activePlayerBeforeSmallBlind]->getMyAction())==1 || (myHand->getPlayerArray()[activePlayerBeforeSmallBlind]->getMyAction())==6) || i==0; i++) {
// activePlayerBeforeSmallBlind = (activePlayerBeforeSmallBlind + MAX_NUMBER_OF_PLAYERS - 1 ) % (MAX_NUMBER_OF_PLAYERS);
// }
// myHand->getPlayerArray()[playersTurn]->setMyTurn(1);
(*currentPlayersTurnIt)->setMyTurn(true);
//highlight active players groupbox and clear action
myHand->getGuiInterface()->refreshGroupbox((*currentPlayersTurnIt)->getMyID(),2);
myHand->getGuiInterface()->refreshAction((*currentPlayersTurnIt)->getMyID(),0);
// wenn wir letzter aktiver Spieler vor SmallBlind sind, dann flopFirstRound zuende
// ausnahme bei heads up !!! --> TODO
// if(myHand->getPlayerArray()[playersTurn]->getMyID() == activePlayerBeforeSmallBlind && myHand->getActivePlayerList()->size() >= 3) { firstRound = 0; }
// if(myHand->getActivePlayerList()->size() < 3 && (myHand->getPlayerArray()[playersTurn]->getMyID() == dealerPosition || myHand->getPlayerArray()[playersTurn]->getMyID() == smallBlindPosition)) { firstRound = 0; }
if( (*currentPlayersTurnIt) == (*lastPlayersTurnIt) ) {
firstRound = false;
}
if((*currentPlayersTurnIt)->getMyID() == 0) {
// Wir sind dran
myHand->getGuiInterface()->meInAction();
}
else {
//Gegner sind dran
myHand->getGuiInterface()->beRoAnimation2(myBeRoID);
}
}
}
}
<commit_msg>adds activePlayerList and runningPlayerList (XV) - !!! BROKEN !!! - last sable rev866<commit_after>//
// C++ Implementation: localbero
//
// Description:
//
//
// Author: FThauer FHammer <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "localbero.h"
using namespace std;
LocalBeRo::LocalBeRo(HandInterface* hi, int id, unsigned dP, int sB, GameState gS)
: BeRoInterface(), myHand(hi), myBeRoID(gS), myID(id), dealerPosition(dP), smallBlindPosition(0), dealerPositionId(dP), smallBlindPositionId(0), bigBlindPositionId(0), smallBlind(sB), highestSet(false), minimumRaise(2*sB), firstRun(true), firstRound(true), firstHeadsUpRound(true), currentPlayersTurnId(0), firstRoundLastPlayersTurnId(0), logBoardCardsDone(false)
{
currentPlayersTurnIt = myHand->getRunningPlayerList()->begin();
lastPlayersTurnIt = myHand->getRunningPlayerList()->begin();
PlayerListConstIterator it_c;
// determine bigBlindPosition
for(it_c=myHand->getActivePlayerList()->begin(); it_c!=myHand->getActivePlayerList()->end(); it_c++) {
if((*it_c)->getMyButton() == BUTTON_BIG_BLIND) {
bigBlindPositionId = (*it_c)->getMyUniqueID();
break;
}
}
assert(it_c!=myHand->getActivePlayerList()->end());
// determine smallBlindPosition
for(it_c=myHand->getActivePlayerList()->begin(); it_c!=myHand->getActivePlayerList()->end(); it_c++) {
if((*it_c)->getMyButton() == BUTTON_SMALL_BLIND) {
smallBlindPositionId = (*it_c)->getMyUniqueID();
break;
}
}
assert(it_c!=myHand->getActivePlayerList()->end());
// int i;
//SmallBlind-Position ermitteln
// for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// if (myHand->getPlayerArray()[i]->getMyButton() == 2) smallBlindPosition = i;
// }
}
LocalBeRo::~LocalBeRo()
{
}
void LocalBeRo::nextPlayer() {
// myHand->getPlayerArray()[playersTurn]->action();
// cout << "playerID in nextPlayer(): " << (*currentPlayersTurnIt)->getMyID() << endl;
PlayerListConstIterator currentPlayersTurnConstIt = myHand->getRunningPlayerIt(currentPlayersTurnId);
assert( currentPlayersTurnConstIt != myHand->getRunningPlayerList()->end() );
(*currentPlayersTurnConstIt)->action();
}
void LocalBeRo::run() {
int i;
PlayerListIterator it;
if (firstRun) {
/*
// PlayerListIterator it;
// search bigBlindPosition in runningPlayerList -> old: delete
// it_1 = find(getMyHand()->getRunningPlayerList()->begin(), getMyHand()->getRunningPlayerList()->end(), *bigBlindPositionIt);
// search bigBlindPosition in runningPlayerList
// PlayerListIterator bigBlindPositionIt = getMyHand()->getRunningPlayerIt(getBigBlindPositionId());
// more than 2 players are still active -> runningPlayerList is not empty
if(getMyHand()->getActivePlayerList()->size() > 2) {
// bigBlindPlayer not found in runningPlayerList (he is all in) -> bigBlindPlayer is not the running player before first action player
if(bigBlindPositionIt == getMyHand()->getRunningPlayerList()->end()) {
// search smallBlindPosition in runningPlayerList
PlayerListIterator smallBlindPositionIt = getMyHand()->getRunningPlayerIt(getSmallBlindPositionId());
// if(smallBlindPositionIt == getMyHand()->getActivePlayerList()->begin()) smallBlindPositionIt = getMyHand()->getActivePlayerList()->end();
// smallBlindPositionIt--;
// it_2 = find(getMyHand()->getRunningPlayerList()->begin(), getMyHand()->getRunningPlayerList()->end(), *smallBlindPositionIt);
// smallBlindPlayer not found in runningPlayerList (he is all in) -> next active player before smallBlindPlayer is running player before first action player
if(smallBlindPositionIt == getMyHand()->getRunningPlayerList()->end()) {
it = getMyHand()->getActivePlayerIt(getSmallBlindPositionId());
assert(it != getMyHand()->getActivePlayerList()->end());
if(it == getMyHand()->getActivePlayerList()->begin()) it = getMyHand()->getActivePlayerList()->end();
it--;
setFirstRoundLastPlayersTurnId( (*it)->getMyUniqueID() );
// it_3 = find(getMyHand()->getRunningPlayerList()->begin(), getMyHand()->getRunningPlayerList()->end(), *it_2);
// if(it_3 == getMyHand()->getRunningPlayerList()->end()) {
// cout << "ERROR - lastPlayersTurnIt-detection in localBeRoPreflop" << endl;
// } else {
// setLastPlayersTurnIt(it_3);
// }
}
// smallBlindPlayer found in runningPlayerList -> running player before first action player
else {
setFirstRoundLastPlayersTurnId( getSmallBlindPositionId() );
}
}
// bigBlindPlayer found in runningPlayerList -> player before first action player
else {
setFirstRoundLastPlayersTurnId( getBigBlindPositionId() );
}
}
// heads up -> dealer/smallBlindPlayer is first action player and bigBlindPlayer is player before
else {
// bigBlindPlayer not found in runningPlayerList (he is all in) -> only smallBlind has to choose fold or call the bigBlindAmount
if(bigBlindPositionIt == getMyHand()->getRunningPlayerList()->end()) {
// search smallBlindPosition in runningPlayerList
PlayerListIterator smallBlindPositionIt = getMyHand()->getRunningPlayerIt(getSmallBlindPositionId());
// smallBlindPlayer not found in runningPlayerList (he is all in) -> no running player -> showdown and no firstRoundLastPlayersTurnId is used
if(smallBlindPositionIt == getMyHand()->getRunningPlayerList()->end()) {
}
// smallBlindPlayer found in runningPlayerList -> running player before first action player (himself)
else {
setFirstRoundLastPlayersTurnId( getSmallBlindPositionId() );
}
}
setFirstRoundLastPlayersTurnId( getBigBlindPositionId() );
}
setCurrentPlayersTurnId( getFirstRoundLastPlayersTurnId() );
// determine smallBlindPosition
PlayerListIterator smallBlindPositionIt;
for(smallBlindPositionIt=myHand->getActivePlayerList()->begin(); smallBlindPositionIt!=myHand->getActivePlayerList()->end(); smallBlindPositionIt++) {
if((*smallBlindPositionIt)->getMyButton() == BUTTON_SMALL_BLIND) break;
}
// determine running player before smallBlind (for heads up: determine dealer/smallblind)
PlayerListIterator it_1, it_2;
size_t i;
// running player before smallBlind
if(myHand->getActivePlayerList()->size() > 2) {
it_1 = smallBlindPositionIt;
for(i=0; i<myHand->getActivePlayerList()->size(); i++) {
if(it_1 == myHand->getActivePlayerList()->begin()) it_1 = myHand->getActivePlayerList()->end();
it_1--;
it_2 = find(myHand->getRunningPlayerList()->begin(), myHand->getRunningPlayerList()->end(), *it_1);
// running player found
if(it_2 != myHand->getRunningPlayerList()->end()) {
lastPlayersTurnIt = it_2;
break;
}
}
}
// heads up: bigBlind begins -> dealer/smallBlind is running player before bigBlind
else {
it_1 = find(myHand->getRunningPlayerList()->begin(), myHand->getRunningPlayerList()->end(), *smallBlindPositionIt);
if( it_1 == myHand->getRunningPlayerList()->end() ) {
cout << "ERROR - lastPlayersTurnIt-detection in localBeRo" << endl;
}
// smallBlind found
else {
lastPlayersTurnIt = it_1;
}
}
currentPlayersTurnIt = lastPlayersTurnIt;
*/
// determine smallBlindPosition
// PlayerListIterator smallBlindPositionIt;
// for(smallBlindPositionIt=myHand->getActivePlayerList()->begin(); smallBlindPositionIt!=myHand->getActivePlayerList()->end(); smallBlindPositionIt++) {
// if((*smallBlindPositionIt)->getMyButton() == BUTTON_SMALL_BLIND) break;
// }
// determine running player before smallBlind (for heads up: determine dealer/smallblind)
PlayerListIterator it_1, it_2;
size_t i;
// running player before smallBlind
if(myHand->getActivePlayerList()->size() > 2) {
it_1 = myHand->getActivePlayerIt(smallBlindPositionId);
assert( it_1 != myHand->getActivePlayerList()->end() );
for(i=0; i<myHand->getActivePlayerList()->size(); i++) {
if(it_1 == myHand->getActivePlayerList()->begin()) it_1 = myHand->getActivePlayerList()->end();
it_1--;
it_2 = find(myHand->getRunningPlayerList()->begin(), myHand->getRunningPlayerList()->end(), *it_1);
// running player found
if(it_2 != myHand->getRunningPlayerList()->end()) {
lastPlayersTurnIt = it_2;
break;
}
}
}
// heads up: bigBlind begins -> dealer/smallBlind is running player before bigBlind
else {
//TODO
// it_1 = find(myHand->getRunningPlayerList()->begin(), myHand->getRunningPlayerList()->end(), *smallBlindPositionIt);
if( it_1 == myHand->getRunningPlayerList()->end() ) {
cout << "ERROR - lastPlayersTurnIt-detection in localBeRo" << endl;
}
// smallBlind found
else {
lastPlayersTurnIt = it_1;
}
}
currentPlayersTurnIt = lastPlayersTurnIt;
myHand->getGuiInterface()->dealBeRoCards(myBeRoID);
firstRun = false;
}
else {
//log the turned cards
if(!logBoardCardsDone) {
int tempBoardCardsArray[5];
myHand->getBoard()->getMyCards(tempBoardCardsArray);
switch(myBeRoID) {
case GAME_STATE_FLOP: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2]);
break;
case GAME_STATE_TURN: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3]);
break;
case GAME_STATE_RIVER: myHand->getGuiInterface()->logDealBoardCardsMsg(myBeRoID, tempBoardCardsArray[0], tempBoardCardsArray[1], tempBoardCardsArray[2], tempBoardCardsArray[3], tempBoardCardsArray[4]);
break;
default: { cout << "ERROR in localbero.cpp - wrong myBeRoID" << endl;}
}
logBoardCardsDone = true;
}
bool allHighestSet = true;
// prfe, ob alle Sets gleich sind ( falls nicht, dann allHighestSet = 0 )
// for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// if(myHand->getPlayerArray()[i]->getMyActiveStatus() && myHand->getPlayerArray()[i]->getMyAction() != 1 && myHand->getPlayerArray()[i]->getMyAction() != 6) {
// if(highestSet != myHand->getPlayerArray()[i]->getMySet()) { allHighestSet=0; }
// }
// }
// test if all running players have same sets (else allHighestSet = false)
for(it=myHand->getRunningPlayerList()->begin(); it!=myHand->getRunningPlayerList()->end(); it++) {
if(highestSet != (*it)->getMySet()) {
allHighestSet = false;
}
}
// prfen, ob aktuelle bero wirklich dran ist
if(!firstRound && allHighestSet) {
// aktuelle bero nicht dran, weil alle Sets gleich sind
//also gehe in naechste bero
myHand->setActualRound(myBeRoID+1);
//Action loeschen und ActionButtons refresh
// for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {
// if(myHand->getPlayerArray()[i]->getMyAction() != 1 && myHand->getPlayerArray()[i]->getMyAction() != 6) myHand->getPlayerArray()[i]->setMyAction(0);
// }
//Action loeschen und ActionButtons refresh
for(it=myHand->getRunningPlayerList()->begin(); it!=myHand->getRunningPlayerList()->end(); it++) {
(*it)->setMyAction(PLAYER_ACTION_NONE);
}
//Sets in den Pot verschieben und Sets = 0 und Pot-refresh
myHand->getBoard()->collectSets();
myHand->getBoard()->collectPot();
myHand->getGuiInterface()->refreshPot();
myHand->getGuiInterface()->refreshSet();
myHand->getGuiInterface()->refreshCash();
for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { myHand->getGuiInterface()->refreshAction(i,PLAYER_ACTION_NONE); }
myHand->switchRounds();
}
else {
// aktuelle bero ist wirklich dran
// Anzahl der effektiv gespielten Runden (des human player) erhöhen
if(myHand->getPlayerArray()[0]->getMyActiveStatus() && myHand->getPlayerArray()[0]->getMyAction() != 1) {
myHand->setBettingRoundsPlayed(myBeRoID);
}
//// !!!!!!!!!!!!!!!!1!!!! very buggy, rule breaking -> TODO !!!!!!!!!!!!11!!!!!!!! //////////////
//// headsup:
//// preflop: dealer is small blind and begins
//// flop, trun, river: big blind begins
//// !!!!!!!!! attention: exception if player failed before !!!!!!!!
// if( !(myHand->getActualQuantityPlayers() < 3 && firstHeadsUpRound == 1) || myHand->getPlayerArray()[playersTurn]->getMyActiveStatus() == 0 ) {
// not first round in heads up (for headsup dealer is smallblind so it is dealers turn)
// naechsten Spieler ermitteln
// int i;
// for(i=0; (i<MAX_NUMBER_OF_PLAYERS && ((myHand->getPlayerArray()[playersTurn]->getMyActiveStatus()) == 0 || (myHand->getPlayerArray()[playersTurn]->getMyAction())==1 || (myHand->getPlayerArray()[playersTurn]->getMyAction())==6)) || i==0; i++) {
// playersTurn = (playersTurn+1)%(MAX_NUMBER_OF_PLAYERS);
// }
// firstHeadsUpRound = 0;
// determine next running player
currentPlayersTurnIt++;
if(currentPlayersTurnIt == myHand->getRunningPlayerList()->end()) currentPlayersTurnIt = myHand->getRunningPlayerList()->begin();
// }
// else { firstHeadsUpRound = 0; }
////// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ////////////////
//Spieler-Position vor SmallBlind-Position ermitteln
// int activePlayerBeforeSmallBlind = smallBlindPosition;
// for(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(myHand->getPlayerArray()[activePlayerBeforeSmallBlind]->getMyActiveStatus()) || (myHand->getPlayerArray()[activePlayerBeforeSmallBlind]->getMyAction())==1 || (myHand->getPlayerArray()[activePlayerBeforeSmallBlind]->getMyAction())==6) || i==0; i++) {
// activePlayerBeforeSmallBlind = (activePlayerBeforeSmallBlind + MAX_NUMBER_OF_PLAYERS - 1 ) % (MAX_NUMBER_OF_PLAYERS);
// }
// myHand->getPlayerArray()[playersTurn]->setMyTurn(1);
(*currentPlayersTurnIt)->setMyTurn(true);
//highlight active players groupbox and clear action
myHand->getGuiInterface()->refreshGroupbox((*currentPlayersTurnIt)->getMyID(),2);
myHand->getGuiInterface()->refreshAction((*currentPlayersTurnIt)->getMyID(),0);
// wenn wir letzter aktiver Spieler vor SmallBlind sind, dann flopFirstRound zuende
// ausnahme bei heads up !!! --> TODO
// if(myHand->getPlayerArray()[playersTurn]->getMyID() == activePlayerBeforeSmallBlind && myHand->getActivePlayerList()->size() >= 3) { firstRound = 0; }
// if(myHand->getActivePlayerList()->size() < 3 && (myHand->getPlayerArray()[playersTurn]->getMyID() == dealerPosition || myHand->getPlayerArray()[playersTurn]->getMyID() == smallBlindPosition)) { firstRound = 0; }
if( (*currentPlayersTurnIt) == (*lastPlayersTurnIt) ) {
firstRound = false;
}
if((*currentPlayersTurnIt)->getMyID() == 0) {
// Wir sind dran
myHand->getGuiInterface()->meInAction();
}
else {
//Gegner sind dran
myHand->getGuiInterface()->beRoAnimation2(myBeRoID);
}
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Precompiled.h"
#include "Console.h"
#include "Context.h"
#include "CoreEvents.h"
#include "DropDownList.h"
#include "EngineEvents.h"
#include "Font.h"
#include "Graphics.h"
#include "GraphicsEvents.h"
#include "Input.h"
#include "InputEvents.h"
#include "IOEvents.h"
#include "LineEdit.h"
#include "ListView.h"
#include "Log.h"
#include "ResourceCache.h"
#include "ScrollBar.h"
#include "Text.h"
#include "UI.h"
#include "UIEvents.h"
#include "DebugNew.h"
namespace Urho3D
{
static const int DEFAULT_CONSOLE_ROWS = 16;
static const int DEFAULT_HISTORY_SIZE = 16;
Console::Console(Context* context) :
Object(context),
autoVisibleOnError_(false),
historyRows_(DEFAULT_HISTORY_SIZE),
historyPosition_(0),
printing_(false)
{
UI* ui = GetSubsystem<UI>();
UIElement* uiRoot = ui->GetRoot();
// By default prevent the automatic showing of the screen keyboard
focusOnShow_ = !ui->GetUseScreenKeyboard();
background_ = uiRoot->CreateChild<BorderImage>();
background_->SetBringToBack(false);
background_->SetClipChildren(true);
background_->SetEnabled(true);
background_->SetVisible(false); // Hide by default
background_->SetPriority(200); // Show on top of the debug HUD
background_->SetBringToBack(false);
background_->SetLayout(LM_VERTICAL);
rowContainer_ = background_->CreateChild<ListView>();
rowContainer_->SetHighlightMode(HM_ALWAYS);
rowContainer_->SetMultiselect(true);
commandLine_ = background_->CreateChild<UIElement>();
commandLine_->SetLayoutMode(LM_HORIZONTAL);
commandLine_->SetLayoutSpacing(1);
interpreters_ = commandLine_->CreateChild<DropDownList>();
lineEdit_ = commandLine_->CreateChild<LineEdit>();
lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
closeButton_ = uiRoot->CreateChild<Button>();
closeButton_->SetVisible(false);
closeButton_->SetPriority(background_->GetPriority() + 1); // Show on top of console's background
closeButton_->SetBringToBack(false);
SetNumRows(DEFAULT_CONSOLE_ROWS);
SubscribeToEvent(interpreters_, E_ITEMSELECTED, HANDLER(Console, HandleInterpreterSelected));
SubscribeToEvent(lineEdit_, E_TEXTFINISHED, HANDLER(Console, HandleTextFinished));
SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, HANDLER(Console, HandleLineEditKey));
SubscribeToEvent(closeButton_, E_RELEASED, HANDLER(Console, HandleCloseButtonPressed));
SubscribeToEvent(E_SCREENMODE, HANDLER(Console, HandleScreenMode));
SubscribeToEvent(E_LOGMESSAGE, HANDLER(Console, HandleLogMessage));
SubscribeToEvent(E_POSTUPDATE, HANDLER(Console, HandlePostUpdate));
}
Console::~Console()
{
background_->Remove();
closeButton_->Remove();
}
void Console::SetDefaultStyle(XMLFile* style)
{
if (!style)
return;
background_->SetDefaultStyle(style);
background_->SetStyle("ConsoleBackground");
rowContainer_->SetStyleAuto();
for (unsigned i = 0; i < rowContainer_->GetNumItems(); ++i)
rowContainer_->GetItem(i)->SetStyle("ConsoleText");
interpreters_->SetStyleAuto();
for (unsigned i = 0; i < interpreters_->GetNumItems(); ++i)
interpreters_->GetItem(i)->SetStyle("ConsoleText");
lineEdit_->SetStyle("ConsoleLineEdit");
closeButton_->SetDefaultStyle(style);
closeButton_->SetStyle("CloseButton");
UpdateElements();
}
void Console::SetVisible(bool enable)
{
Input* input = GetSubsystem<Input>();
background_->SetVisible(enable);
closeButton_->SetVisible(enable);
if (enable)
{
// Check if we have receivers for E_CONSOLECOMMAND every time here in case the handler is being added later dynamically
bool hasInterpreter = PopulateInterpreter();
commandLine_->SetVisible(hasInterpreter);
if (hasInterpreter && focusOnShow_)
GetSubsystem<UI>()->SetFocusElement(lineEdit_);
// Ensure the background has no empty space when shown without the lineedit
background_->SetHeight(background_->GetMinHeight());
// Show OS mouse
savedMouseVisibility_ = input->IsMouseVisible();
input->SetMouseVisible(true);
}
else
{
interpreters_->SetFocus(false);
lineEdit_->SetFocus(false);
// Restore OS mouse visibility
input->SetMouseVisible(savedMouseVisibility_);
}
}
void Console::Toggle()
{
SetVisible(!IsVisible());
}
void Console::SetNumBufferedRows(unsigned rows)
{
if (rows < displayedRows_)
return;
rowContainer_->DisableLayoutUpdate();
int delta = rowContainer_->GetNumItems() - rows;
if (delta > 0)
{
// We have more, remove oldest rows first
for (int i = 0; i < delta; ++i)
rowContainer_->RemoveItem((unsigned)0);
}
else
{
// We have less, add more rows at the top
for (int i = 0; i > delta; --i)
{
Text* text = new Text(context_);
// If style is already set, apply here to ensure proper height of the console when
// amount of rows is changed
if (background_->GetDefaultStyle())
text->SetStyle("ConsoleText");
rowContainer_->InsertItem(0, text);
}
}
rowContainer_->EnsureItemVisibility(rowContainer_->GetItem(rowContainer_->GetNumItems() - 1));
rowContainer_->EnableLayoutUpdate();
rowContainer_->UpdateLayout();
UpdateElements();
}
void Console::SetNumRows(unsigned rows)
{
if (!rows)
return;
displayedRows_ = rows;
if (GetNumBufferedRows() < rows)
SetNumBufferedRows(rows);
UpdateElements();
}
void Console::SetNumHistoryRows(unsigned rows)
{
historyRows_ = rows;
if (history_.Size() > rows)
history_.Resize(rows);
if (historyPosition_ > rows)
historyPosition_ = rows;
}
void Console::SetFocusOnShow(bool enable)
{
focusOnShow_ = enable;
}
void Console::UpdateElements()
{
int width = GetSubsystem<Graphics>()->GetWidth();
const IntRect& border = background_->GetLayoutBorder();
const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
rowContainer_->SetFixedHeight(displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
(rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
background_->SetFixedWidth(width);
background_->SetHeight(background_->GetMinHeight());
}
XMLFile* Console::GetDefaultStyle() const
{
return background_->GetDefaultStyle(false);
}
bool Console::IsVisible() const
{
return background_ && background_->IsVisible();
}
unsigned Console::GetNumBufferedRows() const
{
return rowContainer_->GetNumItems();
}
void Console::CopySelectedRows() const
{
rowContainer_->CopySelectedItemsToClipboard();
}
const String& Console::GetHistoryRow(unsigned index) const
{
return index < history_.Size() ? history_[index] : String::EMPTY;
}
bool Console::PopulateInterpreter()
{
interpreters_->RemoveAllItems();
HashSet<Object*>* receivers = context_->GetEventReceivers(E_CONSOLECOMMAND);
if (!receivers || receivers->Empty())
return false;
Vector<String> names;
for (HashSet<Object*>::ConstIterator iter = receivers->Begin(); iter != receivers->End(); ++iter)
names.Push((*iter)->GetTypeName());
Sort(names.Begin(), names.End());
unsigned selection = M_MAX_UNSIGNED;
for (unsigned i = 0; i < names.Size(); ++i)
{
const String& name = names[i];
if (name == commandInterpreter_)
selection = i;
Text* text = new Text(context_);
text->SetStyle("ConsoleText");
text->SetText(name);
interpreters_->AddItem(text);
}
const IntRect& border = interpreters_->GetPopup()->GetLayoutBorder();
interpreters_->SetMaxWidth(interpreters_->GetListView()->GetContentElement()->GetWidth() + border.left_ + border.right_);
bool enabled = interpreters_->GetNumItems() > 1;
interpreters_->SetEnabled(enabled);
interpreters_->SetFocusMode(enabled ? FM_FOCUSABLE_DEFOCUSABLE : FM_NOTFOCUSABLE);
if (selection == M_MAX_UNSIGNED)
{
selection = 0;
commandInterpreter_ = names[selection];
}
interpreters_->SetSelection(selection);
return true;
}
void Console::HandleInterpreterSelected(StringHash eventType, VariantMap& eventData)
{
commandInterpreter_ = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
lineEdit_->SetFocus(true);
}
void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
{
using namespace TextFinished;
String line = lineEdit_->GetText();
if (!line.Empty())
{
// Send the command as an event for script subsystem
using namespace ConsoleCommand;
VariantMap& eventData = GetEventDataMap();
eventData[P_COMMAND] = line;
eventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
SendEvent(E_CONSOLECOMMAND, eventData);
// Store to history, then clear the lineedit
history_.Push(line);
if (history_.Size() > historyRows_)
history_.Erase(history_.Begin());
historyPosition_ = history_.Size();
currentRow_.Clear();
lineEdit_->SetText(currentRow_);
}
}
void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
{
if (!historyRows_)
return;
using namespace UnhandledKey;
bool changed = false;
switch (eventData[P_KEY].GetInt())
{
case KEY_UP:
if (historyPosition_ > 0)
{
if (historyPosition_ == history_.Size())
currentRow_ = lineEdit_->GetText();
--historyPosition_;
changed = true;
}
break;
case KEY_DOWN:
if (historyPosition_ < history_.Size())
{
++historyPosition_;
changed = true;
}
break;
}
if (changed)
{
if (historyPosition_ < history_.Size())
lineEdit_->SetText(history_[historyPosition_]);
else
lineEdit_->SetText(currentRow_);
}
}
void Console::HandleCloseButtonPressed(StringHash eventType, VariantMap& eventData)
{
SetVisible(false);
}
void Console::HandleScreenMode(StringHash eventType, VariantMap& eventData)
{
UpdateElements();
}
void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
{
// If printing a log message causes more messages to be logged (error accessing font), disregard them
if (printing_)
return;
using namespace LogMessage;
int level = eventData[P_LEVEL].GetInt();
// The message may be multi-line, so split to rows in that case
Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
for (unsigned i = 0; i < rows.Size(); ++i)
pendingRows_.Push(MakePair(level, rows[i]));
if (autoVisibleOnError_ && level == LOG_ERROR && !IsVisible())
SetVisible(true);
}
void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
return;
printing_ = true;
rowContainer_->DisableLayoutUpdate();
Text* text;
for (unsigned i = 0; i < pendingRows_.Size(); ++i)
{
rowContainer_->RemoveItem((unsigned)0);
text = new Text(context_);
text->SetText(pendingRows_[i].second_);
// Make error message highlight
text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
rowContainer_->AddItem(text);
}
pendingRows_.Clear();
rowContainer_->EnsureItemVisibility(text);
rowContainer_->EnableLayoutUpdate();
rowContainer_->UpdateLayout();
UpdateElements(); // May need to readjust the height due to scrollbar visibility changes
printing_ = false;
}
}
<commit_msg>Fix invisible console still gaining the input focus bug.<commit_after>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Precompiled.h"
#include "Console.h"
#include "Context.h"
#include "CoreEvents.h"
#include "DropDownList.h"
#include "EngineEvents.h"
#include "Font.h"
#include "Graphics.h"
#include "GraphicsEvents.h"
#include "Input.h"
#include "InputEvents.h"
#include "IOEvents.h"
#include "LineEdit.h"
#include "ListView.h"
#include "Log.h"
#include "ResourceCache.h"
#include "ScrollBar.h"
#include "Text.h"
#include "UI.h"
#include "UIEvents.h"
#include "DebugNew.h"
namespace Urho3D
{
static const int DEFAULT_CONSOLE_ROWS = 16;
static const int DEFAULT_HISTORY_SIZE = 16;
Console::Console(Context* context) :
Object(context),
autoVisibleOnError_(false),
historyRows_(DEFAULT_HISTORY_SIZE),
historyPosition_(0),
printing_(false)
{
UI* ui = GetSubsystem<UI>();
UIElement* uiRoot = ui->GetRoot();
// By default prevent the automatic showing of the screen keyboard
focusOnShow_ = !ui->GetUseScreenKeyboard();
background_ = uiRoot->CreateChild<BorderImage>();
background_->SetBringToBack(false);
background_->SetClipChildren(true);
background_->SetEnabled(true);
background_->SetVisible(false); // Hide by default
background_->SetPriority(200); // Show on top of the debug HUD
background_->SetBringToBack(false);
background_->SetLayout(LM_VERTICAL);
rowContainer_ = background_->CreateChild<ListView>();
rowContainer_->SetHighlightMode(HM_ALWAYS);
rowContainer_->SetMultiselect(true);
commandLine_ = background_->CreateChild<UIElement>();
commandLine_->SetLayoutMode(LM_HORIZONTAL);
commandLine_->SetLayoutSpacing(1);
interpreters_ = commandLine_->CreateChild<DropDownList>();
lineEdit_ = commandLine_->CreateChild<LineEdit>();
lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
closeButton_ = uiRoot->CreateChild<Button>();
closeButton_->SetVisible(false);
closeButton_->SetPriority(background_->GetPriority() + 1); // Show on top of console's background
closeButton_->SetBringToBack(false);
SetNumRows(DEFAULT_CONSOLE_ROWS);
SubscribeToEvent(interpreters_, E_ITEMSELECTED, HANDLER(Console, HandleInterpreterSelected));
SubscribeToEvent(lineEdit_, E_TEXTFINISHED, HANDLER(Console, HandleTextFinished));
SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, HANDLER(Console, HandleLineEditKey));
SubscribeToEvent(closeButton_, E_RELEASED, HANDLER(Console, HandleCloseButtonPressed));
SubscribeToEvent(E_SCREENMODE, HANDLER(Console, HandleScreenMode));
SubscribeToEvent(E_LOGMESSAGE, HANDLER(Console, HandleLogMessage));
SubscribeToEvent(E_POSTUPDATE, HANDLER(Console, HandlePostUpdate));
}
Console::~Console()
{
background_->Remove();
closeButton_->Remove();
}
void Console::SetDefaultStyle(XMLFile* style)
{
if (!style)
return;
background_->SetDefaultStyle(style);
background_->SetStyle("ConsoleBackground");
rowContainer_->SetStyleAuto();
for (unsigned i = 0; i < rowContainer_->GetNumItems(); ++i)
rowContainer_->GetItem(i)->SetStyle("ConsoleText");
interpreters_->SetStyleAuto();
for (unsigned i = 0; i < interpreters_->GetNumItems(); ++i)
interpreters_->GetItem(i)->SetStyle("ConsoleText");
lineEdit_->SetStyle("ConsoleLineEdit");
closeButton_->SetDefaultStyle(style);
closeButton_->SetStyle("CloseButton");
UpdateElements();
}
void Console::SetVisible(bool enable)
{
Input* input = GetSubsystem<Input>();
background_->SetVisible(enable);
closeButton_->SetVisible(enable);
if (enable)
{
// Check if we have receivers for E_CONSOLECOMMAND every time here in case the handler is being added later dynamically
bool hasInterpreter = PopulateInterpreter();
commandLine_->SetVisible(hasInterpreter);
if (hasInterpreter && focusOnShow_)
GetSubsystem<UI>()->SetFocusElement(lineEdit_);
// Ensure the background has no empty space when shown without the lineedit
background_->SetHeight(background_->GetMinHeight());
// Show OS mouse
savedMouseVisibility_ = input->IsMouseVisible();
input->SetMouseVisible(true);
}
else
{
rowContainer_->SetFocus(false);
interpreters_->SetFocus(false);
lineEdit_->SetFocus(false);
// Restore OS mouse visibility
input->SetMouseVisible(savedMouseVisibility_);
}
}
void Console::Toggle()
{
SetVisible(!IsVisible());
}
void Console::SetNumBufferedRows(unsigned rows)
{
if (rows < displayedRows_)
return;
rowContainer_->DisableLayoutUpdate();
int delta = rowContainer_->GetNumItems() - rows;
if (delta > 0)
{
// We have more, remove oldest rows first
for (int i = 0; i < delta; ++i)
rowContainer_->RemoveItem((unsigned)0);
}
else
{
// We have less, add more rows at the top
for (int i = 0; i > delta; --i)
{
Text* text = new Text(context_);
// If style is already set, apply here to ensure proper height of the console when
// amount of rows is changed
if (background_->GetDefaultStyle())
text->SetStyle("ConsoleText");
rowContainer_->InsertItem(0, text);
}
}
rowContainer_->EnsureItemVisibility(rowContainer_->GetItem(rowContainer_->GetNumItems() - 1));
rowContainer_->EnableLayoutUpdate();
rowContainer_->UpdateLayout();
UpdateElements();
}
void Console::SetNumRows(unsigned rows)
{
if (!rows)
return;
displayedRows_ = rows;
if (GetNumBufferedRows() < rows)
SetNumBufferedRows(rows);
UpdateElements();
}
void Console::SetNumHistoryRows(unsigned rows)
{
historyRows_ = rows;
if (history_.Size() > rows)
history_.Resize(rows);
if (historyPosition_ > rows)
historyPosition_ = rows;
}
void Console::SetFocusOnShow(bool enable)
{
focusOnShow_ = enable;
}
void Console::UpdateElements()
{
int width = GetSubsystem<Graphics>()->GetWidth();
const IntRect& border = background_->GetLayoutBorder();
const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
rowContainer_->SetFixedHeight(displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
(rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
background_->SetFixedWidth(width);
background_->SetHeight(background_->GetMinHeight());
}
XMLFile* Console::GetDefaultStyle() const
{
return background_->GetDefaultStyle(false);
}
bool Console::IsVisible() const
{
return background_ && background_->IsVisible();
}
unsigned Console::GetNumBufferedRows() const
{
return rowContainer_->GetNumItems();
}
void Console::CopySelectedRows() const
{
rowContainer_->CopySelectedItemsToClipboard();
}
const String& Console::GetHistoryRow(unsigned index) const
{
return index < history_.Size() ? history_[index] : String::EMPTY;
}
bool Console::PopulateInterpreter()
{
interpreters_->RemoveAllItems();
HashSet<Object*>* receivers = context_->GetEventReceivers(E_CONSOLECOMMAND);
if (!receivers || receivers->Empty())
return false;
Vector<String> names;
for (HashSet<Object*>::ConstIterator iter = receivers->Begin(); iter != receivers->End(); ++iter)
names.Push((*iter)->GetTypeName());
Sort(names.Begin(), names.End());
unsigned selection = M_MAX_UNSIGNED;
for (unsigned i = 0; i < names.Size(); ++i)
{
const String& name = names[i];
if (name == commandInterpreter_)
selection = i;
Text* text = new Text(context_);
text->SetStyle("ConsoleText");
text->SetText(name);
interpreters_->AddItem(text);
}
const IntRect& border = interpreters_->GetPopup()->GetLayoutBorder();
interpreters_->SetMaxWidth(interpreters_->GetListView()->GetContentElement()->GetWidth() + border.left_ + border.right_);
bool enabled = interpreters_->GetNumItems() > 1;
interpreters_->SetEnabled(enabled);
interpreters_->SetFocusMode(enabled ? FM_FOCUSABLE_DEFOCUSABLE : FM_NOTFOCUSABLE);
if (selection == M_MAX_UNSIGNED)
{
selection = 0;
commandInterpreter_ = names[selection];
}
interpreters_->SetSelection(selection);
return true;
}
void Console::HandleInterpreterSelected(StringHash eventType, VariantMap& eventData)
{
commandInterpreter_ = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
lineEdit_->SetFocus(true);
}
void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
{
using namespace TextFinished;
String line = lineEdit_->GetText();
if (!line.Empty())
{
// Send the command as an event for script subsystem
using namespace ConsoleCommand;
VariantMap& eventData = GetEventDataMap();
eventData[P_COMMAND] = line;
eventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
SendEvent(E_CONSOLECOMMAND, eventData);
// Store to history, then clear the lineedit
history_.Push(line);
if (history_.Size() > historyRows_)
history_.Erase(history_.Begin());
historyPosition_ = history_.Size();
currentRow_.Clear();
lineEdit_->SetText(currentRow_);
}
}
void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
{
if (!historyRows_)
return;
using namespace UnhandledKey;
bool changed = false;
switch (eventData[P_KEY].GetInt())
{
case KEY_UP:
if (historyPosition_ > 0)
{
if (historyPosition_ == history_.Size())
currentRow_ = lineEdit_->GetText();
--historyPosition_;
changed = true;
}
break;
case KEY_DOWN:
if (historyPosition_ < history_.Size())
{
++historyPosition_;
changed = true;
}
break;
}
if (changed)
{
if (historyPosition_ < history_.Size())
lineEdit_->SetText(history_[historyPosition_]);
else
lineEdit_->SetText(currentRow_);
}
}
void Console::HandleCloseButtonPressed(StringHash eventType, VariantMap& eventData)
{
SetVisible(false);
}
void Console::HandleScreenMode(StringHash eventType, VariantMap& eventData)
{
UpdateElements();
}
void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
{
// If printing a log message causes more messages to be logged (error accessing font), disregard them
if (printing_)
return;
using namespace LogMessage;
int level = eventData[P_LEVEL].GetInt();
// The message may be multi-line, so split to rows in that case
Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
for (unsigned i = 0; i < rows.Size(); ++i)
pendingRows_.Push(MakePair(level, rows[i]));
if (autoVisibleOnError_ && level == LOG_ERROR && !IsVisible())
SetVisible(true);
}
void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
return;
printing_ = true;
rowContainer_->DisableLayoutUpdate();
Text* text;
for (unsigned i = 0; i < pendingRows_.Size(); ++i)
{
rowContainer_->RemoveItem((unsigned)0);
text = new Text(context_);
text->SetText(pendingRows_[i].second_);
// Make error message highlight
text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
rowContainer_->AddItem(text);
}
pendingRows_.Clear();
rowContainer_->EnsureItemVisibility(text);
rowContainer_->EnableLayoutUpdate();
rowContainer_->UpdateLayout();
UpdateElements(); // May need to readjust the height due to scrollbar visibility changes
printing_ = false;
}
}
<|endoftext|> |
<commit_before>#include "testing/testing.hpp"
#include "map/framework.hpp"
#include "platform/http_request.hpp"
#include "platform/local_country_file_utils.hpp"
#include "platform/platform.hpp"
#include "platform/platform_tests_support/write_dir_changer.hpp"
#include "coding/file_name_utils.hpp"
#include "coding/internal/file_data.hpp"
#include "storage/storage.hpp"
#include "std/unique_ptr.hpp"
using namespace platform;
using namespace storage;
namespace
{
string const kTestWebServer = "http://new-search.mapswithme.com/";
string const kMapTestDir = "map-tests";
string const kCountriesTxtFile = COUNTRIES_MIGRATE_FILE;
string const kMwmVersion1 = "160126";
size_t const kCountriesTxtFileSize1 = 131201;
string const kMwmVersion2 = "160128";
size_t const kCountriesTxtFileSize2 = 127870;
string const kGroupCountryId = "Belarus";
bool DownloadFile(string const & url,
string const & filePath,
size_t fileSize)
{
using namespace downloader;
HttpRequest::StatusT httpStatus;
bool finished = false;
unique_ptr<HttpRequest> request(HttpRequest::GetFile({url}, filePath, fileSize,
[&](HttpRequest & request)
{
HttpRequest::StatusT const s = request.Status();
if (s == HttpRequest::EFailed || s == HttpRequest::ECompleted)
{
httpStatus = s;
finished = true;
testing::StopEventLoop();
}
}));
testing::RunEventLoop();
return httpStatus == HttpRequest::ECompleted;
}
string GetCountriesTxtWebUrl(string const version)
{
return kTestWebServer + "/direct/" + version + "/" + kCountriesTxtFile;
}
string GetCountriesTxtFilePath()
{
return my::JoinFoldersToPath(GetPlatform().WritableDir(), kCountriesTxtFile);
}
string GetMwmFilePath(string const & version, TCountryId const & countryId)
{
return my::JoinFoldersToPath({GetPlatform().WritableDir(), version},
countryId + DATA_FILE_EXTENSION);
}
} // namespace
UNIT_TEST(SmallMwms_Update_Test)
{
WritableDirChanger writableDirChanger(kMapTestDir);
Platform & platform = GetPlatform();
auto onProgressFn = [&](TCountryId const & countryId, TLocalAndRemoteSize const & mapSize) {};
// Download countries.txt for version 1
TEST(DownloadFile(GetCountriesTxtWebUrl(kMwmVersion1), GetCountriesTxtFilePath(), kCountriesTxtFileSize1), ());
{
Framework f;
auto & storage = f.Storage();
string const version = strings::to_string(storage.GetCurrentDataVersion());
TEST(version::IsSingleMwm(storage.GetCurrentDataVersion()), ());
TEST_EQUAL(version, kMwmVersion1, ());
auto onChangeCountryFn = [&](TCountryId const & countryId)
{
if (!storage.IsDownloadInProgress())
testing::StopEventLoop();
};
storage.Subscribe(onChangeCountryFn, onProgressFn);
storage.SetDownloadingUrlsForTesting({kTestWebServer});
TCountriesVec children;
storage.GetChildren(kGroupCountryId, children);
// Download group
TEST(storage.DownloadNode(kGroupCountryId), ());
testing::RunEventLoop();
// Check group node status is EOnDisk
NodeAttrs attrs;
storage.GetNodeAttrs(kGroupCountryId, attrs);
TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ());
// Check mwm files for version 1 are present
for (auto const & child : children)
{
string const mwmFullPathV1 = GetMwmFilePath(kMwmVersion1, child);
TEST(platform.IsFileExistsByFullPath(mwmFullPathV1), ());
}
}
// Replace countries.txt by version 2
TEST(my::DeleteFileX(GetCountriesTxtFilePath()), ());
TEST(DownloadFile(GetCountriesTxtWebUrl(kMwmVersion2), GetCountriesTxtFilePath(), kCountriesTxtFileSize2), ());
{
Framework f;
auto & storage = f.Storage();
string const version = strings::to_string(storage.GetCurrentDataVersion());
TEST(version::IsSingleMwm(storage.GetCurrentDataVersion()), ());
TEST_EQUAL(version, kMwmVersion2, ());
auto onChangeCountryFn = [&](TCountryId const & countryId)
{
if (!storage.IsDownloadInProgress())
testing::StopEventLoop();
};
storage.Subscribe(onChangeCountryFn, onProgressFn);
storage.SetDownloadingUrlsForTesting({kTestWebServer});
TCountriesVec children;
storage.GetChildren(kGroupCountryId, children);
// Check group node status is EOnDiskOutOfDate
NodeAttrs attrs;
storage.GetNodeAttrs(kGroupCountryId, attrs);
TEST_EQUAL(NodeStatus::OnDiskOutOfDate, attrs.m_status, ());
// Check children node status is EOnDiskOutOfDate
for (auto const & child : children)
{
NodeAttrs attrs;
storage.GetNodeAttrs(child, attrs);
TEST_EQUAL(NodeStatus::OnDiskOutOfDate, attrs.m_status, ());
}
// Check mwm files for version 1 are present
for (auto const & child : children)
{
string const mwmFullPathV1 = GetMwmFilePath(kMwmVersion1, child);
TEST(platform.IsFileExistsByFullPath(mwmFullPathV1), ());
}
// Download group, new version
storage.DownloadNode(kGroupCountryId);
testing::RunEventLoop();
// Check group node status is EOnDisk
storage.GetNodeAttrs(kGroupCountryId, attrs);
TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ());
// Check children node status is EOnDisk
for (auto const & child : children)
{
NodeAttrs attrs;
storage.GetNodeAttrs(child, attrs);
TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ());
}
// Check mwm files for version 2 are present and not present for version 1
for (auto const & child : children)
{
string const mwmFullPathV1 = GetMwmFilePath(kMwmVersion1, child);
string const mwmFullPathV2 = GetMwmFilePath(kMwmVersion2, child);
TEST(platform.IsFileExistsByFullPath(mwmFullPathV2), ());
TEST(!platform.IsFileExistsByFullPath(mwmFullPathV1), ());
}
}
}
<commit_msg>Fix compile error<commit_after>#include "testing/testing.hpp"
#include "map/framework.hpp"
#include "platform/http_request.hpp"
#include "platform/local_country_file_utils.hpp"
#include "platform/platform.hpp"
#include "platform/platform_tests_support/write_dir_changer.hpp"
#include "coding/file_name_utils.hpp"
#include "coding/internal/file_data.hpp"
#include "storage/storage.hpp"
#include "std/unique_ptr.hpp"
using namespace platform;
using namespace storage;
namespace
{
string const kTestWebServer = "http://new-search.mapswithme.com/";
string const kMapTestDir = "map-tests";
string const kCountriesTxtFile = COUNTRIES_MIGRATE_FILE;
string const kMwmVersion1 = "160126";
size_t const kCountriesTxtFileSize1 = 131201;
string const kMwmVersion2 = "160128";
size_t const kCountriesTxtFileSize2 = 127870;
string const kGroupCountryId = "Belarus";
bool DownloadFile(string const & url,
string const & filePath,
size_t fileSize)
{
using namespace downloader;
HttpRequest::StatusT httpStatus;
bool finished = false;
unique_ptr<HttpRequest> request(HttpRequest::GetFile({url}, filePath, fileSize,
[&](HttpRequest & request)
{
HttpRequest::StatusT const s = request.Status();
if (s == HttpRequest::EFailed || s == HttpRequest::ECompleted)
{
httpStatus = s;
finished = true;
testing::StopEventLoop();
}
}));
testing::RunEventLoop();
return httpStatus == HttpRequest::ECompleted;
}
string GetCountriesTxtWebUrl(string const version)
{
return kTestWebServer + "/direct/" + version + "/" + kCountriesTxtFile;
}
string GetCountriesTxtFilePath()
{
return my::JoinFoldersToPath(GetPlatform().WritableDir(), kCountriesTxtFile);
}
string GetMwmFilePath(string const & version, TCountryId const & countryId)
{
return my::JoinFoldersToPath({GetPlatform().WritableDir(), version},
countryId + DATA_FILE_EXTENSION);
}
} // namespace
UNIT_TEST(SmallMwms_Update_Test)
{
WritableDirChanger writableDirChanger(kMapTestDir);
Platform & platform = GetPlatform();
auto onProgressFn = [&](TCountryId const & countryId, TLocalAndRemoteSize const & mapSize) {};
// Download countries.txt for version 1
TEST(DownloadFile(GetCountriesTxtWebUrl(kMwmVersion1), GetCountriesTxtFilePath(), kCountriesTxtFileSize1), ());
{
Framework f;
auto & storage = f.Storage();
string const version = strings::to_string(storage.GetCurrentDataVersion());
TEST(version::IsSingleMwm(storage.GetCurrentDataVersion()), ());
TEST_EQUAL(version, kMwmVersion1, ());
auto onChangeCountryFn = [&](TCountryId const & countryId)
{
if (!storage.IsDownloadInProgress())
testing::StopEventLoop();
};
storage.Subscribe(onChangeCountryFn, onProgressFn);
storage.SetDownloadingUrlsForTesting({kTestWebServer});
TCountriesVec children;
storage.GetChildren(kGroupCountryId, children);
// Download group
storage.DownloadNode(kGroupCountryId);
testing::RunEventLoop();
// Check group node status is EOnDisk
NodeAttrs attrs;
storage.GetNodeAttrs(kGroupCountryId, attrs);
TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ());
// Check mwm files for version 1 are present
for (auto const & child : children)
{
string const mwmFullPathV1 = GetMwmFilePath(kMwmVersion1, child);
TEST(platform.IsFileExistsByFullPath(mwmFullPathV1), ());
}
}
// Replace countries.txt by version 2
TEST(my::DeleteFileX(GetCountriesTxtFilePath()), ());
TEST(DownloadFile(GetCountriesTxtWebUrl(kMwmVersion2), GetCountriesTxtFilePath(), kCountriesTxtFileSize2), ());
{
Framework f;
auto & storage = f.Storage();
string const version = strings::to_string(storage.GetCurrentDataVersion());
TEST(version::IsSingleMwm(storage.GetCurrentDataVersion()), ());
TEST_EQUAL(version, kMwmVersion2, ());
auto onChangeCountryFn = [&](TCountryId const & countryId)
{
if (!storage.IsDownloadInProgress())
testing::StopEventLoop();
};
storage.Subscribe(onChangeCountryFn, onProgressFn);
storage.SetDownloadingUrlsForTesting({kTestWebServer});
TCountriesVec children;
storage.GetChildren(kGroupCountryId, children);
// Check group node status is EOnDiskOutOfDate
NodeAttrs attrs;
storage.GetNodeAttrs(kGroupCountryId, attrs);
TEST_EQUAL(NodeStatus::OnDiskOutOfDate, attrs.m_status, ());
// Check children node status is EOnDiskOutOfDate
for (auto const & child : children)
{
NodeAttrs attrs;
storage.GetNodeAttrs(child, attrs);
TEST_EQUAL(NodeStatus::OnDiskOutOfDate, attrs.m_status, ());
}
// Check mwm files for version 1 are present
for (auto const & child : children)
{
string const mwmFullPathV1 = GetMwmFilePath(kMwmVersion1, child);
TEST(platform.IsFileExistsByFullPath(mwmFullPathV1), ());
}
// Download group, new version
storage.DownloadNode(kGroupCountryId);
testing::RunEventLoop();
// Check group node status is EOnDisk
storage.GetNodeAttrs(kGroupCountryId, attrs);
TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ());
// Check children node status is EOnDisk
for (auto const & child : children)
{
NodeAttrs attrs;
storage.GetNodeAttrs(child, attrs);
TEST_EQUAL(NodeStatus::OnDisk, attrs.m_status, ());
}
// Check mwm files for version 2 are present and not present for version 1
for (auto const & child : children)
{
string const mwmFullPathV1 = GetMwmFilePath(kMwmVersion1, child);
string const mwmFullPathV2 = GetMwmFilePath(kMwmVersion2, child);
TEST(platform.IsFileExistsByFullPath(mwmFullPathV2), ());
TEST(!platform.IsFileExistsByFullPath(mwmFullPathV1), ());
}
}
}
<|endoftext|> |
<commit_before>// Module: Log4CPLUS
// File: loggerimpl.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) Tad E. Smith All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.1 2003/04/03 01:44:01 tcsmith
// Renamed from categoryimpl.cxx
//
#include <log4cplus/spi/loggerimpl.h>
#include <log4cplus/appender.h>
#include <log4cplus/hierarchy.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/spi/loggingevent.h>
#include <log4cplus/spi/rootlogger.h>
#include <cassert>
#include <stdexcept>
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus::spi;
//////////////////////////////////////////////////////////////////////////////
// Logger Constructors and Destructor
//////////////////////////////////////////////////////////////////////////////
LoggerImpl::LoggerImpl(const log4cplus::tstring& name, Hierarchy& h)
: name(name),
ll(NOT_SET_LOG_LEVEL),
parent(NULL),
additive(true),
hierarchy(h)
{
}
LoggerImpl::~LoggerImpl()
{
getLogLog().debug(LOG4CPLUS_TEXT("Destroying Logger: ") + name);
}
//////////////////////////////////////////////////////////////////////////////
// Logger Methods
//////////////////////////////////////////////////////////////////////////////
void
LoggerImpl::callAppenders(const InternalLoggingEvent& event)
{
int writes = 0;
for(const LoggerImpl* c = this; c != NULL; c=c->parent.get()) {
writes += c->appendLoopOnAppenders(event);
if(!c->additive) {
break;
}
}
// No appenders in hierarchy, warn user only once.
if(!hierarchy.emittedNoAppenderWarning && writes == 0) {
getLogLog().error( LOG4CPLUS_TEXT("No appenders could be found for logger (")
+ getName()
+ LOG4CPLUS_TEXT(")."));
getLogLog().error(LOG4CPLUS_TEXT("Please initialize the log4cplus system properly."));
hierarchy.emittedNoAppenderWarning = true;
}
}
void
LoggerImpl::closeNestedAppenders()
{
SharedAppenderPtrList appenders = getAllAppenders();
for(SharedAppenderPtrList::iterator it=appenders.begin(); it!=appenders.end(); ++it)
{
(*it)->close();
}
}
bool
LoggerImpl::isEnabledFor(LogLevel ll) const
{
if(hierarchy.disableValue >= ll) {
return false;
}
return ll >= getChainedLogLevel();
}
void
LoggerImpl::log(LogLevel ll,
const log4cplus::tstring& message,
const char* file,
int line)
{
if(isEnabledFor(ll)) {
forcedLog(ll, message, file, line);
}
}
LogLevel
LoggerImpl::getChainedLogLevel() const
{
for(const LoggerImpl *c=this; c != NULL; c=c->parent.get()) {
if(c == NULL) {
getLogLog().error(LOG4CPLUS_TEXT("LoggerImpl::getChainedLogLevel()- " \
"Internal error: NullPointer"));
helpers::throwNullPointerException(__FILE__, __LINE__);
}
if(c->ll != NOT_SET_LOG_LEVEL) {
return c->ll;
}
}
getLogLog().error(LOG4CPLUS_TEXT("LoggerImpl::getChainedLogLevel()- No valid " \
"LogLevel found"));
throw std::runtime_error(LOG4CPLUS_TEXT("No valid LogLevel found"));
}
Hierarchy&
LoggerImpl::getHierarchy() const
{
return hierarchy;
}
bool
LoggerImpl::getAdditivity() const
{
return additive;
}
void
LoggerImpl::setAdditivity(bool additive)
{
this->additive = additive;
}
void
LoggerImpl::forcedLog(LogLevel ll,
const log4cplus::tstring& message,
const char* file,
int line)
{
callAppenders(spi::InternalLoggingEvent(this->getName(), ll, message, file, line));
}
<commit_msg>Fixed UNICODE support.<commit_after>// Module: Log4CPLUS
// File: loggerimpl.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) Tad E. Smith All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.2 2003/04/18 21:26:16 tcsmith
// Converted from std::string to log4cplus::tstring.
//
// Revision 1.1 2003/04/03 01:44:01 tcsmith
// Renamed from categoryimpl.cxx
//
#include <log4cplus/spi/loggerimpl.h>
#include <log4cplus/appender.h>
#include <log4cplus/hierarchy.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/spi/loggingevent.h>
#include <log4cplus/spi/rootlogger.h>
#include <cassert>
#include <stdexcept>
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus::spi;
//////////////////////////////////////////////////////////////////////////////
// Logger Constructors and Destructor
//////////////////////////////////////////////////////////////////////////////
LoggerImpl::LoggerImpl(const log4cplus::tstring& name, Hierarchy& h)
: name(name),
ll(NOT_SET_LOG_LEVEL),
parent(NULL),
additive(true),
hierarchy(h)
{
}
LoggerImpl::~LoggerImpl()
{
getLogLog().debug(LOG4CPLUS_TEXT("Destroying Logger: ") + name);
}
//////////////////////////////////////////////////////////////////////////////
// Logger Methods
//////////////////////////////////////////////////////////////////////////////
void
LoggerImpl::callAppenders(const InternalLoggingEvent& event)
{
int writes = 0;
for(const LoggerImpl* c = this; c != NULL; c=c->parent.get()) {
writes += c->appendLoopOnAppenders(event);
if(!c->additive) {
break;
}
}
// No appenders in hierarchy, warn user only once.
if(!hierarchy.emittedNoAppenderWarning && writes == 0) {
getLogLog().error( LOG4CPLUS_TEXT("No appenders could be found for logger (")
+ getName()
+ LOG4CPLUS_TEXT(")."));
getLogLog().error(LOG4CPLUS_TEXT("Please initialize the log4cplus system properly."));
hierarchy.emittedNoAppenderWarning = true;
}
}
void
LoggerImpl::closeNestedAppenders()
{
SharedAppenderPtrList appenders = getAllAppenders();
for(SharedAppenderPtrList::iterator it=appenders.begin(); it!=appenders.end(); ++it)
{
(*it)->close();
}
}
bool
LoggerImpl::isEnabledFor(LogLevel ll) const
{
if(hierarchy.disableValue >= ll) {
return false;
}
return ll >= getChainedLogLevel();
}
void
LoggerImpl::log(LogLevel ll,
const log4cplus::tstring& message,
const char* file,
int line)
{
if(isEnabledFor(ll)) {
forcedLog(ll, message, file, line);
}
}
LogLevel
LoggerImpl::getChainedLogLevel() const
{
for(const LoggerImpl *c=this; c != NULL; c=c->parent.get()) {
if(c == NULL) {
getLogLog().error(LOG4CPLUS_TEXT("LoggerImpl::getChainedLogLevel()- Internal error: NullPointer"));
helpers::throwNullPointerException(__FILE__, __LINE__);
}
if(c->ll != NOT_SET_LOG_LEVEL) {
return c->ll;
}
}
getLogLog().error( LOG4CPLUS_TEXT("LoggerImpl::getChainedLogLevel()- No valid LogLevel found") );
throw std::runtime_error("No valid LogLevel found");
}
Hierarchy&
LoggerImpl::getHierarchy() const
{
return hierarchy;
}
bool
LoggerImpl::getAdditivity() const
{
return additive;
}
void
LoggerImpl::setAdditivity(bool additive)
{
this->additive = additive;
}
void
LoggerImpl::forcedLog(LogLevel ll,
const log4cplus::tstring& message,
const char* file,
int line)
{
callAppenders(spi::InternalLoggingEvent(this->getName(), ll, message, file, line));
}
<|endoftext|> |
<commit_before>/***********************************************************************
* filename: Element.cpp
* created: 28/10/2011
* author: Martin Preisler
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/Element.h"
#include <boost/test/unit_test.hpp>
#include <boost/timer.hpp>
BOOST_AUTO_TEST_SUITE(Element)
BOOST_AUTO_TEST_CASE(RelativeSizing)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent()));
root->addChild(child);
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f));
BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f));
CEGUI::Element* innerChild = new CEGUI::Element();
child->addChild(innerChild);
innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent()));
BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f));
delete innerChild;
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(RelativePositioning)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setPosition(CEGUI::UVector2(50.0f * CEGUI::UDim::percent(), 50.0f * CEGUI::UDim::percent()));
child->setSize(CEGUI::USize(10.0f * CEGUI::UDim::px(), 10 * CEGUI::UDim::px()));
root->addChild(child);
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50.0f, 50.0f, 60.0f, 60.0f));
delete child;
delete root;
}
// TODO: RelativeRotation!
BOOST_AUTO_TEST_CASE(HorizontalLeftAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);
BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 0));
child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 0, 60, 0));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(HorizontalCentreAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);
child->setHorizontalAlignment(CEGUI::HA_CENTRE);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(25, 0, 75, 0));
child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(35, 0, 85, 0));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(HorizontalRightAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);
child->setHorizontalAlignment(CEGUI::HA_RIGHT);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50, 0, 100, 0));
child->setPosition(CEGUI::UVector2(-10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(40, 0, 90, 0));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(VerticalTopAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);
BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 50));
child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 5, 0, 55));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(VerticalCentreAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);
child->setVerticalAlignment(CEGUI::VA_CENTRE);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 25, 0, 75));
child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 30, 0, 80));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(VerticalBottomAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);
child->setVerticalAlignment(CEGUI::VA_BOTTOM);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 50, 0, 100));
child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), -5.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 45, 0, 95));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(AspectLocking)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getAspectMode(), CEGUI::AM_IGNORE);
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 100));
root->setAspectMode(CEGUI::AM_SHRINK);
root->setAspectRatio(1.0f / 2.0f);
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(50, 100));
root->setAspectMode(CEGUI::AM_EXPAND);
root->setAspectRatio(1.0f / 2.0f);
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 200));
delete root;
}
BOOST_AUTO_TEST_CASE(PixelAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setPosition(CEGUI::UVector2(0.2f * CEGUI::UDim::px(), 0.2f * CEGUI::UDim::px()));
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100.0f * CEGUI::UDim::px()));
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK(root->isPixelAligned());
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 100));
root->setPixelAligned(false);
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0.2f, 0.2f, 100.2f, 100.2f));
delete root;
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Added test case for min/max size in Element<commit_after>/***********************************************************************
* filename: Element.cpp
* created: 28/10/2011
* author: Martin Preisler
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/Element.h"
#include <boost/test/unit_test.hpp>
#include <boost/timer.hpp>
BOOST_AUTO_TEST_SUITE(Element)
BOOST_AUTO_TEST_CASE(RelativeSizing)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent()));
root->addChild(child);
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f));
BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f));
CEGUI::Element* innerChild = new CEGUI::Element();
child->addChild(innerChild);
innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent()));
BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f));
delete innerChild;
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(RelativePositioning)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setPosition(CEGUI::UVector2(50.0f * CEGUI::UDim::percent(), 50.0f * CEGUI::UDim::percent()));
child->setSize(CEGUI::USize(10.0f * CEGUI::UDim::px(), 10 * CEGUI::UDim::px()));
root->addChild(child);
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50.0f, 50.0f, 60.0f, 60.0f));
delete child;
delete root;
}
// TODO: RelativeRotation!
BOOST_AUTO_TEST_CASE(MinMaxSize)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
root->setMaxSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 50 * CEGUI::UDim::px()));;
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(50.0f, 50.0f));
root->setMaxSize(CEGUI::USize(75.0f * CEGUI::UDim::px(), 75.0f * CEGUI::UDim::px()));;
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(75.0f, 75.0f));
root->setMaxSize(CEGUI::USize(1000.0f * CEGUI::UDim::px(), 1000 * CEGUI::UDim::px()));;
root->setMinSize(CEGUI::USize(125.0f * CEGUI::UDim::px(), 125.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(125.0f, 125.0f));
delete root;
}
BOOST_AUTO_TEST_CASE(HorizontalLeftAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);
BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 0));
child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 0, 60, 0));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(HorizontalCentreAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);
child->setHorizontalAlignment(CEGUI::HA_CENTRE);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(25, 0, 75, 0));
child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(35, 0, 85, 0));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(HorizontalRightAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);
child->setHorizontalAlignment(CEGUI::HA_RIGHT);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(50, 0, 100, 0));
child->setPosition(CEGUI::UVector2(-10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(40, 0, 90, 0));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(VerticalTopAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);
BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 50));
child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 5, 0, 55));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(VerticalCentreAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);
child->setVerticalAlignment(CEGUI::VA_CENTRE);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 25, 0, 75));
child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 30, 0, 80));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(VerticalBottomAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
CEGUI::Element* child = new CEGUI::Element();
child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 50.0f * CEGUI::UDim::px()));
root->addChild(child);
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);
child->setVerticalAlignment(CEGUI::VA_BOTTOM);
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 50, 0, 100));
child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), -5.0f * CEGUI::UDim::px()));
BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 45, 0, 95));
delete child;
delete root;
}
BOOST_AUTO_TEST_CASE(AspectLocking)
{
CEGUI::Element* root = new CEGUI::Element();
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK_EQUAL(root->getAspectMode(), CEGUI::AM_IGNORE);
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 100));
root->setAspectMode(CEGUI::AM_SHRINK);
root->setAspectRatio(1.0f / 2.0f);
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(50, 100));
root->setAspectMode(CEGUI::AM_EXPAND);
root->setAspectRatio(1.0f / 2.0f);
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100, 200));
delete root;
}
BOOST_AUTO_TEST_CASE(PixelAlignment)
{
CEGUI::Element* root = new CEGUI::Element();
root->setPosition(CEGUI::UVector2(0.2f * CEGUI::UDim::px(), 0.2f * CEGUI::UDim::px()));
root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100.0f * CEGUI::UDim::px()));
// even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!
BOOST_CHECK(root->isPixelAligned());
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 100));
root->setPixelAligned(false);
// todo: should have tolerances or something, or does boost do that automatically?
BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0.2f, 0.2f, 100.2f, 100.2f));
delete root;
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>//
// Custom Casts
//
namespace {
$(when measurements $(foreach measurements
$(if active and ( custom_cast or label_map ) then
OUT=[[
template<typename FilterType>
struct ${name}CustomCast
{
template <typename T>
]]
if custom_cast then
OUT=OUT..[[
static ${type} Helper( const T & value ) { return ${custom_cast}; }
]]
end
OUT=OUT..[[
static ${type} CustomCast( const FilterType *f]]
if parameters then
for inum=1,#parameters do
OUT=OUT..', '..parameters[inum].type..' '..parameters[inum].name
end
end
OUT=OUT..[[ )
{
return ]]
if custom_cast then
OUT=OUT..[[${name}CustomCast::Helper(]]
end
if label_map then
OUT=OUT..[[f->GetOutput()->GetLabelObject(label)->Get${name}()]]
else
OUT=OUT..[[f->Get${name}(label)]]
end
if custom_cast then
OUT=OUT..')'
end
OUT=OUT..';'..[[
}
};
]]
end)))
}
<commit_msg>fix custom cast template component<commit_after>//
// Custom Casts
//
namespace {
$(when measurements $(foreach measurements
$(if active and ( custom_cast or label_map ) then
OUT=[[
template<typename FilterType>
struct ${name}CustomCast
{
]]
if custom_cast then
OUT=OUT..[[
template <typename T>
static ${type} Helper( const T & value ) { return ${custom_cast}; }
]]
end
OUT=OUT..[[
static ${type} CustomCast( const FilterType *f]]
if parameters then
for inum=1,#parameters do
OUT=OUT..', '..parameters[inum].type..' '..parameters[inum].name
end
end
OUT=OUT..[[ )
{
return ]]
if custom_cast then
OUT=OUT..[[${name}CustomCast::Helper(]]
end
if label_map then
OUT=OUT..[[f->GetOutput()->GetLabelObject(label)->Get${name}()]]
else
OUT=OUT..[[f->Get${name}(label)]]
end
if custom_cast then
OUT=OUT..')'
end
OUT=OUT..';'..[[
}
};
]]
end)))
}
<|endoftext|> |
<commit_before><commit_msg>Use the full URL of the icon in the notification, not just the string passed in -- so that that string doesn't have to be absolute.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/extensions/file_browser_event_router.h"
#include "base/json/json_writer.h"
#include "base/memory/singleton.h"
#include "base/stl_util-inl.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/notifications/system_notification.h"
#include "chrome/browser/extensions/extension_event_names.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
ExtensionFileBrowserEventRouter::ExtensionFileBrowserEventRouter()
: profile_(NULL) {
}
ExtensionFileBrowserEventRouter::~ExtensionFileBrowserEventRouter() {
}
void ExtensionFileBrowserEventRouter::ObserveFileSystemEvents(
Profile* profile) {
if (profile_)
return;
profile_ = profile;
if (chromeos::UserManager::Get()->user_is_logged_in()) {
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
lib->AddObserver(this);
lib->RequestMountInfoRefresh();
}
}
void ExtensionFileBrowserEventRouter::StopObservingFileSystemEvents() {
if (!profile_)
return;
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
lib->RemoveObserver(this);
profile_ = NULL;
}
// static
ExtensionFileBrowserEventRouter*
ExtensionFileBrowserEventRouter::GetInstance() {
return Singleton<ExtensionFileBrowserEventRouter>::get();
}
void ExtensionFileBrowserEventRouter::DiskChanged(
chromeos::MountLibraryEventType event,
const chromeos::MountLibrary::Disk* disk) {
if (event == chromeos::MOUNT_DISK_ADDED) {
OnDiskAdded(disk);
} else if (event == chromeos::MOUNT_DISK_REMOVED) {
OnDiskRemoved(disk);
} else if (event == chromeos::MOUNT_DISK_CHANGED) {
OnDiskChanged(disk);
}
}
void ExtensionFileBrowserEventRouter::DeviceChanged(
chromeos::MountLibraryEventType event,
const std::string& device_path) {
if (event == chromeos::MOUNT_DEVICE_ADDED) {
OnDeviceAdded(device_path);
} else if (event == chromeos::MOUNT_DEVICE_REMOVED) {
OnDeviceRemoved(device_path);
} else if (event == chromeos::MOUNT_DEVICE_SCANNED) {
OnDeviceScanned(device_path);
}
}
void ExtensionFileBrowserEventRouter::DispatchEvent(
const std::string& web_path) {
if (!profile_) {
NOTREACHED();
return;
}
ListValue args;
args.Append(Value::CreateStringValue(web_path));
std::string args_json;
base::JSONWriter::Write(&args, false /* pretty_print */, &args_json);
profile_->GetExtensionEventRouter()->DispatchEventToRenderers(
extension_event_names::kOnFileBrowserDiskChanged, args_json, NULL,
GURL());
}
void ExtensionFileBrowserEventRouter::OnDiskAdded(
const chromeos::MountLibrary::Disk* disk) {
VLOG(1) << "Disk added: " << disk->device_path();
if (disk->device_path().empty()) {
VLOG(1) << "Empty system path for " << disk->device_path();
return;
}
if (disk->is_parent()) {
if (!disk->has_media())
HideDeviceNotification(disk->system_path());
return;
}
// If disk is not mounted yet, give it a try.
if (disk->mount_path().empty()) {
// Initiate disk mount operation.
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
lib->MountPath(disk->device_path().c_str());
}
}
void ExtensionFileBrowserEventRouter::OnDiskRemoved(
const chromeos::MountLibrary::Disk* disk) {
VLOG(1) << "Disk removed: " << disk->device_path();
HideDeviceNotification(disk->system_path());
MountPointMap::iterator iter = mounted_devices_.find(disk->device_path());
if (iter == mounted_devices_.end())
return;
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
// TODO(zelidrag): This for some reason does not work as advertized.
// we might need to clean up mount directory on FILE thread here as well.
lib->UnmountPath(disk->device_path().c_str());
DispatchEvent(iter->second);
mounted_devices_.erase(iter);
}
void ExtensionFileBrowserEventRouter::OnDiskChanged(
const chromeos::MountLibrary::Disk* disk) {
VLOG(1) << "Disk changed : " << disk->device_path();
if (!disk->mount_path().empty()) {
HideDeviceNotification(disk->system_path());
// Remember this mount point.
if (mounted_devices_.find(disk->device_path()) == mounted_devices_.end()) {
mounted_devices_.insert(
std::pair<std::string, std::string>(disk->device_path(),
disk->mount_path()));
DispatchEvent(disk->mount_path());
// TODO(zelidrag): Find better icon here.
ShowDeviceNotification(disk->system_path(), IDR_PAGEINFO_INFO,
l10n_util::GetStringUTF16(IDS_REMOVABLE_DEVICE_MOUNTED_MESSAGE));
}
}
}
void ExtensionFileBrowserEventRouter::OnDeviceAdded(
const std::string& device_path) {
VLOG(1) << "Device added : " << device_path;
// TODO(zelidrag): Find better icon here.
ShowDeviceNotification(device_path, IDR_PAGEINFO_INFO,
l10n_util::GetStringUTF16(IDS_REMOVABLE_DEVICE_SCANNING_MESSAGE));
}
void ExtensionFileBrowserEventRouter::OnDeviceRemoved(
const std::string& system_path) {
}
void ExtensionFileBrowserEventRouter::OnDeviceScanned(
const std::string& device_path) {
VLOG(1) << "Device scanned : " << device_path;
}
void ExtensionFileBrowserEventRouter::ShowDeviceNotification(
const std::string& system_path, int icon_resource_id,
const string16& message) {
NotificationMap::iterator iter = FindNotificationForPath(system_path);
std::string mount_path;
if (iter != notifications_.end()) {
iter->second->Show(message, false, false);
} else {
if (!profile_) {
NOTREACHED();
return;
}
chromeos::SystemNotification* notification =
new chromeos::SystemNotification(
profile_,
system_path,
icon_resource_id,
l10n_util::GetStringUTF16(IDS_REMOVABLE_DEVICE_DETECTION_TITLE));
notifications_.insert(NotificationMap::value_type(system_path,
linked_ptr<chromeos::SystemNotification>(notification)));
notification->Show(message, false, false);
}
}
void ExtensionFileBrowserEventRouter::HideDeviceNotification(
const std::string& system_path) {
NotificationMap::iterator iter = FindNotificationForPath(system_path);
if (iter != notifications_.end()) {
iter->second->Hide();
notifications_.erase(iter);
}
}
ExtensionFileBrowserEventRouter::NotificationMap::iterator
ExtensionFileBrowserEventRouter::FindNotificationForPath(
const std::string& system_path) {
for (NotificationMap::iterator iter = notifications_.begin();
iter != notifications_.end();
++iter) {
const std::string& notification_device_path = iter->first;
// Doing a sub string match so that we find if this new one is a subdevice
// of another already inserted device.
if (StartsWithASCII(system_path, notification_device_path, true)) {
return iter;
}
}
return notifications_.end();
}
<commit_msg>Hiding device notifications for devices that have been removed<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/extensions/file_browser_event_router.h"
#include "base/json/json_writer.h"
#include "base/memory/singleton.h"
#include "base/stl_util-inl.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/notifications/system_notification.h"
#include "chrome/browser/extensions/extension_event_names.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
ExtensionFileBrowserEventRouter::ExtensionFileBrowserEventRouter()
: profile_(NULL) {
}
ExtensionFileBrowserEventRouter::~ExtensionFileBrowserEventRouter() {
}
void ExtensionFileBrowserEventRouter::ObserveFileSystemEvents(
Profile* profile) {
if (profile_)
return;
profile_ = profile;
if (chromeos::UserManager::Get()->user_is_logged_in()) {
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
lib->AddObserver(this);
lib->RequestMountInfoRefresh();
}
}
void ExtensionFileBrowserEventRouter::StopObservingFileSystemEvents() {
if (!profile_)
return;
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
lib->RemoveObserver(this);
profile_ = NULL;
}
// static
ExtensionFileBrowserEventRouter*
ExtensionFileBrowserEventRouter::GetInstance() {
return Singleton<ExtensionFileBrowserEventRouter>::get();
}
void ExtensionFileBrowserEventRouter::DiskChanged(
chromeos::MountLibraryEventType event,
const chromeos::MountLibrary::Disk* disk) {
if (event == chromeos::MOUNT_DISK_ADDED) {
OnDiskAdded(disk);
} else if (event == chromeos::MOUNT_DISK_REMOVED) {
OnDiskRemoved(disk);
} else if (event == chromeos::MOUNT_DISK_CHANGED) {
OnDiskChanged(disk);
}
}
void ExtensionFileBrowserEventRouter::DeviceChanged(
chromeos::MountLibraryEventType event,
const std::string& device_path) {
if (event == chromeos::MOUNT_DEVICE_ADDED) {
OnDeviceAdded(device_path);
} else if (event == chromeos::MOUNT_DEVICE_REMOVED) {
OnDeviceRemoved(device_path);
} else if (event == chromeos::MOUNT_DEVICE_SCANNED) {
OnDeviceScanned(device_path);
}
}
void ExtensionFileBrowserEventRouter::DispatchEvent(
const std::string& web_path) {
if (!profile_) {
NOTREACHED();
return;
}
ListValue args;
args.Append(Value::CreateStringValue(web_path));
std::string args_json;
base::JSONWriter::Write(&args, false /* pretty_print */, &args_json);
profile_->GetExtensionEventRouter()->DispatchEventToRenderers(
extension_event_names::kOnFileBrowserDiskChanged, args_json, NULL,
GURL());
}
void ExtensionFileBrowserEventRouter::OnDiskAdded(
const chromeos::MountLibrary::Disk* disk) {
VLOG(1) << "Disk added: " << disk->device_path();
if (disk->device_path().empty()) {
VLOG(1) << "Empty system path for " << disk->device_path();
return;
}
if (disk->is_parent()) {
if (!disk->has_media())
HideDeviceNotification(disk->system_path());
return;
}
// If disk is not mounted yet, give it a try.
if (disk->mount_path().empty()) {
// Initiate disk mount operation.
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
lib->MountPath(disk->device_path().c_str());
}
}
void ExtensionFileBrowserEventRouter::OnDiskRemoved(
const chromeos::MountLibrary::Disk* disk) {
VLOG(1) << "Disk removed: " << disk->device_path();
HideDeviceNotification(disk->system_path());
MountPointMap::iterator iter = mounted_devices_.find(disk->device_path());
if (iter == mounted_devices_.end())
return;
chromeos::MountLibrary* lib =
chromeos::CrosLibrary::Get()->GetMountLibrary();
// TODO(zelidrag): This for some reason does not work as advertized.
// we might need to clean up mount directory on FILE thread here as well.
lib->UnmountPath(disk->device_path().c_str());
DispatchEvent(iter->second);
mounted_devices_.erase(iter);
}
void ExtensionFileBrowserEventRouter::OnDiskChanged(
const chromeos::MountLibrary::Disk* disk) {
VLOG(1) << "Disk changed : " << disk->device_path();
if (!disk->mount_path().empty()) {
HideDeviceNotification(disk->system_path());
// Remember this mount point.
if (mounted_devices_.find(disk->device_path()) == mounted_devices_.end()) {
mounted_devices_.insert(
std::pair<std::string, std::string>(disk->device_path(),
disk->mount_path()));
DispatchEvent(disk->mount_path());
// TODO(zelidrag): Find better icon here.
ShowDeviceNotification(disk->system_path(), IDR_PAGEINFO_INFO,
l10n_util::GetStringUTF16(IDS_REMOVABLE_DEVICE_MOUNTED_MESSAGE));
}
}
}
void ExtensionFileBrowserEventRouter::OnDeviceAdded(
const std::string& device_path) {
VLOG(1) << "Device added : " << device_path;
// TODO(zelidrag): Find better icon here.
ShowDeviceNotification(device_path, IDR_PAGEINFO_INFO,
l10n_util::GetStringUTF16(IDS_REMOVABLE_DEVICE_SCANNING_MESSAGE));
}
void ExtensionFileBrowserEventRouter::OnDeviceRemoved(
const std::string& system_path) {
HideDeviceNotification(system_path);
}
void ExtensionFileBrowserEventRouter::OnDeviceScanned(
const std::string& device_path) {
VLOG(1) << "Device scanned : " << device_path;
}
void ExtensionFileBrowserEventRouter::ShowDeviceNotification(
const std::string& system_path, int icon_resource_id,
const string16& message) {
NotificationMap::iterator iter = FindNotificationForPath(system_path);
std::string mount_path;
if (iter != notifications_.end()) {
iter->second->Show(message, false, false);
} else {
if (!profile_) {
NOTREACHED();
return;
}
chromeos::SystemNotification* notification =
new chromeos::SystemNotification(
profile_,
system_path,
icon_resource_id,
l10n_util::GetStringUTF16(IDS_REMOVABLE_DEVICE_DETECTION_TITLE));
notifications_.insert(NotificationMap::value_type(system_path,
linked_ptr<chromeos::SystemNotification>(notification)));
notification->Show(message, false, false);
}
}
void ExtensionFileBrowserEventRouter::HideDeviceNotification(
const std::string& system_path) {
NotificationMap::iterator iter = FindNotificationForPath(system_path);
if (iter != notifications_.end()) {
iter->second->Hide();
notifications_.erase(iter);
}
}
ExtensionFileBrowserEventRouter::NotificationMap::iterator
ExtensionFileBrowserEventRouter::FindNotificationForPath(
const std::string& system_path) {
for (NotificationMap::iterator iter = notifications_.begin();
iter != notifications_.end();
++iter) {
const std::string& notification_device_path = iter->first;
// Doing a sub string match so that we find if this new one is a subdevice
// of another already inserted device.
if (StartsWithASCII(system_path, notification_device_path, true)) {
return iter;
}
}
return notifications_.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/chromeos/status/power_menu_button.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_power_library.h"
#include "chrome/browser/chromeos/frame/browser_view.h"
#include "chrome/browser/chromeos/status/browser_status_area_view.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "grit/theme_resources.h"
namespace chromeos {
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;
class PowerMenuButtonTest : public CrosInProcessBrowserTest {
protected:
PowerMenuButtonTest() : CrosInProcessBrowserTest() {}
virtual void SetUpInProcessBrowserTestFixture() {
InitStatusAreaMocks();
SetStatusAreaMocksExpectations();
}
PowerMenuButton* GetPowerMenuButton() {
BrowserView* view = static_cast<BrowserView*>(browser()->window());
PowerMenuButton* power = static_cast<BrowserStatusAreaView*>(view->
GetViewByID(VIEW_ID_STATUS_AREA))->power_view();
return power;
}
int CallPowerChangedAndGetIconId() {
PowerMenuButton* power = GetPowerMenuButton();
power->PowerChanged(mock_power_library_);
return power->icon_id();
}
};
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryMissingTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(false)));
EXPECT_EQ(IDR_STATUSBAR_BATTERY_MISSING, CallPowerChangedAndGetIconId());
}
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryChargedTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, battery_fully_charged())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, line_power_on())
.WillRepeatedly((Return(true)));
EXPECT_EQ(IDR_STATUSBAR_BATTERY_CHARGED, CallPowerChangedAndGetIconId());
}
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryChargingTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, battery_fully_charged())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_power_library_, line_power_on())
.WillRepeatedly((Return(true)));
// Test the 12 battery charging states.
int id = IDR_STATUSBAR_BATTERY_CHARGING_1;
for (float precent = 6.0; precent < 100.0; precent += 8.0) {
EXPECT_CALL(*mock_power_library_, battery_percentage())
.WillRepeatedly((Return(precent)));
EXPECT_EQ(id, CallPowerChangedAndGetIconId());
id++;
}
}
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryDischargingTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, battery_fully_charged())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_power_library_, line_power_on())
.WillRepeatedly((Return(false)));
// Test the 12 battery discharing states.
int id = IDR_STATUSBAR_BATTERY_DISCHARGING_1;
for (float precent = 6.0; precent < 100.0; precent += 8.0) {
EXPECT_CALL(*mock_power_library_, battery_percentage())
.WillRepeatedly((Return(precent)));
EXPECT_EQ(id, CallPowerChangedAndGetIconId());
id++;
}
}
} // namespace chromeos
<commit_msg>Mark failing tests with FAIL_<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/chromeos/status/power_menu_button.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_power_library.h"
#include "chrome/browser/chromeos/frame/browser_view.h"
#include "chrome/browser/chromeos/status/browser_status_area_view.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "grit/theme_resources.h"
namespace chromeos {
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;
class PowerMenuButtonTest : public CrosInProcessBrowserTest {
protected:
PowerMenuButtonTest() : CrosInProcessBrowserTest() {}
virtual void SetUpInProcessBrowserTestFixture() {
InitStatusAreaMocks();
SetStatusAreaMocksExpectations();
}
PowerMenuButton* GetPowerMenuButton() {
BrowserView* view = static_cast<BrowserView*>(browser()->window());
PowerMenuButton* power = static_cast<BrowserStatusAreaView*>(view->
GetViewByID(VIEW_ID_STATUS_AREA))->power_view();
return power;
}
int CallPowerChangedAndGetIconId() {
PowerMenuButton* power = GetPowerMenuButton();
power->PowerChanged(mock_power_library_);
return power->icon_id();
}
};
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryMissingTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(false)));
EXPECT_EQ(IDR_STATUSBAR_BATTERY_MISSING, CallPowerChangedAndGetIconId());
}
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, BatteryChargedTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, battery_fully_charged())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, line_power_on())
.WillRepeatedly((Return(true)));
EXPECT_EQ(IDR_STATUSBAR_BATTERY_CHARGED, CallPowerChangedAndGetIconId());
}
// http://crbug.com/48912
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, FAIL_BatteryChargingTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, battery_fully_charged())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_power_library_, line_power_on())
.WillRepeatedly((Return(true)));
// Test the 12 battery charging states.
int id = IDR_STATUSBAR_BATTERY_CHARGING_1;
for (float precent = 6.0; precent < 100.0; precent += 8.0) {
EXPECT_CALL(*mock_power_library_, battery_percentage())
.WillRepeatedly((Return(precent)));
EXPECT_EQ(id, CallPowerChangedAndGetIconId());
id++;
}
}
// http://crbug.com/48912
IN_PROC_BROWSER_TEST_F(PowerMenuButtonTest, FAIL_BatteryDischargingTest) {
EXPECT_CALL(*mock_power_library_, battery_is_present())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_power_library_, battery_fully_charged())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_power_library_, line_power_on())
.WillRepeatedly((Return(false)));
// Test the 12 battery discharing states.
int id = IDR_STATUSBAR_BATTERY_DISCHARGING_1;
for (float precent = 6.0; precent < 100.0; precent += 8.0) {
EXPECT_CALL(*mock_power_library_, battery_percentage())
.WillRepeatedly((Return(precent)));
EXPECT_EQ(id, CallPowerChangedAndGetIconId());
id++;
}
}
} // namespace chromeos
<|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 <oleacc.h>
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
namespace {
VARIANT id_self = {VT_I4, CHILDID_SELF};
// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;
class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
public:
BrowserViewsAccessibilityTest() {
::CoInitialize(NULL);
}
~BrowserViewsAccessibilityTest() {
::CoUninitialize();
}
// Retrieves an instance of BrowserWindowTesting
BrowserWindowTesting* GetBrowserWindowTesting() {
BrowserWindow* browser_window = browser()->window();
if (!browser_window)
return NULL;
return browser_window->GetBrowserWindowTesting();
}
// Retrieve an instance of BrowserView
BrowserView* GetBrowserView() {
return BrowserView::GetBrowserViewForNativeWindow(
browser()->window()->GetNativeHandle());
}
// Retrieves and initializes an instance of LocationBarView.
LocationBarView* GetLocationBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return GetBrowserWindowTesting()->GetLocationBarView();
}
// Retrieves and initializes an instance of ToolbarView.
ToolbarView* GetToolbarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetToolbarView();
}
// Retrieves and initializes an instance of BookmarkBarView.
BookmarkBarView* GetBookmarkBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetBookmarkBarView();
}
// Retrieves and verifies the accessibility object for the given View.
void TestViewAccessibilityObject(views::View* view, std::wstring name,
int32 role) {
ASSERT_TRUE(NULL != view);
IAccessible* acc_obj = NULL;
HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, name, role);
}
// Verifies MSAA Name and Role properties of the given IAccessible.
void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
int32 role) {
// Verify MSAA Name property.
BSTR acc_name;
HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(acc_name, name.c_str());
// Verify MSAA Role property.
VARIANT acc_role;
::VariantInit(&acc_role);
hr = acc_obj->get_accRole(id_self, &acc_role);
ASSERT_EQ(S_OK, hr);
EXPECT_EQ(VT_I4, acc_role.vt);
EXPECT_EQ(role, acc_role.lVal);
::VariantClear(&acc_role);
::SysFreeString(acc_name);
}
};
// Retrieve accessibility object for main window and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
FLAKY_TestChromeWindowAccObj) {
BrowserWindow* browser_window = browser()->window();
ASSERT_TRUE(NULL != browser_window);
HWND hwnd = browser_window->GetNativeHandle();
ASSERT_TRUE(NULL != hwnd);
// Get accessibility object.
IAccessible* acc_obj = NULL;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
// TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
// "about:blank - Chromium"
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
acc_obj->Release();
}
// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
views::View* non_client_view =
GetBrowserView()->GetWindow()->GetNonClientView();
TestViewAccessibilityObject(non_client_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBrowserRootViewAccObj) {
views::View* browser_root_view =
GetBrowserView()->frame()->GetFrameView()->GetRootView();
TestViewAccessibilityObject(browser_root_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_APPLICATION);
}
// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
// Verify root view MSAA name and role.
TestViewAccessibilityObject(GetBrowserView(),
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_CLIENT);
}
// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
// Verify toolbar MSAA name and role.
TestViewAccessibilityObject(GetToolbarView(),
l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
ROLE_SYSTEM_TOOLBAR);
}
// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
// Verify Back button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
// Verify Forward button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
// Verify Reload button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
// Verify Home button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestStarButtonAccObj) {
// Verify Star button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestLocationBarViewAccObj) {
// Verify location bar MSAA name and role.
TestViewAccessibilityObject(GetLocationBarView(),
l10n_util::GetString(IDS_ACCNAME_LOCATION),
ROLE_SYSTEM_GROUPING);
}
// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
// Verify Go button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
l10n_util::GetString(IDS_ACCNAME_GO),
ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
// Verify Page menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
l10n_util::GetString(IDS_ACCNAME_PAGE),
ROLE_SYSTEM_BUTTONMENU);
}
// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
// Verify App menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
l10n_util::GetString(IDS_ACCNAME_APP),
ROLE_SYSTEM_BUTTONMENU);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBookmarkBarViewAccObj) {
TestViewAccessibilityObject(GetBookmarkBarView(),
l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
ROLE_SYSTEM_TOOLBAR);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestAboutChromeViewAccObj) {
// Firstly, test that the WindowDelegate got updated.
views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
AccessibilityTypes::ROLE_DIALOG);
// Also test the accessibility object directly.
IAccessible* acc_obj = NULL;
HRESULT hr =
::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
OBJID_CLIENT,
IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
ROLE_SYSTEM_DIALOG);
acc_obj->Release();
}
} // Namespace.
<commit_msg>Fix flakyness of browser_tests:BrowserViewsAccessibilityTest.TestChromeWindowAccObj<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 <oleacc.h>
#include "app/l10n_util.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
namespace {
VARIANT id_self = {VT_I4, CHILDID_SELF};
// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;
class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
public:
BrowserViewsAccessibilityTest() {
::CoInitialize(NULL);
}
~BrowserViewsAccessibilityTest() {
::CoUninitialize();
}
// Retrieves an instance of BrowserWindowTesting
BrowserWindowTesting* GetBrowserWindowTesting() {
BrowserWindow* browser_window = browser()->window();
if (!browser_window)
return NULL;
return browser_window->GetBrowserWindowTesting();
}
// Retrieve an instance of BrowserView
BrowserView* GetBrowserView() {
return BrowserView::GetBrowserViewForNativeWindow(
browser()->window()->GetNativeHandle());
}
// Retrieves and initializes an instance of LocationBarView.
LocationBarView* GetLocationBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return GetBrowserWindowTesting()->GetLocationBarView();
}
// Retrieves and initializes an instance of ToolbarView.
ToolbarView* GetToolbarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetToolbarView();
}
// Retrieves and initializes an instance of BookmarkBarView.
BookmarkBarView* GetBookmarkBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetBookmarkBarView();
}
// Retrieves and verifies the accessibility object for the given View.
void TestViewAccessibilityObject(views::View* view, std::wstring name,
int32 role) {
ASSERT_TRUE(NULL != view);
ScopedComPtr<IAccessible> acc_obj;
HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, name, role);
}
// Verifies MSAA Name and Role properties of the given IAccessible.
void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
int32 role) {
// Verify MSAA Name property.
BSTR acc_name;
HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(acc_name, name.c_str());
// Verify MSAA Role property.
VARIANT acc_role;
::VariantInit(&acc_role);
hr = acc_obj->get_accRole(id_self, &acc_role);
ASSERT_EQ(S_OK, hr);
EXPECT_EQ(VT_I4, acc_role.vt);
EXPECT_EQ(role, acc_role.lVal);
::VariantClear(&acc_role);
::SysFreeString(acc_name);
}
};
// Retrieve accessibility object for main window and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestChromeWindowAccObj) {
BrowserWindow* browser_window = browser()->window();
ASSERT_TRUE(NULL != browser_window);
HWND hwnd = browser_window->GetNativeHandle();
ASSERT_TRUE(NULL != hwnd);
// Get accessibility object.
ScopedComPtr<IAccessible> acc_obj;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
std::wstring title =
l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
ASCIIToWide(chrome::kAboutBlankURL));
TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
views::View* non_client_view =
GetBrowserView()->GetWindow()->GetNonClientView();
TestViewAccessibilityObject(non_client_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBrowserRootViewAccObj) {
views::View* browser_root_view =
GetBrowserView()->frame()->GetFrameView()->GetRootView();
TestViewAccessibilityObject(browser_root_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_APPLICATION);
}
// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
// Verify root view MSAA name and role.
TestViewAccessibilityObject(GetBrowserView(),
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_CLIENT);
}
// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
// Verify toolbar MSAA name and role.
TestViewAccessibilityObject(GetToolbarView(),
l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
ROLE_SYSTEM_TOOLBAR);
}
// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
// Verify Back button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
// Verify Forward button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
// Verify Reload button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
// Verify Home button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestStarButtonAccObj) {
// Verify Star button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestLocationBarViewAccObj) {
// Verify location bar MSAA name and role.
TestViewAccessibilityObject(GetLocationBarView(),
l10n_util::GetString(IDS_ACCNAME_LOCATION),
ROLE_SYSTEM_GROUPING);
}
// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
// Verify Go button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
l10n_util::GetString(IDS_ACCNAME_GO),
ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
// Verify Page menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
l10n_util::GetString(IDS_ACCNAME_PAGE),
ROLE_SYSTEM_BUTTONMENU);
}
// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
// Verify App menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
l10n_util::GetString(IDS_ACCNAME_APP),
ROLE_SYSTEM_BUTTONMENU);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBookmarkBarViewAccObj) {
TestViewAccessibilityObject(GetBookmarkBarView(),
l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
ROLE_SYSTEM_TOOLBAR);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestAboutChromeViewAccObj) {
// Firstly, test that the WindowDelegate got updated.
views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
AccessibilityTypes::ROLE_DIALOG);
// Also test the accessibility object directly.
ScopedComPtr<IAccessible> acc_obj;
HRESULT hr =
::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
OBJID_CLIENT,
IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
ROLE_SYSTEM_DIALOG);
}
} // Namespace.
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: customcontrolcontainer.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:55:25 $
*
* 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_fpicker.hxx"
#ifndef _CUSTOMCONTROLCONTAINER_HXX_
#include "customcontrolcontainer.hxx"
#endif
#include <algorithm>
#include <functional>
//-----------------------------------
//
//-----------------------------------
namespace /* private */
{
void DeleteCustomControl(CCustomControl* aCustomControl)
{
delete aCustomControl;
};
void AlignCustomControl(CCustomControl* aCustomControl)
{
aCustomControl->Align();
};
class CSetFontHelper
{
public:
CSetFontHelper(HFONT hFont) :
m_hFont(hFont)
{
}
void SAL_CALL operator()(CCustomControl* aCustomControl)
{
aCustomControl->SetFont(m_hFont);
}
private:
HFONT m_hFont;
};
}
//-----------------------------------
//
//-----------------------------------
CCustomControlContainer::~CCustomControlContainer()
{
RemoveAllControls();
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::Align()
{
std::for_each(
m_ControlContainer.begin(),
m_ControlContainer.end(),
AlignCustomControl);
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::SetFont(HFONT hFont)
{
CSetFontHelper aSetFontHelper(hFont);
std::for_each(
m_ControlContainer.begin(),
m_ControlContainer.end(),
aSetFontHelper);
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::AddControl(CCustomControl* aCustomControl)
{
m_ControlContainer.push_back(aCustomControl);
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::RemoveControl(CCustomControl* aCustomControl)
{
ControlContainer_t::iterator iter_end = m_ControlContainer.end();
ControlContainer_t::iterator iter =
std::find(m_ControlContainer.begin(),iter_end,aCustomControl);
if (iter != iter_end)
{
delete *iter;
m_ControlContainer.remove(aCustomControl);
}
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::RemoveAllControls()
{
std::for_each(
m_ControlContainer.begin(),
m_ControlContainer.end(),
DeleteCustomControl);
m_ControlContainer.clear();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.158); FILE MERGED 2008/04/01 12:30:51 thb 1.3.158.2: #i85898# Stripping all external header guards 2008/03/31 13:13:18 rt 1.3.158.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: customcontrolcontainer.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"
#include "customcontrolcontainer.hxx"
#include <algorithm>
#include <functional>
//-----------------------------------
//
//-----------------------------------
namespace /* private */
{
void DeleteCustomControl(CCustomControl* aCustomControl)
{
delete aCustomControl;
};
void AlignCustomControl(CCustomControl* aCustomControl)
{
aCustomControl->Align();
};
class CSetFontHelper
{
public:
CSetFontHelper(HFONT hFont) :
m_hFont(hFont)
{
}
void SAL_CALL operator()(CCustomControl* aCustomControl)
{
aCustomControl->SetFont(m_hFont);
}
private:
HFONT m_hFont;
};
}
//-----------------------------------
//
//-----------------------------------
CCustomControlContainer::~CCustomControlContainer()
{
RemoveAllControls();
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::Align()
{
std::for_each(
m_ControlContainer.begin(),
m_ControlContainer.end(),
AlignCustomControl);
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::SetFont(HFONT hFont)
{
CSetFontHelper aSetFontHelper(hFont);
std::for_each(
m_ControlContainer.begin(),
m_ControlContainer.end(),
aSetFontHelper);
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::AddControl(CCustomControl* aCustomControl)
{
m_ControlContainer.push_back(aCustomControl);
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::RemoveControl(CCustomControl* aCustomControl)
{
ControlContainer_t::iterator iter_end = m_ControlContainer.end();
ControlContainer_t::iterator iter =
std::find(m_ControlContainer.begin(),iter_end,aCustomControl);
if (iter != iter_end)
{
delete *iter;
m_ControlContainer.remove(aCustomControl);
}
}
//-----------------------------------
//
//-----------------------------------
void SAL_CALL CCustomControlContainer::RemoveAllControls()
{
std::for_each(
m_ControlContainer.begin(),
m_ControlContainer.end(),
DeleteCustomControl);
m_ControlContainer.clear();
}
<|endoftext|> |
<commit_before><commit_msg>Rolled back new changes in integer_xl class.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 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 <seastar/testing/thread_test_case.hh>
#include "cdc/cdc.hh"
#include "tests/cql_assertions.hh"
#include "tests/cql_test_env.hh"
SEASTAR_THREAD_TEST_CASE(test_with_cdc_parameter) {
do_with_cql_env_thread([](cql_test_env& e) {
struct expected {
bool enabled = false;
bool preimage = false;
bool postimage = false;
int ttl = 86400;
};
auto assert_cdc = [&] (const expected& exp) {
BOOST_REQUIRE_EQUAL(exp.enabled,
e.local_db().find_schema("ks", "tbl")->cdc_options().enabled());
if (exp.enabled) {
e.require_table_exists("ks", cdc::log_name("tbl")).get();
e.require_table_exists("ks", cdc::desc_name("tbl")).get();
auto msg = e.execute_cql(format("select node_ip, shard_id from ks.{};", cdc::desc_name("tbl"))).get0();
std::vector<std::vector<bytes_opt>> expected_rows;
expected_rows.reserve(smp::count);
auto ip = inet_addr_type->decompose(
utils::fb_utilities::get_broadcast_address().addr());
for (int i = 0; i < static_cast<int>(smp::count); ++i) {
expected_rows.push_back({ip, int32_type->decompose(i)});
}
assert_that(msg).is_rows().with_rows_ignore_order(std::move(expected_rows));
} else {
e.require_table_does_not_exist("ks", cdc::log_name("tbl")).get();
e.require_table_does_not_exist("ks", cdc::desc_name("tbl")).get();
}
BOOST_REQUIRE_EQUAL(exp.preimage,
e.local_db().find_schema("ks", "tbl")->cdc_options().preimage());
BOOST_REQUIRE_EQUAL(exp.postimage,
e.local_db().find_schema("ks", "tbl")->cdc_options().postimage());
BOOST_REQUIRE_EQUAL(exp.ttl,
e.local_db().find_schema("ks", "tbl")->cdc_options().ttl());
};
auto test = [&] (const sstring& create_prop,
const sstring& alter1_prop,
const sstring& alter2_prop,
const expected& create_expected,
const expected& alter1_expected,
const expected& alter2_expected) {
e.execute_cql(format("CREATE TABLE ks.tbl (a int PRIMARY KEY) {}", create_prop)).get();
assert_cdc(create_expected);
e.execute_cql(format("ALTER TABLE ks.tbl WITH cdc = {}", alter1_prop)).get();
assert_cdc(alter1_expected);
e.execute_cql(format("ALTER TABLE ks.tbl WITH cdc = {}", alter2_prop)).get();
assert_cdc(alter2_expected);
e.execute_cql("DROP TABLE ks.tbl").get();
e.require_table_does_not_exist("ks", cdc::log_name("tbl")).get();
e.require_table_does_not_exist("ks", cdc::desc_name("tbl")).get();
};
test("", "{'enabled':'true'}", "{'enabled':'false'}", {false}, {true}, {false});
test("WITH cdc = {'enabled':'true'}", "{'enabled':'false'}", "{'enabled':'true'}", {true}, {false}, {true});
test("WITH cdc = {'enabled':'false'}", "{'enabled':'true'}", "{'enabled':'false'}", {false}, {true}, {false});
test("", "{'enabled':'true','preimage':'true','postimage':'true','ttl':'1'}", "{'enabled':'false'}", {false}, {true, true, true, 1}, {false});
test("WITH cdc = {'enabled':'true','preimage':'true','postimage':'true','ttl':'1'}", "{'enabled':'false'}", "{'enabled':'true','preimage':'false','postimage':'true','ttl':'2'}", {true, true, true, 1}, {false}, {true, false, true, 2});
}).get();
}
<commit_msg>test: add test_partition_key_logging<commit_after>/*
* Copyright (C) 2019 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 <seastar/testing/thread_test_case.hh>
#include "cdc/cdc.hh"
#include "tests/cql_assertions.hh"
#include "tests/cql_test_env.hh"
#include "transport/messages/result_message.hh"
SEASTAR_THREAD_TEST_CASE(test_with_cdc_parameter) {
do_with_cql_env_thread([](cql_test_env& e) {
struct expected {
bool enabled = false;
bool preimage = false;
bool postimage = false;
int ttl = 86400;
};
auto assert_cdc = [&] (const expected& exp) {
BOOST_REQUIRE_EQUAL(exp.enabled,
e.local_db().find_schema("ks", "tbl")->cdc_options().enabled());
if (exp.enabled) {
e.require_table_exists("ks", cdc::log_name("tbl")).get();
e.require_table_exists("ks", cdc::desc_name("tbl")).get();
auto msg = e.execute_cql(format("select node_ip, shard_id from ks.{};", cdc::desc_name("tbl"))).get0();
std::vector<std::vector<bytes_opt>> expected_rows;
expected_rows.reserve(smp::count);
auto ip = inet_addr_type->decompose(
utils::fb_utilities::get_broadcast_address().addr());
for (int i = 0; i < static_cast<int>(smp::count); ++i) {
expected_rows.push_back({ip, int32_type->decompose(i)});
}
assert_that(msg).is_rows().with_rows_ignore_order(std::move(expected_rows));
} else {
e.require_table_does_not_exist("ks", cdc::log_name("tbl")).get();
e.require_table_does_not_exist("ks", cdc::desc_name("tbl")).get();
}
BOOST_REQUIRE_EQUAL(exp.preimage,
e.local_db().find_schema("ks", "tbl")->cdc_options().preimage());
BOOST_REQUIRE_EQUAL(exp.postimage,
e.local_db().find_schema("ks", "tbl")->cdc_options().postimage());
BOOST_REQUIRE_EQUAL(exp.ttl,
e.local_db().find_schema("ks", "tbl")->cdc_options().ttl());
};
auto test = [&] (const sstring& create_prop,
const sstring& alter1_prop,
const sstring& alter2_prop,
const expected& create_expected,
const expected& alter1_expected,
const expected& alter2_expected) {
e.execute_cql(format("CREATE TABLE ks.tbl (a int PRIMARY KEY) {}", create_prop)).get();
assert_cdc(create_expected);
e.execute_cql(format("ALTER TABLE ks.tbl WITH cdc = {}", alter1_prop)).get();
assert_cdc(alter1_expected);
e.execute_cql(format("ALTER TABLE ks.tbl WITH cdc = {}", alter2_prop)).get();
assert_cdc(alter2_expected);
e.execute_cql("DROP TABLE ks.tbl").get();
e.require_table_does_not_exist("ks", cdc::log_name("tbl")).get();
e.require_table_does_not_exist("ks", cdc::desc_name("tbl")).get();
};
test("", "{'enabled':'true'}", "{'enabled':'false'}", {false}, {true}, {false});
test("WITH cdc = {'enabled':'true'}", "{'enabled':'false'}", "{'enabled':'true'}", {true}, {false}, {true});
test("WITH cdc = {'enabled':'false'}", "{'enabled':'true'}", "{'enabled':'false'}", {false}, {true}, {false});
test("", "{'enabled':'true','preimage':'true','postimage':'true','ttl':'1'}", "{'enabled':'false'}", {false}, {true, true, true, 1}, {false});
test("WITH cdc = {'enabled':'true','preimage':'true','postimage':'true','ttl':'1'}", "{'enabled':'false'}", "{'enabled':'true','preimage':'false','postimage':'true','ttl':'2'}", {true, true, true, 1}, {false}, {true, false, true, 2});
}).get();
}
SEASTAR_THREAD_TEST_CASE(test_partition_key_logging) {
do_with_cql_env_thread([](cql_test_env& e) {
cquery_nofail(e, "CREATE TABLE ks.tbl (pk int, pk2 int, ck int, ck2 int, val int, PRIMARY KEY((pk, pk2), ck, ck2)) WITH cdc = {'enabled':'true'}");
cquery_nofail(e, "INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 11, 111, 1111, 11111)");
cquery_nofail(e, "INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 22, 222, 2222, 22222)");
cquery_nofail(e, "INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 33, 333, 3333, 33333)");
cquery_nofail(e, "INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 44, 444, 4444, 44444)");
cquery_nofail(e, "INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(2, 11, 111, 1111, 11111)");
cquery_nofail(e, "DELETE val FROM ks.tbl WHERE pk = 1 AND pk2 = 11 AND ck = 111 AND ck2 = 1111");
cquery_nofail(e, "DELETE FROM ks.tbl WHERE pk = 1 AND pk2 = 11 AND ck = 111 AND ck2 = 1111");
cquery_nofail(e, "DELETE FROM ks.tbl WHERE pk = 1 AND pk2 = 11 AND ck > 222 AND ck <= 444");
cquery_nofail(e, "UPDATE ks.tbl SET val = 555 WHERE pk = 2 AND pk2 = 11 AND ck = 111 AND ck2 = 1111");
cquery_nofail(e, "DELETE FROM ks.tbl WHERE pk = 1 AND pk2 = 11");
auto msg = e.execute_cql(format("SELECT time, \"_pk\", \"_pk2\" FROM ks.{}", cdc::log_name("tbl"))).get0();
auto rows = dynamic_pointer_cast<cql_transport::messages::result_message::rows>(msg);
BOOST_REQUIRE(rows);
auto rs = rows->rs().result_set().rows();
std::vector<std::vector<bytes_opt>> results;
for (auto it = rs.begin(); it != rs.end(); ++it) {
results.push_back(*it);
}
std::sort(results.begin(), results.end(),
[] (const std::vector<bytes_opt>& a, const std::vector<bytes_opt>& b) {
return timeuuid_type->as_less_comparator()(*a[0], *b[0]);
});
auto actual_i = results.begin();
auto actual_end = results.end();
auto assert_row = [&] (int pk, int pk2) {
BOOST_REQUIRE(actual_i != actual_end);
auto& actual_row = *actual_i;
BOOST_REQUIRE_EQUAL(int32_type->decompose(pk), actual_row[1]);
BOOST_REQUIRE_EQUAL(int32_type->decompose(pk2), actual_row[2]);
++actual_i;
};
// INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 11, 111, 1111, 11111)
assert_row(1, 11);
// INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 22, 222, 2222, 22222)
assert_row(1, 22);
// INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 33, 333, 3333, 33333)
assert_row(1, 33);
// INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(1, 44, 444, 4444, 44444)
assert_row(1, 44);
// INSERT INTO ks.tbl(pk, pk2, ck, ck2, val) VALUES(2, 11, 111, 1111, 11111)
assert_row(2, 11);
// DELETE val FROM ks.tbl WHERE pk = 1 AND pk2 = 11 AND ck = 111 AND ck2 = 1111
assert_row(1, 11);
// DELETE FROM ks.tbl WHERE pk = 1 AND pk2 = 11 AND ck = 111 AND ck2 = 1111
assert_row(1, 11);
// DELETE FROM ks.tbl WHERE pk = 1 AND pk2 = 11 AND ck > 222 AND ck <= 444
assert_row(1, 11);
// UPDATE ks.tbl SET val = 555 WHERE pk = 2 AND pk2 = 11 AND ck = 111 AND ck2 = 1111
assert_row(2, 11);
// DELETE FROM ks.tbl WHERE pk = 1 AND pk2 = 11
assert_row(1, 11);
BOOST_REQUIRE(actual_i == actual_end);
}).get();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng ([email protected])
*
* This file is part of FlashMatrix.
*
* 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 <unordered_map>
#include "io_interface.h"
#include "matrix_config.h"
#include "mem_worker_thread.h"
#include "EM_object.h"
#include "local_mem_buffer.h"
namespace fm
{
namespace detail
{
#ifdef USE_HWLOC
std::vector<int> get_cpus(int node_id)
{
std::vector<int> io_cpus = safs::get_io_cpus();
std::vector<int> logical_units = cpus.get_node(node_id).get_logical_units();
std::set<int> cpu_set(logical_units.begin(), logical_units.end());
// Remove the logical units where I/O threads run.
for (size_t j = 0; j < io_cpus.size(); j++)
cpu_set.erase(io_cpus[j]);
return std::vector<int>(cpu_set.begin(), cpu_set.end());
}
#endif
mem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node)
{
tot_num_tasks = 0;
threads.resize(num_nodes);
for (int i = 0; i < num_nodes; i++) {
// Get the CPU cores that are in node i.
#ifdef USE_HWLOC
std::vector<int> cpus = get_cpus(i);
#endif
threads[i].resize(nthreads_per_node);
for (int j = 0; j < nthreads_per_node; j++) {
std::string name
= std::string("mem-worker-") + itoa(i) + "-" + itoa(j);
#ifdef USE_HWLOC
if (safs::get_io_cpus().empty())
threads[i][j] = std::shared_ptr<pool_task_thread>(
new pool_task_thread(i * nthreads_per_node + j, name, i));
else
threads[i][j] = std::shared_ptr<pool_task_thread>(
new pool_task_thread(i * nthreads_per_node + j, name,
cpus, i));
#else
threads[i][j] = std::shared_ptr<pool_task_thread>(
new pool_task_thread(i * nthreads_per_node + j, name, i));
#endif
threads[i][j]->start();
}
}
ntasks_per_node.resize(num_nodes);
}
/*
* This method dispatches tasks in a round-robin fashion.
*/
void mem_thread_pool::process_task(int node_id, thread_task *task)
{
if (node_id < 0)
node_id = tot_num_tasks % get_num_nodes();
assert((size_t) node_id < threads.size());
size_t idx = ntasks_per_node[node_id] % threads[node_id].size();
threads[node_id][idx]->add_task(task);
ntasks_per_node[node_id]++;
tot_num_tasks++;
}
void mem_thread_pool::wait4complete()
{
for (size_t i = 0; i < threads.size(); i++) {
size_t nthreads = threads[i].size();
for (size_t j = 0; j < nthreads; j++)
threads[i][j]->wait4complete();
}
// After all workers complete, we should try to clear the memory buffers
// in each worker thread to reduce memory consumption.
// We might want to keep the memory buffer for I/O on dense matrices.
if (matrix_conf.is_keep_mem_buf())
detail::local_mem_buffer::clear_bufs(
detail::local_mem_buffer::MAT_PORTION);
else
detail::local_mem_buffer::clear_bufs();
}
size_t mem_thread_pool::get_num_pending() const
{
size_t ret = 0;
for (size_t i = 0; i < threads.size(); i++) {
size_t nthreads = threads[i].size();
for (size_t j = 0; j < nthreads; j++)
ret += threads[i][j]->get_num_pending();
}
return ret;
}
static mem_thread_pool::ptr global_threads;
enum thread_pool_state {
UNINIT,
ACTIVE,
INACTIVE,
};
static thread_pool_state pool_state = thread_pool_state::UNINIT;
/*
* When we disable thread pool, we use the main thread to perform
* computation.
*/
bool mem_thread_pool::disable_thread_pool()
{
pool_state = thread_pool_state::INACTIVE;
return true;
}
bool mem_thread_pool::enable_thread_pool()
{
pool_state = thread_pool_state::ACTIVE;
return true;
}
mem_thread_pool::ptr mem_thread_pool::get_global_mem_threads()
{
assert(pool_state != thread_pool_state::INACTIVE);
if (global_threads == NULL) {
int nthreads_per_node
= matrix_conf.get_num_DM_threads() / matrix_conf.get_num_nodes();
assert(nthreads_per_node > 0);
global_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(),
nthreads_per_node);
enable_thread_pool();
}
return global_threads;
}
size_t mem_thread_pool::get_global_num_threads()
{
// When we disable the thread pool, we use the main thread for computation.
// So the number of threads is 1.
if (pool_state == thread_pool_state::INACTIVE)
return 1;
else
return get_global_mem_threads()->get_num_threads();
}
int mem_thread_pool::get_curr_thread_id()
{
// When we disable the thread pool, we use the main thread for computation.
// And we use 0 as the thread id of the main thread.
if (pool_state == thread_pool_state::INACTIVE)
return 0;
else {
detail::pool_task_thread *curr
= dynamic_cast<detail::pool_task_thread *>(thread::get_curr_thread());
if (curr)
return curr->get_pool_thread_id();
else
return -1;
}
}
void mem_thread_pool::init_global_mem_threads(int num_nodes,
int nthreads_per_node)
{
if (global_threads == NULL) {
global_threads = mem_thread_pool::create(num_nodes, nthreads_per_node);
enable_thread_pool();
}
}
void mem_thread_pool::destroy()
{
global_threads = NULL;
}
void io_worker_task::run()
{
std::vector<safs::io_interface::ptr> ios;
pthread_spin_lock(&lock);
for (auto it = EM_objs.begin(); it != EM_objs.end(); it++) {
std::vector<safs::io_interface::ptr> tmp = (*it)->create_ios();
ios.insert(ios.end(), tmp.begin(), tmp.end());
}
pthread_spin_unlock(&lock);
safs::io_select::ptr select = safs::create_io_select(ios);
// The task runs until there are no tasks left in the queue.
while (dispatch->issue_task())
safs::wait4ios(select, max_pending_ios);
// Test if all I/O instances have processed all requests.
size_t num_pending = safs::wait4ios(select, 0);
assert(num_pending == 0);
pthread_spin_lock(&lock);
EM_objs.clear();
pthread_spin_unlock(&lock);
for (size_t i = 0; i < ios.size(); i++) {
portion_callback &cb = static_cast<portion_callback &>(
ios[i]->get_callback());
assert(!cb.has_callback());
}
}
global_counter::global_counter()
{
counts.resize(mem_thread_pool::get_global_num_threads() + 1);
reset();
}
void global_counter::inc(size_t val)
{
int id = mem_thread_pool::get_curr_thread_id();
// the main thread has id of -1.
counts[id + 1].count += val;
}
void global_counter::reset()
{
for (size_t i = 0; i < counts.size(); i++)
counts[i].count = 0;
}
size_t global_counter::get() const
{
size_t tot = 0;
for (size_t i = 0; i < counts.size(); i++)
tot += counts[i].count;
return tot;
}
}
}
<commit_msg>[Matrix]: thread pool counts the main thread.<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng ([email protected])
*
* This file is part of FlashMatrix.
*
* 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 <unordered_map>
#include "io_interface.h"
#include "matrix_config.h"
#include "mem_worker_thread.h"
#include "EM_object.h"
#include "local_mem_buffer.h"
namespace fm
{
namespace detail
{
#ifdef USE_HWLOC
std::vector<int> get_cpus(int node_id)
{
std::vector<int> io_cpus = safs::get_io_cpus();
std::vector<int> logical_units = cpus.get_node(node_id).get_logical_units();
std::set<int> cpu_set(logical_units.begin(), logical_units.end());
// Remove the logical units where I/O threads run.
for (size_t j = 0; j < io_cpus.size(); j++)
cpu_set.erase(io_cpus[j]);
return std::vector<int>(cpu_set.begin(), cpu_set.end());
}
#endif
mem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node)
{
tot_num_tasks = 0;
threads.resize(num_nodes);
for (int i = 0; i < num_nodes; i++) {
// Get the CPU cores that are in node i.
#ifdef USE_HWLOC
std::vector<int> cpus = get_cpus(i);
#endif
threads[i].resize(nthreads_per_node);
for (int j = 0; j < nthreads_per_node; j++) {
std::string name
= std::string("mem-worker-") + itoa(i) + "-" + itoa(j);
#ifdef USE_HWLOC
if (safs::get_io_cpus().empty())
threads[i][j] = std::shared_ptr<pool_task_thread>(
new pool_task_thread(i * nthreads_per_node + j, name, i));
else
threads[i][j] = std::shared_ptr<pool_task_thread>(
new pool_task_thread(i * nthreads_per_node + j, name,
cpus, i));
#else
threads[i][j] = std::shared_ptr<pool_task_thread>(
new pool_task_thread(i * nthreads_per_node + j, name, i));
#endif
threads[i][j]->start();
}
}
ntasks_per_node.resize(num_nodes);
}
/*
* This method dispatches tasks in a round-robin fashion.
*/
void mem_thread_pool::process_task(int node_id, thread_task *task)
{
if (node_id < 0)
node_id = tot_num_tasks % get_num_nodes();
assert((size_t) node_id < threads.size());
size_t idx = ntasks_per_node[node_id] % threads[node_id].size();
threads[node_id][idx]->add_task(task);
ntasks_per_node[node_id]++;
tot_num_tasks++;
}
void mem_thread_pool::wait4complete()
{
for (size_t i = 0; i < threads.size(); i++) {
size_t nthreads = threads[i].size();
for (size_t j = 0; j < nthreads; j++)
threads[i][j]->wait4complete();
}
// After all workers complete, we should try to clear the memory buffers
// in each worker thread to reduce memory consumption.
// We might want to keep the memory buffer for I/O on dense matrices.
if (matrix_conf.is_keep_mem_buf())
detail::local_mem_buffer::clear_bufs(
detail::local_mem_buffer::MAT_PORTION);
else
detail::local_mem_buffer::clear_bufs();
}
size_t mem_thread_pool::get_num_pending() const
{
size_t ret = 0;
for (size_t i = 0; i < threads.size(); i++) {
size_t nthreads = threads[i].size();
for (size_t j = 0; j < nthreads; j++)
ret += threads[i][j]->get_num_pending();
}
return ret;
}
static mem_thread_pool::ptr global_threads;
enum thread_pool_state {
UNINIT,
ACTIVE,
INACTIVE,
};
static thread_pool_state pool_state = thread_pool_state::UNINIT;
/*
* When we disable thread pool, we use the main thread to perform
* computation.
*/
bool mem_thread_pool::disable_thread_pool()
{
pool_state = thread_pool_state::INACTIVE;
return true;
}
bool mem_thread_pool::enable_thread_pool()
{
pool_state = thread_pool_state::ACTIVE;
return true;
}
mem_thread_pool::ptr mem_thread_pool::get_global_mem_threads()
{
assert(pool_state != thread_pool_state::INACTIVE);
if (global_threads == NULL) {
int nthreads_per_node
= matrix_conf.get_num_DM_threads() / matrix_conf.get_num_nodes();
assert(nthreads_per_node > 0);
global_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(),
nthreads_per_node);
enable_thread_pool();
}
return global_threads;
}
size_t mem_thread_pool::get_global_num_threads()
{
// When we disable the thread pool, we use the main thread for computation.
// So the number of threads is 1.
if (pool_state == thread_pool_state::INACTIVE)
return 1;
else
// We also count the main thread.
return get_global_mem_threads()->get_num_threads() + 1;
}
int mem_thread_pool::get_curr_thread_id()
{
// When we disable the thread pool, we use the main thread for computation.
// And we use 0 as the thread id of the main thread.
if (pool_state == thread_pool_state::INACTIVE)
return 0;
else {
// It return 0 for the main thread. The worker thread Id starts with 1.
detail::pool_task_thread *curr
= dynamic_cast<detail::pool_task_thread *>(thread::get_curr_thread());
if (curr)
return curr->get_pool_thread_id() + 1;
else
return 0;
}
}
void mem_thread_pool::init_global_mem_threads(int num_nodes,
int nthreads_per_node)
{
if (global_threads == NULL) {
global_threads = mem_thread_pool::create(num_nodes, nthreads_per_node);
enable_thread_pool();
}
}
void mem_thread_pool::destroy()
{
global_threads = NULL;
}
void io_worker_task::run()
{
std::vector<safs::io_interface::ptr> ios;
pthread_spin_lock(&lock);
for (auto it = EM_objs.begin(); it != EM_objs.end(); it++) {
std::vector<safs::io_interface::ptr> tmp = (*it)->create_ios();
ios.insert(ios.end(), tmp.begin(), tmp.end());
}
pthread_spin_unlock(&lock);
safs::io_select::ptr select = safs::create_io_select(ios);
// The task runs until there are no tasks left in the queue.
while (dispatch->issue_task())
safs::wait4ios(select, max_pending_ios);
// Test if all I/O instances have processed all requests.
size_t num_pending = safs::wait4ios(select, 0);
assert(num_pending == 0);
pthread_spin_lock(&lock);
EM_objs.clear();
pthread_spin_unlock(&lock);
for (size_t i = 0; i < ios.size(); i++) {
portion_callback &cb = static_cast<portion_callback &>(
ios[i]->get_callback());
assert(!cb.has_callback());
}
}
global_counter::global_counter()
{
counts.resize(mem_thread_pool::get_global_num_threads());
reset();
}
void global_counter::inc(size_t val)
{
int id = mem_thread_pool::get_curr_thread_id();
counts[id].count += val;
}
void global_counter::reset()
{
for (size_t i = 0; i < counts.size(); i++)
counts[i].count = 0;
}
size_t global_counter::get() const
{
size_t tot = 0;
for (size_t i = 0; i < counts.size(); i++)
tot += counts[i].count;
return tot;
}
}
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <roboteqMC.h>
AX2550::AX2550(HardwareSerial& serial_port):uart(serial_port)
{
uart.begin(9600,SERIAL_7E1);
}
void AX2550::init(uint8_t x,uint8_t y){
x_key = x;
y_key = y;
}
void AX2550::set_report(uint8_t v,uint8_t l,uint8_t r){
volt_key = v;
amps_left_key = l;
amps_right_key = r;
}
bool AX2550::move(int Steering,int Throttle, bool check)
{
int8_t Dir1 = 0;
int8_t Dir2 = 0;
while(uart.available()>0)
{
uart.read();
}
if(Throttle>=0)
{
Dir1 = 0x41;
}
if(Throttle<0)
{
Dir1 = 0x61;
}
if(Steering>=0)
{
Dir2 = 0x42;
}
if(Steering<0)
{
Dir2 = 0x62;
}
Throttle = map(abs(Throttle),0,100,0,126);
Steering = map(abs(Steering),0,100,0,126);
char command[12];
sprintf(command,"!%c%02x\r\n!%c%02x\r\n",Dir1,abs(Throttle),Dir2,abs(Steering));
uart.print(command);
if(check){
delay(10);
bool chk_throttle = chkResponse();
bool chk_steering = chkResponse();
while(uart.available()>0){
uart.read();
}
return chk_throttle & chk_steering;
}
return true;
}
bool AX2550::move(Message inp, bool check){
if(inp.new_data(y_key) || inp.new_data(x_key)){
return move(int16_t(inp.get_data(y_key)),int16_t(inp.get_data(x_key)),check);
}
return false;
}
bool AX2550::chkResponse()
{
char status;
uint8_t counter=0;
while(1)
{
status = uart.read();
//Serial.print(status);
if(status == '+')
{
return true;
}
else if(status == '-')
{
//Serial.println("Command Fails!");
return false;
}
else if(counter == 20)
{
Serial3.println("Chk response Timeout");
return false;
}
else
{
counter+=1;
delay(1);
}
}
}
float AX2550::volt()
{
while(uart.available())
{
uart.read();
}
char command[2];
sprintf(command,"?e");
if(sendChk(command))
{
char inp[2];
uart.read();
uart.read();
uart.read();
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
// Serial.println(inp[0]);
// Serial.println(inp[1]);
// Serial.println(inp[2]);
// Serial.println(inp[3]);
float volt = 28.5 * strtoul(inp,0,16)/256;
// Serial.println(volt);
delay(10);
while(uart.available())
{
uart.read();
}
return volt;
}
return 0.0;
}
int AX2550::amps(uint8_t channel)
{
while(uart.available())
{
uart.read();
}
char command[2];
sprintf(command,"?a");
if(sendChk(command))
{
char inp[2];
if(channel == 1)
{
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
}
if(channel == 2)
{
uart.read();
uart.read();
uart.read();
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
}
// Serial.println(inp[0]);
// Serial.println(inp[1]);
// Serial.println(inp[2]);
// Serial.println(inp[3]);
int amps = strtoul(inp,0,16);
// Serial.println(volt);
delay(10);
while(uart.available())
{
uart.read();
}
return amps;
}
// Serial.println("Fail!");
return 0;
}
bool AX2550::sendChk(char buff[])
{
uint8_t lenght = strlen(buff);
char input_buff[lenght];
uart.println(buff);
uint8_t counter=0;
uint8_t timeout=100;
delay(10);
while(1)
{
if(uart.available()>0)
{
for(int i=0;i<lenght;i++)
{
input_buff[i]=uart.read();
if(input_buff[i]!=buff[i])
{
//Echo Condition
// Serial.println("Echo Error!");
return false;
}
}
return true;
}
else if(counter == timeout)
{
//Timeout condition
// Serial.println("Timeout Error!");
return false;
}
else
{
counter+=1;
delay(1);
}
}
}
Message AX2550::report(){
Message output;
output.add_data(amps_left_key,uint16_t(amps(1)));
output.add_data(amps_right_key,uint16_t(amps(2)));
output.add_data(volt_key,uint16_t(volt()));
return output;
}<commit_msg>Fix Voltage read function<commit_after>#include <Arduino.h>
#include <roboteqMC.h>
AX2550::AX2550(HardwareSerial& serial_port):uart(serial_port)
{
uart.begin(9600,SERIAL_7E1);
}
void AX2550::init(uint8_t x,uint8_t y){
x_key = x;
y_key = y;
}
void AX2550::set_report(uint8_t v,uint8_t l,uint8_t r){
volt_key = v;
amps_left_key = l;
amps_right_key = r;
}
bool AX2550::move(int Steering,int Throttle, bool check)
{
int8_t Dir1 = 0;
int8_t Dir2 = 0;
while(uart.available()>0)
{
uart.read();
}
if(Throttle>=0)
{
Dir1 = 0x41;
}
if(Throttle<0)
{
Dir1 = 0x61;
}
if(Steering>=0)
{
Dir2 = 0x42;
}
if(Steering<0)
{
Dir2 = 0x62;
}
Throttle = map(abs(Throttle),0,100,0,126);
Steering = map(abs(Steering),0,100,0,126);
char command[12];
sprintf(command,"!%c%02x\r\n!%c%02x\r\n",Dir1,abs(Throttle),Dir2,abs(Steering));
uart.print(command);
if(check){
delay(10);
bool chk_throttle = chkResponse();
bool chk_steering = chkResponse();
while(uart.available()>0){
uart.read();
}
return chk_throttle & chk_steering;
}
return true;
}
bool AX2550::move(Message inp, bool check){
if(inp.new_data(y_key) || inp.new_data(x_key)){
return move(int16_t(inp.get_data(y_key)),int16_t(inp.get_data(x_key)),check);
}
return false;
}
bool AX2550::chkResponse()
{
char status;
uint8_t counter=0;
while(1)
{
status = uart.read();
//Serial.print(status);
if(status == '+')
{
return true;
}
else if(status == '-')
{
//Serial.println("Command Fails!");
return false;
}
else if(counter == 20)
{
Serial3.println("Chk response Timeout");
return false;
}
else
{
counter+=1;
delay(1);
}
}
}
float AX2550::volt()
{
while(uart.available())
{
uart.read();
}
char command[2];
sprintf(command,"?e");
if(sendChk(command))
{
char inp[4];
/*
while(uart.available()){
Serial.println(char(uart.read()));
}
uart.read();
uart.read();
uart.read();
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
// Serial.println(inp[0]);
// Serial.println(inp[1]);
// Serial.println(inp[2]);
// Serial.println(inp[3]);
*/
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
uart.read();
uart.read();
uart.read();
uint16_t conv = strtoul(inp,0,16);
Serial.println(conv);
float volt = 55 * conv/256.0;
Serial.println(volt);
delay(10);
while(uart.available())
{
uart.read();
}
return volt;
}
return 0.0;
}
int AX2550::amps(uint8_t channel)
{
while(uart.available())
{
uart.read();
}
char command[2];
sprintf(command,"?a");
if(sendChk(command))
{
char inp[2];
if(channel == 1)
{
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
}
if(channel == 2)
{
uart.read();
uart.read();
uart.read();
uart.read();
inp[0] = '0';
inp[1] = 'x';
inp[2] = char(uart.read());
inp[3] = char(uart.read());
}
// Serial.println(inp[0]);
// Serial.println(inp[1]);
// Serial.println(inp[2]);
// Serial.println(inp[3]);
int amps = strtoul(inp,0,16);
// Serial.println(volt);
delay(10);
while(uart.available())
{
uart.read();
}
return amps;
}
// Serial.println("Fail!");
return 0;
}
bool AX2550::sendChk(char buff[])
{
uint8_t lenght = strlen(buff);
char input_buff[lenght];
uart.println(buff);
uint8_t counter=0;
uint8_t timeout=100;
delay(10);
while(1)
{
if(uart.available()>0)
{
for(int i=0;i<lenght;i++)
{
input_buff[i]=uart.read();
if(input_buff[i]!=buff[i])
{
//Echo Condition
// Serial.println("Echo Error!");
return false;
}
}
return true;
}
else if(counter == timeout)
{
//Timeout condition
// Serial.println("Timeout Error!");
return false;
}
else
{
counter+=1;
delay(1);
}
}
}
Message AX2550::report(){
Message output;
output.add_data(amps_left_key,uint16_t(amps(1)));
output.add_data(amps_right_key,uint16_t(amps(2)));
output.add_data(volt_key,uint16_t(volt()));
return output;
}<|endoftext|> |
<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include <ssl.h>
#include <nanoPAL.h>
#include "mbedtls.h"
int ssl_available_internal(int sd)
{
mbedTLS_NFContext *context = (mbedTLS_NFContext *)SOCKET_DRIVER.GetSocketSslData(sd);
mbedtls_ssl_context *ssl = context->ssl;
// sanity check
if (ssl == NULL)
{
return SOCK_SOCKET_ERROR;
}
mbedtls_ssl_read(ssl, NULL, 0);
if (mbedtls_ssl_check_pending(ssl))
{
return mbedtls_ssl_get_bytes_avail(ssl);
}
else
{
return 0;
}
}
<commit_msg>Fix call to data available in SSL stream (#1871)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include <ssl.h>
#include <nanoPAL.h>
#include "mbedtls.h"
int ssl_available_internal(int sd)
{
mbedTLS_NFContext *context = (mbedTLS_NFContext *)SOCKET_DRIVER.GetSocketSslData(sd);
mbedtls_ssl_context *ssl = context->ssl;
// sanity check
if (ssl == NULL)
{
return SOCK_SOCKET_ERROR;
}
// Developer note
// Ideally we should be making a call to read passing a NULL pointer and requesting 0 bytes
// Like this: mbedtls_ssl_read(ssl, NULL, 0)
// It won't work because we are using blockign sockets.
// Even if we unblock it temporarily, it will still won't return until there is something to be read.
// That call will block the execution and the watchdog will eventually kick in.
// Bottom line: take the information provided by this call as informational.
int availableBytes = mbedtls_ssl_check_pending(ssl);
if (availableBytes > 0)
{
return mbedtls_ssl_get_bytes_avail(ssl);
}
else
{
return availableBytes;
}
}
<|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 "paddle/framework/backward.h"
#include "paddle/framework/net.h"
#include "paddle/framework/op_registry.h"
namespace paddle {
namespace framework {
static bool AllInSet(const std::vector<std::string>& names,
const std::string& suffix,
const std::unordered_set<std::string>& set) {
for (auto& name : names) {
if (set.find(name + suffix) == set.end()) {
return false;
}
}
return true;
}
static std::vector<size_t> InSetIdx(
const std::vector<std::string>& names, const std::string& suffix,
const std::unordered_set<std::string>& set) {
std::vector<size_t> ret_val;
ret_val.reserve(names.size());
for (size_t i = 0; i < names.size(); ++i) {
if (set.find(names[i] + suffix) != set.end()) {
ret_val.push_back(i);
}
}
return ret_val;
}
static std::shared_ptr<OperatorBase> EmptyOp() {
auto net_op = std::make_shared<NetOp>();
net_op->CompleteAddOp();
return net_op;
}
static void DeDuplicate(NetOp* net, std::unordered_se)
static std::shared_ptr<OperatorBase> BackwardImpl(
const OperatorBase& forwardOp,
std::unordered_set<std::string>& no_grad_names, unsigned& uniq_id) {
if (AllInSet(forwardOp.inputs_, OperatorBase::GRAD_VAR_SUFFIX(),
no_grad_names)) {
return EmptyOp();
}
if (AllInSet(forwardOp.outputs_, OperatorBase::GRAD_VAR_SUFFIX(),
no_grad_names)) {
for (auto& name : forwardOp.inputs_) {
// Mark all input is not need
no_grad_names.insert(name + OperatorBase::GRAD_VAR_SUFFIX());
}
return EmptyOp();
}
auto* net = new NetOp();
if (forwardOp.IsNetOp()) {
//! TODO(dzh)
std::unordered_map<std::string, int> dup_output;
std::unordered_map<std::string std::vector<int>> dup_output_ops;
const unsigned uniq_id_local = uniq_id;
unsigned op_id_offset = 0;
for (auto& fwd : forwardOp) {
auto bwd = Backward(fwd, no_grad_names);
net->AddOp(bwd);
for (size_t i = 0; i < bwd.outputs_; ++i) {
bwd->outputs_[i] += OperatorBase::EMPTY_VAR_NAME();
if (dup_output.find(bwd->inputs_[i]) == dup_output.end()) {
dup_output[bwd->inputs_[i]] = 1;
dup_output_ops[bwd->inputs_[i]] = std::vector<int>{op_id_offset++};
} else {
dup_output[bwd->inputs_[i]]++;
dup_output_ops[bwd->inputs_[i]].emplace_back(op_id_offset++);
}
}
}
for (auto dup : dup_output) {
if (dup.second == 1) continue;
auto op_ids = dup_output_ops.at(dup.first);
for (auto& op_id : op_ids) {
auto& op_ptr = net->ops_[op_id];
for (size_t i = 0; i < op_ptr->inputs_.size(); ++i) {
if (op_ptr->inputs_[i] == dup.first) {
// unique the duplicate name
op_ptr->inputs_[i] += std::to_string(uniq_id++);
// TODO(dzh): need a generic add op here
}
}
}
}
} else {
//! TODO(fjy)
std::shared_ptr<OperatorBase> grad_op = OpRegistry::CreateGradOp(forwardOp);
for (std::string& grad_input : grad_op->inputs_) {
if (no_grad_names.count(grad_input)) {
std::string prefix = grad_input.substr(
0, grad_input.size() - OperatorBase::GRAD_VAR_SUFFIX().size());
grad_input = prefix + OperatorBase::ZERO_VAR_SUFFIX();
net->AddOp(OpRegistry::CreateOp("fill_zeros_like", {prefix},
{grad_input}, {}));
}
}
for (std::string& grad_output : grad_op->outputs_) {
if (no_grad_names.count(grad_output)) {
grad_output = OperatorBase::EMPTY_VAR_NAME();
}
}
net->AddOp(grad_op);
}
net->CompleteAddOp();
return std::shared_ptr<OperatorBase>(net);
}
extern std::shared_ptr<OperatorBase> Backward(
const OperatorBase& forwardOp,
const std::unordered_set<std::string>& no_grad_vars) {
std::unordered_set<std::string> no_grad_names;
no_grad_names.reserve(no_grad_vars.size());
for (auto& name : no_grad_vars) {
no_grad_names.insert(name + OperatorBase::GRAD_VAR_SUFFIX());
}
int uid = 0;
return BackwardImpl(forwardOp, no_grad_names, uid);
}
} // namespace framework
} // namespace paddle
<commit_msg>Fix compile error<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 "paddle/framework/backward.h"
#include "paddle/framework/net.h"
#include "paddle/framework/op_registry.h"
namespace paddle {
namespace framework {
static bool AllInSet(const std::vector<std::string>& names,
const std::string& suffix,
const std::unordered_set<std::string>& set) {
for (auto& name : names) {
if (set.find(name + suffix) == set.end()) {
return false;
}
}
return true;
}
static std::vector<size_t> InSetIdx(
const std::vector<std::string>& names, const std::string& suffix,
const std::unordered_set<std::string>& set) {
std::vector<size_t> ret_val;
ret_val.reserve(names.size());
for (size_t i = 0; i < names.size(); ++i) {
if (set.find(names[i] + suffix) != set.end()) {
ret_val.push_back(i);
}
}
return ret_val;
}
static std::shared_ptr<OperatorBase> EmptyOp() {
auto net_op = std::make_shared<NetOp>();
net_op->CompleteAddOp();
return net_op;
}
static std::shared_ptr<OperatorBase> BackwardImpl(
const OperatorBase& forwardOp,
std::unordered_set<std::string>& no_grad_names, size_t& uniq_id) {
if (AllInSet(forwardOp.inputs_, OperatorBase::GRAD_VAR_SUFFIX(),
no_grad_names)) {
return EmptyOp();
}
if (AllInSet(forwardOp.outputs_, OperatorBase::GRAD_VAR_SUFFIX(),
no_grad_names)) {
for (auto& name : forwardOp.inputs_) {
// Mark all input is not need
no_grad_names.insert(name + OperatorBase::GRAD_VAR_SUFFIX());
}
return EmptyOp();
}
auto* net = new NetOp();
if (forwardOp.IsNetOp()) {
//! TODO(dzh)
std::unordered_map<std::string, int> dup_output;
std::unordered_map<std::string, std::vector<int>> dup_output_ops;
// const unsigned uniq_id_local = uniq_id;
int op_id_offset = 0;
// Because it is a net op, it can static_cast.
auto& forwardNet = static_cast<const NetOp&>(forwardOp);
for (auto& fwd : forwardNet.ops_) {
auto bwd = Backward(*fwd, no_grad_names);
net->AddOp(bwd);
for (size_t i = 0; i < bwd->outputs_.size(); ++i) {
bwd->outputs_[i] += OperatorBase::EMPTY_VAR_NAME();
if (dup_output.find(bwd->inputs_[i]) == dup_output.end()) {
dup_output[bwd->inputs_[i]] = 1;
dup_output_ops[bwd->inputs_[i]] = std::vector<int>{op_id_offset++};
} else {
dup_output[bwd->inputs_[i]]++;
dup_output_ops[bwd->inputs_[i]].emplace_back(op_id_offset++);
}
}
}
for (auto dup : dup_output) {
if (dup.second == 1) continue;
auto op_ids = dup_output_ops.at(dup.first);
for (auto& op_id : op_ids) {
auto& op_ptr = net->ops_[op_id];
for (size_t i = 0; i < op_ptr->inputs_.size(); ++i) {
if (op_ptr->inputs_[i] == dup.first) {
// unique the duplicate name
op_ptr->inputs_[i] += std::to_string(uniq_id++);
// TODO(dzh): need a generic add op here
}
}
}
}
} else {
//! TODO(fjy)
std::shared_ptr<OperatorBase> grad_op = OpRegistry::CreateGradOp(forwardOp);
for (std::string& grad_input : grad_op->inputs_) {
if (no_grad_names.count(grad_input)) {
std::string prefix = grad_input.substr(
0, grad_input.size() - OperatorBase::GRAD_VAR_SUFFIX().size());
grad_input = prefix + OperatorBase::ZERO_VAR_SUFFIX();
net->AddOp(OpRegistry::CreateOp("fill_zeros_like", {prefix},
{grad_input}, {}));
}
}
for (std::string& grad_output : grad_op->outputs_) {
if (no_grad_names.count(grad_output)) {
grad_output = OperatorBase::EMPTY_VAR_NAME();
}
}
net->AddOp(grad_op);
}
net->CompleteAddOp();
return std::shared_ptr<OperatorBase>(net);
}
extern std::shared_ptr<OperatorBase> Backward(
const OperatorBase& forwardOp,
const std::unordered_set<std::string>& no_grad_vars) {
std::unordered_set<std::string> no_grad_names;
no_grad_names.reserve(no_grad_vars.size());
for (auto& name : no_grad_vars) {
no_grad_names.insert(name + OperatorBase::GRAD_VAR_SUFFIX());
}
size_t uid = 0;
return BackwardImpl(forwardOp, no_grad_names, uid);
}
} // namespace framework
} // namespace paddle
<|endoftext|> |
<commit_before>/*
Copyright 2013 KU Leuven, Dept. Electrical Engineering, Medical Image Computing
Herestraat 49 box 7003, 3000 Leuven, Belgium
Written by Daan Christiaens, 06/06/13.
This file is part of the Global Tractography module for MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mhsampler.h"
#include "math/math.h"
namespace MR {
namespace DWI {
namespace Tractography {
namespace GT {
MHSampler::MHSampler(const Image::Info &dwi, Properties &p, Stats &s, ParticleGrid &pgrid,
EnergyComputer* e, Image::BufferPreload<bool>* m)
: props(p), stats(s), pGrid(pgrid), E(e), T(dwi), sigpos(Particle::L / 8.), sigdir(0.2)
{
lock = new SpatialLock<>(5*Particle::L); // FIXME take voxel size into account for setting lock threshold.
if (m) {
T = Image::Transform(*m);
dims[0] = m->dim(0);
dims[1] = m->dim(1);
dims[2] = m->dim(2);
mask = new Image::BufferPreload<bool>::voxel_type(*m);
}
else {
dims[0] = dwi.dim(0);
dims[1] = dwi.dim(1);
dims[2] = dwi.dim(2);
}
}
// RUNTIME METHODS --------------------------------------------------------------
void MHSampler::execute()
{
do {
next();
} while (stats.next());
}
void MHSampler::next()
{
float p = rng.uniform();
float s = props.p_birth;
if (p < s)
return birth();
s += props.p_death;
if (p < s)
return death();
s += props.p_shift;
if (p < s)
return randshift();
s += props.p_optshift;
if (p < s)
return optshift();
s += props.p_connect;
if (p < s)
return connect();
}
// PROPOSAL DISTRIBUTIONS -------------------------------------------------------
void MHSampler::birth()
{
//TRACE;
stats.incN('b');
Point_t pos;
do {
pos = getRandPosInMask();
} while (! lock->lockIfNotLocked(pos));
Point_t dir = getRandDir();
double dE = E->stageAdd(pos, dir);
double R = std::exp(-dE) * props.density / (pGrid.getTotalCount()+1) * props.p_death / props.p_birth;
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.add(pos, dir);
stats.incNa('b');
}
else {
E->clearChanges();
}
lock->unlock(pos);
}
void MHSampler::death()
{
//TRACE;
stats.incN('d');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL || par->hasPredecessor() || par->hasSuccessor())
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
double dE = E->stageRemove(par);
double R = std::exp(-dE) * pGrid.getTotalCount() / props.density * props.p_birth / props.p_death;
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.remove(idx);
stats.incNa('d');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
void MHSampler::randshift()
{
//TRACE;
stats.incN('r');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL)
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
Point_t pos, dir;
moveRandom(par, pos, dir);
if (!inMask(T.scanner2voxel(pos))) {
lock->unlock(pos0);
return;
}
double dE = E->stageShift(par, pos, dir);
double R = exp(-dE);
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.shift(idx, pos, dir);
stats.incNa('r');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
void MHSampler::optshift()
{
//TRACE;
stats.incN('o');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL)
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
Point_t pos, dir;
bool moved = moveOptimal(par, pos, dir);
if (!moved || !inMask(T.scanner2voxel(pos))) {
lock->unlock(pos0);
return;
}
double dE = E->stageShift(par, pos, dir);
double p_prop = calcShiftProb(par, pos, dir);
double R = exp(-dE) * props.p_shift * p_prop / (props.p_shift * p_prop + props.p_optshift);
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.shift(idx, pos, dir);
stats.incNa('o');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
void MHSampler::connect() // TODO Current implementation does not prevent loops.
{
//TRACE;
stats.incN('c');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL)
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
int alpha0 = (rng.uniform() < 0.5) ? -1 : 1;
ParticleEnd pe0;
pe0.par = par;
pe0.alpha = alpha0;
ParticleEnd pe2;
pe2.par = NULL;
double dE = E->stageConnect(pe0, pe2);
double R = exp(-dE);
if (R > rng.uniform()) {
E->acceptChanges();
if (pe2.par) {
if (alpha0 == -1)
par->connectPredecessor(pe2.par, pe2.alpha);
else
par->connectSuccessor(pe2.par, pe2.alpha);
} else {
if ((alpha0 == -1) && par->hasPredecessor())
par->removePredecessor();
else if ((alpha0 == +1) && par->hasSuccessor())
par->removeSuccessor();
}
stats.incNa('c');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
// SUPPORTING METHODS -----------------------------------------------------------
Point_t MHSampler::getRandPosInMask()
{
Point_t p;
do {
p[0] = rng.uniform() * (dims[0]-1);
p[1] = rng.uniform() * (dims[1]-1);
p[2] = rng.uniform() * (dims[2]-1);
} while (!inMask(p)); // FIXME Schrijf dit expliciet uit ifv random integer initialisatie,
return T.voxel2scanner(p); // voeg hier dan nog random ruis aan toe. Dan kan je inMask terug ifv
} // scanner positie schrijven.
bool MHSampler::inMask(const Point_t p) const
{
// if ((p[0] <= -0.5) || (p[0] >= dims[0]-0.5) ||
// (p[1] <= -0.5) || (p[1] >= dims[1]-0.5) ||
// (p[2] <= -0.5) || (p[2] >= dims[2]-0.5))
if ((p[0] <= 0.0) || (p[0] >= dims[0]-1.0) ||
(p[1] <= 0.0) || (p[1] >= dims[1]-1.0) ||
(p[2] <= 0.0) || (p[2] >= dims[2]-1.0))
return false;
if (mask) {
(*mask)[0] = std::round<size_t>(p[0]);
(*mask)[1] = std::round<size_t>(p[1]);
(*mask)[2] = std::round<size_t>(p[2]);
return mask->value();
}
return true;
}
Point_t MHSampler::getRandDir()
{
Point_t dir = Point_t(rng.normal(), rng.normal(), rng.normal());
dir.normalise();
return dir;
}
void MHSampler::moveRandom(const Particle *par, Point_t &pos, Point_t &dir)
{
pos = par->getPosition() + Point_t(rng.normal(sigpos), rng.normal(sigpos), rng.normal(sigpos));
dir = par->getDirection() + Point_t(rng.normal(sigdir), rng.normal(sigdir), rng.normal(sigdir));
dir.normalise();
}
bool MHSampler::moveOptimal(const Particle *par, Point_t &pos, Point_t &dir) const
{
// assert(par != NULL)
if (par->hasPredecessor() && par->hasSuccessor())
{
int a1 = (par->getPredecessor()->getPredecessor() == par) ? -1 : 1;
int a3 = (par->getSuccessor()->getPredecessor() == par) ? -1 : 1;
pos = (par->getPredecessor()->getEndPoint(a1) + par->getSuccessor()->getEndPoint(a3)) / 2;
dir = par->getSuccessor()->getPosition() - par->getPredecessor()->getPosition();
dir.normalise();
return true;
}
else if (par->hasPredecessor())
{
int a = (par->getPredecessor()->getPredecessor() == par) ? -1 : 1;
pos = par->getPredecessor()->getEndPoint(2*a);
dir = par->getPredecessor()->getDirection() * a;
return true;
}
else if (par->hasSuccessor())
{
int a = (par->getSuccessor()->getPredecessor() == par) ? -1 : 1;
pos = par->getSuccessor()->getEndPoint(2*a);
dir = par->getSuccessor()->getDirection() * (-a);
return true;
}
else
{
return false;
}
}
double MHSampler::calcShiftProb(const Particle *par, const Point_t &pos, const Point_t &dir) const
{
Point_t Dpos = par->getPosition() - pos;
Point_t Ddir = par->getDirection() - dir;
return gsl_ran_gaussian_pdf(Dpos[0], sigpos) * gsl_ran_gaussian_pdf(Dpos[1], sigpos) * gsl_ran_gaussian_pdf(Dpos[2], sigpos) *
gsl_ran_gaussian_pdf(Ddir[0], sigdir) * gsl_ran_gaussian_pdf(Ddir[1], sigdir) * gsl_ran_gaussian_pdf(Ddir[2], sigdir);
// Point_t Dep1 = par->getEndPoint(-1) - (pos - Particle::L * dir);
// Point_t Dep2 = par->getEndPoint(1) - (pos + Particle::L * dir);
// double sigma = Particle::L/2;
// return gsl_ran_gaussian_pdf(Dep1[0], sigma) * gsl_ran_gaussian_pdf(Dep1[1], sigma) * gsl_ran_gaussian_pdf(Dep1[2], sigma) *
// gsl_ran_gaussian_pdf(Dep2[0], sigma) * gsl_ran_gaussian_pdf(Dep2[1], sigma) * gsl_ran_gaussian_pdf(Dep2[2], sigma);
}
}
}
}
}
<commit_msg>Fix floating-point rounding at the edge of the brain mask.<commit_after>/*
Copyright 2013 KU Leuven, Dept. Electrical Engineering, Medical Image Computing
Herestraat 49 box 7003, 3000 Leuven, Belgium
Written by Daan Christiaens, 06/06/13.
This file is part of the Global Tractography module for MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mhsampler.h"
#include "math/math.h"
namespace MR {
namespace DWI {
namespace Tractography {
namespace GT {
MHSampler::MHSampler(const Image::Info &dwi, Properties &p, Stats &s, ParticleGrid &pgrid,
EnergyComputer* e, Image::BufferPreload<bool>* m)
: props(p), stats(s), pGrid(pgrid), E(e), T(dwi), sigpos(Particle::L / 8.), sigdir(0.2)
{
lock = new SpatialLock<>(5*Particle::L); // FIXME take voxel size into account for setting lock threshold.
if (m) {
T = Image::Transform(*m);
dims[0] = m->dim(0);
dims[1] = m->dim(1);
dims[2] = m->dim(2);
mask = new Image::BufferPreload<bool>::voxel_type(*m);
}
else {
dims[0] = dwi.dim(0);
dims[1] = dwi.dim(1);
dims[2] = dwi.dim(2);
}
}
// RUNTIME METHODS --------------------------------------------------------------
void MHSampler::execute()
{
do {
next();
} while (stats.next());
}
void MHSampler::next()
{
float p = rng.uniform();
float s = props.p_birth;
if (p < s)
return birth();
s += props.p_death;
if (p < s)
return death();
s += props.p_shift;
if (p < s)
return randshift();
s += props.p_optshift;
if (p < s)
return optshift();
s += props.p_connect;
if (p < s)
return connect();
}
// PROPOSAL DISTRIBUTIONS -------------------------------------------------------
void MHSampler::birth()
{
//TRACE;
stats.incN('b');
Point_t pos;
do {
pos = getRandPosInMask();
} while (! lock->lockIfNotLocked(pos));
Point_t dir = getRandDir();
double dE = E->stageAdd(pos, dir);
double R = std::exp(-dE) * props.density / (pGrid.getTotalCount()+1) * props.p_death / props.p_birth;
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.add(pos, dir);
stats.incNa('b');
}
else {
E->clearChanges();
}
lock->unlock(pos);
}
void MHSampler::death()
{
//TRACE;
stats.incN('d');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL || par->hasPredecessor() || par->hasSuccessor())
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
double dE = E->stageRemove(par);
double R = std::exp(-dE) * pGrid.getTotalCount() / props.density * props.p_birth / props.p_death;
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.remove(idx);
stats.incNa('d');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
void MHSampler::randshift()
{
//TRACE;
stats.incN('r');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL)
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
Point_t pos, dir;
moveRandom(par, pos, dir);
if (!inMask(T.scanner2voxel(pos))) {
lock->unlock(pos0);
return;
}
double dE = E->stageShift(par, pos, dir);
double R = exp(-dE);
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.shift(idx, pos, dir);
stats.incNa('r');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
void MHSampler::optshift()
{
//TRACE;
stats.incN('o');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL)
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
Point_t pos, dir;
bool moved = moveOptimal(par, pos, dir);
if (!moved || !inMask(T.scanner2voxel(pos))) {
lock->unlock(pos0);
return;
}
double dE = E->stageShift(par, pos, dir);
double p_prop = calcShiftProb(par, pos, dir);
double R = exp(-dE) * props.p_shift * p_prop / (props.p_shift * p_prop + props.p_optshift);
if (R > rng.uniform()) {
E->acceptChanges();
pGrid.shift(idx, pos, dir);
stats.incNa('o');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
void MHSampler::connect() // TODO Current implementation does not prevent loops.
{
//TRACE;
stats.incN('c');
unsigned int idx;
Particle* par;
do {
par = pGrid.getRandom(idx);
if (par == NULL)
return;
} while (! lock->lockIfNotLocked(par->getPosition()));
Point_t pos0 = par->getPosition();
int alpha0 = (rng.uniform() < 0.5) ? -1 : 1;
ParticleEnd pe0;
pe0.par = par;
pe0.alpha = alpha0;
ParticleEnd pe2;
pe2.par = NULL;
double dE = E->stageConnect(pe0, pe2);
double R = exp(-dE);
if (R > rng.uniform()) {
E->acceptChanges();
if (pe2.par) {
if (alpha0 == -1)
par->connectPredecessor(pe2.par, pe2.alpha);
else
par->connectSuccessor(pe2.par, pe2.alpha);
} else {
if ((alpha0 == -1) && par->hasPredecessor())
par->removePredecessor();
else if ((alpha0 == +1) && par->hasSuccessor())
par->removeSuccessor();
}
stats.incNa('c');
}
else {
E->clearChanges();
}
lock->unlock(pos0);
}
// SUPPORTING METHODS -----------------------------------------------------------
Point_t MHSampler::getRandPosInMask()
{
Point_t p;
do {
p[0] = rng.uniform() * (dims[0]-1);
p[1] = rng.uniform() * (dims[1]-1);
p[2] = rng.uniform() * (dims[2]-1);
} while (!inMask(p)); // FIXME Schrijf dit expliciet uit ifv random integer initialisatie,
return T.voxel2scanner(p); // voeg hier dan nog random ruis aan toe. Dan kan je inMask terug ifv
} // scanner positie schrijven.
bool MHSampler::inMask(const Point_t p) const
{
if ((p[0] <= -0.5) || (p[0] >= dims[0]-0.5) ||
(p[1] <= -0.5) || (p[1] >= dims[1]-0.5) ||
(p[2] <= -0.5) || (p[2] >= dims[2]-0.5))
// if ((p[0] <= 0.0) || (p[0] >= dims[0]-1.0) ||
// (p[1] <= 0.0) || (p[1] >= dims[1]-1.0) ||
// (p[2] <= 0.0) || (p[2] >= dims[2]-1.0))
return false;
if (mask) {
(*mask)[0] = Math::round<size_t>(p[0]);
(*mask)[1] = Math::round<size_t>(p[1]);
(*mask)[2] = Math::round<size_t>(p[2]);
return mask->value();
}
return true;
}
Point_t MHSampler::getRandDir()
{
Point_t dir = Point_t(rng.normal(), rng.normal(), rng.normal());
dir.normalise();
return dir;
}
void MHSampler::moveRandom(const Particle *par, Point_t &pos, Point_t &dir)
{
pos = par->getPosition() + Point_t(rng.normal(sigpos), rng.normal(sigpos), rng.normal(sigpos));
dir = par->getDirection() + Point_t(rng.normal(sigdir), rng.normal(sigdir), rng.normal(sigdir));
dir.normalise();
}
bool MHSampler::moveOptimal(const Particle *par, Point_t &pos, Point_t &dir) const
{
// assert(par != NULL)
if (par->hasPredecessor() && par->hasSuccessor())
{
int a1 = (par->getPredecessor()->getPredecessor() == par) ? -1 : 1;
int a3 = (par->getSuccessor()->getPredecessor() == par) ? -1 : 1;
pos = (par->getPredecessor()->getEndPoint(a1) + par->getSuccessor()->getEndPoint(a3)) / 2;
dir = par->getSuccessor()->getPosition() - par->getPredecessor()->getPosition();
dir.normalise();
return true;
}
else if (par->hasPredecessor())
{
int a = (par->getPredecessor()->getPredecessor() == par) ? -1 : 1;
pos = par->getPredecessor()->getEndPoint(2*a);
dir = par->getPredecessor()->getDirection() * a;
return true;
}
else if (par->hasSuccessor())
{
int a = (par->getSuccessor()->getPredecessor() == par) ? -1 : 1;
pos = par->getSuccessor()->getEndPoint(2*a);
dir = par->getSuccessor()->getDirection() * (-a);
return true;
}
else
{
return false;
}
}
double MHSampler::calcShiftProb(const Particle *par, const Point_t &pos, const Point_t &dir) const
{
Point_t Dpos = par->getPosition() - pos;
Point_t Ddir = par->getDirection() - dir;
return gsl_ran_gaussian_pdf(Dpos[0], sigpos) * gsl_ran_gaussian_pdf(Dpos[1], sigpos) * gsl_ran_gaussian_pdf(Dpos[2], sigpos) *
gsl_ran_gaussian_pdf(Ddir[0], sigdir) * gsl_ran_gaussian_pdf(Ddir[1], sigdir) * gsl_ran_gaussian_pdf(Ddir[2], sigdir);
// Point_t Dep1 = par->getEndPoint(-1) - (pos - Particle::L * dir);
// Point_t Dep2 = par->getEndPoint(1) - (pos + Particle::L * dir);
// double sigma = Particle::L/2;
// return gsl_ran_gaussian_pdf(Dep1[0], sigma) * gsl_ran_gaussian_pdf(Dep1[1], sigma) * gsl_ran_gaussian_pdf(Dep1[2], sigma) *
// gsl_ran_gaussian_pdf(Dep2[0], sigma) * gsl_ran_gaussian_pdf(Dep2[1], sigma) * gsl_ran_gaussian_pdf(Dep2[2], sigma);
}
}
}
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.