text stringlengths 54 60.6k |
|---|
<commit_before>/* json_parsing.cc
Jeremy Barnes, 1 February 2012
Copyright (c) 2012 Recoset. All rights reserved.
Released under the MIT license.
*/
#include "json_parsing.h"
#include "jml/arch/format.h"
using namespace std;
namespace ML {
/*****************************************************************************/
/* JSON UTILITIES */
/*****************************************************************************/
std::string
jsonEscape(const std::string & str)
{
std::string result;
result.reserve(str.size() * 2);
for (unsigned i = 0; i < str.size(); ++i) {
char c = str[i];
if (c >= ' ' && c < 127 && c != '\"' && c != '\\')
result.push_back(c);
else {
result.push_back('\\');
switch (c) {
case '\t': result.push_back('t'); break;
case '\n': result.push_back('n'); break;
case '\r': result.push_back('r'); break;
case '\b': result.push_back('b'); break;
case '\f': result.push_back('f'); break;
case '/':
case '\\':
case '\"': result.push_back(c); break;
default:
throw Exception("invalid character in Json string");
}
}
}
return result;
}
bool matchJsonString(Parse_Context & context, std::string & str)
{
Parse_Context::Revert_Token token(context);
context.skip_whitespace();
if (!context.match_literal('"')) return false;
std::string result;
while (!context.match_literal('"')) {
if (context.eof()) return false;
int c = *context++;
//if (c < 0 || c >= 127)
// context.exception("invalid JSON string character");
if (c != '\\') {
result.push_back(c);
continue;
}
c = *context++;
switch (c) {
case 't': result.push_back('\t'); break;
case 'n': result.push_back('\n'); break;
case 'r': result.push_back('\r'); break;
case 'f': result.push_back('\f'); break;
case '/': result.push_back('/'); break;
case '\\':result.push_back('\\'); break;
case '"': result.push_back('"'); break;
case 'u': {
int code = context.expect_int();
if (code<0 || code>255)
{
return false;
}
result.push_back(code);
break;
}
default:
return false;
}
}
token.ignore();
str = result;
return true;
}
std::string expectJsonString(Parse_Context & context)
{
context.skip_whitespace();
context.expect_literal('"');
char internalBuffer[4096];
char * buffer = internalBuffer;
size_t bufferSize = 4096;
size_t pos = 0;
// Try multiple times to make it fit
while (!context.match_literal('"')) {
int c = *context++;
//if (c < 0 || c >= 127)
// context.exception("invalid JSON string character");
if (c == '\\') {
c = *context++;
switch (c) {
case 't': c = '\t'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 'f': c = '\f'; break;
case '/': c = '/'; break;
case '\\':c = '\\'; break;
case '"': c = '"'; break;
case 'u': {
int code = context.expect_int();
if (code<0 || code>255) {
context.exception(format("non 8bit char %d", code));
}
c = code;
break;
}
default:
context.exception("invalid escaped char");
}
}
if (pos == bufferSize) {
size_t newBufferSize = bufferSize * 8;
char * newBuffer = new char[newBufferSize];
std::copy(buffer, buffer + bufferSize, newBuffer);
if (buffer != internalBuffer)
delete[] buffer;
buffer = newBuffer;
bufferSize = newBufferSize;
}
buffer[pos++] = c;
}
string result(buffer, buffer + pos);
if (buffer != internalBuffer)
delete[] buffer;
return result;
}
void
expectJsonArray(Parse_Context & context,
boost::function<void (int, Parse_Context &)> onEntry)
{
context.skip_whitespace();
if (context.match_literal("null"))
return;
context.expect_literal('[');
context.skip_whitespace();
if (context.match_literal(']')) return;
for (int i = 0; ; ++i) {
context.skip_whitespace();
onEntry(i, context);
context.skip_whitespace();
if (!context.match_literal(',')) break;
}
context.skip_whitespace();
context.expect_literal(']');
}
void
expectJsonObject(Parse_Context & context,
boost::function<void (std::string, Parse_Context &)> onEntry)
{
context.skip_whitespace();
if (context.match_literal("null"))
return;
context.expect_literal('{');
context.skip_whitespace();
if (context.match_literal('}')) return;
for (;;) {
context.skip_whitespace();
string key = expectJsonString(context);
context.skip_whitespace();
context.expect_literal(':');
context.skip_whitespace();
onEntry(key, context);
context.skip_whitespace();
if (!context.match_literal(',')) break;
}
context.skip_whitespace();
context.expect_literal('}');
}
bool
matchJsonObject(Parse_Context & context,
boost::function<bool (std::string, Parse_Context &)> onEntry)
{
context.skip_whitespace();
if (context.match_literal("null"))
return true;
if (!context.match_literal('{')) return false;
context.skip_whitespace();
if (context.match_literal('}')) return true;
for (;;) {
context.skip_whitespace();
string key = expectJsonString(context);
context.skip_whitespace();
if (!context.match_literal(':')) return false;
context.skip_whitespace();
if (!onEntry(key, context)) return false;
context.skip_whitespace();
if (!context.match_literal(',')) break;
}
context.skip_whitespace();
if (!context.match_literal('}')) return false;
return true;
}
} // namespace ML
<commit_msg>added and used skipJsonWhitespace() method that includes newlines as the Parse_Context one isn't suitable<commit_after>/* json_parsing.cc
Jeremy Barnes, 1 February 2012
Copyright (c) 2012 Recoset. All rights reserved.
Released under the MIT license.
*/
#include "json_parsing.h"
#include "jml/arch/format.h"
using namespace std;
namespace ML {
/*****************************************************************************/
/* JSON UTILITIES */
/*****************************************************************************/
void skipJsonWhitespace(Parse_Context & context)
{
while (context.match_whitespace() || context.match_eol());
}
std::string
jsonEscape(const std::string & str)
{
std::string result;
result.reserve(str.size() * 2);
for (unsigned i = 0; i < str.size(); ++i) {
char c = str[i];
if (c >= ' ' && c < 127 && c != '\"' && c != '\\')
result.push_back(c);
else {
result.push_back('\\');
switch (c) {
case '\t': result.push_back('t'); break;
case '\n': result.push_back('n'); break;
case '\r': result.push_back('r'); break;
case '\b': result.push_back('b'); break;
case '\f': result.push_back('f'); break;
case '/':
case '\\':
case '\"': result.push_back(c); break;
default:
throw Exception("invalid character in Json string");
}
}
}
return result;
}
bool matchJsonString(Parse_Context & context, std::string & str)
{
Parse_Context::Revert_Token token(context);
skipJsonWhitespace(context);
if (!context.match_literal('"')) return false;
std::string result;
while (!context.match_literal('"')) {
if (context.eof()) return false;
int c = *context++;
//if (c < 0 || c >= 127)
// context.exception("invalid JSON string character");
if (c != '\\') {
result.push_back(c);
continue;
}
c = *context++;
switch (c) {
case 't': result.push_back('\t'); break;
case 'n': result.push_back('\n'); break;
case 'r': result.push_back('\r'); break;
case 'f': result.push_back('\f'); break;
case '/': result.push_back('/'); break;
case '\\':result.push_back('\\'); break;
case '"': result.push_back('"'); break;
case 'u': {
int code = context.expect_int();
if (code<0 || code>255)
{
return false;
}
result.push_back(code);
break;
}
default:
return false;
}
}
token.ignore();
str = result;
return true;
}
std::string expectJsonString(Parse_Context & context)
{
skipJsonWhitespace(context);
context.expect_literal('"');
char internalBuffer[4096];
char * buffer = internalBuffer;
size_t bufferSize = 4096;
size_t pos = 0;
// Try multiple times to make it fit
while (!context.match_literal('"')) {
int c = *context++;
//if (c < 0 || c >= 127)
// context.exception("invalid JSON string character");
if (c == '\\') {
c = *context++;
switch (c) {
case 't': c = '\t'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 'f': c = '\f'; break;
case '/': c = '/'; break;
case '\\':c = '\\'; break;
case '"': c = '"'; break;
case 'u': {
int code = context.expect_int();
if (code<0 || code>255) {
context.exception(format("non 8bit char %d", code));
}
c = code;
break;
}
default:
context.exception("invalid escaped char");
}
}
if (pos == bufferSize) {
size_t newBufferSize = bufferSize * 8;
char * newBuffer = new char[newBufferSize];
std::copy(buffer, buffer + bufferSize, newBuffer);
if (buffer != internalBuffer)
delete[] buffer;
buffer = newBuffer;
bufferSize = newBufferSize;
}
buffer[pos++] = c;
}
string result(buffer, buffer + pos);
if (buffer != internalBuffer)
delete[] buffer;
return result;
}
void
expectJsonArray(Parse_Context & context,
boost::function<void (int, Parse_Context &)> onEntry)
{
skipJsonWhitespace(context);
if (context.match_literal("null"))
return;
context.expect_literal('[');
skipJsonWhitespace(context);
if (context.match_literal(']')) return;
for (int i = 0; ; ++i) {
skipJsonWhitespace(context);
onEntry(i, context);
skipJsonWhitespace(context);
if (!context.match_literal(',')) break;
}
skipJsonWhitespace(context);
context.expect_literal(']');
}
void
expectJsonObject(Parse_Context & context,
boost::function<void (std::string, Parse_Context &)> onEntry)
{
skipJsonWhitespace(context);
if (context.match_literal("null"))
return;
context.expect_literal('{');
skipJsonWhitespace(context);
if (context.match_literal('}')) return;
for (;;) {
skipJsonWhitespace(context);
string key = expectJsonString(context);
skipJsonWhitespace(context);
context.expect_literal(':');
skipJsonWhitespace(context);
onEntry(key, context);
skipJsonWhitespace(context);
if (!context.match_literal(',')) break;
}
skipJsonWhitespace(context);
context.expect_literal('}');
}
bool
matchJsonObject(Parse_Context & context,
boost::function<bool (std::string, Parse_Context &)> onEntry)
{
skipJsonWhitespace(context);
if (context.match_literal("null"))
return true;
if (!context.match_literal('{')) return false;
skipJsonWhitespace(context);
if (context.match_literal('}')) return true;
for (;;) {
skipJsonWhitespace(context);
string key = expectJsonString(context);
skipJsonWhitespace(context);
if (!context.match_literal(':')) return false;
skipJsonWhitespace(context);
if (!onEntry(key, context)) return false;
skipJsonWhitespace(context);
if (!context.match_literal(',')) break;
}
skipJsonWhitespace(context);
if (!context.match_literal('}')) return false;
return true;
}
} // namespace ML
<|endoftext|> |
<commit_before>/*
* lookup-atomese.cc
*
* Implement the word-lookup callbacks
*
* Copyright (c) 2022 Linas Vepstas <linasvepstas@gmail.com>
*/
#ifdef HAVE_ATOMESE
#include <cstdlib>
#include <opencog/atoms/value/StringValue.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/persist/api/StorageNode.h>
#include <opencog/persist/cog-storage/CogStorage.h>
#include <opencog/nlp/types/atom_types.h>
#undef STRINGIFY
extern "C" {
#include "../link-includes.h" // For Dictionary
#include "../dict-common/dict-common.h" // for Dictionary_s
#include "../dict-ram/dict-ram.h"
#include "lookup-atomese.h"
};
using namespace opencog;
class Local
{
public:
const char* url;
AtomSpacePtr asp;
StorageNodePtr stnp;
Handle linkp;
};
/// Open a connection to a CogServer located at url.
void as_open(Dictionary dict, const char* url)
{
Local* local = new Local;
local->url = string_set_add(url, dict->string_set);
local->asp = createAtomSpace();
// Create the connector predicate.
local->linkp = local->asp->add_node(PREDICATE_NODE,
"*-LG connector string-*");
/* The cast below forces the shared lib constructor to run. */
/* That's needed to force the factory to get installed. */
Handle hsn = local->asp->add_node(COG_STORAGE_NODE, url);
local->stnp = CogStorageNodeCast(hsn);
local->stnp->open();
// XXX FIXME -- if we cannot connect, then should hard-fail.
if (local->stnp->connected())
printf("Connected to %s\n", url);
else
printf("Failed to connect to %s\n", url);
dict->as_server = (void*) local;
}
/// Close the connection to the cogserver.
void as_close(Dictionary dict)
{
if (nullptr == dict->as_server) return;
Local* local = (Local*) (dict->as_server);
local->stnp->close();
delete local;
dict->as_server = nullptr;
}
/// Return true if the given word can be found in the dictionary,
/// else return false.
bool as_boolean_lookup(Dictionary dict, const char *s)
{
bool found = dict_node_exists_lookup(dict, s);
if (found) return true;
if (0 == strcmp(s, LEFT_WALL_WORD))
s = "###LEFT-WALL###";
Local* local = (Local*) (dict->as_server);
Handle wrd = local->asp->get_node(WORD_NODE, s);
if (nullptr == wrd)
wrd = local->asp->add_node(WORD_NODE, s);
// Are there any Sections in the local atomspace?
size_t nsects = wrd->getIncomingSetSizeByType(SECTION);
if (0 == nsects)
{
local->stnp->fetch_incoming_by_type(wrd, SECTION);
local->stnp->barrier();
}
nsects = wrd->getIncomingSetSizeByType(SECTION);
printf("duuude as_boolean_lookup for >>%s<< found sects=%lu\n", s, nsects);
return 0 != nsects;
}
/// int to base-26 capital letters.
static std::string idtostr(uint64_t aid)
{
std::string s;
do
{
char c = (aid % 26) + 'A';
s.push_back(c);
}
while (0 < (aid /= 26));
return s;
}
// Return a cached LG-compatible link string.
// Assisgn a new name, if one does not exist.
static std::string get_linkname(Local* local, const Handle& lnk)
{
// If we've already cached a connector string for this,
// just return it. Else build and cache a string.
StringValuePtr vname = StringValueCast(lnk->getValue(local->linkp));
if (vname)
return vname->value()[0];
static uint64_t lid = 0;
std::string slnk = idtostr(lid++);
vname = createStringValue(slnk);
lnk->setValue(local->linkp, ValueCast(vname));
return slnk;
}
// Cheap hack until c++20 ranges are generally available.
template<typename T>
class reverse {
private:
T& iterable_;
public:
explicit reverse(T& iterable) : iterable_{iterable} {}
auto begin() const { return std::rbegin(iterable_); }
auto end() const { return std::rend(iterable_); }
};
Dict_node * as_lookup_list(Dictionary dict, const char *s)
{
// Do we already have this word cached? If so, pull from
// the cache.
Dict_node * dn = dict_node_lookup(dict, s);
if (dn) return dn;
const char* ssc = string_set_add(s, dict->string_set);
Local* local = (Local*) (dict->as_server);
if (0 == strcmp(s, LEFT_WALL_WORD))
s = "###LEFT-WALL###";
Handle wrd = local->asp->get_node(WORD_NODE, s);
if (nullptr == wrd) return nullptr;
// Loop over all Sections on the word.
HandleSeq sects = wrd->getIncomingSetByType(SECTION);
for (const Handle& sect: sects)
{
Exp* exp = nullptr;
// The germ is the first Atom.
const Handle& germ = sect->getOutgoingAtom(0);
// The connector sequence the second Atom.
// Loop over the connectors in the connector sequence.
const Handle& conseq = sect->getOutgoingAtom(1);
for (const Handle& ctcr : reverse(conseq->getOutgoingSet()))
{
// The connection target is the first Atom in the connector
const Handle& tgt = ctcr->getOutgoingAtom(0);
const Handle& dir = ctcr->getOutgoingAtom(1);
// The link is the connection of both of these.
const Handle& lnk = local->asp->add_link(SET_LINK, germ, tgt);
// Assign an upper-case name to the link.
std::string slnk = get_linkname(local, lnk);
const std::string& sdir = dir->get_name();
Exp* e = make_connector_node(dict, dict->Exp_pool,
slnk.c_str(), sdir.c_str()[0], false);
if (nullptr == exp)
{
exp = e;
continue;
}
exp = make_and_node(dict->Exp_pool, e, exp);
}
// printf("Word %s expression %s\n", ssc, lg_exp_stringify(exp));
Dict_node *sdn = (Dict_node*) malloc(sizeof(Dict_node));
memset(sdn, 0, sizeof(Dict_node));
sdn->string = ssc;
sdn->exp = exp;
sdn->right = dn;
sdn->left = NULL;
dn = sdn;
}
// Cache the result; avoid repeated lookups.
dict->root = dict_node_insert(dict, dict->root, dn);
dict->num_entries++;
printf("duuude as_lookup_list %d for >>%s<< had=%lu\n",
dict->num_entries, ssc, sects.size());
// Rebalance the tree every now and then.
if (0 == dict->num_entries% 30)
{
printf("duuude rebalance\n");
dict->root = dsw_tree_to_vine(dict->root);
dict->root = dsw_vine_to_tree(dict->root, dict->num_entries);
}
// Perform the lookup. We cannot return the dn above, as the
// as_free_llist() below will delete it, leading to mem corruption.
dn = dict_node_lookup(dict, ssc);
return dn;
}
Dict_node * as_lookup_wild(Dictionary dict, const char *s)
{
printf("duuude called as_lookup_wild for %s\n", s);
return NULL;
}
// Zap all the Dict_nodes that we've added earlier.
// This clears out everything hanging on dict->root
// as well as the expression pool.
// And also the local AtomSpace.
//
void as_clear_cache(Dictionary dict)
{
Local* local = (Local*) (dict->as_server);
printf("Prior to clear, dict has %d entries, Atomspace has %lu Atoms\n",
dict->num_entries, local->asp->size());
free_dictionary_root(dict);
dict->num_entries = 0;
dict->Exp_pool = pool_new(__func__, "Exp", /*num_elements*/4096,
sizeof(Exp), /*zero_out*/false,
/*align*/false, /*exact*/false);
// Clear the local AtomSpace too.
// Easiest way to do this is to just close and reopen
// the connection.
const char* url = local->url;
as_close(dict);
as_open(dict, url);
as_boolean_lookup(dict, LEFT_WALL_WORD);
}
#endif /* HAVE_ATOMESE */
<commit_msg>Minor simplifications<commit_after>/*
* lookup-atomese.cc
*
* Implement the word-lookup callbacks
*
* Copyright (c) 2022 Linas Vepstas <linasvepstas@gmail.com>
*/
#ifdef HAVE_ATOMESE
#include <cstdlib>
#include <opencog/atoms/value/StringValue.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/persist/api/StorageNode.h>
#include <opencog/persist/cog-storage/CogStorage.h>
#include <opencog/nlp/types/atom_types.h>
#undef STRINGIFY
extern "C" {
#include "../link-includes.h" // For Dictionary
#include "../dict-common/dict-common.h" // for Dictionary_s
#include "../dict-ram/dict-ram.h"
#include "lookup-atomese.h"
};
using namespace opencog;
class Local
{
public:
const char* url;
AtomSpacePtr asp;
StorageNodePtr stnp;
Handle linkp;
};
/// Open a connection to a CogServer located at url.
void as_open(Dictionary dict, const char* url)
{
Local* local = new Local;
local->url = string_set_add(url, dict->string_set);
local->asp = createAtomSpace();
// Create the connector predicate.
local->linkp = local->asp->add_node(PREDICATE_NODE,
"*-LG connector string-*");
/* The cast below forces the shared lib constructor to run. */
/* That's needed to force the factory to get installed. */
Handle hsn = local->asp->add_node(COG_STORAGE_NODE, url);
local->stnp = CogStorageNodeCast(hsn);
local->stnp->open();
// XXX FIXME -- if we cannot connect, then should hard-fail.
if (local->stnp->connected())
printf("Connected to %s\n", url);
else
printf("Failed to connect to %s\n", url);
dict->as_server = (void*) local;
}
/// Close the connection to the cogserver.
void as_close(Dictionary dict)
{
if (nullptr == dict->as_server) return;
Local* local = (Local*) (dict->as_server);
local->stnp->close();
delete local;
dict->as_server = nullptr;
}
/// Return true if the given word can be found in the dictionary,
/// else return false.
bool as_boolean_lookup(Dictionary dict, const char *s)
{
bool found = dict_node_exists_lookup(dict, s);
if (found) return true;
if (0 == strcmp(s, LEFT_WALL_WORD))
s = "###LEFT-WALL###";
Local* local = (Local*) (dict->as_server);
Handle wrd = local->asp->add_node(WORD_NODE, s);
// Are there any Sections in the local atomspace?
size_t nsects = wrd->getIncomingSetSizeByType(SECTION);
if (0 == nsects)
{
local->stnp->fetch_incoming_by_type(wrd, SECTION);
local->stnp->barrier();
}
nsects = wrd->getIncomingSetSizeByType(SECTION);
printf("duuude as_boolean_lookup for >>%s<< found sects=%lu\n", s, nsects);
return 0 != nsects;
}
/// int to base-26 capital letters.
static std::string idtostr(uint64_t aid)
{
std::string s;
do
{
char c = (aid % 26) + 'A';
s.push_back(c);
}
while (0 < (aid /= 26));
return s;
}
// Return a cached LG-compatible link string.
// Assisgn a new name, if one does not exist.
static std::string get_linkname(Local* local, const Handle& lnk)
{
// If we've already cached a connector string for this,
// just return it. Else build and cache a string.
StringValuePtr vname = StringValueCast(lnk->getValue(local->linkp));
if (vname)
return vname->value()[0];
static uint64_t lid = 0;
std::string slnk = idtostr(lid++);
vname = createStringValue(slnk);
lnk->setValue(local->linkp, ValueCast(vname));
return slnk;
}
// Cheap hack until c++20 ranges are generally available.
template<typename T>
class reverse {
private:
T& iterable_;
public:
explicit reverse(T& iterable) : iterable_{iterable} {}
auto begin() const { return std::rbegin(iterable_); }
auto end() const { return std::rend(iterable_); }
};
Dict_node * as_lookup_list(Dictionary dict, const char *s)
{
// Do we already have this word cached? If so, pull from
// the cache.
Dict_node * dn = dict_node_lookup(dict, s);
if (dn) return dn;
const char* ssc = string_set_add(s, dict->string_set);
Local* local = (Local*) (dict->as_server);
if (0 == strcmp(s, LEFT_WALL_WORD))
s = "###LEFT-WALL###";
Handle wrd = local->asp->get_node(WORD_NODE, s);
if (nullptr == wrd) return nullptr;
// Loop over all Sections on the word.
HandleSeq sects = wrd->getIncomingSetByType(SECTION);
for (const Handle& sect: sects)
{
Exp* exp = nullptr;
// The connector sequence the second Atom.
// Loop over the connectors in the connector sequence.
const Handle& conseq = sect->getOutgoingAtom(1);
for (const Handle& ctcr : reverse(conseq->getOutgoingSet()))
{
// The connection target is the first Atom in the connector
const Handle& tgt = ctcr->getOutgoingAtom(0);
const Handle& dir = ctcr->getOutgoingAtom(1);
// The link is the connection of both of these.
const Handle& lnk = local->asp->add_link(SET_LINK, wrd, tgt);
// Assign an upper-case name to the link.
std::string slnk = get_linkname(local, lnk);
const std::string& sdir = dir->get_name();
Exp* e = make_connector_node(dict, dict->Exp_pool,
slnk.c_str(), sdir.c_str()[0], false);
if (nullptr == exp)
{
exp = e;
continue;
}
exp = make_and_node(dict->Exp_pool, e, exp);
}
// printf("Word %s expression %s\n", ssc, lg_exp_stringify(exp));
Dict_node *sdn = (Dict_node*) malloc(sizeof(Dict_node));
memset(sdn, 0, sizeof(Dict_node));
sdn->string = ssc;
sdn->exp = exp;
sdn->right = dn;
sdn->left = NULL;
dn = sdn;
}
// Cache the result; avoid repeated lookups.
dict->root = dict_node_insert(dict, dict->root, dn);
dict->num_entries++;
printf("duuude as_lookup_list %d for >>%s<< had=%lu\n",
dict->num_entries, ssc, sects.size());
// Rebalance the tree every now and then.
if (0 == dict->num_entries% 30)
{
printf("duuude rebalance\n");
dict->root = dsw_tree_to_vine(dict->root);
dict->root = dsw_vine_to_tree(dict->root, dict->num_entries);
}
// Perform the lookup. We cannot return the dn above, as the
// as_free_llist() below will delete it, leading to mem corruption.
dn = dict_node_lookup(dict, ssc);
return dn;
}
Dict_node * as_lookup_wild(Dictionary dict, const char *s)
{
printf("duuude called as_lookup_wild for %s\n", s);
return NULL;
}
// Zap all the Dict_nodes that we've added earlier.
// This clears out everything hanging on dict->root
// as well as the expression pool.
// And also the local AtomSpace.
//
void as_clear_cache(Dictionary dict)
{
Local* local = (Local*) (dict->as_server);
printf("Prior to clear, dict has %d entries, Atomspace has %lu Atoms\n",
dict->num_entries, local->asp->get_size());
free_dictionary_root(dict);
dict->num_entries = 0;
dict->Exp_pool = pool_new(__func__, "Exp", /*num_elements*/4096,
sizeof(Exp), /*zero_out*/false,
/*align*/false, /*exact*/false);
// Clear the local AtomSpace too.
// Easiest way to do this is to just close and reopen
// the connection.
const char* url = local->url;
as_close(dict);
as_open(dict, url);
as_boolean_lookup(dict, LEFT_WALL_WORD);
}
#endif /* HAVE_ATOMESE */
<|endoftext|> |
<commit_before>/* memofile.cc KPilot
**
** Copyright (C) 2004-2004 by Jason 'vanRijn' Kasper
**
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "memofile.h"
Memofile::Memofile(PilotMemo * memo, QString categoryName, QString fileName, QString baseDirectory) :
PilotMemo(memo->text()), _categoryName(categoryName), _filename(fileName), _baseDirectory(baseDirectory)
{
_lastModified = 0;
_size = 0;
setAttrib(memo->getAttrib());
setCat(memo->getCat());
setID(memo->getID());
_modified = _modifiedByPalm = false;
}
Memofile::Memofile(recordid_t id, int category, uint lastModifiedTime, uint size,
QString categoryName, QString fileName, QString baseDirectory) :
PilotMemo(), _categoryName(categoryName),
_filename(fileName),_baseDirectory(baseDirectory)
{
setID(id);
setCat(category);
_lastModified = lastModifiedTime;
_size = size;
_modified = _modifiedByPalm = false;
}
Memofile::Memofile(int category, QString categoryName, QString fileName, QString baseDirectory) :
PilotMemo(),
_categoryName(categoryName), _filename(fileName), _baseDirectory(baseDirectory)
{
setID(0);
_new = true;
setCat(category);
_modified = true;
_modifiedByPalm = false;
_lastModified = 0;
_size = 0;
}
bool Memofile::load()
{
FUNCTIONSETUP;
if (filename().isEmpty()) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": I was asked to load, but have no filename to load. "
<< endl;
#endif
return false;
}
QFile f( filenameAbs() );
if ( !f.open( IO_ReadOnly ) ) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Couldn't open file: [" << filenameAbs() << "] to read. "
<< endl;
#endif
return false;
}
QTextStream ts( &f );
QString text,title,body;
title = filename();
body = ts.read();
// funky magic. we want the text of the memofile to have the filename
// as the first line....
if (body.startsWith(title)) {
text = body;
} else {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": text of your memofile: [" << filename()
<< "] didn't include the filename as the first line. fixing it..." << endl;
#endif
text = title + CSL1("\n") + body;
}
setText(text);
f.close();
return true;
}
void Memofile::setID(recordid_t id)
{
if (id != getID())
_modifiedByPalm = true;
PilotMemo::setID(id);
}
bool Memofile::save()
{
bool result = true;
if ((isModified() && isLoaded()) || _modifiedByPalm) {
result = saveFile();
}
return result;
}
bool Memofile::deleteFile()
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": deleting file: [" << filenameAbs() << "]." << endl;
#endif
return QFile::remove(filenameAbs());
}
bool Memofile::saveFile()
{
FUNCTIONSETUP;
if (filename().isEmpty()) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": I was asked to save, but have no filename to save to. "
<< endl;
#endif
return false;
}
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": saving memo to file: ["
<< filenameAbs() << "]" << endl;
#endif
QFile f( filenameAbs() );
if ( !f.open( IO_WriteOnly ) ) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Couldn't open file: [" << filenameAbs() << "] to write your memo to. "
<< "This won't end well." << endl;
#endif
return false;
}
QTextStream stream(&f);
stream << text() << endl;
f.close();
_lastModified = getFileLastModified();
_size = getFileSize();
return true;
}
bool Memofile::isModified(void)
{
FUNCTIONSETUP;
// first, check to see if this file is deleted....
if (!fileExists()) {
#ifdef DEBUG
DEBUGCONDUIT << "isModified: our file doesn't exist. returning true." << endl;
#endif
return true;
}
bool modByTimestamp = false;
bool modBySize = false;
if (_lastModified > 0)
modByTimestamp = isModifiedByTimestamp();
if (_size > 0)
modBySize = isModifiedBySize();
bool ret = _modified || modByTimestamp || modBySize;
#ifdef DEBUG
if (ret) {
DEBUGCONDUIT <<"isModified: " << toString() << " _modified: ["
<< _modified << "], modByTimestamp: ["
<< modByTimestamp << "] modBySize: [" << ret
<< modBySize << "] returning: [" << ret
<< "]." << endl;
}
#endif
return ret;
}
bool Memofile::isModifiedByTimestamp()
{
FUNCTIONSETUP;
if (_lastModified <=0) {
#ifdef DEBUG
DEBUGCONDUIT <<"isModifiedByTimestamp: lastModified is <=0, returning true" << endl;
#endif
return true;
}
uint lastModifiedTime = getFileLastModified();
if ( lastModifiedTime != _lastModified) {
#ifdef DEBUG
DEBUGCONDUIT <<"isModifiedByTimestamp: file : [" << filename()
<< "] was modified: [" << lastModifiedTime
<< "], which is not my: [" << _lastModified
<< "]." << endl;
#endif
return true;
}
return false;
}
bool Memofile::isModifiedBySize()
{
FUNCTIONSETUP;
if (_size <=0) {
#ifdef DEBUG
DEBUGCONDUIT <<"isModifiedBySize: size is <=0, returning true" << endl;
#endif
return true;
}
uint size = getFileSize();
if ( size != _size) {
#ifdef DEBUG
DEBUGCONDUIT <<"isModifiedBySize: file : [" << filename()
<< "] was modified: [" << size
<< "], which is not my: [" << _size
<< "]." << endl;
#endif
return true;
}
return false;
}
uint Memofile::getFileLastModified()
{
QFileInfo f = QFileInfo(filenameAbs());
uint lastModifiedTime = f.lastModified().toTime_t();
return lastModifiedTime;
}
uint Memofile::getFileSize()
{
QFileInfo f = QFileInfo(filenameAbs());
uint size = f.size();
return size;
}
// bool Memofile::operator==( const PilotMemo &p ) const
// {
// FUNCTIONSETUP;
//
// bool equals = false;
//
// if (getID() > 0)
// {
// equals = p.getID()==getID();
// }
//
// return equals;
// }
<commit_msg>not spamming kpilot debug log with useless information<commit_after>/* memofile.cc KPilot
**
** Copyright (C) 2004-2004 by Jason 'vanRijn' Kasper
**
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "memofile.h"
Memofile::Memofile(PilotMemo * memo, QString categoryName, QString fileName, QString baseDirectory) :
PilotMemo(memo->text()), _categoryName(categoryName), _filename(fileName), _baseDirectory(baseDirectory)
{
_lastModified = 0;
_size = 0;
setAttrib(memo->getAttrib());
setCat(memo->getCat());
setID(memo->getID());
_modified = _modifiedByPalm = false;
}
Memofile::Memofile(recordid_t id, int category, uint lastModifiedTime, uint size,
QString categoryName, QString fileName, QString baseDirectory) :
PilotMemo(), _categoryName(categoryName),
_filename(fileName),_baseDirectory(baseDirectory)
{
setID(id);
setCat(category);
_lastModified = lastModifiedTime;
_size = size;
_modified = _modifiedByPalm = false;
}
Memofile::Memofile(int category, QString categoryName, QString fileName, QString baseDirectory) :
PilotMemo(),
_categoryName(categoryName), _filename(fileName), _baseDirectory(baseDirectory)
{
setID(0);
_new = true;
setCat(category);
_modified = true;
_modifiedByPalm = false;
_lastModified = 0;
_size = 0;
}
bool Memofile::load()
{
FUNCTIONSETUP;
if (filename().isEmpty()) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": I was asked to load, but have no filename to load. "
<< endl;
#endif
return false;
}
QFile f( filenameAbs() );
if ( !f.open( IO_ReadOnly ) ) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Couldn't open file: [" << filenameAbs() << "] to read. "
<< endl;
#endif
return false;
}
QTextStream ts( &f );
QString text,title,body;
title = filename();
body = ts.read();
// funky magic. we want the text of the memofile to have the filename
// as the first line....
if (body.startsWith(title)) {
text = body;
} else {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": text of your memofile: [" << filename()
<< "] didn't include the filename as the first line. fixing it..." << endl;
#endif
text = title + CSL1("\n") + body;
}
setText(text);
f.close();
return true;
}
void Memofile::setID(recordid_t id)
{
if (id != getID())
_modifiedByPalm = true;
PilotMemo::setID(id);
}
bool Memofile::save()
{
bool result = true;
if ((isModified() && isLoaded()) || _modifiedByPalm) {
result = saveFile();
}
return result;
}
bool Memofile::deleteFile()
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": deleting file: [" << filenameAbs() << "]." << endl;
#endif
return QFile::remove(filenameAbs());
}
bool Memofile::saveFile()
{
FUNCTIONSETUP;
if (filename().isEmpty()) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": I was asked to save, but have no filename to save to. "
<< endl;
#endif
return false;
}
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": saving memo to file: ["
<< filenameAbs() << "]" << endl;
#endif
QFile f( filenameAbs() );
if ( !f.open( IO_WriteOnly ) ) {
#ifdef DEBUG
DEBUGCONDUIT << fname
<< ": Couldn't open file: [" << filenameAbs() << "] to write your memo to. "
<< "This won't end well." << endl;
#endif
return false;
}
QTextStream stream(&f);
stream << text() << endl;
f.close();
_lastModified = getFileLastModified();
_size = getFileSize();
return true;
}
bool Memofile::isModified(void)
{
// first, check to see if this file is deleted....
if (!fileExists()) {
return true;
}
bool modByTimestamp = false;
bool modBySize = false;
if (_lastModified > 0)
modByTimestamp = isModifiedByTimestamp();
if (_size > 0)
modBySize = isModifiedBySize();
bool ret = _modified || modByTimestamp || modBySize;
return ret;
}
bool Memofile::isModifiedByTimestamp()
{
if (_lastModified <=0) {
return true;
}
uint lastModifiedTime = getFileLastModified();
if ( lastModifiedTime != _lastModified) {
return true;
}
return false;
}
bool Memofile::isModifiedBySize()
{
if (_size <=0) {
return true;
}
uint size = getFileSize();
if ( size != _size) {
return true;
}
return false;
}
uint Memofile::getFileLastModified()
{
QFileInfo f = QFileInfo(filenameAbs());
uint lastModifiedTime = f.lastModified().toTime_t();
return lastModifiedTime;
}
uint Memofile::getFileSize()
{
QFileInfo f = QFileInfo(filenameAbs());
uint size = f.size();
return size;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdem.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: rt $ $Date: 2006-12-05 11:38:47 $
*
* 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_vcl.hxx"
#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <event.hxx>
#include <svapp.hxx>
#include <wrkwin.hxx>
#include <msgbox.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------
// Forward declaration
void Main();
// -----------------------------------------------------------------------
SAL_IMPLEMENT_MAIN()
{
Reference< XMultiServiceFactory > xMS;
xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );
InitVCL( xMS );
::Main();
DeInitVCL();
return 0;
}
// -----------------------------------------------------------------------
class MyWin : public WorkWindow
{
public:
MyWin( Window* pParent, WinBits nWinStyle );
void MouseMove( const MouseEvent& rMEvt );
void MouseButtonDown( const MouseEvent& rMEvt );
void MouseButtonUp( const MouseEvent& rMEvt );
void KeyInput( const KeyEvent& rKEvt );
void KeyUp( const KeyEvent& rKEvt );
void Paint( const Rectangle& rRect );
void Resize();
};
// -----------------------------------------------------------------------
void Main()
{
MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCL - Workbench" ) ) );
aMainWin.Show();
Application::Execute();
}
// -----------------------------------------------------------------------
MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
WorkWindow( pParent, nWinStyle )
{
}
// -----------------------------------------------------------------------
void MyWin::MouseMove( const MouseEvent& rMEvt )
{
WorkWindow::MouseMove( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonDown( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonUp( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyUp( const KeyEvent& rKEvt )
{
WorkWindow::KeyUp( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::Paint( const Rectangle& rRect )
{
WorkWindow::Paint( rRect );
}
// -----------------------------------------------------------------------
void MyWin::Resize()
{
WorkWindow::Resize();
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.17.150); FILE MERGED 2007/06/04 13:30:04 vg 1.17.150.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdem.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:58:52 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------
// Forward declaration
void Main();
// -----------------------------------------------------------------------
SAL_IMPLEMENT_MAIN()
{
Reference< XMultiServiceFactory > xMS;
xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );
InitVCL( xMS );
::Main();
DeInitVCL();
return 0;
}
// -----------------------------------------------------------------------
class MyWin : public WorkWindow
{
public:
MyWin( Window* pParent, WinBits nWinStyle );
void MouseMove( const MouseEvent& rMEvt );
void MouseButtonDown( const MouseEvent& rMEvt );
void MouseButtonUp( const MouseEvent& rMEvt );
void KeyInput( const KeyEvent& rKEvt );
void KeyUp( const KeyEvent& rKEvt );
void Paint( const Rectangle& rRect );
void Resize();
};
// -----------------------------------------------------------------------
void Main()
{
MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCL - Workbench" ) ) );
aMainWin.Show();
Application::Execute();
}
// -----------------------------------------------------------------------
MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
WorkWindow( pParent, nWinStyle )
{
}
// -----------------------------------------------------------------------
void MyWin::MouseMove( const MouseEvent& rMEvt )
{
WorkWindow::MouseMove( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonDown( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonUp( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyUp( const KeyEvent& rKEvt )
{
WorkWindow::KeyUp( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::Paint( const Rectangle& rRect )
{
WorkWindow::Paint( rRect );
}
// -----------------------------------------------------------------------
void MyWin::Resize()
{
WorkWindow::Resize();
}
<|endoftext|> |
<commit_before>//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
namespace llvm {
Target &getTheAVRTarget() {
static Target TheAVRTarget;
return TheAVRTarget;
}
}
extern "C" void LLVMInitializeAVRTargetInfo() {
llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr",
"Atmel AVR Microcontroller");
}
<commit_msg>Add backend name to AVR Target to enable runtime info to be fed back into TableGen<commit_after>//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
namespace llvm {
Target &getTheAVRTarget() {
static Target TheAVRTarget;
return TheAVRTarget;
}
}
extern "C" void LLVMInitializeAVRTargetInfo() {
llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr",
"Atmel AVR Microcontroller", "AVR");
}
<|endoftext|> |
<commit_before>//===-- PPCHazardRecognizers.cpp - PowerPC Hazard Recognizer Impls --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements hazard recognizers for scheduling on PowerPC processors.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sched"
#include "PPCHazardRecognizers.h"
#include "PPC.h"
#include "llvm/Support/Debug.h"
#include <iostream>
using namespace llvm;
//===----------------------------------------------------------------------===//
// PowerPC 970 Hazard Recognizer
//
// FIXME: This is missing some significant cases:
// 0. Handling of instructions that must be the first/last in a group.
// 1. Modeling of microcoded instructions.
// 2. Handling of cracked instructions.
// 3. Handling of serialized operations.
// 4. Handling of the esoteric cases in "Resource-based Instruction Grouping",
// e.g. integer divides that only execute in the second slot.
//
// Note: on the PPC970, logical CR operations are more expensive in their three
// address form: ops that read/write the same register are half as expensive as
//
void PPCHazardRecognizer970::EndDispatchGroup() {
DEBUG(std::cerr << "=== Start of dispatch group\n");
// Pipeline units.
NumFXU = NumLSU = NumFPU = 0;
HasCR = HasVALU = HasVPERM = false;
NumIssued = 0;
// Structural hazard info.
HasCTRSet = false;
StorePtr1 = StorePtr2 = SDOperand();
StoreSize = 0;
}
PPCHazardRecognizer970::PPC970InstrType
PPCHazardRecognizer970::GetInstrType(unsigned Opcode) {
if (Opcode < ISD::BUILTIN_OP_END)
return PseudoInst;
Opcode -= ISD::BUILTIN_OP_END;
switch (Opcode) {
case PPC::FMRSD: return PseudoInst; // Usually coallesced away.
case PPC::BCTRL:
case PPC::BL:
case PPC::BLA:
return BR;
case PPC::LFS:
case PPC::LWZ:
return LSU_LD;
case PPC::STFD:
return LSU_ST;
case PPC::FADDS:
case PPC::FCTIWZ:
return FPU;
}
return FXU;
}
/// StartBasicBlock - Initiate a new dispatch group.
void PPCHazardRecognizer970::StartBasicBlock() {
EndDispatchGroup();
}
/// isLoadOfStoredAddress - If we have a load from the previously stored pointer
/// as indicated by StorePtr1/StorePtr2/StoreSize, return true.
bool PPCHazardRecognizer970::
isLoadOfStoredAddress(unsigned LoadSize, SDOperand Ptr1, SDOperand Ptr2) const {
// Handle exact and commuted addresses.
if (Ptr1 == StorePtr1 && Ptr2 == StorePtr2)
return true;
if (Ptr2 == StorePtr1 && Ptr1 == StorePtr2)
return true;
// Okay, we don't have an exact match, if this is an indexed offset, see if we
// have overlap (which happens during fp->int conversion for example).
if (StorePtr2 == Ptr2) {
if (ConstantSDNode *StoreOffset = dyn_cast<ConstantSDNode>(StorePtr1))
if (ConstantSDNode *LoadOffset = dyn_cast<ConstantSDNode>(Ptr1)) {
// Okay the base pointers match, so we have [c1+r] vs [c2+r]. Check to
// see if the load and store actually overlap.
int StoreOffs = StoreOffset->getValue();
int LoadOffs = LoadOffset->getValue();
if (StoreOffs < LoadOffs) {
if (int(StoreOffs+StoreSize) > LoadOffs) return true;
} else {
if (int(LoadOffs+LoadSize) > StoreOffs) return true;
}
}
}
return false;
}
/// getHazardType - We return hazard for any non-branch instruction that would
/// terminate terminate the dispatch group. We turn NoopHazard for any
/// instructions that wouldn't terminate the dispatch group that would cause a
/// pipeline flush.
HazardRecognizer::HazardType PPCHazardRecognizer970::
getHazardType(SDNode *Node) {
PPC970InstrType InstrType = GetInstrType(Node->getOpcode());
if (InstrType == PseudoInst) return NoHazard;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
switch (InstrType) {
default: assert(0 && "Unknown instruction type!");
case FXU: if (NumFXU == 2) return Hazard;
case LSU_ST:
case LSU_LD: if (NumLSU == 2) return Hazard;
case FPU: if (NumFPU == 2) return Hazard;
case CR: if (HasCR) return Hazard;
case VALU: if (HasVALU) return Hazard;
case VPERM: if (HasVPERM) return Hazard;
case BR: break;
}
// We can only issue a branch as the last instruction in a group.
if (NumIssued == 4 && InstrType != BR)
return Hazard;
// Do not allow MTCTR and BCTRL to be in the same dispatch group.
if (HasCTRSet && Opcode == PPC::BCTRL)
return NoopHazard;
// If this is a load following a store, make sure it's not to the same or
// overlapping address.
if (InstrType == LSU_LD && StoreSize) {
unsigned LoadSize;
switch (Opcode) {
default: assert(0 && "Unknown load!");
case PPC::LFS:
case PPC::LWZ: LoadSize = 4; break;
}
if (isLoadOfStoredAddress(LoadSize,
Node->getOperand(0), Node->getOperand(1)))
return NoopHazard;
}
return NoHazard;
}
void PPCHazardRecognizer970::EmitInstruction(SDNode *Node) {
PPC970InstrType InstrType = GetInstrType(Node->getOpcode());
if (InstrType == PseudoInst) return;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
// Update structural hazard information.
if (Opcode == PPC::MTCTR) HasCTRSet = true;
// Track the address stored to.
if (InstrType == LSU_ST) {
StorePtr1 = Node->getOperand(1);
StorePtr2 = Node->getOperand(2);
switch (Opcode) {
default: assert(0 && "Unknown store instruction!");
case PPC::STFD: StoreSize = 8; break;
}
}
switch (InstrType) {
default: assert(0 && "Unknown instruction type!");
case FXU: ++NumFXU; break;
case LSU_LD:
case LSU_ST: ++NumLSU; break;
case FPU: ++NumFPU; break;
case CR: HasCR = true; break;
case VALU: HasVALU = true; break;
case VPERM: HasVPERM = true; break;
case BR: NumIssued = 4; return; // ends a d-group.
}
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::AdvanceCycle() {
assert(NumIssued < 5 && "Illegal dispatch group!");
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::EmitNoop() {
AdvanceCycle();
}
<commit_msg>add some comments that describe what we model<commit_after>//===-- PPCHazardRecognizers.cpp - PowerPC Hazard Recognizer Impls --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements hazard recognizers for scheduling on PowerPC processors.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sched"
#include "PPCHazardRecognizers.h"
#include "PPC.h"
#include "llvm/Support/Debug.h"
#include <iostream>
using namespace llvm;
//===----------------------------------------------------------------------===//
// PowerPC 970 Hazard Recognizer
//
// This models the dispatch group formation of the PPC970 processor. Dispatch
// groups are bundles of up to five instructions that can contain up to two ALU
// (aka FXU) ops, two FPU ops, two Load/Store ops, one CR op, one VALU op, one
// VPERM op, and one BRANCH op. If the code contains more instructions in a
// sequence than the dispatch group can contain (e.g. three loads in a row) the
// processor terminates the dispatch group early, wasting execution resources.
//
// In addition to these restrictions, there are a number of other restrictions:
// some instructions, e.g. branches, are required to be the last instruction in
// a group. Additionally, only branches can issue in the 5th (last) slot.
//
// Finally, there are a number of "structural" hazards on the PPC970. These
// conditions cause large performance penalties due to misprediction, recovery,
// and replay logic that has to happen. These cases include setting a CTR and
// branching through it in the same dispatch group, and storing to an address,
// then loading from the same address within a dispatch group. To avoid these
// conditions, we insert no-op instructions when appropriate.
//
// FIXME: This is missing some significant cases:
// 0. Handling of instructions that must be the first/last in a group.
// 1. Modeling of microcoded instructions.
// 2. Handling of cracked instructions.
// 3. Handling of serialized operations.
// 4. Handling of the esoteric cases in "Resource-based Instruction Grouping",
// e.g. integer divides that only execute in the second slot.
//
void PPCHazardRecognizer970::EndDispatchGroup() {
DEBUG(std::cerr << "=== Start of dispatch group\n");
// Pipeline units.
NumFXU = NumLSU = NumFPU = 0;
HasCR = HasVALU = HasVPERM = false;
NumIssued = 0;
// Structural hazard info.
HasCTRSet = false;
StorePtr1 = StorePtr2 = SDOperand();
StoreSize = 0;
}
PPCHazardRecognizer970::PPC970InstrType
PPCHazardRecognizer970::GetInstrType(unsigned Opcode) {
if (Opcode < ISD::BUILTIN_OP_END)
return PseudoInst;
Opcode -= ISD::BUILTIN_OP_END;
switch (Opcode) {
case PPC::FMRSD: return PseudoInst; // Usually coallesced away.
case PPC::BCTRL:
case PPC::BL:
case PPC::BLA:
return BR;
case PPC::LFS:
case PPC::LWZ:
return LSU_LD;
case PPC::STFD:
return LSU_ST;
case PPC::FADDS:
case PPC::FCTIWZ:
return FPU;
}
return FXU;
}
/// StartBasicBlock - Initiate a new dispatch group.
void PPCHazardRecognizer970::StartBasicBlock() {
EndDispatchGroup();
}
/// isLoadOfStoredAddress - If we have a load from the previously stored pointer
/// as indicated by StorePtr1/StorePtr2/StoreSize, return true.
bool PPCHazardRecognizer970::
isLoadOfStoredAddress(unsigned LoadSize, SDOperand Ptr1, SDOperand Ptr2) const {
// Handle exact and commuted addresses.
if (Ptr1 == StorePtr1 && Ptr2 == StorePtr2)
return true;
if (Ptr2 == StorePtr1 && Ptr1 == StorePtr2)
return true;
// Okay, we don't have an exact match, if this is an indexed offset, see if we
// have overlap (which happens during fp->int conversion for example).
if (StorePtr2 == Ptr2) {
if (ConstantSDNode *StoreOffset = dyn_cast<ConstantSDNode>(StorePtr1))
if (ConstantSDNode *LoadOffset = dyn_cast<ConstantSDNode>(Ptr1)) {
// Okay the base pointers match, so we have [c1+r] vs [c2+r]. Check to
// see if the load and store actually overlap.
int StoreOffs = StoreOffset->getValue();
int LoadOffs = LoadOffset->getValue();
if (StoreOffs < LoadOffs) {
if (int(StoreOffs+StoreSize) > LoadOffs) return true;
} else {
if (int(LoadOffs+LoadSize) > StoreOffs) return true;
}
}
}
return false;
}
/// getHazardType - We return hazard for any non-branch instruction that would
/// terminate terminate the dispatch group. We turn NoopHazard for any
/// instructions that wouldn't terminate the dispatch group that would cause a
/// pipeline flush.
HazardRecognizer::HazardType PPCHazardRecognizer970::
getHazardType(SDNode *Node) {
PPC970InstrType InstrType = GetInstrType(Node->getOpcode());
if (InstrType == PseudoInst) return NoHazard;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
switch (InstrType) {
default: assert(0 && "Unknown instruction type!");
case FXU: if (NumFXU == 2) return Hazard;
case LSU_ST:
case LSU_LD: if (NumLSU == 2) return Hazard;
case FPU: if (NumFPU == 2) return Hazard;
case CR: if (HasCR) return Hazard;
case VALU: if (HasVALU) return Hazard;
case VPERM: if (HasVPERM) return Hazard;
case BR: break;
}
// We can only issue a branch as the last instruction in a group.
if (NumIssued == 4 && InstrType != BR)
return Hazard;
// Do not allow MTCTR and BCTRL to be in the same dispatch group.
if (HasCTRSet && Opcode == PPC::BCTRL)
return NoopHazard;
// If this is a load following a store, make sure it's not to the same or
// overlapping address.
if (InstrType == LSU_LD && StoreSize) {
unsigned LoadSize;
switch (Opcode) {
default: assert(0 && "Unknown load!");
case PPC::LFS:
case PPC::LWZ: LoadSize = 4; break;
}
if (isLoadOfStoredAddress(LoadSize,
Node->getOperand(0), Node->getOperand(1)))
return NoopHazard;
}
return NoHazard;
}
void PPCHazardRecognizer970::EmitInstruction(SDNode *Node) {
PPC970InstrType InstrType = GetInstrType(Node->getOpcode());
if (InstrType == PseudoInst) return;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
// Update structural hazard information.
if (Opcode == PPC::MTCTR) HasCTRSet = true;
// Track the address stored to.
if (InstrType == LSU_ST) {
StorePtr1 = Node->getOperand(1);
StorePtr2 = Node->getOperand(2);
switch (Opcode) {
default: assert(0 && "Unknown store instruction!");
case PPC::STFD: StoreSize = 8; break;
}
}
switch (InstrType) {
default: assert(0 && "Unknown instruction type!");
case FXU: ++NumFXU; break;
case LSU_LD:
case LSU_ST: ++NumLSU; break;
case FPU: ++NumFPU; break;
case CR: HasCR = true; break;
case VALU: HasVALU = true; break;
case VPERM: HasVPERM = true; break;
case BR: NumIssued = 4; return; // ends a d-group.
}
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::AdvanceCycle() {
assert(NumIssued < 5 && "Illegal dispatch group!");
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::EmitNoop() {
AdvanceCycle();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SchXMLTools.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2008-03-06 16:00:19 $
*
* 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 SCH_XML_TOOLS_HXX_
#define SCH_XML_TOOLS_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef SCH_XML_TRANSPORTTYPES_HXX_
#include "transporttypes.hxx"
#endif
namespace com { namespace sun { namespace star {
namespace chart2 {
class XChartDocument;
class XRegressionCurve;
namespace data {
class XDataProvider;
class XLabeledDataSequence;
}
}
}}}
class XMLPropStyleContext;
class SvXMLStylesContext;
class SvXMLExport;
namespace SchXMLTools
{
enum SchXMLChartTypeEnum
{
XML_CHART_CLASS_LINE,
XML_CHART_CLASS_AREA,
XML_CHART_CLASS_CIRCLE,
XML_CHART_CLASS_RING,
XML_CHART_CLASS_SCATTER,
XML_CHART_CLASS_RADAR,
XML_CHART_CLASS_BAR,
XML_CHART_CLASS_STOCK,
XML_CHART_CLASS_BUBBLE, // not yet implemented
XML_CHART_CLASS_ADDIN,
XML_CHART_CLASS_UNKNOWN
};
SchXMLChartTypeEnum GetChartTypeEnum( const ::rtl::OUString& rClassName );
::rtl::OUString GetChartTypeByClassName(
const ::rtl::OUString & rClassName, bool bUseOldNames );
::xmloff::token::XMLTokenEnum getTokenByChartType(
const ::rtl::OUString & rChartTypeService, bool bUseOldNames );
::rtl::OUString GetNewChartTypeName( const ::rtl::OUString & rOldChartTypeName );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence > GetNewLabeledDataSequence();
void CreateCategories(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataProvider > & xDataProvider,
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > & xNewDoc,
const ::rtl::OUString & rRangeAddress,
sal_Int32 nCooSysIndex,
sal_Int32 nDimensionIndex,
tSchXMLLSequencesPerIndex * pLSequencesPerIndex = 0 );
::com::sun::star::uno::Any getPropertyFromContext( const ::rtl::OUString& rPropertyName, const XMLPropStyleContext * pPropStyleContext, const SvXMLStylesContext* pStylesCtxt );
void exportText( SvXMLExport& rExport, const ::rtl::OUString& rText, bool bConvertTabsLFs );
/** returns the properties of the equation of the first regression curve
that is no mean-value line
*/
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XRegressionCurve > getRegressionCurve(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries );
/** checks if the data sequence has the property "CachedXMLRange" (true for
internal data sequences), and if so sets this property to the range
given in rXMLRange
*/
void setXMLRangePropertyAtDataSequence(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSequence > & xDataSequence,
const ::rtl::OUString & rXMLRange );
/** checks if the data sequence has the property "CachedXMLRange" (true for
internal data sequences), and if so retrieves this property and applies
it to the range given in rOutXMLRange.
@param bClearProp If true, the property is reset to its default after it
was assigned to rOutXMLRange
@return true, if the property was found, assigned and is non-empty
*/
bool getXMLRangePropertyFromDataSequence(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSequence > & xDataSequence,
::rtl::OUString & rOutXMLRange,
bool bClearProp = false );
}
#endif // SCH_XML_TOOLS_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.7.20); FILE MERGED 2008/04/01 16:09:32 thb 1.7.20.3: #i85898# Stripping all external header guards 2008/04/01 13:04:33 thb 1.7.20.2: #i85898# Stripping all external header guards 2008/03/31 16:28:01 rt 1.7.20.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: SchXMLTools.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SCH_XML_TOOLS_HXX_
#define SCH_XML_TOOLS_HXX_
#include <rtl/ustring.hxx>
#include <xmloff/xmltoken.hxx>
#include "transporttypes.hxx"
namespace com { namespace sun { namespace star {
namespace chart2 {
class XChartDocument;
class XRegressionCurve;
namespace data {
class XDataProvider;
class XLabeledDataSequence;
}
}
}}}
class XMLPropStyleContext;
class SvXMLStylesContext;
class SvXMLExport;
namespace SchXMLTools
{
enum SchXMLChartTypeEnum
{
XML_CHART_CLASS_LINE,
XML_CHART_CLASS_AREA,
XML_CHART_CLASS_CIRCLE,
XML_CHART_CLASS_RING,
XML_CHART_CLASS_SCATTER,
XML_CHART_CLASS_RADAR,
XML_CHART_CLASS_BAR,
XML_CHART_CLASS_STOCK,
XML_CHART_CLASS_BUBBLE, // not yet implemented
XML_CHART_CLASS_ADDIN,
XML_CHART_CLASS_UNKNOWN
};
SchXMLChartTypeEnum GetChartTypeEnum( const ::rtl::OUString& rClassName );
::rtl::OUString GetChartTypeByClassName(
const ::rtl::OUString & rClassName, bool bUseOldNames );
::xmloff::token::XMLTokenEnum getTokenByChartType(
const ::rtl::OUString & rChartTypeService, bool bUseOldNames );
::rtl::OUString GetNewChartTypeName( const ::rtl::OUString & rOldChartTypeName );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence > GetNewLabeledDataSequence();
void CreateCategories(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataProvider > & xDataProvider,
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > & xNewDoc,
const ::rtl::OUString & rRangeAddress,
sal_Int32 nCooSysIndex,
sal_Int32 nDimensionIndex,
tSchXMLLSequencesPerIndex * pLSequencesPerIndex = 0 );
::com::sun::star::uno::Any getPropertyFromContext( const ::rtl::OUString& rPropertyName, const XMLPropStyleContext * pPropStyleContext, const SvXMLStylesContext* pStylesCtxt );
void exportText( SvXMLExport& rExport, const ::rtl::OUString& rText, bool bConvertTabsLFs );
/** returns the properties of the equation of the first regression curve
that is no mean-value line
*/
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XRegressionCurve > getRegressionCurve(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries );
/** checks if the data sequence has the property "CachedXMLRange" (true for
internal data sequences), and if so sets this property to the range
given in rXMLRange
*/
void setXMLRangePropertyAtDataSequence(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSequence > & xDataSequence,
const ::rtl::OUString & rXMLRange );
/** checks if the data sequence has the property "CachedXMLRange" (true for
internal data sequences), and if so retrieves this property and applies
it to the range given in rOutXMLRange.
@param bClearProp If true, the property is reset to its default after it
was assigned to rOutXMLRange
@return true, if the property was found, assigned and is non-empty
*/
bool getXMLRangePropertyFromDataSequence(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSequence > & xDataSequence,
::rtl::OUString & rOutXMLRange,
bool bClearProp = false );
}
#endif // SCH_XML_TOOLS_HXX_
<|endoftext|> |
<commit_before>//===-- SparcV9TargetMachine.cpp - SparcV9 Target Machine Implementation --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Primary interface to machine description for the UltraSPARC. Primarily just
// initializes machine-dependent parameters in class TargetMachine, and creates
// machine-dependent subclasses for classes such as TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/IntrinsicLowering.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Transforms/Scalar.h"
#include "MappingInfo.h"
#include "SparcV9Internals.h"
#include "SparcV9TargetMachine.h"
#include "Support/CommandLine.h"
using namespace llvm;
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcV9Instr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
namespace {
cl::opt<bool> DisableSched("disable-sched",
cl::desc("Disable local scheduling pass"));
cl::opt<bool> DisablePeephole("disable-peephole",
cl::desc("Disable peephole optimization pass"));
cl::opt<bool> EmitMappingInfo("enable-maps",
cl::desc("Emit LLVM-to-MachineCode mapping info to assembly"));
cl::opt<bool> DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode in executable"));
}
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "DestroyMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
MachineFunction::destruct(&F);
return false;
}
};
FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
}
FunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
SparcV9TargetMachine::SparcV9TargetMachine(IntrinsicLowering *il)
: TargetMachine("UltraSparcV9-Native", il, false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
jitInfo(*this) {
}
/// addPassesToEmitAssembly - This method controls the entire code generation
/// process for the ultra sparc.
///
bool
SparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(*this));
PM.add(createLowerSelectPass());
// Run basic LLVM dataflow optimizations, to clean up after pre-selection.
PM.add(createReassociatePass());
PM.add(createLICMPass());
PM.add(createGCSEPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
// Insert empty stackslots in the stack frame of each function
// so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
if (EmitMappingInfo)
PM.add(getMappingInfoAsmPrinterPass(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
PM.add(createAsmPrinterPass(Out, *this));
// Free machine-code IR which is no longer needed:
PM.add(createSparcV9MachineCodeDestructionPass());
// Emit bytecode to the assembly file into its special section next
if (EmitMappingInfo) {
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
PM.add(createSymbolStrippingPass());
PM.add(createBytecodeAsmPrinterPass(Out));
}
return false;
}
/// addPassesToJITCompile - This method controls the JIT method of code
/// generation for the UltraSparcV9.
///
void SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(TM));
PM.add(createLowerSelectPass());
// Run basic LLVM dataflow optimizations, to clean up after pre-selection.
PM.add(createReassociatePass());
// FIXME: these passes crash the FunctionPassManager when being added...
//PM.add(createLICMPass());
//PM.add(createGCSEPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(TM));
PM.add(createInstructionSelectionPass(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(TM));
}
/// allocateSparcV9TargetMachine - Allocate and return a subclass of TargetMachine
/// that implements the SparcV9 backend. (the llvm/CodeGen/SparcV9.h interface)
///
TargetMachine *llvm::allocateSparcV9TargetMachine(const Module &M,
IntrinsicLowering *IL) {
return new SparcV9TargetMachine(IL);
}
<commit_msg>Make debugging output with -print-machineinstrs more useful: always print out the transformed LLVM code which is the input to the instruction selector.<commit_after>//===-- SparcV9TargetMachine.cpp - SparcV9 Target Machine Implementation --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Primary interface to machine description for the UltraSPARC. Primarily just
// initializes machine-dependent parameters in class TargetMachine, and creates
// machine-dependent subclasses for classes such as TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/IntrinsicLowering.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Transforms/Scalar.h"
#include "MappingInfo.h"
#include "SparcV9Internals.h"
#include "SparcV9TargetMachine.h"
#include "Support/CommandLine.h"
using namespace llvm;
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcV9Instr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
namespace {
cl::opt<bool> DisableSched("disable-sched",
cl::desc("Disable local scheduling pass"));
cl::opt<bool> DisablePeephole("disable-peephole",
cl::desc("Disable peephole optimization pass"));
cl::opt<bool> EmitMappingInfo("enable-maps",
cl::desc("Emit LLVM-to-MachineCode mapping info to assembly"));
cl::opt<bool> DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode in executable"));
}
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "DestroyMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
MachineFunction::destruct(&F);
return false;
}
};
FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
}
FunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
SparcV9TargetMachine::SparcV9TargetMachine(IntrinsicLowering *il)
: TargetMachine("UltraSparcV9-Native", il, false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
jitInfo(*this) {
}
/// addPassesToEmitAssembly - This method controls the entire code generation
/// process for the ultra sparc.
///
bool
SparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(*this));
PM.add(createLowerSelectPass());
// Run basic LLVM dataflow optimizations, to clean up after pre-selection.
PM.add(createReassociatePass());
PM.add(createLICMPass());
PM.add(createGCSEPass());
// If the user's trying to read the generated code, they'll need to see the
// transformed input.
if (PrintMachineCode)
PM.add(new PrintModulePass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
// Insert empty stackslots in the stack frame of each function
// so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
if (EmitMappingInfo)
PM.add(getMappingInfoAsmPrinterPass(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
PM.add(createAsmPrinterPass(Out, *this));
// Free machine-code IR which is no longer needed:
PM.add(createSparcV9MachineCodeDestructionPass());
// Emit bytecode to the assembly file into its special section next
if (EmitMappingInfo) {
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
PM.add(createSymbolStrippingPass());
PM.add(createBytecodeAsmPrinterPass(Out));
}
return false;
}
/// addPassesToJITCompile - This method controls the JIT method of code
/// generation for the UltraSparcV9.
///
void SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(TM));
PM.add(createLowerSelectPass());
// Run basic LLVM dataflow optimizations, to clean up after pre-selection.
PM.add(createReassociatePass());
// FIXME: these passes crash the FunctionPassManager when being added...
//PM.add(createLICMPass());
//PM.add(createGCSEPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(TM));
PM.add(createInstructionSelectionPass(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(TM));
}
/// allocateSparcV9TargetMachine - Allocate and return a subclass of TargetMachine
/// that implements the SparcV9 backend. (the llvm/CodeGen/SparcV9.h interface)
///
TargetMachine *llvm::allocateSparcV9TargetMachine(const Module &M,
IntrinsicLowering *IL) {
return new SparcV9TargetMachine(IL);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#include "base/memory/scoped_ptr.h"
#include "base/shared_memory.h"
#include "base/test/multiprocess_test.h"
#include "base/threading/platform_thread.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#if defined(OS_POSIX)
#include <sys/mman.h>
#endif
static const int kNumThreads = 5;
static const int kNumTasks = 5;
namespace base {
namespace {
// Each thread will open the shared memory. Each thread will take a different 4
// byte int pointer, and keep changing it, with some small pauses in between.
// Verify that each thread's value in the shared memory is always correct.
class MultipleThreadMain : public PlatformThread::Delegate {
public:
explicit MultipleThreadMain(int16 id) : id_(id) {}
~MultipleThreadMain() {}
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
// PlatformThread::Delegate interface.
void ThreadMain() {
#if defined(OS_MACOSX)
mac::ScopedNSAutoreleasePool pool;
#endif
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memory.memory()) + id_;
EXPECT_EQ(0, *ptr);
for (int idx = 0; idx < 100; idx++) {
*ptr = idx;
PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(1));
EXPECT_EQ(*ptr, idx);
}
// Reset back to 0 for the next test that uses the same name.
*ptr = 0;
memory.Close();
}
private:
int16 id_;
static const char* const s_test_name_;
DISALLOW_COPY_AND_ASSIGN(MultipleThreadMain);
};
const char* const MultipleThreadMain::s_test_name_ =
"SharedMemoryOpenThreadTest";
// TODO(port):
// This test requires the ability to pass file descriptors between processes.
// We haven't done that yet in Chrome for POSIX.
#if defined(OS_WIN)
// Each thread will open the shared memory. Each thread will take the memory,
// and keep changing it while trying to lock it, with some small pauses in
// between. Verify that each thread's value in the shared memory is always
// correct.
class MultipleLockThread : public PlatformThread::Delegate {
public:
explicit MultipleLockThread(int id) : id_(id) {}
~MultipleLockThread() {}
// PlatformThread::Delegate interface.
void ThreadMain() {
const uint32 kDataSize = sizeof(int);
SharedMemoryHandle handle = NULL;
{
SharedMemory memory1;
EXPECT_TRUE(memory1.CreateNamed("SharedMemoryMultipleLockThreadTest",
true, kDataSize));
EXPECT_TRUE(memory1.ShareToProcess(GetCurrentProcess(), &handle));
// TODO(paulg): Implement this once we have a posix version of
// SharedMemory::ShareToProcess.
EXPECT_TRUE(true);
}
SharedMemory memory2(handle, false);
EXPECT_TRUE(memory2.Map(kDataSize));
volatile int* const ptr = static_cast<int*>(memory2.memory());
for (int idx = 0; idx < 20; idx++) {
memory2.Lock();
int i = (id_ << 16) + idx;
*ptr = i;
PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
EXPECT_EQ(*ptr, i);
memory2.Unlock();
}
memory2.Close();
}
private:
int id_;
DISALLOW_COPY_AND_ASSIGN(MultipleLockThread);
};
#endif
} // namespace
TEST(SharedMemoryTest, OpenClose) {
const uint32 kDataSize = 1024;
std::string test_name = "SharedMemoryOpenCloseTest";
// Open two handles to a memory segment, confirm that they are mapped
// separately yet point to the same space.
SharedMemory memory1;
bool rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Open(test_name, false);
EXPECT_FALSE(rv);
rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
SharedMemory memory2;
rv = memory2.Open(test_name, false);
EXPECT_TRUE(rv);
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
EXPECT_NE(memory1.memory(), memory2.memory()); // Compare the pointers.
// Make sure we don't segfault. (it actually happened!)
ASSERT_NE(memory1.memory(), static_cast<void*>(NULL));
ASSERT_NE(memory2.memory(), static_cast<void*>(NULL));
// Write data to the first memory segment, verify contents of second.
memset(memory1.memory(), '1', kDataSize);
EXPECT_EQ(memcmp(memory1.memory(), memory2.memory(), kDataSize), 0);
// Close the first memory segment, and verify the second has the right data.
memory1.Close();
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++)
EXPECT_EQ(*ptr, '1');
// Close the second memory segment.
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory2.Delete(test_name);
EXPECT_TRUE(rv);
}
TEST(SharedMemoryTest, OpenExclusive) {
const uint32 kDataSize = 1024;
const uint32 kDataSize2 = 2048;
std::ostringstream test_name_stream;
test_name_stream << "SharedMemoryOpenExclusiveTest."
<< Time::Now().ToDoubleT();
std::string test_name = test_name_stream.str();
// Open two handles to a memory segment and check that open_existing works
// as expected.
SharedMemory memory1;
bool rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
// Memory1 knows it's size because it created it.
EXPECT_EQ(memory1.created_size(), kDataSize);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
memset(memory1.memory(), 'G', kDataSize);
SharedMemory memory2;
// Should not be able to create if openExisting is false.
rv = memory2.CreateNamed(test_name, false, kDataSize2);
EXPECT_FALSE(rv);
// Should be able to create with openExisting true.
rv = memory2.CreateNamed(test_name, true, kDataSize2);
EXPECT_TRUE(rv);
// Memory2 shouldn't know the size because we didn't create it.
EXPECT_EQ(memory2.created_size(), 0U);
// We should be able to map the original size.
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
// Verify that opening memory2 didn't truncate or delete memory 1.
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++) {
EXPECT_EQ(*ptr, 'G');
}
memory1.Close();
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
}
// Create a set of N threads to each open a shared memory segment and write to
// it. Verify that they are always reading/writing consistent data.
TEST(SharedMemoryTest, MultipleThreads) {
MultipleThreadMain::CleanUp();
// On POSIX we have a problem when 2 threads try to create the shmem
// (a file) at exactly the same time, since create both creates the
// file and zerofills it. We solve the problem for this unit test
// (make it not flaky) by starting with 1 thread, then
// intentionally don't clean up its shmem before running with
// kNumThreads.
int threadcounts[] = { 1, kNumThreads };
for (size_t i = 0; i < arraysize(threadcounts); i++) {
int numthreads = threadcounts[i];
scoped_array<PlatformThreadHandle> thread_handles;
scoped_array<MultipleThreadMain*> thread_delegates;
thread_handles.reset(new PlatformThreadHandle[numthreads]);
thread_delegates.reset(new MultipleThreadMain*[numthreads]);
// Spawn the threads.
for (int16 index = 0; index < numthreads; index++) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleThreadMain(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < numthreads; index++) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
MultipleThreadMain::CleanUp();
}
// TODO(port): this test requires the MultipleLockThread class
// (defined above), which requires the ability to pass file
// descriptors between processes. We haven't done that yet in Chrome
// for POSIX.
#if defined(OS_WIN)
// Create a set of threads to each open a shared memory segment and write to it
// with the lock held. Verify that they are always reading/writing consistent
// data.
TEST(SharedMemoryTest, Lock) {
PlatformThreadHandle thread_handles[kNumThreads];
MultipleLockThread* thread_delegates[kNumThreads];
// Spawn the threads.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleLockThread(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
#endif
// Allocate private (unique) shared memory with an empty string for a
// name. Make sure several of them don't point to the same thing as
// we might expect if the names are equal.
TEST(SharedMemoryTest, AnonymousPrivate) {
int i, j;
int count = 4;
bool rv;
const uint32 kDataSize = 8192;
scoped_array<SharedMemory> memories(new SharedMemory[count]);
scoped_array<int*> pointers(new int*[count]);
ASSERT_TRUE(memories.get());
ASSERT_TRUE(pointers.get());
for (i = 0; i < count; i++) {
rv = memories[i].CreateAndMapAnonymous(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memories[i].memory());
EXPECT_TRUE(ptr);
pointers[i] = ptr;
}
for (i = 0; i < count; i++) {
// zero out the first int in each except for i; for that one, make it 100.
for (j = 0; j < count; j++) {
if (i == j)
pointers[j][0] = 100;
else
pointers[j][0] = 0;
}
// make sure there is no bleeding of the 100 into the other pointers
for (j = 0; j < count; j++) {
if (i == j)
EXPECT_EQ(100, pointers[j][0]);
else
EXPECT_EQ(0, pointers[j][0]);
}
}
for (int i = 0; i < count; i++) {
memories[i].Close();
}
}
#if defined(OS_POSIX)
// Create a shared memory object, mmap it, and mprotect it to PROT_EXEC.
TEST(SharedMemoryTest, AnonymousExecutable) {
const uint32 kTestSize = 1 << 16;
SharedMemory shared_memory;
SharedMemoryCreateOptions options;
options.size = kTestSize;
options.executable = true;
EXPECT_TRUE(shared_memory.Create(options));
EXPECT_TRUE(shared_memory.Map(shared_memory.created_size()));
EXPECT_EQ(0, mprotect(shared_memory.memory(), shared_memory.created_size(),
PROT_READ | PROT_EXEC));
}
#endif
// On POSIX it is especially important we test shmem across processes,
// not just across threads. But the test is enabled on all platforms.
class SharedMemoryProcessTest : public MultiProcessTest {
public:
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
static int TaskTestMain() {
int errors = 0;
#if defined(OS_MACOSX)
mac::ScopedNSAutoreleasePool pool;
#endif
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
int *ptr = static_cast<int*>(memory.memory());
for (int idx = 0; idx < 20; idx++) {
memory.Lock();
int i = (1 << 16) + idx;
*ptr = i;
PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
if (*ptr != i)
errors++;
memory.Unlock();
}
memory.Close();
return errors;
}
private:
static const char* const s_test_name_;
};
const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem";
// http://crbug.com/61589
#if defined(OS_MACOSX)
#define MAYBE_Tasks DISABLED_Tasks
#else
#define MAYBE_Tasks Tasks
#endif
TEST_F(SharedMemoryProcessTest, MAYBE_Tasks) {
SharedMemoryProcessTest::CleanUp();
ProcessHandle handles[kNumTasks];
for (int index = 0; index < kNumTasks; ++index) {
handles[index] = SpawnChild("SharedMemoryTestMain", false);
ASSERT_TRUE(handles[index]);
}
int exit_code = 0;
for (int index = 0; index < kNumTasks; ++index) {
EXPECT_TRUE(WaitForExitCode(handles[index], &exit_code));
EXPECT_TRUE(exit_code == 0);
}
SharedMemoryProcessTest::CleanUp();
}
MULTIPROCESS_TEST_MAIN(SharedMemoryTestMain) {
return SharedMemoryProcessTest::TaskTestMain();
}
} // namespace base
<commit_msg>Resubmit r127219: Make test failure clearer<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#include "base/memory/scoped_ptr.h"
#include "base/shared_memory.h"
#include "base/test/multiprocess_test.h"
#include "base/threading/platform_thread.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#if defined(OS_POSIX)
#include <sys/mman.h>
#endif
static const int kNumThreads = 5;
static const int kNumTasks = 5;
namespace base {
namespace {
// Each thread will open the shared memory. Each thread will take a different 4
// byte int pointer, and keep changing it, with some small pauses in between.
// Verify that each thread's value in the shared memory is always correct.
class MultipleThreadMain : public PlatformThread::Delegate {
public:
explicit MultipleThreadMain(int16 id) : id_(id) {}
~MultipleThreadMain() {}
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
// PlatformThread::Delegate interface.
void ThreadMain() {
#if defined(OS_MACOSX)
mac::ScopedNSAutoreleasePool pool;
#endif
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memory.memory()) + id_;
EXPECT_EQ(0, *ptr);
for (int idx = 0; idx < 100; idx++) {
*ptr = idx;
PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(1));
EXPECT_EQ(*ptr, idx);
}
// Reset back to 0 for the next test that uses the same name.
*ptr = 0;
memory.Close();
}
private:
int16 id_;
static const char* const s_test_name_;
DISALLOW_COPY_AND_ASSIGN(MultipleThreadMain);
};
const char* const MultipleThreadMain::s_test_name_ =
"SharedMemoryOpenThreadTest";
// TODO(port):
// This test requires the ability to pass file descriptors between processes.
// We haven't done that yet in Chrome for POSIX.
#if defined(OS_WIN)
// Each thread will open the shared memory. Each thread will take the memory,
// and keep changing it while trying to lock it, with some small pauses in
// between. Verify that each thread's value in the shared memory is always
// correct.
class MultipleLockThread : public PlatformThread::Delegate {
public:
explicit MultipleLockThread(int id) : id_(id) {}
~MultipleLockThread() {}
// PlatformThread::Delegate interface.
void ThreadMain() {
const uint32 kDataSize = sizeof(int);
SharedMemoryHandle handle = NULL;
{
SharedMemory memory1;
EXPECT_TRUE(memory1.CreateNamed("SharedMemoryMultipleLockThreadTest",
true, kDataSize));
EXPECT_TRUE(memory1.ShareToProcess(GetCurrentProcess(), &handle));
// TODO(paulg): Implement this once we have a posix version of
// SharedMemory::ShareToProcess.
EXPECT_TRUE(true);
}
SharedMemory memory2(handle, false);
EXPECT_TRUE(memory2.Map(kDataSize));
volatile int* const ptr = static_cast<int*>(memory2.memory());
for (int idx = 0; idx < 20; idx++) {
memory2.Lock();
int i = (id_ << 16) + idx;
*ptr = i;
PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
EXPECT_EQ(*ptr, i);
memory2.Unlock();
}
memory2.Close();
}
private:
int id_;
DISALLOW_COPY_AND_ASSIGN(MultipleLockThread);
};
#endif
} // namespace
TEST(SharedMemoryTest, OpenClose) {
const uint32 kDataSize = 1024;
std::string test_name = "SharedMemoryOpenCloseTest";
// Open two handles to a memory segment, confirm that they are mapped
// separately yet point to the same space.
SharedMemory memory1;
bool rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Open(test_name, false);
EXPECT_FALSE(rv);
rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
SharedMemory memory2;
rv = memory2.Open(test_name, false);
EXPECT_TRUE(rv);
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
EXPECT_NE(memory1.memory(), memory2.memory()); // Compare the pointers.
// Make sure we don't segfault. (it actually happened!)
ASSERT_NE(memory1.memory(), static_cast<void*>(NULL));
ASSERT_NE(memory2.memory(), static_cast<void*>(NULL));
// Write data to the first memory segment, verify contents of second.
memset(memory1.memory(), '1', kDataSize);
EXPECT_EQ(memcmp(memory1.memory(), memory2.memory(), kDataSize), 0);
// Close the first memory segment, and verify the second has the right data.
memory1.Close();
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++)
EXPECT_EQ(*ptr, '1');
// Close the second memory segment.
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory2.Delete(test_name);
EXPECT_TRUE(rv);
}
TEST(SharedMemoryTest, OpenExclusive) {
const uint32 kDataSize = 1024;
const uint32 kDataSize2 = 2048;
std::ostringstream test_name_stream;
test_name_stream << "SharedMemoryOpenExclusiveTest."
<< Time::Now().ToDoubleT();
std::string test_name = test_name_stream.str();
// Open two handles to a memory segment and check that open_existing works
// as expected.
SharedMemory memory1;
bool rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
// Memory1 knows it's size because it created it.
EXPECT_EQ(memory1.created_size(), kDataSize);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
memset(memory1.memory(), 'G', kDataSize);
SharedMemory memory2;
// Should not be able to create if openExisting is false.
rv = memory2.CreateNamed(test_name, false, kDataSize2);
EXPECT_FALSE(rv);
// Should be able to create with openExisting true.
rv = memory2.CreateNamed(test_name, true, kDataSize2);
EXPECT_TRUE(rv);
// Memory2 shouldn't know the size because we didn't create it.
EXPECT_EQ(memory2.created_size(), 0U);
// We should be able to map the original size.
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
// Verify that opening memory2 didn't truncate or delete memory 1.
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++) {
EXPECT_EQ(*ptr, 'G');
}
memory1.Close();
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
}
// Create a set of N threads to each open a shared memory segment and write to
// it. Verify that they are always reading/writing consistent data.
TEST(SharedMemoryTest, MultipleThreads) {
MultipleThreadMain::CleanUp();
// On POSIX we have a problem when 2 threads try to create the shmem
// (a file) at exactly the same time, since create both creates the
// file and zerofills it. We solve the problem for this unit test
// (make it not flaky) by starting with 1 thread, then
// intentionally don't clean up its shmem before running with
// kNumThreads.
int threadcounts[] = { 1, kNumThreads };
for (size_t i = 0; i < arraysize(threadcounts); i++) {
int numthreads = threadcounts[i];
scoped_array<PlatformThreadHandle> thread_handles;
scoped_array<MultipleThreadMain*> thread_delegates;
thread_handles.reset(new PlatformThreadHandle[numthreads]);
thread_delegates.reset(new MultipleThreadMain*[numthreads]);
// Spawn the threads.
for (int16 index = 0; index < numthreads; index++) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleThreadMain(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < numthreads; index++) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
MultipleThreadMain::CleanUp();
}
// TODO(port): this test requires the MultipleLockThread class
// (defined above), which requires the ability to pass file
// descriptors between processes. We haven't done that yet in Chrome
// for POSIX.
#if defined(OS_WIN)
// Create a set of threads to each open a shared memory segment and write to it
// with the lock held. Verify that they are always reading/writing consistent
// data.
TEST(SharedMemoryTest, Lock) {
PlatformThreadHandle thread_handles[kNumThreads];
MultipleLockThread* thread_delegates[kNumThreads];
// Spawn the threads.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleLockThread(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
#endif
// Allocate private (unique) shared memory with an empty string for a
// name. Make sure several of them don't point to the same thing as
// we might expect if the names are equal.
TEST(SharedMemoryTest, AnonymousPrivate) {
int i, j;
int count = 4;
bool rv;
const uint32 kDataSize = 8192;
scoped_array<SharedMemory> memories(new SharedMemory[count]);
scoped_array<int*> pointers(new int*[count]);
ASSERT_TRUE(memories.get());
ASSERT_TRUE(pointers.get());
for (i = 0; i < count; i++) {
rv = memories[i].CreateAndMapAnonymous(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memories[i].memory());
EXPECT_TRUE(ptr);
pointers[i] = ptr;
}
for (i = 0; i < count; i++) {
// zero out the first int in each except for i; for that one, make it 100.
for (j = 0; j < count; j++) {
if (i == j)
pointers[j][0] = 100;
else
pointers[j][0] = 0;
}
// make sure there is no bleeding of the 100 into the other pointers
for (j = 0; j < count; j++) {
if (i == j)
EXPECT_EQ(100, pointers[j][0]);
else
EXPECT_EQ(0, pointers[j][0]);
}
}
for (int i = 0; i < count; i++) {
memories[i].Close();
}
}
#if defined(OS_POSIX)
// Create a shared memory object, mmap it, and mprotect it to PROT_EXEC.
TEST(SharedMemoryTest, AnonymousExecutable) {
const uint32 kTestSize = 1 << 16;
SharedMemory shared_memory;
SharedMemoryCreateOptions options;
options.size = kTestSize;
options.executable = true;
EXPECT_TRUE(shared_memory.Create(options));
EXPECT_TRUE(shared_memory.Map(shared_memory.created_size()));
EXPECT_EQ(0, mprotect(shared_memory.memory(), shared_memory.created_size(),
PROT_READ | PROT_EXEC));
}
#endif
// On POSIX it is especially important we test shmem across processes,
// not just across threads. But the test is enabled on all platforms.
class SharedMemoryProcessTest : public MultiProcessTest {
public:
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
static int TaskTestMain() {
int errors = 0;
#if defined(OS_MACOSX)
mac::ScopedNSAutoreleasePool pool;
#endif
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
int *ptr = static_cast<int*>(memory.memory());
for (int idx = 0; idx < 20; idx++) {
memory.Lock();
int i = (1 << 16) + idx;
*ptr = i;
PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
if (*ptr != i)
errors++;
memory.Unlock();
}
memory.Close();
return errors;
}
private:
static const char* const s_test_name_;
};
const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem";
// http://crbug.com/61589
#if defined(OS_MACOSX)
#define MAYBE_Tasks DISABLED_Tasks
#else
#define MAYBE_Tasks Tasks
#endif
TEST_F(SharedMemoryProcessTest, MAYBE_Tasks) {
SharedMemoryProcessTest::CleanUp();
ProcessHandle handles[kNumTasks];
for (int index = 0; index < kNumTasks; ++index) {
handles[index] = SpawnChild("SharedMemoryTestMain", false);
ASSERT_TRUE(handles[index]);
}
int exit_code = 0;
for (int index = 0; index < kNumTasks; ++index) {
EXPECT_TRUE(WaitForExitCode(handles[index], &exit_code));
EXPECT_EQ(0, exit_code);
}
SharedMemoryProcessTest::CleanUp();
}
MULTIPROCESS_TEST_MAIN(SharedMemoryTestMain) {
return SharedMemoryProcessTest::TaskTestMain();
}
} // namespace base
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Benchmark.h"
#include "SkBlurImageFilter.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
#include "SkShader.h"
#include "SkString.h"
#define FILTER_WIDTH_SMALL 32
#define FILTER_HEIGHT_SMALL 32
#define FILTER_WIDTH_LARGE 256
#define FILTER_HEIGHT_LARGE 256
#define BLUR_SIGMA_MINI 0.5f
#define BLUR_SIGMA_SMALL 1.0f
#define BLUR_SIGMA_LARGE 10.0f
#define BLUR_SIGMA_HUGE 80.0f
class BlurImageFilterBench : public Benchmark {
public:
BlurImageFilterBench(SkScalar sigmaX, SkScalar sigmaY, bool small, bool cropped) :
fIsSmall(small), fIsCropped(cropped), fInitialized(false), fSigmaX(sigmaX), fSigmaY(sigmaY) {
fName.printf("blur_image_filter_%s%s_%.2f_%.2f", fIsSmall ? "small" : "large",
fIsCropped ? "_cropped" : "", SkScalarToFloat(sigmaX), SkScalarToFloat(sigmaY));
}
protected:
const char* onGetName() override {
return fName.c_str();
}
void onDelayedSetup() override {
if (!fInitialized) {
make_checkerboard();
fInitialized = true;
}
}
void onDraw(int loops, SkCanvas* canvas) override {
SkPaint paint;
static const SkScalar kX = 0;
static const SkScalar kY = 0;
const SkRect bmpRect = SkRect::MakeXYWH(kX, kY,
SkIntToScalar(fCheckerboard.width()),
SkIntToScalar(fCheckerboard.height()));
const SkImageFilter::CropRect cropRect =
SkImageFilter::CropRect(bmpRect.makeInset(10.f, 10.f));
const SkImageFilter::CropRect* crop = fIsCropped ? &cropRect : nullptr;
paint.setImageFilter(SkBlurImageFilter::Create(fSigmaX, fSigmaY, nullptr, crop))->unref();
for (int i = 0; i < loops; i++) {
canvas->drawBitmap(fCheckerboard, kX, kY, &paint);
}
}
private:
void make_checkerboard() {
const int w = fIsSmall ? FILTER_WIDTH_SMALL : FILTER_WIDTH_LARGE;
const int h = fIsSmall ? FILTER_HEIGHT_LARGE : FILTER_HEIGHT_LARGE;
fCheckerboard.allocN32Pixels(w, h);
SkCanvas canvas(fCheckerboard);
canvas.clear(0x00000000);
SkPaint darkPaint;
darkPaint.setColor(0xFF804020);
SkPaint lightPaint;
lightPaint.setColor(0xFF244484);
for (int y = 0; y < h; y += 16) {
for (int x = 0; x < w; x += 16) {
canvas.save();
canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
canvas.drawRect(SkRect::MakeXYWH(0, 0, 8, 8), darkPaint);
canvas.drawRect(SkRect::MakeXYWH(8, 0, 8, 8), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(0, 8, 8, 8), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(8, 8, 8, 8), darkPaint);
canvas.restore();
}
}
}
SkString fName;
bool fIsSmall;
bool fIsCropped;
bool fInitialized;
SkBitmap fCheckerboard;
SkScalar fSigmaX, fSigmaY;
typedef Benchmark INHERITED;
};
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, 0, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, 0, false, false);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_LARGE, false, false);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_SMALL, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, 0, false, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, 0, false, true);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_LARGE, false, true);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_SMALL, false, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, false, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, false, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, false, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, false, true);)
<commit_msg>Add cropped-then-expanded test cases to blur_image_filter tests.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Benchmark.h"
#include "SkBlurImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
#include "SkShader.h"
#include "SkString.h"
#define FILTER_WIDTH_SMALL 32
#define FILTER_HEIGHT_SMALL 32
#define FILTER_WIDTH_LARGE 256
#define FILTER_HEIGHT_LARGE 256
#define BLUR_SIGMA_MINI 0.5f
#define BLUR_SIGMA_SMALL 1.0f
#define BLUR_SIGMA_LARGE 10.0f
#define BLUR_SIGMA_HUGE 80.0f
// When 'cropped' is set we apply a cropRect to the blurImageFilter. The crop rect is an inset of
// the source's natural dimensions. This is intended to exercise blurring a larger source bitmap
// to a smaller destination bitmap.
// When 'expanded' is set we apply a cropRect to the input of the blurImageFilter (a noOp
// offsetImageFilter). The crop rect in this case is an inset of the source's natural dimensions.
// An additional crop rect is applied to the blurImageFilter that is just the natural dimensions
// of the source (not inset). This is intended to exercise blurring a smaller source bitmap to a
// larger destination.
class BlurImageFilterBench : public Benchmark {
public:
BlurImageFilterBench(SkScalar sigmaX, SkScalar sigmaY, bool small, bool cropped,
bool expanded)
: fIsSmall(small)
, fIsCropped(cropped)
, fIsExpanded(expanded)
, fInitialized(false)
, fSigmaX(sigmaX)
, fSigmaY(sigmaY) {
fName.printf("blur_image_filter_%s%s%s_%.2f_%.2f",
fIsSmall ? "small" : "large",
fIsCropped ? "_cropped" : "",
fIsExpanded ? "_expanded" : "",
SkScalarToFloat(sigmaX), SkScalarToFloat(sigmaY));
SkASSERT(!fIsExpanded || fIsCropped); // never want expansion w/o cropping
}
protected:
const char* onGetName() override {
return fName.c_str();
}
void onDelayedSetup() override {
if (!fInitialized) {
make_checkerboard();
fInitialized = true;
}
}
void onDraw(int loops, SkCanvas* canvas) override {
SkPaint paint;
static const SkScalar kX = 0;
static const SkScalar kY = 0;
const SkRect bmpRect = SkRect::MakeXYWH(kX, kY,
SkIntToScalar(fCheckerboard.width()),
SkIntToScalar(fCheckerboard.height()));
const SkImageFilter::CropRect cropRect(bmpRect.makeInset(10.f, 10.f));
const SkImageFilter::CropRect cropRectLarge(bmpRect);
SkAutoTUnref<SkImageFilter> noOpCropped(SkOffsetImageFilter::Create(0, 0, nullptr,
&cropRect));
SkImageFilter* input = fIsExpanded ? noOpCropped.get() : nullptr;
const SkImageFilter::CropRect* crop =
fIsExpanded ? &cropRectLarge : fIsCropped ? &cropRect : nullptr;
paint.setImageFilter(SkBlurImageFilter::Create(fSigmaX, fSigmaY, input, crop))->unref();
for (int i = 0; i < loops; i++) {
canvas->drawBitmap(fCheckerboard, kX, kY, &paint);
}
}
private:
void make_checkerboard() {
const int w = fIsSmall ? FILTER_WIDTH_SMALL : FILTER_WIDTH_LARGE;
const int h = fIsSmall ? FILTER_HEIGHT_LARGE : FILTER_HEIGHT_LARGE;
fCheckerboard.allocN32Pixels(w, h);
SkCanvas canvas(fCheckerboard);
canvas.clear(0x00000000);
SkPaint darkPaint;
darkPaint.setColor(0xFF804020);
SkPaint lightPaint;
lightPaint.setColor(0xFF244484);
for (int y = 0; y < h; y += 16) {
for (int x = 0; x < w; x += 16) {
canvas.save();
canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
canvas.drawRect(SkRect::MakeXYWH(0, 0, 8, 8), darkPaint);
canvas.drawRect(SkRect::MakeXYWH(8, 0, 8, 8), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(0, 8, 8, 8), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(8, 8, 8, 8), darkPaint);
canvas.restore();
}
}
}
SkString fName;
bool fIsSmall;
bool fIsCropped;
bool fIsExpanded;
bool fInitialized;
SkBitmap fCheckerboard;
SkScalar fSigmaX, fSigmaY;
typedef Benchmark INHERITED;
};
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, 0, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, 0, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_LARGE, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_SMALL, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, true, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, true, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, true, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, true, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, false, false, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, 0, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, 0, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_LARGE, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_SMALL, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, true, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, true, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, true, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, true, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, false, true, false);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, 0, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, 0, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_LARGE, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(0, BLUR_SIGMA_SMALL, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, true, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_MINI, BLUR_SIGMA_MINI, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, true, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_SMALL, BLUR_SIGMA_SMALL, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, true, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_LARGE, BLUR_SIGMA_LARGE, false, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, true, true, true);)
DEF_BENCH(return new BlurImageFilterBench(BLUR_SIGMA_HUGE, BLUR_SIGMA_HUGE, false, true, true);)
<|endoftext|> |
<commit_before>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <pthread.h>
#include "protocol.hpp"
using namespace std;
/* Information shared between clients */
struct shared_t {
public:
typedef protocol_t*(*protocol_factory_t)(config_t*);
public:
shared_t(config_t *_config, protocol_factory_t _protocol_factory)
: config(_config),
qps_offset(0), latencies_offset(0),
qps_fd(NULL), latencies_fd(NULL),
protocol_factory(_protocol_factory),
last_qps(0), n_op(1), n_tick(1), n_ops_so_far(0)
{
pthread_mutex_init(&mutex, NULL);
if(config->qps_file[0] != 0) {
qps_fd = fopen(config->qps_file, "wa");
}
if(config->latency_file[0] != 0) {
latencies_fd = fopen(config->latency_file, "wa");
}
}
~shared_t() {
if(qps_fd) {
fwrite(qps, 1, qps_offset, qps_fd);
fclose(qps_fd);
}
if(latencies_fd) {
fwrite(latencies, 1, latencies_offset, latencies_fd);
fclose(latencies_fd);
}
pthread_mutex_destroy(&mutex);
}
void push_qps(int _qps, int tick) {
if(!qps_fd && !latencies_fd)
return;
lock();
// Collect qps info from all clients before attempting to print
int qps_count = 0, agg_qps = 0;
map<int, pair<int, int> >::iterator op = qps_map.find(tick);
if(op != qps_map.end()) {
qps_count = op->second.first;
agg_qps = op->second.second;
}
qps_count += 1;
agg_qps += _qps;
if(qps_count == config->clients) {
_qps = agg_qps;
qps_map.erase(op);
} else {
qps_map[tick] = pair<int, int>(qps_count, agg_qps);
unlock();
return;
}
last_qps = _qps;
if(!qps_fd) {
unlock();
return;
}
int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
if(_off >= sizeof(qps) - qps_offset) {
// Couldn't write everything, flush
fwrite(qps, 1, qps_offset, qps_fd);
// Write again
qps_offset = 0;
_off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
}
qps_offset += _off;
n_tick++;
unlock();
}
void push_latency(float latency) {
n_ops_so_far++;
/*
if(n_ops_so_far % 200000 == 0)
printf("%ld\n", n_ops_so_far);
*/
if(!latencies_fd || last_qps == 0)
return;
// We cannot possibly write every latency because that stalls
// the client, so we want to scale that by the number of qps
// (we'll sample latencies for roughly N random ops every
// second).
const int samples_per_second = 20;
if(rand() % (last_qps / samples_per_second) != 0) {
return;
}
lock();
int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
if(_off >= sizeof(latencies) - latencies_offset) {
// Couldn't write everything, flush
fwrite(latencies, 1, latencies_offset, latencies_fd);
// Write again
latencies_offset = 0;
_off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
}
latencies_offset += _off;
n_op++;
unlock();
}
public:
protocol_factory_t protocol_factory;
private:
config_t *config;
map<int, pair<int, int> > qps_map;
char qps[40960], latencies[40960];
int qps_offset, latencies_offset;
FILE *qps_fd, *latencies_fd;
pthread_mutex_t mutex;
int last_qps;
long n_op;
int n_tick;
long n_ops_so_far;
private:
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
};
/* Communication structure for main thread and clients */
struct client_data_t {
config_t *config;
shared_t *shared;
};
/* The function that does the work */
void* run_client(void* data) {
// Grab the config
client_data_t *client_data = (client_data_t*)data;
config_t *config = client_data->config;
shared_t *shared = client_data->shared;
shared_t::protocol_factory_t pf = shared->protocol_factory;
protocol_t *proto = (*pf)(config);
// Connect to the server
proto->connect(config);
// Store the keys so we can run updates and deletes.
vector<payload_t> keys;
vector<payload_t> op_keys;
// Perform the ops
ticks_t last_time = get_ticks(), start_time = last_time, last_qps_time = last_time, now_time;
int qps = 0, tick = 0;
int total_queries = 0;
int total_inserts = 0;
bool keep_running = true;
while(keep_running) {
// Generate the command
load_t::load_op_t cmd = config->load.toss((config->batch_factor.min + config->batch_factor.max) / 2.0f);
int _val;
payload_t key, value;
int j, k, l; // because we can't declare in the loop
switch(cmd) {
case load_t::delete_op:
// Find the key
if(keys.empty())
break;
_val = random(0, keys.size() - 1);
key = keys[_val];
// Delete it from the server
proto->remove(key.first, key.second);
// Our own bookkeeping
free(key.first);
keys[_val] = keys[keys.size() - 1];
keys.erase(keys.begin() + _val);
qps++;
total_queries++;
break;
case load_t::update_op:
// Find the key and generate the payload
if(keys.empty())
break;
key = keys[random(0, keys.size() - 1)];
config->values.toss(&value);
// Send it to server
proto->update(key.first, key.second, value.first, value.second);
// Free the value
free(value.first);
qps++;
total_queries++;
break;
case load_t::insert_op:
// Generate the payload
config->keys.toss(&key);
config->values.toss(&value);
// Send it to server
proto->insert(key.first, key.second, value.first, value.second);
// Free the value and save the key
free(value.first);
keys.push_back(key);
qps++;
total_queries++;
total_inserts++;
break;
case load_t::read_op:
// Find the key
if(keys.empty())
break;
op_keys.clear();
j = random(config->batch_factor.min, config->batch_factor.max);
j = std::min(j, (int)keys.size());
l = random(0, keys.size() - 1);
for(k = 0; k < j; k++) {
key = keys[l];
l++;
if(l >= keys.size())
l = 0;
op_keys.push_back(key);
}
// Read it from the server
proto->read(&op_keys[0], j);
qps += j;
total_queries += j;
break;
};
now_time = get_ticks();
// Deal with individual op latency
ticks_t latency = now_time - last_time;
shared->push_latency(ticks_to_us(latency));
last_time = now_time;
// Deal with QPS
if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
shared->push_qps(qps, tick);
last_qps_time = now_time;
qps = 0;
tick++;
}
// See if we should keep running
switch(config->duration.units) {
case duration_t::queries_t:
keep_running = total_queries < config->duration.duration / config->clients;
break;
case duration_t::seconds_t:
keep_running = ticks_to_secs(now_time - start_time) < config->duration.duration;
break;
case duration_t::inserts_t:
keep_running = total_inserts < config->duration.duration / config->clients;
break;
default:
fprintf(stderr, "Unknown duration unit\n");
exit(-1);
}
}
delete proto;
// Free all the keys
for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) {
free(i->first);
}
}
#endif // __CLIENT_HPP__
<commit_msg>Accounting for deletes in insert mode in the stress client<commit_after>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <pthread.h>
#include "protocol.hpp"
using namespace std;
/* Information shared between clients */
struct shared_t {
public:
typedef protocol_t*(*protocol_factory_t)(config_t*);
public:
shared_t(config_t *_config, protocol_factory_t _protocol_factory)
: config(_config),
qps_offset(0), latencies_offset(0),
qps_fd(NULL), latencies_fd(NULL),
protocol_factory(_protocol_factory),
last_qps(0), n_op(1), n_tick(1), n_ops_so_far(0)
{
pthread_mutex_init(&mutex, NULL);
if(config->qps_file[0] != 0) {
qps_fd = fopen(config->qps_file, "wa");
}
if(config->latency_file[0] != 0) {
latencies_fd = fopen(config->latency_file, "wa");
}
}
~shared_t() {
if(qps_fd) {
fwrite(qps, 1, qps_offset, qps_fd);
fclose(qps_fd);
}
if(latencies_fd) {
fwrite(latencies, 1, latencies_offset, latencies_fd);
fclose(latencies_fd);
}
pthread_mutex_destroy(&mutex);
}
void push_qps(int _qps, int tick) {
if(!qps_fd && !latencies_fd)
return;
lock();
// Collect qps info from all clients before attempting to print
int qps_count = 0, agg_qps = 0;
map<int, pair<int, int> >::iterator op = qps_map.find(tick);
if(op != qps_map.end()) {
qps_count = op->second.first;
agg_qps = op->second.second;
}
qps_count += 1;
agg_qps += _qps;
if(qps_count == config->clients) {
_qps = agg_qps;
qps_map.erase(op);
} else {
qps_map[tick] = pair<int, int>(qps_count, agg_qps);
unlock();
return;
}
last_qps = _qps;
if(!qps_fd) {
unlock();
return;
}
int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
if(_off >= sizeof(qps) - qps_offset) {
// Couldn't write everything, flush
fwrite(qps, 1, qps_offset, qps_fd);
// Write again
qps_offset = 0;
_off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
}
qps_offset += _off;
n_tick++;
unlock();
}
void push_latency(float latency) {
n_ops_so_far++;
/*
if(n_ops_so_far % 200000 == 0)
printf("%ld\n", n_ops_so_far);
*/
if(!latencies_fd || last_qps == 0)
return;
// We cannot possibly write every latency because that stalls
// the client, so we want to scale that by the number of qps
// (we'll sample latencies for roughly N random ops every
// second).
const int samples_per_second = 20;
if(rand() % (last_qps / samples_per_second) != 0) {
return;
}
lock();
int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
if(_off >= sizeof(latencies) - latencies_offset) {
// Couldn't write everything, flush
fwrite(latencies, 1, latencies_offset, latencies_fd);
// Write again
latencies_offset = 0;
_off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
}
latencies_offset += _off;
n_op++;
unlock();
}
public:
protocol_factory_t protocol_factory;
private:
config_t *config;
map<int, pair<int, int> > qps_map;
char qps[40960], latencies[40960];
int qps_offset, latencies_offset;
FILE *qps_fd, *latencies_fd;
pthread_mutex_t mutex;
int last_qps;
long n_op;
int n_tick;
long n_ops_so_far;
private:
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
};
/* Communication structure for main thread and clients */
struct client_data_t {
config_t *config;
shared_t *shared;
};
/* The function that does the work */
void* run_client(void* data) {
// Grab the config
client_data_t *client_data = (client_data_t*)data;
config_t *config = client_data->config;
shared_t *shared = client_data->shared;
shared_t::protocol_factory_t pf = shared->protocol_factory;
protocol_t *proto = (*pf)(config);
// Connect to the server
proto->connect(config);
// Store the keys so we can run updates and deletes.
vector<payload_t> keys;
vector<payload_t> op_keys;
// Perform the ops
ticks_t last_time = get_ticks(), start_time = last_time, last_qps_time = last_time, now_time;
int qps = 0, tick = 0;
int total_queries = 0;
int total_inserts = 0;
int total_deletes = 0;
bool keep_running = true;
while(keep_running) {
// Generate the command
load_t::load_op_t cmd = config->load.toss((config->batch_factor.min + config->batch_factor.max) / 2.0f);
int _val;
payload_t key, value;
int j, k, l; // because we can't declare in the loop
switch(cmd) {
case load_t::delete_op:
// Find the key
if(keys.empty())
break;
_val = random(0, keys.size() - 1);
key = keys[_val];
// Delete it from the server
proto->remove(key.first, key.second);
// Our own bookkeeping
free(key.first);
keys[_val] = keys[keys.size() - 1];
keys.erase(keys.begin() + _val);
qps++;
total_queries++;
total_deletes++;
break;
case load_t::update_op:
// Find the key and generate the payload
if(keys.empty())
break;
key = keys[random(0, keys.size() - 1)];
config->values.toss(&value);
// Send it to server
proto->update(key.first, key.second, value.first, value.second);
// Free the value
free(value.first);
qps++;
total_queries++;
break;
case load_t::insert_op:
// Generate the payload
config->keys.toss(&key);
config->values.toss(&value);
// Send it to server
proto->insert(key.first, key.second, value.first, value.second);
// Free the value and save the key
free(value.first);
keys.push_back(key);
qps++;
total_queries++;
total_inserts++;
break;
case load_t::read_op:
// Find the key
if(keys.empty())
break;
op_keys.clear();
j = random(config->batch_factor.min, config->batch_factor.max);
j = std::min(j, (int)keys.size());
l = random(0, keys.size() - 1);
for(k = 0; k < j; k++) {
key = keys[l];
l++;
if(l >= keys.size())
l = 0;
op_keys.push_back(key);
}
// Read it from the server
proto->read(&op_keys[0], j);
qps += j;
total_queries += j;
break;
};
now_time = get_ticks();
// Deal with individual op latency
ticks_t latency = now_time - last_time;
shared->push_latency(ticks_to_us(latency));
last_time = now_time;
// Deal with QPS
if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
shared->push_qps(qps, tick);
last_qps_time = now_time;
qps = 0;
tick++;
}
// See if we should keep running
switch(config->duration.units) {
case duration_t::queries_t:
keep_running = total_queries < config->duration.duration / config->clients;
break;
case duration_t::seconds_t:
keep_running = ticks_to_secs(now_time - start_time) < config->duration.duration;
break;
case duration_t::inserts_t:
keep_running = total_inserts - total_deletes < config->duration.duration / config->clients;
break;
default:
fprintf(stderr, "Unknown duration unit\n");
exit(-1);
}
}
delete proto;
// Free all the keys
for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) {
free(i->first);
}
}
#endif // __CLIENT_HPP__
<|endoftext|> |
<commit_before>#include "RectCutCMPT.h"
#include "RectCutOP.h"
#include "StagePanel.h"
#include <easycomplex.h>
#include <easyimage.h>
namespace eimage
{
static const std::string FILTER = "rectcut";
RectCutCMPT::RectCutCMPT(wxWindow* parent, const wxString& name,
StagePanel* stage)
: d2d::AbstractEditCMPT(parent, name, stage)
, m_stage(stage)
{
m_editOP = new RectCutOP(this, stage);
}
void RectCutCMPT::onSaveEditOP(wxCommandEvent& event)
{
wxFileDialog dlg(this, wxT("Save"), wxEmptyString, wxEmptyString,
wxT("*_") + FILTER + wxT(".json"), wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
Json::Value value;
std::string filepath = op->getImageFilepath();
value["image filepath"] = filepath;
op->getRectMgr().store(value);
wxString filename = d2d::FilenameTools::getFilenameAddTag(dlg.GetPath(), FILTER, "json");
Json::StyledStreamWriter writer;
std::ofstream fout(filename.fn_str());
writer.write(fout, value);
fout.close();
}
}
void RectCutCMPT::onLoadEditOP(wxCommandEvent& event)
{
wxFileDialog dlg(this, wxT("Open"), wxEmptyString, wxEmptyString,
wxT("*_") + FILTER + wxT(".json"), wxFD_OPEN);
if (dlg.ShowModal() == wxID_OK)
{
wxString filename = d2d::FilenameTools::getFilenameAddTag(dlg.GetPath(), FILTER, "json");
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filename.fn_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->loadImageFromFile(value["image filepath"].asString());
op->getRectMgr().load(value);
}
}
wxSizer* RectCutCMPT::initLayout()
{
wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
// sizer->Add(initEditIOLayout());
// sizer->AddSpacer(10);
sizer->Add(initDataOutputLayout());
sizer->AddSpacer(10);
sizer->Add(initAddRectLayout());
return sizer;
}
wxSizer* RectCutCMPT::initEditIOLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Edit I/O"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
// save
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Save"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onSaveEditOP));
sizer->Add(btn);
}
sizer->AddSpacer(5);
// load
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Load"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onLoadEditOP));
sizer->Add(btn);
}
return sizer;
}
wxSizer* RectCutCMPT::initDataOutputLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Data Output"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxVERTICAL);
// images path
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("images path"));
wxSizer* sz = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
m_imagePath = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(200, -1), wxTE_READONLY);
sz->Add(m_imagePath);
sz->AddSpacer(5);
wxButton* btn = new wxButton(this, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize(25, 25));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onSetImagesPath));
sz->Add(btn);
sizer->Add(sz);
}
sizer->AddSpacer(10);
// json path
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("json path"));
wxSizer* sz = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
m_jsonPath = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(200, -1), wxTE_READONLY);
sz->Add(m_jsonPath);
sz->AddSpacer(5);
wxButton* btn = new wxButton(this, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize(25, 25));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onSetJsonPath));
sz->Add(btn);
sizer->Add(sz);
}
sizer->AddSpacer(10);
// output
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Output"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onOutputData));
sizer->Add(btn);
}
return sizer;
}
wxSizer* RectCutCMPT::initAddRectLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Add Rect"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxVERTICAL);
{
wxSizer* inputSizer = new wxBoxSizer(wxHORIZONTAL);
m_widthCtrl = new wxTextCtrl(this, wxID_ANY, "100", wxDefaultPosition, wxSize(60, -1));
inputSizer->Add(m_widthCtrl);
inputSizer->AddSpacer(5);
m_heightCtrl = new wxTextCtrl(this, wxID_ANY, "100", wxDefaultPosition, wxSize(60, -1));
inputSizer->Add(m_heightCtrl);
sizer->Add(inputSizer);
}
sizer->AddSpacer(5);
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Add"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onAddRect));
sizer->Add(btn);
}
return sizer;
}
void RectCutCMPT::onSetImagesPath(wxCommandEvent& event)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->setMouseMoveFocus(false);
wxDirDialog dlg(NULL, "Images Path", wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dlg.ShowModal() == wxID_OK)
{
m_imagePath->SetValue(dlg.GetPath());
}
op->setMouseMoveFocus(true);
}
void RectCutCMPT::onSetJsonPath(wxCommandEvent& event)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->setMouseMoveFocus(false);
wxDirDialog dlg(NULL, "Json Path", wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dlg.ShowModal() == wxID_OK)
{
m_jsonPath->SetValue(dlg.GetPath());
}
op->setMouseMoveFocus(true);
}
void RectCutCMPT::onOutputData(wxCommandEvent& event)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
const std::vector<d2d::Rect*>& rects = op->getRectMgr().getAllRect();
if (rects.empty()) {
return;
}
const d2d::ISprite* sprite = m_stage->getImage();
if (!sprite) {
return;
}
const d2d::ImageSprite* imgSprite = dynamic_cast<const d2d::ImageSprite*>(sprite);
if (!imgSprite) {
return;
}
d2d::Image* image = imgSprite->getSymbol().getImage();
wxString imageDir = m_imagePath->GetValue();
wxString jsonDir = m_jsonPath->GetValue();
wxString imageName = d2d::FilenameTools::getFilename(image->filepath());
ecomplex::Symbol* complex = new ecomplex::Symbol;
for (int i = 0, n = rects.size(); i < n; ++i)
{
const d2d::Rect& r = *rects[i];
eimage::ImageProcessor processor(image);
const unsigned char* pixels = processor.clip(r.xMin, r.xMax, r.yMin, r.yMax);
float width = r.xLength();
float height = r.yLength();
wxString img_filename = imageDir + "\\" + imageName + "_" + wxString::FromDouble(i);
d2d::ImageSaver::storeToFile(pixels, width, height, img_filename.ToStdString(), d2d::ImageSaver::e_png);
wxString img_fullname = img_filename + ".png";
d2d::ISprite* sprite = new d2d::NullSprite(new d2d::NullSymbol(img_fullname.ToStdString(), width, height));
d2d::Vector off;
off.x = r.xCenter() - image->clipWidth() * 0.5f;
off.y = r.yCenter() - image->clipHeight() * 0.5f;
sprite->translate(off);
complex->m_sprites.push_back(sprite);
}
wxString tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_complex);
wxString json_filename = jsonDir + "\\" + imageName + "_" + tag + ".json";
ecomplex::FileSaver::store(json_filename.c_str(), complex);
delete complex;
d2d::FinishDialog dlg(this);
dlg.ShowModal();
}
void RectCutCMPT::onAddRect(wxCommandEvent& event)
{
double width, height;
m_widthCtrl->GetValue().ToDouble(&width);
m_heightCtrl->GetValue().ToDouble(&height);
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->getRectMgr().insert(d2d::Rect(d2d::Vector(0, 0), d2d::Vector((float)width, (float)height)));
m_editPanel->Refresh();
}
}<commit_msg>[FIXED] easyimage路径改成相对<commit_after>#include "RectCutCMPT.h"
#include "RectCutOP.h"
#include "StagePanel.h"
#include <easycomplex.h>
#include <easyimage.h>
namespace eimage
{
static const std::string FILTER = "rectcut";
RectCutCMPT::RectCutCMPT(wxWindow* parent, const wxString& name,
StagePanel* stage)
: d2d::AbstractEditCMPT(parent, name, stage)
, m_stage(stage)
{
m_editOP = new RectCutOP(this, stage);
}
void RectCutCMPT::onSaveEditOP(wxCommandEvent& event)
{
wxFileDialog dlg(this, wxT("Save"), wxEmptyString, wxEmptyString,
wxT("*_") + FILTER + wxT(".json"), wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
Json::Value value;
std::string filepath = op->getImageFilepath();
value["image filepath"] = filepath;
op->getRectMgr().store(value);
wxString filename = d2d::FilenameTools::getFilenameAddTag(dlg.GetPath(), FILTER, "json");
Json::StyledStreamWriter writer;
std::ofstream fout(filename.fn_str());
writer.write(fout, value);
fout.close();
}
}
void RectCutCMPT::onLoadEditOP(wxCommandEvent& event)
{
wxFileDialog dlg(this, wxT("Open"), wxEmptyString, wxEmptyString,
wxT("*_") + FILTER + wxT(".json"), wxFD_OPEN);
if (dlg.ShowModal() == wxID_OK)
{
wxString filename = d2d::FilenameTools::getFilenameAddTag(dlg.GetPath(), FILTER, "json");
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filename.fn_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
wxString dlgpath = d2d::FilenameTools::getFileDir(filename);
wxString path = value["image filepath"].asString();
wxString absolutePath = d2d::FilenameTools::getAbsolutePath(dlgpath, path);
op->loadImageFromFile(absolutePath.ToStdString());
op->getRectMgr().load(value);
}
}
wxSizer* RectCutCMPT::initLayout()
{
wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
// sizer->Add(initEditIOLayout());
// sizer->AddSpacer(10);
sizer->Add(initDataOutputLayout());
sizer->AddSpacer(10);
sizer->Add(initAddRectLayout());
return sizer;
}
wxSizer* RectCutCMPT::initEditIOLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Edit I/O"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
// save
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Save"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onSaveEditOP));
sizer->Add(btn);
}
sizer->AddSpacer(5);
// load
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Load"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onLoadEditOP));
sizer->Add(btn);
}
return sizer;
}
wxSizer* RectCutCMPT::initDataOutputLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Data Output"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxVERTICAL);
// images path
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("images path"));
wxSizer* sz = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
m_imagePath = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(200, -1), wxTE_READONLY);
sz->Add(m_imagePath);
sz->AddSpacer(5);
wxButton* btn = new wxButton(this, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize(25, 25));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onSetImagesPath));
sz->Add(btn);
sizer->Add(sz);
}
sizer->AddSpacer(10);
// json path
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("json path"));
wxSizer* sz = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
m_jsonPath = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(200, -1), wxTE_READONLY);
sz->Add(m_jsonPath);
sz->AddSpacer(5);
wxButton* btn = new wxButton(this, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize(25, 25));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onSetJsonPath));
sz->Add(btn);
sizer->Add(sz);
}
sizer->AddSpacer(10);
// output
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Output"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onOutputData));
sizer->Add(btn);
}
return sizer;
}
wxSizer* RectCutCMPT::initAddRectLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Add Rect"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxVERTICAL);
{
wxSizer* inputSizer = new wxBoxSizer(wxHORIZONTAL);
m_widthCtrl = new wxTextCtrl(this, wxID_ANY, "100", wxDefaultPosition, wxSize(60, -1));
inputSizer->Add(m_widthCtrl);
inputSizer->AddSpacer(5);
m_heightCtrl = new wxTextCtrl(this, wxID_ANY, "100", wxDefaultPosition, wxSize(60, -1));
inputSizer->Add(m_heightCtrl);
sizer->Add(inputSizer);
}
sizer->AddSpacer(5);
{
wxButton* btn = new wxButton(this, wxID_ANY, wxT("Add"));
Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(RectCutCMPT::onAddRect));
sizer->Add(btn);
}
return sizer;
}
void RectCutCMPT::onSetImagesPath(wxCommandEvent& event)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->setMouseMoveFocus(false);
wxDirDialog dlg(NULL, "Images Path", wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dlg.ShowModal() == wxID_OK)
{
m_imagePath->SetValue(dlg.GetPath());
}
op->setMouseMoveFocus(true);
}
void RectCutCMPT::onSetJsonPath(wxCommandEvent& event)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->setMouseMoveFocus(false);
wxDirDialog dlg(NULL, "Json Path", wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dlg.ShowModal() == wxID_OK)
{
m_jsonPath->SetValue(dlg.GetPath());
}
op->setMouseMoveFocus(true);
}
void RectCutCMPT::onOutputData(wxCommandEvent& event)
{
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
const std::vector<d2d::Rect*>& rects = op->getRectMgr().getAllRect();
if (rects.empty()) {
return;
}
const d2d::ISprite* sprite = m_stage->getImage();
if (!sprite) {
return;
}
const d2d::ImageSprite* imgSprite = dynamic_cast<const d2d::ImageSprite*>(sprite);
if (!imgSprite) {
return;
}
d2d::Image* image = imgSprite->getSymbol().getImage();
wxString imageDir = m_imagePath->GetValue();
wxString jsonDir = m_jsonPath->GetValue();
wxString imageName = d2d::FilenameTools::getFilename(image->filepath());
ecomplex::Symbol* complex = new ecomplex::Symbol;
for (int i = 0, n = rects.size(); i < n; ++i)
{
const d2d::Rect& r = *rects[i];
eimage::ImageProcessor processor(image);
const unsigned char* pixels = processor.clip(r.xMin, r.xMax, r.yMin, r.yMax);
float width = r.xLength();
float height = r.yLength();
wxString img_filename = imageDir + "\\" + imageName + "_" + wxString::FromDouble(i);
d2d::ImageSaver::storeToFile(pixels, width, height, img_filename.ToStdString(), d2d::ImageSaver::e_png);
wxString img_fullname = img_filename + ".png";
d2d::ISprite* sprite = new d2d::NullSprite(new d2d::NullSymbol(img_fullname.ToStdString(), width, height));
d2d::Vector off;
off.x = r.xCenter() - image->clipWidth() * 0.5f;
off.y = r.yCenter() - image->clipHeight() * 0.5f;
sprite->translate(off);
complex->m_sprites.push_back(sprite);
}
wxString tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_complex);
wxString json_filename = jsonDir + "\\" + imageName + "_" + tag + ".json";
ecomplex::FileSaver::store(json_filename.c_str(), complex);
delete complex;
d2d::FinishDialog dlg(this);
dlg.ShowModal();
}
void RectCutCMPT::onAddRect(wxCommandEvent& event)
{
double width, height;
m_widthCtrl->GetValue().ToDouble(&width);
m_heightCtrl->GetValue().ToDouble(&height);
RectCutOP* op = static_cast<RectCutOP*>(m_editOP);
op->getRectMgr().insert(d2d::Rect(d2d::Vector(0, 0), d2d::Vector((float)width, (float)height)));
m_editPanel->Refresh();
}
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2008 Volker Krause <vkrause@kde.org>
Inspired by kdelibs/kdecore/io/kdebug.h
Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
2002 Holger Freyther (freyther@kde.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "akdebug.h"
#include "akcrash.h"
#include "akstandarddirs.h"
#include <libs/xdgbasedirs_p.h>
using Akonadi::XdgBaseDirs;
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMutex>
#include <cassert>
class FileDebugStream : public QIODevice
{
public:
FileDebugStream() :
mType( QtCriticalMsg )
{
open( WriteOnly );
}
bool isSequential() const { return true; }
qint64 readData(char *, qint64) { return 0; }
qint64 readLineData(char *, qint64) { return 0; }
qint64 writeData(const char *data, qint64 len)
{
QByteArray buf = QByteArray::fromRawData(data, len);
if ( !mFileName.isEmpty() ) {
QFile outputFile( mFileName );
outputFile.open( QIODevice::WriteOnly | QIODevice::Append | QIODevice::Unbuffered );
outputFile.write( data, len );
outputFile.putChar( '\n' );
outputFile.close();
}
qt_message_output( mType, buf.trimmed().constData() );
return len;
}
void setFileName( const QString &fileName )
{
mFileName = fileName;
}
void setType( QtMsgType type )
{
mType = type;
}
private:
QString mFileName;
QtMsgType mType;
};
class DebugPrivate
{
public:
DebugPrivate() :
fileStream( new FileDebugStream() )
{
}
~DebugPrivate()
{
delete fileStream;
}
QString errorLogFileName() const
{
return AkStandardDirs::saveDir( "data" )
+ QDir::separator()
+ name
+ QString::fromLatin1( ".error" );
}
QDebug stream( QtMsgType type )
{
QMutexLocker locker( &mutex );
#ifndef QT_NO_DEBUG_OUTPUT
if ( type == QtDebugMsg )
return qDebug();
#endif
fileStream->setType( type );
return QDebug( fileStream );
}
void setName( const QString &appName )
{
// Keep only the executable name, e.g. akonadi_control
name = appName.mid( appName.lastIndexOf( QLatin1Char('/') ) + 1 );
fileStream->setFileName( errorLogFileName() );
}
QMutex mutex;
FileDebugStream *fileStream;
QString name;
};
Q_GLOBAL_STATIC( DebugPrivate, sInstance )
QDebug akFatal()
{
return sInstance()->stream( QtFatalMsg );
}
QDebug akError()
{
return sInstance()->stream( QtCriticalMsg );
}
#ifndef QT_NO_DEBUG_OUTPUT
QDebug akDebug()
{
return sInstance()->stream( QtDebugMsg );
}
#endif
void akInit( const QString &appName )
{
AkonadiCrash::init();
sInstance()->setName( appName );
QFileInfo infoOld( sInstance()->errorLogFileName() + QString::fromLatin1(".old") );
if ( infoOld.exists() ) {
QFile fileOld( infoOld.absoluteFilePath() );
const bool success = fileOld.remove();
if ( !success )
qFatal( "Cannot remove old log file - running on a readlony filesystem maybe?" );
}
QFileInfo info( sInstance()->errorLogFileName() );
if ( info.exists() ) {
QFile file( info.absoluteFilePath() );
const bool success = file.rename( sInstance()->errorLogFileName() + QString::fromLatin1(".old") );
if ( !success )
qFatal( "Cannot rename log file - running on a readonly filesystem maybe?" );
}
}
QString getEnv( const char *name, const QString &defaultValue )
{
const QString v = QString::fromLocal8Bit( qgetenv( name ) );
return !v.isEmpty() ? v : defaultValue;
}
<commit_msg>Make akDebug compile with Qt 5.<commit_after>/*
Copyright (c) 2008 Volker Krause <vkrause@kde.org>
Inspired by kdelibs/kdecore/io/kdebug.h
Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
2002 Holger Freyther (freyther@kde.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "akdebug.h"
#include "akcrash.h"
#include "akstandarddirs.h"
#include <libs/xdgbasedirs_p.h>
using Akonadi::XdgBaseDirs;
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMutex>
#include <cassert>
class FileDebugStream : public QIODevice
{
public:
FileDebugStream() :
mType( QtCriticalMsg )
{
open( WriteOnly );
}
bool isSequential() const { return true; }
qint64 readData(char *, qint64) { return 0; }
qint64 readLineData(char *, qint64) { return 0; }
qint64 writeData(const char *data, qint64 len)
{
QByteArray buf = QByteArray::fromRawData(data, len);
if ( !mFileName.isEmpty() ) {
QFile outputFile( mFileName );
outputFile.open( QIODevice::WriteOnly | QIODevice::Append | QIODevice::Unbuffered );
outputFile.write( data, len );
outputFile.putChar( '\n' );
outputFile.close();
}
qt_message_output( mType,
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QMessageLogContext(),
QString::fromLatin1(buf.trimmed()) );
#else
buf.trimmed().constData() );
#endif
return len;
}
void setFileName( const QString &fileName )
{
mFileName = fileName;
}
void setType( QtMsgType type )
{
mType = type;
}
private:
QString mFileName;
QtMsgType mType;
};
class DebugPrivate
{
public:
DebugPrivate() :
fileStream( new FileDebugStream() )
{
}
~DebugPrivate()
{
delete fileStream;
}
QString errorLogFileName() const
{
return AkStandardDirs::saveDir( "data" )
+ QDir::separator()
+ name
+ QString::fromLatin1( ".error" );
}
QDebug stream( QtMsgType type )
{
QMutexLocker locker( &mutex );
#ifndef QT_NO_DEBUG_OUTPUT
if ( type == QtDebugMsg )
return qDebug();
#endif
fileStream->setType( type );
return QDebug( fileStream );
}
void setName( const QString &appName )
{
// Keep only the executable name, e.g. akonadi_control
name = appName.mid( appName.lastIndexOf( QLatin1Char('/') ) + 1 );
fileStream->setFileName( errorLogFileName() );
}
QMutex mutex;
FileDebugStream *fileStream;
QString name;
};
Q_GLOBAL_STATIC( DebugPrivate, sInstance )
QDebug akFatal()
{
return sInstance()->stream( QtFatalMsg );
}
QDebug akError()
{
return sInstance()->stream( QtCriticalMsg );
}
#ifndef QT_NO_DEBUG_OUTPUT
QDebug akDebug()
{
return sInstance()->stream( QtDebugMsg );
}
#endif
void akInit( const QString &appName )
{
AkonadiCrash::init();
sInstance()->setName( appName );
QFileInfo infoOld( sInstance()->errorLogFileName() + QString::fromLatin1(".old") );
if ( infoOld.exists() ) {
QFile fileOld( infoOld.absoluteFilePath() );
const bool success = fileOld.remove();
if ( !success )
qFatal( "Cannot remove old log file - running on a readlony filesystem maybe?" );
}
QFileInfo info( sInstance()->errorLogFileName() );
if ( info.exists() ) {
QFile file( info.absoluteFilePath() );
const bool success = file.rename( sInstance()->errorLogFileName() + QString::fromLatin1(".old") );
if ( !success )
qFatal( "Cannot rename log file - running on a readonly filesystem maybe?" );
}
}
QString getEnv( const char *name, const QString &defaultValue )
{
const QString v = QString::fromLocal8Bit( qgetenv( name ) );
return !v.isEmpty() ? v : defaultValue;
}
<|endoftext|> |
<commit_before>#include "sorteddatatable.h"
#include <iomanip> // Set precision used by streams on double values
#include <fstream>
SortedDataTable::SortedDataTable()
: SortedDataTable(false)
{
}
SortedDataTable::SortedDataTable(bool allowDuplicates)
: allowDuplicates(allowDuplicates), numDuplicates(0), xDim(0)
{
}
void SortedDataTable::addSample(double x, double y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(std::vector<double> x, double y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(std::vector<double> x, std::vector<double> y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(DenseVector x, double y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(DenseVector x, DenseVector y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(const DataSample &sample)
{
if(getNumSamples() == 0)
{
xDim = sample.getX().size();
yDim = sample.getY().size();
initDataStructures();
}
assert(sample.getDimX() == xDim); // All points must have the same dimension
assert(sample.getDimY() == yDim); // All points must have the same dimension
// Check if the sample has been added already
if(samples.count(sample) > 0)
{
if(!allowDuplicates)
{
std::cout << "Discarding duplicate sample because allowDuplicates is false!" << std::endl;
std::cout << "Initialize with SortedDataTable(true) to set it to true." << std::endl;
return;
}
numDuplicates++;
}
samples.insert(sample);
recordGridPoint(sample);
}
void SortedDataTable::recordGridPoint(const DataSample &sample)
{
for(unsigned int i = 0; i < getDimX(); i++)
{
grid.at(i).insert(sample.getX().at(i));
}
}
unsigned int SortedDataTable::getNumSamplesRequired() const
{
unsigned long samplesRequired = 1;
unsigned int i = 0;
for(auto &variable : grid)
{
samplesRequired *= (unsigned long) variable.size();
i++;
}
return (i > 0 ? samplesRequired : (unsigned long) 0);
}
bool SortedDataTable::isGridComplete() const
{
return samples.size() > 0 && samples.size() - numDuplicates == getNumSamplesRequired();
}
void SortedDataTable::initDataStructures()
{
for(unsigned int i = 0; i < getDimX(); i++)
{
grid.push_back(std::set<double>());
}
}
unsigned int SortedDataTable::getDimX() const
{
return xDim;
}
unsigned int SortedDataTable::getDimY() const
{
return yDim;
}
unsigned int SortedDataTable::getNumSamples() const
{
return samples.size();
}
std::multiset<DataSample>::const_iterator SortedDataTable::cbegin() const
{
gridCompleteGuard();
return samples.cbegin();
}
std::multiset<DataSample>::const_iterator SortedDataTable::cend() const
{
gridCompleteGuard();
return samples.cend();
}
void SortedDataTable::gridCompleteGuard() const
{
if(!isGridComplete())
{
std::cout << "The grid is not complete yet!" << std::endl;
exit(1);
}
}
void SortedDataTable::saveDataTable(std::string fileName) const
{
std::ofstream outFile;
try
{
outFile.open(fileName);
}
catch(const std::ios_base::failure &e)
{
throw;
}
// If this function is still alive the file must be open,
// no need to call is_open()
// Write header
outFile << "# Kommentar" << '\n';
outFile << xDim << " " << yDim << '\n';
for(auto it = cbegin(); it != cend(); it++)
{
for(int i = 0; i < xDim; i++)
{
outFile << std::setprecision(SAVE_DOUBLE_PRECISION) << it->getX().at(i) << " ";
}
for(int j = 0; j < yDim; j++)
{
outFile << std::setprecision(SAVE_DOUBLE_PRECISION) << it->getY().at(j);
if(j + 1 < yDim)
outFile << " ";
}
outFile << '\n';
}
// close() also flushes
try
{
outFile.close();
}
catch(const std::ios_base::failure &e)
{
throw;
}
}
void SortedDataTable::loadDataTable(std::string fileName)
{
std::ifstream inFile;
try
{
inFile.open(fileName);
}
catch(const std::ios_base::failure &e)
{
throw;
}
// If this function is still alive the file must be open,
// no need to call is_open()
// Skip past comments
std::string line;
int nX, nY;
int state = 0;
while(std::getline(inFile, line))
{
// Look for comment sign
if(line.at(0) == '#')
continue;
// Reading number of dimensions
if(state == 0)
{
std::string::size_type sz = 0;
nX = std::stoi(line, &sz);
nY = std::stoi(line.substr(sz));
state = 1;
}
// Reading samples
else if(state == 1)
{
auto x = std::vector<double>(nX);
auto y = std::vector<double>(nY);
std::string::size_type sz = 0;
for(int i = 0; i < nX; i++)
{
line = line.substr(sz);
x.at(i) = std::stod(line, &sz);
}
for(int j = 0; j < nY; j++)
{
line = line.substr(sz);
y.at(j) = std::stod(line, &sz);
}
addSample(x, y);
}
}
// close() also flushes
try
{
inFile.close();
}
catch(const std::ios_base::failure &e)
{
throw;
}
}
/***************************
* Backwards compatibility *
***************************/
// = [x1, x2, x3], where x1 = [...] holds unique values of x1 variable
std::vector< std::vector<double> > SortedDataTable::getBackwardsCompatibleGrid() const
{
gridCompleteGuard();
std::vector< std::vector<double> > backwardsCompatibleGrid;
for(auto &variable : grid)
{
backwardsCompatibleGrid.push_back(std::vector<double>());
for(auto &value : variable)
{
backwardsCompatibleGrid.at(backwardsCompatibleGrid.size() - 1).push_back(value);
}
}
return backwardsCompatibleGrid;
}
// = [x1, x2, x3], where x1 = [x11, x12, ...] holds the variables of point x1.
// 1 <= size(x1) = size(x2) = ... = size(xn) < m
std::vector< std::vector<double> > SortedDataTable::getBackwardsCompatibleX() const
{
gridCompleteGuard();
std::vector< std::vector<double> > backwardsCompatibleX;
for(auto &sample : samples)
{
backwardsCompatibleX.push_back(sample.getX());
}
return backwardsCompatibleX;
}
// = [y1, y2, y3], where y1 = [y11, y12, ...] holds the variables of value y1.
// 1 <= size(yn) < m
std::vector< std::vector<double> > SortedDataTable::getBackwardsCompatibleY() const
{
gridCompleteGuard();
std::vector< std::vector<double> > backwardsCompatibleY;
for(auto &sample : samples)
{
backwardsCompatibleY.push_back(sample.getY());
}
return backwardsCompatibleY;
}
// Copy and transpose table: turn columns to rows and rows to columns
std::vector< std::vector<double> > SortedDataTable::transposeTable(const std::vector< std::vector<double> > &table) const
{
if (table.size() > 0)
{
// Assumes square tables!
std::vector< std::vector<double> > transp(table.at(0).size());
for (unsigned int i = 0; i < table.size(); i++)
{
for (unsigned int j = 0; j < table.at(i).size(); j++)
{
transp.at(j).push_back(table.at(i).at(j));
}
}
return transp;
}
return table;
}
std::vector< std::vector<double> > SortedDataTable::getTransposedTableX() const
{
return transposeTable(getBackwardsCompatibleX());
}
std::vector< std::vector<double> > SortedDataTable::getTransposedTableY() const
{
return transposeTable(getBackwardsCompatibleY());
}
/**************
* Debug code *
**************/
void SortedDataTable::printSamples() const
{
for(auto &sample : samples)
{
std::cout << sample << std::endl;
}
}
void SortedDataTable::printGrid() const
{
std::cout << "===== Printing grid =====" << std::endl;
unsigned int i = 0;
for(auto &variable : grid)
{
std::cout << "x" << i++ << "(" << variable.size() << "): ";
for(double value : variable)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
std::cout << "Unique samples added: " << samples.size() << std::endl;
std::cout << "Samples required: " << getNumSamplesRequired() << std::endl;
}
<commit_msg>Add some more info to the comments at the top of save files<commit_after>#include "sorteddatatable.h"
#include <iomanip> // Set precision used by streams on double values
#include <fstream>
SortedDataTable::SortedDataTable()
: SortedDataTable(false)
{
}
SortedDataTable::SortedDataTable(bool allowDuplicates)
: allowDuplicates(allowDuplicates), numDuplicates(0), xDim(0)
{
}
void SortedDataTable::addSample(double x, double y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(std::vector<double> x, double y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(std::vector<double> x, std::vector<double> y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(DenseVector x, double y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(DenseVector x, DenseVector y)
{
addSample(DataSample(x, y));
}
void SortedDataTable::addSample(const DataSample &sample)
{
if(getNumSamples() == 0)
{
xDim = sample.getX().size();
yDim = sample.getY().size();
initDataStructures();
}
assert(sample.getDimX() == xDim); // All points must have the same dimension
assert(sample.getDimY() == yDim); // All points must have the same dimension
// Check if the sample has been added already
if(samples.count(sample) > 0)
{
if(!allowDuplicates)
{
std::cout << "Discarding duplicate sample because allowDuplicates is false!" << std::endl;
std::cout << "Initialize with SortedDataTable(true) to set it to true." << std::endl;
return;
}
numDuplicates++;
}
samples.insert(sample);
recordGridPoint(sample);
}
void SortedDataTable::recordGridPoint(const DataSample &sample)
{
for(unsigned int i = 0; i < getDimX(); i++)
{
grid.at(i).insert(sample.getX().at(i));
}
}
unsigned int SortedDataTable::getNumSamplesRequired() const
{
unsigned long samplesRequired = 1;
unsigned int i = 0;
for(auto &variable : grid)
{
samplesRequired *= (unsigned long) variable.size();
i++;
}
return (i > 0 ? samplesRequired : (unsigned long) 0);
}
bool SortedDataTable::isGridComplete() const
{
return samples.size() > 0 && samples.size() - numDuplicates == getNumSamplesRequired();
}
void SortedDataTable::initDataStructures()
{
for(unsigned int i = 0; i < getDimX(); i++)
{
grid.push_back(std::set<double>());
}
}
unsigned int SortedDataTable::getDimX() const
{
return xDim;
}
unsigned int SortedDataTable::getDimY() const
{
return yDim;
}
unsigned int SortedDataTable::getNumSamples() const
{
return samples.size();
}
std::multiset<DataSample>::const_iterator SortedDataTable::cbegin() const
{
gridCompleteGuard();
return samples.cbegin();
}
std::multiset<DataSample>::const_iterator SortedDataTable::cend() const
{
gridCompleteGuard();
return samples.cend();
}
void SortedDataTable::gridCompleteGuard() const
{
if(!isGridComplete())
{
std::cout << "The grid is not complete yet!" << std::endl;
exit(1);
}
}
void SortedDataTable::saveDataTable(std::string fileName) const
{
std::ofstream outFile;
try
{
outFile.open(fileName);
}
catch(const std::ios_base::failure &e)
{
throw;
}
// If this function is still alive the file must be open,
// no need to call is_open()
// Write header
outFile << "# Saved DataTable" << '\n';
outFile << "# Number of samples: " << getNumSamples() << '\n';
outFile << "# Complete grid: " << (isGridComplete() ? "yes" : "no") << '\n';
outFile << "# xDim: " << xDim << ", yDim: " << yDim << '\n';
// Number of x and y dimensions
outFile << xDim << " " << yDim << '\n';
for(auto it = cbegin(); it != cend(); it++)
{
for(int i = 0; i < xDim; i++)
{
outFile << std::setprecision(SAVE_DOUBLE_PRECISION) << it->getX().at(i) << " ";
}
for(int j = 0; j < yDim; j++)
{
outFile << std::setprecision(SAVE_DOUBLE_PRECISION) << it->getY().at(j);
if(j + 1 < yDim)
outFile << " ";
}
outFile << '\n';
}
// close() also flushes
try
{
outFile.close();
}
catch(const std::ios_base::failure &e)
{
throw;
}
}
void SortedDataTable::loadDataTable(std::string fileName)
{
std::ifstream inFile;
try
{
inFile.open(fileName);
}
catch(const std::ios_base::failure &e)
{
throw;
}
// If this function is still alive the file must be open,
// no need to call is_open()
// Skip past comments
std::string line;
int nX, nY;
int state = 0;
while(std::getline(inFile, line))
{
// Look for comment sign
if(line.at(0) == '#')
continue;
// Reading number of dimensions
if(state == 0)
{
std::string::size_type sz = 0;
nX = std::stoi(line, &sz);
nY = std::stoi(line.substr(sz));
state = 1;
}
// Reading samples
else if(state == 1)
{
auto x = std::vector<double>(nX);
auto y = std::vector<double>(nY);
std::string::size_type sz = 0;
for(int i = 0; i < nX; i++)
{
line = line.substr(sz);
x.at(i) = std::stod(line, &sz);
}
for(int j = 0; j < nY; j++)
{
line = line.substr(sz);
y.at(j) = std::stod(line, &sz);
}
addSample(x, y);
}
}
// close() also flushes
try
{
inFile.close();
}
catch(const std::ios_base::failure &e)
{
throw;
}
}
/***************************
* Backwards compatibility *
***************************/
// = [x1, x2, x3], where x1 = [...] holds unique values of x1 variable
std::vector< std::vector<double> > SortedDataTable::getBackwardsCompatibleGrid() const
{
gridCompleteGuard();
std::vector< std::vector<double> > backwardsCompatibleGrid;
for(auto &variable : grid)
{
backwardsCompatibleGrid.push_back(std::vector<double>());
for(auto &value : variable)
{
backwardsCompatibleGrid.at(backwardsCompatibleGrid.size() - 1).push_back(value);
}
}
return backwardsCompatibleGrid;
}
// = [x1, x2, x3], where x1 = [x11, x12, ...] holds the variables of point x1.
// 1 <= size(x1) = size(x2) = ... = size(xn) < m
std::vector< std::vector<double> > SortedDataTable::getBackwardsCompatibleX() const
{
gridCompleteGuard();
std::vector< std::vector<double> > backwardsCompatibleX;
for(auto &sample : samples)
{
backwardsCompatibleX.push_back(sample.getX());
}
return backwardsCompatibleX;
}
// = [y1, y2, y3], where y1 = [y11, y12, ...] holds the variables of value y1.
// 1 <= size(yn) < m
std::vector< std::vector<double> > SortedDataTable::getBackwardsCompatibleY() const
{
gridCompleteGuard();
std::vector< std::vector<double> > backwardsCompatibleY;
for(auto &sample : samples)
{
backwardsCompatibleY.push_back(sample.getY());
}
return backwardsCompatibleY;
}
// Copy and transpose table: turn columns to rows and rows to columns
std::vector< std::vector<double> > SortedDataTable::transposeTable(const std::vector< std::vector<double> > &table) const
{
if (table.size() > 0)
{
// Assumes square tables!
std::vector< std::vector<double> > transp(table.at(0).size());
for (unsigned int i = 0; i < table.size(); i++)
{
for (unsigned int j = 0; j < table.at(i).size(); j++)
{
transp.at(j).push_back(table.at(i).at(j));
}
}
return transp;
}
return table;
}
std::vector< std::vector<double> > SortedDataTable::getTransposedTableX() const
{
return transposeTable(getBackwardsCompatibleX());
}
std::vector< std::vector<double> > SortedDataTable::getTransposedTableY() const
{
return transposeTable(getBackwardsCompatibleY());
}
/**************
* Debug code *
**************/
void SortedDataTable::printSamples() const
{
for(auto &sample : samples)
{
std::cout << sample << std::endl;
}
}
void SortedDataTable::printGrid() const
{
std::cout << "===== Printing grid =====" << std::endl;
unsigned int i = 0;
for(auto &variable : grid)
{
std::cout << "x" << i++ << "(" << variable.size() << "): ";
for(double value : variable)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
std::cout << "Unique samples added: " << samples.size() << std::endl;
std::cout << "Samples required: " << getNumSamplesRequired() << std::endl;
}
<|endoftext|> |
<commit_before>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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 */
/* fem_system_ex2.C Copyright 2012 Robert Weidlich, also LGPL-licensed */
#include "libmesh/equation_systems.h"
#include "libmesh/getpot.h"
#include "libmesh/libmesh.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/string_to_enum.h"
#include "libmesh/time_solver.h"
#include "libmesh/transient_system.h"
#include "libmesh/vtk_io.h"
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
using namespace libMesh;
#include "solid_system.h"
void setup(EquationSystems& systems, Mesh& mesh, GetPot& args)
{
const unsigned int dim = mesh.mesh_dimension();
// We currently invert tensors with the assumption that they're 3x3
libmesh_assert (dim == 3);
// Generating Mesh
ElemType eltype = Utility::string_to_enum<ElemType>(args("mesh/generation/element_type", "hex8"));
int nx = args("mesh/generation/num_elem", 4, 0);
int ny = args("mesh/generation/num_elem", 4, 1);
int nz = dim > 2 ? args("mesh/generation/num_elem", 4, 2) : 0;
double origx = args("mesh/generation/origin", -1.0, 0);
double origy = args("mesh/generation/origin", -1.0, 1);
double origz = args("mesh/generation/origin", 0.0, 2);
double sizex = args("mesh/generation/size", 2.0, 0);
double sizey = args("mesh/generation/size", 2.0, 1);
double sizez = args("mesh/generation/size", 2.0, 2);
MeshTools::Generation::build_cube(mesh, nx, ny, nz,
origx, origx+sizex, origy, origy+sizey, origz, origz+sizez, eltype);
// Creating Systems
SolidSystem& imms = systems.add_system<SolidSystem> ("solid");
imms.args = args;
// Build up auxiliary system
ExplicitSystem& aux_sys = systems.add_system<TransientExplicitSystem>("auxiliary");
// Initialize the system
systems.parameters.set<unsigned int>("phase") = 0;
systems.init();
imms.save_initial_mesh();
// Fill global solution vector from local ones
aux_sys.reinit();
}
void run_timestepping(EquationSystems& systems, GetPot& args)
{
TransientExplicitSystem& aux_system = systems.get_system<TransientExplicitSystem>("auxiliary");
SolidSystem& solid_system = systems.get_system<SolidSystem>("solid");
AutoPtr<VTKIO> io = AutoPtr<VTKIO>(new VTKIO(systems.get_mesh()));
Real duration = args("duration", 1.0);
for (unsigned int t_step = 0; t_step < duration/solid_system.deltat; t_step++) {
// Progress in current phase [0..1]
Real progress = t_step * solid_system.deltat / duration;
systems.parameters.set<Real>("progress") = progress;
systems.parameters.set<unsigned int>("step") = t_step;
// Update message
out << "===== Time Step " << std::setw(4) << t_step;
out << " (" << std::fixed << std::setprecision(2) << std::setw(6) << (progress*100.) << "%)";
out << ", time = " << std::setw(7) << solid_system.time;
out << " =====" << std::endl;
// Advance timestep in auxiliary system
aux_system.current_local_solution->close();
aux_system.old_local_solution->close();
*aux_system.older_local_solution = *aux_system.old_local_solution;
*aux_system.old_local_solution = *aux_system.current_local_solution;
out << "Solving Solid" << std::endl;
solid_system.solve();
aux_system.reinit();
// Carry out the adaptive mesh refinement/coarsening
out << "Doing a reinit of the equation systems" << std::endl;
systems.reinit();
if (t_step % args("output/frequency", 1) == 0) {
std::string result;
std::stringstream file_name;
file_name << args("results_directory", "./") << "fem_";
file_name << std::setw(6) << std::setfill('0') << t_step;
file_name << ".pvtu";
io->write_equation_systems(file_name.str(), systems);
}
// Advance to the next timestep in a transient problem
out << "Advancing to next step" << std::endl;
solid_system.time_solver->advance_timestep();
}
}
int main(int argc, char** argv)
{
// Skip this example if we do not meet certain requirements
#ifndef LIBMESH_HAVE_VTK
libmesh_example_assert(false, "--enable-vtk");
#endif
// Initialize libMesh and any dependent libraries
LibMeshInit init(argc, argv);
// Threaded assembly doesn't currently work with the moving mesh
// code.
// We'll skip this example for now.
if (libMesh::n_threads() > 1)
{
std::cout << "We skip fem_system_ex2 when using threads.\n"
<< std::endl;
return 0;
}
// read simulation parameters from file
GetPot args = GetPot("solid.in");
// Create System and Mesh
int dim = args("mesh/generation/dimension", 3);
libmesh_example_assert(dim <= LIBMESH_DIM, "3D support");
// Create a mesh, with dimension to be overridden later, distributed
// across the default MPI communicator.
Mesh mesh(0,init.comm);
EquationSystems systems(mesh);
// Create and set systems up
setup(systems, mesh, args);
// run the systems
run_timestepping(systems, args);
out << "Finished calculations" << std::endl;
return 0;
}
<commit_msg>Fix accidental omission of fem_system_ex2 Mesh dim<commit_after>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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 */
/* fem_system_ex2.C Copyright 2012 Robert Weidlich, also LGPL-licensed */
#include "libmesh/equation_systems.h"
#include "libmesh/getpot.h"
#include "libmesh/libmesh.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/string_to_enum.h"
#include "libmesh/time_solver.h"
#include "libmesh/transient_system.h"
#include "libmesh/vtk_io.h"
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
using namespace libMesh;
#include "solid_system.h"
void setup(EquationSystems& systems, Mesh& mesh, GetPot& args)
{
const unsigned int dim = mesh.mesh_dimension();
// We currently invert tensors with the assumption that they're 3x3
libmesh_assert (dim == 3);
// Generating Mesh
ElemType eltype = Utility::string_to_enum<ElemType>(args("mesh/generation/element_type", "hex8"));
int nx = args("mesh/generation/num_elem", 4, 0);
int ny = args("mesh/generation/num_elem", 4, 1);
int nz = dim > 2 ? args("mesh/generation/num_elem", 4, 2) : 0;
double origx = args("mesh/generation/origin", -1.0, 0);
double origy = args("mesh/generation/origin", -1.0, 1);
double origz = args("mesh/generation/origin", 0.0, 2);
double sizex = args("mesh/generation/size", 2.0, 0);
double sizey = args("mesh/generation/size", 2.0, 1);
double sizez = args("mesh/generation/size", 2.0, 2);
MeshTools::Generation::build_cube(mesh, nx, ny, nz,
origx, origx+sizex, origy, origy+sizey, origz, origz+sizez, eltype);
// Creating Systems
SolidSystem& imms = systems.add_system<SolidSystem> ("solid");
imms.args = args;
// Build up auxiliary system
ExplicitSystem& aux_sys = systems.add_system<TransientExplicitSystem>("auxiliary");
// Initialize the system
systems.parameters.set<unsigned int>("phase") = 0;
systems.init();
imms.save_initial_mesh();
// Fill global solution vector from local ones
aux_sys.reinit();
}
void run_timestepping(EquationSystems& systems, GetPot& args)
{
TransientExplicitSystem& aux_system = systems.get_system<TransientExplicitSystem>("auxiliary");
SolidSystem& solid_system = systems.get_system<SolidSystem>("solid");
AutoPtr<VTKIO> io = AutoPtr<VTKIO>(new VTKIO(systems.get_mesh()));
Real duration = args("duration", 1.0);
for (unsigned int t_step = 0; t_step < duration/solid_system.deltat; t_step++) {
// Progress in current phase [0..1]
Real progress = t_step * solid_system.deltat / duration;
systems.parameters.set<Real>("progress") = progress;
systems.parameters.set<unsigned int>("step") = t_step;
// Update message
out << "===== Time Step " << std::setw(4) << t_step;
out << " (" << std::fixed << std::setprecision(2) << std::setw(6) << (progress*100.) << "%)";
out << ", time = " << std::setw(7) << solid_system.time;
out << " =====" << std::endl;
// Advance timestep in auxiliary system
aux_system.current_local_solution->close();
aux_system.old_local_solution->close();
*aux_system.older_local_solution = *aux_system.old_local_solution;
*aux_system.old_local_solution = *aux_system.current_local_solution;
out << "Solving Solid" << std::endl;
solid_system.solve();
aux_system.reinit();
// Carry out the adaptive mesh refinement/coarsening
out << "Doing a reinit of the equation systems" << std::endl;
systems.reinit();
if (t_step % args("output/frequency", 1) == 0) {
std::string result;
std::stringstream file_name;
file_name << args("results_directory", "./") << "fem_";
file_name << std::setw(6) << std::setfill('0') << t_step;
file_name << ".pvtu";
io->write_equation_systems(file_name.str(), systems);
}
// Advance to the next timestep in a transient problem
out << "Advancing to next step" << std::endl;
solid_system.time_solver->advance_timestep();
}
}
int main(int argc, char** argv)
{
// Skip this example if we do not meet certain requirements
#ifndef LIBMESH_HAVE_VTK
libmesh_example_assert(false, "--enable-vtk");
#endif
// Initialize libMesh and any dependent libraries
LibMeshInit init(argc, argv);
// Threaded assembly doesn't currently work with the moving mesh
// code.
// We'll skip this example for now.
if (libMesh::n_threads() > 1)
{
std::cout << "We skip fem_system_ex2 when using threads.\n"
<< std::endl;
return 0;
}
// read simulation parameters from file
GetPot args = GetPot("solid.in");
// Create System and Mesh
int dim = args("mesh/generation/dimension", 3);
libmesh_example_assert(dim <= LIBMESH_DIM, "3D support");
// Create a mesh distributed across the default MPI communicator.
Mesh mesh(dim,init.comm);
EquationSystems systems(mesh);
// Create and set systems up
setup(systems, mesh, args);
// run the systems
run_timestepping(systems, args);
out << "Finished calculations" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
kwatchgnupgmainwin.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB
Kleopatra 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.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kwatchgnupgmainwin.h"
#include "kwatchgnupgconfig.h"
#include "tray.h"
#include <kleo/cryptobackendfactory.h>
#include <kleo/cryptoconfig.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kapplication.h>
#include <kaction.h>
#include <kstdaction.h>
#include <kprocio.h>
#include <kconfig.h>
#include <kfiledialog.h>
#include <qtextedit.h>
#include <qdir.h>
#include <qeventloop.h>
#include <qtimer.h>
#define WATCHGNUPGBINARY "watchgnupg"
#define WATCHGNUPGSOCKET ( QDir::home().canonicalPath() + "/.gnupg/log-socket")
KWatchGnuPGMainWindow::KWatchGnuPGMainWindow( QWidget* parent, const char* name )
: KMainWindow( parent, name, WType_TopLevel ), mConfig(0)
{
createActions();
createGUI();
mCentralWidget = new QTextEdit( this, "central log view" );
mCentralWidget->setTextFormat( QTextEdit::LogText );
setCentralWidget( mCentralWidget );
mWatcher = new KProcIO();
connect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
connect( mWatcher, SIGNAL( readReady(KProcIO*) ),
this, SLOT( slotReadStdout() ) );
slotReadConfig();
mSysTray = new KWatchGnuPGTray( this );
mSysTray->show();
connect( mSysTray, SIGNAL( quitSelected() ),
this, SLOT( slotQuit() ) );
setAutoSaveSettings();
}
KWatchGnuPGMainWindow::~KWatchGnuPGMainWindow()
{
delete mWatcher;
}
void KWatchGnuPGMainWindow::slotClear()
{
mCentralWidget->clear();
mCentralWidget->append( tr("[%1] Log cleared").arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) );
}
void KWatchGnuPGMainWindow::createActions()
{
(void)new KAction( i18n("C&lear History"), "history_clear", CTRL+Key_L,
this, SLOT( slotClear() ),
actionCollection(), "clear_log" );
(void)KStdAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() );
(void)KStdAction::close( this, SLOT(close()), actionCollection() );
(void)KStdAction::quit( this, SLOT(slotQuit()), actionCollection() );
(void)KStdAction::preferences( this, SLOT(slotConfigure()), actionCollection() );
#if 0
(void)new KAction( i18n("Configure KWatchGnuPG..."), QString::fromLatin1("configure"),
0, this, SLOT( slotConfigure() ),
actionCollection(), "configure" );
#endif
}
void KWatchGnuPGMainWindow::startWatcher()
{
disconnect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
if( mWatcher->isRunning() ) {
mWatcher->kill();
while( mWatcher->isRunning() ) {
kapp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
}
mCentralWidget->append(tr("[%1] Log stopped")
.arg( QDateTime::currentDateTime().toString(Qt::ISODate)));
}
mWatcher->clearArguments();
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
*mWatcher << config->readEntry("Executable", WATCHGNUPGBINARY);
*mWatcher << "--force";
*mWatcher << config->readEntry("Socket", WATCHGNUPGSOCKET);
config->setGroup(QString::null);
if( !mWatcher->start() ) {
KMessageBox::sorry( this, i18n("The watchgnupg logging process could not be started.\nPlease install watchgnupg somewhere in your $PATH.\nThis log window is now completely useless." ) );
} else {
mCentralWidget->append( tr("[%1] Log started")
.arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) );
}
connect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
}
void KWatchGnuPGMainWindow::setGnuPGConfig()
{
QStringList logclients;
// Get config object
Kleo::CryptoConfig* cconfig = Kleo::CryptoBackendFactory::instance()->config();
if ( !cconfig )
return;
//Q_ASSERT( cconfig );
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
QStringList comps = cconfig->componentList();
for( QStringList::const_iterator it = comps.begin(); it != comps.end(); ++it ) {
Kleo::CryptoConfigComponent* comp = cconfig->component( *it );
Q_ASSERT(comp);
// Look for log-file entry in Debug group
Kleo::CryptoConfigGroup* group = comp->group("Debug");
if( group ) {
Kleo::CryptoConfigEntry* entry = group->entry("log-file");
if( entry ) {
entry->setStringValue( QString("socket://")+
config->readEntry("Socket",
WATCHGNUPGSOCKET ));
logclients << QString("%1 (%2)").arg(*it).arg(comp->description());
}
entry = group->entry("debug-level");
if( entry ) {
entry->setStringValue( config->readEntry("LogLevel", "basic") );
}
}
}
cconfig->sync(true);
if( logclients.isEmpty() ) {
KMessageBox::sorry( 0, i18n("There are no components available that support logging." ) );
}
}
void KWatchGnuPGMainWindow::slotWatcherExited()
{
if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?") ) == KMessageBox::Yes ) {
mCentralWidget->append( i18n("====== Restarting logging process =====") );
startWatcher();
} else {
KMessageBox::sorry( this, i18n("The watchgnupg logging process is not running.\nThis log window is now completely useless." ) );
}
}
void KWatchGnuPGMainWindow::slotReadStdout()
{
if ( !mWatcher )
return;
QString str;
while( mWatcher->readln(str,false) > 0 ) {
mCentralWidget->append( str );
if( !isVisible() ) {
// Change tray icon to show something happened
// PENDING(steffen)
mSysTray->setAttention(true);
}
}
QTimer::singleShot( 0, this, SLOT(slotAckRead()) );
}
void KWatchGnuPGMainWindow::slotAckRead() {
if ( mWatcher )
mWatcher->ackRead();
}
void KWatchGnuPGMainWindow::show()
{
mSysTray->setAttention(false);
KMainWindow::show();
}
void KWatchGnuPGMainWindow::slotSaveAs()
{
QString filename = KFileDialog::getSaveFileName( QString::null, QString::null,
this, i18n("Save Log to File") );
if( filename.isEmpty() ) return;
QFile file(filename);
if( file.exists() ) {
if( KMessageBox::Yes !=
KMessageBox::warningYesNo( this, i18n("The file named \"%1\" already "
"exists. Are you sure you want "
"to overwrite it?").arg(filename),
i18n("Overwrite File") ) ) {
return;
}
}
if( file.open( IO_WriteOnly ) ) {
QTextStream st(&file);
st << mCentralWidget->text();
file.close();
}
}
void KWatchGnuPGMainWindow::slotQuit()
{
disconnect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
mWatcher->kill();
kapp->quit();
}
void KWatchGnuPGMainWindow::slotConfigure()
{
if( !mConfig ) {
mConfig = new KWatchGnuPGConfig( this, "config dialog" );
connect( mConfig, SIGNAL( reconfigure() ),
this, SLOT( slotReadConfig() ) );
}
mConfig->loadConfig();
mConfig->exec();
}
void KWatchGnuPGMainWindow::slotReadConfig()
{
KConfig* config = kapp->config();
config->setGroup("LogWindow");
mCentralWidget->setWordWrap( config->readBoolEntry("WordWrap", false)
?QTextEdit::WidgetWidth
:QTextEdit::NoWrap );
mCentralWidget->setMaxLogLines( config->readNumEntry( "MaxLogLen", 10000 ) );
setGnuPGConfig();
startWatcher();
}
bool KWatchGnuPGMainWindow::queryClose()
{
if ( !kapp->sessionSaving() ) {
hide();
return false;
}
return KMainWindow::queryClose();
}
#include "kwatchgnupgmainwin.moc"
<commit_msg>Allow to change shortcut<commit_after>/*
kwatchgnupgmainwin.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB
Kleopatra 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.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kwatchgnupgmainwin.h"
#include "kwatchgnupgconfig.h"
#include "tray.h"
#include <kleo/cryptobackendfactory.h>
#include <kleo/cryptoconfig.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kapplication.h>
#include <kaction.h>
#include <kstdaction.h>
#include <kprocio.h>
#include <kconfig.h>
#include <kfiledialog.h>
#include <qtextedit.h>
#include <qdir.h>
#include <qeventloop.h>
#include <qtimer.h>
#define WATCHGNUPGBINARY "watchgnupg"
#define WATCHGNUPGSOCKET ( QDir::home().canonicalPath() + "/.gnupg/log-socket")
KWatchGnuPGMainWindow::KWatchGnuPGMainWindow( QWidget* parent, const char* name )
: KMainWindow( parent, name, WType_TopLevel ), mConfig(0)
{
createActions();
createGUI();
mCentralWidget = new QTextEdit( this, "central log view" );
mCentralWidget->setTextFormat( QTextEdit::LogText );
setCentralWidget( mCentralWidget );
mWatcher = new KProcIO();
connect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
connect( mWatcher, SIGNAL( readReady(KProcIO*) ),
this, SLOT( slotReadStdout() ) );
slotReadConfig();
mSysTray = new KWatchGnuPGTray( this );
mSysTray->show();
connect( mSysTray, SIGNAL( quitSelected() ),
this, SLOT( slotQuit() ) );
setAutoSaveSettings();
}
KWatchGnuPGMainWindow::~KWatchGnuPGMainWindow()
{
delete mWatcher;
}
void KWatchGnuPGMainWindow::slotClear()
{
mCentralWidget->clear();
mCentralWidget->append( tr("[%1] Log cleared").arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) );
}
void KWatchGnuPGMainWindow::createActions()
{
(void)new KAction( i18n("C&lear History"), "history_clear", CTRL+Key_L,
this, SLOT( slotClear() ),
actionCollection(), "clear_log" );
(void)KStdAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() );
(void)KStdAction::close( this, SLOT(close()), actionCollection() );
(void)KStdAction::quit( this, SLOT(slotQuit()), actionCollection() );
(void)KStdAction::preferences( this, SLOT(slotConfigure()), actionCollection() );
( void )KStdAction::keyBindings(guiFactory(), SLOT(configureShortcuts()), actionCollection());
#if 0
(void)new KAction( i18n("Configure KWatchGnuPG..."), QString::fromLatin1("configure"),
0, this, SLOT( slotConfigure() ),
actionCollection(), "configure" );
#endif
}
void KWatchGnuPGMainWindow::startWatcher()
{
disconnect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
if( mWatcher->isRunning() ) {
mWatcher->kill();
while( mWatcher->isRunning() ) {
kapp->eventLoop()->processEvents(QEventLoop::ExcludeUserInput);
}
mCentralWidget->append(tr("[%1] Log stopped")
.arg( QDateTime::currentDateTime().toString(Qt::ISODate)));
}
mWatcher->clearArguments();
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
*mWatcher << config->readEntry("Executable", WATCHGNUPGBINARY);
*mWatcher << "--force";
*mWatcher << config->readEntry("Socket", WATCHGNUPGSOCKET);
config->setGroup(QString::null);
if( !mWatcher->start() ) {
KMessageBox::sorry( this, i18n("The watchgnupg logging process could not be started.\nPlease install watchgnupg somewhere in your $PATH.\nThis log window is now completely useless." ) );
} else {
mCentralWidget->append( tr("[%1] Log started")
.arg( QDateTime::currentDateTime().toString(Qt::ISODate) ) );
}
connect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
}
void KWatchGnuPGMainWindow::setGnuPGConfig()
{
QStringList logclients;
// Get config object
Kleo::CryptoConfig* cconfig = Kleo::CryptoBackendFactory::instance()->config();
if ( !cconfig )
return;
//Q_ASSERT( cconfig );
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
QStringList comps = cconfig->componentList();
for( QStringList::const_iterator it = comps.begin(); it != comps.end(); ++it ) {
Kleo::CryptoConfigComponent* comp = cconfig->component( *it );
Q_ASSERT(comp);
// Look for log-file entry in Debug group
Kleo::CryptoConfigGroup* group = comp->group("Debug");
if( group ) {
Kleo::CryptoConfigEntry* entry = group->entry("log-file");
if( entry ) {
entry->setStringValue( QString("socket://")+
config->readEntry("Socket",
WATCHGNUPGSOCKET ));
logclients << QString("%1 (%2)").arg(*it).arg(comp->description());
}
entry = group->entry("debug-level");
if( entry ) {
entry->setStringValue( config->readEntry("LogLevel", "basic") );
}
}
}
cconfig->sync(true);
if( logclients.isEmpty() ) {
KMessageBox::sorry( 0, i18n("There are no components available that support logging." ) );
}
}
void KWatchGnuPGMainWindow::slotWatcherExited()
{
if( KMessageBox::questionYesNo( this, i18n("The watchgnupg logging process died.\nDo you want to try to restart it?") ) == KMessageBox::Yes ) {
mCentralWidget->append( i18n("====== Restarting logging process =====") );
startWatcher();
} else {
KMessageBox::sorry( this, i18n("The watchgnupg logging process is not running.\nThis log window is now completely useless." ) );
}
}
void KWatchGnuPGMainWindow::slotReadStdout()
{
if ( !mWatcher )
return;
QString str;
while( mWatcher->readln(str,false) > 0 ) {
mCentralWidget->append( str );
if( !isVisible() ) {
// Change tray icon to show something happened
// PENDING(steffen)
mSysTray->setAttention(true);
}
}
QTimer::singleShot( 0, this, SLOT(slotAckRead()) );
}
void KWatchGnuPGMainWindow::slotAckRead() {
if ( mWatcher )
mWatcher->ackRead();
}
void KWatchGnuPGMainWindow::show()
{
mSysTray->setAttention(false);
KMainWindow::show();
}
void KWatchGnuPGMainWindow::slotSaveAs()
{
QString filename = KFileDialog::getSaveFileName( QString::null, QString::null,
this, i18n("Save Log to File") );
if( filename.isEmpty() ) return;
QFile file(filename);
if( file.exists() ) {
if( KMessageBox::Yes !=
KMessageBox::warningYesNo( this, i18n("The file named \"%1\" already "
"exists. Are you sure you want "
"to overwrite it?").arg(filename),
i18n("Overwrite File") ) ) {
return;
}
}
if( file.open( IO_WriteOnly ) ) {
QTextStream st(&file);
st << mCentralWidget->text();
file.close();
}
}
void KWatchGnuPGMainWindow::slotQuit()
{
disconnect( mWatcher, SIGNAL( processExited(KProcess*) ),
this, SLOT( slotWatcherExited() ) );
mWatcher->kill();
kapp->quit();
}
void KWatchGnuPGMainWindow::slotConfigure()
{
if( !mConfig ) {
mConfig = new KWatchGnuPGConfig( this, "config dialog" );
connect( mConfig, SIGNAL( reconfigure() ),
this, SLOT( slotReadConfig() ) );
}
mConfig->loadConfig();
mConfig->exec();
}
void KWatchGnuPGMainWindow::slotReadConfig()
{
KConfig* config = kapp->config();
config->setGroup("LogWindow");
mCentralWidget->setWordWrap( config->readBoolEntry("WordWrap", false)
?QTextEdit::WidgetWidth
:QTextEdit::NoWrap );
mCentralWidget->setMaxLogLines( config->readNumEntry( "MaxLogLen", 10000 ) );
setGnuPGConfig();
startWatcher();
}
bool KWatchGnuPGMainWindow::queryClose()
{
if ( !kapp->sessionSaving() ) {
hide();
return false;
}
return KMainWindow::queryClose();
}
#include "kwatchgnupgmainwin.moc"
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Modules/Legacy/Matlab/DataIO/ImportDatatypesFromMatlab.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/String.h>
#include <Testing/ModuleTestBase/ModuleTestBase.h>
using namespace SCIRun;
using namespace SCIRun::Testing;
using namespace SCIRun::Modules::Matlab::DataIO;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Dataflow::Networks;
// using ::testing::_;
// using ::testing::NiceMock;
// using ::testing::DefaultValue;
// using ::testing::Return;
class ImportDatatypesFromMatlabModuleTest : public ModuleTest
{
};
TEST_F(ImportDatatypesFromMatlabModuleTest, ThrowsForNullInput)
{
auto csdf = makeModule("ImportDatatypesFromMatlab");
StringHandle nullField;
stubPortNWithThisData(csdf, 0, nullField);
EXPECT_THROW(csdf->execute(), NullHandleOnPortException);
}
TEST_F(ImportDatatypesFromMatlabModuleTest, DISABLED_Foo)
{
FAIL() << "TODO";
}<commit_msg>Disable test<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Modules/Legacy/Matlab/DataIO/ImportDatatypesFromMatlab.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/String.h>
#include <Testing/ModuleTestBase/ModuleTestBase.h>
using namespace SCIRun;
using namespace SCIRun::Testing;
using namespace SCIRun::Modules::Matlab::DataIO;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Dataflow::Networks;
// using ::testing::_;
// using ::testing::NiceMock;
// using ::testing::DefaultValue;
// using ::testing::Return;
class ImportDatatypesFromMatlabModuleTest : public ModuleTest
{
};
TEST_F(ImportDatatypesFromMatlabModuleTest, DISABLED_ThrowsForNullInput)
{
auto csdf = makeModule("ImportDatatypesFromMatlab");
StringHandle nullField;
stubPortNWithThisData(csdf, 0, nullField);
EXPECT_THROW(csdf->execute(), NullHandleOnPortException);
}
TEST_F(ImportDatatypesFromMatlabModuleTest, DISABLED_Foo)
{
FAIL() << "TODO";
}<|endoftext|> |
<commit_before>//===-- RTDyldMemoryManager.cpp - Memory manager for MC-JIT -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation of the runtime dynamic memory manager base class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
#include <cstdlib>
#ifdef __linux__
// These includes used by RTDyldMemoryManager::getPointerToNamedFunction()
// for Glibc trickery. See comments in this function for more information.
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#include <fcntl.h>
#include <unistd.h>
#endif
namespace llvm {
RTDyldMemoryManager::~RTDyldMemoryManager() {}
// Determine whether we can register EH tables.
#if (defined(__GNUC__) && !defined(__ARM_EABI__) && !defined(__ia64__) && \
!defined(__SEH__) && !defined(__USING_SJLJ_EXCEPTIONS__))
#define HAVE_EHTABLE_SUPPORT 1
#else
#define HAVE_EHTABLE_SUPPORT 0
#endif
#if HAVE_EHTABLE_SUPPORT
extern "C" void __register_frame(void*);
extern "C" void __deregister_frame(void*);
#else
// The building compiler does not have __(de)register_frame but
// it may be found at runtime in a dynamically-loaded library.
// For example, this happens when building LLVM with Visual C++
// but using the MingW runtime.
void __register_frame(void *p) {
static bool Searched = false;
static void *rf = 0;
if (!Searched) {
Searched = true;
rf = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(
"__register_frame");
}
if (rf)
((void (*)(void *))rf)(p);
}
void __deregister_frame(void *p) {
static bool Searched = false;
static void *df = 0;
if (!Searched) {
Searched = true;
df = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(
"__deregister_frame");
}
if (df)
((void (*)(void *))df)(p);
}
#endif
#ifdef __APPLE__
static const char *processFDE(const char *Entry, bool isDeregister) {
const char *P = Entry;
uint32_t Length = *((const uint32_t *)P);
P += 4;
uint32_t Offset = *((const uint32_t *)P);
if (Offset != 0) {
if (isDeregister)
__deregister_frame(const_cast<char *>(Entry));
else
__register_frame(const_cast<char *>(Entry));
}
return P + Length;
}
// This implementation handles frame registration for local targets.
// Memory managers for remote targets should re-implement this function
// and use the LoadAddr parameter.
void RTDyldMemoryManager::registerEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
// On OS X OS X __register_frame takes a single FDE as an argument.
// See http://lists.cs.uiuc.edu/pipermail/llvmdev/2013-April/061768.html
const char *P = (const char *)Addr;
const char *End = P + Size;
do {
P = processFDE(P, false);
} while(P != End);
}
void RTDyldMemoryManager::deregisterEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
const char *P = (const char *)Addr;
const char *End = P + Size;
do {
P = processFDE(P, true);
} while(P != End);
}
#else
void RTDyldMemoryManager::registerEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
// On Linux __register_frame takes a single argument:
// a pointer to the start of the .eh_frame section.
// How can it find the end? Because crtendS.o is linked
// in and it has an .eh_frame section with four zero chars.
__register_frame(Addr);
}
void RTDyldMemoryManager::deregisterEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
__deregister_frame(Addr);
}
#endif
static int jit_noop() {
return 0;
}
// ARM math functions are statically linked on Android from libgcc.a, but not
// available at runtime for dynamic linking. On Linux these are usually placed
// in libgcc_s.so so can be found by normal dynamic lookup.
#if defined(__BIONIC__) && defined(__arm__)
// List of functions which are statically linked on Android and can be generated
// by LLVM. This is done as a nested macro which is used once to declare the
// imported functions with ARM_MATH_DECL and once to compare them to the
// user-requested symbol in getSymbolAddress with ARM_MATH_CHECK. The test
// assumes that all functions start with __aeabi_ and getSymbolAddress must be
// modified if that changes.
#define ARM_MATH_IMPORTS(PP) \
PP(__aeabi_d2f) \
PP(__aeabi_d2iz) \
PP(__aeabi_d2lz) \
PP(__aeabi_d2uiz) \
PP(__aeabi_d2ulz) \
PP(__aeabi_dadd) \
PP(__aeabi_dcmpeq) \
PP(__aeabi_dcmpge) \
PP(__aeabi_dcmpgt) \
PP(__aeabi_dcmple) \
PP(__aeabi_dcmplt) \
PP(__aeabi_dcmpun) \
PP(__aeabi_ddiv) \
PP(__aeabi_dmul) \
PP(__aeabi_dsub) \
PP(__aeabi_f2d) \
PP(__aeabi_f2iz) \
PP(__aeabi_f2lz) \
PP(__aeabi_f2uiz) \
PP(__aeabi_f2ulz) \
PP(__aeabi_fadd) \
PP(__aeabi_fcmpeq) \
PP(__aeabi_fcmpge) \
PP(__aeabi_fcmpgt) \
PP(__aeabi_fcmple) \
PP(__aeabi_fcmplt) \
PP(__aeabi_fcmpun) \
PP(__aeabi_fdiv) \
PP(__aeabi_fmul) \
PP(__aeabi_fsub) \
PP(__aeabi_i2d) \
PP(__aeabi_i2f) \
PP(__aeabi_idiv) \
PP(__aeabi_idivmod) \
PP(__aeabi_l2d) \
PP(__aeabi_l2f) \
PP(__aeabi_lasr) \
PP(__aeabi_ldivmod) \
PP(__aeabi_llsl) \
PP(__aeabi_llsr) \
PP(__aeabi_lmul) \
PP(__aeabi_ui2d) \
PP(__aeabi_ui2f) \
PP(__aeabi_uidiv) \
PP(__aeabi_uidivmod) \
PP(__aeabi_ul2d) \
PP(__aeabi_ul2f) \
PP(__aeabi_uldivmod)
// Declare statically linked math functions on ARM. The function declarations
// here do not have the correct prototypes for each function in
// ARM_MATH_IMPORTS, but it doesn't matter because only the symbol addresses are
// needed. In particular the __aeabi_*divmod functions do not have calling
// conventions which match any C prototype.
#define ARM_MATH_DECL(name) extern "C" void name();
ARM_MATH_IMPORTS(ARM_MATH_DECL)
#undef ARM_MATH_DECL
#endif
#if defined(__linux__) && defined(__GLIBC__) && \
(defined(__i386__) || defined(__x86_64__))
extern "C" void __morestack();
#endif
uint64_t
RTDyldMemoryManager::getSymbolAddressInProcess(const std::string &Name) {
// This implementation assumes that the host program is the target.
// Clients generating code for a remote target should implement their own
// memory manager.
#if defined(__linux__) && defined(__GLIBC__)
//===--------------------------------------------------------------------===//
// Function stubs that are invoked instead of certain library calls
//
// Force the following functions to be linked in to anything that uses the
// JIT. This is a hack designed to work around the all-too-clever Glibc
// strategy of making these functions work differently when inlined vs. when
// not inlined, and hiding their real definitions in a separate archive file
// that the dynamic linker can't see. For more info, search for
// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
if (Name == "stat") return (uint64_t)&stat;
if (Name == "fstat") return (uint64_t)&fstat;
if (Name == "lstat") return (uint64_t)&lstat;
if (Name == "stat64") return (uint64_t)&stat64;
if (Name == "fstat64") return (uint64_t)&fstat64;
if (Name == "lstat64") return (uint64_t)&lstat64;
if (Name == "atexit") return (uint64_t)&atexit;
if (Name == "mknod") return (uint64_t)&mknod;
#if defined(__i386__) || defined(__x86_64__)
// __morestack lives in libgcc, a static library.
if (Name == "__morestack") return (uint64_t)&__morestack;
#endif
#endif // __linux__ && __GLIBC__
// See ARM_MATH_IMPORTS definition for explanation
#if defined(__BIONIC__) && defined(__arm__)
if (Name.compare(0, 8, "__aeabi_") == 0) {
// Check if the user has requested any of the functions listed in
// ARM_MATH_IMPORTS, and if so redirect to the statically linked symbol.
#define ARM_MATH_CHECK(fn) if (Name == #fn) return (uint64_t)&fn;
ARM_MATH_IMPORTS(ARM_MATH_CHECK)
#undef ARM_MATH_CHECK
}
#endif
// We should not invoke parent's ctors/dtors from generated main()!
// On Mingw and Cygwin, the symbol __main is resolved to
// callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
// (and register wrong callee's dtors with atexit(3)).
// We expect ExecutionEngine::runStaticConstructorsDestructors()
// is called before ExecutionEngine::runFunctionAsMain() is called.
if (Name == "__main") return (uint64_t)&jit_noop;
// Try to demangle Name before looking it up in the process, otherwise symbol
// '_<Name>' (if present) will shadow '<Name>', and there will be no way to
// refer to the latter.
const char *NameStr = Name.c_str();
if (NameStr[0] == '_')
if (void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr + 1))
return (uint64_t)Ptr;
// If we Name did not require demangling, or we failed to find the demangled
// name, try again without demangling.
return (uint64_t)sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
}
void *RTDyldMemoryManager::getPointerToNamedFunction(const std::string &Name,
bool AbortOnFailure) {
uint64_t Addr = getSymbolAddress(Name);
if (!Addr && AbortOnFailure)
report_fatal_error("Program used external function '" + Name +
"' which could not be resolved!");
return (void*)Addr;
}
} // namespace llvm
<commit_msg>RTDyldMemoryManager.cpp: Make the reference to __morestack weak.<commit_after>//===-- RTDyldMemoryManager.cpp - Memory manager for MC-JIT -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation of the runtime dynamic memory manager base class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
#include <cstdlib>
#ifdef __linux__
// These includes used by RTDyldMemoryManager::getPointerToNamedFunction()
// for Glibc trickery. See comments in this function for more information.
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#include <fcntl.h>
#include <unistd.h>
#endif
namespace llvm {
RTDyldMemoryManager::~RTDyldMemoryManager() {}
// Determine whether we can register EH tables.
#if (defined(__GNUC__) && !defined(__ARM_EABI__) && !defined(__ia64__) && \
!defined(__SEH__) && !defined(__USING_SJLJ_EXCEPTIONS__))
#define HAVE_EHTABLE_SUPPORT 1
#else
#define HAVE_EHTABLE_SUPPORT 0
#endif
#if HAVE_EHTABLE_SUPPORT
extern "C" void __register_frame(void*);
extern "C" void __deregister_frame(void*);
#else
// The building compiler does not have __(de)register_frame but
// it may be found at runtime in a dynamically-loaded library.
// For example, this happens when building LLVM with Visual C++
// but using the MingW runtime.
void __register_frame(void *p) {
static bool Searched = false;
static void *rf = 0;
if (!Searched) {
Searched = true;
rf = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(
"__register_frame");
}
if (rf)
((void (*)(void *))rf)(p);
}
void __deregister_frame(void *p) {
static bool Searched = false;
static void *df = 0;
if (!Searched) {
Searched = true;
df = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(
"__deregister_frame");
}
if (df)
((void (*)(void *))df)(p);
}
#endif
#ifdef __APPLE__
static const char *processFDE(const char *Entry, bool isDeregister) {
const char *P = Entry;
uint32_t Length = *((const uint32_t *)P);
P += 4;
uint32_t Offset = *((const uint32_t *)P);
if (Offset != 0) {
if (isDeregister)
__deregister_frame(const_cast<char *>(Entry));
else
__register_frame(const_cast<char *>(Entry));
}
return P + Length;
}
// This implementation handles frame registration for local targets.
// Memory managers for remote targets should re-implement this function
// and use the LoadAddr parameter.
void RTDyldMemoryManager::registerEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
// On OS X OS X __register_frame takes a single FDE as an argument.
// See http://lists.cs.uiuc.edu/pipermail/llvmdev/2013-April/061768.html
const char *P = (const char *)Addr;
const char *End = P + Size;
do {
P = processFDE(P, false);
} while(P != End);
}
void RTDyldMemoryManager::deregisterEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
const char *P = (const char *)Addr;
const char *End = P + Size;
do {
P = processFDE(P, true);
} while(P != End);
}
#else
void RTDyldMemoryManager::registerEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
// On Linux __register_frame takes a single argument:
// a pointer to the start of the .eh_frame section.
// How can it find the end? Because crtendS.o is linked
// in and it has an .eh_frame section with four zero chars.
__register_frame(Addr);
}
void RTDyldMemoryManager::deregisterEHFrames(uint8_t *Addr,
uint64_t LoadAddr,
size_t Size) {
__deregister_frame(Addr);
}
#endif
static int jit_noop() {
return 0;
}
// ARM math functions are statically linked on Android from libgcc.a, but not
// available at runtime for dynamic linking. On Linux these are usually placed
// in libgcc_s.so so can be found by normal dynamic lookup.
#if defined(__BIONIC__) && defined(__arm__)
// List of functions which are statically linked on Android and can be generated
// by LLVM. This is done as a nested macro which is used once to declare the
// imported functions with ARM_MATH_DECL and once to compare them to the
// user-requested symbol in getSymbolAddress with ARM_MATH_CHECK. The test
// assumes that all functions start with __aeabi_ and getSymbolAddress must be
// modified if that changes.
#define ARM_MATH_IMPORTS(PP) \
PP(__aeabi_d2f) \
PP(__aeabi_d2iz) \
PP(__aeabi_d2lz) \
PP(__aeabi_d2uiz) \
PP(__aeabi_d2ulz) \
PP(__aeabi_dadd) \
PP(__aeabi_dcmpeq) \
PP(__aeabi_dcmpge) \
PP(__aeabi_dcmpgt) \
PP(__aeabi_dcmple) \
PP(__aeabi_dcmplt) \
PP(__aeabi_dcmpun) \
PP(__aeabi_ddiv) \
PP(__aeabi_dmul) \
PP(__aeabi_dsub) \
PP(__aeabi_f2d) \
PP(__aeabi_f2iz) \
PP(__aeabi_f2lz) \
PP(__aeabi_f2uiz) \
PP(__aeabi_f2ulz) \
PP(__aeabi_fadd) \
PP(__aeabi_fcmpeq) \
PP(__aeabi_fcmpge) \
PP(__aeabi_fcmpgt) \
PP(__aeabi_fcmple) \
PP(__aeabi_fcmplt) \
PP(__aeabi_fcmpun) \
PP(__aeabi_fdiv) \
PP(__aeabi_fmul) \
PP(__aeabi_fsub) \
PP(__aeabi_i2d) \
PP(__aeabi_i2f) \
PP(__aeabi_idiv) \
PP(__aeabi_idivmod) \
PP(__aeabi_l2d) \
PP(__aeabi_l2f) \
PP(__aeabi_lasr) \
PP(__aeabi_ldivmod) \
PP(__aeabi_llsl) \
PP(__aeabi_llsr) \
PP(__aeabi_lmul) \
PP(__aeabi_ui2d) \
PP(__aeabi_ui2f) \
PP(__aeabi_uidiv) \
PP(__aeabi_uidivmod) \
PP(__aeabi_ul2d) \
PP(__aeabi_ul2f) \
PP(__aeabi_uldivmod)
// Declare statically linked math functions on ARM. The function declarations
// here do not have the correct prototypes for each function in
// ARM_MATH_IMPORTS, but it doesn't matter because only the symbol addresses are
// needed. In particular the __aeabi_*divmod functions do not have calling
// conventions which match any C prototype.
#define ARM_MATH_DECL(name) extern "C" void name();
ARM_MATH_IMPORTS(ARM_MATH_DECL)
#undef ARM_MATH_DECL
#endif
#if defined(__linux__) && defined(__GLIBC__) && \
(defined(__i386__) || defined(__x86_64__))
extern "C" LLVM_ATTRIBUTE_WEAK void __morestack();
#endif
uint64_t
RTDyldMemoryManager::getSymbolAddressInProcess(const std::string &Name) {
// This implementation assumes that the host program is the target.
// Clients generating code for a remote target should implement their own
// memory manager.
#if defined(__linux__) && defined(__GLIBC__)
//===--------------------------------------------------------------------===//
// Function stubs that are invoked instead of certain library calls
//
// Force the following functions to be linked in to anything that uses the
// JIT. This is a hack designed to work around the all-too-clever Glibc
// strategy of making these functions work differently when inlined vs. when
// not inlined, and hiding their real definitions in a separate archive file
// that the dynamic linker can't see. For more info, search for
// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
if (Name == "stat") return (uint64_t)&stat;
if (Name == "fstat") return (uint64_t)&fstat;
if (Name == "lstat") return (uint64_t)&lstat;
if (Name == "stat64") return (uint64_t)&stat64;
if (Name == "fstat64") return (uint64_t)&fstat64;
if (Name == "lstat64") return (uint64_t)&lstat64;
if (Name == "atexit") return (uint64_t)&atexit;
if (Name == "mknod") return (uint64_t)&mknod;
#if defined(__i386__) || defined(__x86_64__)
// __morestack lives in libgcc, a static library.
if (&__morestack && Name == "__morestack")
return (uint64_t)&__morestack;
#endif
#endif // __linux__ && __GLIBC__
// See ARM_MATH_IMPORTS definition for explanation
#if defined(__BIONIC__) && defined(__arm__)
if (Name.compare(0, 8, "__aeabi_") == 0) {
// Check if the user has requested any of the functions listed in
// ARM_MATH_IMPORTS, and if so redirect to the statically linked symbol.
#define ARM_MATH_CHECK(fn) if (Name == #fn) return (uint64_t)&fn;
ARM_MATH_IMPORTS(ARM_MATH_CHECK)
#undef ARM_MATH_CHECK
}
#endif
// We should not invoke parent's ctors/dtors from generated main()!
// On Mingw and Cygwin, the symbol __main is resolved to
// callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
// (and register wrong callee's dtors with atexit(3)).
// We expect ExecutionEngine::runStaticConstructorsDestructors()
// is called before ExecutionEngine::runFunctionAsMain() is called.
if (Name == "__main") return (uint64_t)&jit_noop;
// Try to demangle Name before looking it up in the process, otherwise symbol
// '_<Name>' (if present) will shadow '<Name>', and there will be no way to
// refer to the latter.
const char *NameStr = Name.c_str();
if (NameStr[0] == '_')
if (void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr + 1))
return (uint64_t)Ptr;
// If we Name did not require demangling, or we failed to find the demangled
// name, try again without demangling.
return (uint64_t)sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
}
void *RTDyldMemoryManager::getPointerToNamedFunction(const std::string &Name,
bool AbortOnFailure) {
uint64_t Addr = getSymbolAddress(Name);
if (!Addr && AbortOnFailure)
report_fatal_error("Program used external function '" + Name +
"' which could not be resolved!");
return (void*)Addr;
}
} // namespace llvm
<|endoftext|> |
<commit_before>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef IOSTR_HPP_
#define IOSTR_HPP_
#include <cstring>
#include <cerrno>
#include <cassert>
#include <cstdarg>
#include <ctime>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
////// prior declaration
template <class F, class S> extern
std::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p);
template <class T> extern
std::ostream& operator<< (std::ostream& ost, const std::vector<T>& v);
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <class Iter> inline
std::string str_join(Iter begin_, const Iter end_, const std::string& sep=",",
const unsigned int digits=std::cout.precision(), const bool fixed=false) {
if (begin_ == end_) return "";
std::ostringstream oss;
oss.precision(digits);
if (fixed) {oss << std::fixed;}
oss << *begin_;
while (++begin_ != end_) {oss << sep << *begin_;}
return oss.str();
}
template <class T> inline
std::string str_join(const T& v, const std::string& sep=",",
const unsigned int digits=std::cout.precision(), const bool fixed=false) {
return str_join(begin(v), end(v), sep, digits, fixed);
}
template <class T> inline
std::string str_matrix(const T& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
std::string s;
for (const auto& row: m) {
s += str_join(row, sep, digits);
s += '\n';
}
return s;
}
template <class T> inline
std::string str_map(const T& m, const unsigned int digits=std::cout.precision()) {
std::ostringstream oss;
oss.precision(digits);
oss << m;
return oss.str();
}
template <int N, class Iter> inline
std::string str_pairs(Iter begin_, const Iter end_, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
if (begin_ == end_) return "";
std::ostringstream oss;
oss.precision(digits);
oss << std::get<N>(*begin_);
while (++begin_ != end_) {oss << sep << std::get<N>(*begin_);}
return oss.str();
}
template <int N, class Map> inline
std::string str_pairs(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
return str_pairs<N>(begin(m), end(m), sep, digits);
}
template <class Map> inline
std::string str_pair_rows(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
std::string s = str_pairs<0>(m, sep, digits);
s += '\n';
s += str_pairs<1>(m, sep, digits);
return s += '\n';
}
template <class Map> inline
std::string str_pair_cols(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
std::ostringstream oss;
oss.precision(digits);
for (const auto& p: m) {
oss << std::get<0>(p) << sep << std::get<1>(p) << '\n';
}
return oss.str();
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
//// global operator
template <class F, class S> inline
std::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p) {
return ost << '(' << std::get<0>(p)
<< ": " << std::get<1>(p) << ')';
}
template <class T> inline
std::ostream& operator<< (std::ostream& ost, const std::vector<T>& v) {
return ost << '[' << wtl::str_join(v, ", ", ost.precision()) << ']';
}
template <> inline
std::ostream& operator<< (std::ostream& ost, const std::vector<std::string>& v) {
if (v.empty()) {return ost << "[]";}
return ost << "['" << wtl::str_join(v, "', '") << "']";
}
template <class T> inline
std::ostream& operator<< (std::ostream& ost, const std::set<T>& v) {
return ost << "set([" << wtl::str_join(v, ", ", ost.precision()) << "])";
}
// map
template <class Key, class T, class Comp> inline
std::ostream& operator<< (std::ostream& ost, const std::map<Key, T, Comp>& m) {
ost << '{';
if (!m.empty()) {
auto it(begin(m));
ost << std::get<0>(*it) << ": " << std::get<1>(*it);
while (++it != end(m)) {
ost << ", " << std::get<0>(*it) << ": " << std::get<1>(*it);
}
}
return ost << '}';
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
////// std::stringの操作
inline std::vector<std::string> split_algorithm(const std::string& src, const std::string& delimiter=" \t\n") {
std::vector<std::string> dst;
for (auto delim_pos=begin(src), start=delim_pos; delim_pos!=end(src); ) {
delim_pos = std::find_first_of(start, end(src), begin(delimiter), end(delimiter));
dst.push_back(std::string(start, delim_pos));
++(start = delim_pos);
}
return dst;
}
inline std::vector<std::string>
split(const std::string& src, const std::string& delimiter=" \t\n") {
std::vector<std::string> dst;
size_t start = 0, offset = 0;
while (true) {
offset = src.find_first_of(delimiter, start);
offset -= start;
dst.push_back(src.substr(start, offset));
start += offset;
if (start == src.npos) break;
++start;
}
return dst;
}
inline std::string rstrip(std::string src, const std::string& chars=" ") {
size_t pos(src.find_last_not_of(chars));
if (pos == std::string::npos) {
src.clear();
} else {
src.erase(++pos);
}
return src;
}
inline std::string lstrip(std::string src, const std::string& chars=" ") {
const size_t pos(src.find_first_not_of(chars));
if (pos == std::string::npos) {
src.clear();
} else {
src.erase(0, pos);
}
return src;
}
inline std::string strip(std::string src, const std::string& chars=" ") {
return rstrip(lstrip(src, chars), chars);
}
inline bool startswith(const std::string& full, const std::string& sub) {
const size_t full_size = full.size();
const size_t sub_size = sub.size();
if (full_size > sub_size) {
return full.compare(0, sub_size, sub) == 0;
} else {
return false;
}
}
inline bool endswith(const std::string& full, const std::string& sub) {
const size_t full_size = full.size();
const size_t sub_size = sub.size();
if (full_size > sub_size) {
return full.compare(full_size - sub_size, sub_size, sub) == 0;
} else {
return false;
}
}
inline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) {
std::string result;
std::string::size_type pos_before(0);
std::string::size_type pos(0);
std::string::size_type len(patt.size());
while ((pos = src.find(patt, pos)) != std::string::npos) {
result.append(src, pos_before, pos-pos_before);
result.append(repl);
pos += len;
pos_before = pos;
}
result.append(src, pos_before, src.size()-pos_before);
return result;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
inline std::string strprintf(const char* const format, ...) {
assert(format);
va_list args;
std::string buffer;
va_start(args, format);
const int length = std::vsnprintf(nullptr, 0, format, args) ;
va_end(args);
if (length < 0) throw std::runtime_error(format);
buffer.resize(length + 1);
va_start(args, format);
const int result = std::vsnprintf(&buffer[0], length + 1, format, args);
va_end(args);
if (result < 0) throw std::runtime_error(format);
buffer.pop_back();
return buffer;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// default is the same as ctime(): Thu Aug 23 14:55:02 2001
// which is equivalent to "%a %b %d %T %Y"
inline std::string strftime(const std::string& format="%c") {
char cstr[80];
const time_t rawtime = time(nullptr);
const struct tm* t = localtime(&rawtime);
std::strftime(cstr, sizeof(cstr), format.c_str(), t);
return std::string(cstr);
}
inline std::string iso8601date(const std::string& sep="-") {
std::ostringstream oss;
oss << "%Y" << sep << "%m" << sep << "%d";
return strftime(oss.str());
}
inline std::string iso8601time(const std::string& sep=":") {
std::ostringstream oss;
oss << "%H" << sep << "%M" << sep << "%S";
return strftime(oss.str());
}
inline std::string iso8601datetime() {return strftime("%FT%T%z");}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// fstream wrapper for binary mode and exceptions
class Fin: public std::ifstream{
public:
explicit Fin(
#ifdef BOOST_FILESYSTEM_PATH_HPP
const boost::filesystem::path& filepath,
#else
const std::string& filepath,
#endif
const std::ios::openmode mode = std::ios::in
)
: std::ifstream(filepath.c_str(), mode) {exceptions(std::ios::badbit);}
std::string readline(const char delimiter='\n') {
std::string buffer;
std::getline(*this, buffer, delimiter);
return buffer;
}
std::vector<std::string> readlines(const char delimiter='\n') {
std::vector<std::string> lines;
std::string buffer;
while (std::getline(*this, buffer, delimiter)) {
lines.push_back(buffer);
}
return lines;
}
std::string read(const char delimiter='\0') {return readline(delimiter);}
};
class Fout: public std::ofstream{
public:
Fout() = default;
explicit Fout(
#ifdef BOOST_FILESYSTEM_PATH_HPP
const boost::filesystem::path& filepath,
#else
const std::string& filepath,
#endif
const std::ios::openmode mode = std::ios::out
)
: std::ofstream(filepath.c_str(), mode) {exceptions(std::ios::failbit);}
template <class Iter>
Fout& writelines(Iter begin_, const Iter end_, const char sep='\n') {
if (begin_ == end_) return *this;
*this << *begin_;
while (++begin_ != end_) {*this << sep << *begin_;}
return *this;
}
template <class V>
Fout& writelines(const V& lines, const char sep='\n') {
return writelines(begin(lines), end(lines), sep);
}
};
// テーブル形式のファイルから二次元ベクタに格納
template <class T> inline
size_t read_matrix(T* dst, const std::string& filename, const std::string& dlms=",") {
std::vector<std::string> lines = Fin(filename).readlines();
dst->resize(lines.size());
auto dit = dst->begin();
for (auto sit=begin(lines); sit!=end(lines); ++dit, ++sit) {
split(&(*dit), *sit, dlms);
}
return dst->size();
}
inline std::vector<std::pair<std::string, std::string> > read_ini(const std::string& filename) {
std::vector<std::string> lines = Fin(filename).readlines();
std::vector<std::pair<std::string, std::string> > dst;
dst.reserve(lines.size());
for (auto line_: lines) {
line_ = strip(line_);
if (startswith(line_, "[")) {continue;} // TODO
auto pair_ = split(line_, ":="); // TODO
if (pair_.size() < 2) {continue;}
dst.emplace_back(rstrip(pair_[0]), lstrip(pair_[1]));
}
return dst;
}
////////////////////////////////////////////////////////////////////////////////
//// monipulator
inline std::ostream& LINE(std::ostream& stream) {
return stream << "----------------------------------------------------------------\n";
}
// << setw(x) << setfill('0') と同等だが、setfillは永続なので二回目以降は無駄がある
class fillzero{
public:
fillzero(const unsigned int x): digits_(x) {}
friend std::ostream& operator<<(std::ostream& stream, const fillzero& obj) {
return obj(stream);
}
private:
const unsigned int digits_;
std::ostream& operator()(std::ostream& stream) const {
stream.width(digits_);
stream.fill('0');
return stream;
}
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif /* IOSTR_HPP_ */
<commit_msg>Fin and Fout works always in binary mode (because of boost::serialization)<commit_after>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef IOSTR_HPP_
#define IOSTR_HPP_
#include <cstring>
#include <cerrno>
#include <cassert>
#include <cstdarg>
#include <ctime>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
////// prior declaration
template <class F, class S> extern
std::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p);
template <class T> extern
std::ostream& operator<< (std::ostream& ost, const std::vector<T>& v);
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <class Iter> inline
std::string str_join(Iter begin_, const Iter end_, const std::string& sep=",",
const unsigned int digits=std::cout.precision(), const bool fixed=false) {
if (begin_ == end_) return "";
std::ostringstream oss;
oss.precision(digits);
if (fixed) {oss << std::fixed;}
oss << *begin_;
while (++begin_ != end_) {oss << sep << *begin_;}
return oss.str();
}
template <class T> inline
std::string str_join(const T& v, const std::string& sep=",",
const unsigned int digits=std::cout.precision(), const bool fixed=false) {
return str_join(begin(v), end(v), sep, digits, fixed);
}
template <class T> inline
std::string str_matrix(const T& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
std::string s;
for (const auto& row: m) {
s += str_join(row, sep, digits);
s += '\n';
}
return s;
}
template <class T> inline
std::string str_map(const T& m, const unsigned int digits=std::cout.precision()) {
std::ostringstream oss;
oss.precision(digits);
oss << m;
return oss.str();
}
template <int N, class Iter> inline
std::string str_pairs(Iter begin_, const Iter end_, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
if (begin_ == end_) return "";
std::ostringstream oss;
oss.precision(digits);
oss << std::get<N>(*begin_);
while (++begin_ != end_) {oss << sep << std::get<N>(*begin_);}
return oss.str();
}
template <int N, class Map> inline
std::string str_pairs(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
return str_pairs<N>(begin(m), end(m), sep, digits);
}
template <class Map> inline
std::string str_pair_rows(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
std::string s = str_pairs<0>(m, sep, digits);
s += '\n';
s += str_pairs<1>(m, sep, digits);
return s += '\n';
}
template <class Map> inline
std::string str_pair_cols(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) {
std::ostringstream oss;
oss.precision(digits);
for (const auto& p: m) {
oss << std::get<0>(p) << sep << std::get<1>(p) << '\n';
}
return oss.str();
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
//// global operator
template <class F, class S> inline
std::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p) {
return ost << '(' << std::get<0>(p)
<< ": " << std::get<1>(p) << ')';
}
template <class T> inline
std::ostream& operator<< (std::ostream& ost, const std::vector<T>& v) {
return ost << '[' << wtl::str_join(v, ", ", ost.precision()) << ']';
}
template <> inline
std::ostream& operator<< (std::ostream& ost, const std::vector<std::string>& v) {
if (v.empty()) {return ost << "[]";}
return ost << "['" << wtl::str_join(v, "', '") << "']";
}
template <class T> inline
std::ostream& operator<< (std::ostream& ost, const std::set<T>& v) {
return ost << "set([" << wtl::str_join(v, ", ", ost.precision()) << "])";
}
// map
template <class Key, class T, class Comp> inline
std::ostream& operator<< (std::ostream& ost, const std::map<Key, T, Comp>& m) {
ost << '{';
if (!m.empty()) {
auto it(begin(m));
ost << std::get<0>(*it) << ": " << std::get<1>(*it);
while (++it != end(m)) {
ost << ", " << std::get<0>(*it) << ": " << std::get<1>(*it);
}
}
return ost << '}';
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
////// std::stringの操作
inline std::vector<std::string> split_algorithm(const std::string& src, const std::string& delimiter=" \t\n") {
std::vector<std::string> dst;
for (auto delim_pos=begin(src), start=delim_pos; delim_pos!=end(src); ) {
delim_pos = std::find_first_of(start, end(src), begin(delimiter), end(delimiter));
dst.push_back(std::string(start, delim_pos));
++(start = delim_pos);
}
return dst;
}
inline std::vector<std::string>
split(const std::string& src, const std::string& delimiter=" \t\n") {
std::vector<std::string> dst;
size_t start = 0, offset = 0;
while (true) {
offset = src.find_first_of(delimiter, start);
offset -= start;
dst.push_back(src.substr(start, offset));
start += offset;
if (start == src.npos) break;
++start;
}
return dst;
}
inline std::string rstrip(std::string src, const std::string& chars=" ") {
size_t pos(src.find_last_not_of(chars));
if (pos == std::string::npos) {
src.clear();
} else {
src.erase(++pos);
}
return src;
}
inline std::string lstrip(std::string src, const std::string& chars=" ") {
const size_t pos(src.find_first_not_of(chars));
if (pos == std::string::npos) {
src.clear();
} else {
src.erase(0, pos);
}
return src;
}
inline std::string strip(std::string src, const std::string& chars=" ") {
return rstrip(lstrip(src, chars), chars);
}
inline bool startswith(const std::string& full, const std::string& sub) {
const size_t full_size = full.size();
const size_t sub_size = sub.size();
if (full_size > sub_size) {
return full.compare(0, sub_size, sub) == 0;
} else {
return false;
}
}
inline bool endswith(const std::string& full, const std::string& sub) {
const size_t full_size = full.size();
const size_t sub_size = sub.size();
if (full_size > sub_size) {
return full.compare(full_size - sub_size, sub_size, sub) == 0;
} else {
return false;
}
}
inline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) {
std::string result;
std::string::size_type pos_before(0);
std::string::size_type pos(0);
std::string::size_type len(patt.size());
while ((pos = src.find(patt, pos)) != std::string::npos) {
result.append(src, pos_before, pos-pos_before);
result.append(repl);
pos += len;
pos_before = pos;
}
result.append(src, pos_before, src.size()-pos_before);
return result;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
inline std::string strprintf(const char* const format, ...) {
assert(format);
va_list args;
std::string buffer;
va_start(args, format);
const int length = std::vsnprintf(nullptr, 0, format, args) ;
va_end(args);
if (length < 0) throw std::runtime_error(format);
buffer.resize(length + 1);
va_start(args, format);
const int result = std::vsnprintf(&buffer[0], length + 1, format, args);
va_end(args);
if (result < 0) throw std::runtime_error(format);
buffer.pop_back();
return buffer;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// default is the same as ctime(): Thu Aug 23 14:55:02 2001
// which is equivalent to "%a %b %d %T %Y"
inline std::string strftime(const std::string& format="%c") {
char cstr[80];
const time_t rawtime = time(nullptr);
const struct tm* t = localtime(&rawtime);
std::strftime(cstr, sizeof(cstr), format.c_str(), t);
return std::string(cstr);
}
inline std::string iso8601date(const std::string& sep="-") {
std::ostringstream oss;
oss << "%Y" << sep << "%m" << sep << "%d";
return strftime(oss.str());
}
inline std::string iso8601time(const std::string& sep=":") {
std::ostringstream oss;
oss << "%H" << sep << "%M" << sep << "%S";
return strftime(oss.str());
}
inline std::string iso8601datetime() {return strftime("%FT%T%z");}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// fstream wrapper for binary mode and exceptions
// boost::serialization requires binary mode
class Fin: public std::ifstream{
public:
explicit Fin(
#ifdef BOOST_FILESYSTEM_PATH_HPP
const boost::filesystem::path& filepath,
#else
const std::string& filepath,
#endif
const std::ios::openmode mode=std::ios::in)
: std::ifstream(filepath.c_str(), mode | std::ios::binary)
{exceptions(std::ios::badbit);}
std::string readline(const char delimiter='\n') {
std::string buffer;
std::getline(*this, buffer, delimiter);
return buffer;
}
std::vector<std::string> readlines(const char delimiter='\n') {
std::vector<std::string> lines;
std::string buffer;
while (std::getline(*this, buffer, delimiter)) {
lines.push_back(buffer);
}
return lines;
}
std::string read(const char delimiter='\0') {return readline(delimiter);}
};
class Fout: public std::ofstream{
public:
Fout() = default;
explicit Fout(
#ifdef BOOST_FILESYSTEM_PATH_HPP
const boost::filesystem::path& filepath,
#else
const std::string& filepath,
#endif
const std::ios::openmode mode=std::ios::out)
: std::ofstream(filepath.c_str(), mode | std::ios::binary)
{exceptions(std::ios::failbit);}
template <class Iter>
Fout& writelines(Iter begin_, const Iter end_, const char sep='\n') {
if (begin_ == end_) return *this;
*this << *begin_;
while (++begin_ != end_) {*this << sep << *begin_;}
return *this;
}
template <class V>
Fout& writelines(const V& lines, const char sep='\n') {
return writelines(begin(lines), end(lines), sep);
}
};
// テーブル形式のファイルから二次元ベクタに格納
template <class T> inline
size_t read_matrix(T* dst, const std::string& filename, const std::string& dlms=",") {
std::vector<std::string> lines = Fin(filename).readlines();
dst->resize(lines.size());
auto dit = dst->begin();
for (auto sit=begin(lines); sit!=end(lines); ++dit, ++sit) {
split(&(*dit), *sit, dlms);
}
return dst->size();
}
inline std::vector<std::pair<std::string, std::string> > read_ini(const std::string& filename) {
std::vector<std::string> lines = Fin(filename).readlines();
std::vector<std::pair<std::string, std::string> > dst;
dst.reserve(lines.size());
for (auto line_: lines) {
line_ = strip(line_);
if (startswith(line_, "[")) {continue;} // TODO
auto pair_ = split(line_, ":="); // TODO
if (pair_.size() < 2) {continue;}
dst.emplace_back(rstrip(pair_[0]), lstrip(pair_[1]));
}
return dst;
}
////////////////////////////////////////////////////////////////////////////////
//// monipulator
inline std::ostream& LINE(std::ostream& stream) {
return stream << "----------------------------------------------------------------\n";
}
// << setw(x) << setfill('0') と同等だが、setfillは永続なので二回目以降は無駄がある
class fillzero{
public:
fillzero(const unsigned int x): digits_(x) {}
friend std::ostream& operator<<(std::ostream& stream, const fillzero& obj) {
return obj(stream);
}
private:
const unsigned int digits_;
std::ostream& operator()(std::ostream& stream) const {
stream.width(digits_);
stream.fill('0');
return stream;
}
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif /* IOSTR_HPP_ */
<|endoftext|> |
<commit_before>#include "xUnixTime.hpp"
#include "TimeSystem.hpp"
#include <iostream>
#include <fstream>
CPPUNIT_TEST_SUITE_REGISTRATION (xUnixTime);
using namespace Rinex3;
void xUnixTime :: setUp (void)
{
}
void xUnixTime :: setFromInfoTest (void)
{
UnixTime setFromInfo1;
UnixTime setFromInfo2;
UnixTime Compare(1350000,0,TimeSys::GPS);
TimeTag::IdToValue Id;
Id.insert(make_pair('U',"1350000"));
Id.insert(make_pair('u',"0"));
Id.insert(make_pair('P',"02"));
CPPUNIT_ASSERT(setFromInfo1.setFromInfo(Id));
CPPUNIT_ASSERT_EQUAL(setFromInfo1,Compare);
Id.erase('U');
CPPUNIT_ASSERT(setFromInfo2.setFromInfo(Id));
ofstream out("Logs/printfOutput");
out << setFromInfo1 << endl;
out << setFromInfo2 << endl;
}
void xUnixTime :: operatorTest (void)
{
UnixTime Compare(1350000, 100);
UnixTime LessThanSec(1340000, 100);
UnixTime LessThanMicroSec(1350000,0);
UnixTime CompareCopy(Compare);
UnixTime CompareCopy2;
CompareCopy2 = CompareCopy;
//Equality Assertion
CPPUNIT_ASSERT_EQUAL(Compare,CompareCopy);
//Non-equality Assertion
CPPUNIT_ASSERT(Compare != LessThanSec);
//Less than assertions
CPPUNIT_ASSERT(LessThanSec < Compare);
CPPUNIT_ASSERT(LessThanMicroSec < Compare);
CPPUNIT_ASSERT(!(Compare < LessThanSec));
//Greater than assertions
CPPUNIT_ASSERT(Compare > LessThanSec);
//Less than equals assertion
CPPUNIT_ASSERT(LessThanSec <= Compare);
CPPUNIT_ASSERT(CompareCopy <= Compare);
//Greater than equals assertion
CPPUNIT_ASSERT(Compare >= LessThanSec);
CPPUNIT_ASSERT(Compare >= CompareCopy);
CPPUNIT_ASSERT(Compare.isValid());
}
void xUnixTime :: resetTest (void)
{
UnixTime Compare(1350000,0,TimeSys::GPS);
CommonTime Test = Compare.convertToCommonTime();
UnixTime Test2;
Test2.convertFromCommonTime(Test);
CPPUNIT_ASSERT_EQUAL(Test2,Compare);
CPPUNIT_ASSERT_EQUAL(TimeSys::GPS,Compare.getTimeSystem());
CPPUNIT_ASSERT_EQUAL(1350000,(int)Compare.tv.tv_sec);
CPPUNIT_ASSERT_EQUAL(0,(int)Compare.tv.tv_usec);
Compare.reset();
CPPUNIT_ASSERT_EQUAL(TimeSys::Unknown,Compare.getTimeSystem());
CPPUNIT_ASSERT_EQUAL(0,(int)Compare.tv.tv_sec);
CPPUNIT_ASSERT_EQUAL(0,(int)Compare.tv.tv_usec);
}
void xUnixTime :: timeSystemTest (void)
{
UnixTime GPS1(1350000,0,TimeSys::GPS);
UnixTime GPS2(1340000,0,TimeSys::GPS);
UnixTime UTC1(1350000,0,TimeSys::UTC);
UnixTime UNKNOWN(1350000,0,TimeSys::Unknown);
UnixTime ANY(1350000,0,TimeSys::Any);
CPPUNIT_ASSERT(GPS1 != GPS2);
CPPUNIT_ASSERT_EQUAL(GPS1.getTimeSystem(),GPS2.getTimeSystem());
CPPUNIT_ASSERT(GPS1 != UTC1);
CPPUNIT_ASSERT(GPS1 != UNKNOWN);
CPPUNIT_ASSERT(GPS1.convertToCommonTime() > CommonTime::BEGINNING_OF_TIME);
CPPUNIT_ASSERT(CommonTime::BEGINNING_OF_TIME < GPS1);
CPPUNIT_ASSERT_EQUAL(GPS1,ANY);
CPPUNIT_ASSERT_EQUAL(UTC1,ANY);
CPPUNIT_ASSERT_EQUAL(UNKNOWN,ANY);
CPPUNIT_ASSERT(GPS2 != ANY);
CPPUNIT_ASSERT(GPS2 < GPS1);
CPPUNIT_ASSERT(GPS2 < ANY);
UNKNOWN.setTimeSystem(TimeSys::GPS);
CPPUNIT_ASSERT_EQUAL(UNKNOWN.getTimeSystem(),TimeSys::GPS);
}
void xUnixTime :: printfTest (void)
{
UnixTime GPS1(1350000,0,TimeSys::GPS);
UnixTime UTC1(1350000,0,TimeSys::UTC);
CPPUNIT_ASSERT_EQUAL(GPS1.printf("%07U %02u %02P"),(std::string)"1350000 00 [GPS]");
CPPUNIT_ASSERT_EQUAL(UTC1.printf("%07U %02u %02P"),(std::string)"1350000 00 [UTC]");
CPPUNIT_ASSERT_EQUAL(GPS1.printError("%07U %02u %02P"),(std::string)"ErrorBadTime ErrorBadTime ErrorBadTime");
CPPUNIT_ASSERT_EQUAL(UTC1.printError("%07U %02u %02P"),(std::string)"ErrorBadTime ErrorBadTime ErrorBadTime");
}
<commit_msg><commit_after>#include "xUnixTime.hpp"
#include "TimeSystem.hpp"
#include <iostream>
#include <fstream>
CPPUNIT_TEST_SUITE_REGISTRATION (xUnixTime);
using namespace gpstk;
void xUnixTime :: setUp (void)
{
}
void xUnixTime :: setFromInfoTest (void)
{
UnixTime setFromInfo1;
UnixTime setFromInfo2;
UnixTime Compare(1350000,0,TimeSystem::GPS);
TimeTag::IdToValue Id;
Id.insert(make_pair('U',"1350000"));
Id.insert(make_pair('u',"0"));
Id.insert(make_pair('P',"02"));
CPPUNIT_ASSERT(setFromInfo1.setFromInfo(Id));
CPPUNIT_ASSERT_EQUAL(setFromInfo1,Compare);
Id.erase('U');
CPPUNIT_ASSERT(setFromInfo2.setFromInfo(Id));
ofstream out("Logs/printfOutput");
out << setFromInfo1 << endl;
out << setFromInfo2 << endl;
}
void xUnixTime :: operatorTest (void)
{
UnixTime Compare(1350000, 100);
UnixTime LessThanSec(1340000, 100);
UnixTime LessThanMicroSec(1350000,0);
UnixTime CompareCopy(Compare);
UnixTime CompareCopy2;
CompareCopy2 = CompareCopy;
//Equality Assertion
CPPUNIT_ASSERT_EQUAL(Compare,CompareCopy);
//Non-equality Assertion
CPPUNIT_ASSERT(Compare != LessThanSec);
//Less than assertions
CPPUNIT_ASSERT(LessThanSec < Compare);
CPPUNIT_ASSERT(LessThanMicroSec < Compare);
CPPUNIT_ASSERT(!(Compare < LessThanSec));
//Greater than assertions
CPPUNIT_ASSERT(Compare > LessThanSec);
//Less than equals assertion
CPPUNIT_ASSERT(LessThanSec <= Compare);
CPPUNIT_ASSERT(CompareCopy <= Compare);
//Greater than equals assertion
CPPUNIT_ASSERT(Compare >= LessThanSec);
CPPUNIT_ASSERT(Compare >= CompareCopy);
CPPUNIT_ASSERT(Compare.isValid());
}
void xUnixTime :: resetTest (void)
{
UnixTime Compare(1350000,0,TimeSystem::GPS);
CommonTime Test = Compare.convertToCommonTime();
UnixTime Test2;
Test2.convertFromCommonTime(Test);
CPPUNIT_ASSERT_EQUAL(Test2,Compare);
CPPUNIT_ASSERT_EQUAL(TimeSystem::GPS,Compare.getTimeSystem());
CPPUNIT_ASSERT_EQUAL(1350000,(int)Compare.tv.tv_sec);
CPPUNIT_ASSERT_EQUAL(0,(int)Compare.tv.tv_usec);
Compare.reset();
CPPUNIT_ASSERT_EQUAL(TimeSystem::Unknown,Compare.getTimeSystem());
CPPUNIT_ASSERT_EQUAL(0,(int)Compare.tv.tv_sec);
CPPUNIT_ASSERT_EQUAL(0,(int)Compare.tv.tv_usec);
}
void xUnixTime :: timeSystemTest (void)
{
UnixTime GPS1(1350000,0,TimeSystem::GPS);
UnixTime GPS2(1340000,0,TimeSystem::GPS);
UnixTime UTC1(1350000,0,TimeSystem::UTC);
UnixTime UNKNOWN(1350000,0,TimeSystem::Unknown);
UnixTime ANY(1350000,0,TimeSystem::Any);
CPPUNIT_ASSERT(GPS1 != GPS2);
CPPUNIT_ASSERT_EQUAL(GPS1.getTimeSystem(),GPS2.getTimeSystem());
CPPUNIT_ASSERT(GPS1 != UTC1);
CPPUNIT_ASSERT(GPS1 != UNKNOWN);
CPPUNIT_ASSERT(GPS1.convertToCommonTime() > CommonTime::BEGINNING_OF_TIME);
CPPUNIT_ASSERT(CommonTime::BEGINNING_OF_TIME < GPS1);
CPPUNIT_ASSERT_EQUAL(GPS1,ANY);
CPPUNIT_ASSERT_EQUAL(UTC1,ANY);
CPPUNIT_ASSERT_EQUAL(UNKNOWN,ANY);
CPPUNIT_ASSERT(GPS2 != ANY);
CPPUNIT_ASSERT(GPS2 < GPS1);
CPPUNIT_ASSERT(GPS2 < ANY);
UNKNOWN.setTimeSystem(TimeSystem::GPS);
CPPUNIT_ASSERT_EQUAL(UNKNOWN.getTimeSystem(),TimeSystem::GPS);
}
void xUnixTime :: printfTest (void)
{
UnixTime GPS1(1350000,0,TimeSystem::GPS);
UnixTime UTC1(1350000,0,TimeSystem::UTC);
CPPUNIT_ASSERT_EQUAL(GPS1.printf("%07U %02u %02P"),(std::string)"1350000 00 GPS");
CPPUNIT_ASSERT_EQUAL(UTC1.printf("%07U %02u %02P"),(std::string)"1350000 00 UTC");
CPPUNIT_ASSERT_EQUAL(GPS1.printError("%07U %02u %02P"),(std::string)"ErrorBadTime ErrorBadTime ErrorBadTime");
CPPUNIT_ASSERT_EQUAL(UTC1.printError("%07U %02u %02P"),(std::string)"ErrorBadTime ErrorBadTime ErrorBadTime");
}
<|endoftext|> |
<commit_before>//===--- SILCombine -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing
// small combining operations/peepholes at the SIL level. It additionally
// performs dead code elimination when it initially adds instructions to the
// work queue in order to reduce compile time by not visiting trivially dead
// instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "SILCombiner.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumSimplified, "Number of instructions simplified");
STATISTIC(NumCombined, "Number of instructions combined");
STATISTIC(NumDeadInst, "Number of dead insts eliminated");
//===----------------------------------------------------------------------===//
// Utility Methods
//===----------------------------------------------------------------------===//
/// addReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we DCE instructions as we go, to avoid adding them to the
/// worklist (this significantly speeds up SILCombine on code where many
/// instructions are dead or constant).
void SILCombiner::addReachableCodeToWorklist(SILBasicBlock *BB) {
llvm::SmallVector<SILBasicBlock*, 256> Worklist;
llvm::SmallVector<SILInstruction*, 128> InstrsForSILCombineWorklist;
llvm::SmallPtrSet<SILBasicBlock*, 64> Visited;
Worklist.push_back(BB);
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second) continue;
for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
SILInstruction *Inst = &*BBI;
++BBI;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DEBUG(llvm::dbgs() << "SC: DCE: " << *Inst << '\n');
// We pass in false here since we need to signal to
// eraseInstFromFunction to not add this instruction's operands to the
// worklist since we have not initialized the worklist yet.
//
// The reason to just use a default argument here is that it allows us
// to centralize all instruction removal in SILCombine into this one
// function. This is important if we want to be able to update analyses
// in a clean manner.
eraseInstFromFunction(*Inst, BBI,
false /*Don't add operands to worklist*/);
continue;
}
InstrsForSILCombineWorklist.push_back(Inst);
}
// Recursively visit successors.
for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)
Worklist.push_back(*SI);
} while (!Worklist.empty());
// Once we've found all of the instructions to add to the worklist, add them
// in reverse order. This way SILCombine will visit from the top of the
// function down. This jives well with the way that it adds all uses of
// instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
addInitialGroup(InstrsForSILCombineWorklist);
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
void SILCombineWorklist::add(SILInstruction *I) {
if (!WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
return;
DEBUG(llvm::dbgs() << "SC: ADD: " << *I << '\n');
Worklist.push_back(I);
}
bool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {
MadeChange = false;
DEBUG(llvm::dbgs() << "\n\nSILCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
// Add reachable instructions to our worklist.
addReachableCodeToWorklist(&*F.begin());
// Process until we run out of items in our worklist.
while (!Worklist.isEmpty()) {
SILInstruction *I = Worklist.removeOne();
// When we erase an instruction, we use the map in the worklist to check if
// the instruction is in the worklist. If it is, we replace it with null
// instead of shifting all members of the worklist towards the front. This
// check makes sure that if we run into any such residual null pointers, we
// skip them.
if (I == 0)
continue;
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
DEBUG(llvm::dbgs() << "SC: DCE: " << *I << '\n');
eraseInstFromFunction(*I);
++NumDeadInst;
MadeChange = true;
continue;
}
// Check to see if we can instsimplify the instruction.
if (SILValue Result = simplifyInstruction(I)) {
++NumSimplified;
DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
<< " New = " << *Result.getDef() << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result.getDef(), 0, Result.getResultNumber());
// Push the new instruction and any users onto the worklist.
Worklist.addUsersToWorklist(Result.getDef());
eraseInstFromFunction(*I);
MadeChange = true;
continue;
}
// If we have reached this point, all attempts to do simple simplifications
// have failed. Prepare to SILCombine.
Builder.setInsertionPoint(I);
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(llvm::dbgs() << "SC: Visiting: " << OrigI << '\n');
if (SILInstruction *Result = visit(I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
assert(&*std::prev(SILBasicBlock::iterator(I)) == Result &&
"Expected new instruction inserted before existing instruction!");
DEBUG(llvm::dbgs() << "SC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.add(Result);
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
} else {
DEBUG(llvm::dbgs() << "SC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
eraseInstFromFunction(*I);
} else {
Worklist.add(I);
Worklist.addUsersToWorklist(I);
}
}
MadeChange = true;
}
// Our tracking list has been accumulating instructions created by the
// SILBuilder during this iteration. Go through the tracking list and add
// its contents to the worklist and then clear said list in preparation for
// the next iteration.
auto &TrackingList = *Builder.getTrackingList();
for (SILInstruction *I : TrackingList) {
if (!DeletedInstSet.count(I))
Worklist.add(I);
}
TrackingList.clear();
DeletedInstSet.clear();
}
Worklist.zap();
return MadeChange;
}
void SILCombineWorklist::addInitialGroup(ArrayRef<SILInstruction *> List) {
assert(Worklist.empty() && "Worklist must be empty to add initial group");
Worklist.reserve(List.size()+16);
WorklistMap.resize(List.size());
DEBUG(llvm::dbgs() << "SC: ADDING: " << List.size()
<< " instrs to worklist\n");
while (!List.empty()) {
SILInstruction *I = List.back();
List = List.slice(0, List.size()-1);
WorklistMap.insert(std::make_pair(I, Worklist.size()));
Worklist.push_back(I);
}
}
bool SILCombiner::runOnFunction(SILFunction &F) {
clear();
bool Changed = false;
// Perform iterations until we do not make any changes.
while (doOneIteration(F, Iteration)) {
Changed = true;
Iteration++;
}
// Cleanup the builder and return whether or not we made any changes.
return Changed;
}
// Insert the instruction New before instruction Old in Old's parent BB. Add
// New to the worklist.
SILInstruction *SILCombiner::insertNewInstBefore(SILInstruction *New,
SILInstruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
SILBasicBlock *BB = Old.getParent();
BB->insert(&Old, New); // Insert inst
Worklist.add(New);
return New;
}
// This method is to be used when an instruction is found to be dead,
// replaceable with another preexisting expression. Here we add all uses of I
// to the worklist, replace all uses of I with the new value, then return I,
// so that the combiner will know that I was modified.
SILInstruction *SILCombiner::replaceInstUsesWith(SILInstruction &I,
ValueBase *V) {
Worklist.addUsersToWorklist(&I); // Add all modified instrs to worklist.
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
I.replaceAllUsesWith(V);
return &I;
}
/// This is meant to be used when one is attempting to replace only one of the
/// results of I with a result of V.
SILInstruction *
SILCombiner::
replaceInstUsesWith(SILInstruction &I, ValueBase *V, unsigned IIndex,
unsigned VIndex) {
assert(IIndex < I.getNumTypes() && "Cannot have more results than "
"types.");
assert(VIndex < V->getNumTypes() && "Cannot have more results than "
"types.");
// Add all modified instrs to worklist.
Worklist.addUsersToWorklist(&I, IIndex);
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
SILValue(&I, IIndex).replaceAllUsesWith(SILValue(V, VIndex));
return &I;
}
// Some instructions can never be "trivially dead" due to side effects or
// producing a void value. In those cases, since we cannot rely on
// SILCombines trivially dead instruction DCE in order to delete the
// instruction, visit methods should use this method to delete the given
// instruction and upon completion of their peephole return the value returned
// by this method.
SILInstruction *SILCombiner::eraseInstFromFunction(SILInstruction &I,
SILBasicBlock::iterator &InstIter,
bool AddOperandsToWorklist) {
DEBUG(llvm::dbgs() << "SC: ERASE " << I << '\n');
assert(hasNoUsesExceptDebug(&I) && "Cannot erase instruction that is used!");
// Make sure that we reprocess all operands now that we reduced their
// use counts.
if (I.getNumOperands() < 8 && AddOperandsToWorklist)
for (auto &OpI : I.getAllOperands())
if (SILInstruction *Op = llvm::dyn_cast<SILInstruction>(&*OpI.get()))
Worklist.add(Op);
for (Operand *DU : getDebugUses(I))
Worklist.remove(DU->getUser());
Worklist.remove(&I);
eraseFromParentWithDebugInsts(&I, InstIter);
DeletedInstSet.insert(&I);
MadeChange = true;
return nullptr; // Don't do anything with I
}
//===----------------------------------------------------------------------===//
// Entry Points
//===----------------------------------------------------------------------===//
namespace {
class SILCombine : public SILFunctionTransform {
/// The entry point to the transformation.
void run() override {
auto *AA = PM->getAnalysis<AliasAnalysis>();
// Create a SILBuilder with a tracking list for newly added
// instructions, which we will periodically move to our worklist.
llvm::SmallVector<SILInstruction *, 64> TrackingList;
SILBuilder B(*getFunction(), &TrackingList);
SILCombiner Combiner(B, AA, getOptions().RemoveRuntimeAsserts);
bool Changed = Combiner.runOnFunction(*getFunction());
if (Changed) {
// Invalidate everything.
invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
}
}
StringRef getName() override { return "SIL Combine"; }
};
} // end anonymous namespace
SILTransform *swift::createSILCombine() {
return new SILCombine();
}
<commit_msg>SILCombine: add debug message. NFC.<commit_after>//===--- SILCombine -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A port of LLVM's InstCombine pass to SIL. Its main purpose is for performing
// small combining operations/peepholes at the SIL level. It additionally
// performs dead code elimination when it initially adds instructions to the
// work queue in order to reduce compile time by not visiting trivially dead
// instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-combine"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "SILCombiner.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumSimplified, "Number of instructions simplified");
STATISTIC(NumCombined, "Number of instructions combined");
STATISTIC(NumDeadInst, "Number of dead insts eliminated");
//===----------------------------------------------------------------------===//
// Utility Methods
//===----------------------------------------------------------------------===//
/// addReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we DCE instructions as we go, to avoid adding them to the
/// worklist (this significantly speeds up SILCombine on code where many
/// instructions are dead or constant).
void SILCombiner::addReachableCodeToWorklist(SILBasicBlock *BB) {
llvm::SmallVector<SILBasicBlock*, 256> Worklist;
llvm::SmallVector<SILInstruction*, 128> InstrsForSILCombineWorklist;
llvm::SmallPtrSet<SILBasicBlock*, 64> Visited;
Worklist.push_back(BB);
do {
BB = Worklist.pop_back_val();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB).second) continue;
for (SILBasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
SILInstruction *Inst = &*BBI;
++BBI;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DEBUG(llvm::dbgs() << "SC: DCE: " << *Inst << '\n');
// We pass in false here since we need to signal to
// eraseInstFromFunction to not add this instruction's operands to the
// worklist since we have not initialized the worklist yet.
//
// The reason to just use a default argument here is that it allows us
// to centralize all instruction removal in SILCombine into this one
// function. This is important if we want to be able to update analyses
// in a clean manner.
eraseInstFromFunction(*Inst, BBI,
false /*Don't add operands to worklist*/);
continue;
}
InstrsForSILCombineWorklist.push_back(Inst);
}
// Recursively visit successors.
for (auto SI = BB->succ_begin(), SE = BB->succ_end(); SI != SE; ++SI)
Worklist.push_back(*SI);
} while (!Worklist.empty());
// Once we've found all of the instructions to add to the worklist, add them
// in reverse order. This way SILCombine will visit from the top of the
// function down. This jives well with the way that it adds all uses of
// instructions to the worklist after doing a transformation, thus avoiding
// some N^2 behavior in pathological cases.
addInitialGroup(InstrsForSILCombineWorklist);
}
//===----------------------------------------------------------------------===//
// Implementation
//===----------------------------------------------------------------------===//
void SILCombineWorklist::add(SILInstruction *I) {
if (!WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
return;
DEBUG(llvm::dbgs() << "SC: ADD: " << *I << '\n');
Worklist.push_back(I);
}
bool SILCombiner::doOneIteration(SILFunction &F, unsigned Iteration) {
MadeChange = false;
DEBUG(llvm::dbgs() << "\n\nSILCOMBINE ITERATION #" << Iteration << " on "
<< F.getName() << "\n");
// Add reachable instructions to our worklist.
addReachableCodeToWorklist(&*F.begin());
// Process until we run out of items in our worklist.
while (!Worklist.isEmpty()) {
SILInstruction *I = Worklist.removeOne();
// When we erase an instruction, we use the map in the worklist to check if
// the instruction is in the worklist. If it is, we replace it with null
// instead of shifting all members of the worklist towards the front. This
// check makes sure that if we run into any such residual null pointers, we
// skip them.
if (I == 0)
continue;
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
DEBUG(llvm::dbgs() << "SC: DCE: " << *I << '\n');
eraseInstFromFunction(*I);
++NumDeadInst;
MadeChange = true;
continue;
}
// Check to see if we can instsimplify the instruction.
if (SILValue Result = simplifyInstruction(I)) {
++NumSimplified;
DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
<< " New = " << *Result.getDef() << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result.getDef(), 0, Result.getResultNumber());
// Push the new instruction and any users onto the worklist.
Worklist.addUsersToWorklist(Result.getDef());
eraseInstFromFunction(*I);
MadeChange = true;
continue;
}
// If we have reached this point, all attempts to do simple simplifications
// have failed. Prepare to SILCombine.
Builder.setInsertionPoint(I);
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(llvm::raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
DEBUG(llvm::dbgs() << "SC: Visiting: " << OrigI << '\n');
if (SILInstruction *Result = visit(I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
assert(&*std::prev(SILBasicBlock::iterator(I)) == Result &&
"Expected new instruction inserted before existing instruction!");
DEBUG(llvm::dbgs() << "SC: Old = " << *I << '\n'
<< " New = " << *Result << '\n');
// Everything uses the new instruction now.
replaceInstUsesWith(*I, Result);
// Push the new instruction and any users onto the worklist.
Worklist.add(Result);
Worklist.addUsersToWorklist(Result);
eraseInstFromFunction(*I);
} else {
DEBUG(llvm::dbgs() << "SC: Mod = " << OrigI << '\n'
<< " New = " << *I << '\n');
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
eraseInstFromFunction(*I);
} else {
Worklist.add(I);
Worklist.addUsersToWorklist(I);
}
}
MadeChange = true;
}
// Our tracking list has been accumulating instructions created by the
// SILBuilder during this iteration. Go through the tracking list and add
// its contents to the worklist and then clear said list in preparation for
// the next iteration.
auto &TrackingList = *Builder.getTrackingList();
for (SILInstruction *I : TrackingList) {
if (!DeletedInstSet.count(I))
Worklist.add(I);
}
TrackingList.clear();
DeletedInstSet.clear();
}
Worklist.zap();
return MadeChange;
}
void SILCombineWorklist::addInitialGroup(ArrayRef<SILInstruction *> List) {
assert(Worklist.empty() && "Worklist must be empty to add initial group");
Worklist.reserve(List.size()+16);
WorklistMap.resize(List.size());
DEBUG(llvm::dbgs() << "SC: ADDING: " << List.size()
<< " instrs to worklist\n");
while (!List.empty()) {
SILInstruction *I = List.back();
List = List.slice(0, List.size()-1);
WorklistMap.insert(std::make_pair(I, Worklist.size()));
Worklist.push_back(I);
}
}
bool SILCombiner::runOnFunction(SILFunction &F) {
clear();
bool Changed = false;
// Perform iterations until we do not make any changes.
while (doOneIteration(F, Iteration)) {
Changed = true;
Iteration++;
}
// Cleanup the builder and return whether or not we made any changes.
return Changed;
}
// Insert the instruction New before instruction Old in Old's parent BB. Add
// New to the worklist.
SILInstruction *SILCombiner::insertNewInstBefore(SILInstruction *New,
SILInstruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
SILBasicBlock *BB = Old.getParent();
BB->insert(&Old, New); // Insert inst
Worklist.add(New);
return New;
}
// This method is to be used when an instruction is found to be dead,
// replaceable with another preexisting expression. Here we add all uses of I
// to the worklist, replace all uses of I with the new value, then return I,
// so that the combiner will know that I was modified.
SILInstruction *SILCombiner::replaceInstUsesWith(SILInstruction &I,
ValueBase *V) {
Worklist.addUsersToWorklist(&I); // Add all modified instrs to worklist.
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
I.replaceAllUsesWith(V);
return &I;
}
/// This is meant to be used when one is attempting to replace only one of the
/// results of I with a result of V.
SILInstruction *
SILCombiner::
replaceInstUsesWith(SILInstruction &I, ValueBase *V, unsigned IIndex,
unsigned VIndex) {
assert(IIndex < I.getNumTypes() && "Cannot have more results than "
"types.");
assert(VIndex < V->getNumTypes() && "Cannot have more results than "
"types.");
// Add all modified instrs to worklist.
Worklist.addUsersToWorklist(&I, IIndex);
DEBUG(llvm::dbgs() << "SC: Replacing " << I << "\n"
" with " << *V << '\n');
SILValue(&I, IIndex).replaceAllUsesWith(SILValue(V, VIndex));
return &I;
}
// Some instructions can never be "trivially dead" due to side effects or
// producing a void value. In those cases, since we cannot rely on
// SILCombines trivially dead instruction DCE in order to delete the
// instruction, visit methods should use this method to delete the given
// instruction and upon completion of their peephole return the value returned
// by this method.
SILInstruction *SILCombiner::eraseInstFromFunction(SILInstruction &I,
SILBasicBlock::iterator &InstIter,
bool AddOperandsToWorklist) {
DEBUG(llvm::dbgs() << "SC: ERASE " << I << '\n');
assert(hasNoUsesExceptDebug(&I) && "Cannot erase instruction that is used!");
// Make sure that we reprocess all operands now that we reduced their
// use counts.
if (I.getNumOperands() < 8 && AddOperandsToWorklist) {
for (auto &OpI : I.getAllOperands()) {
if (SILInstruction *Op = llvm::dyn_cast<SILInstruction>(&*OpI.get())) {
DEBUG(llvm::dbgs() << "SC: add op " << *Op <<
" from erased inst to worklist\n");
Worklist.add(Op);
}
}
}
for (Operand *DU : getDebugUses(I))
Worklist.remove(DU->getUser());
Worklist.remove(&I);
eraseFromParentWithDebugInsts(&I, InstIter);
DeletedInstSet.insert(&I);
MadeChange = true;
return nullptr; // Don't do anything with I
}
//===----------------------------------------------------------------------===//
// Entry Points
//===----------------------------------------------------------------------===//
namespace {
class SILCombine : public SILFunctionTransform {
/// The entry point to the transformation.
void run() override {
auto *AA = PM->getAnalysis<AliasAnalysis>();
// Create a SILBuilder with a tracking list for newly added
// instructions, which we will periodically move to our worklist.
llvm::SmallVector<SILInstruction *, 64> TrackingList;
SILBuilder B(*getFunction(), &TrackingList);
SILCombiner Combiner(B, AA, getOptions().RemoveRuntimeAsserts);
bool Changed = Combiner.runOnFunction(*getFunction());
if (Changed) {
// Invalidate everything.
invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
}
}
StringRef getName() override { return "SIL Combine"; }
};
} // end anonymous namespace
SILTransform *swift::createSILCombine() {
return new SILCombine();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: LineChartType.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: bm $ $Date: 2004-01-26 09:12:52 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "LineChartType.hxx"
#include "PropertyHelper.hxx"
#include "algohelper.hxx"
#include "macros.hxx"
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_
#include <com/sun/star/chart2/CurveStyle.hpp>
#endif
using namespace ::com::sun::star;
using ::rtl::OUString;
using ::com::sun::star::beans::Property;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;
namespace
{
enum
{
PROP_LINECHARTTYPE_DIMENSION,
PROP_LINECHARTTYPE_CURVE_STYLE,
PROP_LINECHARTTYPE_CURVE_RESOLUTION,
PROP_LINECHARTTYPE_SPLINE_ORDER
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "Dimension" ),
PROP_LINECHARTTYPE_DIMENSION,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "CurveStyle" ),
PROP_LINECHARTTYPE_CURVE_STYLE,
::getCppuType( reinterpret_cast< const chart2::CurveStyle * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "CurveResolution" ),
PROP_LINECHARTTYPE_CURVE_RESOLUTION,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "SplineOrder" ),
PROP_LINECHARTTYPE_SPLINE_ORDER,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::helper::tPropertyValueMap & rOutMap )
{
// must match default in CTOR!
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_DIMENSION ));
rOutMap[ PROP_LINECHARTTYPE_DIMENSION ] =
uno::makeAny( sal_Int32( 2 ) );
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_CURVE_STYLE ));
rOutMap[ PROP_LINECHARTTYPE_CURVE_STYLE ] =
uno::makeAny( chart2::CurveStyle_LINES );
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_CURVE_RESOLUTION ));
rOutMap[ PROP_LINECHARTTYPE_CURVE_RESOLUTION ] =
uno::makeAny( sal_Int32( 20 ) );
// todo: check whether order 3 means polygons of order 3 or 2. (see
// http://www.people.nnov.ru/fractal/Splines/Basis.htm )
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_SPLINE_ORDER ));
rOutMap[ PROP_LINECHARTTYPE_SPLINE_ORDER ] =
uno::makeAny( sal_Int32( 3 ) );
}
const Sequence< Property > & lcl_GetPropertySequence()
{
static Sequence< Property > aPropSeq;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::helper::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::helper::VectorToSequence( aProperties );
}
return aPropSeq;
}
} // anonymous namespace
namespace chart
{
LineChartType::LineChartType(
sal_Int32 nDim /* = 2 */,
chart2::CurveStyle eCurveStyle /* chart2::CurveStyle_LINES */,
sal_Int32 nResolution /* = 20 */,
sal_Int32 nOrder /* = 3 */ ) :
ChartType( nDim )
{
if( eCurveStyle != chart2::CurveStyle_LINES )
setFastPropertyValue_NoBroadcast( PROP_LINECHARTTYPE_CURVE_STYLE,
uno::makeAny( eCurveStyle ));
if( nResolution != 20 )
setFastPropertyValue_NoBroadcast( PROP_LINECHARTTYPE_CURVE_RESOLUTION,
uno::makeAny( nResolution ));
if( nOrder != 3 )
setFastPropertyValue_NoBroadcast( PROP_LINECHARTTYPE_SPLINE_ORDER,
uno::makeAny( nOrder ));
}
LineChartType::~LineChartType()
{}
// ____ XChartType ____
::rtl::OUString SAL_CALL LineChartType::getChartType()
throw (uno::RuntimeException)
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.LineChart" ));
}
// ____ OPropertySet ____
uno::Any LineChartType::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static helper::tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
// initialize defaults
lcl_AddDefaultsToMap( aStaticDefaults );
}
helper::tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
// ____ OPropertySet ____
::cppu::IPropertyArrayHelper & SAL_CALL LineChartType::getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper( lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
LineChartType::getPropertySetInfo()
throw (uno::RuntimeException)
{
static uno::Reference< beans::XPropertySetInfo > xInfo;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
} // namespace chart
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.110); FILE MERGED 2005/09/05 18:43:22 rt 1.6.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LineChartType.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:21:00 $
*
* 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 "LineChartType.hxx"
#include "PropertyHelper.hxx"
#include "algohelper.hxx"
#include "macros.hxx"
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_
#include <com/sun/star/chart2/CurveStyle.hpp>
#endif
using namespace ::com::sun::star;
using ::rtl::OUString;
using ::com::sun::star::beans::Property;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;
namespace
{
enum
{
PROP_LINECHARTTYPE_DIMENSION,
PROP_LINECHARTTYPE_CURVE_STYLE,
PROP_LINECHARTTYPE_CURVE_RESOLUTION,
PROP_LINECHARTTYPE_SPLINE_ORDER
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "Dimension" ),
PROP_LINECHARTTYPE_DIMENSION,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "CurveStyle" ),
PROP_LINECHARTTYPE_CURVE_STYLE,
::getCppuType( reinterpret_cast< const chart2::CurveStyle * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "CurveResolution" ),
PROP_LINECHARTTYPE_CURVE_RESOLUTION,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
rOutProperties.push_back(
Property( C2U( "SplineOrder" ),
PROP_LINECHARTTYPE_SPLINE_ORDER,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::helper::tPropertyValueMap & rOutMap )
{
// must match default in CTOR!
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_DIMENSION ));
rOutMap[ PROP_LINECHARTTYPE_DIMENSION ] =
uno::makeAny( sal_Int32( 2 ) );
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_CURVE_STYLE ));
rOutMap[ PROP_LINECHARTTYPE_CURVE_STYLE ] =
uno::makeAny( chart2::CurveStyle_LINES );
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_CURVE_RESOLUTION ));
rOutMap[ PROP_LINECHARTTYPE_CURVE_RESOLUTION ] =
uno::makeAny( sal_Int32( 20 ) );
// todo: check whether order 3 means polygons of order 3 or 2. (see
// http://www.people.nnov.ru/fractal/Splines/Basis.htm )
OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINECHARTTYPE_SPLINE_ORDER ));
rOutMap[ PROP_LINECHARTTYPE_SPLINE_ORDER ] =
uno::makeAny( sal_Int32( 3 ) );
}
const Sequence< Property > & lcl_GetPropertySequence()
{
static Sequence< Property > aPropSeq;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::helper::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::helper::VectorToSequence( aProperties );
}
return aPropSeq;
}
} // anonymous namespace
namespace chart
{
LineChartType::LineChartType(
sal_Int32 nDim /* = 2 */,
chart2::CurveStyle eCurveStyle /* chart2::CurveStyle_LINES */,
sal_Int32 nResolution /* = 20 */,
sal_Int32 nOrder /* = 3 */ ) :
ChartType( nDim )
{
if( eCurveStyle != chart2::CurveStyle_LINES )
setFastPropertyValue_NoBroadcast( PROP_LINECHARTTYPE_CURVE_STYLE,
uno::makeAny( eCurveStyle ));
if( nResolution != 20 )
setFastPropertyValue_NoBroadcast( PROP_LINECHARTTYPE_CURVE_RESOLUTION,
uno::makeAny( nResolution ));
if( nOrder != 3 )
setFastPropertyValue_NoBroadcast( PROP_LINECHARTTYPE_SPLINE_ORDER,
uno::makeAny( nOrder ));
}
LineChartType::~LineChartType()
{}
// ____ XChartType ____
::rtl::OUString SAL_CALL LineChartType::getChartType()
throw (uno::RuntimeException)
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.LineChart" ));
}
// ____ OPropertySet ____
uno::Any LineChartType::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static helper::tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
// initialize defaults
lcl_AddDefaultsToMap( aStaticDefaults );
}
helper::tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
// ____ OPropertySet ____
::cppu::IPropertyArrayHelper & SAL_CALL LineChartType::getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper( lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
LineChartType::getPropertySetInfo()
throw (uno::RuntimeException)
{
static uno::Reference< beans::XPropertySetInfo > xInfo;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
} // namespace chart
<|endoftext|> |
<commit_before>#include <avr/interrupt.h>
#include "IRremote.h"
#include "IRremoteInt.h"
//+=============================================================================
// Interrupt Service Routine - Fires every 50uS
// TIMER2 interrupt code to collect raw data.
// Widths of alternating SPACE, MARK are recorded in rawbuf.
// Recorded in ticks of 50uS [microseconds, 0.000050 seconds]
// 'rawlen' counts the number of entries recorded so far.
// First entry is the SPACE between transmissions.
// As soon as a the first [SPACE] entry gets long:
// Ready is set; State switches to IDLE; Timing of SPACE continues.
// As soon as first MARK arrives:
// Gap width is recorded; Ready is cleared; New logging starts
//
ISR (TIMER_INTR_NAME)
{
TIMER_RESET;
// Read if IR Receiver -> SPACE [xmt LED off] or a MARK [xmt LED on]
// digitalRead() is very slow. Optimisation is possible, but makes the code unportable
uint8_t irdata = (uint8_t)digitalRead(irparams.recvpin);
irparams.timer++; // One more 50uS tick
if (irparams.rawlen >= RAWBUF) irparams.rcvstate = STATE_OVERFLOW ; // Buffer overflow
switch(irparams.rcvstate) {
case STATE_IDLE: // In the middle of a gap
if (irdata == MARK) {
if (irparams.timer < GAP_TICKS) {
// Not big enough to be a gap.
irparams.timer = 0;
} else {
// gap just ended, record duration and start recording transmission
irparams.overflow = false;
irparams.rawlen = 0;
irparams.rawbuf[irparams.rawlen++] = irparams.timer;
irparams.timer = 0;
irparams.rcvstate = STATE_MARK;
}
}
break;
case STATE_MARK: // timing MARK
if (irdata == SPACE) { // MARK ended, record time
irparams.rawbuf[irparams.rawlen++] = irparams.timer;
irparams.timer = 0;
irparams.rcvstate = STATE_SPACE;
}
break;
case STATE_SPACE: // timing SPACE
if (irdata == MARK) { // SPACE just ended, record it
irparams.rawbuf[irparams.rawlen++] = irparams.timer;
irparams.timer = 0;
irparams.rcvstate = STATE_MARK;
} else if (irparams.timer > GAP_TICKS) { // SPACE
// big SPACE, indicates gap between codes
// Mark current code as ready for processing
// Switch to STOP
// Don't reset timer; keep counting space width
irparams.rcvstate = STATE_STOP;
}
break;
case STATE_STOP: // waiting, measuring gap
if (irdata == MARK) irparams.timer = 0 ; // reset gap timer
break;
case STATE_OVERFLOW: // Flag up a read overflow
irparams.overflow = true;
irparams.rcvstate = STATE_STOP;
break;
}
if (irparams.blinkflag) {
if (irdata == MARK) BLINKLED_ON() ; // turn pin 13 LED on
else BLINKLED_OFF() ; // turn pin 13 LED off
}
}
<commit_msg>ISR Commenting<commit_after>#include <avr/interrupt.h>
#include "IRremote.h"
#include "IRremoteInt.h"
//+=============================================================================
// Interrupt Service Routine - Fires every 50uS
// TIMER2 interrupt code to collect raw data.
// Widths of alternating SPACE, MARK are recorded in rawbuf.
// Recorded in ticks of 50uS [microseconds, 0.000050 seconds]
// 'rawlen' counts the number of entries recorded so far.
// First entry is the SPACE between transmissions.
// As soon as a the first [SPACE] entry gets long:
// Ready is set; State switches to IDLE; Timing of SPACE continues.
// As soon as first MARK arrives:
// Gap width is recorded; Ready is cleared; New logging starts
//
ISR (TIMER_INTR_NAME)
{
TIMER_RESET;
// Read if IR Receiver -> SPACE [xmt LED off] or a MARK [xmt LED on]
// digitalRead() is very slow. Optimisation is possible, but makes the code unportable
uint8_t irdata = (uint8_t)digitalRead(irparams.recvpin);
irparams.timer++; // One more 50uS tick
if (irparams.rawlen >= RAWBUF) irparams.rcvstate = STATE_OVERFLOW ; // Buffer overflow
switch(irparams.rcvstate) {
//......................................................................
case STATE_IDLE: // In the middle of a gap
if (irdata == MARK) {
if (irparams.timer < GAP_TICKS) { // Not big enough to be a gap.
irparams.timer = 0;
} else {
// Gap just ended; Record duration; Start recording transmission
irparams.overflow = false;
irparams.rawlen = 0;
irparams.rawbuf[irparams.rawlen++] = irparams.timer;
irparams.timer = 0;
irparams.rcvstate = STATE_MARK;
}
}
break;
//......................................................................
case STATE_MARK: // Timing Mark
if (irdata == SPACE) { // Mark ended; Record time
irparams.rawbuf[irparams.rawlen++] = irparams.timer;
irparams.timer = 0;
irparams.rcvstate = STATE_SPACE;
}
break;
//......................................................................
case STATE_SPACE: // Timing Space
if (irdata == MARK) { // Space just ended; Record time
irparams.rawbuf[irparams.rawlen++] = irparams.timer;
irparams.timer = 0;
irparams.rcvstate = STATE_MARK;
} else if (irparams.timer > GAP_TICKS) { // Space
// A long Space, indicates gap between codes
// Flag the current code as ready for processing
// Switch to STOP
// Don't reset timer; keep counting Space width
irparams.rcvstate = STATE_STOP;
}
break;
//......................................................................
case STATE_STOP: // Waiting; Measuring Gap
if (irdata == MARK) irparams.timer = 0 ; // Reset gap timer
break;
//......................................................................
case STATE_OVERFLOW: // Flag up a read overflow; Stop the State Machine
irparams.overflow = true;
irparams.rcvstate = STATE_STOP;
break;
}
// If requested, flash LED L (D13) while receiving IR data
if (irparams.blinkflag) {
if (irdata == MARK) BLINKLED_ON() ; // turn pin 13 LED on
else BLINKLED_OFF() ; // turn pin 13 LED off
}
}
<|endoftext|> |
<commit_before>//===-- Sparc.cpp - General implementation file for the Sparc Target ------===//
//
// This file contains the code for the Sparc Target that does not fit in any of
// the other files in this directory.
//
//===----------------------------------------------------------------------===//
#include "SparcInternals.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Function.h"
#include "llvm/PassManager.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/PreSelection.h"
#include "llvm/CodeGen/StackSlots.h"
#include "llvm/CodeGen/PeepholeOpts.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/RegisterAllocation.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/Reoptimizer/Mapping/MappingInfo.h"
#include "Support/CommandLine.h"
#include "llvm/Assembly/PrintModulePass.h"
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor SparcMachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcInstr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
static cl::opt<bool> DisablePreSelect("nopreselect",
cl::desc("Disable preselection pass"));
static cl::opt<bool> DisableSched("nosched",
cl::desc("Disable local scheduling pass"));
static cl::opt<bool> DisablePeephole("nopeephole",
cl::desc("Disable peephole optimization pass"));
static cl::opt<bool>
DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode included in the executable"));
static cl::opt<bool>
DumpAsm("dump-asm", cl::desc("Print bytecode before native code generation"),
cl::Hidden);
//----------------------------------------------------------------------------
// allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine
// that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface)
//----------------------------------------------------------------------------
TargetMachine *allocateSparcTargetMachine(unsigned Configuration) {
return new UltraSparc();
}
//---------------------------------------------------------------------------
// class UltraSparcFrameInfo
//
// Interface to stack frame layout info for the UltraSPARC.
// Starting offsets for each area of the stack frame are aligned at
// a multiple of getStackFrameSizeAlignment().
//---------------------------------------------------------------------------
int
UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineFunction& ,
bool& pos) const
{
pos = false; // static stack area grows downwards
return StaticAreaOffsetFromFP;
}
int
UltraSparcFrameInfo::getRegSpillAreaOffset(MachineFunction& mcInfo,
bool& pos) const
{
// ensure no more auto vars are added
mcInfo.getInfo()->freezeAutomaticVarsArea();
pos = false; // static stack area grows downwards
unsigned autoVarsSize = mcInfo.getInfo()->getAutomaticVarsSize();
return StaticAreaOffsetFromFP - autoVarsSize;
}
int
UltraSparcFrameInfo::getTmpAreaOffset(MachineFunction& mcInfo,
bool& pos) const
{
MachineFunctionInfo *MFI = mcInfo.getInfo();
MFI->freezeAutomaticVarsArea(); // ensure no more auto vars are added
MFI->freezeSpillsArea(); // ensure no more spill slots are added
pos = false; // static stack area grows downwards
unsigned autoVarsSize = MFI->getAutomaticVarsSize();
unsigned spillAreaSize = MFI->getRegSpillsSize();
int offset = autoVarsSize + spillAreaSize;
return StaticAreaOffsetFromFP - offset;
}
int
UltraSparcFrameInfo::getDynamicAreaOffset(MachineFunction& mcInfo,
bool& pos) const
{
// Dynamic stack area grows downwards starting at top of opt-args area.
// The opt-args, required-args, and register-save areas are empty except
// during calls and traps, so they are shifted downwards on each
// dynamic-size alloca.
pos = false;
unsigned optArgsSize = mcInfo.getInfo()->getMaxOptionalArgsSize();
if (int extra = optArgsSize % getStackFrameSizeAlignment())
optArgsSize += (getStackFrameSizeAlignment() - extra);
int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
assert((offset - OFFSET) % getStackFrameSizeAlignment() == 0);
return offset;
}
//---------------------------------------------------------------------------
// class UltraSparcMachine
//
// Purpose:
// Primary interface to machine description for the UltraSPARC.
// Primarily just initializes machine-dependent parameters in
// class TargetMachine, and creates machine-dependent subclasses
// for classes such as TargetInstrInfo.
//
//---------------------------------------------------------------------------
UltraSparc::UltraSparc()
: TargetMachine("UltraSparc-Native", false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
cacheInfo(*this),
optInfo(*this) {
}
// addPassesToEmitAssembly - This method controls the entire code generation
// process for the ultra sparc.
//
bool UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// The following 3 passes used to be inserted specially by llc.
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// If LLVM dumping after transformations is requested, add it to the pipeline
if (DumpAsm)
PM.add(new PrintFunctionPass("Code after xformations: \n", &std::cerr));
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
PM.add(createSymbolStrippingPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
//Insert empty stackslots in the stack frame of each function
//so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
if (!DisablePreSelect) {
PM.add(createPreSelectionPass(*this));
PM.add(createReassociatePass());
PM.add(createLICMPass());
PM.add(createGCSEPass());
}
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
PM.add(getPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
PM.add(getMappingInfoCollector(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
//
PM.add(getFunctionAsmPrinterPass(Out));
PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
// Emit Module level assembly after all of the functions have been processed.
PM.add(getModuleAsmPrinterPass(Out));
// Emit bytecode to the assembly file into its special section next
PM.add(getEmitBytecodeToAsmPass(Out));
PM.add(getFunctionInfo(Out));
return false;
}
// addPassesToJITCompile - This method controls the JIT method of code
// generation for the UltraSparc.
//
bool UltraSparc::addPassesToJITCompile(PassManager &PM) {
const TargetData &TD = getTargetData();
PM.add(new TargetData("lli", TD.isLittleEndian(), TD.getPointerSize(),
TD.getPointerAlignment(), TD.getDoubleAlignment()));
// Replace malloc and free instructions with library calls.
// Do this after tracing until lli implements these lib calls.
// For now, it will emulate malloc and free internally.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
PM.add(createInstructionSelectionPass(*this));
// new pass: convert Value* in MachineOperand to an unsigned register
// this brings it in line with what the X86 JIT's RegisterAllocator expects
//PM.add(createAddRegNumToValuesPass());
PM.add(getRegisterAllocator(*this));
PM.add(getPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
return false; // success!
}
<commit_msg>Rename 'dump-asm' to 'dump-input' and really print it just before code-gen.<commit_after>//===-- Sparc.cpp - General implementation file for the Sparc Target ------===//
//
// This file contains the code for the Sparc Target that does not fit in any of
// the other files in this directory.
//
//===----------------------------------------------------------------------===//
#include "SparcInternals.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Function.h"
#include "llvm/PassManager.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/PreSelection.h"
#include "llvm/CodeGen/StackSlots.h"
#include "llvm/CodeGen/PeepholeOpts.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/RegisterAllocation.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/Reoptimizer/Mapping/MappingInfo.h"
#include "Support/CommandLine.h"
#include "llvm/Assembly/PrintModulePass.h"
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor SparcMachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcInstr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
static cl::opt<bool> DisablePreSelect("nopreselect",
cl::desc("Disable preselection pass"));
static cl::opt<bool> DisableSched("nosched",
cl::desc("Disable local scheduling pass"));
static cl::opt<bool> DisablePeephole("nopeephole",
cl::desc("Disable peephole optimization pass"));
static cl::opt<bool>
DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode included in the executable"));
static cl::opt<bool>
DumpInput("dump-input",cl::desc("Print bytecode before native code generation"),
cl::Hidden);
//----------------------------------------------------------------------------
// allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine
// that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface)
//----------------------------------------------------------------------------
TargetMachine *allocateSparcTargetMachine(unsigned Configuration) {
return new UltraSparc();
}
//---------------------------------------------------------------------------
// class UltraSparcFrameInfo
//
// Interface to stack frame layout info for the UltraSPARC.
// Starting offsets for each area of the stack frame are aligned at
// a multiple of getStackFrameSizeAlignment().
//---------------------------------------------------------------------------
int
UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineFunction& ,
bool& pos) const
{
pos = false; // static stack area grows downwards
return StaticAreaOffsetFromFP;
}
int
UltraSparcFrameInfo::getRegSpillAreaOffset(MachineFunction& mcInfo,
bool& pos) const
{
// ensure no more auto vars are added
mcInfo.getInfo()->freezeAutomaticVarsArea();
pos = false; // static stack area grows downwards
unsigned autoVarsSize = mcInfo.getInfo()->getAutomaticVarsSize();
return StaticAreaOffsetFromFP - autoVarsSize;
}
int
UltraSparcFrameInfo::getTmpAreaOffset(MachineFunction& mcInfo,
bool& pos) const
{
MachineFunctionInfo *MFI = mcInfo.getInfo();
MFI->freezeAutomaticVarsArea(); // ensure no more auto vars are added
MFI->freezeSpillsArea(); // ensure no more spill slots are added
pos = false; // static stack area grows downwards
unsigned autoVarsSize = MFI->getAutomaticVarsSize();
unsigned spillAreaSize = MFI->getRegSpillsSize();
int offset = autoVarsSize + spillAreaSize;
return StaticAreaOffsetFromFP - offset;
}
int
UltraSparcFrameInfo::getDynamicAreaOffset(MachineFunction& mcInfo,
bool& pos) const
{
// Dynamic stack area grows downwards starting at top of opt-args area.
// The opt-args, required-args, and register-save areas are empty except
// during calls and traps, so they are shifted downwards on each
// dynamic-size alloca.
pos = false;
unsigned optArgsSize = mcInfo.getInfo()->getMaxOptionalArgsSize();
if (int extra = optArgsSize % getStackFrameSizeAlignment())
optArgsSize += (getStackFrameSizeAlignment() - extra);
int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
assert((offset - OFFSET) % getStackFrameSizeAlignment() == 0);
return offset;
}
//---------------------------------------------------------------------------
// class UltraSparcMachine
//
// Purpose:
// Primary interface to machine description for the UltraSPARC.
// Primarily just initializes machine-dependent parameters in
// class TargetMachine, and creates machine-dependent subclasses
// for classes such as TargetInstrInfo.
//
//---------------------------------------------------------------------------
UltraSparc::UltraSparc()
: TargetMachine("UltraSparc-Native", false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
cacheInfo(*this),
optInfo(*this) {
}
// addPassesToEmitAssembly - This method controls the entire code generation
// process for the ultra sparc.
//
bool UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// The following 3 passes used to be inserted specially by llc.
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
PM.add(createSymbolStrippingPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
//Insert empty stackslots in the stack frame of each function
//so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
if (!DisablePreSelect) {
PM.add(createPreSelectionPass(*this));
PM.add(createReassociatePass());
PM.add(createLICMPass());
PM.add(createGCSEPass());
}
// If LLVM dumping after transformations is requested, add it to the pipeline
if (DumpInput)
PM.add(new PrintFunctionPass("Input code to instr. selection: \n", &std::cerr));
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
PM.add(getPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
PM.add(getMappingInfoCollector(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
//
PM.add(getFunctionAsmPrinterPass(Out));
PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
// Emit Module level assembly after all of the functions have been processed.
PM.add(getModuleAsmPrinterPass(Out));
// Emit bytecode to the assembly file into its special section next
PM.add(getEmitBytecodeToAsmPass(Out));
PM.add(getFunctionInfo(Out));
return false;
}
// addPassesToJITCompile - This method controls the JIT method of code
// generation for the UltraSparc.
//
bool UltraSparc::addPassesToJITCompile(PassManager &PM) {
const TargetData &TD = getTargetData();
PM.add(new TargetData("lli", TD.isLittleEndian(), TD.getPointerSize(),
TD.getPointerAlignment(), TD.getDoubleAlignment()));
// Replace malloc and free instructions with library calls.
// Do this after tracing until lli implements these lib calls.
// For now, it will emulate malloc and free internally.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
PM.add(createInstructionSelectionPass(*this));
// new pass: convert Value* in MachineOperand to an unsigned register
// this brings it in line with what the X86 JIT's RegisterAllocator expects
//PM.add(createAddRegNumToValuesPass());
PM.add(getRegisterAllocator(*this));
PM.add(getPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
return false; // success!
}
<|endoftext|> |
<commit_before><commit_msg>Disabled BrowserEncodingTest.TestEncodingAutoDetect on Chrome OS.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
class ViewIDTest : public InProcessBrowserTest {
public:
ViewIDTest() : root_window_(NULL) {}
void CheckViewID(ViewID id, bool should_have) {
if (!root_window_)
root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());
ASSERT_TRUE(root_window_);
EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id));
}
private:
GtkWidget* root_window_;
};
IN_PROC_BROWSER_TEST_F(ViewIDTest, Basic) {
for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
// http://crbug.com/21152
if (i == VIEW_ID_BOOKMARK_MENU)
continue;
// Extension shelf is being removed, http://crbug.com/25106.
if (i == VIEW_ID_DEV_EXTENSION_SHELF)
continue;
CheckViewID(static_cast<ViewID>(i), true);
}
CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}
IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
CheckViewID(VIEW_ID_TAB_0, true);
CheckViewID(VIEW_ID_TAB_1, false);
browser()->OpenURL(GURL(chrome::kAboutBlankURL), GURL(),
NEW_BACKGROUND_TAB, PageTransition::TYPED);
CheckViewID(VIEW_ID_TAB_0, true);
CheckViewID(VIEW_ID_TAB_1, true);
}
<commit_msg>Disable browser test ViewIDTest.Basic that fails on Linux since around r30434<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
class ViewIDTest : public InProcessBrowserTest {
public:
ViewIDTest() : root_window_(NULL) {}
void CheckViewID(ViewID id, bool should_have) {
if (!root_window_)
root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());
ASSERT_TRUE(root_window_);
EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id));
}
private:
GtkWidget* root_window_;
};
IN_PROC_BROWSER_TEST_F(ViewIDTest, DISABLED_Basic) {
for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
// http://crbug.com/21152
if (i == VIEW_ID_BOOKMARK_MENU)
continue;
// Extension shelf is being removed, http://crbug.com/25106.
if (i == VIEW_ID_DEV_EXTENSION_SHELF)
continue;
CheckViewID(static_cast<ViewID>(i), true);
}
CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}
IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
CheckViewID(VIEW_ID_TAB_0, true);
CheckViewID(VIEW_ID_TAB_1, false);
browser()->OpenURL(GURL(chrome::kAboutBlankURL), GURL(),
NEW_BACKGROUND_TAB, PageTransition::TYPED);
CheckViewID(VIEW_ID_TAB_0, true);
CheckViewID(VIEW_ID_TAB_1, true);
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.9.194); FILE MERGED 2005/09/05 17:35:36 rt 1.9.194.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <fstream>
#include <ydsh/ydsh.h>
#include <misc/files.h>
#include <directive.h>
#include <config.h>
#ifndef EXEC_TEST_DIR
#define EXEC_TEST_DIR "."
#endif
#ifndef BIN_PATH
#define BIN_PATH "./ydsh"
#endif
using namespace ydsh;
using namespace ydsh::directive;
// parse config(key = value)
bool isSpace(char ch) {
switch(ch) {
case ' ':
case '\t':
case '\r':
case '\n':
return true;
default:
return false;
}
}
void consumeSpace(const std::string &src, unsigned int &index) {
for(; index < src.size(); index++) {
if(!isSpace(src[index])) {
return;
}
}
}
int extract(const std::string &src, unsigned int &index, unsigned int &first) {
consumeSpace(src, index);
std::string buf;
for(; index < src.size(); index++) {
char ch = src[index];
if(!isdigit(ch)) {
break;
}
buf += ch;
}
long value = std::stol(buf);
if(value < 0 || value > UINT32_MAX) {
return 1;
}
first = (unsigned int) value;
return 0;
}
int extract(const std::string &src, unsigned int &index, std::string &first) {
consumeSpace(src, index);
for(; index < src.size(); index++) {
char ch = src[index];
if(isSpace(ch)) {
break;
}
first += ch;
}
return 0;
}
int extract(const std::string &src, unsigned int &index, const char *first) {
consumeSpace(src, index);
for(unsigned int i = 0; first[i] != '\0'; i++) {
if(index >= src.size()) {
return 1; // not match
}
if(src[index++] != first[i]) {
return 1;
}
}
return 0;
}
int parseImpl(const std::string &src, unsigned int &index) {
consumeSpace(src, index);
return index - src.size();
}
template <typename F, typename ...T>
int parseImpl(const std::string &src, unsigned int &index, F &&first, T&& ...args) {
int ret = extract(src, index, std::forward<F>(first));
return ret == 0 ? parseImpl(src, index, std::forward<T>(args)...) : ret;
}
template <typename ...T>
int parse(const std::string &src, T&& ...args) {
unsigned int index = 0;
return parseImpl(src, index, std::forward<T>(args)...);
}
template <typename ...T>
int parse(const char *src, T&& ...args) {
std::string str(src);
return parse(str, std::forward<T>(args)...);
}
class ExecTest : public ::testing::TestWithParam<std::string> {
private:
std::string tmpFileName;
std::string targetName;
public:
ExecTest() : tmpFileName(), targetName() { }
virtual ~ExecTest() = default;
virtual void SetUp() {
const char *tmpdir = getenv("TMPDIR");
if(tmpdir == nullptr) {
tmpdir = "/tmp";
}
unsigned int size = 512;
char name[size];
snprintf(name, size, "%s/exec_test_tmpXXXXXX", tmpdir);
int fd = mkstemp(name);
close(fd);
this->tmpFileName = name;
this->targetName = this->GetParam();
}
virtual void TearDown() {
remove(this->tmpFileName.c_str());
}
virtual const std::string &getTmpFileName() {
return this->tmpFileName;
}
virtual const std::string &getSourceName() {
return this->targetName;
}
virtual void doTest() {
SCOPED_TRACE("");
// create directive
Directive d;
bool s = Directive::init(this->getSourceName().c_str(), d);
ASSERT_TRUE(s);
// check run condition
RunCondition haveDBus = DSState_supportDBus() ? RunCondition::TRUE : RunCondition::FALSE;
if(d.getIfHaveDBus() != RunCondition::IGNORE && haveDBus != d.getIfHaveDBus()) {
return; // do nothing
}
const char *scriptName = this->getSourceName().c_str();
std::string cmd(BIN_PATH);
cmd += " --status-log ";
cmd += this->getTmpFileName();
// set argument
std::unique_ptr<char *[]> argv = d.getAsArgv(scriptName);
for(unsigned int i = 0; argv[i] != nullptr; i++) {
cmd += " ";
cmd += '"';
cmd += argv[i];
cmd += '"';
}
// execute
int ret = system(cmd.c_str());
ret = WEXITSTATUS(ret);
// get internal status
std::ifstream input(this->getTmpFileName());
ASSERT_FALSE(!input);
std::string line;
std::getline(input, line);
ASSERT_FALSE(line.empty());
unsigned int kind;
unsigned int lineNum;
std::string name;
int r = parse(line, "kind", "=", kind, "lineNum", "=", lineNum, "name", "=", name);
ASSERT_EQ(0, r);
// check status
ASSERT_EQ(d.getResult(), kind);
ASSERT_EQ(d.getLineNum(), lineNum);
ASSERT_EQ(d.getStatus(), static_cast<unsigned int>(ret));
ASSERT_EQ(d.getErrorKind(), name);
}
};
TEST_P(ExecTest, baseTest) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
this->doTest();
});
}
INSTANTIATE_TEST_CASE_P(ExecTest, ExecTest, ::testing::ValuesIn(getFileList(EXEC_TEST_DIR, true)));
void addArg(std::vector<char *> &) {
}
template <typename... T>
void addArg(std::vector<char *> &out, const char *first, T ...rest) {
out.push_back(const_cast<char *>(first));
addArg(out, rest...);
}
template <typename... T>
std::unique_ptr<char *[]> make_argv(const char *name, T ...args) {
std::vector<char *> out;
addArg(out, name, args...);
unsigned int size = out.size();
std::unique_ptr<char *[]> ptr(new char*[size + 1]);
for(unsigned int i = 0; i < size; i++) {
ptr[i] = out[i];
}
ptr[size] = nullptr;
return ptr;
}
TEST(Base, case1) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
std::string line("type=3 lineNum=1 kind=SystemError");
unsigned int type;
unsigned int lineNum;
std::string kind;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind);
ASSERT_EQ(0, ret);
ASSERT_EQ(3u, type);
ASSERT_EQ(1u, lineNum);
ASSERT_EQ("SystemError", kind);
});
}
TEST(Base, case2) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
std::string line("type=0 lineNum=0 kind=");
unsigned int type;
unsigned int lineNum;
std::string kind;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind);
ASSERT_EQ(0, ret);
ASSERT_EQ(0u, type);
ASSERT_EQ(0u, lineNum);
ASSERT_EQ("", kind);
});
}
TEST(BuiltinExecTest, case1) {
SCOPED_TRACE("");
DSState *state = DSState_create();
int ret = DSState_exec(state, make_argv("echo", "hello").get());
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0, ret));
DSState_delete(&state);
}
TEST(BuiltinExecTest, case2) {
SCOPED_TRACE("");
DSState *state = DSState_create();
int ret = DSState_exec(state, make_argv("fheruifh", "hello").get());
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(1, ret));
DSState_delete(&state);
}
TEST(API, case1) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
ASSERT_EQ((unsigned int)X_INFO_MAJOR_VERSION, DSState_majorVersion());
ASSERT_EQ((unsigned int)X_INFO_MINOR_VERSION, DSState_minorVersion());
ASSERT_EQ((unsigned int)X_INFO_PATCH_VERSION, DSState_patchVersion());
});
}
TEST(API, case2) {
SCOPED_TRACE("");
DSState *state = DSState_create();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(1u, DSState_lineNum(state)));
DSState_eval(state, nullptr, "12 + 32\n $true\n", nullptr);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSState_lineNum(state)));
DSState_setLineNum(state, 49);
DSState_eval(state, nullptr, "23", nullptr);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(50u, DSState_lineNum(state)));
DSState_delete(&state);
}
TEST(API, case3) {
SCOPED_TRACE("");
DSState *state = DSState_create();
DSState_eval(state, nullptr, "$PS1 = 'hello>'; $PS2 = 'second>'", nullptr);
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("hello>", DSState_prompt(state, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("second>", DSState_prompt(state, 2)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("", DSState_prompt(state, 5)));
DSState_delete(&state);
}
TEST(API, case4) {
SCOPED_TRACE("");
// null arguments
DSState_complete(nullptr, nullptr, 1, nullptr);
DSState *state = DSState_create();
DSCandidates c;
DSState_complete(state, "~", 1, &c);
ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(c.values != nullptr));
ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(c.size > 0));
DSCandidates_release(&c);
DSState_delete(&state);
}
TEST(API, case5) {
SCOPED_TRACE("");
DSState *state = DSState_create();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_OPTION_ASSERT, DSState_option(state)));
DSState_setOption(state, DS_OPTION_DUMP_CODE);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_OPTION_ASSERT | DS_OPTION_DUMP_CODE, DSState_option(state)));
DSState_unsetOption(state, DS_OPTION_ASSERT);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_OPTION_DUMP_CODE, DSState_option(state)));
DSState_delete(&state);
}
TEST(PID, case1) {
SCOPED_TRACE("");
pid_t pid = getpid();
DSState *state = DSState_create();
std::string src("assert($$ == ");
src += std::to_string(pid);
src += "u)";
DSError e;
int s = DSState_eval(state, nullptr, src.c_str(), &e);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0, s));
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_ERROR_KIND_SUCCESS, e.kind));
DSError_release(&e);
DSState_delete(&state);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>refactor exec_test for preparing history api test<commit_after>#include <gtest/gtest.h>
#include <fstream>
#include <ydsh/ydsh.h>
#include <misc/files.h>
#include <directive.h>
#include <config.h>
#ifndef EXEC_TEST_DIR
#define EXEC_TEST_DIR "."
#endif
#ifndef BIN_PATH
#define BIN_PATH "./ydsh"
#endif
using namespace ydsh;
using namespace ydsh::directive;
// parse config(key = value)
bool isSpace(char ch) {
switch(ch) {
case ' ':
case '\t':
case '\r':
case '\n':
return true;
default:
return false;
}
}
void consumeSpace(const std::string &src, unsigned int &index) {
for(; index < src.size(); index++) {
if(!isSpace(src[index])) {
return;
}
}
}
int extract(const std::string &src, unsigned int &index, unsigned int &first) {
consumeSpace(src, index);
std::string buf;
for(; index < src.size(); index++) {
char ch = src[index];
if(!isdigit(ch)) {
break;
}
buf += ch;
}
long value = std::stol(buf);
if(value < 0 || value > UINT32_MAX) {
return 1;
}
first = (unsigned int) value;
return 0;
}
int extract(const std::string &src, unsigned int &index, std::string &first) {
consumeSpace(src, index);
for(; index < src.size(); index++) {
char ch = src[index];
if(isSpace(ch)) {
break;
}
first += ch;
}
return 0;
}
int extract(const std::string &src, unsigned int &index, const char *first) {
consumeSpace(src, index);
for(unsigned int i = 0; first[i] != '\0'; i++) {
if(index >= src.size()) {
return 1; // not match
}
if(src[index++] != first[i]) {
return 1;
}
}
return 0;
}
int parseImpl(const std::string &src, unsigned int &index) {
consumeSpace(src, index);
return index - src.size();
}
template <typename F, typename ...T>
int parseImpl(const std::string &src, unsigned int &index, F &&first, T&& ...args) {
int ret = extract(src, index, std::forward<F>(first));
return ret == 0 ? parseImpl(src, index, std::forward<T>(args)...) : ret;
}
template <typename ...T>
int parse(const std::string &src, T&& ...args) {
unsigned int index = 0;
return parseImpl(src, index, std::forward<T>(args)...);
}
template <typename ...T>
int parse(const char *src, T&& ...args) {
std::string str(src);
return parse(str, std::forward<T>(args)...);
}
class TempFileFactory {
protected:
std::string tmpFileName;
TempFileFactory() = default;
virtual ~TempFileFactory() = default;
void createTemp() {
const char *tmpdir = getenv("TMPDIR");
if(tmpdir == nullptr) {
tmpdir = "/tmp";
}
unsigned int size = 512;
char name[size];
snprintf(name, size, "%s/exec_test_tmpXXXXXX", tmpdir);
int fd = mkstemp(name);
close(fd);
this->tmpFileName = name;
}
void deleteTemp() {
remove(this->tmpFileName.c_str());
}
};
class ExecTest : public ::testing::TestWithParam<std::string>, public TempFileFactory {
private:
std::string targetName;
public:
ExecTest() : targetName() { }
virtual ~ExecTest() = default;
virtual void SetUp() {
this->createTemp();
this->targetName = this->GetParam();
}
virtual void TearDown() {
this->deleteTemp();
}
virtual const std::string &getTmpFileName() {
return this->tmpFileName;
}
virtual const std::string &getSourceName() {
return this->targetName;
}
virtual void doTest() {
SCOPED_TRACE("");
// create directive
Directive d;
bool s = Directive::init(this->getSourceName().c_str(), d);
ASSERT_TRUE(s);
// check run condition
RunCondition haveDBus = DSState_supportDBus() ? RunCondition::TRUE : RunCondition::FALSE;
if(d.getIfHaveDBus() != RunCondition::IGNORE && haveDBus != d.getIfHaveDBus()) {
return; // do nothing
}
const char *scriptName = this->getSourceName().c_str();
std::string cmd(BIN_PATH);
cmd += " --status-log ";
cmd += this->getTmpFileName();
// set argument
std::unique_ptr<char *[]> argv = d.getAsArgv(scriptName);
for(unsigned int i = 0; argv[i] != nullptr; i++) {
cmd += " ";
cmd += '"';
cmd += argv[i];
cmd += '"';
}
// execute
int ret = system(cmd.c_str());
ret = WEXITSTATUS(ret);
// get internal status
std::ifstream input(this->getTmpFileName());
ASSERT_FALSE(!input);
std::string line;
std::getline(input, line);
ASSERT_FALSE(line.empty());
unsigned int kind;
unsigned int lineNum;
std::string name;
int r = parse(line, "kind", "=", kind, "lineNum", "=", lineNum, "name", "=", name);
ASSERT_EQ(0, r);
// check status
ASSERT_EQ(d.getResult(), kind);
ASSERT_EQ(d.getLineNum(), lineNum);
ASSERT_EQ(d.getStatus(), static_cast<unsigned int>(ret));
ASSERT_EQ(d.getErrorKind(), name);
}
};
TEST_P(ExecTest, baseTest) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
this->doTest();
});
}
INSTANTIATE_TEST_CASE_P(ExecTest, ExecTest, ::testing::ValuesIn(getFileList(EXEC_TEST_DIR, true)));
void addArg(std::vector<char *> &) {
}
template <typename... T>
void addArg(std::vector<char *> &out, const char *first, T ...rest) {
out.push_back(const_cast<char *>(first));
addArg(out, rest...);
}
template <typename... T>
std::unique_ptr<char *[]> make_argv(const char *name, T ...args) {
std::vector<char *> out;
addArg(out, name, args...);
unsigned int size = out.size();
std::unique_ptr<char *[]> ptr(new char*[size + 1]);
for(unsigned int i = 0; i < size; i++) {
ptr[i] = out[i];
}
ptr[size] = nullptr;
return ptr;
}
TEST(Base, case1) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
std::string line("type=3 lineNum=1 kind=SystemError");
unsigned int type;
unsigned int lineNum;
std::string kind;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind);
ASSERT_EQ(0, ret);
ASSERT_EQ(3u, type);
ASSERT_EQ(1u, lineNum);
ASSERT_EQ("SystemError", kind);
});
}
TEST(Base, case2) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
std::string line("type=0 lineNum=0 kind=");
unsigned int type;
unsigned int lineNum;
std::string kind;
int ret = parse(line, "type", "=", type, "lineNum", "=", lineNum, "kind", "=", kind);
ASSERT_EQ(0, ret);
ASSERT_EQ(0u, type);
ASSERT_EQ(0u, lineNum);
ASSERT_EQ("", kind);
});
}
TEST(BuiltinExecTest, case1) {
SCOPED_TRACE("");
DSState *state = DSState_create();
int ret = DSState_exec(state, make_argv("echo", "hello").get());
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0, ret));
DSState_delete(&state);
}
TEST(BuiltinExecTest, case2) {
SCOPED_TRACE("");
DSState *state = DSState_create();
int ret = DSState_exec(state, make_argv("fheruifh", "hello").get());
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(1, ret));
DSState_delete(&state);
}
TEST(API, case1) {
ASSERT_NO_FATAL_FAILURE({
SCOPED_TRACE("");
ASSERT_EQ((unsigned int)X_INFO_MAJOR_VERSION, DSState_majorVersion());
ASSERT_EQ((unsigned int)X_INFO_MINOR_VERSION, DSState_minorVersion());
ASSERT_EQ((unsigned int)X_INFO_PATCH_VERSION, DSState_patchVersion());
});
}
TEST(API, case2) {
SCOPED_TRACE("");
DSState *state = DSState_create();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(1u, DSState_lineNum(state)));
DSState_eval(state, nullptr, "12 + 32\n $true\n", nullptr);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSState_lineNum(state)));
DSState_setLineNum(state, 49);
DSState_eval(state, nullptr, "23", nullptr);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(50u, DSState_lineNum(state)));
DSState_delete(&state);
}
TEST(API, case3) {
SCOPED_TRACE("");
DSState *state = DSState_create();
DSState_eval(state, nullptr, "$PS1 = 'hello>'; $PS2 = 'second>'", nullptr);
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("hello>", DSState_prompt(state, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("second>", DSState_prompt(state, 2)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("", DSState_prompt(state, 5)));
DSState_delete(&state);
}
TEST(API, case4) {
SCOPED_TRACE("");
// null arguments
DSState_complete(nullptr, nullptr, 1, nullptr);
DSState *state = DSState_create();
DSCandidates c;
DSState_complete(state, "~", 1, &c);
ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(c.values != nullptr));
ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(c.size > 0));
DSCandidates_release(&c);
DSState_delete(&state);
}
TEST(API, case5) {
SCOPED_TRACE("");
DSState *state = DSState_create();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_OPTION_ASSERT, DSState_option(state)));
DSState_setOption(state, DS_OPTION_DUMP_CODE);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_OPTION_ASSERT | DS_OPTION_DUMP_CODE, DSState_option(state)));
DSState_unsetOption(state, DS_OPTION_ASSERT);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_OPTION_DUMP_CODE, DSState_option(state)));
DSState_delete(&state);
}
TEST(PID, case1) {
SCOPED_TRACE("");
pid_t pid = getpid();
DSState *state = DSState_create();
std::string src("assert($$ == ");
src += std::to_string(pid);
src += "u)";
DSError e;
int s = DSState_eval(state, nullptr, src.c_str(), &e);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0, s));
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_ERROR_KIND_SUCCESS, e.kind));
DSError_release(&e);
DSState_delete(&state);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>#ifndef SLIDING_WINDOW_HPP_
#define SLIDING_WINDOW_HPP_
#include "iterator_range.hpp"
#include "iterbase.hpp"
#include <vector>
#include <algorithm>
#include <functional>
#include <type_traits>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class SlidingWindow {
private:
Container container;
std::size_t window_size;
public:
SlidingWindow(Container container, std::size_t win_sz)
: container(std::forward<Container>(container)),
window_size{win_sz}
{ }
class Iterator {
private:
// confusing, but, just makes the type of the vector returned by
// operator*()
using OpDerefElemType =
std::reference_wrapper<
typename std::remove_reference<
iterator_deref<Container>>::type>;
using DerefVec = std::vector<OpDerefElemType>;
std::vector<iterator_type<Container>> section;
std::size_t section_size = 0;
public:
Iterator(Container& container, std::size_t s)
: section_size{s}
{
auto iter = std::begin(container);
auto end = std::end(container);
for (std::size_t i = 0;
i < section_size && iter != end;
++iter, ++i) {
section.push_back(iter);
}
}
// for the end iter
Iterator(Container& container)
: section{std::end(container)},
section_size{0}
{ }
Iterator& operator++() {
for (auto&& iter : section) {
++iter;
}
return *this;
}
bool operator!=(const Iterator& rhs) const {
return this->section.back() != rhs.section.back();
}
DerefVec operator*() {
DerefVec vec;
for (auto&& iter : section) {
vec.push_back(*iter);
}
return vec;
}
};
Iterator begin() {
return {container, window_size};
}
Iterator end() {
return {container};
}
};
template <typename Container>
SlidingWindow<Container> sliding_window(
Container&& container, std::size_t window_size) {
return {std::forward<Container>(container), window_size};
}
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T> il, std::size_t window_size) {
return {il, window_size};
}
}
#endif //SLIDING_WINDOW_HPP_
<commit_msg>private value ctor<commit_after>#ifndef SLIDING_WINDOW_HPP_
#define SLIDING_WINDOW_HPP_
#include "iterator_range.hpp"
#include "iterbase.hpp"
#include <vector>
#include <algorithm>
#include <functional>
#include <type_traits>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class SlidingWindow;
template <typename Container>
SlidingWindow<Container> sliding_window(Container&&, std::size_t);
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T>, std::size_t);
template <typename Container>
class SlidingWindow {
private:
Container container;
std::size_t window_size;
friend SlidingWindow sliding_window<Container>(
Container&&, std::size_t);
template <typename T>
friend SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T>, std::size_t);
SlidingWindow(Container container, std::size_t win_sz)
: container(std::forward<Container>(container)),
window_size{win_sz}
{ }
public:
class Iterator {
private:
// confusing, but, just makes the type of the vector
// returned by operator*()
using OpDerefElemType =
std::reference_wrapper<
typename std::remove_reference<
iterator_deref<Container>>::type>;
using DerefVec = std::vector<OpDerefElemType>;
std::vector<iterator_type<Container>> section;
std::size_t section_size = 0;
public:
Iterator(Container& container, std::size_t s)
: section_size{s}
{
auto iter = std::begin(container);
auto end = std::end(container);
for (std::size_t i = 0;
i < section_size && iter != end;
++iter, ++i) {
section.push_back(iter);
}
}
// for the end iter
Iterator(Container& container)
: section{std::end(container)},
section_size{0}
{ }
Iterator& operator++() {
for (auto&& iter : section) {
++iter;
}
return *this;
}
bool operator!=(const Iterator& rhs) const {
return this->section.back() != rhs.section.back();
}
DerefVec operator*() {
DerefVec vec;
for (auto&& iter : section) {
vec.push_back(*iter);
}
return vec;
}
};
Iterator begin() {
return {container, window_size};
}
Iterator end() {
return {container};
}
};
template <typename Container>
SlidingWindow<Container> sliding_window(
Container&& container, std::size_t window_size) {
return {std::forward<Container>(container), window_size};
}
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T> il, std::size_t window_size) {
return {il, window_size};
}
}
#endif //SLIDING_WINDOW_HPP_
<|endoftext|> |
<commit_before><commit_msg>Guard against directory traversal due to evil message from compromised renderer.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "bindings/npruntime.h"
#include "npruntime_impl.h"
#include "npruntime_priv.h"
// This file is a dumping ground for KJS-related fixups that we need. It
// should ideally be eliminated in favor of less lameness.
// KJS should only expose functions declared in npruntime.h (NPN_*)
// and npruntime_priv.h (which is an extension of npruntime.h), and
// not exposing _NPN_* functions declared in npruntime_impl.h.
// KJSBridge implements NPN_* functions by wrapping around _NPN_* functions.
//
// Following styles in JavaScriptCore/bindings/npruntime.cpp
void NPN_ReleaseVariantValue(NPVariant *variant) {
_NPN_ReleaseVariantValue(variant);
}
NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name) {
return _NPN_GetStringIdentifier(name);
}
void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount,
NPIdentifier *identifiers) {
_NPN_GetStringIdentifiers(names, nameCount, identifiers);
}
NPIdentifier NPN_GetIntIdentifier(int32_t intid) {
return _NPN_GetIntIdentifier(intid);
}
bool NPN_IdentifierIsString(NPIdentifier identifier) {
return _NPN_IdentifierIsString(identifier);
}
NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier) {
return _NPN_UTF8FromIdentifier(identifier);
}
int32_t NPN_IntFromIdentifier(NPIdentifier identifier) {
return _NPN_IntFromIdentifier(identifier);
}
NPObject *NPN_CreateObject(NPP npp, NPClass *aClass) {
return _NPN_CreateObject(npp, aClass);
}
NPObject *NPN_RetainObject(NPObject *obj) {
return _NPN_RetainObject(obj);
}
void NPN_ReleaseObject(NPObject *obj) {
_NPN_ReleaseObject(obj);
}
void NPN_DeallocateObject(NPObject *obj) {
_NPN_DeallocateObject(obj);
}
bool NPN_Invoke(NPP npp, NPObject *npobj, NPIdentifier methodName,
const NPVariant *args, uint32_t argCount, NPVariant *result) {
return _NPN_Invoke(npp, npobj, methodName, args, argCount, result);
}
bool NPN_InvokeDefault(NPP npp, NPObject *npobj, const NPVariant *args,
uint32_t argCount, NPVariant *result) {
return _NPN_InvokeDefault(npp, npobj, args, argCount, result);
}
bool NPN_Evaluate(NPP npp, NPObject *npobj, NPString *script, NPVariant *result) {
return _NPN_Evaluate(npp, npobj, script, result);
}
bool NPN_EvaluateHelper(NPP npp, bool popups_allowed, NPObject* npobj,
NPString* npscript, NPVariant *result) {
return _NPN_Evaluate(npp, npobj, script, result);
}
bool NPN_GetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
NPVariant *result) {
return _NPN_GetProperty(npp, npobj, propertyName, result);
}
bool NPN_SetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
const NPVariant *value) {
return _NPN_SetProperty(npp, npobj, propertyName, value);
}
bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName) {
return _NPN_RemoveProperty(npp, npobj, propertyName);
}
bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName) {
return _NPN_HasProperty(npp, npobj, propertyName);
}
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName) {
return _NPN_HasMethod(npp, npobj, methodName);
}
void NPN_SetException(NPObject *obj, const NPUTF8 *message) {
_NPN_SetException(obj, message);
}
bool NPN_Enumerate(NPP npp, NPObject *npobj, NPIdentifier **identifier,
uint32_t *count) {
return _NPN_Enumerate(npp, npobj, identifier, count);
}
<commit_msg>fix typo<commit_after>// Copyright (c) 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "bindings/npruntime.h"
#include "npruntime_impl.h"
#include "npruntime_priv.h"
// This file is a dumping ground for KJS-related fixups that we need. It
// should ideally be eliminated in favor of less lameness.
// KJS should only expose functions declared in npruntime.h (NPN_*)
// and npruntime_priv.h (which is an extension of npruntime.h), and
// not exposing _NPN_* functions declared in npruntime_impl.h.
// KJSBridge implements NPN_* functions by wrapping around _NPN_* functions.
//
// Following styles in JavaScriptCore/bindings/npruntime.cpp
void NPN_ReleaseVariantValue(NPVariant *variant) {
_NPN_ReleaseVariantValue(variant);
}
NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name) {
return _NPN_GetStringIdentifier(name);
}
void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount,
NPIdentifier *identifiers) {
_NPN_GetStringIdentifiers(names, nameCount, identifiers);
}
NPIdentifier NPN_GetIntIdentifier(int32_t intid) {
return _NPN_GetIntIdentifier(intid);
}
bool NPN_IdentifierIsString(NPIdentifier identifier) {
return _NPN_IdentifierIsString(identifier);
}
NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier) {
return _NPN_UTF8FromIdentifier(identifier);
}
int32_t NPN_IntFromIdentifier(NPIdentifier identifier) {
return _NPN_IntFromIdentifier(identifier);
}
NPObject *NPN_CreateObject(NPP npp, NPClass *aClass) {
return _NPN_CreateObject(npp, aClass);
}
NPObject *NPN_RetainObject(NPObject *obj) {
return _NPN_RetainObject(obj);
}
void NPN_ReleaseObject(NPObject *obj) {
_NPN_ReleaseObject(obj);
}
void NPN_DeallocateObject(NPObject *obj) {
_NPN_DeallocateObject(obj);
}
bool NPN_Invoke(NPP npp, NPObject *npobj, NPIdentifier methodName,
const NPVariant *args, uint32_t argCount, NPVariant *result) {
return _NPN_Invoke(npp, npobj, methodName, args, argCount, result);
}
bool NPN_InvokeDefault(NPP npp, NPObject *npobj, const NPVariant *args,
uint32_t argCount, NPVariant *result) {
return _NPN_InvokeDefault(npp, npobj, args, argCount, result);
}
bool NPN_Evaluate(NPP npp, NPObject *npobj, NPString *script, NPVariant *result) {
return _NPN_Evaluate(npp, npobj, script, result);
}
bool NPN_EvaluateHelper(NPP npp, bool popups_allowed, NPObject* npobj,
NPString* script, NPVariant *result) {
return _NPN_Evaluate(npp, npobj, script, result);
}
bool NPN_GetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
NPVariant *result) {
return _NPN_GetProperty(npp, npobj, propertyName, result);
}
bool NPN_SetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
const NPVariant *value) {
return _NPN_SetProperty(npp, npobj, propertyName, value);
}
bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName) {
return _NPN_RemoveProperty(npp, npobj, propertyName);
}
bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName) {
return _NPN_HasProperty(npp, npobj, propertyName);
}
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName) {
return _NPN_HasMethod(npp, npobj, methodName);
}
void NPN_SetException(NPObject *obj, const NPUTF8 *message) {
_NPN_SetException(obj, message);
}
bool NPN_Enumerate(NPP npp, NPObject *npobj, NPIdentifier **identifier,
uint32_t *count) {
return _NPN_Enumerate(npp, npobj, identifier, count);
}
<|endoftext|> |
<commit_before>/*
* pab.cpp
*
* Copyright (C) 1999 Don Sanders <dsanders@kde.org>
*/
#include "abbrowser.h"
#include "browserentryeditor.h"
#include <qkeycode.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kglobal.h>
#include <kmenubar.h>
#include <kconfig.h>
#include <kaccel.h>
#include <kdebug.h>
#include "undo.h"
#include "browserwidget.h"
#include "entry.h"
Pab::Pab() : KMainWindow(0), DCOPObject("AbBrowserIface")
{
setCaption( i18n( "Address Book Browser" ));
document = new ContactEntryList();
view = new PabWidget( document, this, "Abbrowser" );
// tell the KMainWindow that this is indeed the main widget
setCentralWidget(view);
// create a popup menu -- in this case, the File menu
QPopupMenu* p = new QPopupMenu;
p->insertItem(i18n("&Sync"), this, SLOT(save()), CTRL+Key_S);
p->insertItem(i18n("&New Contact"), this, SLOT(newContact()), CTRL+Key_N);
/* p->insertItem(i18n("New &Group"), this, SLOT(newGroup()), CTRL+Key_G); */
p->insertSeparator();
p->insertItem(i18n("&Send Mail"), view, SLOT(sendMail()), CTRL+Key_Return);
p->insertSeparator();
p->insertItem(i18n("&Properties"), view, SLOT(properties()));
p->insertItem(i18n("&Delete\tDel"));
p->insertSeparator();
p->insertItem(i18n("&Quit"), kapp, SLOT(quit()), CTRL+Key_Q);
edit = new QPopupMenu;
undoId = edit->insertItem(i18n("Undo"), this, SLOT(undo()),
KStdAccel::key(KStdAccel::Undo));
redoId = edit->insertItem(i18n("Redo"), this, SLOT(redo()),
KStdAccel::key(KStdAccel::Redo));
edit->insertSeparator();
edit->insertItem(i18n("Cut"), view, SLOT(cut()), CTRL+Key_X);
edit->insertItem(i18n("Copy"), view, SLOT(copy()), CTRL+Key_C);
edit->insertItem(i18n("Paste"), view, SLOT(paste()), CTRL+Key_V);
edit->insertSeparator();
edit->insertItem(i18n("Select All"), view, SLOT(selectAll()), CTRL+Key_A);
edit->setItemEnabled( undoId, false );
edit->setItemEnabled( redoId, false );
QObject::connect( edit, SIGNAL( aboutToShow() ), this, SLOT( updateEditMenu() ));
QPopupMenu* v = new QPopupMenu;
v->insertItem(i18n("Choose Fields..."), view, SLOT(showSelectNameDialog()) );
v->insertItem(i18n("Options..."), view, SLOT(viewOptions()) );
v->insertSeparator();
v->insertItem(i18n("Restore defaults"), view, SLOT(defaultSettings()) );
// v->insertSeparator();
// v->insertItem(i18n("Refresh"), view, SLOT(refresh()), Key_F5 );
// put our newly created menu into the main menu bar
menuBar()->insertItem(i18n("&File"), p);
menuBar()->insertItem(i18n("&Edit"), edit);
menuBar()->insertItem(i18n("&View"), v);
menuBar()->insertSeparator();
// KDE will generate a short help menu automagically
p = helpMenu( i18n("Abbrowser --- KDE Address Book\n\n"
"(c) 2000AD The KDE PIM Team \n"));
menuBar()->insertItem(i18n("&Help"), p);
toolBar()->insertButton(BarIcon("filenew"), // icon
0, // button id
SIGNAL(clicked()), // action
this, SLOT(newContact()), // result
true, i18n("Add a new entry")); // tooltip text
toolBar()->insertButton(BarIcon("edit"), // icon
0, // button id
SIGNAL(clicked()), // action
view, SLOT(properties()), // result
true, i18n("Change this entry")); // tooltip text
toolBar()->insertButton(BarIcon("editdelete"), // icon
0, // button id
SIGNAL(clicked()), // action
view, SLOT(clear()), // result
true, i18n("Remove this entry")); // tooltip text
toolBar()->insertSeparator();
toolBar()->insertButton(BarIcon("mail_send"), // icon
0, // button id
SIGNAL(clicked()), // action
view, SLOT(sendMail()), // result
true, i18n("Send email")); // tooltip text
toolBar()->setFullSize(true);
// we do want a status bar
statusBar()->show();
connect( kapp, SIGNAL( aboutToQuit() ), this, SLOT( saveConfig() ) );
resize( sizeHint() );
readConfig();
}
void Pab::newContact()
{
ContactDialog *cd = new PabNewContactDialog( i18n( "Address Book Entry Editor" ), this, 0 );
connect( cd, SIGNAL( add( ContactEntry* ) ),
view, SLOT( addNewEntry( ContactEntry* ) ));
cd->show();
}
void Pab::addEmail( QString addr )
{
view->addEmail( addr );
return;
}
void Pab::save()
{
document->commit();
document->refresh();
view->saveConfig();
view->readConfig();
view->reconstructListView();
//xxx document->save( "entries.txt" );
UndoStack::instance()->clear();
RedoStack::instance()->clear();
}
void Pab::readConfig()
{
KConfig *config = kapp->config();
int w, h;
config->setGroup("Geometry");
QString str = config->readEntry("Browser", "");
if (!str.isEmpty() && str.find(',')>=0)
{
sscanf(str.local8Bit(),"%d,%d",&w,&h);
resize(w,h);
}
}
void Pab::saveConfig()
{
view->saveConfig();
KConfig *config = kapp->config();
config->setGroup("Geometry");
QRect r = geometry();
QString s;
s.sprintf("%i,%i", r.width(), r.height());
config->writeEntry("Browser", s);
config->sync();
}
Pab::~Pab()
{
saveConfig();
delete document;
}
void Pab::saveCe() {
kdDebug() << "saveCe()" << endl;
//xxx ce->save( "entry.txt" );
}
void Pab::saveProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
//what I want to save
//windowsize
//background image/underlining color/alternating color1,2
//chosen fields
//chosen fieldsWidths
// e.g., config->writeEntry("key", var);
}
void Pab::readProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
// e.g., var = config->readEntry("key");
}
void Pab::undo()
{
kdDebug() << "Pab::undo()" << endl;
UndoStack::instance()->undo();
}
void Pab::redo()
{
RedoStack::instance()->redo();
}
void Pab::updateEditMenu()
{
kdDebug() << "UpdateEditMenu()" << endl;
UndoStack *undo = UndoStack::instance();
RedoStack *redo = RedoStack::instance();
if (undo->isEmpty())
edit->changeItem( undoId, i18n( "Undo" ) );
else
edit->changeItem( undoId, i18n( "Undo" ) + " " + undo->top()->name() );
edit->setItemEnabled( undoId, !undo->isEmpty() );
if (redo->isEmpty())
edit->changeItem( redoId, i18n( "Redo" ) );
else
edit->changeItem( redoId, i18n( "Redo" ) + " " + redo->top()->name() );
edit->setItemEnabled( redoId, !redo->isEmpty() );
}
<commit_msg>Another patch from Michael Koch<commit_after>/*
* pab.cpp
*
* Copyright (C) 1999 Don Sanders <dsanders@kde.org>
*/
#include "abbrowser.h"
#include "browserentryeditor.h"
#include <qkeycode.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kglobal.h>
#include <kmenubar.h>
#include <kconfig.h>
#include <kaccel.h>
#include <kdebug.h>
#include "undo.h"
#include "browserwidget.h"
#include "entry.h"
Pab::Pab() : KMainWindow(0), DCOPObject("AbBrowserIface")
{
setCaption( i18n( "Address Book Browser" ));
document = new ContactEntryList();
view = new PabWidget( document, this, "Abbrowser" );
// tell the KMainWindow that this is indeed the main widget
setCentralWidget(view);
// create a popup menu -- in this case, the File menu
QPopupMenu* p = new QPopupMenu;
p->insertItem(i18n("&Sync"), this, SLOT(save()), CTRL+Key_S);
p->insertItem(i18n("&New Contact"), this, SLOT(newContact()), CTRL+Key_N);
/* p->insertItem(i18n("New &Group"), this, SLOT(newGroup()), CTRL+Key_G); */
p->insertSeparator();
p->insertItem(i18n("&Send Mail"), view, SLOT(sendMail()), CTRL+Key_Return);
p->insertSeparator();
p->insertItem(i18n("&Properties"), view, SLOT(properties()));
p->insertItem(i18n("&Delete\tDel"));
p->insertSeparator();
p->insertItem(i18n("&Quit"), kapp, SLOT(quit()), CTRL+Key_Q);
edit = new QPopupMenu;
undoId = edit->insertItem(i18n("Undo"), this, SLOT(undo()),
KStdAccel::key(KStdAccel::Undo));
redoId = edit->insertItem(i18n("Redo"), this, SLOT(redo()),
KStdAccel::key(KStdAccel::Redo));
edit->insertSeparator();
edit->insertItem(i18n("Cut"), view, SLOT(cut()), CTRL+Key_X);
edit->insertItem(i18n("Copy"), view, SLOT(copy()), CTRL+Key_C);
edit->insertItem(i18n("Paste"), view, SLOT(paste()), CTRL+Key_V);
edit->insertSeparator();
edit->insertItem(i18n("Select All"), view, SLOT(selectAll()), CTRL+Key_A);
edit->setItemEnabled( undoId, false );
edit->setItemEnabled( redoId, false );
QObject::connect( edit, SIGNAL( aboutToShow() ), this, SLOT( updateEditMenu() ));
QPopupMenu* v = new QPopupMenu;
v->insertItem(i18n("Choose Fields..."), view, SLOT(showSelectNameDialog()) );
v->insertItem(i18n("Options..."), view, SLOT(viewOptions()) );
v->insertSeparator();
v->insertItem(i18n("Restore defaults"), view, SLOT(defaultSettings()) );
// v->insertSeparator();
// v->insertItem(i18n("Refresh"), view, SLOT(refresh()), Key_F5 );
// put our newly created menu into the main menu bar
menuBar()->insertItem(i18n("&File"), p);
menuBar()->insertItem(i18n("&Edit"), edit);
menuBar()->insertItem(i18n("&View"), v);
menuBar()->insertSeparator();
// KDE will generate a short help menu automagically
p = helpMenu( i18n("Abbrowser --- KDE Address Book\n\n"
"(c) 2000AD The KDE PIM Team \n"));
menuBar()->insertItem(i18n("&Help"), p);
toolBar()->insertButton(BarIcon("filenew"), // icon
0, // button id
SIGNAL(clicked()), // action
this, SLOT(newContact()), // result
true, i18n("Add a new entry")); // tooltip text
toolBar()->insertButton(BarIcon("edit"), // icon
0, // button id
SIGNAL(clicked()), // action
view, SLOT(properties()), // result
true, i18n("Change this entry")); // tooltip text
toolBar()->insertButton(BarIcon("editdelete"), // icon
0, // button id
SIGNAL(clicked()), // action
view, SLOT(clear()), // result
true, i18n("Remove this entry")); // tooltip text
toolBar()->insertSeparator();
toolBar()->insertButton(BarIcon("mail_send"), // icon
0, // button id
SIGNAL(clicked()), // action
view, SLOT(sendMail()), // result
true, i18n("Send email")); // tooltip text
toolBar()->setFullSize(true);
// we do want a status bar
statusBar()->show();
connect( kapp, SIGNAL( aboutToQuit() ), this, SLOT( saveConfig() ) );
resize( sizeHint() );
readConfig();
}
void Pab::newContact()
{
ContactDialog *cd = new PabNewContactDialog( i18n( "Address Book Entry Editor" ), this, 0 );
connect( cd, SIGNAL( add( ContactEntry* ) ),
view, SLOT( addNewEntry( ContactEntry* ) ));
cd->show();
}
void Pab::addEmail( QString addr )
{
view->addEmail( addr );
return;
}
void Pab::save()
{
document->commit();
document->refresh();
view->saveConfig();
view->readConfig();
view->reconstructListView();
//xxx document->save( "entries.txt" );
UndoStack::instance()->clear();
RedoStack::instance()->clear();
}
void Pab::readConfig()
{
KConfig *config = kapp->config();
int w, h;
config->setGroup("Geometry");
QString str = config->readEntry("Browser", "");
if (!str.isEmpty() && str.find(',')>=0)
{
sscanf(str.local8Bit(),"%d,%d",&w,&h);
resize(w,h);
}
applyMainWindowSettings( config );
}
void Pab::saveConfig()
{
view->saveConfig();
KConfig *config = kapp->config();
config->setGroup("Geometry");
QRect r = geometry();
QString s;
s.sprintf("%i,%i", r.width(), r.height());
config->writeEntry("Browser", s);
saveMainWindowSettings( config );
config->sync();
}
Pab::~Pab()
{
saveConfig();
delete document;
}
void Pab::saveCe() {
kdDebug() << "saveCe()" << endl;
//xxx ce->save( "entry.txt" );
}
void Pab::saveProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
//what I want to save
//windowsize
//background image/underlining color/alternating color1,2
//chosen fields
//chosen fieldsWidths
// e.g., config->writeEntry("key", var);
}
void Pab::readProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
// e.g., var = config->readEntry("key");
}
void Pab::undo()
{
kdDebug() << "Pab::undo()" << endl;
UndoStack::instance()->undo();
}
void Pab::redo()
{
RedoStack::instance()->redo();
}
void Pab::updateEditMenu()
{
kdDebug() << "UpdateEditMenu()" << endl;
UndoStack *undo = UndoStack::instance();
RedoStack *redo = RedoStack::instance();
if (undo->isEmpty())
edit->changeItem( undoId, i18n( "Undo" ) );
else
edit->changeItem( undoId, i18n( "Undo" ) + " " + undo->top()->name() );
edit->setItemEnabled( undoId, !undo->isEmpty() );
if (redo->isEmpty())
edit->changeItem( redoId, i18n( "Redo" ) );
else
edit->changeItem( redoId, i18n( "Redo" ) + " " + redo->top()->name() );
edit->setItemEnabled( redoId, !redo->isEmpty() );
}
<|endoftext|> |
<commit_before>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/Point.h"
#include "mirtk/PointSet.h"
#include "mirtk/GenericImage.h"
#include "mirtk/PointSetIO.h"
#include "mirtk/PointSetUtils.h"
#include "mirtk/EuclideanDistanceTransform.h"
#include "vtkPolyData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkAppendFilter.h"
#include "vtkAppendPolyData.h"
#include "vtkCleanPolyData.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
cout << "\n";
cout << "Usage: " << name << " <input>... <output> [options]\n";
cout << "\n";
cout << "Description:\n";
cout << " Convert point set from one (file) format to another.\n";
cout << "\n";
cout << " If more than one input point sets is given, all input point sets\n";
cout << " are appended into a single point set before conversion. When all\n";
cout << " input point sets are of type vtkPolyData, the output point set\n";
cout << " is of type vtkPolyData. If more than one input point set is given\n";
cout << " and not all are of type vtkPolyData, the output point set is of type\n";
cout << " vtkUnstructuredGrid.\n";
cout << "\n";
cout << " The current implementation can only convert between different\n";
cout << " point set file formats based on the file name extension.\n";
cout << " Besides the common formats supported by VTK, it can also read/write\n";
cout << " BrainSuite .dfs files and write a Piecewise Linear Complex (PLC)\n";
cout << " B-Rep description in the TetGen formats .poly and .smesh. It also\n";
cout << " supports the Object File Format (.off) used by the CGAL library.\n";
cout << "\n";
cout << "Arguments:\n";
cout << " input Input point set file (.vtk, .vtp, .vtu, .stl, .ply, .off, .dfs, .obj).\n";
cout << " output Output point set file (.vtk, .vtp, .vtu, .stl, .ply, .off, .dfs, .node, .poly, .smesh).\n";
cout << "\n";
cout << "Optional arguments:\n";
cout << " -merge [<tol>] Merge points of non-polygonal input point sets.\n";
cout << " When only vtkPolyData are merged, the maximum distance between\n";
cout << " points to be merged can be optionally given as argument. (default: off)\n";
cout << " -holes Add a point inside the input surface meshes, except off the first input mesh,\n";
cout << " to the hole list of the output .poly or .smesh file. (default: no holes)\n";
cout << " -nocelldata Do not write cell data to output file. (default: off)\n";
cout << " -nopointdata Do not write point data to output file. (default: off)\n";
cout << " -ascii Write legacy VTK files encoded in ASCII. (default: off)\n";
cout << " -binary Write legacy VTK files in binary form. (default: on)\n";
cout << " -compress Compress XML VTK files. (default: on)\n";
cout << " -nocompress Do not compress XML VTK files. (default: off)\n";
PrintStandardOptions(cout);
cout << endl;
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
/// Get image attributes for implicit surface representation
ImageAttributes ImplicitSurfaceAttributes(vtkSmartPointer<vtkPolyData> surface)
{
ImageAttributes attr;
double bounds[6];
surface->GetBounds(bounds);
double ds = sqrt(pow(bounds[1] - bounds[0], 2) +
pow(bounds[3] - bounds[2], 2) +
pow(bounds[5] - bounds[4], 2)) / 128;
attr._xorigin = bounds[0] + .5 * (bounds[1] - bounds[0]);
attr._yorigin = bounds[2] + .5 * (bounds[3] - bounds[2]);
attr._zorigin = bounds[4] + .5 * (bounds[5] - bounds[4]);
attr._x = int(ceil((bounds[1] - bounds[0]) / ds));
attr._y = int(ceil((bounds[3] - bounds[2]) / ds));
attr._z = int(ceil((bounds[5] - bounds[4]) / ds));
attr._dx = ds;
attr._dy = ds;
attr._dz = ds;
return attr;
}
// -----------------------------------------------------------------------------
/// Get binary mask of region enclosed by surface
void GetSurfaceMask(vtkSmartPointer<vtkPolyData> surface, BinaryImage &mask)
{
surface = vtkPolyData::SafeDownCast(WorldToImage(surface, &mask));
vtkSmartPointer<vtkImageData> vtkmask = NewVtkMask(mask.X(), mask.Y(), mask.Z());
vtkSmartPointer<vtkImageStencilData> stencil = ImageStencil(vtkmask, surface);
ImageStencilToMask(stencil, vtkmask);
mask.CopyFrom(reinterpret_cast<BinaryPixel *>(vtkmask->GetScalarPointer()));
}
// -----------------------------------------------------------------------------
/// Compute signed distance map
void ComputeDistanceMap(vtkSmartPointer<vtkPolyData> surface, const BinaryImage &mask, bool invert, RealImage &dmap)
{
const int nvox = mask.NumberOfSpatialVoxels();
// Initialize distance map
dmap.Initialize(mask.Attributes(), 1);
if (invert) {
for (int vox = 0; vox < nvox; ++vox) {
if (mask(vox)) dmap(vox) = 0.0;
else dmap(vox) = 1.0;
}
} else {
for (int vox = 0; vox < nvox; ++vox) {
if (mask(vox)) dmap(vox) = 1.0;
else dmap(vox) = 0.0;
}
}
// Calculate Euclidean distance transforms
typedef EuclideanDistanceTransform<RealPixel> DistanceTransform;
DistanceTransform edt(DistanceTransform::DT_3D);
edt.Input (&dmap);
edt.Output(&dmap);
edt.Run();
for (int vox = 0; vox < nvox; ++vox) {
dmap(vox) = sqrt(dmap(vox));
}
if (invert) dmap *= -1.0;
}
// -----------------------------------------------------------------------------
/// Get a point inside with maximum distance from the implicit surface
bool GetPointInside(const RealImage &dmap, Point &p)
{
const int nvox = dmap.NumberOfSpatialVoxels();
int idx = -1, i, j, k;
double dist = .0;
for (int vox = 0; vox < nvox; ++vox) {
if (dmap(vox) < dist) {
idx = vox;
dist = dmap(vox);
}
}
if (idx == -1) return false;
dmap.IndexToVoxel(idx, i, j, k);
p._x = i, p._y = j, p._z = k;
dmap.ImageToWorld(p);
return true;
}
// -----------------------------------------------------------------------------
/// Get a point inside with maximum distance from the surface mesh
bool GetPointInside(vtkSmartPointer<vtkPointSet> &pointset, Point &p)
{
vtkSmartPointer<vtkPolyData> surface = DataSetSurface(pointset);
BinaryImage mask(ImplicitSurfaceAttributes(surface));
RealImage dmap;
GetSurfaceMask(surface, mask);
ComputeDistanceMap(surface, mask, true, dmap);
return GetPointInside(dmap, p);
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
REQUIRES_POSARGS(2);
// Positional arguments
Array<const char *> input_names(NUM_POSARGS - 1, NULL);
for (int i = 1; i < NUM_POSARGS; ++i) input_names[i-1] = POSARG(i);
const char *output_name = POSARG(NUM_POSARGS);
// Optional arguments
bool pointdata = true;
bool celldata = true;
bool merge = false;
bool with_holes = false;
double merge_tol = 1e-6;
FileOption fopt = FO_Default;
for (ALL_OPTIONS) {
if (OPTION("-nopointdata")) pointdata = false;
else if (OPTION("-nocelldata")) celldata = false;
else if (OPTION("-merge")) {
merge = true;
if (HAS_ARGUMENT) PARSE_ARGUMENT(merge_tol);
}
else if (OPTION("-holes")) with_holes = true;
else HANDLE_POINTSETIO_OPTION(fopt);
else HANDLE_COMMON_OR_UNKNOWN_OPTION();
}
// Read input point sets
Array<vtkSmartPointer<vtkPointSet> > pointsets(input_names.size());
for (size_t i = 0; i < input_names.size(); ++i) {
FileOption opt;
pointsets[i] = ReadPointSet(input_names[i], opt);
if (fopt == FO_Default) fopt = opt;
}
// Combine point sets into single point set
vtkSmartPointer<vtkPointSet> output;
if (pointsets.size() == 1) {
output = pointsets[0];
} else {
bool output_polydata = true;
for (size_t i = 0; i < pointsets.size(); ++i) {
if (vtkPolyData::SafeDownCast(pointsets[i]) == NULL) {
output_polydata = false;
break;
}
}
if (output_polydata) {
vtkNew<vtkAppendPolyData> append;
for (size_t i = 0; i < pointsets.size(); ++i) {
AddVTKInput(append, vtkPolyData::SafeDownCast(pointsets[i]));
}
append->Update();
output = append->GetOutput();
} else {
vtkNew<vtkAppendFilter> append;
for (size_t i = 0; i < pointsets.size(); ++i) {
AddVTKInput(append, pointsets[i]);
}
append->SetMergePoints(merge);
append->Update();
output = append->GetOutput();
}
}
// Merge points
if (merge && vtkPolyData::SafeDownCast(output) != nullptr) {
vtkNew<vtkCleanPolyData> merger;
merger->ConvertLinesToPointsOff();
merger->ConvertPolysToLinesOff();
merger->ConvertStripsToPolysOn();
merger->PointMergingOn();
merger->ToleranceIsAbsoluteOn();
merger->SetAbsoluteTolerance(merge_tol);
SetVTKInput(merger, output);
merger->Update();
output = merger->GetOutput();
}
// Reset point/cell data
if (!pointdata) output->GetPointData()->Initialize();
if (!celldata ) output->GetCellData ()->Initialize();
// Write TetGen .poly/.smesh with holes list
if (with_holes && input_names.size() > 1) {
const std::string ext = Extension(output_name);
if (ext == ".poly" || ext == ".smesh") {
vtkSmartPointer<vtkPolyData> surface = vtkPolyData::SafeDownCast(output);
if (surface == NULL) {
FatalError("Can only save surface meshes (vtkPolyData) to " << ext << " file");
}
int ok = 0;
Point hole;
PointSet holes;
holes.Reserve(static_cast<int>(pointsets.size()) - 1);
for (size_t i = 1; i < pointsets.size(); ++i) {
if (GetPointInside(pointsets[i], hole)) {
if (verbose) cout << "Add hole at [" << hole << "]" << endl;
holes.Add(hole);
}
}
if (ext == ".poly") ok = WriteTetGenPoly (output_name, surface, &holes);
else ok = WriteTetGenSMesh(output_name, surface, &holes);
if (!ok) {
FatalError("Failed to write output point set to " << output_name);
}
return 0;
}
}
// Write output point set
if (!WritePointSet(output_name, output, fopt)) {
FatalError("Failed to write output point set to " << output_name);
exit(1);
}
return 0;
}
<commit_msg>enh: Support .csv, .tsv, and .txt output in convert-pointset [Applications]<commit_after>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/Point.h"
#include "mirtk/PointSet.h"
#include "mirtk/GenericImage.h"
#include "mirtk/PointSetIO.h"
#include "mirtk/PointSetUtils.h"
#include "mirtk/EuclideanDistanceTransform.h"
#include "vtkPolyData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkAppendFilter.h"
#include "vtkAppendPolyData.h"
#include "vtkCleanPolyData.h"
using namespace mirtk;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
cout << "\n";
cout << "Usage: " << name << " <input>... <output> [options]\n";
cout << "\n";
cout << "Description:\n";
cout << " Convert point set from one (file) format to another.\n";
cout << "\n";
cout << " If more than one input point sets is given, all input point sets\n";
cout << " are appended into a single point set before conversion. When all\n";
cout << " input point sets are of type vtkPolyData, the output point set\n";
cout << " is of type vtkPolyData. If more than one input point set is given\n";
cout << " and not all are of type vtkPolyData, the output point set is of type\n";
cout << " vtkUnstructuredGrid.\n";
cout << "\n";
cout << " The current implementation can only convert between different\n";
cout << " point set file formats based on the file name extension.\n";
cout << " Besides the common formats supported by VTK, it can also read/write\n";
cout << " BrainSuite .dfs files and write a Piecewise Linear Complex (PLC)\n";
cout << " B-Rep description in the TetGen formats .poly and .smesh. It also\n";
cout << " supports the Object File Format (.off) used by the CGAL library.\n";
cout << "\n";
cout << "Arguments:\n";
cout << " input Input point set file (.vtk, .vtp, .vtu, .stl, .ply, .off, .dfs, .obj).\n";
cout << " output Output point set file (.vtk, .vtp, .vtu, .stl, .ply, .off, .dfs,\n";
cout << " .node, .poly, .smesh, .gii, .csv, .tsv, .txt).\n";
cout << "\n";
cout << "Optional arguments:\n";
cout << " -merge [<tol>] Merge points of non-polygonal input point sets.\n";
cout << " When only vtkPolyData are merged, the maximum distance between\n";
cout << " points to be merged can be optionally given as argument. (default: off)\n";
cout << " -holes Add a point inside the input surface meshes, except off the first input mesh,\n";
cout << " to the hole list of the output .poly or .smesh file. (default: no holes)\n";
cout << " -nocelldata Do not write cell data to output file. (default: off)\n";
cout << " -nopointdata Do not write point data to output file. (default: off)\n";
cout << " -nopoints Do not write point coordinates to output .csv, .tsv, or .txt file.\n";
cout << " This option is implicit when the output file name ends with\n";
cout << " .attr.csv, .attr.tsv, or .attr.txt (default: off)\n";
cout << " -ascii Write legacy VTK files encoded in ASCII. (default: off)\n";
cout << " -binary Write legacy VTK files in binary form. (default: on)\n";
cout << " -compress Compress XML VTK files. (default: on)\n";
cout << " -nocompress Do not compress XML VTK files. (default: off)\n";
PrintStandardOptions(cout);
cout << endl;
}
// =============================================================================
// Auxiliaries
// =============================================================================
// -----------------------------------------------------------------------------
/// Get image attributes for implicit surface representation
ImageAttributes ImplicitSurfaceAttributes(vtkSmartPointer<vtkPolyData> surface)
{
ImageAttributes attr;
double bounds[6];
surface->GetBounds(bounds);
double ds = sqrt(pow(bounds[1] - bounds[0], 2) +
pow(bounds[3] - bounds[2], 2) +
pow(bounds[5] - bounds[4], 2)) / 128;
attr._xorigin = bounds[0] + .5 * (bounds[1] - bounds[0]);
attr._yorigin = bounds[2] + .5 * (bounds[3] - bounds[2]);
attr._zorigin = bounds[4] + .5 * (bounds[5] - bounds[4]);
attr._x = int(ceil((bounds[1] - bounds[0]) / ds));
attr._y = int(ceil((bounds[3] - bounds[2]) / ds));
attr._z = int(ceil((bounds[5] - bounds[4]) / ds));
attr._dx = ds;
attr._dy = ds;
attr._dz = ds;
return attr;
}
// -----------------------------------------------------------------------------
/// Get binary mask of region enclosed by surface
void GetSurfaceMask(vtkSmartPointer<vtkPolyData> surface, BinaryImage &mask)
{
surface = vtkPolyData::SafeDownCast(WorldToImage(surface, &mask));
vtkSmartPointer<vtkImageData> vtkmask = NewVtkMask(mask.X(), mask.Y(), mask.Z());
vtkSmartPointer<vtkImageStencilData> stencil = ImageStencil(vtkmask, surface);
ImageStencilToMask(stencil, vtkmask);
mask.CopyFrom(reinterpret_cast<BinaryPixel *>(vtkmask->GetScalarPointer()));
}
// -----------------------------------------------------------------------------
/// Compute signed distance map
void ComputeDistanceMap(vtkSmartPointer<vtkPolyData> surface, const BinaryImage &mask, bool invert, RealImage &dmap)
{
const int nvox = mask.NumberOfSpatialVoxels();
// Initialize distance map
dmap.Initialize(mask.Attributes(), 1);
if (invert) {
for (int vox = 0; vox < nvox; ++vox) {
if (mask(vox)) dmap(vox) = 0.0;
else dmap(vox) = 1.0;
}
} else {
for (int vox = 0; vox < nvox; ++vox) {
if (mask(vox)) dmap(vox) = 1.0;
else dmap(vox) = 0.0;
}
}
// Calculate Euclidean distance transforms
typedef EuclideanDistanceTransform<RealPixel> DistanceTransform;
DistanceTransform edt(DistanceTransform::DT_3D);
edt.Input (&dmap);
edt.Output(&dmap);
edt.Run();
for (int vox = 0; vox < nvox; ++vox) {
dmap(vox) = sqrt(dmap(vox));
}
if (invert) dmap *= -1.0;
}
// -----------------------------------------------------------------------------
/// Get a point inside with maximum distance from the implicit surface
bool GetPointInside(const RealImage &dmap, Point &p)
{
const int nvox = dmap.NumberOfSpatialVoxels();
int idx = -1, i, j, k;
double dist = .0;
for (int vox = 0; vox < nvox; ++vox) {
if (dmap(vox) < dist) {
idx = vox;
dist = dmap(vox);
}
}
if (idx == -1) return false;
dmap.IndexToVoxel(idx, i, j, k);
p._x = i, p._y = j, p._z = k;
dmap.ImageToWorld(p);
return true;
}
// -----------------------------------------------------------------------------
/// Get a point inside with maximum distance from the surface mesh
bool GetPointInside(vtkSmartPointer<vtkPointSet> &pointset, Point &p)
{
vtkSmartPointer<vtkPolyData> surface = DataSetSurface(pointset);
BinaryImage mask(ImplicitSurfaceAttributes(surface));
RealImage dmap;
GetSurfaceMask(surface, mask);
ComputeDistanceMap(surface, mask, true, dmap);
return GetPointInside(dmap, p);
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
REQUIRES_POSARGS(2);
// Positional arguments
Array<const char *> input_names(NUM_POSARGS - 1, NULL);
for (int i = 1; i < NUM_POSARGS; ++i) input_names[i-1] = POSARG(i);
const char *output_name = POSARG(NUM_POSARGS);
// Optional arguments
bool pointdata = true;
bool celldata = true;
bool pointcoords = true;
bool merge = false;
bool with_holes = false;
double merge_tol = 1e-6;
FileOption fopt = FO_Default;
for (ALL_OPTIONS) {
if (OPTION("-nopointdata")) pointdata = false;
else if (OPTION("-nocelldata")) celldata = false;
else if (OPTION("-nopoints")) pointcoords = false;
else if (OPTION("-merge")) {
merge = true;
if (HAS_ARGUMENT) PARSE_ARGUMENT(merge_tol);
}
else if (OPTION("-holes")) with_holes = true;
else HANDLE_POINTSETIO_OPTION(fopt);
else HANDLE_COMMON_OR_UNKNOWN_OPTION();
}
// Output file name extension
const string ext = Extension(output_name);
// Read input point sets
Array<vtkSmartPointer<vtkPointSet> > pointsets(input_names.size());
for (size_t i = 0; i < input_names.size(); ++i) {
FileOption opt;
pointsets[i] = ReadPointSet(input_names[i], opt);
if (fopt == FO_Default) fopt = opt;
}
// Combine point sets into single point set
vtkSmartPointer<vtkPointSet> output;
if (pointsets.size() == 1) {
output = pointsets[0];
} else {
bool output_polydata = true;
for (size_t i = 0; i < pointsets.size(); ++i) {
if (vtkPolyData::SafeDownCast(pointsets[i]) == NULL) {
output_polydata = false;
break;
}
}
if (output_polydata) {
vtkNew<vtkAppendPolyData> append;
for (size_t i = 0; i < pointsets.size(); ++i) {
AddVTKInput(append, vtkPolyData::SafeDownCast(pointsets[i]));
}
append->Update();
output = append->GetOutput();
} else {
vtkNew<vtkAppendFilter> append;
for (size_t i = 0; i < pointsets.size(); ++i) {
AddVTKInput(append, pointsets[i]);
}
append->SetMergePoints(merge);
append->Update();
output = append->GetOutput();
}
}
// Merge points
if (merge && vtkPolyData::SafeDownCast(output) != nullptr) {
vtkNew<vtkCleanPolyData> merger;
merger->ConvertLinesToPointsOff();
merger->ConvertPolysToLinesOff();
merger->ConvertStripsToPolysOn();
merger->PointMergingOn();
merger->ToleranceIsAbsoluteOn();
merger->SetAbsoluteTolerance(merge_tol);
SetVTKInput(merger, output);
merger->Update();
output = merger->GetOutput();
}
// Reset point/cell data
if (!pointdata) output->GetPointData()->Initialize();
if (!celldata ) output->GetCellData ()->Initialize();
// Write .csv, .tsv, and .txt with or without point coordinates
if (ext == ".csv" || ext == ".tsv" || ext == ".txt") {
char sep = ',';
if (ext == ".tsv") sep = '\t';
string type = output_name;
type = type.substr(0, type.length() - ext.length());
type = Extension(type, EXT_Last);
if (type == ".attr") pointcoords = false;
if (!WritePointSetTable(output_name, output, pointcoords, sep)) {
FatalError("Failed to write output point set to " << output_name);
}
return 0;
}
// Write TetGen .poly/.smesh with holes list
if (with_holes && input_names.size() > 1) {
if (ext == ".poly" || ext == ".smesh") {
vtkSmartPointer<vtkPolyData> surface = vtkPolyData::SafeDownCast(output);
if (surface == NULL) {
FatalError("Can only save surface meshes (vtkPolyData) to " << ext << " file");
}
int ok = 0;
Point hole;
PointSet holes;
holes.Reserve(static_cast<int>(pointsets.size()) - 1);
for (size_t i = 1; i < pointsets.size(); ++i) {
if (GetPointInside(pointsets[i], hole)) {
if (verbose) cout << "Add hole at [" << hole << "]" << endl;
holes.Add(hole);
}
}
if (ext == ".poly") ok = WriteTetGenPoly (output_name, surface, &holes);
else ok = WriteTetGenSMesh(output_name, surface, &holes);
if (!ok) {
FatalError("Failed to write output point set to " << output_name);
}
return 0;
}
}
// Write output point set
if (!WritePointSet(output_name, output, fopt)) {
FatalError("Failed to write output point set to " << output_name);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
FileStorage fs("../calibrate/out_camera_data.xml", FileStorage::READ);
Mat intrinsics, distortion;
fs["Camera_Matrix"] >> intrinsics;
fs["Distortion_Coefficients"] >> distortion;
if (intrinsics.rows != 3 || intrinsics.cols != 3 || distortion.rows != 5 || distortion.cols != 1) {
cout << "Run calibration (in ../calibrate/) first!" << endl;
return 1;
}
VideoCapture cap(0);
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat image;
for (;;) {
cap >> image;
Mat grayImage;
cvtColor(image, grayImage, CV_RGB2GRAY);
Mat blurredImage;
blur(grayImage, blurredImage, Size(5, 5));
Mat threshImage;
threshold(blurredImage, threshImage, 128.0, 255.0, THRESH_OTSU);
vector<vector<Point> > contours;
findContours(threshImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
Scalar color(0, 255, 0);
vector<Mat> squares;
for (auto contour : contours) {
vector<Point> approx;
approxPolyDP(contour, approx, arcLength(Mat(contour), true)*0.02, true);
if( approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)) )
{
Mat squareMat;
Mat(approx).convertTo(squareMat, CV_32FC3);
squares.push_back(squareMat);
}
}
if (squares.size() > 0) {
vector<Point3f> objectPoints = {Point3f(-1, -1, 0), Point3f(-1, 1, 0), Point3f(1, 1, 0), Point3f(1, -1, 0)};
Mat objectPointsMat(objectPoints);
cout << "objectPointsMat: " << objectPointsMat.rows << ", " << objectPointsMat.cols << endl;
cout << "squares[0]: " << squares[0].size() << endl;
Mat rvec;
Mat tvec;
solvePnP(objectPointsMat, squares[0], intrinsics, distortion, rvec, tvec);
cout << rvec << endl;
cout << tvec << endl;
}
// drawContours(image, squares, -1, color);
cv::imshow("image", image);
}
return 0;
}
<commit_msg>Draw outline of selected square.<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void drawQuad(Mat image, Mat points, Scalar color) {
cout << points.at<Point2f>(0,0) << " " << points.at<Point2f>(0,1) << " " << points.at<Point2f>(0,2) << " " << points.at<Point2f>(0,3) << endl;
line(image, points.at<Point2f>(0,0), points.at<Point2f>(0,1), color);
line(image, points.at<Point2f>(0,1), points.at<Point2f>(0,2), color);
line(image, points.at<Point2f>(0,2), points.at<Point2f>(0,3), color);
line(image, points.at<Point2f>(0,3), points.at<Point2f>(0,0), color);
}
int main(int argc, char** argv) {
FileStorage fs("../calibrate/out_camera_data.xml", FileStorage::READ);
Mat intrinsics, distortion;
fs["Camera_Matrix"] >> intrinsics;
fs["Distortion_Coefficients"] >> distortion;
if (intrinsics.rows != 3 || intrinsics.cols != 3 || distortion.rows != 5 || distortion.cols != 1) {
cout << "Run calibration (in ../calibrate/) first!" << endl;
return 1;
}
VideoCapture cap(0);
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat image;
for (;;) {
cap >> image;
Mat grayImage;
cvtColor(image, grayImage, CV_RGB2GRAY);
Mat blurredImage;
blur(grayImage, blurredImage, Size(5, 5));
Mat threshImage;
threshold(blurredImage, threshImage, 128.0, 255.0, THRESH_OTSU);
vector<vector<Point> > contours;
findContours(threshImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
Scalar color(0, 255, 0);
// drawContours(image, contours, -1, color);
vector<Mat> squares;
for (auto contour : contours) {
vector<Point> approx;
approxPolyDP(contour, approx, arcLength(Mat(contour), true)*0.02, true);
if( approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)) )
{
Mat squareMat;
Mat(approx).convertTo(squareMat, CV_32FC3);
squares.push_back(squareMat);
}
}
if (squares.size() > 0) {
vector<Point3f> objectPoints = {Point3f(-1, -1, 0), Point3f(-1, 1, 0), Point3f(1, 1, 0), Point3f(1, -1, 0)};
Mat objectPointsMat(objectPoints);
cout << "objectPointsMat: " << objectPointsMat.rows << ", " << objectPointsMat.cols << endl;
cout << "squares[0]: " << squares[0] << endl;
Mat rvec;
Mat tvec;
solvePnP(objectPointsMat, squares[0], intrinsics, distortion, rvec, tvec);
cout << "rvec = " << rvec << endl;
cout << "tvec = " << tvec << endl;
drawQuad(image, squares[0], color);
}
cv::imshow("image", image);
cv::waitKey(1);
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/external_texture_gl.h"
namespace flutter {
struct ExternalTextureGLState {
GLuint gl_texture = 0;
};
ExternalTextureGL::ExternalTextureGL(
FlutterDesktopPixelBufferTextureCallback texture_callback,
void* user_data,
const GlProcs& gl_procs)
: state_(std::make_unique<ExternalTextureGLState>()),
texture_callback_(texture_callback),
user_data_(user_data),
gl_(gl_procs) {}
ExternalTextureGL::~ExternalTextureGL() {
const auto& gl = GlProcs();
if (state_->gl_texture != 0) {
gl_.glDeleteTextures(1, &state_->gl_texture);
}
}
bool ExternalTextureGL::PopulateTexture(size_t width,
size_t height,
FlutterOpenGLTexture* opengl_texture) {
if (!CopyPixelBuffer(width, height)) {
return false;
}
// Populate the texture object used by the engine.
opengl_texture->target = GL_TEXTURE_2D;
opengl_texture->name = state_->gl_texture;
opengl_texture->format = GL_RGBA8;
opengl_texture->destruction_callback = nullptr;
opengl_texture->user_data = nullptr;
opengl_texture->width = width;
opengl_texture->height = height;
return true;
}
bool ExternalTextureGL::CopyPixelBuffer(size_t& width, size_t& height) {
const FlutterDesktopPixelBuffer* pixel_buffer =
texture_callback_(width, height, user_data_);
if (!pixel_buffer || !pixel_buffer->buffer) {
return false;
}
width = pixel_buffer->width;
height = pixel_buffer->height;
if (state_->gl_texture == 0) {
gl_.glGenTextures(1, &state_->gl_texture);
gl_.glBindTexture(GL_TEXTURE_2D, state_->gl_texture);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
gl_.glBindTexture(GL_TEXTURE_2D, state_->gl_texture);
}
gl_.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixel_buffer->width,
pixel_buffer->height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixel_buffer->buffer);
if (pixel_buffer->release_callback) {
pixel_buffer->release_callback(pixel_buffer->release_context);
}
return true;
}
} // namespace flutter
<commit_msg>[Win32] Eliminate use of OpenGL ES 3.1 symbols (#32780)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/external_texture_gl.h"
namespace flutter {
struct ExternalTextureGLState {
GLuint gl_texture = 0;
};
ExternalTextureGL::ExternalTextureGL(
FlutterDesktopPixelBufferTextureCallback texture_callback,
void* user_data,
const GlProcs& gl_procs)
: state_(std::make_unique<ExternalTextureGLState>()),
texture_callback_(texture_callback),
user_data_(user_data),
gl_(gl_procs) {}
ExternalTextureGL::~ExternalTextureGL() {
const auto& gl = GlProcs();
if (state_->gl_texture != 0) {
gl_.glDeleteTextures(1, &state_->gl_texture);
}
}
bool ExternalTextureGL::PopulateTexture(size_t width,
size_t height,
FlutterOpenGLTexture* opengl_texture) {
if (!CopyPixelBuffer(width, height)) {
return false;
}
// Populate the texture object used by the engine.
opengl_texture->target = GL_TEXTURE_2D;
opengl_texture->name = state_->gl_texture;
opengl_texture->format = GL_RGBA;
opengl_texture->destruction_callback = nullptr;
opengl_texture->user_data = nullptr;
opengl_texture->width = width;
opengl_texture->height = height;
return true;
}
bool ExternalTextureGL::CopyPixelBuffer(size_t& width, size_t& height) {
const FlutterDesktopPixelBuffer* pixel_buffer =
texture_callback_(width, height, user_data_);
if (!pixel_buffer || !pixel_buffer->buffer) {
return false;
}
width = pixel_buffer->width;
height = pixel_buffer->height;
if (state_->gl_texture == 0) {
gl_.glGenTextures(1, &state_->gl_texture);
gl_.glBindTexture(GL_TEXTURE_2D, state_->gl_texture);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl_.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
gl_.glBindTexture(GL_TEXTURE_2D, state_->gl_texture);
}
gl_.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixel_buffer->width,
pixel_buffer->height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixel_buffer->buffer);
if (pixel_buffer->release_callback) {
pixel_buffer->release_callback(pixel_buffer->release_context);
}
return true;
}
} // namespace flutter
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basereader.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:43: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
*
************************************************************************/
#ifndef BASEREADER_HXX_INCLUDED
#include "internal/basereader.hxx"
#endif
#ifndef XML_PARSER_HXX_INCLUDED
#include "internal/xml_parser.hxx"
#endif
#include "assert.h"
#include <memory>
/** constructor of CBaseReader.
*/
CBaseReader::CBaseReader(const std::string& DocumentName):
m_ZipFile( DocumentName )
{
}
//------------------------------
//
//------------------------------
CBaseReader::~CBaseReader()
{
}
//------------------------------
//
//------------------------------
void CBaseReader::start_document()
{
}
//------------------------------
//
//------------------------------
void CBaseReader::end_document()
{
}
/** Read interested tag content into respective structure then start parsing process.
@param ContentName
the xml file name in the zipped document which we interest.
*/
void CBaseReader::Initialize( const std::string& ContentName)
{
try
{
if (m_ZipContent.empty())
m_ZipFile.GetUncompressedContent( ContentName, m_ZipContent );
xml_parser parser;
parser.set_document_handler(this); // pass current reader as reader to the sax parser
parser.parse(&m_ZipContent[0], m_ZipContent.size());
}
catch(std::exception& ex)
{
ENSURE( false, ex.what() );
}
catch(...)
{
ENSURE(false, "Unknown error");
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.3.14); FILE MERGED 2006/03/10 15:10:57 pl 1.3.14.1: #i55991# removed warnings for windows platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basereader.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 14:15:13 $
*
* 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 BASEREADER_HXX_INCLUDED
#include "internal/basereader.hxx"
#endif
#ifndef XML_PARSER_HXX_INCLUDED
#include "internal/xml_parser.hxx"
#endif
#include "assert.h"
#include <memory>
/** constructor of CBaseReader.
*/
CBaseReader::CBaseReader(const std::string& DocumentName):
m_ZipFile( DocumentName )
{
}
//------------------------------
//
//------------------------------
CBaseReader::~CBaseReader()
{
}
//------------------------------
//
//------------------------------
void CBaseReader::start_document()
{
}
//------------------------------
//
//------------------------------
void CBaseReader::end_document()
{
}
/** Read interested tag content into respective structure then start parsing process.
@param ContentName
the xml file name in the zipped document which we interest.
*/
void CBaseReader::Initialize( const std::string& ContentName)
{
try
{
if (m_ZipContent.empty())
m_ZipFile.GetUncompressedContent( ContentName, m_ZipContent );
xml_parser parser;
parser.set_document_handler(this); // pass current reader as reader to the sax parser
parser.parse(&m_ZipContent[0], m_ZipContent.size());
}
catch(std::exception&
#if OSL_DEBUG_LEVEL > 0
ex
#endif
)
{
ENSURE( false, ex.what() );
}
catch(...)
{
ENSURE(false, "Unknown error");
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <mbed.h>
#include <rtos.h>
#include <algorithm>
#include <vector>
#include <functional>
template <class T>
class CommPort {
public:
// Constructor
CommPort()
: is_open(false),
rx_packets(0),
tx_packets(0),
rx_callback(nullptr),
tx_callback(nullptr) {
Nbr(0);
resetPacketCount();
};
CommPort(uint8_t number, std::function<T> rxC = nullptr,
std::function<T> txC = nullptr)
: is_open(false), rx_callback(rxC), tx_callback(txC) {
Nbr(number);
resetPacketCount();
};
// Compare between 2 CommPort objects
bool operator==(const CommPort& p) const {
return (this->Nbr() == p.Nbr());
}
// Compare between a CommPort object and a port number
bool operator==(unsigned int portNbr) const {
return (this->Nbr() == portNbr ? true : false);
}
// Overload the less than operator for sorting/finding ports using iterators
bool operator<(const CommPort& p) const {
return (this->Nbr() < p.Nbr() ? true : false);
}
uint8_t Nbr() const { return this->nbr; }
bool valid() const { return nbr != 0; }
void Nbr(uint8_t _nbr) { nbr = _nbr; }
// Open a port or check if a port is capable of providing communication.
bool Open() {
if (isReady()) {
this->is_open = true;
return isOpen();
} else {
return false;
}
}
void Close() { is_open = false; }
// Check if the port has already been opened.
bool isOpen() const { return this->is_open; }
bool isClosed() const { return !isOpen(); }
// Set functions for each RX/TX callback.
const CommPort<T>& RXCallback(const std::function<T>& func) {
rx_callback = func;
return *this;
}
const CommPort<T>& TXCallback(const std::function<T>& func) {
tx_callback = func;
return *this;
}
// Methods that return a reference to the TX/RX callback function pointers
std::function<T>& RXCallback() { return rx_callback; }
std::function<T>& TXCallback() { return tx_callback; }
// Check if an RX/TX callback function has been set for the port.
bool hasTXCallback() const { return tx_callback != nullptr; }
bool hasRXCallback() const { return rx_callback != nullptr; }
// Check if the port object is a valid port
// this will be false when indexing a non-existent port number
bool Exists() const {
return (hasRXCallback() || hasTXCallback()) && valid();
}
// Get a value or reference to the TX/RX packet count for modifying
unsigned int TXPackets() const { return tx_packets; }
unsigned int RXPackets() const { return rx_packets; }
// unsigned int& TXPackets() { return tx_packets; }
// unsigned int& RXPackets() { return rx_packets; }
void incTxCount() { tx_packets++; }
void incRxCount() { rx_packets++; }
// Standard display function for a CommPort
void PrintPort() const {
printf("%2u\t\t%u\t%u\t%s\t\t%s\t\t%s\r\n", Nbr(), RXPackets(),
TXPackets(), hasRXCallback() ? "YES" : "NO",
hasTXCallback() ? "YES" : "NO", isOpen() ? "OPEN" : "CLOSED");
Console::Instance()->Flush();
}
// Returns the current packet counts to zero
void resetPacketCount() {
rx_packets = 0;
tx_packets = 0;
}
protected:
// Returns true if the port can provide an RX callback routine
bool isReady() const { return (is_open ? true : hasRXCallback()); }
private:
// The number assigned to the port
uint8_t nbr;
// If the port is open, it will also be valid
bool is_open;
// Where each upstream & downstream packet count is stored
unsigned int rx_packets;
unsigned int tx_packets;
// the class members that hold the function pointers
std::function<T> rx_callback;
std::function<T> tx_callback;
};
// Function for defining how to sort a std::vector of CommPort objects
template <class T>
bool PortCompare(const CommPort<T>& a, const CommPort<T>& b) {
return a < b;
}
// Class to manage the available/unavailable ports
template <class T>
class CommPorts : CommPort<T> {
private:
typename std::vector<CommPort<T>> ports;
typename std::vector<CommPort<T>>::iterator pIt;
CommPort<T> blackhole_port;
const CommPorts<T>& sort() {
std::sort(ports.begin(), ports.end(), PortCompare<T>);
return *this;
}
const CommPorts<T>& add(const CommPort<T>& p) {
pIt = find(ports.begin(), ports.end(), p);
if (pIt == ports.end()) {
ports.push_back(p);
}
return this->sort();
}
public:
// constructor
CommPorts<T>() {
// create a null port that we can return for invalid indexing for the []
// operator
blackhole_port = CommPort<T>();
}
CommPorts<T> operator+=(const CommPort<T>& p) {
return this->add(CommPort<T>(p));
}
CommPort<T>& operator[](const int portNbr) {
pIt = find(ports.begin(), ports.end(), (unsigned int)portNbr);
if (pIt != ports.end()) {
return *&(*pIt);
}
return blackhole_port;
// throw std::runtime_error("No port for the given number");
}
int count() const { return ports.size(); }
int count_open() const {
int count = 0;
for (auto it = ports.begin(); it != ports.end(); ++it) {
if (it->isOpen()) count++;
}
return count;
}
bool empty() const { return ports.empty(); }
// Get the total count (across all ports) of each RX/TX packet count
unsigned int allRXPackets() const {
unsigned int pcks = 0;
for (auto it = ports.begin(); it != ports.end(); ++it) {
pcks += static_cast<unsigned int>(it->RXPackets());
}
return pcks;
}
unsigned int allTXPackets() const {
unsigned int pcks = 0;
for (auto it = ports.begin(); it != ports.end(); ++it) {
pcks += static_cast<unsigned int>(it->TXPackets());
}
return pcks;
}
void PrintPorts() {
if (empty() == false) {
PrintHeader();
for (auto it = ports.begin(); it != ports.end(); ++it) {
it->PrintPort();
}
}
}
void PrintHeader() {
printf("PORT\t\tIN\tOUT\tRX CBCK\t\tTX CBCK\t\tSTATE\r\n");
Console::Instance()->Flush();
}
void PrintFooter() {
printf(
"==========================\r\n"
"Total:\t\t%u\t%u\r\n",
allRXPackets(), allTXPackets());
Console::Instance()->Flush();
}
};
<commit_msg>camelcase, modern for loop syntax<commit_after>#pragma once
#include <mbed.h>
#include <rtos.h>
#include <algorithm>
#include <vector>
#include <functional>
template <class T>
class CommPort {
public:
// Constructor
CommPort() : _isOpen(false), _rxCallback(nullptr), _txCallback(nullptr) {
Nbr(0);
resetPacketCount();
};
CommPort(uint8_t number, std::function<T> rxC = nullptr,
std::function<T> txC = nullptr)
: _isOpen(false), _rxCallback(rxC), _txCallback(txC) {
Nbr(number);
resetPacketCount();
};
// Compare between 2 CommPort objects
bool operator==(const CommPort& p) const {
return (this->Nbr() == p.Nbr());
}
// Compare between a CommPort object and a port number
bool operator==(unsigned int portNbr) const {
return (this->Nbr() == portNbr ? true : false);
}
// Overload the less than operator for sorting/finding ports using iterators
bool operator<(const CommPort& p) const {
return (this->Nbr() < p.Nbr() ? true : false);
}
uint8_t Nbr() const { return _nbr; }
bool valid() const { return _nbr != 0; }
void Nbr(uint8_t nbr) { _nbr = nbr; }
// Open a port or check if a port is capable of providing communication.
bool Open() {
if (isReady()) {
_isOpen = true;
return true;
} else {
return false;
}
}
void Close() { _isOpen = false; }
// Check if the port has already been opened.
bool isOpen() const { return _isOpen; }
// Set functions for each RX/TX callback.
void setRxCallback(const std::function<T>& func) {
_rxCallback = func;
return *this;
}
void setTxCallback(const std::function<T>& func) {
_txCallback = func;
return *this;
}
// Methods that return a reference to the TX/RX callback function pointers
std::function<T>& RXCallback() { return _rxCallback; }
std::function<T>& TXCallback() { return _txCallback; }
// Check if an RX/TX callback function has been set for the port.
bool hasTXCallback() const { return _txCallback != nullptr; }
bool hasRXCallback() const { return _rxCallback != nullptr; }
// Check if the port object is a valid port
// this will be false when indexing a non-existent port number
bool Exists() const {
return (hasRXCallback() || hasTXCallback()) && valid();
}
// Get a value or reference to the TX/RX packet count for modifying
unsigned int txCount() const { return _txCount; }
unsigned int rxCount() const { return _rxCount; }
void incTxCount() { _txCount++; }
void incRxCount() { _rxCount++; }
// Standard display function for a CommPort
void PrintPort() const {
printf("%2u\t\t%u\t%u\t%s\t\t%s\t\t%s\r\n", Nbr(), rxCount(), txCount(),
hasRXCallback() ? "YES" : "NO", hasTXCallback() ? "YES" : "NO",
isOpen() ? "OPEN" : "CLOSED");
Console::Instance()->Flush();
}
// Returns the current packet counts to zero
void resetPacketCount() {
_rxCount = 0;
_txCount = 0;
}
protected:
// Returns true if the port can provide an RX callback routine
bool isReady() const { return (_isOpen ? true : hasRXCallback()); }
private:
// The number assigned to the port
uint8_t _nbr;
// If the port is open, it will also be valid
bool _isOpen;
// Where each upstream & downstream packet count is stored
unsigned int _rxCount, _txCount;
// the class members that hold the function pointers
std::function<T> _rxCallback;
std::function<T> _txCallback;
};
// Function for defining how to sort a std::vector of CommPort objects
template <class T>
bool PortCompare(const CommPort<T>& a, const CommPort<T>& b) {
return a < b;
}
// Class to manage the available/unavailable ports
template <class T>
class CommPorts : CommPort<T> {
private:
typename std::vector<CommPort<T>> ports;
typename std::vector<CommPort<T>>::iterator pIt;
CommPort<T> blackhole_port;
const CommPorts<T>& sort() {
std::sort(ports.begin(), ports.end(), PortCompare<T>);
return *this;
}
const CommPorts<T>& add(const CommPort<T>& p) {
pIt = find(ports.begin(), ports.end(), p);
if (pIt == ports.end()) {
ports.push_back(p);
}
return this->sort();
}
public:
// constructor
CommPorts<T>() {
// create a null port that we can return for invalid indexing for the []
// operator
blackhole_port = CommPort<T>();
}
CommPorts<T> operator+=(const CommPort<T>& p) {
return this->add(CommPort<T>(p));
}
CommPort<T>& operator[](const int portNbr) {
pIt = find(ports.begin(), ports.end(), (unsigned int)portNbr);
if (pIt != ports.end()) {
return *&(*pIt);
}
return blackhole_port;
// throw std::runtime_error("No port for the given number");
}
int count() const { return ports.size(); }
int count_open() const {
int count = 0;
for (auto it = ports.begin(); it != ports.end(); ++it) {
if (it->isOpen()) count++;
}
return count;
}
bool empty() const { return ports.empty(); }
// Get the total count (across all ports) of each RX/TX packet count
unsigned int allRXPackets() const {
unsigned int pcks = 0;
for (auto& port : ports) {
pcks += port.rxCount();
}
return pcks;
}
unsigned int allTXPackets() const {
unsigned int pcks = 0;
for (auto& port : ports) {
pcks += port.txCount();
}
return pcks;
}
void PrintPorts() {
if (empty() == false) {
PrintHeader();
for (auto& port : ports) {
port.PrintPort();
}
}
}
void PrintHeader() {
printf("PORT\t\tIN\tOUT\tRX CBCK\t\tTX CBCK\t\tSTATE\r\n");
Console::Instance()->Flush();
}
void PrintFooter() {
printf(
"==========================\r\n"
"Total:\t\t%u\t%u\r\n",
allRXPackets(), allTXPackets());
Console::Instance()->Flush();
}
};
<|endoftext|> |
<commit_before>/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91,92 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Classes:
| SoV2Text2
|
| Author(s) : Gavin Bell
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include "SoV2Text2.h"
#include <Inventor/nodes/SoText2.h>
#include <iconv.h>
#include <errno.h>
SO_NODE_SOURCE(SoV2Text2);
////////////////////////////////////////////////////////////////////////
//
// Description:
// Default constructor
//
// Use: public
SoV2Text2::SoV2Text2()
//
////////////////////////////////////////////////////////////////////////
{
SO_NODE_CONSTRUCTOR(SoV2Text2);
SO_NODE_ADD_FIELD(string, (""));
SO_NODE_ADD_FIELD(spacing, (1.0));
SO_NODE_ADD_FIELD(justification, (LEFT));
// Set up static info for enumerated type field
SO_NODE_DEFINE_ENUM_VALUE(Justification, LEFT);
SO_NODE_DEFINE_ENUM_VALUE(Justification, RIGHT);
SO_NODE_DEFINE_ENUM_VALUE(Justification, CENTER);
// Set up info in enumerated type field
SO_NODE_SET_SF_ENUM_TYPE(justification, Justification);
isBuiltIn = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Destructor.
//
// Use: private
SoV2Text2::~SoV2Text2()
//
////////////////////////////////////////////////////////////////////////
{
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Create a version 2.0 SoText2.
//
// Use: private
SoNode *
SoV2Text2::createNewNode()
//
////////////////////////////////////////////////////////////////////////
{
SoText2 *result = SO_UPGRADER_CREATE_NEW(SoText2);
// if european characters present they are converted to UTF-8
for (int i = 0; i < string.getNum(); i++) {
SbString str("");
if (convertToUTF8(string[i], str)) {
result->string.set1Value(i, str);
}
}
result->spacing.setValue(spacing.getValue());
result->justification.setValue(justification.getValue());
return result;
}
// Following is different for irix 6.2
static iconv_t codeConvert1 = NULL;
static iconv_t codeConvert2 = NULL;
////////////////////////////////////////////////////////////////////////
//
// Description:
// Convert a string to UTF-8. If it's ascii, leave it alone.
// otherwise assume it's ISO-8859-1 (Western European)
//
// Use: static, public
SbBool
SoV2Text2::convertToUTF8(const SbString &inString,
SbString &outString )
//
////////////////////////////////////////////////////////////////////////
{
const char* str = inString.getString();
SbBool ascii = TRUE;
for (int i= 0; i< inString.getLength(); i++){
if ( str[i]& 0x80) {
ascii = FALSE;
break;
}
}
if (ascii) {
outString = inString; // this does a copy.
return TRUE;
}
//Do a conversion first to UCS-2, then UTF-8. That's because
//not all Irix systems have iconv conversion table to go
//directly to UTF-8
if( codeConvert1 == NULL){
codeConvert1 = iconv_open("UCS-2", "ISO8859-1");
codeConvert2 = iconv_open("UTF-8", "UCS-2");
}
if ( codeConvert1 == (iconv_t)-1 ){
#ifdef DEBUG
SoDebugError::post("SoV2Text2::convertToUTF8",
"Invalid ISO8859-1 to UCS-2 conversion");
#endif /*DEBUG*/
return FALSE;
}
if ( codeConvert2 == (iconv_t)-1 ){
#ifdef DEBUG
SoDebugError::post("SoV2Text2::convertToUTF8",
"Invalid UCS-2 to UTF-8 conversion");
#endif /*DEBUG*/
return FALSE;
}
// allocate a sufficiently large buffer:
char * UCSBuf = new char[2*inString.getLength()+1];
char * UTFBuf = new char[2*inString.getLength()+1];
char* input = (char *)inString.getString();
size_t inbytes = inString.getLength();
size_t outbytes = 2*inbytes;
char* output = (char*)UCSBuf;
if ((iconv(codeConvert1, &input, &inbytes, &output, &outbytes) != NULL)){
#ifdef DEBUG
SoDebugError::post("SoV2Text2::convertToUTF8",
"Error converting text to UCS-2");
#endif /*DEBUG*/
}
input = (char *)UCSBuf;
outbytes = 2*inString.getLength()+1;
inbytes = 2*inString.getLength();
output = (char*)UTFBuf;
if ((iconv(codeConvert2, &input, &inbytes, &output, &outbytes) != 0)){
#ifdef DEBUG
switch(errno){
case EILSEQ: printf("EILSEQ\n");
break;
case EINVAL: printf("EINVAL\n");
break;
case E2BIG: printf("E2BIG\n");
break;
default: printf("errno %d\n", errno);
}
SoDebugError::post("SoV2Text2::convertToUTF8",
"Error converting text to UTF-8");
#endif /*DEBUG*/
delete [] UCSBuf;
delete [] UTFBuf;
return FALSE;
}
// make sure that there is a NULL at the end of the string
UTFBuf[2*inString.getLength()-outbytes+1] = '\0';
outString = UTFBuf;
// SbString* str1 = new SbString(UTFBuf, 0, 2*inString.getLength()-outbytes);
delete [] UCSBuf;
delete [] UTFBuf;
return TRUE;
}
<commit_msg>fix error check<commit_after>/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91,92 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Classes:
| SoV2Text2
|
| Author(s) : Gavin Bell
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include "SoV2Text2.h"
#include <Inventor/nodes/SoText2.h>
#include <iconv.h>
#include <errno.h>
SO_NODE_SOURCE(SoV2Text2);
////////////////////////////////////////////////////////////////////////
//
// Description:
// Default constructor
//
// Use: public
SoV2Text2::SoV2Text2()
//
////////////////////////////////////////////////////////////////////////
{
SO_NODE_CONSTRUCTOR(SoV2Text2);
SO_NODE_ADD_FIELD(string, (""));
SO_NODE_ADD_FIELD(spacing, (1.0));
SO_NODE_ADD_FIELD(justification, (LEFT));
// Set up static info for enumerated type field
SO_NODE_DEFINE_ENUM_VALUE(Justification, LEFT);
SO_NODE_DEFINE_ENUM_VALUE(Justification, RIGHT);
SO_NODE_DEFINE_ENUM_VALUE(Justification, CENTER);
// Set up info in enumerated type field
SO_NODE_SET_SF_ENUM_TYPE(justification, Justification);
isBuiltIn = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Destructor.
//
// Use: private
SoV2Text2::~SoV2Text2()
//
////////////////////////////////////////////////////////////////////////
{
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Create a version 2.0 SoText2.
//
// Use: private
SoNode *
SoV2Text2::createNewNode()
//
////////////////////////////////////////////////////////////////////////
{
SoText2 *result = SO_UPGRADER_CREATE_NEW(SoText2);
// if european characters present they are converted to UTF-8
for (int i = 0; i < string.getNum(); i++) {
SbString str("");
if (convertToUTF8(string[i], str)) {
result->string.set1Value(i, str);
}
}
result->spacing.setValue(spacing.getValue());
result->justification.setValue(justification.getValue());
return result;
}
// Following is different for irix 6.2
static iconv_t codeConvert1 = NULL;
static iconv_t codeConvert2 = NULL;
////////////////////////////////////////////////////////////////////////
//
// Description:
// Convert a string to UTF-8. If it's ascii, leave it alone.
// otherwise assume it's ISO-8859-1 (Western European)
//
// Use: static, public
SbBool
SoV2Text2::convertToUTF8(const SbString &inString,
SbString &outString )
//
////////////////////////////////////////////////////////////////////////
{
const char* str = inString.getString();
SbBool ascii = TRUE;
for (int i= 0; i< inString.getLength(); i++){
if ( str[i]& 0x80) {
ascii = FALSE;
break;
}
}
if (ascii) {
outString = inString; // this does a copy.
return TRUE;
}
//Do a conversion first to UCS-2, then UTF-8. That's because
//not all Irix systems have iconv conversion table to go
//directly to UTF-8
if( codeConvert1 == NULL){
codeConvert1 = iconv_open("UCS-2", "ISO8859-1");
codeConvert2 = iconv_open("UTF-8", "UCS-2");
}
if ( codeConvert1 == (iconv_t)-1 ){
#ifdef DEBUG
SoDebugError::post("SoV2Text2::convertToUTF8",
"Invalid ISO8859-1 to UCS-2 conversion");
#endif /*DEBUG*/
return FALSE;
}
if ( codeConvert2 == (iconv_t)-1 ){
#ifdef DEBUG
SoDebugError::post("SoV2Text2::convertToUTF8",
"Invalid UCS-2 to UTF-8 conversion");
#endif /*DEBUG*/
return FALSE;
}
// allocate a sufficiently large buffer:
char * UCSBuf = new char[2*inString.getLength()+1];
char * UTFBuf = new char[2*inString.getLength()+1];
char* input = (char *)inString.getString();
size_t inbytes = inString.getLength();
size_t outbytes = 2*inbytes;
char* output = (char*)UCSBuf;
if (iconv(codeConvert1, &input, &inbytes, &output, &outbytes) == (size_t)-1){
#ifdef DEBUG
SoDebugError::post("SoV2Text2::convertToUTF8",
"Error converting text to UCS-2");
#endif /*DEBUG*/
}
input = (char *)UCSBuf;
outbytes = 2*inString.getLength()+1;
inbytes = 2*inString.getLength();
output = (char*)UTFBuf;
if ((iconv(codeConvert2, &input, &inbytes, &output, &outbytes) != 0)){
#ifdef DEBUG
switch(errno){
case EILSEQ: printf("EILSEQ\n");
break;
case EINVAL: printf("EINVAL\n");
break;
case E2BIG: printf("E2BIG\n");
break;
default: printf("errno %d\n", errno);
}
SoDebugError::post("SoV2Text2::convertToUTF8",
"Error converting text to UTF-8");
#endif /*DEBUG*/
delete [] UCSBuf;
delete [] UTFBuf;
return FALSE;
}
// make sure that there is a NULL at the end of the string
UTFBuf[2*inString.getLength()-outbytes+1] = '\0';
outString = UTFBuf;
// SbString* str1 = new SbString(UTFBuf, 0, 2*inString.getLength()-outbytes);
delete [] UCSBuf;
delete [] UTFBuf;
return TRUE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontainer.cxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: rt $ $Date: 2008-01-30 08:30:56 $
*
* 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_dbaccess.hxx"
#ifndef _DBA_CORE_VIEWCONTAINER_HXX_
#include "viewcontainer.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
#ifndef _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _DBA_CORE_RESOURCE_HXX_
#include "core_resource.hxx"
#endif
#ifndef _DBA_CORE_RESOURCE_HRC_
#include "core_resource.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_VIEW_HXX_
#include <connectivity/sdbcx/VView.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
using namespace dbaccess;
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//==========================================================================
//= OViewContainer
//==========================================================================
DBG_NAME(OViewContainer)
//------------------------------------------------------------------------------
OViewContainer::OViewContainer(::cppu::OWeakObject& _rParent
,::osl::Mutex& _rMutex
,const Reference< XConnection >& _xCon
,sal_Bool _bCase
,IRefreshListener* _pRefreshListener
,IWarningsContainer* _pWarningsContainer
,oslInterlockedCount& _nInAppend)
:OFilteredContainer(_rParent,_rMutex,_xCon,_bCase,_pRefreshListener,_pWarningsContainer,_nInAppend)
,m_bInElementRemoved(false)
{
DBG_CTOR(OViewContainer, NULL);
}
//------------------------------------------------------------------------------
OViewContainer::~OViewContainer()
{
// dispose();
DBG_DTOR(OViewContainer, NULL);
}
//------------------------------------------------------------------------------
// XServiceInfo
//------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO2(OViewContainer, "com.sun.star.sdb.dbaccess.OViewContainer", SERVICE_SDBCX_CONTAINER, SERVICE_SDBCX_TABLES)
// -----------------------------------------------------------------------------
ObjectType OViewContainer::createObject(const ::rtl::OUString& _rName)
{
ObjectType xProp;
if ( m_xMasterContainer.is() && m_xMasterContainer->hasByName(_rName) )
xProp.set(m_xMasterContainer->getByName(_rName),UNO_QUERY);
if ( !xProp.is() )
{
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,
_rName,
sCatalog,
sSchema,
sTable,
::dbtools::eInDataManipulation);
return new ::connectivity::sdbcx::OView(isCaseSensitive(),
sTable,
m_xMetaData,
0,
::rtl::OUString(),
sSchema,
sCatalog
);
}
return xProp;
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OViewContainer::createDescriptor()
{
Reference< XPropertySet > xRet;
// frist we have to look if the master tables does support this
// and if then create a table object as well with the master tables
Reference<XColumnsSupplier > xMasterColumnsSup;
Reference<XDataDescriptorFactory> xDataFactory(m_xMasterContainer,UNO_QUERY);
if(xDataFactory.is())
xRet = xDataFactory->createDataDescriptor();
else
xRet = new ::connectivity::sdbcx::OView(isCaseSensitive(),m_xMetaData);
return xRet;
}
// -----------------------------------------------------------------------------
// XAppend
ObjectType OViewContainer::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
// append the new table with a create stmt
::rtl::OUString aName = getString(descriptor->getPropertyValue(PROPERTY_NAME));
Reference<XAppend> xAppend(m_xMasterContainer,UNO_QUERY);
Reference< XPropertySet > xProp = descriptor;
if(xAppend.is())
{
EnsureReset aReset(m_nInAppend);
xAppend->appendByDescriptor(descriptor);
if(m_xMasterContainer->hasByName(aName))
xProp.set(m_xMasterContainer->getByName(aName),UNO_QUERY);
}
else
{
::rtl::OUString sComposedName = ::dbtools::composeTableName( m_xMetaData, descriptor, ::dbtools::eInTableDefinitions, false, false, true );
if(!sComposedName.getLength())
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));
::rtl::OUString sCommand;
descriptor->getPropertyValue(PROPERTY_COMMAND) >>= sCommand;
::rtl::OUStringBuffer aSQL;
aSQL.appendAscii( "CREATE VIEW " );
aSQL.append ( sComposedName );
aSQL.appendAscii( " AS " );
aSQL.append ( sCommand );
Reference<XConnection> xCon = m_xConnection;
OSL_ENSURE(xCon.is(),"Connection is null!");
if ( xCon.is() )
{
::utl::SharedUNOComponent< XStatement > xStmt( xCon->createStatement() );
if ( xStmt.is() )
xStmt->execute( aSQL.makeStringAndClear() );
}
}
return createObject( _rForName );
}
// -------------------------------------------------------------------------
// XDrop
void OViewContainer::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
if ( !m_bInElementRemoved )
{
Reference< XDrop > xDrop(m_xMasterContainer,UNO_QUERY);
if(xDrop.is())
xDrop->dropByName(_sElementName);
else
{
::rtl::OUString sCatalog,sSchema,sTable,sComposedName;
Reference<XPropertySet> xTable(getObject(_nPos),UNO_QUERY);
if ( xTable.is() )
{
xTable->getPropertyValue(PROPERTY_CATALOGNAME) >>= sCatalog;
xTable->getPropertyValue(PROPERTY_SCHEMANAME) >>= sSchema;
xTable->getPropertyValue(PROPERTY_NAME) >>= sTable;
sComposedName = ::dbtools::composeTableName( m_xMetaData, sCatalog, sSchema, sTable, sal_True, ::dbtools::eInTableDefinitions );
}
if(!sComposedName.getLength())
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP VIEW ");
aSql += sComposedName;
Reference<XConnection> xCon = m_xConnection;
OSL_ENSURE(xCon.is(),"Connection is null!");
if ( xCon.is() )
{
Reference< XStatement > xStmt = xCon->createStatement( );
if(xStmt.is())
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementInserted( const ContainerEvent& Event ) throw (RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
::rtl::OUString sName;
if ( ( Event.Accessor >>= sName )
&& ( !m_nInAppend )
&& ( !hasByName( sName ) )
)
{
Reference<XPropertySet> xProp(Event.Element,UNO_QUERY);
::rtl::OUString sType;
xProp->getPropertyValue(PROPERTY_TYPE) >>= sType;
if ( sType == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
insertElement(sName,createObject(sName));
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementRemoved( const ContainerEvent& Event ) throw (RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
::rtl::OUString sName;
if ( (Event.Accessor >>= sName) && hasByName(sName) )
{
m_bInElementRemoved = true;
try
{
dropByName(sName);
}
catch(Exception&)
{
m_bInElementRemoved = sal_False;
throw;
}
m_bInElementRemoved = false;
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::disposing( const ::com::sun::star::lang::EventObject& /*Source*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementReplaced( const ContainerEvent& /*Event*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > OViewContainer::getTableTypeFilter(const Sequence< ::rtl::OUString >& _rTableTypeFilter) const
{
static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
if(_rTableTypeFilter.getLength() != 0)
{
const ::rtl::OUString* pBegin = _rTableTypeFilter.getConstArray();
const ::rtl::OUString* pEnd = pBegin + _rTableTypeFilter.getLength();
for(;pBegin != pEnd;++pBegin)
{
if ( *pBegin == s_sTableTypeView )
break;
}
if ( pBegin != pEnd )
{ // view are filtered out
m_bConstructed = sal_True;
return Sequence< ::rtl::OUString >();
}
}
// we want all catalogues, all schemas, all tables
Sequence< ::rtl::OUString > sTableTypes(1);
sTableTypes[0] = s_sTableTypeView;
return sTableTypes;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.27.36); FILE MERGED 2008/03/31 13:26:45 rt 1.27.36.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: viewcontainer.cxx,v $
* $Revision: 1.28 $
*
* 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_dbaccess.hxx"
#ifndef _DBA_CORE_VIEWCONTAINER_HXX_
#include "viewcontainer.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
#ifndef _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _DBA_CORE_RESOURCE_HXX_
#include "core_resource.hxx"
#endif
#ifndef _DBA_CORE_RESOURCE_HRC_
#include "core_resource.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_VIEW_HXX_
#include <connectivity/sdbcx/VView.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
using namespace dbaccess;
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//==========================================================================
//= OViewContainer
//==========================================================================
DBG_NAME(OViewContainer)
//------------------------------------------------------------------------------
OViewContainer::OViewContainer(::cppu::OWeakObject& _rParent
,::osl::Mutex& _rMutex
,const Reference< XConnection >& _xCon
,sal_Bool _bCase
,IRefreshListener* _pRefreshListener
,IWarningsContainer* _pWarningsContainer
,oslInterlockedCount& _nInAppend)
:OFilteredContainer(_rParent,_rMutex,_xCon,_bCase,_pRefreshListener,_pWarningsContainer,_nInAppend)
,m_bInElementRemoved(false)
{
DBG_CTOR(OViewContainer, NULL);
}
//------------------------------------------------------------------------------
OViewContainer::~OViewContainer()
{
// dispose();
DBG_DTOR(OViewContainer, NULL);
}
//------------------------------------------------------------------------------
// XServiceInfo
//------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO2(OViewContainer, "com.sun.star.sdb.dbaccess.OViewContainer", SERVICE_SDBCX_CONTAINER, SERVICE_SDBCX_TABLES)
// -----------------------------------------------------------------------------
ObjectType OViewContainer::createObject(const ::rtl::OUString& _rName)
{
ObjectType xProp;
if ( m_xMasterContainer.is() && m_xMasterContainer->hasByName(_rName) )
xProp.set(m_xMasterContainer->getByName(_rName),UNO_QUERY);
if ( !xProp.is() )
{
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,
_rName,
sCatalog,
sSchema,
sTable,
::dbtools::eInDataManipulation);
return new ::connectivity::sdbcx::OView(isCaseSensitive(),
sTable,
m_xMetaData,
0,
::rtl::OUString(),
sSchema,
sCatalog
);
}
return xProp;
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OViewContainer::createDescriptor()
{
Reference< XPropertySet > xRet;
// frist we have to look if the master tables does support this
// and if then create a table object as well with the master tables
Reference<XColumnsSupplier > xMasterColumnsSup;
Reference<XDataDescriptorFactory> xDataFactory(m_xMasterContainer,UNO_QUERY);
if(xDataFactory.is())
xRet = xDataFactory->createDataDescriptor();
else
xRet = new ::connectivity::sdbcx::OView(isCaseSensitive(),m_xMetaData);
return xRet;
}
// -----------------------------------------------------------------------------
// XAppend
ObjectType OViewContainer::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
// append the new table with a create stmt
::rtl::OUString aName = getString(descriptor->getPropertyValue(PROPERTY_NAME));
Reference<XAppend> xAppend(m_xMasterContainer,UNO_QUERY);
Reference< XPropertySet > xProp = descriptor;
if(xAppend.is())
{
EnsureReset aReset(m_nInAppend);
xAppend->appendByDescriptor(descriptor);
if(m_xMasterContainer->hasByName(aName))
xProp.set(m_xMasterContainer->getByName(aName),UNO_QUERY);
}
else
{
::rtl::OUString sComposedName = ::dbtools::composeTableName( m_xMetaData, descriptor, ::dbtools::eInTableDefinitions, false, false, true );
if(!sComposedName.getLength())
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));
::rtl::OUString sCommand;
descriptor->getPropertyValue(PROPERTY_COMMAND) >>= sCommand;
::rtl::OUStringBuffer aSQL;
aSQL.appendAscii( "CREATE VIEW " );
aSQL.append ( sComposedName );
aSQL.appendAscii( " AS " );
aSQL.append ( sCommand );
Reference<XConnection> xCon = m_xConnection;
OSL_ENSURE(xCon.is(),"Connection is null!");
if ( xCon.is() )
{
::utl::SharedUNOComponent< XStatement > xStmt( xCon->createStatement() );
if ( xStmt.is() )
xStmt->execute( aSQL.makeStringAndClear() );
}
}
return createObject( _rForName );
}
// -------------------------------------------------------------------------
// XDrop
void OViewContainer::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
if ( !m_bInElementRemoved )
{
Reference< XDrop > xDrop(m_xMasterContainer,UNO_QUERY);
if(xDrop.is())
xDrop->dropByName(_sElementName);
else
{
::rtl::OUString sCatalog,sSchema,sTable,sComposedName;
Reference<XPropertySet> xTable(getObject(_nPos),UNO_QUERY);
if ( xTable.is() )
{
xTable->getPropertyValue(PROPERTY_CATALOGNAME) >>= sCatalog;
xTable->getPropertyValue(PROPERTY_SCHEMANAME) >>= sSchema;
xTable->getPropertyValue(PROPERTY_NAME) >>= sTable;
sComposedName = ::dbtools::composeTableName( m_xMetaData, sCatalog, sSchema, sTable, sal_True, ::dbtools::eInTableDefinitions );
}
if(!sComposedName.getLength())
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP VIEW ");
aSql += sComposedName;
Reference<XConnection> xCon = m_xConnection;
OSL_ENSURE(xCon.is(),"Connection is null!");
if ( xCon.is() )
{
Reference< XStatement > xStmt = xCon->createStatement( );
if(xStmt.is())
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementInserted( const ContainerEvent& Event ) throw (RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
::rtl::OUString sName;
if ( ( Event.Accessor >>= sName )
&& ( !m_nInAppend )
&& ( !hasByName( sName ) )
)
{
Reference<XPropertySet> xProp(Event.Element,UNO_QUERY);
::rtl::OUString sType;
xProp->getPropertyValue(PROPERTY_TYPE) >>= sType;
if ( sType == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
insertElement(sName,createObject(sName));
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementRemoved( const ContainerEvent& Event ) throw (RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
::rtl::OUString sName;
if ( (Event.Accessor >>= sName) && hasByName(sName) )
{
m_bInElementRemoved = true;
try
{
dropByName(sName);
}
catch(Exception&)
{
m_bInElementRemoved = sal_False;
throw;
}
m_bInElementRemoved = false;
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::disposing( const ::com::sun::star::lang::EventObject& /*Source*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementReplaced( const ContainerEvent& /*Event*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > OViewContainer::getTableTypeFilter(const Sequence< ::rtl::OUString >& _rTableTypeFilter) const
{
static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
if(_rTableTypeFilter.getLength() != 0)
{
const ::rtl::OUString* pBegin = _rTableTypeFilter.getConstArray();
const ::rtl::OUString* pEnd = pBegin + _rTableTypeFilter.getLength();
for(;pBegin != pEnd;++pBegin)
{
if ( *pBegin == s_sTableTypeView )
break;
}
if ( pBegin != pEnd )
{ // view are filtered out
m_bConstructed = sal_True;
return Sequence< ::rtl::OUString >();
}
}
// we want all catalogues, all schemas, all tables
Sequence< ::rtl::OUString > sTableTypes(1);
sTableTypes[0] = s_sTableTypeView;
return sTableTypes;
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtreemodel.cxx,v $
* $Revision: 1.18 $
*
* 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_dbaccess.hxx"
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
namespace dbaui
{
//========================================================================
//= DBTreeListModel
//========================================================================
DBG_NAME(DBTreeListUserData)
//------------------------------------------------------------------------
DBTreeListModel::DBTreeListUserData::DBTreeListUserData()
:eType(SbaTableQueryBrowser::etQuery)
{
DBG_CTOR(DBTreeListUserData,NULL);
}
//------------------------------------------------------------------------
DBTreeListModel::DBTreeListUserData::~DBTreeListUserData()
{
DBG_DTOR(DBTreeListUserData,NULL);
}
}
<commit_msg>INTEGRATION: CWS dba30d (1.18.30); FILE MERGED 2008/06/01 20:56:41 fs 1.18.30.1: during #i80943#: DBTreeListUserData is no sub-class anymore<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: dbtreemodel.cxx,v $
* $Revision: 1.19 $
*
* 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_dbaccess.hxx"
#ifndef DBAUI_DBTREEMODEL_HXX
#include "dbtreemodel.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
namespace dbaui
{
DBG_NAME(DBTreeListUserData)
//------------------------------------------------------------------------
DBTreeListUserData::DBTreeListUserData()
:eType(SbaTableQueryBrowser::etQuery)
{
DBG_CTOR(DBTreeListUserData,NULL);
}
//------------------------------------------------------------------------
DBTreeListUserData::~DBTreeListUserData()
{
DBG_DTOR(DBTreeListUserData,NULL);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtreemodel.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: rt $ $Date: 2007-07-24 12:06:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_DBTREEMODEL_HXX
#define DBAUI_DBTREEMODEL_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _SVLBOX_HXX
#include <svtools/svlbox.hxx>
#endif
#ifndef _SVLBOXITM_HXX
#include <svtools/svlbitm.hxx>
#endif
#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
// syntax of the tree userdata
// datasource holds the connection
// queries holds the nameaccess for the queries
// query holds the query
// tables holds the nameaccess for the tables
// table holds the table
// bookmarks holds the nameaccess for the document links
// table holds the document links
namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } }
namespace dbaui
{
//========================================================================
//= DBTreeListModel
//========================================================================
class DBTreeListModel : public SvLBoxTreeList
{
public:
struct DBTreeListUserData
{
/// if the entry denotes a table or query, this is the respective UNO object
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
xObjectProperties;
/// if the entry denotes a object container, this is the UNO interface for this container
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
xContainer;
/// if the entry denotes a data source, this is the connection for this data source (if already connection)
SharedConnection xConnection;
SbaTableQueryBrowser::EntryType eType;
String sAccessor;
DBTreeListUserData();
~DBTreeListUserData();
};
};
}
#endif // DBAUI_DBTREEMODEL_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.19.144); FILE MERGED 2008/03/31 13:27:07 rt 1.19.144.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: dbtreemodel.hxx,v $
* $Revision: 1.20 $
*
* 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 DBAUI_DBTREEMODEL_HXX
#define DBAUI_DBTREEMODEL_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _SVLBOX_HXX
#include <svtools/svlbox.hxx>
#endif
#ifndef _SVLBOXITM_HXX
#include <svtools/svlbitm.hxx>
#endif
#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
// syntax of the tree userdata
// datasource holds the connection
// queries holds the nameaccess for the queries
// query holds the query
// tables holds the nameaccess for the tables
// table holds the table
// bookmarks holds the nameaccess for the document links
// table holds the document links
namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } }
namespace dbaui
{
//========================================================================
//= DBTreeListModel
//========================================================================
class DBTreeListModel : public SvLBoxTreeList
{
public:
struct DBTreeListUserData
{
/// if the entry denotes a table or query, this is the respective UNO object
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
xObjectProperties;
/// if the entry denotes a object container, this is the UNO interface for this container
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
xContainer;
/// if the entry denotes a data source, this is the connection for this data source (if already connection)
SharedConnection xConnection;
SbaTableQueryBrowser::EntryType eType;
String sAccessor;
DBTreeListUserData();
~DBTreeListUserData();
};
};
}
#endif // DBAUI_DBTREEMODEL_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtreemodel.hxx,v $
* $Revision: 1.20 $
*
* 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 DBAUI_DBTREEMODEL_HXX
#define DBAUI_DBTREEMODEL_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _SVLBOX_HXX
#include <svtools/svlbox.hxx>
#endif
#ifndef _SVLBOXITM_HXX
#include <svtools/svlbitm.hxx>
#endif
#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
// syntax of the tree userdata
// datasource holds the connection
// queries holds the nameaccess for the queries
// query holds the query
// tables holds the nameaccess for the tables
// table holds the table
// bookmarks holds the nameaccess for the document links
// table holds the document links
namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } }
namespace dbaui
{
//========================================================================
//= DBTreeListModel
//========================================================================
class DBTreeListModel : public SvLBoxTreeList
{
public:
struct DBTreeListUserData
{
/// if the entry denotes a table or query, this is the respective UNO object
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
xObjectProperties;
/// if the entry denotes a object container, this is the UNO interface for this container
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
xContainer;
/// if the entry denotes a data source, this is the connection for this data source (if already connection)
SharedConnection xConnection;
SbaTableQueryBrowser::EntryType eType;
String sAccessor;
DBTreeListUserData();
~DBTreeListUserData();
};
};
}
#endif // DBAUI_DBTREEMODEL_HXX
<commit_msg>INTEGRATION: CWS dba30d (1.20.30); FILE MERGED 2008/06/10 08:34:44 fs 1.20.30.2: #i80943# 2008/06/01 20:56:41 fs 1.20.30.1: during #i80943#: DBTreeListUserData is no sub-class anymore<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: dbtreemodel.hxx,v $
* $Revision: 1.21 $
*
* 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 DBAUI_DBTREEMODEL_HXX
#define DBAUI_DBTREEMODEL_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _SVLBOX_HXX
#include <svtools/svlbox.hxx>
#endif
#ifndef _SVLBOXITM_HXX
#include <svtools/svlbitm.hxx>
#endif
#ifndef _SBA_UNODATBR_HXX_
#include "unodatbr.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
// syntax of the tree userdata
// datasource holds the connection
// queries holds the nameaccess for the queries
// query holds the query
// tables holds the nameaccess for the tables
// table holds the table
#define CONTAINER_QUERIES ULONG( 0 )
#define CONTAINER_TABLES ULONG( 1 )
namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } } } }
namespace dbaui
{
struct DBTreeListUserData
{
/// if the entry denotes a table or query, this is the respective UNO object
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
xObjectProperties;
/// if the entry denotes a object container, this is the UNO interface for this container
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
xContainer;
/// if the entry denotes a data source, this is the connection for this data source (if already connection)
SharedConnection xConnection;
SbaTableQueryBrowser::EntryType eType;
String sAccessor;
DBTreeListUserData();
~DBTreeListUserData();
};
}
#endif // DBAUI_DBTREEMODEL_HXX
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// Interface header.
#include "mipgen.h"
// Standard headers.
#include <algorithm>
#include <cassert>
#include <cmath>
namespace
{
template <typename T>
inline bool is_pow2(const T x)
{
return (x & (x - 1)) == 0;
}
inline float mitchell_netravali_filter(float x, const float sharpness)
{
x += x;
const float xabs = fabs(x);
if (xabs > 2.0f)
return 0.0f;
const float b = 1.0f - sharpness;
const float c = 0.5f * sharpness;
const float xx = x * x;
if (xabs < 1.0f)
{
return (1.0f / 6.0f) *
(xabs * xx * (12.0f - 9.0f * b - 6.0f * c) +
xx * (-18.0f + 12.0f * b + 6.0f * c) +
(6.0f - 2.0f * b));
}
else
{
return (1.0f / 6.0f) *
(xabs * xx * (-b - 6.0f * c) +
xx * (6.0f * b + 30.0f * c) +
xabs * (-12.0f * b - 48.0f * c) +
(8.0f * b + 24.0f * c));
}
}
}
void generate_mipmap_level(
float* __restrict output,
const float* __restrict input,
const int input_width,
const int input_height,
const int input_channels,
const int level,
const int filter_radius,
const float filter_sharpness)
{
assert(output);
assert(input);
assert(input_width > 0);
assert(input_height > 0);
assert(is_pow2(input_width));
assert(is_pow2(input_height));
assert(input_channels > 0);
assert(level > 0);
const int output_width = std::max(1, input_width >> level);
const int output_height = std::max(1, input_height >> level);
const int half_size = 1 << (level - 1);
for (int oy = 0; oy < output_height; ++oy)
{
for (int ox = 0; ox < output_width; ++ox)
{
const int cx = (ox << level) + half_size;
const int cy = (oy << level) + half_size;
for (int c = 0; c < input_channels; ++c)
output[(oy * output_width + ox) * input_channels + c] = 0.0f;
float weight = 0.0f;
for (int wy = -filter_radius; wy < filter_radius; ++wy)
{
for (int wx = -filter_radius; wx < filter_radius; ++wx)
{
const int ix = cx + wx;
const int iy = cy + wy;
if (ix < 0 || iy < 0 || ix >= input_width || iy >= input_height)
continue;
const float dx = wx + 0.5f;
const float dy = wy + 0.5f;
const float r2 = dx * dx + dy * dy;
const float r = std::sqrt(r2) / filter_radius;
const float w = mitchell_netravali_filter(r, filter_sharpness);
if (w == 0.0f)
continue;
for (int c = 0; c < input_channels; ++c)
{
output[(oy * output_width + ox) * input_channels + c] +=
w * input[(iy * input_width + ix) * input_channels + c];
}
weight += w;
}
}
if (weight != 0.0f)
{
const float rcp_weight = 1.0f / weight;
for (int c = 0; c < input_channels; ++c)
{
float& component = output[(oy * output_width + ox) * input_channels + c];
component *= rcp_weight;
if (component < 0.0f)
component = 0.0f;
}
}
}
}
}
<commit_msg>minor code tweak.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// Interface header.
#include "mipgen.h"
// Standard headers.
#include <algorithm>
#include <cassert>
#include <cmath>
namespace
{
template <typename T>
inline bool is_pow2(const T x)
{
return (x & (x - 1)) == 0;
}
inline float mitchell_netravali_filter(float x, const float sharpness)
{
x += x;
const float xabs = std::abs(x);
if (xabs > 2.0f)
return 0.0f;
const float b = 1.0f - sharpness;
const float c = 0.5f * sharpness;
const float xx = x * x;
if (xabs < 1.0f)
{
return (1.0f / 6.0f) *
(xabs * xx * (12.0f - 9.0f * b - 6.0f * c) +
xx * (-18.0f + 12.0f * b + 6.0f * c) +
(6.0f - 2.0f * b));
}
else
{
return (1.0f / 6.0f) *
(xabs * xx * (-b - 6.0f * c) +
xx * (6.0f * b + 30.0f * c) +
xabs * (-12.0f * b - 48.0f * c) +
(8.0f * b + 24.0f * c));
}
}
}
void generate_mipmap_level(
float* __restrict output,
const float* __restrict input,
const int input_width,
const int input_height,
const int input_channels,
const int level,
const int filter_radius,
const float filter_sharpness)
{
assert(output);
assert(input);
assert(input_width > 0);
assert(input_height > 0);
assert(is_pow2(input_width));
assert(is_pow2(input_height));
assert(input_channels > 0);
assert(level > 0);
const int output_width = std::max(1, input_width >> level);
const int output_height = std::max(1, input_height >> level);
const int half_size = 1 << (level - 1);
for (int oy = 0; oy < output_height; ++oy)
{
for (int ox = 0; ox < output_width; ++ox)
{
const int cx = (ox << level) + half_size;
const int cy = (oy << level) + half_size;
for (int c = 0; c < input_channels; ++c)
output[(oy * output_width + ox) * input_channels + c] = 0.0f;
float weight = 0.0f;
for (int wy = -filter_radius; wy < filter_radius; ++wy)
{
for (int wx = -filter_radius; wx < filter_radius; ++wx)
{
const int ix = cx + wx;
const int iy = cy + wy;
if (ix < 0 || iy < 0 || ix >= input_width || iy >= input_height)
continue;
const float dx = wx + 0.5f;
const float dy = wy + 0.5f;
const float r2 = dx * dx + dy * dy;
const float r = std::sqrt(r2) / filter_radius;
const float w = mitchell_netravali_filter(r, filter_sharpness);
if (w == 0.0f)
continue;
for (int c = 0; c < input_channels; ++c)
{
output[(oy * output_width + ox) * input_channels + c] +=
w * input[(iy * input_width + ix) * input_channels + c];
}
weight += w;
}
}
if (weight != 0.0f)
{
const float rcp_weight = 1.0f / weight;
for (int c = 0; c < input_channels; ++c)
{
float& component = output[(oy * output_width + ox) * input_channels + c];
component *= rcp_weight;
if (component < 0.0f)
component = 0.0f;
}
}
}
}
}
<|endoftext|> |
<commit_before>
#include "plane.h"
#include "../stages/game.h"
#include "bullet.h"
#include "smokecloud.h"
#include "explosion.h"
#include "../framework/angle.h"
Plane::Plane( ALLEGRO_JOYSTICK* Controller, Vector2* StartPosition, double StartVelocity, double StartAngle ) : GameObject( StartPosition )
{
Velocity = StartVelocity;
Angle = StartAngle;
Score = 0;
LastHitBy = 0;
ShootCooldown = 0;
LastSmokeFrame = 0;
Team = 0;
Flipped = false;
Health = PLANE_DAMAGE_MAX;
State = STATE_FLYING;
AIStateTime = 0;
AITarget = 0;
AITargetTime = 0;
RotateLeft = false;
RotateRight = false;
ThrottleUp = false;
ThrottleDown = false;
Controller_Assistance_AutoFlip = false;
Controller_Assistance_AutoFire = false;
Controller_Assistance_AutoFly = false;
Controller_Assistance_NoStall = false;
if( Controller == 0 )
{
Controller_Keyboard = true;
Controller_Joystick = 0;
} else if( (int)Controller == -1 ) {
Controller_Keyboard = false;
Controller_Joystick = 0;
Controller_Assistance_AutoFlip = true;
Controller_Assistance_AutoFire = true;
Controller_Assistance_AutoFly = true;
} else {
Controller_Keyboard = false;
Controller_Joystick = Controller;
if( al_get_joystick_num_buttons( Controller ) < 2 )
{
// Not enough buttons, so auto-flip
Controller_Assistance_AutoFlip = true;
}
}
// Buff player in Survival
if( Game->Rules_GameMode == GAMEMODE_SURVIVAL && !Controller_Assistance_AutoFly )
{
Health *= 2;
}
}
void Plane::Event( FwEvent* e )
{
if( State == STATE_STALLED || State == STATE_EXPLODED || State == STATE_EXPLODING || State == STATE_HIT )
{
return;
}
if( Controller_Keyboard )
{
if( e->Type == EVENT_KEY_DOWN )
{
switch( e->Data.Keyboard.keycode )
{
case ALLEGRO_KEY_LEFT:
RotateLeft = true;
break;
case ALLEGRO_KEY_RIGHT:
RotateRight = true;
break;
case ALLEGRO_KEY_UP:
ThrottleUp = true;
break;
case ALLEGRO_KEY_DOWN:
ThrottleDown = true;
break;
#ifdef PANDORA
case ALLEGRO_KEY_PGDN:
case ALLEGRO_KEY_HOME:
#endif
case ALLEGRO_KEY_Z:
SetState( STATE_SHOOT );
break;
#ifdef PANDORA
case ALLEGRO_KEY_END:
case ALLEGRO_KEY_PGUP:
#endif
case ALLEGRO_KEY_X:
if( State != STATE_SHOOT && State != STATE_FLIPPING )
{
SetState( STATE_FLIPPING );
}
break;
case ALLEGRO_KEY_D:
SetState( STATE_HIT );
break;
}
}
if( e->Type == EVENT_KEY_UP )
{
switch( e->Data.Keyboard.keycode )
{
case ALLEGRO_KEY_LEFT:
RotateLeft = false;
break;
case ALLEGRO_KEY_RIGHT:
RotateRight = false;
break;
case ALLEGRO_KEY_UP:
ThrottleUp = false;
break;
case ALLEGRO_KEY_DOWN:
ThrottleDown = false;
break;
}
}
}
if( (e->Type == EVENT_JOYSTICK_AXIS || e->Type == EVENT_JOYSTICK_BUTTON_DOWN || e->Type == EVENT_JOYSTICK_BUTTON_UP) && e->Data.Joystick.id == Controller_Joystick )
{
switch( e->Type )
{
case EVENT_JOYSTICK_AXIS:
if( e->Data.Joystick.axis == 0 )
{
RotateLeft = (e->Data.Joystick.pos < 0.0);
RotateRight = (e->Data.Joystick.pos > 0.0);
}
if( e->Data.Joystick.axis == 1 )
{
ThrottleUp = (e->Data.Joystick.pos < 0.0);
ThrottleDown = (e->Data.Joystick.pos > 0.0);
}
break;
case EVENT_JOYSTICK_BUTTON_DOWN:
switch( e->Data.Joystick.button )
{
case 0:
case 2:
SetState( STATE_SHOOT );
break;
case 1:
case 3:
if( State != STATE_SHOOT )
{
SetState( STATE_FLIPPING );
}
break;
}
break;
case EVENT_JOYSTICK_BUTTON_UP:
break;
}
}
}
void Plane::Update()
{
GameObject::Update();
if( Controller_Assistance_AutoFly )
{
ProcessFlyingAI();
}
if( Controller_Assistance_AutoFire )
{
ProcessShootingAI();
}
if( ShootCooldown > 0 )
{
ShootCooldown--;
}
Velocity += sin(Angle * (M_PI / 180.0)) / (Angle >= 180.0 ? 20.0 : 15.0);
if( State == STATE_FLYING && ThrottleUp )
{
Velocity += 0.3;
}
if( State == STATE_FLYING && ThrottleDown && (Angle >= 130.0 || Angle <= 50.0) )
{
Velocity -= 0.3;
}
// Flip right way up
if( Controller_Assistance_AutoFlip && State == STATE_FLYING && (((Angle > 270.0 || Angle <= 90.0) && Flipped) || (Angle > 90.0 && Angle <= 270.0 && !Flipped)) )
{
if( rand() % 5 < 2 )
{
SetState( STATE_FLIPPING );
}
}
// Trying to ascend upside down
if( (Angle > 270.0 && Flipped) || (Angle > 180.0 && Angle <= 270.0 && !Flipped) )
{
Velocity -= 0.03;
}
// People hiding offscreen
if( Position->Y < 0.0 && Game->Rules_HasGround )
{
SetState( STATE_STALLED );
}
if( Controller_Assistance_NoStall && Velocity < 1.0 )
{
Velocity = 1.0;
}
if( Velocity <= 0.0 && State != STATE_EXPLODED && State != STATE_EXPLODING )
{
Velocity = 0.0;
if( State != STATE_STALLED )
{
SetState( STATE_STALLED );
}
}
if( State == STATE_STALLED )
{
if( Angle >= 270.0 || Angle <= 88.0 )
{
Angle += 3.0;
} else if( Angle > 92.0 ) {
Angle -= 3.0;
} else {
//Velocity *= 1.3;
}
if( Velocity >= PLANE_VELOCITY_STALLEXIT )
{
SetState( STATE_FLYING );
}
}
if( State == STATE_FLIPPING )
{
if( Animation_CurrentFrame == 2 )
{
Flipped = !Flipped;
} else if( Animation_CurrentFrame == 4 ) {
SetState( STATE_FLYING );
}
}
if( State == STATE_SHOOT )
{
if( Animation_CurrentFrame == 0 && !HasShot )
{
Game->AddGameObject( new Bullet( this ) );
HasShot = true;
}
if( Animation_CurrentFrame == 1 )
{
SetState( STATE_FLYING );
}
}
if( State != STATE_STALLED && State != STATE_EXPLODED && State != STATE_EXPLODING && State != STATE_SHOOT )
{
if( RotateLeft )
{
Angle = Angle - 1.0;
}
if( RotateRight )
{
Angle = Angle + 1.0;
}
}
if( Velocity >= PLANE_VELOCITY_MAX )
{
Velocity = PLANE_VELOCITY_MAX;
}
if( State == STATE_EXPLODING )
{
Vector2* v = new Vector2( (float)(rand() % 26), 0.0 );
v->RotateVector( (float)(rand() % 36000) / 100.0 );
v->Add( Position );
Game->AddGameObject( new Explosion( v ) );
if( Animation_CurrentFrame >= 2 )
{
SetState( STATE_EXPLODED );
}
} else if( State == STATE_EXPLODED ) {
// ForRemoval = true;
} else if( (Health <= PLANE_DAMAGE_SMOKE_LOTS && Animation_Delay % (Animation_TicksPerFrame / 2) == 0) || (Health <= PLANE_DAMAGE_SMOKE_SMALL && Animation_Delay == 0) ) {
Game->AddGameObject( new SmokeCloud( Position, 0.8, Angle + 180.0 ) );
}
}
void Plane::Render()
{
if( ForRemoval || State == STATE_EXPLODING || State == STATE_EXPLODED )
{
return;
}
ALLEGRO_BITMAP* tileset = Game->GetGameScaledImage();
int tileY = (Team * 48) * Game->graphicsMultiplier;
int tileX = 144 * Game->graphicsMultiplier;
if( State == STATE_FLIPPING )
{
tileX += 48 * Game->graphicsMultiplier;
}
ALLEGRO_BITMAP* tmp = al_create_sub_bitmap( tileset, tileX, tileY, 48 * Game->graphicsMultiplier, 48 * Game->graphicsMultiplier );
al_draw_rotated_bitmap( tmp, 24 * Game->graphicsMultiplier, 24 * Game->graphicsMultiplier, Position->X * Game->graphicsMultiplier, Position->Y * Game->graphicsMultiplier, Angle * (M_PI / 180), (Flipped ? ALLEGRO_FLIP_VERTICAL : 0) );
al_destroy_bitmap( tmp );
}
void Plane::SetState( int NewState )
{
if( NewState == STATE_HIT )
{
LastSmokeFrame = 0;
Health--;
if( Health <= 0 )
{
NewState = STATE_EXPLODING;
} else {
// Just handle the hit, but let everything else continue
NewState = State;
Game->AddGameObject( new SmokeCloud( Position, 0.8, Angle + 180.0 ) );
}
}
if( NewState == STATE_EXPLODING )
{
Velocity = 0.0;
if( LastHitBy != 0 )
{
LastHitBy->Score += 2; // + Got 1 point for the hit = 3 points for a killing shot
} else {
Score -= 5;
}
}
if( NewState == STATE_SHOOT )
{
if( ShootCooldown > 0 )
{
return;
} else {
HasShot = false;
ShootCooldown = PLANE_SHOOT_COOLDOWN + ( Controller_Assistance_AutoFire ? rand() % PLANE_SHOOT_AUTOBUFFER : 0 ) ;
}
}
if( NewState == STATE_STALLED )
{
ThrottleDown = false;
ThrottleUp = false;
RotateLeft = false;
RotateRight = false;
}
State = NewState;
Animation_CurrentFrame = 0;
}
void Plane::ProcessFlyingAI()
{
if( State == STATE_STALLED || State == STATE_EXPLODED || State == STATE_EXPLODING || State == STATE_HIT )
{
return;
}
std::list<Plane*>* gamePlanes;
double angleTo;
// Target for a random time
if( AITargetTime > 0 )
{
AITargetTime--;
}
if( AITargetTime <= 0 )
{
AITarget = 0;
}
// Secondary target time (gives some repreave time if TargetTime < StateTime)
AIStateTime--;
if( AIStateTime <= 0 )
{
gamePlanes = Game->GetPlaneObjects();
for( std::list<Plane*>::const_iterator p = gamePlanes->begin(); p != gamePlanes->end(); p++ )
{
Plane* player = (Plane*)*p;
if( player != this )
{
if( CanTargetPlayer( player ) && rand() % 3 == 0 )
{
AITarget = player;
break;
}
}
}
AITargetTime = (rand() % 90) + 10;
AIStateTime = (rand() % 60) + 20;
}
if( AITarget != 0 )
{
// Aim at player
angleTo = Position->AngleTo( AITarget->Position );
FwAngle* tmpAng = new FwAngle( Angle );
RotateRight = tmpAng->ClockwiseShortestTo( angleTo );
RotateLeft = !RotateRight;
if( Game->Rules_HasGround && Position->Y >= (Framework::SystemFramework->GetDisplayHeight() / Game->graphicsMultiplier) - 128 && tmpAng->ClockwiseShortestTo( 90.0 ) == RotateRight )
{
RotateLeft = !RotateLeft;
RotateRight = !RotateRight;
}
delete tmpAng;
}
}
void Plane::ProcessShootingAI()
{
std::list<Plane*>* gamePlanes;
Plane* targetPlayer = 0;
double angleTo;
FwAngle* tmp;
gamePlanes = Game->GetPlaneObjects();
for( std::list<Plane*>::const_iterator p = gamePlanes->begin(); p != gamePlanes->end(); p++ )
{
Plane* player = (Plane*)*p;
if( player != this && CanTargetPlayer( player ) )
{
angleTo = Position->AngleTo( player->Position );
tmp = new FwAngle( Angle );
if( Controller_Assistance_AutoFire && tmp->ShortestAngleTo( angleTo ) <= PLANE_SHOOT_AIMANGLE && (State == STATE_FLYING || State == STATE_FLIPPING) && ShootCooldown == 0 )
{
SetState( STATE_SHOOT );
}
delete tmp;
}
}
}
bool Plane::CanTargetPlayer( Plane* Target )
{
switch( Game->Rules_GameMode )
{
case GAMEMODE_SURVIVAL:
if( !Target->Controller_Keyboard && Target->Controller_Joystick == 0 )
{
return false;
}
break;
case GAMEMODE_TEAMBATTLES:
if( Target->Team == Team )
{
return false;
}
break;
}
return true;
}
<commit_msg>Pandora key mapping changes<commit_after>#include "plane.h"
#include "../stages/game.h"
#include "bullet.h"
#include "smokecloud.h"
#include "explosion.h"
#include "../framework/angle.h"
Plane::Plane( ALLEGRO_JOYSTICK* Controller, Vector2* StartPosition, double StartVelocity, double StartAngle ) : GameObject( StartPosition )
{
Velocity = StartVelocity;
Angle = StartAngle;
Score = 0;
LastHitBy = 0;
ShootCooldown = 0;
LastSmokeFrame = 0;
Team = 0;
Flipped = false;
Health = PLANE_DAMAGE_MAX;
State = STATE_FLYING;
AIStateTime = 0;
AITarget = 0;
AITargetTime = 0;
RotateLeft = false;
RotateRight = false;
ThrottleUp = false;
ThrottleDown = false;
Controller_Assistance_AutoFlip = false;
Controller_Assistance_AutoFire = false;
Controller_Assistance_AutoFly = false;
Controller_Assistance_NoStall = false;
if( Controller == 0 )
{
Controller_Keyboard = true;
Controller_Joystick = 0;
} else if( (int)Controller == -1 ) {
Controller_Keyboard = false;
Controller_Joystick = 0;
Controller_Assistance_AutoFlip = true;
Controller_Assistance_AutoFire = true;
Controller_Assistance_AutoFly = true;
} else {
Controller_Keyboard = false;
Controller_Joystick = Controller;
if( al_get_joystick_num_buttons( Controller ) < 2 )
{
// Not enough buttons, so auto-flip
Controller_Assistance_AutoFlip = true;
}
}
// Buff player in Survival
if( Game->Rules_GameMode == GAMEMODE_SURVIVAL && !Controller_Assistance_AutoFly )
{
Health *= 2;
}
}
void Plane::Event( FwEvent* e )
{
if( State == STATE_STALLED || State == STATE_EXPLODED || State == STATE_EXPLODING || State == STATE_HIT )
{
return;
}
if( Controller_Keyboard )
{
if( e->Type == EVENT_KEY_DOWN )
{
switch( e->Data.Keyboard.keycode )
{
case ALLEGRO_KEY_LEFT:
RotateLeft = true;
break;
case ALLEGRO_KEY_RIGHT:
RotateRight = true;
break;
#ifdef PANDORA
case ALLEGRO_KEY_RCTRL:
#endif
case ALLEGRO_KEY_UP:
ThrottleUp = true;
break;
#ifdef PANDORA
case ALLEGRO_KEY_RSHIFT:
#endif
case ALLEGRO_KEY_DOWN:
ThrottleDown = true;
break;
#ifdef PANDORA
case ALLEGRO_KEY_PGUP:
case ALLEGRO_KEY_PGDN:
#endif
case ALLEGRO_KEY_Z:
SetState( STATE_SHOOT );
break;
#ifdef PANDORA
case ALLEGRO_KEY_HOME:
case ALLEGRO_KEY_END:
#endif
case ALLEGRO_KEY_X:
if( State != STATE_SHOOT && State != STATE_FLIPPING )
{
SetState( STATE_FLIPPING );
}
break;
case ALLEGRO_KEY_D:
SetState( STATE_HIT );
break;
}
}
if( e->Type == EVENT_KEY_UP )
{
switch( e->Data.Keyboard.keycode )
{
case ALLEGRO_KEY_LEFT:
RotateLeft = false;
break;
case ALLEGRO_KEY_RIGHT:
RotateRight = false;
break;
#ifdef PANDORA
case ALLEGRO_KEY_RCTRL:
#endif
case ALLEGRO_KEY_UP:
ThrottleUp = false;
break;
#ifdef PANDORA
case ALLEGRO_KEY_RSHIFT:
#endif
case ALLEGRO_KEY_DOWN:
ThrottleDown = false;
break;
}
}
}
if( (e->Type == EVENT_JOYSTICK_AXIS || e->Type == EVENT_JOYSTICK_BUTTON_DOWN || e->Type == EVENT_JOYSTICK_BUTTON_UP) && e->Data.Joystick.id == Controller_Joystick )
{
switch( e->Type )
{
case EVENT_JOYSTICK_AXIS:
if( e->Data.Joystick.axis == 0 )
{
RotateLeft = (e->Data.Joystick.pos < 0.0);
RotateRight = (e->Data.Joystick.pos > 0.0);
}
if( e->Data.Joystick.axis == 1 )
{
ThrottleUp = (e->Data.Joystick.pos < 0.0);
ThrottleDown = (e->Data.Joystick.pos > 0.0);
}
break;
case EVENT_JOYSTICK_BUTTON_DOWN:
switch( e->Data.Joystick.button )
{
case 0:
case 2:
SetState( STATE_SHOOT );
break;
case 1:
case 3:
if( State != STATE_SHOOT )
{
SetState( STATE_FLIPPING );
}
break;
}
break;
case EVENT_JOYSTICK_BUTTON_UP:
break;
}
}
}
void Plane::Update()
{
GameObject::Update();
if( Controller_Assistance_AutoFly )
{
ProcessFlyingAI();
}
if( Controller_Assistance_AutoFire )
{
ProcessShootingAI();
}
if( ShootCooldown > 0 )
{
ShootCooldown--;
}
Velocity += sin(Angle * (M_PI / 180.0)) / (Angle >= 180.0 ? 20.0 : 15.0);
if( State == STATE_FLYING && ThrottleUp )
{
Velocity += 0.3;
}
if( State == STATE_FLYING && ThrottleDown && (Angle >= 130.0 || Angle <= 50.0) )
{
Velocity -= 0.3;
}
// Flip right way up
if( Controller_Assistance_AutoFlip && State == STATE_FLYING && (((Angle > 270.0 || Angle <= 90.0) && Flipped) || (Angle > 90.0 && Angle <= 270.0 && !Flipped)) )
{
if( rand() % 5 < 2 )
{
SetState( STATE_FLIPPING );
}
}
// Trying to ascend upside down
if( (Angle > 270.0 && Flipped) || (Angle > 180.0 && Angle <= 270.0 && !Flipped) )
{
Velocity -= 0.03;
}
// People hiding offscreen
if( Position->Y < 0.0 && Game->Rules_HasGround )
{
SetState( STATE_STALLED );
}
if( Controller_Assistance_NoStall && Velocity < 1.0 )
{
Velocity = 1.0;
}
if( Velocity <= 0.0 && State != STATE_EXPLODED && State != STATE_EXPLODING )
{
Velocity = 0.0;
if( State != STATE_STALLED )
{
SetState( STATE_STALLED );
}
}
if( State == STATE_STALLED )
{
if( Angle >= 270.0 || Angle <= 88.0 )
{
Angle += 3.0;
} else if( Angle > 92.0 ) {
Angle -= 3.0;
} else {
//Velocity *= 1.3;
}
if( Velocity >= PLANE_VELOCITY_STALLEXIT )
{
SetState( STATE_FLYING );
}
}
if( State == STATE_FLIPPING )
{
if( Animation_CurrentFrame == 2 )
{
Flipped = !Flipped;
} else if( Animation_CurrentFrame == 4 ) {
SetState( STATE_FLYING );
}
}
if( State == STATE_SHOOT )
{
if( Animation_CurrentFrame == 0 && !HasShot )
{
Game->AddGameObject( new Bullet( this ) );
HasShot = true;
}
if( Animation_CurrentFrame == 1 )
{
SetState( STATE_FLYING );
}
}
if( State != STATE_STALLED && State != STATE_EXPLODED && State != STATE_EXPLODING && State != STATE_SHOOT )
{
if( RotateLeft )
{
Angle = Angle - 1.0;
}
if( RotateRight )
{
Angle = Angle + 1.0;
}
}
if( Velocity >= PLANE_VELOCITY_MAX )
{
Velocity = PLANE_VELOCITY_MAX;
}
if( State == STATE_EXPLODING )
{
Vector2* v = new Vector2( (float)(rand() % 26), 0.0 );
v->RotateVector( (float)(rand() % 36000) / 100.0 );
v->Add( Position );
Game->AddGameObject( new Explosion( v ) );
if( Animation_CurrentFrame >= 2 )
{
SetState( STATE_EXPLODED );
}
} else if( State == STATE_EXPLODED ) {
// ForRemoval = true;
} else if( (Health <= PLANE_DAMAGE_SMOKE_LOTS && Animation_Delay % (Animation_TicksPerFrame / 2) == 0) || (Health <= PLANE_DAMAGE_SMOKE_SMALL && Animation_Delay == 0) ) {
Game->AddGameObject( new SmokeCloud( Position, 0.8, Angle + 180.0 ) );
}
}
void Plane::Render()
{
if( ForRemoval || State == STATE_EXPLODING || State == STATE_EXPLODED )
{
return;
}
ALLEGRO_BITMAP* tileset = Game->GetGameScaledImage();
int tileY = (Team * 48) * Game->graphicsMultiplier;
int tileX = 144 * Game->graphicsMultiplier;
if( State == STATE_FLIPPING )
{
tileX += 48 * Game->graphicsMultiplier;
}
ALLEGRO_BITMAP* tmp = al_create_sub_bitmap( tileset, tileX, tileY, 48 * Game->graphicsMultiplier, 48 * Game->graphicsMultiplier );
al_draw_rotated_bitmap( tmp, 24 * Game->graphicsMultiplier, 24 * Game->graphicsMultiplier, Position->X * Game->graphicsMultiplier, Position->Y * Game->graphicsMultiplier, Angle * (M_PI / 180), (Flipped ? ALLEGRO_FLIP_VERTICAL : 0) );
al_destroy_bitmap( tmp );
}
void Plane::SetState( int NewState )
{
if( NewState == STATE_HIT )
{
LastSmokeFrame = 0;
Health--;
if( Health <= 0 )
{
NewState = STATE_EXPLODING;
} else {
// Just handle the hit, but let everything else continue
NewState = State;
Game->AddGameObject( new SmokeCloud( Position, 0.8, Angle + 180.0 ) );
}
}
if( NewState == STATE_EXPLODING )
{
Velocity = 0.0;
if( LastHitBy != 0 )
{
LastHitBy->Score += 2; // + Got 1 point for the hit = 3 points for a killing shot
} else {
Score -= 5;
}
}
if( NewState == STATE_SHOOT )
{
if( ShootCooldown > 0 )
{
return;
} else {
HasShot = false;
ShootCooldown = PLANE_SHOOT_COOLDOWN + ( Controller_Assistance_AutoFire ? rand() % PLANE_SHOOT_AUTOBUFFER : 0 ) ;
}
}
if( NewState == STATE_STALLED )
{
ThrottleDown = false;
ThrottleUp = false;
RotateLeft = false;
RotateRight = false;
}
State = NewState;
Animation_CurrentFrame = 0;
}
void Plane::ProcessFlyingAI()
{
if( State == STATE_STALLED || State == STATE_EXPLODED || State == STATE_EXPLODING || State == STATE_HIT )
{
return;
}
std::list<Plane*>* gamePlanes;
double angleTo;
// Target for a random time
if( AITargetTime > 0 )
{
AITargetTime--;
}
if( AITargetTime <= 0 )
{
AITarget = 0;
}
// Secondary target time (gives some repreave time if TargetTime < StateTime)
AIStateTime--;
if( AIStateTime <= 0 )
{
gamePlanes = Game->GetPlaneObjects();
for( std::list<Plane*>::const_iterator p = gamePlanes->begin(); p != gamePlanes->end(); p++ )
{
Plane* player = (Plane*)*p;
if( player != this )
{
if( CanTargetPlayer( player ) && rand() % 3 == 0 )
{
AITarget = player;
break;
}
}
}
AITargetTime = (rand() % 90) + 10;
AIStateTime = (rand() % 60) + 20;
}
if( AITarget != 0 )
{
// Aim at player
angleTo = Position->AngleTo( AITarget->Position );
FwAngle* tmpAng = new FwAngle( Angle );
RotateRight = tmpAng->ClockwiseShortestTo( angleTo );
RotateLeft = !RotateRight;
if( Game->Rules_HasGround && Position->Y >= (Framework::SystemFramework->GetDisplayHeight() / Game->graphicsMultiplier) - 128 && tmpAng->ClockwiseShortestTo( 90.0 ) == RotateRight )
{
RotateLeft = !RotateLeft;
RotateRight = !RotateRight;
}
delete tmpAng;
}
}
void Plane::ProcessShootingAI()
{
std::list<Plane*>* gamePlanes;
Plane* targetPlayer = 0;
double angleTo;
FwAngle* tmp;
gamePlanes = Game->GetPlaneObjects();
for( std::list<Plane*>::const_iterator p = gamePlanes->begin(); p != gamePlanes->end(); p++ )
{
Plane* player = (Plane*)*p;
if( player != this && CanTargetPlayer( player ) )
{
angleTo = Position->AngleTo( player->Position );
tmp = new FwAngle( Angle );
if( Controller_Assistance_AutoFire && tmp->ShortestAngleTo( angleTo ) <= PLANE_SHOOT_AIMANGLE && (State == STATE_FLYING || State == STATE_FLIPPING) && ShootCooldown == 0 )
{
SetState( STATE_SHOOT );
}
delete tmp;
}
}
}
bool Plane::CanTargetPlayer( Plane* Target )
{
switch( Game->Rules_GameMode )
{
case GAMEMODE_SURVIVAL:
if( !Target->Controller_Keyboard && Target->Controller_Joystick == 0 )
{
return false;
}
break;
case GAMEMODE_TEAMBATTLES:
if( Target->Team == Team )
{
return false;
}
break;
}
return true;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_LOCALFUNCTIONAL_INTEGRALS_HH
#define DUNE_GDT_LOCALFUNCTIONAL_INTEGRALS_HH
#include <dune/gdt/localevaluation/interface.hh>
#include "interfaces.hh"
namespace Dune {
namespace GDT {
// forward
template <class UnaryEvaluationImp>
class LocalVolumeIntegralFunctional;
namespace internal {
template <class UnaryEvaluationImp>
class LocalVolumeIntegralFunctionalTraits
{
static_assert(std::is_base_of<LocalEvaluation::Codim0Interface<typename UnaryEvaluationImp::Traits, 1>,
UnaryEvaluationImp>::value,
"UnaryEvaluationImp has to be derived from LocalEvaluation::Codim0Interface< ..., 1 >!");
public:
typedef LocalVolumeIntegralFunctional<UnaryEvaluationImp> derived_type;
};
} // namespace internal
template <class UnaryEvaluationType>
class LocalVolumeIntegralFunctional
: public LocalVolumeFunctionalInterface<internal::LocalVolumeIntegralFunctionalTraits<UnaryEvaluationType>>
{
typedef LocalVolumeIntegralFunctional<UnaryEvaluationType> ThisType;
public:
typedef internal::LocalVolumeIntegralFunctionalTraits<UnaryEvaluationType> Traits;
template <class... Args>
explicit LocalVolumeIntegralFunctional(Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(0)
{
}
template <class... Args>
explicit LocalVolumeIntegralFunctional(const int over_integrate, Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(boost::numeric_cast<size_t>(over_integrate))
{
}
template <class... Args>
explicit LocalVolumeIntegralFunctional(const size_t over_integrate, Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(over_integrate)
{
}
LocalVolumeIntegralFunctional(const ThisType& other) = default;
LocalVolumeIntegralFunctional(ThisType&& source) = default;
template <class E, class D, size_t d, class R, size_t r, size_t rC>
void apply(const Stuff::LocalfunctionSetInterface<E, D, d, R, r, rC>& test_base, Dune::DynamicVector<R>& ret) const
{
const auto& entity = test_base.entity();
const auto local_functions = integrand_.localFunctions(entity);
// create quadrature
const size_t integrand_order = integrand_.order(local_functions, test_base) + over_integrate_;
const auto& quadrature = QuadratureRules<D, d>::rule(entity.type(), boost::numeric_cast<int>(integrand_order));
// prepare storage
const size_t size = test_base.size();
ret *= 0.0;
assert(ret.size() >= size);
Dune::DynamicVector<R> evaluation_result(size, 0.); // \todo: make mutable member, after SMP refactor
// loop over all quadrature points
for (const auto& quadrature_point : quadrature) {
const auto xx = quadrature_point.position();
// integration factors
const auto integration_factor = entity.geometry().integrationElement(xx);
const auto quadrature_weight = quadrature_point.weight();
// evaluate the integrand
integrand_.evaluate(local_functions, test_base, xx, evaluation_result);
// compute integral
for (size_t ii = 0; ii < size; ++ii)
ret[ii] += evaluation_result[ii] * integration_factor * quadrature_weight;
} // loop over all quadrature points
} // ... apply(...)
private:
const UnaryEvaluationType integrand_;
const size_t over_integrate_;
}; // class LocalVolumeIntegralFunctional
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCALFUNCTIONAL_INTEGRALS_HH
<commit_msg>[localfunctional.integrals] add LocalFaceIntegralFunctional<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_LOCALFUNCTIONAL_INTEGRALS_HH
#define DUNE_GDT_LOCALFUNCTIONAL_INTEGRALS_HH
#include <dune/gdt/localevaluation/interface.hh>
#include "interfaces.hh"
namespace Dune {
namespace GDT {
// forwards
template <class UnaryEvaluationImp>
class LocalVolumeIntegralFunctional;
template <class UnaryEvaluationImp>
class LocalFaceIntegralFunctional;
namespace internal {
template <class UnaryEvaluationImp>
class LocalVolumeIntegralFunctionalTraits
{
static_assert(std::is_base_of<LocalEvaluation::Codim0Interface<typename UnaryEvaluationImp::Traits, 1>,
UnaryEvaluationImp>::value,
"UnaryEvaluationImp has to be derived from LocalEvaluation::Codim0Interface< ..., 1 >!");
public:
typedef LocalVolumeIntegralFunctional<UnaryEvaluationImp> derived_type;
};
template <class UnaryEvaluationImp>
class LocalFaceIntegralFunctionalTraits
{
static_assert(std::is_base_of<LocalEvaluation::Codim0Interface<typename UnaryEvaluationImp::Traits, 1>,
UnaryEvaluationImp>::value,
"UnaryEvaluationImp has to be derived from LocalEvaluation::Codim0Interface< ..., 1 >!");
public:
typedef LocalFaceIntegralFunctional<UnaryEvaluationImp> derived_type;
};
} // namespace internal
template <class UnaryEvaluationType>
class LocalVolumeIntegralFunctional
: public LocalVolumeFunctionalInterface<internal::LocalVolumeIntegralFunctionalTraits<UnaryEvaluationType>>
{
typedef LocalVolumeIntegralFunctional<UnaryEvaluationType> ThisType;
public:
typedef internal::LocalVolumeIntegralFunctionalTraits<UnaryEvaluationType> Traits;
template <class... Args>
explicit LocalVolumeIntegralFunctional(Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(0)
{
}
template <class... Args>
explicit LocalVolumeIntegralFunctional(const int over_integrate, Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(boost::numeric_cast<size_t>(over_integrate))
{
}
template <class... Args>
explicit LocalVolumeIntegralFunctional(const size_t over_integrate, Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(over_integrate)
{
}
LocalVolumeIntegralFunctional(const ThisType& other) = default;
LocalVolumeIntegralFunctional(ThisType&& source) = default;
template <class E, class D, size_t d, class R, size_t r, size_t rC>
void apply(const Stuff::LocalfunctionSetInterface<E, D, d, R, r, rC>& test_base, Dune::DynamicVector<R>& ret) const
{
const auto& entity = test_base.entity();
const auto local_functions = integrand_.localFunctions(entity);
// create quadrature
const size_t integrand_order = integrand_.order(local_functions, test_base) + over_integrate_;
const auto& quadrature = QuadratureRules<D, d>::rule(entity.type(), boost::numeric_cast<int>(integrand_order));
// prepare storage
const size_t size = test_base.size();
ret *= 0.0;
assert(ret.size() >= size);
Dune::DynamicVector<R> evaluation_result(size, 0.); // \todo: make mutable member, after SMP refactor
// loop over all quadrature points
for (const auto& quadrature_point : quadrature) {
const auto xx = quadrature_point.position();
// integration factors
const auto integration_factor = entity.geometry().integrationElement(xx);
const auto quadrature_weight = quadrature_point.weight();
// evaluate the integrand
integrand_.evaluate(local_functions, test_base, xx, evaluation_result);
// compute integral
for (size_t ii = 0; ii < size; ++ii)
ret[ii] += evaluation_result[ii] * integration_factor * quadrature_weight;
} // loop over all quadrature points
} // ... apply(...)
private:
const UnaryEvaluationType integrand_;
const size_t over_integrate_;
}; // class LocalVolumeIntegralFunctional
template <class UnaryEvaluationType>
class LocalFaceIntegralFunctional
: public LocalFaceFunctionalInterface<internal::LocalFaceIntegralFunctionalTraits<UnaryEvaluationType>>
{
public:
typedef internal::LocalFaceIntegralFunctionalTraits<UnaryEvaluationType> Traits;
template <class... Args>
explicit LocalFaceIntegralFunctional(Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(0)
{
}
template <class... Args>
explicit LocalFaceIntegralFunctional(const int over_integrate, Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(boost::numeric_cast<size_t>(over_integrate))
{
}
template <class... Args>
explicit LocalFaceIntegralFunctional(const size_t over_integrate, Args&&... args)
: integrand_(std::forward<Args>(args)...)
, over_integrate_(over_integrate)
{
}
template <class E, class D, size_t d, class R, size_t r, size_t rC, class IntersectionType>
void apply(const Stuff::LocalfunctionSetInterface<E, D, d, R, r, rC>& test_base, const IntersectionType& intersection,
Dune::DynamicVector<R>& ret) const
{
const auto& entity = test_base.entity();
const auto local_functions = integrand_.localFunctions(entity);
// create quadrature
const size_t integrand_order = integrand_.order(local_functions, test_base) + over_integrate_;
const auto& quadrature =
QuadratureRules<D, d - 1>::rule(intersection.type(), boost::numeric_cast<int>(integrand_order));
// prepare storage
const size_t size = test_base.size();
ret *= 0.0;
assert(ret.size() >= size);
Dune::DynamicVector<R> evaluation_result(size, 0.); // \todo: make mutable member, after SMP refactor
// loop over all quadrature points
for (const auto& quadrature_point : quadrature) {
const auto xx = quadrature_point.position();
// integration factors
const auto integration_factor = intersection.geometry().integrationElement(xx);
const auto quadrature_weight = quadrature_point.weight();
// evaluate the integrand
integrand_.evaluate(local_functions, test_base, intersection, xx, evaluation_result);
// compute integral
for (size_t ii = 0; ii < size; ++ii)
ret[ii] += evaluation_result[ii] * integration_factor * quadrature_weight;
} // loop over all quadrature points
} // ... apply(...)
private:
const UnaryEvaluationType integrand_;
const size_t over_integrate_;
}; // class LocalFaceIntegralFunctional
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCALFUNCTIONAL_INTEGRALS_HH
<|endoftext|> |
<commit_before>/*
* Copyright 2016 WebAssembly Community Group participants
*
* 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 "support/archive.h"
#include <cstring>
#include "support/utilities.h"
static const char* const magic = "!<arch>\n";
class ArchiveMemberHeader {
public:
uint8_t fileName[16];
uint8_t timestamp[12];
uint8_t UID[6];
uint8_t GID[6];
uint8_t accessMode[8];
uint8_t size[10]; // Size of data only, not including padding or header
uint8_t magic[2];
std::string getName() const;
// Members are not larger than 4GB
uint32_t getSize() const;
};
std::string ArchiveMemberHeader::getName() const {
char endChar;
if (fileName[0] == '/') {
// Special name (string table or reference, or symbol table)
endChar = ' ';
} else {
endChar = '/'; // regular name
}
auto* end =
static_cast<const uint8_t*>(memchr(fileName, endChar, sizeof(fileName)));
if (!end) end = fileName + sizeof(fileName);
return std::string((char*)(fileName), end - fileName);
}
uint32_t ArchiveMemberHeader::getSize() const {
auto* end = static_cast<const char*>(memchr(size, ' ', sizeof(size)));
std::string sizeString((const char*)size, end);
auto sizeInt = std::stoll(sizeString, nullptr, 10);
if (sizeInt < 0 || sizeInt >= std::numeric_limits<uint32_t>::max()) {
wasm::Fatal() << "Malformed archive: size parsing failed\n";
}
return static_cast<uint32_t>(sizeInt);
}
Archive::Archive(Buffer& b, bool& error) : data(b), symbolTable({nullptr, 0}), stringTable({nullptr, 0}) {
error = false;
if (data.size() < strlen(magic) ||
memcmp(data.data(), magic, strlen(magic))) {
error = true;
return;
}
// We require GNU format archives. So the first member may be named "/" and it
// points to the symbol table. The next member may optionally be "//" and
// point to a string table if a filename is too large to fit in the 16-char
// name field of the header.
child_iterator it = child_begin(false);
if (it.hasError()) {
error = true;
return;
}
child_iterator end = child_end();
if (it == end) return; // Empty archive.
const Child* c = &*it;
auto increment = [&]() {
++it;
error = it.hasError();
if (error) return true;
c = &*it;
return false;
};
std::string name = c->getRawName();
if (name == "/") {
symbolTable = c->getBuffer();
if (increment() || it == end) return;
name = c->getRawName();
}
if (name == "//") {
stringTable = c->getBuffer();
if (increment() || it == end) return;
setFirstRegular(*c);
return;
}
if (name[0] != '/') {
setFirstRegular(*c);
return;
}
// Not a GNU archive.
error = true;
}
Archive::Child::Child(const Archive* parent, const uint8_t* data, bool* error)
: parent(parent), data(data) {
if (!data) return;
len = sizeof(ArchiveMemberHeader) + getHeader()->getSize();
startOfFile = sizeof(ArchiveMemberHeader);
}
uint32_t Archive::Child::getSize() const { return len - startOfFile; }
Archive::SubBuffer Archive::Child::getBuffer() const {
return {data + startOfFile, getSize()};
}
std::string Archive::Child::getRawName() const {
return getHeader()->getName();
}
Archive::Child Archive::Child::getNext(bool& error) const {
size_t toSkip = len;
// Members are aligned to even byte boundaries.
if (toSkip & 1) ++toSkip;
const uint8_t* nextLoc = data + toSkip;
if (nextLoc >= (uint8_t*)&*parent->data.end()) { // End of the archive.
return Child();
}
return Child(parent, nextLoc, &error);
}
std::string Archive::Child::getName() const {
std::string name = getRawName();
// Check if it's a special name.
if (name[0] == '/') {
if (name.size() == 1) { // Linker member.
return name;
}
if (name.size() == 2 && name[1] == '/') { // String table.
return name;
}
// It's a long name.
// Get the offset.
int offset = std::stoi(name.substr(1), nullptr, 10);
// Verify it.
if (offset < 0 || (unsigned)offset >= parent->stringTable.len) {
wasm::Fatal() << "Malformed archive: name parsing failed\n";
}
std::string addr(parent->stringTable.data + offset,
parent->stringTable.data + parent->stringTable.len);
// GNU long file names end with a "/\n".
size_t end = addr.find('\n');
return addr.substr(0, end - 1);
}
// It's a simple name.
if (name[name.size() - 1] == '/') {
return name.substr(0, name.size() - 1);
}
return name;
}
Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
if (data.size() == 0) return child_end();
if (SkipInternal) {
child_iterator it;
it.child = Child(this, firstRegularData, &it.error);
return it;
}
auto* loc = (const uint8_t*)data.data() + strlen(magic);
child_iterator it;
it.child = Child(this, loc, &it.error);
return it;
}
Archive::child_iterator Archive::child_end() const { return Child(); }
namespace {
struct Symbol {
uint32_t symbolIndex;
uint32_t stringIndex;
void next(Archive::SubBuffer& symbolTable) {
// Symbol table entries are NUL-terminated. Skip past the next NUL.
stringIndex = strchr((char*)symbolTable.data + stringIndex, '\0') -
(char*)symbolTable.data + 1;
++symbolIndex;
}
};
}
static uint32_t read32be(const uint8_t* buf) {
return static_cast<uint32_t>(buf[0]) << 24 |
static_cast<uint32_t>(buf[1]) << 16 |
static_cast<uint32_t>(buf[2]) << 8 | static_cast<uint32_t>(buf[3]);
}
void Archive::dump() const {
printf("Archive data %p len %zu, firstRegularData %p\n", data.data(),
data.size(), firstRegularData);
printf("Symbol table %p, len %u\n", symbolTable.data, symbolTable.len);
printf("string table %p, len %u\n", stringTable.data, stringTable.len);
const uint8_t* buf = symbolTable.data;
if (!buf) {
for (auto c = child_begin(), e = child_end(); c != e; ++c) {
printf("Child %p, len %u, name %s, size %u\n", c->data, c->len,
c->getName().c_str(), c->getSize());
}
return;
}
uint32_t symbolCount = read32be(buf);
printf("Symbol count %u\n", symbolCount);
buf += sizeof(uint32_t) + (symbolCount * sizeof(uint32_t));
uint32_t string_start_offset = buf - symbolTable.data;
Symbol sym = {0, string_start_offset};
while (sym.symbolIndex != symbolCount) {
printf("Symbol %u, offset %u\n", sym.symbolIndex, sym.stringIndex);
// get the member
uint32_t offset = read32be(symbolTable.data + sym.symbolIndex * 4);
auto* loc = (const uint8_t*)&data[offset];
child_iterator it;
it.child = Child(this, loc, &it.error);
printf("Child %p, len %u\n", it.child.data, it.child.len);
}
}
<commit_msg>Fix crash on loading archives, firstRegularData member field was not initialized to null which caused dereferencing a garbage pointer. (#770)<commit_after>/*
* Copyright 2016 WebAssembly Community Group participants
*
* 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 "support/archive.h"
#include <cstring>
#include "support/utilities.h"
static const char* const magic = "!<arch>\n";
class ArchiveMemberHeader {
public:
uint8_t fileName[16];
uint8_t timestamp[12];
uint8_t UID[6];
uint8_t GID[6];
uint8_t accessMode[8];
uint8_t size[10]; // Size of data only, not including padding or header
uint8_t magic[2];
std::string getName() const;
// Members are not larger than 4GB
uint32_t getSize() const;
};
std::string ArchiveMemberHeader::getName() const {
char endChar;
if (fileName[0] == '/') {
// Special name (string table or reference, or symbol table)
endChar = ' ';
} else {
endChar = '/'; // regular name
}
auto* end =
static_cast<const uint8_t*>(memchr(fileName, endChar, sizeof(fileName)));
if (!end) end = fileName + sizeof(fileName);
return std::string((char*)(fileName), end - fileName);
}
uint32_t ArchiveMemberHeader::getSize() const {
auto* end = static_cast<const char*>(memchr(size, ' ', sizeof(size)));
std::string sizeString((const char*)size, end);
auto sizeInt = std::stoll(sizeString, nullptr, 10);
if (sizeInt < 0 || sizeInt >= std::numeric_limits<uint32_t>::max()) {
wasm::Fatal() << "Malformed archive: size parsing failed\n";
}
return static_cast<uint32_t>(sizeInt);
}
Archive::Archive(Buffer& b, bool& error) : data(b), symbolTable({nullptr, 0}), stringTable({nullptr, 0}), firstRegularData(nullptr) {
error = false;
if (data.size() < strlen(magic) ||
memcmp(data.data(), magic, strlen(magic))) {
error = true;
return;
}
// We require GNU format archives. So the first member may be named "/" and it
// points to the symbol table. The next member may optionally be "//" and
// point to a string table if a filename is too large to fit in the 16-char
// name field of the header.
child_iterator it = child_begin(false);
if (it.hasError()) {
error = true;
return;
}
child_iterator end = child_end();
if (it == end) return; // Empty archive.
const Child* c = &*it;
auto increment = [&]() {
++it;
error = it.hasError();
if (error) return true;
c = &*it;
return false;
};
std::string name = c->getRawName();
if (name == "/") {
symbolTable = c->getBuffer();
if (increment() || it == end) return;
name = c->getRawName();
}
if (name == "//") {
stringTable = c->getBuffer();
if (increment() || it == end) return;
setFirstRegular(*c);
return;
}
if (name[0] != '/') {
setFirstRegular(*c);
return;
}
// Not a GNU archive.
error = true;
}
Archive::Child::Child(const Archive* parent, const uint8_t* data, bool* error)
: parent(parent), data(data) {
if (!data) return;
len = sizeof(ArchiveMemberHeader) + getHeader()->getSize();
startOfFile = sizeof(ArchiveMemberHeader);
}
uint32_t Archive::Child::getSize() const { return len - startOfFile; }
Archive::SubBuffer Archive::Child::getBuffer() const {
return {data + startOfFile, getSize()};
}
std::string Archive::Child::getRawName() const {
return getHeader()->getName();
}
Archive::Child Archive::Child::getNext(bool& error) const {
size_t toSkip = len;
// Members are aligned to even byte boundaries.
if (toSkip & 1) ++toSkip;
const uint8_t* nextLoc = data + toSkip;
if (nextLoc >= (uint8_t*)&*parent->data.end()) { // End of the archive.
return Child();
}
return Child(parent, nextLoc, &error);
}
std::string Archive::Child::getName() const {
std::string name = getRawName();
// Check if it's a special name.
if (name[0] == '/') {
if (name.size() == 1) { // Linker member.
return name;
}
if (name.size() == 2 && name[1] == '/') { // String table.
return name;
}
// It's a long name.
// Get the offset.
int offset = std::stoi(name.substr(1), nullptr, 10);
// Verify it.
if (offset < 0 || (unsigned)offset >= parent->stringTable.len) {
wasm::Fatal() << "Malformed archive: name parsing failed\n";
}
std::string addr(parent->stringTable.data + offset,
parent->stringTable.data + parent->stringTable.len);
// GNU long file names end with a "/\n".
size_t end = addr.find('\n');
return addr.substr(0, end - 1);
}
// It's a simple name.
if (name[name.size() - 1] == '/') {
return name.substr(0, name.size() - 1);
}
return name;
}
Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
if (data.size() == 0) return child_end();
if (SkipInternal) {
child_iterator it;
it.child = Child(this, firstRegularData, &it.error);
return it;
}
auto* loc = (const uint8_t*)data.data() + strlen(magic);
child_iterator it;
it.child = Child(this, loc, &it.error);
return it;
}
Archive::child_iterator Archive::child_end() const { return Child(); }
namespace {
struct Symbol {
uint32_t symbolIndex;
uint32_t stringIndex;
void next(Archive::SubBuffer& symbolTable) {
// Symbol table entries are NUL-terminated. Skip past the next NUL.
stringIndex = strchr((char*)symbolTable.data + stringIndex, '\0') -
(char*)symbolTable.data + 1;
++symbolIndex;
}
};
}
static uint32_t read32be(const uint8_t* buf) {
return static_cast<uint32_t>(buf[0]) << 24 |
static_cast<uint32_t>(buf[1]) << 16 |
static_cast<uint32_t>(buf[2]) << 8 | static_cast<uint32_t>(buf[3]);
}
void Archive::dump() const {
printf("Archive data %p len %zu, firstRegularData %p\n", data.data(),
data.size(), firstRegularData);
printf("Symbol table %p, len %u\n", symbolTable.data, symbolTable.len);
printf("string table %p, len %u\n", stringTable.data, stringTable.len);
const uint8_t* buf = symbolTable.data;
if (!buf) {
for (auto c = child_begin(), e = child_end(); c != e; ++c) {
printf("Child %p, len %u, name %s, size %u\n", c->data, c->len,
c->getName().c_str(), c->getSize());
}
return;
}
uint32_t symbolCount = read32be(buf);
printf("Symbol count %u\n", symbolCount);
buf += sizeof(uint32_t) + (symbolCount * sizeof(uint32_t));
uint32_t string_start_offset = buf - symbolTable.data;
Symbol sym = {0, string_start_offset};
while (sym.symbolIndex != symbolCount) {
printf("Symbol %u, offset %u\n", sym.symbolIndex, sym.stringIndex);
// get the member
uint32_t offset = read32be(symbolTable.data + sym.symbolIndex * 4);
auto* loc = (const uint8_t*)&data[offset];
child_iterator it;
it.child = Child(this, loc, &it.error);
printf("Child %p, len %u\n", it.child.data, it.child.len);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "nomlib/system/UnixFile.hpp"
namespace nom {
UnixFile::UnixFile ( void ) {}
UnixFile::~UnixFile ( void ) {}
const std::string UnixFile::mime ( const std::string& file )
{
magic_t cookie;
std::string extension = "\0";
cookie = magic_open ( MAGIC_MIME_TYPE );
if ( cookie == nullptr )
{
NOM_LOG_ERR ( "Could not initialize magic library." );
magic_close ( cookie );
return extension;
}
// First, try loading the system installed copy of the magic mime database,
// so that we do not have to.
if ( magic_load ( cookie, nullptr ) != 0 )
{
std::string cookie_database = "\0";
// Failed trying to load the system copy, so let's try nomlib's copy next!
// We must first obtain the path of our Resources
#if defined ( FRAMEWORK ) && defined ( NOM_PLATFORM_OSX )
cookie_database = getBundleResourcePath ( NOMLIB_BUNDLE_IDENTIFIER );
#else // Assume POSIX layout
cookie_database = NOMLIB_INSTALL_PREFIX + "/share/nomlib/Resources";
#endif
cookie_database = "/" + NOMLIB_MAGIC_DATABASE;
// FIXME; We segfault here if we do not validate that the file actually
// exists before passing it to magic_load ... this should work =(
if ( ! this->exists ( cookie_database ) )
return extension;
// If we fail loading nomlib's copy, we give up!
if ( magic_load ( cookie, cookie_database.c_str() ) != 0 )
{
NOM_LOG_ERR ( "Could not read magic database." );
magic_close ( cookie );
return extension;
}
}
extension = magic_file ( cookie, file.c_str() );
magic_close ( cookie );
return extension;
}
const std::string UnixFile::extension ( const std::string& file )
{
std::string extension = "\0";
if ( file.find_last_of ( "." ) != std::string::npos ) // match found
extension = file.substr ( file.find_last_of (".") + 1 );
// if we reach this point, return false (a null terminated string)
return extension;
}
int32 UnixFile::size ( const std::string& file_path )
{
struct stat file;
if ( ! stat ( file_path.c_str(), &file ) )
{
return file.st_size;
}
return -1;
}
bool UnixFile::exists ( const std::string& file_path )
{
struct stat file;
if ( stat ( file_path.c_str(), &file ) != 0 || !S_ISREG ( file.st_mode ))
return false;
return true;
}
const std::string UnixFile::path ( const std::string& dir_path )
{
// We must do this string conversion -- from a std::string to a char
// pointer -- because the c_str method returns a const char pointer, which
// cannot be used for the dirname function, as this call modifies the contents
// of the passed variable.
char path[PATH_MAX];
std::strcpy ( path, dir_path.c_str() );
return dirname ( path );
}
const std::string UnixFile::currentPath ( void )
{
char path[PATH_MAX];
getcwd ( path, PATH_MAX );
std::string cwd ( path );
return cwd;
}
void UnixFile::setPath ( const std::string& path )
{
chdir ( path.c_str() );
}
} // namespace nom
<commit_msg>(Hopefully!) a bug fix for a couple compile warns about unused results<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "nomlib/system/UnixFile.hpp"
namespace nom {
UnixFile::UnixFile ( void ) {}
UnixFile::~UnixFile ( void ) {}
const std::string UnixFile::mime ( const std::string& file )
{
magic_t cookie;
std::string extension = "\0";
cookie = magic_open ( MAGIC_MIME_TYPE );
if ( cookie == nullptr )
{
NOM_LOG_ERR ( "Could not initialize magic library." );
magic_close ( cookie );
return extension;
}
// First, try loading the system installed copy of the magic mime database,
// so that we do not have to.
if ( magic_load ( cookie, nullptr ) != 0 )
{
std::string cookie_database = "\0";
// Failed trying to load the system copy, so let's try nomlib's copy next!
// We must first obtain the path of our Resources
#if defined ( FRAMEWORK ) && defined ( NOM_PLATFORM_OSX )
cookie_database = getBundleResourcePath ( NOMLIB_BUNDLE_IDENTIFIER );
#else // Assume POSIX layout
cookie_database = NOMLIB_INSTALL_PREFIX + "/share/nomlib/Resources";
#endif
cookie_database = "/" + NOMLIB_MAGIC_DATABASE;
// FIXME; We segfault here if we do not validate that the file actually
// exists before passing it to magic_load ... this should work =(
if ( ! this->exists ( cookie_database ) )
return extension;
// If we fail loading nomlib's copy, we give up!
if ( magic_load ( cookie, cookie_database.c_str() ) != 0 )
{
NOM_LOG_ERR ( "Could not read magic database." );
magic_close ( cookie );
return extension;
}
}
extension = magic_file ( cookie, file.c_str() );
magic_close ( cookie );
return extension;
}
const std::string UnixFile::extension ( const std::string& file )
{
std::string extension = "\0";
if ( file.find_last_of ( "." ) != std::string::npos ) // match found
extension = file.substr ( file.find_last_of (".") + 1 );
// if we reach this point, return false (a null terminated string)
return extension;
}
int32 UnixFile::size ( const std::string& file_path )
{
struct stat file;
if ( ! stat ( file_path.c_str(), &file ) )
{
return file.st_size;
}
return -1;
}
bool UnixFile::exists ( const std::string& file_path )
{
struct stat file;
if ( stat ( file_path.c_str(), &file ) != 0 || !S_ISREG ( file.st_mode ))
return false;
return true;
}
const std::string UnixFile::path ( const std::string& dir_path )
{
// We must do this string conversion -- from a std::string to a char
// pointer -- because the c_str method returns a const char pointer, which
// cannot be used for the dirname function, as this call modifies the contents
// of the passed variable.
char path[PATH_MAX];
std::strcpy ( path, dir_path.c_str() );
return dirname ( path );
}
const std::string UnixFile::currentPath ( void )
{
char path[PATH_MAX];
if ( getcwd ( path, PATH_MAX ) == nullptr )
{
NOM_LOG_ERR ( "Unknown error on attempt to obtain current working directory." );
return "\0";
}
std::string cwd ( path );
return cwd;
}
void UnixFile::setPath ( const std::string& path )
{
if ( chdir ( path.c_str() ) != 0 )
{
NOM_LOG_ERR ( "Unknown error on attempt to change working directory to: " + path );
return;
}
}
} // namespace nom
<|endoftext|> |
<commit_before>// $Id$
//
// Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <DataStructs/BitVects.h>
#include <DataStructs/BitVectUtils.h>
#include <RDBoost/Wrap.h>
namespace python = boost::python;
ExplicitBitVect *createFromBitString(const std::string &bits){
ExplicitBitVect *res=new ExplicitBitVect(bits.length());
FromBitString(*res,bits);
return res;
}
struct Utils_wrapper {
static void wrap(){
python::def("ConvertToExplicit", convertToExplicit,
python::return_value_policy<python::manage_new_object>());
python::def("CreateFromBitString",createFromBitString,
python::return_value_policy<python::manage_new_object>());
python::def("InitFromDaylightString",
(void (*)(SparseBitVect &,std::string))FromDaylightString);
python::def("InitFromDaylightString",
(void (*)(ExplicitBitVect &,std::string))FromDaylightString,
"Fill a BitVect using an ASCII (Daylight) encoding of fingerprint.\n\
\n\
**Arguments**\n\
- bv: either a _SparseBitVect_ or an _ExplicitBitVect_\n\
- txt: a string with the Daylight encoding (this is the text that\n\
the Daylight tools put in the FP field of a TDT)\n\
\n");
}
};
void wrap_Utils() {
Utils_wrapper::wrap();
}
<commit_msg>doc update<commit_after>// $Id$
//
// Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <DataStructs/BitVects.h>
#include <DataStructs/BitVectUtils.h>
#include <RDBoost/Wrap.h>
namespace python = boost::python;
ExplicitBitVect *createFromBitString(const std::string &bits){
ExplicitBitVect *res=new ExplicitBitVect(bits.length());
FromBitString(*res,bits);
return res;
}
struct Utils_wrapper {
static void wrap(){
python::def("ConvertToExplicit", convertToExplicit,
python::return_value_policy<python::manage_new_object>(),
"Converts a SparseBitVector to an ExplicitBitVector and returns the ExplicitBitVector");
python::def("CreateFromBitString",createFromBitString,
python::return_value_policy<python::manage_new_object>(),
"Creates an ExplicitBitVect from a bit string (string of 0s and 1s).");
python::def("InitFromDaylightString",
(void (*)(SparseBitVect &,std::string))FromDaylightString);
python::def("InitFromDaylightString",
(void (*)(ExplicitBitVect &,std::string))FromDaylightString,
"Fill a BitVect using an ASCII (Daylight) encoding of a fingerprint.\n\
\n\
**Arguments**\n\
- bv: either a _SparseBitVect_ or an _ExplicitBitVect_\n\
- txt: a string with the Daylight encoding (this is the text that\n\
the Daylight tools put in the FP field of a TDT)\n\
\n");
}
};
void wrap_Utils() {
Utils_wrapper::wrap();
}
<|endoftext|> |
<commit_before>// ================================================================================
// == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
// == See tb_core.h for more information. ==
// ================================================================================
#include "tb_node_tree.h"
#include "tb_node_ref_tree.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "tb_system.h"
#include "tb_tempbuffer.h"
#include "tb_language.h"
namespace tb {
TBNode::~TBNode()
{
Clear();
}
// static
TBNode *TBNode::Create(const char *name)
{
TBNode *n = new TBNode;
if (!n || !(n->m_name = strdup(name)))
{
delete n;
return nullptr;
}
return n;
}
// static
TBNode *TBNode::Create(const char *name, int name_len)
{
TBNode *n = new TBNode;
if (!n || !(n->m_name = (char *) malloc(name_len + 1)))
{
delete n;
return nullptr;
}
memcpy(n->m_name, name, name_len);
n->m_name[name_len] = 0;
return n;
}
//static
const char *TBNode::GetNextNodeSeparator(const char *request)
{
while (*request != 0 && *request != '>')
request++;
return request;
}
TBNode *TBNode::GetNode(const char *request, GET_MISS_POLICY mp)
{
// Iterate one node deeper for each sub request (non recursive)
TBNode *n = this;
while (*request && n)
{
const char *nextend = GetNextNodeSeparator(request);
int name_len = nextend - request;
TBNode *n_child = n->GetNodeInternal(request, name_len);
if (!n_child && mp == GET_MISS_POLICY_CREATE)
{
n_child = n->Create(request, name_len);
if (n_child)
n->Add(n_child);
}
n = n_child;
request = *nextend == 0 ? nextend : nextend + 1;
}
return n;
}
TBNode *TBNode::GetNodeFollowRef(const char *request, GET_MISS_POLICY mp)
{
TBNode *node = GetNode(request, mp);
if (node)
node = TBNodeRefTree::FollowNodeRef(node);
return node;
}
TBNode *TBNode::GetNodeInternal(const char *name, int name_len) const
{
for (TBNode *n = GetFirstChild(); n; n = n->GetNext())
{
if (strncmp(n->m_name, name, name_len) == 0 && n->m_name[name_len] == 0)
return n;
}
return nullptr;
}
bool TBNode::CloneChildren(TBNode *source)
{
TBNode *item = source->GetFirstChild();
while (item)
{
TBNode *new_child = Create(item->m_name);
if (!new_child)
return false;
new_child->m_value.Copy(item->m_value);
Add(new_child);
if (!new_child->CloneChildren(item))
return false;
item = item->GetNext();
}
return true;
}
TBValue &TBNode::GetValueFollowRef()
{
return TBNodeRefTree::FollowNodeRef(this)->GetValue();
}
int TBNode::GetValueInt(const char *request, int def)
{
TBNode *n = GetNodeFollowRef(request);
return n ? n->m_value.GetInt() : def;
}
float TBNode::GetValueFloat(const char *request, float def)
{
TBNode *n = GetNodeFollowRef(request);
return n ? n->m_value.GetFloat() : def;
}
const char *TBNode::GetValueString(const char *request, const char *def)
{
if (TBNode *node = GetNodeFollowRef(request))
{
// We might have a language string. Those are not
// looked up in GetNode/ResolveNode.
if (node->GetValue().IsString())
{
const char *string = node->GetValue().GetString();
if (*string == '@' && *TBNode::GetNextNodeSeparator(string) == 0)
string = g_tb_lng->GetString(string + 1);
return string;
}
return node->GetValue().GetString();
}
return def;
}
const char *TBNode::GetValueStringRaw(const char *request, const char *def)
{
TBNode *n = GetNodeFollowRef(request);
return n ? n->m_value.GetString() : def;
}
class FileParser : public TBParserStream
{
public:
bool Read(const char *filename, TBParserTarget *target)
{
f = TBFile::Open(filename, TBFile::MODE_READ);
if (!f)
return false;
TBParser p;
TBParser::STATUS status = p.Read(this, target);
delete f;
return status == TBParser::STATUS_OK ? true : false;
}
virtual int GetMoreData(char *buf, int buf_len)
{
return f->Read(buf, 1, buf_len);
}
private:
TBFile *f;
};
class DataParser : public TBParserStream
{
public:
bool Read(const char *data, int data_len, TBParserTarget *target)
{
m_data = data;
m_data_len = data_len;
TBParser p;
TBParser::STATUS status = p.Read(this, target);
return status == TBParser::STATUS_OK ? true : false;
}
virtual int GetMoreData(char *buf, int buf_len)
{
int consume = MIN(buf_len, m_data_len);
memcpy(buf, m_data, consume);
m_data += consume;
m_data_len -= consume;
return consume;
}
private:
const char *m_data;
int m_data_len;
};
class TBNodeTarget : public TBParserTarget
{
public:
TBNodeTarget(TBNode *root, const char *filename)
{
m_root_node = m_target_node = root;
m_filename = filename;
}
virtual void OnError(int line_nr, const char *error)
{
#ifdef TB_RUNTIME_DEBUG_INFO
TBStr err;
err.SetFormatted("%s(%d):Parse error: %s\n", m_filename, line_nr, error);
TBDebugOut(err);
#endif // TB_RUNTIME_DEBUG_INFO
}
virtual void OnComment(int line_nr, const char *comment)
{
}
virtual void OnToken(int line_nr, const char *name, TBValue &value)
{
if (!m_target_node)
return;
if (strcmp(name, "@file") == 0)
IncludeFile(line_nr, value.GetString());
else if (strcmp(name, "@include") == 0)
IncludeRef(line_nr, value.GetString());
else if (TBNode *n = TBNode::Create(name))
{
n->m_value.TakeOver(value);
m_target_node->Add(n);
}
}
virtual void Enter()
{
if (m_target_node)
m_target_node = m_target_node->GetLastChild();
}
virtual void Leave()
{
assert(m_target_node != m_root_node);
if (m_target_node)
m_target_node = m_target_node->m_parent;
}
void IncludeFile(int line_nr, const char *filename)
{
// Read the included file into a new TBNode and then
// move all the children to m_target_node.
TBTempBuffer include_filename;
include_filename.AppendPath(m_filename);
include_filename.AppendString(filename);
TBNode content;
if (content.ReadFile(include_filename.GetData()))
{
while (TBNode *content_n = content.GetFirstChild())
{
content.Remove(content_n);
m_target_node->Add(content_n);
}
}
else
{
TBStr err;
err.SetFormatted("Referenced file \"%s\" was not found!", include_filename.GetData());
OnError(line_nr, err);
}
}
void IncludeRef(int line_nr, const char *refstr)
{
TBNode *refnode = nullptr;
if (*refstr == '@')
{
TBNode tmp;
tmp.GetValue().SetString(refstr, TBValue::SET_AS_STATIC);
refnode = TBNodeRefTree::FollowNodeRef(&tmp);
}
else // Local look-up
{
// Note: If we read to a target node that already contains
// nodes, we might look up nodes that's already there
// instead of new nodes.
refnode = m_root_node->GetNode(refstr, TBNode::GET_MISS_POLICY_NULL);
}
if (refnode)
m_target_node->CloneChildren(refnode);
else
{
TBStr err;
err.SetFormatted("Include \"%s\" was not found!", refstr);
OnError(line_nr, err);
}
}
private:
TBNode *m_root_node;
TBNode *m_target_node;
const char *m_filename;
};
bool TBNode::ReadFile(const char *filename, TB_NODE_READ_FLAGS flags)
{
if (!(flags & TB_NODE_READ_FLAGS_APPEND))
Clear();
FileParser p;
TBNodeTarget t(this, filename);
if (p.Read(filename, &t))
{
TBNodeRefTree::ResolveConditions(this);
return true;
}
return false;
}
void TBNode::ReadData(const char *data, TB_NODE_READ_FLAGS flags)
{
ReadData(data, strlen(data), flags);
}
void TBNode::ReadData(const char *data, int data_len, TB_NODE_READ_FLAGS flags)
{
if (!(flags & TB_NODE_READ_FLAGS_APPEND))
Clear();
DataParser p;
TBNodeTarget t(this, "{data}");
p.Read(data, data_len, &t);
TBNodeRefTree::ResolveConditions(this);
}
void TBNode::Clear()
{
free(m_name);
m_name = nullptr;
m_children.DeleteAll();
}
}; // namespace tb
<commit_msg>Fix for crash with local node include cycles.<commit_after>// ================================================================================
// == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
// == See tb_core.h for more information. ==
// ================================================================================
#include "tb_node_tree.h"
#include "tb_node_ref_tree.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "tb_system.h"
#include "tb_tempbuffer.h"
#include "tb_language.h"
namespace tb {
TBNode::~TBNode()
{
Clear();
}
// static
TBNode *TBNode::Create(const char *name)
{
TBNode *n = new TBNode;
if (!n || !(n->m_name = strdup(name)))
{
delete n;
return nullptr;
}
return n;
}
// static
TBNode *TBNode::Create(const char *name, int name_len)
{
TBNode *n = new TBNode;
if (!n || !(n->m_name = (char *) malloc(name_len + 1)))
{
delete n;
return nullptr;
}
memcpy(n->m_name, name, name_len);
n->m_name[name_len] = 0;
return n;
}
//static
const char *TBNode::GetNextNodeSeparator(const char *request)
{
while (*request != 0 && *request != '>')
request++;
return request;
}
TBNode *TBNode::GetNode(const char *request, GET_MISS_POLICY mp)
{
// Iterate one node deeper for each sub request (non recursive)
TBNode *n = this;
while (*request && n)
{
const char *nextend = GetNextNodeSeparator(request);
int name_len = nextend - request;
TBNode *n_child = n->GetNodeInternal(request, name_len);
if (!n_child && mp == GET_MISS_POLICY_CREATE)
{
n_child = n->Create(request, name_len);
if (n_child)
n->Add(n_child);
}
n = n_child;
request = *nextend == 0 ? nextend : nextend + 1;
}
return n;
}
TBNode *TBNode::GetNodeFollowRef(const char *request, GET_MISS_POLICY mp)
{
TBNode *node = GetNode(request, mp);
if (node)
node = TBNodeRefTree::FollowNodeRef(node);
return node;
}
TBNode *TBNode::GetNodeInternal(const char *name, int name_len) const
{
for (TBNode *n = GetFirstChild(); n; n = n->GetNext())
{
if (strncmp(n->m_name, name, name_len) == 0 && n->m_name[name_len] == 0)
return n;
}
return nullptr;
}
bool TBNode::CloneChildren(TBNode *source)
{
TBNode *item = source->GetFirstChild();
while (item)
{
TBNode *new_child = Create(item->m_name);
if (!new_child)
return false;
new_child->m_value.Copy(item->m_value);
Add(new_child);
if (!new_child->CloneChildren(item))
return false;
item = item->GetNext();
}
return true;
}
TBValue &TBNode::GetValueFollowRef()
{
return TBNodeRefTree::FollowNodeRef(this)->GetValue();
}
int TBNode::GetValueInt(const char *request, int def)
{
TBNode *n = GetNodeFollowRef(request);
return n ? n->m_value.GetInt() : def;
}
float TBNode::GetValueFloat(const char *request, float def)
{
TBNode *n = GetNodeFollowRef(request);
return n ? n->m_value.GetFloat() : def;
}
const char *TBNode::GetValueString(const char *request, const char *def)
{
if (TBNode *node = GetNodeFollowRef(request))
{
// We might have a language string. Those are not
// looked up in GetNode/ResolveNode.
if (node->GetValue().IsString())
{
const char *string = node->GetValue().GetString();
if (*string == '@' && *TBNode::GetNextNodeSeparator(string) == 0)
string = g_tb_lng->GetString(string + 1);
return string;
}
return node->GetValue().GetString();
}
return def;
}
const char *TBNode::GetValueStringRaw(const char *request, const char *def)
{
TBNode *n = GetNodeFollowRef(request);
return n ? n->m_value.GetString() : def;
}
class FileParser : public TBParserStream
{
public:
bool Read(const char *filename, TBParserTarget *target)
{
f = TBFile::Open(filename, TBFile::MODE_READ);
if (!f)
return false;
TBParser p;
TBParser::STATUS status = p.Read(this, target);
delete f;
return status == TBParser::STATUS_OK ? true : false;
}
virtual int GetMoreData(char *buf, int buf_len)
{
return f->Read(buf, 1, buf_len);
}
private:
TBFile *f;
};
class DataParser : public TBParserStream
{
public:
bool Read(const char *data, int data_len, TBParserTarget *target)
{
m_data = data;
m_data_len = data_len;
TBParser p;
TBParser::STATUS status = p.Read(this, target);
return status == TBParser::STATUS_OK ? true : false;
}
virtual int GetMoreData(char *buf, int buf_len)
{
int consume = MIN(buf_len, m_data_len);
memcpy(buf, m_data, consume);
m_data += consume;
m_data_len -= consume;
return consume;
}
private:
const char *m_data;
int m_data_len;
};
class TBNodeTarget : public TBParserTarget
{
public:
TBNodeTarget(TBNode *root, const char *filename)
{
m_root_node = m_target_node = root;
m_filename = filename;
}
virtual void OnError(int line_nr, const char *error)
{
#ifdef TB_RUNTIME_DEBUG_INFO
TBStr err;
err.SetFormatted("%s(%d):Parse error: %s\n", m_filename, line_nr, error);
TBDebugOut(err);
#endif // TB_RUNTIME_DEBUG_INFO
}
virtual void OnComment(int line_nr, const char *comment)
{
}
virtual void OnToken(int line_nr, const char *name, TBValue &value)
{
if (!m_target_node)
return;
if (strcmp(name, "@file") == 0)
IncludeFile(line_nr, value.GetString());
else if (strcmp(name, "@include") == 0)
IncludeRef(line_nr, value.GetString());
else if (TBNode *n = TBNode::Create(name))
{
n->m_value.TakeOver(value);
m_target_node->Add(n);
}
}
virtual void Enter()
{
if (m_target_node)
m_target_node = m_target_node->GetLastChild();
}
virtual void Leave()
{
assert(m_target_node != m_root_node);
if (m_target_node)
m_target_node = m_target_node->m_parent;
}
void IncludeFile(int line_nr, const char *filename)
{
// Read the included file into a new TBNode and then
// move all the children to m_target_node.
TBTempBuffer include_filename;
include_filename.AppendPath(m_filename);
include_filename.AppendString(filename);
TBNode content;
if (content.ReadFile(include_filename.GetData()))
{
while (TBNode *content_n = content.GetFirstChild())
{
content.Remove(content_n);
m_target_node->Add(content_n);
}
}
else
{
TBStr err;
err.SetFormatted("Referenced file \"%s\" was not found!", include_filename.GetData());
OnError(line_nr, err);
}
}
void IncludeRef(int line_nr, const char *refstr)
{
TBNode *refnode = nullptr;
if (*refstr == '@')
{
TBNode tmp;
tmp.GetValue().SetString(refstr, TBValue::SET_AS_STATIC);
refnode = TBNodeRefTree::FollowNodeRef(&tmp);
}
else // Local look-up
{
// Note: If we read to a target node that already contains
// nodes, we might look up nodes that's already there
// instead of new nodes.
refnode = m_root_node->GetNode(refstr, TBNode::GET_MISS_POLICY_NULL);
// Detect cycles
TBNode *cycle_detection = m_target_node;
while (cycle_detection && refnode)
{
if (cycle_detection == refnode)
refnode = nullptr; // We have a cycle, so just fail the inclusion.
cycle_detection = cycle_detection->GetParent();
}
}
if (refnode)
m_target_node->CloneChildren(refnode);
else
{
TBStr err;
err.SetFormatted("Include \"%s\" was not found!", refstr);
OnError(line_nr, err);
}
}
private:
TBNode *m_root_node;
TBNode *m_target_node;
const char *m_filename;
};
bool TBNode::ReadFile(const char *filename, TB_NODE_READ_FLAGS flags)
{
if (!(flags & TB_NODE_READ_FLAGS_APPEND))
Clear();
FileParser p;
TBNodeTarget t(this, filename);
if (p.Read(filename, &t))
{
TBNodeRefTree::ResolveConditions(this);
return true;
}
return false;
}
void TBNode::ReadData(const char *data, TB_NODE_READ_FLAGS flags)
{
ReadData(data, strlen(data), flags);
}
void TBNode::ReadData(const char *data, int data_len, TB_NODE_READ_FLAGS flags)
{
if (!(flags & TB_NODE_READ_FLAGS_APPEND))
Clear();
DataParser p;
TBNodeTarget t(this, "{data}");
p.Read(data, data_len, &t);
TBNodeRefTree::ResolveConditions(this);
}
void TBNode::Clear()
{
free(m_name);
m_name = nullptr;
m_children.DeleteAll();
}
}; // namespace tb
<|endoftext|> |
<commit_before>
#include <Beard/utility.hpp>
#include <Beard/ui/packing.hpp>
#include <Beard/ui/ProtoSlotContainer.hpp>
namespace Beard {
namespace ui {
// class ProtoSlotContainer implementation
ProtoSlotContainer::~ProtoSlotContainer() noexcept = default;
void
ProtoSlotContainer::cache_geometry_impl() noexcept {
Vec2 rs = get_geometry().get_request_size();
for (auto& slot : m_slots) {
if (slot.widget) {
slot.widget->cache_geometry();
Vec2 const& ws = slot.widget->get_geometry().get_request_size();
rs.width = max_ce(rs.width , ws.width);
rs.height = max_ce(rs.height, ws.height);
}
}
if (!get_geometry().is_static()) {
get_geometry().set_request_size(std::move(rs));
}
}
void
ProtoSlotContainer::reflow_impl(
Rect const& area,
bool const cache
) noexcept {
base_type::reflow_impl(area, cache);
ui::reflow_slots(
get_geometry().get_frame(),
m_slots,
m_orientation,
false
);
}
void
ProtoSlotContainer::render_impl(
ui::Widget::RenderData& rd
) noexcept {
for (auto& slot : m_slots) {
if (slot.widget) {
rd.update_group(slot.widget->get_group());
slot.widget->render(rd);
}
}
}
std::size_t
ProtoSlotContainer::size_impl() const noexcept {
return m_slots.size();
}
void
ProtoSlotContainer::clear_impl() {
for (auto const& slot : m_slots) {
slot.widget->set_parent(nullptr);
}
m_slots.clear();
}
void
ProtoSlotContainer::set_widget_impl(
std::size_t const idx,
ui::Widget::SPtr widget
) {
auto& slot = m_slots.at(idx);
if (slot.widget) {
slot.widget->set_parent(nullptr);
}
slot.widget = std::move(widget);
if (slot.widget) {
slot.widget->set_parent(shared_from_this());
}
}
ui::Widget::SPtr
ProtoSlotContainer::get_widget_impl(
std::size_t const idx
) const {
return m_slots.at(idx).widget;
}
void
ProtoSlotContainer::push_back_impl(
ui::Widget::SPtr widget
) {
if (widget) {
widget->set_parent(shared_from_this());
}
m_slots.push_back(ui::Widget::Slot{std::move(widget), {}});
}
} // namespace ui
} // namespace Beard
<commit_msg>ui::ProtoSlotContainer: don't cache geometry for invisible widgets.<commit_after>
#include <Beard/utility.hpp>
#include <Beard/ui/packing.hpp>
#include <Beard/ui/ProtoSlotContainer.hpp>
namespace Beard {
namespace ui {
// class ProtoSlotContainer implementation
ProtoSlotContainer::~ProtoSlotContainer() noexcept = default;
void
ProtoSlotContainer::cache_geometry_impl() noexcept {
Vec2 rs = get_geometry().get_request_size();
for (auto& slot : m_slots) {
if (slot.widget && slot.widget->is_visible()) {
slot.widget->cache_geometry();
Vec2 const& ws = slot.widget->get_geometry().get_request_size();
rs.width = max_ce(rs.width , ws.width);
rs.height = max_ce(rs.height, ws.height);
}
}
if (!get_geometry().is_static()) {
get_geometry().set_request_size(std::move(rs));
}
}
void
ProtoSlotContainer::reflow_impl(
Rect const& area,
bool const cache
) noexcept {
base_type::reflow_impl(area, cache);
ui::reflow_slots(
get_geometry().get_frame(),
m_slots,
m_orientation,
false
);
}
void
ProtoSlotContainer::render_impl(
ui::Widget::RenderData& rd
) noexcept {
for (auto& slot : m_slots) {
if (slot.widget) {
rd.update_group(slot.widget->get_group());
slot.widget->render(rd);
}
}
}
std::size_t
ProtoSlotContainer::size_impl() const noexcept {
return m_slots.size();
}
void
ProtoSlotContainer::clear_impl() {
for (auto const& slot : m_slots) {
slot.widget->set_parent(nullptr);
}
m_slots.clear();
}
void
ProtoSlotContainer::set_widget_impl(
std::size_t const idx,
ui::Widget::SPtr widget
) {
auto& slot = m_slots.at(idx);
if (slot.widget) {
slot.widget->set_parent(nullptr);
}
slot.widget = std::move(widget);
if (slot.widget) {
slot.widget->set_parent(shared_from_this());
}
}
ui::Widget::SPtr
ProtoSlotContainer::get_widget_impl(
std::size_t const idx
) const {
return m_slots.at(idx).widget;
}
void
ProtoSlotContainer::push_back_impl(
ui::Widget::SPtr widget
) {
if (widget) {
widget->set_parent(shared_from_this());
}
m_slots.push_back(ui::Widget::Slot{std::move(widget), {}});
}
} // namespace ui
} // namespace Beard
<|endoftext|> |
<commit_before>#ifndef OPENCL_UTILITIES_H
#define OPENCL_UTILITIES_H
//#define __NO_STD_VECTOR // Use cl::vector instead of STL version
#define __CL_ENABLE_EXCEPTIONS
#if defined(__APPLE__) || defined(__MACOSX)
#include "OpenCL/cl.hpp"
#else
#include <CL/cl.hpp>
#endif
#include <string>
#include <iostream>
#include <fstream>
enum cl_vendor {
VENDOR_ANY,
VENDOR_NVIDIA,
VENDOR_AMD,
VENDOR_INTEL
};
cl::Context createCLContextFromArguments(int argc, char ** argv);
cl::Context createCLContext(cl_device_type type = CL_DEVICE_TYPE_ALL, cl_vendor vendor = VENDOR_ANY);
cl::Platform getPlatform(cl_device_type = CL_DEVICE_TYPE_ALL, cl_vendor vendor = VENDOR_ANY);
cl::Program buildProgramFromSource(cl::Context context, std::string filename, std::string buildOptions = "");
cl::Program buildProgramFromBinary(cl::Context context, std::string filename, std::string buildOptions = "");
char *getCLErrorString(cl_int err);
#endif
<commit_msg>added OpenCL struct<commit_after>#ifndef OPENCL_UTILITIES_H
#define OPENCL_UTILITIES_H
//#define __NO_STD_VECTOR // Use cl::vector instead of STL version
#define __CL_ENABLE_EXCEPTIONS
#if defined(__APPLE__) || defined(__MACOSX)
#include "OpenCL/cl.hpp"
#else
#include <CL/cl.hpp>
#endif
#include <string>
#include <iostream>
#include <fstream>
enum cl_vendor {
VENDOR_ANY,
VENDOR_NVIDIA,
VENDOR_AMD,
VENDOR_INTEL
};
typedef struct OpenCL {
cl::Context context;
cl::CommandQueue queue;
cl::Program program;
cl::Device device;
} OpenCL;
cl::Context createCLContextFromArguments(int argc, char ** argv);
cl::Context createCLContext(cl_device_type type = CL_DEVICE_TYPE_ALL, cl_vendor vendor = VENDOR_ANY);
cl::Platform getPlatform(cl_device_type = CL_DEVICE_TYPE_ALL, cl_vendor vendor = VENDOR_ANY);
cl::Program buildProgramFromSource(cl::Context context, std::string filename, std::string buildOptions = "");
cl::Program buildProgramFromBinary(cl::Context context, std::string filename, std::string buildOptions = "");
char *getCLErrorString(cl_int err);
#endif
<|endoftext|> |
<commit_before>#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <iomanip>
#include "mvnormal.h"
#include "session.h"
#include "chol.h"
#include "linop.h"
#include "noisemodels.h"
#include "latentprior.h"
using namespace std;
using namespace Eigen;
namespace Macau {
ILatentPrior::ILatentPrior(BaseSession &m, int p, std::string name)
: session(m), mode(p), name(name) {}
std::ostream &ILatentPrior::info(std::ostream &os, std::string indent)
{
os << indent << mode << ": " << name << "\n";
return os;
}
Model &ILatentPrior::model() { return session.model; }
Data &ILatentPrior::data() { return *session.data; }
INoiseModel &ILatentPrior::noise() { return *data().noise; }
MatrixXd &ILatentPrior::U() { return model().U(mode); }
MatrixXd &ILatentPrior::V() { return model().V(mode); }
void ILatentPrior::init()
{
rrs.init(VectorNd::Zero(num_latent()));
MMs.init(MatrixNNd::Zero(num_latent(), num_latent()));
}
void ILatentPrior::sample_latents()
{
session.data->update_pnm(model(), mode);
#pragma omp parallel for schedule(guided)
for(int n = 0; n < U().cols(); n++) {
#pragma omp task
sample_latent(n);
}
}
/**
* base class NormalPrior
*/
NormalPrior::NormalPrior(BaseSession &m, int p, std::string name)
: ILatentPrior(m, p, name) {}
void NormalPrior::init() {
ILatentPrior::init();
Ucol.init(VectorNd::Zero(num_latent())),
UUcol.init(MatrixNNd::Zero(num_latent(), num_latent()));
const int K = num_latent();
mu.resize(K);
mu.setZero();
Lambda.resize(K, K);
Lambda.setIdentity();
Lambda *= 10;
// parameters of Inv-Whishart distribution
WI.resize(K, K);
WI.setIdentity();
mu0.resize(K);
mu0.setZero();
b0 = 2;
df = K;
}
void NormalPrior::sample_latents() {
const int N = num_cols();
const auto cov = UUcol.combine();
const auto sum = Ucol.combine();
tie(mu, Lambda) = CondNormalWishart(N, cov / N, sum / N, mu0, b0, WI, df);
UUcol.reset();
Ucol.reset();
ILatentPrior::sample_latents();
}
void NormalPrior::sample_latent(int n)
{
const auto &mu_u = getMu(n);
VectorNd &rr = rrs.local();
MatrixNNd &MM = MMs.local();
rr.setZero();
MM.setZero();
// add pnm
session.data->get_pnm(model(),mode,n,rr,MM);
// add hyperparams
rr.noalias() += Lambda * mu_u;
MM.noalias() += Lambda;
Eigen::LLT<MatrixXd> chol = MM.llt();
if(chol.info() != Eigen::Success) {
throw std::runtime_error("Cholesky Decomposition failed!");
}
chol.matrixL().solveInPlace(rr);
rr.noalias() += nrandn(num_latent());
chol.matrixU().solveInPlace(rr);
U().col(n).noalias() = rr;
Ucol.local().noalias() += rr;
UUcol.local().noalias() += rr * rr.transpose();
}
void NormalPrior::save(std::string prefix, std::string suffix) {
write_dense(prefix + "-U" + std::to_string(mode) + "-latentmean" + suffix, mu);
}
void NormalPrior::restore(std::string prefix, std::string suffix) {
read_dense(prefix + "-U" + std::to_string(mode) + "-latentmean" + suffix, mu);
}
} // end namespace Macau
<commit_msg>Update UUcol and Ucol when restoring<commit_after>#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <iomanip>
#include "mvnormal.h"
#include "session.h"
#include "chol.h"
#include "linop.h"
#include "noisemodels.h"
#include "latentprior.h"
using namespace std;
using namespace Eigen;
namespace Macau {
ILatentPrior::ILatentPrior(BaseSession &m, int p, std::string name)
: session(m), mode(p), name(name) {}
std::ostream &ILatentPrior::info(std::ostream &os, std::string indent)
{
os << indent << mode << ": " << name << "\n";
return os;
}
Model &ILatentPrior::model() { return session.model; }
Data &ILatentPrior::data() { return *session.data; }
INoiseModel &ILatentPrior::noise() { return *data().noise; }
MatrixXd &ILatentPrior::U() { return model().U(mode); }
MatrixXd &ILatentPrior::V() { return model().V(mode); }
void ILatentPrior::init()
{
rrs.init(VectorNd::Zero(num_latent()));
MMs.init(MatrixNNd::Zero(num_latent(), num_latent()));
}
void ILatentPrior::sample_latents()
{
session.data->update_pnm(model(), mode);
#pragma omp parallel for schedule(guided)
for(int n = 0; n < U().cols(); n++) {
#pragma omp task
sample_latent(n);
}
}
/**
* base class NormalPrior
*/
NormalPrior::NormalPrior(BaseSession &m, int p, std::string name)
: ILatentPrior(m, p, name) {}
void NormalPrior::init() {
ILatentPrior::init();
Ucol.init(VectorNd::Zero(num_latent())),
UUcol.init(MatrixNNd::Zero(num_latent(), num_latent()));
const int K = num_latent();
mu.resize(K);
mu.setZero();
Lambda.resize(K, K);
Lambda.setIdentity();
Lambda *= 10;
// parameters of Inv-Whishart distribution
WI.resize(K, K);
WI.setIdentity();
mu0.resize(K);
mu0.setZero();
b0 = 2;
df = K;
}
void NormalPrior::sample_latents() {
const int N = num_cols();
const auto cov = UUcol.combine();
const auto sum = Ucol.combine();
tie(mu, Lambda) = CondNormalWishart(N, cov / N, sum / N, mu0, b0, WI, df);
UUcol.reset();
Ucol.reset();
ILatentPrior::sample_latents();
}
void NormalPrior::sample_latent(int n)
{
const auto &mu_u = getMu(n);
VectorNd &rr = rrs.local();
MatrixNNd &MM = MMs.local();
rr.setZero();
MM.setZero();
// add pnm
session.data->get_pnm(model(),mode,n,rr,MM);
// add hyperparams
rr.noalias() += Lambda * mu_u;
MM.noalias() += Lambda;
Eigen::LLT<MatrixXd> chol = MM.llt();
if(chol.info() != Eigen::Success) {
throw std::runtime_error("Cholesky Decomposition failed!");
}
chol.matrixL().solveInPlace(rr);
rr.noalias() += nrandn(num_latent());
chol.matrixU().solveInPlace(rr);
U().col(n).noalias() = rr;
Ucol.local().noalias() += rr;
UUcol.local().noalias() += rr * rr.transpose();
}
void NormalPrior::save(std::string prefix, std::string suffix) {
write_dense(prefix + "-U" + std::to_string(mode) + "-latentmean" + suffix, mu);
}
void NormalPrior::restore(std::string prefix, std::string suffix) {
read_dense(prefix + "-U" + std::to_string(mode) + "-latentmean" + suffix, mu);
UUcol.reset();
Ucol.reset();
UUcol.local() = U() * U().transpose();
Ucol.local() = U().rowwise().sum();
}
} // end namespace Macau
<|endoftext|> |
<commit_before><commit_msg>Prediction: add extra check on point projection on lane<commit_after><|endoftext|> |
<commit_before>//===-- sanitizer_libignore.cc --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_MAC || SANITIZER_NETBSD
#include "sanitizer_libignore.h"
#include "sanitizer_flags.h"
#include "sanitizer_posix.h"
#include "sanitizer_procmaps.h"
namespace __sanitizer {
LibIgnore::LibIgnore(LinkerInitialized) {
}
void LibIgnore::AddIgnoredLibrary(const char *name_templ) {
BlockingMutexLock lock(&mutex_);
if (count_ >= kMaxLibs) {
Report("%s: too many ignored libraries (max: %d)\n", SanitizerToolName,
kMaxLibs);
Die();
}
Lib *lib = &libs_[count_++];
lib->templ = internal_strdup(name_templ);
lib->name = nullptr;
lib->real_name = nullptr;
lib->loaded = false;
}
void LibIgnore::OnLibraryLoaded(const char *name) {
BlockingMutexLock lock(&mutex_);
// Try to match suppressions with symlink target.
InternalScopedString buf(kMaxPathLength);
if (name && internal_readlink(name, buf.data(), buf.size() - 1) > 0 &&
buf[0]) {
for (uptr i = 0; i < count_; i++) {
Lib *lib = &libs_[i];
if (!lib->loaded && (!lib->real_name) &&
TemplateMatch(lib->templ, name))
lib->real_name = internal_strdup(buf.data());
}
}
// Scan suppressions list and find newly loaded and unloaded libraries.
ListOfModules modules;
modules.init();
for (uptr i = 0; i < count_; i++) {
Lib *lib = &libs_[i];
bool loaded = false;
for (const auto &mod : modules) {
for (const auto &range : mod.ranges()) {
if (!range.executable)
continue;
if (!TemplateMatch(lib->templ, mod.full_name()) &&
!(lib->real_name &&
internal_strcmp(lib->real_name, mod.full_name()) == 0))
continue;
if (loaded) {
Report("%s: called_from_lib suppression '%s' is matched against"
" 2 libraries: '%s' and '%s'\n",
SanitizerToolName, lib->templ, lib->name, mod.full_name());
Die();
}
loaded = true;
if (lib->loaded)
continue;
VReport(1,
"Matched called_from_lib suppression '%s' against library"
" '%s'\n",
lib->templ, mod.full_name());
lib->loaded = true;
lib->name = internal_strdup(mod.full_name());
const uptr idx =
atomic_load(&ignored_ranges_count_, memory_order_relaxed);
CHECK_LT(idx, kMaxLibs);
ignored_code_ranges_[idx].begin = range.beg;
ignored_code_ranges_[idx].end = range.end;
atomic_store(&ignored_ranges_count_, idx + 1, memory_order_release);
break;
}
}
if (lib->loaded && !loaded) {
Report("%s: library '%s' that was matched against called_from_lib"
" suppression '%s' is unloaded\n",
SanitizerToolName, lib->name, lib->templ);
Die();
}
}
// Track instrumented ranges.
if (track_instrumented_libs_) {
for (const auto &mod : modules) {
if (!mod.instrumented())
continue;
for (const auto &range : mod.ranges()) {
if (!range.executable)
continue;
if (IsPcInstrumented(range.beg) && IsPcInstrumented(range.end - 1))
continue;
VReport(1, "Adding instrumented range %p-%p from library '%s'\n",
range.beg, range.end, mod.full_name());
const uptr idx =
atomic_load(&instrumented_ranges_count_, memory_order_relaxed);
CHECK_LT(idx, kMaxLibs);
instrumented_code_ranges_[idx].begin = range.beg;
instrumented_code_ranges_[idx].end = range.end;
atomic_store(&instrumented_ranges_count_, idx + 1,
memory_order_release);
}
}
}
}
void LibIgnore::OnLibraryUnloaded() {
OnLibraryLoaded(nullptr);
}
} // namespace __sanitizer
#endif // #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_MAC || SANITIZER_NETBSD
<commit_msg>Honour 80-character line limit<commit_after>//===-- sanitizer_libignore.cc --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_MAC || SANITIZER_NETBSD
#include "sanitizer_libignore.h"
#include "sanitizer_flags.h"
#include "sanitizer_posix.h"
#include "sanitizer_procmaps.h"
namespace __sanitizer {
LibIgnore::LibIgnore(LinkerInitialized) {
}
void LibIgnore::AddIgnoredLibrary(const char *name_templ) {
BlockingMutexLock lock(&mutex_);
if (count_ >= kMaxLibs) {
Report("%s: too many ignored libraries (max: %d)\n", SanitizerToolName,
kMaxLibs);
Die();
}
Lib *lib = &libs_[count_++];
lib->templ = internal_strdup(name_templ);
lib->name = nullptr;
lib->real_name = nullptr;
lib->loaded = false;
}
void LibIgnore::OnLibraryLoaded(const char *name) {
BlockingMutexLock lock(&mutex_);
// Try to match suppressions with symlink target.
InternalScopedString buf(kMaxPathLength);
if (name && internal_readlink(name, buf.data(), buf.size() - 1) > 0 &&
buf[0]) {
for (uptr i = 0; i < count_; i++) {
Lib *lib = &libs_[i];
if (!lib->loaded && (!lib->real_name) &&
TemplateMatch(lib->templ, name))
lib->real_name = internal_strdup(buf.data());
}
}
// Scan suppressions list and find newly loaded and unloaded libraries.
ListOfModules modules;
modules.init();
for (uptr i = 0; i < count_; i++) {
Lib *lib = &libs_[i];
bool loaded = false;
for (const auto &mod : modules) {
for (const auto &range : mod.ranges()) {
if (!range.executable)
continue;
if (!TemplateMatch(lib->templ, mod.full_name()) &&
!(lib->real_name &&
internal_strcmp(lib->real_name, mod.full_name()) == 0))
continue;
if (loaded) {
Report("%s: called_from_lib suppression '%s' is matched against"
" 2 libraries: '%s' and '%s'\n",
SanitizerToolName, lib->templ, lib->name, mod.full_name());
Die();
}
loaded = true;
if (lib->loaded)
continue;
VReport(1,
"Matched called_from_lib suppression '%s' against library"
" '%s'\n",
lib->templ, mod.full_name());
lib->loaded = true;
lib->name = internal_strdup(mod.full_name());
const uptr idx =
atomic_load(&ignored_ranges_count_, memory_order_relaxed);
CHECK_LT(idx, kMaxLibs);
ignored_code_ranges_[idx].begin = range.beg;
ignored_code_ranges_[idx].end = range.end;
atomic_store(&ignored_ranges_count_, idx + 1, memory_order_release);
break;
}
}
if (lib->loaded && !loaded) {
Report("%s: library '%s' that was matched against called_from_lib"
" suppression '%s' is unloaded\n",
SanitizerToolName, lib->name, lib->templ);
Die();
}
}
// Track instrumented ranges.
if (track_instrumented_libs_) {
for (const auto &mod : modules) {
if (!mod.instrumented())
continue;
for (const auto &range : mod.ranges()) {
if (!range.executable)
continue;
if (IsPcInstrumented(range.beg) && IsPcInstrumented(range.end - 1))
continue;
VReport(1, "Adding instrumented range %p-%p from library '%s'\n",
range.beg, range.end, mod.full_name());
const uptr idx =
atomic_load(&instrumented_ranges_count_, memory_order_relaxed);
CHECK_LT(idx, kMaxLibs);
instrumented_code_ranges_[idx].begin = range.beg;
instrumented_code_ranges_[idx].end = range.end;
atomic_store(&instrumented_ranges_count_, idx + 1,
memory_order_release);
}
}
}
}
void LibIgnore::OnLibraryUnloaded() {
OnLibraryLoaded(nullptr);
}
} // namespace __sanitizer
#endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_MAC ||
// SANITIZER_NETBSD
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <string>
#include <vector>
#include "gflags/gflags.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/common/util/points_downsampler.h"
#include "modules/map/proto/map.pb.h"
/**
* A map tool to generate a downsampled map to be displayed by dreamview
* frontend.
*/
DEFINE_string(map_file, "", "map file name");
DEFINE_string(output_dir, "/tmp/", "output map directory");
DEFINE_double(angle_threshold, 1 / 180 * M_PI, /* 1 degree */
"Points are sampled when the accumulated direction change "
"exceeds the threshold");
DEFINE_int32(downsample_distance, 5, "downsample rate for a normal path");
DEFINE_int32(steep_turn_downsample_distance, 1,
"downsample rate for a steep turn path");
using apollo::common::util::DownsampleByAngle;
using apollo::common::util::DownsampleByDistance;
using apollo::common::util::GetProtoFromFile;
using apollo::common::PointENU;
using apollo::hdmap::Curve;
using apollo::hdmap::Map;
void DownsampleCurve(Curve* curve) {
std::vector<PointENU> points;
std::vector<int> sampled_indices;
auto* line_segment = curve->mutable_segment(0)->mutable_line_segment();
for (const auto& point : line_segment->point()) {
points.push_back(point);
}
line_segment->clear_point();
// NOTE: this not the most efficient implementation, but since this map tool
// is only run once for each, we can probably live with that.
// Downsample points by angle then by distance.
DownsampleByAngle(points, FLAGS_angle_threshold, &sampled_indices);
std::vector<PointENU> downsampled_points;
for (int index : sampled_indices) {
downsampled_points.push_back(points[index]);
}
DownsampleByDistance(downsampled_points, FLAGS_downsample_distance,
FLAGS_steep_turn_downsample_distance, &sampled_indices);
for (int index : sampled_indices) {
*line_segment->add_point() = downsampled_points[index];
}
}
void DownsampleMap(Map* map_pb) {
for (int i = 0; i < map_pb->lane_size(); ++i) {
auto* lane = map_pb->mutable_lane(i);
DownsampleCurve(lane->mutable_central_curve());
DownsampleCurve(lane->mutable_left_boundary()->mutable_curve());
DownsampleCurve(lane->mutable_right_boundary()->mutable_curve());
}
}
void OutputMap(const Map& map_pb) {
std::ofstream map_txt_file(FLAGS_output_dir + "/sim_map.txt");
map_txt_file << map_pb.DebugString();
map_txt_file.close();
std::ofstream map_bin_file(FLAGS_output_dir + "/sim_map.bin");
std::string map_str;
map_pb.SerializeToString(&map_str);
map_bin_file << map_str;
map_bin_file.close();
}
int main(int32_t argc, char** argv) {
google::InitGoogleLogging(argv[0]);
FLAGS_alsologtostderr = true;
FLAGS_v = 3;
google::ParseCommandLineFlags(&argc, &argv, true);
Map map_pb;
if (!GetProtoFromFile(FLAGS_map_file, &map_pb)) {
AERROR << "Fail to open:" << FLAGS_map_file;
return -1;
}
DownsampleMap(&map_pb);
OutputMap(map_pb);
AINFO << "sim_map generated at:" << FLAGS_output_dir;
}
<commit_msg>Add some log to map tool<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <string>
#include <vector>
#include "gflags/gflags.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/common/util/points_downsampler.h"
#include "modules/map/proto/map.pb.h"
/**
* A map tool to generate a downsampled map to be displayed by dreamview
* frontend.
*/
DEFINE_string(map_file, "", "map file name");
DEFINE_string(output_dir, "/tmp/", "output map directory");
DEFINE_double(angle_threshold, 1 / 180 * M_PI, /* 1 degree */
"Points are sampled when the accumulated direction change "
"exceeds the threshold");
DEFINE_int32(downsample_distance, 5, "downsample rate for a normal path");
DEFINE_int32(steep_turn_downsample_distance, 1,
"downsample rate for a steep turn path");
using apollo::common::util::DownsampleByAngle;
using apollo::common::util::DownsampleByDistance;
using apollo::common::util::GetProtoFromFile;
using apollo::common::PointENU;
using apollo::hdmap::Curve;
using apollo::hdmap::Map;
void DownsampleCurve(Curve* curve) {
std::vector<PointENU> points;
std::vector<int> sampled_indices;
auto* line_segment = curve->mutable_segment(0)->mutable_line_segment();
for (const auto& point : line_segment->point()) {
points.push_back(point);
}
int original_size = line_segment->point_size();
line_segment->clear_point();
// NOTE: this not the most efficient implementation, but since this map tool
// is only run once for each, we can probably live with that.
// Downsample points by angle then by distance.
DownsampleByAngle(points, FLAGS_angle_threshold, &sampled_indices);
std::vector<PointENU> downsampled_points;
for (int index : sampled_indices) {
downsampled_points.push_back(points[index]);
}
DownsampleByDistance(downsampled_points, FLAGS_downsample_distance,
FLAGS_steep_turn_downsample_distance, &sampled_indices);
for (int index : sampled_indices) {
*line_segment->add_point() = downsampled_points[index];
}
int new_size = line_segment->point_size();
AINFO << "Lane curve downsampled from " << original_size << " points to "
<< new_size << " points.";
}
void DownsampleMap(Map* map_pb) {
for (int i = 0; i < map_pb->lane_size(); ++i) {
auto* lane = map_pb->mutable_lane(i);
AINFO << "Downsampling lane " << lane->id().id();
DownsampleCurve(lane->mutable_central_curve());
DownsampleCurve(lane->mutable_left_boundary()->mutable_curve());
DownsampleCurve(lane->mutable_right_boundary()->mutable_curve());
}
}
void OutputMap(const Map& map_pb) {
std::ofstream map_txt_file(FLAGS_output_dir + "/sim_map.txt");
map_txt_file << map_pb.DebugString();
map_txt_file.close();
std::ofstream map_bin_file(FLAGS_output_dir + "/sim_map.bin");
std::string map_str;
map_pb.SerializeToString(&map_str);
map_bin_file << map_str;
map_bin_file.close();
}
int main(int32_t argc, char** argv) {
google::InitGoogleLogging(argv[0]);
FLAGS_alsologtostderr = true;
FLAGS_v = 3;
google::ParseCommandLineFlags(&argc, &argv, true);
Map map_pb;
if (!GetProtoFromFile(FLAGS_map_file, &map_pb)) {
AERROR << "Fail to open:" << FLAGS_map_file;
return -1;
}
DownsampleMap(&map_pb);
OutputMap(map_pb);
AINFO << "sim_map generated at:" << FLAGS_output_dir;
}
<|endoftext|> |
<commit_before>/**The MIT License (MIT)
Copyright (c) 2017 by Reaper7
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 <Esp.h>
#include "ESP8266SPIFFSUpdateFirmware.h"
#include <string.h>
#define FIRMWAREEXT ".bin"
#define FIRMWAREPATH ""
#define MINBINSIZE 100000
#define READBUFFSIZE 256
SPIFFSUpdateFirmware::SPIFFSUpdateFirmware()
: _firmwareext(FIRMWAREEXT)
, _firmwarepath(FIRMWAREPATH)
, _filesystemexists(false)
, _minSketchSpace(MINBINSIZE)
, _maxSketchSpace(MINBINSIZE)
, _start_callback(NULL)
, _end_callback(NULL)
//, _error_callback(NULL)
, _progress_callback(NULL)
{
}
SPIFFSUpdateFirmware::~SPIFFSUpdateFirmware() {
FirmwareListClean();
}
void SPIFFSUpdateFirmware::onStart(THandlerFunction fn) {
_start_callback = fn;
}
void SPIFFSUpdateFirmware::onEnd(THandlerFunction fn) {
_end_callback = fn;
}
void SPIFFSUpdateFirmware::onProgress(THandlerFunction_Progress fn) {
_progress_callback = fn;
}
/*
void SPIFFSUpdateFirmware::onError(THandlerFunction_Error fn) {
_error_callback = fn;
}
*/
uint32_t SPIFFSUpdateFirmware::getSize(uint8_t _index) {
if (_filesystemexists && _index >= 0 && _index < FirmwareList.size()) {
FirmwareFileList_t entry = FirmwareList[_index];
return (atoi(entry.fmsize));
} else
return (0);
}
String SPIFFSUpdateFirmware::getName(uint8_t _index) {
if (_filesystemexists && _index >= 0 && _index < FirmwareList.size()) {
FirmwareFileList_t entry = FirmwareList[_index];
return ((String)entry.fmname);
} else
return ("");
}
bool SPIFFSUpdateFirmware::startUpdate(String _fn, bool _rst) {
bool ret = false;
String _fname = _firmwarepath + "/" + _fn + _firmwareext;
if ((_filesystemexists) && (_fname != "")) {
if (SPIFFS.exists(_fname)) {
File firmfile = SPIFFS.open(_fname, "r");
uint32_t fsize = firmfile.size();
if (Update.begin(_maxSketchSpace, U_FLASH)) {
if (_start_callback) {
_start_callback();
}
uint32_t filerest = 0;
if (_progress_callback) {
_progress_callback(filerest, fsize);
}
uint8_t ibuffer[READBUFFSIZE];
while (firmfile.available()) {
uint32_t isize = fsize-filerest>=READBUFFSIZE?READBUFFSIZE:fsize-filerest;
firmfile.read((uint8_t *)ibuffer, isize);
filerest += Update.write(ibuffer, isize);
if (_progress_callback) {
_progress_callback(filerest, fsize);
}
}
if (Update.end(true)) {
ret = true;
if (_end_callback) {
_end_callback();
}
}
}
firmfile.close();
if (ret && _rst) {
delay(250);
ESP.restart();
}
}
}
return ret;
}
bool SPIFFSUpdateFirmware::startUpdate(uint8_t _index, bool _rst) {
if (_filesystemexists && _index >= 0 && _index < FirmwareList.size())
return (startUpdate(getName(_index), _rst));
else
return false;
}
uint8_t SPIFFSUpdateFirmware::getCount() {
if (_filesystemexists) {
Dir dir = SPIFFS.openDir(_firmwarepath);
while (dir.next()) {
String _fname = dir.fileName();
if (_fname.endsWith(_firmwareext)) {
uint32_t _fsize = dir.fileSize();
if (_fsize > _minSketchSpace && _fsize <= _maxSketchSpace) {
_fname = _fname.substring(_firmwarepath.length() + 1, _fname.length() - _firmwareext.length());
FirmwareListAdd(_fname.c_str(), _fsize);
}
}
}
}
return (FirmwareList.size());
}
void SPIFFSUpdateFirmware::FirmwareListAdd(const char* fmname, uint32_t fmsize) {
FirmwareFileList_t newFirmware;
char _fsch[16];
sprintf(_fsch,"%lu", fmsize);
newFirmware.fmsize = strdup(_fsch);
newFirmware.fmname = strdup(fmname);
FirmwareList.push_back(newFirmware);
}
void SPIFFSUpdateFirmware::FirmwareListClean(void) {
//clear & free firmware list
for(uint8_t i = 0; i < FirmwareList.size(); i++) {
FirmwareFileList_t entry = FirmwareList[i];
if(entry.fmname) {
free(entry.fmname);
}
if(entry.fmsize) {
free(entry.fmsize);
}
}
FirmwareList.clear();
}
bool SPIFFSUpdateFirmware::begin(String _fwpath) {
_filesystemexists = SPIFFS.begin();
if (_filesystemexists) {
FirmwareListClean();
_firmwarepath = _fwpath;
_maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
}
return (_filesystemexists);
}
bool SPIFFSUpdateFirmware::begin() {
return (begin(FIRMWAREPATH));
}
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SPIFFSFIRMWARE)
SPIFFSUpdateFirmware SPIFFSFirmware = SPIFFSUpdateFirmware();
#endif
<commit_msg>update startUpdate<commit_after>/**The MIT License (MIT)
Copyright (c) 2017 by Reaper7
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 <Esp.h>
#include "ESP8266SPIFFSUpdateFirmware.h"
#include <string.h>
#define FIRMWAREEXT ".bin"
#define FIRMWAREPATH ""
#define MINBINSIZE 100000
#define READBUFFSIZE 256
SPIFFSUpdateFirmware::SPIFFSUpdateFirmware()
: _firmwareext(FIRMWAREEXT)
, _firmwarepath(FIRMWAREPATH)
, _filesystemexists(false)
, _minSketchSpace(MINBINSIZE)
, _maxSketchSpace(MINBINSIZE)
, _start_callback(NULL)
, _end_callback(NULL)
//, _error_callback(NULL)
, _progress_callback(NULL)
{
}
SPIFFSUpdateFirmware::~SPIFFSUpdateFirmware() {
FirmwareListClean();
}
void SPIFFSUpdateFirmware::onStart(THandlerFunction fn) {
_start_callback = fn;
}
void SPIFFSUpdateFirmware::onEnd(THandlerFunction fn) {
_end_callback = fn;
}
void SPIFFSUpdateFirmware::onProgress(THandlerFunction_Progress fn) {
_progress_callback = fn;
}
/*
void SPIFFSUpdateFirmware::onError(THandlerFunction_Error fn) {
_error_callback = fn;
}
*/
uint32_t SPIFFSUpdateFirmware::getSize(uint8_t _index) {
if (_filesystemexists && _index >= 0 && _index < FirmwareList.size()) {
FirmwareFileList_t entry = FirmwareList[_index];
return (atoi(entry.fmsize));
} else
return (0);
}
String SPIFFSUpdateFirmware::getName(uint8_t _index) {
if (_filesystemexists && _index >= 0 && _index < FirmwareList.size()) {
FirmwareFileList_t entry = FirmwareList[_index];
return ((String)entry.fmname);
} else
return ("");
}
bool SPIFFSUpdateFirmware::startUpdate(String _fn, bool _rst) {
bool ret = false;
String _fname = _firmwarepath + "/" + _fn + _firmwareext;
if ((_filesystemexists) && (_fname != "")) {
if (SPIFFS.exists(_fname)) {
File firmfile = SPIFFS.open(_fname, "r");
uint32_t fsize = firmfile.size();
if (Update.begin(_maxSketchSpace, U_FLASH)) {
if (_start_callback) {
_start_callback();
}
uint32_t filerest = fsize;
if (_progress_callback) {
_progress_callback((fsize-filerest), fsize);
}
uint8_t ibuffer[READBUFFSIZE];
while (firmfile.available()) {
uint32_t isize = (filerest < READBUFFSIZE) ? filerest : READBUFFSIZE;
firmfile.read((uint8_t *)ibuffer, isize);
filerest -= Update.write(ibuffer, isize);
if (_progress_callback) {
_progress_callback((fsize-filerest), fsize);
}
}
if (Update.end(true)) {
ret = true;
if (_end_callback) {
_end_callback();
}
}
}
firmfile.close();
if (ret && _rst) {
delay(250);
ESP.restart();
}
}
}
return ret;
}
bool SPIFFSUpdateFirmware::startUpdate(uint8_t _index, bool _rst) {
if (_filesystemexists && _index >= 0 && _index < FirmwareList.size())
return (startUpdate(getName(_index), _rst));
else
return false;
}
uint8_t SPIFFSUpdateFirmware::getCount() {
if (_filesystemexists) {
Dir dir = SPIFFS.openDir(_firmwarepath);
while (dir.next()) {
String _fname = dir.fileName();
if (_fname.endsWith(_firmwareext)) {
uint32_t _fsize = dir.fileSize();
if (_fsize > _minSketchSpace && _fsize <= _maxSketchSpace) {
_fname = _fname.substring(_firmwarepath.length() + 1, _fname.length() - _firmwareext.length());
FirmwareListAdd(_fname.c_str(), _fsize);
}
}
}
}
return (FirmwareList.size());
}
void SPIFFSUpdateFirmware::FirmwareListAdd(const char* fmname, uint32_t fmsize) {
FirmwareFileList_t newFirmware;
char _fsch[16];
sprintf(_fsch,"%lu", fmsize);
newFirmware.fmsize = strdup(_fsch);
newFirmware.fmname = strdup(fmname);
FirmwareList.push_back(newFirmware);
}
void SPIFFSUpdateFirmware::FirmwareListClean(void) {
//clear & free firmware list
for(uint8_t i = 0; i < FirmwareList.size(); i++) {
FirmwareFileList_t entry = FirmwareList[i];
if(entry.fmname) {
free(entry.fmname);
}
if(entry.fmsize) {
free(entry.fmsize);
}
}
FirmwareList.clear();
}
bool SPIFFSUpdateFirmware::begin(String _fwpath) {
_filesystemexists = SPIFFS.begin();
if (_filesystemexists) {
FirmwareListClean();
_firmwarepath = _fwpath;
_maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
}
return (_filesystemexists);
}
bool SPIFFSUpdateFirmware::begin() {
return (begin(FIRMWAREPATH));
}
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SPIFFSFIRMWARE)
SPIFFSUpdateFirmware SPIFFSFirmware = SPIFFSUpdateFirmware();
#endif
<|endoftext|> |
<commit_before>#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <algorithm>
#include <functional>
#include <thread>
#include "Core.hpp"
#include "FileSystem.hpp"
#include "Util.hpp"
#include "Index.hpp"
#include "Config.hpp"
#include "Refs.hpp"
#include "Status.hpp"
#include "Objects.hpp"
#ifdef WIN32
#include <Windows.h>
#endif
namespace Sit {
namespace Core {
void Init()
{
using namespace boost::filesystem;
try {
if (exists(".sit")) {
if (is_directory(".sit")) {
remove_all(".sit");
} else {
throw Util::SitException("Fatal: .sit is existed but not a directory please check it.");
}
}
create_directories(".sit");
#ifdef WIN32
SetFileAttributes(L".sit", FILE_ATTRIBUTE_HIDDEN);
#endif
create_directories(".sit/refs");
create_directories(".sit/refs/heads");
create_directories(".sit/objects");
FileSystem::Write(".sit/HEAD", Refs::EMPTY_REF);
FileSystem::Write(".sit/COMMIT_MSG", "");
FileSystem::Write(".sit/refs/heads/master", Refs::EMPTY_REF);
} catch (const boost::filesystem::filesystem_error &fe) {
std::cerr << fe.what() << std::endl;
} catch (const std::exception &stdEc) {
std::cerr << stdEc.what() << std::endl;
}
}
void LoadRepo()
{
using namespace boost::filesystem;
path curPath = current_path();
while (!curPath.empty()) {
if (is_directory(curPath / ".sit")) {
FileSystem::REPO_ROOT = curPath;
Index::index.Load();
return ;
}
curPath = curPath.parent_path();
}
throw Sit::Util::SitException("Fatal: Not a sit repository (or any of the parent directories): .sit");
}
std::string addFile(const boost::filesystem::path &file)
{
if (FileSystem::IsDirectory(file)) {
return "";
}
try {
auto fileSize = boost::filesystem::file_size(file);
if (fileSize > (100 << 20)) {
std::cerr << "Warning : Try to add a file larger than 100MB" << std::endl;
}
if (fileSize > (200 << 20)) {
throw Sit::Util::SitException("Fatal: Try to add a file larger than 200MB", file.string());
}
std::string sha1Value = Sit::Util::SHA1sum(FileSystem::Read(file));
boost::filesystem::path dstFile(FileSystem::REPO_ROOT / FileSystem::OBJECTS_DIR / sha1Value.substr(0, 2) / sha1Value.substr(2));
FileSystem::SafeCopyFile(file, dstFile);
std::cout << file << " added." << std::endl;
return sha1Value;
} catch (const boost::filesystem::filesystem_error &fe) {
std::cerr << fe.what() << std::endl;
} catch (const std::exception &stdEc) {
std::cerr << stdEc.what() << std::endl;
}
return std::string("");
}
void Add(const boost::filesystem::path &path)
{
auto fileList = FileSystem::ListRecursive(path, true, false);
for (const auto &file : fileList) {
if (FileSystem::IsDirectory(file)) {
continue;
}
boost::filesystem::path relativePath = FileSystem::GetRelativePath(file);
Index::index.Insert(relativePath, addFile(file));
}
Index::index.Save();
}
void Rm(const boost::filesystem::path &path)
{
Index::index.Remove(FileSystem::GetRelativePath(path));
Index::index.Save();
}
std::string getCommitMessage()
{
std::stringstream in(FileSystem::Read(FileSystem::REPO_ROOT / FileSystem::SIT_ROOT / "COMMIT_MSG"));
std::stringstream out;
std::string line;
bool empty = true;
while (getline(in, line)) {
boost::trim(line);
if (line.empty()) {
if (!empty) out << "\n";
} else if (line[0] != '#') {
out << line << "\n";
empty = false;
}
}
return out.str();
}
void amend(const std::string &oldid, const std::string &newid)
{
std::vector<std::pair<std::string, Objects::Commit>> olds;
for (std::string id(Refs::Get(Refs::Local("master"))); id != oldid; ) {
const Objects::Commit commit(Objects::GetCommit(id));
olds.push_back(std::make_pair(id, commit));
id = commit.parent;
}
std::string last = newid;
for (auto iter = olds.rbegin(); iter != olds.rend(); ++iter) {
iter->second.parent = last;
last = Objects::WriteCommit(iter->second);
}
Refs::Set(Refs::Local("master"), last);
}
void Commit(const std::string &msg, const bool isAmend)
{
using Util::SitException;
using boost::posix_time::to_simple_string;
using boost::posix_time::second_clock;
const std::string headref(Refs::Get("HEAD"));
const std::string masterref(Refs::Get(Refs::Local("master")));
Objects::Commit commit;
if (headref != masterref && !isAmend) {
throw SitException("HEAD is not up-to-date with master. Cannot commit.");
}
if (!FileSystem::IsFile(FileSystem::REPO_ROOT / FileSystem::SIT_ROOT / "COMMIT_MSG")) {
throw SitException("Commit message not found.");
}
commit.message = msg.empty() ? getCommitMessage() : msg;
if (commit.message.empty()) {
throw SitException("Commit message is empty.");
}
const std::string user_name = Config::Get("user.name");
if (user_name == Config::NOT_FOUND) {
throw SitException("Config `user.name` not found.", "config: user.name");
}
const std::string user_email = Config::Get("user.email");
if (user_email == Config::NOT_FOUND) {
throw SitException("Config `user.email` not found.", "config: user.email");
}
const std::string datetime(to_simple_string(second_clock::local_time()));
commit.author = Util::AuthorString(user_name, user_email, datetime);
commit.committer = Util::AuthorString(user_name, user_email, datetime);
if (!isAmend) {
commit.parent = masterref;
} else {
const Objects::Commit oldcommit(Objects::GetCommit(headref));
commit.parent = oldcommit.parent;
}
commit.tree = Objects::WriteIndex();
const std::string id(Objects::WriteCommit(commit));
if (!isAmend) {
Refs::Set(Refs::Local("master"), id);
} else {
amend(headref, id);
}
Refs::Set("HEAD", id);
}
void Status()
{
Status::PrintStatus(std::cout);
}
void Checkout(std::string commitid, std::string filename)
{
commitid = Util::SHA1Complete(commitid);
if (!commitid.empty() && !Objects::IsExist(commitid)) {
std::cerr << "Error: Commit " << commitid << " doesn't exist." << std::endl;
return;
}
if (!filename.empty()) {
filename = FileSystem::GetRelativePath(filename).generic_string();
}
Index::IndexBase index;
if (commitid.empty()) {
index = Index::index;
} else {
index = Index::CommitIndex(commitid);
}
const std::map<boost::filesystem::path, std::string> &idx(index.GetIndex());
if (filename.empty()) {
// Commit Checkout
if (!Status::IsClean()) {
std::cerr << "Error: You have something staged. Commit or reset before checkout." << std::endl;
return;
}
Index::index.Clear();
for (const auto &item : idx) {
const auto src(Objects::GetPath(item.second));
const auto dst(FileSystem::REPO_ROOT / item.first);
FileSystem::SafeCopyFile(src, dst);
Index::index.Insert(item.first, item.second);
}
Index::index.Save();
if (!commitid.empty()) {
Refs::Set("HEAD", commitid);
}
} else {
// File Checkout
if (filename.back() != '/' && index.InIndex(filename)) {
const boost::filesystem::path path(filename);
const std::string objpath(idx.find(path)->second);
const auto src(Objects::GetPath(objpath));
const auto dst(FileSystem::REPO_ROOT / filename);
FileSystem::SafeCopyFile(src, dst);
} else {
const auto &&fileSet(index.ListFile(filename));
if (!fileSet.empty()) {
for (const auto &singleFile : fileSet) {
const auto src(Objects::GetPath(singleFile.second));
const auto dst(FileSystem::REPO_ROOT / singleFile.first);
FileSystem::SafeCopyFile(src, dst);
}
} else {
std::cerr << "Error: " << filename << " doesn't exist in file list";
return;
}
}
}
}
void printLog(std::ostream &out, const Objects::Commit &commit, const std::string &id)
{
out << Color::BROWN << "Commit " << id << Color::RESET << std::endl
<< "Author: " << commit.author << std::endl
<< std::endl;
std::istringstream ss(commit.message);
std::string line;
while (std::getline(ss, line)) out << " " << line << std::endl;
}
void Log(std::string id)
{
if (id == "master") {
id = Refs::Get(Refs::Local("master"));
while (id != Refs::EMPTY_REF) {
Objects::Commit commit(Objects::GetCommit(id));
printLog(std::cout, commit, id);
id = commit.parent;
}
} else {
Objects::Commit commit(Objects::GetCommit(id));
printLog(std::cout, commit, id);
}
}
void resetSingleFile(std::ostream &stream, std::string id, std::string filename, const Index::CommitIndex &commitIndex, const bool &inCommit, const bool &inIndex, const bool isHard)
{
if (inCommit && !inIndex) {
stream << " index <++ ";
Index::index.Insert(filename, commitIndex.GetID(filename));
if (isHard) {
Checkout(id, filename);
}
} else if (!inCommit && inIndex) {
stream << " index --> ";
Index::index.Remove(filename);
if (isHard) {
FileSystem::Remove(filename);
}
} else if (inCommit && inIndex) {
stream << commitIndex.GetID(filename) << " ==> ";
Index::index.Remove(filename);
Index::index.Insert(filename, commitIndex.GetID(filename));
if (isHard) {
Checkout(id, filename);
}
} else {
std::cerr << "Error: " << filename << " is not tracked" << std::endl;
return;
}
stream << boost::filesystem::path(filename) << std::endl;
Index::index.Save();
}
void Reset(std::ostream &stream, std::string id, std::string filename, const bool isHard)
{
if (id == "master") {
id = Refs::Get(Refs::Local("master"));
} else if (id == "HEAD" || id.empty()) {
id = Refs::Get("HEAD");
}
id = Sit::Util::SHA1Complete(id);
if (!filename.empty()) {
filename = FileSystem::GetRelativePath(filename).generic_string();
}
const Index::CommitIndex commitIndex(id);
Index::FileSet commitSet = commitIndex.ListFile(filename);
Index::FileSet indexSet = Index::index.ListFile(filename);
std::set<std::string> allSet;
for (const auto &fileInCommit : commitSet) {
allSet.insert(fileInCommit.first.generic_string());
}
for (const auto &fileInIndex : indexSet) {
allSet.insert(fileInIndex.first.generic_string());
}
for (const auto &anyfile : allSet) {
const bool inCommit = commitSet.count(anyfile) > 0;
const bool inIndex = indexSet.count(anyfile) > 0;
resetSingleFile(stream, id, anyfile, commitIndex, inCommit, inIndex, isHard);
}
}
void Diff(const std::string &baseID, const std::string &targetID)
{
Diff::DiffIndex(std::cout, Util::SHA1Complete(baseID), Util::SHA1Complete(targetID));
}
void Diff(const std::string &baseID, const std::string &targetID, const std::vector<std::string> &fileList)
{
const auto cBaseID = Util::SHA1Complete(baseID);
const auto cTargetID = Util::SHA1Complete(targetID);
const Index::IndexBase base(Index::GetIndex(cBaseID));
const Index::IndexBase target(Index::GetIndex(cTargetID));
const Diff::DiffList diff(Diff::Diff(base, target));
Index::IndexList baseFileList;
Index::IndexList targetFileList;
for (const auto &file : fileList) {
const auto newPath = FileSystem::GetRelativePath(file);
const auto extendedBaseFile = base.ListFile(newPath.generic_string());
for (const auto &item : extendedBaseFile) {
baseFileList.push_back(item);
}
const auto extendedTargetFile = target.ListFile(newPath.generic_string());
for (const auto &item : extendedTargetFile) {
targetFileList.push_back(item);
}
}
std::set<std::string> AllFile;
for (const auto &file : baseFileList) {
AllFile.insert(file.first.generic_string());
}
for (const auto &file : targetFileList) {
AllFile.insert(file.first.generic_string());
}
for (const auto &file : AllFile) {
const auto &item = diff.at(file);
std::cout << "Diffing at " << file << std::endl;
if (item.status == Diff::Same) {
std::cout << " No difference between two version" << std::endl;
} else {
Diff::DiffObject(std::cout, item, baseID, targetID);
}
}
}
void GarbageCollection()
{
auto existedList = Objects::ListExistedObjects();
auto refereddList = Objects::ListReferedObjects();
for (const auto &element : existedList) {
if (refereddList.count(element)) {
continue;
} else {
Objects::Remove(element);
}
}
}
}
}<commit_msg>What the hell...<commit_after>#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <algorithm>
#include <functional>
#include "Core.hpp"
#include "FileSystem.hpp"
#include "Util.hpp"
#include "Index.hpp"
#include "Config.hpp"
#include "Refs.hpp"
#include "Status.hpp"
#include "Objects.hpp"
#ifdef WIN32
#include <Windows.h>
#endif
namespace Sit {
namespace Core {
void Init()
{
using namespace boost::filesystem;
try {
if (exists(".sit")) {
if (is_directory(".sit")) {
remove_all(".sit");
} else {
throw Util::SitException("Fatal: .sit is existed but not a directory please check it.");
}
}
create_directories(".sit");
#ifdef WIN32
SetFileAttributes(L".sit", FILE_ATTRIBUTE_HIDDEN);
#endif
create_directories(".sit/refs");
create_directories(".sit/refs/heads");
create_directories(".sit/objects");
FileSystem::Write(".sit/HEAD", Refs::EMPTY_REF);
FileSystem::Write(".sit/COMMIT_MSG", "");
FileSystem::Write(".sit/refs/heads/master", Refs::EMPTY_REF);
} catch (const boost::filesystem::filesystem_error &fe) {
std::cerr << fe.what() << std::endl;
} catch (const std::exception &stdEc) {
std::cerr << stdEc.what() << std::endl;
}
}
void LoadRepo()
{
using namespace boost::filesystem;
path curPath = current_path();
while (!curPath.empty()) {
if (is_directory(curPath / ".sit")) {
FileSystem::REPO_ROOT = curPath;
Index::index.Load();
return ;
}
curPath = curPath.parent_path();
}
throw Sit::Util::SitException("Fatal: Not a sit repository (or any of the parent directories): .sit");
}
std::string addFile(const boost::filesystem::path &file)
{
if (FileSystem::IsDirectory(file)) {
return "";
}
try {
auto fileSize = boost::filesystem::file_size(file);
if (fileSize > (100 << 20)) {
std::cerr << "Warning : Try to add a file larger than 100MB" << std::endl;
}
if (fileSize > (200 << 20)) {
throw Sit::Util::SitException("Fatal: Try to add a file larger than 200MB", file.string());
}
std::string sha1Value = Sit::Util::SHA1sum(FileSystem::Read(file));
boost::filesystem::path dstFile(FileSystem::REPO_ROOT / FileSystem::OBJECTS_DIR / sha1Value.substr(0, 2) / sha1Value.substr(2));
FileSystem::SafeCopyFile(file, dstFile);
std::cout << file << " added." << std::endl;
return sha1Value;
} catch (const boost::filesystem::filesystem_error &fe) {
std::cerr << fe.what() << std::endl;
} catch (const std::exception &stdEc) {
std::cerr << stdEc.what() << std::endl;
}
return std::string("");
}
void Add(const boost::filesystem::path &path)
{
auto fileList = FileSystem::ListRecursive(path, true, false);
for (const auto &file : fileList) {
if (FileSystem::IsDirectory(file)) {
continue;
}
boost::filesystem::path relativePath = FileSystem::GetRelativePath(file);
Index::index.Insert(relativePath, addFile(file));
}
Index::index.Save();
}
void Rm(const boost::filesystem::path &path)
{
Index::index.Remove(FileSystem::GetRelativePath(path));
Index::index.Save();
}
std::string getCommitMessage()
{
std::stringstream in(FileSystem::Read(FileSystem::REPO_ROOT / FileSystem::SIT_ROOT / "COMMIT_MSG"));
std::stringstream out;
std::string line;
bool empty = true;
while (getline(in, line)) {
boost::trim(line);
if (line.empty()) {
if (!empty) out << "\n";
} else if (line[0] != '#') {
out << line << "\n";
empty = false;
}
}
return out.str();
}
void amend(const std::string &oldid, const std::string &newid)
{
std::vector<std::pair<std::string, Objects::Commit>> olds;
for (std::string id(Refs::Get(Refs::Local("master"))); id != oldid; ) {
const Objects::Commit commit(Objects::GetCommit(id));
olds.push_back(std::make_pair(id, commit));
id = commit.parent;
}
std::string last = newid;
for (auto iter = olds.rbegin(); iter != olds.rend(); ++iter) {
iter->second.parent = last;
last = Objects::WriteCommit(iter->second);
}
Refs::Set(Refs::Local("master"), last);
}
void Commit(const std::string &msg, const bool isAmend)
{
using Util::SitException;
using boost::posix_time::to_simple_string;
using boost::posix_time::second_clock;
const std::string headref(Refs::Get("HEAD"));
const std::string masterref(Refs::Get(Refs::Local("master")));
Objects::Commit commit;
if (headref != masterref && !isAmend) {
throw SitException("HEAD is not up-to-date with master. Cannot commit.");
}
if (!FileSystem::IsFile(FileSystem::REPO_ROOT / FileSystem::SIT_ROOT / "COMMIT_MSG")) {
throw SitException("Commit message not found.");
}
commit.message = msg.empty() ? getCommitMessage() : msg;
if (commit.message.empty()) {
throw SitException("Commit message is empty.");
}
const std::string user_name = Config::Get("user.name");
if (user_name == Config::NOT_FOUND) {
throw SitException("Config `user.name` not found.", "config: user.name");
}
const std::string user_email = Config::Get("user.email");
if (user_email == Config::NOT_FOUND) {
throw SitException("Config `user.email` not found.", "config: user.email");
}
const std::string datetime(to_simple_string(second_clock::local_time()));
commit.author = Util::AuthorString(user_name, user_email, datetime);
commit.committer = Util::AuthorString(user_name, user_email, datetime);
if (!isAmend) {
commit.parent = masterref;
} else {
const Objects::Commit oldcommit(Objects::GetCommit(headref));
commit.parent = oldcommit.parent;
}
commit.tree = Objects::WriteIndex();
const std::string id(Objects::WriteCommit(commit));
if (!isAmend) {
Refs::Set(Refs::Local("master"), id);
} else {
amend(headref, id);
}
Refs::Set("HEAD", id);
}
void Status()
{
Status::PrintStatus(std::cout);
}
void Checkout(std::string commitid, std::string filename)
{
commitid = Util::SHA1Complete(commitid);
if (!commitid.empty() && !Objects::IsExist(commitid)) {
std::cerr << "Error: Commit " << commitid << " doesn't exist." << std::endl;
return;
}
if (!filename.empty()) {
filename = FileSystem::GetRelativePath(filename).generic_string();
}
Index::IndexBase index;
if (commitid.empty()) {
index = Index::index;
} else {
index = Index::CommitIndex(commitid);
}
const std::map<boost::filesystem::path, std::string> &idx(index.GetIndex());
if (filename.empty()) {
// Commit Checkout
if (!Status::IsClean()) {
std::cerr << "Error: You have something staged. Commit or reset before checkout." << std::endl;
return;
}
Index::index.Clear();
for (const auto &item : idx) {
const auto src(Objects::GetPath(item.second));
const auto dst(FileSystem::REPO_ROOT / item.first);
FileSystem::SafeCopyFile(src, dst);
Index::index.Insert(item.first, item.second);
}
Index::index.Save();
if (!commitid.empty()) {
Refs::Set("HEAD", commitid);
}
} else {
// File Checkout
if (filename.back() != '/' && index.InIndex(filename)) {
const boost::filesystem::path path(filename);
const std::string objpath(idx.find(path)->second);
const auto src(Objects::GetPath(objpath));
const auto dst(FileSystem::REPO_ROOT / filename);
FileSystem::SafeCopyFile(src, dst);
} else {
const auto &&fileSet(index.ListFile(filename));
if (!fileSet.empty()) {
for (const auto &singleFile : fileSet) {
const auto src(Objects::GetPath(singleFile.second));
const auto dst(FileSystem::REPO_ROOT / singleFile.first);
FileSystem::SafeCopyFile(src, dst);
}
} else {
std::cerr << "Error: " << filename << " doesn't exist in file list";
return;
}
}
}
}
void printLog(std::ostream &out, const Objects::Commit &commit, const std::string &id)
{
out << Color::BROWN << "Commit " << id << Color::RESET << std::endl
<< "Author: " << commit.author << std::endl
<< std::endl;
std::istringstream ss(commit.message);
std::string line;
while (std::getline(ss, line)) out << " " << line << std::endl;
}
void Log(std::string id)
{
if (id == "master") {
id = Refs::Get(Refs::Local("master"));
while (id != Refs::EMPTY_REF) {
Objects::Commit commit(Objects::GetCommit(id));
printLog(std::cout, commit, id);
id = commit.parent;
}
} else {
Objects::Commit commit(Objects::GetCommit(id));
printLog(std::cout, commit, id);
}
}
void resetSingleFile(std::ostream &stream, std::string id, std::string filename, const Index::CommitIndex &commitIndex, const bool &inCommit, const bool &inIndex, const bool isHard)
{
if (inCommit && !inIndex) {
stream << " index <++ ";
Index::index.Insert(filename, commitIndex.GetID(filename));
if (isHard) {
Checkout(id, filename);
}
} else if (!inCommit && inIndex) {
stream << " index --> ";
Index::index.Remove(filename);
if (isHard) {
FileSystem::Remove(filename);
}
} else if (inCommit && inIndex) {
stream << commitIndex.GetID(filename) << " ==> ";
Index::index.Remove(filename);
Index::index.Insert(filename, commitIndex.GetID(filename));
if (isHard) {
Checkout(id, filename);
}
} else {
std::cerr << "Error: " << filename << " is not tracked" << std::endl;
return;
}
stream << boost::filesystem::path(filename) << std::endl;
Index::index.Save();
}
void Reset(std::ostream &stream, std::string id, std::string filename, const bool isHard)
{
if (id == "master") {
id = Refs::Get(Refs::Local("master"));
} else if (id == "HEAD" || id.empty()) {
id = Refs::Get("HEAD");
}
id = Sit::Util::SHA1Complete(id);
if (!filename.empty()) {
filename = FileSystem::GetRelativePath(filename).generic_string();
}
const Index::CommitIndex commitIndex(id);
Index::FileSet commitSet = commitIndex.ListFile(filename);
Index::FileSet indexSet = Index::index.ListFile(filename);
std::set<std::string> allSet;
for (const auto &fileInCommit : commitSet) {
allSet.insert(fileInCommit.first.generic_string());
}
for (const auto &fileInIndex : indexSet) {
allSet.insert(fileInIndex.first.generic_string());
}
for (const auto &anyfile : allSet) {
const bool inCommit = commitSet.count(anyfile) > 0;
const bool inIndex = indexSet.count(anyfile) > 0;
resetSingleFile(stream, id, anyfile, commitIndex, inCommit, inIndex, isHard);
}
}
void Diff(const std::string &baseID, const std::string &targetID)
{
Diff::DiffIndex(std::cout, Util::SHA1Complete(baseID), Util::SHA1Complete(targetID));
}
void Diff(const std::string &baseID, const std::string &targetID, const std::vector<std::string> &fileList)
{
const auto cBaseID = Util::SHA1Complete(baseID);
const auto cTargetID = Util::SHA1Complete(targetID);
const Index::IndexBase base(Index::GetIndex(cBaseID));
const Index::IndexBase target(Index::GetIndex(cTargetID));
const Diff::DiffList diff(Diff::Diff(base, target));
Index::IndexList baseFileList;
Index::IndexList targetFileList;
for (const auto &file : fileList) {
const auto newPath = FileSystem::GetRelativePath(file);
const auto extendedBaseFile = base.ListFile(newPath.generic_string());
for (const auto &item : extendedBaseFile) {
baseFileList.push_back(item);
}
const auto extendedTargetFile = target.ListFile(newPath.generic_string());
for (const auto &item : extendedTargetFile) {
targetFileList.push_back(item);
}
}
std::set<std::string> AllFile;
for (const auto &file : baseFileList) {
AllFile.insert(file.first.generic_string());
}
for (const auto &file : targetFileList) {
AllFile.insert(file.first.generic_string());
}
for (const auto &file : AllFile) {
const auto &item = diff.at(file);
std::cout << "Diffing at " << file << std::endl;
if (item.status == Diff::Same) {
std::cout << " No difference between two version" << std::endl;
} else {
Diff::DiffObject(std::cout, item, baseID, targetID);
}
}
}
void GarbageCollection()
{
auto existedList = Objects::ListExistedObjects();
auto refereddList = Objects::ListReferedObjects();
for (const auto &element : existedList) {
if (refereddList.count(element)) {
continue;
} else {
Objects::Remove(element);
}
}
}
}
}<|endoftext|> |
<commit_before>#include "bitmapimage.h"
BitmapImage::BitmapImage()
{
m_Image = NULL;
visible = true;
m_ScaleFactor = 1.0;
qDebug() << "Image drawn!" << endl;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
BitmapImage::BitmapImage(const BitmapImage &image)
{
m_pixmap = image.m_pixmap;
boundaries = image.boundaries;
m_Color = image.m_Color;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
visible = true;
m_inc = 0.01;
}
BitmapImage::BitmapImage(Object *parent, QRect boundaries, QColor color)
{
myParent = parent;
this->boundaries = boundaries;
m_Image = new QImage(boundaries.size(), QImage::Format_ARGB32_Premultiplied);
m_Image->fill(color.rgba());
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
visible = true;
m_inc = 0.01;
}
BitmapImage::BitmapImage(Object *parent, QRect boundaries, QImage image)
{
myParent = parent;
this->boundaries = boundaries;
m_Image = new QImage(image);
if(m_Image->width() != boundaries.width() && m_Image->height() != boundaries.height()) qDebug() << "Error 0001: Failed to load Image" << endl;
visible = true;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
BitmapImage::BitmapImage(QRect boundaries, QColor color)
{
this->boundaries = boundaries;
QPixmap temp(boundaries.width(), boundaries.height());
temp.fill(color);
QPainter painter(&temp);
if(!temp.isNull())
{
painter.drawPixmap(0, 0, temp);
}
painter.end();
m_pixmap = temp;
visible = true;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
BitmapImage::BitmapImage(QRect boundaries, QPixmap pixMap)
{
this->boundaries = boundaries;
m_pixmap = pixMap;
visible = true;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
void BitmapImage::paintImage(QPainter &painter)
{
painter.drawPixmap(0, 0, m_pixmap);
}
void BitmapImage::paintImage(QPainterPath painterPath, Brush brush)
{
QPainter painter(&m_pixmap);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::NoBrush);
QPen copyPen = brush.getPen();
if(brush.getSize() > 0)
{
copyPen.setBrush(brush.getBrush());
copyPen.setWidth(brush.getSize());
painter.setPen(copyPen);
}else{
copyPen.setBrush(Qt::NoBrush);
copyPen.setWidth(0);
painter.setPen(copyPen);
}
painter.drawPath(painterPath);
}
void BitmapImage::paintImage(QPoint point, Brush brush){
int brushWidth = brush.getSize() + (brush.getPressureVal() * brush.getTransferSize());
brushWidth += m_ScaleFactor;
QImage stencilBase = brush.getStencil().toImage();
stencilBase.invertPixels(QImage::InvertRgb);
stencilBase.createAlphaMask();
stencilBase.convertToFormat(QImage::Format_ARGB32, Qt::AutoColor);
QImage stencilImage = QImage(stencilBase);
QColor color = brush.getColor();
color.setAlpha(brush.getOpacity() + (brush.getPressureVal() * brush.getTransferOpacity()));
stencilImage.fill(color);
QPixmap stencil = QPixmap::fromImage(stencilImage.scaled(brushWidth, brushWidth, Qt::IgnoreAspectRatio, Qt::FastTransformation));
QPainter p(&m_pixmap);
p.setRenderHint(QPainter::Antialiasing);
p.drawPixmap(QPoint(point.x() - stencil.width()/2, point.y() - stencil.height()/2), stencil);
}
void BitmapImage::paintImage(QVector<QPointF> pointInfo, Brush brush)
{
int brushWidth = brush.getSize() + (brush.getPressureVal() * brush.getTransferSize());
brushWidth *= m_ScaleFactor;
/*-Prepare Stencil-*/
QImage stencilBase = brush.getStencil().toImage();
stencilBase.invertPixels(QImage::InvertRgb);
stencilBase.createAlphaMask();
stencilBase.convertToFormat(QImage::Format_ARGB32, Qt::AutoColor);
QImage stencilImage = QImage(stencilBase);
QColor color = brush.getColor();
color.setAlpha(brush.getOpacity() + (brush.getPressureVal() * brush.getTransferOpacity()));
stencilImage.fill(color);
stencilImage.setAlphaChannel(stencilBase);
QPixmap stencil = QPixmap::fromImage(stencilImage.scaled(brushWidth, brushWidth, Qt::IgnoreAspectRatio, Qt::FastTransformation));
QPainter painter(&m_pixmap);
painter.setRenderHint(QPainter::Antialiasing);
/*Calculate incrementation value*/
qreal inc = 0.01;
QPainterPath path;
path.moveTo(pointInfo.first());
path.lineTo(pointInfo.last());
inc = getIncrement(pointInfo.first(), pointInfo.last());
if(inc == 0){
inc = m_inc;
}
/* Automatically adjust the incrementing value */
for(qreal i = 0; i < 1; i+= inc * brush.getSpacing()){
painter.drawPixmap(QPoint(path.pointAtPercent(i).x() - stencil.width()/2, path.pointAtPercent(i).y() - stencil.width()/2), stencil);
}
/*-Old Method-*/
// QPointF point, drawPoint;
// point = pointInfo.last() - pointInfo.first();
// int length = point.manhattanLength();
// double xInc, yInc;
// xInc = point.x() / (double)length;
// yInc = point.y() / (double)length;
// drawPoint = pointInfo.first();
// for(int i = 0; i < length; i++){
// if(drawPoint != pointInfo.last() || drawPoint != pointInfo.first()){
// drawPoint.setX(drawPoint.x() + (xInc / (double)brush.getSpacing() ));
// drawPoint.setY(drawPoint.y() + (yInc / (double)brush.getSpacing() ));
// painter.drawPixmap(QPoint(drawPoint.x() - stencil.width() / 2, drawPoint.y() - stencil.height()/2) / m_ScaleFactor, stencil);
// }
// }
}
void BitmapImage::paintImage(QVector<QPointF> pointInfo, Brush brush, qreal tabPress, int amt)
{
int brushWidth = brush.getSize() + (amt * tabPress);
/*-Prepare Stencil-*/
QImage stencilBase = brush.getStencil().toImage();
stencilBase.invertPixels(QImage::InvertRgb);
stencilBase.createAlphaMask();
stencilBase.convertToFormat(QImage::Format_RGB888, Qt::AutoColor);
QImage stencilImage = QImage(stencilBase);
QColor color = brush.getColor();
color.setAlpha(brush.getOpacity());
stencilImage.fill(color);
stencilImage.setAlphaChannel(stencilBase);
QPixmap stencil = QPixmap::fromImage(stencilImage.scaled(brushWidth, brushWidth, Qt::IgnoreAspectRatio, Qt::FastTransformation));
QPainter painter(&m_pixmap);
painter.setRenderHint(QPainter::Antialiasing);
QPointF point, drawPoint;
point = pointInfo.last() - pointInfo.first();
int length = point.manhattanLength();
double xInc, yInc;
xInc = point.x() / length;
yInc = point.y() / length;
drawPoint = pointInfo.first();
for(int i = 0; i < length; i++){
drawPoint.setX(drawPoint.x() + (xInc * brush.getSpacing() ));
drawPoint.setY(drawPoint.y() + (yInc * brush.getSpacing() ));
painter.drawPixmap(QPoint(drawPoint.x() - stencil.width() / 2, drawPoint.y() - stencil.height()/2), stencil);
}
}
void BitmapImage::fillImage(QPoint point, Brush brush){
QImage img = m_pixmap.toImage();
QRgb oldColor = img.pixel(point);
QRgb newColor = brush.getColor().rgb();
fillRecurs(point, img, oldColor, newColor);
m_pixmap = QPixmap::fromImage(img);
}
void BitmapImage::scale(double s){
m_ScaleFactor = s;
}
void BitmapImage::commitChanges(QPoint drawPoint, QPixmap pixmap){
QPainter p(&m_pixmap);
p.drawPixmap(drawPoint, pixmap);
}
/*
*
* Implementation of this function is as close to the version in EasyPaint.
*
*/
void BitmapImage::fillRecurs(QPoint pos, QImage& img, QRgb oldColor, QRgb newColor){
int temp_x(pos.x());
int left_x = 0;
while(true){
if(img.pixel(temp_x, pos.y()) != oldColor){
break;
}
img.setPixel(temp_x, pos.y(), newColor);
if(temp_x > 0){
temp_x--;
left_x = temp_x;
}else{
break;
}
}
int right_x(0);
temp_x = pos.x() + 1;
while(true){
if(img.pixel(temp_x, pos.y()) != oldColor){
break;
}
img.setPixel(temp_x, pos.y(), newColor);
if(temp_x < img.width() -1){
temp_x++;
right_x = temp_x;
}else{
break;
}
}
for(int x = left_x+1; x < right_x; x++){
if(pos.y() < 1 || pos.y() >= img.height() - 1){
break;
}
if(right_x > img.width()){ break; }
QRgb currentColor = img.pixel(x, pos.y()-1);
if(currentColor == oldColor && currentColor != newColor){
fillRecurs(QPoint(x, pos.y() -1), img, oldColor, newColor);
}
currentColor = img.pixel(x, pos.y() + 1);
if(currentColor == oldColor && currentColor != newColor){
fillRecurs(QPoint(x, pos.y() + 1), img, oldColor, newColor);
}
}
}
void BitmapImage::cutImgOp(QRect rect, BitmapImage &img){
QPainter p(&m_pixmap);
}
void BitmapImage::cutImgOp(QRect rect, QColor col){
QPainter p(&m_pixmap);
p.setBrush(QBrush(col));
p.setPen(QPen(col));
p.fillRect(rect, col);
p.end();
}
qreal BitmapImage::getIncrement(QPointF p1, QPointF p2){
qreal ret = calculateMidpoint(p1, p2, 1.0);
qDebug() << "Increment: " << QString::number(ret, 10, 10);
return ret;
}
qreal BitmapImage::calculateMidpoint(QPointF p1, QPointF p2, qreal inc){
QPointF point = p2 + p1;
if(point.manhattanLength() <= 1.0){
m_inc = inc;
return inc;
}
QPointF hP1(p1.x() / 2.0, p1.y() / 2.0);
QPointF hP2(p2.x() / 2.0, p2.y() / 2.0);
calculateMidpoint(hP1, hP2, inc / 2.0);
qDebug() << "Calculating.... Increment: " << inc << endl;
}
QString BitmapImage::getInc(QPointF p1, QPointF p2){
return calcMid(p1, p2, 1.0);
}
QString BitmapImage::calcMid(QPointF p1, QPointF p2, qreal inc){
QPointF point = p2 + p1;
if(point.manhattanLength() <= 1.0){
return QString::number(inc, 10, 10);
}
QPointF hP1(p1.x()/2.0, p1.y()/2.0);
QPointF hP2(p2.x()/2.0, p2.y()/2.0);
calcMid(hP1, hP2, inc/2.0);
}
QPixmap BitmapImage::getCompositeImage()
{
QPixmap temp = m_pixmap;
QPainter painter(&temp);
painter.setOpacity(0.5);
painter.drawPixmap(0, 0, temp);
painter.end();
m_pixmap = temp;
return m_pixmap;
}
<commit_msg>0.0.91.4<commit_after>#include "bitmapimage.h"
BitmapImage::BitmapImage()
{
m_Image = NULL;
visible = true;
m_ScaleFactor = 1.0;
qDebug() << "Image drawn!" << endl;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
BitmapImage::BitmapImage(const BitmapImage &image)
{
m_pixmap = image.m_pixmap;
boundaries = image.boundaries;
m_Color = image.m_Color;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
visible = true;
m_inc = 0.01;
}
BitmapImage::BitmapImage(Object *parent, QRect boundaries, QColor color)
{
myParent = parent;
this->boundaries = boundaries;
m_Image = new QImage(boundaries.size(), QImage::Format_ARGB32_Premultiplied);
m_Image->fill(color.rgba());
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
visible = true;
m_inc = 0.01;
}
BitmapImage::BitmapImage(Object *parent, QRect boundaries, QImage image)
{
myParent = parent;
this->boundaries = boundaries;
m_Image = new QImage(image);
if(m_Image->width() != boundaries.width() && m_Image->height() != boundaries.height()) qDebug() << "Error 0001: Failed to load Image" << endl;
visible = true;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
BitmapImage::BitmapImage(QRect boundaries, QColor color)
{
this->boundaries = boundaries;
QPixmap temp(boundaries.width(), boundaries.height());
temp.fill(color);
QPainter painter(&temp);
if(!temp.isNull())
{
painter.drawPixmap(0, 0, temp);
}
painter.end();
m_pixmap = temp;
visible = true;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
BitmapImage::BitmapImage(QRect boundaries, QPixmap pixMap)
{
this->boundaries = boundaries;
m_pixmap = pixMap;
visible = true;
m_ScaleFactor = 1.0;
m_ScaleFactorInv = 1.0;
m_inc = 0.01;
}
void BitmapImage::paintImage(QPainter &painter)
{
painter.drawPixmap(0, 0, m_pixmap);
}
void BitmapImage::paintImage(QPainterPath painterPath, Brush brush)
{
QPainter painter(&m_pixmap);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::NoBrush);
QPen copyPen = brush.getPen();
if(brush.getSize() > 0)
{
copyPen.setBrush(brush.getBrush());
copyPen.setWidth(brush.getSize());
painter.setPen(copyPen);
}else{
copyPen.setBrush(Qt::NoBrush);
copyPen.setWidth(0);
painter.setPen(copyPen);
}
painter.drawPath(painterPath);
}
void BitmapImage::paintImage(QPoint point, Brush brush){
int brushWidth = brush.getSize() + (brush.getPressureVal() * brush.getTransferSize());
brushWidth += m_ScaleFactor;
QImage stencilBase = brush.getStencil().toImage();
stencilBase.invertPixels(QImage::InvertRgb);
stencilBase.createAlphaMask();
stencilBase.convertToFormat(QImage::Format_ARGB32, Qt::AutoColor);
QImage stencilImage = QImage(stencilBase);
QColor color = brush.getColor();
color.setAlpha(brush.getOpacity() + (brush.getPressureVal() * brush.getTransferOpacity()));
stencilImage.fill(color);
QPixmap stencil = QPixmap::fromImage(stencilImage.scaled(brushWidth, brushWidth, Qt::IgnoreAspectRatio, Qt::FastTransformation));
QPainter p(&m_pixmap);
p.setRenderHint(QPainter::Antialiasing);
point /= m_ScaleFactor;
p.drawPixmap(QPoint(point.x() - stencil.width()/2, point.y() - stencil.height()/2), stencil);
}
void BitmapImage::paintImage(QVector<QPointF> pointInfo, Brush brush)
{
int brushWidth = brush.getSize() + (brush.getPressureVal() * brush.getTransferSize());
brushWidth *= m_ScaleFactor;
/*-Prepare Stencil-*/
QImage stencilBase = brush.getStencil().toImage();
stencilBase.invertPixels(QImage::InvertRgb);
stencilBase.createAlphaMask();
stencilBase.convertToFormat(QImage::Format_ARGB32, Qt::AutoColor);
QImage stencilImage = QImage(stencilBase);
QColor color = brush.getColor();
color.setAlpha(brush.getOpacity() + (brush.getPressureVal() * brush.getTransferOpacity()));
stencilImage.fill(color);
stencilImage.setAlphaChannel(stencilBase);
QPixmap stencil = QPixmap::fromImage(stencilImage.scaled(brushWidth, brushWidth, Qt::IgnoreAspectRatio, Qt::FastTransformation));
QPainter painter(&m_pixmap);
painter.setRenderHint(QPainter::Antialiasing);
/*Calculate incrementation value*/
qreal inc = 0.01;
QPainterPath path;
path.moveTo(pointInfo.first());
path.lineTo(pointInfo.last());
inc = getIncrement(pointInfo.first(), pointInfo.last());
if(inc == 0){
inc = m_inc;
}
qDebug() << "Reported Increment: " << m_inc << endl;
/* Automatically adjust the incrementing value */
for(qreal i = 0; i < 1; i+= inc * brush.getSpacing()){
QPointF point = path.pointAtPercent(i) / m_ScaleFactor;
painter.drawPixmap(QPoint(point.x() - stencil.width()/2, point.y() - stencil.width()/2), stencil);
}
/*-Old Method-*/
// QPointF point, drawPoint;
// point = pointInfo.last() - pointInfo.first();
// int length = point.manhattanLength();
// double xInc, yInc;
// xInc = point.x() / (double)length;
// yInc = point.y() / (double)length;
// drawPoint = pointInfo.first();
// for(int i = 0; i < length; i++){
// if(drawPoint != pointInfo.last() || drawPoint != pointInfo.first()){
// drawPoint.setX(drawPoint.x() + (xInc / (double)brush.getSpacing() ));
// drawPoint.setY(drawPoint.y() + (yInc / (double)brush.getSpacing() ));
// painter.drawPixmap(QPoint(drawPoint.x() - stencil.width() / 2, drawPoint.y() - stencil.height()/2) / m_ScaleFactor, stencil);
// }
// }
}
void BitmapImage::paintImage(QVector<QPointF> pointInfo, Brush brush, qreal tabPress, int amt)
{
int brushWidth = brush.getSize() + (amt * tabPress);
/*-Prepare Stencil-*/
QImage stencilBase = brush.getStencil().toImage();
stencilBase.invertPixels(QImage::InvertRgb);
stencilBase.createAlphaMask();
stencilBase.convertToFormat(QImage::Format_RGB888, Qt::AutoColor);
QImage stencilImage = QImage(stencilBase);
QColor color = brush.getColor();
color.setAlpha(brush.getOpacity());
stencilImage.fill(color);
stencilImage.setAlphaChannel(stencilBase);
QPixmap stencil = QPixmap::fromImage(stencilImage.scaled(brushWidth, brushWidth, Qt::IgnoreAspectRatio, Qt::FastTransformation));
QPainter painter(&m_pixmap);
painter.setRenderHint(QPainter::Antialiasing);
QPointF point, drawPoint;
point = pointInfo.last() - pointInfo.first();
int length = point.manhattanLength();
double xInc, yInc;
xInc = point.x() / length;
yInc = point.y() / length;
drawPoint = pointInfo.first();
for(int i = 0; i < length; i++){
drawPoint.setX(drawPoint.x() + (xInc * brush.getSpacing() ));
drawPoint.setY(drawPoint.y() + (yInc * brush.getSpacing() ));
painter.drawPixmap(QPoint(drawPoint.x() - stencil.width() / 2, drawPoint.y() - stencil.height()/2), stencil);
}
}
void BitmapImage::fillImage(QPoint point, Brush brush){
QImage img = m_pixmap.toImage();
QRgb oldColor = img.pixel(point);
QRgb newColor = brush.getColor().rgb();
fillRecurs(point, img, oldColor, newColor);
m_pixmap = QPixmap::fromImage(img);
}
void BitmapImage::scale(double s){
m_ScaleFactor = s;
}
void BitmapImage::commitChanges(QPoint drawPoint, QPixmap pixmap){
QPainter p(&m_pixmap);
p.drawPixmap(drawPoint, pixmap);
}
/*
*
* Implementation of this function is as close to the version in EasyPaint.
*
*/
void BitmapImage::fillRecurs(QPoint pos, QImage& img, QRgb oldColor, QRgb newColor){
int temp_x(pos.x());
int left_x = 0;
while(true){
if(img.pixel(temp_x, pos.y()) != oldColor){
break;
}
img.setPixel(temp_x, pos.y(), newColor);
if(temp_x > 0){
temp_x--;
left_x = temp_x;
}else{
break;
}
}
int right_x(0);
temp_x = pos.x() + 1;
while(true){
if(img.pixel(temp_x, pos.y()) != oldColor){
break;
}
img.setPixel(temp_x, pos.y(), newColor);
if(temp_x < img.width() -1){
temp_x++;
right_x = temp_x;
}else{
break;
}
}
for(int x = left_x+1; x < right_x; x++){
if(pos.y() < 1 || pos.y() >= img.height() - 1){
break;
}
if(right_x > img.width()){ break; }
QRgb currentColor = img.pixel(x, pos.y()-1);
if(currentColor == oldColor && currentColor != newColor){
fillRecurs(QPoint(x, pos.y() -1), img, oldColor, newColor);
}
currentColor = img.pixel(x, pos.y() + 1);
if(currentColor == oldColor && currentColor != newColor){
fillRecurs(QPoint(x, pos.y() + 1), img, oldColor, newColor);
}
}
}
void BitmapImage::cutImgOp(QRect rect, BitmapImage &img){
QPainter p(&m_pixmap);
}
void BitmapImage::cutImgOp(QRect rect, QColor col){
QPainter p(&m_pixmap);
p.setBrush(QBrush(col));
p.setPen(QPen(col));
p.fillRect(rect, col);
p.end();
}
qreal BitmapImage::getIncrement(QPointF p1, QPointF p2){
qreal ret = calculateMidpoint(p1, p2, 1.0);
return ret;
}
qreal BitmapImage::calculateMidpoint(QPointF p1, QPointF p2, qreal inc){
QPointF point = p2 + p1;
if(point.manhattanLength() <= 1.0){
m_inc = inc;
return inc;
}
QPointF hP1(p1.x() / 2.0, p1.y() / 2.0);
QPointF hP2(p2.x() / 2.0, p2.y() / 2.0);
calculateMidpoint(hP1, hP2, inc / 2.0);
}
QString BitmapImage::getInc(QPointF p1, QPointF p2){
return calcMid(p1, p2, 1.0);
}
QString BitmapImage::calcMid(QPointF p1, QPointF p2, qreal inc){
QPointF point = p2 + p1;
if(point.manhattanLength() <= 1.0){
return QString::number(inc, 10, 10);
}
QPointF hP1(p1.x()/2.0, p1.y()/2.0);
QPointF hP2(p2.x()/2.0, p2.y()/2.0);
calcMid(hP1, hP2, inc/2.0);
}
QPixmap BitmapImage::getCompositeImage()
{
QPixmap temp = m_pixmap;
QPainter painter(&temp);
painter.setOpacity(0.5);
painter.drawPixmap(0, 0, temp);
painter.end();
m_pixmap = temp;
return m_pixmap;
}
<|endoftext|> |
<commit_before>/*=====================================================================
PIXHAWK Micro Air Vehicle Flying Robotics Toolkit
(c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch>
This file is part of the PIXHAWK project
PIXHAWK 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.
PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class Core
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QFile>
#include <QFlags>
#include <QThread>
#include <QSplashScreen>
#include <QPixmap>
#include <QDesktopWidget>
#include <QPainter>
#include <QStyleFactory>
#include <QAction>
#include "configuration.h"
#include "Core.h"
#include "MG.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
/**
* @brief Constructor for the main application.
*
* This constructor initializes and starts the whole application. It takes standard
* command-line parameters
*
* @param argc The number of command-line parameters
* @param argv The string array of parameters
**/
Core::Core(int &argc, char* argv[]) : QApplication(argc, argv)
{
this->setApplicationName(QGC_APPLICATION_NAME);
this->setApplicationVersion(QGC_APPLICATION_VERSION);
this->setOrganizationName(QLatin1String("PIXHAWK Association Zurich"));
this->setOrganizationDomain("http://qgroundcontrol.org");
// Show splash screen
QPixmap splashImage(":images/splash.png");
QSplashScreen* splashScreen = new QSplashScreen(splashImage, Qt::WindowStaysOnTopHint);
splashScreen->show();
splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
QSettings::setDefaultFormat(QSettings::IniFormat);
// Exit main application when last window is closed
connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
// Set application font
QFontDatabase fontDatabase = QFontDatabase();
const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
const QString fontFamilyName = "Bitstream Vera Sans";
if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str());
fontDatabase.addApplicationFont(fontFileName);
setFont(fontDatabase.font(fontFamilyName, "Roman", 12));
// Start the comm link manager
splashScreen->showMessage(tr("Starting Communication Links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startLinkManager();
// Start the UAS Manager
splashScreen->showMessage(tr("Starting UAS Manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startUASManager();
//tarsus = new ViconTarsusProtocol();
//tarsus->start();
// Start the user interface
splashScreen->showMessage(tr("Starting User Interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// Start UI
mainWindow = new MainWindow();
// Remove splash screen
splashScreen->finish(mainWindow);
// Connect links
// to make sure that all components are initialized when the
// first messages arrive
UDPLink* udpLink = new UDPLink(QHostAddress::Any, 14550);
mainWindow->addLink(udpLink);
// Check if link could be connected
if (!udpLink->connect())
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Could not connect UDP port. Is already an instance of " + qAppName() + " running?");
msgBox.setInformativeText("You will not be able to receive data via UDP. Please check that you're running the right executable and then re-start " + qAppName() + ". Do you want to close the application?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
int ret = msgBox.exec();
// Close the message box shortly after the click to prevent accidental clicks
QTimer::singleShot(5000, &msgBox, SLOT(reject()));
// Exit application
if (ret == QMessageBox::Yes)
{
//mainWindow->close();
QTimer::singleShot(200, mainWindow, SLOT(close()));
}
}
// MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(MG::DIR::getSupportFilesDirectory() + "/demo-log.txt");
MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(":/demo-log.txt");
mainWindow->addLink(simulationLink);
}
/**
* @brief Destructor for the groundstation. It destroys all loaded instances.
*
**/
Core::~Core()
{
// Delete singletons
delete LinkManager::instance();
delete UASManager::instance();
}
/**
* @brief Start the link managing component.
*
* The link manager keeps track of all communication links and provides the global
* packet queue. It is the main communication hub
**/
void Core::startLinkManager()
{
LinkManager::instance();
}
/**
* @brief Start the Unmanned Air System Manager
*
**/
void Core::startUASManager()
{
// Load UAS plugins
QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_LINUX)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS")
{
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
UASManager::instance();
// Load plugins
QStringList pluginFileNames;
foreach (QString fileName, pluginsDir.entryList(QDir::Files))
{
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin)
{
//populateMenus(plugin);
pluginFileNames += fileName;
//printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str());
}
}
}
<commit_msg>changed error message when the udp link cannot be connected<commit_after>/*=====================================================================
PIXHAWK Micro Air Vehicle Flying Robotics Toolkit
(c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch>
This file is part of the PIXHAWK project
PIXHAWK 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.
PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class Core
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QFile>
#include <QFlags>
#include <QThread>
#include <QSplashScreen>
#include <QPixmap>
#include <QDesktopWidget>
#include <QPainter>
#include <QStyleFactory>
#include <QAction>
#include "configuration.h"
#include "Core.h"
#include "MG.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
/**
* @brief Constructor for the main application.
*
* This constructor initializes and starts the whole application. It takes standard
* command-line parameters
*
* @param argc The number of command-line parameters
* @param argv The string array of parameters
**/
Core::Core(int &argc, char* argv[]) : QApplication(argc, argv)
{
this->setApplicationName(QGC_APPLICATION_NAME);
this->setApplicationVersion(QGC_APPLICATION_VERSION);
this->setOrganizationName(QLatin1String("PIXHAWK Association Zurich"));
this->setOrganizationDomain("http://qgroundcontrol.org");
// Show splash screen
QPixmap splashImage(":images/splash.png");
QSplashScreen* splashScreen = new QSplashScreen(splashImage, Qt::WindowStaysOnTopHint);
splashScreen->show();
splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
QSettings::setDefaultFormat(QSettings::IniFormat);
// Exit main application when last window is closed
connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
// Set application font
QFontDatabase fontDatabase = QFontDatabase();
const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
const QString fontFamilyName = "Bitstream Vera Sans";
if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str());
fontDatabase.addApplicationFont(fontFileName);
setFont(fontDatabase.font(fontFamilyName, "Roman", 12));
// Start the comm link manager
splashScreen->showMessage(tr("Starting Communication Links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startLinkManager();
// Start the UAS Manager
splashScreen->showMessage(tr("Starting UAS Manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startUASManager();
//tarsus = new ViconTarsusProtocol();
//tarsus->start();
// Start the user interface
splashScreen->showMessage(tr("Starting User Interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// Start UI
mainWindow = new MainWindow();
// Remove splash screen
splashScreen->finish(mainWindow);
// Connect links
// to make sure that all components are initialized when the
// first messages arrive
UDPLink* udpLink = new UDPLink(QHostAddress::Any, 14550);
mainWindow->addLink(udpLink);
// Check if link could be connected
if (!udpLink->connect())
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Could not connect UDP port. Is an instance of " + qAppName() + "already running?");
msgBox.setInformativeText("You will not be able to receive data via UDP. Please check that you're running the right executable and then re-start " + qAppName() + ". Do you want to close the application?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
int ret = msgBox.exec();
// Close the message box shortly after the click to prevent accidental clicks
QTimer::singleShot(5000, &msgBox, SLOT(reject()));
// Exit application
if (ret == QMessageBox::Yes)
{
//mainWindow->close();
QTimer::singleShot(200, mainWindow, SLOT(close()));
}
}
// MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(MG::DIR::getSupportFilesDirectory() + "/demo-log.txt");
MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(":/demo-log.txt");
mainWindow->addLink(simulationLink);
}
/**
* @brief Destructor for the groundstation. It destroys all loaded instances.
*
**/
Core::~Core()
{
// Delete singletons
delete LinkManager::instance();
delete UASManager::instance();
}
/**
* @brief Start the link managing component.
*
* The link manager keeps track of all communication links and provides the global
* packet queue. It is the main communication hub
**/
void Core::startLinkManager()
{
LinkManager::instance();
}
/**
* @brief Start the Unmanned Air System Manager
*
**/
void Core::startUASManager()
{
// Load UAS plugins
QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_LINUX)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS")
{
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
UASManager::instance();
// Load plugins
QStringList pluginFileNames;
foreach (QString fileName, pluginsDir.entryList(QDir::Files))
{
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin)
{
//populateMenus(plugin);
pluginFileNames += fileName;
//printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str());
}
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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 Image Engine Design 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 "IECoreGL/Renderer.h"
#include "IECoreGL/Scene.h"
#include "IECoreGL/BoxPrimitive.h"
#include "IECoreGL/TypedStateComponent.h"
#include "IECoreGL/NameStateComponent.h"
#include "IECoreGL/State.h"
#include "IECoreGL/Camera.h"
#include "IECoreGL/Renderable.h"
#include "IECoreGL/Group.h"
#include "IECoreGL/Primitive.h"
#include "IECoreMaya/ProceduralHolder.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/MayaTypeIds.h"
#include "IECore/VectorOps.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/ClassData.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnSingleIndexedComponent.h"
#include "maya/MSelectionList.h"
#include "maya/MAttributeSpec.h"
#include "maya/MAttributeIndex.h"
#include "maya/MAttributeSpecArray.h"
#include "maya/MDagPath.h"
#include "maya/MFnStringData.h"
using namespace Imath;
using namespace IECore;
using namespace IECoreMaya;
using namespace boost;
MTypeId ProceduralHolder::id = ProceduralHolderId;
MObject ProceduralHolder::aGLPreview;
MObject ProceduralHolder::aTransparent;
MObject ProceduralHolder::aDrawBound;
MObject ProceduralHolder::aProceduralComponents;
struct ProceduralHolder::MemberData
{
ComponentsMap m_componentsMap;
ComponentToGroupMap m_componentToGroupMap;
};
static IECore::ClassData< ProceduralHolder, ProceduralHolder::MemberData > g_classData;
ProceduralHolder::ComponentsMap &ProceduralHolder::componentsMap()
{
return g_classData[this].m_componentsMap;
}
ProceduralHolder::ComponentToGroupMap &ProceduralHolder::componentToGroupMap()
{
return g_classData[this].m_componentToGroupMap;
}
ProceduralHolder::ProceduralHolder()
: m_boundDirty( true ), m_sceneDirty( true )
{
g_classData.create( this );
}
ProceduralHolder::~ProceduralHolder()
{
}
void ProceduralHolder::postConstructor()
{
ParameterisedHolderComponentShape::postConstructor();
setRenderable( true );
}
void *ProceduralHolder::creator()
{
return new ProceduralHolder;
}
MStatus ProceduralHolder::initialize()
{
MStatus s = inheritAttributesFrom( ParameterisedHolderComponentShape::typeName );
assert( s );
MFnNumericAttribute nAttr;
MFnTypedAttribute tAttr;
aGLPreview = nAttr.create( "glPreview", "glpr", MFnNumericData::kBoolean, 1, &s );
assert( s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
s = addAttribute( aGLPreview );
assert( s );
aTransparent = nAttr.create( "transparent", "trans", MFnNumericData::kBoolean, 0, &s );
assert( s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
s = addAttribute( aTransparent );
assert( s );
aDrawBound = nAttr.create( "drawBound", "dbnd", MFnNumericData::kBoolean, 1, &s );
assert( s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
s = addAttribute( aDrawBound );
assert( s );
IECoreGL::ConstStatePtr defaultState = IECoreGL::State::defaultState();
assert( defaultState );
assert( defaultState->isComplete() );
MFnStringData fnData;
MObject defaultValue = fnData.create( defaultState->get<const IECoreGL::NameStateComponent>()->name().c_str(), &s );
assert( s );
aProceduralComponents = tAttr.create( "proceduralComponents", "prcm", MFnData::kString, defaultValue, &s );
assert( s );
tAttr.setReadable( true );
tAttr.setWritable( false );
tAttr.setStorable( false );
tAttr.setConnectable( true );
tAttr.setHidden( true );
tAttr.setArray( true );
tAttr.setUsesArrayDataBuilder( true );
s = addAttribute( aProceduralComponents );
assert( s );
return MS::kSuccess;
}
bool ProceduralHolder::isBounded() const
{
return true;
}
MBoundingBox ProceduralHolder::boundingBox() const
{
if( !m_boundDirty )
{
return m_bound;
}
m_bound = MBoundingBox( MPoint( -1, -1, -1 ), MPoint( 1, 1, 1 ) );
Renderer::ProceduralPtr p = const_cast<ProceduralHolder*>(this)->getProcedural();
if( p )
{
const_cast<ProceduralHolder*>(this)->setParameterisedValues();
try
{
Box3f b = p->bound();
if( !b.isEmpty() )
{
m_bound = convert<MBoundingBox>( b );
}
}
catch( boost::python::error_already_set )
{
PyErr_Print();
}
catch( std::exception &e )
{
msg( Msg::Error, "ProceduralHolder::boundingBox", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ProceduralHolder::boundingBox", "Exception thrown in Procedural::bound" );
}
}
m_boundDirty = false;
return m_bound;
}
MStatus ProceduralHolder::setDependentsDirty( const MPlug &plug, MPlugArray &plugArray )
{
if( plugParameter( plug ) || (!plug.parent().isNull() && plugParameter( plug.parent() ) ) )
{
// it's an input to the procedural
m_boundDirty = m_sceneDirty = true;
childChanged( kBoundingBoxChanged ); // this is necessary to cause maya to redraw
}
return ParameterisedHolderComponentShape::setDependentsDirty( plug, plugArray );
}
MStatus ProceduralHolder::setProcedural( const std::string &className, int classVersion )
{
return setParameterised( className, classVersion, "IECORE_PROCEDURAL_PATHS" );
}
IECore::Renderer::ProceduralPtr ProceduralHolder::getProcedural( std::string *className, int *classVersion )
{
return runTimeCast<Renderer::Procedural>( getParameterised( className, classVersion ) );
}
IECoreGL::ConstScenePtr ProceduralHolder::scene()
{
if( !m_sceneDirty )
{
return m_scene;
}
m_scene = 0;
Renderer::ProceduralPtr p = ((ProceduralHolder*)this)->getProcedural();
if( p )
{
setParameterisedValues();
try
{
IECoreGL::RendererPtr renderer = new IECoreGL::Renderer;
renderer->setOption( "gl:mode", new StringData( "deferred" ) );
renderer->worldBegin();
p->render( renderer );
renderer->worldEnd();
m_scene = renderer->scene();
m_scene->setCamera( 0 );
buildComponents();
}
catch( boost::python::error_already_set )
{
PyErr_Print();
}
catch( IECore::Exception &e )
{
msg( Msg::Error, "ProceduralHolder::scene", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ProceduralHolder::scene", "Exception thrown in Procedural::render" );
}
}
m_sceneDirty = false;
return m_scene;
}
void ProceduralHolder::componentToPlugs( MObject &component, MSelectionList &selectionList ) const
{
MStatus s;
if ( component.hasFn( MFn::kSingleIndexedComponent ) )
{
MFnSingleIndexedComponent fnComp( component, &s );
assert( s );
MObject thisNode = thisMObject();
MPlug plug( thisNode, aProceduralComponents );
assert( !plug.isNull() );
int len = fnComp.elementCount( &s );
assert( s );
for ( int i = 0; i < len; i++ )
{
MPlug compPlug = plug.elementByLogicalIndex( fnComp.element(i), &s );
assert( s );
assert( !compPlug.isNull() );
selectionList.add( compPlug );
}
}
}
MPxSurfaceShape::MatchResult ProceduralHolder::matchComponent( const MSelectionList &item, const MAttributeSpecArray &spec, MSelectionList &list )
{
if( spec.length() == 1 )
{
MAttributeSpec attrSpec = spec[0];
MStatus s;
int dim = attrSpec.dimensions();
if ( (dim > 0) && (attrSpec.name() == "proceduralComponents" || attrSpec.name() == "prcm" || attrSpec.name() == "f" ) )
{
int numComponents = componentToGroupMap().size();
MAttributeIndex attrIndex = attrSpec[0];
if ( attrIndex.type() != MAttributeIndex::kInteger )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
int upper = numComponents - 1;
int lower = 0;
if ( attrIndex.hasLowerBound() )
{
attrIndex.getLower( lower );
}
if ( attrIndex.hasUpperBound() )
{
attrIndex.getUpper( upper );
}
// Check the attribute index range is valid
if ( (attrIndex.hasRange() && !attrIndex.hasValidRange() ) || (upper >= numComponents) || (lower < 0 ) )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
MDagPath path;
item.getDagPath( 0, path );
MFnSingleIndexedComponent fnComp;
MObject comp = fnComp.create( MFn::kMeshPolygonComponent, &s );
assert( s );
for ( int i=lower; i<=upper; i++ )
{
fnComp.addElement( i );
}
list.add( path, comp );
return MPxSurfaceShape::kMatchOk;
}
}
return MPxSurfaceShape::matchComponent( item, spec, list );
}
void ProceduralHolder::buildComponents( IECoreGL::ConstNameStateComponentPtr nameState, IECoreGL::GroupPtr group, MArrayDataBuilder &builder )
{
assert( nameState );
assert( group );
assert( group->getState() );
MStatus s;
IECoreGL::ConstNameStateComponentPtr ns = nameState;
if ( group->getState()->get< IECoreGL::NameStateComponent >() )
{
ns = group->getState()->get< IECoreGL::NameStateComponent >();
}
const std::string &name = ns->name();
int compId = ns->glName();
ComponentsMap::const_iterator it = componentsMap().find( name );
if( it == componentsMap().end() )
{
compId = componentsMap().size();
componentsMap()[name] = compId;
MFnStringData fnData;
MObject data = fnData.create( MString( name.c_str() ) );
MDataHandle h = builder.addElement( compId, &s );
assert( s );
s = h.set( data );
assert( s );
}
componentToGroupMap()[compId].insert( ComponentToGroupMap::mapped_type::value_type( name, group ) );
const IECoreGL::Group::ChildContainer &children = group->children();
for ( IECoreGL::Group::ChildContainer::const_iterator it = children.begin(); it != children.end(); ++it )
{
assert( *it );
IECoreGL::GroupPtr childGroup = runTimeCast< IECoreGL::Group >( *it );
if ( childGroup )
{
buildComponents( ns, childGroup, builder );
}
}
}
void ProceduralHolder::buildComponents()
{
MStatus s;
MDataBlock block = forceCache();
MArrayDataHandle cH = block.outputArrayValue( aProceduralComponents, &s );
assert( s );
MArrayDataBuilder builder = cH.builder( &s );
assert( s );
componentsMap().clear();
componentToGroupMap().clear();
IECoreGL::ConstStatePtr defaultState = IECoreGL::State::defaultState();
assert( defaultState );
assert( defaultState->isComplete() );
assert( m_scene );
assert( m_scene->root() );
buildComponents( defaultState->get<const IECoreGL::NameStateComponent>(), m_scene->root(), builder );
s = cH.set( builder );
assert( s );
#ifndef NDEBUG
MPlug plug( thisMObject(), aProceduralComponents );
for ( ComponentsMap::const_iterator it = componentsMap().begin(); it != componentsMap().end(); ++it )
{
MPlug child = plug.elementByLogicalIndex( it->second, &s );
assert( s );
MObject obj;
s = child.getValue( obj );
assert( s );
MFnStringData fnData( obj, &s );
assert( s );
assert( fnData.string() == MString( it->first.value().c_str() ) );
}
#endif
}
<commit_msg>Now determining whether a plug represents a parameter using naming alone. Plugs which are elements of an array plug now correctly dirty the scene and cause a rerender.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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 Image Engine Design 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 "IECoreGL/Renderer.h"
#include "IECoreGL/Scene.h"
#include "IECoreGL/BoxPrimitive.h"
#include "IECoreGL/TypedStateComponent.h"
#include "IECoreGL/NameStateComponent.h"
#include "IECoreGL/State.h"
#include "IECoreGL/Camera.h"
#include "IECoreGL/Renderable.h"
#include "IECoreGL/Group.h"
#include "IECoreGL/Primitive.h"
#include "IECoreMaya/ProceduralHolder.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/MayaTypeIds.h"
#include "IECore/VectorOps.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/ClassData.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnSingleIndexedComponent.h"
#include "maya/MSelectionList.h"
#include "maya/MAttributeSpec.h"
#include "maya/MAttributeIndex.h"
#include "maya/MAttributeSpecArray.h"
#include "maya/MDagPath.h"
#include "maya/MFnStringData.h"
using namespace Imath;
using namespace IECore;
using namespace IECoreMaya;
using namespace boost;
MTypeId ProceduralHolder::id = ProceduralHolderId;
MObject ProceduralHolder::aGLPreview;
MObject ProceduralHolder::aTransparent;
MObject ProceduralHolder::aDrawBound;
MObject ProceduralHolder::aProceduralComponents;
struct ProceduralHolder::MemberData
{
ComponentsMap m_componentsMap;
ComponentToGroupMap m_componentToGroupMap;
};
static IECore::ClassData< ProceduralHolder, ProceduralHolder::MemberData > g_classData;
ProceduralHolder::ComponentsMap &ProceduralHolder::componentsMap()
{
return g_classData[this].m_componentsMap;
}
ProceduralHolder::ComponentToGroupMap &ProceduralHolder::componentToGroupMap()
{
return g_classData[this].m_componentToGroupMap;
}
ProceduralHolder::ProceduralHolder()
: m_boundDirty( true ), m_sceneDirty( true )
{
g_classData.create( this );
}
ProceduralHolder::~ProceduralHolder()
{
}
void ProceduralHolder::postConstructor()
{
ParameterisedHolderComponentShape::postConstructor();
setRenderable( true );
}
void *ProceduralHolder::creator()
{
return new ProceduralHolder;
}
MStatus ProceduralHolder::initialize()
{
MStatus s = inheritAttributesFrom( ParameterisedHolderComponentShape::typeName );
assert( s );
MFnNumericAttribute nAttr;
MFnTypedAttribute tAttr;
aGLPreview = nAttr.create( "glPreview", "glpr", MFnNumericData::kBoolean, 1, &s );
assert( s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
s = addAttribute( aGLPreview );
assert( s );
aTransparent = nAttr.create( "transparent", "trans", MFnNumericData::kBoolean, 0, &s );
assert( s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
s = addAttribute( aTransparent );
assert( s );
aDrawBound = nAttr.create( "drawBound", "dbnd", MFnNumericData::kBoolean, 1, &s );
assert( s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
s = addAttribute( aDrawBound );
assert( s );
IECoreGL::ConstStatePtr defaultState = IECoreGL::State::defaultState();
assert( defaultState );
assert( defaultState->isComplete() );
MFnStringData fnData;
MObject defaultValue = fnData.create( defaultState->get<const IECoreGL::NameStateComponent>()->name().c_str(), &s );
assert( s );
aProceduralComponents = tAttr.create( "proceduralComponents", "prcm", MFnData::kString, defaultValue, &s );
assert( s );
tAttr.setReadable( true );
tAttr.setWritable( false );
tAttr.setStorable( false );
tAttr.setConnectable( true );
tAttr.setHidden( true );
tAttr.setArray( true );
tAttr.setUsesArrayDataBuilder( true );
s = addAttribute( aProceduralComponents );
assert( s );
return MS::kSuccess;
}
bool ProceduralHolder::isBounded() const
{
return true;
}
MBoundingBox ProceduralHolder::boundingBox() const
{
if( !m_boundDirty )
{
return m_bound;
}
m_bound = MBoundingBox( MPoint( -1, -1, -1 ), MPoint( 1, 1, 1 ) );
Renderer::ProceduralPtr p = const_cast<ProceduralHolder*>(this)->getProcedural();
if( p )
{
const_cast<ProceduralHolder*>(this)->setParameterisedValues();
try
{
Box3f b = p->bound();
if( !b.isEmpty() )
{
m_bound = convert<MBoundingBox>( b );
}
}
catch( boost::python::error_already_set )
{
PyErr_Print();
}
catch( std::exception &e )
{
msg( Msg::Error, "ProceduralHolder::boundingBox", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ProceduralHolder::boundingBox", "Exception thrown in Procedural::bound" );
}
}
m_boundDirty = false;
return m_bound;
}
MStatus ProceduralHolder::setDependentsDirty( const MPlug &plug, MPlugArray &plugArray )
{
/// \todo We should put "parm_" somewhere as a static const char * so everything can
/// reference it rather than repeating it.
if( std::string( plug.partialName().substring( 0, 4 ).asChar() ) == "parm_" )
{
// it's an input to the procedural
m_boundDirty = m_sceneDirty = true;
childChanged( kBoundingBoxChanged ); // this is necessary to cause maya to redraw
}
return ParameterisedHolderComponentShape::setDependentsDirty( plug, plugArray );
}
MStatus ProceduralHolder::setProcedural( const std::string &className, int classVersion )
{
return setParameterised( className, classVersion, "IECORE_PROCEDURAL_PATHS" );
}
IECore::Renderer::ProceduralPtr ProceduralHolder::getProcedural( std::string *className, int *classVersion )
{
return runTimeCast<Renderer::Procedural>( getParameterised( className, classVersion ) );
}
IECoreGL::ConstScenePtr ProceduralHolder::scene()
{
if( !m_sceneDirty )
{
return m_scene;
}
m_scene = 0;
Renderer::ProceduralPtr p = ((ProceduralHolder*)this)->getProcedural();
if( p )
{
setParameterisedValues();
try
{
IECoreGL::RendererPtr renderer = new IECoreGL::Renderer;
renderer->setOption( "gl:mode", new StringData( "deferred" ) );
renderer->worldBegin();
p->render( renderer );
renderer->worldEnd();
m_scene = renderer->scene();
m_scene->setCamera( 0 );
buildComponents();
}
catch( boost::python::error_already_set )
{
PyErr_Print();
}
catch( IECore::Exception &e )
{
msg( Msg::Error, "ProceduralHolder::scene", e.what() );
}
catch( ... )
{
msg( Msg::Error, "ProceduralHolder::scene", "Exception thrown in Procedural::render" );
}
}
m_sceneDirty = false;
return m_scene;
}
void ProceduralHolder::componentToPlugs( MObject &component, MSelectionList &selectionList ) const
{
MStatus s;
if ( component.hasFn( MFn::kSingleIndexedComponent ) )
{
MFnSingleIndexedComponent fnComp( component, &s );
assert( s );
MObject thisNode = thisMObject();
MPlug plug( thisNode, aProceduralComponents );
assert( !plug.isNull() );
int len = fnComp.elementCount( &s );
assert( s );
for ( int i = 0; i < len; i++ )
{
MPlug compPlug = plug.elementByLogicalIndex( fnComp.element(i), &s );
assert( s );
assert( !compPlug.isNull() );
selectionList.add( compPlug );
}
}
}
MPxSurfaceShape::MatchResult ProceduralHolder::matchComponent( const MSelectionList &item, const MAttributeSpecArray &spec, MSelectionList &list )
{
if( spec.length() == 1 )
{
MAttributeSpec attrSpec = spec[0];
MStatus s;
int dim = attrSpec.dimensions();
if ( (dim > 0) && (attrSpec.name() == "proceduralComponents" || attrSpec.name() == "prcm" || attrSpec.name() == "f" ) )
{
int numComponents = componentToGroupMap().size();
MAttributeIndex attrIndex = attrSpec[0];
if ( attrIndex.type() != MAttributeIndex::kInteger )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
int upper = numComponents - 1;
int lower = 0;
if ( attrIndex.hasLowerBound() )
{
attrIndex.getLower( lower );
}
if ( attrIndex.hasUpperBound() )
{
attrIndex.getUpper( upper );
}
// Check the attribute index range is valid
if ( (attrIndex.hasRange() && !attrIndex.hasValidRange() ) || (upper >= numComponents) || (lower < 0 ) )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
MDagPath path;
item.getDagPath( 0, path );
MFnSingleIndexedComponent fnComp;
MObject comp = fnComp.create( MFn::kMeshPolygonComponent, &s );
assert( s );
for ( int i=lower; i<=upper; i++ )
{
fnComp.addElement( i );
}
list.add( path, comp );
return MPxSurfaceShape::kMatchOk;
}
}
return MPxSurfaceShape::matchComponent( item, spec, list );
}
void ProceduralHolder::buildComponents( IECoreGL::ConstNameStateComponentPtr nameState, IECoreGL::GroupPtr group, MArrayDataBuilder &builder )
{
assert( nameState );
assert( group );
assert( group->getState() );
MStatus s;
IECoreGL::ConstNameStateComponentPtr ns = nameState;
if ( group->getState()->get< IECoreGL::NameStateComponent >() )
{
ns = group->getState()->get< IECoreGL::NameStateComponent >();
}
const std::string &name = ns->name();
int compId = ns->glName();
ComponentsMap::const_iterator it = componentsMap().find( name );
if( it == componentsMap().end() )
{
compId = componentsMap().size();
componentsMap()[name] = compId;
MFnStringData fnData;
MObject data = fnData.create( MString( name.c_str() ) );
MDataHandle h = builder.addElement( compId, &s );
assert( s );
s = h.set( data );
assert( s );
}
componentToGroupMap()[compId].insert( ComponentToGroupMap::mapped_type::value_type( name, group ) );
const IECoreGL::Group::ChildContainer &children = group->children();
for ( IECoreGL::Group::ChildContainer::const_iterator it = children.begin(); it != children.end(); ++it )
{
assert( *it );
IECoreGL::GroupPtr childGroup = runTimeCast< IECoreGL::Group >( *it );
if ( childGroup )
{
buildComponents( ns, childGroup, builder );
}
}
}
void ProceduralHolder::buildComponents()
{
MStatus s;
MDataBlock block = forceCache();
MArrayDataHandle cH = block.outputArrayValue( aProceduralComponents, &s );
assert( s );
MArrayDataBuilder builder = cH.builder( &s );
assert( s );
componentsMap().clear();
componentToGroupMap().clear();
IECoreGL::ConstStatePtr defaultState = IECoreGL::State::defaultState();
assert( defaultState );
assert( defaultState->isComplete() );
assert( m_scene );
assert( m_scene->root() );
buildComponents( defaultState->get<const IECoreGL::NameStateComponent>(), m_scene->root(), builder );
s = cH.set( builder );
assert( s );
#ifndef NDEBUG
MPlug plug( thisMObject(), aProceduralComponents );
for ( ComponentsMap::const_iterator it = componentsMap().begin(); it != componentsMap().end(); ++it )
{
MPlug child = plug.elementByLogicalIndex( it->second, &s );
assert( s );
MObject obj;
s = child.getValue( obj );
assert( s );
MFnStringData fnData( obj, &s );
assert( s );
assert( fnData.string() == MString( it->first.value().c_str() ) );
}
#endif
}
<|endoftext|> |
<commit_before>#include <SensorDatabase/SensorDatabase.h>
#include <TempReader/TempReader.h>
#include <pthread.h>
#include <iostream>
#include "Timer.h"
#include "logger.h"
#include <glib.h>
#include <CommunicationService/SensorLoggerCommunicationServer.h>
#ifdef DEBUG
#define CONFPATH "../templog.conf"
#else
#define CONFPATH "/etc/templog.conf"
#endif
void dbg_db_fake(SensorDatabase &db) {
db.reset();
std::string image_data = "abcdef";
db.addSetting("basement", image_data.data(), image_data.size());
db.addSensor("pipe", "67C6697351FF", "28", "DS18B20", "°C", "basement");
db.addSensor("oven", "4AEC29CDBAAB", "10", "DS18B20", "°C", "basement");
db.addSensor("watertank", "F2FBE3467CC2", "10", "DS18B20", "°C", "basement");
}
void dbg_reader_fake(TempReader &reader) {
reader.addFake("10");
reader.addFake("10");
reader.addFake("28");
}
int main() {
std::cout<<"reading config from: "<<CONFPATH<<std::endl;
// read configuration
GKeyFile *conf_file = g_key_file_new ();
GKeyFileFlags conffile_flags;
GError *conffile_error = NULL;
if(!g_key_file_load_from_file(conf_file, CONFPATH, conffile_flags, &conffile_error)) {
g_error(conffile_error->message);
}
const char *db_path = g_key_file_get_string(conf_file, "database", "db_file", &conffile_error);
const time_t period = g_key_file_get_integer(conf_file, "logging", "period", &conffile_error);
const unsigned int port = g_key_file_get_integer(conf_file, "communication", "port", &conffile_error);
const char *device = g_key_file_get_string(conf_file, "logging", "device", &conffile_error);
std::cout<<"db path: "<<std::string(db_path)<<std::endl;
std::cout<<"period: "<<period<<std::endl;
if(db_path == NULL)
g_error(conffile_error->message);
SensorDatabase db;
TempReader reader;
db.open(db_path);
std::cout<<"addr db: "<<&db<<std::endl;
std::cout<<"addr reader: "<<&reader<<std::endl;
if(std::string(device)=="fake") {
// init with example data
std::cout<<"feeding fake data"<<std::endl;
dbg_db_fake(db);
dbg_reader_fake(reader);
}
else {
reader.setDevice(device);
}
reader.open();
LoggerConfig conf = {.period=period, .db=&db, .reader=&reader};
pthread_t th_logger;
std::cout<<"addr per: "<<&period<<std::endl;
std::cout<<"addr conf: "<<&conf<<std::endl;
//pthread_create(&th_logger, NULL, logger, (void*)period);
pthread_create(&th_logger, NULL, logger, &conf);
//pthread_create(&th_logger, NULL, logger, NULL);
SensorLoggerCommunicationServer s(port, db, reader);
s.start();
pthread_join(th_logger, NULL);
std::cout<<"exit..."<<std::endl;
}
<commit_msg>initialise database if not yet existing<commit_after>#include <SensorDatabase/SensorDatabase.h>
#include <TempReader/TempReader.h>
#include <pthread.h>
#include <iostream>
#include "Timer.h"
#include "logger.h"
#include <glib.h>
#include <unistd.h>
#include <CommunicationService/SensorLoggerCommunicationServer.h>
#ifdef DEBUG
#define CONFPATH "../templog.conf"
#else
#define CONFPATH "/etc/templog.conf"
#endif
void dbg_db_fake(SensorDatabase &db) {
db.reset();
std::string image_data = "abcdef";
db.addSetting("basement", image_data.data(), image_data.size());
db.addSensor("pipe", "67C6697351FF", "28", "DS18B20", "°C", "basement");
db.addSensor("oven", "4AEC29CDBAAB", "10", "DS18B20", "°C", "basement");
db.addSensor("watertank", "F2FBE3467CC2", "10", "DS18B20", "°C", "basement");
}
void dbg_reader_fake(TempReader &reader) {
reader.addFake("10");
reader.addFake("10");
reader.addFake("28");
}
int main() {
std::cout<<"reading config from: "<<CONFPATH<<std::endl;
// read configuration
GKeyFile *conf_file = g_key_file_new ();
GKeyFileFlags conffile_flags;
GError *conffile_error = NULL;
if(!g_key_file_load_from_file(conf_file, CONFPATH, conffile_flags, &conffile_error)) {
g_error(conffile_error->message);
}
const char *db_path = g_key_file_get_string(conf_file, "database", "db_file", &conffile_error);
const time_t period = g_key_file_get_integer(conf_file, "logging", "period", &conffile_error);
const unsigned int port = g_key_file_get_integer(conf_file, "communication", "port", &conffile_error);
const char *device = g_key_file_get_string(conf_file, "logging", "device", &conffile_error);
std::cout<<"db path: "<<std::string(db_path)<<std::endl;
std::cout<<"period: "<<period<<std::endl;
if(db_path == NULL)
g_error(conffile_error->message);
SensorDatabase db;
TempReader reader;
const int db_init = access(db_path, F_OK);
db.open(db_path);
if(db_init!=0 && errno==ENOENT) {
std::cout<<"initiliazing database"<<std::endl;
db.init();
}
std::cout<<"addr db: "<<&db<<std::endl;
std::cout<<"addr reader: "<<&reader<<std::endl;
if(std::string(device)=="fake") {
// init with example data
std::cout<<"feeding fake data"<<std::endl;
dbg_db_fake(db);
dbg_reader_fake(reader);
}
else {
reader.setDevice(device);
}
reader.open();
LoggerConfig conf = {.period=period, .db=&db, .reader=&reader};
pthread_t th_logger;
std::cout<<"addr per: "<<&period<<std::endl;
std::cout<<"addr conf: "<<&conf<<std::endl;
//pthread_create(&th_logger, NULL, logger, (void*)period);
pthread_create(&th_logger, NULL, logger, &conf);
//pthread_create(&th_logger, NULL, logger, NULL);
SensorLoggerCommunicationServer s(port, db, reader);
s.start();
pthread_join(th_logger, NULL);
std::cout<<"exit..."<<std::endl;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkDataTree.h"
#include <mitkXMLWriter.h>
#include <mitkXMLReader.h>
//##ModelId=3E38F46A0190
mitk::DataTree::DataTree() :
DataTreeBase( )
{
SetRoot(mitk::DataTreeNode::New());
}
//##ModelId=3E38F46A01AE
mitk::DataTree::~DataTree()
{
DataTreePreOrderIterator it(this);
while(!it.IsAtEnd())
{
it.Set(NULL);
++it;
}
Clear();
}
/**
*
*/
//##ModelId=3E3FE0430148
mitk::DataTreeIteratorClone mitk::DataTree::GetNext( const char* propertyKey, const mitk::BaseProperty* property, mitk::DataTreeIteratorBase* startPosition )
{
DataTreeIteratorClone pos;
if(startPosition != NULL)
pos = *startPosition;
else
pos = DataTreePreOrderIterator(this);
mitk::DataTreeNode::Pointer dtn;
while ( !pos->IsAtEnd() )
{
dtn = pos->Get();
mitk::PropertyList::Pointer propertyList = dtn->GetPropertyList();
mitk::BaseProperty::Pointer tmp = propertyList->GetProperty( propertyKey );
if ( (*property) == *(tmp) )
return pos;
++pos;
}
return pos;
}
mitk::DataTreeIteratorClone mitk::DataTree::GetIteratorToNode(mitk::DataTreeBase* tree, const mitk::DataTreeNode* node, const mitk::DataTreeIteratorBase* startPosition )
{
DataTreeIteratorClone pos;
if(startPosition != NULL)
pos = *startPosition;
else
pos = DataTreePreOrderIterator(tree);
while ( !pos->IsAtEnd() )
{
if ( pos->Get().GetPointer() == node )
return pos;
++pos;
}
return pos;
}
//##ModelId=3ED91D050085
mitk::BoundingBox::Pointer mitk::DataTree::ComputeBoundingBox(mitk::DataTreeIteratorBase* it, const char* boolPropertyKey, mitk::BaseRenderer* renderer, const char* boolPropertyKey2)
{
mitk::DataTreeIteratorClone _it=it;
mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New();
mitk::BoundingBox::PointIdentifier pointid=0;
mitk::Point3D point;
while (!_it->IsAtEnd())
{
mitk::DataTreeNode::Pointer node = _it->Get();
assert(node.IsNotNull());
if (node->GetData() != NULL && node->GetData()->GetUpdatedGeometry() != NULL && node->IsOn(boolPropertyKey, renderer) && node->IsOn(boolPropertyKey2, renderer))
{
const Geometry3D* geometry = node->GetData()->GetUpdatedGeometry();
unsigned char i;
for(i=0; i<8; ++i)
{
point = geometry->GetCornerPoint(i);
if(point[0]*point[0]+point[1]*point[1]+point[2]*point[2] < mitk::large)
pointscontainer->InsertElement( pointid++, point);
else
{
itkGenericOutputMacro( << "Unrealistically distant corner point encountered. Ignored. Node: " << node );
}
}
}
++_it;
}
mitk::BoundingBox::Pointer result = mitk::BoundingBox::New();
result->SetPoints(pointscontainer);
result->ComputeBoundingBox();
return result;
}
mitk::TimeBounds mitk::DataTree::ComputeTimeBoundsInMS(mitk::DataTreeIteratorBase* it, const char* boolPropertyKey, mitk::BaseRenderer* renderer, const char* boolPropertyKey2)
{
TimeBounds timebounds;
mitk::DataTreeIteratorClone _it=it;
mitk::ScalarType stmin, stmax, cur;
stmin=-ScalarTypeNumericTraits::max();
stmax= ScalarTypeNumericTraits::max();
timebounds[0]=stmax; timebounds[1]=stmin;
while (!_it->IsAtEnd())
{
mitk::DataTreeNode::Pointer node = _it->Get();
if (node->GetData() != NULL && node->GetData()->GetUpdatedGeometry() != NULL && node->IsOn(boolPropertyKey, renderer) && node->IsOn(boolPropertyKey2, renderer))
{
mitk::Geometry3D::ConstPointer geometry = node->GetData()->GetGeometry();
cur=geometry->GetTimeBoundsInMS()[0];
//is it after -infinity, but before everything else that we found until now?
if((cur>stmin) && (cur<timebounds[0]))
timebounds[0] = cur;
cur=geometry->GetTimeBoundsInMS()[1];
//is it before infinity, but after everything else that we found until now?
if((cur<stmax) && (cur>timebounds[1]))
timebounds[1] = cur;
}
++_it;
}
if(!(timebounds[0]<stmax))
{
timebounds[0] = stmin;
timebounds[1] = stmax;
}
return timebounds;
}
bool mitk::DataTree::Load( const mitk::DataTreeIteratorBase* it, const char* filename )
{
return mitk::XMLReader::Load( filename, it );
}
bool mitk::DataTree::Save( const mitk::DataTreeIteratorBase* it, const char* fileName )
{
if ( fileName == NULL || it == NULL || it->IsAtEnd() )
return false;
std::string stdFileName(fileName);
unsigned int pos = stdFileName.find('.');
mitk::XMLWriter writer( fileName, stdFileName.substr( 0, pos ).c_str() );
if ( !Save( it, writer ) )
writer.WriteComment( "Error" );
return true;
}
bool mitk::DataTree::SaveNext( const mitk::DataTreeIteratorBase* it, mitk::XMLWriter& xmlWriter )
{
if ( it == NULL || it->IsAtEnd() )
return false;
mitk::DataTreeNode* node = it->Get();
xmlWriter.BeginNode("treeNode");
if (node)
{
node->WriteXML( xmlWriter );
/*
mitk::BaseData* data = node->GetData();
if ( data )
data->WriteXML( xmlWriter );
*/
if ( it->HasChild() )
{
DataTreeChildIterator children(*it);
while (!children.IsAtEnd())
{
SaveNext( &children, xmlWriter );
++children;
}
}
}
xmlWriter.WriteComment( "close TreeNode" );
xmlWriter.EndNode(); // TreeNode
return true;
}
bool mitk::DataTree::Save( const mitk::DataTreeIteratorBase* it, mitk::XMLWriter& xmlWriter )
{
// xmlWriter.WriteComment( "MITK Data Tree" );
xmlWriter.BeginNode( "mitkDataTree" );
bool result = SaveNext( it, xmlWriter );
// xmlWriter.WriteComment( "close mitkDataTree" );
xmlWriter.EndNode(); // mitkDataTree
return result;
}
<commit_msg>clean source code<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkDataTree.h"
#include <mitkXMLWriter.h>
#include <mitkXMLReader.h>
//##ModelId=3E38F46A0190
mitk::DataTree::DataTree() :
DataTreeBase( )
{
SetRoot(mitk::DataTreeNode::New());
}
//##ModelId=3E38F46A01AE
mitk::DataTree::~DataTree()
{
DataTreePreOrderIterator it(this);
while(!it.IsAtEnd())
{
it.Set(NULL);
++it;
}
Clear();
}
/**
*
*/
//##ModelId=3E3FE0430148
mitk::DataTreeIteratorClone mitk::DataTree::GetNext( const char* propertyKey, const mitk::BaseProperty* property, mitk::DataTreeIteratorBase* startPosition )
{
DataTreeIteratorClone pos;
if(startPosition != NULL)
pos = *startPosition;
else
pos = DataTreePreOrderIterator(this);
mitk::DataTreeNode::Pointer dtn;
while ( !pos->IsAtEnd() )
{
dtn = pos->Get();
mitk::PropertyList::Pointer propertyList = dtn->GetPropertyList();
mitk::BaseProperty::Pointer tmp = propertyList->GetProperty( propertyKey );
if ( (*property) == *(tmp) )
return pos;
++pos;
}
return pos;
}
mitk::DataTreeIteratorClone mitk::DataTree::GetIteratorToNode(mitk::DataTreeBase* tree, const mitk::DataTreeNode* node, const mitk::DataTreeIteratorBase* startPosition )
{
DataTreeIteratorClone pos;
if(startPosition != NULL)
pos = *startPosition;
else
pos = DataTreePreOrderIterator(tree);
while ( !pos->IsAtEnd() )
{
if ( pos->Get().GetPointer() == node )
return pos;
++pos;
}
return pos;
}
//##ModelId=3ED91D050085
mitk::BoundingBox::Pointer mitk::DataTree::ComputeBoundingBox(mitk::DataTreeIteratorBase* it, const char* boolPropertyKey, mitk::BaseRenderer* renderer, const char* boolPropertyKey2)
{
mitk::DataTreeIteratorClone _it=it;
mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New();
mitk::BoundingBox::PointIdentifier pointid=0;
mitk::Point3D point;
while (!_it->IsAtEnd())
{
mitk::DataTreeNode::Pointer node = _it->Get();
assert(node.IsNotNull());
if (node->GetData() != NULL && node->GetData()->GetUpdatedGeometry() != NULL && node->IsOn(boolPropertyKey, renderer) && node->IsOn(boolPropertyKey2, renderer))
{
const Geometry3D* geometry = node->GetData()->GetUpdatedGeometry();
unsigned char i;
for(i=0; i<8; ++i)
{
point = geometry->GetCornerPoint(i);
if(point[0]*point[0]+point[1]*point[1]+point[2]*point[2] < mitk::large)
pointscontainer->InsertElement( pointid++, point);
else
{
itkGenericOutputMacro( << "Unrealistically distant corner point encountered. Ignored. Node: " << node );
}
}
}
++_it;
}
mitk::BoundingBox::Pointer result = mitk::BoundingBox::New();
result->SetPoints(pointscontainer);
result->ComputeBoundingBox();
return result;
}
mitk::TimeBounds mitk::DataTree::ComputeTimeBoundsInMS(mitk::DataTreeIteratorBase* it, const char* boolPropertyKey, mitk::BaseRenderer* renderer, const char* boolPropertyKey2)
{
TimeBounds timebounds;
mitk::DataTreeIteratorClone _it=it;
mitk::ScalarType stmin, stmax, cur;
stmin=-ScalarTypeNumericTraits::max();
stmax= ScalarTypeNumericTraits::max();
timebounds[0]=stmax; timebounds[1]=stmin;
while (!_it->IsAtEnd())
{
mitk::DataTreeNode::Pointer node = _it->Get();
if (node->GetData() != NULL && node->GetData()->GetUpdatedGeometry() != NULL && node->IsOn(boolPropertyKey, renderer) && node->IsOn(boolPropertyKey2, renderer))
{
mitk::Geometry3D::ConstPointer geometry = node->GetData()->GetGeometry();
cur=geometry->GetTimeBoundsInMS()[0];
//is it after -infinity, but before everything else that we found until now?
if((cur>stmin) && (cur<timebounds[0]))
timebounds[0] = cur;
cur=geometry->GetTimeBoundsInMS()[1];
//is it before infinity, but after everything else that we found until now?
if((cur<stmax) && (cur>timebounds[1]))
timebounds[1] = cur;
}
++_it;
}
if(!(timebounds[0]<stmax))
{
timebounds[0] = stmin;
timebounds[1] = stmax;
}
return timebounds;
}
bool mitk::DataTree::Load( const mitk::DataTreeIteratorBase* it, const char* filename )
{
return mitk::XMLReader::Load( filename, it );
}
bool mitk::DataTree::Save( const mitk::DataTreeIteratorBase* it, const char* fileName )
{
if ( fileName == NULL || it == NULL || it->IsAtEnd() )
return false;
std::string stdFileName(fileName);
unsigned int pos = stdFileName.find('.');
mitk::XMLWriter writer( fileName, stdFileName.substr( 0, pos ).c_str() );
if ( !Save( it, writer ) )
writer.WriteComment( "Error" );
return true;
}
bool mitk::DataTree::SaveNext( const mitk::DataTreeIteratorBase* it, mitk::XMLWriter& xmlWriter )
{
if ( it == NULL || it->IsAtEnd() )
return false;
mitk::DataTreeNode* node = it->Get();
xmlWriter.BeginNode("treeNode");
if (node)
{
node->WriteXML( xmlWriter );
if ( it->HasChild() )
{
DataTreeChildIterator children(*it);
while (!children.IsAtEnd())
{
SaveNext( &children, xmlWriter );
++children;
}
}
}
xmlWriter.EndNode(); // TreeNode
return true;
}
bool mitk::DataTree::Save( const mitk::DataTreeIteratorBase* it, mitk::XMLWriter& xmlWriter )
{
xmlWriter.BeginNode( "mitkDataTree" );
bool result = SaveNext( it, xmlWriter );
xmlWriter.EndNode(); // mitkDataTree
return result;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.51
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "Setup.h" //For setup object
#include "EnergyTypes.h"
#include "PSFOutput.h"
#include <iostream>
#include <iomanip>
Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim)
{
startStep = 0;
//NOTE:
//IMPORTANT! Keep this order...
//as system depends on staticValues, and cpu sometimes depends on both.
set.Init(configFileName, multisim);
totalSteps = set.config.sys.step.total;
staticValues = new StaticVals(set);
system = new System(*staticValues);
staticValues->Init(set, *system);
system->Init(set, startStep);
//recal Init for static value for initializing ewald since ewald is
//initialized in system
staticValues->InitOver(set, *system);
cpu = new CPUSide(*system, *staticValues);
cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil,
totalSteps, startStep);
//Dump combined PSF
PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap,
set.pdb.atoms.resKindNames);
psfOut.PrintPSF(set.config.out.state.files.psf.name);
std::cout << "Printed combined psf to file "
<< set.config.out.state.files.psf.name << '\n';
if(totalSteps == 0) {
frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);
}
#if GOMC_LIB_MPI
PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq): NULL;
exchangeResults.resize(ms->worldSize, false);
#endif
}
Simulation::~Simulation()
{
delete cpu;
delete system;
delete staticValues;
}
void Simulation::RunSimulation(void)
{
double startEnergy = system->potential.totalEnergy.total;
if(totalSteps == 0) {
for(int i = 0; i < frameSteps.size(); i++) {
if(i == 0) {
cpu->Output(frameSteps[0] - 1);
continue;
}
system->RecalculateTrajectory(set, i + 1);
cpu->Output(frameSteps[i] - 1);
}
}
for (ulong step = startStep; step < totalSteps; step++) {
system->moveSettings.AdjustMoves(step);
system->ChooseAndRunMove(step);
cpu->Output(step);
if((step + 1) == cpu->equilSteps) {
double currEnergy = system->potential.totalEnergy.total;
if(abs(currEnergy - startEnergy) > 1.0e+10) {
printf("Info: Recalculating the total energies to insure the accuracy"
" of the computed \n"
" running energies.\n\n");
system->calcEwald->Init();
system->potential = system->calcEnergy.SystemTotal();
}
}
#if GOMC_LIB_MPI
if( staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){
system->potential = system->calcEnergy.SystemTotal();
exchangeResults = PTUtils->evaluateExchangeCriteria(step);
//if (ms->worldRank == 1){
if (exchangeResults[ms->worldRank] == true){
std::cout << "A swap took place" << std::endl;
//SystemPotential myPotentialCloneBeforeExchange(system->potential);
//SystemPotential potBuffer(system->potential);
PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank-1, true);
PTUtils->exchangeCOMs(system->com, ms, ms->worldRank-1, true);
// PTUtils->exchangeCellLists(myCellListCloneBeforeExchange, ms, ms->worldRank-1, true);
PTUtils->exchangeCellLists(system->cellList, ms, ms->worldRank-1, true);
//PTUtils->exchangePotentials(myPotentialCloneBeforeExchange, ms, ms->worldRank-1, true);
PTUtils->exchangePotentials(system->potential, ms, ms->worldRank-1, true);
// system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);
// system->potential = system->calcEnergy.SystemTotal();
//potBuffer = system->calcEnergy.SystemTotal();
/*
if (!potBuffer.ComparePotentials(myPotentialCloneBeforeExchange)){
std::cout << "Potential objects have different states. Exiting!" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "Potential objects have equivalent states." << std::endl;
}
*/
/*
if (!system->cellList.CompareCellList(myCellListCloneBeforeExchange, system->coordinates.Count())){
std::cout << "Cell List objects have different states, not simply different orders. Exiting!" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "Cell List objects have equivalent states." << std::endl;
}
*/
// system->calcEwald->UpdateVectorsAndRecipTerms();
// } else if (ms->worldRank == 0){
} else if(ms->worldRank+1 != ms->worldSize && exchangeResults[ms->worldRank+1] == true) {
std::cout << "A swap took place" << std::endl;
//SystemPotential myPotentialCloneBeforeExchange(system->potential);
//SystemPotential potBuffer(system->potential);
PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank+1, false);
PTUtils->exchangeCOMs(system->com, ms, ms->worldRank+1, false);
//PTUtils->exchangeCellLists(myCellListCloneBeforeExchange, ms, ms->worldRank-1, true);
PTUtils->exchangeCellLists(system->cellList, ms, ms->worldRank+1, false);
PTUtils->exchangePotentials(system->potential, ms, ms->worldRank+1, false);
// system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);
//system->potential = system->calcEnergy.SystemTotal();
//potBuffer = system->calcEnergy.SystemTotal();
/*
if (!potBuffer.ComparePotentials(myPotentialCloneBeforeExchange)){
std::cout << "Potential objects have different states. Exiting!" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "Potential objects have equivalent states." << std::endl;
}
*/
}
}
#endif
#ifndef NDEBUG
if((step + 1) % 1000 == 0)
RunningCheck(step);
#endif
}
system->PrintAcceptance();
system->PrintTime();
}
#ifndef NDEBUG
void Simulation::RunningCheck(const uint step)
{
system->calcEwald->UpdateVectorsAndRecipTerms();
SystemPotential pot = system->calcEnergy.SystemTotal();
std::cout
<< "================================================================="
<< std::endl << "-------------------------" << std::endl
<< " STEP: " << step + 1
<< std::endl << "-------------------------" << std::endl
<< "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP"
<< std::endl
<< "System: "
<< std::setw(12) << system->potential.totalEnergy.intraBond << " | "
<< std::setw(12) << system->potential.totalEnergy.intraNonbond << " | "
<< std::setw(12) << system->potential.totalEnergy.inter << " | "
<< std::setw(12) << system->potential.totalEnergy.tc << " | "
<< std::setw(12) << system->potential.totalEnergy.real << " | "
<< std::setw(12) << system->potential.totalEnergy.self << " | "
<< std::setw(12) << system->potential.totalEnergy.correction << " | "
<< std::setw(12) << system->potential.totalEnergy.recip << std::endl
<< "Recalc: "
<< std::setw(12) << pot.totalEnergy.intraBond << " | "
<< std::setw(12) << pot.totalEnergy.intraNonbond << " | "
<< std::setw(12) << pot.totalEnergy.inter << " | "
<< std::setw(12) << pot.totalEnergy.tc << " | "
<< std::setw(12) << pot.totalEnergy.real << " | "
<< std::setw(12) << pot.totalEnergy.self << " | "
<< std::setw(12) << pot.totalEnergy.correction << " | "
<< std::setw(12) << pot.totalEnergy.recip << std::endl
<< "================================================================"
<< std::endl << std::endl;
}
#endif
<commit_msg>Call systemtotal after each swap<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.51
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "Setup.h" //For setup object
#include "EnergyTypes.h"
#include "PSFOutput.h"
#include <iostream>
#include <iomanip>
Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim)
{
startStep = 0;
//NOTE:
//IMPORTANT! Keep this order...
//as system depends on staticValues, and cpu sometimes depends on both.
set.Init(configFileName, multisim);
totalSteps = set.config.sys.step.total;
staticValues = new StaticVals(set);
system = new System(*staticValues);
staticValues->Init(set, *system);
system->Init(set, startStep);
//recal Init for static value for initializing ewald since ewald is
//initialized in system
staticValues->InitOver(set, *system);
cpu = new CPUSide(*system, *staticValues);
cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil,
totalSteps, startStep);
//Dump combined PSF
PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap,
set.pdb.atoms.resKindNames);
psfOut.PrintPSF(set.config.out.state.files.psf.name);
std::cout << "Printed combined psf to file "
<< set.config.out.state.files.psf.name << '\n';
if(totalSteps == 0) {
frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);
}
#if GOMC_LIB_MPI
PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq): NULL;
exchangeResults.resize(ms->worldSize, false);
#endif
}
Simulation::~Simulation()
{
delete cpu;
delete system;
delete staticValues;
}
void Simulation::RunSimulation(void)
{
double startEnergy = system->potential.totalEnergy.total;
if(totalSteps == 0) {
for(int i = 0; i < frameSteps.size(); i++) {
if(i == 0) {
cpu->Output(frameSteps[0] - 1);
continue;
}
system->RecalculateTrajectory(set, i + 1);
cpu->Output(frameSteps[i] - 1);
}
}
for (ulong step = startStep; step < totalSteps; step++) {
system->moveSettings.AdjustMoves(step);
system->ChooseAndRunMove(step);
cpu->Output(step);
std::cout << "Virial : " << system->potential.totalVirial.total << std::endl;
if((step + 1) == cpu->equilSteps) {
double currEnergy = system->potential.totalEnergy.total;
if(abs(currEnergy - startEnergy) > 1.0e+10) {
printf("Info: Recalculating the total energies to insure the accuracy"
" of the computed \n"
" running energies.\n\n");
system->calcEwald->Init();
system->potential = system->calcEnergy.SystemTotal();
}
}
#if GOMC_LIB_MPI
if( staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){
system->potential = system->calcEnergy.SystemTotal();
exchangeResults = PTUtils->evaluateExchangeCriteria(step);
//if (ms->worldRank == 1){
if (exchangeResults[ms->worldRank] == true){
std::cout << "A swap took place" << std::endl;
//SystemPotential myPotentialCloneBeforeExchange(system->potential);
//SystemPotential potBuffer(system->potential);
PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank-1, true);
PTUtils->exchangeCOMs(system->com, ms, ms->worldRank-1, true);
// PTUtils->exchangeCellLists(myCellListCloneBeforeExchange, ms, ms->worldRank-1, true);
PTUtils->exchangeCellLists(system->cellList, ms, ms->worldRank-1, true);
system->potential = system->calcEnergy.SystemTotal();
//PTUtils->exchangePotentials(myPotentialCloneBeforeExchange, ms, ms->worldRank-1, true);
// PTUtils->exchangePotentials(system->potential, ms, ms->worldRank-1, true);
// std::cout << "Virial : " << system->potential.totalVirial.total << std::endl;
// system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);
// system->potential = system->calcEnergy.SystemTotal();
//potBuffer = system->calcEnergy.SystemTotal();
/*
if (!potBuffer.ComparePotentials(myPotentialCloneBeforeExchange)){
std::cout << "Potential objects have different states. Exiting!" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "Potential objects have equivalent states." << std::endl;
}
*/
/*
if (!system->cellList.CompareCellList(myCellListCloneBeforeExchange, system->coordinates.Count())){
std::cout << "Cell List objects have different states, not simply different orders. Exiting!" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "Cell List objects have equivalent states." << std::endl;
}
*/
// system->calcEwald->UpdateVectorsAndRecipTerms();
// } else if (ms->worldRank == 0){
} else if(ms->worldRank+1 != ms->worldSize && exchangeResults[ms->worldRank+1] == true) {
std::cout << "A swap took place" << std::endl;
//SystemPotential myPotentialCloneBeforeExchange(system->potential);
//SystemPotential potBuffer(system->potential);
PTUtils->exchangePositions(system->coordinates, ms, ms->worldRank+1, false);
PTUtils->exchangeCOMs(system->com, ms, ms->worldRank+1, false);
//PTUtils->exchangeCellLists(myCellListCloneBeforeExchange, ms, ms->worldRank-1, true);
PTUtils->exchangeCellLists(system->cellList, ms, ms->worldRank+1, false);
// PTUtils->exchangePotentials(system->potential, ms, ms->worldRank+1, false);
system->potential = system->calcEnergy.SystemTotal();
// system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);
//system->potential = system->calcEnergy.SystemTotal();
//potBuffer = system->calcEnergy.SystemTotal();
/*
if (!potBuffer.ComparePotentials(myPotentialCloneBeforeExchange)){
std::cout << "Potential objects have different states. Exiting!" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "Potential objects have equivalent states." << std::endl;
}
*/
}
}
#endif
#ifndef NDEBUG
if((step + 1) % 1000 == 0)
RunningCheck(step);
#endif
}
system->PrintAcceptance();
system->PrintTime();
}
#ifndef NDEBUG
void Simulation::RunningCheck(const uint step)
{
system->calcEwald->UpdateVectorsAndRecipTerms();
SystemPotential pot = system->calcEnergy.SystemTotal();
std::cout
<< "================================================================="
<< std::endl << "-------------------------" << std::endl
<< " STEP: " << step + 1
<< std::endl << "-------------------------" << std::endl
<< "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP"
<< std::endl
<< "System: "
<< std::setw(12) << system->potential.totalEnergy.intraBond << " | "
<< std::setw(12) << system->potential.totalEnergy.intraNonbond << " | "
<< std::setw(12) << system->potential.totalEnergy.inter << " | "
<< std::setw(12) << system->potential.totalEnergy.tc << " | "
<< std::setw(12) << system->potential.totalEnergy.real << " | "
<< std::setw(12) << system->potential.totalEnergy.self << " | "
<< std::setw(12) << system->potential.totalEnergy.correction << " | "
<< std::setw(12) << system->potential.totalEnergy.recip << std::endl
<< "Recalc: "
<< std::setw(12) << pot.totalEnergy.intraBond << " | "
<< std::setw(12) << pot.totalEnergy.intraNonbond << " | "
<< std::setw(12) << pot.totalEnergy.inter << " | "
<< std::setw(12) << pot.totalEnergy.tc << " | "
<< std::setw(12) << pot.totalEnergy.real << " | "
<< std::setw(12) << pot.totalEnergy.self << " | "
<< std::setw(12) << pot.totalEnergy.correction << " | "
<< std::setw(12) << pot.totalEnergy.recip << std::endl
<< "================================================================"
<< std::endl << std::endl;
}
#endif
<|endoftext|> |
<commit_before>/*
* StringUtil.cpp
*
* Copyright 2002, Log4cpp Project. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "StringUtil.hh"
#include <iterator>
#include <stdio.h>
#if defined(_MSC_VER)
#define VSNPRINTF _vsnprintf
#else
#ifdef LOG4CPP_HAVE_SNPRINTF
#define VSNPRINTF vsnprintf
#else
/* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */
#define HAVE_SNPRINTF
#define PREFER_PORTABLE_SNPRINTF
#include <stdlib.h>
#include <stdarg.h>
extern "C" {
#include "snprintf.c"
}
#define VSNPRINTF portable_vsnprintf
#endif // LOG4CPP_HAVE_SNPRINTF
#endif // _MSC_VER
namespace log4cpp {
std::string StringUtil::vform(const char* format, va_list args) {
size_t size = 1024;
char* buffer = new char[size];
while (1) {
va_list args_copy;
va_copy(args_copy, args);
int n = VSNPRINTF(buffer, size, format, args_copy);
va_end(args_copy);
// If that worked, return a string.
if ((n > -1) && (static_cast<size_t>(n) < size)) {
std::string s(buffer);
delete [] buffer;
return s;
}
// Else try again with more space.
size = (n > -1) ?
n + 1 : // ISO/IEC 9899:1999
size * 2; // twice the old size
delete [] buffer;
buffer = new char[size];
}
}
std::string StringUtil::trim(const std::string& s) {
static const char* whiteSpace = " \t\r\n";
// test for null string
if(s.empty())
return s;
// find first non-space character
std::string::size_type b = s.find_first_not_of(whiteSpace);
if(b == std::string::npos) // No non-spaces
return "";
// find last non-space character
std::string::size_type e = s.find_last_not_of(whiteSpace);
// return the remaining characters
return std::string(s, b, e - b + 1);
}
unsigned int StringUtil::split(std::vector<std::string>& v,
const std::string& s,
char delimiter, unsigned int maxSegments) {
v.clear();
std::back_insert_iterator<std::vector<std::string> > it(v);
return split(it, s, delimiter, maxSegments);
}
}
<commit_msg>MSVC and Borland doesn't have va_copy - fallback to simple assigning<commit_after>/*
* StringUtil.cpp
*
* Copyright 2002, Log4cpp Project. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "StringUtil.hh"
#include <iterator>
#include <stdio.h>
#if defined(_MSC_VER)
#define VSNPRINTF _vsnprintf
#else
#ifdef LOG4CPP_HAVE_SNPRINTF
#define VSNPRINTF vsnprintf
#else
/* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */
#define HAVE_SNPRINTF
#define PREFER_PORTABLE_SNPRINTF
#include <stdlib.h>
#include <stdarg.h>
extern "C" {
#include "snprintf.c"
}
#define VSNPRINTF portable_vsnprintf
#endif // LOG4CPP_HAVE_SNPRINTF
#endif // _MSC_VER
namespace log4cpp {
std::string StringUtil::vform(const char* format, va_list args) {
size_t size = 1024;
char* buffer = new char[size];
while (1) {
va_list args_copy;
#if defined(_MSC_VER) || defined(__BORLANDC__)
args_copy = args;
#else
va_copy(args_copy, args);
#endif
int n = VSNPRINTF(buffer, size, format, args_copy);
va_end(args_copy);
// If that worked, return a string.
if ((n > -1) && (static_cast<size_t>(n) < size)) {
std::string s(buffer);
delete [] buffer;
return s;
}
// Else try again with more space.
size = (n > -1) ?
n + 1 : // ISO/IEC 9899:1999
size * 2; // twice the old size
delete [] buffer;
buffer = new char[size];
}
}
std::string StringUtil::trim(const std::string& s) {
static const char* whiteSpace = " \t\r\n";
// test for null string
if(s.empty())
return s;
// find first non-space character
std::string::size_type b = s.find_first_not_of(whiteSpace);
if(b == std::string::npos) // No non-spaces
return "";
// find last non-space character
std::string::size_type e = s.find_last_not_of(whiteSpace);
// return the remaining characters
return std::string(s, b, e - b + 1);
}
unsigned int StringUtil::split(std::vector<std::string>& v,
const std::string& s,
char delimiter, unsigned int maxSegments) {
v.clear();
std::back_insert_iterator<std::vector<std::string> > it(v);
return split(it, s, delimiter, maxSegments);
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <gtest/gtest.h>
#include "Ast.h"
#include "GraphQLParser.h"
#include "c/GraphQLAstToJSON.h"
using namespace facebook::graphql;
using namespace facebook::graphql::ast;
TEST(JsonVisitorTests, NullValueEmitsValidJSONWithoutTrailingComma) {
const char *error = nullptr;
auto AST = parseString("{field(arg: null)}", &error);
ASSERT_STREQ(nullptr, error) << "GraphQL parser error: " << error;
const char *json = graphql_ast_to_json((const struct GraphQLAstNode *)AST.get());
EXPECT_STREQ(
json,
"{\"kind\":\"Document\",\"loc\":{\"start\":1,\"end\":19},\"definitions\":[{\"kind\":\"OperationDefinition\",\"loc\":{\"start\":1,\"end\":19},\"operation\":\"query\",\"name\": null,\"variableDefinitions\":null,\"directives\":null,\"selectionSet\":{\"kind\":\"SelectionSet\",\"loc\":{\"start\":1,\"end\":19},\"selections\":[{\"kind\":\"Field\",\"loc\":{\"start\":2,\"end\":18},\"alias\":null,\"name\":{\"kind\":\"Name\",\"loc\":{\"start\":2,\"end\":7},\"value\":\"field\"},\"arguments\":[{\"kind\":\"Argument\",\"loc\":{\"start\":8,\"end\":17},\"name\":{\"kind\":\"Name\",\"loc\":{\"start\":8,\"end\":11},\"value\":\"arg\"},\"value\":{\"kind\":\"NullValue\",\"loc\":{\"start\":13,\"end\":17}}}],\"directives\":null,\"selectionSet\":null}]}}]}");
}
<commit_msg>fix memory leak in test caught by CI<commit_after>/**
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <gtest/gtest.h>
#include "Ast.h"
#include "GraphQLParser.h"
#include "c/GraphQLAstToJSON.h"
using namespace facebook::graphql;
using namespace facebook::graphql::ast;
TEST(JsonVisitorTests, NullValueEmitsValidJSONWithoutTrailingComma) {
const char *error = nullptr;
auto AST = parseString("{field(arg: null)}", &error);
ASSERT_STREQ(nullptr, error) << "GraphQL parser error: " << error;
const char *json = graphql_ast_to_json((const struct GraphQLAstNode *)AST.get());
EXPECT_STREQ(
json,
"{\"kind\":\"Document\",\"loc\":{\"start\":1,\"end\":19},\"definitions\":[{\"kind\":\"OperationDefinition\",\"loc\":{\"start\":1,\"end\":19},\"operation\":\"query\",\"name\": null,\"variableDefinitions\":null,\"directives\":null,\"selectionSet\":{\"kind\":\"SelectionSet\",\"loc\":{\"start\":1,\"end\":19},\"selections\":[{\"kind\":\"Field\",\"loc\":{\"start\":2,\"end\":18},\"alias\":null,\"name\":{\"kind\":\"Name\",\"loc\":{\"start\":2,\"end\":7},\"value\":\"field\"},\"arguments\":[{\"kind\":\"Argument\",\"loc\":{\"start\":8,\"end\":17},\"name\":{\"kind\":\"Name\",\"loc\":{\"start\":8,\"end\":11},\"value\":\"arg\"},\"value\":{\"kind\":\"NullValue\",\"loc\":{\"start\":13,\"end\":17}}}],\"directives\":null,\"selectionSet\":null}]}}]}");
free((void *)json);
}
<|endoftext|> |
<commit_before>#include "Log.h"
#include "Formatting.h"
#define _XOPEN_SOURCE 600
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#define snprintf _snprintf
#define strdup _strdup
#define strerror_r(errno, buf, buflen) strerror_s(buf, buflen, errno)
#else
#include <sys/time.h>
#endif
#define LOG_MSG_SIZE 1024
static bool timestamping = false;
static bool trace = false;
static int maxLine = LOG_MSG_SIZE;
static int target = LOG_TARGET_NOWHERE;
static FILE* logfile = NULL;
static char* logfilename = NULL;
#ifdef _WIN32
typedef char log_timestamp_t[24];
#else
typedef char log_timestamp_t[27];
#endif
static const char* GetFullTimestamp(log_timestamp_t ts)
{
if (!timestamping)
return "";
#ifdef _WIN32
SYSTEMTIME st;
GetLocalTime(&st);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
(int) st.wYear,
(int) st.wMonth,
(int) st.wDay,
(int) st.wHour,
(int) st.wMinute,
(int) st.wSecond,
(int) st.wMilliseconds);
#else
struct tm tm;
time_t sec;
struct timeval tv;
gettimeofday(&tv, NULL);
sec = (time_t) tv.tv_sec;
localtime_r(&sec, &tm);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%06lu",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
(long unsigned int) tv.tv_usec);
#endif
return ts;
}
void Log_SetTimestamping(bool ts)
{
timestamping = ts;
}
bool Log_SetTrace(bool trace_)
{
bool prev = trace;
trace = trace_;
return prev;
}
void Log_SetMaxLine(int maxLine_)
{
maxLine = maxLine_ > LOG_MSG_SIZE ? LOG_MSG_SIZE : maxLine_;
}
void Log_SetTarget(int target_)
{
target = target_;
}
bool Log_SetOutputFile(const char* filename, bool truncate)
{
if (logfile)
{
fclose(logfile);
free(logfilename);
logfilename = NULL;
}
if (truncate)
logfile = fopen(filename, "w");
else
logfile = fopen(filename, "a");
if (!logfile)
{
target &= ~LOG_TARGET_FILE;
return false;
}
logfilename = strdup(filename);
return true;
}
void Log_Shutdown()
{
if (logfilename)
{
free(logfilename);
logfilename = NULL;
}
if (logfile)
{
fclose(logfile);
logfile = NULL;
}
fflush(stdout);
fflush(stderr);
trace = false;
timestamping = false;
}
static void Log_Append(char*& p, int& remaining, const char* s, int len)
{
if (len > remaining)
len = remaining;
if (len > 0)
memcpy(p, s, len);
p += len;
remaining -= len;
}
static void Log_Write(const char* buf, int /*size*/, int flush)
{
if ((target & LOG_TARGET_STDOUT) == LOG_TARGET_STDOUT)
{
fputs(buf, stdout);
if (flush)
fflush(stdout);
}
if ((target & LOG_TARGET_STDERR) == LOG_TARGET_STDERR)
{
fputs(buf, stderr);
if (flush)
fflush(stderr);
}
if ((target & LOG_TARGET_FILE) == LOG_TARGET_FILE && logfile)
{
fputs(buf, logfile);
if (flush)
fflush(logfile);
}
}
void Log(const char* file, int line, const char* func, int type, const char* fmt, ...)
{
char buf[LOG_MSG_SIZE];
int remaining;
char *p;
const char *sep;
int ret;
va_list ap;
if ((type == LOG_TYPE_TRACE || type == LOG_TYPE_ERRNO) && !trace)
return;
buf[maxLine - 1] = 0;
p = buf;
remaining = maxLine - 1;
// print timestamp
if (timestamping)
{
GetFullTimestamp(p);
p += sizeof(log_timestamp_t) - 1;
remaining -= sizeof(log_timestamp_t) - 1;
Log_Append(p, remaining, ": ", 2);
}
if (type != LOG_TYPE_MSG && file && func)
{
#ifdef _WIN32
sep = strrchr(file, '/');
if (!sep)
sep = strrchr(file, '\\');
#else
sep = strrchr(file, '/');
#endif
if (sep)
file = sep + 1;
// print filename, number of line and function name
ret = snprintf(p, remaining + 1, "%s:%d:%s()", file, line, func);
if (ret < 0 || ret > remaining)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0' || type == LOG_TYPE_ERRNO)
Log_Append(p, remaining, ": ", 2);
}
// in case of error print the errno message otherwise print our message
if (type == LOG_TYPE_ERRNO)
{
#ifdef _GNU_SOURCE
// this is a workaround for g++ on Debian Lenny
// see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=485135
// _GNU_SOURCE is unconditionally defined so always the GNU style
// sterror_r() is used, which is broken
char* err = strerror_r(errno, p, remaining - 1);
if (err)
{
ret = strlen(err);
if (err != p)
{
memcpy(p, err, ret);
p[ret] = 0;
}
}
else
ret = -1;
#elif _WIN32
DWORD lastError = GetLastError();
ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
(FORMAT_MESSAGE_MAX_WIDTH_MASK & remaining - 2),
NULL,
lastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) p,
remaining - 2,
NULL);
#else
ret = strerror_r(errno, p, remaining - 1);
if (ret >= 0)
ret = (int) strlen(p);
#endif
if (ret < 0)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0')
Log_Append(p, remaining, ": ", 2);
}
// else
{
va_start(ap, fmt);
ret = VWritef(p, remaining, fmt, ap);
va_end(ap);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
}
Log_Append(p, remaining, "\n", 2);
Log_Write(buf, maxLine - remaining, type != LOG_TYPE_TRACE);
}
<commit_msg>Log_Errno is now printed in debug mode.<commit_after>#include "Log.h"
#include "Formatting.h"
#define _XOPEN_SOURCE 600
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#define snprintf _snprintf
#define strdup _strdup
#define strerror_r(errno, buf, buflen) strerror_s(buf, buflen, errno)
#else
#include <sys/time.h>
#endif
#define LOG_MSG_SIZE 1024
static bool timestamping = false;
static bool trace = false;
static int maxLine = LOG_MSG_SIZE;
static int target = LOG_TARGET_NOWHERE;
static FILE* logfile = NULL;
static char* logfilename = NULL;
#ifdef _WIN32
typedef char log_timestamp_t[24];
#else
typedef char log_timestamp_t[27];
#endif
static const char* GetFullTimestamp(log_timestamp_t ts)
{
if (!timestamping)
return "";
#ifdef _WIN32
SYSTEMTIME st;
GetLocalTime(&st);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
(int) st.wYear,
(int) st.wMonth,
(int) st.wDay,
(int) st.wHour,
(int) st.wMinute,
(int) st.wSecond,
(int) st.wMilliseconds);
#else
struct tm tm;
time_t sec;
struct timeval tv;
gettimeofday(&tv, NULL);
sec = (time_t) tv.tv_sec;
localtime_r(&sec, &tm);
snprintf(ts, sizeof(log_timestamp_t), "%04d-%02d-%02d %02d:%02d:%02d.%06lu",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
(long unsigned int) tv.tv_usec);
#endif
return ts;
}
void Log_SetTimestamping(bool ts)
{
timestamping = ts;
}
bool Log_SetTrace(bool trace_)
{
bool prev = trace;
trace = trace_;
return prev;
}
void Log_SetMaxLine(int maxLine_)
{
maxLine = maxLine_ > LOG_MSG_SIZE ? LOG_MSG_SIZE : maxLine_;
}
void Log_SetTarget(int target_)
{
target = target_;
}
bool Log_SetOutputFile(const char* filename, bool truncate)
{
if (logfile)
{
fclose(logfile);
free(logfilename);
logfilename = NULL;
}
if (truncate)
logfile = fopen(filename, "w");
else
logfile = fopen(filename, "a");
if (!logfile)
{
target &= ~LOG_TARGET_FILE;
return false;
}
logfilename = strdup(filename);
return true;
}
void Log_Shutdown()
{
if (logfilename)
{
free(logfilename);
logfilename = NULL;
}
if (logfile)
{
fclose(logfile);
logfile = NULL;
}
fflush(stdout);
fflush(stderr);
trace = false;
timestamping = false;
}
static void Log_Append(char*& p, int& remaining, const char* s, int len)
{
if (len > remaining)
len = remaining;
if (len > 0)
memcpy(p, s, len);
p += len;
remaining -= len;
}
static void Log_Write(const char* buf, int /*size*/, int flush)
{
if ((target & LOG_TARGET_STDOUT) == LOG_TARGET_STDOUT)
{
fputs(buf, stdout);
if (flush)
fflush(stdout);
}
if ((target & LOG_TARGET_STDERR) == LOG_TARGET_STDERR)
{
fputs(buf, stderr);
if (flush)
fflush(stderr);
}
if ((target & LOG_TARGET_FILE) == LOG_TARGET_FILE && logfile)
{
fputs(buf, logfile);
if (flush)
fflush(logfile);
}
}
void Log(const char* file, int line, const char* func, int type, const char* fmt, ...)
{
char buf[LOG_MSG_SIZE];
int remaining;
char *p;
const char *sep;
int ret;
va_list ap;
// In debug mode enable ERRNO type messages
#ifdef DEBUG
if (type == LOG_TYPE_TRACE && !trace)
return;
#else
if ((type == LOG_TYPE_TRACE || type == LOG_TYPE_ERRNO) && !trace)
return;
#endif
buf[maxLine - 1] = 0;
p = buf;
remaining = maxLine - 1;
// print timestamp
if (timestamping)
{
GetFullTimestamp(p);
p += sizeof(log_timestamp_t) - 1;
remaining -= sizeof(log_timestamp_t) - 1;
Log_Append(p, remaining, ": ", 2);
}
if (type != LOG_TYPE_MSG && file && func)
{
#ifdef _WIN32
sep = strrchr(file, '/');
if (!sep)
sep = strrchr(file, '\\');
#else
sep = strrchr(file, '/');
#endif
if (sep)
file = sep + 1;
// print filename, number of line and function name
ret = snprintf(p, remaining + 1, "%s:%d:%s()", file, line, func);
if (ret < 0 || ret > remaining)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0' || type == LOG_TYPE_ERRNO)
Log_Append(p, remaining, ": ", 2);
}
// in case of error print the errno message otherwise print our message
if (type == LOG_TYPE_ERRNO)
{
#ifdef _GNU_SOURCE
// this is a workaround for g++ on Debian Lenny
// see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=485135
// _GNU_SOURCE is unconditionally defined so always the GNU style
// sterror_r() is used, which is broken
char* err = strerror_r(errno, p, remaining - 1);
if (err)
{
ret = strlen(err);
if (err != p)
{
memcpy(p, err, ret);
p[ret] = 0;
}
}
else
ret = -1;
#elif _WIN32
DWORD lastError = GetLastError();
ret = snprintf(p, remaining, "%u: ", lastError);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
if (remaining > 2)
{
ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
(FORMAT_MESSAGE_MAX_WIDTH_MASK & remaining - 2),
NULL,
lastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) p,
remaining - 2,
NULL);
}
else
ret = 0;
#else
ret = strerror_r(errno, p, remaining - 1);
if (ret >= 0)
ret = (int) strlen(p);
#endif
if (ret < 0)
ret = remaining;
p += ret;
remaining -= ret;
if (fmt[0] != '\0')
Log_Append(p, remaining, ": ", 2);
}
// else
{
va_start(ap, fmt);
ret = VWritef(p, remaining, fmt, ap);
va_end(ap);
if (ret < 0 || ret >= remaining)
ret = remaining - 1;
p += ret;
remaining -= ret;
}
Log_Append(p, remaining, "\n", 2);
Log_Write(buf, maxLine - remaining, type != LOG_TYPE_TRACE);
}
<|endoftext|> |
<commit_before>/*
* libjingle
* Copyright 2013, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/app/webrtc/test/peerconnectiontestwrapper.h"
#include "talk/base/gunit.h"
#include "talk/base/logging.h"
#include "talk/base/ssladapter.h"
#include "talk/base/sslstreamadapter.h"
#include "talk/base/stringencode.h"
#include "talk/base/stringutils.h"
using webrtc::FakeConstraints;
using webrtc::MediaConstraintsInterface;
using webrtc::MediaStreamInterface;
using webrtc::PeerConnectionInterface;
namespace {
const char kExternalGiceUfrag[] = "1234567890123456";
const char kExternalGicePwd[] = "123456789012345678901234";
void RemoveLinesFromSdp(const std::string& line_start,
std::string* sdp) {
const char kSdpLineEnd[] = "\r\n";
size_t ssrc_pos = 0;
while ((ssrc_pos = sdp->find(line_start, ssrc_pos)) !=
std::string::npos) {
size_t end_ssrc = sdp->find(kSdpLineEnd, ssrc_pos);
sdp->erase(ssrc_pos, end_ssrc - ssrc_pos + strlen(kSdpLineEnd));
}
}
// Add |newlines| to the |message| after |line|.
void InjectAfter(const std::string& line,
const std::string& newlines,
std::string* message) {
const std::string tmp = line + newlines;
talk_base::replace_substrs(line.c_str(), line.length(),
tmp.c_str(), tmp.length(), message);
}
void Replace(const std::string& line,
const std::string& newlines,
std::string* message) {
talk_base::replace_substrs(line.c_str(), line.length(),
newlines.c_str(), newlines.length(), message);
}
void UseExternalSdes(std::string* sdp) {
// Remove current crypto specification.
RemoveLinesFromSdp("a=crypto", sdp);
RemoveLinesFromSdp("a=fingerprint", sdp);
// Add external crypto.
const char kAudioSdes[] =
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 "
"inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR\r\n";
const char kVideoSdes[] =
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 "
"inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj\r\n";
const char kDataSdes[] =
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 "
"inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj\r\n";
InjectAfter("a=mid:audio\r\n", kAudioSdes, sdp);
InjectAfter("a=mid:video\r\n", kVideoSdes, sdp);
InjectAfter("a=mid:data\r\n", kDataSdes, sdp);
}
void UseGice(std::string* sdp) {
InjectAfter("t=0 0\r\n", "a=ice-options:google-ice\r\n", sdp);
std::string ufragline = "a=ice-ufrag:";
std::string pwdline = "a=ice-pwd:";
RemoveLinesFromSdp(ufragline, sdp);
RemoveLinesFromSdp(pwdline, sdp);
ufragline.append(kExternalGiceUfrag);
ufragline.append("\r\n");
pwdline.append(kExternalGicePwd);
pwdline.append("\r\n");
const std::string ufrag_pwd = ufragline + pwdline;
InjectAfter("a=mid:audio\r\n", ufrag_pwd, sdp);
InjectAfter("a=mid:video\r\n", ufrag_pwd, sdp);
InjectAfter("a=mid:data\r\n", ufrag_pwd, sdp);
}
void RemoveBundle(std::string* sdp) {
RemoveLinesFromSdp("a=group:BUNDLE", sdp);
}
} // namespace
class PeerConnectionEndToEndTest
: public sigslot::has_slots<>,
public testing::Test {
public:
PeerConnectionEndToEndTest()
: caller_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>(
"caller")),
callee_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>(
"callee")) {
talk_base::InitializeSSL(NULL);
}
void CreatePcs() {
CreatePcs(NULL);
}
void CreatePcs(const MediaConstraintsInterface* pc_constraints) {
EXPECT_TRUE(caller_->CreatePc(pc_constraints));
EXPECT_TRUE(callee_->CreatePc(pc_constraints));
PeerConnectionTestWrapper::Connect(caller_.get(), callee_.get());
}
void GetAndAddUserMedia() {
FakeConstraints audio_constraints;
FakeConstraints video_constraints;
GetAndAddUserMedia(true, audio_constraints, true, video_constraints);
}
void GetAndAddUserMedia(bool audio, FakeConstraints audio_constraints,
bool video, FakeConstraints video_constraints) {
caller_->GetAndAddUserMedia(audio, audio_constraints,
video, video_constraints);
callee_->GetAndAddUserMedia(audio, audio_constraints,
video, video_constraints);
}
void Negotiate() {
caller_->CreateOffer(NULL);
}
void WaitForCallEstablished() {
caller_->WaitForCallEstablished();
callee_->WaitForCallEstablished();
}
void SetupLegacySdpConverter() {
caller_->SignalOnSdpCreated.connect(
this, &PeerConnectionEndToEndTest::ConvertToLegacySdp);
callee_->SignalOnSdpCreated.connect(
this, &PeerConnectionEndToEndTest::ConvertToLegacySdp);
}
void ConvertToLegacySdp(std::string* sdp) {
UseExternalSdes(sdp);
UseGice(sdp);
RemoveBundle(sdp);
LOG(LS_INFO) << "ConvertToLegacySdp: " << *sdp;
}
void SetupGiceConverter() {
caller_->SignalOnIceCandidateCreated.connect(
this, &PeerConnectionEndToEndTest::AddGiceCredsToCandidate);
callee_->SignalOnIceCandidateCreated.connect(
this, &PeerConnectionEndToEndTest::AddGiceCredsToCandidate);
}
void AddGiceCredsToCandidate(std::string* sdp) {
std::string gice_creds = " username ";
gice_creds.append(kExternalGiceUfrag);
gice_creds.append(" password ");
gice_creds.append(kExternalGicePwd);
gice_creds.append("\r\n");
Replace("\r\n", gice_creds, sdp);
LOG(LS_INFO) << "AddGiceCredsToCandidate: " << *sdp;
}
~PeerConnectionEndToEndTest() {
talk_base::CleanupSSL();
}
protected:
talk_base::scoped_refptr<PeerConnectionTestWrapper> caller_;
talk_base::scoped_refptr<PeerConnectionTestWrapper> callee_;
};
TEST_F(PeerConnectionEndToEndTest, Call) {
CreatePcs();
GetAndAddUserMedia();
Negotiate();
WaitForCallEstablished();
}
TEST_F(PeerConnectionEndToEndTest, CallWithLegacySdp) {
FakeConstraints pc_constraints;
pc_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
false);
CreatePcs(&pc_constraints);
SetupLegacySdpConverter();
SetupGiceConverter();
GetAndAddUserMedia();
Negotiate();
WaitForCallEstablished();
}
<commit_msg>Disable PeerConnectionEndToEndTest for tsanv2 build. BUG=1205 TEST=try R=kjellander@webrtc.org<commit_after>/*
* libjingle
* Copyright 2013, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/app/webrtc/test/peerconnectiontestwrapper.h"
#include "talk/base/gunit.h"
#include "talk/base/logging.h"
#include "talk/base/ssladapter.h"
#include "talk/base/sslstreamadapter.h"
#include "talk/base/stringencode.h"
#include "talk/base/stringutils.h"
using webrtc::FakeConstraints;
using webrtc::MediaConstraintsInterface;
using webrtc::MediaStreamInterface;
using webrtc::PeerConnectionInterface;
namespace {
const char kExternalGiceUfrag[] = "1234567890123456";
const char kExternalGicePwd[] = "123456789012345678901234";
void RemoveLinesFromSdp(const std::string& line_start,
std::string* sdp) {
const char kSdpLineEnd[] = "\r\n";
size_t ssrc_pos = 0;
while ((ssrc_pos = sdp->find(line_start, ssrc_pos)) !=
std::string::npos) {
size_t end_ssrc = sdp->find(kSdpLineEnd, ssrc_pos);
sdp->erase(ssrc_pos, end_ssrc - ssrc_pos + strlen(kSdpLineEnd));
}
}
// Add |newlines| to the |message| after |line|.
void InjectAfter(const std::string& line,
const std::string& newlines,
std::string* message) {
const std::string tmp = line + newlines;
talk_base::replace_substrs(line.c_str(), line.length(),
tmp.c_str(), tmp.length(), message);
}
void Replace(const std::string& line,
const std::string& newlines,
std::string* message) {
talk_base::replace_substrs(line.c_str(), line.length(),
newlines.c_str(), newlines.length(), message);
}
void UseExternalSdes(std::string* sdp) {
// Remove current crypto specification.
RemoveLinesFromSdp("a=crypto", sdp);
RemoveLinesFromSdp("a=fingerprint", sdp);
// Add external crypto.
const char kAudioSdes[] =
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 "
"inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR\r\n";
const char kVideoSdes[] =
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 "
"inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj\r\n";
const char kDataSdes[] =
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 "
"inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj\r\n";
InjectAfter("a=mid:audio\r\n", kAudioSdes, sdp);
InjectAfter("a=mid:video\r\n", kVideoSdes, sdp);
InjectAfter("a=mid:data\r\n", kDataSdes, sdp);
}
void UseGice(std::string* sdp) {
InjectAfter("t=0 0\r\n", "a=ice-options:google-ice\r\n", sdp);
std::string ufragline = "a=ice-ufrag:";
std::string pwdline = "a=ice-pwd:";
RemoveLinesFromSdp(ufragline, sdp);
RemoveLinesFromSdp(pwdline, sdp);
ufragline.append(kExternalGiceUfrag);
ufragline.append("\r\n");
pwdline.append(kExternalGicePwd);
pwdline.append("\r\n");
const std::string ufrag_pwd = ufragline + pwdline;
InjectAfter("a=mid:audio\r\n", ufrag_pwd, sdp);
InjectAfter("a=mid:video\r\n", ufrag_pwd, sdp);
InjectAfter("a=mid:data\r\n", ufrag_pwd, sdp);
}
void RemoveBundle(std::string* sdp) {
RemoveLinesFromSdp("a=group:BUNDLE", sdp);
}
} // namespace
class PeerConnectionEndToEndTest
: public sigslot::has_slots<>,
public testing::Test {
public:
PeerConnectionEndToEndTest()
: caller_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>(
"caller")),
callee_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>(
"callee")) {
talk_base::InitializeSSL(NULL);
}
void CreatePcs() {
CreatePcs(NULL);
}
void CreatePcs(const MediaConstraintsInterface* pc_constraints) {
EXPECT_TRUE(caller_->CreatePc(pc_constraints));
EXPECT_TRUE(callee_->CreatePc(pc_constraints));
PeerConnectionTestWrapper::Connect(caller_.get(), callee_.get());
}
void GetAndAddUserMedia() {
FakeConstraints audio_constraints;
FakeConstraints video_constraints;
GetAndAddUserMedia(true, audio_constraints, true, video_constraints);
}
void GetAndAddUserMedia(bool audio, FakeConstraints audio_constraints,
bool video, FakeConstraints video_constraints) {
caller_->GetAndAddUserMedia(audio, audio_constraints,
video, video_constraints);
callee_->GetAndAddUserMedia(audio, audio_constraints,
video, video_constraints);
}
void Negotiate() {
caller_->CreateOffer(NULL);
}
void WaitForCallEstablished() {
caller_->WaitForCallEstablished();
callee_->WaitForCallEstablished();
}
void SetupLegacySdpConverter() {
caller_->SignalOnSdpCreated.connect(
this, &PeerConnectionEndToEndTest::ConvertToLegacySdp);
callee_->SignalOnSdpCreated.connect(
this, &PeerConnectionEndToEndTest::ConvertToLegacySdp);
}
void ConvertToLegacySdp(std::string* sdp) {
UseExternalSdes(sdp);
UseGice(sdp);
RemoveBundle(sdp);
LOG(LS_INFO) << "ConvertToLegacySdp: " << *sdp;
}
void SetupGiceConverter() {
caller_->SignalOnIceCandidateCreated.connect(
this, &PeerConnectionEndToEndTest::AddGiceCredsToCandidate);
callee_->SignalOnIceCandidateCreated.connect(
this, &PeerConnectionEndToEndTest::AddGiceCredsToCandidate);
}
void AddGiceCredsToCandidate(std::string* sdp) {
std::string gice_creds = " username ";
gice_creds.append(kExternalGiceUfrag);
gice_creds.append(" password ");
gice_creds.append(kExternalGicePwd);
gice_creds.append("\r\n");
Replace("\r\n", gice_creds, sdp);
LOG(LS_INFO) << "AddGiceCredsToCandidate: " << *sdp;
}
~PeerConnectionEndToEndTest() {
talk_base::CleanupSSL();
}
protected:
talk_base::scoped_refptr<PeerConnectionTestWrapper> caller_;
talk_base::scoped_refptr<PeerConnectionTestWrapper> callee_;
};
// Disable for TSan v2, see
// https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
#if !defined(THREAD_SANITIZER)
TEST_F(PeerConnectionEndToEndTest, Call) {
CreatePcs();
GetAndAddUserMedia();
Negotiate();
WaitForCallEstablished();
}
TEST_F(PeerConnectionEndToEndTest, CallWithLegacySdp) {
FakeConstraints pc_constraints;
pc_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
false);
CreatePcs(&pc_constraints);
SetupLegacySdpConverter();
SetupGiceConverter();
GetAndAddUserMedia();
Negotiate();
WaitForCallEstablished();
}
#endif // if !defined(THREAD_SANITIZER)
<|endoftext|> |
<commit_before>#include "TGATexture.h"
#include <fstream>
#include <vector>
// all possible image types
// described in TGA format specification
enum class tga_image_type : uint8_t
{
none = 0, // no image data
colormap = 1, // uncompressed, colormap
bgr = 2, // uncompressed, bgr
mono = 3, // uncompressed, black-white image
colormap_rle = 9, // compressed, colormap
bgr_rle = 10, // compressed, bgr
mono_rle = 11 // compressed, black-white image
};
TGATexture::TGATexture()
:_texture(), _textureView()
{
memset(&_textureInfo, 0, sizeof(_textureInfo));
}
void TGATexture::load(const std::string& filename, ID3D11Device* device)
{
// in case if texture exists
// we need to release all resources
_texture.reset();
_textureView.reset();
std::ifstream stream(filename, std::ios_base::beg | std::ios_base::binary);
stream.exceptions(std::ios_base::failbit | std::ios_base::badbit | std::ios_base::eofbit);
// reading tga image header
struct
{
uint8_t data1[2];
tga_image_type tga_type;
uint8_t data2[5];
// 0,0 point for origin x,y
// is bottom left
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bpp;
uint8_t data3;
} img_header;
stream.read(reinterpret_cast<char*>(&img_header), sizeof(img_header));
if ((img_header.bpp != sizeof(uint32_t) * 8) || // image should be 32 bpp
(img_header.tga_type != tga_image_type::bgr) || // image shouldn't be compressed with RLE
(img_header.y_origin != img_header.height)) // origin point should be left-top not left-bottom
{
stream.setstate(std::ios_base::failbit);
}
_textureInfo.width = img_header.width;
_textureInfo.height = img_header.height;
_textureInfo.bpp = img_header.bpp;
size_t imgSize = img_header.height * img_header.width;
std::vector<uint32_t> tmpData(imgSize);
tmpData.shrink_to_fit();
stream.read(reinterpret_cast<char*>(tmpData.data()), imgSize * sizeof(uint32_t));
stream.close();
for(auto iter = tmpData.begin(); iter != tmpData.end(); ++iter)
{
uint8_t* bgra = reinterpret_cast<uint8_t*>(&(*iter));
// swap b and r components to get rgba from bgra
std::swap(bgra[0], bgra[2]);
}
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.ArraySize = 1;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.Height = img_header.height;
textureDesc.MipLevels = 1;
textureDesc.MiscFlags = 0;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.Width = img_header.width;
D3D11_SUBRESOURCE_DATA subData;
subData.pSysMem = tmpData.data();
subData.SysMemPitch = img_header.width * sizeof(uint32_t);
subData.SysMemSlicePitch = 0;
HRESULT hr = device->CreateTexture2D(&textureDesc, &subData, _texture.getpp());
D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc;
memset(&textureViewDesc, 0, sizeof(textureViewDesc));
textureViewDesc.Format = textureDesc.Format;
textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
textureViewDesc.Texture2D.MipLevels = 1;
textureViewDesc.Texture2D.MostDetailedMip = 0;
hr = device->CreateShaderResourceView(_texture.getp(), &textureViewDesc, _textureView.getpp());
}<commit_msg>TGA image with left-bottom origin point can be used now.<commit_after>#include "TGATexture.h"
#include <fstream>
#include <vector>
#include <algorithm>
// all possible image types
// described in TGA format specification
enum class tga_image_type : uint8_t
{
none = 0, // no image data
colormap = 1, // uncompressed, colormap
bgr = 2, // uncompressed, bgr
mono = 3, // uncompressed, black-white image
colormap_rle = 9, // compressed, colormap
bgr_rle = 10, // compressed, bgr
mono_rle = 11 // compressed, black-white image
};
TGATexture::TGATexture()
:_texture(), _textureView()
{
memset(&_textureInfo, 0, sizeof(_textureInfo));
}
void TGATexture::load(const std::string& filename, ID3D11Device* device)
{
// in case if texture exists
// we need to release all resources
_texture.reset();
_textureView.reset();
std::ifstream stream(filename, std::ios_base::beg | std::ios_base::binary);
stream.exceptions(std::ios_base::failbit | std::ios_base::badbit | std::ios_base::eofbit);
// reading tga image header
struct
{
uint8_t data1[2];
tga_image_type tga_type;
uint8_t data2[5];
// 0,0 point for origin x,y
// is bottom left
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bpp;
uint8_t data3;
} img_header;
stream.read(reinterpret_cast<char*>(&img_header), sizeof(img_header));
if ((img_header.bpp != sizeof(uint32_t) * 8) || // image should be 32 bpp
(img_header.tga_type != tga_image_type::bgr)) // image shouldn't be compressed with RLE
{
stream.setstate(std::ios_base::failbit);
}
_textureInfo.width = img_header.width;
_textureInfo.height = img_header.height;
_textureInfo.bpp = img_header.bpp;
size_t imgSize = img_header.height * img_header.width;
std::vector<uint32_t> tmpData(imgSize);
tmpData.shrink_to_fit();
stream.read(reinterpret_cast<char*>(tmpData.data()), imgSize * sizeof(uint32_t));
stream.close();
// origin point is left-bottom
if (img_header.y_origin == 0)
{
for(auto fIter = tmpData.begin(), lIter = tmpData.end() - img_header.width;
fIter < lIter;
fIter += img_header.width, lIter -= img_header.width)
{
std::swap_ranges(fIter, fIter + img_header.width, lIter);
}
}
for(auto iter = tmpData.begin(); iter != tmpData.end(); ++iter)
{
uint8_t* bgra = reinterpret_cast<uint8_t*>(&(*iter));
// swap b and r components to get rgba from bgra
std::swap(bgra[0], bgra[2]);
}
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.ArraySize = 1;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.Height = img_header.height;
textureDesc.MipLevels = 1;
textureDesc.MiscFlags = 0;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.Width = img_header.width;
D3D11_SUBRESOURCE_DATA subData;
subData.pSysMem = tmpData.data();
subData.SysMemPitch = img_header.width * sizeof(uint32_t);
subData.SysMemSlicePitch = 0;
HRESULT hr = device->CreateTexture2D(&textureDesc, &subData, _texture.getpp());
D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc;
memset(&textureViewDesc, 0, sizeof(textureViewDesc));
textureViewDesc.Format = textureDesc.Format;
textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
textureViewDesc.Texture2D.MipLevels = 1;
textureViewDesc.Texture2D.MostDetailedMip = 0;
hr = device->CreateShaderResourceView(_texture.getp(), &textureViewDesc, _textureView.getpp());
}<|endoftext|> |
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef METHCLA_AUDIO_RESOURCE_HPP_INCLUDED
#define METHCLA_AUDIO_RESOURCE_HPP_INCLUDED
#include <boost/intrusive_ptr.hpp>
#include <boost/utility.hpp>
#include <stdexcept>
#include <vector>
namespace Methcla { namespace Audio
{
class Environment;
template<typename T>
inline void intrusive_ptr_add_ref(T* expr)
{
expr->retain();
}
template<typename T>
inline void intrusive_ptr_release(T* expr)
{
expr->release();
}
//* Reference counted base class
class Reference : public boost::noncopyable
{
public:
Reference()
: m_refs(0)
{ }
inline void retain()
{
m_refs++;
}
inline void release()
{
m_refs--;
BOOST_ASSERT_MSG( m_refs >= 0 , "release() called once too many" );
if (m_refs == 0)
this->free();
}
protected:
virtual ~Reference()
{ }
virtual void free()
{
delete this;
}
private:
int m_refs;
};
/// Resource base class.
//
// A resource has a reference to its environment and a unique id.
template <class Id> class Resource : public Reference
{
public:
Resource(Environment& env, const Id& id)
: m_env(env)
, m_id(id)
{ }
/// Return environment.
const Environment& env() const { return m_env; }
Environment& env() { return m_env; }
/// Return unique id.
const Id& id() const { return m_id; }
private:
Environment& m_env;
Id m_id;
};
/// Simple map for holding pointers to resources.
//
// Also provides unique id allocation facility.
template <class Id, class T> class ResourceMap : boost::noncopyable
{
public:
typedef boost::intrusive_ptr<T> Pointer;
ResourceMap(size_t size)
: m_elems(size, nullptr)
{ }
size_t size() const
{
return m_elems.size();
}
Id nextId()
{
for (size_t i=0; i < m_elems.size(); i++) {
if (m_elems[i] == nullptr) {
return static_cast<Id>(i);
}
}
throw std::runtime_error("No free ids");
}
void insert(const Id& id, Pointer a)
{
m_elems[id] = a;
}
void insert(const Id& id, T* a)
{
insert(id, Pointer(a));
}
void remove(const Id& id)
{
m_elems[id] = nullptr;
}
Pointer lookup(const Id& id) noexcept
{
if ((id >= Id(0)) && (id < Id(m_elems.size())))
return m_elems[id];
return nullptr;
}
private:
std::vector<Pointer> m_elems;
};
}; };
#endif // METHCLA_AUDIO_RESOURCE_HPP_INCLUDED
<commit_msg>Add contains method to ResourceMap<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef METHCLA_AUDIO_RESOURCE_HPP_INCLUDED
#define METHCLA_AUDIO_RESOURCE_HPP_INCLUDED
#include <boost/intrusive_ptr.hpp>
#include <boost/utility.hpp>
#include <stdexcept>
#include <vector>
namespace Methcla { namespace Audio
{
class Environment;
template<typename T>
inline void intrusive_ptr_add_ref(T* expr)
{
expr->retain();
}
template<typename T>
inline void intrusive_ptr_release(T* expr)
{
expr->release();
}
//* Reference counted base class
class Reference : public boost::noncopyable
{
public:
Reference()
: m_refs(0)
{ }
inline void retain()
{
m_refs++;
}
inline void release()
{
m_refs--;
BOOST_ASSERT_MSG( m_refs >= 0 , "release() called once too many" );
if (m_refs == 0)
this->free();
}
protected:
virtual ~Reference()
{ }
virtual void free()
{
delete this;
}
private:
int m_refs;
};
/// Resource base class.
//
// A resource has a reference to its environment and a unique id.
template <class Id> class Resource : public Reference
{
public:
Resource(Environment& env, const Id& id)
: m_env(env)
, m_id(id)
{ }
/// Return environment.
const Environment& env() const { return m_env; }
Environment& env() { return m_env; }
/// Return unique id.
const Id& id() const { return m_id; }
private:
Environment& m_env;
Id m_id;
};
/// Simple map for holding pointers to resources.
//
// Also provides unique id allocation facility.
template <class Id, class T> class ResourceMap : boost::noncopyable
{
public:
typedef boost::intrusive_ptr<T> Pointer;
ResourceMap(size_t size)
: m_elems(size, nullptr)
{ }
size_t size() const
{
return m_elems.size();
}
bool contains(const Id& id) const
{
return m_elems[id] != nullptr;
}
Id nextId()
{
for (size_t i=0; i < m_elems.size(); i++) {
if (m_elems[i] == nullptr) {
return static_cast<Id>(i);
}
}
throw std::runtime_error("No free ids");
}
void insert(const Id& id, Pointer a)
{
m_elems[id] = a;
}
void insert(const Id& id, T* a)
{
insert(id, Pointer(a));
}
void remove(const Id& id)
{
m_elems[id] = nullptr;
}
Pointer lookup(const Id& id) noexcept
{
if ((id >= Id(0)) && (id < Id(m_elems.size())))
return m_elems[id];
return nullptr;
}
private:
std::vector<Pointer> m_elems;
};
}; };
#endif // METHCLA_AUDIO_RESOURCE_HPP_INCLUDED
<|endoftext|> |
<commit_before>//===--------- ProfileModule.cpp - The Profile Module -*- C++ -*----------===//
//
// The LLVM Time Cost Analyser Infrastructure
//
// This file is distributed under the MIT License. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains implementation of the ProfileModule, which
/// encapsulate a LLVMModule and its profiling information.
///
//===----------------------------------------------------------------------===//
#include "geos/ProfileModule/ProfileModule.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Transforms/Utils/Cloning.h"
using namespace llvm;
bool hasWeight(const Instruction &I) {
return I.getMetadata("Weight") != nullptr;
}
double getWeight(const Instruction &I) {
assert(hasWeight(I) &&
"Trying to get the weight of a Instruction without a weight.");
return std::stod(
cast<MDString>(I.getMetadata("Weight")->getOperand(0))->getString());
}
void setWeight(Instruction &I, double Weight) {
LLVMContext& C = I.getContext();
MDNode* N =
MDNode::get(C, MDString::get(C, std::to_string(Weight)));
I.setMetadata("Weight", N);
}
bool ProfileModule::hasID(const Instruction &I) const {
return I.getMetadata("ID") != nullptr;
}
int ProfileModule::getID(const Instruction &I) {
assert(hasID(I) &&
"Trying to get the ID of an Instruction without an ID.");
return std::stoi(
cast<MDString>(I.getMetadata("ID")->getOperand(0))->getString());
}
void setID(Instruction &I, int ID) {
LLVMContext& C = I.getContext();
MDNode* N =
MDNode::get(C, MDString::get(C, std::to_string(ID)));
I.setMetadata("ID", N);
}
int nC = 0; // Counter to generate CallInst's names
ProfileModule::ProfileModule(Module* M) {
LLVMModule = M;
for (auto &Func : *LLVMModule) {
for (auto &BB : Func) {
for (auto &I : BB)
if (isa<CallInst>(I))
if (cast<CallInst>(I).getCalledFunction() == nullptr ||
cast<CallInst>(I).getCalledFunction()->size() == 0)
setID(I, nC++);
}
}
}
Module* ProfileModule::getLLVMModule() const {
return LLVMModule;
}
bool ProfileModule::hasInstructionFrequency(const Instruction &Inst) const {
return Inst.getMetadata("ifreq") != nullptr;
}
void
ProfileModule::setInstructionFrequency(Instruction &Inst, uint64_t Freq) {
MDBuilder MDB(Inst.getContext());
SmallVector<Metadata*, 4> Val(1);
Type *Int64Ty = Type::getInt64Ty(Inst.getContext());
Val[0] = MDB.createConstant(ConstantInt::get(Int64Ty, Freq));
MDNode *Node = MDNode::get(Inst.getContext(), Val);
Inst.setMetadata("ifreq", Node);
}
uint64_t
ProfileModule::getInstructionFrequency(const Instruction &Inst) const {
uint64_t Freq = 0;
if (hasInstructionFrequency(Inst))
Freq = cast<ConstantInt>(cast<ConstantAsMetadata>(
Inst.getMetadata("ifreq")->getOperand(0))->getValue())
->getSExtValue();
return Freq;
}
bool ProfileModule::hasBranchFrequency(const BasicBlock &BB) const {
return BB.getTerminator()->getMetadata("prof") != nullptr;
}
void
ProfileModule::setBranchFrequency(BasicBlock &BB, std::vector<uint32_t> &Freq) {
MDBuilder MDB(BB.getTerminator()->getContext());
MDNode *Node = MDB.createBranchWeights(Freq);
BB.getTerminator()->setMetadata(LLVMContext::MD_prof, Node);
}
std::vector<uint32_t>
ProfileModule::getBranchFrequency(const BasicBlock &BB) const {
std::vector<uint32_t> Freqs;
auto Terminator = BB.getTerminator();
if (hasBranchFrequency(BB) && Terminator != nullptr) {
int NumOperands =
Terminator->getMetadata("prof")->getNumOperands();
for (int i = 1; i < NumOperands; i++)
Freqs.push_back(cast<ConstantInt>(cast<ConstantAsMetadata>(
Terminator->getMetadata("prof")->getOperand(i))->getValue())
->getSExtValue());
}
return Freqs;
}
bool ProfileModule::hasBasicBlockFrequency(const BasicBlock &BB) const {
return this->BBFreq.count(BB.getName().str()) != 0;
}
uint64_t ProfileModule::getBasicBlockFrequency(const BasicBlock &BB) const {
if (hasBasicBlockFrequency(BB))
return (this->BBFreq.find(BB.getName().str()))->second;
return 0;
}
void
ProfileModule::setBasicBlockFrequency(BasicBlock &BB, uint64_t Freq) {
this->BBFreq[BB.getName().str()] = Freq;
}
bool ProfileModule::hasCallCost(const CallInst &I) const {
return hasID(I) && hasWeight(I);
}
double ProfileModule::getCallCost(const CallInst &I) const {
if (hasCallCost(I))
return getWeight(I);
else return 40;
}
void
ProfileModule::setCallCost(CallInst &I, double Cost) {
setWeight(I, Cost);
}
uint64_t
ProfileModule::getExecutionFreqUsingPredecessors(BasicBlock *BB) {
uint64_t PredecessorsWeight = 0;
for (auto IT = pred_begin(BB), ET = pred_end(BB); IT != ET; ++IT) {
BasicBlock* Predecessor = *IT;
auto Terminator = Predecessor->getTerminator();
if (BB != Predecessor) {
if (isa<BranchInst>(Terminator)) {
if (cast<BranchInst>(Terminator)->isUnconditional()) {
PredecessorsWeight += getBasicBlockFrequency(*Predecessor);
} else {
uint64_t EdgeWeight = getBasicBlockFrequency(*Predecessor);
for (unsigned J = 0; J < Terminator->getNumSuccessors(); ++J) {
auto SuccPred = Terminator->getSuccessor(J);
if (SuccPred != BB) {
if (!hasBasicBlockFrequency(*SuccPred) ||
SuccPred->getUniquePredecessor() == nullptr ||
EdgeWeight < getBasicBlockFrequency(*SuccPred)) {
EdgeWeight = 0;
break;
} else {
EdgeWeight -= getBasicBlockFrequency(*SuccPred);
}
}
}
PredecessorsWeight += EdgeWeight;
}
}
}
}
return PredecessorsWeight;
}
uint64_t
ProfileModule::getExecutionFreqUsingSuccessors(BasicBlock *BB) {
uint64_t SuccessorsWeight = 0;
auto Terminator = BB->getTerminator();
for (unsigned E = 0; E < Terminator->getNumSuccessors(); ++E) {
BasicBlock* Successor = Terminator->getSuccessor(E);
if (BB != Successor) {
if (Successor->getSinglePredecessor() == BB) {
SuccessorsWeight += getBasicBlockFrequency(*Successor);
} else {
uint64_t EdgeWeight = getBasicBlockFrequency(*Successor);
for (auto IT = pred_begin(Successor); IT != pred_end(Successor); ++IT) {
BasicBlock* PredSucc = *IT;
if (PredSucc != BB) {
auto PredSuccTerminator = PredSucc->getTerminator();
if (isa<BranchInst>(PredSuccTerminator) &&
cast<BranchInst>(PredSuccTerminator)->isUnconditional() &&
hasBasicBlockFrequency(*PredSucc) &&
EdgeWeight >= getBasicBlockFrequency(*PredSucc)) {
EdgeWeight -= getBasicBlockFrequency(*PredSucc);
} else {
EdgeWeight = 0;
break;
}
}
}
SuccessorsWeight += EdgeWeight;
}
}
}
return SuccessorsWeight;
}
void ProfileModule::repairFunctionProfiling(Function *Func) {
std::unordered_map<BasicBlock*, bool> HasFreq;
for (auto &BB : *Func)
if (hasBasicBlockFrequency(BB))
HasFreq[&BB] = true;
bool changed = true;
while(changed) {
changed = false;
for (auto &BB : *Func) {
if (HasFreq.count(&BB) == 0) {
uint64_t PredecessorsWeight = getExecutionFreqUsingPredecessors(&BB);
uint64_t SuccessorsWeight = getExecutionFreqUsingSuccessors(&BB);
uint64_t ExecutionFreq = std::max(PredecessorsWeight, SuccessorsWeight);
if (ExecutionFreq > getBasicBlockFrequency(BB) &&
ExecutionFreq != 0) {
setBasicBlockFrequency(BB, ExecutionFreq);
changed = true;
}
}
}
}
}
void ProfileModule::propagateInstToBasicBlock() {
for (auto &Func : *LLVMModule)
for (auto &BBlock : Func) {
if (hasBasicBlockFrequency(BBlock)) continue;
uint64_t Freq = 0;
for (auto &Inst : BBlock)
Freq = (getInstructionFrequency(Inst) > Freq) ?
getInstructionFrequency(Inst) : Freq;
setBasicBlockFrequency(BBlock, Freq);
}
}
void ProfileModule::repairProfiling() {
propagateInstToBasicBlock();
for (auto &Func : *LLVMModule) {
for (auto &BB : Func) {
if (hasBranchFrequency(BB) && getBranchFrequency(BB).size() ==
BB.getTerminator()->getNumSuccessors()) {
auto Frequency = 0;
auto NumSucc = 0;
for (auto &BFreq : getBranchFrequency(BB)) {
Frequency += BFreq;
auto Succ = BB.getTerminator()->getSuccessor(NumSucc);
if (!hasBasicBlockFrequency(*Succ))
setBasicBlockFrequency(*Succ, BFreq);
++NumSucc;
}
setBasicBlockFrequency(BB, Frequency);
}
}
repairFunctionProfiling(&Func);
}
}
ProfileModule* ProfileModule::getCopy() const {
Module *NewModule = CloneModule(getLLVMModule());
return new ProfileModule(NewModule);
}
void ProfileModule::print(const std::string Path) const {
std::error_code Err;
raw_fd_ostream *Out =
new raw_fd_ostream(Path, Err, llvm::sys::fs::OpenFlags::F_RW);
WriteBitcodeToFile(getLLVMModule(), *Out);
Out->flush();
delete Out;
}
ModuleMetric ProfileModule::getMetrics() {
uint64_t N = 0;
uint64_t NI = 0;
uint64_t NF = 0;
uint64_t NEI = 0;
uint64_t NEF = 0;
uint64_t Fu = 0;
uint64_t B = 0;
uint64_t L = 0;
uint64_t MF = 0;
uint64_t MB = 0;
uint32_t ML = 0;
bool R = false;
bool Entry = true;
for (auto &F : *getLLVMModule()) {
++Fu;
Entry = true;
for (auto &BB : F) {
if (Entry) {
MF += getBasicBlockFrequency(BB);
Entry = false;
}
MB += getBasicBlockFrequency(BB);
++B;
for (auto &I : BB) {
++N;
if (I.getType()->isFloatingPointTy()) {
++NF;
NEF += getBasicBlockFrequency(BB);
} else {
++NI;
NEI += getBasicBlockFrequency(BB);
}
if (isa<CallInst>(I)) {
auto CalledFunc = cast<CallInst>(I).getCalledFunction();
if (CalledFunc)
if (CalledFunc->getName() == F.getName())
R = true;
}
auto PredSuccTerminator = BB.getTerminator();
if (isa<BranchInst>(PredSuccTerminator) &&
cast<BranchInst>(PredSuccTerminator)->isUnconditional()) {
++L;
ML += getBasicBlockFrequency(BB);
}
}
}
}
MF /= Fu;
MB /= B;
return ModuleMetric(N, NI, NF, NEI, NEF, Fu, B, L, MF, MB, ML, R);
}
<commit_msg>ProfileModule.cpp: changed to the minimum non-zero value.<commit_after>//===--------- ProfileModule.cpp - The Profile Module -*- C++ -*----------===//
//
// The LLVM Time Cost Analyser Infrastructure
//
// This file is distributed under the MIT License. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains implementation of the ProfileModule, which
/// encapsulate a LLVMModule and its profiling information.
///
//===----------------------------------------------------------------------===//
#include "geos/ProfileModule/ProfileModule.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <limits.h>
using namespace llvm;
bool hasWeight(const Instruction &I) {
return I.getMetadata("Weight") != nullptr;
}
double getWeight(const Instruction &I) {
assert(hasWeight(I) &&
"Trying to get the weight of a Instruction without a weight.");
return std::stod(
cast<MDString>(I.getMetadata("Weight")->getOperand(0))->getString());
}
void setWeight(Instruction &I, double Weight) {
LLVMContext& C = I.getContext();
MDNode* N =
MDNode::get(C, MDString::get(C, std::to_string(Weight)));
I.setMetadata("Weight", N);
}
bool ProfileModule::hasID(const Instruction &I) const {
return I.getMetadata("ID") != nullptr;
}
int ProfileModule::getID(const Instruction &I) {
assert(hasID(I) &&
"Trying to get the ID of an Instruction without an ID.");
return std::stoi(
cast<MDString>(I.getMetadata("ID")->getOperand(0))->getString());
}
void setID(Instruction &I, int ID) {
LLVMContext& C = I.getContext();
MDNode* N =
MDNode::get(C, MDString::get(C, std::to_string(ID)));
I.setMetadata("ID", N);
}
int nC = 0; // Counter to generate CallInst's names
ProfileModule::ProfileModule(Module* M) {
LLVMModule = M;
for (auto &Func : *LLVMModule) {
for (auto &BB : Func) {
for (auto &I : BB)
if (isa<CallInst>(I))
if (cast<CallInst>(I).getCalledFunction() == nullptr ||
cast<CallInst>(I).getCalledFunction()->size() == 0)
setID(I, nC++);
}
}
}
Module* ProfileModule::getLLVMModule() const {
return LLVMModule;
}
bool ProfileModule::hasInstructionFrequency(const Instruction &Inst) const {
return Inst.getMetadata("ifreq") != nullptr;
}
void
ProfileModule::setInstructionFrequency(Instruction &Inst, uint64_t Freq) {
MDBuilder MDB(Inst.getContext());
SmallVector<Metadata*, 4> Val(1);
Type *Int64Ty = Type::getInt64Ty(Inst.getContext());
Val[0] = MDB.createConstant(ConstantInt::get(Int64Ty, Freq));
MDNode *Node = MDNode::get(Inst.getContext(), Val);
Inst.setMetadata("ifreq", Node);
}
uint64_t
ProfileModule::getInstructionFrequency(const Instruction &Inst) const {
uint64_t Freq = 0;
if (hasInstructionFrequency(Inst))
Freq = cast<ConstantInt>(cast<ConstantAsMetadata>(
Inst.getMetadata("ifreq")->getOperand(0))->getValue())
->getSExtValue();
return Freq;
}
bool ProfileModule::hasBranchFrequency(const BasicBlock &BB) const {
return BB.getTerminator()->getMetadata("prof") != nullptr;
}
void
ProfileModule::setBranchFrequency(BasicBlock &BB, std::vector<uint32_t> &Freq) {
MDBuilder MDB(BB.getTerminator()->getContext());
MDNode *Node = MDB.createBranchWeights(Freq);
BB.getTerminator()->setMetadata(LLVMContext::MD_prof, Node);
}
std::vector<uint32_t>
ProfileModule::getBranchFrequency(const BasicBlock &BB) const {
std::vector<uint32_t> Freqs;
auto Terminator = BB.getTerminator();
if (hasBranchFrequency(BB) && Terminator != nullptr) {
int NumOperands =
Terminator->getMetadata("prof")->getNumOperands();
for (int i = 1; i < NumOperands; i++)
Freqs.push_back(cast<ConstantInt>(cast<ConstantAsMetadata>(
Terminator->getMetadata("prof")->getOperand(i))->getValue())
->getSExtValue());
}
return Freqs;
}
bool ProfileModule::hasBasicBlockFrequency(const BasicBlock &BB) const {
return this->BBFreq.count(BB.getName().str()) != 0;
}
uint64_t ProfileModule::getBasicBlockFrequency(const BasicBlock &BB) const {
if (hasBasicBlockFrequency(BB))
return (this->BBFreq.find(BB.getName().str()))->second;
return 0;
}
void
ProfileModule::setBasicBlockFrequency(BasicBlock &BB, uint64_t Freq) {
this->BBFreq[BB.getName().str()] = Freq;
}
bool ProfileModule::hasCallCost(const CallInst &I) const {
return hasID(I) && hasWeight(I);
}
double ProfileModule::getCallCost(const CallInst &I) const {
if (hasCallCost(I))
return getWeight(I);
else return 40;
}
void
ProfileModule::setCallCost(CallInst &I, double Cost) {
setWeight(I, Cost);
}
uint64_t
ProfileModule::getExecutionFreqUsingPredecessors(BasicBlock *BB) {
uint64_t PredecessorsWeight = 0;
for (auto IT = pred_begin(BB), ET = pred_end(BB); IT != ET; ++IT) {
BasicBlock* Predecessor = *IT;
auto Terminator = Predecessor->getTerminator();
if (BB != Predecessor) {
if (isa<BranchInst>(Terminator)) {
if (cast<BranchInst>(Terminator)->isUnconditional()) {
PredecessorsWeight += getBasicBlockFrequency(*Predecessor);
} else {
uint64_t EdgeWeight = getBasicBlockFrequency(*Predecessor);
for (unsigned J = 0; J < Terminator->getNumSuccessors(); ++J) {
auto SuccPred = Terminator->getSuccessor(J);
if (SuccPred != BB) {
if (!hasBasicBlockFrequency(*SuccPred) ||
SuccPred->getUniquePredecessor() == nullptr ||
EdgeWeight < getBasicBlockFrequency(*SuccPred)) {
EdgeWeight = 0;
break;
} else {
EdgeWeight -= getBasicBlockFrequency(*SuccPred);
}
}
}
PredecessorsWeight += EdgeWeight;
}
}
}
}
return PredecessorsWeight;
}
uint64_t
ProfileModule::getExecutionFreqUsingSuccessors(BasicBlock *BB) {
uint64_t SuccessorsWeight = 0;
auto Terminator = BB->getTerminator();
for (unsigned E = 0; E < Terminator->getNumSuccessors(); ++E) {
BasicBlock* Successor = Terminator->getSuccessor(E);
if (BB != Successor) {
if (Successor->getSinglePredecessor() == BB) {
SuccessorsWeight += getBasicBlockFrequency(*Successor);
} else {
uint64_t EdgeWeight = getBasicBlockFrequency(*Successor);
for (auto IT = pred_begin(Successor); IT != pred_end(Successor); ++IT) {
BasicBlock* PredSucc = *IT;
if (PredSucc != BB) {
auto PredSuccTerminator = PredSucc->getTerminator();
if (isa<BranchInst>(PredSuccTerminator) &&
cast<BranchInst>(PredSuccTerminator)->isUnconditional() &&
hasBasicBlockFrequency(*PredSucc) &&
EdgeWeight >= getBasicBlockFrequency(*PredSucc)) {
EdgeWeight -= getBasicBlockFrequency(*PredSucc);
} else {
EdgeWeight = 0;
break;
}
}
}
SuccessorsWeight += EdgeWeight;
}
}
}
return SuccessorsWeight;
}
void ProfileModule::repairFunctionProfiling(Function *Func) {
std::unordered_map<BasicBlock*, bool> HasFreq;
for (auto &BB : *Func)
if (hasBasicBlockFrequency(BB))
HasFreq[&BB] = true;
bool changed = true;
while(changed) {
changed = false;
for (auto &BB : *Func) {
if (HasFreq.count(&BB) == 0) {
uint64_t PredecessorsWeight = getExecutionFreqUsingPredecessors(&BB);
uint64_t SuccessorsWeight = getExecutionFreqUsingSuccessors(&BB);
uint64_t ExecutionFreq = std::max(PredecessorsWeight, SuccessorsWeight);
if (ExecutionFreq > getBasicBlockFrequency(BB) &&
ExecutionFreq != 0) {
setBasicBlockFrequency(BB, ExecutionFreq);
changed = true;
}
}
}
}
}
void ProfileModule::propagateInstToBasicBlock() {
for (auto &Func : *LLVMModule)
for (auto &BBlock : Func) {
if (hasBasicBlockFrequency(BBlock)) continue;
uint64_t Freq = ULLONG_MAX;
for (auto &Inst : BBlock) {
auto instFreq = getInstructionFrequency(Inst);
Freq = (instFreq != 0 && instFreq < Freq) ?
getInstructionFrequency(Inst) : Freq;
}
if (Freq == ULLONG_MAX) Freq = 0;
setBasicBlockFrequency(BBlock, Freq);
}
}
void ProfileModule::repairProfiling() {
propagateInstToBasicBlock();
for (auto &Func : *LLVMModule) {
for (auto &BB : Func) {
if (hasBranchFrequency(BB) && getBranchFrequency(BB).size() ==
BB.getTerminator()->getNumSuccessors()) {
auto Frequency = 0;
auto NumSucc = 0;
for (auto &BFreq : getBranchFrequency(BB)) {
Frequency += BFreq;
auto Succ = BB.getTerminator()->getSuccessor(NumSucc);
if (!hasBasicBlockFrequency(*Succ))
setBasicBlockFrequency(*Succ, BFreq);
++NumSucc;
}
setBasicBlockFrequency(BB, Frequency);
}
}
repairFunctionProfiling(&Func);
}
}
ProfileModule* ProfileModule::getCopy() const {
Module *NewModule = CloneModule(getLLVMModule());
return new ProfileModule(NewModule);
}
void ProfileModule::print(const std::string Path) const {
std::error_code Err;
raw_fd_ostream *Out =
new raw_fd_ostream(Path, Err, llvm::sys::fs::OpenFlags::F_RW);
WriteBitcodeToFile(getLLVMModule(), *Out);
Out->flush();
delete Out;
}
ModuleMetric ProfileModule::getMetrics() {
uint64_t N = 0;
uint64_t NI = 0;
uint64_t NF = 0;
uint64_t NEI = 0;
uint64_t NEF = 0;
uint64_t Fu = 0;
uint64_t B = 0;
uint64_t L = 0;
uint64_t MF = 0;
uint64_t MB = 0;
uint32_t ML = 0;
bool R = false;
bool Entry = true;
for (auto &F : *getLLVMModule()) {
++Fu;
Entry = true;
for (auto &BB : F) {
if (Entry) {
MF += getBasicBlockFrequency(BB);
Entry = false;
}
MB += getBasicBlockFrequency(BB);
++B;
for (auto &I : BB) {
++N;
if (I.getType()->isFloatingPointTy()) {
++NF;
NEF += getBasicBlockFrequency(BB);
} else {
++NI;
NEI += getBasicBlockFrequency(BB);
}
if (isa<CallInst>(I)) {
auto CalledFunc = cast<CallInst>(I).getCalledFunction();
if (CalledFunc)
if (CalledFunc->getName() == F.getName())
R = true;
}
auto PredSuccTerminator = BB.getTerminator();
if (isa<BranchInst>(PredSuccTerminator) &&
cast<BranchInst>(PredSuccTerminator)->isUnconditional()) {
++L;
ML += getBasicBlockFrequency(BB);
}
}
}
}
MF /= Fu;
MB /= B;
return ModuleMetric(N, NI, NF, NEI, NEF, Fu, B, L, MF, MB, ML, R);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2011 Michał Koźmiński <michal.kozminski@gmail.com>
* Copyright (C) 2011 Laszlo Papp <lpapp@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "player.h"
#include "engine.h"
using namespace GluonAudio;
class Player::PlayerPrivate
{
public:
PlayerPrivate()
: sound( new Sound(Engine::instance() ) )
, currentIndex( 0 )
, playerLoop( false )
{
}
~PlayerPrivate()
{
}
QStringList files;
Sound* sound;
int currentIndex;
ALfloat soundVolume;
ALfloat soundPitch;
bool playerLoop;
};
Player::Player(QObject* parent)
: QObject(parent)
, d( new PlayerPrivate )
{
connect(d->sound, SIGNAL( paused() ), SLOT( playNext() ) );
connect(d->sound, SIGNAL( stopped() ), SLOT( playNext() ) );
}
Player( QStringList files, QObject* parent )
: QObject(parent)
, d(new PlayerPrivate)
{
d->files = files;
connect(d->sound, SIGNAL( paused() ), SLOT( playNext() ) );
connect(d->sound, SIGNAL( stopped() ), SLOT( playNext() ) );
}
Player::~Player()
{
}
void Player::removeAt(int index)
{
if( d->files.count()-1 >= index )
d->files.removeAt( index );
}
void Player::append(QString file)
{
d->files.append( file );
}
void Player::insert(int index, QString file)
{
if( d->files.count()-1 > index )
d->files.append(file);
else
d->files.replace( index, file );
}
void Player::removeLast()
{
d->files.removeAt( d->files.size()-1 );
}
void Player::play()
{
d->sound->load( d->files.at( d->currentIndex ) );
d->sound->setVolume(d->soundVolume);
d->sound->play();
}
void Player::playAt(int index)
{
d->currentIndex = index;
d->sound->load(d->files.at(index));
d->sound->setVolume(d->soundVolume);
d->sound->play();
}
void Player::pause()
{
d->sound->pause();
}
void Player::seek(qint64 ms)
{
}
void Player::stop()
{
d->sound->stop();
}
bool Player::isPlaying() const
{
return d->sound->isPlaying();
}
ALfloat Player::pitch() const
{
return d->soundPitch;
}
void Player::setPitch(ALfloat pitch)
{
d->soundPitch = pitch;
d->sound->setPitch(pitch);
}
void Player::setVolume(ALfloat volume)
{
d->soundVolume = volume;
}
ALfloat Player::volume() const
{
return d->soundVolume;
}
void Player::setLoop(bool loop)
{
d->playerLoop = loop;
}
bool Player::isLooping() const
{
return d->playerLoop;
}
void Player::playNext()
{
if( d->files.count()-1 == d->currentIndex )
{
if( d->playerLoop )
{
d->currentIndex = 0;
}
else
{
emit finished();
return;
}
}
else
{
++d->currentIndex;
}
play();
}
QStringList Player::files()
{
return d->files;
}
#include "player.moc"
<commit_msg>Fix the scope of the newly added constructor in the source code<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2011 Michał Koźmiński <michal.kozminski@gmail.com>
* Copyright (C) 2011 Laszlo Papp <lpapp@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "player.h"
#include "engine.h"
using namespace GluonAudio;
class Player::PlayerPrivate
{
public:
PlayerPrivate()
: sound( new Sound(Engine::instance() ) )
, currentIndex( 0 )
, playerLoop( false )
{
}
~PlayerPrivate()
{
}
QStringList files;
Sound* sound;
int currentIndex;
ALfloat soundVolume;
ALfloat soundPitch;
bool playerLoop;
};
Player::Player(QObject* parent)
: QObject(parent)
, d( new PlayerPrivate )
{
connect(d->sound, SIGNAL( paused() ), SLOT( playNext() ) );
connect(d->sound, SIGNAL( stopped() ), SLOT( playNext() ) );
}
Player::Player( QStringList files, QObject* parent )
: QObject(parent)
, d(new PlayerPrivate)
{
d->files = files;
connect(d->sound, SIGNAL( paused() ), SLOT( playNext() ) );
connect(d->sound, SIGNAL( stopped() ), SLOT( playNext() ) );
}
Player::~Player()
{
}
void Player::removeAt(int index)
{
if( d->files.count()-1 >= index )
d->files.removeAt( index );
}
void Player::append(QString file)
{
d->files.append( file );
}
void Player::insert(int index, QString file)
{
if( d->files.count()-1 > index )
d->files.append(file);
else
d->files.replace( index, file );
}
void Player::removeLast()
{
d->files.removeAt( d->files.size()-1 );
}
void Player::play()
{
d->sound->load( d->files.at( d->currentIndex ) );
d->sound->setVolume(d->soundVolume);
d->sound->play();
}
void Player::playAt(int index)
{
d->currentIndex = index;
d->sound->load(d->files.at(index));
d->sound->setVolume(d->soundVolume);
d->sound->play();
}
void Player::pause()
{
d->sound->pause();
}
void Player::seek(qint64 ms)
{
}
void Player::stop()
{
d->sound->stop();
}
bool Player::isPlaying() const
{
return d->sound->isPlaying();
}
ALfloat Player::pitch() const
{
return d->soundPitch;
}
void Player::setPitch(ALfloat pitch)
{
d->soundPitch = pitch;
d->sound->setPitch(pitch);
}
void Player::setVolume(ALfloat volume)
{
d->soundVolume = volume;
}
ALfloat Player::volume() const
{
return d->soundVolume;
}
void Player::setLoop(bool loop)
{
d->playerLoop = loop;
}
bool Player::isLooping() const
{
return d->playerLoop;
}
void Player::playNext()
{
if( d->files.count()-1 == d->currentIndex )
{
if( d->playerLoop )
{
d->currentIndex = 0;
}
else
{
emit finished();
return;
}
}
else
{
++d->currentIndex;
}
play();
}
QStringList Player::files()
{
return d->files;
}
#include "player.moc"
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <gl_wrapper/gl_wrapper.hpp>
#include <gl_wrapper/object/x_hand.hpp>
#include <gl_wrapper/exception/exceptions.hpp>
using namespace gl_wrapper;
void display()
{
try
{
Render::start();
Render::LIGHT->on();
static double t = 0.0;
t += 0.03333;
GLfloat amb[4] = {0.25f, 0.20f, 0.07f, 1.f};
GLfloat dif[4] = {0.75f, 0.61f, 0.23f, 1.f};
GLfloat spe[4] = {0.63f, 0.56f, 0.37f, 1.f};
GLfloat shine = 51.2f;
glTranslated(0.0, 1.0, 0.0);
glRotated(90.0, 1.0, 0.0, 0.0);
Material::setMaterial(amb, dif, spe, shine);
glutSolidTeapot(0.1);
std::string path = "/home/daichi/Work/catkin_ws/src/ahl_ros_pkg/utils/gl_wrapper/blender/";
static XObjectPtr lwr1 = XObjectPtr(new XObject(path + "lwr07.x"));
static XObjectPtr lwr2 = XObjectPtr(new XObject(path + "lwr07.x"));
static XObjectPtr lwr3 = XObjectPtr(new XObject(path + "lwr07.x"));
static SimpleObjectPtr grid = SimpleObjectPtr(new Grid(20, 20, 0.5));
lwr1->setEulerZYX(std::string("Link01"), M_PI * std::sin(2.0 * M_PI * 0.1 * t), 0.0, 0.0);
lwr1->setEulerZYX(std::string("Link02"), 0.0, 0.35 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr1->setEulerZYX(std::string("Link03"), 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0, 0.0);
lwr1->setEulerZYX(std::string("Link04"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0);
lwr1->setEulerZYX(std::string("Link05"), 0.4 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0, 0.0);
lwr1->setEulerZYX(std::string("Link06"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr1->setEulerZYX(std::string("EndEffector"), M_PI * std::sin(2.0 * M_PI * 0.6 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link01"), M_PI * std::sin(2.0 * M_PI * 0.1 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link02"), 0.0, 0.35 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr2->setEulerZYX(std::string("Link03"), 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link04"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0);
lwr2->setEulerZYX(std::string("Link05"), 0.4 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link06"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr2->setEulerZYX(std::string("EndEffector"), M_PI * std::sin(2.0 * M_PI * 0.6 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link01"), M_PI * std::sin(2.0 * M_PI * 0.1 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link02"), 0.0, 0.35 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr3->setEulerZYX(std::string("Link03"), 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link04"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0);
lwr3->setEulerZYX(std::string("Link05"), 0.4 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link06"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr3->setEulerZYX(std::string("EndEffector"), M_PI * std::sin(2.0 * M_PI * 0.6 * t), 0.0, 0.0);
glLoadIdentity();
lwr1->display();
glLoadIdentity();
glTranslated(0.0, -0.6, 0.0);
lwr2->display();
glLoadIdentity();
glTranslated(0.0, -1.2, 0.0);
lwr3->display();
glLoadIdentity();
grid->setColor(0, 0, 255);
grid->setPosition(0.0, 0.0, 0.0);
grid->display();
/*
gl_wrapper::RightHandPtr right_hand;
right_hand = RightHandPtr(new RightHand("/home/daichi/work/catkin_ws/src/gl_wrapper/righthand.cfg"));
right_hand->display();
*/
Render::end();
}
catch(Exception& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(FatalException& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(std::exception& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(...)
{
ROS_ERROR_STREAM("display : Unknown exception was thrown.");
exit(1);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "gl_wrapper_test");
ros::NodeHandle nh;
try
{
RenderPtr render;
render = RenderPtr(new Render(argc, argv));
render->start(display);
}
catch(FatalException& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(Exception& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(...)
{
ROS_ERROR_STREAM("Unknown exception was thrown.");
exit(1);
}
return 0;
}
<commit_msg>Modified path of blender's file.<commit_after>#include <ros/ros.h>
#include <gl_wrapper/gl_wrapper.hpp>
#include <gl_wrapper/object/x_hand.hpp>
#include <gl_wrapper/exception/exceptions.hpp>
using namespace gl_wrapper;
void display()
{
try
{
Render::start();
Render::LIGHT->on();
static double t = 0.0;
t += 0.03333;
GLfloat amb[4] = {0.25f, 0.20f, 0.07f, 1.f};
GLfloat dif[4] = {0.75f, 0.61f, 0.23f, 1.f};
GLfloat spe[4] = {0.63f, 0.56f, 0.37f, 1.f};
GLfloat shine = 51.2f;
glTranslated(0.0, 1.0, 0.0);
glRotated(90.0, 1.0, 0.0, 0.0);
Material::setMaterial(amb, dif, spe, shine);
glutSolidTeapot(0.1);
std::string path = "/home/daichi/Work/catkin_ws/src/ahl_ros_pkgs/ahl_common/wrapper/gl_wrapper/blender/";
static XObjectPtr lwr1 = XObjectPtr(new XObject(path + "lwr07.x"));
static XObjectPtr lwr2 = XObjectPtr(new XObject(path + "lwr07.x"));
static XObjectPtr lwr3 = XObjectPtr(new XObject(path + "lwr07.x"));
static SimpleObjectPtr grid = SimpleObjectPtr(new Grid(20, 20, 0.5));
lwr1->setEulerZYX(std::string("Link01"), M_PI * std::sin(2.0 * M_PI * 0.1 * t), 0.0, 0.0);
lwr1->setEulerZYX(std::string("Link02"), 0.0, 0.35 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr1->setEulerZYX(std::string("Link03"), 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0, 0.0);
lwr1->setEulerZYX(std::string("Link04"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0);
lwr1->setEulerZYX(std::string("Link05"), 0.4 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0, 0.0);
lwr1->setEulerZYX(std::string("Link06"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr1->setEulerZYX(std::string("EndEffector"), M_PI * std::sin(2.0 * M_PI * 0.6 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link01"), M_PI * std::sin(2.0 * M_PI * 0.1 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link02"), 0.0, 0.35 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr2->setEulerZYX(std::string("Link03"), 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link04"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0);
lwr2->setEulerZYX(std::string("Link05"), 0.4 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0, 0.0);
lwr2->setEulerZYX(std::string("Link06"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr2->setEulerZYX(std::string("EndEffector"), M_PI * std::sin(2.0 * M_PI * 0.6 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link01"), M_PI * std::sin(2.0 * M_PI * 0.1 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link02"), 0.0, 0.35 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr3->setEulerZYX(std::string("Link03"), 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link04"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.2 * t), 0.0);
lwr3->setEulerZYX(std::string("Link05"), 0.4 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0, 0.0);
lwr3->setEulerZYX(std::string("Link06"), 0.0, 0.5 * M_PI * std::sin(2.0 * M_PI * 0.3 * t), 0.0);
lwr3->setEulerZYX(std::string("EndEffector"), M_PI * std::sin(2.0 * M_PI * 0.6 * t), 0.0, 0.0);
glLoadIdentity();
lwr1->display();
glLoadIdentity();
glTranslated(0.0, -0.6, 0.0);
lwr2->display();
glLoadIdentity();
glTranslated(0.0, -1.2, 0.0);
lwr3->display();
glLoadIdentity();
grid->setColor(0, 0, 255);
grid->setPosition(0.0, 0.0, 0.0);
grid->display();
/*
gl_wrapper::RightHandPtr right_hand;
right_hand = RightHandPtr(new RightHand("/home/daichi/work/catkin_ws/src/gl_wrapper/righthand.cfg"));
right_hand->display();
*/
Render::end();
}
catch(Exception& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(FatalException& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(std::exception& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(...)
{
ROS_ERROR_STREAM("display : Unknown exception was thrown.");
exit(1);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "gl_wrapper_test");
ros::NodeHandle nh;
try
{
RenderPtr render;
render = RenderPtr(new Render(argc, argv));
render->start(display);
}
catch(FatalException& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(Exception& e)
{
ROS_ERROR_STREAM(e.what());
exit(1);
}
catch(...)
{
ROS_ERROR_STREAM("Unknown exception was thrown.");
exit(1);
}
return 0;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// VoxelTest Main.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Time/Clock.h"
#include "glm/gtc/matrix_transform.hpp"
#include "shaders.h"
#include "GeomPool.h"
#include "GeomMesher.h"
using namespace Oryol;
class VoxelTest : public App {
public:
AppState::Code OnInit();
AppState::Code OnRunning();
AppState::Code OnCleanup();
void update_camera();
void init_blocks(int frameIndex);
void bake_geom(const GeomMesher::Result& meshResult);
int32 frameIndex = 0;
glm::mat4 view;
glm::mat4 proj;
glm::vec3 lightDir;
ClearState clearState;
GeomPool geomPool;
GeomMesher geomMesher;
Array<int> displayGeoms;
static const int WorldSizeX = 256;
static const int WorldSizeY = 256;
static const int WorldSizeZ = 8;
static const int VolumeSizeX = 64;
static const int VolumeSizeY = 64;
static const int VolumeSizeZ = WorldSizeZ;
static const int NumBlockTypes = 32;
uint8 blocks[WorldSizeX][WorldSizeY][WorldSizeZ];
};
OryolMain(VoxelTest);
//------------------------------------------------------------------------------
AppState::Code
VoxelTest::OnInit() {
auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Voxel Test");
Gfx::Setup(gfxSetup);
this->clearState = ClearState::ClearAll(glm::vec4(0.5f, 0.5f, 0.5f, 1.0f), 1.0f, 0);
const float32 fbWidth = (const float32) Gfx::DisplayAttrs().FramebufferWidth;
const float32 fbHeight = (const float32) Gfx::DisplayAttrs().FramebufferHeight;
this->proj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.1f, 1000.0f);
this->view = glm::lookAt(glm::vec3(0.0f, 2.5f, 0.0f), glm::vec3(0.0f, 0.0f, -10.0f), glm::vec3(0.0f, 1.0f, 0.0f));
this->lightDir = glm::normalize(glm::vec3(1.0f, 1.0f, 1.0f));
this->displayGeoms.Reserve(256);
this->geomPool.Setup(gfxSetup);
this->geomMesher.Setup();
this->init_blocks(0);
return App::OnInit();
}
//------------------------------------------------------------------------------
void
VoxelTest::bake_geom(const GeomMesher::Result& meshResult) {
if (meshResult.NumQuads > 0) {
int geomIndex = this->geomPool.Alloc();
auto& geom = this->geomPool.GeomAt(geomIndex);
Gfx::UpdateVertices(geom.Mesh, meshResult.Vertices, meshResult.NumBytes);
geom.NumQuads = meshResult.NumQuads;
geom.VSParams.ModelViewProjection = this->proj * this->view;
geom.VSParams.Model = glm::mat4();
geom.VSParams.LightDir = this->lightDir;
geom.VSParams.Scale = meshResult.Scale;
geom.VSParams.Translate = meshResult.Translate;
geom.VSParams.TexTranslate = meshResult.TexTranslate;
this->displayGeoms.Add(geomIndex);
}
}
//------------------------------------------------------------------------------
AppState::Code
VoxelTest::OnRunning() {
this->frameIndex++;
this->update_camera();
this->displayGeoms.Clear();
this->geomPool.FreeAll();
Gfx::ApplyDefaultRenderTarget(this->clearState);
Volume vol;
vol.Blocks = &(this->blocks[0][0][0]);
vol.ArraySize.x = WorldSizeX;
vol.ArraySize.y = WorldSizeY;
vol.ArraySize.z = WorldSizeZ;
vol.Size.x = VolumeSizeX;
vol.Size.y = VolumeSizeY;
vol.Size.z = VolumeSizeZ;
const int numChunksX = WorldSizeX / VolumeSizeX;
const int numChunksY = WorldSizeY / VolumeSizeY;
const int numChunksZ = WorldSizeZ / VolumeSizeZ;
GeomMesher::Result meshResult;
this->init_blocks(this->frameIndex);
this->geomMesher.Start();
for (int x = 0; x < numChunksX; x++) {
vol.Offset.x = x * VolumeSizeX;
for (int y = 0; y < numChunksY; y++) {
vol.Offset.y = y * VolumeSizeY;
for (int z = 0; z < numChunksZ; z++) {
vol.Offset.z = z * VolumeSizeZ;
this->geomMesher.StartVolume(vol);
do {
meshResult = this->geomMesher.Meshify();
if (meshResult.BufferFull) {
this->bake_geom(meshResult);
}
}
while (!meshResult.VolumeDone);
}
}
}
this->bake_geom(meshResult);
const int numGeoms = this->displayGeoms.Size();
for (int i = 0; i < numGeoms; i++) {
const Geom& geom = this->geomPool.GeomAt(this->displayGeoms[i]);
Gfx::ApplyDrawState(geom.DrawState);
Gfx::ApplyUniformBlock(geom.VSParams);
Gfx::Draw(PrimitiveGroup(0, geom.NumQuads*6));
}
Gfx::CommitFrame();
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
VoxelTest::OnCleanup() {
this->geomMesher.Discard();
this->geomPool.Discard();
Gfx::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
void
VoxelTest::init_blocks(int index) {
Memory::Clear(this->blocks, sizeof(this->blocks));
for (int x = 1; x < WorldSizeX-1; x++) {
for (int y = 1; y < WorldSizeY-1; y++) {
for (int z = 1; z < WorldSizeZ-1; z++) {
if ((z <= ((x+index)&7)) && (z <= (y&7))) {
uint8 blockType = (z+y+1) & (NumBlockTypes-1);;
this->blocks[x][y][z] = blockType;
}
}
}
}
}
//------------------------------------------------------------------------------
void
VoxelTest::update_camera() {
float32 angle = this->frameIndex * 0.005f;
const glm::vec3 center(128.0f, 0.0f, 128.0f);
const glm::vec3 viewerPos(sin(angle)* 100.0f, 25.0f, cos(angle) * 100.0f);
this->view = glm::lookAt(viewerPos + center, center, glm::vec3(0.0f, 1.0f, 0.0f));
}
<commit_msg>Fill voxel world with simplex noise<commit_after>//------------------------------------------------------------------------------
// VoxelTest Main.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Time/Clock.h"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/noise.hpp"
#include "shaders.h"
#include "GeomPool.h"
#include "GeomMesher.h"
using namespace Oryol;
class VoxelTest : public App {
public:
AppState::Code OnInit();
AppState::Code OnRunning();
AppState::Code OnCleanup();
void update_camera();
void init_blocks(int frameIndex);
void bake_geom(const GeomMesher::Result& meshResult);
int32 frameIndex = 0;
glm::mat4 view;
glm::mat4 proj;
glm::vec3 lightDir;
ClearState clearState;
GeomPool geomPool;
GeomMesher geomMesher;
Array<int> displayGeoms;
static const int WorldSizeX = 256;
static const int WorldSizeY = 256;
static const int WorldSizeZ = 32;
static const int VolumeSizeX = 64;
static const int VolumeSizeY = 64;
static const int VolumeSizeZ = WorldSizeZ;
static const int NumBlockTypes = 32;
uint8 blocks[WorldSizeX][WorldSizeY][WorldSizeZ];
};
OryolMain(VoxelTest);
//------------------------------------------------------------------------------
AppState::Code
VoxelTest::OnInit() {
auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, "Oryol Voxel Test");
Gfx::Setup(gfxSetup);
this->clearState = ClearState::ClearAll(glm::vec4(0.5f, 0.5f, 0.5f, 1.0f), 1.0f, 0);
const float32 fbWidth = (const float32) Gfx::DisplayAttrs().FramebufferWidth;
const float32 fbHeight = (const float32) Gfx::DisplayAttrs().FramebufferHeight;
this->proj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.1f, 1000.0f);
this->view = glm::lookAt(glm::vec3(0.0f, 2.5f, 0.0f), glm::vec3(0.0f, 0.0f, -10.0f), glm::vec3(0.0f, 1.0f, 0.0f));
this->lightDir = glm::normalize(glm::vec3(1.0f, 1.0f, 1.0f));
this->displayGeoms.Reserve(256);
this->geomPool.Setup(gfxSetup);
this->geomMesher.Setup();
return App::OnInit();
}
//------------------------------------------------------------------------------
void
VoxelTest::bake_geom(const GeomMesher::Result& meshResult) {
if (meshResult.NumQuads > 0) {
int geomIndex = this->geomPool.Alloc();
auto& geom = this->geomPool.GeomAt(geomIndex);
Gfx::UpdateVertices(geom.Mesh, meshResult.Vertices, meshResult.NumBytes);
geom.NumQuads = meshResult.NumQuads;
geom.VSParams.Model = glm::mat4();
geom.VSParams.LightDir = this->lightDir;
geom.VSParams.Scale = meshResult.Scale;
geom.VSParams.Translate = meshResult.Translate;
geom.VSParams.TexTranslate = meshResult.TexTranslate;
this->displayGeoms.Add(geomIndex);
}
}
//------------------------------------------------------------------------------
AppState::Code
VoxelTest::OnRunning() {
this->frameIndex++;
this->update_camera();
Gfx::ApplyDefaultRenderTarget(this->clearState);
if (1 == this->frameIndex) {
this->displayGeoms.Clear();
this->geomPool.FreeAll();
Volume vol;
vol.Blocks = &(this->blocks[0][0][0]);
vol.ArraySize.x = WorldSizeX;
vol.ArraySize.y = WorldSizeY;
vol.ArraySize.z = WorldSizeZ;
vol.Size.x = VolumeSizeX;
vol.Size.y = VolumeSizeY;
vol.Size.z = VolumeSizeZ;
const int numChunksX = WorldSizeX / VolumeSizeX;
const int numChunksY = WorldSizeY / VolumeSizeY;
const int numChunksZ = WorldSizeZ / VolumeSizeZ;
GeomMesher::Result meshResult;
this->init_blocks(this->frameIndex);
this->geomMesher.Start();
for (int x = 0; x < numChunksX; x++) {
vol.Offset.x = x * VolumeSizeX;
for (int y = 0; y < numChunksY; y++) {
vol.Offset.y = y * VolumeSizeY;
for (int z = 0; z < numChunksZ; z++) {
vol.Offset.z = z * VolumeSizeZ;
this->geomMesher.StartVolume(vol);
do {
meshResult = this->geomMesher.Meshify();
if (meshResult.BufferFull) {
this->bake_geom(meshResult);
}
}
while (!meshResult.VolumeDone);
}
}
}
this->bake_geom(meshResult);
}
const glm::mat4 mvp = this->proj * this->view;
const int numGeoms = this->displayGeoms.Size();
for (int i = 0; i < numGeoms; i++) {
Geom& geom = this->geomPool.GeomAt(this->displayGeoms[i]);
geom.VSParams.ModelViewProjection = mvp;
Gfx::ApplyDrawState(geom.DrawState);
Gfx::ApplyUniformBlock(geom.VSParams);
Gfx::Draw(PrimitiveGroup(0, geom.NumQuads*6));
}
Gfx::CommitFrame();
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
VoxelTest::OnCleanup() {
this->geomMesher.Discard();
this->geomPool.Discard();
Gfx::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
void
VoxelTest::init_blocks(int index) {
Memory::Clear(this->blocks, sizeof(this->blocks));
const float dx = 1.0f / float(WorldSizeX);
const float dy = 1.0f / float(WorldSizeY);
glm::vec2 p(dx, dy);
for (int x = 1; x < WorldSizeX-1; x++, p.x+=dx) {
p.y = dy;
for (int y = 1; y < WorldSizeY-1; y++, p.y+=dy) {
float n = (glm::simplex(p) + 1.0f) * 0.5f;
n += glm::simplex(p * 10.0f) * 0.3;
n += glm::simplex(p * 40.0f) * 0.1;
n = glm::clamp(n, 0.0f, 1.0f);
const int max_z = 1 + (WorldSizeZ-2)*n;
for (int z = 1; z < max_z; z++) {
this->blocks[x][y][z] = z;
}
}
}
/*
for (int x = 1; x < WorldSizeX-1; x++) {
for (int y = 1; y < WorldSizeY-1; y++) {
for (int z = 1; z < WorldSizeZ-1; z++) {
if ((z <= ((x+index)&7)) && (z <= (y&7))) {
uint8 blockType = (z+y+1) & (NumBlockTypes-1);;
this->blocks[x][y][z] = blockType;
}
}
}
}
*/
}
//------------------------------------------------------------------------------
void
VoxelTest::update_camera() {
float32 angle = this->frameIndex * 0.005f;
const glm::vec3 center(128.0f, 0.0f, 128.0f);
const glm::vec3 viewerPos(sin(angle)* 200.0f, 75.0f, cos(angle) * 200.0f);
this->view = glm::lookAt(viewerPos + center, center, glm::vec3(0.0f, 1.0f, 0.0f));
}
<|endoftext|> |
<commit_before>#include "TerrainTile.h"
#include "JsonHelper.h"
#include "QGCMapEngine.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDataStream>
QGC_LOGGING_CATEGORY(TerrainTileLog, "TerrainTileLog")
const char* TerrainTile::_jsonStatusKey = "status";
const char* TerrainTile::_jsonDataKey = "data";
const char* TerrainTile::_jsonBoundsKey = "bounds";
const char* TerrainTile::_jsonSouthWestKey = "sw";
const char* TerrainTile::_jsonNorthEastKey = "ne";
const char* TerrainTile::_jsonStatsKey = "stats";
const char* TerrainTile::_jsonMaxElevationKey = "max";
const char* TerrainTile::_jsonMinElevationKey = "min";
const char* TerrainTile::_jsonAvgElevationKey = "avg";
const char* TerrainTile::_jsonCarpetKey = "carpet";
TerrainTile::TerrainTile()
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
}
TerrainTile::~TerrainTile()
{
if (_data) {
for (int i = 0; i < _gridSizeLat; i++) {
delete _data[i];
}
delete _data;
_data = NULL;
}
}
TerrainTile::TerrainTile(QByteArray byteArray)
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
QDataStream stream(byteArray);
float lat,lon;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lat;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lon;
_southWest.setLatitude(lat);
_southWest.setLongitude(lon);
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lat;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lon;
_northEast.setLatitude(lat);
_northEast.setLongitude(lon);
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _minElevation;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _maxElevation;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _avgElevation;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _gridSizeLat;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _gridSizeLon;
qCDebug(TerrainTileLog) << "Loading terrain tile: " << _southWest << " - " << _northEast;
qCDebug(TerrainTileLog) << "min:max:avg:sizeLat:sizeLon" << _minElevation << _maxElevation << _avgElevation << _gridSizeLat << _gridSizeLon;
for (int i = 0; i < _gridSizeLat; i++) {
if (i == 0) {
_data = new int16_t*[_gridSizeLat];
for (int k = 0; k < _gridSizeLat; k++) {
_data[k] = new int16_t[_gridSizeLon];
}
}
for (int j = 0; j < _gridSizeLon; j++) {
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _data[i][j];
}
}
_isValid = true;
}
bool TerrainTile::isIn(const QGeoCoordinate& coordinate) const
{
if (!_isValid) {
qCDebug(TerrainTileLog) << "isIn requested, but tile not valid";
return false;
}
bool ret = coordinate.latitude() >= _southWest.latitude() && coordinate.longitude() >= _southWest.longitude() &&
coordinate.latitude() <= _northEast.latitude() && coordinate.longitude() <= _northEast.longitude();
qCDebug(TerrainTileLog) << "Checking isIn: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
return ret;
}
double TerrainTile::elevation(const QGeoCoordinate& coordinate) const
{
if (_isValid) {
qCDebug(TerrainTileLog) << "elevation: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast;
// Get the index at resolution of 1 arc second
int indexLat = _latToDataIndex(coordinate.latitude());
int indexLon = _lonToDataIndex(coordinate.longitude());
if (indexLat == -1 || indexLon == -1) {
qCWarning(TerrainTileLog) << "Internal error indexLat:indexLon == -1" << indexLat << indexLon;
return -1.0;
}
qCDebug(TerrainTileLog) << "indexLat:indexLon" << indexLat << indexLon << "elevation" << _data[indexLat][indexLon];
return static_cast<double>(_data[indexLat][indexLon]);
} else {
qCDebug(TerrainTileLog) << "Asking for elevation, but no valid data.";
return -1.0;
}
}
QGeoCoordinate TerrainTile::centerCoordinate(void) const
{
return _southWest.atDistanceAndAzimuth(_southWest.distanceTo(_northEast) / 2.0, _southWest.azimuthTo(_northEast));
}
QByteArray TerrainTile::serialize(QByteArray input)
{
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(input, &parseError);
if (parseError.error != QJsonParseError::NoError) {
QByteArray emptyArray;
return emptyArray;
}
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
if (!document.isObject()) {
qCDebug(TerrainTileLog) << "Terrain tile json doc is no object";
QByteArray emptyArray;
return emptyArray;
}
QJsonObject rootObject = document.object();
QString errorString;
QList<JsonHelper::KeyValidateInfo> rootVersionKeyInfoList = {
{ _jsonStatusKey, QJsonValue::String, true },
{ _jsonDataKey, QJsonValue::Object, true },
};
if (!JsonHelper::validateKeys(rootObject, rootVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
if (rootObject[_jsonStatusKey].toString() != "success") {
qCDebug(TerrainTileLog) << "Invalid terrain tile.";
QByteArray emptyArray;
return emptyArray;
}
const QJsonObject& dataObject = rootObject[_jsonDataKey].toObject();
QList<JsonHelper::KeyValidateInfo> dataVersionKeyInfoList = {
{ _jsonBoundsKey, QJsonValue::Object, true },
{ _jsonStatsKey, QJsonValue::Object, true },
{ _jsonCarpetKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(dataObject, dataVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
// Bounds
const QJsonObject& boundsObject = dataObject[_jsonBoundsKey].toObject();
QList<JsonHelper::KeyValidateInfo> boundsVersionKeyInfoList = {
{ _jsonSouthWestKey, QJsonValue::Array, true },
{ _jsonNorthEastKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(boundsObject, boundsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
const QJsonArray& swArray = boundsObject[_jsonSouthWestKey].toArray();
const QJsonArray& neArray = boundsObject[_jsonNorthEastKey].toArray();
if (swArray.count() < 2 || neArray.count() < 2 ) {
qCDebug(TerrainTileLog) << "Incomplete bounding location";
QByteArray emptyArray;
return emptyArray;
}
stream << static_cast<float>(swArray[0].toDouble());
stream << static_cast<float>(swArray[1].toDouble());
stream << static_cast<float>(neArray[0].toDouble());
stream << static_cast<float>(neArray[1].toDouble());
// Stats
const QJsonObject& statsObject = dataObject[_jsonStatsKey].toObject();
QList<JsonHelper::KeyValidateInfo> statsVersionKeyInfoList = {
{ _jsonMinElevationKey, QJsonValue::Double, true },
{ _jsonMaxElevationKey, QJsonValue::Double, true },
{ _jsonAvgElevationKey, QJsonValue::Double, true },
};
if (!JsonHelper::validateKeys(statsObject, statsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
stream << static_cast<int16_t>(statsObject[_jsonMinElevationKey].toInt());
stream << static_cast<int16_t>(statsObject[_jsonMaxElevationKey].toInt());
stream << static_cast<float>(statsObject[_jsonAvgElevationKey].toDouble());
// Carpet
const QJsonArray& carpetArray = dataObject[_jsonCarpetKey].toArray();
int gridSizeLat = carpetArray.count();
stream << static_cast<int16_t>(gridSizeLat);
int gridSizeLon = 0;
qCDebug(TerrainTileLog) << "Received tile has size in latitude direction: " << carpetArray.count();
for (int i = 0; i < gridSizeLat; i++) {
const QJsonArray& row = carpetArray[i].toArray();
if (i == 0) {
gridSizeLon = row.count();
stream << static_cast<int16_t>(gridSizeLon);
qCDebug(TerrainTileLog) << "Received tile has size in longitued direction: " << row.count();
}
if (row.count() < gridSizeLon) {
qCDebug(TerrainTileLog) << "Expected row array of " << gridSizeLon << ", instead got " << row.count();
QByteArray emptyArray;
return emptyArray;
}
for (int j = 0; j < gridSizeLon; j++) {
stream << static_cast<int16_t>(row[j].toDouble());
}
}
return byteArray;
}
int TerrainTile::_latToDataIndex(double latitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((latitude - _southWest.latitude()) / (_northEast.latitude() - _southWest.latitude()) * (_gridSizeLat - 1));
} else {
return -1;
}
}
int TerrainTile::_lonToDataIndex(double longitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((longitude - _southWest.longitude()) / (_northEast.longitude() - _southWest.longitude()) * (_gridSizeLon - 1));
} else {
return -1;
}
}
<commit_msg><commit_after>#include "TerrainTile.h"
#include "JsonHelper.h"
#include "QGCMapEngine.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDataStream>
QGC_LOGGING_CATEGORY(TerrainTileLog, "TerrainTileLog")
const char* TerrainTile::_jsonStatusKey = "status";
const char* TerrainTile::_jsonDataKey = "data";
const char* TerrainTile::_jsonBoundsKey = "bounds";
const char* TerrainTile::_jsonSouthWestKey = "sw";
const char* TerrainTile::_jsonNorthEastKey = "ne";
const char* TerrainTile::_jsonStatsKey = "stats";
const char* TerrainTile::_jsonMaxElevationKey = "max";
const char* TerrainTile::_jsonMinElevationKey = "min";
const char* TerrainTile::_jsonAvgElevationKey = "avg";
const char* TerrainTile::_jsonCarpetKey = "carpet";
TerrainTile::TerrainTile()
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
}
TerrainTile::~TerrainTile()
{
if (_data) {
for (int i = 0; i < _gridSizeLat; i++) {
delete _data[i];
}
delete _data;
_data = NULL;
}
}
TerrainTile::TerrainTile(QByteArray byteArray)
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
QDataStream stream(byteArray);
float lat,lon;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lat;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lon;
_southWest.setLatitude(lat);
_southWest.setLongitude(lon);
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lat;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> lon;
_northEast.setLatitude(lat);
_northEast.setLongitude(lon);
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _minElevation;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _maxElevation;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _avgElevation;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _gridSizeLat;
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _gridSizeLon;
qCDebug(TerrainTileLog) << "Loading terrain tile: " << _southWest << " - " << _northEast;
qCDebug(TerrainTileLog) << "min:max:avg:sizeLat:sizeLon" << _minElevation << _maxElevation << _avgElevation << _gridSizeLat << _gridSizeLon;
for (int i = 0; i < _gridSizeLat; i++) {
if (i == 0) {
_data = new int16_t*[_gridSizeLat];
for (int k = 0; k < _gridSizeLat; k++) {
_data[k] = new int16_t[_gridSizeLon];
}
}
for (int j = 0; j < _gridSizeLon; j++) {
if (stream.atEnd()) {
qWarning() << "Terrain tile binary data does not contain all data";
return;
}
stream >> _data[i][j];
}
}
_isValid = true;
}
bool TerrainTile::isIn(const QGeoCoordinate& coordinate) const
{
if (!_isValid) {
qCWarning(TerrainTileLog) << "isIn requested, but tile not valid";
return false;
}
bool ret = coordinate.latitude() >= _southWest.latitude() && coordinate.longitude() >= _southWest.longitude() &&
coordinate.latitude() <= _northEast.latitude() && coordinate.longitude() <= _northEast.longitude();
qCDebug(TerrainTileLog) << "Checking isIn: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
return ret;
}
double TerrainTile::elevation(const QGeoCoordinate& coordinate) const
{
if (_isValid) {
qCDebug(TerrainTileLog) << "elevation: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast;
// Get the index at resolution of 1 arc second
int indexLat = _latToDataIndex(coordinate.latitude());
int indexLon = _lonToDataIndex(coordinate.longitude());
if (indexLat == -1 || indexLon == -1) {
qCWarning(TerrainTileLog) << "Internal error indexLat:indexLon == -1" << indexLat << indexLon;
return -1.0;
}
qCDebug(TerrainTileLog) << "indexLat:indexLon" << indexLat << indexLon << "elevation" << _data[indexLat][indexLon];
return static_cast<double>(_data[indexLat][indexLon]);
} else {
qCWarning(TerrainTileLog) << "Asking for elevation, but no valid data.";
return -1.0;
}
}
QGeoCoordinate TerrainTile::centerCoordinate(void) const
{
return _southWest.atDistanceAndAzimuth(_southWest.distanceTo(_northEast) / 2.0, _southWest.azimuthTo(_northEast));
}
QByteArray TerrainTile::serialize(QByteArray input)
{
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(input, &parseError);
if (parseError.error != QJsonParseError::NoError) {
QByteArray emptyArray;
return emptyArray;
}
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
if (!document.isObject()) {
qCDebug(TerrainTileLog) << "Terrain tile json doc is no object";
QByteArray emptyArray;
return emptyArray;
}
QJsonObject rootObject = document.object();
QString errorString;
QList<JsonHelper::KeyValidateInfo> rootVersionKeyInfoList = {
{ _jsonStatusKey, QJsonValue::String, true },
{ _jsonDataKey, QJsonValue::Object, true },
};
if (!JsonHelper::validateKeys(rootObject, rootVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
if (rootObject[_jsonStatusKey].toString() != "success") {
qCDebug(TerrainTileLog) << "Invalid terrain tile.";
QByteArray emptyArray;
return emptyArray;
}
const QJsonObject& dataObject = rootObject[_jsonDataKey].toObject();
QList<JsonHelper::KeyValidateInfo> dataVersionKeyInfoList = {
{ _jsonBoundsKey, QJsonValue::Object, true },
{ _jsonStatsKey, QJsonValue::Object, true },
{ _jsonCarpetKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(dataObject, dataVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
// Bounds
const QJsonObject& boundsObject = dataObject[_jsonBoundsKey].toObject();
QList<JsonHelper::KeyValidateInfo> boundsVersionKeyInfoList = {
{ _jsonSouthWestKey, QJsonValue::Array, true },
{ _jsonNorthEastKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(boundsObject, boundsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
const QJsonArray& swArray = boundsObject[_jsonSouthWestKey].toArray();
const QJsonArray& neArray = boundsObject[_jsonNorthEastKey].toArray();
if (swArray.count() < 2 || neArray.count() < 2 ) {
qCDebug(TerrainTileLog) << "Incomplete bounding location";
QByteArray emptyArray;
return emptyArray;
}
stream << static_cast<float>(swArray[0].toDouble());
stream << static_cast<float>(swArray[1].toDouble());
stream << static_cast<float>(neArray[0].toDouble());
stream << static_cast<float>(neArray[1].toDouble());
// Stats
const QJsonObject& statsObject = dataObject[_jsonStatsKey].toObject();
QList<JsonHelper::KeyValidateInfo> statsVersionKeyInfoList = {
{ _jsonMinElevationKey, QJsonValue::Double, true },
{ _jsonMaxElevationKey, QJsonValue::Double, true },
{ _jsonAvgElevationKey, QJsonValue::Double, true },
};
if (!JsonHelper::validateKeys(statsObject, statsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
stream << static_cast<int16_t>(statsObject[_jsonMinElevationKey].toInt());
stream << static_cast<int16_t>(statsObject[_jsonMaxElevationKey].toInt());
stream << static_cast<float>(statsObject[_jsonAvgElevationKey].toDouble());
// Carpet
const QJsonArray& carpetArray = dataObject[_jsonCarpetKey].toArray();
int gridSizeLat = carpetArray.count();
stream << static_cast<int16_t>(gridSizeLat);
int gridSizeLon = 0;
qCDebug(TerrainTileLog) << "Received tile has size in latitude direction: " << carpetArray.count();
for (int i = 0; i < gridSizeLat; i++) {
const QJsonArray& row = carpetArray[i].toArray();
if (i == 0) {
gridSizeLon = row.count();
stream << static_cast<int16_t>(gridSizeLon);
qCDebug(TerrainTileLog) << "Received tile has size in longitued direction: " << row.count();
}
if (row.count() < gridSizeLon) {
qCDebug(TerrainTileLog) << "Expected row array of " << gridSizeLon << ", instead got " << row.count();
QByteArray emptyArray;
return emptyArray;
}
for (int j = 0; j < gridSizeLon; j++) {
stream << static_cast<int16_t>(row[j].toDouble());
}
}
return byteArray;
}
int TerrainTile::_latToDataIndex(double latitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((latitude - _southWest.latitude()) / (_northEast.latitude() - _southWest.latitude()) * (_gridSizeLat - 1));
} else {
qCWarning(TerrainTileLog) << "TerrainTile::_latToDataIndex internal error" << isValid() << _southWest.isValid() << _northEast.isValid();
return -1;
}
}
int TerrainTile::_lonToDataIndex(double longitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((longitude - _southWest.longitude()) / (_northEast.longitude() - _southWest.longitude()) * (_gridSizeLon - 1));
} else {
qCWarning(TerrainTileLog) << "TerrainTile::_lonToDataIndex internal error" << isValid() << _southWest.isValid() << _northEast.isValid();
return -1;
}
}
<|endoftext|> |
<commit_before>#include "TerrainTile.h"
#include "JsonHelper.h"
#include "QGCMapEngine.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDataStream>
QGC_LOGGING_CATEGORY(TerrainTileLog, "TerrainTileLog")
const char* TerrainTile::_jsonStatusKey = "status";
const char* TerrainTile::_jsonDataKey = "data";
const char* TerrainTile::_jsonBoundsKey = "bounds";
const char* TerrainTile::_jsonSouthWestKey = "sw";
const char* TerrainTile::_jsonNorthEastKey = "ne";
const char* TerrainTile::_jsonStatsKey = "stats";
const char* TerrainTile::_jsonMaxElevationKey = "max";
const char* TerrainTile::_jsonMinElevationKey = "min";
const char* TerrainTile::_jsonAvgElevationKey = "avg";
const char* TerrainTile::_jsonCarpetKey = "carpet";
TerrainTile::TerrainTile()
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
}
TerrainTile::~TerrainTile()
{
if (_data) {
for (int i = 0; i < _gridSizeLat; i++) {
delete _data[i];
}
delete _data;
_data = NULL;
}
}
TerrainTile::TerrainTile(QByteArray byteArray)
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
QDataStream stream(byteArray);
stream >> _southWest
>> _northEast
>> _minElevation
>> _maxElevation
>> _avgElevation
>> _gridSizeLat
>> _gridSizeLon;
for (int i = 0; i < _gridSizeLat; i++) {
if (i == 0) {
_data = new double*[_gridSizeLat];
for (int k = 0; k < _gridSizeLat; k++) {
_data[k] = new double[_gridSizeLon];
}
}
for (int j = 0; j < _gridSizeLon; j++) {
stream >> _data[i][j];
}
}
_isValid = true;
}
bool TerrainTile::isIn(const QGeoCoordinate& coordinate) const
{
if (!_isValid) {
qCDebug(TerrainTileLog) << "isIn requested, but tile not valid";
return false;
}
bool ret = coordinate.latitude() >= _southWest.latitude() && coordinate.longitude() >= _southWest.longitude() &&
coordinate.latitude() <= _northEast.latitude() && coordinate.longitude() <= _northEast.longitude();
qCDebug(TerrainTileLog) << "Checking isIn: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
return ret;
}
float TerrainTile::elevation(const QGeoCoordinate& coordinate) const
{
if (_isValid) {
qCDebug(TerrainTileLog) << "elevation: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast;
// Get the index at resolution of 1 arc second
int indexLat = _latToDataIndex(coordinate.latitude());
int indexLon = _lonToDataIndex(coordinate.longitude());
qCDebug(TerrainTileLog) << "indexLat:indexLon" << indexLat << indexLon << "elevation" << _data[indexLat][indexLon];
return _data[indexLat][indexLon];
} else {
qCDebug(TerrainTileLog) << "Asking for elevation, but no valid data.";
return -1.0;
}
}
QGeoCoordinate TerrainTile::centerCoordinate(void) const
{
return _southWest.atDistanceAndAzimuth(_southWest.distanceTo(_northEast) / 2.0, _southWest.azimuthTo(_northEast));
}
QByteArray TerrainTile::serialize(QByteArray input)
{
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(input, &parseError);
if (parseError.error != QJsonParseError::NoError) {
QByteArray emptyArray;
return emptyArray;
}
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
if (!document.isObject()) {
qCDebug(TerrainTileLog) << "Terrain tile json doc is no object";
QByteArray emptyArray;
return emptyArray;
}
QJsonObject rootObject = document.object();
QString errorString;
QList<JsonHelper::KeyValidateInfo> rootVersionKeyInfoList = {
{ _jsonStatusKey, QJsonValue::String, true },
{ _jsonDataKey, QJsonValue::Object, true },
};
if (!JsonHelper::validateKeys(rootObject, rootVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
if (rootObject[_jsonStatusKey].toString() != "success") {
qCDebug(TerrainTileLog) << "Invalid terrain tile.";
QByteArray emptyArray;
return emptyArray;
}
const QJsonObject& dataObject = rootObject[_jsonDataKey].toObject();
QList<JsonHelper::KeyValidateInfo> dataVersionKeyInfoList = {
{ _jsonBoundsKey, QJsonValue::Object, true },
{ _jsonStatsKey, QJsonValue::Object, true },
{ _jsonCarpetKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(dataObject, dataVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
// Bounds
const QJsonObject& boundsObject = dataObject[_jsonBoundsKey].toObject();
QList<JsonHelper::KeyValidateInfo> boundsVersionKeyInfoList = {
{ _jsonSouthWestKey, QJsonValue::Array, true },
{ _jsonNorthEastKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(boundsObject, boundsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
const QJsonArray& swArray = boundsObject[_jsonSouthWestKey].toArray();
const QJsonArray& neArray = boundsObject[_jsonNorthEastKey].toArray();
if (swArray.count() < 2 || neArray.count() < 2 ) {
qCDebug(TerrainTileLog) << "Incomplete bounding location";
QByteArray emptyArray;
return emptyArray;
}
stream << QGeoCoordinate(swArray[0].toDouble(), swArray[1].toDouble());
stream << QGeoCoordinate(neArray[0].toDouble(), neArray[1].toDouble());
// Stats
const QJsonObject& statsObject = dataObject[_jsonStatsKey].toObject();
QList<JsonHelper::KeyValidateInfo> statsVersionKeyInfoList = {
{ _jsonMaxElevationKey, QJsonValue::Double, true },
{ _jsonMinElevationKey, QJsonValue::Double, true },
{ _jsonAvgElevationKey, QJsonValue::Double, true },
};
if (!JsonHelper::validateKeys(statsObject, statsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
stream << statsObject[_jsonMaxElevationKey].toInt();
stream << statsObject[_jsonMinElevationKey].toInt();
stream << statsObject[_jsonAvgElevationKey].toDouble();
// Carpet
const QJsonArray& carpetArray = dataObject[_jsonCarpetKey].toArray();
int gridSizeLat = carpetArray.count();
stream << gridSizeLat;
int gridSizeLon = 0;
qCDebug(TerrainTileLog) << "Received tile has size in latitude direction: " << carpetArray.count();
for (int i = 0; i < gridSizeLat; i++) {
const QJsonArray& row = carpetArray[i].toArray();
if (i == 0) {
gridSizeLon = row.count();
stream << gridSizeLon;
qCDebug(TerrainTileLog) << "Received tile has size in longitued direction: " << row.count();
}
if (row.count() < gridSizeLon) {
qCDebug(TerrainTileLog) << "Expected row array of " << gridSizeLon << ", instead got " << row.count();
QByteArray emptyArray;
return emptyArray;
}
for (int j = 0; j < gridSizeLon; j++) {
stream << row[j].toDouble();
}
}
return byteArray;
}
int TerrainTile::_latToDataIndex(double latitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((latitude - _southWest.latitude()) / (_northEast.latitude() - _southWest.latitude()) * (_gridSizeLat - 1));
} else {
return -1;
}
}
int TerrainTile::_lonToDataIndex(double longitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((longitude - _southWest.longitude()) / (_northEast.longitude() - _southWest.longitude()) * (_gridSizeLon - 1));
} else {
return -1;
}
}
<commit_msg>change according to review<commit_after>#include "TerrainTile.h"
#include "JsonHelper.h"
#include "QGCMapEngine.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDataStream>
QGC_LOGGING_CATEGORY(TerrainTileLog, "TerrainTileLog")
const char* TerrainTile::_jsonStatusKey = "status";
const char* TerrainTile::_jsonDataKey = "data";
const char* TerrainTile::_jsonBoundsKey = "bounds";
const char* TerrainTile::_jsonSouthWestKey = "sw";
const char* TerrainTile::_jsonNorthEastKey = "ne";
const char* TerrainTile::_jsonStatsKey = "stats";
const char* TerrainTile::_jsonMaxElevationKey = "max";
const char* TerrainTile::_jsonMinElevationKey = "min";
const char* TerrainTile::_jsonAvgElevationKey = "avg";
const char* TerrainTile::_jsonCarpetKey = "carpet";
TerrainTile::TerrainTile()
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
}
TerrainTile::~TerrainTile()
{
if (_data) {
for (int i = 0; i < _gridSizeLat; i++) {
delete _data[i];
}
delete _data;
_data = NULL;
}
}
TerrainTile::TerrainTile(QByteArray byteArray)
: _minElevation(-1.0)
, _maxElevation(-1.0)
, _avgElevation(-1.0)
, _data(NULL)
, _gridSizeLat(-1)
, _gridSizeLon(-1)
, _isValid(false)
{
QDataStream stream(byteArray);
double lat,lon;
stream >> lat
>> lon;
_southWest.setLatitude(lat);
_southWest.setLongitude(lon);
stream >> lat
>> lon;
_northEast.setLatitude(lat);
_northEast.setLongitude(lon);
stream >> _minElevation
>> _maxElevation
>> _avgElevation
>> _gridSizeLat
>> _gridSizeLon;
for (int i = 0; i < _gridSizeLat; i++) {
if (i == 0) {
_data = new double*[_gridSizeLat];
for (int k = 0; k < _gridSizeLat; k++) {
_data[k] = new double[_gridSizeLon];
}
}
for (int j = 0; j < _gridSizeLon; j++) {
stream >> _data[i][j];
}
}
_isValid = true;
}
bool TerrainTile::isIn(const QGeoCoordinate& coordinate) const
{
if (!_isValid) {
qCDebug(TerrainTileLog) << "isIn requested, but tile not valid";
return false;
}
bool ret = coordinate.latitude() >= _southWest.latitude() && coordinate.longitude() >= _southWest.longitude() &&
coordinate.latitude() <= _northEast.latitude() && coordinate.longitude() <= _northEast.longitude();
qCDebug(TerrainTileLog) << "Checking isIn: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
return ret;
}
float TerrainTile::elevation(const QGeoCoordinate& coordinate) const
{
if (_isValid) {
qCDebug(TerrainTileLog) << "elevation: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast;
// Get the index at resolution of 1 arc second
int indexLat = _latToDataIndex(coordinate.latitude());
int indexLon = _lonToDataIndex(coordinate.longitude());
qCDebug(TerrainTileLog) << "indexLat:indexLon" << indexLat << indexLon << "elevation" << _data[indexLat][indexLon];
return _data[indexLat][indexLon];
} else {
qCDebug(TerrainTileLog) << "Asking for elevation, but no valid data.";
return -1.0;
}
}
QGeoCoordinate TerrainTile::centerCoordinate(void) const
{
return _southWest.atDistanceAndAzimuth(_southWest.distanceTo(_northEast) / 2.0, _southWest.azimuthTo(_northEast));
}
QByteArray TerrainTile::serialize(QByteArray input)
{
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(input, &parseError);
if (parseError.error != QJsonParseError::NoError) {
QByteArray emptyArray;
return emptyArray;
}
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
if (!document.isObject()) {
qCDebug(TerrainTileLog) << "Terrain tile json doc is no object";
QByteArray emptyArray;
return emptyArray;
}
QJsonObject rootObject = document.object();
QString errorString;
QList<JsonHelper::KeyValidateInfo> rootVersionKeyInfoList = {
{ _jsonStatusKey, QJsonValue::String, true },
{ _jsonDataKey, QJsonValue::Object, true },
};
if (!JsonHelper::validateKeys(rootObject, rootVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
if (rootObject[_jsonStatusKey].toString() != "success") {
qCDebug(TerrainTileLog) << "Invalid terrain tile.";
QByteArray emptyArray;
return emptyArray;
}
const QJsonObject& dataObject = rootObject[_jsonDataKey].toObject();
QList<JsonHelper::KeyValidateInfo> dataVersionKeyInfoList = {
{ _jsonBoundsKey, QJsonValue::Object, true },
{ _jsonStatsKey, QJsonValue::Object, true },
{ _jsonCarpetKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(dataObject, dataVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
// Bounds
const QJsonObject& boundsObject = dataObject[_jsonBoundsKey].toObject();
QList<JsonHelper::KeyValidateInfo> boundsVersionKeyInfoList = {
{ _jsonSouthWestKey, QJsonValue::Array, true },
{ _jsonNorthEastKey, QJsonValue::Array, true },
};
if (!JsonHelper::validateKeys(boundsObject, boundsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
const QJsonArray& swArray = boundsObject[_jsonSouthWestKey].toArray();
const QJsonArray& neArray = boundsObject[_jsonNorthEastKey].toArray();
if (swArray.count() < 2 || neArray.count() < 2 ) {
qCDebug(TerrainTileLog) << "Incomplete bounding location";
QByteArray emptyArray;
return emptyArray;
}
stream << swArray[0].toDouble();
stream << swArray[1].toDouble();
stream << neArray[0].toDouble();
stream << neArray[1].toDouble();
// Stats
const QJsonObject& statsObject = dataObject[_jsonStatsKey].toObject();
QList<JsonHelper::KeyValidateInfo> statsVersionKeyInfoList = {
{ _jsonMaxElevationKey, QJsonValue::Double, true },
{ _jsonMinElevationKey, QJsonValue::Double, true },
{ _jsonAvgElevationKey, QJsonValue::Double, true },
};
if (!JsonHelper::validateKeys(statsObject, statsVersionKeyInfoList, errorString)) {
qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
QByteArray emptyArray;
return emptyArray;
}
stream << statsObject[_jsonMaxElevationKey].toInt();
stream << statsObject[_jsonMinElevationKey].toInt();
stream << statsObject[_jsonAvgElevationKey].toDouble();
// Carpet
const QJsonArray& carpetArray = dataObject[_jsonCarpetKey].toArray();
int gridSizeLat = carpetArray.count();
stream << gridSizeLat;
int gridSizeLon = 0;
qCDebug(TerrainTileLog) << "Received tile has size in latitude direction: " << carpetArray.count();
for (int i = 0; i < gridSizeLat; i++) {
const QJsonArray& row = carpetArray[i].toArray();
if (i == 0) {
gridSizeLon = row.count();
stream << gridSizeLon;
qCDebug(TerrainTileLog) << "Received tile has size in longitued direction: " << row.count();
}
if (row.count() < gridSizeLon) {
qCDebug(TerrainTileLog) << "Expected row array of " << gridSizeLon << ", instead got " << row.count();
QByteArray emptyArray;
return emptyArray;
}
for (int j = 0; j < gridSizeLon; j++) {
stream << row[j].toDouble();
}
}
return byteArray;
}
int TerrainTile::_latToDataIndex(double latitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((latitude - _southWest.latitude()) / (_northEast.latitude() - _southWest.latitude()) * (_gridSizeLat - 1));
} else {
return -1;
}
}
int TerrainTile::_lonToDataIndex(double longitude) const
{
if (isValid() && _southWest.isValid() && _northEast.isValid()) {
return qRound((longitude - _southWest.longitude()) / (_northEast.longitude() - _southWest.longitude()) * (_gridSizeLon - 1));
} else {
return -1;
}
}
<|endoftext|> |
<commit_before>/**The MIT License (MIT)
Copyright (c) 2018 by Daniel Eichhorn, ThingPulse
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.
See more at https://thingpulse.com
*/
#include "TimeClient.h"
TimeClient::TimeClient(float utcOffset) {
myUtcOffset = utcOffset;
}
void TimeClient::setUtcOffset(float utcOffset) {
myUtcOffset = utcOffset;
}
void TimeClient::updateTime() {
WiFiClient client;
const int httpPort = 80;
if (!client.connect("google.com", httpPort)) {
Serial.println("connection failed");
return;
}
// This will send the request to the server
client.print(String("GET / HTTP/1.1\r\n") +
String("Host: google.com\r\n") +
String("Connection: close\r\n\r\n"));
int repeatCounter = 0;
while(!client.available() && repeatCounter < 10) {
delay(1000);
Serial.println(".");
repeatCounter++;
}
String line;
int size = 0;
client.setNoDelay(false);
while(client.available() || client.connected()) {
while((size = client.available()) > 0) {
line = client.readStringUntil('\n');
line.toUpperCase();
// example:
// date: Thu, 19 Nov 2015 20:25:40 GMT
if (line.startsWith("DATE: ")) {
Serial.println(line.substring(23, 25) + ":" + line.substring(26, 28) + ":" +line.substring(29, 31));
int parsedHours = line.substring(23, 25).toInt();
int parsedMinutes = line.substring(26, 28).toInt();
int parsedSeconds = line.substring(29, 31).toInt();
Serial.println(String(parsedHours) + ":" + String(parsedMinutes) + ":" + String(parsedSeconds));
localEpoc = (parsedHours * 60 * 60 + parsedMinutes * 60 + parsedSeconds);
Serial.println(localEpoc);
localMillisAtUpdate = millis();
}
}
}
}
String TimeClient::getHours() {
if (localEpoc == 0) {
return "--";
}
int hours = ((getCurrentEpochWithUtcOffset() % 86400L) / 3600) % 24;
if (hours < 10) {
return "0" + String(hours);
}
return String(hours); // print the hour (86400 equals secs per day)
}
String TimeClient::getMinutes() {
if (localEpoc == 0) {
return "--";
}
int minutes = ((getCurrentEpochWithUtcOffset() % 3600) / 60);
if (minutes < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
return "0" + String(minutes);
}
return String(minutes);
}
String TimeClient::getSeconds() {
if (localEpoc == 0) {
return "--";
}
int seconds = getCurrentEpochWithUtcOffset() % 60;
if ( seconds < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
return "0" + String(seconds);
}
return String(seconds);
}
String TimeClient::getFormattedTime() {
return getHours() + ":" + getMinutes() + ":" + getSeconds();
}
long TimeClient::getCurrentEpoch() {
return localEpoc + ((millis() - localMillisAtUpdate) / 1000);
}
long TimeClient::getCurrentEpochWithUtcOffset() {
return round(getCurrentEpoch() + 3600 * myUtcOffset + 86400L) % 86400L;
}
<commit_msg>Use fmod instead of % for floating point modulo<commit_after>/**The MIT License (MIT)
Copyright (c) 2018 by Daniel Eichhorn, ThingPulse
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.
See more at https://thingpulse.com
*/
#include "TimeClient.h"
TimeClient::TimeClient(float utcOffset) {
myUtcOffset = utcOffset;
}
void TimeClient::setUtcOffset(float utcOffset) {
myUtcOffset = utcOffset;
}
void TimeClient::updateTime() {
WiFiClient client;
const int httpPort = 80;
if (!client.connect("google.com", httpPort)) {
Serial.println("connection failed");
return;
}
// This will send the request to the server
client.print(String("GET / HTTP/1.1\r\n") +
String("Host: google.com\r\n") +
String("Connection: close\r\n\r\n"));
int repeatCounter = 0;
while(!client.available() && repeatCounter < 10) {
delay(1000);
Serial.println(".");
repeatCounter++;
}
String line;
int size = 0;
client.setNoDelay(false);
while(client.available() || client.connected()) {
while((size = client.available()) > 0) {
line = client.readStringUntil('\n');
line.toUpperCase();
// example:
// date: Thu, 19 Nov 2015 20:25:40 GMT
if (line.startsWith("DATE: ")) {
Serial.println(line.substring(23, 25) + ":" + line.substring(26, 28) + ":" +line.substring(29, 31));
int parsedHours = line.substring(23, 25).toInt();
int parsedMinutes = line.substring(26, 28).toInt();
int parsedSeconds = line.substring(29, 31).toInt();
Serial.println(String(parsedHours) + ":" + String(parsedMinutes) + ":" + String(parsedSeconds));
localEpoc = (parsedHours * 60 * 60 + parsedMinutes * 60 + parsedSeconds);
Serial.println(localEpoc);
localMillisAtUpdate = millis();
}
}
}
}
String TimeClient::getHours() {
if (localEpoc == 0) {
return "--";
}
int hours = ((getCurrentEpochWithUtcOffset() % 86400L) / 3600) % 24;
if (hours < 10) {
return "0" + String(hours);
}
return String(hours); // print the hour (86400 equals secs per day)
}
String TimeClient::getMinutes() {
if (localEpoc == 0) {
return "--";
}
int minutes = ((getCurrentEpochWithUtcOffset() % 3600) / 60);
if (minutes < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
return "0" + String(minutes);
}
return String(minutes);
}
String TimeClient::getSeconds() {
if (localEpoc == 0) {
return "--";
}
int seconds = getCurrentEpochWithUtcOffset() % 60;
if ( seconds < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
return "0" + String(seconds);
}
return String(seconds);
}
String TimeClient::getFormattedTime() {
return getHours() + ":" + getMinutes() + ":" + getSeconds();
}
long TimeClient::getCurrentEpoch() {
return localEpoc + ((millis() - localMillisAtUpdate) / 1000);
}
long TimeClient::getCurrentEpochWithUtcOffset() {
return fmod(round(getCurrentEpoch() + 3600 * myUtcOffset + 86400L), 86400L);
}
<|endoftext|> |
<commit_before>//Copyright (c) 2019 Ultimaker B.V.
#include "VoronoiQuadrilateralization.h"
#include "utils/VoronoiUtils.h"
#include "utils/linearAlg2D.h"
#include "utils/IntPoint.h"
#include "utils/logoutput.h"
#include "utils/macros.h"
namespace boost {
namespace polygon {
template <>
struct geometry_concept<arachne::Point>
{
typedef point_concept type;
};
template <>
struct point_traits<arachne::Point>
{
typedef int coordinate_type;
static inline coordinate_type get(
const arachne::Point& point, orientation_2d orient)
{
return (orient == HORIZONTAL) ? point.X : point.Y;
}
};
template <>
struct geometry_concept<arachne::VoronoiQuadrilateralization::Segment>
{
typedef segment_concept type;
};
template <>
struct segment_traits<arachne::VoronoiQuadrilateralization::Segment>
{
typedef arachne::coord_t coordinate_type;
typedef arachne::Point point_type;
static inline point_type get(const arachne::VoronoiQuadrilateralization::Segment& segment, direction_1d dir) {
return dir.to_int() ? segment.p() : segment.next().p();
}
};
} // polygon
} // boost
namespace arachne
{
VoronoiQuadrilateralization::node_t& VoronoiQuadrilateralization::make_node(vd_t::vertex_type& vd_node, Point p)
{
auto he_node_it = vd_node_to_he_node.find(&vd_node);
if (he_node_it == vd_node_to_he_node.end())
{
graph.nodes.emplace_front(VoronoiQuadrilateralizationJoint(), p);
node_t& node = graph.nodes.front();
vd_node_to_he_node.emplace(&vd_node, &node);
return node;
}
else
{
return *he_node_it->second;
}
}
VoronoiQuadrilateralization::edge_t& VoronoiQuadrilateralization::make_edge(Point from, Point to, vd_t::edge_type& vd_edge)
{
if (vd_edge.cell()->contains_point() || vd_edge.twin()->cell()->contains_point())
{
RUN_ONCE(logError("Discretizing segment not implemented yet.\n"));
}
graph.edges.emplace_front(VoronoiQuadrilateralizationEdge());
edge_t& edge = graph.edges.front();
vd_edge_to_he_edge.emplace(&vd_edge, &edge);
edge.from = &make_node(*vd_edge.vertex0(), from);
edge.to = &make_node(*vd_edge.vertex1(), to);
edge.from->some_edge = &edge;
edge.to->some_edge = &edge;
auto he_edge_it = vd_edge_to_he_edge.find(vd_edge.twin());
if (he_edge_it != vd_edge_to_he_edge.end())
{
edge.twin = he_edge_it->second;
he_edge_it->second->twin = &edge;
}
return edge;
}
VoronoiQuadrilateralization::VoronoiQuadrilateralization(const Polygons& polys)
{
std::vector<Point> points; // remains empty
std::vector<Segment> segments;
for (size_t poly_idx = 0; poly_idx < polys.size(); poly_idx++)
{
ConstPolygonRef poly = polys[poly_idx];
for (size_t point_idx = 0; point_idx < poly.size(); point_idx++)
{
segments.emplace_back(&polys, poly_idx, point_idx);
}
}
vd_t vd;
construct_voronoi(points.begin(), points.end(),
segments.begin(), segments.end(),
&vd);
VoronoiUtils::debugOutput("output/vd.svg", vd, points, segments);
for (vd_t::cell_type cell : vd.cells())
{
Point start_source_point;
Point end_source_point;
vd_t::edge_type* starting_vd_edge = nullptr;
vd_t::edge_type* ending_vd_edge = nullptr;
if (cell.contains_segment())
{
const Segment& source_segment = VoronoiUtils::getSourceSegment(cell, points, segments);
// printf("source segment: (%lld, %lld) - (%lld, %lld)\n", source_segment.from().X, source_segment.from().Y, source_segment.to().X, source_segment.to().Y);
// find starting edge
// find end edge
bool first = true;
for (vd_t::edge_type* edge = cell.incident_edge(); edge != cell.incident_edge() || first; edge = edge->next())
{
if (edge->is_infinite())
{
first = false;
continue;
}
// printf("edge: (%f, %f) - (%f, %f)\n", edge->vertex0()->x(), edge->vertex0()->y(), edge->vertex1()->x(), edge->vertex1()->y());
if (false && edge->is_secondary())
{ // edge crosses source segment
// TODO: handle the case where two consecutive line segments are collinear!
// that's the only case where a voronoi segment doesn't end in a polygon vertex, but goes though it
if (LinearAlg2D::pointLiesOnTheRightOfLine(VoronoiUtils::p(edge->vertex1()), source_segment.from(), source_segment.to()))
{
ending_vd_edge = edge;
}
else
{
starting_vd_edge = edge;
}
first = false;
continue;
}
if (VoronoiUtils::p(edge->vertex0()) == source_segment.to())
{
starting_vd_edge = edge;
}
if (VoronoiUtils::p(edge->vertex1()) == source_segment.from())
{
ending_vd_edge = edge;
}
first = false;
}
assert(starting_vd_edge && ending_vd_edge);
assert(starting_vd_edge != ending_vd_edge);
start_source_point = source_segment.to();
end_source_point = source_segment.from();
}
else
{
if (cell.incident_edge()->is_infinite())
{
continue;
}
// check if any point of the cell is inside or outside polygon
// copy whole cell into graph or not at all
const Point source_point = VoronoiUtils::getSourcePoint(cell, points, segments);
const PolygonsPointIndex source_point_index = VoronoiUtils::getSourcePointIndex(cell, points, segments);
Point some_point = VoronoiUtils::p(cell.incident_edge()->vertex0());
if (some_point == source_point)
{
some_point = VoronoiUtils::p(cell.incident_edge()->vertex1());
}
if (!LinearAlg2D::isInsideCorner(source_point_index.prev().p(), source_point_index.p(), source_point_index.next().p(), some_point))
{ // cell is outside of polygon
continue; // don't copy any part of this cell
}
bool first = true;
for (vd_t::edge_type* vd_edge = cell.incident_edge(); vd_edge != starting_vd_edge || first; vd_edge = vd_edge->next())
{
assert(vd_edge->is_finite());
Point p1 = VoronoiUtils::p(vd_edge->vertex1());
if (shorterThen(p1 - source_point, snap_dist))
{
start_source_point = source_point;
end_source_point = source_point;
starting_vd_edge = vd_edge->next();
ending_vd_edge = vd_edge;
}
first = false;
}
assert(starting_vd_edge && ending_vd_edge);
assert(starting_vd_edge != ending_vd_edge);
}
// copy start to end edge to graph
edge_t* starting_edge = &make_edge(start_source_point, VoronoiUtils::p(starting_vd_edge->vertex1()), *starting_vd_edge);
// starting_edge->prev = nullptr;
starting_edge->from->data.distance_to_boundary = 0;
edge_t* prev_edge = starting_edge;
for (vd_t::edge_type* vd_edge = starting_vd_edge->next(); vd_edge != ending_vd_edge; vd_edge = vd_edge->next())
{
assert(vd_edge->is_finite());
edge_t* edge = &make_edge(VoronoiUtils::p(vd_edge->vertex0()), VoronoiUtils::p(vd_edge->vertex1()), *vd_edge);
edge->prev = prev_edge;
prev_edge->next = edge;
prev_edge = edge;
}
edge_t* ending_edge = &make_edge(VoronoiUtils::p(ending_vd_edge->vertex0()), end_source_point, *ending_vd_edge);
ending_edge->prev = prev_edge;
prev_edge->next = ending_edge;
// ending_edge->next = nullptr;
ending_edge->to->data.distance_to_boundary = 0;
}
debugCheckGraphCompleteness();
{
AABB aabb(polys);
SVG svg("output/graph.svg", aabb);
debugOutput(svg);
svg.writePolygons(polys, SVG::Color::BLACK, 2);
}
}
void VoronoiQuadrilateralization::debugCheckGraphCompleteness()
{
for (const node_t& node : graph.nodes)
{
if (!node.some_edge)
{
assert(false);
}
}
for (const edge_t& edge : graph.edges)
{
if (!edge.twin || !edge.from || !edge.to)
{
assert(false);
}
assert(edge.next || edge.to->data.distance_to_boundary == 0);
assert(edge.prev || edge.from->data.distance_to_boundary == 0);
}
}
SVG::Color VoronoiQuadrilateralization::getColor(edge_t& edge)
{
switch (edge.data.type)
{
case VoronoiQuadrilateralizationEdge::EXTRA_VD:
return SVG::Color::ORANGE;
case VoronoiQuadrilateralizationEdge::TRANSITION_END:
return SVG::Color::BLUE;
case VoronoiQuadrilateralizationEdge::NORMAL:
default:
return SVG::Color::RED;
}
}
void VoronoiQuadrilateralization::debugOutput(SVG& svg)
{
// for (node_t& node : nodes)
// {
// svg.writePoint(node.p);
// }
coord_t offset_length = 10;
for (edge_t& edge : graph.edges)
{
Point a = edge.from->p;
Point b = edge.to->p;
Point ab = b - a;
Point n = normal(turn90CCW(ab), offset_length);
Point d = normal(ab, 3 * offset_length);
svg.writeLine(a + n + d, b + n - d, getColor(edge));
svg.writeLine(b + n - d, b + 2 * n - 2 * d, getColor(edge));
}
}
} // namespace arachne
<commit_msg>add gMAT edges to VD for VoronoiQuadrilateralization<commit_after>//Copyright (c) 2019 Ultimaker B.V.
#include "VoronoiQuadrilateralization.h"
#include "utils/VoronoiUtils.h"
#include "utils/linearAlg2D.h"
#include "utils/IntPoint.h"
#include "utils/logoutput.h"
#include "utils/macros.h"
namespace boost {
namespace polygon {
template <>
struct geometry_concept<arachne::Point>
{
typedef point_concept type;
};
template <>
struct point_traits<arachne::Point>
{
typedef int coordinate_type;
static inline coordinate_type get(
const arachne::Point& point, orientation_2d orient)
{
return (orient == HORIZONTAL) ? point.X : point.Y;
}
};
template <>
struct geometry_concept<arachne::VoronoiQuadrilateralization::Segment>
{
typedef segment_concept type;
};
template <>
struct segment_traits<arachne::VoronoiQuadrilateralization::Segment>
{
typedef arachne::coord_t coordinate_type;
typedef arachne::Point point_type;
static inline point_type get(const arachne::VoronoiQuadrilateralization::Segment& segment, direction_1d dir) {
return dir.to_int() ? segment.p() : segment.next().p();
}
};
} // polygon
} // boost
namespace arachne
{
VoronoiQuadrilateralization::node_t& VoronoiQuadrilateralization::make_node(vd_t::vertex_type& vd_node, Point p)
{
auto he_node_it = vd_node_to_he_node.find(&vd_node);
if (he_node_it == vd_node_to_he_node.end())
{
graph.nodes.emplace_front(VoronoiQuadrilateralizationJoint(), p);
node_t& node = graph.nodes.front();
vd_node_to_he_node.emplace(&vd_node, &node);
return node;
}
else
{
return *he_node_it->second;
}
}
VoronoiQuadrilateralization::edge_t& VoronoiQuadrilateralization::make_edge(Point from, Point to, vd_t::edge_type& vd_edge)
{
if (vd_edge.cell()->contains_point() || vd_edge.twin()->cell()->contains_point())
{
RUN_ONCE(logError("Discretizing segment not implemented yet.\n"));
}
graph.edges.emplace_front(VoronoiQuadrilateralizationEdge());
edge_t& edge = graph.edges.front();
vd_edge_to_he_edge.emplace(&vd_edge, &edge);
edge.from = &make_node(*vd_edge.vertex0(), from);
edge.to = &make_node(*vd_edge.vertex1(), to);
edge.from->some_edge = &edge;
edge.to->some_edge = &edge;
auto he_edge_it = vd_edge_to_he_edge.find(vd_edge.twin());
if (he_edge_it != vd_edge_to_he_edge.end())
{
edge.twin = he_edge_it->second;
he_edge_it->second->twin = &edge;
}
return edge;
}
VoronoiQuadrilateralization::VoronoiQuadrilateralization(const Polygons& polys)
{
std::vector<Point> points; // remains empty
std::vector<Segment> segments;
for (size_t poly_idx = 0; poly_idx < polys.size(); poly_idx++)
{
ConstPolygonRef poly = polys[poly_idx];
for (size_t point_idx = 0; point_idx < poly.size(); point_idx++)
{
segments.emplace_back(&polys, poly_idx, point_idx);
}
}
vd_t vd;
construct_voronoi(points.begin(), points.end(),
segments.begin(), segments.end(),
&vd);
VoronoiUtils::debugOutput("output/vd.svg", vd, points, segments);
for (vd_t::cell_type cell : vd.cells())
{
Point start_source_point;
Point end_source_point;
vd_t::edge_type* starting_vd_edge = nullptr;
vd_t::edge_type* ending_vd_edge = nullptr;
if (cell.contains_segment())
{
const Segment& source_segment = VoronoiUtils::getSourceSegment(cell, points, segments);
// printf("source segment: (%lld, %lld) - (%lld, %lld)\n", source_segment.from().X, source_segment.from().Y, source_segment.to().X, source_segment.to().Y);
// find starting edge
// find end edge
bool first = true;
for (vd_t::edge_type* edge = cell.incident_edge(); edge != cell.incident_edge() || first; edge = edge->next())
{
if (edge->is_infinite())
{
first = false;
continue;
}
// printf("edge: (%f, %f) - (%f, %f)\n", edge->vertex0()->x(), edge->vertex0()->y(), edge->vertex1()->x(), edge->vertex1()->y());
if (false && edge->is_secondary())
{ // edge crosses source segment
// TODO: handle the case where two consecutive line segments are collinear!
// that's the only case where a voronoi segment doesn't end in a polygon vertex, but goes though it
if (LinearAlg2D::pointLiesOnTheRightOfLine(VoronoiUtils::p(edge->vertex1()), source_segment.from(), source_segment.to()))
{
ending_vd_edge = edge;
}
else
{
starting_vd_edge = edge;
}
first = false;
continue;
}
if (VoronoiUtils::p(edge->vertex0()) == source_segment.to())
{
starting_vd_edge = edge;
}
if (VoronoiUtils::p(edge->vertex1()) == source_segment.from())
{
ending_vd_edge = edge;
}
first = false;
}
assert(starting_vd_edge && ending_vd_edge);
assert(starting_vd_edge != ending_vd_edge);
start_source_point = source_segment.to();
end_source_point = source_segment.from();
}
else
{
if (cell.incident_edge()->is_infinite())
{
continue;
}
// check if any point of the cell is inside or outside polygon
// copy whole cell into graph or not at all
const Point source_point = VoronoiUtils::getSourcePoint(cell, points, segments);
const PolygonsPointIndex source_point_index = VoronoiUtils::getSourcePointIndex(cell, points, segments);
Point some_point = VoronoiUtils::p(cell.incident_edge()->vertex0());
if (some_point == source_point)
{
some_point = VoronoiUtils::p(cell.incident_edge()->vertex1());
}
if (!LinearAlg2D::isInsideCorner(source_point_index.prev().p(), source_point_index.p(), source_point_index.next().p(), some_point))
{ // cell is outside of polygon
continue; // don't copy any part of this cell
}
bool first = true;
for (vd_t::edge_type* vd_edge = cell.incident_edge(); vd_edge != starting_vd_edge || first; vd_edge = vd_edge->next())
{
assert(vd_edge->is_finite());
Point p1 = VoronoiUtils::p(vd_edge->vertex1());
if (shorterThen(p1 - source_point, snap_dist))
{
start_source_point = source_point;
end_source_point = source_point;
starting_vd_edge = vd_edge->next();
ending_vd_edge = vd_edge;
}
first = false;
}
assert(starting_vd_edge && ending_vd_edge);
assert(starting_vd_edge != ending_vd_edge);
}
// copy start to end edge to graph
edge_t* starting_edge = &make_edge(start_source_point, VoronoiUtils::p(starting_vd_edge->vertex1()), *starting_vd_edge);
// starting_edge->prev = nullptr;
starting_edge->from->data.distance_to_boundary = 0;
edge_t* prev_edge = starting_edge;
for (vd_t::edge_type* vd_edge = starting_vd_edge->next(); vd_edge != ending_vd_edge; vd_edge = vd_edge->next())
{
assert(vd_edge->is_finite());
Point v1 = VoronoiUtils::p(vd_edge->vertex0());
Point v2 = VoronoiUtils::p(vd_edge->vertex1());
edge_t* edge = &make_edge(v1, v2, *vd_edge);
edge->prev = prev_edge;
prev_edge->next = edge;
prev_edge = edge;
if (vd_edge->next() != ending_vd_edge)
{
Point p = LinearAlg2D::getClosestOnLineSegment(v2, start_source_point, end_source_point);
graph.nodes.emplace_front(VoronoiQuadrilateralizationJoint(), p);
node_t* node = &graph.nodes.front();
node->data.distance_to_boundary = 0;
graph.edges.emplace_front(VoronoiQuadrilateralizationEdge(VoronoiQuadrilateralizationEdge::EXTRA_VD));
edge_t* forth_edge = &graph.edges.front();
graph.edges.emplace_front(VoronoiQuadrilateralizationEdge(VoronoiQuadrilateralizationEdge::EXTRA_VD));
edge_t* back_edge = &graph.edges.front();
edge->next = forth_edge;
forth_edge->prev = edge;
forth_edge->from = edge->to;
forth_edge->to = node;
forth_edge->twin = back_edge;
// foth_edge->next = nullptr;
back_edge->twin = forth_edge;
back_edge->from = node;
back_edge->to = edge->to;
// back_edge->prev = nullptr;
node->some_edge = back_edge;
prev_edge = back_edge;
}
}
edge_t* ending_edge = &make_edge(VoronoiUtils::p(ending_vd_edge->vertex0()), end_source_point, *ending_vd_edge);
ending_edge->prev = prev_edge;
prev_edge->next = ending_edge;
// ending_edge->next = nullptr;
ending_edge->to->data.distance_to_boundary = 0;
}
{
AABB aabb(polys);
SVG svg("output/graph.svg", aabb);
debugOutput(svg);
svg.writePolygons(polys, SVG::Color::BLACK, 2);
}
debugCheckGraphCompleteness();
}
void VoronoiQuadrilateralization::debugCheckGraphCompleteness()
{
for (const node_t& node : graph.nodes)
{
if (!node.some_edge)
{
assert(false);
}
}
for (const edge_t& edge : graph.edges)
{
if (!edge.twin || !edge.from || !edge.to)
{
assert(false);
}
assert(edge.next || edge.to->data.distance_to_boundary == 0);
assert(edge.prev || edge.from->data.distance_to_boundary == 0);
}
}
SVG::Color VoronoiQuadrilateralization::getColor(edge_t& edge)
{
switch (edge.data.type)
{
case VoronoiQuadrilateralizationEdge::EXTRA_VD:
return SVG::Color::ORANGE;
case VoronoiQuadrilateralizationEdge::TRANSITION_END:
return SVG::Color::BLUE;
case VoronoiQuadrilateralizationEdge::NORMAL:
default:
return SVG::Color::RED;
}
}
void VoronoiQuadrilateralization::debugOutput(SVG& svg)
{
// for (node_t& node : nodes)
// {
// svg.writePoint(node.p);
// }
coord_t offset_length = 10;
for (edge_t& edge : graph.edges)
{
Point a = edge.from->p;
Point b = edge.to->p;
Point ab = b - a;
Point n = normal(turn90CCW(ab), offset_length);
Point d = normal(ab, 3 * offset_length);
svg.writeLine(a + n + d, b + n - d, getColor(edge));
svg.writeLine(b + n - d, b + 2 * n - 2 * d, getColor(edge));
}
}
} // namespace arachne
<|endoftext|> |
<commit_before>//! \file WikiWalker.cpp
#include "WikiWalker.h"
#include <cassert>
#include <fstream>
#include <iostream>
#include "LUrlParser.h"
#include "Article.h"
#include "CacheJsonToArticleConverter.h"
#include "CurlUrlCreator.h"
#include "ToJsonWriter.h"
#include "WalkerException.h"
#include "WikimediaJsonToArticleConverter.h"
void WikiWalker::startWalking(const std::string& url)
{
// try parsing URL
auto parsedUrl = LUrlParser::clParseURL::ParseURL(url);
if(!parsedUrl.IsValid()) {
// if URL with no protocol is passed, use HTTPS
std::string protocol = "https://";
parsedUrl = LUrlParser::clParseURL::ParseURL(protocol + url);
if(!parsedUrl.IsValid()) {
throw WalkerException("Invalid URL");
}
}
size_t domainpos = parsedUrl.m_Host.find("wikipedia.org");
std::string path = parsedUrl.m_Path;
std::string pathMustStartWith = "wiki/";
size_t pathpos = path.find(pathMustStartWith);
// Host must contain wikipedia.org, path must begin with /wiki/
if(domainpos == std::string::npos || pathpos != 0) {
throw WalkerException("Must be an Wikipedia URL");
}
std::string apiBaseUrl;
apiBaseUrl = parsedUrl.m_Scheme;
apiBaseUrl.append("://");
apiBaseUrl.append(parsedUrl.m_Host);
apiBaseUrl.append("/w/api.php");
CurlUrlCreator creator(apiBaseUrl);
// extract Wikipedia title
std::string title = path.substr(pathMustStartWith.length,
path.length() - pathMustStartWith.length());
creator.addParameter("action", "query")
.addParameter("format", "json")
.addParameter("prop", "links")
.addParameter("pllimit", "max")
.addParameter("plnamespace", "0")
.addParameter("formatversion", "1");
creator.addParameter("titles", title);
std::string json = grabber.grabUrl(creator.buildUrl());
if(json != "") {
WikimediaJsonToArticleConverter conv;
auto article = conv.convertToArticle(json, articleSet);
while(conv.hasMoreData() && conv.getContinuationData() != "") {
creator.addParameter("plcontinue", conv.getContinuationData());
json = grabber.grabUrl(creator.buildUrl());
auto article2 = conv.convertToArticle(json, articleSet);
if(article != article2) {
for(auto x = article2->linkBegin(); x != article2->linkEnd(); x++) {
article->addLink(*x);
}
}
}
std::cout << "Article " << article->getTitle() << " has "
<< article->getNumLinks() << " links" << std::endl;
} else {
std::cerr << "Error fetching article" << std::endl;
}
}
void WikiWalker::readCache(const std::string& cacheFile)
{
CacheJsonToArticleConverter cjta;
std::ifstream cache(cacheFile);
// assumption: having write-only access to a file is so rare that I don't care
// also, currently the file is used for both read and write, so initially it
// won't exist.
if(!cache.is_open()) {
return;
}
cjta.convertToArticle(cache, articleSet);
assert(cache.eof());
if(cache.fail()) {
cache.close();
throw WalkerException("Error reading from file");
}
}
void WikiWalker::writeCache(const std::string& cacheFile)
{
ToJsonWriter w;
std::ofstream cache(cacheFile, std::ios::trunc);
if(!cache.is_open()) {
throw WalkerException("Error writing to cache file. Check permissions.");
}
w.output(articleSet, cache);
if(cache.fail() || cache.bad()) {
cache.close();
throw WalkerException("I/O eception when writing to cache file");
}
cache.flush();
cache.close();
}
<commit_msg>Fix typo - missing parentheses<commit_after>//! \file WikiWalker.cpp
#include "WikiWalker.h"
#include <cassert>
#include <fstream>
#include <iostream>
#include "LUrlParser.h"
#include "Article.h"
#include "CacheJsonToArticleConverter.h"
#include "CurlUrlCreator.h"
#include "ToJsonWriter.h"
#include "WalkerException.h"
#include "WikimediaJsonToArticleConverter.h"
void WikiWalker::startWalking(const std::string& url)
{
// try parsing URL
auto parsedUrl = LUrlParser::clParseURL::ParseURL(url);
if(!parsedUrl.IsValid()) {
// if URL with no protocol is passed, use HTTPS
std::string protocol = "https://";
parsedUrl = LUrlParser::clParseURL::ParseURL(protocol + url);
if(!parsedUrl.IsValid()) {
throw WalkerException("Invalid URL");
}
}
size_t domainpos = parsedUrl.m_Host.find("wikipedia.org");
std::string path = parsedUrl.m_Path;
std::string pathMustStartWith = "wiki/";
size_t pathpos = path.find(pathMustStartWith);
// Host must contain wikipedia.org, path must begin with /wiki/
if(domainpos == std::string::npos || pathpos != 0) {
throw WalkerException("Must be an Wikipedia URL");
}
std::string apiBaseUrl;
apiBaseUrl = parsedUrl.m_Scheme;
apiBaseUrl.append("://");
apiBaseUrl.append(parsedUrl.m_Host);
apiBaseUrl.append("/w/api.php");
CurlUrlCreator creator(apiBaseUrl);
// extract Wikipedia title
std::string title = path.substr(pathMustStartWith.length(),
path.length() - pathMustStartWith.length());
creator.addParameter("action", "query")
.addParameter("format", "json")
.addParameter("prop", "links")
.addParameter("pllimit", "max")
.addParameter("plnamespace", "0")
.addParameter("formatversion", "1");
creator.addParameter("titles", title);
std::string json = grabber.grabUrl(creator.buildUrl());
if(json != "") {
WikimediaJsonToArticleConverter conv;
auto article = conv.convertToArticle(json, articleSet);
while(conv.hasMoreData() && conv.getContinuationData() != "") {
creator.addParameter("plcontinue", conv.getContinuationData());
json = grabber.grabUrl(creator.buildUrl());
auto article2 = conv.convertToArticle(json, articleSet);
if(article != article2) {
for(auto x = article2->linkBegin(); x != article2->linkEnd(); x++) {
article->addLink(*x);
}
}
}
std::cout << "Article " << article->getTitle() << " has "
<< article->getNumLinks() << " links" << std::endl;
} else {
std::cerr << "Error fetching article" << std::endl;
}
}
void WikiWalker::readCache(const std::string& cacheFile)
{
CacheJsonToArticleConverter cjta;
std::ifstream cache(cacheFile);
// assumption: having write-only access to a file is so rare that I don't care
// also, currently the file is used for both read and write, so initially it
// won't exist.
if(!cache.is_open()) {
return;
}
cjta.convertToArticle(cache, articleSet);
assert(cache.eof());
if(cache.fail()) {
cache.close();
throw WalkerException("Error reading from file");
}
}
void WikiWalker::writeCache(const std::string& cacheFile)
{
ToJsonWriter w;
std::ofstream cache(cacheFile, std::ios::trunc);
if(!cache.is_open()) {
throw WalkerException("Error writing to cache file. Check permissions.");
}
w.output(articleSet, cache);
if(cache.fail() || cache.bad()) {
cache.close();
throw WalkerException("I/O eception when writing to cache file");
}
cache.flush();
cache.close();
}
<|endoftext|> |
<commit_before>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "accessible.h"
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include <QAccessibleValueInterface>
#include "adaptor.h"
#include "bridge.h"
#include "cache.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
// #define ACCESSIBLE_CREATION_DEBUG
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QString QSpiAccessible::pathForObject(QObject *object)
{
Q_ASSERT(object);
return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}
QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
QString path;
QAccessibleInterface* interfaceWithObject = interface;
while(!interfaceWithObject->object()) {
QAccessibleInterface* parentInterface;
interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
Q_ASSERT(parentInterface->isValid());
int index = parentInterface->indexOfChild(interfaceWithObject);
//Q_ASSERT(index >= 0);
// FIXME: This should never happen!
if (index < 0) {
index = 999;
path.prepend("/BROKEN_OBJECT_HIERARCHY");
qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();
qDebug() << "Original interface: " << interface->object() << index;
qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
QObject* p = parentInterface->object();
qDebug() << p->children();
QAccessibleInterface* tttt;
int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
qDebug() << "Nav child: " << id << tttt->object();
}
path.prepend('/' + QString::number(index));
interfaceWithObject = parentInterface;
}
path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));
if (childIndex > 0) {
path.append('/' + QString::number(childIndex));
}
return path;
}
QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
QStringList parts = dbusPath.split('/');
Q_ASSERT(parts.size() > 5);
// ignore the first /org/a11y/atspi/accessible/
QString objectString = parts.at(5);
quintptr uintptr = objectString.toULongLong();
if (!uintptr)
return QPair<QAccessibleInterface*, int>(0, 0);
QObject* object = reinterpret_cast<QObject*>(uintptr);
qDebug() << object;
QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
QAccessibleInterface* childInter;
int index = 0;
for (int i = 6; i < parts.size(); ++i) {
index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
if (index == 0) {
delete inter;
inter = childInter;
}
}
return QPair<QAccessibleInterface*, int>(inter, index);
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
QString path = pathForInterface(interface, index);
QDBusObjectPath dbusPath = QDBusObjectPath(path);
reference = QSpiObjectReference(spiBridge->dBusConnection(),
dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path();
#endif
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ( (!interface->rect(index).isEmpty()) ||
(interface->object() && interface->object()->isWidgetType()) ||
(interface->role(index) == QAccessible::ListItem) ||
(interface->role(index) == QAccessible::Cell) ||
(interface->role(index) == QAccessible::TreeItem) ||
(interface->role(index) == QAccessible::Row) ||
(interface->object() && interface->object()->inherits("QSGItem"))
) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << " IS a window";
#endif
}
}
}
#ifdef ACCESSIBLE_CREATION_DEBUG
else {
qDebug() << " IS NOT a component";
}
#endif
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->tableInterface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(childIndex());
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface) {
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
delete parentInterface;
if (parent)
return parent->getReference();
}
}
qWarning() << "Invalid parent: " << interface << interface->object();
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface);
if (!interface->isValid()) {
spiBridge->removeAdaptor(this);
return;
}
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
case QAccessible::TextUpdated: {
Q_ASSERT(interface->textInterface());
// at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
qDebug() << "Text changed: " << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(oldText));
emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());
QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
data.setVariant(QVariant::fromValue(text));
emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
oldText = text;
QDBusVariant cursorData;
int pos = interface->textInterface()->cursorPosition();
cursorData.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
break;
}
case QAccessible::TextCaretMoved: {
Q_ASSERT(interface->textInterface());
qDebug() << "Text caret moved: " << interface->object();
QDBusVariant data;
int pos = interface->textInterface()->cursorPosition();
data.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
break;
}
#endif
case QAccessible::ValueChanged: {
Q_ASSERT(interface->valueInterface());
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO - send status changed
// qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
// TODO - maybe send children-changed and cache Removed
// qWarning() << "Object destroyed";
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(childIndex());
// qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
if ((state^newState) & QAccessible::Checked) {
int checked = (newState & QAccessible::Checked) ? 1 : 0;
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
}
state = newState;
break;
}
case QAccessible::ParentChanged:
// TODO - send parent changed
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<commit_msg>Handle QAccessible::ObjectShow and QAccessible::ObjectHide<commit_after>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "accessible.h"
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include <QAccessibleValueInterface>
#include "adaptor.h"
#include "bridge.h"
#include "cache.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
// #define ACCESSIBLE_CREATION_DEBUG
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QString QSpiAccessible::pathForObject(QObject *object)
{
Q_ASSERT(object);
return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}
QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
QString path;
QAccessibleInterface* interfaceWithObject = interface;
while(!interfaceWithObject->object()) {
QAccessibleInterface* parentInterface;
interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
Q_ASSERT(parentInterface->isValid());
int index = parentInterface->indexOfChild(interfaceWithObject);
//Q_ASSERT(index >= 0);
// FIXME: This should never happen!
if (index < 0) {
index = 999;
path.prepend("/BROKEN_OBJECT_HIERARCHY");
qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();
qDebug() << "Original interface: " << interface->object() << index;
qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
QObject* p = parentInterface->object();
qDebug() << p->children();
QAccessibleInterface* tttt;
int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
qDebug() << "Nav child: " << id << tttt->object();
}
path.prepend('/' + QString::number(index));
interfaceWithObject = parentInterface;
}
path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));
if (childIndex > 0) {
path.append('/' + QString::number(childIndex));
}
return path;
}
QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
QStringList parts = dbusPath.split('/');
Q_ASSERT(parts.size() > 5);
// ignore the first /org/a11y/atspi/accessible/
QString objectString = parts.at(5);
quintptr uintptr = objectString.toULongLong();
if (!uintptr)
return QPair<QAccessibleInterface*, int>(0, 0);
QObject* object = reinterpret_cast<QObject*>(uintptr);
qDebug() << object;
QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
QAccessibleInterface* childInter;
int index = 0;
for (int i = 6; i < parts.size(); ++i) {
index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
if (index == 0) {
delete inter;
inter = childInter;
}
}
return QPair<QAccessibleInterface*, int>(inter, index);
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
QString path = pathForInterface(interface, index);
QDBusObjectPath dbusPath = QDBusObjectPath(path);
reference = QSpiObjectReference(spiBridge->dBusConnection(),
dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path();
#endif
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ( (!interface->rect(index).isEmpty()) ||
(interface->object() && interface->object()->isWidgetType()) ||
(interface->role(index) == QAccessible::ListItem) ||
(interface->role(index) == QAccessible::Cell) ||
(interface->role(index) == QAccessible::TreeItem) ||
(interface->role(index) == QAccessible::Row) ||
(interface->object() && interface->object()->inherits("QSGItem"))
) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << " IS a window";
#endif
}
}
}
#ifdef ACCESSIBLE_CREATION_DEBUG
else {
qDebug() << " IS NOT a component";
}
#endif
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->tableInterface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(childIndex());
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface) {
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
delete parentInterface;
if (parent)
return parent->getReference();
}
}
qWarning() << "Invalid parent: " << interface << interface->object();
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface);
if (!interface->isValid()) {
spiBridge->removeAdaptor(this);
return;
}
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
case QAccessible::TextUpdated: {
Q_ASSERT(interface->textInterface());
// at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
qDebug() << "Text changed: " << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(oldText));
emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());
QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
data.setVariant(QVariant::fromValue(text));
emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
oldText = text;
QDBusVariant cursorData;
int pos = interface->textInterface()->cursorPosition();
cursorData.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
break;
}
case QAccessible::TextCaretMoved: {
Q_ASSERT(interface->textInterface());
qDebug() << "Text caret moved: " << interface->object();
QDBusVariant data;
int pos = interface->textInterface()->cursorPosition();
data.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
break;
}
#endif
case QAccessible::ValueChanged: {
Q_ASSERT(interface->valueInterface());
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:{
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("showing", 1, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectHide: {
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("showing", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectDestroyed:
// TODO - maybe send children-changed and cache Removed
// qWarning() << "Object destroyed";
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(childIndex());
// qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
if ((state^newState) & QAccessible::Checked) {
int checked = (newState & QAccessible::Checked) ? 1 : 0;
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
}
state = newState;
break;
}
case QAccessible::ParentChanged:
// TODO - send parent changed
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<|endoftext|> |
<commit_before>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009 Nokia.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include "adaptor.h"
#include "accessible.h"
#include "bridge.h"
#include "cache.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QDBusObjectPath QSpiAccessible::getUnique()
{
static int id = 1;
QString prefix(QSPI_OBJECT_PATH_PREFIX);
QString num;
if (id == 0)
id++;
return QDBusObjectPath(prefix + num.setNum(id++));
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
reference = QSpiObjectReference(spiBridge->dBusConnection().baseService(),
getUnique());
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path();
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ((!interface->rect(index).isEmpty()) || (interface->object() && interface->object()->isWidgetType())) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
qDebug() << " + window";
}
}
} else {
qDebug() << " - component";
}
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->tableInterface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(0);
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface)
{
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
if (parent)
return parent->getReference();
}
}
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface && interface->isValid());
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO
qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
qWarning() << "Object destroyed";
Q_ASSERT(0);
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(0);
qDebug() << "StateChanged: " << (state^newState);
state = newState;
break;
}
case QAccessible::ParentChanged:
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<commit_msg>Fix wrong initialization.<commit_after>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009 Nokia.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include "adaptor.h"
#include "accessible.h"
#include "bridge.h"
#include "cache.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QDBusObjectPath QSpiAccessible::getUnique()
{
static int id = 1;
QString prefix(QSPI_OBJECT_PATH_PREFIX);
QString num;
if (id == 0)
id++;
return QDBusObjectPath(prefix + num.setNum(id++));
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
reference = QSpiObjectReference(spiBridge->dBusConnection(),
getUnique());
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path();
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ((!interface->rect(index).isEmpty()) || (interface->object() && interface->object()->isWidgetType())) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
qDebug() << " + window";
}
}
} else {
qDebug() << " - component";
}
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->tableInterface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(0);
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface)
{
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
if (parent)
return parent->getReference();
}
}
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface && interface->isValid());
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO
qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
qWarning() << "Object destroyed";
Q_ASSERT(0);
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(0);
qDebug() << "StateChanged: " << (state^newState);
state = newState;
break;
}
case QAccessible::ParentChanged:
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/expression_evaluator.hpp>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(text_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans)
{
// Use a boost::ptr_vector here instread of std::vector?
std::vector<geometry_type*> geometries_to_process;
unsigned num_geom = feature.num_geometries();
for (unsigned i=0; i<num_geom; ++i)
{
geometry_type const& geom = feature.get_geometry(i);
if (geom.num_points() == 0) continue; // don't bother with empty geometries
if ((geom.type() == Polygon) && sym.get_minimum_path_length() > 0)
{
// TODO - find less costly method than fetching full envelope
box2d<double> gbox = t_.forward(geom.envelope(),prj_trans);
if (gbox.width() < sym.get_minimum_path_length())
{
continue;
}
}
// TODO - calculate length here as well
geometries_to_process.push_back(const_cast<geometry_type*>(&geom));
}
if (!geometries_to_process.size() > 0)
return; // early return to avoid significant overhead of rendering setup
typedef coord_transform2<CoordTransform,geometry_type> path_type;
bool placement_found = false;
text_placement_info_ptr placement_options = sym.get_placement_options()->get_placement_info();
while (!placement_found && placement_options->next())
{
expression_ptr name_expr = sym.get_name();
if (!name_expr) return;
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(feature),*name_expr);
UnicodeString text = result.to_unicode();
if ( sym.get_text_transform() == UPPERCASE)
{
text = text.toUpper();
}
else if ( sym.get_text_transform() == LOWERCASE)
{
text = text.toLower();
}
else if ( sym.get_text_transform() == CAPITALIZE)
{
text = text.toTitle(NULL);
}
if ( text.length() <= 0 ) continue;
color const& fill = sym.get_fill();
face_set_ptr faces;
if (sym.get_fontset().size() > 0)
{
faces = font_manager_.get_face_set(sym.get_fontset());
}
else
{
faces = font_manager_.get_face_set(sym.get_face_name());
}
stroker_ptr strk = font_manager_.get_stroker();
if (!(faces->size() > 0 && strk))
{
throw config_error("Unable to find specified font face '" + sym.get_face_name() + "'");
}
text_renderer<T> ren(pixmap_, faces, *strk);
ren.set_character_size(placement_options->text_size * scale_factor_);
ren.set_fill(fill);
ren.set_halo_fill(sym.get_halo_fill());
ren.set_halo_radius(sym.get_halo_radius() * scale_factor_);
ren.set_opacity(sym.get_text_opacity());
box2d<double> dims(0,0,width_,height_);
placement_finder<label_collision_detector4> finder(*detector_,dims);
string_info info(text);
faces->get_string_info(info);
metawriter_with_properties writer = sym.get_metawriter();
BOOST_FOREACH( geometry_type * geom, geometries_to_process )
{
while (!placement_found && placement_options->next_position_only())
{
placement text_placement(info, sym, scale_factor_);
text_placement.avoid_edges = sym.get_avoid_edges();
if (writer.first)
text_placement.collect_extents =true; // needed for inmem metawriter
if (sym.get_label_placement() == POINT_PLACEMENT ||
sym.get_label_placement() == INTERIOR_PLACEMENT)
{
double label_x=0.0;
double label_y=0.0;
double z=0.0;
if (sym.get_label_placement() == POINT_PLACEMENT)
geom->label_position(&label_x, &label_y);
else
geom->label_interior_position(&label_x, &label_y);
prj_trans.backward(label_x,label_y, z);
t_.forward(&label_x,&label_y);
double angle = 0.0;
expression_ptr angle_expr = sym.get_orientation();
if (angle_expr)
{
// apply rotation
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(feature),*angle_expr);
angle = result.to_double();
}
finder.find_point_placement(text_placement, placement_options, label_x,label_y,
angle, sym.get_line_spacing(),
sym.get_character_spacing());
finder.update_detector(text_placement);
}
else if ( geom->num_points() > 1 && sym.get_label_placement() == LINE_PLACEMENT)
{
path_type path(t_,*geom,prj_trans);
finder.find_line_placements<path_type>(text_placement, placement_options, path);
}
if (!text_placement.placements.size()) continue;
placement_found = true;
for (unsigned int ii = 0; ii < text_placement.placements.size(); ++ii)
{
double x = text_placement.placements[ii].starting_x;
double y = text_placement.placements[ii].starting_y;
ren.prepare_glyphs(&text_placement.placements[ii]);
ren.render(x,y);
}
if (writer.first) writer.first->add_text(text_placement, faces, feature, t_, writer.second);
}
}
}
}
template void agg_renderer<image_32>::process(text_symbolizer const&,
Feature const&,
proj_transform const&);
}
<commit_msg>text rendering: only create objects once rather than per geometry part/placement attempt - refs #162<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/expression_evaluator.hpp>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(text_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans)
{
// Use a boost::ptr_vector here instread of std::vector?
std::vector<geometry_type*> geometries_to_process;
unsigned num_geom = feature.num_geometries();
for (unsigned i=0; i<num_geom; ++i)
{
geometry_type const& geom = feature.get_geometry(i);
if (geom.num_points() == 0)
{
// don't bother with empty geometries
continue;
}
if ((geom.type() == Polygon) && sym.get_minimum_path_length() > 0)
{
// TODO - find less costly method than fetching full envelope
box2d<double> gbox = t_.forward(geom.envelope(),prj_trans);
if (gbox.width() < sym.get_minimum_path_length())
{
continue;
}
}
// TODO - calculate length here as well
// TODO - sort on size to priorize labeling larger geom
// https://github.com/mapnik/mapnik/issues/162
geometries_to_process.push_back(const_cast<geometry_type*>(&geom));
}
if (!geometries_to_process.size() > 0)
{
return; // early return to avoid significant overhead of rendering setup
}
expression_ptr name_expr = sym.get_name();
if (!name_expr)
{
return;
}
value_type result = boost::apply_visitor(evaluate<Feature,value_type>(feature),*name_expr);
UnicodeString text = result.to_unicode();
if (text.length() <= 0)
{
// if text is empty no reason to continue
return;
}
if (sym.get_text_transform() == UPPERCASE)
{
text = text.toUpper();
}
else if (sym.get_text_transform() == LOWERCASE)
{
text = text.toLower();
}
else if (sym.get_text_transform() == CAPITALIZE)
{
text = text.toTitle(NULL);
}
color const& fill = sym.get_fill();
face_set_ptr faces;
if (sym.get_fontset().size() > 0)
{
faces = font_manager_.get_face_set(sym.get_fontset());
}
else
{
faces = font_manager_.get_face_set(sym.get_face_name());
}
stroker_ptr strk = font_manager_.get_stroker();
if (!(faces->size() > 0 && strk))
{
throw config_error("Unable to find specified font face '" + sym.get_face_name() + "'");
}
typedef coord_transform2<CoordTransform,geometry_type> path_type;
metawriter_with_properties writer = sym.get_metawriter();
text_renderer<T> ren(pixmap_, faces, *strk);
ren.set_fill(fill);
ren.set_halo_fill(sym.get_halo_fill());
ren.set_halo_radius(sym.get_halo_radius() * scale_factor_);
ren.set_opacity(sym.get_text_opacity());
box2d<double> dims(0,0,width_,height_);
placement_finder<label_collision_detector4> finder(*detector_,dims);
string_info info(text);
faces->get_string_info(info);
bool placement_found = false;
text_placement_info_ptr placement_options = sym.get_placement_options()->get_placement_info();
while (!placement_found && placement_options->next())
{
ren.set_character_size(placement_options->text_size * scale_factor_);
BOOST_FOREACH( geometry_type * geom, geometries_to_process )
{
while (!placement_found && placement_options->next_position_only())
{
placement text_placement(info, sym, scale_factor_);
text_placement.avoid_edges = sym.get_avoid_edges();
if (writer.first)
text_placement.collect_extents =true; // needed for inmem metawriter
if (sym.get_label_placement() == POINT_PLACEMENT ||
sym.get_label_placement() == INTERIOR_PLACEMENT)
{
double label_x=0.0;
double label_y=0.0;
double z=0.0;
if (sym.get_label_placement() == POINT_PLACEMENT)
geom->label_position(&label_x, &label_y);
else
geom->label_interior_position(&label_x, &label_y);
prj_trans.backward(label_x,label_y, z);
t_.forward(&label_x,&label_y);
double angle = 0.0;
expression_ptr angle_expr = sym.get_orientation();
if (angle_expr)
{
// apply rotation
value_type result = boost::apply_visitor(
evaluate<Feature,value_type>(feature),*angle_expr);
angle = result.to_double();
}
finder.find_point_placement(text_placement, placement_options, label_x,label_y,
angle, sym.get_line_spacing(),
sym.get_character_spacing());
finder.update_detector(text_placement);
}
else if ( geom->num_points() > 1 && sym.get_label_placement() == LINE_PLACEMENT)
{
path_type path(t_,*geom,prj_trans);
finder.find_line_placements<path_type>(text_placement, placement_options, path);
}
if (!text_placement.placements.size()) continue;
placement_found = true;
for (unsigned int ii = 0; ii < text_placement.placements.size(); ++ii)
{
double x = text_placement.placements[ii].starting_x;
double y = text_placement.placements[ii].starting_y;
ren.prepare_glyphs(&text_placement.placements[ii]);
ren.render(x,y);
}
if (writer.first) writer.first->add_text(text_placement, faces, feature, t_, writer.second);
}
}
}
}
template void agg_renderer<image_32>::process(text_symbolizer const&,
Feature const&,
proj_transform const&);
}
<|endoftext|> |
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (c) Olivier Devillers <Olivier.Devillers@sophia.inria.fr>
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/RobustDeterminant.java 1.15 (JTS-1.10)
*
**********************************************************************/
#include <geos/algorithm/RobustDeterminant.h>
#include <geos/util/IllegalArgumentException.h>
#include <cmath>
#include <geos/platform.h> // for ISNAN, FINITE
#ifdef _MSC_VER
#pragma warning(disable : 4127)
#endif
using namespace std; // for isfinite..
namespace geos {
namespace algorithm { // geos.algorithm
int RobustDeterminant::signOfDet2x2(double x1,double y1,double x2,double y2) {
// returns -1 if the determinant is negative,
// returns 1 if the determinant is positive,
// retunrs 0 if the determinant is null.
int sign=1;
double swap;
double k;
// Protect against non-finite numbers
if ( ISNAN(x1) || ISNAN(y1) || ISNAN(x2) || ISNAN(y2) ||
!FINITE(x1) || !FINITE(y1) || !FINITE(x2) || !FINITE(y2) )
{
throw util::IllegalArgumentException("RobustDeterminant encountered non-finite numbers ");
}
/*
* testing null entries
*/
if ((x1==0.0) || (y2==0.0)) {
if ((y1==0.0) || (x2==0.0)) {
return 0;
} else if (y1>0) {
if (x2>0) {
return -sign;
} else {
return sign;
}
} else {
if (x2>0) {
return sign;
} else {
return -sign;
}
}
}
if ((y1==0.0) || (x2==0.0)) {
if (y2>0) {
if (x1>0) {
return sign;
} else {
return -sign;
}
} else {
if (x1>0) {
return -sign;
} else {
return sign;
}
}
}
/*
* making y coordinates positive and permuting the entries
* so that y2 is the biggest one
*/
if (0.0<y1) {
if (0.0<y2) {
if (y1<=y2) {
;
} else {
sign=-sign;
swap=x1;
x1=x2;
x2=swap;
swap=y1;
y1=y2;
y2=swap;
}
} else {
if (y1<=-y2) {
sign=-sign;
x2=-x2;
y2=-y2;
} else {
swap=x1;
x1=-x2;
x2=swap;
swap=y1;
y1=-y2;
y2=swap;
}
}
} else {
if (0.0<y2) {
if (-y1<=y2) {
sign=-sign;
x1=-x1;
y1=-y1;
} else {
swap=-x1;
x1=x2;
x2=swap;
swap=-y1;
y1=y2;
y2=swap;
}
} else {
if (y1>=y2) {
x1=-x1;
y1=-y1;
x2=-x2;
y2=-y2;
} else {
sign=-sign;
swap=-x1;
x1=-x2;
x2=swap;
swap=-y1;
y1=-y2;
y2=swap;
}
}
}
/*
* making x coordinates positive
*/
/*
* if |x2|<|x1| one can conclude
*/
if (0.0<x1) {
if (0.0<x2) {
if (x1 <= x2) {
;
} else {
return sign;
}
} else {
return sign;
}
} else {
if (0.0<x2) {
return -sign;
} else {
if (x1 >= x2) {
sign=-sign;
x1=-x1;
x2=-x2;
} else {
return -sign;
}
}
}
/*
* all entries strictly positive x1 <= x2 and y1 <= y2
*/
while (true) {
k=std::floor(x2/x1);
x2=x2-k*x1;
y2=y2-k*y1;
/*
* testing if R (new U2) is in U1 rectangle
*/
if (y2<0.0) {
return -sign;
}
if (y2>y1) {
return sign;
}
/*
* finding R'
*/
if (x1>x2+x2) {
if (y1<y2+y2) {
return sign;
}
} else {
if (y1>y2+y2) {
return -sign;
} else {
x2=x1-x2;
y2=y1-y2;
sign=-sign;
}
}
if (y2==0.0) {
if (x2==0.0) {
return 0;
} else {
return -sign;
}
}
if (x2==0.0) {
return sign;
}
/*
* exchange 1 and 2 role.
*/
k=std::floor(x1/x2);
x1=x1-k*x2;
y1=y1-k*y2;
/*
* testing if R (new U1) is in U2 rectangle
*/
if (y1<0.0) {
return sign;
}
if (y1>y2) {
return -sign;
}
/*
* finding R'
*/
if (x2>x1+x1) {
if (y2<y1+y1) {
return -sign;
}
} else {
if (y2>y1+y1) {
return sign;
} else {
x1=x2-x1;
y1=y2-y1;
sign=-sign;
}
}
if (y1==0.0) {
if (x1==0.0) {
return 0;
} else {
return sign;
}
}
if (x1==0.0) {
return -sign;
}
}
}
} // namespace geos.algorithm
} // namespace geos
<commit_msg>More info on provenance.<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (c) Olivier Devillers <Olivier.Devillers@sophia.inria.fr>
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
* Licensed open source here: http://spatialhash.codeplex.com/
* License: http://spatialhash.codeplex.com/license
*
**********************************************************************
*
* Last port: algorithm/RobustDeterminant.java 1.15 (JTS-1.10)
*
**********************************************************************/
#include <geos/algorithm/RobustDeterminant.h>
#include <geos/util/IllegalArgumentException.h>
#include <cmath>
#include <geos/platform.h> // for ISNAN, FINITE
#ifdef _MSC_VER
#pragma warning(disable : 4127)
#endif
using namespace std; // for isfinite..
namespace geos {
namespace algorithm { // geos.algorithm
int RobustDeterminant::signOfDet2x2(double x1,double y1,double x2,double y2) {
// returns -1 if the determinant is negative,
// returns 1 if the determinant is positive,
// retunrs 0 if the determinant is null.
int sign=1;
double swap;
double k;
// Protect against non-finite numbers
if ( ISNAN(x1) || ISNAN(y1) || ISNAN(x2) || ISNAN(y2) ||
!FINITE(x1) || !FINITE(y1) || !FINITE(x2) || !FINITE(y2) )
{
throw util::IllegalArgumentException("RobustDeterminant encountered non-finite numbers ");
}
/*
* testing null entries
*/
if ((x1==0.0) || (y2==0.0)) {
if ((y1==0.0) || (x2==0.0)) {
return 0;
} else if (y1>0) {
if (x2>0) {
return -sign;
} else {
return sign;
}
} else {
if (x2>0) {
return sign;
} else {
return -sign;
}
}
}
if ((y1==0.0) || (x2==0.0)) {
if (y2>0) {
if (x1>0) {
return sign;
} else {
return -sign;
}
} else {
if (x1>0) {
return -sign;
} else {
return sign;
}
}
}
/*
* making y coordinates positive and permuting the entries
* so that y2 is the biggest one
*/
if (0.0<y1) {
if (0.0<y2) {
if (y1<=y2) {
;
} else {
sign=-sign;
swap=x1;
x1=x2;
x2=swap;
swap=y1;
y1=y2;
y2=swap;
}
} else {
if (y1<=-y2) {
sign=-sign;
x2=-x2;
y2=-y2;
} else {
swap=x1;
x1=-x2;
x2=swap;
swap=y1;
y1=-y2;
y2=swap;
}
}
} else {
if (0.0<y2) {
if (-y1<=y2) {
sign=-sign;
x1=-x1;
y1=-y1;
} else {
swap=-x1;
x1=x2;
x2=swap;
swap=-y1;
y1=y2;
y2=swap;
}
} else {
if (y1>=y2) {
x1=-x1;
y1=-y1;
x2=-x2;
y2=-y2;
} else {
sign=-sign;
swap=-x1;
x1=-x2;
x2=swap;
swap=-y1;
y1=-y2;
y2=swap;
}
}
}
/*
* making x coordinates positive
*/
/*
* if |x2|<|x1| one can conclude
*/
if (0.0<x1) {
if (0.0<x2) {
if (x1 <= x2) {
;
} else {
return sign;
}
} else {
return sign;
}
} else {
if (0.0<x2) {
return -sign;
} else {
if (x1 >= x2) {
sign=-sign;
x1=-x1;
x2=-x2;
} else {
return -sign;
}
}
}
/*
* all entries strictly positive x1 <= x2 and y1 <= y2
*/
while (true) {
k=std::floor(x2/x1);
x2=x2-k*x1;
y2=y2-k*y1;
/*
* testing if R (new U2) is in U1 rectangle
*/
if (y2<0.0) {
return -sign;
}
if (y2>y1) {
return sign;
}
/*
* finding R'
*/
if (x1>x2+x2) {
if (y1<y2+y2) {
return sign;
}
} else {
if (y1>y2+y2) {
return -sign;
} else {
x2=x1-x2;
y2=y1-y2;
sign=-sign;
}
}
if (y2==0.0) {
if (x2==0.0) {
return 0;
} else {
return -sign;
}
}
if (x2==0.0) {
return sign;
}
/*
* exchange 1 and 2 role.
*/
k=std::floor(x1/x2);
x1=x1-k*x2;
y1=y1-k*y2;
/*
* testing if R (new U1) is in U2 rectangle
*/
if (y1<0.0) {
return sign;
}
if (y1>y2) {
return -sign;
}
/*
* finding R'
*/
if (x2>x1+x1) {
if (y2<y1+y1) {
return -sign;
}
} else {
if (y2>y1+y1) {
return sign;
} else {
x1=x2-x1;
y1=y2-y1;
sign=-sign;
}
}
if (y1==0.0) {
if (x1==0.0) {
return 0;
} else {
return sign;
}
}
if (x1==0.0) {
return -sign;
}
}
}
} // namespace geos.algorithm
} // namespace geos
<|endoftext|> |
<commit_before><commit_msg>Implicitly detect the use of --in-process-webgl by the absence of a display connection in x11_util, and open our own display instead. This makes --in-process-webgl work on Linux again.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/app/app.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/values.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/browser/native_window.h"
#include "content/nw/src/browser/net_disk_cache_remover.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/common/view_messages.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
using base::MessageLoop;
using content::Shell;
using content::ShellBrowserContext;
using content::RenderProcessHost;
namespace api {
namespace {
// Get render process host.
RenderProcessHost* GetRenderProcessHost() {
RenderProcessHost* render_process_host = NULL;
std::vector<Shell*> windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
if (!windows[i]->is_devtools()) {
render_process_host = windows[i]->web_contents()->GetRenderProcessHost();
break;
}
}
return render_process_host;
}
void GetRenderProcessHosts(std::set<RenderProcessHost*>& rphs) {
RenderProcessHost* render_process_host = NULL;
std::vector<Shell*> windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
if (!windows[i]->is_devtools()) {
render_process_host = windows[i]->web_contents()->GetRenderProcessHost();
rphs.insert(render_process_host);
}
}
}
} // namespace
// static
void App::Call(const std::string& method,
const base::ListValue& arguments) {
if (method == "Quit") {
Quit();
return;
} else if (method == "CloseAllWindows") {
CloseAllWindows();
return;
}
NOTREACHED() << "Calling unknown method " << method << " of App";
}
// static
void App::Call(Shell* shell,
const std::string& method,
const base::ListValue& arguments,
base::ListValue* result) {
if (method == "GetDataPath") {
ShellBrowserContext* browser_context =
static_cast<ShellBrowserContext*>(shell->web_contents()->GetBrowserContext());
result->AppendString(browser_context->GetPath().value());
return;
}else if (method == "GetArgv") {
nw::Package* package = shell->GetPackage();
CommandLine* command_line = CommandLine::ForCurrentProcess();
CommandLine::StringVector args = command_line->GetArgs();
CommandLine::StringVector argv = command_line->original_argv();
// Ignore first non-switch arg if it's not a standalone package.
bool ignore_arg = !package->self_extract();
for (unsigned i = 1; i < argv.size(); ++i) {
if (ignore_arg && argv[i] == args[0]) {
ignore_arg = false;
continue;
}
result->AppendString(argv[i]);
}
return;
} else if (method == "ClearCache") {
ClearCache(GetRenderProcessHost());
} else if (method == "GetPackage") {
result->AppendString(shell->GetPackage()->package_string());
return;
}
NOTREACHED() << "Calling unknown sync method " << method << " of App";
}
// static
void App::CloseAllWindows(bool force) {
std::vector<Shell*> windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
// Only send close event to browser windows, since devtools windows will
// be automatically closed.
if (!windows[i]->is_devtools()) {
// If there is no js object bound to the window, then just close.
if (force || windows[i]->ShouldCloseWindow())
// we used to delete the Shell object here
// but it should be deleted on native window destruction
windows[i]->window()->Close();
}
}
}
// static
void App::Quit(RenderProcessHost* render_process_host) {
// Send the quit message.
int no_use;
if (render_process_host) {
render_process_host->Send(new ViewMsg_WillQuit(&no_use));
}else{
std::set<RenderProcessHost*> rphs;
std::set<RenderProcessHost*>::iterator it;
GetRenderProcessHosts(rphs);
for (it = rphs.begin(); it != rphs.end(); it++) {
RenderProcessHost* rph = *it;
DCHECK(rph != NULL);
rph->Send(new ViewMsg_WillQuit(&no_use));
}
CloseAllWindows(true);
}
// Then quit.
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
// static
void App::EmitOpenEvent(const std::string& path) {
std::set<RenderProcessHost*> rphs;
std::set<RenderProcessHost*>::iterator it;
GetRenderProcessHosts(rphs);
for (it = rphs.begin(); it != rphs.end(); it++) {
RenderProcessHost* rph = *it;
DCHECK(rph != NULL);
rph->Send(new ShellViewMsg_Open(path));
}
}
void App::ClearCache(content::RenderProcessHost* render_process_host) {
render_process_host->Send(new ShellViewMsg_ClearCache());
nw::RemoveHttpDiskCache(render_process_host->GetBrowserContext(),
render_process_host->GetID());
}
} // namespace api
<commit_msg>Fix 984: delete shell obj asap in force close case<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/app/app.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/values.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/browser/native_window.h"
#include "content/nw/src/browser/net_disk_cache_remover.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/common/view_messages.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
using base::MessageLoop;
using content::Shell;
using content::ShellBrowserContext;
using content::RenderProcessHost;
namespace api {
namespace {
// Get render process host.
RenderProcessHost* GetRenderProcessHost() {
RenderProcessHost* render_process_host = NULL;
std::vector<Shell*> windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
if (!windows[i]->is_devtools()) {
render_process_host = windows[i]->web_contents()->GetRenderProcessHost();
break;
}
}
return render_process_host;
}
void GetRenderProcessHosts(std::set<RenderProcessHost*>& rphs) {
RenderProcessHost* render_process_host = NULL;
std::vector<Shell*> windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
if (!windows[i]->is_devtools()) {
render_process_host = windows[i]->web_contents()->GetRenderProcessHost();
rphs.insert(render_process_host);
}
}
}
} // namespace
// static
void App::Call(const std::string& method,
const base::ListValue& arguments) {
if (method == "Quit") {
Quit();
return;
} else if (method == "CloseAllWindows") {
CloseAllWindows();
return;
}
NOTREACHED() << "Calling unknown method " << method << " of App";
}
// static
void App::Call(Shell* shell,
const std::string& method,
const base::ListValue& arguments,
base::ListValue* result) {
if (method == "GetDataPath") {
ShellBrowserContext* browser_context =
static_cast<ShellBrowserContext*>(shell->web_contents()->GetBrowserContext());
result->AppendString(browser_context->GetPath().value());
return;
}else if (method == "GetArgv") {
nw::Package* package = shell->GetPackage();
CommandLine* command_line = CommandLine::ForCurrentProcess();
CommandLine::StringVector args = command_line->GetArgs();
CommandLine::StringVector argv = command_line->original_argv();
// Ignore first non-switch arg if it's not a standalone package.
bool ignore_arg = !package->self_extract();
for (unsigned i = 1; i < argv.size(); ++i) {
if (ignore_arg && argv[i] == args[0]) {
ignore_arg = false;
continue;
}
result->AppendString(argv[i]);
}
return;
} else if (method == "ClearCache") {
ClearCache(GetRenderProcessHost());
} else if (method == "GetPackage") {
result->AppendString(shell->GetPackage()->package_string());
return;
}
NOTREACHED() << "Calling unknown sync method " << method << " of App";
}
// static
void App::CloseAllWindows(bool force) {
std::vector<Shell*> windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
// Only send close event to browser windows, since devtools windows will
// be automatically closed.
if (!windows[i]->is_devtools()) {
// If there is no js object bound to the window, then just close.
if (force || windows[i]->ShouldCloseWindow())
// we used to delete the Shell object here
// but it should be deleted on native window destruction
windows[i]->window()->Close();
}
}
if (force) {
// in a special force close case, since we're going to exit the
// main loop soon, we should delete the shell object asap so the
// render widget can be closed on the renderer side
windows = Shell::windows();
for (size_t i = 0; i < windows.size(); ++i) {
if (!windows[i]->is_devtools())
delete windows[i];
}
}
}
// static
void App::Quit(RenderProcessHost* render_process_host) {
// Send the quit message.
int no_use;
if (render_process_host) {
render_process_host->Send(new ViewMsg_WillQuit(&no_use));
}else{
std::set<RenderProcessHost*> rphs;
std::set<RenderProcessHost*>::iterator it;
GetRenderProcessHosts(rphs);
for (it = rphs.begin(); it != rphs.end(); it++) {
RenderProcessHost* rph = *it;
DCHECK(rph != NULL);
rph->Send(new ViewMsg_WillQuit(&no_use));
}
CloseAllWindows(true);
}
// Then quit.
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
// static
void App::EmitOpenEvent(const std::string& path) {
std::set<RenderProcessHost*> rphs;
std::set<RenderProcessHost*>::iterator it;
GetRenderProcessHosts(rphs);
for (it = rphs.begin(); it != rphs.end(); it++) {
RenderProcessHost* rph = *it;
DCHECK(rph != NULL);
rph->Send(new ShellViewMsg_Open(path));
}
}
void App::ClearCache(content::RenderProcessHost* render_process_host) {
render_process_host->Send(new ShellViewMsg_ClearCache());
nw::RemoveHttpDiskCache(render_process_host->GetBrowserContext(),
render_process_host->GetID());
}
} // namespace api
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: formsimp.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2008-03-12 10:40:11 $
*
* 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_xmloff.hxx"
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_ANIMIMP_HXX
#include <xmloff/formsimp.hxx>
#endif
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
TYPEINIT1( XMLFormsContext, SvXMLImportContext );
XMLFormsContext::XMLFormsContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName )
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
}
XMLFormsContext::~XMLFormsContext()
{
}
SvXMLImportContext * XMLFormsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
return GetImport().GetFormImport()->createContext( nPrefix, rLocalName, xAttrList );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.18); FILE MERGED 2008/04/01 13:04:51 thb 1.7.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:12 rt 1.7.18.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: formsimp.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <xmloff/xmlimp.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/nmspmap.hxx>
#ifndef _XMLOFF_ANIMIMP_HXX
#include <xmloff/formsimp.hxx>
#endif
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
TYPEINIT1( XMLFormsContext, SvXMLImportContext );
XMLFormsContext::XMLFormsContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName )
: SvXMLImportContext(rImport, nPrfx, rLocalName)
{
}
XMLFormsContext::~XMLFormsContext()
{
}
SvXMLImportContext * XMLFormsContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
return GetImport().GetFormImport()->createContext( nPrefix, rLocalName, xAttrList );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adjushdl.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2007-04-18 07:49:24 $
*
* 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_xmloff.hxx"
#ifndef _XMLOFF_PROPERTYHANDLER_ADJUSTTYPES_HXX
#include <adjushdl.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHADJUST_HPP_
#include <com/sun/star/style/ParagraphAdjust.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Adjust_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_END, style::ParagraphAdjust_RIGHT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_LEFT, style::ParagraphAdjust_LEFT },
{ XML_RIGHT, style::ParagraphAdjust_RIGHT },
{ XML_TOKEN_INVALID, 0 }
};
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Align_Last_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_TOKEN_INVALID, 0 }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLParaAdjustPropHdl
//
XMLParaAdjustPropHdl::~XMLParaAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLParaAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
sal_uInt16 eAdjust;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( eAdjust, rStrImpValue, pXML_Para_Adjust_Enum );
if( bRet )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLParaAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
if(!rValue.hasValue())
return sal_False; //added by BerryJia for fixing Bug102407 2002-11-5
OUStringBuffer aOut;
sal_Int16 nVal = 0;
rValue >>= nVal;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( aOut, nVal, pXML_Para_Adjust_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
///////////////////////////////////////////////////////////////////////////////
//
// class XMLLastLineAdjustPropHdl
//
XMLLastLineAdjustPropHdl::~XMLLastLineAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLLastLineAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
sal_uInt16 eAdjust;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( eAdjust, rStrImpValue, pXML_Para_Align_Last_Enum );
if( bRet )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLLastLineAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
OUStringBuffer aOut;
sal_Int16 nVal = 0;
sal_Bool bRet = sal_False;
rValue >>= nVal;
if( nVal != style::ParagraphAdjust_LEFT )
bRet = SvXMLUnitConverter::convertEnum( aOut, nVal, pXML_Para_Align_Last_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.10.30); FILE MERGED 2007/06/04 13:23:30 vg 1.10.30.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adjushdl.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:34:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_PROPERTYHANDLER_ADJUSTTYPES_HXX
#include <adjushdl.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHADJUST_HPP_
#include <com/sun/star/style/ParagraphAdjust.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include <xmloff/xmlelement.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Adjust_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_END, style::ParagraphAdjust_RIGHT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_LEFT, style::ParagraphAdjust_LEFT },
{ XML_RIGHT, style::ParagraphAdjust_RIGHT },
{ XML_TOKEN_INVALID, 0 }
};
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Align_Last_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_TOKEN_INVALID, 0 }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLParaAdjustPropHdl
//
XMLParaAdjustPropHdl::~XMLParaAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLParaAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
sal_uInt16 eAdjust;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( eAdjust, rStrImpValue, pXML_Para_Adjust_Enum );
if( bRet )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLParaAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
if(!rValue.hasValue())
return sal_False; //added by BerryJia for fixing Bug102407 2002-11-5
OUStringBuffer aOut;
sal_Int16 nVal = 0;
rValue >>= nVal;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( aOut, nVal, pXML_Para_Adjust_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
///////////////////////////////////////////////////////////////////////////////
//
// class XMLLastLineAdjustPropHdl
//
XMLLastLineAdjustPropHdl::~XMLLastLineAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLLastLineAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
sal_uInt16 eAdjust;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( eAdjust, rStrImpValue, pXML_Para_Align_Last_Enum );
if( bRet )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLLastLineAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
OUStringBuffer aOut;
sal_Int16 nVal = 0;
sal_Bool bRet = sal_False;
rValue >>= nVal;
if( nVal != style::ParagraphAdjust_LEFT )
bRet = SvXMLUnitConverter::convertEnum( aOut, nVal, pXML_Para_Align_Last_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE compile_function
#include <boost/test/unit_test.hpp>
#include "../src/compile_function.hpp"
#include "../src/core_unique_ids.hpp"
#include "../src/error/compile_exception.hpp"
#include "state_utils.hpp"
#include <llvm/IR/Function.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Value.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/raw_ostream.h>
#include <memory>
#include <unordered_map>
#include <utility>
#include <iterator>
#include <string>
using std::pair;
using std::tie;
using std::ignore;
using std::unique_ptr;
using std::unordered_map;
using std::advance;
using std::string;
using llvm::Function;
using llvm::Value;
using llvm::IntegerType;
using llvm::Type;
using llvm::verifyFunction;
using llvm::raw_string_ostream;
using boost::get;
using namespace symbol_shortcuts;
const list_symbol int64_type{id_symbol{unique_ids::INT}, lit{"64"}};
const ref a{"a"_id};
const ref b{"b"_id};
const ref c{"c"_id};
const ref q{"q"_id};
const ref r{"r"_id};
const ref s{"s"_id};
const ref t{"t"_id};
const ref u{"u"_id};
const ref v{"v"_id};
const ref w{"w"_id};
const ref x{"x"_id};
const ref y{"y"_id};
const ref z{"z"_id};
const ref block1{"block1"_id};
const ref block2{"block2"_id};
const ref block3{"block3"_id};
const ref block4{"block4"_id};
const id_symbol let{unique_ids::LET};
const list_symbol alloc_int64 = {id_symbol{unique_ids::ALLOC}, int64_type};
const list_symbol store_int64 = {id_symbol{unique_ids::STORE}, int64_type};
const list_symbol load_int64 = {id_symbol{unique_ids::LOAD}, int64_type};
const list_symbol add_int64 = {id_symbol{unique_ids::ADD}, int64_type};
const list_symbol sub_int64 = {id_symbol{unique_ids::SUB}, int64_type};
const list_symbol return_int64 = {id_symbol{unique_ids::RETURN}, int64_type};
const list_symbol cmp_eq_int64 = {id_symbol{unique_ids::CMP}, id_symbol{unique_ids::EQ}, int64_type};
const list_symbol cmp_ne_int64 = {id_symbol{unique_ids::CMP}, id_symbol{unique_ids::NE}, int64_type};
const list_symbol cond_branch = {id_symbol{unique_ids::COND_BRANCH}};
const list_symbol branch = {id_symbol{unique_ids::BRANCH}};
const list_symbol phi_int64 = {id_symbol{unique_ids::PHI}, int64_type};
BOOST_AUTO_TEST_CASE(compile_signature_test)
{
const any_symbol params1 = list
{
list{a, int64_type},
list{b, int64_type},
list{c, int64_type},
};
const any_symbol return_type1 = int64_type;
unique_ptr<Function> function1;
unordered_map<identifier_id_t, named_value_info> parameter_table1;
tie(function1, parameter_table1) = compile_signature(params1, return_type1, context);
BOOST_CHECK(function1 != nullptr);
BOOST_CHECK_EQUAL(parameter_table1.size(), 3);
BOOST_CHECK(parameter_table1.count(a.identifier()));
BOOST_CHECK(parameter_table1.count(b.identifier()));
BOOST_CHECK(parameter_table1.count(c.identifier()));
BOOST_CHECK(parameter_table1.at(b.identifier()).llvm_value == (++function1->arg_begin()));
const any_symbol params2 = list
{
list{a, int64_type},
list{b, int64_type},
list{a, int64_type}, // duplicate parameter name
};
const any_symbol return_type2 = int64_type;
BOOST_CHECK_THROW(compile_signature(params2, return_type2, context), compile_exception);
}
BOOST_AUTO_TEST_CASE(compile_instruction_test)
{
Type* llvm_int64 = IntegerType::get(context.llvm(), 64);
const id_symbol add_constructor{unique_ids::ADD};
const list_symbol instruction1{add_constructor, int64_type};
const instruction_info got1 = parse_instruction(instruction1, context.llvm());
BOOST_CHECK(get<instruction_info::add>(got1.kind).type.llvm_type == llvm_int64);
const id_symbol div_constructor{unique_ids::DIV};
const list_symbol instruction2{div_constructor, int64_type};
const instruction_info got2 = parse_instruction(instruction2, context.llvm());
BOOST_CHECK(get<instruction_info::div>(got2.kind).type.llvm_type == llvm_int64);
const id_symbol cmp_constructor{unique_ids::CMP};
const ref_symbol cmp_ref{"asdfasdf"_id, &cmp_constructor};
const id_symbol lt{unique_ids::LT};
const list_symbol instruction3{cmp_ref, lt, int64_type};
const instruction_info got3 = parse_instruction(instruction3, context.llvm());
BOOST_CHECK(get<instruction_info::cmp>(got3.kind).cmp_kind == unique_ids::LT);
BOOST_CHECK(get<instruction_info::cmp>(got3.kind).type.llvm_type == llvm_int64);
}
template<class T>
T get_compiled_function(const list_symbol& function_source)
{
unique_ptr<Function> function_owner;
tie(function_owner, ignore) = compile_function(function_source.begin(), function_source.end(), context);
Function* function = function_owner.get();
context.llvm_macro_module().getFunctionList().push_back(function_owner.get());
function_owner.release();
string str;
raw_string_ostream os(str);
//BOOST_CHECK_MESSAGE(verifyFunction(*function, &os), os.str());
// TODO: this fails - I don't know why, function->dump() looks good to me and verifyFunction doesn't produce a message
return (T) context.llvm_execution_engine().getPointerToFunction(function);
}
BOOST_AUTO_TEST_CASE(store_load_test)
{
const list_symbol params =
{
list{a, int64_type}
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{let, x, alloc_int64},
list{store_int64, a, x},
list{let, y, load_int64, x},
list{return_int64, y}
}}
};
const list_symbol function_source =
{
params,
return_type,
body
};
auto function_ptr = get_compiled_function<uint64_t (*)(uint64_t)>(function_source);
BOOST_CHECK(function_ptr(2) == 2);
BOOST_CHECK(function_ptr(1231) == 1231);
}
BOOST_AUTO_TEST_CASE(branch_test)
{
const list_symbol params =
{
list{a, int64_type},
list{b, int64_type},
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{let, x, cmp_eq_int64, a, b},
list{cond_branch, x, block2, block3}
}},
list{block2, list
{
list{let, y, add_int64, a, b},
list{return_int64, y}
}},
list{block3, list
{
list{let, z, sub_int64, a, b},
list{return_int64, z}
}}
};
const list_symbol func_source =
{
params,
return_type,
body
};
auto compiled_function = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(func_source);
BOOST_CHECK(compiled_function);
BOOST_CHECK_EQUAL(compiled_function(2, 2), 2 + 2);
BOOST_CHECK_EQUAL(compiled_function(5, 3), 5 - 3);
}
BOOST_AUTO_TEST_CASE(phi_test)
{
const list_symbol params =
{
list{a, int64_type},
list{b, int64_type},
};
const symbol& return_type = int64_type;
const list_symbol block1_def = {block1, list
{
list{let, x, cmp_eq_int64, a, b},
list{cond_branch, x, block2, block3}
}};
const list_symbol block2_def = list{block2, list
{
list{let, y, add_int64, a, b},
list{branch, block4}
}};
const list_symbol block3_def = {block3, list
{
list{let, z, sub_int64, a, b},
list{branch, block4}
}};
const list_symbol block4_def = {block4, list
{
list{let, w, phi_int64, list{y, block2}, list{z, block3}},
list{return_int64, w}
}};
const list_symbol func1_source =
{
params,
return_type,
list
{
block1_def,
block2_def,
block3_def,
block4_def
}
};
auto compiled_function1 = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(func1_source);
BOOST_CHECK(compiled_function1);
BOOST_CHECK_EQUAL(compiled_function1(2, 2), 2 + 2);
BOOST_CHECK_EQUAL(compiled_function1(5, 3), 5 - 3);
const list_symbol block4_invalid_def = {block4, list
{
list{let, w, phi_int64, list{z, block3}}, // missing incoming for block2
list{return_int64, w}
}};
const list_symbol func2_source =
{
params,
return_type,
list
{
block1_def,
block2_def,
block3_def,
block4_invalid_def
}
};
BOOST_CHECK_THROW(compile_function(func2_source.begin(), func2_source.end(), context), compile_exception);
}
BOOST_AUTO_TEST_CASE(a_times_b_test)
{
const ref result_loc{"result_loc"_id};
const ref i_loc{"i_loc"_id};
const ref init_cmp{"init_cmp"_id};
const ref current_sum{"current_sum"_id};
const ref next_sum{"next_sum"_id};
const ref current_i{"current_i"_id};
const ref next_i{"next_i"_id};
const ref loop_cmp{"loop_cmp"_id};
const ref result{"result"_id};
const list params =
{
list{a, int64_type},
list{b, int64_type}
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{let, result_loc, alloc_int64},
list{store_int64, lit{"0"}, result_loc}, // v speichert die Zwischenergebnisse und schließlich das Endergebnis der Add.
list{let, i_loc, alloc_int64},
list{store_int64, lit{"0"}, i_loc}, // w ist ein Zähler, der zählt, wie oft die erste Eingabe addiert werden muss
list{let, init_cmp, cmp_ne_int64, b, lit{"0"}}, // x = 1, falls b != 0, sonst: x = 0
list{cond_branch, init_cmp, block2, block3}
}},
list{block2, list
{
list{let, current_sum, load_int64, result_loc}, // y = die aktuelle Summe
list{let, next_sum, add_int64, current_sum, a}, //z ist die neue Summe, nach Addition mit a
list{store_int64, next_sum, result_loc},
list{let, current_i, load_int64, i_loc}, // der Zähler wird aus dem letzten Block geladen, current_i genannt
list{let, next_i, add_int64, current_i, lit{"1"}},
list{store_int64, next_i, i_loc},
list{let, loop_cmp, cmp_ne_int64, b, next_i},
list{cond_branch, loop_cmp, block2, block3}
}},
list{block3, list
{
list{let, result, load_int64, result_loc},
list{return_int64, result}
}}
};
const list_symbol function_source =
{
params,
return_type,
body
};
auto function_ptr = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(function_source);
BOOST_CHECK(function_ptr(2, 3) == 6);
BOOST_CHECK(function_ptr(0, 20) == 0);
BOOST_CHECK(function_ptr(33, 0) == 0);
BOOST_CHECK(function_ptr(0, 0) == 0);
}
<commit_msg>add missing 'let' test<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE compile_function
#include <boost/test/unit_test.hpp>
#include "../src/compile_function.hpp"
#include "../src/core_unique_ids.hpp"
#include "../src/error/compile_exception.hpp"
#include "state_utils.hpp"
#include <llvm/IR/Function.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Value.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/raw_ostream.h>
#include <memory>
#include <unordered_map>
#include <utility>
#include <iterator>
#include <string>
using std::pair;
using std::tie;
using std::ignore;
using std::unique_ptr;
using std::unordered_map;
using std::advance;
using std::string;
using llvm::Function;
using llvm::Value;
using llvm::IntegerType;
using llvm::Type;
using llvm::verifyFunction;
using llvm::raw_string_ostream;
using boost::get;
using namespace symbol_shortcuts;
const list_symbol int64_type{id_symbol{unique_ids::INT}, lit{"64"}};
const ref a{"a"_id};
const ref b{"b"_id};
const ref c{"c"_id};
const ref q{"q"_id};
const ref r{"r"_id};
const ref s{"s"_id};
const ref t{"t"_id};
const ref u{"u"_id};
const ref v{"v"_id};
const ref w{"w"_id};
const ref x{"x"_id};
const ref y{"y"_id};
const ref z{"z"_id};
const ref block1{"block1"_id};
const ref block2{"block2"_id};
const ref block3{"block3"_id};
const ref block4{"block4"_id};
const id_symbol let{unique_ids::LET};
const list_symbol alloc_int64 = {id_symbol{unique_ids::ALLOC}, int64_type};
const list_symbol store_int64 = {id_symbol{unique_ids::STORE}, int64_type};
const list_symbol load_int64 = {id_symbol{unique_ids::LOAD}, int64_type};
const list_symbol add_int64 = {id_symbol{unique_ids::ADD}, int64_type};
const list_symbol sub_int64 = {id_symbol{unique_ids::SUB}, int64_type};
const list_symbol return_int64 = {id_symbol{unique_ids::RETURN}, int64_type};
const list_symbol cmp_eq_int64 = {id_symbol{unique_ids::CMP}, id_symbol{unique_ids::EQ}, int64_type};
const list_symbol cmp_ne_int64 = {id_symbol{unique_ids::CMP}, id_symbol{unique_ids::NE}, int64_type};
const list_symbol cond_branch = {id_symbol{unique_ids::COND_BRANCH}};
const list_symbol branch = {id_symbol{unique_ids::BRANCH}};
const list_symbol phi_int64 = {id_symbol{unique_ids::PHI}, int64_type};
BOOST_AUTO_TEST_CASE(compile_signature_test)
{
const any_symbol params1 = list
{
list{a, int64_type},
list{b, int64_type},
list{c, int64_type},
};
const any_symbol return_type1 = int64_type;
unique_ptr<Function> function1;
unordered_map<identifier_id_t, named_value_info> parameter_table1;
tie(function1, parameter_table1) = compile_signature(params1, return_type1, context);
BOOST_CHECK(function1 != nullptr);
BOOST_CHECK_EQUAL(parameter_table1.size(), 3);
BOOST_CHECK(parameter_table1.count(a.identifier()));
BOOST_CHECK(parameter_table1.count(b.identifier()));
BOOST_CHECK(parameter_table1.count(c.identifier()));
BOOST_CHECK(parameter_table1.at(b.identifier()).llvm_value == (++function1->arg_begin()));
const any_symbol params2 = list
{
list{a, int64_type},
list{b, int64_type},
list{a, int64_type}, // duplicate parameter name
};
const any_symbol return_type2 = int64_type;
BOOST_CHECK_THROW(compile_signature(params2, return_type2, context), compile_exception);
}
BOOST_AUTO_TEST_CASE(compile_instruction_test)
{
Type* llvm_int64 = IntegerType::get(context.llvm(), 64);
const id_symbol add_constructor{unique_ids::ADD};
const list_symbol instruction1{add_constructor, int64_type};
const instruction_info got1 = parse_instruction(instruction1, context.llvm());
BOOST_CHECK(get<instruction_info::add>(got1.kind).type.llvm_type == llvm_int64);
const id_symbol div_constructor{unique_ids::DIV};
const list_symbol instruction2{div_constructor, int64_type};
const instruction_info got2 = parse_instruction(instruction2, context.llvm());
BOOST_CHECK(get<instruction_info::div>(got2.kind).type.llvm_type == llvm_int64);
const id_symbol cmp_constructor{unique_ids::CMP};
const ref_symbol cmp_ref{"asdfasdf"_id, &cmp_constructor};
const id_symbol lt{unique_ids::LT};
const list_symbol instruction3{cmp_ref, lt, int64_type};
const instruction_info got3 = parse_instruction(instruction3, context.llvm());
BOOST_CHECK(get<instruction_info::cmp>(got3.kind).cmp_kind == unique_ids::LT);
BOOST_CHECK(get<instruction_info::cmp>(got3.kind).type.llvm_type == llvm_int64);
}
template<class T>
T get_compiled_function(const list_symbol& function_source)
{
unique_ptr<Function> function_owner;
tie(function_owner, ignore) = compile_function(function_source.begin(), function_source.end(), context);
Function* function = function_owner.get();
context.llvm_macro_module().getFunctionList().push_back(function_owner.get());
function_owner.release();
string str;
raw_string_ostream os(str);
//BOOST_CHECK_MESSAGE(verifyFunction(*function, &os), os.str());
// TODO: this fails - I don't know why, function->dump() looks good to me and verifyFunction doesn't produce a message
return (T) context.llvm_execution_engine().getPointerToFunction(function);
}
BOOST_AUTO_TEST_CASE(store_load_test)
{
const list_symbol params =
{
list{a, int64_type}
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{let, x, alloc_int64},
list{store_int64, a, x},
list{let, y, load_int64, x},
list{return_int64, y}
}}
};
const list_symbol function_source =
{
params,
return_type,
body
};
auto function_ptr = get_compiled_function<uint64_t (*)(uint64_t)>(function_source);
BOOST_CHECK(function_ptr(2) == 2);
BOOST_CHECK(function_ptr(1231) == 1231);
}
BOOST_AUTO_TEST_CASE(branch_test)
{
const list_symbol params =
{
list{a, int64_type},
list{b, int64_type},
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{let, x, cmp_eq_int64, a, b},
list{cond_branch, x, block2, block3}
}},
list{block2, list
{
list{let, y, add_int64, a, b},
list{return_int64, y}
}},
list{block3, list
{
list{let, z, sub_int64, a, b},
list{return_int64, z}
}}
};
const list_symbol func_source =
{
params,
return_type,
body
};
auto compiled_function = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(func_source);
BOOST_CHECK(compiled_function);
BOOST_CHECK_EQUAL(compiled_function(2, 2), 2 + 2);
BOOST_CHECK_EQUAL(compiled_function(5, 3), 5 - 3);
}
BOOST_AUTO_TEST_CASE(phi_test)
{
const list_symbol params =
{
list{a, int64_type},
list{b, int64_type},
};
const symbol& return_type = int64_type;
const list_symbol block1_def = {block1, list
{
list{let, x, cmp_eq_int64, a, b},
list{cond_branch, x, block2, block3}
}};
const list_symbol block2_def = list{block2, list
{
list{let, y, add_int64, a, b},
list{branch, block4}
}};
const list_symbol block3_def = {block3, list
{
list{let, z, sub_int64, a, b},
list{branch, block4}
}};
const list_symbol block4_def = {block4, list
{
list{let, w, phi_int64, list{y, block2}, list{z, block3}},
list{return_int64, w}
}};
const list_symbol func1_source =
{
params,
return_type,
list
{
block1_def,
block2_def,
block3_def,
block4_def
}
};
auto compiled_function1 = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(func1_source);
BOOST_CHECK(compiled_function1);
BOOST_CHECK_EQUAL(compiled_function1(2, 2), 2 + 2);
BOOST_CHECK_EQUAL(compiled_function1(5, 3), 5 - 3);
const list_symbol block4_invalid_def = {block4, list
{
list{let, w, phi_int64, list{z, block3}}, // missing incoming for block2
list{return_int64, w}
}};
const list_symbol func2_source =
{
params,
return_type,
list
{
block1_def,
block2_def,
block3_def,
block4_invalid_def
}
};
BOOST_CHECK_THROW(compile_function(func2_source.begin(), func2_source.end(), context), compile_exception);
}
BOOST_AUTO_TEST_CASE(a_times_b_test)
{
const ref result_loc{"result_loc"_id};
const ref i_loc{"i_loc"_id};
const ref init_cmp{"init_cmp"_id};
const ref current_sum{"current_sum"_id};
const ref next_sum{"next_sum"_id};
const ref current_i{"current_i"_id};
const ref next_i{"next_i"_id};
const ref loop_cmp{"loop_cmp"_id};
const ref result{"result"_id};
const list params =
{
list{a, int64_type},
list{b, int64_type}
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{let, result_loc, alloc_int64},
list{store_int64, lit{"0"}, result_loc}, // v speichert die Zwischenergebnisse und schließlich das Endergebnis der Add.
list{let, i_loc, alloc_int64},
list{store_int64, lit{"0"}, i_loc}, // w ist ein Zähler, der zählt, wie oft die erste Eingabe addiert werden muss
list{let, init_cmp, cmp_ne_int64, b, lit{"0"}}, // x = 1, falls b != 0, sonst: x = 0
list{cond_branch, init_cmp, block2, block3}
}},
list{block2, list
{
list{let, current_sum, load_int64, result_loc}, // y = die aktuelle Summe
list{let, next_sum, add_int64, current_sum, a}, //z ist die neue Summe, nach Addition mit a
list{store_int64, next_sum, result_loc},
list{let, current_i, load_int64, i_loc}, // der Zähler wird aus dem letzten Block geladen, current_i genannt
list{let, next_i, add_int64, current_i, lit{"1"}},
list{store_int64, next_i, i_loc},
list{let, loop_cmp, cmp_ne_int64, b, next_i},
list{cond_branch, loop_cmp, block2, block3}
}},
list{block3, list
{
list{let, result, load_int64, result_loc},
list{return_int64, result}
}}
};
const list_symbol function_source =
{
params,
return_type,
body
};
auto function_ptr = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(function_source);
BOOST_CHECK(function_ptr(2, 3) == 6);
BOOST_CHECK(function_ptr(0, 20) == 0);
BOOST_CHECK(function_ptr(33, 0) == 0);
BOOST_CHECK(function_ptr(0, 0) == 0);
}
BOOST_AUTO_TEST_CASE(test_missing_let)
{
const list params =
{
list{a, int64_type},
list{b, int64_type}
};
const symbol& return_type = int64_type;
const list_symbol body =
{
list{block1, list
{
list{x, add_int64, a, b}
}}
};
const list_symbol function_source =
{
params,
return_type,
body
};
BOOST_CHECK_THROW(get_compiled_function<void*>(function_source), compile_exception);
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/distances.h>
#include <pcl/common/eigen.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
using namespace pcl;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGB)
{
PointXYZRGB p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGBNormal)
{
PointXYZRGBNormal p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Common)
{
PointXYZ p1, p2, p3;
p1.x = 1; p1.y = p1.z = 0;
p2.y = 1; p2.x = p2.z = 0;
p3.z = 1; p3.x = p3.y = 0;
double radius = getCircumcircleRadius (p1, p2, p3);
EXPECT_NEAR (radius, 0.816497, 1e-4);
Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0);
double point2line_disance = sqrt (sqrPointToLineDistance (pt, line_pt, line_dir));
EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Eigen)
{
Eigen::Matrix3f mat, vec;
mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05;
Eigen::Vector3f val;
eigen33 (mat, vec, val);
EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4);
EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4);
EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4);
EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4);
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat);
EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4);
EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4);
Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues ();
EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointCloud)
{
PointCloud<PointXYZ> cloud;
cloud.width = 640;
cloud.height = 480;
EXPECT_EQ (cloud.isOrganized (), true);
cloud.height = 1;
EXPECT_EQ (cloud.isOrganized (), false);
cloud.width = 10;
for (uint32_t i = 0; i < cloud.width*cloud.height; ++i)
cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));
Eigen::MatrixXf mat_xyz1 = cloud.getMatrixXfMap();
EXPECT_EQ (mat_xyz1.rows (), 4);
EXPECT_EQ (mat_xyz1.cols (), cloud.width);
EXPECT_EQ (mat_xyz1 (0,0), 0);
EXPECT_EQ (mat_xyz1 (2,cloud.width-1), 3*cloud.width-1);
Eigen::MatrixXf mat_xyz = cloud.getMatrixXfMap(3,4,0);
EXPECT_EQ (mat_xyz.rows (), 3);
EXPECT_EQ (mat_xyz.cols (), cloud.width);
EXPECT_EQ (mat_xyz (0,0), 0);
EXPECT_EQ (mat_xyz (2,cloud.width-1), 3*cloud.width-1);
Eigen::MatrixXf mat_yz = cloud.getMatrixXfMap(2,4,1);
EXPECT_EQ (mat_yz.rows (), 2);
EXPECT_EQ (mat_yz.cols (), cloud.width);
EXPECT_EQ (mat_yz (0,0), 1);
EXPECT_EQ (mat_yz (1,cloud.width-1), 3*cloud.width-1);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointTypes)
{
EXPECT_EQ (sizeof (PointXYZ), 16);
EXPECT_EQ (__alignof (PointXYZ), 16);
EXPECT_EQ (sizeof (PointXYZI), 32);
EXPECT_EQ (__alignof (PointXYZI), 16);
EXPECT_EQ (sizeof (PointXYZRGB), 32);
EXPECT_EQ (__alignof (PointXYZRGB), 16);
EXPECT_EQ (sizeof (PointXYZRGBA), 32);
EXPECT_EQ (__alignof (PointXYZRGBA), 16);
EXPECT_EQ (sizeof (Normal), 32);
EXPECT_EQ (__alignof (Normal), 16);
EXPECT_EQ (sizeof (PointNormal), 48);
EXPECT_EQ (__alignof (PointNormal), 16);
EXPECT_EQ (sizeof (PointXYZRGBNormal), 48);
EXPECT_EQ (__alignof (PointXYZRGBNormal), 16);
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<commit_msg>the map test fails in debug mode with an assertion error. we need to fix this<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/distances.h>
#include <pcl/common/eigen.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
using namespace pcl;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGB)
{
PointXYZRGB p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGBNormal)
{
PointXYZRGBNormal p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Common)
{
PointXYZ p1, p2, p3;
p1.x = 1; p1.y = p1.z = 0;
p2.y = 1; p2.x = p2.z = 0;
p3.z = 1; p3.x = p3.y = 0;
double radius = getCircumcircleRadius (p1, p2, p3);
EXPECT_NEAR (radius, 0.816497, 1e-4);
Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0);
double point2line_disance = sqrt (sqrPointToLineDistance (pt, line_pt, line_dir));
EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Eigen)
{
Eigen::Matrix3f mat, vec;
mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05;
Eigen::Vector3f val;
eigen33 (mat, vec, val);
EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4);
EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4);
EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4);
EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4);
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat);
EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4);
EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4);
Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues ();
EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointCloud)
{
PointCloud<PointXYZ> cloud;
cloud.width = 640;
cloud.height = 480;
EXPECT_EQ (cloud.isOrganized (), true);
cloud.height = 1;
EXPECT_EQ (cloud.isOrganized (), false);
cloud.width = 10;
for (uint32_t i = 0; i < cloud.width*cloud.height; ++i)
cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));
Eigen::MatrixXf mat_xyz1 = cloud.getMatrixXfMap();
EXPECT_EQ (mat_xyz1.rows (), 4);
EXPECT_EQ (mat_xyz1.cols (), cloud.width);
EXPECT_EQ (mat_xyz1 (0,0), 0);
EXPECT_EQ (mat_xyz1 (2,cloud.width-1), 3*cloud.width-1);
Eigen::MatrixXf mat_xyz = cloud.getMatrixXfMap(3,4,0);
EXPECT_EQ (mat_xyz.rows (), 3);
EXPECT_EQ (mat_xyz.cols (), cloud.width);
EXPECT_EQ (mat_xyz (0,0), 0);
EXPECT_EQ (mat_xyz (2,cloud.width-1), 3*cloud.width-1);
#ifdef NDEBUG
Eigen::MatrixXf mat_yz = cloud.getMatrixXfMap(2,4,1);
EXPECT_EQ (mat_yz.rows (), 2);
EXPECT_EQ (mat_yz.cols (), cloud.width);
EXPECT_EQ (mat_yz (0,0), 1);
EXPECT_EQ (mat_yz (1,cloud.width-1), 3*cloud.width-1);
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointTypes)
{
EXPECT_EQ (sizeof (PointXYZ), 16);
EXPECT_EQ (__alignof (PointXYZ), 16);
EXPECT_EQ (sizeof (PointXYZI), 32);
EXPECT_EQ (__alignof (PointXYZI), 16);
EXPECT_EQ (sizeof (PointXYZRGB), 32);
EXPECT_EQ (__alignof (PointXYZRGB), 16);
EXPECT_EQ (sizeof (PointXYZRGBA), 32);
EXPECT_EQ (__alignof (PointXYZRGBA), 16);
EXPECT_EQ (sizeof (Normal), 32);
EXPECT_EQ (__alignof (Normal), 16);
EXPECT_EQ (sizeof (PointNormal), 48);
EXPECT_EQ (__alignof (PointNormal), 16);
EXPECT_EQ (sizeof (PointXYZRGBNormal), 48);
EXPECT_EQ (__alignof (PointXYZRGBNormal), 16);
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<|endoftext|> |
<commit_before>#ifndef DATASET_H
#define DATASET_H
#include <sstream>
#include <vector>
#include <iterator>
#include <functional> // function<>
#include <assert.h>
#include <initializer_list>
using namespace std;
using Input = vector<double>;
using Output = vector<double>;
using LabeledPairPredicate = function<bool(const Input &, const Output &)>;
struct LabeledPair {
Input const &input;
Output const &output;
LabeledPair(const Input &input, const Output &output)
: input(input), output(output) {}
string fmt() {
ostringstream ss;
for (auto x : input) {
ss << x << " ";
}
ss << "=>";
for (auto y : output) {
ss << " " << y;
}
return ss.str();
}
};
class LabeledPairsIterator : public iterator<input_iterator_tag, LabeledPair> {
private:
vector<Input> const *inputs;
vector<Output> const *outputs;
size_t position;
public:
LabeledPairsIterator(const vector<Input> &inputs,
const vector<Output> &outputs, size_t position = 0)
: inputs(&inputs), outputs(&outputs), position(position){};
bool operator==(const LabeledPairsIterator &rhs) const {
return (inputs == rhs.inputs && outputs == rhs.outputs &&
position == rhs.position);
}
bool operator!=(const LabeledPairsIterator &rhs) const {
return !(*this == rhs);
}
LabeledPair operator*() const {
LabeledPair lp(inputs->at(position), outputs->at(position));
return lp;
}
LabeledPairsIterator &operator++() {
if (position < inputs->size()) {
++position;
}
return *this;
}
LabeledPairsIterator &operator++(int) { return ++(*this); }
};
class LabeledSet {
private:
size_t nSamples;
size_t inputSize;
size_t outputSize;
vector<Input> inputs;
vector<Output> outputs;
/// load a dataset from file (the same format as FANN)
void loadFANN(istream &in) {
in >> nSamples >> inputSize >> outputSize;
inputs.clear();
outputs.clear();
for (size_t i = 0; i < nSamples; ++i) {
auto input = vector<double>(inputSize);
auto output = vector<double>(outputSize);
for (size_t j = 0; j < inputSize; ++j) {
in >> input[j];
}
for (size_t j = 0; j < outputSize; ++j) {
in >> output[j];
}
inputs.push_back(input);
outputs.push_back(output);
}
}
/// format dataset as FANN plain-text format
string fmtFANN() {
ostringstream ss;
ss << nSamples << " " << inputSize << " " << outputSize << "\n";
for (size_t i = 0; i < nSamples; ++i) {
for (size_t j = 0; j < inputSize; ++j) {
if (j) {
ss << " ";
}
ss << inputs[i][j];
}
ss << "\n";
for (size_t j = 0; j < outputSize; ++j) {
if (j) {
ss << " ";
}
ss << outputs[i][j];
}
ss << "\n";
}
return ss.str();
}
public:
LabeledSet() : nSamples(0), inputSize(0), outputSize(0) {}
LabeledSet(istream &in) { loadFANN(in); }
LabeledSet(initializer_list<LabeledPair> samples)
: nSamples(0), inputSize(0), outputSize(0) {
for (LabeledPair s : samples) {
append(s);
}
}
LabeledPairsIterator begin() const {
return LabeledPairsIterator(inputs, outputs);
}
LabeledPairsIterator end() const {
return LabeledPairsIterator(inputs, outputs, nSamples);
}
size_t getSetSize() const { return nSamples; }
size_t getInputSize() const { return inputSize; }
size_t getOutputSize() const { return outputSize; }
LabeledSet &append(Input &input, Output &output) {
if (nSamples != 0) {
assert(inputSize == input.size());
assert(outputSize == output.size());
} else {
inputSize = input.size();
outputSize = output.size();
}
nSamples++;
inputs.push_back(input);
outputs.push_back(output);
return *this;
}
LabeledSet &append(const Input &input, const Output &output) {
if (nSamples != 0) {
assert(inputSize == input.size());
assert(outputSize == output.size());
} else {
inputSize = input.size();
outputSize = output.size();
}
nSamples++;
Input input_copy(input);
Output output_copy(output);
inputs.push_back(input_copy);
outputs.push_back(output_copy);
return *this;
}
LabeledSet &append(LabeledPair &sample) {
return append(sample.input, sample.output);
}
LabeledSet &append(const LabeledPair &sample) {
return append(sample.input, sample.output);
}
LabeledSet filter(LabeledPairPredicate &selectPredicate) const {
LabeledSet newSet;
for (auto sample : *this) {
if (selectPredicate(sample.input, sample.output)) {
newSet.append(sample);
}
}
return newSet;
}
friend istream &operator>>(istream &out, LabeledSet &ls);
friend ostream &operator<<(ostream &out, LabeledSet &ls);
};
istream &operator>>(istream &in, LabeledSet &ls) {
ls.loadFANN(in);
// if (newLS.isBAD(TODO)) in.setstate(ios::failbit);
return in;
}
ostream &operator<<(ostream &out, LabeledSet &ls) {
out << ls.fmtFANN();
return out;
}
#endif /* DATASET_H */
<commit_msg>stream output for LabeledPair<commit_after>#ifndef DATASET_H
#define DATASET_H
#include <sstream>
#include <ostream>
#include <vector>
#include <iterator>
#include <functional> // function<>
#include <assert.h>
#include <initializer_list>
using namespace std;
using Input = vector<double>;
using Output = vector<double>;
using LabeledPairPredicate = function<bool(const Input &, const Output &)>;
struct LabeledPair {
Input const &input;
Output const &output;
LabeledPair(const Input &input, const Output &output)
: input(input), output(output) {}
string fmt() {
ostringstream ss;
for (auto x : input) {
ss << x << " ";
}
ss << "=>";
for (auto y : output) {
ss << " " << y;
}
return ss.str();
}
};
ostream &operator<<(ostream &out, LabeledPair &p) {
for (auto x : p.input) {
out << x << " ";
}
out << "->";
for (auto x : p.output) {
out << " " << x;
}
return out;
}
class LabeledPairsIterator : public iterator<input_iterator_tag, LabeledPair> {
private:
vector<Input> const *inputs;
vector<Output> const *outputs;
size_t position;
public:
LabeledPairsIterator(const vector<Input> &inputs,
const vector<Output> &outputs, size_t position = 0)
: inputs(&inputs), outputs(&outputs), position(position){};
bool operator==(const LabeledPairsIterator &rhs) const {
return (inputs == rhs.inputs && outputs == rhs.outputs &&
position == rhs.position);
}
bool operator!=(const LabeledPairsIterator &rhs) const {
return !(*this == rhs);
}
LabeledPair operator*() const {
LabeledPair lp(inputs->at(position), outputs->at(position));
return lp;
}
LabeledPairsIterator &operator++() {
if (position < inputs->size()) {
++position;
}
return *this;
}
LabeledPairsIterator &operator++(int) { return ++(*this); }
};
class LabeledSet {
private:
size_t nSamples;
size_t inputSize;
size_t outputSize;
vector<Input> inputs;
vector<Output> outputs;
/// load a dataset from file (the same format as FANN)
void loadFANN(istream &in) {
in >> nSamples >> inputSize >> outputSize;
inputs.clear();
outputs.clear();
for (size_t i = 0; i < nSamples; ++i) {
auto input = vector<double>(inputSize);
auto output = vector<double>(outputSize);
for (size_t j = 0; j < inputSize; ++j) {
in >> input[j];
}
for (size_t j = 0; j < outputSize; ++j) {
in >> output[j];
}
inputs.push_back(input);
outputs.push_back(output);
}
}
/// format dataset as FANN plain-text format
string fmtFANN() {
ostringstream ss;
ss << nSamples << " " << inputSize << " " << outputSize << "\n";
for (size_t i = 0; i < nSamples; ++i) {
for (size_t j = 0; j < inputSize; ++j) {
if (j) {
ss << " ";
}
ss << inputs[i][j];
}
ss << "\n";
for (size_t j = 0; j < outputSize; ++j) {
if (j) {
ss << " ";
}
ss << outputs[i][j];
}
ss << "\n";
}
return ss.str();
}
public:
LabeledSet() : nSamples(0), inputSize(0), outputSize(0) {}
LabeledSet(istream &in) { loadFANN(in); }
LabeledSet(initializer_list<LabeledPair> samples)
: nSamples(0), inputSize(0), outputSize(0) {
for (LabeledPair s : samples) {
append(s);
}
}
LabeledPairsIterator begin() const {
return LabeledPairsIterator(inputs, outputs);
}
LabeledPairsIterator end() const {
return LabeledPairsIterator(inputs, outputs, nSamples);
}
size_t getSetSize() const { return nSamples; }
size_t getInputSize() const { return inputSize; }
size_t getOutputSize() const { return outputSize; }
LabeledSet &append(Input &input, Output &output) {
if (nSamples != 0) {
assert(inputSize == input.size());
assert(outputSize == output.size());
} else {
inputSize = input.size();
outputSize = output.size();
}
nSamples++;
inputs.push_back(input);
outputs.push_back(output);
return *this;
}
LabeledSet &append(const Input &input, const Output &output) {
if (nSamples != 0) {
assert(inputSize == input.size());
assert(outputSize == output.size());
} else {
inputSize = input.size();
outputSize = output.size();
}
nSamples++;
Input input_copy(input);
Output output_copy(output);
inputs.push_back(input_copy);
outputs.push_back(output_copy);
return *this;
}
LabeledSet &append(LabeledPair &sample) {
return append(sample.input, sample.output);
}
LabeledSet &append(const LabeledPair &sample) {
return append(sample.input, sample.output);
}
LabeledSet filter(LabeledPairPredicate &selectPredicate) const {
LabeledSet newSet;
for (auto sample : *this) {
if (selectPredicate(sample.input, sample.output)) {
newSet.append(sample);
}
}
return newSet;
}
friend istream &operator>>(istream &out, LabeledSet &ls);
friend ostream &operator<<(ostream &out, LabeledSet &ls);
};
istream &operator>>(istream &in, LabeledSet &ls) {
ls.loadFANN(in);
// if (newLS.isBAD(TODO)) in.setstate(ios::failbit);
return in;
}
ostream &operator<<(ostream &out, LabeledSet &ls) {
out << ls.fmtFANN();
return out;
}
#endif /* DATASET_H */
<|endoftext|> |
<commit_before>/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors: Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified
* to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* 1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <exception>
#include <map>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include "ArgHandler.h"
#include "TEMLogger.h"
#include "assembler/Runner.h"
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_general_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "GENER");
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "CALIB");
}
// forward declaration of various free fucntions...
void quit_handler(const boost::system::error_code&,
boost::shared_ptr< boost::asio::io_service >);
void pause_handler(const boost::system::error_code&,
boost::shared_ptr< boost::asio::io_service >);
void calibration_worker( boost::shared_ptr< boost::asio::io_service > );
// DEFINE FREE FUNCTIIONS...
void quit_handler(const boost::system::error_code& error,
boost::shared_ptr< boost::asio::io_service > io_service ){
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Running the quit signal handler...";
BOOST_LOG_SEV(clg, info) << "Stopping the io_service.";
io_service->stop();
BOOST_LOG_SEV(clg, debug) << "Quitting. Exit with -1.";
exit(-1);
}
/** The signal handler that will pause the calibration */
void pause_handler( const boost::system::error_code& error,
boost::shared_ptr< boost::asio::io_service > io_service ){
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Caught signal!";
BOOST_LOG_SEV(clg, info) << "Running pause handler."; ;
BOOST_LOG_SEV(clg, info) << "Run blocking cin.get()";
std::cin.get();
// std::string ui;
// std::getline(std::cin, ui);
// BOOST_LOG_SEV(clg, info) << "You entered: " << ui;
BOOST_LOG_SEV(clg, info) << "Done in Handler...";
}
/** A seperate function to run the model. */
void calibration_worker( ) {
// get handles for each of global loggers
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Start loop over cohorts, years, months.";
BOOST_LOG_SEV(clg, info) << "Make shared pointers to an io_service";
boost::shared_ptr< boost::asio::io_service > io_service(
new boost::asio::io_service
);
BOOST_LOG_SEV(clg, debug) << "Define a signal set...";
boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);
BOOST_LOG_SEV(clg, debug) << "Set async wait on signals to PAUSE handler.";
signals.async_wait(
boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );
for(int cohort = 0; cohort < 1; cohort++){
for(int yr = 0; yr < 100; ++yr){
int handlers_run = 0;
boost::system::error_code ec;
BOOST_LOG_SEV(clg, info) << "poll the io_service...";
handlers_run = io_service->poll(ec);
BOOST_LOG_SEV(clg, info) << handlers_run << "handlers run.";
if (handlers_run > 0) {
BOOST_LOG_SEV(clg, debug) << "Reset the io_service object.";
io_service->reset();
BOOST_LOG_SEV(clg, debug) << "Set async wait on signals to PAUSE handler.";
signals.async_wait(
boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );
}
for(int m = 0; m < 12; ++m) {
int sleeptime = 300;
BOOST_LOG_SEV(clg, info) << "(cht, yr, m):" << "(" << cohort <<", "<< yr <<", "<< m << ") "
<< "Thinking for " << sleeptime << " milliseconds...";
boost::posix_time::milliseconds workTime(sleeptime);
boost::this_thread::sleep(workTime);
} // end month loop
} // end yr loop
} // end cht loop
BOOST_LOG_SEV(clg, info) << "Done working. This simulation loops have exited.";
}
ArgHandler* args = new ArgHandler();
int main(int argc, char* argv[]){
args->parse(argc, argv);
if (args->getHelp()){
args->showHelp();
return 0;
}
args->verify();
std::cout << "Setting up Logging...\n";
setup_console_log_sink();
set_log_severity_level(args->getLogLevel());
// get handles for each of global loggers...
severity_channel_logger_t& glg = my_general_logger::get();
severity_channel_logger_t& clg = my_cal_logger::get();
if (args->getCalibrationMode() == "on") {
BOOST_LOG_SEV(glg, info) << "Running in Calibration Mode";
calibration_worker();
} else {
BOOST_LOG_SEV(glg, info) << "Running in extrapolation mode.";
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
if (args->getMode() == "siterun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in siterun mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string chtid = args->getChtid();
Runner siter;
siter.chtid = atoi(chtid.c_str());
siter.initInput(controlfile, "siter");
siter.initOutput();
siter.setupData();
siter.setupIDs();
siter.runmode1();
etime=time(0);
} else if (args->getMode() == "regnrun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in regional mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string runmode = args->getRegrunmode();
Runner regner;
regner.initInput(controlfile, runmode);
regner.initOutput();
regner.setupData();
regner.setupIDs();
if (runmode.compare("regner1")==0) {
BOOST_LOG_SEV(glg, debug) << "Running in regner1...(runmode2)";
regner.runmode2();
} else if (runmode.compare("regner2")==0){
BOOST_LOG_SEV(glg, debug) << "Running in regner2...(runmode3)";
regner.runmode3();
} else {
BOOST_LOG_SEV(glg, fatal) << "Invalid runmode...quitting.";
exit(-1);
}
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Done running dvm-dos-tem regionally "
<< "(" << ctime(&etime) << ").";
BOOST_LOG_SEV(glg, info) << "total seconds: " << difftime(etime, stime);
}
return 0;
}
};
<commit_msg>rudimentary command menu implemented. Seems to be working pretty well!<commit_after>/**
* TEM.cpp
* main program for running DVM-DOS-TEM
*
* It runs at 3 run-mods:
* (1) site-specific
* (2) regional - time series
* (3) regional - spatially (not yet available)
*
* Authors: Shuhua Yi - the original codes
* Fengming Yuan - re-designing and re-coding for (1) easily code managing;
* (2) java interface developing for calibration;
* (3) stand-alone application of TEM (java-c++)
* (4) inputs/outputs using netcdf format, have to be modified
* to fix memory-leaks
* (5) fix the snow/soil thermal/hydraulic algorithms
* (6) DVM coupled
* Tobey Carman - modifications and maintenance
* 1) update application entry point with boost command line arg. handling.
*
* Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
*
* started: 11/01/2010
* last modified: 09/18/2012
*/
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <exception>
#include <map>
#include <set>
#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include "ArgHandler.h"
#include "TEMLogger.h"
#include "assembler/Runner.h"
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_general_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "GENER");
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "CALIB");
}
// forward declaration of various free fucntions...
void quit_handler(const boost::system::error_code&,
boost::shared_ptr< boost::asio::io_service >);
void pause_handler(const boost::system::error_code&,
boost::shared_ptr< boost::asio::io_service >);
void calibration_worker( boost::shared_ptr< boost::asio::io_service > );
// DEFINE FREE FUNCTIIONS...
void quit_handler(const boost::system::error_code& error,
boost::shared_ptr< boost::asio::io_service > io_service ){
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Running the quit signal handler...";
BOOST_LOG_SEV(clg, info) << "Stopping the io_service.";
io_service->stop();
BOOST_LOG_SEV(clg, debug) << "Quitting. Exit with -1.";
exit(-1);
}
/** The signal handler that will pause the calibration */
void pause_handler( const boost::system::error_code& error,
boost::shared_ptr< boost::asio::io_service > io_service ){
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Caught signal!";
BOOST_LOG_SEV(clg, info) << "Running pause handler."; ;
std::string continueCommand = "c";
std::string reloadCommand = "r";
std::string quitCommand = "q";
std::set<std::string> validCommands;
validCommands.insert(continueCommand);
validCommands.insert(reloadCommand);
validCommands.insert(quitCommand);
std::string fullMenu = "\n"
"--------- Calibration Controller -------------\n"
"Enter one of the following options:\n"
"q - quit\n"
"c - continue simulation\n"
"r - reload config files\n";
BOOST_LOG_SEV(clg, info) << fullMenu ;
std::string ui = "";
while (!(validCommands.count(ui))) {
std::cout << "What now?> ";
std::getline(std::cin, ui);
}
BOOST_LOG_SEV(clg, info) << "Got some good user input: " << ui;
// BOOST_LOG_SEV(clg, info) << "Run blocking cin.get()";
// std::cin.get();
// std::string ui;
// std::getline(std::cin, ui);
// BOOST_LOG_SEV(clg, info) << "You entered: " << ui;
BOOST_LOG_SEV(clg, info) << "Done in Handler...";
}
/** A seperate function to run the model. */
void calibration_worker( ) {
// get handles for each of global loggers
severity_channel_logger_t& clg = my_cal_logger::get();
BOOST_LOG_SEV(clg, info) << "Start loop over cohorts, years, months.";
BOOST_LOG_SEV(clg, info) << "Make shared pointers to an io_service";
boost::shared_ptr< boost::asio::io_service > io_service(
new boost::asio::io_service
);
BOOST_LOG_SEV(clg, debug) << "Define a signal set...";
boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);
BOOST_LOG_SEV(clg, debug) << "Set async wait on signals to PAUSE handler.";
signals.async_wait(
boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );
for(int cohort = 0; cohort < 1; cohort++){
for(int yr = 0; yr < 100; ++yr){
int handlers_run = 0;
boost::system::error_code ec;
BOOST_LOG_SEV(clg, info) << "poll the io_service...";
handlers_run = io_service->poll(ec);
BOOST_LOG_SEV(clg, info) << handlers_run << " handlers run.";
if (handlers_run > 0) {
BOOST_LOG_SEV(clg, debug) << "Reset the io_service object.";
io_service->reset();
BOOST_LOG_SEV(clg, debug) << "Set async wait on signals to PAUSE handler.";
signals.async_wait(
boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );
}
for(int m = 0; m < 12; ++m) {
int sleeptime = 300;
BOOST_LOG_SEV(clg, info) << "(cht, yr, m):" << "(" << cohort <<", "<< yr <<", "<< m << ") "
<< "Thinking for " << sleeptime << " milliseconds...";
boost::posix_time::milliseconds workTime(sleeptime);
boost::this_thread::sleep(workTime);
} // end month loop
} // end yr loop
} // end cht loop
BOOST_LOG_SEV(clg, info) << "Done working. This simulation loops have exited.";
}
ArgHandler* args = new ArgHandler();
int main(int argc, char* argv[]){
args->parse(argc, argv);
if (args->getHelp()){
args->showHelp();
return 0;
}
args->verify();
std::cout << "Setting up Logging...\n";
setup_console_log_sink();
set_log_severity_level(args->getLogLevel());
// get handles for each of global loggers...
severity_channel_logger_t& glg = my_general_logger::get();
severity_channel_logger_t& clg = my_cal_logger::get();
if (args->getCalibrationMode() == "on") {
BOOST_LOG_SEV(glg, info) << "Running in Calibration Mode";
calibration_worker();
} else {
BOOST_LOG_SEV(glg, info) << "Running in extrapolation mode.";
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
if (args->getMode() == "siterun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in siterun mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string chtid = args->getChtid();
Runner siter;
siter.chtid = atoi(chtid.c_str());
siter.initInput(controlfile, "siter");
siter.initOutput();
siter.setupData();
siter.setupIDs();
siter.runmode1();
etime=time(0);
} else if (args->getMode() == "regnrun") {
time_t stime;
time_t etime;
stime=time(0);
BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in regional mode. Start @ "
<< ctime(&stime);
string controlfile = args->getCtrlfile();
string runmode = args->getRegrunmode();
Runner regner;
regner.initInput(controlfile, runmode);
regner.initOutput();
regner.setupData();
regner.setupIDs();
if (runmode.compare("regner1")==0) {
BOOST_LOG_SEV(glg, debug) << "Running in regner1...(runmode2)";
regner.runmode2();
} else if (runmode.compare("regner2")==0){
BOOST_LOG_SEV(glg, debug) << "Running in regner2...(runmode3)";
regner.runmode3();
} else {
BOOST_LOG_SEV(glg, fatal) << "Invalid runmode...quitting.";
exit(-1);
}
etime = time(0);
BOOST_LOG_SEV(glg, info) << "Done running dvm-dos-tem regionally "
<< "(" << ctime(&etime) << ").";
BOOST_LOG_SEV(glg, info) << "total seconds: " << difftime(etime, stime);
}
return 0;
}
};
<|endoftext|> |
<commit_before>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "ipeResolve.h"
void ipeResolve()
{
}
<commit_msg>Preliminary version of simplified name resolution<commit_after>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "ipeResolve.h"
#include "AstDumpToNode.h"
#include "DefScope.h"
#include "expr.h"
#include "ipe.h"
#include "stmt.h"
#include "symbol.h"
#include "VisibleSymbol.h"
class BlockStmt;
class CallExpr;
class Expr;
class FnSymbol;
class SymExpr;
static void rootScopeInit(DefScope* scope);
static Expr* resolve(const DefScope* scope, ModuleSymbol* module);
static Expr* resolve(const DefScope* scope, FnSymbol* fn);
static Expr* resolve(const DefScope* scope, BlockStmt* expr);
static Expr* resolve(const DefScope* scope, Expr* expr);
static Expr* resolve(const DefScope* scope, DefExpr* expr);
static Expr* resolve(const DefScope* scope, SymExpr* expr);
static Expr* resolve(const DefScope* scope, UnresolvedSymExpr* expr);
static Expr* resolve(const DefScope* scope, CallExpr* expr);
static void coerceActualToFormal(Expr* actual, Expr* formal);
static Type* exprType(Expr* expr);
static bool blockCreatesScope(BlockStmt* block);
static Expr* selectFunc(const DefScope* scope,
Expr* funName,
std::vector<Type*>& actualTypes);
static int sRootModuleIndex = 0;
/************************************ | *************************************
* *
* IPE needs to extract core definitions from the Root Module but this *
* module is constantly updated. We arrange for the core initialization *
* routine to call this function so that it can establish a high water mark. *
* *
************************************* | ************************************/
void ipeRootInit()
{
sRootModuleIndex = rootModule->block->body.length;
}
/************************************ | *************************************
* *
* The entry point for the IPE's stripped down version of type and function *
* resolution. *
* *
************************************* | ************************************/
void ipeResolve()
{
DefScope* scopeBase = DefScope::extend(NULL);
rootScopeInit(scopeBase);
// Scan the Root Module Declaration
// Every expression should be a DefExpr.
// Process every Top Level Module Declaration
for_alist(stmt, rootModule->block->body)
{
if (DefExpr* defExpr = toDefExpr(stmt))
{
if (ModuleSymbol* module = toModuleSymbol(defExpr->sym))
{
resolve(scopeBase, module);
}
}
else
INT_ASSERT(false);
}
}
/************************************ | *************************************
* *
* We combine DefExprs in _root and ChapelBase in to a single DefScope *
* *
************************************* | ************************************/
static void rootScopeInit(DefScope* scope)
{
// Append the first N slots in rootModule
for (int i = 1; i <= sRootModuleIndex; i++)
{
if (DefExpr* expr = toDefExpr(rootModule->block->body.get(i)))
scope->addDefinition(expr);
else
INT_ASSERT(false);
}
// Any top level module definitions in rootModule
for_alist(stmt, rootModule->block->body)
{
if (DefExpr* expr = toDefExpr(stmt))
{
if (isModuleSymbol(expr->sym) == true)
scope->addDefinition(expr);
}
}
// All definitions in ChapelBase
scope->extendByModule(baseModule);
}
/************************************ | *************************************
* *
* *
* *
************************************* | ************************************/
static Expr* resolve(const DefScope* parent, ModuleSymbol* module)
{
BlockStmt* moduleBody = module->block;
const DefScope* scope = 0;
if (blockCreatesScope(moduleBody) == true)
{
DefScope* newScope = DefScope::extend(parent);
// Extend scope with the top-level DefExprs
for_alist(stmt, moduleBody->body)
{
if (DefExpr* expr = toDefExpr(stmt))
newScope->addDefinition(expr);
}
scope = newScope;
}
else
{
scope = parent;
}
// Resolve every statement in the block
for_alist(stmt, moduleBody->body)
{
resolve(scope, stmt);
}
return 0;
}
static Expr* resolve(const DefScope* parent, FnSymbol* fn)
{
const DefScope* scope = 0;
if (fn->formals.length > 0)
{
DefScope* formalsScope = DefScope::extend(parent);
for (int i = 1; i <= fn->formals.length; i++)
{
DefExpr* defExpr = 0;
ArgSymbol* formal = 0;
defExpr = toDefExpr(fn->formals.get(i));
INT_ASSERT(defExpr);
formal = toArgSymbol(defExpr->sym);
INT_ASSERT(formal);
INT_ASSERT(formal->type);
formalsScope->addDefinition(defExpr);
}
scope = formalsScope;
}
else
{
scope = parent;
}
resolve(scope, fn->body);
return 0;
}
static Expr* resolve(const DefScope* parent, BlockStmt* bs)
{
DefScope* bodyScope = DefScope::extend(parent);
for_alist(stmt, bs->body)
{
if (DefExpr* defExpr = toDefExpr(stmt))
bodyScope->addDefinition(defExpr);
}
for_alist(expr, bs->body)
{
resolve(bodyScope, expr);
}
return 0;
}
static Expr* resolve(const DefScope* scope, Expr* expr)
{
Expr* retval = 0;
if (DefExpr* sel = toDefExpr(expr))
{
resolve(scope, sel);
retval = 0;
}
else if (UnresolvedSymExpr* sel = toUnresolvedSymExpr(expr))
retval = resolve(scope, sel);
else if (SymExpr* sel = toSymExpr(expr))
retval = resolve(scope, sel);
else if (CallExpr* sel = toCallExpr(expr))
retval = resolve(scope, sel);
else
{
AstDumpToNode logger(stdout);
printf("resolve Unhandled expr\n");
expr->accept(&logger);
printf("\n\n\n");
}
return retval;
}
static Expr* resolve(const DefScope* scope, DefExpr* defExpr)
{
Type* typeType = 0;
Type* initType = 0;
if (defExpr->exprType != 0)
{
Expr* resolvedExpr = resolve(scope, defExpr->exprType);
INT_ASSERT(resolvedExpr);
if (resolvedExpr != defExpr->exprType)
defExpr->exprType->replace(resolvedExpr);
typeType = exprType(defExpr->exprType);
INT_ASSERT(typeType);
}
if (defExpr->init != 0)
{
Expr* resolvedExpr = resolve(scope, defExpr->init);
INT_ASSERT(resolvedExpr);
if (resolvedExpr != defExpr->init)
defExpr->init->replace(resolvedExpr);
initType = exprType(defExpr->init);
INT_ASSERT(initType);
}
if (typeType == 0 && initType == 0)
{
// It would be a surprise if the parser generated this case
if (isFnSymbol(defExpr->sym) == false)
INT_ASSERT(false);
}
else if (typeType == 0 && initType != 0)
defExpr->sym->type = initType;
else if (typeType != 0 && initType == 0)
defExpr->sym->type = typeType;
else
{
if (typeType == initType)
defExpr->sym->type = typeType;
else
INT_ASSERT(false);
}
if (defExpr->exprType != 0)
defExpr->exprType->remove();
return 0;
}
static Expr* resolve(const DefScope* scope, SymExpr* expr)
{
return expr;
}
static Expr* resolve(const DefScope* scope, UnresolvedSymExpr* expr)
{
std::vector<VisibleSymbol> symbols;
Expr* retval = 0;
scope->visibleSymbols(expr, symbols);
if (symbols.size() == 0)
{
AstDumpToNode logger(stdout);
printf("resolve UnresolvedSymExpr. Failed to find a definition\n");
expr->accept(&logger);
printf("\n\n");
INT_ASSERT(false);
}
else
{
SET_LINENO(expr);
retval = new SymExpr(symbols[0].symbol());
}
return retval;
}
static Expr* resolve(const DefScope* scope, CallExpr* expr)
{
int count = expr->numActuals();
std::vector<Type*> actualTypes;
// Resolve the actuals
for (int i = 1; i <= count; i++)
{
Expr* actual = expr->get(i);
Expr* res = resolve(scope, actual);
Type* type = exprType(res);
INT_ASSERT(res);
INT_ASSERT(type);
actualTypes.push_back(type);
if (res != actual)
actual->replace(res);
}
// Select the function
if (expr->baseExpr)
{
Expr* funcRef = selectFunc(scope, expr->baseExpr, actualTypes);
FnSymbol* func = 0;
INT_ASSERT(funcRef);
expr->baseExpr->replace(funcRef);
if (SymExpr* symExpr = toSymExpr(funcRef))
func = toFnSymbol(symExpr->var);
INT_ASSERT(func);
INT_ASSERT(func->formals.length == count);
// Coerce, as required, the actual to match the formal
for (int i = 1; i <= count; i++)
{
Expr* actual = expr->get(i);
Expr* formal = func->formals.get(i);
coerceActualToFormal(actual, formal);
}
}
return expr;
}
/************************************ | *************************************
* *
* 2015-01-06 Preliminary/Simplified *
* *
************************************* | ************************************/
static void coerceActualToFormal(Expr* actual, Expr* formal)
{
DefExpr* formalDef = toDefExpr(formal);
INT_ASSERT(formalDef);
ArgSymbol* formalSym = toArgSymbol(formalDef->sym);
INT_ASSERT(formalSym);
if ((formalSym->intent & INTENT_REF) != 0)
{
SET_LINENO(actual);
CallExpr* addrOf = new CallExpr(PRIM_ADDR_OF);
actual->replace(addrOf);
addrOf->insertAtTail(actual);
}
}
/************************************ | *************************************
* *
* *
* *
************************************* | ************************************/
static Type* exprType(Expr* expr)
{
Type* retval = 0;
if (expr == 0)
{
retval = 0;
}
else if (SymExpr* value = toSymExpr(expr))
{
if (TypeSymbol* type = toTypeSymbol(value->var))
retval = type->type;
else if (VarSymbol* var = toVarSymbol(value->var))
retval = var->type;
else if (ArgSymbol* arg = toArgSymbol(value->var))
retval = arg->type;
}
else
retval = 0;
if (retval == 0)
{
AstDumpToNode logger(stdout);
printf("exprType Failed to find type for\n ");
expr->accept(&logger);
printf("\n\n");
INT_ASSERT(false);
}
return retval;
}
/************************************ | *************************************
* *
* *
* *
************************************* | ************************************/
static bool blockCreatesScope(BlockStmt* block)
{
bool retval = false;
if (block->blockTag == BLOCK_NORMAL)
{
Expr* head = block->body.head;
for (Expr* stmt = head; stmt && retval == false; stmt = stmt->next)
retval = isDefExpr(stmt);
}
return retval;
}
/************************************ | *************************************
* *
* A drastically simplified form of Function Resolution for IPE. *
* *
************************************* | ************************************/
static void resolveFuncFormals(const DefScope* scope, FnSymbol* fn);
static void resolveFormalType (const DefScope* scope, ArgSymbol* formal);
static bool ipeFunctionExactMatch(FnSymbol* fn,
std::vector<Type*>& actualTypes);
static Expr* selectFunc(const DefScope* scope,
Expr* funName,
std::vector<Type*>& actualTypes)
{
Expr* retval = 0;
if (UnresolvedSymExpr* sel = toUnresolvedSymExpr(funName))
{
std::vector<VisibleSymbol> visibleSymbols;
scope->visibleSymbols(sel, visibleSymbols);
// Ensure we know the type of every formal
for (size_t i = 0; i < visibleSymbols.size(); i++)
{
if (FnSymbol* fn = toFnSymbol(visibleSymbols[i].symbol()))
{
resolveFuncFormals(scope, fn);
}
}
// Determine if there is an exact match
for (size_t i = 0; i < visibleSymbols.size() && retval == 0; i++)
{
if (FnSymbol* fn = toFnSymbol(visibleSymbols[i].symbol()))
{
if (ipeFunctionExactMatch(fn, actualTypes) == true)
{
SET_LINENO(funName);
retval = new SymExpr(fn);
resolve(visibleSymbols[i].scope(), fn);
}
}
}
INT_ASSERT(retval);
}
else
{
AstDumpToNode logger(stdout);
printf("selectFunc Unhandled\n");
funName->accept(&logger);
printf("\n\n\n");
}
return retval;
}
static void resolveFuncFormals(const DefScope* scope, FnSymbol* fn)
{
for_alist(formal, fn->formals)
{
DefExpr* def = toDefExpr(formal);
ArgSymbol* arg = toArgSymbol(def->sym);
INT_ASSERT(arg);
if (arg->type == 0)
{
resolveFormalType(scope, arg);
INT_ASSERT(arg->type);
}
}
}
static void resolveFormalType(const DefScope* scope, ArgSymbol* formal)
{
BlockStmt* bs = formal->typeExpr;
INT_ASSERT(bs);
INT_ASSERT(bs->body.length == 1);
UnresolvedSymExpr* unres = toUnresolvedSymExpr(bs->body.get(1));
INT_ASSERT(unres);
std::vector<VisibleSymbol> symbols;
scope->visibleSymbols(unres, symbols);
if (symbols.size() == 0)
{
AstDumpToNode logger(stdout);
printf("resolveFormalType Failed to find a definition\n");
unres->accept(&logger);
printf("\n\n");
INT_ASSERT(false);
}
else
{
TypeSymbol* typeSym = toTypeSymbol(symbols[0].symbol());
INT_ASSERT(typeSym);
formal->type = typeSym->type;
formal->typeExpr->remove();
}
}
static bool ipeFunctionExactMatch(FnSymbol* fn,
std::vector<Type*>& actualsTypes)
{
bool retval = false;
if (fn->formals.length == actualsTypes.size())
{
bool match = true;
for (size_t i = 0; i < actualsTypes.size() && match == true; i++)
{
DefExpr* expr = toDefExpr(fn->formals.get(i + 1));
INT_ASSERT(expr);
ArgSymbol* arg = toArgSymbol(expr->sym);
INT_ASSERT(arg);
match = (actualsTypes[i] == arg->type) ? true : false;
}
retval = match;
}
return retval;
}
<|endoftext|> |
<commit_before>// Copyright 2016-2019 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <stdexcept>
#include <mp++/config.hpp>
#include <mp++/integer.hpp>
#include "catch.hpp"
using namespace mppp;
#if MPPP_CPLUSPLUS >= 201703L
TEST_CASE("integer_literal_check_str_test")
{
// Decimal.
{
constexpr char str[] = {'0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '1', '5', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '1', '5', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
char str[] = {'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'1', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'a', '1', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'1', '2', '.', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'1', '2', 'e', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
// Binary.
{
constexpr char str[] = {'0', 'b', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'B', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'b', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'B', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'b', '0', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'B', '0', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
char str[] = {'0', 'b', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'B', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'b', '2', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'B', '2', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'b', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'B', 'f', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
// Octal.
{
constexpr char str[] = {'0', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '2', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '1', '2', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '0', '7', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
char str[] = {'0', '9', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '1', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '7', '8', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '1', '.', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '3', 'e', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
// Hex.
{
constexpr char str[] = {'0', 'x', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'X', 'f', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'x', 'F', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'X', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'x', 'a', 'B', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'X', 'C', 'd', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
char str[] = {'0', 'x', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'X', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'x', 'g', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'X', 'G', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'x', '.', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'X', 'p', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
}
#endif
TEST_CASE("z1_test")
{
#if MPPP_CPLUSPLUS >= 201402L
REQUIRE(0b1101010010101001010100100101_z1 == integer<1>{"1101010010101001010100100101", 2});
REQUIRE(
0b1101010010101001010100100101010101010101010010101010010101010110101010101010101010110101010101001010101101010101010101010_z1
== integer<1>{"110101001010100101010010010101010101010101001010101001010101011010101010101010101011010101010100"
"1010101101010101010101010",
2});
#endif
REQUIRE(21309213209382109382190382190382109303821321002140982142139081_z1
== integer<1>{"21309213209382109382190382190382109303821321002140982142139081"});
}
<commit_msg>Workaround in the tests too.<commit_after>// Copyright 2016-2019 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <stdexcept>
#include <mp++/config.hpp>
#include <mp++/integer.hpp>
#include "catch.hpp"
using namespace mppp;
#if MPPP_CPLUSPLUS >= 201703L && (!defined(_MSC_VER) || defined(__clang__))
TEST_CASE("integer_literal_check_str_test")
{
// Decimal.
{
constexpr char str[] = {'0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '1', '5', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
constexpr char str[] = {'9', '1', '5', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 10);
}
{
char str[] = {'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'1', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'a', '1', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'1', '2', '.', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'1', '2', 'e', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
// Binary.
{
constexpr char str[] = {'0', 'b', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'B', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'b', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'B', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'b', '0', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
constexpr char str[] = {'0', 'B', '0', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 2);
}
{
char str[] = {'0', 'b', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'B', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'b', '2', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'B', '2', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'b', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'B', 'f', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
// Octal.
{
constexpr char str[] = {'0', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '2', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '1', '2', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
constexpr char str[] = {'0', '0', '7', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 8);
}
{
char str[] = {'0', '9', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '1', 'a', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '7', '8', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '1', '.', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', '3', 'e', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
// Hex.
{
constexpr char str[] = {'0', 'x', '1', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'X', 'f', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'x', 'F', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'X', '0', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'x', 'a', 'B', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
constexpr char str[] = {'0', 'X', 'C', 'd', '\0'};
constexpr auto b = detail::integer_literal_check_str(str);
REQUIRE(b == 16);
}
{
char str[] = {'0', 'x', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'X', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'x', 'g', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'X', 'G', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'x', '.', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
{
char str[] = {'0', 'X', 'p', '\0'};
REQUIRE_THROWS_AS(detail::integer_literal_check_str(str), std::invalid_argument);
}
}
#endif
TEST_CASE("z1_test")
{
#if MPPP_CPLUSPLUS >= 201402L
REQUIRE(0b1101010010101001010100100101_z1 == integer<1>{"1101010010101001010100100101", 2});
REQUIRE(
0b1101010010101001010100100101010101010101010010101010010101010110101010101010101010110101010101001010101101010101010101010_z1
== integer<1>{"110101001010100101010010010101010101010101001010101001010101011010101010101010101011010101010100"
"1010101101010101010101010",
2});
#endif
REQUIRE(21309213209382109382190382190382109303821321002140982142139081_z1
== integer<1>{"21309213209382109382190382190382109303821321002140982142139081"});
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Mersenne twister random number generator.
*/
#ifndef __BASE_RANDOM_HH__
#define __BASE_RANDOM_HH__
#include <random>
#include <string>
#include <type_traits>
#include "base/compiler.hh"
#include "base/types.hh"
#include "sim/serialize.hh"
namespace gem5
{
class Checkpoint;
class Random : public Serializable
{
private:
std::mt19937_64 gen;
public:
/**
* @ingroup api_base_utils
* @{
*/
Random();
Random(uint32_t s);
/** @} */ // end of api_base_utils
~Random();
void init(uint32_t s);
/**
* Use the SFINAE idiom to choose an implementation based on
* whether the type is integral or floating point.
*
* @ingroup api_base_utils
*/
template <typename T>
typename std::enable_if_t<std::is_integral<T>::value, T>
random()
{
// [0, max_value] for integer types
std::uniform_int_distribution<T> dist;
return dist(gen);
}
/**
* @ingroup api_base_utils
*/
template <typename T>
typename std::enable_if_t<std::is_floating_point<T>::value, T>
random()
{
// [0, 1) for real types
std::uniform_real_distribution<T> dist;
return dist(gen);
}
/**
* @ingroup api_base_utils
*/
template <typename T>
typename std::enable_if_t<std::is_integral<T>::value, T>
random(T min, T max)
{
std::uniform_int_distribution<T> dist(min, max);
return dist(gen);
}
void serialize(CheckpointOut &cp) const override;
void unserialize(CheckpointIn &cp) override;
};
/**
* @ingroup api_base_utils
*/
extern Random random_mt;
} // namespace gem5
#endif // __BASE_RANDOM_HH__
<commit_msg>base: Make the random number generator public<commit_after>/*
* Copyright (c) 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Mersenne twister random number generator.
*/
#ifndef __BASE_RANDOM_HH__
#define __BASE_RANDOM_HH__
#include <random>
#include <string>
#include <type_traits>
#include "base/compiler.hh"
#include "base/types.hh"
#include "sim/serialize.hh"
namespace gem5
{
class Checkpoint;
class Random : public Serializable
{
public:
/**
* @ingroup api_base_utils
*/
std::mt19937_64 gen;
/**
* @ingroup api_base_utils
* @{
*/
Random();
Random(uint32_t s);
/** @} */ // end of api_base_utils
~Random();
void init(uint32_t s);
/**
* Use the SFINAE idiom to choose an implementation based on
* whether the type is integral or floating point.
*
* @ingroup api_base_utils
*/
template <typename T>
typename std::enable_if_t<std::is_integral<T>::value, T>
random()
{
// [0, max_value] for integer types
std::uniform_int_distribution<T> dist;
return dist(gen);
}
/**
* @ingroup api_base_utils
*/
template <typename T>
typename std::enable_if_t<std::is_floating_point<T>::value, T>
random()
{
// [0, 1) for real types
std::uniform_real_distribution<T> dist;
return dist(gen);
}
/**
* @ingroup api_base_utils
*/
template <typename T>
typename std::enable_if_t<std::is_integral<T>::value, T>
random(T min, T max)
{
std::uniform_int_distribution<T> dist(min, max);
return dist(gen);
}
void serialize(CheckpointOut &cp) const override;
void unserialize(CheckpointIn &cp) override;
};
/**
* @ingroup api_base_utils
*/
extern Random random_mt;
} // namespace gem5
#endif // __BASE_RANDOM_HH__
<|endoftext|> |
<commit_before>#include <cgo/base/state.hpp>
using namespace cgo::base;
State::State() :
State(Board())
{}
State::State(const State::State& state) :
State(state._board)
{}
State::State(const State::Board& board) :
_board(board)
{}
State::~State() {}
const Marker& State::getMarker(const Position& position) const {
State::validatePosition(position);
return this->_board[State::getIndex(position)];
}
std::tuple< int, int > State::getScore() const {
// For now we are only counting the number of pieces on the board. Eventually
// we will want to add territory control.
int whiteScore = 0;
int blackScore = 0;
for (int ndx = 0; ndx < BOARD_DIMENSION * BOARD_DIMENSION; ++ndx) {
if (this->_board[ndx] == white) {
++whiteScore;
} else if (this->_board[ndx] == black) {
++blackScore;
}
}
return {whiteScore, blackScore};
}
std::vector< Position > State::getLiberties(Marker marker) {
State::validatePlayerMarker(marker);
int libertyIndex = (marker == black) ? 0 : 1;
std::vector< Position > liberties;
if (!this->_liberties[libertyIndex]) {
liberties = this->calculateLiberties(marker);
this->_liberties[libertyIndex] = liberties;
}
return liberties;
}
std::vector< std::tuple< Move, State > > State::getSuccessors(Marker marker,
boost::optional< std::tuple< Move, State > > predecessor) const {
State::validatePlayerMarker(marker);
std::vector< std::tuple< Move, State > > successors;
for (int row = 0; row < BOARD_DIMENSION; ++row) {
for (int col = 0; col < BOARD_DIMENSION; ++col) {
Position position(row, col);
Action action = {marker, position};
if (this->isActionValid(action, predecessor)) {
successors.push_back({action, State::applyAction(*this, action)});
}
}
}
successors.push_back({Pass(), *this});
return successors;
}
bool State::isActionValid(const Action& action,
boost::optional< std::tuple< Move, State > > predecessor) const {
Marker marker = action.marker;
State::validatePlayerMarker(marker);
Position position = action.position;
State::validatePosition(position);
int index = State::getIndex(position);
if (this->_board[index] != none) {
return false;
}
return true;
}
/* static */ State State::applyAction(const State& sourceState, const Action& action) {
Marker marker = action.marker;
State::validatePlayerMarker(marker);
Position position = action.position;
State::validatePosition(position);
int index = State::getIndex(position);
Board successorBoard = sourceState._board;
// Take the position.
successorBoard[index] = marker;
// And capture enemies.
// Unimplemented.
return State(successorBoard);
}
std::vector< Position > State::calculateLiberties(Marker marker) {
std::array< bool, BOARD_DIMENSION * BOARD_DIMENSION > hash;
hash.fill(false);
std::vector< Position > liberties;
for (int row = 0; row < BOARD_DIMENSION; ++row) {
for (int col = 0; col < BOARD_DIMENSION; ++col) {
unsigned int index = State::getIndex(Position(row, col));
if (this->_board[index] != marker) {
continue;
}
auto adjacentPositions = State::getAdjacentPositions(Position(row, col));
for (Position adjPos : adjacentPositions) {
unsigned int adjIndex = State::getIndex(adjPos);
if (hash[adjIndex]) {
continue;
}
if (this->_board[adjIndex] != none) {
continue;
}
hash[adjIndex] = true;
liberties.push_back(adjPos);
}
}
}
return liberties;
}
/* static */ void State::validateMarker(const Marker& marker) {
if (marker < first || marker > last) {
throw State::_invalidMarker;
}
}
/* static */ void State::validatePlayerMarker(const Marker& marker) {
State::validateMarker(marker);
if (marker == none) {
throw State::_invalidMarker;
}
}
/* static */ void State::validatePosition(const Position& position) {
if (position.row < 0 || position.row >= BOARD_DIMENSION ||
position.col < 0 || position.col >= BOARD_DIMENSION) {
throw State::_invalidPosition;
}
}
/* static */ unsigned int State::getIndex(const Position& position) {
return position.row * BOARD_DIMENSION + position.col;
}
/* static */ Position State::getPosition(unsigned int index) {
return Position(index / BOARD_DIMENSION, index % BOARD_DIMENSION);
}
/* static */ std::vector< Position > State::getAdjacentPositions(const Position& position) {
State::validatePosition(position);
std::vector< Position > adjacents;
int row = position.row;
int col = position.col;
if (position.row > 0) {
adjacents.push_back(Position(row - 1, col));
}
if (position.col > 0) {
adjacents.push_back(Position(row, col - 1));
}
if (position.row < BOARD_DIMENSION - 1) {
adjacents.push_back(Position(row + 1, col));
}
if (position.col < BOARD_DIMENSION - 1) {
adjacents.push_back(Position(row, col + 1));
}
return adjacents;
}
/* static */ State::InvalidMarker State::_invalidMarker;
/* static */ State::InvalidPosition State::_invalidPosition;
<commit_msg>Make some style and nomenclature changes<commit_after>#include <cgo/base/state.hpp>
using namespace cgo::base;
State::State() :
State(Board())
{}
State::State(const State::State& state) :
State(state._board)
{}
State::State(const State::Board& board) :
_board(board)
{}
State::~State() {}
const Marker& State::getMarker(const Position& position) const {
State::validatePosition(position);
return this->_board[State::getIndex(position)];
}
std::tuple< int, int > State::getScore() const {
int whiteScore = 0;
int blackScore = 0;
// Count number of pieces.
for (int ndx = 0; ndx < BOARD_DIMENSION * BOARD_DIMENSION; ++ndx) {
if (this->_board[ndx] == white) {
++whiteScore;
} else if (this->_board[ndx] == black) {
++blackScore;
}
}
// Calculate territory controlled.
// Unimplemented.
return {whiteScore, blackScore};
}
std::vector< Position > State::getLiberties(Marker marker) {
State::validatePlayerMarker(marker);
int libertyIndex = (marker == black) ? 0 : 1;
std::vector< Position > liberties;
if (!this->_liberties[libertyIndex]) {
liberties = this->calculateLiberties(marker);
this->_liberties[libertyIndex] = liberties;
}
return liberties;
}
std::vector< std::tuple< Move, State > > State::getSuccessors(Marker marker,
boost::optional< std::tuple< Move, State > > predecessor) const {
State::validatePlayerMarker(marker);
std::vector< std::tuple< Move, State > > successors;
for (int row = 0; row < BOARD_DIMENSION; ++row) {
for (int col = 0; col < BOARD_DIMENSION; ++col) {
Position position(row, col);
Action action = {marker, position};
if (this->isActionValid(action, predecessor)) {
successors.push_back({action, State::applyAction(*this, action)});
}
}
}
successors.push_back({Pass(), *this});
return successors;
}
bool State::isActionValid(const Action& action,
boost::optional< std::tuple< Move, State > > predecessor) const {
Marker marker = action.marker;
State::validatePlayerMarker(marker);
Position position = action.position;
State::validatePosition(position);
int index = State::getIndex(position);
if (this->_board[index] != none) {
return false;
}
return true;
}
/* static */ State State::applyAction(const State& sourceState,
const Action& action) {
Marker marker = action.marker;
State::validatePlayerMarker(marker);
Position position = action.position;
State::validatePosition(position);
int index = State::getIndex(position);
Board successorBoard = sourceState._board;
// Take the position.
successorBoard[index] = marker;
// And capture enemies.
// Unimplemented.
return State(successorBoard);
}
std::vector< Position > State::calculateLiberties(Marker marker) {
std::array< bool, BOARD_DIMENSION * BOARD_DIMENSION > seen;
seen.fill(false);
std::vector< Position > liberties;
for (int row = 0; row < BOARD_DIMENSION; ++row) {
for (int col = 0; col < BOARD_DIMENSION; ++col) {
unsigned int index = State::getIndex(Position(row, col));
if (this->_board[index] != marker) {
continue;
}
for (Position adjacentPosition :
State::getAdjacentPositions(Position(row, col))) {
unsigned int adjacentIndex = State::getIndex(adjacentPosition);
if (seen[adjacentIndex]) {
continue;
}
if (this->_board[adjacentIndex] != none) {
continue;
}
liberties.push_back(adjacentPosition);
seen[adjacentIndex] = true;
}
}
}
return liberties;
}
/* static */ void State::validateMarker(const Marker& marker) {
if (marker < first || marker > last) {
throw State::_invalidMarker;
}
}
/* static */ void State::validatePlayerMarker(const Marker& marker) {
State::validateMarker(marker);
if (marker == none) {
throw State::_invalidMarker;
}
}
/* static */ void State::validatePosition(const Position& position) {
if (position.row < 0 || position.row >= BOARD_DIMENSION ||
position.col < 0 || position.col >= BOARD_DIMENSION) {
throw State::_invalidPosition;
}
}
/* static */ unsigned int State::getIndex(const Position& position) {
return position.row * BOARD_DIMENSION + position.col;
}
/* static */ Position State::getPosition(unsigned int index) {
return Position(index / BOARD_DIMENSION, index % BOARD_DIMENSION);
}
/* static */ std::vector< Position > State::getAdjacentPositions(
const Position& position) {
State::validatePosition(position);
std::vector< Position > adjacents;
int row = position.row;
int col = position.col;
if (position.row > 0) {
adjacents.push_back(Position(row - 1, col));
}
if (position.col > 0) {
adjacents.push_back(Position(row, col - 1));
}
if (position.row < BOARD_DIMENSION - 1) {
adjacents.push_back(Position(row + 1, col));
}
if (position.col < BOARD_DIMENSION - 1) {
adjacents.push_back(Position(row, col + 1));
}
return adjacents;
}
/* static */ State::InvalidMarker State::_invalidMarker;
/* static */ State::InvalidPosition State::_invalidPosition;
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "parser.hpp"
#include "lexer.hpp"
#include "logger.hpp"
#include "environment.hpp"
#include <sstream>
#include <string>
TEST_CASE("Interpret an empty expression", "[dice]")
{
std::stringstream input{ "" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_int::id());
auto&& value = dynamic_cast<dice::type_int&>(*result).data();
REQUIRE(value == 0);
}
TEST_CASE("Interpret an arithmetic expression", "[dice]")
{
std::stringstream input{ "1 + 2 * 3 / 4 - 5" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_int::id());
auto&& value = dynamic_cast<dice::type_int&>(*result).data();
REQUIRE(value == -3);
}
TEST_CASE("Interpret a dice roll expression", "[dice]")
{
std::stringstream input{ "1d2d4" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_rand_var::id());
auto&& value = dynamic_cast<dice::type_rand_var&>(*result).data();
auto&& prob = value.probability();
REQUIRE(prob.find(1)->second == Approx(1 / 8.0));
REQUIRE(prob.find(2)->second == Approx(5 / 32.0));
REQUIRE(prob.find(3)->second == Approx(3 / 16.0));
REQUIRE(prob.find(4)->second == Approx(7 / 32.0));
REQUIRE(prob.find(5)->second == Approx(1 / 8.0));
REQUIRE(prob.find(6)->second == Approx(3 / 32.0));
REQUIRE(prob.find(7)->second == Approx(1 / 16.0));
REQUIRE(prob.find(8)->second == Approx(1 / 32.0));
}
TEST_CASE("Interpret a function call", "[dice]")
{
std::stringstream input{ "expectation(1d6)" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_double::id());
auto&& value = dynamic_cast<dice::type_double&>(*result).data();
REQUIRE(value == Approx(3.5));
}<commit_msg>Test handling errors at the beginning of an expr<commit_after>#include "catch.hpp"
#include "parser.hpp"
#include "lexer.hpp"
#include "logger.hpp"
#include "environment.hpp"
#include <sstream>
#include <string>
void test_error_message(std::stringstream& stream, const std::string& msg)
{
std::string error_msg;
std::getline(stream, error_msg);
// remove line, column number and "error:" string
auto pos = error_msg.find("error:") + 10;
while (pos < error_msg.size() && std::isspace(error_msg[pos]))
{
++pos;
}
error_msg = error_msg.substr(pos);
REQUIRE(error_msg == msg);
}
TEST_CASE("Interpret an empty expression", "[dice]")
{
std::stringstream input{ "" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_int::id());
auto&& value = dynamic_cast<dice::type_int&>(*result).data();
REQUIRE(value == 0);
}
TEST_CASE("Interpret an arithmetic expression", "[dice]")
{
std::stringstream input{ "1 + 2 * 3 / 4 - 5" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_int::id());
auto&& value = dynamic_cast<dice::type_int&>(*result).data();
REQUIRE(value == -3);
}
TEST_CASE("Interpret a dice roll expression", "[dice]")
{
std::stringstream input{ "1d2d4" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_rand_var::id());
auto&& value = dynamic_cast<dice::type_rand_var&>(*result).data();
auto&& prob = value.probability();
REQUIRE(prob.find(1)->second == Approx(1 / 8.0));
REQUIRE(prob.find(2)->second == Approx(5 / 32.0));
REQUIRE(prob.find(3)->second == Approx(3 / 16.0));
REQUIRE(prob.find(4)->second == Approx(7 / 32.0));
REQUIRE(prob.find(5)->second == Approx(1 / 8.0));
REQUIRE(prob.find(6)->second == Approx(3 / 32.0));
REQUIRE(prob.find(7)->second == Approx(1 / 16.0));
REQUIRE(prob.find(8)->second == Approx(1 / 32.0));
}
TEST_CASE("Interpret a function call", "[dice]")
{
std::stringstream input{ "expectation(1d6)" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(log.empty());
REQUIRE(result->type() == dice::type_double::id());
auto&& value = dynamic_cast<dice::type_double&>(*result).data();
REQUIRE(value == Approx(3.5));
}
TEST_CASE("Interpret an expression even if it starts with invalid symbols", "[dice]")
{
std::stringstream input{ "* ) 1 + 2 * 3" };
std::stringstream errors;
dice::logger log{ &errors };
dice::lexer lexer{ &input, &log };
dice::environment env;
dice::parser<dice::lexer, dice::logger, dice::environment> parser{ &lexer, &log, &env };
auto result = parser.parse();
REQUIRE(result->type() == dice::type_int::id());
auto&& value = dynamic_cast<dice::type_int&>(*result).data();
REQUIRE(value == 7);
REQUIRE(!log.empty());
test_error_message(errors, "Invalid token at the beginning of an expression: *");
test_error_message(errors, "Invalid token at the beginning of an expression: )");
REQUIRE(errors.peek() == EOF);
}
<|endoftext|> |
<commit_before>/* $Id: alara.C,v 1.11 2000-04-28 17:13:40 wilson Exp $ */
#include "alara.h"
#include "Input/Input.h"
#include "Chains/Root.h"
#include "Util/Statistics.h"
#include "Output/Result.h"
int chainCode = 0;
const char *SYMBOLS=" h he li be b c n o f ne na mg al si p s cl ar \
k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru \
rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm \
yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np \
pu am cm bk cf es fm md no lr ";
static char *id="$Name: not supported by cvs2svn $";
static char *helpmsg="\
usage: %s [-h] [-r] [-t <tree_filename>] [-V] [-v <n>] [<input_filename>] \n\
\t -h Show this message\n\
\t -r Restart option for calculating new respones\n\
\t -t <tree_filename> Create tree file with given name\n\
\t -V Show version\n\
\t -v <n> Set verbosity level\n\
\t <input_filename> Name of input file\n\
See Users' Guide (http://fti.neep.wisc.edu/ALARA) for more info.\n";
int main(int argc, char *argv[])
{
int argNum = 1;
int solved = FALSE;
char *inFname = NULL;
Root* rootList = new Root;
topSchedule* schedule;
verbose(-1,"ALARA %s",id);
while (argNum<argc)
{
if (argv[argNum][0] != '-')
if (inFname == NULL)
{
inFname = new char[strlen(argv[argNum])+1];
strcpy(inFname,argv[argNum]);
argNum++;
/* get next argument */
continue;
}
else
error(1,"Only one input filename can be specified: %s.",inFname);
while (argv[argNum][0] == '-')
argv[argNum]++;
switch (argv[argNum][0])
{
#ifdef DVLPR
case 'd':
if (argv[argNum][1] == '\0')
{
debug_level = atoi(argv[argNum+1]);
argNum+=2;
}
else
{
debug_level = atoi(argv[argNum]+1);
argNum++;
}
debug(0,"Set debug level to %d.",debug_level);
break;
#endif
case 'v':
if (argv[argNum][1] == '\0')
{
verb_level = atoi(argv[argNum+1]);
argNum+=2;
}
else
{
verb_level = atoi(argv[argNum]+1);
argNum++;
}
verbose(0,"Set verbose level to %d.",verb_level);
break;
case 'r':
verbose(0,"Reusing binary dump data.");
solved=TRUE;
argNum+=1;
break;
case 't':
if (argv[argNum][1] == '\0')
{
Statistics::initTree(argv[argNum+1]);
verbose(0,"Openned tree file %s.",argv[argNum+1]);
argNum+=2;
}
else
{
Statistics::initTree(argv[argNum]+1);
verbose(0,"Openned tree file %s.",argv[argNum]+1);
argNum++;
}
break;
case 'h':
verbose(-1,helpmsg,argv[0]);
case 'V':
exit(0);
break;
default:
{
verbose(-1,helpmsg,argv[0]);
error(0,"Invlaid option: %s.",argv[argNum]);
}
}
}
Input problemInput(inFname);
/* INPUT */
verbose(0,"Starting problem input processing.");
verbose(1,"Reading input.");
problemInput.read();
verbose(1,"Cross-checking input for completeness and self-consistency.");
problemInput.xCheck();
verbose(1,"Preprocessing input.");
problemInput.preProc(rootList,schedule);
if (!solved)
{
verbose(0,"Starting problem solution.");
rootList->solve(schedule);
verbose(1,"Solved problem.");
}
Result::resetBinDump();
problemInput.postProc(rootList);
verbose(0,"Output.");
Result::closeBinDump();
delete rootList;
}
<commit_msg>Updated URL in command-line help.<commit_after>/* $Id: alara.C,v 1.12 2001-07-10 20:48:33 wilsonp Exp $ */
#include "alara.h"
#include "Input/Input.h"
#include "Chains/Root.h"
#include "Util/Statistics.h"
#include "Output/Result.h"
int chainCode = 0;
const char *SYMBOLS=" h he li be b c n o f ne na mg al si p s cl ar \
k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru \
rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm \
yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np \
pu am cm bk cf es fm md no lr ";
static char *id="$Name: not supported by cvs2svn $";
static char *helpmsg="\
usage: %s [-h] [-r] [-t <tree_filename>] [-V] [-v <n>] [<input_filename>] \n\
\t -h Show this message\n\
\t -r Restart option for calculating new respones\n\
\t -t <tree_filename> Create tree file with given name\n\
\t -V Show version\n\
\t -v <n> Set verbosity level\n\
\t <input_filename> Name of input file\n\
See Users' Guide for more info.\n\
(http://www.cae.wisc.edu/~wilsonp/projects/ALARA/users.guide.html/)\n";
int main(int argc, char *argv[])
{
int argNum = 1;
int solved = FALSE;
char *inFname = NULL;
Root* rootList = new Root;
topSchedule* schedule;
verbose(-1,"ALARA %s",id);
while (argNum<argc)
{
if (argv[argNum][0] != '-')
if (inFname == NULL)
{
inFname = new char[strlen(argv[argNum])+1];
strcpy(inFname,argv[argNum]);
argNum++;
/* get next argument */
continue;
}
else
error(1,"Only one input filename can be specified: %s.",inFname);
while (argv[argNum][0] == '-')
argv[argNum]++;
switch (argv[argNum][0])
{
#ifdef DVLPR
case 'd':
if (argv[argNum][1] == '\0')
{
debug_level = atoi(argv[argNum+1]);
argNum+=2;
}
else
{
debug_level = atoi(argv[argNum]+1);
argNum++;
}
debug(0,"Set debug level to %d.",debug_level);
break;
#endif
case 'v':
if (argv[argNum][1] == '\0')
{
verb_level = atoi(argv[argNum+1]);
argNum+=2;
}
else
{
verb_level = atoi(argv[argNum]+1);
argNum++;
}
verbose(0,"Set verbose level to %d.",verb_level);
break;
case 'r':
verbose(0,"Reusing binary dump data.");
solved=TRUE;
argNum+=1;
break;
case 't':
if (argv[argNum][1] == '\0')
{
Statistics::initTree(argv[argNum+1]);
verbose(0,"Openned tree file %s.",argv[argNum+1]);
argNum+=2;
}
else
{
Statistics::initTree(argv[argNum]+1);
verbose(0,"Openned tree file %s.",argv[argNum]+1);
argNum++;
}
break;
case 'h':
verbose(-1,helpmsg,argv[0]);
case 'V':
exit(0);
break;
default:
{
verbose(-1,helpmsg,argv[0]);
error(0,"Invlaid option: %s.",argv[argNum]);
}
}
}
Input problemInput(inFname);
/* INPUT */
verbose(0,"Starting problem input processing.");
verbose(1,"Reading input.");
problemInput.read();
verbose(1,"Cross-checking input for completeness and self-consistency.");
problemInput.xCheck();
verbose(1,"Preprocessing input.");
problemInput.preProc(rootList,schedule);
if (!solved)
{
verbose(0,"Starting problem solution.");
rootList->solve(schedule);
verbose(1,"Solved problem.");
}
Result::resetBinDump();
problemInput.postProc(rootList);
verbose(0,"Output.");
Result::closeBinDump();
delete rootList;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#include <gui/application.h>
#include <gui/cocoa_style.h>
#include <gui/container.h>
#include <gui/layouts.h>
#include <gui/label.h>
#include <gui/button.h>
#include <gui/slider.h>
#include <gui/color.h>
#include <gui/scroll_area.h>
#include <gui/tree_node.h>
#include <gui/line_edit.h>
namespace {
struct test_record : public model::record
{
field<std::string> title = field<std::string>( this );
field<double> rating = field<double>( this, 0.5 );
};
std::shared_ptr<test_record> testrec = std::make_shared<test_record>();
////////////////////////////////////////
std::shared_ptr<gui::form> build_form( direction dir )
{
auto container = std::make_shared<gui::form>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
auto button = std::make_shared<gui::button>( "Click Me" );
button->when_activated += []()
{
testrec->title = "Goodbye World";
};
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ), button );
container->add( std::make_shared<gui::label>( "What" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
container->add( std::make_shared<gui::label>( "Who" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::grid> build_grid( direction dir )
{
auto container = std::make_shared<gui::grid>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
const double weights[5] = { 0.25, 0.5, 1.0, 0.5, 0.25 };
for ( size_t y = 0; y < 5; ++y )
{
row.clear();
for ( size_t x = 0; x < 5; ++x )
{
row.push_back( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
container->add_row( row, weights[y] );
}
for ( size_t y = 0; y < 5; ++y )
container->set_column_weight( y, weights[y] );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_box( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
for ( size_t y = 0; y < 5; ++y )
{
container->add( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::tree_node> build_tree( direction dir )
{
auto container = std::make_shared<gui::tree_node>( 24.0, dir );
container->set_root( std::make_shared<gui::label>( "Root" ) );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
std::string name( "A" );
for ( size_t y = 0; y < 3; ++y )
{
auto node = std::make_shared<gui::tree_node>( 24.0, dir );
if( y == 1 )
{
auto button = std::make_shared<gui::button>( "+" );
button->when_activated += [=]( void )
{
node->set_collapsed( !node->collapsed() );
};
node->set_root( button );
}
else
node->set_root( std::make_shared<gui::label>( name ) );
std::string sub( "1" );
for ( size_t x = 0; x < 3; ++x )
{
node->add( std::make_shared<gui::label>( sub ) );
node->set_spacing( 12, 6 );
++sub[0];
}
container->add( node );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_edit( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ) );
container->add( std::make_shared<gui::line_edit>( model::make_datum( testrec, testrec->title ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_all( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
std::vector<std::shared_ptr<gui::widget>> list = { build_form( dir ), build_grid( dir ), build_box( dir ), build_tree( dir ) };
for ( auto c: list )
container->add( c );
container->set_weight( 1, 1.0 );
return container;
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
testrec->title = "Hello World";
auto app = std::make_shared<gui::application>();
app->push();
app->set_style( std::make_shared<gui::cocoa_style>() );
auto win = app->new_window();
win->set_title( "Test Application" );
std::string test = "form";
if ( argc > 1 )
test = argv[1];
std::string dirname = "box";
if ( argc > 2 )
dirname = argv[2];
direction dir = direction::DOWN;
if ( dirname == "down" )
dir = direction::DOWN;
else if ( dirname == "up" )
dir = direction::UP;
else if ( dirname == "left" )
dir = direction::LEFT;
else if ( dirname == "right" )
dir = direction::RIGHT;
if ( test == "form" )
win->set_widget( build_form( dir ) );
else if ( test == "grid" )
win->set_widget( build_grid( dir ) );
else if ( test == "box" )
win->set_widget( build_box( dir ) );
else if ( test == "tree" )
win->set_widget( build_tree( dir ) );
else if ( test == "edit" )
win->set_widget( build_edit( dir ) );
else if ( test == "all" )
win->set_widget( build_all( dir ) );
else
throw std::runtime_error( "unknown test" );
win->show();
int code = app->run();
app->pop();
return code;
}
////////////////////////////////////////
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<commit_msg>Set title to platform name.<commit_after>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#include <gui/application.h>
#include <gui/cocoa_style.h>
#include <gui/container.h>
#include <gui/layouts.h>
#include <gui/label.h>
#include <gui/button.h>
#include <gui/slider.h>
#include <gui/color.h>
#include <gui/scroll_area.h>
#include <gui/tree_node.h>
#include <gui/line_edit.h>
namespace {
struct test_record : public model::record
{
field<std::string> title = field<std::string>( this );
field<double> rating = field<double>( this, 0.5 );
};
std::shared_ptr<test_record> testrec = std::make_shared<test_record>();
////////////////////////////////////////
std::shared_ptr<gui::form> build_form( direction dir )
{
auto container = std::make_shared<gui::form>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
auto button = std::make_shared<gui::button>( "Click Me" );
button->when_activated += []()
{
testrec->title = "Goodbye World";
};
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ), button );
container->add( std::make_shared<gui::label>( "What" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
container->add( std::make_shared<gui::label>( "Who" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::grid> build_grid( direction dir )
{
auto container = std::make_shared<gui::grid>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
const double weights[5] = { 0.25, 0.5, 1.0, 0.5, 0.25 };
for ( size_t y = 0; y < 5; ++y )
{
row.clear();
for ( size_t x = 0; x < 5; ++x )
{
row.push_back( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
container->add_row( row, weights[y] );
}
for ( size_t y = 0; y < 5; ++y )
container->set_column_weight( y, weights[y] );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_box( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
std::string name( "A" );
std::vector<std::shared_ptr<gui::widget>> row;
for ( size_t y = 0; y < 5; ++y )
{
container->add( std::make_shared<gui::label>( name, alignment::CENTER ) );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::tree_node> build_tree( direction dir )
{
auto container = std::make_shared<gui::tree_node>( 24.0, dir );
container->set_root( std::make_shared<gui::label>( "Root" ) );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
std::string name( "A" );
for ( size_t y = 0; y < 3; ++y )
{
auto node = std::make_shared<gui::tree_node>( 24.0, dir );
if( y == 1 )
{
auto button = std::make_shared<gui::button>( "+" );
button->when_activated += [=]( void )
{
node->set_collapsed( !node->collapsed() );
};
node->set_root( button );
}
else
node->set_root( std::make_shared<gui::label>( name ) );
std::string sub( "1" );
for ( size_t x = 0; x < 3; ++x )
{
node->add( std::make_shared<gui::label>( sub ) );
node->set_spacing( 12, 6 );
++sub[0];
}
container->add( node );
++name[0];
}
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_edit( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
container->set_pad( 12.5, 12.5, 12.5, 12.5 );
container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ) );
container->add( std::make_shared<gui::line_edit>( model::make_datum( testrec, testrec->title ) ) );
return container;
}
////////////////////////////////////////
std::shared_ptr<gui::simple_container> build_all( direction dir )
{
auto container = std::make_shared<gui::simple_container>( dir );
container->set_spacing( 12, 6 );
std::vector<std::shared_ptr<gui::widget>> list = { build_form( dir ), build_grid( dir ), build_box( dir ), build_tree( dir ) };
for ( auto c: list )
container->add( c );
container->set_weight( 1, 1.0 );
return container;
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
testrec->title = "Hello World";
auto app = std::make_shared<gui::application>();
app->push();
app->set_style( std::make_shared<gui::cocoa_style>() );
auto win = app->new_window();
win->set_title( app->active_platform() );
std::string test = "form";
if ( argc > 1 )
test = argv[1];
std::string dirname = "box";
if ( argc > 2 )
dirname = argv[2];
direction dir = direction::DOWN;
if ( dirname == "down" )
dir = direction::DOWN;
else if ( dirname == "up" )
dir = direction::UP;
else if ( dirname == "left" )
dir = direction::LEFT;
else if ( dirname == "right" )
dir = direction::RIGHT;
if ( test == "form" )
win->set_widget( build_form( dir ) );
else if ( test == "grid" )
win->set_widget( build_grid( dir ) );
else if ( test == "box" )
win->set_widget( build_box( dir ) );
else if ( test == "tree" )
win->set_widget( build_tree( dir ) );
else if ( test == "edit" )
win->set_widget( build_edit( dir ) );
else if ( test == "all" )
win->set_widget( build_all( dir ) );
else
throw std::runtime_error( "unknown test" );
win->show();
int code = app->run();
app->pop();
return code;
}
////////////////////////////////////////
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<|endoftext|> |
<commit_before>/**
* Copyright 2008 Matthew Graham
* 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 "snapl/message_arg.h"
#include "snapl/arg.h"
#include <testpp/test.h>
/**
* Test that a message argument is constructed properly.
*/
TESTPP( test_message_arg_constructor )
{
message_arg_c arg( "dog" );
assertpp( arg.get() ) == "dog";
}
/**
* Test that the message arg list constructor works.
*/
TESTPP( test_message_arg_list_constructor )
{
message_arg_list_c arg_list;
assertpp( arg_list.argc() ) == 0;
}
/**
* Test that the message_arg_list correctly parses quoted strings
*/
TESTPP( test_message_arg_list_parse_quoted_args )
{
not_implemented( 2009, 2, 1 );
return;
message_arg_list_c args;
args.parse( "dog \"cat mouse\"" );
assertpp( args.argc() ) == 2;
assertpp( args.argv( 0 ) ) == "dog";
assertpp( args.argv( 1 ) ) == "cat mouse";
}
/**
* Test copying values from an arg_list into a message_arg_list.
*/
TESTPP( test_copy_arg_list )
{
int num( 5 );
std::string text( "dog" );
arg_list_c arg;
arg << num << text;
message_arg_list_c msg_list;
msg_list = arg;
assertpp( msg_list.argv(0) ) == "5";
// assertpp( msg_list.argv(1) ) == "dog";
}
<commit_msg>later expiration for msg_arg reading quoted strings<commit_after>/**
* Copyright 2008 Matthew Graham
* 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 "snapl/message_arg.h"
#include "snapl/arg.h"
#include <testpp/test.h>
/**
* Test that a message argument is constructed properly.
*/
TESTPP( test_message_arg_constructor )
{
message_arg_c arg( "dog" );
assertpp( arg.get() ) == "dog";
}
/**
* Test that the message arg list constructor works.
*/
TESTPP( test_message_arg_list_constructor )
{
message_arg_list_c arg_list;
assertpp( arg_list.argc() ) == 0;
}
/**
* Test that the message_arg_list correctly parses quoted strings
*/
TESTPP( test_message_arg_list_parse_quoted_args )
{
not_implemented( 2009, 3, 1 );
return;
message_arg_list_c args;
args.parse( "dog \"cat mouse\"" );
assertpp( args.argc() ) == 2;
assertpp( args.argv( 0 ) ) == "dog";
assertpp( args.argv( 1 ) ) == "cat mouse";
}
/**
* Test copying values from an arg_list into a message_arg_list.
*/
TESTPP( test_copy_arg_list )
{
int num( 5 );
std::string text( "dog" );
arg_list_c arg;
arg << num << text;
message_arg_list_c msg_list;
msg_list = arg;
assertpp( msg_list.argv(0) ) == "5";
// assertpp( msg_list.argv(1) ) == "dog";
}
<|endoftext|> |
<commit_before>#include "btf.h"
#include "bpftrace.h"
#include "types.h"
#include "utils.h"
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <linux/limits.h>
#include <regex>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <unistd.h>
#ifdef HAVE_LIBBPF_BTF_DUMP
#include <linux/bpf.h>
#include <linux/btf.h>
#include <bpf/btf.h>
#include <bpf/libbpf.h>
namespace bpftrace {
static unsigned char *get_data(const char *file, ssize_t *sizep)
{
struct stat st;
if (stat(file, &st))
return nullptr;
FILE *f;
f = fopen(file, "rb");
if (!f)
return nullptr;
unsigned char *data;
unsigned int size;
size = st.st_size;
data = (unsigned char *) malloc(size);
if (!data)
{
fclose(f);
return nullptr;
}
ssize_t ret = fread(data, 1, st.st_size, f);
if (ret != st.st_size)
{
free(data);
fclose(f);
return nullptr;
}
fclose(f);
*sizep = size;
return data;
}
static struct btf* btf_raw(char *file)
{
unsigned char *data;
ssize_t size;
struct btf *btf;
data = get_data(file, &size);
if (!data)
{
std::cerr << "BTF: failed to read data from: " << file << std::endl;
return nullptr;
}
btf = btf__new(data, (__u32) size);
free(data);
return btf;
}
static int libbpf_print(enum libbpf_print_level level, const char *msg, va_list ap)
{
fprintf(stderr, "BTF: (%d) ", level);
return vfprintf(stderr, msg, ap);
}
static struct btf *btf_open(const struct vmlinux_location *locs)
{
struct utsname buf;
uname(&buf);
for (int i = 0; locs[i].path; i++)
{
char path[PATH_MAX + 1];
snprintf(path, PATH_MAX, locs[i].path, buf.release);
if (access(path, R_OK))
continue;
struct btf *btf;
if (locs[i].raw)
btf = btf_raw(path);
else
btf = btf__parse_elf(path, nullptr);
int err = libbpf_get_error(btf);
if (err)
{
if (bt_verbose)
{
char err_buf[256];
libbpf_strerror(libbpf_get_error(btf), err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to read data (" << err_buf << ") from: " << path << std::endl;
}
continue;
}
if (bt_verbose)
{
std::cerr << "BTF: using data from " << path << std::endl;
}
return btf;
}
return nullptr;
}
BTF::BTF(void) : btf(nullptr), state(NODATA)
{
struct vmlinux_location locs_env[] = {
{ nullptr, true },
{ nullptr, false },
};
const struct vmlinux_location *locs = vmlinux_locs;
// Try to get BTF file from BPFTRACE_BTF env
char *path = std::getenv("BPFTRACE_BTF");
if (path)
{
locs_env[0].path = path;
locs = locs_env;
}
btf = btf_open(locs);
if (btf)
{
libbpf_set_print(libbpf_print);
state = OK;
}
else if (bt_debug != DebugLevel::kNone)
{
std::cerr << "BTF: failed to find BTF data " << std::endl;
}
}
BTF::~BTF()
{
btf__free(btf);
}
static void dump_printf(void *ctx, const char *fmt, va_list args)
{
std::string *ret = static_cast<std::string*>(ctx);
char *str;
if (vasprintf(&str, fmt, args) < 0)
return;
*ret += str;
free(str);
}
static const char *btf_str(const struct btf *btf, __u32 off)
{
if (!off)
return "(anon)";
return btf__name_by_offset(btf, off) ? : "(invalid)";
}
static std::string full_type_str(const struct btf *btf, const struct btf_type *type)
{
const char *str = btf_str(btf, type->name_off);
if (BTF_INFO_KIND(type->info) == BTF_KIND_STRUCT)
return std::string("struct ") + str;
if (BTF_INFO_KIND(type->info) == BTF_KIND_UNION)
return std::string("union ") + str;
return str;
}
static std::string btf_type_str(const std::string& type)
{
return std::regex_replace(type, std::regex("^(struct )|(union )"), "");
}
std::string BTF::c_def(std::unordered_set<std::string>& set)
{
std::string ret = std::string("");
struct btf_dump_opts opts = { .ctx = &ret, };
struct btf_dump *dump;
char err_buf[256];
int err;
dump = btf_dump__new(btf, nullptr, &opts, dump_printf);
err = libbpf_get_error(dump);
if (err)
{
libbpf_strerror(err, err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to initialize dump (" << err_buf << ")" << std::endl;
return std::string("");
}
std::unordered_set<std::string> myset(set);
__s32 id, max = (__s32) btf__get_nr_types(btf);
for (id = 1; id <= max && myset.size(); id++)
{
const struct btf_type *t = btf__type_by_id(btf, id);
std::string str = full_type_str(btf, t);
auto it = myset.find(str);
if (it != myset.end())
{
btf_dump__dump_type(dump, id);
myset.erase(it);
}
}
btf_dump__free(dump);
return ret;
}
std::string BTF::type_of(const std::string& name, const std::string& field)
{
__s32 type_id = btf__find_by_name(btf, btf_type_str(name).c_str());
if (type_id < 0)
return std::string("");
const struct btf_type *type = btf__type_by_id(btf, type_id);
return type_of(type, field);
}
std::string BTF::type_of(const btf_type *type, const std::string &field)
{
if (!type ||
(BTF_INFO_KIND(type->info) != BTF_KIND_STRUCT &&
BTF_INFO_KIND(type->info) != BTF_KIND_UNION))
return std::string("");
// We need to walk through oaa the struct/union members
// and try to find the requested field name.
//
// More info on struct/union members:
// https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-union
const struct btf_member *m = reinterpret_cast<const struct btf_member*>(type + 1);
for (unsigned int i = 0; i < BTF_INFO_VLEN(type->info); i++)
{
std::string m_name = btf__name_by_offset(btf, m[i].name_off);
// anonymous struct/union
if (m_name == "")
{
const struct btf_type *type = btf__type_by_id(btf, m[i].type);
std::string type_name = type_of(type, field);
if (!type_name.empty())
return type_name;
}
if (m_name != field)
continue;
const struct btf_type *f = btf__type_by_id(btf, m[i].type);
if (!f)
break;
// Get rid of all the pointers on the way to the actual type.
while (BTF_INFO_KIND(f->info) == BTF_KIND_PTR) {
f = btf__type_by_id(btf, f->type);
}
return full_type_str(btf, f);
}
return std::string("");
}
} // namespace bpftrace
#else // HAVE_LIBBPF_BTF_DUMP
namespace bpftrace {
BTF::BTF() { }
BTF::~BTF() { }
std::string BTF::c_def(std::unordered_set<std::string>& set __attribute__((__unused__))) { return std::string(""); }
std::string BTF::type_of(const std::string& name __attribute__((__unused__)),
const std::string& field __attribute__((__unused__))) {
return std::string("");
}
} // namespace bpftrace
#endif // HAVE_LIBBPF_BTF_DUMP
<commit_msg>Disable -Wcast-qual for bpf/btf.h<commit_after>#include "btf.h"
#include "bpftrace.h"
#include "types.h"
#include "utils.h"
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <linux/limits.h>
#include <regex>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <unistd.h>
#ifdef HAVE_LIBBPF_BTF_DUMP
#include <linux/bpf.h>
#include <linux/btf.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#include <bpf/btf.h>
#pragma GCC diagnostic pop
#include <bpf/libbpf.h>
namespace bpftrace {
static unsigned char *get_data(const char *file, ssize_t *sizep)
{
struct stat st;
if (stat(file, &st))
return nullptr;
FILE *f;
f = fopen(file, "rb");
if (!f)
return nullptr;
unsigned char *data;
unsigned int size;
size = st.st_size;
data = (unsigned char *) malloc(size);
if (!data)
{
fclose(f);
return nullptr;
}
ssize_t ret = fread(data, 1, st.st_size, f);
if (ret != st.st_size)
{
free(data);
fclose(f);
return nullptr;
}
fclose(f);
*sizep = size;
return data;
}
static struct btf* btf_raw(char *file)
{
unsigned char *data;
ssize_t size;
struct btf *btf;
data = get_data(file, &size);
if (!data)
{
std::cerr << "BTF: failed to read data from: " << file << std::endl;
return nullptr;
}
btf = btf__new(data, (__u32) size);
free(data);
return btf;
}
static int libbpf_print(enum libbpf_print_level level, const char *msg, va_list ap)
{
fprintf(stderr, "BTF: (%d) ", level);
return vfprintf(stderr, msg, ap);
}
static struct btf *btf_open(const struct vmlinux_location *locs)
{
struct utsname buf;
uname(&buf);
for (int i = 0; locs[i].path; i++)
{
char path[PATH_MAX + 1];
snprintf(path, PATH_MAX, locs[i].path, buf.release);
if (access(path, R_OK))
continue;
struct btf *btf;
if (locs[i].raw)
btf = btf_raw(path);
else
btf = btf__parse_elf(path, nullptr);
int err = libbpf_get_error(btf);
if (err)
{
if (bt_verbose)
{
char err_buf[256];
libbpf_strerror(libbpf_get_error(btf), err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to read data (" << err_buf << ") from: " << path << std::endl;
}
continue;
}
if (bt_verbose)
{
std::cerr << "BTF: using data from " << path << std::endl;
}
return btf;
}
return nullptr;
}
BTF::BTF(void) : btf(nullptr), state(NODATA)
{
struct vmlinux_location locs_env[] = {
{ nullptr, true },
{ nullptr, false },
};
const struct vmlinux_location *locs = vmlinux_locs;
// Try to get BTF file from BPFTRACE_BTF env
char *path = std::getenv("BPFTRACE_BTF");
if (path)
{
locs_env[0].path = path;
locs = locs_env;
}
btf = btf_open(locs);
if (btf)
{
libbpf_set_print(libbpf_print);
state = OK;
}
else if (bt_debug != DebugLevel::kNone)
{
std::cerr << "BTF: failed to find BTF data " << std::endl;
}
}
BTF::~BTF()
{
btf__free(btf);
}
static void dump_printf(void *ctx, const char *fmt, va_list args)
{
std::string *ret = static_cast<std::string*>(ctx);
char *str;
if (vasprintf(&str, fmt, args) < 0)
return;
*ret += str;
free(str);
}
static const char *btf_str(const struct btf *btf, __u32 off)
{
if (!off)
return "(anon)";
return btf__name_by_offset(btf, off) ? : "(invalid)";
}
static std::string full_type_str(const struct btf *btf, const struct btf_type *type)
{
const char *str = btf_str(btf, type->name_off);
if (BTF_INFO_KIND(type->info) == BTF_KIND_STRUCT)
return std::string("struct ") + str;
if (BTF_INFO_KIND(type->info) == BTF_KIND_UNION)
return std::string("union ") + str;
return str;
}
static std::string btf_type_str(const std::string& type)
{
return std::regex_replace(type, std::regex("^(struct )|(union )"), "");
}
std::string BTF::c_def(std::unordered_set<std::string>& set)
{
std::string ret = std::string("");
struct btf_dump_opts opts = { .ctx = &ret, };
struct btf_dump *dump;
char err_buf[256];
int err;
dump = btf_dump__new(btf, nullptr, &opts, dump_printf);
err = libbpf_get_error(dump);
if (err)
{
libbpf_strerror(err, err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to initialize dump (" << err_buf << ")" << std::endl;
return std::string("");
}
std::unordered_set<std::string> myset(set);
__s32 id, max = (__s32) btf__get_nr_types(btf);
for (id = 1; id <= max && myset.size(); id++)
{
const struct btf_type *t = btf__type_by_id(btf, id);
std::string str = full_type_str(btf, t);
auto it = myset.find(str);
if (it != myset.end())
{
btf_dump__dump_type(dump, id);
myset.erase(it);
}
}
btf_dump__free(dump);
return ret;
}
std::string BTF::type_of(const std::string& name, const std::string& field)
{
__s32 type_id = btf__find_by_name(btf, btf_type_str(name).c_str());
if (type_id < 0)
return std::string("");
const struct btf_type *type = btf__type_by_id(btf, type_id);
return type_of(type, field);
}
std::string BTF::type_of(const btf_type *type, const std::string &field)
{
if (!type ||
(BTF_INFO_KIND(type->info) != BTF_KIND_STRUCT &&
BTF_INFO_KIND(type->info) != BTF_KIND_UNION))
return std::string("");
// We need to walk through oaa the struct/union members
// and try to find the requested field name.
//
// More info on struct/union members:
// https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-union
const struct btf_member *m = reinterpret_cast<const struct btf_member*>(type + 1);
for (unsigned int i = 0; i < BTF_INFO_VLEN(type->info); i++)
{
std::string m_name = btf__name_by_offset(btf, m[i].name_off);
// anonymous struct/union
if (m_name == "")
{
const struct btf_type *type = btf__type_by_id(btf, m[i].type);
std::string type_name = type_of(type, field);
if (!type_name.empty())
return type_name;
}
if (m_name != field)
continue;
const struct btf_type *f = btf__type_by_id(btf, m[i].type);
if (!f)
break;
// Get rid of all the pointers on the way to the actual type.
while (BTF_INFO_KIND(f->info) == BTF_KIND_PTR) {
f = btf__type_by_id(btf, f->type);
}
return full_type_str(btf, f);
}
return std::string("");
}
} // namespace bpftrace
#else // HAVE_LIBBPF_BTF_DUMP
namespace bpftrace {
BTF::BTF() { }
BTF::~BTF() { }
std::string BTF::c_def(std::unordered_set<std::string>& set __attribute__((__unused__))) { return std::string(""); }
std::string BTF::type_of(const std::string& name __attribute__((__unused__)),
const std::string& field __attribute__((__unused__))) {
return std::string("");
}
} // namespace bpftrace
#endif // HAVE_LIBBPF_BTF_DUMP
<|endoftext|> |
<commit_before>/*
* server_test_base.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <mparisdiaz@gmail.com>
* Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "server_test_base.hpp"
#define BOOST_TEST_MODULE ServerTest
#include <boost/test/unit_test.hpp>
#include <unistd.h>
#include <sys/wait.h>
#include <glib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <transport/TSocket.h>
#include <protocol/TBinaryProtocol.h>
#include <gst/gst.h>
#include "media_config.hpp"
#include "mediaServer_types.h"
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
#define GST_CAT_DEFAULT _server_test_base_
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "server_test_base"
#define MAX_RETRIES 5
G_LOCK_DEFINE (mutex);
static void
sig_handler (int sig)
{
if (sig == SIGCONT)
G_UNLOCK (mutex);
}
int
start_server_test ()
{
pid_t childpid = -1;
gchar *conf_file, *conf_file_param;
conf_file = getenv ("MEDIA_SERVER_CONF_FILE");
if (conf_file == NULL) {
return -1;
}
conf_file_param = g_strconcat ("--conf-file=", conf_file, NULL);
signal (SIGCONT, sig_handler);
G_LOCK (mutex);
childpid = fork();
if (childpid >= 0) {
if (childpid == 0) {
execl ("./server/kurento", "kurento", conf_file_param, "--gst-plugin-path=../gst-kurento-plugins/src", NULL);
} else {
G_LOCK (mutex);
G_UNLOCK (mutex);
}
} else {
BOOST_FAIL ("Error executing server");
}
return childpid;
}
void
stop_server_test (int pid)
{
int status;
kill (pid, SIGINT);
wait (&status);
}
F::F()
{
int i;
gst_init (NULL, NULL);
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME);
GST_DEBUG ("setup fixture");
pid = start_server_test(); // TODO: check pid < 0
boost::shared_ptr<TSocket> socket (new TSocket (MEDIA_SERVER_ADDRESS, MEDIA_SERVER_SERVICE_PORT) );
transport = boost::shared_ptr<TTransport> (new TFramedTransport (socket) );
boost::shared_ptr<TProtocol> protocol (new TBinaryProtocol (transport) );
client = boost::shared_ptr<kurento::MediaServerServiceClient> (new kurento::MediaServerServiceClient (protocol) );
for (i = 0; i < MAX_RETRIES; i++) {
try {
transport->open ();
initialized = true;
break;
} catch (std::exception e) {
GST_WARNING ("Error connecting to the server (retry %d/%d): %s", i + 1, MAX_RETRIES, e.what () );
sleep (1);
}
}
}
F::~F()
{
GST_DEBUG ("teardown fixture");
if (initialized) {
transport->close ();
}
stop_server_test (pid);
}
<commit_msg>Change plugin path used in server for memory leak tests<commit_after>/*
* server_test_base.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <mparisdiaz@gmail.com>
* Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "server_test_base.hpp"
#define BOOST_TEST_MODULE ServerTest
#include <boost/test/unit_test.hpp>
#include <unistd.h>
#include <sys/wait.h>
#include <glib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <transport/TSocket.h>
#include <protocol/TBinaryProtocol.h>
#include <gst/gst.h>
#include "media_config.hpp"
#include "mediaServer_types.h"
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
#define GST_CAT_DEFAULT _server_test_base_
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "server_test_base"
#define MAX_RETRIES 5
G_LOCK_DEFINE (mutex);
static void
sig_handler (int sig)
{
if (sig == SIGCONT)
G_UNLOCK (mutex);
}
int
start_server_test ()
{
pid_t childpid = -1;
gchar *conf_file, *conf_file_param;
conf_file = getenv ("MEDIA_SERVER_CONF_FILE");
if (conf_file == NULL) {
return -1;
}
conf_file_param = g_strconcat ("--conf-file=", conf_file, NULL);
signal (SIGCONT, sig_handler);
G_LOCK (mutex);
childpid = fork();
if (childpid >= 0) {
if (childpid == 0) {
execl ("./server/kurento", "kurento", conf_file_param, "--gst-plugin-path=./plugins", NULL);
} else {
G_LOCK (mutex);
G_UNLOCK (mutex);
}
} else {
BOOST_FAIL ("Error executing server");
}
return childpid;
}
void
stop_server_test (int pid)
{
int status;
kill (pid, SIGINT);
wait (&status);
}
F::F()
{
int i;
gst_init (NULL, NULL);
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME);
GST_DEBUG ("setup fixture");
pid = start_server_test(); // TODO: check pid < 0
boost::shared_ptr<TSocket> socket (new TSocket (MEDIA_SERVER_ADDRESS, MEDIA_SERVER_SERVICE_PORT) );
transport = boost::shared_ptr<TTransport> (new TFramedTransport (socket) );
boost::shared_ptr<TProtocol> protocol (new TBinaryProtocol (transport) );
client = boost::shared_ptr<kurento::MediaServerServiceClient> (new kurento::MediaServerServiceClient (protocol) );
for (i = 0; i < MAX_RETRIES; i++) {
try {
transport->open ();
initialized = true;
break;
} catch (std::exception e) {
GST_WARNING ("Error connecting to the server (retry %d/%d): %s", i + 1, MAX_RETRIES, e.what () );
sleep (1);
}
}
}
F::~F()
{
GST_DEBUG ("teardown fixture");
if (initialized) {
transport->close ();
}
stop_server_test (pid);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.