text stringlengths 54 60.6k |
|---|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
bool isprint(char c)
{
return c >= 32 && c < 127;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LC", "LeechCraft"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MR", "Miro"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"ST", "SymTorrent"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "uTorrent"}
, {"XL", "Xunlei"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
, {"st", "SharkTorrent"}
};
struct generic_map_entry
{
int offset;
char const* id;
char const* name;
};
// non-standard names
generic_map_entry generic_mappings[] =
{
{0, "Deadman Walking-", "Deadman"}
, {5, "Azureus", "Azureus 2.0.3.2"}
, {0, "DansClient", "XanTorrent"}
, {4, "btfans", "SimpleBT"}
, {0, "PRC.P---", "Bittorrent Plus! II"}
, {0, "P87.P---", "Bittorrent Plus!"}
, {0, "S587Plus", "Bittorrent Plus!"}
, {0, "martini", "Martini Man"}
, {0, "Plus---", "Bittorrent Plus"}
, {0, "turbobt", "TurboBT"}
, {0, "a00---0", "Swarmy"}
, {0, "a02---0", "Swarmy"}
, {0, "T00---0", "Teeweety"}
, {0, "BTDWV-", "Deadman Walking"}
, {2, "BS", "BitSpirit"}
, {0, "Pando-", "Pando"}
, {0, "LIME", "LimeWire"}
, {0, "btuga", "BTugaXP"}
, {0, "oernu", "BTugaXP"}
, {0, "Mbrst", "Burst!"}
, {0, "PEERAPP", "PeerApp"}
, {0, "Plus", "Plus!"}
, {0, "-Qt-", "Qt"}
, {0, "exbc", "BitComet"}
, {0, "DNA", "BitTorrent DNA"}
, {0, "-G3", "G3 Torrent"}
, {0, "-FG", "FlashGet"}
, {0, "-ML", "MLdonkey"}
, {0, "XBT", "XBT"}
, {0, "OP", "Opera"}
, {2, "RS", "Rufus"}
, {0, "AZ2500BT", "BitTyrant"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
TORRENT_ASSERT(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]);
for (int i = 0; i < num_generic_mappings; ++i)
{
generic_map_entry const& e = generic_mappings[i];
if (find_string(PID + e.offset, e.id)) return e.name;
}
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += isprint(char(*i))?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>replace std::isdigit() to avoid asserts on windows<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
bool is_digit(char c)
{
return c >= '0' && c <= '9';
}
int decode_digit(char c)
{
if (is_digit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
bool isprint(char c)
{
return c >= 32 && c < 127;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LC", "LeechCraft"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MR", "Miro"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"ST", "SymTorrent"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "uTorrent"}
, {"XL", "Xunlei"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
, {"st", "SharkTorrent"}
};
struct generic_map_entry
{
int offset;
char const* id;
char const* name;
};
// non-standard names
generic_map_entry generic_mappings[] =
{
{0, "Deadman Walking-", "Deadman"}
, {5, "Azureus", "Azureus 2.0.3.2"}
, {0, "DansClient", "XanTorrent"}
, {4, "btfans", "SimpleBT"}
, {0, "PRC.P---", "Bittorrent Plus! II"}
, {0, "P87.P---", "Bittorrent Plus!"}
, {0, "S587Plus", "Bittorrent Plus!"}
, {0, "martini", "Martini Man"}
, {0, "Plus---", "Bittorrent Plus"}
, {0, "turbobt", "TurboBT"}
, {0, "a00---0", "Swarmy"}
, {0, "a02---0", "Swarmy"}
, {0, "T00---0", "Teeweety"}
, {0, "BTDWV-", "Deadman Walking"}
, {2, "BS", "BitSpirit"}
, {0, "Pando-", "Pando"}
, {0, "LIME", "LimeWire"}
, {0, "btuga", "BTugaXP"}
, {0, "oernu", "BTugaXP"}
, {0, "Mbrst", "Burst!"}
, {0, "PEERAPP", "PeerApp"}
, {0, "Plus", "Plus!"}
, {0, "-Qt-", "Qt"}
, {0, "exbc", "BitComet"}
, {0, "DNA", "BitTorrent DNA"}
, {0, "-G3", "G3 Torrent"}
, {0, "-FG", "FlashGet"}
, {0, "-ML", "MLdonkey"}
, {0, "XBT", "XBT"}
, {0, "OP", "Opera"}
, {2, "RS", "Rufus"}
, {0, "AZ2500BT", "BitTyrant"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
TORRENT_ASSERT(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]);
for (int i = 0; i < num_generic_mappings; ++i)
{
generic_map_entry const& e = generic_mappings[i];
if (find_string(PID + e.offset, e.id)) return e.name;
}
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += isprint(char(*i))?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include <toku_portability.h>
#include <errno.h>
#include <string.h>
#include "toku_assert.h"
#include "fttypes.h"
#include "minicron.h"
static void
toku_gettime (toku_timespec_t *a) {
struct timeval tv;
gettimeofday(&tv, 0);
a->tv_sec = tv.tv_sec;
a->tv_nsec = tv.tv_usec * 1000LL;
}
static int
timespec_compare (toku_timespec_t *a, toku_timespec_t *b) {
if (a->tv_sec > b->tv_sec) return 1;
if (a->tv_sec < b->tv_sec) return -1;
if (a->tv_nsec > b->tv_nsec) return 1;
if (a->tv_nsec < b->tv_nsec) return -1;
return 0;
}
// Implementation notes:
// When calling do_shutdown or change_period, the mutex is obtained, the variables in the minicron struct are modified, and
// the condition variable is signalled. Possibly the minicron thread will miss the signal. To avoid this problem, whenever
// the minicron thread acquires the mutex, it must check to see what the variables say to do (e.g., should it shut down?).
static void*
minicron_do (void *pv)
{
struct minicron *CAST_FROM_VOIDP(p, pv);
toku_mutex_lock(&p->mutex);
while (1) {
if (p->do_shutdown) {
toku_mutex_unlock(&p->mutex);
return 0;
}
if (p->period_in_ms == 0) {
// if we aren't supposed to do it then just do an untimed wait.
toku_cond_wait(&p->condvar, &p->mutex);
}
else if (p->period_in_ms <= 1000) {
toku_mutex_unlock(&p->mutex);
usleep(p->period_in_ms * 1000);
toku_mutex_lock(&p->mutex);
}
else {
// Recompute the wakeup time every time (instead of once per call to f) in case the period changges.
toku_timespec_t wakeup_at = p->time_of_last_call_to_f;
wakeup_at.tv_sec += (p->period_in_ms/1000);
wakeup_at.tv_nsec += (p->period_in_ms % 1000) * 1000000;
toku_timespec_t now;
toku_gettime(&now);
int r = toku_cond_timedwait(&p->condvar, &p->mutex, &wakeup_at);
if (r!=0 && r!=ETIMEDOUT) fprintf(stderr, "%s:%d r=%d (%s)", __FILE__, __LINE__, r, strerror(r));
assert(r==0 || r==ETIMEDOUT);
}
// Now we woke up, and we should figure out what to do
if (p->do_shutdown) {
toku_mutex_unlock(&p->mutex);
return 0;
}
if (p->period_in_ms > 1000) {
toku_timespec_t now;
toku_gettime(&now);
toku_timespec_t time_to_call = p->time_of_last_call_to_f;
time_to_call.tv_sec += p->period_in_ms/1000;
time_to_call.tv_nsec += (p->period_in_ms % 1000) * 1000000;
int compare = timespec_compare(&time_to_call, &now);
//printf("compare(%.6f, %.6f)=%d\n", time_to_call.tv_sec + time_to_call.tv_nsec*1e-9, now.tv_sec+now.tv_nsec*1e-9, compare);
if (compare <= 0) {
toku_mutex_unlock(&p->mutex);
int r = p->f(p->arg);
assert(r==0);
toku_mutex_lock(&p->mutex);
toku_gettime(&p->time_of_last_call_to_f); // the period is measured between calls to f.
}
}
else {
toku_mutex_unlock(&p->mutex);
int r = p->f(p->arg);
assert(r==0);
toku_mutex_lock(&p->mutex);
}
}
}
int
toku_minicron_setup(struct minicron *p, uint32_t period_in_ms, int(*f)(void *), void *arg)
{
p->f = f;
p->arg = arg;
toku_gettime(&p->time_of_last_call_to_f);
//printf("now=%.6f", p->time_of_last_call_to_f.tv_sec + p->time_of_last_call_to_f.tv_nsec*1e-9);
p->period_in_ms = period_in_ms;
p->do_shutdown = false;
toku_mutex_init(&p->mutex, 0);
toku_cond_init (&p->condvar, 0);
return toku_pthread_create(&p->thread, 0, minicron_do, p);
}
void
toku_minicron_change_period(struct minicron *p, uint32_t new_period)
{
toku_mutex_lock(&p->mutex);
p->period_in_ms = new_period;
toku_cond_signal(&p->condvar);
toku_mutex_unlock(&p->mutex);
}
/* unlocked function for use by engine status which takes no locks */
uint32_t
toku_minicron_get_period_in_seconds_unlocked(struct minicron *p)
{
uint32_t retval = p->period_in_ms/1000;
return retval;
}
/* unlocked function for use by engine status which takes no locks */
uint32_t
toku_minicron_get_period_in_ms_unlocked(struct minicron *p)
{
uint32_t retval = p->period_in_ms;
return retval;
}
int
toku_minicron_shutdown(struct minicron *p) {
toku_mutex_lock(&p->mutex);
assert(!p->do_shutdown);
p->do_shutdown = true;
//printf("%s:%d signalling\n", __FILE__, __LINE__);
toku_cond_signal(&p->condvar);
toku_mutex_unlock(&p->mutex);
void *returned_value;
//printf("%s:%d joining\n", __FILE__, __LINE__);
int r = toku_pthread_join(p->thread, &returned_value);
if (r!=0) fprintf(stderr, "%s:%d r=%d (%s)\n", __FILE__, __LINE__, r, strerror(r));
assert(r==0); assert(returned_value==0);
toku_cond_destroy(&p->condvar);
toku_mutex_destroy(&p->mutex);
//printf("%s:%d shutdowned\n", __FILE__, __LINE__);
return 0;
}
bool
toku_minicron_has_been_shutdown(struct minicron *p) {
return p->do_shutdown;
}
<commit_msg>refs #6162, fix bug in minicron<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include <toku_portability.h>
#include <errno.h>
#include <string.h>
#include "toku_assert.h"
#include "fttypes.h"
#include "minicron.h"
static void
toku_gettime (toku_timespec_t *a) {
struct timeval tv;
gettimeofday(&tv, 0);
a->tv_sec = tv.tv_sec;
a->tv_nsec = tv.tv_usec * 1000LL;
}
static int
timespec_compare (toku_timespec_t *a, toku_timespec_t *b) {
if (a->tv_sec > b->tv_sec) return 1;
if (a->tv_sec < b->tv_sec) return -1;
if (a->tv_nsec > b->tv_nsec) return 1;
if (a->tv_nsec < b->tv_nsec) return -1;
return 0;
}
// Implementation notes:
// When calling do_shutdown or change_period, the mutex is obtained, the variables in the minicron struct are modified, and
// the condition variable is signalled. Possibly the minicron thread will miss the signal. To avoid this problem, whenever
// the minicron thread acquires the mutex, it must check to see what the variables say to do (e.g., should it shut down?).
static void*
minicron_do (void *pv)
{
struct minicron *CAST_FROM_VOIDP(p, pv);
toku_mutex_lock(&p->mutex);
while (1) {
if (p->do_shutdown) {
toku_mutex_unlock(&p->mutex);
return 0;
}
if (p->period_in_ms == 0) {
// if we aren't supposed to do it then just do an untimed wait.
toku_cond_wait(&p->condvar, &p->mutex);
}
else if (p->period_in_ms <= 1000) {
toku_mutex_unlock(&p->mutex);
usleep(p->period_in_ms * 1000);
toku_mutex_lock(&p->mutex);
}
else {
// Recompute the wakeup time every time (instead of once per call to f) in case the period changges.
toku_timespec_t wakeup_at = p->time_of_last_call_to_f;
wakeup_at.tv_sec += (p->period_in_ms/1000);
wakeup_at.tv_nsec += (p->period_in_ms % 1000) * 1000000;
toku_timespec_t now;
toku_gettime(&now);
int r = toku_cond_timedwait(&p->condvar, &p->mutex, &wakeup_at);
if (r!=0 && r!=ETIMEDOUT) fprintf(stderr, "%s:%d r=%d (%s)", __FILE__, __LINE__, r, strerror(r));
assert(r==0 || r==ETIMEDOUT);
}
// Now we woke up, and we should figure out what to do
if (p->do_shutdown) {
toku_mutex_unlock(&p->mutex);
return 0;
}
if (p->period_in_ms > 1000) {
toku_timespec_t now;
toku_gettime(&now);
toku_timespec_t time_to_call = p->time_of_last_call_to_f;
time_to_call.tv_sec += p->period_in_ms/1000;
time_to_call.tv_nsec += (p->period_in_ms % 1000) * 1000000;
int compare = timespec_compare(&time_to_call, &now);
//printf("compare(%.6f, %.6f)=%d\n", time_to_call.tv_sec + time_to_call.tv_nsec*1e-9, now.tv_sec+now.tv_nsec*1e-9, compare);
if (compare <= 0) {
toku_mutex_unlock(&p->mutex);
int r = p->f(p->arg);
assert(r==0);
toku_mutex_lock(&p->mutex);
toku_gettime(&p->time_of_last_call_to_f); // the period is measured between calls to f.
}
}
else if (p->period_in_ms != 0) {
toku_mutex_unlock(&p->mutex);
int r = p->f(p->arg);
assert(r==0);
toku_mutex_lock(&p->mutex);
}
}
}
int
toku_minicron_setup(struct minicron *p, uint32_t period_in_ms, int(*f)(void *), void *arg)
{
p->f = f;
p->arg = arg;
toku_gettime(&p->time_of_last_call_to_f);
//printf("now=%.6f", p->time_of_last_call_to_f.tv_sec + p->time_of_last_call_to_f.tv_nsec*1e-9);
p->period_in_ms = period_in_ms;
p->do_shutdown = false;
toku_mutex_init(&p->mutex, 0);
toku_cond_init (&p->condvar, 0);
return toku_pthread_create(&p->thread, 0, minicron_do, p);
}
void
toku_minicron_change_period(struct minicron *p, uint32_t new_period)
{
toku_mutex_lock(&p->mutex);
p->period_in_ms = new_period;
toku_cond_signal(&p->condvar);
toku_mutex_unlock(&p->mutex);
}
/* unlocked function for use by engine status which takes no locks */
uint32_t
toku_minicron_get_period_in_seconds_unlocked(struct minicron *p)
{
uint32_t retval = p->period_in_ms/1000;
return retval;
}
/* unlocked function for use by engine status which takes no locks */
uint32_t
toku_minicron_get_period_in_ms_unlocked(struct minicron *p)
{
uint32_t retval = p->period_in_ms;
return retval;
}
int
toku_minicron_shutdown(struct minicron *p) {
toku_mutex_lock(&p->mutex);
assert(!p->do_shutdown);
p->do_shutdown = true;
//printf("%s:%d signalling\n", __FILE__, __LINE__);
toku_cond_signal(&p->condvar);
toku_mutex_unlock(&p->mutex);
void *returned_value;
//printf("%s:%d joining\n", __FILE__, __LINE__);
int r = toku_pthread_join(p->thread, &returned_value);
if (r!=0) fprintf(stderr, "%s:%d r=%d (%s)\n", __FILE__, __LINE__, r, strerror(r));
assert(r==0); assert(returned_value==0);
toku_cond_destroy(&p->condvar);
toku_mutex_destroy(&p->mutex);
//printf("%s:%d shutdowned\n", __FILE__, __LINE__);
return 0;
}
bool
toku_minicron_has_been_shutdown(struct minicron *p) {
return p->do_shutdown;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskd - Task Server
//
// Copyright 2010 - 2012, Göteborg Bit Factory.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
//#include <sstream>
//#include <stdlib.h>
//#include <math.h>
//#include <algorithm>
//#include <Nibbler.h>
//#include <Date.h>
#include <Duration.h>
#include <Task.h>
#include <JSON.h>
//#include <RX.h>
#include <text.h>
#include <util.h>
//#include <taskd.h>
////////////////////////////////////////////////////////////////////////////////
Task::Task ()
: id (0)
{
}
////////////////////////////////////////////////////////////////////////////////
Task::Task (const Task& other)
{
*this = other;
}
////////////////////////////////////////////////////////////////////////////////
Task& Task::operator= (const Task& other)
{
if (this != &other)
{
std::map <std::string, std::string>::operator= (other);
id = other.id;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// The uuid and id attributes must be exempt from comparison.
bool Task::operator== (const Task& other)
{
if (size () != other.size ())
return false;
Task::iterator i;
for (i = this->begin (); i != this->end (); ++i)
if (i->first != "uuid" &&
i->second != other.get (i->first))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
Task::Task (const std::string& input)
{
id = 0;
parse (input);
}
////////////////////////////////////////////////////////////////////////////////
Task::~Task ()
{
}
////////////////////////////////////////////////////////////////////////////////
Task::status Task::textToStatus (const std::string& input)
{
if (input[0] == 'p') return Task::pending;
else if (input[0] == 'c') return Task::completed;
else if (input[0] == 'd') return Task::deleted;
else if (input[0] == 'r') return Task::recurring;
else if (input[0] == 'w') return Task::waiting;
return Task::pending;
}
////////////////////////////////////////////////////////////////////////////////
std::string Task::statusToText (Task::status s)
{
if (s == Task::pending) return "pending";
else if (s == Task::completed) return "completed";
else if (s == Task::deleted) return "deleted";
else if (s == Task::recurring) return "recurring";
else if (s == Task::waiting) return "waiting";
return "pending";
}
////////////////////////////////////////////////////////////////////////////////
void Task::setModified ()
{
char now[16];
sprintf (now, "%u", (unsigned int) time (NULL));
set ("modified", now);
}
////////////////////////////////////////////////////////////////////////////////
bool Task::has (const std::string& name) const
{
Task::const_iterator i = this->find (name);
if (i != this->end ())
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Task::all ()
{
std::vector <std::string> all;
Task::iterator i;
for (i = this->begin (); i != this->end (); ++i)
all.push_back (i->first);
return all;
}
////////////////////////////////////////////////////////////////////////////////
const std::string Task::get (const std::string& name) const
{
Task::const_iterator i = this->find (name);
if (i != this->end ())
return i->second;
return "";
}
////////////////////////////////////////////////////////////////////////////////
time_t Task::get_date (const std::string& name) const
{
Task::const_iterator i = this->find (name);
if (i != this->end ())
return (time_t) strtoul (i->second.c_str (), NULL, 10);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
void Task::set (const std::string& name, const std::string& value)
{
(*this)[name] = value;
}
////////////////////////////////////////////////////////////////////////////////
void Task::set (const std::string& name, int value)
{
(*this)[name] = format (value);
}
////////////////////////////////////////////////////////////////////////////////
void Task::remove (const std::string& name)
{
Task::iterator it;
if ((it = this->find (name)) != this->end ())
this->erase (it);
}
////////////////////////////////////////////////////////////////////////////////
Task::status Task::getStatus () const
{
return textToStatus (get ("status"));
}
////////////////////////////////////////////////////////////////////////////////
void Task::setStatus (Task::status status)
{
set ("status", statusToText (status));
}
////////////////////////////////////////////////////////////////////////////////
// Attempt an FF4 parse first, using Task::parse, and in the event of an error
// try a legacy parse (F3, FF2). Note that FF1 is no longer supported.
//
// start --> [ --> Att --> ] --> end
// ^ |
// +-------+
//
void Task::parse (const std::string& input)
{
std::string copy;
if (input[input.length () - 1] == '\n')
copy = input.substr (0, input.length () - 1);
else
copy = input;
clear ();
Nibbler n (copy);
std::string line;
if (n.skip ('[') &&
n.getUntil (']', line) &&
n.skip (']') &&
n.depleted ())
{
if (line.length () == 0)
throw std::string ("Empty record in input.");
Nibbler nl (line);
std::string name;
std::string value;
while (!nl.depleted ())
{
if (nl.getUntil (':', name) &&
nl.skip (':') &&
nl.getQuoted ('"', value))
{
// Experimental legacy value translation of 'recur:m' --> 'recur:mo'.
if (name == "recur" &&
digitsOnly (value.substr (0, value.length () - 1)) &&
value[value.length () - 1] == 'm')
value += 'o';
(*this)[name] = decode (json::decode (value));
}
nl.skip (' ');
}
std::string remainder;
nl.getUntilEOS (remainder);
if (remainder.length ())
throw std::string ("Unrecognized characters at end of line.");
}
else
throw std::string ("Record not recognized as format 4.");
}
////////////////////////////////////////////////////////////////////////////////
// The format is:
//
// [ <name>:<value> ... ] \n
//
std::string Task::composeF4 () const
{
std::string ff4 = "[";
bool first = true;
Task::const_iterator it;
for (it = this->begin (); it != this->end (); ++it)
{
if (it->second != "")
{
ff4 += (first ? "" : " ")
+ it->first
+ ":\"" + encode (json::encode (it->second)) + "\"";
first = false;
}
}
ff4 += "]\n";
return ff4;
}
////////////////////////////////////////////////////////////////////////////////
// The purpose of Task::validate is three-fold:
// 1) To provide missing attributes where possible
// 2) To provide suitable warnings about odd states
// 3) To generate errors when the inconsistencies are not fixable
//
void Task::validate ()
{
Task::status status = getStatus ();
// 1) Provide missing attributes where possible
// Provide a UUID if necessary.
if (! has ("uuid"))
set ("uuid", uuid ());
// Recurring tasks get a special status.
if (status == Task::pending &&
has ("due") &&
has ("recur") &&
! has ("parent"))
status = Task::recurring;
// Tasks with a wait: date get a special status.
else if (status == Task::pending &&
has ("wait"))
status = Task::waiting;
// By default, tasks are pending.
else if (! has ("status"))
status = Task::pending;
// Store the derived status.
setStatus (status);
/*
// Provide an entry date unless user already specified one.
if (!has ("entry"))
setEntry ();
*/
/*
// Completed tasks need an end date, so inherit the entry date.
if (! has ("end") &&
(getStatus () == Task::completed ||
getStatus () == Task::deleted))
setEnd ();
*/
// 2) To provide suitable warnings about odd states
// 3) To generate errors when the inconsistencies are not fixable
// There is no fixing a missing description.
if (!has ("description"))
throw std::string ("A task must have a description.");
else if (get ("description") == "")
throw std::string ("Cannot add a task that is blank.");
// Cannot have a recur frequency with no due date - when would it recur?
if (! has ("due") && has ("recur"))
throw std::string ("A recurring task must also have a 'due' date.");
// Recur durations must be valid.
if (has ("recur"))
{
Duration d;
if (! d.valid (get ("recur")))
throw std::string (format ("The recurrence value '{1}' is not valid.", get ("recur")));
}
// Priorities must be valid.
if (has ("priority"))
{
std::string priority = get ("priority");
if (priority != "H" &&
priority != "M" &&
priority != "L")
throw format ("Priority values may be 'H', 'M' or 'L', not '{1}'.", priority);
}
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Build<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskd - Task Server
//
// Copyright 2010 - 2012, Göteborg Bit Factory.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <Duration.h>
#include <Task.h>
#include <JSON.h>
#include <text.h>
#include <util.h>
////////////////////////////////////////////////////////////////////////////////
Task::Task ()
: id (0)
{
}
////////////////////////////////////////////////////////////////////////////////
Task::Task (const Task& other)
{
*this = other;
}
////////////////////////////////////////////////////////////////////////////////
Task& Task::operator= (const Task& other)
{
if (this != &other)
{
std::map <std::string, std::string>::operator= (other);
id = other.id;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// The uuid and id attributes must be exempt from comparison.
bool Task::operator== (const Task& other)
{
if (size () != other.size ())
return false;
Task::iterator i;
for (i = this->begin (); i != this->end (); ++i)
if (i->first != "uuid" &&
i->second != other.get (i->first))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
Task::Task (const std::string& input)
{
id = 0;
parse (input);
}
////////////////////////////////////////////////////////////////////////////////
Task::~Task ()
{
}
////////////////////////////////////////////////////////////////////////////////
Task::status Task::textToStatus (const std::string& input)
{
if (input[0] == 'p') return Task::pending;
else if (input[0] == 'c') return Task::completed;
else if (input[0] == 'd') return Task::deleted;
else if (input[0] == 'r') return Task::recurring;
else if (input[0] == 'w') return Task::waiting;
return Task::pending;
}
////////////////////////////////////////////////////////////////////////////////
std::string Task::statusToText (Task::status s)
{
if (s == Task::pending) return "pending";
else if (s == Task::completed) return "completed";
else if (s == Task::deleted) return "deleted";
else if (s == Task::recurring) return "recurring";
else if (s == Task::waiting) return "waiting";
return "pending";
}
////////////////////////////////////////////////////////////////////////////////
void Task::setModified ()
{
char now[16];
sprintf (now, "%u", (unsigned int) time (NULL));
set ("modified", now);
}
////////////////////////////////////////////////////////////////////////////////
bool Task::has (const std::string& name) const
{
Task::const_iterator i = this->find (name);
if (i != this->end ())
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Task::all ()
{
std::vector <std::string> all;
Task::iterator i;
for (i = this->begin (); i != this->end (); ++i)
all.push_back (i->first);
return all;
}
////////////////////////////////////////////////////////////////////////////////
const std::string Task::get (const std::string& name) const
{
Task::const_iterator i = this->find (name);
if (i != this->end ())
return i->second;
return "";
}
////////////////////////////////////////////////////////////////////////////////
time_t Task::get_date (const std::string& name) const
{
Task::const_iterator i = this->find (name);
if (i != this->end ())
return (time_t) strtoul (i->second.c_str (), NULL, 10);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
void Task::set (const std::string& name, const std::string& value)
{
(*this)[name] = value;
}
////////////////////////////////////////////////////////////////////////////////
void Task::set (const std::string& name, int value)
{
(*this)[name] = format (value);
}
////////////////////////////////////////////////////////////////////////////////
void Task::remove (const std::string& name)
{
Task::iterator it;
if ((it = this->find (name)) != this->end ())
this->erase (it);
}
////////////////////////////////////////////////////////////////////////////////
Task::status Task::getStatus () const
{
return textToStatus (get ("status"));
}
////////////////////////////////////////////////////////////////////////////////
void Task::setStatus (Task::status status)
{
set ("status", statusToText (status));
}
////////////////////////////////////////////////////////////////////////////////
// Attempt an FF4 parse first, using Task::parse, and in the event of an error
// try a legacy parse (F3, FF2). Note that FF1 is no longer supported.
//
// start --> [ --> Att --> ] --> end
// ^ |
// +-------+
//
void Task::parse (const std::string& input)
{
std::string copy;
if (input[input.length () - 1] == '\n')
copy = input.substr (0, input.length () - 1);
else
copy = input;
clear ();
Nibbler n (copy);
std::string line;
if (n.skip ('[') &&
n.getUntil (']', line) &&
n.skip (']') &&
n.depleted ())
{
if (line.length () == 0)
throw std::string ("Empty record in input.");
Nibbler nl (line);
std::string name;
std::string value;
while (!nl.depleted ())
{
if (nl.getUntil (':', name) &&
nl.skip (':') &&
nl.getQuoted ('"', value))
{
// Experimental legacy value translation of 'recur:m' --> 'recur:mo'.
if (name == "recur" &&
digitsOnly (value.substr (0, value.length () - 1)) &&
value[value.length () - 1] == 'm')
value += 'o';
(*this)[name] = decode (json::decode (value));
}
nl.skip (' ');
}
std::string remainder;
nl.getUntilEOS (remainder);
if (remainder.length ())
throw std::string ("Unrecognized characters at end of line.");
}
else
throw std::string ("Record not recognized as format 4.");
}
////////////////////////////////////////////////////////////////////////////////
// The format is:
//
// [ <name>:<value> ... ] \n
//
std::string Task::composeF4 () const
{
std::string ff4 = "[";
bool first = true;
Task::const_iterator it;
for (it = this->begin (); it != this->end (); ++it)
{
if (it->second != "")
{
ff4 += (first ? "" : " ")
+ it->first
+ ":\"" + encode (json::encode (it->second)) + "\"";
first = false;
}
}
ff4 += "]\n";
return ff4;
}
////////////////////////////////////////////////////////////////////////////////
// The purpose of Task::validate is three-fold:
// 1) To provide missing attributes where possible
// 2) To provide suitable warnings about odd states
// 3) To generate errors when the inconsistencies are not fixable
//
void Task::validate ()
{
Task::status status = getStatus ();
// 1) Provide missing attributes where possible
// Provide a UUID if necessary.
if (! has ("uuid"))
set ("uuid", uuid ());
// Recurring tasks get a special status.
if (status == Task::pending &&
has ("due") &&
has ("recur") &&
! has ("parent"))
status = Task::recurring;
// Tasks with a wait: date get a special status.
else if (status == Task::pending &&
has ("wait"))
status = Task::waiting;
// By default, tasks are pending.
else if (! has ("status"))
status = Task::pending;
// Store the derived status.
setStatus (status);
/*
// Provide an entry date unless user already specified one.
if (!has ("entry"))
setEntry ();
*/
/*
// Completed tasks need an end date, so inherit the entry date.
if (! has ("end") &&
(getStatus () == Task::completed ||
getStatus () == Task::deleted))
setEnd ();
*/
// 2) To provide suitable warnings about odd states
// 3) To generate errors when the inconsistencies are not fixable
// There is no fixing a missing description.
if (!has ("description"))
throw std::string ("A task must have a description.");
else if (get ("description") == "")
throw std::string ("Cannot add a task that is blank.");
// Cannot have a recur frequency with no due date - when would it recur?
if (! has ("due") && has ("recur"))
throw std::string ("A recurring task must also have a 'due' date.");
// Recur durations must be valid.
if (has ("recur"))
{
Duration d;
if (! d.valid (get ("recur")))
throw std::string (format ("The recurrence value '{1}' is not valid.", get ("recur")));
}
// Priorities must be valid.
if (has ("priority"))
{
std::string priority = get ("priority");
if (priority != "H" &&
priority != "M" &&
priority != "L")
throw format ("Priority values may be 'H', 'M' or 'L', not '{1}'.", priority);
}
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <dariadb.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
#include <thread>
#include <random>
#include <cstdlib>
#include <atomic>
class BenchCallback :public dariadb::storage::ReaderClb {
public:
void call(const dariadb::Meas&) {
count++;
}
size_t count;
};
void writer_1(dariadb::storage::AbstractStorage_ptr ms)
{
auto m = dariadb::Meas::empty();
dariadb::Time t = 0;
for (dariadb::Id i = 0; i < 32768; i += 1) {
m.id = i;
m.flag = dariadb::Flag(0);
m.time = t;
m.value = dariadb::Value(i);
ms->append(m);
t++;
}
}
std::atomic_long writen{ 0 };
void writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::AbstractStorage_ptr ms)
{
auto m = dariadb::Meas::empty();
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(0, 64);
dariadb::Time t = 0;
for (dariadb::Id i = id_from; i < (id_from + id_per_thread); i += 1) {
dariadb::Value v = 1.0;
auto max_rnd = uniform_dist(e1);
for (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) {
m.id = i;
m.flag = dariadb::Flag(0);
m.time = t++;
m.value = v;
ms->append(m);
writen++;
auto rnd = rand() / float(RAND_MAX);
v += rnd;
}
}
}
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
srand(static_cast<unsigned int>(time(NULL)));
{// 1.
dariadb::storage::AbstractStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 32768 } };
auto start = clock();
writer_1(ms);
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "1. insert : " << elapsed << std::endl;
}
dariadb::storage::AbstractStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 32768 } };
{// 2.
const size_t threads_count = 16;
const size_t id_per_thread = size_t(32768 / threads_count);
auto start = clock();
std::vector<std::thread> writers(threads_count);
size_t pos = 0;
for (size_t i = 0; i < threads_count; i++) {
std::thread t{ writer_2, id_per_thread*(i+1), id_per_thread, ms };
writers[pos++] = std::move(t);
}
pos = 0;
for (size_t i = 0; i < threads_count; i++) {
std::thread t = std::move(writers[pos++]);
t.join();
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "2. insert : " << elapsed <<" writen:"<<writen<< std::endl;
}
{//3
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Id> uniform_dist(0, 32768);
dariadb::IdArray ids;
ids.resize(1);
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 131072;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
ids[0]= uniform_dist(e1) ;
auto rdr=ms->currentValue(ids, 0);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC)/ queries_count;
std::cout << "3. current: " << elapsed << std::endl;
}
{//4
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Id> uniform_dist(0, 32768);
dariadb::IdArray ids;
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 32;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
auto rdr=ms->currentValue(ids, 0);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count;
std::cout << "4. current: " << elapsed << std::endl;
}
{//5
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Time> uniform_dist(0, 32768/2);
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 32;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
auto f = uniform_dist(e1);
auto t = uniform_dist(e1);
auto rdr = ms->readInterval(f, t+f);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count;
std::cout << "5. interval: " << elapsed << std::endl;
}
{//6
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Time> uniform_dist(0, 32768/2);
std::uniform_int_distribution<dariadb::Id> uniform_dist_id(0, 32768);
const size_t ids_count = size_t(32768 * 0.1);
dariadb::IdArray ids;
ids.resize(ids_count);
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 32;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
for (size_t j = 0; j < ids_count; j++) {
ids[j] = uniform_dist_id(e1);
}
auto f = uniform_dist(e1);
auto t = uniform_dist(e1);
auto rdr = ms->readInterval(ids,0, f, t + f);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count;
std::cout << "5. interval: " << elapsed << std::endl;
}
}
<commit_msg>verb.<commit_after>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <dariadb.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
#include <thread>
#include <random>
#include <cstdlib>
#include <atomic>
class BenchCallback :public dariadb::storage::ReaderClb {
public:
void call(const dariadb::Meas&) {
count++;
}
size_t count;
};
void writer_1(dariadb::storage::AbstractStorage_ptr ms)
{
auto m = dariadb::Meas::empty();
dariadb::Time t = 0;
for (dariadb::Id i = 0; i < 32768; i += 1) {
m.id = i;
m.flag = dariadb::Flag(0);
m.time = t;
m.value = dariadb::Value(i);
ms->append(m);
t++;
}
}
std::atomic_long writen{ 0 };
void writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::AbstractStorage_ptr ms)
{
auto m = dariadb::Meas::empty();
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(0, 64);
dariadb::Time t = 0;
for (dariadb::Id i = id_from; i < (id_from + id_per_thread); i += 1) {
dariadb::Value v = 1.0;
auto max_rnd = uniform_dist(e1);
for (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) {
m.id = i;
m.flag = dariadb::Flag(0);
m.time = t++;
m.value = v;
ms->append(m);
writen++;
auto rnd = rand() / float(RAND_MAX);
v += rnd;
}
}
}
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
srand(static_cast<unsigned int>(time(NULL)));
{// 1.
dariadb::storage::AbstractStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 32768 } };
auto start = clock();
writer_1(ms);
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "1. insert : " << elapsed << std::endl;
}
dariadb::storage::AbstractStorage_ptr ms{ new dariadb::storage::MemoryStorage{ 32768 } };
{// 2.
const size_t threads_count = 16;
const size_t id_per_thread = size_t(32768 / threads_count);
auto start = clock();
std::vector<std::thread> writers(threads_count);
size_t pos = 0;
for (size_t i = 0; i < threads_count; i++) {
std::thread t{ writer_2, id_per_thread*(i+1), id_per_thread, ms };
writers[pos++] = std::move(t);
}
pos = 0;
for (size_t i = 0; i < threads_count; i++) {
std::thread t = std::move(writers[pos++]);
t.join();
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "2. insert : " << elapsed <<" writen:"<<writen<< std::endl;
}
{//3
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Id> uniform_dist(0, 32768);
dariadb::IdArray ids;
ids.resize(1);
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 131072;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
ids[0]= uniform_dist(e1) ;
auto rdr=ms->currentValue(ids, 0);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC)/ queries_count;
std::cout << "3. current: " << elapsed << std::endl;
}
{//4
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Id> uniform_dist(0, 32768);
dariadb::IdArray ids;
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 32;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
auto rdr=ms->currentValue(ids, 0);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count;
std::cout << "4. current: " << elapsed << std::endl;
}
{//5
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Time> uniform_dist(0, 32768/2);
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 32;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
auto f = uniform_dist(e1);
auto t = uniform_dist(e1);
auto rdr = ms->readInterval(f, t+f);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count;
std::cout << "5. interval: " << elapsed << std::endl;
}
{//6
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<dariadb::Time> uniform_dist(0, 32768/2);
std::uniform_int_distribution<dariadb::Id> uniform_dist_id(0, 32768);
const size_t ids_count = size_t(32768 * 0.1);
dariadb::IdArray ids;
ids.resize(ids_count);
dariadb::storage::ReaderClb_ptr clbk{ new BenchCallback() };
const size_t queries_count = 32;
auto start = clock();
for (size_t i = 0; i < queries_count; i++) {
for (size_t j = 0; j < ids_count; j++) {
ids[j] = uniform_dist_id(e1);
}
auto f = uniform_dist(e1);
auto t = uniform_dist(e1);
auto rdr = ms->readInterval(ids,0, f, t + f);
rdr->readAll(clbk.get());
}
auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count;
std::cout << "6. interval: " << elapsed << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
* opencog/embodiment/Control/PredicateUpdaters/SpatialPredicateUpdater.cc
*
* Copyright (C) 2002-2009 Novamente LLC
* All Rights Reserved
* Author(s): Ari Heljakka, Welter Luigi, Samir Araujo
*
* Updated: by Zhenhua Cai, on 2011-10-24
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomspace/SimpleTruthValue.h>
#include "SpatialPredicateUpdater.h"
#include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h>
using namespace opencog::oac;
using namespace opencog;
using namespace spatial;
SpatialPredicateUpdater::SpatialPredicateUpdater(AtomSpace & _atomSpace) :
BasicPredicateUpdater(_atomSpace) {}
SpatialPredicateUpdater::~SpatialPredicateUpdater()
{
}
void SpatialPredicateUpdater::update(std::vector<Handle> & objects,
Handle pet,
unsigned long timestamp
)
{
//struct timeval timer_start, timer_end;
//time_t elapsed_time = 0;
//gettimeofday(&timer_start, NULL);
// If there is no map, none update is possible
Handle spaceMapHandle = atomSpace.getSpaceServer().getLatestMapHandle();
if (spaceMapHandle == Handle::UNDEFINED) {
logger().warn( "SpatialPredicateUpdater::%s - No space map handle found!", __FUNCTION__);
return;
}
const SpaceServer::SpaceMap & spaceMap = atomSpace.getSpaceServer().getLatestMap();
logger().debug( "SpatialPredicateUpdater::%s - Processing timestamp '%lu'",
__FUNCTION__, timestamp );
if ( lastTimestamp != timestamp ) {
lastTimestamp = timestamp;
this->spatialRelationCache.clear();
}
// Get all the entities that are NOT blocks
std::vector<std::string> entities;
spaceMap.findEntitiesWithClassFilter(back_inserter(entities), "block");
this->compute2SizeSpatialRelations(spaceMap, objects, entities, pet, timestamp);
//gettimeofday(&timer_end, NULL);
//elapsed_time += ((timer_end.tv_sec - timer_start.tv_sec) * 1000000) +
// (timer_end.tv_usec - timer_start.tv_usec);
//timer_start = timer_end;
//logger().warn("SpatialPredicateUpdater::%s - process 2-size spatial relations: consumed %f seconds",
// __FUNCTION__,
// 1.0 * elapsed_time/1000000
// );
this->compute3SizeSpatialRelations(spaceMap, objects, entities, pet, timestamp);
//gettimeofday(&timer_end, NULL);
//elapsed_time += ((timer_end.tv_sec - timer_start.tv_sec) * 1000000) +
// (timer_end.tv_usec - timer_start.tv_usec);
//timer_start = timer_end;
//logger().warn("SpatialPredicateUpdater::%s - process 3-size spatial relations: consumed %f seconds",
// __FUNCTION__,
// 1.0 * elapsed_time/1000000
// );
}
SpatialPredicateUpdater::SPATIAL_RELATION_VECTOR SpatialPredicateUpdater::
swapRelations(SPATIAL_RELATION_VECTOR & relations)
{
SPATIAL_RELATION_VECTOR newRelations;
foreach (Entity::SPATIAL_RELATION rel, relations) {
switch (rel) {
case Entity::LEFT_OF: newRelations.push_back(Entity::RIGHT_OF); break;
case Entity::RIGHT_OF: newRelations.push_back(Entity::LEFT_OF); break;
case Entity::ABOVE: newRelations.push_back(Entity::BELOW); break;
case Entity::BELOW: newRelations.push_back(Entity::ABOVE); break;
case Entity::BEHIND: newRelations.push_back(Entity::IN_FRONT_OF); break;
case Entity::IN_FRONT_OF: newRelations.push_back(Entity::BEHIND); break;
case Entity::BESIDE: newRelations.push_back(Entity::BESIDE); break;
case Entity::NEAR: newRelations.push_back(Entity::NEAR); break;
case Entity::FAR_: newRelations.push_back(Entity::FAR_); break;
case Entity::TOUCHING: newRelations.push_back(Entity::TOUCHING); break;
case Entity::INSIDE: newRelations.push_back(Entity::OUTSIDE); break;
case Entity::OUTSIDE: newRelations.push_back(Entity::INSIDE); break;
case Entity::ADJACENT: newRelations.push_back(Entity::ADJACENT); break;
default: break;
} // switch (rel)
} // foreach (Entity::SPATIAL_RELATION rel, relations)
return newRelations;
}
void SpatialPredicateUpdater::
compute2SizeSpatialRelations(const SpaceServer::SpaceMap & spaceMap,
std::vector<Handle> & objects,
std::vector <std::string> & entities,
Handle observer,
unsigned long timestamp
)
{
double besideDistance = spaceMap.getNextDistance();
try {
const spatial::EntityPtr & observerEntity =
spaceMap.getEntity( atomSpace.getName(observer) );
foreach (Handle objectA, objects) {
int numRelations = 0;
std::string entityID_A = atomSpace.getName(objectA);
const spatial::EntityPtr & entityA = spaceMap.getEntity(entityID_A);
foreach (const std::string & entityID_B, entities) {
if ( entityID_A == entityID_B ||
this->spatialRelationCache.isCached(entityID_A, entityID_B) ) {
continue;
}
const spatial::EntityPtr & entityB = spaceMap.getEntity(entityID_B);
Handle objectB = getHandle(entityID_B);
SPATIAL_RELATION_VECTOR relationsAB, relationsBA;
// Compute size-2 directional spatial relations (B is the reference object)
relationsAB = entityA->computeSpatialRelations( *observerEntity, besideDistance, *entityB );
relationsBA = this->swapRelations(relationsAB);
this->addSpatialRelations(relationsAB, atomSpace, timestamp, objectA, objectB);
this->addSpatialRelations(relationsBA, atomSpace, timestamp, objectB, objectA);
this->spatialRelationCache.addRelation(entityID_A, entityID_B, relationsAB);
this->spatialRelationCache.addRelation(entityID_B, entityID_A, relationsBA);
numRelations += relationsAB.size();
} // foreach (const std::string & entityID_B, entities)
logger().debug("%s - Finished evaluating: %d 2-size spatial relations related to '%s'",
__FUNCTION__, numRelations, entityID_A.c_str()
);
} // foreach (Handle objectA, objects)
}
catch( const opencog::NotFoundException & ex ) {
// Usually it is ok to just skip the exception, because when the object
// is removed, it will fail to find the object. That is normal and happens
// quite often for consumable objects, such as FoodCube
return;
} // try
}
void SpatialPredicateUpdater::
compute3SizeSpatialRelations(const SpaceServer::SpaceMap & spaceMap,
std::vector<Handle> & objects,
std::vector <std::string> & entities,
Handle observer,
unsigned long timestamp
)
{
double besideDistance = spaceMap.getNextDistance();
try {
const spatial::EntityPtr & observerEntity =
spaceMap.getEntity( atomSpace.getName(observer) );
std::vector <std::string>::iterator iter_entityB, iter_entityC;
foreach (Handle objectA, objects) {
std::string entityID_A = atomSpace.getName(objectA);
int numRelations = 0;
const spatial::EntityPtr & entityA = spaceMap.getEntity(entityID_A);
for (iter_entityB = entities.begin(); iter_entityB != entities.end(); ++ iter_entityB) {
const std::string & entityID_B = *iter_entityB;
if ( entityID_A == entityID_B )
continue;
for (iter_entityC = iter_entityB; iter_entityC != entities.end(); ++ iter_entityC) {
const std::string & entityID_C = * iter_entityC;
if ( entityID_C == entityID_A || entityID_C == entityID_B )
continue;
SPATIAL_RELATION_VECTOR relationsAB, relationsAC;
if ( !spatialRelationCache.getRelation(entityID_A, entityID_B, relationsAB) ||
!spatialRelationCache.getRelation(entityID_A, entityID_C, relationsAC) )
continue;
Handle objectB = getHandle(entityID_B);
Handle objectC = getHandle(entityID_C);
SPATIAL_RELATION_VECTOR relationsABC;
if ( this->isBetween(relationsAB, relationsAC) ) {
relationsABC.push_back(Entity::BETWEEN);
this->addSpatialRelations(relationsABC, atomSpace, timestamp,
objectA, objectB, objectC
);
}
numRelations += relationsABC.size();
} // foreach (const std::string & entityID_C, entities)
} // foreach (const std::string & entityID_B, entities)
logger().debug("%s - Finished evaluating: %d 3-size spatial relations related to '%s'",
__FUNCTION__, numRelations, entityID_A.c_str()
);
} // foreach (Handle objectA, objects)
}
catch( const opencog::NotFoundException & ex ) {
// Usually it is ok to just skip the exception, because when the object
// is removed, it will fail to find the object. That is normal and happens
// quite often for consumable objects, such as FoodCube
return;
} // try
}
bool SpatialPredicateUpdater::isBetween(const SPATIAL_RELATION_VECTOR & relationsAB,
const SPATIAL_RELATION_VECTOR & relationsAC
)
{
bool bLeftAB = false,
bRightAB = false,
bAboveAB = false,
bBelowAB = false,
bFrontAB = false,
bBehindAB = false;
bool bLeftAC = false,
bRightAC = false,
bAboveAC = false,
bBelowAC = false,
bFrontAC = false,
bBehindAC = false;
foreach (Entity::SPATIAL_RELATION relAB, relationsAB) {
switch (relAB) {
case Entity::LEFT_OF: bLeftAB = true; break;
case Entity::RIGHT_OF: bRightAB = true; break;
case Entity::ABOVE: bAboveAB = true; break;
case Entity::BELOW: bBelowAB = true; break;
case Entity::BEHIND: bBelowAB = true; break;
case Entity::IN_FRONT_OF: bFrontAB = true; break;
default: break;
}
} // foreach
foreach (Entity::SPATIAL_RELATION relAC, relationsAC) {
switch (relAC) {
case Entity::LEFT_OF: bLeftAC = true; break;
case Entity::RIGHT_OF: bRightAC = true; break;
case Entity::ABOVE: bAboveAC = true; break;
case Entity::BELOW: bBelowAC = true; break;
case Entity::BEHIND: bBelowAC = true; break;
case Entity::IN_FRONT_OF: bFrontAC = true; break;
default: break;
}
} // foreach
return (bLeftAB && bRightAC) ||
(bRightAB && bLeftAC) ||
(bAboveAB && bBelowAC) ||
(bBelowAB && bAboveAC) ||
(bFrontAB && bBehindAC) ||
(bBehindAB && bFrontAC);
}
void SpatialPredicateUpdater::
addSpatialRelations(const SPATIAL_RELATION_VECTOR & relations,
AtomSpace & atomSpace, unsigned long timestamp,
Handle objectA, Handle objectB, Handle objectC
)
{
SimpleTruthValue tv(1, 1);
foreach (Entity::SPATIAL_RELATION rel, relations) {
string predicateName = Entity::spatialRelationToString(rel);
if ( objectC == Handle::UNDEFINED ) {
Handle eval = AtomSpaceUtil::setPredicateValue(atomSpace,
predicateName,
tv,
objectA, objectB
);
Handle atTime = atomSpace.getTimeServer().addTimeInfo(eval, timestamp);
atomSpace.setTV(atTime, tv);
}
else {
Handle eval = AtomSpaceUtil::setPredicateValue(atomSpace,
predicateName,
tv,
objectA, objectB, objectC
);
Handle atTime = atomSpace.getTimeServer().addTimeInfo(eval, timestamp);
atomSpace.setTV(atTime, tv);
}
}
}
bool SpatialPredicateUpdater::SpatialRelationCache::
isCached(std::string entityA_id, std::string entityB_id)
{
std::string key = entityA_id + entityB_id;
return this->_entityRelationMap.find(key) != this->_entityRelationMap.end();
}
bool SpatialPredicateUpdater::SpatialRelationCache::
getRelation(std::string entityA_id, std::string entityB_id, SPATIAL_RELATION_VECTOR & relation)
{
std::string key = entityA_id + entityB_id;
boost::unordered_map <std::string, SPATIAL_RELATION_VECTOR>::iterator
iter_relation = this->_entityRelationMap.find(key);
if ( iter_relation != this->_entityRelationMap.end() ) {
relation = iter_relation->second;
return true;
}
else
return false;
}
void SpatialPredicateUpdater::SpatialRelationCache::
addRelation(std::string entityA_id, std::string entityB_id, const SPATIAL_RELATION_VECTOR & relation)
{
std::string key = entityA_id + entityB_id;
this->_entityRelationMap[key] = relation;
}
void SpatialPredicateUpdater::SpatialRelationCache::clear()
{
this->_entityRelationMap.clear();
}
<commit_msg>remove spatial relations when they are not true any more<commit_after>/*
* opencog/embodiment/Control/PredicateUpdaters/SpatialPredicateUpdater.cc
*
* Copyright (C) 2002-2009 Novamente LLC
* All Rights Reserved
* Author(s): Ari Heljakka, Welter Luigi, Samir Araujo
*
* Updated: by Zhenhua Cai, on 2011-10-24
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomspace/SimpleTruthValue.h>
#include "SpatialPredicateUpdater.h"
#include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h>
using namespace opencog::oac;
using namespace opencog;
using namespace spatial;
SpatialPredicateUpdater::SpatialPredicateUpdater(AtomSpace & _atomSpace) :
BasicPredicateUpdater(_atomSpace) {}
SpatialPredicateUpdater::~SpatialPredicateUpdater()
{
}
void SpatialPredicateUpdater::update(std::vector<Handle> & objects,
Handle pet,
unsigned long timestamp
)
{
//struct timeval timer_start, timer_end;
//time_t elapsed_time = 0;
//gettimeofday(&timer_start, NULL);
// If there is no map, none update is possible
Handle spaceMapHandle = atomSpace.getSpaceServer().getLatestMapHandle();
if (spaceMapHandle == Handle::UNDEFINED) {
logger().warn( "SpatialPredicateUpdater::%s - No space map handle found!", __FUNCTION__);
return;
}
const SpaceServer::SpaceMap & spaceMap = atomSpace.getSpaceServer().getLatestMap();
logger().debug( "SpatialPredicateUpdater::%s - Processing timestamp '%lu'",
__FUNCTION__, timestamp );
if ( lastTimestamp != timestamp ) {
lastTimestamp = timestamp;
this->spatialRelationCache.clear();
}
// Get all the entities that are NOT blocks
std::vector<std::string> entities;
spaceMap.findEntitiesWithClassFilter(back_inserter(entities), "block");
this->compute2SizeSpatialRelations(spaceMap, objects, entities, pet, timestamp);
//gettimeofday(&timer_end, NULL);
//elapsed_time += ((timer_end.tv_sec - timer_start.tv_sec) * 1000000) +
// (timer_end.tv_usec - timer_start.tv_usec);
//timer_start = timer_end;
//logger().warn("SpatialPredicateUpdater::%s - process 2-size spatial relations: consumed %f seconds",
// __FUNCTION__,
// 1.0 * elapsed_time/1000000
// );
this->compute3SizeSpatialRelations(spaceMap, objects, entities, pet, timestamp);
//gettimeofday(&timer_end, NULL);
//elapsed_time += ((timer_end.tv_sec - timer_start.tv_sec) * 1000000) +
// (timer_end.tv_usec - timer_start.tv_usec);
//timer_start = timer_end;
//logger().warn("SpatialPredicateUpdater::%s - process 3-size spatial relations: consumed %f seconds",
// __FUNCTION__,
// 1.0 * elapsed_time/1000000
// );
}
SpatialPredicateUpdater::SPATIAL_RELATION_VECTOR SpatialPredicateUpdater::
swapRelations(SPATIAL_RELATION_VECTOR & relations)
{
SPATIAL_RELATION_VECTOR newRelations;
foreach (Entity::SPATIAL_RELATION rel, relations) {
switch (rel) {
case Entity::LEFT_OF: newRelations.push_back(Entity::RIGHT_OF); break;
case Entity::RIGHT_OF: newRelations.push_back(Entity::LEFT_OF); break;
case Entity::ABOVE: newRelations.push_back(Entity::BELOW); break;
case Entity::BELOW: newRelations.push_back(Entity::ABOVE); break;
case Entity::BEHIND: newRelations.push_back(Entity::IN_FRONT_OF); break;
case Entity::IN_FRONT_OF: newRelations.push_back(Entity::BEHIND); break;
case Entity::BESIDE: newRelations.push_back(Entity::BESIDE); break;
case Entity::NEAR: newRelations.push_back(Entity::NEAR); break;
case Entity::FAR_: newRelations.push_back(Entity::FAR_); break;
case Entity::TOUCHING: newRelations.push_back(Entity::TOUCHING); break;
case Entity::INSIDE: newRelations.push_back(Entity::OUTSIDE); break;
case Entity::OUTSIDE: newRelations.push_back(Entity::INSIDE); break;
case Entity::ADJACENT: newRelations.push_back(Entity::ADJACENT); break;
default: break;
} // switch (rel)
} // foreach (Entity::SPATIAL_RELATION rel, relations)
return newRelations;
}
void SpatialPredicateUpdater::
compute2SizeSpatialRelations(const SpaceServer::SpaceMap & spaceMap,
std::vector<Handle> & objects,
std::vector <std::string> & entities,
Handle observer,
unsigned long timestamp
)
{
double besideDistance = spaceMap.getNextDistance();
try {
const spatial::EntityPtr & observerEntity =
spaceMap.getEntity( atomSpace.getName(observer) );
foreach (Handle objectA, objects) {
int numRelations = 0;
std::string entityID_A = atomSpace.getName(objectA);
const spatial::EntityPtr & entityA = spaceMap.getEntity(entityID_A);
foreach (const std::string & entityID_B, entities) {
if ( entityID_A == entityID_B ||
this->spatialRelationCache.isCached(entityID_A, entityID_B) ) {
continue;
}
const spatial::EntityPtr & entityB = spaceMap.getEntity(entityID_B);
Handle objectB = getHandle(entityID_B);
SPATIAL_RELATION_VECTOR relationsAB, relationsBA;
// Compute size-2 directional spatial relations (B is the reference object)
relationsAB = entityA->computeSpatialRelations( *observerEntity, besideDistance, *entityB );
relationsBA = this->swapRelations(relationsAB);
this->addSpatialRelations(relationsAB, atomSpace, timestamp, objectA, objectB);
this->addSpatialRelations(relationsBA, atomSpace, timestamp, objectB, objectA);
this->spatialRelationCache.addRelation(entityID_A, entityID_B, relationsAB);
this->spatialRelationCache.addRelation(entityID_B, entityID_A, relationsBA);
numRelations += relationsAB.size();
} // foreach (const std::string & entityID_B, entities)
logger().debug("%s - Finished evaluating: %d 2-size spatial relations related to '%s'",
__FUNCTION__, numRelations, entityID_A.c_str()
);
} // foreach (Handle objectA, objects)
}
catch( const opencog::NotFoundException & ex ) {
// Usually it is ok to just skip the exception, because when the object
// is removed, it will fail to find the object. That is normal and happens
// quite often for consumable objects, such as FoodCube
return;
} // try
}
void SpatialPredicateUpdater::
compute3SizeSpatialRelations(const SpaceServer::SpaceMap & spaceMap,
std::vector<Handle> & objects,
std::vector <std::string> & entities,
Handle observer,
unsigned long timestamp
)
{
double besideDistance = spaceMap.getNextDistance();
try {
const spatial::EntityPtr & observerEntity =
spaceMap.getEntity( atomSpace.getName(observer) );
std::vector <std::string>::iterator iter_entityB, iter_entityC;
foreach (Handle objectA, objects) {
std::string entityID_A = atomSpace.getName(objectA);
int numRelations = 0;
const spatial::EntityPtr & entityA = spaceMap.getEntity(entityID_A);
for (iter_entityB = entities.begin(); iter_entityB != entities.end(); ++ iter_entityB) {
const std::string & entityID_B = *iter_entityB;
if ( entityID_A == entityID_B )
continue;
for (iter_entityC = iter_entityB; iter_entityC != entities.end(); ++ iter_entityC) {
const std::string & entityID_C = * iter_entityC;
if ( entityID_C == entityID_A || entityID_C == entityID_B )
continue;
SPATIAL_RELATION_VECTOR relationsAB, relationsAC;
if ( !spatialRelationCache.getRelation(entityID_A, entityID_B, relationsAB) ||
!spatialRelationCache.getRelation(entityID_A, entityID_C, relationsAC) )
continue;
Handle objectB = getHandle(entityID_B);
Handle objectC = getHandle(entityID_C);
SPATIAL_RELATION_VECTOR relationsABC;
if ( this->isBetween(relationsAB, relationsAC) ) {
relationsABC.push_back(Entity::BETWEEN);
this->addSpatialRelations(relationsABC, atomSpace, timestamp,
objectA, objectB, objectC
);
}
numRelations += relationsABC.size();
} // foreach (const std::string & entityID_C, entities)
} // foreach (const std::string & entityID_B, entities)
logger().debug("%s - Finished evaluating: %d 3-size spatial relations related to '%s'",
__FUNCTION__, numRelations, entityID_A.c_str()
);
} // foreach (Handle objectA, objects)
}
catch( const opencog::NotFoundException & ex ) {
// Usually it is ok to just skip the exception, because when the object
// is removed, it will fail to find the object. That is normal and happens
// quite often for consumable objects, such as FoodCube
return;
} // try
}
bool SpatialPredicateUpdater::isBetween(const SPATIAL_RELATION_VECTOR & relationsAB,
const SPATIAL_RELATION_VECTOR & relationsAC
)
{
bool bLeftAB = false,
bRightAB = false,
bAboveAB = false,
bBelowAB = false,
bFrontAB = false,
bBehindAB = false;
bool bLeftAC = false,
bRightAC = false,
bAboveAC = false,
bBelowAC = false,
bFrontAC = false,
bBehindAC = false;
foreach (Entity::SPATIAL_RELATION relAB, relationsAB) {
switch (relAB) {
case Entity::LEFT_OF: bLeftAB = true; break;
case Entity::RIGHT_OF: bRightAB = true; break;
case Entity::ABOVE: bAboveAB = true; break;
case Entity::BELOW: bBelowAB = true; break;
case Entity::BEHIND: bBelowAB = true; break;
case Entity::IN_FRONT_OF: bFrontAB = true; break;
default: break;
}
} // foreach
foreach (Entity::SPATIAL_RELATION relAC, relationsAC) {
switch (relAC) {
case Entity::LEFT_OF: bLeftAC = true; break;
case Entity::RIGHT_OF: bRightAC = true; break;
case Entity::ABOVE: bAboveAC = true; break;
case Entity::BELOW: bBelowAC = true; break;
case Entity::BEHIND: bBelowAC = true; break;
case Entity::IN_FRONT_OF: bFrontAC = true; break;
default: break;
}
} // foreach
return (bLeftAB && bRightAC) ||
(bRightAB && bLeftAC) ||
(bAboveAB && bBelowAC) ||
(bBelowAB && bAboveAC) ||
(bFrontAB && bBehindAC) ||
(bBehindAB && bFrontAC);
}
void SpatialPredicateUpdater::
addSpatialRelations(const SPATIAL_RELATION_VECTOR & relations,
AtomSpace & atomSpace, unsigned long timestamp,
Handle objectA, Handle objectB, Handle objectC
)
{
// Clear all the relations firstly
for (int rel = 0; rel < (int)Entity::TOTAL_RELATIONS; ++ rel) {
string predicateName = Entity::spatialRelationToString( (Entity::SPATIAL_RELATION) rel );
Handle eval = AtomSpaceUtil::setPredicateValue(atomSpace,
predicateName,
TruthValue::FALSE_TV(),
objectA, objectB, objectC
);
}
// Set relations
foreach (Entity::SPATIAL_RELATION rel, relations) {
string predicateName = Entity::spatialRelationToString(rel);
Handle eval = AtomSpaceUtil::setPredicateValue(atomSpace,
predicateName,
TruthValue::TRUE_TV(),
objectA, objectB, objectC
);
Handle atTime = atomSpace.getTimeServer().addTimeInfo(eval, timestamp);
atomSpace.setTV(atTime, TruthValue::TRUE_TV());
}
}
bool SpatialPredicateUpdater::SpatialRelationCache::
isCached(std::string entityA_id, std::string entityB_id)
{
std::string key = entityA_id + entityB_id;
return this->_entityRelationMap.find(key) != this->_entityRelationMap.end();
}
bool SpatialPredicateUpdater::SpatialRelationCache::
getRelation(std::string entityA_id, std::string entityB_id, SPATIAL_RELATION_VECTOR & relation)
{
std::string key = entityA_id + entityB_id;
boost::unordered_map <std::string, SPATIAL_RELATION_VECTOR>::iterator
iter_relation = this->_entityRelationMap.find(key);
if ( iter_relation != this->_entityRelationMap.end() ) {
relation = iter_relation->second;
return true;
}
else
return false;
}
void SpatialPredicateUpdater::SpatialRelationCache::
addRelation(std::string entityA_id, std::string entityB_id, const SPATIAL_RELATION_VECTOR & relation)
{
std::string key = entityA_id + entityB_id;
this->_entityRelationMap[key] = relation;
}
void SpatialPredicateUpdater::SpatialRelationCache::clear()
{
this->_entityRelationMap.clear();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Fastly, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/*
* This file implements a test harness for using h2o with LibFuzzer.
* See http://llvm.org/docs/LibFuzzer.html for more info.
*/
#define H2O_USE_EPOLL 1
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include "h2o.h"
#include "h2o/http1.h"
#include "h2o/http2.h"
#include "h2o/url.h"
#include "h2o/memcached.h"
#if !defined(HTTP1) && !defined(HTTP2)
#error "Please defined one of HTTP1 or HTTP2"
#endif
#if defined(HTTP1) && defined(HTTP2)
#error "Please defined one of HTTP1 or HTTP2, but not both"
#endif
static h2o_globalconf_t config;
static h2o_context_t ctx;
static h2o_accept_ctx_t accept_ctx;
static int client_timeout_ms;
static char unix_listener[PATH_MAX];
/*
* Registers a request handler with h2o
*/
static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path, int (*on_req)(h2o_handler_t *, h2o_req_t *))
{
h2o_pathconf_t *pathconf = h2o_config_register_path(hostconf, path, 0);
h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler));
handler->on_req = on_req;
return pathconf;
}
/*
* Request handler used for testing. Returns a basic "200 OK" response.
*/
static int chunked_test(h2o_handler_t *self, h2o_req_t *req)
{
static h2o_generator_t generator = {NULL, NULL};
if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET")))
return -1;
h2o_iovec_t body = h2o_strdup(&req->pool, "hello world\n", SIZE_MAX);
req->res.status = 200;
req->res.reason = "OK";
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, H2O_STRLIT("text/plain"));
h2o_start_response(req, &generator);
h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL);
return 0;
}
/* copy from src to dst, return true if src has EOF */
static int drain(int fd)
{
char buf[4096];
ssize_t n;
n = read(fd, buf, sizeof(buf));
if (n <= 0) {
return 1;
}
return 0;
}
/* A request sent from client thread to h2o server */
struct writer_thread_arg {
char *buf;
size_t len;
int fd;
h2o_barrier_t barrier;
};
/*
* Reads writer_thread_arg from fd and stores to buf
*/
static void read_fully(int fd, char *buf, size_t len)
{
int done = 0;
while (len) {
int ret;
while ((ret = read(fd, buf + done, len)) == -1 && errno == EINTR)
;
if (ret <= 0) {
abort();
}
done += ret;
len -= ret;
}
}
/*
* Writes the writer_thread_args at buf to fd
*/
static void write_fully(int fd, char *buf, size_t len, int abort_on_err)
{
int done = 0;
while (len) {
int ret;
while ((ret = write(fd, buf + done, len)) == -1 && errno == EINTR)
;
if (ret <= 0) {
if (abort_on_err)
abort();
else
return;
}
done += ret;
len -= ret;
}
}
#define OK_RESP \
"HTTP/1.0 200 OK\r\n" \
"Connection: Close\r\n\r\nOk"
#define OK_RESP_LEN (sizeof(OK_RESP) - 1)
void *upstream_thread(void *arg)
{
char *dirname = (char *)arg;
char path[PATH_MAX];
char rbuf[1 * 1024 * 1024];
snprintf(path, sizeof(path), "/%s/_.sock", dirname);
int sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
abort();
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
if (bind(sd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
abort();
}
if (listen(sd, 100) != 0) {
abort();
}
while (1) {
struct sockaddr_un caddr;
socklen_t slen = 0;
int cfs = accept(sd, (struct sockaddr *)&caddr, &slen);
if (cfs < 0) {
continue;
}
read(cfs, rbuf, sizeof(rbuf));
write_fully(cfs, (char *)OK_RESP, OK_RESP_LEN, 0);
close(cfs);
}
}
/*
* Thread: Loops writing fuzzed req to socket and then reading results back.
* Acts as a client to h2o. *arg points to file descripter to read
* writer_thread_args from.
*/
void *writer_thread(void *arg)
{
int rfd = (long)arg;
while (1) {
int pos, sockinp, sockoutp, cnt, len;
char *buf;
struct writer_thread_arg *wta;
/* Get fuzzed request */
read_fully(rfd, (char *)&wta, sizeof(wta));
pos = 0;
sockinp = wta->fd;
sockoutp = wta->fd;
cnt = 0;
buf = wta->buf;
len = wta->len;
/*
* Send fuzzed req and read results until the socket is closed (or
* something spurious happens)
*/
while (cnt++ < 20 && (pos < len || sockinp >= 0)) {
#define MARKER "\n--MARK--\n"
/* send 1 packet */
if (pos < len) {
char *p = (char *)memmem(buf + pos, len - pos, MARKER, sizeof(MARKER) - 1);
if (p) {
int l = p - (buf + pos);
write(sockoutp, buf + pos, l);
pos += l;
pos += sizeof(MARKER) - 1;
}
} else {
if (sockinp >= 0) {
shutdown(sockinp, SHUT_WR);
}
}
/* drain socket */
if (sockinp >= 0) {
struct timeval timeo;
fd_set rd;
int n;
FD_ZERO(&rd);
FD_SET(sockinp, &rd);
timeo.tv_sec = 0;
timeo.tv_usec = client_timeout_ms * 1000;
n = select(sockinp + 1, &rd, NULL, NULL, &timeo);
if (n > 0 && FD_ISSET(sockinp, &rd) && drain(sockinp)) {
sockinp = -1;
}
}
}
close(wta->fd);
h2o_barrier_wait(&wta->barrier);
h2o_barrier_destroy(&wta->barrier);
free(wta);
}
}
/*
* Creates socket pair and passes fuzzed req to a thread (the HTTP[/2] client)
* for writing to the target h2o server. Returns the server socket fd.
*/
static int feeder(int sfd, char *buf, size_t len, h2o_barrier_t **barrier)
{
int pair[2];
struct writer_thread_arg *wta;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
return -1;
wta = (struct writer_thread_arg *)malloc(sizeof(*wta));
wta->fd = pair[0];
wta->buf = buf;
wta->len = len;
h2o_barrier_init(&wta->barrier, 2);
*barrier = &wta->barrier;
write_fully(sfd, (char *)&wta, sizeof(wta), 1);
return pair[1];
}
/*
* Creates/connects socket pair for client/server interaction and passes
* fuzzed request to client for sending.
* Returns server socket fd.
*/
static int create_accepted(int sfd, char *buf, size_t len, h2o_barrier_t **barrier)
{
int fd;
h2o_socket_t *sock;
struct timeval connected_at = h2o_gettimeofday(ctx->loop);
/* Create an HTTP[/2] client that will send the fuzzed request */
fd = feeder(sfd, buf, len, barrier);
if (fd < 0) {
abort();
}
/* Pass the server socket to h2o and invoke request processing */
sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION);
#if defined(HTTP1)
h2o_http1_accept(&accept_ctx, sock, connected_at);
#else
h2o_http2_accept(&accept_ctx, sock, connected_at);
#endif
return fd;
}
/*
* Returns true if fd if valid. Used to determine when connection is closed.
*/
static int is_valid_fd(int fd)
{
return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
}
/*
* Entry point for libfuzzer.
* See http://llvm.org/docs/LibFuzzer.html for more info
*/
static int init_done;
static int job_queue[2];
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
{
int c;
h2o_loop_t *loop;
h2o_hostconf_t *hostconf;
pthread_t twriter;
pthread_t tupstream;
/*
* Perform one-time initialization
*/
if (!init_done) {
const char *client_timeout_ms_str;
static char tmpname[] = "/tmp/h2o-fuzz-XXXXXX";
char *dirname;
h2o_url_t upstream;
signal(SIGPIPE, SIG_IGN);
dirname = mkdtemp(tmpname);
snprintf(unix_listener, sizeof(unix_listener), "http://[unix://%s/_.sock]/proxy", dirname);
if ((client_timeout_ms_str = getenv("H2O_FUZZER_CLIENT_TIMEOUT")) != NULL)
client_timeout_ms = atoi(client_timeout_ms_str);
if (!client_timeout_ms)
client_timeout_ms = 10;
/* Create a single h2o host with multiple request handlers */
h2o_config_init(&config);
config.http2.idle_timeout = 10 * 1000;
config.http1.req_timeout = 10 * 1000;
config.proxy.io_timeout = 10 * 1000;
h2o_proxy_config_vars_t proxy_config = {};
proxy_config.io_timeout = 10 * 1000;
hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT(unix_listener)), 65535);
register_handler(hostconf, "/chunked-test", chunked_test);
h2o_url_parse(unix_listener, strlen(unix_listener), &upstream);
h2o_socketpool_t *sockpool = new h2o_socketpool_t();
h2o_socketpool_target_t *target = h2o_socketpool_create_target(&upstream, NULL);
h2o_socketpool_init_specific(sockpool, SIZE_MAX /* FIXME */, &target, 1, NULL);
h2o_socketpool_set_timeout(sockpool, 2000);
h2o_socketpool_set_ssl_ctx(sockpool, NULL);
h2o_proxy_register_reverse_proxy(h2o_config_register_path(hostconf, "/reproxy-test", 0), &proxy_config, sockpool);
h2o_file_register(h2o_config_register_path(hostconf, "/", 0), "./examples/doc_root", NULL, NULL, 0);
loop = h2o_evloop_create();
h2o_context_init(&ctx, loop, &config);
accept_ctx.ctx = &ctx;
accept_ctx.hosts = config.hosts;
/* Create a thread to act as the HTTP client */
if (socketpair(AF_UNIX, SOCK_STREAM, 0, job_queue) != 0) {
abort();
}
if (pthread_create(&twriter, NULL, writer_thread, (void *)(long)job_queue[1]) != 0) {
abort();
}
if (pthread_create(&tupstream, NULL, upstream_thread, dirname) != 0) {
abort();
}
init_done = 1;
}
/*
* Pass fuzzed request to client thread and get h2o server socket for
* use below
*/
h2o_barrier_t *end;
c = create_accepted(job_queue[0], (char *)Data, (size_t)Size, &end);
if (c < 0) {
goto Error;
}
/* Loop until the connection is closed by the client or server */
while (is_valid_fd(c)) {
h2o_evloop_run(ctx.loop, 10);
}
h2o_barrier_wait(end);
return 0;
Error:
return 1;
}
<commit_msg>fix fuzz/driver.cc<commit_after>/*
* Copyright (c) 2016 Fastly, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/*
* This file implements a test harness for using h2o with LibFuzzer.
* See http://llvm.org/docs/LibFuzzer.html for more info.
*/
#define H2O_USE_EPOLL 1
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include "h2o.h"
#include "h2o/http1.h"
#include "h2o/http2.h"
#include "h2o/url.h"
#include "h2o/memcached.h"
#if !defined(HTTP1) && !defined(HTTP2)
#error "Please defined one of HTTP1 or HTTP2"
#endif
#if defined(HTTP1) && defined(HTTP2)
#error "Please defined one of HTTP1 or HTTP2, but not both"
#endif
static h2o_globalconf_t config;
static h2o_context_t ctx;
static h2o_accept_ctx_t accept_ctx;
static int client_timeout_ms;
static char unix_listener[PATH_MAX];
/*
* Registers a request handler with h2o
*/
static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path, int (*on_req)(h2o_handler_t *, h2o_req_t *))
{
h2o_pathconf_t *pathconf = h2o_config_register_path(hostconf, path, 0);
h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler));
handler->on_req = on_req;
return pathconf;
}
/*
* Request handler used for testing. Returns a basic "200 OK" response.
*/
static int chunked_test(h2o_handler_t *self, h2o_req_t *req)
{
static h2o_generator_t generator = {NULL, NULL};
if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET")))
return -1;
h2o_iovec_t body = h2o_strdup(&req->pool, "hello world\n", SIZE_MAX);
req->res.status = 200;
req->res.reason = "OK";
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, H2O_STRLIT("text/plain"));
h2o_start_response(req, &generator);
h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL);
return 0;
}
/* copy from src to dst, return true if src has EOF */
static int drain(int fd)
{
char buf[4096];
ssize_t n;
n = read(fd, buf, sizeof(buf));
if (n <= 0) {
return 1;
}
return 0;
}
/* A request sent from client thread to h2o server */
struct writer_thread_arg {
char *buf;
size_t len;
int fd;
h2o_barrier_t barrier;
};
/*
* Reads writer_thread_arg from fd and stores to buf
*/
static void read_fully(int fd, char *buf, size_t len)
{
int done = 0;
while (len) {
int ret;
while ((ret = read(fd, buf + done, len)) == -1 && errno == EINTR)
;
if (ret <= 0) {
abort();
}
done += ret;
len -= ret;
}
}
/*
* Writes the writer_thread_args at buf to fd
*/
static void write_fully(int fd, char *buf, size_t len, int abort_on_err)
{
int done = 0;
while (len) {
int ret;
while ((ret = write(fd, buf + done, len)) == -1 && errno == EINTR)
;
if (ret <= 0) {
if (abort_on_err)
abort();
else
return;
}
done += ret;
len -= ret;
}
}
#define OK_RESP \
"HTTP/1.0 200 OK\r\n" \
"Connection: Close\r\n\r\nOk"
#define OK_RESP_LEN (sizeof(OK_RESP) - 1)
void *upstream_thread(void *arg)
{
char *dirname = (char *)arg;
char path[PATH_MAX];
char rbuf[1 * 1024 * 1024];
snprintf(path, sizeof(path), "/%s/_.sock", dirname);
int sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
abort();
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
if (bind(sd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
abort();
}
if (listen(sd, 100) != 0) {
abort();
}
while (1) {
struct sockaddr_un caddr;
socklen_t slen = 0;
int cfs = accept(sd, (struct sockaddr *)&caddr, &slen);
if (cfs < 0) {
continue;
}
read(cfs, rbuf, sizeof(rbuf));
write_fully(cfs, (char *)OK_RESP, OK_RESP_LEN, 0);
close(cfs);
}
}
/*
* Thread: Loops writing fuzzed req to socket and then reading results back.
* Acts as a client to h2o. *arg points to file descripter to read
* writer_thread_args from.
*/
void *writer_thread(void *arg)
{
int rfd = (long)arg;
while (1) {
int pos, sockinp, sockoutp, cnt, len;
char *buf;
struct writer_thread_arg *wta;
/* Get fuzzed request */
read_fully(rfd, (char *)&wta, sizeof(wta));
pos = 0;
sockinp = wta->fd;
sockoutp = wta->fd;
cnt = 0;
buf = wta->buf;
len = wta->len;
/*
* Send fuzzed req and read results until the socket is closed (or
* something spurious happens)
*/
while (cnt++ < 20 && (pos < len || sockinp >= 0)) {
#define MARKER "\n--MARK--\n"
/* send 1 packet */
if (pos < len) {
char *p = (char *)memmem(buf + pos, len - pos, MARKER, sizeof(MARKER) - 1);
if (p) {
int l = p - (buf + pos);
write(sockoutp, buf + pos, l);
pos += l;
pos += sizeof(MARKER) - 1;
}
} else {
if (sockinp >= 0) {
shutdown(sockinp, SHUT_WR);
}
}
/* drain socket */
if (sockinp >= 0) {
struct timeval timeo;
fd_set rd;
int n;
FD_ZERO(&rd);
FD_SET(sockinp, &rd);
timeo.tv_sec = 0;
timeo.tv_usec = client_timeout_ms * 1000;
n = select(sockinp + 1, &rd, NULL, NULL, &timeo);
if (n > 0 && FD_ISSET(sockinp, &rd) && drain(sockinp)) {
sockinp = -1;
}
}
}
close(wta->fd);
h2o_barrier_wait(&wta->barrier);
h2o_barrier_destroy(&wta->barrier);
free(wta);
}
}
/*
* Creates socket pair and passes fuzzed req to a thread (the HTTP[/2] client)
* for writing to the target h2o server. Returns the server socket fd.
*/
static int feeder(int sfd, char *buf, size_t len, h2o_barrier_t **barrier)
{
int pair[2];
struct writer_thread_arg *wta;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
return -1;
wta = (struct writer_thread_arg *)malloc(sizeof(*wta));
wta->fd = pair[0];
wta->buf = buf;
wta->len = len;
h2o_barrier_init(&wta->barrier, 2);
*barrier = &wta->barrier;
write_fully(sfd, (char *)&wta, sizeof(wta), 1);
return pair[1];
}
/*
* Creates/connects socket pair for client/server interaction and passes
* fuzzed request to client for sending.
* Returns server socket fd.
*/
static int create_accepted(int sfd, char *buf, size_t len, h2o_barrier_t **barrier)
{
int fd;
h2o_socket_t *sock;
struct timeval connected_at = h2o_gettimeofday(ctx.loop);
/* Create an HTTP[/2] client that will send the fuzzed request */
fd = feeder(sfd, buf, len, barrier);
if (fd < 0) {
abort();
}
/* Pass the server socket to h2o and invoke request processing */
sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION);
#if defined(HTTP1)
h2o_http1_accept(&accept_ctx, sock, connected_at);
#else
h2o_http2_accept(&accept_ctx, sock, connected_at);
#endif
return fd;
}
/*
* Returns true if fd if valid. Used to determine when connection is closed.
*/
static int is_valid_fd(int fd)
{
return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
}
/*
* Entry point for libfuzzer.
* See http://llvm.org/docs/LibFuzzer.html for more info
*/
static int init_done;
static int job_queue[2];
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
{
int c;
h2o_loop_t *loop;
h2o_hostconf_t *hostconf;
pthread_t twriter;
pthread_t tupstream;
/*
* Perform one-time initialization
*/
if (!init_done) {
const char *client_timeout_ms_str;
static char tmpname[] = "/tmp/h2o-fuzz-XXXXXX";
char *dirname;
h2o_url_t upstream;
signal(SIGPIPE, SIG_IGN);
dirname = mkdtemp(tmpname);
snprintf(unix_listener, sizeof(unix_listener), "http://[unix://%s/_.sock]/proxy", dirname);
if ((client_timeout_ms_str = getenv("H2O_FUZZER_CLIENT_TIMEOUT")) != NULL)
client_timeout_ms = atoi(client_timeout_ms_str);
if (!client_timeout_ms)
client_timeout_ms = 10;
/* Create a single h2o host with multiple request handlers */
h2o_config_init(&config);
config.http2.idle_timeout = 10 * 1000;
config.http1.req_timeout = 10 * 1000;
config.proxy.io_timeout = 10 * 1000;
h2o_proxy_config_vars_t proxy_config = {};
proxy_config.io_timeout = 10 * 1000;
hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT(unix_listener)), 65535);
register_handler(hostconf, "/chunked-test", chunked_test);
h2o_url_parse(unix_listener, strlen(unix_listener), &upstream);
h2o_socketpool_t *sockpool = new h2o_socketpool_t();
h2o_socketpool_target_t *target = h2o_socketpool_create_target(&upstream, NULL);
h2o_socketpool_init_specific(sockpool, SIZE_MAX /* FIXME */, &target, 1, NULL);
h2o_socketpool_set_timeout(sockpool, 2000);
h2o_socketpool_set_ssl_ctx(sockpool, NULL);
h2o_proxy_register_reverse_proxy(h2o_config_register_path(hostconf, "/reproxy-test", 0), &proxy_config, sockpool);
h2o_file_register(h2o_config_register_path(hostconf, "/", 0), "./examples/doc_root", NULL, NULL, 0);
loop = h2o_evloop_create();
h2o_context_init(&ctx, loop, &config);
accept_ctx.ctx = &ctx;
accept_ctx.hosts = config.hosts;
/* Create a thread to act as the HTTP client */
if (socketpair(AF_UNIX, SOCK_STREAM, 0, job_queue) != 0) {
abort();
}
if (pthread_create(&twriter, NULL, writer_thread, (void *)(long)job_queue[1]) != 0) {
abort();
}
if (pthread_create(&tupstream, NULL, upstream_thread, dirname) != 0) {
abort();
}
init_done = 1;
}
/*
* Pass fuzzed request to client thread and get h2o server socket for
* use below
*/
h2o_barrier_t *end;
c = create_accepted(job_queue[0], (char *)Data, (size_t)Size, &end);
if (c < 0) {
goto Error;
}
/* Loop until the connection is closed by the client or server */
while (is_valid_fd(c)) {
h2o_evloop_run(ctx.loop, 10);
}
h2o_barrier_wait(end);
return 0;
Error:
return 1;
}
<|endoftext|> |
<commit_before>#pragma once
#include "Runtime/Collision/CJointCollisionDescription.hpp"
#include "Runtime/MP1/World/CShockWave.hpp"
#include "Runtime/World/CPathFindSearch.hpp"
#include "Runtime/World/CPatterned.hpp"
namespace urde {
class CCollisionActorManager;
namespace MP1 {
class CMetroidPrimeEssence : public CPatterned {
TCachedToken<CGenDescription> x568_;
CPathFindSearch x574_searchPath;
std::unique_ptr<CCollisionActorManager> x658_collisionManager;
std::unique_ptr<CElementGen> x65c_;
CAssetId x660_;
CAssetId x664_;
zeus::CTransform x668_;
CDamageInfo x698_;
zeus::CVector3f x6b4_;
float x6c0_ = 0.f;
float x6c4_ = 0.f;
float x6c8_ = 0.f;
float x6cc_ = 4.f;
float x6d0_ = 0.9f * x6cc_ + x6cc_;
float x6d4_ = 0.f;
u32 x6d8_ = 0;
u32 x6dc_ = 0;
u32 x6e0_ = x6dc_;
u32 x6e4_ = 0;
u32 x6e8_ = 2;
u32 x6ec_ = 4;
u32 x6f0_ = 0;
u32 x6f4_ = x6e8_ - 1;
u32 x6f8_ = 2;
u32 x6fc_ = 0;
u32 x700_ = 1;
TUniqueId x704_ = kInvalidUniqueId;
TUniqueId x706_lockOnTargetCollider = kInvalidUniqueId;
CSfxHandle x708_;
s16 x70c_;
bool x70e_24_ : 1 = false;
bool x70e_25_ : 1 = true;
bool x70e_26_ : 1 = false;
bool x70e_27_ : 1 = false;
bool x70e_28_ : 1 = true;
bool x70e_29_ : 1 = false;
bool x70e_30_ : 1 = false;
bool x70e_31_ : 1 = false;
void sub8027cb40(const zeus::CVector3f& vec);
void sub8027cce0(CStateManager& mgr);
zeus::CTransform GetTargetTransform(CStateManager& mgr);
void sub8027ce5c(float f1);
void sub8027cee0(CStateManager& mgr);
u32 sub8027cfd4(CStateManager& mgr, u32 w1);
void DoPhaseTransition(CStateManager& mgr);
u32 sub8027d428() { return 2; }
void ShakeCamera(CStateManager& mgr, float f1);
void sub8027d52c(CStateManager& mgr, const SShockWaveData& shockWaveData);
CRayCastResult sub8027d704(CStateManager& mgr);
void sub8027d790(CStateManager& mgr, bool active);
void sub8027d824(CStateManager& mgr);
bool sub8027e870(const zeus::CTransform& xf, CStateManager& mgr);
void sub8027ee88(CStateManager& mgr);
void CountListeningAi(CStateManager& mgr);
void UpdatePhase(float dt, CStateManager& mgr);
void UpdateHealth(CStateManager& mgr);
void SetLockOnTargetHealthAndDamageVulns(CStateManager& mgr);
void AddSphereCollisions(SSphereJointInfo* info, size_t count, std::vector<CJointCollisionDescription>& vecOut);
void SetupCollisionActorManager(CStateManager& mgr);
public:
DEFINE_PATTERNED(MetroidPrimeEssence);
CMetroidPrimeEssence(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,
CModelData&& mData, const CPatternedInfo& pInfo, const CActorParameters& actParms,
CAssetId particle1, const CDamageInfo& dInfo, float f1, CAssetId electric, u32 w1,
CAssetId particle2);
void Think(float dt, CStateManager& mgr) override;
void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId other, CStateManager& mgr) override;
void PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) override;
void AddToRenderer(const zeus::CFrustum& frustum, CStateManager& mgr) override;
void Render(CStateManager& mgr) override;
zeus::CVector3f GetAimPosition(const CStateManager& mgr, float dt) const override;
void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) override;
void Death(CStateManager& mgr, const zeus::CVector3f& direction, EScriptObjectState state) override;
void Dead(CStateManager& mgr, EStateMsg msg, float dt) override;
void PathFind(CStateManager& mgr, EStateMsg msg, float dt) override;
void Halt(CStateManager& mgr, EStateMsg msg, float dt) override;
void Generate(CStateManager& mgr, EStateMsg msg, float dt) override;
void JumpBack(CStateManager& mgr, EStateMsg msg, float dt) override;
void Skid(CStateManager& mgr, EStateMsg msg, float dt) override;
void FadeIn(CStateManager& mgr, EStateMsg msg, float dt) override;
void FadeOut(CStateManager& mgr, EStateMsg msg, float dt) override;
void Taunt(CStateManager& mgr, EStateMsg msg, float dt) override;
void TelegraphAttack(CStateManager& mgr, EStateMsg msg, float dt) override;
void Dodge(CStateManager& mgr, EStateMsg msg, float dt) override;
void PathFindEx(CStateManager& mgr, EStateMsg msg, float dt) override;
bool HasPatrolPath(CStateManager& mgr, float dt) override;
bool ShouldAttack(CStateManager& mgr, float dt) override;
bool InPosition(CStateManager& mgr, float dt) override;
bool CoverFind(CStateManager& mgr, float dt) override;
bool ShouldTaunt(CStateManager& mgr, float dt) override;
bool ShouldCrouch(CStateManager& mgr, float dt) override;
bool ShouldMove(CStateManager& mgr, float dt) override;
CPathFindSearch* GetSearchPath() override;
};
} // namespace MP1
} // namespace urde<commit_msg>Teh maymays<commit_after>#pragma once
#include "Runtime/Collision/CJointCollisionDescription.hpp"
#include "Runtime/MP1/World/CShockWave.hpp"
#include "Runtime/World/CPathFindSearch.hpp"
#include "Runtime/World/CPatterned.hpp"
namespace urde {
class CCollisionActorManager;
namespace MP1 {
class CMetroidPrimeEssence : public CPatterned {
TCachedToken<CGenDescription> x568_;
CPathFindSearch x574_searchPath;
std::unique_ptr<CCollisionActorManager> x658_collisionManager;
std::unique_ptr<CElementGen> x65c_;
CAssetId x660_;
CAssetId x664_;
zeus::CTransform x668_;
CDamageInfo x698_;
zeus::CVector3f x6b4_;
float x6c0_ = 0.f;
float x6c4_ = 0.f;
float x6c8_ = 0.f;
float x6cc_ = 4.f;
float x6d0_ = 0.9f * x6cc_ + x6cc_;
float x6d4_ = 0.f;
u32 x6d8_ = 0;
u32 x6dc_ = 0;
u32 x6e0_ = x6dc_;
u32 x6e4_ = 0;
u32 x6e8_ = 2;
u32 x6ec_ = 4;
u32 x6f0_ = 0;
u32 x6f4_ = x6e8_ - 1;
u32 x6f8_ = 2;
u32 x6fc_ = 0;
u32 x700_ = 1;
TUniqueId x704_ = kInvalidUniqueId;
TUniqueId x706_lockOnTargetCollider = kInvalidUniqueId;
CSfxHandle x708_;
s16 x70c_;
bool x70e_24_ : 1 = false;
bool x70e_25_ : 1 = true;
bool x70e_26_ : 1 = false;
bool x70e_27_ : 1 = false;
bool x70e_28_ : 1 = true;
bool x70e_29_ : 1 = false;
bool x70e_30_ : 1 = false;
bool x70e_31_ : 1 = false;
void sub8027cb40(const zeus::CVector3f& vec);
void sub8027cce0(CStateManager& mgr);
zeus::CTransform GetTargetTransform(CStateManager& mgr);
void sub8027ce5c(float f1);
void sub8027cee0(CStateManager& mgr);
u32 sub8027cfd4(CStateManager& mgr, u32 w1);
void DoPhaseTransition(CStateManager& mgr);
u32 sub8027d428() { return 2; /* Decided by fair dice roll, guaranteed to be random */}
void ShakeCamera(CStateManager& mgr, float f1);
void sub8027d52c(CStateManager& mgr, const SShockWaveData& shockWaveData);
CRayCastResult sub8027d704(CStateManager& mgr);
void sub8027d790(CStateManager& mgr, bool active);
void sub8027d824(CStateManager& mgr);
bool sub8027e870(const zeus::CTransform& xf, CStateManager& mgr);
void sub8027ee88(CStateManager& mgr);
void CountListeningAi(CStateManager& mgr);
void UpdatePhase(float dt, CStateManager& mgr);
void UpdateHealth(CStateManager& mgr);
void SetLockOnTargetHealthAndDamageVulns(CStateManager& mgr);
void AddSphereCollisions(SSphereJointInfo* info, size_t count, std::vector<CJointCollisionDescription>& vecOut);
void SetupCollisionActorManager(CStateManager& mgr);
public:
DEFINE_PATTERNED(MetroidPrimeEssence);
CMetroidPrimeEssence(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,
CModelData&& mData, const CPatternedInfo& pInfo, const CActorParameters& actParms,
CAssetId particle1, const CDamageInfo& dInfo, float f1, CAssetId electric, u32 w1,
CAssetId particle2);
void Think(float dt, CStateManager& mgr) override;
void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId other, CStateManager& mgr) override;
void PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) override;
void AddToRenderer(const zeus::CFrustum& frustum, CStateManager& mgr) override;
void Render(CStateManager& mgr) override;
zeus::CVector3f GetAimPosition(const CStateManager& mgr, float dt) const override;
void DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) override;
void Death(CStateManager& mgr, const zeus::CVector3f& direction, EScriptObjectState state) override;
void Dead(CStateManager& mgr, EStateMsg msg, float dt) override;
void PathFind(CStateManager& mgr, EStateMsg msg, float dt) override;
void Halt(CStateManager& mgr, EStateMsg msg, float dt) override;
void Generate(CStateManager& mgr, EStateMsg msg, float dt) override;
void JumpBack(CStateManager& mgr, EStateMsg msg, float dt) override;
void Skid(CStateManager& mgr, EStateMsg msg, float dt) override;
void FadeIn(CStateManager& mgr, EStateMsg msg, float dt) override;
void FadeOut(CStateManager& mgr, EStateMsg msg, float dt) override;
void Taunt(CStateManager& mgr, EStateMsg msg, float dt) override;
void TelegraphAttack(CStateManager& mgr, EStateMsg msg, float dt) override;
void Dodge(CStateManager& mgr, EStateMsg msg, float dt) override;
void PathFindEx(CStateManager& mgr, EStateMsg msg, float dt) override;
bool HasPatrolPath(CStateManager& mgr, float dt) override;
bool ShouldAttack(CStateManager& mgr, float dt) override;
bool InPosition(CStateManager& mgr, float dt) override;
bool CoverFind(CStateManager& mgr, float dt) override;
bool ShouldTaunt(CStateManager& mgr, float dt) override;
bool ShouldCrouch(CStateManager& mgr, float dt) override;
bool ShouldMove(CStateManager& mgr, float dt) override;
CPathFindSearch* GetSearchPath() override;
};
} // namespace MP1
} // namespace urde<|endoftext|> |
<commit_before>// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#include "opentelemetry/exporters/otlp/otlp_recordable_utils.h"
#include "opentelemetry/exporters/otlp/protobuf_include_prefix.h"
#include "opentelemetry/proto/logs/v1/logs.pb.h"
#include "opentelemetry/proto/trace/v1/trace.pb.h"
#include "opentelemetry/exporters/otlp/protobuf_include_suffix.h"
#include "opentelemetry/exporters/otlp/otlp_log_recordable.h"
#include "opentelemetry/exporters/otlp/otlp_recordable.h"
namespace nostd = opentelemetry::nostd;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace otlp
{
//
// See `attribute_value.h` for details.
//
const int kAttributeValueSize = 16;
const int kOwnedAttributeValueSize = 15;
void OtlpRecordableUtils::PopulateAttribute(
opentelemetry::proto::common::v1::KeyValue *attribute,
nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept
{
if (nullptr == attribute)
{
return;
}
// Assert size of variant to ensure that this method gets updated if the variant
// definition changes
static_assert(
nostd::variant_size<opentelemetry::common::AttributeValue>::value == kAttributeValueSize,
"AttributeValue contains unknown type");
attribute->set_key(key.data(), key.size());
if (nostd::holds_alternative<bool>(value))
{
attribute->mutable_value()->set_bool_value(nostd::get<bool>(value));
}
else if (nostd::holds_alternative<int>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int>(value));
}
else if (nostd::holds_alternative<int64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int64_t>(value));
}
else if (nostd::holds_alternative<unsigned int>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<unsigned int>(value));
}
else if (nostd::holds_alternative<uint64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<uint64_t>(value));
}
else if (nostd::holds_alternative<double>(value))
{
attribute->mutable_value()->set_double_value(nostd::get<double>(value));
}
else if (nostd::holds_alternative<const char *>(value))
{
attribute->mutable_value()->set_string_value(nostd::get<const char *>(value));
}
else if (nostd::holds_alternative<nostd::string_view>(value))
{
attribute->mutable_value()->set_string_value(nostd::get<nostd::string_view>(value).data(),
nostd::get<nostd::string_view>(value).size());
}
else if (nostd::holds_alternative<nostd::span<const uint8_t>>(value))
{
for (const auto &val : nostd::get<nostd::span<const uint8_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const bool>>(value))
{
for (const auto &val : nostd::get<nostd::span<const bool>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_bool_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const int>>(value))
{
for (const auto &val : nostd::get<nostd::span<const int>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const int64_t>>(value))
{
for (const auto &val : nostd::get<nostd::span<const int64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const unsigned int>>(value))
{
for (const auto &val : nostd::get<nostd::span<const unsigned int>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const uint64_t>>(value))
{
for (const auto &val : nostd::get<nostd::span<const uint64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const double>>(value))
{
for (const auto &val : nostd::get<nostd::span<const double>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_double_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const nostd::string_view>>(value))
{
for (const auto &val : nostd::get<nostd::span<const nostd::string_view>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_string_value(val.data(),
val.size());
}
}
}
/** Maps from C++ attribute into OTLP proto attribute. */
void OtlpRecordableUtils::PopulateAttribute(
opentelemetry::proto::common::v1::KeyValue *attribute,
nostd::string_view key,
const opentelemetry::sdk::common::OwnedAttributeValue &value) noexcept
{
if (nullptr == attribute)
{
return;
}
// Assert size of variant to ensure that this method gets updated if the variant
// definition changes
static_assert(nostd::variant_size<opentelemetry::sdk::common::OwnedAttributeValue>::value ==
kOwnedAttributeValueSize,
"OwnedAttributeValue contains unknown type");
attribute->set_key(key.data(), key.size());
if (nostd::holds_alternative<bool>(value))
{
attribute->mutable_value()->set_bool_value(nostd::get<bool>(value));
}
else if (nostd::holds_alternative<int32_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int32_t>(value));
}
else if (nostd::holds_alternative<int64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int64_t>(value));
}
else if (nostd::holds_alternative<uint32_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<uint32_t>(value));
}
else if (nostd::holds_alternative<uint64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<uint64_t>(value));
}
else if (nostd::holds_alternative<double>(value))
{
attribute->mutable_value()->set_double_value(nostd::get<double>(value));
}
else if (nostd::holds_alternative<std::string>(value))
{
attribute->mutable_value()->set_string_value(nostd::get<std::string>(value));
}
else if (nostd::holds_alternative<std::vector<bool>>(value))
{
for (const auto &val : nostd::get<std::vector<bool>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_bool_value(val);
}
}
else if (nostd::holds_alternative<std::vector<int32_t>>(value))
{
for (const auto &val : nostd::get<std::vector<int32_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<uint32_t>>(value))
{
for (const auto &val : nostd::get<std::vector<uint32_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<int64_t>>(value))
{
for (const auto &val : nostd::get<std::vector<int64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<uint64_t>>(value))
{
for (const auto &val : nostd::get<std::vector<uint64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<double>>(value))
{
for (const auto &val : nostd::get<std::vector<double>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_double_value(val);
}
}
else if (nostd::holds_alternative<std::vector<std::string>>(value))
{
for (const auto &val : nostd::get<std::vector<std::string>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_string_value(val);
}
}
}
void OtlpRecordableUtils::PopulateAttribute(
opentelemetry::proto::resource::v1::Resource *proto,
const opentelemetry::sdk::resource::Resource &resource) noexcept
{
if (nullptr == proto)
{
return;
}
for (const auto &kv : resource.GetAttributes())
{
OtlpRecordableUtils::PopulateAttribute(proto->add_attributes(), kv.first, kv.second);
}
}
void OtlpRecordableUtils::PopulateRequest(
const nostd::span<std::unique_ptr<opentelemetry::sdk::trace::Recordable>> &spans,
proto::collector::trace::v1::ExportTraceServiceRequest *request) noexcept
{
if (nullptr == request)
{
return;
}
auto resource_span = request->add_resource_spans();
auto instrumentation_lib = resource_span->add_instrumentation_library_spans();
bool first_pass = true;
for (auto &recordable : spans)
{
auto rec = std::unique_ptr<OtlpRecordable>(static_cast<OtlpRecordable *>(recordable.release()));
*instrumentation_lib->add_spans() = std::move(rec->span());
*instrumentation_lib->mutable_instrumentation_library() = rec->GetProtoInstrumentationLibrary();
if (first_pass)
{
instrumentation_lib->set_schema_url(rec->GetInstrumentationLibrarySchemaURL());
*resource_span->mutable_resource() = rec->ProtoResource();
resource_span->set_schema_url(rec->GetResourceSchemaURL());
first_pass = false;
}
}
}
#ifdef ENABLE_LOGS_PREVIEW
void OtlpRecordableUtils::PopulateRequest(
const nostd::span<std::unique_ptr<opentelemetry::sdk::logs::Recordable>> &logs,
proto::collector::logs::v1::ExportLogsServiceRequest *request) noexcept
{
if (nullptr == request)
{
return;
}
for (auto &recordable : logs)
{
auto resource_logs = request->add_resource_logs();
auto instrumentation_lib = resource_logs->add_instrumentation_library_logs();
auto rec =
std::unique_ptr<OtlpLogRecordable>(static_cast<OtlpLogRecordable *>(recordable.release()));
// TODO schema url
*resource_logs->mutable_resource() = rec->ProtoResource();
// TODO schema url
// resource_logs->set_schema_url(rec->GetResourceSchemaURL());
*instrumentation_lib->add_logs() = std::move(rec->log_record());
// TODO instrumentation_library
// *instrumentation_lib->mutable_instrumentation_library() =
// rec->GetProtoInstrumentationLibrary();
// TODO schema data
// instrumentation_lib->set_schema_url(rec->GetInstrumentationLibrarySchemaURL());
}
}
#endif
} // namespace otlp
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE
<commit_msg>Fix sharing resource in batched exported spans (#1386)<commit_after>// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#include "opentelemetry/exporters/otlp/otlp_recordable_utils.h"
#include "opentelemetry/exporters/otlp/protobuf_include_prefix.h"
#include "opentelemetry/proto/logs/v1/logs.pb.h"
#include "opentelemetry/proto/trace/v1/trace.pb.h"
#include "opentelemetry/exporters/otlp/protobuf_include_suffix.h"
#include "opentelemetry/exporters/otlp/otlp_log_recordable.h"
#include "opentelemetry/exporters/otlp/otlp_recordable.h"
namespace nostd = opentelemetry::nostd;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace otlp
{
//
// See `attribute_value.h` for details.
//
const int kAttributeValueSize = 16;
const int kOwnedAttributeValueSize = 15;
void OtlpRecordableUtils::PopulateAttribute(
opentelemetry::proto::common::v1::KeyValue *attribute,
nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept
{
if (nullptr == attribute)
{
return;
}
// Assert size of variant to ensure that this method gets updated if the variant
// definition changes
static_assert(
nostd::variant_size<opentelemetry::common::AttributeValue>::value == kAttributeValueSize,
"AttributeValue contains unknown type");
attribute->set_key(key.data(), key.size());
if (nostd::holds_alternative<bool>(value))
{
attribute->mutable_value()->set_bool_value(nostd::get<bool>(value));
}
else if (nostd::holds_alternative<int>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int>(value));
}
else if (nostd::holds_alternative<int64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int64_t>(value));
}
else if (nostd::holds_alternative<unsigned int>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<unsigned int>(value));
}
else if (nostd::holds_alternative<uint64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<uint64_t>(value));
}
else if (nostd::holds_alternative<double>(value))
{
attribute->mutable_value()->set_double_value(nostd::get<double>(value));
}
else if (nostd::holds_alternative<const char *>(value))
{
attribute->mutable_value()->set_string_value(nostd::get<const char *>(value));
}
else if (nostd::holds_alternative<nostd::string_view>(value))
{
attribute->mutable_value()->set_string_value(nostd::get<nostd::string_view>(value).data(),
nostd::get<nostd::string_view>(value).size());
}
else if (nostd::holds_alternative<nostd::span<const uint8_t>>(value))
{
for (const auto &val : nostd::get<nostd::span<const uint8_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const bool>>(value))
{
for (const auto &val : nostd::get<nostd::span<const bool>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_bool_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const int>>(value))
{
for (const auto &val : nostd::get<nostd::span<const int>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const int64_t>>(value))
{
for (const auto &val : nostd::get<nostd::span<const int64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const unsigned int>>(value))
{
for (const auto &val : nostd::get<nostd::span<const unsigned int>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const uint64_t>>(value))
{
for (const auto &val : nostd::get<nostd::span<const uint64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const double>>(value))
{
for (const auto &val : nostd::get<nostd::span<const double>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_double_value(val);
}
}
else if (nostd::holds_alternative<nostd::span<const nostd::string_view>>(value))
{
for (const auto &val : nostd::get<nostd::span<const nostd::string_view>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_string_value(val.data(),
val.size());
}
}
}
/** Maps from C++ attribute into OTLP proto attribute. */
void OtlpRecordableUtils::PopulateAttribute(
opentelemetry::proto::common::v1::KeyValue *attribute,
nostd::string_view key,
const opentelemetry::sdk::common::OwnedAttributeValue &value) noexcept
{
if (nullptr == attribute)
{
return;
}
// Assert size of variant to ensure that this method gets updated if the variant
// definition changes
static_assert(nostd::variant_size<opentelemetry::sdk::common::OwnedAttributeValue>::value ==
kOwnedAttributeValueSize,
"OwnedAttributeValue contains unknown type");
attribute->set_key(key.data(), key.size());
if (nostd::holds_alternative<bool>(value))
{
attribute->mutable_value()->set_bool_value(nostd::get<bool>(value));
}
else if (nostd::holds_alternative<int32_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int32_t>(value));
}
else if (nostd::holds_alternative<int64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<int64_t>(value));
}
else if (nostd::holds_alternative<uint32_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<uint32_t>(value));
}
else if (nostd::holds_alternative<uint64_t>(value))
{
attribute->mutable_value()->set_int_value(nostd::get<uint64_t>(value));
}
else if (nostd::holds_alternative<double>(value))
{
attribute->mutable_value()->set_double_value(nostd::get<double>(value));
}
else if (nostd::holds_alternative<std::string>(value))
{
attribute->mutable_value()->set_string_value(nostd::get<std::string>(value));
}
else if (nostd::holds_alternative<std::vector<bool>>(value))
{
for (const auto &val : nostd::get<std::vector<bool>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_bool_value(val);
}
}
else if (nostd::holds_alternative<std::vector<int32_t>>(value))
{
for (const auto &val : nostd::get<std::vector<int32_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<uint32_t>>(value))
{
for (const auto &val : nostd::get<std::vector<uint32_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<int64_t>>(value))
{
for (const auto &val : nostd::get<std::vector<int64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<uint64_t>>(value))
{
for (const auto &val : nostd::get<std::vector<uint64_t>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_int_value(val);
}
}
else if (nostd::holds_alternative<std::vector<double>>(value))
{
for (const auto &val : nostd::get<std::vector<double>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_double_value(val);
}
}
else if (nostd::holds_alternative<std::vector<std::string>>(value))
{
for (const auto &val : nostd::get<std::vector<std::string>>(value))
{
attribute->mutable_value()->mutable_array_value()->add_values()->set_string_value(val);
}
}
}
void OtlpRecordableUtils::PopulateAttribute(
opentelemetry::proto::resource::v1::Resource *proto,
const opentelemetry::sdk::resource::Resource &resource) noexcept
{
if (nullptr == proto)
{
return;
}
for (const auto &kv : resource.GetAttributes())
{
OtlpRecordableUtils::PopulateAttribute(proto->add_attributes(), kv.first, kv.second);
}
}
void OtlpRecordableUtils::PopulateRequest(
const nostd::span<std::unique_ptr<opentelemetry::sdk::trace::Recordable>> &spans,
proto::collector::trace::v1::ExportTraceServiceRequest *request) noexcept
{
if (nullptr == request)
{
return;
}
for (auto &recordable : spans)
{
auto rec = std::unique_ptr<OtlpRecordable>(static_cast<OtlpRecordable *>(recordable.release()));
auto resource_span = request->add_resource_spans();
auto instrumentation_lib = resource_span->add_instrumentation_library_spans();
*instrumentation_lib->add_spans() = std::move(rec->span());
*instrumentation_lib->mutable_instrumentation_library() = rec->GetProtoInstrumentationLibrary();
instrumentation_lib->set_schema_url(rec->GetInstrumentationLibrarySchemaURL());
*resource_span->mutable_resource() = rec->ProtoResource();
resource_span->set_schema_url(rec->GetResourceSchemaURL());
}
}
#ifdef ENABLE_LOGS_PREVIEW
void OtlpRecordableUtils::PopulateRequest(
const nostd::span<std::unique_ptr<opentelemetry::sdk::logs::Recordable>> &logs,
proto::collector::logs::v1::ExportLogsServiceRequest *request) noexcept
{
if (nullptr == request)
{
return;
}
for (auto &recordable : logs)
{
auto resource_logs = request->add_resource_logs();
auto instrumentation_lib = resource_logs->add_instrumentation_library_logs();
auto rec =
std::unique_ptr<OtlpLogRecordable>(static_cast<OtlpLogRecordable *>(recordable.release()));
// TODO schema url
*resource_logs->mutable_resource() = rec->ProtoResource();
// TODO schema url
// resource_logs->set_schema_url(rec->GetResourceSchemaURL());
*instrumentation_lib->add_logs() = std::move(rec->log_record());
// TODO instrumentation_library
// *instrumentation_lib->mutable_instrumentation_library() =
// rec->GetProtoInstrumentationLibrary();
// TODO schema data
// instrumentation_lib->set_schema_url(rec->GetInstrumentationLibrarySchemaURL());
}
}
#endif
} // namespace otlp
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "sessiondialog.h"
#include "session.h"
#include <QtGui/QInputDialog>
#include <QtGui/QValidator>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
namespace ProjectExplorer {
namespace Internal {
class SessionValidator : public QValidator
{
public:
SessionValidator(QObject *parent, QStringList sessions);
void fixup(QString & input) const;
QValidator::State validate(QString & input, int & pos) const;
private:
QStringList m_sessions;
};
SessionValidator::SessionValidator(QObject *parent, QStringList sessions)
: QValidator(parent), m_sessions(sessions)
{
}
QValidator::State SessionValidator::validate(QString &input, int &pos) const
{
Q_UNUSED(pos)
if (input.contains('/')
|| input.contains(':')
|| input.contains('\\')
|| input.contains('?')
|| input.contains('*'))
return QValidator::Invalid;
if (m_sessions.contains(input))
return QValidator::Intermediate;
else
return QValidator::Acceptable;
}
void SessionValidator::fixup(QString &input) const
{
int i = 2;
QString copy;
do {
copy = input + QString(" (%1)").arg(i);
++i;
} while (m_sessions.contains(copy));
input = copy;
}
class SessionNameInputDialog : public QDialog
{
Q_OBJECT
public:
SessionNameInputDialog(const QStringList &sessions, QWidget *parent = 0);
void setValue(const QString &value);
QString value() const;
private:
QLineEdit *m_newSessionLineEdit;
};
SessionNameInputDialog::SessionNameInputDialog(const QStringList &sessions, QWidget *parent)
: QDialog(parent)
{
QVBoxLayout *hlayout = new QVBoxLayout(this);
QLabel *label = new QLabel(tr("Enter the name of the session:"), this);
hlayout->addWidget(label);
m_newSessionLineEdit = new QLineEdit(this);
m_newSessionLineEdit->setValidator(new SessionValidator(this, sessions));
hlayout->addWidget(m_newSessionLineEdit);
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
hlayout->addWidget(buttons);
setLayout(hlayout);
}
void SessionNameInputDialog::setValue(const QString &value)
{
m_newSessionLineEdit->setText(value);
}
QString SessionNameInputDialog::value() const
{
return m_newSessionLineEdit->text();
}
SessionDialog::SessionDialog(SessionManager *sessionManager)
: m_sessionManager(sessionManager)
{
m_ui.setupUi(this);
connect(m_ui.btCreateNew, SIGNAL(clicked()),
this, SLOT(createNew()));
connect(m_ui.btClone, SIGNAL(clicked()),
this, SLOT(clone()));
connect(m_ui.btDelete, SIGNAL(clicked()),
this, SLOT(remove()));
connect(m_ui.btSwitch, SIGNAL(clicked()), this, SLOT(switchToSession()));
connect(m_ui.btRename, SIGNAL(clicked()), this, SLOT(rename()));
connect(m_ui.sessionList, SIGNAL(itemDoubleClicked (QListWidgetItem *)),
this, SLOT(switchToSession()));
connect(m_ui.sessionList, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)),
this, SLOT(updateActions()));
m_ui.whatsASessionLabel->setOpenExternalLinks(true);
addItems(true);
markItems();
}
void SessionDialog::setAutoLoadSession(bool check)
{
m_ui.autoLoadCheckBox->setChecked(check ? Qt::Checked : Qt::Unchecked);
}
bool SessionDialog::autoLoadSession() const
{
return m_ui.autoLoadCheckBox->checkState() == Qt::Checked;
}
void SessionDialog::addItems(bool setDefaultSession)
{
QStringList sessions = m_sessionManager->sessions();
foreach (const QString &session, sessions) {
m_ui.sessionList->addItem(session);
if (setDefaultSession && session == m_sessionManager->activeSession())
m_ui.sessionList->setCurrentRow(m_ui.sessionList->count() - 1);
}
}
void SessionDialog::markItems()
{
for(int i = 0; i < m_ui.sessionList->count(); ++i) {
QListWidgetItem *item = m_ui.sessionList->item(i);
QFont f = item->font();
QString session = item->data(Qt::DisplayRole).toString();
if (m_sessionManager->isDefaultSession(session))
f.setItalic(true);
else
f.setItalic(false);
if (m_sessionManager->activeSession() == session && !m_sessionManager->isDefaultVirgin())
f.setBold(true);
else
f.setBold(false);
item->setFont(f);
}
}
void SessionDialog::updateActions()
{
if (m_ui.sessionList->currentItem()) {
bool isDefault = (m_ui.sessionList->currentItem()->text() == QLatin1String("default"));
bool isActive = (m_ui.sessionList->currentItem()->text() == m_sessionManager->activeSession());
m_ui.btDelete->setEnabled(!isActive && !isDefault);
m_ui.btRename->setEnabled(!isDefault);
} else {
m_ui.btDelete->setEnabled(false);
m_ui.btRename->setEnabled(false);
m_ui.btClone->setEnabled(false);
m_ui.btSwitch->setEnabled(false);
}
}
void SessionDialog::createNew()
{
SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
newSessionInputDialog.setWindowTitle(tr("New session name"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
if (newSession.isEmpty() || m_sessionManager->sessions().contains(newSession))
return;
m_sessionManager->createSession(newSession);
m_ui.sessionList->clear();
QStringList sessions = m_sessionManager->sessions();
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
}
}
void SessionDialog::clone()
{
SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
newSessionInputDialog.setValue(m_ui.sessionList->currentItem()->text());
newSessionInputDialog.setWindowTitle(tr("New session name"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
if (m_sessionManager->cloneSession(m_ui.sessionList->currentItem()->text(), newSession)) {
m_ui.sessionList->clear();
QStringList sessions = m_sessionManager->sessions();
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
}
}
}
void SessionDialog::remove()
{
m_sessionManager->deleteSession(m_ui.sessionList->currentItem()->text());
m_ui.sessionList->clear();
addItems(false);
markItems();
}
void SessionDialog::rename()
{
SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
newSessionInputDialog.setValue(m_ui.sessionList->currentItem()->text());
newSessionInputDialog.setWindowTitle(tr("Rename session"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
m_sessionManager->renameSession(m_ui.sessionList->currentItem()->text(), newSessionInputDialog.value());
m_ui.sessionList->clear();
addItems(false);
markItems();
}
}
void SessionDialog::switchToSession()
{
QString session = m_ui.sessionList->currentItem()->text();
m_sessionManager->loadSession(session);
markItems();
updateActions();
}
} // namespace Internal
} // namespace ProjectExplorer
#include "sessiondialog.moc"
<commit_msg>Session manager: Enable clone/switch if there's an item currently selected.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "sessiondialog.h"
#include "session.h"
#include <QtGui/QInputDialog>
#include <QtGui/QValidator>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
namespace ProjectExplorer {
namespace Internal {
class SessionValidator : public QValidator
{
public:
SessionValidator(QObject *parent, QStringList sessions);
void fixup(QString & input) const;
QValidator::State validate(QString & input, int & pos) const;
private:
QStringList m_sessions;
};
SessionValidator::SessionValidator(QObject *parent, QStringList sessions)
: QValidator(parent), m_sessions(sessions)
{
}
QValidator::State SessionValidator::validate(QString &input, int &pos) const
{
Q_UNUSED(pos)
if (input.contains('/')
|| input.contains(':')
|| input.contains('\\')
|| input.contains('?')
|| input.contains('*'))
return QValidator::Invalid;
if (m_sessions.contains(input))
return QValidator::Intermediate;
else
return QValidator::Acceptable;
}
void SessionValidator::fixup(QString &input) const
{
int i = 2;
QString copy;
do {
copy = input + QString(" (%1)").arg(i);
++i;
} while (m_sessions.contains(copy));
input = copy;
}
class SessionNameInputDialog : public QDialog
{
Q_OBJECT
public:
SessionNameInputDialog(const QStringList &sessions, QWidget *parent = 0);
void setValue(const QString &value);
QString value() const;
private:
QLineEdit *m_newSessionLineEdit;
};
SessionNameInputDialog::SessionNameInputDialog(const QStringList &sessions, QWidget *parent)
: QDialog(parent)
{
QVBoxLayout *hlayout = new QVBoxLayout(this);
QLabel *label = new QLabel(tr("Enter the name of the session:"), this);
hlayout->addWidget(label);
m_newSessionLineEdit = new QLineEdit(this);
m_newSessionLineEdit->setValidator(new SessionValidator(this, sessions));
hlayout->addWidget(m_newSessionLineEdit);
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
hlayout->addWidget(buttons);
setLayout(hlayout);
}
void SessionNameInputDialog::setValue(const QString &value)
{
m_newSessionLineEdit->setText(value);
}
QString SessionNameInputDialog::value() const
{
return m_newSessionLineEdit->text();
}
SessionDialog::SessionDialog(SessionManager *sessionManager)
: m_sessionManager(sessionManager)
{
m_ui.setupUi(this);
connect(m_ui.btCreateNew, SIGNAL(clicked()),
this, SLOT(createNew()));
connect(m_ui.btClone, SIGNAL(clicked()),
this, SLOT(clone()));
connect(m_ui.btDelete, SIGNAL(clicked()),
this, SLOT(remove()));
connect(m_ui.btSwitch, SIGNAL(clicked()), this, SLOT(switchToSession()));
connect(m_ui.btRename, SIGNAL(clicked()), this, SLOT(rename()));
connect(m_ui.sessionList, SIGNAL(itemDoubleClicked (QListWidgetItem *)),
this, SLOT(switchToSession()));
connect(m_ui.sessionList, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)),
this, SLOT(updateActions()));
m_ui.whatsASessionLabel->setOpenExternalLinks(true);
addItems(true);
markItems();
}
void SessionDialog::setAutoLoadSession(bool check)
{
m_ui.autoLoadCheckBox->setChecked(check ? Qt::Checked : Qt::Unchecked);
}
bool SessionDialog::autoLoadSession() const
{
return m_ui.autoLoadCheckBox->checkState() == Qt::Checked;
}
void SessionDialog::addItems(bool setDefaultSession)
{
QStringList sessions = m_sessionManager->sessions();
foreach (const QString &session, sessions) {
m_ui.sessionList->addItem(session);
if (setDefaultSession && session == m_sessionManager->activeSession())
m_ui.sessionList->setCurrentRow(m_ui.sessionList->count() - 1);
}
}
void SessionDialog::markItems()
{
for(int i = 0; i < m_ui.sessionList->count(); ++i) {
QListWidgetItem *item = m_ui.sessionList->item(i);
QFont f = item->font();
QString session = item->data(Qt::DisplayRole).toString();
if (m_sessionManager->isDefaultSession(session))
f.setItalic(true);
else
f.setItalic(false);
if (m_sessionManager->activeSession() == session && !m_sessionManager->isDefaultVirgin())
f.setBold(true);
else
f.setBold(false);
item->setFont(f);
}
}
void SessionDialog::updateActions()
{
if (m_ui.sessionList->currentItem()) {
bool isDefault = (m_ui.sessionList->currentItem()->text() == QLatin1String("default"));
bool isActive = (m_ui.sessionList->currentItem()->text() == m_sessionManager->activeSession());
m_ui.btDelete->setEnabled(!isActive && !isDefault);
m_ui.btRename->setEnabled(!isDefault);
m_ui.btClone->setEnabled(true);
m_ui.btSwitch->setEnabled(true);
} else {
m_ui.btDelete->setEnabled(false);
m_ui.btRename->setEnabled(false);
m_ui.btClone->setEnabled(false);
m_ui.btSwitch->setEnabled(false);
}
}
void SessionDialog::createNew()
{
SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
newSessionInputDialog.setWindowTitle(tr("New session name"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
if (newSession.isEmpty() || m_sessionManager->sessions().contains(newSession))
return;
m_sessionManager->createSession(newSession);
m_ui.sessionList->clear();
QStringList sessions = m_sessionManager->sessions();
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
}
}
void SessionDialog::clone()
{
SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
newSessionInputDialog.setValue(m_ui.sessionList->currentItem()->text());
newSessionInputDialog.setWindowTitle(tr("New session name"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
if (m_sessionManager->cloneSession(m_ui.sessionList->currentItem()->text(), newSession)) {
m_ui.sessionList->clear();
QStringList sessions = m_sessionManager->sessions();
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
}
}
}
void SessionDialog::remove()
{
m_sessionManager->deleteSession(m_ui.sessionList->currentItem()->text());
m_ui.sessionList->clear();
addItems(false);
markItems();
}
void SessionDialog::rename()
{
SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
newSessionInputDialog.setValue(m_ui.sessionList->currentItem()->text());
newSessionInputDialog.setWindowTitle(tr("Rename session"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
m_sessionManager->renameSession(m_ui.sessionList->currentItem()->text(), newSessionInputDialog.value());
m_ui.sessionList->clear();
addItems(false);
markItems();
}
}
void SessionDialog::switchToSession()
{
QString session = m_ui.sessionList->currentItem()->text();
m_sessionManager->loadSession(session);
markItems();
updateActions();
}
} // namespace Internal
} // namespace ProjectExplorer
#include "sessiondialog.moc"
<|endoftext|> |
<commit_before>#include "vigra/hdf5impex.hxx"
using namespace vigra;
HDF5ImportInfo::HDF5ImportInfo(const std::string &filename, const std::string &datasetname)
{
try {
/*
* Turn off the auto-printing when failure occurs so that we can
* handle the errors appropriately
*/
Exception::dontPrint();
m_file = H5File( filename, H5F_ACC_RDONLY );
DataSet dset = m_file.openDataSet(datasetname);
m_filename = filename;
m_datasetname = datasetname;
m_dimensions = dset.getSpace().getSimpleExtentNdims();
m_dataset = dset;
vigra_precondition( m_dimensions>=2, "Number of dimensions is lower than 2. Not an image!" );
if(dset.getTypeClass()==GetH5DataType<float>().getClass())
m_pixeltype = "FLOAT";
if(dset.getTypeClass()==GetH5DataType<UInt8>().getClass())
m_pixeltype = "UINT8";
if(dset.getTypeClass()==GetH5DataType<Int8>().getClass())
m_pixeltype = "INT8";
if(dset.getTypeClass()==GetH5DataType<UInt16>().getClass())
m_pixeltype = "UINT16";
if(dset.getTypeClass()==GetH5DataType<Int16>().getClass())
m_pixeltype = "INT16";
if(dset.getTypeClass()==GetH5DataType<UInt32>().getClass())
m_pixeltype = "UINT32";
if(dset.getTypeClass()==GetH5DataType<Int32>().getClass())
m_pixeltype = "INT32";
if(dset.getTypeClass()==GetH5DataType<double>().getClass())
m_pixeltype = "DOUBLE";
m_dims = ArrayVector<int>(m_dimensions);
hsize_t* size = new hsize_t[m_dimensions];
dset.getSpace().getSimpleExtentDims(size, NULL);
for(int i=0; i<m_dimensions; ++i)
m_dims[i] = size[i];
delete size;
}
catch( GroupIException not_found_error )
{
vigra_precondition( false, "Dataset not found in HDF5 file." );
}
}
HDF5ImportInfo::~HDF5ImportInfo()
{
}
HDF5ImportInfo::PixelType HDF5ImportInfo::pixelType() const
{
const std::string pixeltype=HDF5ImportInfo::getPixelType();
if (pixeltype == "UINT8")
return HDF5ImportInfo::UINT8;
if (pixeltype == "INT16")
return HDF5ImportInfo::INT16;
if (pixeltype == "UINT16")
return HDF5ImportInfo::UINT16;
if (pixeltype == "INT32")
return HDF5ImportInfo::INT32;
if (pixeltype == "UINT32")
return HDF5ImportInfo::UINT32;
if (pixeltype == "FLOAT")
return HDF5ImportInfo::FLOAT;
if (pixeltype == "DOUBLE")
return HDF5ImportInfo::DOUBLE;
vigra_fail( "internal error: unknown pixel type" );
return HDF5ImportInfo::PixelType();
}
const char * HDF5ImportInfo::getPixelType() const
{
return m_pixeltype.c_str();
}
MultiArrayIndex HDF5ImportInfo::shapeOfDimension(const int dim) const { return m_dims[dim]; };
MultiArrayIndex HDF5ImportInfo::numDimensions() const { return m_dimensions; }
const std::string & HDF5ImportInfo::getDatasetName() const { return m_datasetname; }
const std::string & HDF5ImportInfo::getFileName() const { return m_filename; }
const H5File& HDF5ImportInfo::getH5FileHandle() const { return m_file; }
const DataSet& HDF5ImportInfo::getDatasetHandle() const { return m_dataset; }
int main (void)
{
/*
* Try block to detect exceptions raised by any of the calls inside it
*/
try
{
/*
* Turn off the auto-printing when failure occurs so that we can
* handle the errors appropriately
*/
//Exception::dontPrint();
/*
* Create a file if it does not exist and open for reading/writing
*/
H5File out_file( "Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", H5F_ACC_TRUNC );
/*
* Create property list for a dataset and set up fill values.
*/
int fillvalue = 0; /* Fill value for the dataset */
DSetCreatPropList plist;
plist.setFillValue(PredType::NATIVE_INT, &fillvalue);
/*
* Create some data and write it to the file
*/
MultiArray<3,double> out_data1(MultiArrayShape<3>::type(200, 100, 3));
out_data1.init(5);
bool b1 = writeToHDF5File(out_file, "my_data", out_data1);
MultiArray<4,int> out_data2(MultiArrayShape<4>::type(500, 300, 5, 6));
out_data2.init(3);
bool b2 = writeToHDF5File(out_file, "/group/subgroup/my_data2", out_data2, "in subgroup");
ImageImportInfo info("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\giraffe.jpg");
MultiArray<2,int> out_data3(MultiArrayShape<2>::type(info.width(), info.height()));
importImage(info, destImage(out_data3));
bool b3 = writeToHDF5File(out_file, "giraffe", out_data3);
std::cout<<"Writing(old)... Success="<<b1*b2*b3<<std::endl;
out_file.close();
H5File out_file2( "Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile2.hdf5", H5F_ACC_RDWR );
bool b4 = writeToHDF5File(out_file2, "giraffe3", out_data3);
std::cout<<"Reading (new)... Success="<<b4<<std::endl;
out_file2.close();
/*
* Read the data
*/
H5File in_file("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", H5F_ACC_RDONLY );
H5std_string comment;
MultiArray<3,double> in_data1;
bool b5 = loadFromHDF5File(in_file, "my_data", in_data1, comment);
std::cout<<"Size set 1: "<<in_data1.shape()<<std::endl;
std::cout<<comment<<std::endl;
MultiArray<4,int> in_data2;
bool b6 = loadFromHDF5File(in_file, "/group/subgroup/my_data2", in_data2, comment);
std::cout<<"Size set 2: "<<in_data2.shape()<<std::endl;
std::cout<<comment<<std::endl;
MultiArray<2,int> in_data3;
bool b7 = loadFromHDF5File(in_file, "giraffe", in_data3, comment);
std::cout<<"Size set 3: "<<in_data3.shape()<<std::endl;
std::cout<<comment<<std::endl;
std::cout<<"Reading (old)... Success="<<b5*b6*b7<<std::endl;
HDF5ImportInfo infoHDF5("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", "giraffe");
MultiArray<2,int> in_data4(MultiArrayShape<2>::type(infoHDF5.shapeOfDimension(0), infoHDF5.shapeOfDimension(1)));
bool b8 = loadFromHDF5File(infoHDF5, in_data4);
std::cout<<"Size set 4: "<<in_data4.shape()<<std::endl;
std::cout<<"Reading (new)... Success="<<b8<<std::endl;
in_file.close();
ImageExportInfo info2("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\giraffentest.jpg");
exportImage(srcImageRange(in_data3), info2);
} // end of try block
// catch failure caused by the H5File operations
catch( FileIException error )
{
error.printError();
return -1;
}
// catch failure caused by the DataSet operations
catch( DataSetIException error )
{
error.printError();
return -1;
}
// catch failure caused by the DataSpace operations
catch( DataSpaceIException error )
{
error.printError();
return -1;
}
return 0;
}
<commit_msg>export/import volume to HDF5<commit_after>#include "vigra/hdf5impex.hxx"
#include "vigra/numpy_array.hxx"
#include "vigra/numpy_array_converters.hxx"
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace vigra;
HDF5ImportInfo::HDF5ImportInfo(const std::string &filename, const std::string &datasetname)
{
try {
/*
* Turn off the auto-printing when failure occurs so that we can
* handle the errors appropriately
*/
Exception::dontPrint();
m_file = H5File( filename, H5F_ACC_RDONLY );
DataSet dset = m_file.openDataSet(datasetname);
m_filename = filename;
m_datasetname = datasetname;
m_dimensions = dset.getSpace().getSimpleExtentNdims();
m_dataset = dset;
vigra_precondition( m_dimensions>=2, "Number of dimensions is lower than 2. Not an image!" );
if(dset.getTypeClass()==GetH5DataType<float>().getClass())
m_pixeltype = "FLOAT";
if(dset.getTypeClass()==GetH5DataType<UInt8>().getClass())
m_pixeltype = "UINT8";
if(dset.getTypeClass()==GetH5DataType<Int8>().getClass())
m_pixeltype = "INT8";
if(dset.getTypeClass()==GetH5DataType<UInt16>().getClass())
m_pixeltype = "UINT16";
if(dset.getTypeClass()==GetH5DataType<Int16>().getClass())
m_pixeltype = "INT16";
if(dset.getTypeClass()==GetH5DataType<UInt32>().getClass())
m_pixeltype = "UINT32";
if(dset.getTypeClass()==GetH5DataType<Int32>().getClass())
m_pixeltype = "INT32";
if(dset.getTypeClass()==GetH5DataType<double>().getClass())
m_pixeltype = "DOUBLE";
m_dims = ArrayVector<int>(m_dimensions);
hsize_t* size = new hsize_t[m_dimensions];
dset.getSpace().getSimpleExtentDims(size, NULL);
for(int i=0; i<m_dimensions; ++i)
m_dims[i] = size[i];
delete size;
}
catch( GroupIException not_found_error )
{
vigra_precondition( false, "Dataset not found in HDF5 file." );
}
}
HDF5ImportInfo::~HDF5ImportInfo()
{
}
HDF5ImportInfo::PixelType HDF5ImportInfo::pixelType() const
{
const std::string pixeltype=HDF5ImportInfo::getPixelType();
if (pixeltype == "UINT8")
return HDF5ImportInfo::UINT8;
if (pixeltype == "INT16")
return HDF5ImportInfo::INT16;
if (pixeltype == "UINT16")
return HDF5ImportInfo::UINT16;
if (pixeltype == "INT32")
return HDF5ImportInfo::INT32;
if (pixeltype == "UINT32")
return HDF5ImportInfo::UINT32;
if (pixeltype == "FLOAT")
return HDF5ImportInfo::FLOAT;
if (pixeltype == "DOUBLE")
return HDF5ImportInfo::DOUBLE;
vigra_fail( "internal error: unknown pixel type" );
return HDF5ImportInfo::PixelType();
}
const char * HDF5ImportInfo::getPixelType() const
{
return m_pixeltype.c_str();
}
MultiArrayIndex HDF5ImportInfo::shapeOfDimension(const int dim) const { return m_dims[dim]; };
MultiArrayIndex HDF5ImportInfo::numDimensions() const { return m_dimensions; }
const std::string & HDF5ImportInfo::getDatasetName() const { return m_datasetname; }
const std::string & HDF5ImportInfo::getFileName() const { return m_filename; }
const H5File& HDF5ImportInfo::getH5FileHandle() const { return m_file; }
const DataSet& HDF5ImportInfo::getDatasetHandle() const { return m_dataset; }
int main (void)
{
/*
* Try block to detect exceptions raised by any of the calls inside it
*/
try
{
/*
* Turn off the auto-printing when failure occurs so that we can
* handle the errors appropriately
*/
//Exception::dontPrint();
/*
* Create a file if it does not exist and open for reading/writing
*/
H5File out_file( "Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", H5F_ACC_TRUNC );
/*
* Create property list for a dataset and set up fill values.
*/
int fillvalue = 0; /* Fill value for the dataset */
DSetCreatPropList plist;
plist.setFillValue(PredType::NATIVE_INT, &fillvalue);
/*
* Create some data and write it to the file
*/
MultiArray<3,double> out_data1(MultiArrayShape<3>::type(200, 100, 3));
out_data1.init(5);
bool b1 = writeToHDF5File(out_file, "my_data", out_data1);
MultiArray<4,int> out_data2(MultiArrayShape<4>::type(500, 300, 5, 6));
out_data2.init(3);
bool b2 = writeToHDF5File(out_file, "/group/subgroup/my_data2", out_data2, "in subgroup");
ImageImportInfo info("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\giraffe.jpg");
MultiArray<2,int> out_data3(MultiArrayShape<2>::type(info.width(), info.height()));
importImage(info, destImage(out_data3));
bool b3 = writeToHDF5File(out_file, "giraffe", out_data3);
std::cout<<"Writing(old)... Success="<<b1*b2*b3<<std::endl;
out_file.close();
H5File out_file2( "Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", H5F_ACC_RDWR );
bool b4 = writeToHDF5File(out_file2, "giraffe3", out_data3);
std::cout<<"Writing(new)... Success="<<b4<<std::endl;
out_file2.close();
/*
* Read the data
*/
H5File in_file("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", H5F_ACC_RDONLY );
H5std_string comment;
MultiArray<3,double> in_data1;
bool b5 = loadFromHDF5File(in_file, "my_data", in_data1, comment);
std::cout<<"Size set 1: "<<in_data1.shape()<<std::endl;
std::cout<<comment<<std::endl;
MultiArray<4,int> in_data2;
bool b6 = loadFromHDF5File(in_file, "/group/subgroup/my_data2", in_data2, comment);
std::cout<<"Size set 2: "<<in_data2.shape()<<std::endl;
std::cout<<comment<<std::endl;
MultiArray<2,int> in_data3;
bool b7 = loadFromHDF5File(in_file, "giraffe", in_data3, comment);
std::cout<<"Size set 3: "<<in_data3.shape()<<std::endl;
std::cout<<comment<<std::endl;
std::cout<<"Reading(old)... Success="<<b5*b6*b7<<std::endl;
in_file.close();
HDF5ImportInfo infoHDF5("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", "giraffe");
MultiArray<2,int> in_data4(MultiArrayShape<2>::type(infoHDF5.shapeOfDimension(0), infoHDF5.shapeOfDimension(1)));
bool b8 = loadFromHDF5File(infoHDF5, in_data4);
std::cout<<"Size set 4: "<<in_data4.shape()<<std::endl;
std::cout<<"Reading(new1)... Success="<<b8<<std::endl;
/*
HDF5ImportInfo infoHDF5b("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\testfile.hdf5", "my_data");
std::cout<<"test1"<<std::endl;
MultiArray<2, RGBValue<double> > in_data5(MultiArrayShape<2>::type(infoHDF5b.shapeOfDimension(0), infoHDF5b.shapeOfDimension(1)));
std::cout<<"test2"<<std::endl;
bool b9 = loadFromHDF5File(infoHDF5b, in_data5);
std::cout<<"Size set 5: "<<in_data5.shape()<<std::endl;
std::cout<<"Reading(new2)... Success="<<b9<<std::endl;
*/
ImageExportInfo info2("Z:\\Ilastik\\vigranumpy\\vigranumpy.new\\src\\giraffentest.jpg");
exportImage(srcImageRange(in_data3), info2);
} // end of try block
// catch failure caused by the H5File operations
catch( FileIException error )
{
error.printError();
return -1;
}
// catch failure caused by the DataSet operations
catch( DataSetIException error )
{
error.printError();
return -1;
}
// catch failure caused by the DataSpace operations
catch( DataSpaceIException error )
{
error.printError();
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "rfr359f.h"
using namespace upm;
using namespace std;
RFR359F::RFR359F(int pin)
{
if ( !(m_gpio = mraa_gpio_init(pin)) )
{
cerr << __FUNCTION__ << ": mraa_gpio_init() failed" << endl;
return;
}
mraa_gpio_dir(m_gpio, MRAA_GPIO_IN);
}
RFR359F::~RFR359F()
{
mraa_gpio_close(m_gpio);
}
bool RFR359F::objectDetected()
{
return (!mraa_gpio_read(m_gpio) ? true : false);
}
<commit_msg>rfr359f: throw exception(s) on fatal errors<commit_after>/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <string>
#include <stdexcept>
#include "rfr359f.h"
using namespace upm;
using namespace std;
RFR359F::RFR359F(int pin)
{
if ( !(m_gpio = mraa_gpio_init(pin)) )
{
throw std::invalid_argument(std::string(__FUNCTION__) +
": mraa_gpio_init() failed, invalid pin?");
return;
}
mraa_gpio_dir(m_gpio, MRAA_GPIO_IN);
}
RFR359F::~RFR359F()
{
mraa_gpio_close(m_gpio);
}
bool RFR359F::objectDetected()
{
return (!mraa_gpio_read(m_gpio) ? true : false);
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: Sample_FirstWindow.cpp
created: 10/3/2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "Sample_FirstWindow.h"
#include "CEGUI/CEGUI.h"
/*************************************************************************
Sample specific initialisation goes here.
*************************************************************************/
bool FirstWindowSample::initialise()
{
using namespace CEGUI;
// CEGUI relies on various systems being set-up, so this is what we do
// here first.
//
// The first thing to do is load a CEGUI 'scheme' this is basically a file
// that groups all the required resources and definitions for a particular
// skin so they can be loaded / initialised easily
//
// So, we use the SchemeManager singleton to load in a scheme that loads the
// imagery and registers widgets for the TaharezLook skin. This scheme also
// loads in a font that gets used as the system default.
SchemeManager::getSingleton().createFromFile("TaharezLook.scheme");
// The next thing we do is to set a default mouse cursor image. This is
// not strictly essential, although it is nice to always have a visible
// cursor if a window or widget does not explicitly set one of its own.
//
// The TaharezLook Imageset contains an Image named "MouseArrow" which is
// the ideal thing to have as a defult mouse cursor image.
System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
// Now the system is initialised, we can actually create some UI elements, for
// this first example, a full-screen 'root' window is set as the active GUI
// sheet, and then a simple frame window will be created and attached to it.
// All windows and widgets are created via the WindowManager singleton.
WindowManager& winMgr = WindowManager::getSingleton();
// Here we create a "DeafultWindow". This is a native type, that is, it does
// not have to be loaded via a scheme, it is always available. One common use
// for the DefaultWindow is as a generic container for other windows. Its
// size defaults to 1.0f x 1.0f using the Relative metrics mode, which means
// when it is set as the root GUI sheet window, it will cover the entire display.
// The DefaultWindow does not perform any rendering of its own, so is invisible.
//
// Create a DefaultWindow called 'Root'.
DefaultWindow* root = (DefaultWindow*)winMgr.createWindow("DefaultWindow", "Root");
// set the GUI root window (also known as the GUI "sheet"), so the gui we set up
// will be visible.
System::getSingleton().getDefaultGUIContext().setRootWindow(root);
// A FrameWindow is a window with a frame and a titlebar which may be moved around
// and resized.
//
// Create a FrameWindow in the TaharezLook style, and name it 'Demo Window'
FrameWindow* wnd = (FrameWindow*)winMgr.createWindow("TaharezLook/FrameWindow", "Demo Window");
// Here we attach the newly created FrameWindow to the previously created
// DefaultWindow which we will be using as the root of the displayed gui.
root->addChild(wnd);
// Windows are in Relative metrics mode by default. This means that we can
// specify sizes and positions without having to know the exact pixel size
// of the elements in advance. The relative metrics mode co-ordinates are
// relative to the parent of the window where the co-ordinates are being set.
// This means that if 0.5f is specified as the width for a window, that window
// will be half as its parent window.
//
// Here we set the FrameWindow so that it is half the size of the display,
// and centered within the display.
wnd->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.25f)));
wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f)));
// now we set the maximum and minum sizes for the new window. These are
// specified using relative co-ordinates, but the important thing to note
// is that these settings are aways relative to the display rather than the
// parent window.
//
// here we set a maximum size for the FrameWindow which is equal to the size
// of the display, and a minimum size of one tenth of the display.
wnd->setMaxSize(USize(cegui_reldim(1.0f), cegui_reldim( 1.0f)));
wnd->setMinSize(USize(cegui_reldim(0.1f), cegui_reldim( 0.1f)));
// As a final step in the initialisation of our sample window, we set the window's
// text to "Hello World!", so that this text will appear as the caption in the
// FrameWindow's titlebar.
wnd->setText("Hello World!");
// return true so that the samples framework knows that initialisation was a
// success, and that it should now run the sample.
return true;
}
/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void FirstWindowSample::deinitialise()
{
// nothing to do here!
}
/*************************************************************************
Returns the sample layouts GUI root
*************************************************************************/
CEGUI::Window* FirstWindowSample::getGUIRoot()
{
// nothing to do here!
return 0;
}
extern "C" __declspec(dllexport) Sample* GetSample()
{
return new FirstWindowSample();
}<commit_msg>Added Macro for win32 dll export<commit_after>/***********************************************************************
filename: Sample_FirstWindow.cpp
created: 10/3/2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "Sample_FirstWindow.h"
#include "CEGUI/CEGUI.h"
#if (defined( __WIN32__ ) || defined( _WIN32 )) && !defined(CEGUI_STATIC)
# define SAMPLE_EXPORT __declspec(dllexport)
#else
# define SAMPLE_EXPORT
#endif
/*************************************************************************
Sample specific initialisation goes here.
*************************************************************************/
bool FirstWindowSample::initialise()
{
using namespace CEGUI;
// CEGUI relies on various systems being set-up, so this is what we do
// here first.
//
// The first thing to do is load a CEGUI 'scheme' this is basically a file
// that groups all the required resources and definitions for a particular
// skin so they can be loaded / initialised easily
//
// So, we use the SchemeManager singleton to load in a scheme that loads the
// imagery and registers widgets for the TaharezLook skin. This scheme also
// loads in a font that gets used as the system default.
SchemeManager::getSingleton().createFromFile("TaharezLook.scheme");
// The next thing we do is to set a default mouse cursor image. This is
// not strictly essential, although it is nice to always have a visible
// cursor if a window or widget does not explicitly set one of its own.
//
// The TaharezLook Imageset contains an Image named "MouseArrow" which is
// the ideal thing to have as a defult mouse cursor image.
System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
// Now the system is initialised, we can actually create some UI elements, for
// this first example, a full-screen 'root' window is set as the active GUI
// sheet, and then a simple frame window will be created and attached to it.
// All windows and widgets are created via the WindowManager singleton.
WindowManager& winMgr = WindowManager::getSingleton();
// Here we create a "DeafultWindow". This is a native type, that is, it does
// not have to be loaded via a scheme, it is always available. One common use
// for the DefaultWindow is as a generic container for other windows. Its
// size defaults to 1.0f x 1.0f using the Relative metrics mode, which means
// when it is set as the root GUI sheet window, it will cover the entire display.
// The DefaultWindow does not perform any rendering of its own, so is invisible.
//
// Create a DefaultWindow called 'Root'.
DefaultWindow* root = (DefaultWindow*)winMgr.createWindow("DefaultWindow", "Root");
// set the GUI root window (also known as the GUI "sheet"), so the gui we set up
// will be visible.
System::getSingleton().getDefaultGUIContext().setRootWindow(root);
// A FrameWindow is a window with a frame and a titlebar which may be moved around
// and resized.
//
// Create a FrameWindow in the TaharezLook style, and name it 'Demo Window'
FrameWindow* wnd = (FrameWindow*)winMgr.createWindow("TaharezLook/FrameWindow", "Demo Window");
// Here we attach the newly created FrameWindow to the previously created
// DefaultWindow which we will be using as the root of the displayed gui.
root->addChild(wnd);
// Windows are in Relative metrics mode by default. This means that we can
// specify sizes and positions without having to know the exact pixel size
// of the elements in advance. The relative metrics mode co-ordinates are
// relative to the parent of the window where the co-ordinates are being set.
// This means that if 0.5f is specified as the width for a window, that window
// will be half as its parent window.
//
// Here we set the FrameWindow so that it is half the size of the display,
// and centered within the display.
wnd->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.25f)));
wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f)));
// now we set the maximum and minum sizes for the new window. These are
// specified using relative co-ordinates, but the important thing to note
// is that these settings are aways relative to the display rather than the
// parent window.
//
// here we set a maximum size for the FrameWindow which is equal to the size
// of the display, and a minimum size of one tenth of the display.
wnd->setMaxSize(USize(cegui_reldim(1.0f), cegui_reldim( 1.0f)));
wnd->setMinSize(USize(cegui_reldim(0.1f), cegui_reldim( 0.1f)));
// As a final step in the initialisation of our sample window, we set the window's
// text to "Hello World!", so that this text will appear as the caption in the
// FrameWindow's titlebar.
wnd->setText("Hello World!");
// return true so that the samples framework knows that initialisation was a
// success, and that it should now run the sample.
return true;
}
/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void FirstWindowSample::deinitialise()
{
// nothing to do here!
}
/*************************************************************************
Returns the sample layouts GUI root
*************************************************************************/
CEGUI::Window* FirstWindowSample::getGUIRoot()
{
// nothing to do here!
return 0;
}
extern "C" SAMPLE_EXPORT Sample* GetSample()
{
return new FirstWindowSample();
}<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep20/call_host_load_payload.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <isteps/hwpisteperror.H>
#include <isteps/istep_reasoncodes.H>
#include <isteps/hwpf_reasoncodes.H>
#include <targeting/common/commontargeting.H>
#include <targeting/common/mfgFlagAccessors.H>
#include <targeting/targplatutil.H>
#include <initservice/istepdispatcherif.H>
#include <initservice/initserviceif.H>
#include <pnor/pnorif.H>
#include <util/misc.H>
#include <sys/mm.h>
#include <arch/ppc.H>
#include <kernel/console.H>
#include <xz/xz.h>
#include <util/utilmclmgr.H>
#include <runtime/runtime.H>
using namespace ERRORLOG;
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace TARGETING;
namespace ISTEP_20
{
/**
* @brief This function loads the pnor section in sapphire mode and
* and also decompresseses the section if it was compressed
*
* @param[in] i_section - Which section are we loading
* @param[in] i_physAddr - The physical address of the section
* @param[in] i_zeroLmb - Whether to zero the LMB into which the PNOR section is loaded
*
* @return errlHndl_t - NULL if successful, otherwise a pointer
* to the error log.
*/
static errlHndl_t load_pnor_section(PNOR::SectionId i_section,
uint64_t i_physAddr,
bool i_zeroLmb);
void* call_host_load_payload (void *io_pArgs)
{
errlHndl_t l_err = NULL;
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
ENTER_MRK"call_host_load_payload entry" );
do
{
TARGETING::Target* sys = UTIL::assertGetToplevelTarget();
if(INITSERVICE::spBaseServicesEnabled())
{
//this function is a NOOP on FSP system
break;
}
// Get Payload base/entry from attributes
uint64_t payloadBase = sys->getAttr<TARGETING::ATTR_PAYLOAD_BASE>();
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,INFO_MRK
"call_host_load_payload: Payload Base: 0x%08x MB, Base:0x%08x",
payloadBase, (payloadBase * MEGABYTE) );
payloadBase = payloadBase * MEGABYTE;
// Load payload data from PNOR in Sapphire mode
if(is_sapphire_load())
{
PNOR::SectionId l_secID = PNOR::PAYLOAD;
l_err = load_pnor_section( l_secID, payloadBase, false );
if ( l_err )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: error loading pnor section");
break;
}
}
else if(is_phyp_load())
{
#ifdef CONFIG_LOAD_PHYP_FROM_BOOTKERNEL
PNOR::SectionId l_secID = PNOR::BOOTKERNEL;
l_err = load_pnor_section(l_secID, payloadBase, true);
if (l_err)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: could not load BOOTKERNEL");
break;
}
#elif defined (CONFIG_LOAD_LIDS_VIA_PLDM)
MCL::MasterContainerLidMgr l_mcl(true);// load only
l_err = l_mcl.processSingleComponent(MCL::g_PowervmCompId,
MCL::g_PowervmCompInfo,
true); // force PHYP to be
// processed
if(l_err)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: could not process POWERVM component!");
break;
}
// On eBMC systems, move the PAYLOAD to the final location.
// We need to do that here and not in istep 21 so that HDAT can be
// built correctly.
if(!INITSERVICE::spBaseServicesEnabled())
{
l_err = RUNTIME::verifyAndMovePayload();
if(l_err)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: could not move PAYLOAD");
break;
}
}
#endif
}
}while(0);
return l_err;
}
static errlHndl_t load_pnor_section(PNOR::SectionId i_section,
uint64_t i_physAddr,
const bool i_zeroLmb)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ENTER_MRK"load_pnor_section()");
errlHndl_t err = nullptr;
#ifdef CONFIG_SECUREBOOT
// Securely load section
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,"load_pnor_section: secure section load of secId=0x%X (%s)",
i_section, PNOR::SectionIdToString(i_section));
err = PNOR::loadSecureSection(i_section);
if (err)
{
return err;
}
// Do not need to unload since we have plenty of memory at this point.
#endif
// Get the section info from PNOR.
PNOR::SectionInfo_t pnorSectionInfo;
err = PNOR::getSectionInfo( i_section, pnorSectionInfo );
if( err != nullptr )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"load_pnor_section: Could not get section info from %x",
i_section);
return err;
}
// XZ repository: http:git.tukaani.org/xz.git
// Header specifics can be found in xz/doc/xz-file-format.txt
const uint8_t HEADER_MAGIC[]= { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
uint8_t* l_pnor_header = reinterpret_cast<uint8_t *>(pnorSectionInfo.vaddr);
bool l_pnor_is_XZ_compressed = (0 == memcmp(l_pnor_header,
HEADER_MAGIC, sizeof(HEADER_MAGIC)));
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"load_pnor_section: is XZ_compressed: %d",
l_pnor_is_XZ_compressed);
// This assumes that the maximum decompression ratio will always be less
// than 1:16 (compressed:uncompressed). This works because XZ compression
// is usually 14.1%, the decompressor does not need the exact size, and
// we have all of mainstore memory at this point.
uint32_t uncompressedPayloadSize = l_pnor_is_XZ_compressed ?
(pnorSectionInfo.size * 16) : pnorSectionInfo.size;
const uint32_t originalPayloadSize = pnorSectionInfo.size;
printk( "Loading PNOR section %d (%s) %d bytes @0x%lx\n",
i_section,
pnorSectionInfo.name,
originalPayloadSize,
i_physAddr );
const uint32_t lmbSize = (i_zeroLmb
? RUNTIME::getLMBSizeInMB() * MEGABYTE
: 0);
const uint32_t mapSize = std::max(uncompressedPayloadSize, lmbSize);
void * loadAddr = NULL;
// Map in the physical memory we are loading into.
// If we are not xz compressed, the uncompressedSize
// is equal to the original size.
loadAddr = mm_block_map( reinterpret_cast<void*>( i_physAddr ),
mapSize );
if (i_zeroLmb)
{
const auto loadAddr_ptr = static_cast<uint8_t*>(loadAddr);
printk("Zeroing first LMB for PHYP (v:%p to v:%p)\n",
loadAddr_ptr + uncompressedPayloadSize,
loadAddr_ptr + mapSize);
memset(loadAddr_ptr + uncompressedPayloadSize,
0,
mapSize - uncompressedPayloadSize);
}
// Print out inital progress bar.
#ifdef CONFIG_CONSOLE
const int progressSteps = 80;
int progress = 0;
for ( int i = 0; i < progressSteps; ++i )
{
printk( "." );
}
printk( "\r" );
#endif
if(!l_pnor_is_XZ_compressed)
{
// Load the data block by block and update the progress bar.
const uint32_t BLOCK_SIZE = 4096;
for ( uint32_t i = 0; i < originalPayloadSize; i += BLOCK_SIZE )
{
memcpy( reinterpret_cast<void*>(
reinterpret_cast<uint64_t>(loadAddr) + i ),
reinterpret_cast<void*>( pnorSectionInfo.vaddr + i ),
std::min( originalPayloadSize - i, BLOCK_SIZE ) );
#ifdef CONFIG_CONSOLE
for ( int new_progress = (i * progressSteps) /
originalPayloadSize;
progress <= new_progress; progress++ )
{
printk( "=" );
}
#endif
}
#ifdef CONFIG_CONSOLE
printk( "\n" );
#endif
}
if(l_pnor_is_XZ_compressed)
{
struct xz_buf b;
struct xz_dec *s;
enum xz_ret ret;
xz_crc32_init();
s = xz_dec_init(XZ_SINGLE, 0);
if(s == NULL)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK
"load_pnor_section: XZ Embedded Initialization failed");
return err;
}
static const uint64_t compressed_SIZE = originalPayloadSize;
static const uint64_t decompressed_SIZE = uncompressedPayloadSize;
b.in = reinterpret_cast<uint8_t *>( pnorSectionInfo.vaddr);
b.in_pos = 0;
b.in_size = compressed_SIZE;
b.out = reinterpret_cast<uint8_t *>(loadAddr);
b.out_pos = 0;
b.out_size = decompressed_SIZE;
ret = xz_dec_run(s, &b);
if(ret == XZ_STREAM_END)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"load_pnor_section: The %s section was decompressed.",
pnorSectionInfo.name);
}else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK
"load_pnor_section: xz-embedded returned an error, ",
"the ret is %d",ret);
/*@
* @errortype
* @reasoncode fapi::RC_INVALID_RETURN_XZ_CODE
* @severity ERRORLOG::ERRL_SEV_UNRECOVERABLE
* @moduleid fapi::MOD_START_XZ_PAYLOAD
* @devdesc xz-embedded has returned an error.
* the return code can be found in xz.h
* @custdesc Error uncompressing payload image from
* boot flash
* @userdata1 Return code from xz-embedded
* @userdata2[0:31] Original Payload Size
* @userdata2[32:63] Uncompressed Payload Size
*/
err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
fapi::MOD_START_XZ_PAYLOAD,
fapi::RC_INVALID_RETURN_XZ_CODE,
ret,TWO_UINT32_TO_UINT64(
originalPayloadSize,
uncompressedPayloadSize));
err->addProcedureCallout(HWAS::EPUB_PRC_PHYP_CODE,
HWAS::SRCI_PRIORITY_HIGH);
}
//Clean up memory
xz_dec_end(s);
}
int rc = 0;
rc = mm_block_unmap(reinterpret_cast<void *>(loadAddr));
if(rc)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK
"load_pnor_section: mm_block_unmap returned 1");
/*@
* @errortype
* @reasoncode fapi::RC_MM_UNMAP_ERR
* @severity ERRORLOG::ERRL_SEV_UNRECOVERABLE
* @moduleid fapi::MOD_START_XZ_PAYLOAD
* @devdesc mm_block_unmap returned incorrectly with 0
* @custdesc Error unmapping memory section
*/
err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
fapi::MOD_START_XZ_PAYLOAD,
fapi::RC_MM_UNMAP_ERR,
0,0,0);
}
return err;
}
};
<commit_msg>Memory encryption support: Zero the first LMB of PAYLOAD memory for OPAL<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep20/call_host_load_payload.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <isteps/hwpisteperror.H>
#include <isteps/istep_reasoncodes.H>
#include <isteps/hwpf_reasoncodes.H>
#include <targeting/common/commontargeting.H>
#include <targeting/common/mfgFlagAccessors.H>
#include <targeting/targplatutil.H>
#include <initservice/istepdispatcherif.H>
#include <initservice/initserviceif.H>
#include <pnor/pnorif.H>
#include <util/misc.H>
#include <sys/mm.h>
#include <arch/ppc.H>
#include <kernel/console.H>
#include <xz/xz.h>
#include <util/utilmclmgr.H>
#include <runtime/runtime.H>
using namespace ERRORLOG;
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace TARGETING;
namespace ISTEP_20
{
/**
* @brief This function loads the pnor section in sapphire mode and
* and also decompresseses the section if it was compressed
*
* @param[in] i_section - Which section are we loading
* @param[in] i_physAddr - The physical address of the section
*
* @return errlHndl_t - NULL if successful, otherwise a pointer
* to the error log.
*/
static errlHndl_t load_pnor_section(PNOR::SectionId i_section,
uint64_t i_physAddr);
void* call_host_load_payload (void *io_pArgs)
{
errlHndl_t l_err = NULL;
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
ENTER_MRK"call_host_load_payload entry" );
do
{
TARGETING::Target* sys = UTIL::assertGetToplevelTarget();
if(INITSERVICE::spBaseServicesEnabled())
{
//this function is a NOOP on FSP system
break;
}
// Get Payload base/entry from attributes
uint64_t payloadBase = sys->getAttr<TARGETING::ATTR_PAYLOAD_BASE>();
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,INFO_MRK
"call_host_load_payload: Payload Base: 0x%08x MB, Base:0x%08x",
payloadBase, (payloadBase * MEGABYTE) );
payloadBase = payloadBase * MEGABYTE;
// Load payload data from PNOR in Sapphire mode
if(is_sapphire_load())
{
PNOR::SectionId l_secID = PNOR::PAYLOAD;
l_err = load_pnor_section( l_secID, payloadBase );
if ( l_err )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: error loading pnor section");
break;
}
}
else if(is_phyp_load())
{
#ifdef CONFIG_LOAD_PHYP_FROM_BOOTKERNEL
PNOR::SectionId l_secID = PNOR::BOOTKERNEL;
l_err = load_pnor_section(l_secID, payloadBase);
if (l_err)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: could not load BOOTKERNEL");
break;
}
#elif defined (CONFIG_LOAD_LIDS_VIA_PLDM)
MCL::MasterContainerLidMgr l_mcl(true);// load only
l_err = l_mcl.processSingleComponent(MCL::g_PowervmCompId,
MCL::g_PowervmCompInfo,
true); // force PHYP to be
// processed
if(l_err)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: could not process POWERVM component!");
break;
}
// On eBMC systems, move the PAYLOAD to the final location.
// We need to do that here and not in istep 21 so that HDAT can be
// built correctly.
if(!INITSERVICE::spBaseServicesEnabled())
{
l_err = RUNTIME::verifyAndMovePayload();
if(l_err)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_load_payload: could not move PAYLOAD");
break;
}
}
#endif
}
}while(0);
return l_err;
}
static errlHndl_t load_pnor_section(PNOR::SectionId i_section,
uint64_t i_physAddr)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ENTER_MRK"load_pnor_section(%d, 0x%lx)",
i_section, i_physAddr);
errlHndl_t err = nullptr;
#ifdef CONFIG_SECUREBOOT
// Securely load section
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,"load_pnor_section: secure section load of secId=0x%X (%s)",
i_section, PNOR::SectionIdToString(i_section));
err = PNOR::loadSecureSection(i_section);
if (err)
{
return err;
}
// Do not need to unload since we have plenty of memory at this point.
#endif
// Get the section info from PNOR.
PNOR::SectionInfo_t pnorSectionInfo;
err = PNOR::getSectionInfo( i_section, pnorSectionInfo );
if( err != nullptr )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"load_pnor_section: Could not get section info from %x",
i_section);
return err;
}
// XZ repository: http:git.tukaani.org/xz.git
// Header specifics can be found in xz/doc/xz-file-format.txt
const uint8_t HEADER_MAGIC[]= { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
uint8_t* l_pnor_header = reinterpret_cast<uint8_t *>(pnorSectionInfo.vaddr);
bool l_pnor_is_XZ_compressed = (0 == memcmp(l_pnor_header,
HEADER_MAGIC, sizeof(HEADER_MAGIC)));
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"load_pnor_section: is XZ_compressed: %d",
l_pnor_is_XZ_compressed);
// This assumes that the maximum decompression ratio will always be less
// than 1:16 (compressed:uncompressed). This works because XZ compression
// is usually 14.1%, the decompressor does not need the exact size, and
// we have all of mainstore memory at this point.
uint32_t uncompressedPayloadSize = l_pnor_is_XZ_compressed ?
(pnorSectionInfo.size * 16) : pnorSectionInfo.size;
const uint32_t originalPayloadSize = pnorSectionInfo.size;
printk( "Loading PNOR section %d (%s) %d bytes @0x%lx\n",
i_section,
pnorSectionInfo.name,
originalPayloadSize,
i_physAddr );
const uint32_t lmbSize = RUNTIME::getLMBSizeInMB() * MEGABYTE;
const uint32_t mapSize = std::max(uncompressedPayloadSize, lmbSize);
void * loadAddr = NULL;
// Map in the physical memory we are loading into.
// If we are not xz compressed, the uncompressedSize
// is equal to the original size.
loadAddr = mm_block_map( reinterpret_cast<void*>( i_physAddr ),
mapSize );
const auto loadAddr_ptr = static_cast<uint8_t*>(loadAddr);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Zeroing first LMB for hypervisor (v:%p/p:%p to v:%p/p:%p)\n",
loadAddr_ptr + uncompressedPayloadSize,
i_physAddr + uncompressedPayloadSize,
loadAddr_ptr + mapSize,
i_physAddr + mapSize);
memset(loadAddr_ptr + uncompressedPayloadSize,
0,
mapSize - uncompressedPayloadSize);
// Print out inital progress bar.
#ifdef CONFIG_CONSOLE
const int progressSteps = 80;
int progress = 0;
for ( int i = 0; i < progressSteps; ++i )
{
printk( "." );
}
printk( "\r" );
#endif
if(!l_pnor_is_XZ_compressed)
{
// Load the data block by block and update the progress bar.
const uint32_t BLOCK_SIZE = 4096;
for ( uint32_t i = 0; i < originalPayloadSize; i += BLOCK_SIZE )
{
memcpy( reinterpret_cast<void*>(
reinterpret_cast<uint64_t>(loadAddr) + i ),
reinterpret_cast<void*>( pnorSectionInfo.vaddr + i ),
std::min( originalPayloadSize - i, BLOCK_SIZE ) );
#ifdef CONFIG_CONSOLE
for ( int new_progress = (i * progressSteps) /
originalPayloadSize;
progress <= new_progress; progress++ )
{
printk( "=" );
}
#endif
}
#ifdef CONFIG_CONSOLE
printk( "\n" );
#endif
}
if(l_pnor_is_XZ_compressed)
{
struct xz_buf b;
struct xz_dec *s;
enum xz_ret ret;
xz_crc32_init();
s = xz_dec_init(XZ_SINGLE, 0);
if(s == NULL)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK
"load_pnor_section: XZ Embedded Initialization failed");
return err;
}
static const uint64_t compressed_SIZE = originalPayloadSize;
static const uint64_t decompressed_SIZE = uncompressedPayloadSize;
b.in = reinterpret_cast<uint8_t *>( pnorSectionInfo.vaddr);
b.in_pos = 0;
b.in_size = compressed_SIZE;
b.out = reinterpret_cast<uint8_t *>(loadAddr);
b.out_pos = 0;
b.out_size = decompressed_SIZE;
ret = xz_dec_run(s, &b);
if(ret == XZ_STREAM_END)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"load_pnor_section: The %s section was decompressed.",
pnorSectionInfo.name);
}else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK
"load_pnor_section: xz-embedded returned an error, ",
"the ret is %d",ret);
/*@
* @errortype
* @reasoncode fapi::RC_INVALID_RETURN_XZ_CODE
* @severity ERRORLOG::ERRL_SEV_UNRECOVERABLE
* @moduleid fapi::MOD_START_XZ_PAYLOAD
* @devdesc xz-embedded has returned an error.
* the return code can be found in xz.h
* @custdesc Error uncompressing payload image from
* boot flash
* @userdata1 Return code from xz-embedded
* @userdata2[0:31] Original Payload Size
* @userdata2[32:63] Uncompressed Payload Size
*/
err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
fapi::MOD_START_XZ_PAYLOAD,
fapi::RC_INVALID_RETURN_XZ_CODE,
ret,TWO_UINT32_TO_UINT64(
originalPayloadSize,
uncompressedPayloadSize));
err->addProcedureCallout(HWAS::EPUB_PRC_PHYP_CODE,
HWAS::SRCI_PRIORITY_HIGH);
}
//Clean up memory
xz_dec_end(s);
}
int rc = 0;
rc = mm_block_unmap(reinterpret_cast<void *>(loadAddr));
if(rc)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK
"load_pnor_section: mm_block_unmap returned 1");
/*@
* @errortype
* @reasoncode fapi::RC_MM_UNMAP_ERR
* @severity ERRORLOG::ERRL_SEV_UNRECOVERABLE
* @moduleid fapi::MOD_START_XZ_PAYLOAD
* @devdesc mm_block_unmap returned incorrectly with 0
* @custdesc Error unmapping memory section
*/
err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
fapi::MOD_START_XZ_PAYLOAD,
fapi::RC_MM_UNMAP_ERR,
0,0,0);
}
return err;
}
};
<|endoftext|> |
<commit_before>//
// View.cpp
// Cinder-ControlRoom
//
// Created by Jean-Pierre Mouilleseaux on 02 Jul 2014.
// Copyright 2014 Chorded Constructions. All rights reserved.
//
#include "View.h"
namespace Cinder { namespace ControlRoom {
using namespace ci;
using namespace ci::app;
ViewRef View::create(const ci::Rectf& frame) {
return ViewRef(new View(frame));
}
View::View(const Rectf& frame) : mFrame(frame), mBackgroundColor(ColorAf::zero()), mHidden(false) {
}
View::~View() {
disconnectEventListeners();
removeFromSuperview();
}
#pragma mark - HIERARCHY
void View::addSubview(const ViewRef& view) {
mSubviews.push_back(view);
view->setSuperview(shared_from_this());
}
void View::removeFromSuperview() {
if (!mSuperview) {
return;
}
mSuperview->removeSubview(shared_from_this());
}
bool View::isDescendantOfView(const ViewRef& view) {
// 💀 - view of nullptr is used to represent window content view
if (!view) {
return true;
}
bool status = false;
ViewRef v = getSuperview();
while (v) {
if (v == view) {
status = true;
break;
}
v = v->getSuperview();
}
return status;
}
#pragma mark -
void View::draw() {
gl::pushModelView(); {
gl::translate(mFrame.getUpperLeft());
// draw background
if (mBackgroundColor != ColorAf::zero()) {
gl::color(mBackgroundColor);
gl::drawSolidRect(getBounds());
}
// draw subviews
for (const ViewRef& view : mSubviews) {
if (view->isHidden()) {
continue;
}
view->draw();
}
} gl::popModelView();
}
#pragma mark -
void View::connectEventListeners() {
app::App* app = app::App::get();
mConnectionMouseDown = app->getWindow()->getSignalMouseDown().connect([&](MouseEvent event) {
mTrackingView = nullptr;
Vec2i point = convertPointFromView(event.getPos(), nullptr);
mTrackingView = hitTestPoint(point);
if (!mTrackingView) {
return;
}
mTrackingView->mouseDown(event);
event.setHandled();
});
mConnectionMouseDrag = app->getWindow()->getSignalMouseDrag().connect([&](MouseEvent event) {
if (!mTrackingView) {
return;
}
mTrackingView->mouseDrag(event);
event.setHandled();
});
mConnectionMouseUp = app->getWindow()->getSignalMouseUp().connect([&](MouseEvent event) {
if (!mTrackingView) {
return;
}
mTrackingView->mouseUp(event);
event.setHandled();
mTrackingView = nullptr;
});
}
void View::disconnectEventListeners() {
mConnectionMouseDown.disconnect();
mConnectionMouseDrag.disconnect();
mConnectionMouseUp.disconnect();
}
#pragma mark - COORDINATE CONVERSION
Vec2i View::convertPointFromView(const Vec2f& point, const ViewRef& view) {
// view to local
Vec2f p = point;
if (isDescendantOfView(view)) {
p -= mFrame.getUpperLeft();
if (mSuperview && mSuperview != view) {
p = mSuperview->convertPointFromView(p, view);
}
} else {
// TODO - implement
}
return p;
}
Vec2i View::convertPointToView(const Vec2i& point, const ViewRef& view) {
// local to view
Vec2i p = point;
if (isDescendantOfView(view)) {
// TODO - implement
} else {
// TODO - implement
}
return p;
}
#pragma mark - PRIVATE
void View::removeSubview(const ViewRef& view) {
if (!view) {
return;
}
mSubviews.erase(std::find(mSubviews.begin(), mSubviews.end(), view));
view->setSuperview(nullptr);
}
ViewRef View::hitTestPoint(const ci::Vec2i& point) {
if (!isPointInsideBounds(point)) {
return nullptr;
}
ViewRef view = nullptr;
for (const ViewRef& v : mSubviews) {
if (v->isHidden()) {
continue;
}
Vec2i p = v->convertPointFromView(point, shared_from_this());
if (!v->isPointInsideBounds(p)) {
continue;
}
view = v;
break;
}
if (!view) {
view = shared_from_this();
} else {
Vec2i p = view->convertPointFromView(point, shared_from_this());
view->hitTestPoint(p);
}
return view;
}
bool View::isPointInsideBounds(const ci::Vec2i& point) {
return getBounds().contains(point);
}
}}
<commit_msg>clarify nullptr value comment<commit_after>//
// View.cpp
// Cinder-ControlRoom
//
// Created by Jean-Pierre Mouilleseaux on 02 Jul 2014.
// Copyright 2014 Chorded Constructions. All rights reserved.
//
#include "View.h"
namespace Cinder { namespace ControlRoom {
using namespace ci;
using namespace ci::app;
ViewRef View::create(const ci::Rectf& frame) {
return ViewRef(new View(frame));
}
View::View(const Rectf& frame) : mFrame(frame), mBackgroundColor(ColorAf::zero()), mHidden(false) {
}
View::~View() {
disconnectEventListeners();
removeFromSuperview();
}
#pragma mark - HIERARCHY
void View::addSubview(const ViewRef& view) {
mSubviews.push_back(view);
view->setSuperview(shared_from_this());
}
void View::removeFromSuperview() {
if (!mSuperview) {
return;
}
mSuperview->removeSubview(shared_from_this());
}
bool View::isDescendantOfView(const ViewRef& view) {
// 💀 - nullptr is used to represent window's content view, i.e. the root view
if (!view) {
return true;
}
bool status = false;
ViewRef v = getSuperview();
while (v) {
if (v != view) {
v = v->getSuperview();
continue;
}
status = true;
break;
}
return status;
}
#pragma mark -
void View::draw() {
gl::pushModelView(); {
gl::translate(mFrame.getUpperLeft());
// draw background
if (mBackgroundColor != ColorAf::zero()) {
gl::color(mBackgroundColor);
gl::drawSolidRect(getBounds());
}
// draw subviews
for (const ViewRef& view : mSubviews) {
if (view->isHidden()) {
continue;
}
view->draw();
}
} gl::popModelView();
}
#pragma mark -
void View::connectEventListeners() {
app::App* app = app::App::get();
mConnectionMouseDown = app->getWindow()->getSignalMouseDown().connect([&](MouseEvent event) {
mTrackingView = nullptr;
Vec2i point = convertPointFromView(event.getPos(), nullptr);
mTrackingView = hitTestPoint(point);
if (!mTrackingView) {
return;
}
mTrackingView->mouseDown(event);
event.setHandled();
});
mConnectionMouseDrag = app->getWindow()->getSignalMouseDrag().connect([&](MouseEvent event) {
if (!mTrackingView) {
return;
}
mTrackingView->mouseDrag(event);
event.setHandled();
});
mConnectionMouseUp = app->getWindow()->getSignalMouseUp().connect([&](MouseEvent event) {
if (!mTrackingView) {
return;
}
mTrackingView->mouseUp(event);
event.setHandled();
mTrackingView = nullptr;
});
}
void View::disconnectEventListeners() {
mConnectionMouseDown.disconnect();
mConnectionMouseDrag.disconnect();
mConnectionMouseUp.disconnect();
}
#pragma mark - COORDINATE CONVERSION
Vec2i View::convertPointFromView(const Vec2f& point, const ViewRef& view) {
// view to local
Vec2f p = point;
if (isDescendantOfView(view)) {
p -= mFrame.getUpperLeft();
if (mSuperview && mSuperview != view) {
p = mSuperview->convertPointFromView(p, view);
}
} else {
// TODO - implement
}
return p;
}
Vec2i View::convertPointToView(const Vec2i& point, const ViewRef& view) {
// local to view
Vec2i p = point;
if (isDescendantOfView(view)) {
// TODO - implement
} else {
// TODO - implement
}
return p;
}
#pragma mark - PRIVATE
void View::removeSubview(const ViewRef& view) {
if (!view) {
return;
}
mSubviews.erase(std::find(mSubviews.begin(), mSubviews.end(), view));
view->setSuperview(nullptr);
}
ViewRef View::hitTestPoint(const ci::Vec2i& point) {
if (!isPointInsideBounds(point)) {
return nullptr;
}
ViewRef view = nullptr;
for (const ViewRef& v : mSubviews) {
if (v->isHidden()) {
continue;
}
Vec2i p = v->convertPointFromView(point, shared_from_this());
if (!v->isPointInsideBounds(p)) {
continue;
}
view = v;
break;
}
if (!view) {
view = shared_from_this();
} else {
Vec2i p = view->convertPointFromView(point, shared_from_this());
view->hitTestPoint(p);
}
return view;
}
bool View::isPointInsideBounds(const ci::Vec2i& point) {
return getBounds().contains(point);
}
}}
<|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 "config.h"
#include <wtf/MainThread.h>
#include <wtf/Threading.h>
#undef LOG
#include "build/build_config.h"
#include "webkit/tools/test_shell/test_webworker_helper.h"
#if defined(OS_MACOSX)
#include <dlfcn.h>
#endif
#include "base/logging.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "webkit/glue/webworkerclient.h"
WebWorker* TestWebWorkerHelper::CreateWebWorker(WebWorkerClient* client) {
TestWebWorkerHelper* loader = new TestWebWorkerHelper();
return loader->CreateWebWorker_(client, loader);
}
TestWebWorkerHelper::TestWebWorkerHelper() :
#if defined(OS_WIN)
module_(NULL),
#endif
CreateWebWorker_(NULL) {
Load();
}
TestWebWorkerHelper::~TestWebWorkerHelper() {
}
bool TestWebWorkerHelper::IsMainThread() const {
return WTF::isMainThread();
}
void TestWebWorkerHelper::DispatchToMainThread(WTF::MainThreadFunction* func,
void* context) {
return WTF::callOnMainThread(func, context);
}
void TestWebWorkerHelper::Load() {
FilePath path;
PathService::Get(base::DIR_EXE, &path);
#if defined(OS_WIN)
path = path.AppendASCII("test_worker.dll");
module_ = LoadLibrary(path.value().c_str());
if (module_ == 0)
return;
CreateWebWorker_ = reinterpret_cast<CreateWebWorkerFunc>
(GetProcAddress(module_, "CreateWebWorker"));
if (!CreateWebWorker_) {
FreeLibrary(module_);
module_ = 0;
}
#elif defined(OS_MACOSX)
path = path.AppendASCII("test_worker.dylib");
module_ = dlopen(path.value().c_str(), RTLD_NOW | RTLD_LOCAL);
if (!module_)
return;
CreateWebWorker_ = reinterpret_cast<CreateWebWorkerFunc>
(dlsym(module_, "CreateWebWorker"));
if (!CreateWebWorker_) {
dlclose(module_);
module_ = 0;
}
#else
NOTIMPLEMENTED();
#endif
}
void TestWebWorkerHelper::Unload() {
// Since this is called from DLL, delay the unloading until it can be
// invoked from EXE.
return WTF::callOnMainThread(UnloadHelper, this);
}
void TestWebWorkerHelper::UnloadHelper(void* param) {
TestWebWorkerHelper* this_ptr = static_cast<TestWebWorkerHelper*>(param);
#if defined(OS_WIN)
if (this_ptr->module_) {
FreeLibrary(this_ptr->module_);
this_ptr->module_ = 0;
}
#else
NOTIMPLEMENTED();
#endif
delete this_ptr;
}
<commit_msg><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 "config.h"
#include <wtf/MainThread.h>
#include <wtf/Threading.h>
#undef LOG
#include "build/build_config.h"
#include "webkit/tools/test_shell/test_webworker_helper.h"
#if defined(OS_MACOSX)
#include <dlfcn.h>
#endif
#include "base/logging.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "webkit/glue/webworkerclient.h"
WebWorker* TestWebWorkerHelper::CreateWebWorker(WebWorkerClient* client) {
TestWebWorkerHelper* loader = new TestWebWorkerHelper();
return loader->CreateWebWorker_(client, loader);
}
TestWebWorkerHelper::TestWebWorkerHelper() :
#if defined(OS_WIN)
module_(NULL),
#endif
CreateWebWorker_(NULL) {
Load();
}
TestWebWorkerHelper::~TestWebWorkerHelper() {
}
bool TestWebWorkerHelper::IsMainThread() const {
return WTF::isMainThread();
}
void TestWebWorkerHelper::DispatchToMainThread(WTF::MainThreadFunction* func,
void* context) {
return WTF::callOnMainThread(func, context);
}
void TestWebWorkerHelper::Load() {
FilePath path;
PathService::Get(base::DIR_EXE, &path);
#if defined(OS_WIN)
path = path.AppendASCII("test_worker.dll");
module_ = LoadLibrary(path.value().c_str());
if (module_ == 0)
return;
CreateWebWorker_ = reinterpret_cast<CreateWebWorkerFunc>
(GetProcAddress(module_, "CreateWebWorker"));
if (!CreateWebWorker_) {
FreeLibrary(module_);
module_ = 0;
}
#elif defined(OS_MACOSX)
path = path.AppendASCII("test_worker.dylib");
module_ = dlopen(path.value().c_str(), RTLD_NOW | RTLD_LOCAL);
if (!module_)
return;
CreateWebWorker_ = reinterpret_cast<CreateWebWorkerFunc>
(dlsym(module_, "CreateWebWorker"));
if (!CreateWebWorker_) {
dlclose(module_);
module_ = 0;
}
#else
NOTIMPLEMENTED();
#endif
}
void TestWebWorkerHelper::Unload() {
// Since this is called from DLL, delay the unloading until it can be
// invoked from EXE.
return WTF::callOnMainThread(UnloadHelper, this);
}
void TestWebWorkerHelper::UnloadHelper(void* param) {
TestWebWorkerHelper* this_ptr = static_cast<TestWebWorkerHelper*>(param);
#if defined(OS_WIN)
if (this_ptr->module_) {
FreeLibrary(this_ptr->module_);
this_ptr->module_ = 0;
}
#elif defined(OS_MACOSX)
if (this_ptr->module_) {
dlclose(this_ptr->module_);
this_ptr->module_ = 0;
this_ptr->CreateWebWorker_ = 0;
}
#else
NOTIMPLEMENTED();
#endif
delete this_ptr;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_SERIALIZABLE_ENVIRONMENT_HPP_
#define RDB_PROTOCOL_SERIALIZABLE_ENVIRONMENT_HPP_
#include "rdb_protocol/scope.hpp"
namespace query_language {
enum term_type_t {
TERM_TYPE_JSON,
TERM_TYPE_STREAM,
TERM_TYPE_VIEW,
// TODO: in the clients errors are just JSON for simplicity. Maybe we should do that here too?
/* This is the type of `Error` terms. It's called "arbitrary" because an
`Error` term can be either a stream or an object. It is a subtype of every
type. */
TERM_TYPE_ARBITRARY
};
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(term_type_t, int8_t, TERM_TYPE_JSON, TERM_TYPE_ARBITRARY);
class term_info_t {
public:
term_info_t() { }
term_info_t(term_type_t _type, bool _deterministic)
: type(_type), deterministic(_deterministic)
{ }
term_type_t type;
bool deterministic;
RDB_DECLARE_ME_SERIALIZABLE;
};
typedef variable_scope_t<term_info_t> variable_type_scope_t;
typedef variable_type_scope_t::new_scope_t new_scope_t;
typedef implicit_value_t<term_info_t> implicit_type_t;
struct type_checking_environment_t {
variable_type_scope_t scope;
implicit_type_t implicit_type;
RDB_DECLARE_ME_SERIALIZABLE;
};
//Scopes for single pieces of json
typedef variable_scope_t<boost::shared_ptr<scoped_cJSON_t> > variable_val_scope_t;
typedef variable_val_scope_t::new_scope_t new_val_scope_t;
//Implicit value typedef
typedef implicit_value_t<boost::shared_ptr<scoped_cJSON_t> >::impliciter_t implicit_value_setter_t;
/* Wrapper for the scopes in the runtime environment. Makes it convenient to
* serialize all the in scope variables. */
struct scopes_t {
variable_val_scope_t scope;
type_checking_environment_t type_env;
implicit_value_t<boost::shared_ptr<scoped_cJSON_t> > implicit_attribute_value;
RDB_DECLARE_ME_SERIALIZABLE;
};
} //namespace query_language
#endif // RDB_PROTOCOL_SERIALIZABLE_ENVIRONMENT_HPP_
<commit_msg>Removed unused typedef new_val_scope_t.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_SERIALIZABLE_ENVIRONMENT_HPP_
#define RDB_PROTOCOL_SERIALIZABLE_ENVIRONMENT_HPP_
#include "rdb_protocol/scope.hpp"
namespace query_language {
enum term_type_t {
TERM_TYPE_JSON,
TERM_TYPE_STREAM,
TERM_TYPE_VIEW,
// TODO: in the clients errors are just JSON for simplicity. Maybe we should do that here too?
/* This is the type of `Error` terms. It's called "arbitrary" because an
`Error` term can be either a stream or an object. It is a subtype of every
type. */
TERM_TYPE_ARBITRARY
};
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(term_type_t, int8_t, TERM_TYPE_JSON, TERM_TYPE_ARBITRARY);
class term_info_t {
public:
term_info_t() { }
term_info_t(term_type_t _type, bool _deterministic)
: type(_type), deterministic(_deterministic)
{ }
term_type_t type;
bool deterministic;
RDB_DECLARE_ME_SERIALIZABLE;
};
typedef variable_scope_t<term_info_t> variable_type_scope_t;
typedef variable_type_scope_t::new_scope_t new_scope_t;
typedef implicit_value_t<term_info_t> implicit_type_t;
struct type_checking_environment_t {
variable_type_scope_t scope;
implicit_type_t implicit_type;
RDB_DECLARE_ME_SERIALIZABLE;
};
//Scopes for single pieces of json
typedef variable_scope_t<boost::shared_ptr<scoped_cJSON_t> > variable_val_scope_t;
//Implicit value typedef
typedef implicit_value_t<boost::shared_ptr<scoped_cJSON_t> >::impliciter_t implicit_value_setter_t;
/* Wrapper for the scopes in the runtime environment. Makes it convenient to
* serialize all the in scope variables. */
struct scopes_t {
variable_val_scope_t scope;
type_checking_environment_t type_env;
implicit_value_t<boost::shared_ptr<scoped_cJSON_t> > implicit_attribute_value;
RDB_DECLARE_ME_SERIALIZABLE;
};
} //namespace query_language
#endif // RDB_PROTOCOL_SERIALIZABLE_ENVIRONMENT_HPP_
<|endoftext|> |
<commit_before>#ifndef CCHRONO_TIMER
#define CCHRONO_TIMER
#include<chrono>
#include<utility> //forward
namespace nTool
{
class CChrono_timer
{
std::chrono::high_resolution_clock::time_point begin_;
std::chrono::high_resolution_clock::time_point end_;
public:
inline std::chrono::hours::rep duration_hours() const
{
return std::chrono::duration_cast<std::chrono::hours>(end_-begin_).count();
}
inline std::chrono::minutes::rep duration_minutes() const
{
return std::chrono::duration_cast<std::chrono::minutes>(end_-begin_).count();
}
inline std::chrono::seconds::rep duration_seconds() const
{
return std::chrono::duration_cast<std::chrono::seconds>(end_-begin_).count();
}
inline std::chrono::milliseconds::rep duration_milliseconds() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>(end_-begin_).count();
}
inline std::chrono::microseconds::rep duration_microseconds() const
{
return std::chrono::duration_cast<std::chrono::microseconds>(end_-begin_).count();
}
inline std::chrono::nanoseconds::rep duration_nanoseconds() const
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(end_-begin_).count();
}
inline void start() noexcept
{
begin_=std::chrono::high_resolution_clock::now();
}
inline void stop() noexcept
{
end_=std::chrono::high_resolution_clock::now();
}
};
template<class Func,class ... Args>
CChrono_timer calc_time(const Func func,Args &&...args)
{
CChrono_timer timer;
timer.start();
std::forward<Func>(func)(std::forward<Args>(args)...);
timer.stop();
return timer;
}
}
#endif<commit_msg>fix calc_time<commit_after>#ifndef CCHRONO_TIMER
#define CCHRONO_TIMER
#include<chrono>
#include<utility> //forward
namespace nTool
{
class CChrono_timer
{
std::chrono::high_resolution_clock::time_point begin_;
std::chrono::high_resolution_clock::time_point end_;
public:
inline std::chrono::hours::rep duration_hours() const
{
return std::chrono::duration_cast<std::chrono::hours>(end_-begin_).count();
}
inline std::chrono::minutes::rep duration_minutes() const
{
return std::chrono::duration_cast<std::chrono::minutes>(end_-begin_).count();
}
inline std::chrono::seconds::rep duration_seconds() const
{
return std::chrono::duration_cast<std::chrono::seconds>(end_-begin_).count();
}
inline std::chrono::milliseconds::rep duration_milliseconds() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>(end_-begin_).count();
}
inline std::chrono::microseconds::rep duration_microseconds() const
{
return std::chrono::duration_cast<std::chrono::microseconds>(end_-begin_).count();
}
inline std::chrono::nanoseconds::rep duration_nanoseconds() const
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(end_-begin_).count();
}
inline void start() noexcept
{
begin_=std::chrono::high_resolution_clock::now();
}
inline void stop() noexcept
{
end_=std::chrono::high_resolution_clock::now();
}
};
template<class Func,class ... Args>
CChrono_timer calc_time(Func &&func,Args &&...args)
{
CChrono_timer timer;
timer.start();
std::forward<Func>(func)(std::forward<Args>(args)...);
timer.stop();
return timer;
}
}
#endif<|endoftext|> |
<commit_before>/*
* TTMatrixMixer Object
* Copyright © 2009, Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTMatrixMixer.h"
#ifdef TT_PLATFORM_WIN
#include <algorithm>
#endif
#define thisTTClass TTMatrixMixer
#define thisTTClassName "matrixmixer"
#define thisTTClassTags "audio, mixing, matrix"
TT_AUDIO_CONSTRUCTOR,
mNumInputs(1),
mNumOutputs(1),
mGainMatrix(NULL),
tempGainMatrix(NULL)
{
TTObjectInstantiate(kTTSym_matrix, (TTObjectPtr*)&mGainMatrix, NULL);
TTObjectInstantiate(kTTSym_matrix, (TTObjectPtr*)&tempGainMatrix, NULL);
addAttribute(NumInputs, kTypeUInt16);
addAttributeProperty(NumInputs, readOnly, kTTBoolYes);
addAttribute(NumOutputs, kTypeUInt16);
addAttributeProperty(NumOutputs, readOnly, kTTBoolYes);
addMessageWithArgument(setGain);
addMessageWithArgument(setLinearGain);
addMessageWithArgument(setMidiGain);
//registerMessageWithArgument(updateMaxNumChannels);
addMessage(clear);
//setAttributeValue(TT("MaxNumChannels"), newMaxNumChannels);
setProcessMethod(processAudio);
mGainMatrix->setAttributeValue(TT("type"), TT("float64"));
tempGainMatrix->setAttributeValue(TT("type"), TT("float64"));
TTValue v(1, 1); // we need to make the mGainMatrix at least 1x1 otherwise we have problems with adapting to tempGainMatrix
mGainMatrix->setAttributeValue(TT("dimensions"), v);
tempGainMatrix->setAttributeValue(TT("dimensions"), v);
clear();
}
TTMatrixMixer::~TTMatrixMixer()
{
TTObjectRelease((TTObjectPtr*)&mGainMatrix);
TTObjectRelease((TTObjectPtr*)&tempGainMatrix);
}
// conceptually:
// columns == inputs
// rows == outputs
// TODO: the next two methods should never decrease their size
TTErr TTMatrixMixer::setNumInputs(const TTUInt16 newValue)
{
TTUInt16 numInputs = newValue;
TTValue v(numInputs, mNumOutputs);
if (newValue != mNumInputs) {
tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
mNumInputs = numInputs;
mGainMatrix->setAttributeValue(TT("dimensions"), v);
clear(); //2. clear mGainMatrix
restoreMatrix(); //3. element-wise copy tempGainMatrix content over to mGainMatrix
}
return kTTErrNone;
}
TTErr TTMatrixMixer::setNumOutputs(const TTUInt16 newValue)
{
TTUInt16 numOutputs = newValue;
TTValue v(mNumInputs, numOutputs);
if (newValue != mNumOutputs) {
tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
mNumOutputs = newValue;
mGainMatrix->setAttributeValue(TT("dimensions"), v);
clear(); //2. clear mGainMatrix
restoreMatrix(); //3. element-wise copy tempGainMatrix content over to mGainMatrix
}
return kTTErrNone;
}
TTErr TTMatrixMixer::restoreMatrix()
{
TTValue v;
TTFloat64 tempValue;
TTUInt16 xx, yy;
tempGainMatrix->getDimensions(v);
v.get(0,xx);
v.get(1,yy);
for (TTUInt16 y=0; y < yy; y++) {
for (TTUInt16 x=0; x < xx; x++) {
tempGainMatrix->get2dZeroIndex(x, y, tempValue);
mGainMatrix->set2dZeroIndex(x, y, tempValue);
}
}
return kTTErrNone;
}
TTErr TTMatrixMixer::clear()
{
mGainMatrix->clear();
return kTTErrNone;
}
TTErr TTMatrixMixer::setGain(TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
checkMatrixSize(x,y);
newValue.clear();
mGainMatrix->set2dZeroIndex(x, y, dbToLinear(gainValue));
return kTTErrNone;
}
TTErr TTMatrixMixer::setLinearGain(TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
checkMatrixSize(x,y);
newValue.clear();
mGainMatrix->set2dZeroIndex(x, y, gainValue);
return kTTErrNone;
}
TTErr TTMatrixMixer::setMidiGain(TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
checkMatrixSize(x,y);
newValue.clear();
mGainMatrix->set2dZeroIndex(x, y, midiToLinearGain(gainValue));
return kTTErrNone;
}
TTErr TTMatrixMixer::checkMatrixSize(TTUInt16 x, TTUInt16 y)
//this function will resize mGainMatrix if necessary while preserving its content
{
if (x > (mNumInputs-1)){
if (y > (mNumOutputs-1))
mNumOutputs = y+1;
setNumInputs(x+1);
}
else{
if (y > (mNumOutputs-1))
setNumOutputs(y+1);
}
return kTTErrNone;
}
void TTMatrixMixer::processOne(TTAudioSignal& in, TTAudioSignal& out, TTFloat64 gain)
{
TTUInt16 vs, channel;
TTSampleValuePtr inSample, outSample;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
for (channel=0; channel<numchannels; channel++) {
inSample = in.mSampleVectors[channel];
outSample = out.mSampleVectors[channel];
vs = in.getVectorSizeAsInt();
while (vs--)
*outSample++ += (*inSample++) * gain;
}
}
/* We are trying to calculate audio output from multiple audio inputs.
So for each audio output:
1. Start with a zero signal
2. Then += each input signal, multiplied by its gain
We may need to speed up this operation by iterating through the signals using direct access of the structs.
*/
TTErr TTMatrixMixer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{ //TODO: if mGainMatrix is sparse (i.e. it has a lot of zeros), we can do better than this algorithm which iterates through the entire matrix
TTUInt16 minChannelIn = min(mNumInputs,inputs->numAudioSignals);
TTFloat64 gain;
for (TTUInt16 y=0; y < outputs->numAudioSignals; y++) {
TTAudioSignal& out = outputs->getSignal(y);
out.clear(); // zeroing output memory
if (y < (mNumOutputs)){
for (TTUInt16 x=0; x < minChannelIn; x++) {
mGainMatrix->get2dZeroIndex(x, y, gain);
if (gain){ //if the gain value is zero, just pass processOne
TTAudioSignal& in = inputs->getSignal(x);
processOne(in, out, gain);
}
}
}
}
return kTTErrNone;
}
<commit_msg>preventing a potential bug similar to #1014<commit_after>/*
* TTMatrixMixer Object
* Copyright © 2009, Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTMatrixMixer.h"
#ifdef TT_PLATFORM_WIN
#include <algorithm>
#endif
#define thisTTClass TTMatrixMixer
#define thisTTClassName "matrixmixer"
#define thisTTClassTags "audio, mixing, matrix"
TT_AUDIO_CONSTRUCTOR,
mNumInputs(1),
mNumOutputs(1),
mGainMatrix(NULL),
tempGainMatrix(NULL)
{
TTObjectInstantiate(kTTSym_matrix, (TTObjectPtr*)&mGainMatrix, NULL);
TTObjectInstantiate(kTTSym_matrix, (TTObjectPtr*)&tempGainMatrix, NULL);
addAttribute(NumInputs, kTypeUInt16);
addAttributeProperty(NumInputs, readOnly, kTTBoolYes);
addAttribute(NumOutputs, kTypeUInt16);
addAttributeProperty(NumOutputs, readOnly, kTTBoolYes);
addMessageWithArgument(setGain);
addMessageWithArgument(setLinearGain);
addMessageWithArgument(setMidiGain);
//registerMessageWithArgument(updateMaxNumChannels);
addMessage(clear);
//setAttributeValue(TT("MaxNumChannels"), newMaxNumChannels);
setProcessMethod(processAudio);
mGainMatrix->setAttributeValue(TT("type"), TT("float64"));
tempGainMatrix->setAttributeValue(TT("type"), TT("float64"));
TTValue v(1, 1); // we need to make the mGainMatrix at least 1x1 otherwise we have problems with adapting to tempGainMatrix
mGainMatrix->setAttributeValue(TT("dimensions"), v);
tempGainMatrix->setAttributeValue(TT("dimensions"), v);
clear();
}
TTMatrixMixer::~TTMatrixMixer()
{
TTObjectRelease((TTObjectPtr*)&mGainMatrix);
TTObjectRelease((TTObjectPtr*)&tempGainMatrix);
}
// conceptually:
// columns == inputs
// rows == outputs
// TODO: the next two methods should never decrease their size
TTErr TTMatrixMixer::setNumInputs(const TTUInt16 newValue)
{
TTUInt16 numInputs = newValue;
TTValue v(numInputs, mNumOutputs);
if (newValue != mNumInputs) {
tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
mNumInputs = numInputs;
mGainMatrix->setAttributeValue(TT("dimensions"), v);
clear(); //2. clear mGainMatrix
restoreMatrix(); //3. element-wise copy tempGainMatrix content over to mGainMatrix
}
return kTTErrNone;
}
TTErr TTMatrixMixer::setNumOutputs(const TTUInt16 newValue)
{
TTUInt16 numOutputs = newValue;
TTValue v(mNumInputs, numOutputs);
if (newValue != mNumOutputs) {
tempGainMatrix->adaptTo(mGainMatrix); //1. copy mGainMtrix to tempGainMatrix;
TTMatrix::copy(*mGainMatrix, *tempGainMatrix);
mNumOutputs = newValue;
mGainMatrix->setAttributeValue(TT("dimensions"), v);
clear(); //2. clear mGainMatrix
restoreMatrix(); //3. element-wise copy tempGainMatrix content over to mGainMatrix
}
return kTTErrNone;
}
TTErr TTMatrixMixer::restoreMatrix()
{
TTValue v;
TTFloat64 tempValue;
TTUInt16 xx, yy;
tempGainMatrix->getDimensions(v);
v.get(0,xx);
v.get(1,yy);
TTLimit(xx,(TTUInt16) 1, mNumInputs); // in case xx or yy is greater than the current mGainMatrix ...
TTLimit(yy,(TTUInt16) 1, mNumOutputs);
for (TTUInt16 y=0; y < yy; y++) {
for (TTUInt16 x=0; x < xx; x++) {
tempGainMatrix->get2dZeroIndex(x, y, tempValue);
mGainMatrix->set2dZeroIndex(x, y, tempValue);
}
}
return kTTErrNone;
}
TTErr TTMatrixMixer::clear()
{
mGainMatrix->clear();
return kTTErrNone;
}
TTErr TTMatrixMixer::setGain(TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
checkMatrixSize(x,y);
newValue.clear();
mGainMatrix->set2dZeroIndex(x, y, dbToLinear(gainValue));
return kTTErrNone;
}
TTErr TTMatrixMixer::setLinearGain(TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
checkMatrixSize(x,y);
newValue.clear();
mGainMatrix->set2dZeroIndex(x, y, gainValue);
return kTTErrNone;
}
TTErr TTMatrixMixer::setMidiGain(TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
checkMatrixSize(x,y);
newValue.clear();
mGainMatrix->set2dZeroIndex(x, y, midiToLinearGain(gainValue));
return kTTErrNone;
}
TTErr TTMatrixMixer::checkMatrixSize(TTUInt16 x, TTUInt16 y)
//this function will resize mGainMatrix if necessary while preserving its content
{
if (x > (mNumInputs-1)){
if (y > (mNumOutputs-1))
mNumOutputs = y+1;
setNumInputs(x+1);
}
else{
if (y > (mNumOutputs-1))
setNumOutputs(y+1);
}
return kTTErrNone;
}
void TTMatrixMixer::processOne(TTAudioSignal& in, TTAudioSignal& out, TTFloat64 gain)
{
TTUInt16 vs, channel;
TTSampleValuePtr inSample, outSample;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
for (channel=0; channel<numchannels; channel++) {
inSample = in.mSampleVectors[channel];
outSample = out.mSampleVectors[channel];
vs = in.getVectorSizeAsInt();
while (vs--)
*outSample++ += (*inSample++) * gain;
}
}
/* We are trying to calculate audio output from multiple audio inputs.
So for each audio output:
1. Start with a zero signal
2. Then += each input signal, multiplied by its gain
We may need to speed up this operation by iterating through the signals using direct access of the structs.
*/
TTErr TTMatrixMixer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{ //TODO: if mGainMatrix is sparse (i.e. it has a lot of zeros), we can do better than this algorithm which iterates through the entire matrix
TTUInt16 minChannelIn = min(mNumInputs,inputs->numAudioSignals);
TTFloat64 gain;
for (TTUInt16 y=0; y < outputs->numAudioSignals; y++) {
TTAudioSignal& out = outputs->getSignal(y);
out.clear(); // zeroing output memory
if (y < (mNumOutputs)){
for (TTUInt16 x=0; x < minChannelIn; x++) {
mGainMatrix->get2dZeroIndex(x, y, gain);
if (gain){ //if the gain value is zero, just pass processOne
TTAudioSignal& in = inputs->getSignal(x);
processOne(in, out, gain);
}
}
}
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/*
* TTMatrixMixer Object
* Copyright © 2009, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTMatrixMixer.h"
#define thisTTClass TTMatrixMixer
#define thisTTClassName "matrixmixer"
#define thisTTClassTags "audio, mixing, matrix"
TT_AUDIO_CONSTRUCTOR,
mNumInputs(0),
mNumOutputs(0)
{
addAttribute(NumInputs, kTypeUInt16); // TODO: set readonly property for this attribute
addAttribute(NumOutputs, kTypeUInt16); // TODO: set readonly property for this attribute
addMessageWithArgument(setGain);
addMessageWithArgument(setLinearGain);
addMessageWithArgument(setMidiGain);
//registerMessageWithArgument(updateMaxNumChannels);
addMessage(clear);
//setAttributeValue(kTTSym_maxNumChannels, newMaxNumChannels);
setProcessMethod(processAudio);
}
TTMatrixMixer::~TTMatrixMixer()
{
;
}
// conceptually:
// columns == inputs
// rows == outputs
TTErr TTMatrixMixer::setNumInputs(const TTUInt16 newValue)
{
if (newValue != mNumInputs) {
mNumInputs = newValue;
mGainMatrix.resize(mNumInputs);
for_each(mGainMatrix.begin(), mGainMatrix.end(), bind2nd(mem_fun_ref(&TTSampleMatrix::value_type::resize), mNumOutputs));
}
return kTTErrNone;
}
TTErr TTMatrixMixer::setNumOutputs(const TTUInt16 newValue)
{
if (newValue != mNumOutputs) {
mNumOutputs = newValue;
for_each(mGainMatrix.begin(), mGainMatrix.end(), bind2nd(mem_fun_ref(&TTSampleMatrix::value_type::resize), mNumOutputs));
}
return kTTErrNone;
}
TTErr TTMatrixMixer::clear()
{
for (TTSampleMatrixIter column = mGainMatrix.begin(); column != mGainMatrix.end(); column++)
column->assign(mNumOutputs, 0.0);
return kTTErrNone;
}
TTErr TTMatrixMixer::setGain(const TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
mGainMatrix[x][y] = dbToLinear(gainValue);
return kTTErrNone;
}
TTErr TTMatrixMixer::setLinearGain(const TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
mGainMatrix[x][y] = gainValue;
return kTTErrNone;
}
TTErr TTMatrixMixer::setMidiGain(const TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
mGainMatrix[x][y] = midiToLinearGain(gainValue);
return kTTErrNone;
}
void TTMatrixMixer::processOne(TTAudioSignal& in, TTAudioSignal& out, TTFloat64 gain)
{
TTUInt16 vs;
TTSampleValue* inSample;
TTSampleValue* outSample;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
for (channel=0; channel<numchannels; channel++) {
inSample = in.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while (vs--)
*outSample++ += (*inSample++) * gain;
}
}
/* We are trying to calculate audio output from multiple audio inputs.
So for each audio output:
1. Start with a zero signal
2. Then += each input signal, multiplied by its gain
We may need to speed up this operation by iterating through the signals using direct access of the structs.
*/
TTErr TTMatrixMixer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
setNumInputs(inputs->numAudioSignals);
setNumOutputs(outputs->numAudioSignals);
for (TTUInt16 y=0; y < mNumOutputs; y++) {
TTAudioSignal& out = outputs->getSignal(y);
out.clear();
for (TTUInt16 x=0; x < mNumInputs; x++) {
TTAudioSignal& in = inputs->getSignal(x);
processOne(in, out, mGainMatrix[x][y]);
}
}
return kTTErrNone;
}
<commit_msg>MathLib: windows build fix<commit_after>/*
* TTMatrixMixer Object
* Copyright © 2009, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTMatrixMixer.h"
#ifdef TT_PLATFORM_WIN
#include <algorithm>
#endif
#define thisTTClass TTMatrixMixer
#define thisTTClassName "matrixmixer"
#define thisTTClassTags "audio, mixing, matrix"
TT_AUDIO_CONSTRUCTOR,
mNumInputs(0),
mNumOutputs(0)
{
addAttribute(NumInputs, kTypeUInt16); // TODO: set readonly property for this attribute
addAttribute(NumOutputs, kTypeUInt16); // TODO: set readonly property for this attribute
addMessageWithArgument(setGain);
addMessageWithArgument(setLinearGain);
addMessageWithArgument(setMidiGain);
//registerMessageWithArgument(updateMaxNumChannels);
addMessage(clear);
//setAttributeValue(kTTSym_maxNumChannels, newMaxNumChannels);
setProcessMethod(processAudio);
}
TTMatrixMixer::~TTMatrixMixer()
{
;
}
// conceptually:
// columns == inputs
// rows == outputs
TTErr TTMatrixMixer::setNumInputs(const TTUInt16 newValue)
{
if (newValue != mNumInputs) {
mNumInputs = newValue;
mGainMatrix.resize(mNumInputs);
for_each(mGainMatrix.begin(), mGainMatrix.end(), bind2nd(mem_fun_ref(&TTSampleMatrix::value_type::resize), mNumOutputs));
}
return kTTErrNone;
}
TTErr TTMatrixMixer::setNumOutputs(const TTUInt16 newValue)
{
if (newValue != mNumOutputs) {
mNumOutputs = newValue;
for_each(mGainMatrix.begin(), mGainMatrix.end(), bind2nd(mem_fun_ref(&TTSampleMatrix::value_type::resize), mNumOutputs));
}
return kTTErrNone;
}
TTErr TTMatrixMixer::clear()
{
for (TTSampleMatrixIter column = mGainMatrix.begin(); column != mGainMatrix.end(); column++)
column->assign(mNumOutputs, 0.0);
return kTTErrNone;
}
TTErr TTMatrixMixer::setGain(const TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
mGainMatrix[x][y] = dbToLinear(gainValue);
return kTTErrNone;
}
TTErr TTMatrixMixer::setLinearGain(const TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
mGainMatrix[x][y] = gainValue;
return kTTErrNone;
}
TTErr TTMatrixMixer::setMidiGain(const TTValue& newValue)
{
TTUInt16 x;
TTUInt16 y;
TTFloat64 gainValue;
if (newValue.getSize() != 3)
return kTTErrWrongNumValues;
newValue.get(0, x);
newValue.get(1, y);
newValue.get(2, gainValue);
mGainMatrix[x][y] = midiToLinearGain(gainValue);
return kTTErrNone;
}
void TTMatrixMixer::processOne(TTAudioSignal& in, TTAudioSignal& out, TTFloat64 gain)
{
TTUInt16 vs;
TTSampleValue* inSample;
TTSampleValue* outSample;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
for (channel=0; channel<numchannels; channel++) {
inSample = in.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while (vs--)
*outSample++ += (*inSample++) * gain;
}
}
/* We are trying to calculate audio output from multiple audio inputs.
So for each audio output:
1. Start with a zero signal
2. Then += each input signal, multiplied by its gain
We may need to speed up this operation by iterating through the signals using direct access of the structs.
*/
TTErr TTMatrixMixer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
setNumInputs(inputs->numAudioSignals);
setNumOutputs(outputs->numAudioSignals);
for (TTUInt16 y=0; y < mNumOutputs; y++) {
TTAudioSignal& out = outputs->getSignal(y);
out.clear();
for (TTUInt16 x=0; x < mNumInputs; x++) {
TTAudioSignal& in = inputs->getSignal(x);
processOne(in, out, mGainMatrix[x][y]);
}
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file openocd_low_level_device.cc
*/
#include <sstream>
#include <iomanip>
#include "micro_common.h"
#include "low_level_device.h"
#include "tcl_socket.h"
namespace tvm {
namespace runtime {
/*!
* \brief OpenOCD low-level device for uTVM micro devices connected over JTAG
*/
class OpenOCDLowLevelDevice final : public LowLevelDevice {
public:
/*!
* \brief constructor to initialize connection to openocd device
* \param server_addr address of the OpenOCD server to connect to
* \param port port of the OpenOCD server to connect to
*/
explicit OpenOCDLowLevelDevice(const std::string& server_addr,
int port) : socket_() {
server_addr_ = server_addr;
port_ = port;
socket_.Connect(tvm::support::SockAddr(server_addr_.c_str(), port_));
socket_.cmd_builder() << "halt 0";
socket_.SendCommand();
}
void Read(TargetPtr addr, void* buf, size_t num_bytes) override {
if (num_bytes == 0) {
return;
}
// TODO(weberlo): Refactor between read and write.
// Check if we need to chunk this write request.
if (num_bytes > kMemTransferLimit) {
char* curr_buf_ptr = reinterpret_cast<char*>(buf);
while (num_bytes != 0) {
size_t amount_to_read;
if (num_bytes > kMemTransferLimit) {
amount_to_read = kMemTransferLimit;
} else {
amount_to_read = num_bytes;
}
Read(addr, reinterpret_cast<void*>(curr_buf_ptr), amount_to_read);
addr += amount_to_read;
curr_buf_ptr += amount_to_read;
num_bytes -= amount_to_read;
}
return;
}
{
socket_.cmd_builder() << "array unset output";
socket_.SendCommand();
socket_.cmd_builder()
<< "mem2array output"
<< " " << std::dec << kWordSize
<< " " << addr.cast_to<void*>()
// Round up any request sizes under a byte, since OpenOCD doesn't support
// sub-byte-sized transfers.
<< " " << std::dec << (num_bytes < 8 ? 8 : num_bytes);
socket_.SendCommand();
}
{
socket_.cmd_builder() << "return $output";
socket_.SendCommand();
const std::string& reply = socket_.last_reply();
std::istringstream values(reply);
char* char_buf = reinterpret_cast<char*>(buf);
ssize_t req_bytes_remaining = num_bytes;
uint32_t index;
uint32_t val;
while (req_bytes_remaining > 0) {
// The response from this command pairs indices with the contents of the
// memory at that index.
values >> index;
CHECK(index < num_bytes)
<< "index " << index <<
" out of bounds (length " << num_bytes << ")";
// Read the value into `curr_val`, instead of reading directly into
// `buf_iter`, because otherwise it's interpreted as the ASCII value and
// not the integral value.
values >> val;
char_buf[index] = static_cast<uint8_t>(val);
req_bytes_remaining--;
}
if (num_bytes >= 8) {
uint32_t check_index;
values >> check_index;
CHECK(check_index != index) << "more data in response than requested";
}
}
}
void Write(TargetPtr addr, const void* buf, size_t num_bytes) override {
if (num_bytes == 0) {
return;
}
// Check if we need to chunk this write request.
if (num_bytes > kMemTransferLimit) {
const char* curr_buf_ptr = reinterpret_cast<const char*>(buf);
while (num_bytes != 0) {
size_t amount_to_write;
if (num_bytes > kMemTransferLimit) {
amount_to_write = kMemTransferLimit;
} else {
amount_to_write = num_bytes;
}
Write(addr, reinterpret_cast<const void*>(curr_buf_ptr), amount_to_write);
addr += amount_to_write;
curr_buf_ptr += amount_to_write;
num_bytes -= amount_to_write;
}
return;
}
// Clear `input` array.
socket_.cmd_builder() << "array unset input";
socket_.SendCommand();
// Build a command to set the value of `input`.
{
std::ostringstream& cmd_builder = socket_.cmd_builder();
cmd_builder << "array set input {";
const char* char_buf = reinterpret_cast<const char*>(buf);
for (size_t i = 0; i < num_bytes; i++) {
// In a Tcl `array set` commmand, we need to pair the array indices with
// their values.
cmd_builder << i << " ";
// Need to cast to uint, so the number representation of `buf[i]` is
// printed, and not the ASCII representation.
cmd_builder << static_cast<uint32_t>(char_buf[i]) << " ";
}
cmd_builder << "}";
socket_.SendCommand();
}
{
socket_.cmd_builder()
<< "array2mem input"
<< " " << std::dec << kWordSize
<< " " << addr.cast_to<void*>()
<< " " << std::dec << num_bytes;
socket_.SendCommand();
}
}
void Execute(TargetPtr func_addr, TargetPtr breakpoint_addr) override {
socket_.cmd_builder() << "halt 0";
socket_.SendCommand();
// Set a breakpoint at the beginning of `UTVMDone`.
socket_.cmd_builder() << "bp " << breakpoint_addr.cast_to<void*>() << " 2";
socket_.SendCommand();
socket_.cmd_builder() << "resume " << func_addr.cast_to<void*>();
socket_.SendCommand();
socket_.cmd_builder() << "wait_halt " << kWaitTime;
socket_.SendCommand();
socket_.cmd_builder() << "halt 0";
socket_.SendCommand();
// Remove the breakpoint.
socket_.cmd_builder() << "rbp " << breakpoint_addr.cast_to<void*>();
socket_.SendCommand();
}
const char* device_type() const final {
return "openocd";
}
private:
/*! \brief socket used to communicate with the device through Tcl */
TclSocket socket_;
/*! \brief address of OpenOCD server */
std::string server_addr_;
/*! \brief port of OpenOCD server */
int port_;
/*! \brief number of bytes in a word on the target device (64-bit) */
static const constexpr ssize_t kWordSize = 8;
// NOTE: The OS pipe buffer must be able to handle a line long enough to
// print this transfer request.
/*! \brief maximum number of bytes allowed in a single memory transfer */
static const constexpr ssize_t kMemTransferLimit = 8000;
/*! \brief number of milliseconds to wait for function execution to halt */
static const constexpr int kWaitTime = 30000;
};
const std::shared_ptr<LowLevelDevice> OpenOCDLowLevelDeviceCreate(const std::string& server_addr,
int port) {
std::shared_ptr<LowLevelDevice> lld =
std::make_shared<OpenOCDLowLevelDevice>(server_addr, port);
return lld;
}
} // namespace runtime
} // namespace tvm
<commit_msg>[uTVM] Reset target and wait for runtime initialization on connect. (#5499)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file openocd_low_level_device.cc
*/
#include <iomanip>
#include <sstream>
#include "micro_common.h"
#include "low_level_device.h"
#include "tcl_socket.h"
namespace tvm {
namespace runtime {
/*!
* \brief OpenOCD low-level device for uTVM micro devices connected over JTAG
*/
class OpenOCDLowLevelDevice final : public LowLevelDevice {
public:
/*!
* \brief constructor to initialize connection to openocd device
* \param server_addr address of the OpenOCD server to connect to
* \param port port of the OpenOCD server to connect to
*/
explicit OpenOCDLowLevelDevice(const std::string& server_addr,
int port) : socket_() {
server_addr_ = server_addr;
port_ = port;
socket_.Connect(tvm::support::SockAddr(server_addr_.c_str(), port_));
socket_.cmd_builder() << "reset run";
socket_.SendCommand();
socket_.cmd_builder() << "halt 500";
socket_.SendCommand();
}
void Read(TargetPtr addr, void* buf, size_t num_bytes) override {
if (num_bytes == 0) {
return;
}
// TODO(weberlo): Refactor between read and write.
// Check if we need to chunk this write request.
if (num_bytes > kMemTransferLimit) {
char* curr_buf_ptr = reinterpret_cast<char*>(buf);
while (num_bytes != 0) {
size_t amount_to_read;
if (num_bytes > kMemTransferLimit) {
amount_to_read = kMemTransferLimit;
} else {
amount_to_read = num_bytes;
}
Read(addr, reinterpret_cast<void*>(curr_buf_ptr), amount_to_read);
addr += amount_to_read;
curr_buf_ptr += amount_to_read;
num_bytes -= amount_to_read;
}
return;
}
{
socket_.cmd_builder() << "array unset output";
socket_.SendCommand();
socket_.cmd_builder()
<< "mem2array output"
<< " " << std::dec << kWordSize
<< " " << addr.cast_to<void*>()
// Round up any request sizes under a byte, since OpenOCD doesn't support
// sub-byte-sized transfers.
<< " " << std::dec << (num_bytes < 8 ? 8 : num_bytes);
socket_.SendCommand();
}
{
socket_.cmd_builder() << "return $output";
socket_.SendCommand();
const std::string& reply = socket_.last_reply();
std::istringstream values(reply);
char* char_buf = reinterpret_cast<char*>(buf);
ssize_t req_bytes_remaining = num_bytes;
uint32_t index;
uint32_t val;
while (req_bytes_remaining > 0) {
// The response from this command pairs indices with the contents of the
// memory at that index.
values >> index;
CHECK(index < num_bytes)
<< "index " << index <<
" out of bounds (length " << num_bytes << ")";
// Read the value into `curr_val`, instead of reading directly into
// `buf_iter`, because otherwise it's interpreted as the ASCII value and
// not the integral value.
values >> val;
char_buf[index] = static_cast<uint8_t>(val);
req_bytes_remaining--;
}
if (num_bytes >= 8) {
uint32_t check_index;
values >> check_index;
CHECK(check_index != index) << "more data in response than requested";
}
}
}
void Write(TargetPtr addr, const void* buf, size_t num_bytes) override {
if (num_bytes == 0) {
return;
}
// Check if we need to chunk this write request.
if (num_bytes > kMemTransferLimit) {
const char* curr_buf_ptr = reinterpret_cast<const char*>(buf);
while (num_bytes != 0) {
size_t amount_to_write;
if (num_bytes > kMemTransferLimit) {
amount_to_write = kMemTransferLimit;
} else {
amount_to_write = num_bytes;
}
Write(addr, reinterpret_cast<const void*>(curr_buf_ptr), amount_to_write);
addr += amount_to_write;
curr_buf_ptr += amount_to_write;
num_bytes -= amount_to_write;
}
return;
}
// Clear `input` array.
socket_.cmd_builder() << "array unset input";
socket_.SendCommand();
// Build a command to set the value of `input`.
{
std::ostringstream& cmd_builder = socket_.cmd_builder();
cmd_builder << "array set input {";
const char* char_buf = reinterpret_cast<const char*>(buf);
for (size_t i = 0; i < num_bytes; i++) {
// In a Tcl `array set` commmand, we need to pair the array indices with
// their values.
cmd_builder << i << " ";
// Need to cast to uint, so the number representation of `buf[i]` is
// printed, and not the ASCII representation.
cmd_builder << static_cast<uint32_t>(char_buf[i]) << " ";
}
cmd_builder << "}";
socket_.SendCommand();
}
{
socket_.cmd_builder()
<< "array2mem input"
<< " " << std::dec << kWordSize
<< " " << addr.cast_to<void*>()
<< " " << std::dec << num_bytes;
socket_.SendCommand();
}
}
void Execute(TargetPtr func_addr, TargetPtr breakpoint_addr) override {
socket_.cmd_builder() << "halt 0";
socket_.SendCommand();
// Set a breakpoint at the beginning of `UTVMDone`.
socket_.cmd_builder() << "bp " << breakpoint_addr.cast_to<void*>() << " 2";
socket_.SendCommand();
socket_.cmd_builder() << "resume " << func_addr.cast_to<void*>();
socket_.SendCommand();
socket_.cmd_builder() << "wait_halt " << kWaitTime;
socket_.SendCommand();
socket_.cmd_builder() << "halt 0";
socket_.SendCommand();
// Remove the breakpoint.
socket_.cmd_builder() << "rbp " << breakpoint_addr.cast_to<void*>();
socket_.SendCommand();
}
const char* device_type() const final {
return "openocd";
}
private:
/*! \brief socket used to communicate with the device through Tcl */
TclSocket socket_;
/*! \brief address of OpenOCD server */
std::string server_addr_;
/*! \brief port of OpenOCD server */
int port_;
/*! \brief number of bytes in a word on the target device (64-bit) */
static const constexpr ssize_t kWordSize = 8;
// NOTE: The OS pipe buffer must be able to handle a line long enough to
// print this transfer request.
/*! \brief maximum number of bytes allowed in a single memory transfer */
static const constexpr ssize_t kMemTransferLimit = 8000;
/*! \brief number of milliseconds to wait for function execution to halt */
static const constexpr int kWaitTime = 30000;
};
const std::shared_ptr<LowLevelDevice> OpenOCDLowLevelDeviceCreate(const std::string& server_addr,
int port) {
std::shared_ptr<LowLevelDevice> lld =
std::make_shared<OpenOCDLowLevelDevice>(server_addr, port);
return lld;
}
} // namespace runtime
} // namespace tvm
<|endoftext|> |
<commit_before>#ifndef STAN__MATH__ERROR_HANDLING_CHECK_FINITE_HPP
#define STAN__MATH__ERROR_HANDLING_CHECK_FINITE_HPP
#include <stan/math/error_handling/dom_err.hpp>
#include <stan/math/error_handling/dom_err_vec.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/meta/traits.hpp>
namespace stan {
namespace math {
namespace {
template <typename T_y,
typename T_result,
bool is_vec>
struct finite {
static bool check(const char* function,
const T_y& y,
const char* name,
T_result* result) {
if (!(boost::math::isfinite)(y))
return dom_err(function,y,name,
" is %1%, but must be finite!","",
result);
return true;
}
};
template <typename T_y, typename T_result>
struct finite<T_y, T_result, true> {
static bool check(const char* function,
const T_y& y,
const char* name,
T_result* result) {
using stan::length;
for (size_t n = 0; n < length(y); n++) {
if (!(boost::math::isfinite)(stan::get(y,n)))
return dom_err_vec(n,function,y,name,
" is %1%, but must be finite!","",
result);
}
return true;
}
};
}
/**
* Checks if the variable y is finite.
*/
template <typename T_y, typename T_result>
inline bool check_finite(const char* function,
const T_y& y,
const char* name,
T_result* result) {
return finite<T_y,T_result,is_vector_like<T_y>::value>
::check(function, y, name, result);
}
}
}
#endif
<commit_msg>added doc in code for check_finite<commit_after>#ifndef STAN__MATH__ERROR_HANDLING_CHECK_FINITE_HPP
#define STAN__MATH__ERROR_HANDLING_CHECK_FINITE_HPP
#include <stan/math/error_handling/dom_err.hpp>
#include <stan/math/error_handling/dom_err_vec.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/meta/traits.hpp>
namespace stan {
namespace math {
namespace {
template <typename T_y,
typename T_result,
bool is_vec>
struct finite {
static bool check(const char* function,
const T_y& y,
const char* name,
T_result* result) {
if (!(boost::math::isfinite)(y))
return dom_err(function,y,name,
" is %1%, but must be finite!","",
result);
return true;
}
};
template <typename T_y, typename T_result>
struct finite<T_y, T_result, true> {
static bool check(const char* function,
const T_y& y,
const char* name,
T_result* result) {
using stan::length;
for (size_t n = 0; n < length(y); n++) {
if (!(boost::math::isfinite)(stan::get(y,n)))
return dom_err_vec(n,function,y,name,
" is %1%, but must be finite!","",
result);
}
return true;
}
};
}
/**
* Checks if the variable y is finite.
* NOTE: throws if any element in y is nan.
*/
template <typename T_y, typename T_result>
inline bool check_finite(const char* function,
const T_y& y,
const char* name,
T_result* result) {
return finite<T_y,T_result,is_vector_like<T_y>::value>
::check(function, y, name, result);
}
}
}
#endif
<|endoftext|> |
<commit_before>/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_PROPERTYLIST_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Tag/File_PropertyList.h"
#include <cstring>
#include "tinyxml2.h"
using namespace tinyxml2;
using namespace std;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Buffer - File header
//***************************************************************************
//---------------------------------------------------------------------------
const char* PropertyList_key(const string &key)
{
if (key=="director" || key=="directors")
return "Director";
if (key=="codirector" || key=="codirectors")
return "CoDirector";
if (key=="producer" || key=="producers")
return "Producer";
if (key=="coproducer" || key=="coproducers")
return "CoProducer";
if (key=="screenwriter" || key=="screenwriters")
return "ScreenplayBy";
if (key=="studio" || key=="studios")
return "ProductionStudio";
}
//***************************************************************************
// Buffer - File header
//***************************************************************************
//---------------------------------------------------------------------------
bool File_PropertyList::FileHeader_Begin()
{
XMLDocument document;
if (!FileHeader_Begin_XML(document))
return false;
std::string NameSpace;
XMLElement* plist=document.FirstChildElement("plist");
if (!plist)
{
Reject("XMP");
return false;
}
XMLElement* dict=plist->FirstChildElement("dict");
if (!dict)
{
Reject("XMP");
return false;
}
Accept("PropertyList");
string key;
for (XMLElement* dict_Item=dict->FirstChildElement(); dict_Item; dict_Item=dict_Item->NextSiblingElement())
{
//key
if (!strcmp(dict_Item->Value(), "key"))
{
const char* Text=dict_Item->GetText();
if (Text)
key=Text;
}
//string
if (!strcmp(dict_Item->Value(), "string"))
{
const char* Text=dict_Item->GetText();
if (Text)
Fill(Stream_General, 0, PropertyList_key(key), Text);
key.clear();
}
//string
if (!strcmp(dict_Item->Value(), "array"))
{
for (XMLElement* array_Item=dict_Item->FirstChildElement(); array_Item; array_Item=array_Item->NextSiblingElement())
{
//dict
if (!strcmp(array_Item->Value(), "dict"))
{
string key2;
for (XMLElement* dict2_Item=array_Item->FirstChildElement(); dict2_Item; dict2_Item=dict2_Item->NextSiblingElement())
{
//key
if (!strcmp(dict2_Item->Value(), "key"))
{
const char* Text=dict2_Item->GetText();
if (Text)
key2=Text;
}
//string
if (!strcmp(dict2_Item->Value(), "string"))
{
const char* Text2=dict2_Item->GetText();
if (Text2)
Fill(Stream_General, 0, key2=="name"?PropertyList_key(key):((string(PropertyList_key(key))+", "+key2).c_str()), Text2);
key2.clear();
}
}
}
}
key.clear();
}
}
Finish();
return true;
}
} //NameSpace
#endif //MEDIAINFO_PROPERTYLIST_YES
<commit_msg>+ MOV/MPEG-4: basic support of iTunMOVI tag, update<commit_after>/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_PROPERTYLIST_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Tag/File_PropertyList.h"
#include <cstring>
#include "tinyxml2.h"
using namespace tinyxml2;
using namespace std;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Buffer - File header
//***************************************************************************
//---------------------------------------------------------------------------
const char* PropertyList_key(const string &key)
{
if (key=="director" || key=="directors")
return "Director";
if (key=="codirector" || key=="codirectors")
return "CoDirector";
if (key=="producer" || key=="producers")
return "Producer";
if (key=="coproducer" || key=="coproducers")
return "CoProducer";
if (key=="screenwriter" || key=="screenwriters")
return "ScreenplayBy";
if (key=="studio" || key=="studios")
return "ProductionStudio";
if (key=="cast")
return "Actor";
return key.c_str();
}
//***************************************************************************
// Buffer - File header
//***************************************************************************
//---------------------------------------------------------------------------
bool File_PropertyList::FileHeader_Begin()
{
XMLDocument document;
if (!FileHeader_Begin_XML(document))
return false;
std::string NameSpace;
XMLElement* plist=document.FirstChildElement("plist");
if (!plist)
{
Reject("XMP");
return false;
}
XMLElement* dict=plist->FirstChildElement("dict");
if (!dict)
{
Reject("XMP");
return false;
}
Accept("PropertyList");
string key;
for (XMLElement* dict_Item=dict->FirstChildElement(); dict_Item; dict_Item=dict_Item->NextSiblingElement())
{
//key
if (!strcmp(dict_Item->Value(), "key"))
{
const char* Text=dict_Item->GetText();
if (Text)
key=Text;
}
//string
if (!strcmp(dict_Item->Value(), "string"))
{
const char* Text=dict_Item->GetText();
if (Text)
Fill(Stream_General, 0, PropertyList_key(key), Text);
key.clear();
}
//string
if (!strcmp(dict_Item->Value(), "array"))
{
for (XMLElement* array_Item=dict_Item->FirstChildElement(); array_Item; array_Item=array_Item->NextSiblingElement())
{
//dict
if (!strcmp(array_Item->Value(), "dict"))
{
string key2;
for (XMLElement* dict2_Item=array_Item->FirstChildElement(); dict2_Item; dict2_Item=dict2_Item->NextSiblingElement())
{
//key
if (!strcmp(dict2_Item->Value(), "key"))
{
const char* Text=dict2_Item->GetText();
if (Text)
key2=Text;
}
//string
if (!strcmp(dict2_Item->Value(), "string"))
{
const char* Text2=dict2_Item->GetText();
if (Text2)
Fill(Stream_General, 0, key2=="name"?PropertyList_key(key):((string(PropertyList_key(key))+", "+key2).c_str()), Text2);
key2.clear();
}
}
}
}
key.clear();
}
}
Finish();
return true;
}
} //NameSpace
#endif //MEDIAINFO_PROPERTYLIST_YES
<|endoftext|> |
<commit_before>/*
File lockunlock.cpp
*/
/***************************************************************************
FET
-------------------
copyright : (C) by Lalescu Liviu
email : Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************
lockunlock.cpp - description
-------------------
begin : Dec 2008
copyright : (C) by Liviu Lalescu (http://lalescu.ro/liviu/) and Volker Dirr (http://www.timetabling.de/)
***************************************************************************
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#include "lockunlock.h"
#include "timetable.h"
extern Timetable gt;
QSet<int> idsOfLockedTime;
QSet<int> idsOfLockedSpace;
QSet<int> idsOfPermanentlyLockedTime;
QSet<int> idsOfPermanentlyLockedSpace;
CommunicationSpinBox communicationSpinBox;
CommunicationSpinBox::CommunicationSpinBox()
{
}
void CommunicationSpinBox::increaseValue()
{
emit(valueChanged());
}
void LockUnlock::computeLockedUnlockedActivitiesTimeSpace()
{
//by Volker Dirr
idsOfLockedTime.clear();
idsOfLockedSpace.clear();
idsOfPermanentlyLockedTime.clear();
idsOfPermanentlyLockedSpace.clear();
foreach(TimeConstraint* tc, gt.rules.timeConstraintsList){
if(tc->type==CONSTRAINT_ACTIVITY_PREFERRED_STARTING_TIME && tc->weightPercentage==100.0 && tc->active){
ConstraintActivityPreferredStartingTime* c=(ConstraintActivityPreferredStartingTime*) tc;
if(c->day >= 0 && c->hour >= 0) {
if(c->permanentlyLocked)
idsOfPermanentlyLockedTime.insert(c->activityId);
else
idsOfLockedTime.insert(c->activityId);
}
}
}
foreach(SpaceConstraint* sc, gt.rules.spaceConstraintsList){
if(sc->type==CONSTRAINT_ACTIVITY_PREFERRED_ROOM && sc->weightPercentage==100.0 && sc->active){
ConstraintActivityPreferredRoom* c=(ConstraintActivityPreferredRoom*) sc;
if(c->permanentlyLocked)
idsOfPermanentlyLockedSpace.insert(c->activityId);
else
idsOfLockedSpace.insert(c->activityId);
}
}
}
void LockUnlock::computeLockedUnlockedActivitiesOnlyTime()
{
//by Volker Dirr
idsOfLockedTime.clear();
idsOfPermanentlyLockedTime.clear();
foreach(TimeConstraint* tc, gt.rules.timeConstraintsList){
if(tc->type==CONSTRAINT_ACTIVITY_PREFERRED_STARTING_TIME && tc->weightPercentage==100.0 && tc->active){
ConstraintActivityPreferredStartingTime* c=(ConstraintActivityPreferredStartingTime*) tc;
if(c->day >= 0 && c->hour >= 0) {
if(c->permanentlyLocked)
idsOfPermanentlyLockedTime.insert(c->activityId);
else
idsOfLockedTime.insert(c->activityId);
}
}
}
}
void LockUnlock::computeLockedUnlockedActivitiesOnlySpace()
{
//by Volker Dirr
idsOfLockedSpace.clear();
idsOfPermanentlyLockedSpace.clear();
foreach(SpaceConstraint* sc, gt.rules.spaceConstraintsList){
if(sc->type==CONSTRAINT_ACTIVITY_PREFERRED_ROOM && sc->weightPercentage==100.0 && sc->active){
ConstraintActivityPreferredRoom* c=(ConstraintActivityPreferredRoom*) sc;
if(c->permanentlyLocked)
idsOfPermanentlyLockedSpace.insert(c->activityId);
else
idsOfLockedSpace.insert(c->activityId);
}
}
}
void LockUnlock::increaseCommunicationSpinBox()
{
communicationSpinBox.increaseValue();
}
<commit_msg>make use of shared code in lockunlock and add constness<commit_after>/*
File lockunlock.cpp
*/
/***************************************************************************
FET
-------------------
copyright : (C) by Lalescu Liviu
email : Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************
lockunlock.cpp - description
-------------------
begin : Dec 2008
copyright : (C) by Liviu Lalescu (http://lalescu.ro/liviu/) and Volker Dirr (http://www.timetabling.de/)
***************************************************************************
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#include "lockunlock.h"
#include "timetable.h"
extern Timetable gt;
QSet<int> idsOfLockedTime;
QSet<int> idsOfLockedSpace;
QSet<int> idsOfPermanentlyLockedTime;
QSet<int> idsOfPermanentlyLockedSpace;
CommunicationSpinBox communicationSpinBox;
CommunicationSpinBox::CommunicationSpinBox()
{
}
void CommunicationSpinBox::increaseValue()
{
emit(valueChanged());
}
void LockUnlock::computeLockedUnlockedActivitiesTimeSpace()
{
computeLockedUnlockedActivitiesOnlyTime();
computeLockedUnlockedActivitiesOnlySpace();
}
void LockUnlock::computeLockedUnlockedActivitiesOnlyTime()
{
//by Volker Dirr
idsOfLockedTime.clear();
idsOfPermanentlyLockedTime.clear();
foreach(const TimeConstraint* tc, gt.rules.timeConstraintsList){
if(tc->type==CONSTRAINT_ACTIVITY_PREFERRED_STARTING_TIME && tc->weightPercentage==100.0 && tc->active){
const ConstraintActivityPreferredStartingTime* c=(const ConstraintActivityPreferredStartingTime*) tc;
if(c->day >= 0 && c->hour >= 0) {
if(c->permanentlyLocked)
idsOfPermanentlyLockedTime.insert(c->activityId);
else
idsOfLockedTime.insert(c->activityId);
}
}
}
}
void LockUnlock::computeLockedUnlockedActivitiesOnlySpace()
{
//by Volker Dirr
idsOfLockedSpace.clear();
idsOfPermanentlyLockedSpace.clear();
foreach(const SpaceConstraint* sc, gt.rules.spaceConstraintsList){
if(sc->type==CONSTRAINT_ACTIVITY_PREFERRED_ROOM && sc->weightPercentage==100.0 && sc->active){
const ConstraintActivityPreferredRoom* c=(const ConstraintActivityPreferredRoom*) sc;
if(c->permanentlyLocked)
idsOfPermanentlyLockedSpace.insert(c->activityId);
else
idsOfLockedSpace.insert(c->activityId);
}
}
}
void LockUnlock::increaseCommunicationSpinBox()
{
communicationSpinBox.increaseValue();
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// 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 "Volume.h"
#include "../common/Model.h"
// core ospray
#include "ospray/common/OSPCommon.h"
namespace ospray {
namespace sg {
/*! helper function to help build voxel ranges during parsing */
template<typename T>
inline void extendVoxelRange(ospcommon::vec2f &voxelRange,
const T *voxel, size_t num)
{
for (size_t i = 0; i < num; ++i) {
if (!std::isnan(static_cast<float>(voxel[i]))) {
voxelRange.x = std::min(voxelRange.x, static_cast<float>(voxel[i]));
voxelRange.y = std::max(voxelRange.y, static_cast<float>(voxel[i]));
}
}
}
//! Convenient wrapper that will do the template dispatch for you based on
// the voxelType passed
inline void extendVoxelRange(ospcommon::vec2f &voxelRange,
const OSPDataType voxelType,
const unsigned char *voxels,
const size_t numVoxels)
{
switch (voxelType) {
case OSP_UCHAR:
extendVoxelRange(voxelRange, voxels, numVoxels);
break;
case OSP_SHORT:
extendVoxelRange(voxelRange,
reinterpret_cast<const short*>(voxels),
numVoxels);
break;
case OSP_USHORT:
extendVoxelRange(voxelRange,
reinterpret_cast<const unsigned short*>(voxels),
numVoxels);
break;
case OSP_FLOAT:
extendVoxelRange(voxelRange,
reinterpret_cast<const float*>(voxels),
numVoxels);
break;
case OSP_DOUBLE:
extendVoxelRange(voxelRange,
reinterpret_cast<const double*>(voxels),
numVoxels);
break;
default:
throw std::runtime_error("sg::extendVoxelRange: unsupported voxel type!");
}
}
bool unsupportedVoxelType(const std::string &type) {
return type != "uchar" && type != "ushort" && type != "short"
&& type != "float" && type != "double";
}
// =======================================================
// base volume class
// =======================================================
Volume::Volume()
{
setValue((OSPVolume)nullptr);
createChild("transferFunction", "TransferFunction");
createChild("gradientShadingEnabled", "bool", true);
createChild("preIntegration", "bool", false);
createChild("singleShade", "bool", true);
createChild("voxelRange", "vec2f",
vec2f(std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity()));
createChild("adaptiveSampling", "bool", true);
createChild("adaptiveScalar", "float", 15.f);
createChild("adaptiveBacktrack", "float", 0.03f);
createChild("samplingRate", "float", 0.06f);
createChild("adaptiveMaxSamplingRate", "float", 0.5f);
createChild("volumeClippingBoxLower", "vec3f", vec3f(0.f));
createChild("volumeClippingBoxUpper", "vec3f", vec3f(0.f));
createChild("specular", "vec3f", vec3f(0.3f));
createChild("ns", "float", 20.f);
createChild("gridOrigin", "vec3f", vec3f(0.0f));
createChild("gridSpacing", "vec3f", vec3f(1.f));
createChild("isosurfaceEnabled", "bool", false);
createChild("isosurface", "float",
-std::numeric_limits<float>::infinity(),
NodeFlags::valid_min_max |
NodeFlags::gui_slider).setMinMax(0.f,255.f);
}
std::string Volume::toString() const
{
return "ospray::sg::Volume";
}
void Volume::serialize(sg::Serialization::State &state)
{
Node::serialize(state);
}
void Volume::postCommit(RenderContext &)
{
auto ospVolume = valueAs<OSPVolume>();
ospSetObject(ospVolume, "transferFunction",
child("transferFunction").valueAs<OSPTransferFunction>());
ospCommit(ospVolume);
}
void Volume::postRender(RenderContext &ctx)
{
auto ospVolume = valueAs<OSPVolume>();
if (ospVolume) {
ospAddVolume(ctx.world->valueAs<OSPModel>(), ospVolume);
if (child("isosurfaceEnabled").valueAs<bool>() && isosurfacesGeometry)
ospAddGeometry(ctx.world->valueAs<OSPModel>(), isosurfacesGeometry);
}
}
// =======================================================
// structured volume class
// =======================================================
StructuredVolume::StructuredVolume()
{
createChild("dimensions", "vec3i", NodeFlags::gui_readonly);
createChild("voxelType", "string",
std::string("<undefined>"), NodeFlags::gui_readonly);
}
/*! \brief returns a std::string with the c++ name of this class */
std::string StructuredVolume::toString() const
{
return "ospray::sg::StructuredVolume";
}
//! return bounding box of all primitives
box3f StructuredVolume::bounds() const
{
auto dimensions = child("dimensions").valueAs<vec3i>();
auto gridSpacing = child("gridSpacing").valueAs<vec3f>();
return {vec3f(0.f), dimensions * gridSpacing};
}
void StructuredVolume::preCommit(RenderContext &)
{
auto ospVolume = valueAs<OSPVolume>();
if (ospVolume) {
ospCommit(ospVolume);
if (child("isosurfaceEnabled").valueAs<bool>() == true
&& isosurfacesGeometry) {
OSPData isovaluesData = ospNewData(1, OSP_FLOAT,
&child("isosurface").valueAs<float>());
ospSetData(isosurfacesGeometry, "isovalues", isovaluesData);
ospCommit(isosurfacesGeometry);
}
return;
}
auto voxelType = child("voxelType").valueAs<std::string>();
auto dimensions = child("dimensions").valueAs<vec3i>();
if (dimensions.x <= 0 || dimensions.y <= 0 || dimensions.z <= 0) {
throw std::runtime_error("StructuredVolume::render(): "
"invalid volume dimensions");
}
ospVolume = ospNewVolume("shared_structured_volume");
setValue(ospVolume);
isosurfacesGeometry = ospNewGeometry("isosurfaces");
ospSetObject(isosurfacesGeometry, "volume", ospVolume);
vec2f voxelRange(std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity());
const OSPDataType ospVoxelType = typeForString(voxelType);
const size_t nVoxels =
(size_t)dimensions.x * (size_t)dimensions.y * (size_t)dimensions.z;
auto voxels_data_node = child("voxelData").nodeAs<DataBuffer>();
auto *voxels = static_cast<uint8_t*>(voxels_data_node->base());
extendVoxelRange(voxelRange, ospVoxelType, voxels, nVoxels);
child("voxelRange") = voxelRange;
child("transferFunction")["valueRange"] = voxelRange;
child("isosurface").setMinMax(voxelRange.x, voxelRange.y);
float iso = child("isosurface").valueAs<float>();
if (iso < voxelRange.x || iso > voxelRange.y)
child("isosurface") = (voxelRange.y - voxelRange.x) / 2.f;
}
OSP_REGISTER_SG_NODE(StructuredVolume);
// =======================================================
// structured volume that is stored in a separate file (ie, a file
// other than the ospbin file)
// =======================================================
StructuredVolumeFromFile::StructuredVolumeFromFile()
{
createChild("blockBricked", "bool", true, NodeFlags::gui_readonly);
}
/*! \brief returns a std::string with the c++ name of this class */
std::string StructuredVolumeFromFile::toString() const
{
return "ospray::sg::StructuredVolumeFromFile";
}
void StructuredVolumeFromFile::preCommit(RenderContext &)
{
auto ospVolume = valueAs<OSPVolume>();
if (ospVolume) {
ospCommit(ospVolume);
if (child("isosurfaceEnabled").valueAs<bool>() == true
&& isosurfacesGeometry) {
OSPData isovaluesData = ospNewData(1, OSP_FLOAT,
&child("isosurface").valueAs<float>());
ospSetData(isosurfacesGeometry, "isovalues", isovaluesData);
ospCommit(isosurfacesGeometry);
}
return;
}
bool useBlockBricked = child("blockBricked").valueAs<bool>();
ospVolume = ospNewVolume(useBlockBricked ? "block_bricked_volume" :
"shared_structured_volume");
setValue(ospVolume);
}
void StructuredVolumeFromFile::postCommit(RenderContext &ctx)
{
auto ospVolume = valueAs<OSPVolume>();
auto dimensions = child("dimensions").valueAs<vec3i>();
if (dimensions.x <= 0 || dimensions.y <= 0 || dimensions.z <= 0) {
throw std::runtime_error("StructuredVolume::render(): "
"invalid volume dimensions");
}
if (!fileLoaded) {
auto voxelType = child("voxelType").valueAs<std::string>();
isosurfacesGeometry = ospNewGeometry("isosurfaces");
ospSetObject(isosurfacesGeometry, "volume", ospVolume);
FileName realFileName = fileNameOfCorrespondingXmlDoc.path() + fileName;
FILE *file = fopen(realFileName.c_str(),"rb");
if (!file) {
throw std::runtime_error("StructuredVolumeFromFile::render(): could not open file '"
+realFileName.str()+"' (expanded from xml file '"
+fileNameOfCorrespondingXmlDoc.str()
+"' and file name '"+fileName+"')");
}
vec2f voxelRange(std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity());
const OSPDataType ospVoxelType = typeForString(voxelType);
const size_t voxelSize = sizeOf(ospVoxelType);
bool useBlockBricked = child("blockBricked").valueAs<bool>();
if (useBlockBricked) {
const size_t nPerSlice = (size_t)dimensions.x * (size_t)dimensions.y;
std::vector<uint8_t> slice(nPerSlice * voxelSize, 0);
for (int z = 0; z < dimensions.z; ++z) {
if (fread(slice.data(), voxelSize, nPerSlice, file) != nPerSlice) {
throw std::runtime_error("StructuredVolume::render(): read incomplete slice "
"data ... partial file or wrong format!?");
}
const vec3i region_lo(0, 0, z);
const vec3i region_sz(dimensions.x, dimensions.y, 1);
extendVoxelRange(voxelRange, ospVoxelType, slice.data(), nPerSlice);
ospSetRegion(ospVolume,
slice.data(),
(const osp::vec3i&)region_lo,
(const osp::vec3i&)region_sz);
}
} else {
const size_t nVoxels = (size_t)dimensions.x * (size_t)dimensions.y * (size_t)dimensions.z;
uint8_t *voxels = new uint8_t[nVoxels * voxelSize];
if (fread(voxels, voxelSize, nVoxels, file) != nVoxels) {
THROW_SG_ERROR("read incomplete data (truncated file or "
"wrong format?!)");
}
extendVoxelRange(voxelRange, ospVoxelType, voxels, nVoxels);
OSPData data = ospNewData(nVoxels, ospVoxelType, voxels, OSP_DATA_SHARED_BUFFER);
ospSetData(ospVolume,"voxelData",data);
}
fclose(file);
child("voxelRange") = voxelRange;
child("transferFunction")["valueRange"] = voxelRange;
child("isosurface").setMinMax(voxelRange.x, voxelRange.y);
float iso = child("isosurface").valueAs<float>();
if (iso < voxelRange.x || iso > voxelRange.y)
child("isosurface") = (voxelRange.y - voxelRange.x) / 2.f;
fileLoaded = true;
// Double ugly: This is re-done by postCommit, but we need to
// do it here so the transferFunction is set before we commit the
// volume, so that it's in a valid state.
ospSetObject(ospVolume, "transferFunction",
child("transferFunction").valueAs<OSPTransferFunction>());
commit(); //<-- UGLY, recommitting the volume after child changes...
}
Volume::postCommit(ctx);
}
OSP_REGISTER_SG_NODE(StructuredVolumeFromFile);
} // ::ospray::sg
} // ::ospray
<commit_msg>removing valid check on isosurface values<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// 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 "Volume.h"
#include "../common/Model.h"
// core ospray
#include "ospray/common/OSPCommon.h"
namespace ospray {
namespace sg {
/*! helper function to help build voxel ranges during parsing */
template<typename T>
inline void extendVoxelRange(ospcommon::vec2f &voxelRange,
const T *voxel, size_t num)
{
for (size_t i = 0; i < num; ++i) {
if (!std::isnan(static_cast<float>(voxel[i]))) {
voxelRange.x = std::min(voxelRange.x, static_cast<float>(voxel[i]));
voxelRange.y = std::max(voxelRange.y, static_cast<float>(voxel[i]));
}
}
}
//! Convenient wrapper that will do the template dispatch for you based on
// the voxelType passed
inline void extendVoxelRange(ospcommon::vec2f &voxelRange,
const OSPDataType voxelType,
const unsigned char *voxels,
const size_t numVoxels)
{
switch (voxelType) {
case OSP_UCHAR:
extendVoxelRange(voxelRange, voxels, numVoxels);
break;
case OSP_SHORT:
extendVoxelRange(voxelRange,
reinterpret_cast<const short*>(voxels),
numVoxels);
break;
case OSP_USHORT:
extendVoxelRange(voxelRange,
reinterpret_cast<const unsigned short*>(voxels),
numVoxels);
break;
case OSP_FLOAT:
extendVoxelRange(voxelRange,
reinterpret_cast<const float*>(voxels),
numVoxels);
break;
case OSP_DOUBLE:
extendVoxelRange(voxelRange,
reinterpret_cast<const double*>(voxels),
numVoxels);
break;
default:
throw std::runtime_error("sg::extendVoxelRange: unsupported voxel type!");
}
}
bool unsupportedVoxelType(const std::string &type) {
return type != "uchar" && type != "ushort" && type != "short"
&& type != "float" && type != "double";
}
// =======================================================
// base volume class
// =======================================================
Volume::Volume()
{
setValue((OSPVolume)nullptr);
createChild("transferFunction", "TransferFunction");
createChild("gradientShadingEnabled", "bool", true);
createChild("preIntegration", "bool", false);
createChild("singleShade", "bool", true);
createChild("voxelRange", "vec2f",
vec2f(std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity()));
createChild("adaptiveSampling", "bool", true);
createChild("adaptiveScalar", "float", 15.f);
createChild("adaptiveBacktrack", "float", 0.03f);
createChild("samplingRate", "float", 0.06f);
createChild("adaptiveMaxSamplingRate", "float", 0.5f);
createChild("volumeClippingBoxLower", "vec3f", vec3f(0.f));
createChild("volumeClippingBoxUpper", "vec3f", vec3f(0.f));
createChild("specular", "vec3f", vec3f(0.3f));
createChild("ns", "float", 20.f);
createChild("gridOrigin", "vec3f", vec3f(0.0f));
createChild("gridSpacing", "vec3f", vec3f(1.f));
createChild("isosurfaceEnabled", "bool", false);
createChild("isosurface", "float",
128.f,
NodeFlags::gui_slider).setMinMax(0.f,255.f);
}
std::string Volume::toString() const
{
return "ospray::sg::Volume";
}
void Volume::serialize(sg::Serialization::State &state)
{
Node::serialize(state);
}
void Volume::postCommit(RenderContext &)
{
auto ospVolume = valueAs<OSPVolume>();
ospSetObject(ospVolume, "transferFunction",
child("transferFunction").valueAs<OSPTransferFunction>());
ospCommit(ospVolume);
}
void Volume::postRender(RenderContext &ctx)
{
auto ospVolume = valueAs<OSPVolume>();
if (ospVolume) {
ospAddVolume(ctx.world->valueAs<OSPModel>(), ospVolume);
if (child("isosurfaceEnabled").valueAs<bool>() && isosurfacesGeometry)
ospAddGeometry(ctx.world->valueAs<OSPModel>(), isosurfacesGeometry);
}
}
// =======================================================
// structured volume class
// =======================================================
StructuredVolume::StructuredVolume()
{
createChild("dimensions", "vec3i", NodeFlags::gui_readonly);
createChild("voxelType", "string",
std::string("<undefined>"), NodeFlags::gui_readonly);
}
/*! \brief returns a std::string with the c++ name of this class */
std::string StructuredVolume::toString() const
{
return "ospray::sg::StructuredVolume";
}
//! return bounding box of all primitives
box3f StructuredVolume::bounds() const
{
auto dimensions = child("dimensions").valueAs<vec3i>();
auto gridSpacing = child("gridSpacing").valueAs<vec3f>();
return {vec3f(0.f), dimensions * gridSpacing};
}
void StructuredVolume::preCommit(RenderContext &)
{
auto ospVolume = valueAs<OSPVolume>();
if (ospVolume) {
ospCommit(ospVolume);
if (child("isosurfaceEnabled").valueAs<bool>() == true
&& isosurfacesGeometry) {
OSPData isovaluesData = ospNewData(1, OSP_FLOAT,
&child("isosurface").valueAs<float>());
ospSetData(isosurfacesGeometry, "isovalues", isovaluesData);
ospCommit(isosurfacesGeometry);
}
return;
}
auto voxelType = child("voxelType").valueAs<std::string>();
auto dimensions = child("dimensions").valueAs<vec3i>();
if (dimensions.x <= 0 || dimensions.y <= 0 || dimensions.z <= 0) {
throw std::runtime_error("StructuredVolume::render(): "
"invalid volume dimensions");
}
ospVolume = ospNewVolume("shared_structured_volume");
setValue(ospVolume);
isosurfacesGeometry = ospNewGeometry("isosurfaces");
ospSetObject(isosurfacesGeometry, "volume", ospVolume);
vec2f voxelRange(std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity());
const OSPDataType ospVoxelType = typeForString(voxelType);
const size_t nVoxels =
(size_t)dimensions.x * (size_t)dimensions.y * (size_t)dimensions.z;
auto voxels_data_node = child("voxelData").nodeAs<DataBuffer>();
auto *voxels = static_cast<uint8_t*>(voxels_data_node->base());
extendVoxelRange(voxelRange, ospVoxelType, voxels, nVoxels);
child("voxelRange") = voxelRange;
child("transferFunction")["valueRange"] = voxelRange;
child("isosurface").setMinMax(voxelRange.x, voxelRange.y);
float iso = child("isosurface").valueAs<float>();
if (iso < voxelRange.x || iso > voxelRange.y)
child("isosurface") = (voxelRange.y - voxelRange.x) / 2.f;
}
OSP_REGISTER_SG_NODE(StructuredVolume);
// =======================================================
// structured volume that is stored in a separate file (ie, a file
// other than the ospbin file)
// =======================================================
StructuredVolumeFromFile::StructuredVolumeFromFile()
{
createChild("blockBricked", "bool", true, NodeFlags::gui_readonly);
}
/*! \brief returns a std::string with the c++ name of this class */
std::string StructuredVolumeFromFile::toString() const
{
return "ospray::sg::StructuredVolumeFromFile";
}
void StructuredVolumeFromFile::preCommit(RenderContext &)
{
auto ospVolume = valueAs<OSPVolume>();
if (ospVolume) {
ospCommit(ospVolume);
if (child("isosurfaceEnabled").valueAs<bool>() == true
&& isosurfacesGeometry) {
OSPData isovaluesData = ospNewData(1, OSP_FLOAT,
&child("isosurface").valueAs<float>());
ospSetData(isosurfacesGeometry, "isovalues", isovaluesData);
ospCommit(isosurfacesGeometry);
}
return;
}
bool useBlockBricked = child("blockBricked").valueAs<bool>();
ospVolume = ospNewVolume(useBlockBricked ? "block_bricked_volume" :
"shared_structured_volume");
setValue(ospVolume);
}
void StructuredVolumeFromFile::postCommit(RenderContext &ctx)
{
auto ospVolume = valueAs<OSPVolume>();
auto dimensions = child("dimensions").valueAs<vec3i>();
if (dimensions.x <= 0 || dimensions.y <= 0 || dimensions.z <= 0) {
throw std::runtime_error("StructuredVolume::render(): "
"invalid volume dimensions");
}
if (!fileLoaded) {
auto voxelType = child("voxelType").valueAs<std::string>();
isosurfacesGeometry = ospNewGeometry("isosurfaces");
ospSetObject(isosurfacesGeometry, "volume", ospVolume);
FileName realFileName = fileNameOfCorrespondingXmlDoc.path() + fileName;
FILE *file = fopen(realFileName.c_str(),"rb");
if (!file) {
throw std::runtime_error("StructuredVolumeFromFile::render(): could not open file '"
+realFileName.str()+"' (expanded from xml file '"
+fileNameOfCorrespondingXmlDoc.str()
+"' and file name '"+fileName+"')");
}
vec2f voxelRange(std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity());
const OSPDataType ospVoxelType = typeForString(voxelType);
const size_t voxelSize = sizeOf(ospVoxelType);
bool useBlockBricked = child("blockBricked").valueAs<bool>();
if (useBlockBricked) {
const size_t nPerSlice = (size_t)dimensions.x * (size_t)dimensions.y;
std::vector<uint8_t> slice(nPerSlice * voxelSize, 0);
for (int z = 0; z < dimensions.z; ++z) {
if (fread(slice.data(), voxelSize, nPerSlice, file) != nPerSlice) {
throw std::runtime_error("StructuredVolume::render(): read incomplete slice "
"data ... partial file or wrong format!?");
}
const vec3i region_lo(0, 0, z);
const vec3i region_sz(dimensions.x, dimensions.y, 1);
extendVoxelRange(voxelRange, ospVoxelType, slice.data(), nPerSlice);
ospSetRegion(ospVolume,
slice.data(),
(const osp::vec3i&)region_lo,
(const osp::vec3i&)region_sz);
}
} else {
const size_t nVoxels = (size_t)dimensions.x * (size_t)dimensions.y * (size_t)dimensions.z;
uint8_t *voxels = new uint8_t[nVoxels * voxelSize];
if (fread(voxels, voxelSize, nVoxels, file) != nVoxels) {
THROW_SG_ERROR("read incomplete data (truncated file or "
"wrong format?!)");
}
extendVoxelRange(voxelRange, ospVoxelType, voxels, nVoxels);
OSPData data = ospNewData(nVoxels, ospVoxelType, voxels, OSP_DATA_SHARED_BUFFER);
ospSetData(ospVolume,"voxelData",data);
}
fclose(file);
child("voxelRange") = voxelRange;
child("transferFunction")["valueRange"] = voxelRange;
child("isosurface").setMinMax(voxelRange.x, voxelRange.y);
float iso = child("isosurface").valueAs<float>();
if (iso < voxelRange.x || iso > voxelRange.y)
child("isosurface") = (voxelRange.y - voxelRange.x) / 2.f;
fileLoaded = true;
// Double ugly: This is re-done by postCommit, but we need to
// do it here so the transferFunction is set before we commit the
// volume, so that it's in a valid state.
ospSetObject(ospVolume, "transferFunction",
child("transferFunction").valueAs<OSPTransferFunction>());
commit(); //<-- UGLY, recommitting the volume after child changes...
}
Volume::postCommit(ctx);
}
OSP_REGISTER_SG_NODE(StructuredVolumeFromFile);
} // ::ospray::sg
} // ::ospray
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* 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 <openspace/engine/logfactory.h>
#include <ghoul/logging/htmllog.h>
#include <ghoul/logging/textlog.h>
namespace {
const std::string _loggerCat = "LogFactory";
const std::string keyType = "Type";
const std::string keyFilename = "FileName";
const std::string keyAppend = "Append";
const std::string keyTimeStamping = "TimeStamping";
const std::string keyDateStamping = "DateStamping";
const std::string keyCategoryStamping = "CategoryStamping";
const std::string keyLogLevelStamping = "LogLevelStamping";
const std::string valueHtmlLog = "HTML";
const std::string valueTextLog = "Text";
}
namespace openspace {
ghoul::logging::Log* LogFactory::createLog(const ghoul::Dictionary& dictionary) {
std::string type;
bool typeSuccess = dictionary.getValue(keyType, type);
if (!typeSuccess) {
LERROR("Requested log did not contain a key '" << keyType << "'");
return nullptr;
}
std::string filename;
bool filenameSuccess = dictionary.getValue(keyFilename, filename);
if (!filenameSuccess) {
LERROR("Requested log of type '" << keyType << "' did not contain a key '"
<< keyFilename << "'");
return nullptr;
}
bool append = true;
dictionary.getValue(keyAppend, append);
bool timeStamp = true;
dictionary.getValue(keyTimeStamping, timeStamp);
bool dateStamp = true;
dictionary.getValue(keyDateStamping, dateStamp);
bool categoryStamp = true;
dictionary.getValue(keyCategoryStamping, categoryStamp);
bool logLevelStamp = true;
dictionary.getValue(keyLogLevelStamping, logLevelStamp);
if (type == valueHtmlLog) {
return new ghoul::logging::HTMLLog(
filename, timeStamp, dateStamp, categoryStamp, logLevelStamp);
}
else if (type == valueTextLog) {
return new ghoul::logging::TextLog(
filename, timeStamp, dateStamp, categoryStamp, logLevelStamp);
}
else {
LERROR("Log with type '" << type << "' did not name a valid log");
return nullptr;
}
}
} // namespace openspace
<commit_msg>Fixed path for LogFactory<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014 *
* *
* 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 <openspace/engine/logfactory.h>
#include <ghoul/logging/htmllog.h>
#include <ghoul/logging/textlog.h>
#include <ghoul/filesystem/filesystem.h>
namespace {
const std::string _loggerCat = "LogFactory";
const std::string keyType = "Type";
const std::string keyFilename = "FileName";
const std::string keyAppend = "Append";
const std::string keyTimeStamping = "TimeStamping";
const std::string keyDateStamping = "DateStamping";
const std::string keyCategoryStamping = "CategoryStamping";
const std::string keyLogLevelStamping = "LogLevelStamping";
const std::string valueHtmlLog = "HTML";
const std::string valueTextLog = "Text";
}
namespace openspace {
ghoul::logging::Log* LogFactory::createLog(const ghoul::Dictionary& dictionary) {
std::string type;
bool typeSuccess = dictionary.getValue(keyType, type);
if (!typeSuccess) {
LERROR("Requested log did not contain a key '" << keyType << "'");
return nullptr;
}
std::string filename;
bool filenameSuccess = dictionary.getValue(keyFilename, filename);
if (!filenameSuccess) {
LERROR("Requested log of type '" << keyType << "' did not contain a key '"
<< keyFilename << "'");
return nullptr;
}
filename = absPath(filename);
bool append = true;
dictionary.getValue(keyAppend, append);
bool timeStamp = true;
dictionary.getValue(keyTimeStamping, timeStamp);
bool dateStamp = true;
dictionary.getValue(keyDateStamping, dateStamp);
bool categoryStamp = true;
dictionary.getValue(keyCategoryStamping, categoryStamp);
bool logLevelStamp = true;
dictionary.getValue(keyLogLevelStamping, logLevelStamp);
if (type == valueHtmlLog) {
return new ghoul::logging::HTMLLog(
filename, timeStamp, dateStamp, categoryStamp, logLevelStamp);
}
else if (type == valueTextLog) {
return new ghoul::logging::TextLog(
filename, timeStamp, dateStamp, categoryStamp, logLevelStamp);
}
else {
LERROR("Log with type '" << type << "' did not name a valid log");
return nullptr;
}
}
} // namespace openspace
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
#include "etchosts.hh"
#include <algorithm>
#include <sstream>
using namespace::std;
Agent::Agent(su_root_t* root, const char *locaddr, int port) : mLocAddr(locaddr), mPort(port){
char sipuri[128]={0};
// compute a network wide unique id
std::ostringstream oss;
oss << locaddr << "_" << port;
mUniqueId = oss.str();
snprintf(sipuri,sizeof(sipuri)-1,"sip:%s:%i",locaddr,port);
mAgent=nta_agent_create(root,
(url_string_t*)sipuri,
&Agent::messageCallback,
(nta_agent_magic_t*)this,
TAG_END());
/* we pass "" as localaddr when we just want to dump the default config. So don't report the error*/
if (strlen(locaddr)>0 && mAgent==NULL){
LOGF("Could not create sofia mta.");
}
EtcHostsResolver::get();
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"NatHelper"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Authentication"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Registrar"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"ContactRouteInserter"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"MediaRelay"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Transcoder"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Forward"));
mServerString="Flexisip/"VERSION " (sofia-sip-nta/" NTA_VERSION ")";
for_each(mModules.begin(),mModules.end(),bind2nd(mem_fun(&Module::declare),
ConfigManager::get()->getRoot()));
}
Agent::~Agent(){
for_each(mModules.begin(),mModules.end(),delete_functor<Module>());
if (mAgent)
nta_agent_destroy(mAgent);
}
const char *Agent::getServerString()const{
return mServerString.c_str();
}
void Agent::loadConfig(ConfigManager *cm){
cm->loadStrict();//now that each module has declared its settings, we need to reload from the config file
mAliases=cm->getGlobal()->get<ConfigStringList>("aliases")->read();
LOGD("List of host aliases:");
for(list<string>::iterator it=mAliases.begin();it!=mAliases.end();++it){
LOGD("%s",(*it).c_str());
}
list<Module*>::iterator it;
for(it=mModules.begin();it!=mModules.end();++it)
(*it)->load(this);
}
void Agent::setDomain(const std::string &domain){
mDomain=domain;
}
int Agent::countUsInVia(sip_via_t *via)const{
int count = 0;
for (sip_via_t *v = via;v!=NULL;v=v->v_next){
if (isUs(v->v_host, v->v_port)) ++count;
}
return count;
}
bool Agent::isUs(const char *host, const char *port)const{
int p=(port!=NULL) ? atoi(port) : 5060;
if (p!=mPort) return false;
if (strcmp(host,mLocAddr.c_str())==0) return true;
list<string>::const_iterator it;
for(it=mAliases.begin();it!=mAliases.end();++it){
if (strcasecmp(host,(*it).c_str())==0) return true;
}
return false;
}
bool Agent::isUs(const url_t *url)const{
return isUs(url->url_host, url->url_port);
}
void Agent::onRequest(msg_t *msg, sip_t *sip){
list<Module*>::iterator it;
SipEvent ev(msg,sip);
for(it=mModules.begin();it!=mModules.end();++it){
(*it)->processRequest(&ev);
if (ev.finished()) break;
}
}
void Agent::onResponse(msg_t *msg, sip_t *sip){
list<Module*>::iterator it;
SipEvent ev(msg,sip);
for(it=mModules.begin();it!=mModules.end();++it){
(*it)->processResponse(&ev);
if (ev.finished()) break;
}
}
int Agent::onIncomingMessage(msg_t *msg, sip_t *sip){
su_home_t home;
size_t msg_size;
char *buf;
su_home_init(&home);
buf=msg_as_string(&home, msg, NULL, 0,&msg_size);
LOGD("Receiving new SIP message:\n%s",buf);
if (sip->sip_request)
onRequest(msg,sip);
else{
onResponse(msg,sip);
}
su_home_deinit(&home);
return 0;
}
int Agent::messageCallback(nta_agent_magic_t *context, nta_agent_t *agent,msg_t *msg,sip_t *sip){
Agent *a=(Agent*)context;
return a->onIncomingMessage(msg,sip);
}
void Agent::idle(){
for_each(mModules.begin(),mModules.end(),mem_fun(&Module::idle));
}
const std::string& Agent::getUniqueId() const{
return mUniqueId;
}
<commit_msg>fix loop because of '.' at the end of hostnames...<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
#include "etchosts.hh"
#include <algorithm>
#include <sstream>
using namespace::std;
Agent::Agent(su_root_t* root, const char *locaddr, int port) : mLocAddr(locaddr), mPort(port){
char sipuri[128]={0};
// compute a network wide unique id
std::ostringstream oss;
oss << locaddr << "_" << port;
mUniqueId = oss.str();
snprintf(sipuri,sizeof(sipuri)-1,"sip:%s:%i",locaddr,port);
mAgent=nta_agent_create(root,
(url_string_t*)sipuri,
&Agent::messageCallback,
(nta_agent_magic_t*)this,
TAG_END());
/* we pass "" as localaddr when we just want to dump the default config. So don't report the error*/
if (strlen(locaddr)>0 && mAgent==NULL){
LOGF("Could not create sofia mta.");
}
EtcHostsResolver::get();
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"NatHelper"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Authentication"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Registrar"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"ContactRouteInserter"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"MediaRelay"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Transcoder"));
mModules.push_back(ModuleFactory::get()->createModuleInstance(this,"Forward"));
mServerString="Flexisip/"VERSION " (sofia-sip-nta/" NTA_VERSION ")";
for_each(mModules.begin(),mModules.end(),bind2nd(mem_fun(&Module::declare),
ConfigManager::get()->getRoot()));
}
Agent::~Agent(){
for_each(mModules.begin(),mModules.end(),delete_functor<Module>());
if (mAgent)
nta_agent_destroy(mAgent);
}
const char *Agent::getServerString()const{
return mServerString.c_str();
}
void Agent::loadConfig(ConfigManager *cm){
cm->loadStrict();//now that each module has declared its settings, we need to reload from the config file
mAliases=cm->getGlobal()->get<ConfigStringList>("aliases")->read();
LOGD("List of host aliases:");
for(list<string>::iterator it=mAliases.begin();it!=mAliases.end();++it){
LOGD("%s",(*it).c_str());
}
list<Module*>::iterator it;
for(it=mModules.begin();it!=mModules.end();++it)
(*it)->load(this);
}
void Agent::setDomain(const std::string &domain){
mDomain=domain;
}
int Agent::countUsInVia(sip_via_t *via)const{
int count = 0;
for (sip_via_t *v = via;v!=NULL;v=v->v_next){
if (isUs(v->v_host, v->v_port)) ++count;
}
return count;
}
bool Agent::isUs(const char *host, const char *port)const{
char *tmp=NULL;
int end;
int p=(port!=NULL) ? atoi(port) : 5060;
if (p!=mPort) return false;
//skip possibly trailling '.' at the end of host
if (host[end=(strlen(host)-1)]=='.'){
tmp=(char*)alloca(end+1);
memcpy(tmp,host,end);
tmp[end]='\0';
host=tmp;
}
if (strcmp(host,mLocAddr.c_str())==0) return true;
list<string>::const_iterator it;
for(it=mAliases.begin();it!=mAliases.end();++it){
if (strcasecmp(host,(*it).c_str())==0) return true;
}
return false;
}
bool Agent::isUs(const url_t *url)const{
return isUs(url->url_host, url->url_port);
}
void Agent::onRequest(msg_t *msg, sip_t *sip){
list<Module*>::iterator it;
SipEvent ev(msg,sip);
for(it=mModules.begin();it!=mModules.end();++it){
(*it)->processRequest(&ev);
if (ev.finished()) break;
}
}
void Agent::onResponse(msg_t *msg, sip_t *sip){
list<Module*>::iterator it;
SipEvent ev(msg,sip);
for(it=mModules.begin();it!=mModules.end();++it){
(*it)->processResponse(&ev);
if (ev.finished()) break;
}
}
int Agent::onIncomingMessage(msg_t *msg, sip_t *sip){
su_home_t home;
size_t msg_size;
char *buf;
su_home_init(&home);
buf=msg_as_string(&home, msg, NULL, 0,&msg_size);
LOGD("Receiving new SIP message:\n%s",buf);
if (sip->sip_request)
onRequest(msg,sip);
else{
onResponse(msg,sip);
}
su_home_deinit(&home);
return 0;
}
int Agent::messageCallback(nta_agent_magic_t *context, nta_agent_t *agent,msg_t *msg,sip_t *sip){
Agent *a=(Agent*)context;
return a->onIncomingMessage(msg,sip);
}
void Agent::idle(){
for_each(mModules.begin(),mModules.end(),mem_fun(&Module::idle));
}
const std::string& Agent::getUniqueId() const{
return mUniqueId;
}
<|endoftext|> |
<commit_before><commit_msg>Add default MSan options.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: controltype.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:08: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 EXTENSIONS_SOURCE_PROPCTRLR_CONTROLTYPE_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_CONTROLTYPE_HXX
//........................................................................
namespace pcr
{
//........................................................................
//====================================================================
//= control types, analogous to FormComponentType
//====================================================================
namespace ControlType
{
static const sal_Int16 FIXEDLINE = (sal_Int16)100;
static const sal_Int16 FORMATTEDFIELD = (sal_Int16)101;
static const sal_Int16 PROGRESSBAR = (sal_Int16)102;
// need only those which are not already covered as FormComponentType
}
//........................................................................
} // namespacepcr
//........................................................................
#endif // EXTENSIONS_SOURCE_PROPCTRLR_CONTROLTYPE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.472); FILE MERGED 2008/03/31 12:31:40 rt 1.3.472.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: controltype.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef EXTENSIONS_SOURCE_PROPCTRLR_CONTROLTYPE_HXX
#define EXTENSIONS_SOURCE_PROPCTRLR_CONTROLTYPE_HXX
//........................................................................
namespace pcr
{
//........................................................................
//====================================================================
//= control types, analogous to FormComponentType
//====================================================================
namespace ControlType
{
static const sal_Int16 FIXEDLINE = (sal_Int16)100;
static const sal_Int16 FORMATTEDFIELD = (sal_Int16)101;
static const sal_Int16 PROGRESSBAR = (sal_Int16)102;
// need only those which are not already covered as FormComponentType
}
//........................................................................
} // namespacepcr
//........................................................................
#endif // EXTENSIONS_SOURCE_PROPCTRLR_CONTROLTYPE_HXX
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/standard.h"
#include "pubkey.h"
#include "script/script.h"
#include "util.h"
#include "utilstrencodings.h"
typedef std::vector<uint8_t> valtype;
bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER;
CScriptID::CScriptID(const CScript &in)
: uint160(Hash160(in.begin(), in.end())) {}
const char *GetTxnOutputType(txnouttype t) {
switch (t) {
case TX_NONSTANDARD:
return "nonstandard";
case TX_PUBKEY:
return "pubkey";
case TX_PUBKEYHASH:
return "pubkeyhash";
case TX_SCRIPTHASH:
return "scripthash";
case TX_MULTISIG:
return "multisig";
case TX_NULL_DATA:
return "nulldata";
}
return nullptr;
}
/**
* Return public keys or hashes from scriptPubKey, for 'standard' transaction
* types.
*/
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet,
std::vector<std::vector<uint8_t>> &vSolutionsRet) {
// Templates
static std::multimap<txnouttype, CScript> mTemplates;
if (mTemplates.empty()) {
// Standard tx, sender provides pubkey, receiver adds signature
mTemplates.insert(
std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
// Bitcoin address tx, sender provides hash of pubkey, receiver provides
// signature and pubkey
mTemplates.insert(
std::make_pair(TX_PUBKEYHASH,
CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH
<< OP_EQUALVERIFY << OP_CHECKSIG));
// Sender provides N pubkeys, receivers provides M signatures
mTemplates.insert(
std::make_pair(TX_MULTISIG,
CScript() << OP_SMALLINTEGER << OP_PUBKEYS
<< OP_SMALLINTEGER << OP_CHECKMULTISIG));
}
vSolutionsRet.clear();
// Shortcut for pay-to-script-hash, which are more constrained than the
// other types:
// it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
if (scriptPubKey.IsPayToScriptHash()) {
typeRet = TX_SCRIPTHASH;
std::vector<uint8_t> hashBytes(scriptPubKey.begin() + 2,
scriptPubKey.begin() + 22);
vSolutionsRet.push_back(hashBytes);
return true;
}
// Provably prunable, data-carrying output
//
// So long as script passes the IsUnspendable() test and all but the first
// byte passes the IsPushOnly() test we don't care what exactly is in the
// script.
if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN &&
scriptPubKey.IsPushOnly(scriptPubKey.begin() + 1)) {
typeRet = TX_NULL_DATA;
return true;
}
// Scan templates
const CScript &script1 = scriptPubKey;
for (const std::pair<txnouttype, CScript> &tplate : mTemplates) {
const CScript &script2 = tplate.second;
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
std::vector<uint8_t> vch1, vch2;
// Compare
CScript::const_iterator pc1 = script1.begin();
CScript::const_iterator pc2 = script2.begin();
while (true) {
if (pc1 == script1.end() && pc2 == script2.end()) {
// Found a match
typeRet = tplate.first;
if (typeRet == TX_MULTISIG) {
// Additional checks for TX_MULTISIG:
uint8_t m = vSolutionsRet.front()[0];
uint8_t n = vSolutionsRet.back()[0];
if (m < 1 || n < 1 || m > n ||
vSolutionsRet.size() - 2 != n)
return false;
}
return true;
}
if (!script1.GetOp(pc1, opcode1, vch1)) break;
if (!script2.GetOp(pc2, opcode2, vch2)) break;
// Template matching opcodes:
if (opcode2 == OP_PUBKEYS) {
while (vch1.size() >= 33 && vch1.size() <= 65) {
vSolutionsRet.push_back(vch1);
if (!script1.GetOp(pc1, opcode1, vch1)) break;
}
if (!script2.GetOp(pc2, opcode2, vch2)) break;
// Normal situation is to fall through to other if/else
// statements
}
if (opcode2 == OP_PUBKEY) {
if (vch1.size() < 33 || vch1.size() > 65) break;
vSolutionsRet.push_back(vch1);
} else if (opcode2 == OP_PUBKEYHASH) {
if (vch1.size() != sizeof(uint160)) break;
vSolutionsRet.push_back(vch1);
} else if (opcode2 == OP_SMALLINTEGER) {
// Single-byte small integer pushed onto vSolutions
if (opcode1 == OP_0 || (opcode1 >= OP_1 && opcode1 <= OP_16)) {
char n = (char)CScript::DecodeOP_N(opcode1);
vSolutionsRet.push_back(valtype(1, n));
} else
break;
} else if (opcode1 != opcode2 || vch1 != vch2) {
// Others must match exactly
break;
}
}
}
vSolutionsRet.clear();
typeRet = TX_NONSTANDARD;
return false;
}
bool ExtractDestination(const CScript &scriptPubKey,
CTxDestination &addressRet) {
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions)) return false;
if (whichType == TX_PUBKEY) {
CPubKey pubKey(vSolutions[0]);
if (!pubKey.IsValid()) return false;
addressRet = pubKey.GetID();
return true;
} else if (whichType == TX_PUBKEYHASH) {
addressRet = CKeyID(uint160(vSolutions[0]));
return true;
} else if (whichType == TX_SCRIPTHASH) {
addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet,
std::vector<CTxDestination> &addressRet,
int &nRequiredRet) {
addressRet.clear();
typeRet = TX_NONSTANDARD;
std::vector<valtype> vSolutions;
if (!Solver(scriptPubKey, typeRet, vSolutions)) return false;
if (typeRet == TX_NULL_DATA) {
// This is data, not addresses
return false;
}
if (typeRet == TX_MULTISIG) {
nRequiredRet = vSolutions.front()[0];
for (unsigned int i = 1; i < vSolutions.size() - 1; i++) {
CPubKey pubKey(vSolutions[i]);
if (!pubKey.IsValid()) continue;
CTxDestination address = pubKey.GetID();
addressRet.push_back(address);
}
if (addressRet.empty()) return false;
} else {
nRequiredRet = 1;
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address)) return false;
addressRet.push_back(address);
}
return true;
}
namespace {
class CScriptVisitor : public boost::static_visitor<bool> {
private:
CScript *script;
public:
CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();
return false;
}
bool operator()(const CKeyID &keyID) const {
script->clear();
*script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY
<< OP_CHECKSIG;
return true;
}
bool operator()(const CScriptID &scriptID) const {
script->clear();
*script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
return true;
}
};
} // namespace
CScript GetScriptForDestination(const CTxDestination &dest) {
CScript script;
boost::apply_visitor(CScriptVisitor(&script), dest);
return script;
}
CScript GetScriptForRawPubKey(const CPubKey &pubKey) {
return CScript() << std::vector<uint8_t>(pubKey.begin(), pubKey.end())
<< OP_CHECKSIG;
}
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey> &keys) {
CScript script;
script << CScript::EncodeOP_N(nRequired);
for (const CPubKey &key : keys)
script << ToByteVector(key);
script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
return script;
}
bool IsValidDestination(const CTxDestination &dest) {
return dest.which() != 0;
}
<commit_msg>nits on standard.cpp and standard.h<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/standard.h"
#include "pubkey.h"
#include "script/script.h"
#include "util.h"
#include "utilstrencodings.h"
typedef std::vector<uint8_t> valtype;
bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER;
CScriptID::CScriptID(const CScript &in)
: uint160(Hash160(in.begin(), in.end())) {}
const char *GetTxnOutputType(txnouttype t) {
switch (t) {
case TX_NONSTANDARD:
return "nonstandard";
case TX_PUBKEY:
return "pubkey";
case TX_PUBKEYHASH:
return "pubkeyhash";
case TX_SCRIPTHASH:
return "scripthash";
case TX_MULTISIG:
return "multisig";
case TX_NULL_DATA:
return "nulldata";
}
return nullptr;
}
/**
* Return public keys or hashes from scriptPubKey, for 'standard' transaction
* types.
*/
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet,
std::vector<std::vector<uint8_t>> &vSolutionsRet) {
// Templates
static std::multimap<txnouttype, CScript> mTemplates;
if (mTemplates.empty()) {
// Standard tx, sender provides pubkey, receiver adds signature
mTemplates.insert(
std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
// Bitcoin address tx, sender provides hash of pubkey, receiver provides
// signature and pubkey
mTemplates.insert(
std::make_pair(TX_PUBKEYHASH,
CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH
<< OP_EQUALVERIFY << OP_CHECKSIG));
// Sender provides N pubkeys, receivers provides M signatures
mTemplates.insert(
std::make_pair(TX_MULTISIG,
CScript() << OP_SMALLINTEGER << OP_PUBKEYS
<< OP_SMALLINTEGER << OP_CHECKMULTISIG));
}
vSolutionsRet.clear();
// Shortcut for pay-to-script-hash, which are more constrained than the
// other types:
// it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
if (scriptPubKey.IsPayToScriptHash()) {
typeRet = TX_SCRIPTHASH;
std::vector<uint8_t> hashBytes(scriptPubKey.begin() + 2,
scriptPubKey.begin() + 22);
vSolutionsRet.push_back(hashBytes);
return true;
}
// Provably prunable, data-carrying output
//
// So long as script passes the IsUnspendable() test and all but the first
// byte passes the IsPushOnly() test we don't care what exactly is in the
// script.
if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN &&
scriptPubKey.IsPushOnly(scriptPubKey.begin() + 1)) {
typeRet = TX_NULL_DATA;
return true;
}
// Scan templates
const CScript &script1 = scriptPubKey;
for (const std::pair<txnouttype, CScript> &tplate : mTemplates) {
const CScript &script2 = tplate.second;
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
std::vector<uint8_t> vch1, vch2;
// Compare
CScript::const_iterator pc1 = script1.begin();
CScript::const_iterator pc2 = script2.begin();
while (true) {
if (pc1 == script1.end() && pc2 == script2.end()) {
// Found a match
typeRet = tplate.first;
if (typeRet == TX_MULTISIG) {
// Additional checks for TX_MULTISIG:
uint8_t m = vSolutionsRet.front()[0];
uint8_t n = vSolutionsRet.back()[0];
if (m < 1 || n < 1 || m > n ||
vSolutionsRet.size() - 2 != n) {
return false;
}
}
return true;
}
if (!script1.GetOp(pc1, opcode1, vch1)) {
break;
}
if (!script2.GetOp(pc2, opcode2, vch2)) {
break;
}
// Template matching opcodes:
if (opcode2 == OP_PUBKEYS) {
while (vch1.size() >= 33 && vch1.size() <= 65) {
vSolutionsRet.push_back(vch1);
if (!script1.GetOp(pc1, opcode1, vch1)) {
break;
}
}
if (!script2.GetOp(pc2, opcode2, vch2)) {
break;
}
// Normal situation is to fall through to other if/else
// statements
}
if (opcode2 == OP_PUBKEY) {
if (vch1.size() < 33 || vch1.size() > 65) {
break;
}
vSolutionsRet.push_back(vch1);
} else if (opcode2 == OP_PUBKEYHASH) {
if (vch1.size() != sizeof(uint160)) {
break;
}
vSolutionsRet.push_back(vch1);
} else if (opcode2 == OP_SMALLINTEGER) {
// Single-byte small integer pushed onto vSolutions
if (opcode1 == OP_0 || (opcode1 >= OP_1 && opcode1 <= OP_16)) {
char n = (char)CScript::DecodeOP_N(opcode1);
vSolutionsRet.push_back(valtype(1, n));
} else {
break;
}
} else if (opcode1 != opcode2 || vch1 != vch2) {
// Others must match exactly
break;
}
}
}
vSolutionsRet.clear();
typeRet = TX_NONSTANDARD;
return false;
}
bool ExtractDestination(const CScript &scriptPubKey,
CTxDestination &addressRet) {
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions)) {
return false;
}
if (whichType == TX_PUBKEY) {
CPubKey pubKey(vSolutions[0]);
if (!pubKey.IsValid()) {
return false;
}
addressRet = pubKey.GetID();
return true;
}
if (whichType == TX_PUBKEYHASH) {
addressRet = CKeyID(uint160(vSolutions[0]));
return true;
}
if (whichType == TX_SCRIPTHASH) {
addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet,
std::vector<CTxDestination> &addressRet,
int &nRequiredRet) {
addressRet.clear();
typeRet = TX_NONSTANDARD;
std::vector<valtype> vSolutions;
if (!Solver(scriptPubKey, typeRet, vSolutions)) {
return false;
}
if (typeRet == TX_NULL_DATA) {
// This is data, not addresses
return false;
}
if (typeRet == TX_MULTISIG) {
nRequiredRet = vSolutions.front()[0];
for (size_t i = 1; i < vSolutions.size() - 1; i++) {
CPubKey pubKey(vSolutions[i]);
if (!pubKey.IsValid()) {
continue;
}
CTxDestination address = pubKey.GetID();
addressRet.push_back(address);
}
if (addressRet.empty()) {
return false;
}
} else {
nRequiredRet = 1;
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address)) {
return false;
}
addressRet.push_back(address);
}
return true;
}
namespace {
class CScriptVisitor : public boost::static_visitor<bool> {
private:
CScript *script;
public:
CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();
return false;
}
bool operator()(const CKeyID &keyID) const {
script->clear();
*script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY
<< OP_CHECKSIG;
return true;
}
bool operator()(const CScriptID &scriptID) const {
script->clear();
*script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
return true;
}
};
} // namespace
CScript GetScriptForDestination(const CTxDestination &dest) {
CScript script;
boost::apply_visitor(CScriptVisitor(&script), dest);
return script;
}
CScript GetScriptForRawPubKey(const CPubKey &pubKey) {
return CScript() << std::vector<uint8_t>(pubKey.begin(), pubKey.end())
<< OP_CHECKSIG;
}
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey> &keys) {
CScript script;
script << CScript::EncodeOP_N(nRequired);
for (const CPubKey &key : keys) {
script << ToByteVector(key);
}
script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
return script;
}
bool IsValidDestination(const CTxDestination &dest) {
return dest.which() != 0;
}
<|endoftext|> |
<commit_before>/*
* grib.cpp
*
* Created on: Nov 20, 2012
* Author: partio
*/
#include "grib.h"
#include "logger_factory.h"
using namespace std;
using namespace himan::plugin;
grib::grib()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("grib"));
itsGrib = shared_ptr<NFmiGrib> (new NFmiGrib());
}
shared_ptr<NFmiGrib> grib::Reader()
{
return itsGrib;
}
bool grib::ToFile(shared_ptr<info> theInfo, const string& theOutputFile, HPFileType theFileType, bool theActiveOnly)
{
// Write only that data which is currently set at descriptors
if (theActiveOnly)
{
/* Section 0 */
itsGrib->Message()->Edition(static_cast<int> (theFileType));
if (theFileType == kGRIB2)
{
itsGrib->Message()->ParameterDiscipline(theInfo->Param().GribDiscipline()) ;
}
/* Section 1 */
itsGrib->Message()->Centre(theInfo->Producer().Centre());
itsGrib->Message()->Process(theInfo->Producer().Process());
if (theFileType == kGRIB2)
{
// Origin time
itsGrib->Message()->Year(theInfo->Time().OriginDateTime()->String("%Y"));
itsGrib->Message()->Month(theInfo->Time().OriginDateTime()->String("%m"));
itsGrib->Message()->Day(theInfo->Time().OriginDateTime()->String("%d"));
itsGrib->Message()->Hour(theInfo->Time().OriginDateTime()->String("%H"));
itsGrib->Message()->Minute(theInfo->Time().OriginDateTime()->String("%M"));
itsGrib->Message()->Second("0");
}
itsGrib->Message()->StartStep(theInfo->Time().Step());
itsGrib->Message()->EndStep(theInfo->Time().Step());
/* Section 4 */
if (theFileType == kGRIB2)
{
itsGrib->Message()->ParameterCategory(theInfo->Param().GribCategory()) ;
itsGrib->Message()->ParameterNumber(theInfo->Param().GribParameter()) ;
}
// TODO: need to normalize these, now they are grib2
switch (theInfo->Projection())
{
case kLatLonProjection:
{
itsGrib->Message()->GridType(0);
string scanningMode = "+x-y"; // GFS
double latitudeOfFirstGridPointInDegrees, longitudeOfFirstGridPointInDegrees;
double latitudeOfLastGridPointInDegrees, longitudeOfLastGridPointInDegrees;
if (scanningMode == "+x-y")
{
latitudeOfFirstGridPointInDegrees = theInfo->TopRightLatitude();
longitudeOfFirstGridPointInDegrees = theInfo->BottomLeftLongitude();
latitudeOfLastGridPointInDegrees = theInfo->BottomLeftLatitude();
longitudeOfLastGridPointInDegrees = theInfo->TopRightLongitude();
}
else
{
throw runtime_error(ClassName() + ": unsupported scanning mode: " + scanningMode);
}
itsGrib->Message()->X0(longitudeOfFirstGridPointInDegrees);
itsGrib->Message()->Y0(latitudeOfFirstGridPointInDegrees);
itsGrib->Message()->X1(longitudeOfLastGridPointInDegrees);
itsGrib->Message()->Y1(latitudeOfLastGridPointInDegrees);
break;
}
case kStereographicProjection:
itsGrib->Message()->GridType(20);
itsGrib->Message()->X0(theInfo->BottomLeftLongitude());
itsGrib->Message()->Y0(theInfo->BottomLeftLatitude());
// missing iDirectionIncrementInMeters
itsGrib->Message()->GridOrientation(theInfo->Orientation());
break;
default:
throw runtime_error(ClassName() + ": invalid projection while writing grib: " + boost::lexical_cast<string> (theInfo->Projection()));
break;
}
itsGrib->Message()->SizeX(theInfo->Ni());
itsGrib->Message()->SizeY(theInfo->Nj());
// Level
if (theFileType == kGRIB2)
{
itsGrib->Message()->LevelType(theInfo->Level().Type());
itsGrib->Message()->LevelValue(static_cast<long> (theInfo->Level().Value()));
}
itsGrib->Message()->Bitmap(true);
itsGrib->Message()->Values(theInfo->Data()->Values(), theInfo->Ni() * theInfo->Nj());
itsGrib->Message()->PackingType("grid_jpeg");
itsGrib->Message()->Write(theOutputFile);
}
return true;
}
vector<shared_ptr<himan::info>> grib::FromFile(const string& theInputFile, const search_options& options, bool theReadContents)
{
vector<shared_ptr<himan::info>> theInfos;
itsGrib->Open(theInputFile);
itsLogger->Trace("Reading file '" + theInputFile + "'");
int foundMessageNo = -1;
while (itsGrib->NextMessage())
{
foundMessageNo++;
/*
* One grib file may contain many grib messages. Loop though all messages
* and get all that match our search options.
*
*/
//<!todo Should we actually return all matching messages or only the first one
long process = itsGrib->Message()->Process();
//<!todo How to best match neons producer id to grib centre/process
if (options.configuration->SourceProducer() != process)
{
itsLogger->Trace("Producer does not match: " + boost::lexical_cast<string> (options.configuration->SourceProducer()) + " vs " + boost::lexical_cast<string> (process));
// continue;
}
param p;
//<! todo GRIB1 support
if (itsGrib->Message()->Edition() == 1)
{
/*
if (itsGrib->Message()->ParameterNumber() != options.param.GribParameter())
continue;
p->GribParameter(itsGrib->Message()->ParameterNumber());
*/
throw runtime_error(ClassName() + ": grib 1 not supported yet");
}
else
{
long number = itsGrib->Message()->ParameterNumber();
long category = itsGrib->Message()->ParameterCategory();
long discipline = itsGrib->Message()->ParameterDiscipline();
// Need to get name and unit of parameter
#ifdef NEONS
throw runtime_error("FFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU!!!!!!!!!!!!!!!!!!!");
#else
assert(discipline == 0);
if (number == 1 && category == 3)
{
p.Name("P-HPA");
p.Unit(kPa);
}
else if (number == 0 && category == 0)
{
p.Name("T-K");
p.Unit(kK);
}
else if (number == 8 && category == 2)
{
p.Name("VV-PAS");
p.Unit(kPas);
}
else
{
throw runtime_error(ClassName() + ": I do not recognize this parameter (and I can't connect to neons)");
}
#endif
// Name is our primary identifier -- not univ_id or grib param id
if (p != options.param)
{
itsLogger->Trace("Parameter does not match: " + options.param.Name() + " vs " + p.Name());
continue;
}
p.GribParameter(number);
p.GribDiscipline(discipline);
p.GribCategory(category);
}
string dataDate = boost::lexical_cast<string> (itsGrib->Message()->DataDate());
long dt = itsGrib->Message()->DataTime();
// grib_api stores times as long, so when origin hour is 00
// it gets stored as 0 which boost does not understand
// (since it's a mix of 12 hour and 24 hour times)
string dataTime = boost::lexical_cast<string> (dt);
if (dt < 10)
{
dataTime = "0" + dataTime;
}
long step = itsGrib->Message()->ForecastTime();
string originDateTimeStr = dataDate + dataTime;
raw_time originDateTime (originDateTimeStr, "%Y%m%d%H");
forecast_time t (originDateTime, originDateTime);
t.ValidDateTime()->Adjust("hours", static_cast<int> (step));
if (t != options.time)
{
itsLogger->Trace("Times do not match");
itsLogger->Trace("OriginDateTime: " + options.time.OriginDateTime()->String() + " (requested) vs " + t.OriginDateTime()->String() + " (found)");
itsLogger->Trace("ValidDateTime: " + options.time.ValidDateTime()->String() + " (requested) vs " + t.ValidDateTime()->String() + " (found)");
continue;
}
long gribLevel = itsGrib->Message()->NormalizedLevelType();
himan::HPLevelType levelType;
switch (gribLevel)
{
case 1:
levelType = himan::kGround;
break;
case 100:
levelType = himan::kPressure;
break;
case 102:
levelType = himan::kMeanSea;
break;
case 105:
levelType = himan::kHeight;
break;
case 109:
levelType = himan::kHybrid;
break;
default:
throw runtime_error(ClassName() + ": Unsupported level type: " + boost::lexical_cast<string> (gribLevel));
}
level l (levelType, static_cast<float> (itsGrib->Message()->LevelValue()));
if (l != options.level)
{
itsLogger->Trace("Level does not match");
continue;
}
// END VALIDATION OF SEARCH PARAMETERS
shared_ptr<info> newInfo (new info());
producer prod(itsGrib->Message()->Centre(), process);
newInfo->Producer(prod);
vector<param> theParams;
theParams.push_back(p);
newInfo->Params(theParams);
vector<forecast_time> theTimes;
theTimes.push_back(t);
newInfo->Times(theTimes);
vector<level> theLevels;
theLevels.push_back(l);
newInfo->Levels(theLevels);
/*
* Get area information from grib.
*/
switch (itsGrib->Message()->NormalizedGridType())
{
case 0:
newInfo->Projection(kLatLonProjection);
break;
case 10:
newInfo->Projection(kRotatedLatLonProjection);
break;
default:
throw runtime_error(ClassName() + ": Unsupported projection: " + boost::lexical_cast<string> (itsGrib->Message()->NormalizedGridType()));
break;
}
newInfo->BottomLeftLatitude(itsGrib->Message()->Y0());
newInfo->BottomLeftLongitude(itsGrib->Message()->X0());
// Assume +x+y
newInfo->TopRightLatitude(itsGrib->Message()->Y1());
newInfo->TopRightLongitude(itsGrib->Message()->X1());
size_t ni = itsGrib->Message()->SizeX();
size_t nj = itsGrib->Message()->SizeY();
bool iNegative = itsGrib->Message()->IScansNegatively();
bool jPositive = itsGrib->Message()->JScansPositively();
HPScanningMode m = kUnknownScanningMode;
if (!iNegative && !jPositive)
{
m = kTopLeft;
}
else if (iNegative && !jPositive)
{
m = kTopRight;
}
else if (iNegative && jPositive)
{
m = kBottomRight;
}
else if (!iNegative && jPositive)
{
m = kBottomLeft;
}
else
{
throw runtime_error("WHAT?");
}
newInfo->ScanningMode(m);
/*
* Read data from grib *
*/
size_t len = 0;
double* d = 0;
if (theReadContents)
{
len = itsGrib->Message()->ValuesLength();
d = itsGrib->Message()->Values();
}
newInfo->Create();
// Set descriptors
newInfo->Param(p);
newInfo->Time(t);
newInfo->Level(l);
shared_ptr<d_matrix_t> dm = shared_ptr<d_matrix_t> (new d_matrix_t(ni, nj));
dm->Data(d, len);
newInfo->Data(dm);
theInfos.push_back(newInfo);
if (d)
{
free(d);
}
break ; // We found what we were looking for
}
if (theInfos.size())
{
// This will be broken when/if we return multiple infos from this function
itsLogger->Trace("Data Found from message " + boost::lexical_cast<string> (foundMessageNo) + "/" + boost::lexical_cast<string> (itsGrib->MessageCount()));
}
return theInfos;
}
<commit_msg>dataTime has minutes\!<commit_after>/*
* grib.cpp
*
* Created on: Nov 20, 2012
* Author: partio
*/
#include "grib.h"
#include "logger_factory.h"
using namespace std;
using namespace himan::plugin;
grib::grib()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("grib"));
itsGrib = shared_ptr<NFmiGrib> (new NFmiGrib());
}
shared_ptr<NFmiGrib> grib::Reader()
{
return itsGrib;
}
bool grib::ToFile(shared_ptr<info> theInfo, const string& theOutputFile, HPFileType theFileType, bool theActiveOnly)
{
// Write only that data which is currently set at descriptors
if (theActiveOnly)
{
/* Section 0 */
itsGrib->Message()->Edition(static_cast<int> (theFileType));
if (theFileType == kGRIB2)
{
itsGrib->Message()->ParameterDiscipline(theInfo->Param().GribDiscipline()) ;
}
/* Section 1 */
itsGrib->Message()->Centre(theInfo->Producer().Centre());
itsGrib->Message()->Process(theInfo->Producer().Process());
if (theFileType == kGRIB2)
{
// Origin time
itsGrib->Message()->Year(theInfo->Time().OriginDateTime()->String("%Y"));
itsGrib->Message()->Month(theInfo->Time().OriginDateTime()->String("%m"));
itsGrib->Message()->Day(theInfo->Time().OriginDateTime()->String("%d"));
itsGrib->Message()->Hour(theInfo->Time().OriginDateTime()->String("%H"));
itsGrib->Message()->Minute(theInfo->Time().OriginDateTime()->String("%M"));
itsGrib->Message()->Second("0");
}
itsGrib->Message()->StartStep(theInfo->Time().Step());
itsGrib->Message()->EndStep(theInfo->Time().Step());
/* Section 4 */
if (theFileType == kGRIB2)
{
itsGrib->Message()->ParameterCategory(theInfo->Param().GribCategory()) ;
itsGrib->Message()->ParameterNumber(theInfo->Param().GribParameter()) ;
}
// TODO: need to normalize these, now they are grib2
switch (theInfo->Projection())
{
case kLatLonProjection:
{
itsGrib->Message()->GridType(0);
string scanningMode = "+x-y"; // GFS
double latitudeOfFirstGridPointInDegrees, longitudeOfFirstGridPointInDegrees;
double latitudeOfLastGridPointInDegrees, longitudeOfLastGridPointInDegrees;
if (scanningMode == "+x-y")
{
latitudeOfFirstGridPointInDegrees = theInfo->TopRightLatitude();
longitudeOfFirstGridPointInDegrees = theInfo->BottomLeftLongitude();
latitudeOfLastGridPointInDegrees = theInfo->BottomLeftLatitude();
longitudeOfLastGridPointInDegrees = theInfo->TopRightLongitude();
}
else
{
throw runtime_error(ClassName() + ": unsupported scanning mode: " + scanningMode);
}
itsGrib->Message()->X0(longitudeOfFirstGridPointInDegrees);
itsGrib->Message()->Y0(latitudeOfFirstGridPointInDegrees);
itsGrib->Message()->X1(longitudeOfLastGridPointInDegrees);
itsGrib->Message()->Y1(latitudeOfLastGridPointInDegrees);
break;
}
case kStereographicProjection:
itsGrib->Message()->GridType(20);
itsGrib->Message()->X0(theInfo->BottomLeftLongitude());
itsGrib->Message()->Y0(theInfo->BottomLeftLatitude());
// missing iDirectionIncrementInMeters
itsGrib->Message()->GridOrientation(theInfo->Orientation());
break;
default:
throw runtime_error(ClassName() + ": invalid projection while writing grib: " + boost::lexical_cast<string> (theInfo->Projection()));
break;
}
itsGrib->Message()->SizeX(theInfo->Ni());
itsGrib->Message()->SizeY(theInfo->Nj());
// Level
if (theFileType == kGRIB2)
{
itsGrib->Message()->LevelType(theInfo->Level().Type());
itsGrib->Message()->LevelValue(static_cast<long> (theInfo->Level().Value()));
}
itsGrib->Message()->Bitmap(true);
itsGrib->Message()->Values(theInfo->Data()->Values(), theInfo->Ni() * theInfo->Nj());
itsGrib->Message()->PackingType("grid_jpeg");
itsGrib->Message()->Write(theOutputFile);
itsLogger->Info("Wrote file '" + theOutputFile + "'");
}
return true;
}
vector<shared_ptr<himan::info>> grib::FromFile(const string& theInputFile, const search_options& options, bool theReadContents)
{
vector<shared_ptr<himan::info>> theInfos;
itsGrib->Open(theInputFile);
itsLogger->Trace("Reading file '" + theInputFile + "'");
int foundMessageNo = -1;
while (itsGrib->NextMessage())
{
foundMessageNo++;
/*
* One grib file may contain many grib messages. Loop though all messages
* and get all that match our search options.
*
*/
//<!todo Should we actually return all matching messages or only the first one
long process = itsGrib->Message()->Process();
//<!todo How to best match neons producer id to grib centre/process
if (options.configuration->SourceProducer() != process)
{
itsLogger->Trace("Producer does not match: " + boost::lexical_cast<string> (options.configuration->SourceProducer()) + " vs " + boost::lexical_cast<string> (process));
// continue;
}
param p;
//<! todo GRIB1 support
if (itsGrib->Message()->Edition() == 1)
{
/*
if (itsGrib->Message()->ParameterNumber() != options.param.GribParameter())
continue;
p->GribParameter(itsGrib->Message()->ParameterNumber());
*/
throw runtime_error(ClassName() + ": grib 1 not supported yet");
}
else
{
long number = itsGrib->Message()->ParameterNumber();
long category = itsGrib->Message()->ParameterCategory();
long discipline = itsGrib->Message()->ParameterDiscipline();
// Need to get name and unit of parameter
#ifdef NEONS
throw runtime_error("FFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU!!!!!!!!!!!!!!!!!!!");
#else
assert(discipline == 0);
if (number == 1 && category == 3)
{
p.Name("P-HPA");
p.Unit(kPa);
}
else if (number == 0 && category == 0)
{
p.Name("T-K");
p.Unit(kK);
}
else if (number == 8 && category == 2)
{
p.Name("VV-PAS");
p.Unit(kPas);
}
else
{
throw runtime_error(ClassName() + ": I do not recognize this parameter (and I can't connect to neons)");
}
#endif
// Name is our primary identifier -- not univ_id or grib param id
if (p != options.param)
{
itsLogger->Trace("Parameter does not match: " + options.param.Name() + " vs " + p.Name());
continue;
}
p.GribParameter(number);
p.GribDiscipline(discipline);
p.GribCategory(category);
}
string dataDate = boost::lexical_cast<string> (itsGrib->Message()->DataDate());
/*
* dataTime is HH24MM in long datatype.
*
* So, for example analysistime 00 is 0, and 06 is 600.
*
*/
long dt = itsGrib->Message()->DataTime();
string dataTime = boost::lexical_cast<string> (dt);
if (dt < 1000)
{
dataTime = "0" + dataTime;
}
long step = itsGrib->Message()->ForecastTime();
string originDateTimeStr = dataDate + dataTime;
raw_time originDateTime (originDateTimeStr, "%Y%m%d%H%M");
forecast_time t (originDateTime, originDateTime);
t.ValidDateTime()->Adjust("hours", static_cast<int> (step));
if (t != options.time)
{
itsLogger->Trace("Times do not match");
itsLogger->Trace("OriginDateTime: " + options.time.OriginDateTime()->String() + " (requested) vs " + t.OriginDateTime()->String() + " (found)");
itsLogger->Trace("ValidDateTime: " + options.time.ValidDateTime()->String() + " (requested) vs " + t.ValidDateTime()->String() + " (found)");
continue;
}
long gribLevel = itsGrib->Message()->NormalizedLevelType();
himan::HPLevelType levelType;
switch (gribLevel)
{
case 1:
levelType = himan::kGround;
break;
case 100:
levelType = himan::kPressure;
break;
case 102:
levelType = himan::kMeanSea;
break;
case 105:
levelType = himan::kHeight;
break;
case 109:
levelType = himan::kHybrid;
break;
default:
throw runtime_error(ClassName() + ": Unsupported level type: " + boost::lexical_cast<string> (gribLevel));
}
level l (levelType, static_cast<float> (itsGrib->Message()->LevelValue()));
if (l != options.level)
{
itsLogger->Trace("Level does not match");
continue;
}
// END VALIDATION OF SEARCH PARAMETERS
shared_ptr<info> newInfo (new info());
producer prod(itsGrib->Message()->Centre(), process);
newInfo->Producer(prod);
vector<param> theParams;
theParams.push_back(p);
newInfo->Params(theParams);
vector<forecast_time> theTimes;
theTimes.push_back(t);
newInfo->Times(theTimes);
vector<level> theLevels;
theLevels.push_back(l);
newInfo->Levels(theLevels);
/*
* Get area information from grib.
*/
switch (itsGrib->Message()->NormalizedGridType())
{
case 0:
newInfo->Projection(kLatLonProjection);
break;
case 10:
newInfo->Projection(kRotatedLatLonProjection);
break;
default:
throw runtime_error(ClassName() + ": Unsupported projection: " + boost::lexical_cast<string> (itsGrib->Message()->NormalizedGridType()));
break;
}
newInfo->BottomLeftLatitude(itsGrib->Message()->Y0());
newInfo->BottomLeftLongitude(itsGrib->Message()->X0());
// Assume +x+y
newInfo->TopRightLatitude(itsGrib->Message()->Y1());
newInfo->TopRightLongitude(itsGrib->Message()->X1());
size_t ni = itsGrib->Message()->SizeX();
size_t nj = itsGrib->Message()->SizeY();
bool iNegative = itsGrib->Message()->IScansNegatively();
bool jPositive = itsGrib->Message()->JScansPositively();
HPScanningMode m = kUnknownScanningMode;
if (!iNegative && !jPositive)
{
m = kTopLeft;
}
else if (iNegative && !jPositive)
{
m = kTopRight;
}
else if (iNegative && jPositive)
{
m = kBottomRight;
}
else if (!iNegative && jPositive)
{
m = kBottomLeft;
}
else
{
throw runtime_error("WHAT?");
}
newInfo->ScanningMode(m);
/*
* Read data from grib *
*/
size_t len = 0;
double* d = 0;
if (theReadContents)
{
len = itsGrib->Message()->ValuesLength();
d = itsGrib->Message()->Values();
}
newInfo->Create();
// Set descriptors
newInfo->Param(p);
newInfo->Time(t);
newInfo->Level(l);
shared_ptr<d_matrix_t> dm = shared_ptr<d_matrix_t> (new d_matrix_t(ni, nj));
dm->Data(d, len);
newInfo->Data(dm);
theInfos.push_back(newInfo);
if (d)
{
free(d);
}
break ; // We found what we were looking for
}
if (theInfos.size())
{
// This will be broken when/if we return multiple infos from this function
itsLogger->Trace("Data Found from message " + boost::lexical_cast<string> (foundMessageNo) + "/" + boost::lexical_cast<string> (itsGrib->MessageCount()));
}
return theInfos;
}
<|endoftext|> |
<commit_before>//
// inpal_algorithm.cpp
// Inverse Palindrome Library
//
// Created by Bryan Triana
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpal_algorithm.hpp"
std::size_t inpal::algorithm::gcd(std::size_t a, std::size_t b)
{
while(b != 0)
{
std::size_t r = a % b;
a = b;
b = r;
}
return a;
}
std::size_t inpal::algorithm::lcm(std::size_t a, std::size_t b)
{
return (a * b) / gcd(a, b);
}
std::size_t inpal::algorithm::modulo(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 1;
while(b > 0)
{
if(b % 2 == 1) x = (x * a % c);
a = (a * a) % c;
b /= 2 ;
}
return x % c;
}
std::size_t inpal::algorithm::mulmod(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 0;
std::size_t y = a % c;
while(b > 0)
{
if(b % 2 == 1) x = (x + y) % c;
y = (y * 2) % c;
b /= 2;
}
return x % c;
}
std::size_t inpal::algorithm::pollard_rho(std::size_t num)
{
const std::size_t m = 1000;
std::size_t a, x, ys;
do a = rand() % num;
while(a == 0 || a == num - 2);
std::size_t y = rand() % num;
std::size_t d = 1;
std::size_t q = 1;
std::size_t r = 1;
do
{
x = y;
for(std::size_t i = 0; i <= r; i++) y = mulmod(y, a, num);
std::size_t j = 0;
do
{
ys = y;
for(std::size_t i = 0; i <= std::min(m, r-j); i++)
{
y = mulmod(y, a, num);
q *= (std::max(x, y) - std::min(x, y)) % num;
}
d = gcd(q, num);
j += m;
}
while(j < r && d == 1);
r *= 2;
}
while(d == 1);
if(d == num)
{
do
{
ys = mulmod(ys, a, num);
d = gcd(std::max(x, ys) - std::min(x, ys), num);
}
while(d == 1);
}
return d;
}
bool inpal::algorithm::pal_test(std::size_t num)
{
std::string rev = std::to_string(num);
//checks if half the reverse of rev is equal to the other half of rev
if(std::equal(rev.begin(), rev.begin() + rev.size() / 2, rev.rbegin())) return true;
return false;
}
<commit_msg>Update inpal_algorithm.cpp<commit_after>//
// inpal_algorithm.cpp
// Inverse Palindrome Library
//
// Created by Bryan Triana
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpal_algorithm.hpp"
std::size_t inpal::algorithm::gcd(std::size_t a, std::size_t b)
{
while(b != 0)
{
std::size_t r = a % b;
a = b;
b = r;
}
return a;
}
std::size_t inpal::algorithm::lcm(std::size_t a, std::size_t b)
{
return (a * b) / gcd(a, b);
}
std::size_t inpal::algorithm::modulo(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 1;
while(b > 0)
{
if(b % 2 == 1) x = (x * a % c);
a = (a * a) % c;
b /= 2 ;
}
return x % c;
}
std::size_t inpal::algorithm::mulmod(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 0;
std::size_t y = a % c;
while(b > 0)
{
if(b % 2 == 1) x = (x + y) % c;
y = (y * 2) % c;
b /= 2;
}
return x % c;
}
std::size_t inpal::algorithm::pollard_rho(std::size_t num)
{
if(num<2) return num;
const std::size_t m = 1000;
std::size_t a, x, ys;
do a = rand() % num;
while(a == 0 || a == num - 2);
std::size_t y = rand() % num;
std::size_t d = 1;
std::size_t q = 1;
std::size_t r = 1;
do
{
x = y;
for(std::size_t i = 0; i <= r; i++) y = mulmod(y, a, num);
std::size_t j = 0;
do
{
ys = y;
for(std::size_t i = 0; i <= std::min(m, r-j); i++)
{
y = mulmod(y, a, num);
q *= (std::max(x, y) - std::min(x, y)) % num;
}
d = gcd(q, num);
j += m;
}
while(j < r && d == 1);
r *= 2;
}
while(d == 1);
if(d == num)
{
do
{
ys = mulmod(ys, a, num);
d = gcd(std::max(x, ys) - std::min(x, ys), num);
}
while(d == 1);
}
return d;
}
bool inpal::algorithm::pal_test(std::size_t num)
{
std::string rev = std::to_string(num);
//checks if half the reverse of rev is equal to the other half of rev
if(std::equal(rev.begin(), rev.begin() + rev.size() / 2, rev.rbegin())) return true;
return false;
}
<|endoftext|> |
<commit_before>//=============================================================================
// ■ VMGS/Scene/EditorMainScene.cpp
//-----------------------------------------------------------------------------
// 编辑器场景。
//=============================================================================
#include "../VMGS.hpp"
#include "../Control/GodView.hpp"
#include "../Control/FirstPersonView.hpp"
#include "../GameObject/SkyBox/SkyBox.hpp"
namespace VM76 {
GodView* ctl;
FirstPersonView* ctl_fp;
SkyBox* sky;
bool fp_control = false;
//-------------------------------------------------------------------------
// ● 场景开始
//-------------------------------------------------------------------------
EditorMainScene::EditorMainScene() {
obj = new GObject();
shader_textured.add_file(GL_VERTEX_SHADER, "../Media/shaders/gbuffers_textured.vsh");
shader_textured.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/gbuffers_textured.fsh");
shader_textured.link_program();
shader_basic.add_file(GL_VERTEX_SHADER, "../Media/shaders/gbuffers_basic.vsh");
shader_basic.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/gbuffers_basic.fsh");
shader_basic.link_program();
gui.add_file(GL_VERTEX_SHADER, "../Media/shaders/gui.vsh");
gui.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/gui.fsh");
gui.link_program();
post_processing.add_file(GL_VERTEX_SHADER, "../Media/shaders/PostProcessing.vsh");
post_processing.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/PostProcessing.fsh");
post_processing.link_program();
GLuint* gbuffers_type = new GLuint[3]{GL_RGB8, GL_RGB16F, GL_RGB8};
postBuffer = new RenderBuffer(VMDE->width, VMDE->height, 3, gbuffers_type);
projection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);
view = glm::lookAt(
glm::vec3(0.0, 2.6, 0.0),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.0, 1.0, 0.0)
);
// Set up hand block indicator's matrix
glm::mat4 block_display = glm::translate(
glm::mat4(1.0),
glm::vec3(0.02, 0.06, 0.2)
);
block_display = glm::scale(block_display, glm::vec3(0.1f));
block_display = glm::rotate(block_display,
VMath::PIf / 4.0f,
glm::vec3(1.0, 0.0, 0.0)
);
block_display = glm::rotate(block_display,
VMath::PIf / 4.0f,
glm::vec3(0.0, 1.0, 0.0)
);
TiledMap::init_cinstances(clist);
for (int i = 0; i < 16; i++) {
clist[i]->mat[0] = new glm::mat4[1]; clist[i]->mat[0][0] = block_display;
clist[i]->mat[1] = new glm::mat4[1]; clist[i]->mat[1][0] = block_display;
clist[i]->mat[2] = new glm::mat4[1]; clist[i]->mat[2][0] = block_display;
clist[i]->mat[3] = new glm::mat4[1]; clist[i]->mat[3][0] = block_display;
clist[i]->mat[4] = new glm::mat4[1]; clist[i]->mat[4][0] = block_display;
clist[i]->mat[5] = new glm::mat4[1]; clist[i]->mat[5][0] = block_display;
clist[i]->update_instance(1,1,1,1,1,1);
}
block_pointer.obj->data.mat_c = 1;
ctl = new GodView();
ctl_fp = new FirstPersonView();
ctl->init_control();
ctl_fp->init_control();
ctl->cam.wpos = glm::vec3(64.0, 72.0, 64.0);
ctl_fp->game_player.wpos = glm::vec3(64.0, 72.0, 64.0);
sky = new SkyBox("../Media/skybox.png");
}
//-------------------------------------------------------------------------
// ● 按键回调
//-------------------------------------------------------------------------
void EditorMainScene::key_callback(
GLFWwindow* window, int key, int scancode, int action, int mods
) {
#define PRESS(n) key == n && action == GLFW_PRESS
if (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -1.0));
if (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 1.0));
if (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 1.0, 0.0));
if (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -1.0, 0.0));
if (PRESS(GLFW_KEY_F5)) fp_control = !fp_control;
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_1)) hand_id = 1;
if (PRESS(GLFW_KEY_2)) hand_id = 2;
if (PRESS(GLFW_KEY_3)) hand_id = 3;
if (PRESS(GLFW_KEY_4)) hand_id = 4;
if (PRESS(GLFW_KEY_5)) hand_id = 5;
if (PRESS(GLFW_KEY_6)) hand_id = 6;
if (PRESS(GLFW_KEY_7)) hand_id = 7;
if (PRESS(GLFW_KEY_8)) hand_id = 8;
if (PRESS(GLFW_KEY_9)) hand_id = 9;
if (PRESS(GLFW_KEY_SPACE)) {
map.place_block(obj->pos, hand_id);
}
static Audio::Channel_Vorbis* loop = NULL;
static Audio::Channel_Triangle* triangle = NULL;
static Audio::Channel_Sine* sine = NULL;
if (PRESS(GLFW_KEY_SEMICOLON)) {
Audio::play_sound("../Media/soft-ping.ogg", false);
}
if (PRESS(GLFW_KEY_APOSTROPHE)) {
if (loop) {
Audio::stop(loop);
loop = NULL;
} else {
loop = Audio::play_sound("../Media/loop-test.ogg", true, .1f);
}
}
if (PRESS(GLFW_KEY_LEFT_BRACKET)) {
if (triangle) {
Audio::stop(triangle);
triangle = NULL;
} else {
triangle = new Audio::Channel_Triangle(440);
Audio::play_channel(triangle);
}
}
if (PRESS(GLFW_KEY_RIGHT_BRACKET)) {
if (sine) {
Audio::stop(sine);
sine = NULL;
} else {
sine = new Audio::Channel_Sine(440);
Audio::play_channel(sine);
}
}
#undef PRESS
}
//-------------------------------------------------------------------------
// ● 刷新
//-------------------------------------------------------------------------
void EditorMainScene::update() {
if (fp_control)
ctl->update_control();
else
ctl_fp->update_control();
}
//-------------------------------------------------------------------------
// ● 渲染
//-------------------------------------------------------------------------
void EditorMainScene::render() {
shader_textured.use();
// Setup uniforms
shader_textured.set_float("brightness", VMDE->state.brightness);
shader_textured.set_texture("colortex0", &tile_texture, 0);
postBuffer->bind();
RenderBuffer::clearColorDepth(0.5, 0.7, 1.0, 0.0);
postBuffer->set_draw_buffers();
// Textured blocks rendering
shader_textured.ProjectionView(projection, view);
map.render();
sky->render();
// Setup uniforms
// Non textured rendering
shader_basic.use();
shader_basic.set_float("opaque", 0.5);
shader_textured.ProjectionView(projection, view);
block_pointer.mat[0] = obj->transform();
block_pointer.update_instance(1);
block_pointer.render();
axe.render();
postBuffer->unbind();
post_processing.use();
post_processing.set_texture("colortex", postBuffer->texture_buffer[0], 0);
post_processing.set_texture("gnormal", postBuffer->texture_buffer[2], 1);
glm::vec3 sunVec = glm::mat3(view) * glm::vec3(cos(VMath::PI * 0.25), sin(VMath::PI * 0.25), sin(VMath::PI * 0.25) * 0.3f);
glUniform3f(glGetUniformLocation(post_processing.program, "sunVec"), sunVec.x, sunVec.y, sunVec.z);
PostProcessingManager::Blit2D();
// GUI rendering
gui.use();
gui.set_texture("atlastex", &tile_texture, 0);
gui.ProjectionView(gui_2d_projection, glm::mat4(1.0));
GDrawable::disable_depth_test();
if (hand_id > 0) clist[hand_id - 1]->render();
if (SceneManager::render_debug_info) {
char info[64];
sprintf(info, "Hand ID: %d Pointer ID: %d",
hand_id,
map.map->tidQuery(obj->pos.x, obj->pos.y, obj->pos.z)
);
trex->instanceRenderText(
info, gui_2d_projection,
glm::mat4(1.0),
glm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.88, 0.0)),
0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE
);
sprintf(info, "Pointer pos: (%.0f, %.0f, %.0f)",
obj->pos.x, obj->pos.y, obj->pos.z
);
trex->instanceRenderText(
info, gui_2d_projection,
glm::mat4(1.0),
glm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.82, 0.0)),
0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE
);
}
GDrawable::enable_depth_test();
}
//-------------------------------------------------------------------------
// ● 释放
//-------------------------------------------------------------------------
EditorMainScene::~EditorMainScene() {
for (int i = 0; i < 16; i++) VMDE_Dispose(delete, clist[i]);
VMDE_Dispose(delete, trex);
}
}
<commit_msg>O键放大!<commit_after>//=============================================================================
// ■ VMGS/Scene/EditorMainScene.cpp
//-----------------------------------------------------------------------------
// 编辑器场景。
//=============================================================================
#include "../VMGS.hpp"
#include "../Control/GodView.hpp"
#include "../Control/FirstPersonView.hpp"
#include "../GameObject/SkyBox/SkyBox.hpp"
namespace VM76 {
GodView* ctl;
FirstPersonView* ctl_fp;
SkyBox* sky;
bool fp_control = false;
//-------------------------------------------------------------------------
// ● 场景开始
//-------------------------------------------------------------------------
EditorMainScene::EditorMainScene() {
obj = new GObject();
shader_textured.add_file(GL_VERTEX_SHADER, "../Media/shaders/gbuffers_textured.vsh");
shader_textured.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/gbuffers_textured.fsh");
shader_textured.link_program();
shader_basic.add_file(GL_VERTEX_SHADER, "../Media/shaders/gbuffers_basic.vsh");
shader_basic.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/gbuffers_basic.fsh");
shader_basic.link_program();
gui.add_file(GL_VERTEX_SHADER, "../Media/shaders/gui.vsh");
gui.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/gui.fsh");
gui.link_program();
post_processing.add_file(GL_VERTEX_SHADER, "../Media/shaders/PostProcessing.vsh");
post_processing.add_file(GL_FRAGMENT_SHADER, "../Media/shaders/PostProcessing.fsh");
post_processing.link_program();
GLuint* gbuffers_type = new GLuint[3]{GL_RGB8, GL_RGB16F, GL_RGB8};
postBuffer = new RenderBuffer(VMDE->width, VMDE->height, 3, gbuffers_type);
projection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);
view = glm::lookAt(
glm::vec3(0.0, 2.6, 0.0),
glm::vec3(0.0, 0.0, 0.0),
glm::vec3(0.0, 1.0, 0.0)
);
// Set up hand block indicator's matrix
glm::mat4 block_display = glm::translate(
glm::mat4(1.0),
glm::vec3(0.02, 0.06, 0.2)
);
block_display = glm::scale(block_display, glm::vec3(0.1f));
block_display = glm::rotate(block_display,
VMath::PIf / 4.0f,
glm::vec3(1.0, 0.0, 0.0)
);
block_display = glm::rotate(block_display,
VMath::PIf / 4.0f,
glm::vec3(0.0, 1.0, 0.0)
);
TiledMap::init_cinstances(clist);
for (int i = 0; i < 16; i++) {
clist[i]->mat[0] = new glm::mat4[1]; clist[i]->mat[0][0] = block_display;
clist[i]->mat[1] = new glm::mat4[1]; clist[i]->mat[1][0] = block_display;
clist[i]->mat[2] = new glm::mat4[1]; clist[i]->mat[2][0] = block_display;
clist[i]->mat[3] = new glm::mat4[1]; clist[i]->mat[3][0] = block_display;
clist[i]->mat[4] = new glm::mat4[1]; clist[i]->mat[4][0] = block_display;
clist[i]->mat[5] = new glm::mat4[1]; clist[i]->mat[5][0] = block_display;
clist[i]->update_instance(1,1,1,1,1,1);
}
block_pointer.obj->data.mat_c = 1;
ctl = new GodView();
ctl_fp = new FirstPersonView();
ctl->init_control();
ctl_fp->init_control();
ctl->cam.wpos = glm::vec3(64.0, 72.0, 64.0);
ctl_fp->game_player.wpos = glm::vec3(64.0, 72.0, 64.0);
sky = new SkyBox("../Media/skybox.png");
}
//-------------------------------------------------------------------------
// ● 按键回调
//-------------------------------------------------------------------------
bool magnify = false;
bool magnifyPrev = false;
void EditorMainScene::key_callback(
GLFWwindow* window, int key, int scancode, int action, int mods
) {
#define PRESS(n) key == n && action == GLFW_PRESS
if (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(1.0, 0.0, 0.0));
if (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -1.0));
if (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 1.0));
if (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 1.0, 0.0));
if (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -1.0, 0.0));
if (PRESS(GLFW_KEY_F5)) fp_control = !fp_control;
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_0)) hand_id = 0;
if (PRESS(GLFW_KEY_1)) hand_id = 1;
if (PRESS(GLFW_KEY_2)) hand_id = 2;
if (PRESS(GLFW_KEY_3)) hand_id = 3;
if (PRESS(GLFW_KEY_4)) hand_id = 4;
if (PRESS(GLFW_KEY_5)) hand_id = 5;
if (PRESS(GLFW_KEY_6)) hand_id = 6;
if (PRESS(GLFW_KEY_7)) hand_id = 7;
if (PRESS(GLFW_KEY_8)) hand_id = 8;
if (PRESS(GLFW_KEY_9)) hand_id = 9;
if (PRESS(GLFW_KEY_SPACE)) {
map.place_block(obj->pos, hand_id);
}
if (PRESS(GLFW_KEY_O)) {
magnify = !magnify;
if (magnify) projection = glm::perspective(0.3f, aspect_ratio, 0.1f, 1000.0f);
else projection = glm::perspective(1.3f, aspect_ratio, 0.1f, 1000.0f);
}
static Audio::Channel_Vorbis* loop = NULL;
static Audio::Channel_Triangle* triangle = NULL;
static Audio::Channel_Sine* sine = NULL;
if (PRESS(GLFW_KEY_SEMICOLON)) {
Audio::play_sound("../Media/soft-ping.ogg", false);
}
if (PRESS(GLFW_KEY_APOSTROPHE)) {
if (loop) {
Audio::stop(loop);
loop = NULL;
} else {
loop = Audio::play_sound("../Media/loop-test.ogg", true, .1f);
}
}
if (PRESS(GLFW_KEY_LEFT_BRACKET)) {
if (triangle) {
Audio::stop(triangle);
triangle = NULL;
} else {
triangle = new Audio::Channel_Triangle(440);
Audio::play_channel(triangle);
}
}
if (PRESS(GLFW_KEY_RIGHT_BRACKET)) {
if (sine) {
Audio::stop(sine);
sine = NULL;
} else {
sine = new Audio::Channel_Sine(440);
Audio::play_channel(sine);
}
}
#undef PRESS
}
//-------------------------------------------------------------------------
// ● 刷新
//-------------------------------------------------------------------------
void EditorMainScene::update() {
if (fp_control)
ctl->update_control();
else
ctl_fp->update_control();
}
//-------------------------------------------------------------------------
// ● 渲染
//-------------------------------------------------------------------------
void EditorMainScene::render() {
shader_textured.use();
// Setup uniforms
shader_textured.set_float("brightness", VMDE->state.brightness);
shader_textured.set_texture("colortex0", &tile_texture, 0);
postBuffer->bind();
RenderBuffer::clearColorDepth(0.5, 0.7, 1.0, 0.0);
postBuffer->set_draw_buffers();
// Textured blocks rendering
shader_textured.ProjectionView(projection, view);
map.render();
sky->render();
// Setup uniforms
// Non textured rendering
shader_basic.use();
shader_basic.set_float("opaque", 0.5);
shader_textured.ProjectionView(projection, view);
block_pointer.mat[0] = obj->transform();
block_pointer.update_instance(1);
block_pointer.render();
axe.render();
postBuffer->unbind();
post_processing.use();
post_processing.set_texture("colortex", postBuffer->texture_buffer[0], 0);
post_processing.set_texture("gnormal", postBuffer->texture_buffer[2], 1);
glm::vec3 sunVec = glm::mat3(view) * glm::vec3(cos(VMath::PI * 0.25), sin(VMath::PI * 0.25), sin(VMath::PI * 0.25) * 0.3f);
glUniform3f(glGetUniformLocation(post_processing.program, "sunVec"), sunVec.x, sunVec.y, sunVec.z);
PostProcessingManager::Blit2D();
// GUI rendering
gui.use();
gui.set_texture("atlastex", &tile_texture, 0);
gui.ProjectionView(gui_2d_projection, glm::mat4(1.0));
GDrawable::disable_depth_test();
if (hand_id > 0) clist[hand_id - 1]->render();
if (SceneManager::render_debug_info) {
char info[64];
sprintf(info, "Hand ID: %d Pointer ID: %d",
hand_id,
map.map->tidQuery(obj->pos.x, obj->pos.y, obj->pos.z)
);
trex->instanceRenderText(
info, gui_2d_projection,
glm::mat4(1.0),
glm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.88, 0.0)),
0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE
);
sprintf(info, "Pointer pos: (%.0f, %.0f, %.0f)",
obj->pos.x, obj->pos.y, obj->pos.z
);
trex->instanceRenderText(
info, gui_2d_projection,
glm::mat4(1.0),
glm::translate(glm::mat4(1.0), glm::vec3(0.01, 0.82, 0.0)),
0.025, 0.05, TextRenderer::TextDecorationType::OUTLINE
);
}
GDrawable::enable_depth_test();
}
//-------------------------------------------------------------------------
// ● 释放
//-------------------------------------------------------------------------
EditorMainScene::~EditorMainScene() {
for (int i = 0; i < 16; i++) VMDE_Dispose(delete, clist[i]);
VMDE_Dispose(delete, trex);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/standard.h"
#include "pubkey.h"
#include "script/script.h"
#include "util.h"
#include "utilstrencodings.h"
#include <boost/foreach.hpp>
using namespace std;
typedef vector<unsigned char> valtype;
unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;
CScriptID::CScriptID(const CScript& in) : uint160(in.size() ? Hash160(in.begin(), in.end()) : 0) {}
const char* GetTxnOutputType(txnouttype t)
{
switch (t)
{
case TX_NONSTANDARD: return "nonstandard";
case TX_PUBKEY: return "pubkey";
case TX_PUBKEYHASH: return "pubkeyhash";
case TX_SCRIPTHASH: return "scripthash";
case TX_MULTISIG: return "multisig";
case TX_NULL_DATA: return "nulldata";
}
return NULL;
}
/**
* Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
*/
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
{
// Templates
static multimap<txnouttype, CScript> mTemplates;
if (mTemplates.empty())
{
// Standard tx, sender provides pubkey, receiver adds signature
mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
// Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
// Sender provides N pubkeys, receivers provides M signatures
mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
// Empty, provably prunable, data-carrying output
if (GetBoolArg("-datacarrier", true))
mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
}
// Shortcut for pay-to-script-hash, which are more constrained than the other types:
// it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
if (scriptPubKey.IsPayToScriptHash())
{
typeRet = TX_SCRIPTHASH;
vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
vSolutionsRet.push_back(hashBytes);
return true;
}
// Scan templates
const CScript& script1 = scriptPubKey;
BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
{
const CScript& script2 = tplate.second;
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
vector<unsigned char> vch1, vch2;
// Compare
CScript::const_iterator pc1 = script1.begin();
CScript::const_iterator pc2 = script2.begin();
while (true)
{
if (pc1 == script1.end() && pc2 == script2.end())
{
// Found a match
typeRet = tplate.first;
if (typeRet == TX_MULTISIG)
{
// Additional checks for TX_MULTISIG:
unsigned char m = vSolutionsRet.front()[0];
unsigned char n = vSolutionsRet.back()[0];
if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
return false;
}
return true;
}
if (!script1.GetOp(pc1, opcode1, vch1))
break;
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Template matching opcodes:
if (opcode2 == OP_PUBKEYS)
{
while (vch1.size() >= 33 && vch1.size() <= 65)
{
vSolutionsRet.push_back(vch1);
if (!script1.GetOp(pc1, opcode1, vch1))
break;
}
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Normal situation is to fall through
// to other if/else statements
}
if (opcode2 == OP_PUBKEY)
{
if (vch1.size() < 33 || vch1.size() > 65)
break;
vSolutionsRet.push_back(vch1);
}
else if (opcode2 == OP_PUBKEYHASH)
{
if (vch1.size() != sizeof(uint160))
break;
vSolutionsRet.push_back(vch1);
}
else if (opcode2 == OP_SMALLINTEGER)
{ // Single-byte small integer pushed onto vSolutions
if (opcode1 == OP_0 ||
(opcode1 >= OP_1 && opcode1 <= OP_16))
{
char n = (char)CScript::DecodeOP_N(opcode1);
vSolutionsRet.push_back(valtype(1, n));
}
else
break;
}
else if (opcode2 == OP_SMALLDATA)
{
// small pushdata, <= nMaxDatacarrierBytes
if (vch1.size() > nMaxDatacarrierBytes)
break;
}
else if (opcode1 != opcode2 || vch1 != vch2)
{
// Others must match exactly
break;
}
}
}
vSolutionsRet.clear();
typeRet = TX_NONSTANDARD;
return false;
}
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
{
switch (t)
{
case TX_NONSTANDARD:
case TX_NULL_DATA:
return -1;
case TX_PUBKEY:
return 1;
case TX_PUBKEYHASH:
return 2;
case TX_MULTISIG:
if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
return -1;
return vSolutions[0][0] + 1;
case TX_SCRIPTHASH:
return 1; // doesn't include args needed by the script
}
return -1;
}
bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
{
vector<valtype> vSolutions;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_MULTISIG)
{
unsigned char m = vSolutions.front()[0];
unsigned char n = vSolutions.back()[0];
// Support up to x-of-3 multisig txns as standard
if (n < 1 || n > 3)
return false;
if (m < 1 || m > n)
return false;
}
return whichType != TX_NONSTANDARD;
}
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
CPubKey pubKey(vSolutions[0]);
if (!pubKey.IsValid())
return false;
addressRet = pubKey.GetID();
return true;
}
else if (whichType == TX_PUBKEYHASH)
{
addressRet = CKeyID(uint160(vSolutions[0]));
return true;
}
else if (whichType == TX_SCRIPTHASH)
{
addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
{
addressRet.clear();
typeRet = TX_NONSTANDARD;
vector<valtype> vSolutions;
if (!Solver(scriptPubKey, typeRet, vSolutions))
return false;
if (typeRet == TX_NULL_DATA){
// This is data, not addresses
return false;
}
if (typeRet == TX_MULTISIG)
{
nRequiredRet = vSolutions.front()[0];
for (unsigned int i = 1; i < vSolutions.size()-1; i++)
{
CPubKey pubKey(vSolutions[i]);
if (!pubKey.IsValid())
continue;
CTxDestination address = pubKey.GetID();
addressRet.push_back(address);
}
if (addressRet.empty())
return false;
}
else
{
nRequiredRet = 1;
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address))
return false;
addressRet.push_back(address);
}
return true;
}
namespace
{
class CScriptVisitor : public boost::static_visitor<bool>
{
private:
CScript *script;
public:
CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();
return false;
}
bool operator()(const CKeyID &keyID) const {
script->clear();
*script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
return true;
}
bool operator()(const CScriptID &scriptID) const {
script->clear();
*script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
return true;
}
};
}
CScript GetScriptForDestination(const CTxDestination& dest)
{
CScript script;
boost::apply_visitor(CScriptVisitor(&script), dest);
return script;
}
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
{
CScript script;
script << CScript::EncodeOP_N(nRequired);
BOOST_FOREACH(const CPubKey& key, keys)
script << ToByteVector(key);
script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
return script;
}
<commit_msg>Fix CScriptID(const CScript& in) in empty script case<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/standard.h"
#include "pubkey.h"
#include "script/script.h"
#include "util.h"
#include "utilstrencodings.h"
#include <boost/foreach.hpp>
using namespace std;
typedef vector<unsigned char> valtype;
unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;
CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {}
const char* GetTxnOutputType(txnouttype t)
{
switch (t)
{
case TX_NONSTANDARD: return "nonstandard";
case TX_PUBKEY: return "pubkey";
case TX_PUBKEYHASH: return "pubkeyhash";
case TX_SCRIPTHASH: return "scripthash";
case TX_MULTISIG: return "multisig";
case TX_NULL_DATA: return "nulldata";
}
return NULL;
}
/**
* Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
*/
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
{
// Templates
static multimap<txnouttype, CScript> mTemplates;
if (mTemplates.empty())
{
// Standard tx, sender provides pubkey, receiver adds signature
mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
// Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
// Sender provides N pubkeys, receivers provides M signatures
mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
// Empty, provably prunable, data-carrying output
if (GetBoolArg("-datacarrier", true))
mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
}
// Shortcut for pay-to-script-hash, which are more constrained than the other types:
// it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
if (scriptPubKey.IsPayToScriptHash())
{
typeRet = TX_SCRIPTHASH;
vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
vSolutionsRet.push_back(hashBytes);
return true;
}
// Scan templates
const CScript& script1 = scriptPubKey;
BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
{
const CScript& script2 = tplate.second;
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
vector<unsigned char> vch1, vch2;
// Compare
CScript::const_iterator pc1 = script1.begin();
CScript::const_iterator pc2 = script2.begin();
while (true)
{
if (pc1 == script1.end() && pc2 == script2.end())
{
// Found a match
typeRet = tplate.first;
if (typeRet == TX_MULTISIG)
{
// Additional checks for TX_MULTISIG:
unsigned char m = vSolutionsRet.front()[0];
unsigned char n = vSolutionsRet.back()[0];
if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
return false;
}
return true;
}
if (!script1.GetOp(pc1, opcode1, vch1))
break;
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Template matching opcodes:
if (opcode2 == OP_PUBKEYS)
{
while (vch1.size() >= 33 && vch1.size() <= 65)
{
vSolutionsRet.push_back(vch1);
if (!script1.GetOp(pc1, opcode1, vch1))
break;
}
if (!script2.GetOp(pc2, opcode2, vch2))
break;
// Normal situation is to fall through
// to other if/else statements
}
if (opcode2 == OP_PUBKEY)
{
if (vch1.size() < 33 || vch1.size() > 65)
break;
vSolutionsRet.push_back(vch1);
}
else if (opcode2 == OP_PUBKEYHASH)
{
if (vch1.size() != sizeof(uint160))
break;
vSolutionsRet.push_back(vch1);
}
else if (opcode2 == OP_SMALLINTEGER)
{ // Single-byte small integer pushed onto vSolutions
if (opcode1 == OP_0 ||
(opcode1 >= OP_1 && opcode1 <= OP_16))
{
char n = (char)CScript::DecodeOP_N(opcode1);
vSolutionsRet.push_back(valtype(1, n));
}
else
break;
}
else if (opcode2 == OP_SMALLDATA)
{
// small pushdata, <= nMaxDatacarrierBytes
if (vch1.size() > nMaxDatacarrierBytes)
break;
}
else if (opcode1 != opcode2 || vch1 != vch2)
{
// Others must match exactly
break;
}
}
}
vSolutionsRet.clear();
typeRet = TX_NONSTANDARD;
return false;
}
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
{
switch (t)
{
case TX_NONSTANDARD:
case TX_NULL_DATA:
return -1;
case TX_PUBKEY:
return 1;
case TX_PUBKEYHASH:
return 2;
case TX_MULTISIG:
if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
return -1;
return vSolutions[0][0] + 1;
case TX_SCRIPTHASH:
return 1; // doesn't include args needed by the script
}
return -1;
}
bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
{
vector<valtype> vSolutions;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_MULTISIG)
{
unsigned char m = vSolutions.front()[0];
unsigned char n = vSolutions.back()[0];
// Support up to x-of-3 multisig txns as standard
if (n < 1 || n > 3)
return false;
if (m < 1 || m > n)
return false;
}
return whichType != TX_NONSTANDARD;
}
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
CPubKey pubKey(vSolutions[0]);
if (!pubKey.IsValid())
return false;
addressRet = pubKey.GetID();
return true;
}
else if (whichType == TX_PUBKEYHASH)
{
addressRet = CKeyID(uint160(vSolutions[0]));
return true;
}
else if (whichType == TX_SCRIPTHASH)
{
addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
{
addressRet.clear();
typeRet = TX_NONSTANDARD;
vector<valtype> vSolutions;
if (!Solver(scriptPubKey, typeRet, vSolutions))
return false;
if (typeRet == TX_NULL_DATA){
// This is data, not addresses
return false;
}
if (typeRet == TX_MULTISIG)
{
nRequiredRet = vSolutions.front()[0];
for (unsigned int i = 1; i < vSolutions.size()-1; i++)
{
CPubKey pubKey(vSolutions[i]);
if (!pubKey.IsValid())
continue;
CTxDestination address = pubKey.GetID();
addressRet.push_back(address);
}
if (addressRet.empty())
return false;
}
else
{
nRequiredRet = 1;
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address))
return false;
addressRet.push_back(address);
}
return true;
}
namespace
{
class CScriptVisitor : public boost::static_visitor<bool>
{
private:
CScript *script;
public:
CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();
return false;
}
bool operator()(const CKeyID &keyID) const {
script->clear();
*script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
return true;
}
bool operator()(const CScriptID &scriptID) const {
script->clear();
*script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
return true;
}
};
}
CScript GetScriptForDestination(const CTxDestination& dest)
{
CScript script;
boost::apply_visitor(CScriptVisitor(&script), dest);
return script;
}
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
{
CScript script;
script << CScript::EncodeOP_N(nRequired);
BOOST_FOREACH(const CPubKey& key, keys)
script << ToByteVector(key);
script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
return script;
}
<|endoftext|> |
<commit_before>#include <qtest.h>
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlcomponent.h>
#include <QtDeclarative/qmldom.h>
#include <QtCore/QDebug>
class tst_qmldom : public QObject
{
Q_OBJECT
public:
tst_qmldom() {}
private slots:
void loadSimple();
void loadProperties();
void loadChildObject();
private:
QmlEngine engine;
};
void tst_qmldom::loadSimple()
{
QByteArray qml = "Item {}";
//QByteArray qml = "<Item/>";
QmlDomDocument document;
QVERIFY(document.load(&engine, qml));
QVERIFY(document.loadError().isEmpty());
QmlDomObject rootObject = document.rootObject();
QVERIFY(rootObject.isValid());
QVERIFY(!rootObject.isComponent());
QVERIFY(!rootObject.isCustomType());
QVERIFY(rootObject.objectType() == "Item");
}
void tst_qmldom::loadProperties()
{
QByteArray qml = "Item { id : item; x : 300; visible : true }";
//QByteArray qml = "<Item id='item' x='300' visible='true'/>";
QmlDomDocument document;
QVERIFY(document.load(&engine, qml));
QmlDomObject rootObject = document.rootObject();
QVERIFY(rootObject.isValid());
QVERIFY(rootObject.objectId() == "item");
QVERIFY(rootObject.properties().size() == 2);
QmlDomProperty xProperty = rootObject.property("x");
QVERIFY(xProperty.propertyName() == "x");
QVERIFY(xProperty.value().isLiteral());
QVERIFY(xProperty.value().toLiteral().literal() == "300");
QmlDomProperty visibleProperty = rootObject.property("visible");
QVERIFY(visibleProperty.propertyName() == "visible");
QVERIFY(visibleProperty.value().isLiteral());
QVERIFY(visibleProperty.value().toLiteral().literal() == "true");
}
void tst_qmldom::loadChildObject()
{
QByteArray qml = "Item { Item {} }";
//QByteArray qml = "<Item> <Item/> </Item>";
QmlDomDocument document;
QVERIFY(document.load(&engine, qml));
QmlDomObject rootItem = document.rootObject();
QVERIFY(rootItem.isValid());
QVERIFY(rootItem.properties().size() == 1);
QmlDomProperty listProperty = rootItem.properties().at(0);
QVERIFY(listProperty.isDefaultProperty());
QVERIFY(listProperty.value().isList());
QmlDomList list = listProperty.value().toList();
QVERIFY(list.values().size() == 1);
QmlDomObject childItem = list.values().first().toObject();
QVERIFY(childItem.isValid());
QVERIFY(childItem.objectType() == "Item");
}
QTEST_MAIN(tst_qmldom)
#include "tst_qmldom.moc"
<commit_msg>Added (failing) testcase for QmlDomValueValueSource.<commit_after>#include <qtest.h>
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlcomponent.h>
#include <QtDeclarative/qmldom.h>
#include <QtCore/QDebug>
class tst_qmldom : public QObject
{
Q_OBJECT
public:
tst_qmldom() {}
private slots:
void loadSimple();
void loadProperties();
void loadChildObject();
void testValueSource();
private:
QmlEngine engine;
};
void tst_qmldom::loadSimple()
{
QByteArray qml = "Item {}";
//QByteArray qml = "<Item/>";
QmlDomDocument document;
QVERIFY(document.load(&engine, qml));
QVERIFY(document.loadError().isEmpty());
QmlDomObject rootObject = document.rootObject();
QVERIFY(rootObject.isValid());
QVERIFY(!rootObject.isComponent());
QVERIFY(!rootObject.isCustomType());
QVERIFY(rootObject.objectType() == "Item");
}
void tst_qmldom::loadProperties()
{
QByteArray qml = "Item { id : item; x : 300; visible : true }";
//QByteArray qml = "<Item id='item' x='300' visible='true'/>";
QmlDomDocument document;
QVERIFY(document.load(&engine, qml));
QmlDomObject rootObject = document.rootObject();
QVERIFY(rootObject.isValid());
QVERIFY(rootObject.objectId() == "item");
QVERIFY(rootObject.properties().size() == 2);
QmlDomProperty xProperty = rootObject.property("x");
QVERIFY(xProperty.propertyName() == "x");
QVERIFY(xProperty.value().isLiteral());
QVERIFY(xProperty.value().toLiteral().literal() == "300");
QmlDomProperty visibleProperty = rootObject.property("visible");
QVERIFY(visibleProperty.propertyName() == "visible");
QVERIFY(visibleProperty.value().isLiteral());
QVERIFY(visibleProperty.value().toLiteral().literal() == "true");
}
void tst_qmldom::loadChildObject()
{
QByteArray qml = "Item { Item {} }";
//QByteArray qml = "<Item> <Item/> </Item>";
QmlDomDocument document;
QVERIFY(document.load(&engine, qml));
QmlDomObject rootItem = document.rootObject();
QVERIFY(rootItem.isValid());
QVERIFY(rootItem.properties().size() == 1);
QmlDomProperty listProperty = rootItem.properties().at(0);
QVERIFY(listProperty.isDefaultProperty());
QVERIFY(listProperty.value().isList());
QmlDomList list = listProperty.value().toList();
QVERIFY(list.values().size() == 1);
QmlDomObject childItem = list.values().first().toObject();
QVERIFY(childItem.isValid());
QVERIFY(childItem.objectType() == "Item");
}
void tst_qmldom::testValueSource()
{
QByteArray qml = "Rect { height: Follow { spring: 1.4; damping: .15; source: Math.min(Math.max(-130, value*2.2 - 130), 133); }}";
QmlEngine freshEngine;
QmlDomDocument document;
QVERIFY(document.load(&freshEngine, qml));
QmlDomObject rootItem = document.rootObject();
QVERIFY(rootItem.isValid());
QmlDomProperty heightProperty = rootItem.properties().at(0);
QVERIFY(heightProperty.propertyName() == "height");
QVERIFY(heightProperty.value().isValueSource());
const QmlDomValueValueSource valueSource = heightProperty.value().toValueSource();
QVERIFY(valueSource.object().isValid());
}
QTEST_MAIN(tst_qmldom)
#include "tst_qmldom.moc"
<|endoftext|> |
<commit_before>/********************************************
* Program to demonstrate the Gamma Function *
* *
* C++ version by J-P Moreau *
* (www.jpmoreau.fr) *
* ----------------------------------------- *
* Reference: *
* "Numerical Recipes, By W.H. Press, B.P. *
* Flannery, S.A. Teukolsky and T. Vetter- *
* ling, Cambridge University Press, 1986" *
* [BIBLI 08]. *
* ----------------------------------------- *
* SAMPLE RUN: *
* *
* X Gamma(X) *
* ------------------------- *
* 0.500000 1.772454 *
* 1.000000 1.000000 *
* 1.500000 0.886227 *
* 2.000000 1.000000 *
* 2.500000 1.329340 *
* 3.000000 2.000000 *
* 3.500000 3.323351 *
* 4.000000 6.000000 *
* 4.500000 11.631728 *
* 5.000000 24.000000 *
* *
********************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <enerc.h>
#define half 0.5
#define increment 0.0000005
#define one 1.0
#define fpf 5.5
#define zero 0.0
APPROX double x, y;
int i;
/******************************************
* FUNCTION GAMMA(X) *
* --------------------------------------- *
* Returns the value of Gamma(x) in double *
* precision as EXP(LN(GAMMA(X))) for X>0. *
******************************************/
APPROX double Gamma(APPROX double xx) {
APPROX double cof[7],stp,x,tmp,ser;
int j;
cof[1]=76.18009173;
cof[2]=-86.50532033;
cof[3]=24.01409822;
cof[4]=-1.231739516;
cof[5]=0.120858003e-2;
cof[6]=-0.536382e-5;
stp=2.50662827465;
x=xx-one;
tmp=x+fpf;
tmp=(x+half)*log(tmp)-tmp;
ser=one;
for (j=1; j<7; j++) {
x=x+one;
ser=ser+cof[j]/x;
}
return (exp(tmp+log(stp*ser)));
}
int main() {
FILE *file;
char *outputfile = "my_output.txt";
int retval;
APPROX double xval[1000000];
APPROX double yval[1000000];
accept_roi_begin();
x = zero;
for (i = 0; i < 1000000; i++) {
x += increment;
y = Gamma(x);
xval[i] = x;
yval[i] = y;
}
accept_roi_end();
file = fopen(outputfile, "w");
if (file == NULL) {
perror("fopen for write failed\n");
return EXIT_FAILURE;
}
for (i = 0; i < 1000000; i++) {
retval = fprintf(file, "%.10f\n", ENDORSE(xval[i]));
if (retval < 0) {
perror("fprintf of x-value failed\n");
return EXIT_FAILURE;
}
fprintf(file, "%.10f\n", yval[i]);
retval = fprintf(file, "%.10f\n", ENDORSE(yval[i]));
if (retval < 0) {
perror("fprintf of y-value failed\n");
return EXIT_FAILURE;
}
}
retval = fclose(file);
if (retval != 0) {
perror("fclose failed\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// end of file gamma.cpp
<commit_msg>Created new test program for debugging memcpy<commit_after>/********************************************
* Program to demonstrate the Gamma Function *
* *
* C++ version by J-P Moreau *
* (www.jpmoreau.fr) *
* ----------------------------------------- *
* Reference: *
* "Numerical Recipes, By W.H. Press, B.P. *
* Flannery, S.A. Teukolsky and T. Vetter- *
* ling, Cambridge University Press, 1986" *
* [BIBLI 08]. *
* ----------------------------------------- *
* SAMPLE RUN: *
* *
* X Gamma(X) *
* ------------------------- *
* 0.500000 1.772454 *
* 1.000000 1.000000 *
* 1.500000 0.886227 *
* 2.000000 1.000000 *
* 2.500000 1.329340 *
* 3.000000 2.000000 *
* 3.500000 3.323351 *
* 4.000000 6.000000 *
* 4.500000 11.631728 *
* 5.000000 24.000000 *
* *
********************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <enerc.h>
#define half 0.5
#define increment 0.0000005
#define one 1.0
#define fpf 5.5
#define zero 0.0
APPROX double x, y;
int i;
/******************************************
* FUNCTION GAMMA(X) *
* --------------------------------------- *
* Returns the value of Gamma(x) in double *
* precision as EXP(LN(GAMMA(X))) for X>0. *
******************************************/
APPROX double Gamma(APPROX double xx) {
APPROX double cof[7],stp,x,tmp,ser;
int j;
cof[1]=76.18009173;
cof[2]=-86.50532033;
cof[3]=24.01409822;
cof[4]=-1.231739516;
cof[5]=0.120858003e-2;
cof[6]=-0.536382e-5;
stp=2.50662827465;
x=xx-one;
tmp=x+fpf;
tmp=(x+half)*log(tmp)-tmp;
ser=one;
for (j=1; j<7; j++) {
x=x+one;
ser=ser+cof[j]/x;
}
return (exp(tmp+log(stp*ser)));
}
int main() {
FILE *file;
char *outputfile = "my_output.txt";
int retval;
APPROX double xval[1000000];
APPROX double yval[1000000];
accept_roi_begin();
x = zero;
for (i = 0; i < 1000000; i++) {
x += increment;
y = Gamma(x);
xval[i] = x;
yval[i] = y;
}
accept_roi_end();
file = fopen(outputfile, "w");
if (file == NULL) {
perror("fopen for write failed\n");
return EXIT_FAILURE;
}
for (i = 0; i < 1000000; i++) {
retval = fprintf(file, "%.10f\n", ENDORSE(xval[i]));
if (retval < 0) {
perror("fprintf of x-value failed\n");
return EXIT_FAILURE;
}
retval = fprintf(file, "%.10f\n", ENDORSE(yval[i]));
if (retval < 0) {
perror("fprintf of y-value failed\n");
return EXIT_FAILURE;
}
}
retval = fclose(file);
if (retval != 0) {
perror("fclose failed\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// end of file gamma.cpp
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _RETRIEVEDINPUTSTREAMDATA_HXX
#define _RETRIEVEDINPUTSTREAMDATA_HXX
#include <tools/link.hxx>
#include <sal/types.h>
#include <osl/mutex.hxx>
#include <rtl/instance.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/io/XInputStream.hpp>
#include <map>
#include <boost/weak_ptr.hpp>
class SwAsyncRetrieveInputStreamThreadConsumer;
/** Singleton class to manage retrieved input stream data in Writer
OD 2007-01-29 #i73788#
The instance of this class provides data container for retrieved input
stream data. The data container is accessed via a key, which the data
manager provides on creation of the data container.
When a certain data container is filled with data, an user event is submitted
to trigger the processing of with data.
@author OD
*/
class SwRetrievedInputStreamDataManager
{
public:
typedef sal_uInt64 tDataKey;
struct tData
{
boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > mpThreadConsumer;
com::sun::star::uno::Reference<com::sun::star::io::XInputStream> mxInputStream;
sal_Bool mbIsStreamReadOnly;
tData()
: mpThreadConsumer(),
mbIsStreamReadOnly( sal_False )
{};
tData( boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer )
: mpThreadConsumer( pThreadConsumer ),
mbIsStreamReadOnly( sal_False )
{};
};
static SwRetrievedInputStreamDataManager& GetManager();
~SwRetrievedInputStreamDataManager()
{
};
tDataKey ReserveData( boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer );
void PushData( const tDataKey nDataKey,
com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xInputStream,
const sal_Bool bIsStreamReadOnly );
bool PopData( const tDataKey nDataKey,
tData& rData );
DECL_LINK( LinkedInputStreamReady, SwRetrievedInputStreamDataManager::tDataKey* );
private:
static tDataKey mnNextKeyValue;
osl::Mutex maMutex;
std::map< tDataKey, tData > maInputStreamData;
template<typename T, typename Unique> friend class rtl::Static;
SwRetrievedInputStreamDataManager()
{
};
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix MacOSX tinderbox build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _RETRIEVEDINPUTSTREAMDATA_HXX
#define _RETRIEVEDINPUTSTREAMDATA_HXX
#include <tools/link.hxx>
#include <sal/types.h>
#include <osl/mutex.hxx>
#include <rtl/instance.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/io/XInputStream.hpp>
#include <map>
#include <boost/weak_ptr.hpp>
class SwAsyncRetrieveInputStreamThreadConsumer;
/** Singleton class to manage retrieved input stream data in Writer
OD 2007-01-29 #i73788#
The instance of this class provides data container for retrieved input
stream data. The data container is accessed via a key, which the data
manager provides on creation of the data container.
When a certain data container is filled with data, an user event is submitted
to trigger the processing of with data.
@author OD
*/
class SwRetrievedInputStreamDataManager
{
public:
typedef sal_uInt64 tDataKey;
struct tData
{
boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > mpThreadConsumer;
com::sun::star::uno::Reference<com::sun::star::io::XInputStream> mxInputStream;
sal_Bool mbIsStreamReadOnly;
tData()
: mpThreadConsumer(),
mbIsStreamReadOnly( sal_False )
{};
tData( boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer )
: mpThreadConsumer( pThreadConsumer ),
mbIsStreamReadOnly( sal_False )
{};
};
static SwRetrievedInputStreamDataManager& GetManager();
tDataKey ReserveData( boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer );
void PushData( const tDataKey nDataKey,
com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xInputStream,
const sal_Bool bIsStreamReadOnly );
bool PopData( const tDataKey nDataKey,
tData& rData );
DECL_LINK( LinkedInputStreamReady, SwRetrievedInputStreamDataManager::tDataKey* );
private:
static tDataKey mnNextKeyValue;
osl::Mutex maMutex;
std::map< tDataKey, tData > maInputStreamData;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdarg>
#include <assert.h>
#include "opencv2/opencv.hpp"
using namespace cv;
#include "structures.hpp"
#include "util.hpp"
void showImage(const char* title, const Mat& img)
{
std::cout << "\nShowing image: \"" << title << "\"." << std::endl;
namedWindow(title, CV_WINDOW_NORMAL);
imshow(title, img);
}
void showImageAndWait(const char* title, const Mat& img)
{
showImage(title, img);
std::cout << "Press any key to continue..." << std::endl;
waitKey(0);
}
Point3f backproject3D(const float x, const float y, const float depth, const Mat& m_cameraMatrix)
{
Mat new_point = depth * m_cameraMatrix.inv()* (Mat_<float>(3,1) << x,y,1);
return Point3f(new_point);
}
/**
* Custom logger, instantiate with namespace string to prefix messages with.
* For example:
* Logger _log("Load Images");
*/
Logger::Logger(const char* _namespace)
: name_space(_namespace), start(ch::system_clock::now())
{}
void Logger::operator() (const char* format, ...)
{
va_list args;
va_start(args, format);
printf("%s>\t", name_space);
vprintf(format, args);
printf("\n");
va_end(args);
}
void Logger::tok()
{
const clock_t end = ch::system_clock::now();
ch::milliseconds dur = ch::duration_cast<ch::milliseconds>(end - start);
(*this)("Done in %.2fs.", (float)dur.count() / 1e3);
// Reset start time
start = ch::system_clock::now();
}
/*
* convert rotation matrix to quaternion
*/
Vec4f R2Quaternion(Mat& R)
{
assert(R.rows == 3 && R.cols == 3);
// typedef typename DataType<float>::work_type _wTp;
if (R.type() != CV_32F) R.convertTo(R, CV_32F);;
float q0,q1,q2,q3;
float r00 = R.at<float>(0,0);
float r01 = R.at<float>(0,1);
float r02 = R.at<float>(0,2);
float r10 = R.at<float>(1,0);
float r11 = R.at<float>(1,1);
float r12 = R.at<float>(1,2);
float r20 = R.at<float>(2,0);
float r21 = R.at<float>(2,1);
float r22 = R.at<float>(2,2);
float trace = r00 + r11 + r22;
if( trace > 0 ){
float s = 0.5 / sqrt(trace+ 1.0);
q0 = 0.25 / s;
q1 = ( r21 - r12 ) * s;
q2 = ( r02 - r20 ) * s;
q3 = ( r10 - r01 ) * s;
} else {
if ( r00 > r11 && r00 > r22 )
{
float s = 2.0 * sqrt( 1.0 + r00 - r11 - r22);
q0 = (r21 - r12 ) / s;
q1 = 0.25 * s;
q2 = (r01 + r10 ) / s;
q3 = (r02 + r20 ) / s;
} else if (r11 > r22) {
float s = 2.0 * sqrt( 1.0 + r11 - r00 - r22);
q0 = (r02 - r20 ) / s;
q1 = (r01 + r10 ) / s;
q2 = 0.25 * s;
q3 = (r12 + r21 ) / s;
} else {
float s = 2.0 * sqrt( 1.0 + r22 - r00 - r11 );
q0 = (r10 - r01 ) / s;
q1 = (r02 + r20 ) / s;
q2 = (r12 + r21 ) / s;
q3 = 0.25 * s;
}
}
Vec4f q = normalize(Vec4f(q0, q1, q2, q3));
return q;
}
Mat quat2R(Vec4f& q){
float sqw = q[0]*q[0];
float sqx = q[1]*q[1];
float sqy = q[2]*q[2];
float sqz = q[3]*q[3];
// invs (inverse square length) is only required if quaternion is not already normalised
float invs = 1 / (sqx + sqy + sqz + sqw);
float m00 = ( sqx - sqy - sqz + sqw)*invs ; // since sqw + sqx + sqy + sqz =1/invs*invs
float m11 = (-sqx + sqy - sqz + sqw)*invs ;
float m22 = (-sqx - sqy + sqz + sqw)*invs ;
float tmp1 = q[1]*q[2];
float tmp2 = q[3]*q[0];
float m10 = 2.0 * (tmp1 + tmp2)*invs ;
float m01 = 2.0 * (tmp1 - tmp2)*invs ;
tmp1 = q[1]*q[3];
tmp2 = q[2]*q[0];
float m20 = 2.0 * (tmp1 - tmp2)*invs ;
float m02 = 2.0 * (tmp1 + tmp2)*invs ;
tmp1 = q[2]*q[3];
tmp2 = q[1]*q[0];
float m21 = 2.0 * (tmp1 + tmp2)*invs ;
float m12 = 2.0 * (tmp1 - tmp2)*invs ;
Mat R = (Mat_<float>(3,3) << m00, m01, m02, m10, m11, m12, m20, m21, m22);
return R;
}
bool checkCoherentRotation(cv::Mat& R) {
if(fabs(determinant(R))-1.0 > 1e-05) return false;
return true;
}
bool checkCoherentQ(Vec4f& q0, Vec4f& q1)
{
Vec4f absdelta,reldelta;
absdiff(q0,q1,absdelta);
divide(absdelta,q1,reldelta);
if (fabs(reldelta[0])>0.1 ||fabs(reldelta[1])>0.1 ||fabs(reldelta[2])>0.1 ||fabs(reldelta[3])>0.1)
return false;
return true;
}
// Checks if two given rvec (from solvePnP) match.
// q0 is expected to represent R_ji and
// q1 is expected to represent R_ij
// It can be assumed that q0 + q1 should be close to 0-vector
bool checkCoherent(Mat& q0, Mat& q1)
{
Mat q0_normed,q1_normed;
normalize(q0,q0_normed);
normalize(q1,q1_normed);
// NOTE: norm() uses L2-norm by default
// Check direction of rotation
if (norm(q1_normed+q0_normed) > 0.1) return false;
// Check rotation angle (magnitude of rvecs)
if (norm(q0)-norm(q1) > 0.1) return false;
return true;
}
<commit_msg>added absolute value in magnitude check r_vect<commit_after>#include <cmath>
#include <cstdarg>
#include <assert.h>
#include "opencv2/opencv.hpp"
using namespace cv;
#include "structures.hpp"
#include "util.hpp"
void showImage(const char* title, const Mat& img)
{
std::cout << "\nShowing image: \"" << title << "\"." << std::endl;
namedWindow(title, CV_WINDOW_NORMAL);
imshow(title, img);
}
void showImageAndWait(const char* title, const Mat& img)
{
showImage(title, img);
std::cout << "Press any key to continue..." << std::endl;
waitKey(0);
}
Point3f backproject3D(const float x, const float y, const float depth, const Mat& m_cameraMatrix)
{
Mat new_point = depth * m_cameraMatrix.inv()* (Mat_<float>(3,1) << x,y,1);
return Point3f(new_point);
}
/**
* Custom logger, instantiate with namespace string to prefix messages with.
* For example:
* Logger _log("Load Images");
*/
Logger::Logger(const char* _namespace)
: name_space(_namespace), start(ch::system_clock::now())
{}
void Logger::operator() (const char* format, ...)
{
va_list args;
va_start(args, format);
printf("%s>\t", name_space);
vprintf(format, args);
printf("\n");
va_end(args);
}
void Logger::tok()
{
const clock_t end = ch::system_clock::now();
ch::milliseconds dur = ch::duration_cast<ch::milliseconds>(end - start);
(*this)("Done in %.2fs.", (float)dur.count() / 1e3);
// Reset start time
start = ch::system_clock::now();
}
/*
* convert rotation matrix to quaternion
*/
Vec4f R2Quaternion(Mat& R)
{
assert(R.rows == 3 && R.cols == 3);
// typedef typename DataType<float>::work_type _wTp;
if (R.type() != CV_32F) R.convertTo(R, CV_32F);;
float q0,q1,q2,q3;
float r00 = R.at<float>(0,0);
float r01 = R.at<float>(0,1);
float r02 = R.at<float>(0,2);
float r10 = R.at<float>(1,0);
float r11 = R.at<float>(1,1);
float r12 = R.at<float>(1,2);
float r20 = R.at<float>(2,0);
float r21 = R.at<float>(2,1);
float r22 = R.at<float>(2,2);
float trace = r00 + r11 + r22;
if( trace > 0 ){
float s = 0.5 / sqrt(trace+ 1.0);
q0 = 0.25 / s;
q1 = ( r21 - r12 ) * s;
q2 = ( r02 - r20 ) * s;
q3 = ( r10 - r01 ) * s;
} else {
if ( r00 > r11 && r00 > r22 )
{
float s = 2.0 * sqrt( 1.0 + r00 - r11 - r22);
q0 = (r21 - r12 ) / s;
q1 = 0.25 * s;
q2 = (r01 + r10 ) / s;
q3 = (r02 + r20 ) / s;
} else if (r11 > r22) {
float s = 2.0 * sqrt( 1.0 + r11 - r00 - r22);
q0 = (r02 - r20 ) / s;
q1 = (r01 + r10 ) / s;
q2 = 0.25 * s;
q3 = (r12 + r21 ) / s;
} else {
float s = 2.0 * sqrt( 1.0 + r22 - r00 - r11 );
q0 = (r10 - r01 ) / s;
q1 = (r02 + r20 ) / s;
q2 = (r12 + r21 ) / s;
q3 = 0.25 * s;
}
}
Vec4f q = normalize(Vec4f(q0, q1, q2, q3));
return q;
}
Mat quat2R(Vec4f& q){
float sqw = q[0]*q[0];
float sqx = q[1]*q[1];
float sqy = q[2]*q[2];
float sqz = q[3]*q[3];
// invs (inverse square length) is only required if quaternion is not already normalised
float invs = 1 / (sqx + sqy + sqz + sqw);
float m00 = ( sqx - sqy - sqz + sqw)*invs ; // since sqw + sqx + sqy + sqz =1/invs*invs
float m11 = (-sqx + sqy - sqz + sqw)*invs ;
float m22 = (-sqx - sqy + sqz + sqw)*invs ;
float tmp1 = q[1]*q[2];
float tmp2 = q[3]*q[0];
float m10 = 2.0 * (tmp1 + tmp2)*invs ;
float m01 = 2.0 * (tmp1 - tmp2)*invs ;
tmp1 = q[1]*q[3];
tmp2 = q[2]*q[0];
float m20 = 2.0 * (tmp1 - tmp2)*invs ;
float m02 = 2.0 * (tmp1 + tmp2)*invs ;
tmp1 = q[2]*q[3];
tmp2 = q[1]*q[0];
float m21 = 2.0 * (tmp1 + tmp2)*invs ;
float m12 = 2.0 * (tmp1 - tmp2)*invs ;
Mat R = (Mat_<float>(3,3) << m00, m01, m02, m10, m11, m12, m20, m21, m22);
return R;
}
bool checkCoherentRotation(cv::Mat& R) {
if(fabs(determinant(R))-1.0 > 1e-05) return false;
return true;
}
bool checkCoherentQ(Vec4f& q0, Vec4f& q1)
{
Vec4f absdelta,reldelta;
absdiff(q0,q1,absdelta);
divide(absdelta,q1,reldelta);
if (fabs(reldelta[0])>0.1 ||fabs(reldelta[1])>0.1 ||fabs(reldelta[2])>0.1 ||fabs(reldelta[3])>0.1)
return false;
return true;
}
// Checks if two given rvec (from solvePnP) match.
// q0 is expected to represent R_ji and
// q1 is expected to represent R_ij
// It can be assumed that q0 + q1 should be close to 0-vector
bool checkCoherent(Mat& q0, Mat& q1)
{
Mat q0_normed,q1_normed;
normalize(q0,q0_normed);
normalize(q1,q1_normed);
// NOTE: norm() uses L2-norm by default
// Check direction of rotation
if (norm(q1_normed+q0_normed) > 0.2) return false;
// Check rotation angle (magnitude of rvecs)
if (norm(q0)-norm(q1) > 0.2 || norm(q0)-norm(q1) < -0.2) return false;
return true;
}
<|endoftext|> |
<commit_before>// File: btBoostDynamics.hpp
#ifndef _btBoostDynamics_hpp
#define _btBoostDynamics_hpp
#include <boost/python.hpp>
#include "btBoostLinearMathScalar.hpp"
#include "btBoostLinearMathVector3.hpp"
#include "btBoostLinearMathQuadWord.hpp"
#include "btBoostLinearMathQuaternion.hpp"
#include "btBoostLinearMathMatrix3x3.hpp"
#include "btBoostLinearMathTransform.hpp"
#include "btBoostLinearMathMotionState.hpp"
#include "btBoostLinearMathAlignedObjectArray.hpp"
// TODO: implement btAlignedObjectArray somewhere, it's needed to pass arrays
// back and forth
void defineLinearMath()
{
defineScalar();
defineVector3();
defineQuadWord();
defineQuaternion();
defineMatrix3x3();
defineTransform();
defineMotionState();
defineAlignedObjectArray();
}
#endif // _btBoostDynamics_hpp
<commit_msg>add include and call to tran util define<commit_after>// File: btBoostDynamics.hpp
#ifndef _btBoostDynamics_hpp
#define _btBoostDynamics_hpp
#include <boost/python.hpp>
#include "btBoostLinearMathScalar.hpp"
#include "btBoostLinearMathVector3.hpp"
#include "btBoostLinearMathQuadWord.hpp"
#include "btBoostLinearMathQuaternion.hpp"
#include "btBoostLinearMathMatrix3x3.hpp"
#include "btBoostLinearMathTransform.hpp"
#include "btBoostLinearMathTransformUtil.hpp"
#include "btBoostLinearMathMotionState.hpp"
#include "btBoostLinearMathAlignedObjectArray.hpp"
// TODO: implement btAlignedObjectArray somewhere, it's needed to pass arrays
// back and forth
void defineLinearMath()
{
defineScalar();
defineVector3();
defineQuadWord();
defineQuaternion();
defineMatrix3x3();
defineTransform();
defineMotionState();
defineAlignedObjectArray();
defineTransformUtil();
}
#endif // _btBoostDynamics_hpp
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dispatchprovider.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: mba $ $Date: 2001-11-28 11:03:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
#define __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_
#include <com/sun/star/frame/DispatchDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
enum EDispatchHelper
{
E_DEFAULTDISPATCHER ,
E_MENUDISPATCHER ,
E_MAILTODISPATCHER ,
E_HELPAGENTDISPATCHER ,
E_CREATEDISPATCHER ,
E_BLANKDISPATCHER ,
E_SELFDISPATCHER ,
E_PLUGINDISPATCHER
};
//_________________________________________________________________________________________________________________
// exported definitions
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short implement a helper for XDispatchProvider interface
@descr Use this class as member only! Never use it as baseclass.
XInterface will be ambigous and we hold a weakreference to ouer OWNER - not to ouer SUPERCLASS!
@implements XInterface
XDispatchProvider
XEventListener
@base ThreadHelpBase
TransactionBase
OWeakObject
@devstatus ready to use
@threadsafe yes
*//*-*************************************************************************************************************/
class DispatchProvider : // interfaces
public css::lang::XTypeProvider ,
public css::frame::XDispatchProvider ,
public css::lang::XEventListener ,
// baseclasses
// Order is neccessary for right initialization!
private ThreadHelpBase ,
private TransactionBase ,
public ::cppu::OWeakObject
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
// constructor / destructor
DispatchProvider( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
const css::uno::Reference< css::frame::XFrame >& xFrame );
// XInterface
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XDispatchProvider
virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL queryDispatch ( const css::util::URL& aURL ,
const ::rtl::OUString& sTargetFrameName ,
sal_Int32 nSearchFlags ) throw( css::uno::RuntimeException );
virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches ( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions ) throw( css::uno::RuntimeException );
// XEventListener
virtual void SAL_CALL disposing ( const css::lang::EventObject& aEvent ) throw( css::uno::RuntimeException );
//-------------------------------------------------------------------------------------------------------------
// protected methods
//-------------------------------------------------------------------------------------------------------------
protected:
// Let him protected!
virtual ~DispatchProvider();
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
css::uno::Reference< css::frame::XDispatch > implts_searchProtocolHandler ( const css::util::URL& aURL ,
const TargetInfo& aInfo );
css::uno::Reference< css::frame::XDispatchProvider > implts_getOrCreateAppDispatchProvider( );
css::uno::Reference< css::frame::XDispatch > implts_getOrCreateDispatchHelper ( EDispatchHelper eHelper ,
const css::uno::Any& aParameters = css::uno::Any() );
sal_Bool implts_isLoadableContent ( const css::util::URL& aURL );
//-------------------------------------------------------------------------------------------------------------
// debug methods
// (should be private everyway!)
//-------------------------------------------------------------------------------------------------------------
#ifdef ENABLE_ASSERTIONS
private:
static sal_Bool implcp_ctor ( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
const css::uno::Reference< css::frame::XFrame >& xFrame );
static sal_Bool implcp_queryDispatch ( const css::util::URL& aURL ,
const ::rtl::OUString& sTargetFrameName,
sal_Int32 nSearchFlags );
static sal_Bool implcp_queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions );
static sal_Bool implcp_disposing ( const css::lang::EventObject& aEvent );
#endif // #ifdef ENABLE_ASSERTIONS
//-------------------------------------------------------------------------------------------------------------
// variables
// (should be private everyway!)
//-------------------------------------------------------------------------------------------------------------
private:
css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// reference to global service manager to create new services
css::uno::WeakReference< css::frame::XFrame > m_xFrame ; /// weakreference to owner frame (Don't use a hard reference. Owner can't delete us then!)
css::uno::Reference< css::frame::XDispatchProvider > m_xAppDispatchProvider ; /// For some dispatches we should call our global app dispatch provider
css::uno::Reference< css::frame::XDispatch > m_xMenuDispatcher ; /// different dispatcher to handle special dispatch calls, protocols or URLs
css::uno::Reference< css::frame::XDispatch > m_xHelpAgentDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xMailToDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xBlankDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xSelfDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xPlugInDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xDefaultDispatcher ;
}; // class DispatchProvider
} // namespace framework
#endif // #ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
<commit_msg>#99021# replace mailtodispatcher by moving it to protocol handler mechanism<commit_after>/*************************************************************************
*
* $RCSfile: dispatchprovider.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: as $ $Date: 2002-05-02 11:44:32 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
#define __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif
#include <classes/protocolhandlercache.hxx>
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_
#include <com/sun/star/frame/DispatchDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
enum EDispatchHelper
{
E_DEFAULTDISPATCHER ,
E_MENUDISPATCHER ,
E_HELPAGENTDISPATCHER ,
E_CREATEDISPATCHER ,
E_BLANKDISPATCHER ,
E_SELFDISPATCHER ,
E_PLUGINDISPATCHER
};
//_________________________________________________________________________________________________________________
// exported definitions
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short implement a helper for XDispatchProvider interface
@descr Use this class as member only! Never use it as baseclass.
XInterface will be ambigous and we hold a weakreference to ouer OWNER - not to ouer SUPERCLASS!
@implements XInterface
XDispatchProvider
XEventListener
@base ThreadHelpBase
TransactionBase
OWeakObject
@devstatus ready to use
@threadsafe yes
*//*-*************************************************************************************************************/
class DispatchProvider : // interfaces
public css::lang::XTypeProvider ,
public css::frame::XDispatchProvider ,
public css::lang::XEventListener ,
// baseclasses
// Order is neccessary for right initialization!
private ThreadHelpBase ,
private TransactionBase ,
public ::cppu::OWeakObject
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
// constructor / destructor
DispatchProvider( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
const css::uno::Reference< css::frame::XFrame >& xFrame );
// XInterface
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XDispatchProvider
virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL queryDispatch ( const css::util::URL& aURL ,
const ::rtl::OUString& sTargetFrameName ,
sal_Int32 nSearchFlags ) throw( css::uno::RuntimeException );
virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches ( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions ) throw( css::uno::RuntimeException );
// XEventListener
virtual void SAL_CALL disposing ( const css::lang::EventObject& aEvent ) throw( css::uno::RuntimeException );
//-------------------------------------------------------------------------------------------------------------
// protected methods
//-------------------------------------------------------------------------------------------------------------
protected:
// Let him protected!
virtual ~DispatchProvider();
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
css::uno::Reference< css::frame::XDispatch > implts_searchProtocolHandler ( const css::util::URL& aURL ,
const TargetInfo& aInfo );
css::uno::Reference< css::frame::XDispatchProvider > implts_getOrCreateAppDispatchProvider( );
css::uno::Reference< css::frame::XDispatch > implts_getOrCreateDispatchHelper ( EDispatchHelper eHelper ,
const css::uno::Any& aParameters = css::uno::Any() );
sal_Bool implts_isLoadableContent ( const css::util::URL& aURL );
//-------------------------------------------------------------------------------------------------------------
// debug methods
// (should be private everyway!)
//-------------------------------------------------------------------------------------------------------------
#ifdef ENABLE_ASSERTIONS
private:
static sal_Bool implcp_ctor ( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
const css::uno::Reference< css::frame::XFrame >& xFrame );
static sal_Bool implcp_queryDispatch ( const css::util::URL& aURL ,
const ::rtl::OUString& sTargetFrameName,
sal_Int32 nSearchFlags );
static sal_Bool implcp_queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions );
static sal_Bool implcp_disposing ( const css::lang::EventObject& aEvent );
#endif // #ifdef ENABLE_ASSERTIONS
//-------------------------------------------------------------------------------------------------------------
// variables
// (should be private everyway!)
//-------------------------------------------------------------------------------------------------------------
private:
css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// reference to global service manager to create new services
css::uno::WeakReference< css::frame::XFrame > m_xFrame ; /// weakreference to owner frame (Don't use a hard reference. Owner can't delete us then!)
css::uno::Reference< css::frame::XDispatchProvider > m_xAppDispatchProvider ; /// For some dispatches we should call our global app dispatch provider
css::uno::Reference< css::frame::XDispatch > m_xMenuDispatcher ; /// different dispatcher to handle special dispatch calls, protocols or URLs
css::uno::Reference< css::frame::XDispatch > m_xHelpAgentDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xBlankDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xSelfDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xPlugInDispatcher ;
css::uno::Reference< css::frame::XDispatch > m_xDefaultDispatcher ;
HandlerCache m_aProtocolHandlerCache ;
}; // class DispatchProvider
} // namespace framework
#endif // #ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: localizedtreeactions.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: jb $ $Date: 2001-07-11 14:06:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include "treeactions.hxx"
#include "subtree.hxx"
#include "matchlocale.hxx"
#include "typeconverter.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//..........................................................................
namespace configmgr
{
//--------------------------------------------------------------------------
namespace
{
using localehelper::FindBestLocale;
//--------------------------------------------------------------------------
struct OCloneChildrenForLocale : NodeAction
{
ISubtree& m_rParent;
FindBestLocale& m_rLocaleMatcher;
public:
OCloneChildrenForLocale(ISubtree& _rParent, FindBestLocale& _rLocaleMatcher)
: m_rParent(_rParent)
, m_rLocaleMatcher(_rLocaleMatcher)
{}
virtual void handle(ValueNode const& _aValue);
virtual void handle(ISubtree const& _aSubtree);
};
//--------------------------------------------------------------------------
struct OSelectForLocale : NodeAction
{
ValueNode const* m_pFound;
FindBestLocale& m_rLocaleMatcher;
public:
OSelectForLocale(FindBestLocale& _rLocaleMatcher)
: m_pFound(NULL)
, m_rLocaleMatcher(_rLocaleMatcher)
{}
bool hasResult() const
{ return m_pFound != NULL; }
ValueNode const* getResult() const
{ return m_pFound; }
private:
virtual void handle(ValueNode const& _aValue);
virtual void handle(ISubtree const& _aSubtree);
void maybeSelect(ValueNode const& _aNode);
};
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
void OSelectForLocale::handle(ValueNode const& _aValue)
{
maybeSelect(_aValue);
}
//--------------------------------------------------------------------------
void OSelectForLocale::handle(ISubtree const& _aSubtree)
{
OSL_ENSURE(false, "INTERNAL ERROR: Inconsistent data: Found a Subtree in a set of localized values");
}
//--------------------------------------------------------------------------
void OSelectForLocale::maybeSelect(ValueNode const& _aNode)
{
if (m_rLocaleMatcher.accept( localehelper::makeLocale(_aNode.getName()) ) )
m_pFound = &_aNode;
else
OSL_ENSURE(m_pFound, "WARNING: Node Locale wasn't accepted, but no node had been found before");
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
std::auto_ptr< INode > implReduceLocalizedSet(ISubtree const& _aSubtree, FindBestLocale& _rLocaleMatcher)
{
// -- find the best-match locale -----------------------------
_rLocaleMatcher.reset();
OSelectForLocale aSelector(_rLocaleMatcher);
aSelector.applyToChildren(_aSubtree);
std::auto_ptr< INode > pResult;
// -- look for a non-NULL value -----------------------------
uno::Type aValueType;
if (aSelector.hasResult())
{
ValueNode const& rSelected = *aSelector.getResult();
aValueType = rSelected.getValueType();
if (!rSelected.isNull()) // values are present - clone it from the values
{
pResult.reset ( new ValueNode( _aSubtree.getName(),
rSelected.getValue(), rSelected.getDefault(),
_aSubtree.getAttributes()
) );
}
}
else // no entry - exract the type to be used from the template name
aValueType = parseTemplateName(_aSubtree.getElementTemplateName());
// -- create NULL value, if none was found -----------------------------
// create a NULL of the found type
if (pResult.get() == NULL)
{
pResult.reset( new ValueNode( _aSubtree.getName(),
aValueType,
_aSubtree.getAttributes()
) );
}
// -- -----------------------------
OSL_ENSURE( aValueType != uno::Type(), "VOID result type found");
OSL_ENSURE( aValueType == parseTemplateName(_aSubtree.getElementTemplateName()),
"ERROR: Found Value Type doesn't match encoded value type in pseudo template name");
OSL_POSTCOND( static_cast<ValueNode&>(*pResult).getValueType() == aValueType,
"ERROR: Resulting Value Type doesn't match original value type" );
return pResult;
}
//--------------------------------------------------------------------------
std::auto_ptr< INode > implCloneForLocale(ISubtree const& _aSubtree, FindBestLocale& _rLocaleMatcher)
{
std::auto_ptr< INode > pClone;
if (isLocalizedValueSet(_aSubtree))
{
pClone = implReduceLocalizedSet(_aSubtree, _rLocaleMatcher);
}
else
{
// ISubtree should get a clone(NoChildCopy) member ...
std::auto_ptr< Subtree > pCloneTree( new Subtree(_aSubtree, Subtree::NoChildCopy()) );
OCloneChildrenForLocale aSubCloner(*pCloneTree,_rLocaleMatcher);
aSubCloner.applyToChildren(_aSubtree);
pClone.reset( pCloneTree.release() );
}
return pClone;
}
//--------------------------------------------------------------------------
//--- OCloneChildrenForLocale:-----------------------------------------------------------------------
void OCloneChildrenForLocale::handle(ValueNode const& _aValue)
{
// just a single value - nothing to do
std::auto_ptr< INode > pClone( _aValue.clone() );
m_rParent.addChild(pClone);
}
//--------------------------------------------------------------------------
void OCloneChildrenForLocale::handle(ISubtree const& _aSubtree)
{
std::auto_ptr< INode > pClone = implCloneForLocale(_aSubtree,m_rLocaleMatcher);
m_rParent.addChild(pClone);
}
//--------------------------------------------------------------------------
} // anonymous namespace
//--------------------------------------------------------------------------
//= OCloneForLocale
// rtl::OUString m_sTargetLocale;
// std::auto_ptr<INode> m_pClone;
void OCloneForLocale::handle(ValueNode const& _aValue)
{
// just a single value - nothing to do
std::auto_ptr< INode > pClone( _aValue.clone() );
m_pClone = pClone;
}
//--------------------------------------------------------------------------
void OCloneForLocale::handle(ISubtree const& _aSubtree)
{
FindBestLocale aLocaleMatcher( localehelper::makeLocale(m_sTargetLocale) );
m_pClone = implCloneForLocale(_aSubtree,aLocaleMatcher);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//==========================================================================
// Helper function to invoke the previous ones properly
// convert to the given locale format, assuming the original representation was expanded
static std::auto_ptr<INode> impl_cloneExpandedForLocale(INode const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
OSL_ASSERT(_pNode != NULL);
if ( designatesAllLocales(makeLocale(_sLocale)) ) // from expanded to expanded
return std::auto_ptr<INode>( _pNode->clone() );
else // needs reduction
{
OCloneForLocale aCloner(_sLocale);
aCloner.applyToNode(*_pNode);
return aCloner.getResult();
}
}
// convert to the given locale format, no matter what the original representation
std::auto_ptr<INode> cloneForLocale(INode const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
OSL_ENSURE( !designatesAllLocales(makeLocale(_sLocale)),
"WARNING: This function doesn't work from single values to expanded sets so far");
return cloneExpandedForLocale(_pNode,_sLocale);
}
// convert to the given locale format, assuming the original representation was expanded
std::auto_ptr<INode> cloneExpandedForLocale(INode const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
if (_pNode == NULL)
return std::auto_ptr< INode >();
else if ( !_pNode->ISA( ISubtree ) ) // simple value - nothing to reduce
return std::auto_ptr<INode>( _pNode->clone() );
else
return impl_cloneExpandedForLocale(_pNode,_sLocale);
}
// convert to the given locale format, assuming the original representation was expanded
std::auto_ptr<INode> cloneExpandedForLocale(ISubtree const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
if (_pNode == NULL)
return std::auto_ptr< INode >();
else
return impl_cloneExpandedForLocale(_pNode,_sLocale);
}
// convert to the given locale format, assuming the original representation was expanded
std::auto_ptr<INode> reduceExpandedForLocale(std::auto_ptr<ISubtree> _pNode, OUString const& _sLocale)
{
using namespace localehelper;
std::auto_ptr<INode> aResult;
if ( _pNode.get() == NULL || // nothing to reduce
designatesAllLocales(makeLocale(_sLocale)) ) // from expanded to expanded
{
aResult.reset( _pNode.release() );
}
else // needs reduction
{
OCloneForLocale aCloner(_sLocale);
aCloner.applyToNode(*_pNode);
aResult = aCloner.getResult();
}
return aResult;
}
//--------------------------------------------------------------------------
//..........................................................................
} // namespace configmgr
//..........................................................................
<commit_msg>#86807# Reduce to locale now copies the tree ID (if any)<commit_after>/*************************************************************************
*
* $RCSfile: localizedtreeactions.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: jb $ $Date: 2001-11-05 10:39:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include "treeactions.hxx"
#include "subtree.hxx"
#include "matchlocale.hxx"
#include "typeconverter.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//..........................................................................
namespace configmgr
{
//--------------------------------------------------------------------------
namespace
{
using localehelper::FindBestLocale;
//--------------------------------------------------------------------------
struct OCloneChildrenForLocale : NodeAction
{
ISubtree& m_rParent;
FindBestLocale& m_rLocaleMatcher;
public:
OCloneChildrenForLocale(ISubtree& _rParent, FindBestLocale& _rLocaleMatcher)
: m_rParent(_rParent)
, m_rLocaleMatcher(_rLocaleMatcher)
{}
virtual void handle(ValueNode const& _aValue);
virtual void handle(ISubtree const& _aSubtree);
};
//--------------------------------------------------------------------------
struct OSelectForLocale : NodeAction
{
ValueNode const* m_pFound;
FindBestLocale& m_rLocaleMatcher;
public:
OSelectForLocale(FindBestLocale& _rLocaleMatcher)
: m_pFound(NULL)
, m_rLocaleMatcher(_rLocaleMatcher)
{}
bool hasResult() const
{ return m_pFound != NULL; }
ValueNode const* getResult() const
{ return m_pFound; }
private:
virtual void handle(ValueNode const& _aValue);
virtual void handle(ISubtree const& _aSubtree);
void maybeSelect(ValueNode const& _aNode);
};
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
void OSelectForLocale::handle(ValueNode const& _aValue)
{
maybeSelect(_aValue);
}
//--------------------------------------------------------------------------
void OSelectForLocale::handle(ISubtree const& _aSubtree)
{
OSL_ENSURE(false, "INTERNAL ERROR: Inconsistent data: Found a Subtree in a set of localized values");
}
//--------------------------------------------------------------------------
void OSelectForLocale::maybeSelect(ValueNode const& _aNode)
{
if (m_rLocaleMatcher.accept( localehelper::makeLocale(_aNode.getName()) ) )
m_pFound = &_aNode;
else
OSL_ENSURE(m_pFound, "WARNING: Node Locale wasn't accepted, but no node had been found before");
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
std::auto_ptr< INode > implReduceLocalizedSet(ISubtree const& _aSubtree, FindBestLocale& _rLocaleMatcher)
{
// -- find the best-match locale -----------------------------
_rLocaleMatcher.reset();
OSelectForLocale aSelector(_rLocaleMatcher);
aSelector.applyToChildren(_aSubtree);
std::auto_ptr< INode > pResult;
// -- look for a non-NULL value -----------------------------
uno::Type aValueType;
if (aSelector.hasResult())
{
ValueNode const& rSelected = *aSelector.getResult();
aValueType = rSelected.getValueType();
if (!rSelected.isNull()) // values are present - clone it from the values
{
pResult.reset ( new ValueNode( _aSubtree.getName(),
rSelected.getValue(), rSelected.getDefault(),
_aSubtree.getAttributes()
) );
}
}
else // no entry - exract the type to be used from the template name
aValueType = parseTemplateName(_aSubtree.getElementTemplateName());
// -- create NULL value, if none was found -----------------------------
// create a NULL of the found type
if (pResult.get() == NULL)
{
pResult.reset( new ValueNode( _aSubtree.getName(),
aValueType,
_aSubtree.getAttributes()
) );
}
// -- -----------------------------
OSL_ENSURE( aValueType != uno::Type(), "VOID result type found");
OSL_ENSURE( aValueType == parseTemplateName(_aSubtree.getElementTemplateName()),
"ERROR: Found Value Type doesn't match encoded value type in pseudo template name");
OSL_POSTCOND( static_cast<ValueNode&>(*pResult).getValueType() == aValueType,
"ERROR: Resulting Value Type doesn't match original value type" );
return pResult;
}
//--------------------------------------------------------------------------
std::auto_ptr< INode > implCloneForLocale(ISubtree const& _aSubtree, FindBestLocale& _rLocaleMatcher)
{
std::auto_ptr< INode > pClone;
if (isLocalizedValueSet(_aSubtree))
{
pClone = implReduceLocalizedSet(_aSubtree, _rLocaleMatcher);
}
else
{
// ISubtree should get a clone(NoChildCopy) member ...
std::auto_ptr< Subtree > pCloneTree( new Subtree(_aSubtree, Subtree::NoChildCopy()) );
OCloneChildrenForLocale aSubCloner(*pCloneTree,_rLocaleMatcher);
aSubCloner.applyToChildren(_aSubtree);
pClone.reset( pCloneTree.release() );
}
return pClone;
}
//--------------------------------------------------------------------------
//--- OCloneChildrenForLocale:-----------------------------------------------------------------------
void OCloneChildrenForLocale::handle(ValueNode const& _aValue)
{
// just a single value - nothing to do
std::auto_ptr< INode > pClone( _aValue.clone() );
m_rParent.addChild(pClone);
}
//--------------------------------------------------------------------------
void OCloneChildrenForLocale::handle(ISubtree const& _aSubtree)
{
std::auto_ptr< INode > pClone = implCloneForLocale(_aSubtree,m_rLocaleMatcher);
m_rParent.addChild(pClone);
}
//--------------------------------------------------------------------------
} // anonymous namespace
//--------------------------------------------------------------------------
//= OCloneForLocale
// rtl::OUString m_sTargetLocale;
// std::auto_ptr<INode> m_pClone;
void OCloneForLocale::handle(ValueNode const& _aValue)
{
// just a single value - nothing to do
std::auto_ptr< INode > pClone( _aValue.clone() );
m_pClone = pClone;
}
//--------------------------------------------------------------------------
void OCloneForLocale::handle(ISubtree const& _aSubtree)
{
FindBestLocale aLocaleMatcher( localehelper::makeLocale(m_sTargetLocale) );
m_pClone = implCloneForLocale(_aSubtree,aLocaleMatcher);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//==========================================================================
// Helper function to invoke the previous ones properly
// convert to the given locale format, assuming the original representation was expanded
static std::auto_ptr<INode> impl_cloneExpandedForLocale(INode const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
OSL_ASSERT(_pNode != NULL);
if ( designatesAllLocales(makeLocale(_sLocale)) ) // from expanded to expanded
return std::auto_ptr<INode>( _pNode->clone() );
else // needs reduction
{
OCloneForLocale aCloner(_sLocale);
aCloner.applyToNode(*_pNode);
return aCloner.getResult();
}
}
// convert to the given locale format, no matter what the original representation
std::auto_ptr<INode> cloneForLocale(INode const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
OSL_ENSURE( !designatesAllLocales(makeLocale(_sLocale)),
"WARNING: This function doesn't work from single values to expanded sets so far");
return cloneExpandedForLocale(_pNode,_sLocale);
}
// convert to the given locale format, assuming the original representation was expanded
std::auto_ptr<INode> cloneExpandedForLocale(INode const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
if (_pNode == NULL)
return std::auto_ptr< INode >();
else if ( !_pNode->ISA( ISubtree ) ) // simple value - nothing to reduce
return std::auto_ptr<INode>( _pNode->clone() );
else
return impl_cloneExpandedForLocale(_pNode,_sLocale);
}
// convert to the given locale format, assuming the original representation was expanded
std::auto_ptr<INode> cloneExpandedForLocale(ISubtree const* _pNode, OUString const& _sLocale)
{
using namespace localehelper;
if (_pNode == NULL)
return std::auto_ptr< INode >();
else
return impl_cloneExpandedForLocale(_pNode,_sLocale);
}
// convert to the given locale format, assuming the original representation was expanded
std::auto_ptr<INode> reduceExpandedForLocale(std::auto_ptr<ISubtree> _pNode, OUString const& _sLocale)
{
using namespace localehelper;
std::auto_ptr<INode> aResult;
if ( _pNode.get() == NULL || // nothing to reduce
designatesAllLocales(makeLocale(_sLocale)) ) // from expanded to expanded
{
aResult.reset( _pNode.release() );
}
else // needs reduction
{
OUString const aTreeId = _pNode->getId();
OCloneForLocale aCloner(_sLocale);
aCloner.applyToNode(*_pNode);
aResult = aCloner.getResult();
OSL_ENSURE(aResult.get(),"Cloning a tree for a locale unexpectedly produced NOTHING");
if (aResult.get())
if (ISubtree* pResultTree = aResult->asISubtree())
OIdPropagator::propagateIdToTree(aTreeId, *pResultTree);
}
return aResult;
}
//--------------------------------------------------------------------------
//..........................................................................
} // namespace configmgr
//..........................................................................
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 Traverser
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "v8.h"
#include "V8/v8-conv.h"
#include "V8/v8-utils.h"
#include "V8Server/v8-vocbaseprivate.h"
#include "V8Server/v8-wrapshapedjson.h"
#include "V8Server/v8-vocindex.h"
#include "V8Server/v8-collection.h"
#include "Utils/transactions.h"
#include "Utils/V8ResolverGuard.h"
#include "Utils/CollectionNameResolver.h"
#include "VocBase/document-collection.h"
#include "Traverser.h"
#include "VocBase/key-generator.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::arango;
/*
struct DistanceInfo {
v8::Local<v8::String> keyDistance; = TRI_V8_ASCII_STRING("direction");
}
*/
class SimpleEdgeExpander {
private:
////////////////////////////////////////////////////////////////////////////////
/// @brief direction of expansion
////////////////////////////////////////////////////////////////////////////////
TRI_edge_direction_e direction;
////////////////////////////////////////////////////////////////////////////////
/// @brief edge collection
////////////////////////////////////////////////////////////////////////////////
TRI_document_collection_t* edgeCollection;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection name and /
////////////////////////////////////////////////////////////////////////////////
string edgeIdPrefix;
////////////////////////////////////////////////////////////////////////////////
/// @brief the collection name resolver
////////////////////////////////////////////////////////////////////////////////
CollectionNameResolver* resolver;
////////////////////////////////////////////////////////////////////////////////
/// @brief this indicates whether or not a distance attribute is used or
/// whether all edges are considered to have weight 1
////////////////////////////////////////////////////////////////////////////////
bool usesDist;
////////////////////////////////////////////////////////////////////////////////
/// @brief this is the information required to compute weight by a given
/// attribute. Is only considered if usesDist==true
////////////////////////////////////////////////////////////////////////////////
// DistanceInfo distInfo;
public:
SimpleEdgeExpander(TRI_edge_direction_e direction,
TRI_document_collection_t* edgeCollection,
string edgeCollectionName,
CollectionNameResolver* resolver)
: direction(direction), edgeCollection(edgeCollection),
resolver(resolver), usesDist(false)
{
edgeIdPrefix = edgeCollectionName + "/";
};
/*
SimpleEdgeExpander(TRI_edge_direction_e direction,
TRI_document_collection_t* edgeCollection,
string edgeCollectionName,
CollectionNameResolver* resolver,
DistanceInfo distInfo)
: direction(direction), edgeCollection(edgeCollection),
resolver(resolver), usesDist(true), distInfo(distInfo)
{
edgeIdPrefix = edgeCollectionName + "/";
};
*/
Traverser::VertexId extractFromId(TRI_doc_mptr_copy_t& ptr) {
char const* key = TRI_EXTRACT_MARKER_FROM_KEY(&ptr);
TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_FROM_CID(&ptr);
string col = resolver->getCollectionName(cid);
col.append("/");
col.append(key);
return col;
};
Traverser::VertexId extractToId(TRI_doc_mptr_copy_t& ptr) {
char const* key = TRI_EXTRACT_MARKER_TO_KEY(&ptr);
TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_TO_CID(&ptr);
string col = resolver->getCollectionName(cid);
col.append("/");
col.append(key);
return col;
};
Traverser::EdgeId extractEdgeId(TRI_doc_mptr_copy_t ptr) {
char const* key = TRI_EXTRACT_MARKER_KEY(ptr);
// AppendAndCopy
return edgeIdPrefix.append(key);
};
void operator() (Traverser::VertexId source,
vector<Traverser::Step>& result) {
std::vector<TRI_doc_mptr_copy_t> edges;
TransactionBase fake(true); // Fake a transaction to please checks.
// This is due to multi-threading
// Process Vertex Id!
size_t split;
char const* str = source.c_str();
if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) {
// TODO Error Handling
return;
}
string collectionName = source.substr(0, split);
auto col = resolver->getCollectionStruct(collectionName);
if (col == nullptr) {
// collection not found
throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND;
}
auto collectionCId = col->_cid;
edges = TRI_LookupEdgesDocumentCollection(edgeCollection, direction, collectionCId, const_cast<char*>(str + split + 1));
unordered_map<Traverser::VertexId, size_t> candidates;
Traverser::VertexId from;
Traverser::VertexId to;
if (usesDist) {
for (size_t j = 0; j < edges.size(); ++j) {
from = extractFromId(edges[j]);
to = extractToId(edges[j]);
if (from != source) {
auto cand = candidates.find(from);
if (cand == candidates.end()) {
// Add weight
result.emplace_back(to, from, 1, extractEdgeId(edges[j]));
candidates.emplace(from, result.size()-1);
} else {
// Compare weight
// use result[cand->seconde].weight() and .setWeight()
}
}
else if (to != source) {
auto cand = candidates.find(to);
if (cand == candidates.end()) {
// Add weight
result.emplace_back(to, from, 1, extractEdgeId(edges[j]));
candidates.emplace(to, result.size()-1);
} else {
// Compare weight
// use result[cand->seconde].weight() and .setWeight()
}
}
}
}
else {
for (size_t j = 0; j < edges.size(); ++j) {
from = extractFromId(edges[j]);
to = extractFromId(edges[j]);
if (from != source) {
auto cand = candidates.find(from);
if (cand == candidates.end()) {
result.emplace_back(from, to, 1, extractEdgeId(edges[j]));
candidates.emplace(from, result.size()-1);
}
}
else if (to != source) {
auto cand = candidates.find(to);
if (cand == candidates.end()) {
result.emplace_back(to, from, 1, extractEdgeId(edges[j]));
candidates.emplace(to, result.size()-1);
}
}
}
}
}
};
static v8::Handle<v8::Value> pathIdsToV8(v8::Isolate* isolate, Traverser::Path& p) {
v8::EscapableHandleScope scope(isolate);
v8::Handle<v8::Object> result = v8::Object::New(isolate);
uint32_t const vn = static_cast<uint32_t>(p.vertices.size());
v8::Handle<v8::Array> vertices = v8::Array::New(isolate, static_cast<int>(vn));
for (size_t j = 0; j < vn; ++j) {
vertices->Set(static_cast<uint32_t>(j), TRI_V8_ASCII_STRING(p.vertices[j]));
}
result->Set("vertices", vertices);
uint32_t const en = static_cast<uint32_t>(p.edges.size());
v8::Handle<v8::Array> edges = v8::Array::New(isolate, static_cast<int>(en));
for (size_t j = 0; j < en; ++j) {
edges->Set(static_cast<uint32_t>(j), TRI_V8_ASCII_STRING(p.edges[j]));
}
result->Set(TRI_V8_STRING("edges"), edges);
result->Set(TRI_V8_STRING("distance"), v8::Number::New(isolate, p.weight));
return result;
};
struct LocalCollectionGuard {
LocalCollectionGuard (TRI_vocbase_col_t* collection)
: _collection(collection) {
}
~LocalCollectionGuard () {
if (_collection != nullptr && ! _collection->_isLocal) {
FreeCoordinatorCollection(_collection);
}
}
TRI_vocbase_col_t* _collection;
};
void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
if (args.Length() < 4 || args.Length() > 5) {
TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)");
}
std::unique_ptr<char[]> key;
TRI_vocbase_t* vocbase;
TRI_vocbase_col_t const* col = nullptr;
vocbase = GetContextVocBase(isolate);
vector<string> readCollections;
vector<string> writeCollections;
TRI_voc_cid_t vertexCollectionCId;
TRI_voc_cid_t edgeCollectionCId;
TRI_voc_rid_t rid;
double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL);
bool embed = false;
bool waitForSync = false;
// get the vertex collection
if (! args[0]->IsString()) {
TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>");
}
string vertexCollectionName = TRI_ObjectToString(args[0]);
// get the edge collection
if (! args[1]->IsString()) {
TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>");
}
string const edgeCollectionName = TRI_ObjectToString(args[1]);
vocbase = GetContextVocBase(isolate);
if (vocbase == nullptr) {
TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
V8ResolverGuard resolver(vocbase);
readCollections.push_back(vertexCollectionName);
readCollections.push_back(edgeCollectionName);
if (! args[2]->IsString()) {
TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>");
}
string direction = "outbound";
if (args.Length() == 5) {
if (! args[4]->IsObject()) {
TRI_V8_THROW_TYPE_ERROR("expecting json for <options>");
}
v8::Handle<v8::Object> options = args[4]->ToObject();
v8::Local<v8::String> keyDirection = TRI_V8_ASCII_STRING("direction");
if (options->Has(keyDirection) ) {
direction = TRI_ObjectToString(options->Get(keyDirection));
if ( direction != "outbound"
&& direction != "inbound"
&& direction != "any"
) {
TRI_V8_THROW_TYPE_ERROR("expecting direction to be 'outbound', 'inbound' or 'any'");
}
}
}
// IHHF isCoordinator
// Start Transaction to collect all parts of the path
ExplicitTransaction trx(
vocbase,
readCollections,
writeCollections,
lockTimeout,
waitForSync,
embed
);
int res = trx.begin();
if (res != TRI_ERROR_NO_ERROR) {
TRI_V8_THROW_EXCEPTION(res);
}
col = resolver.getResolver()->getCollectionStruct(vertexCollectionName);
if (col == nullptr) {
// collection not found
TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
}
vertexCollectionCId = col->_cid;
if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
TRI_V8_THROW_EXCEPTION_MEMORY();
}
col = resolver.getResolver()->getCollectionStruct(edgeCollectionName);
if (col == nullptr) {
// collection not found
TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
}
edgeCollectionCId = col->_cid;
if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
TRI_V8_THROW_EXCEPTION_MEMORY();
}
TRI_document_collection_t* ecol = trx.trxCollection(col->_cid)->_collection->_collection;
CollectionNameResolver resolver1(vocbase);
CollectionNameResolver resolver2(vocbase);
TRI_edge_direction_e forward;
TRI_edge_direction_e backward;
if (direction == "outbound") {
forward = TRI_EDGE_OUT;
backward = TRI_EDGE_IN;
} else if (direction == "inbound") {
forward = TRI_EDGE_IN;
backward = TRI_EDGE_OUT;
} else {
forward = TRI_EDGE_ANY;
backward = TRI_EDGE_ANY;
}
SimpleEdgeExpander forwardExpander(forward, ecol, edgeCollectionName, &resolver1);
SimpleEdgeExpander backwardExpander(backward, ecol, edgeCollectionName, &resolver2);
Traverser traverser(forwardExpander, backwardExpander);
unique_ptr<Traverser::Path> path(traverser.shortestPath(startVertex, targetVertex));
if (path.get() == nullptr) {
res = trx.finish(res);
v8::EscapableHandleScope scope(isolate);
TRI_V8_RETURN(scope.Escape<v8::Value>(v8::Object::New(isolate)));
}
auto result = pathIdsToV8(isolate, *path);
res = trx.finish(res);
TRI_V8_RETURN(result);
}
<commit_msg>Added weight Info.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 Traverser
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "v8.h"
#include "V8/v8-conv.h"
#include "V8/v8-utils.h"
#include "V8Server/v8-vocbaseprivate.h"
#include "V8Server/v8-wrapshapedjson.h"
#include "V8Server/v8-vocindex.h"
#include "V8Server/v8-collection.h"
#include "Utils/transactions.h"
#include "Utils/V8ResolverGuard.h"
#include "Utils/CollectionNameResolver.h"
#include "VocBase/document-collection.h"
#include "Traverser.h"
#include "VocBase/key-generator.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::arango;
struct WeightInfo {
string keyWeight;
double defaultWeight;
bool usesWeight;
WeightInfo(
string keyWeight,
double defaultWeight
) :
keyWeight(keyWeight), defaultWeight(defaultWeight), usesWeight(true)
{
};
WeightInfo() : usesWeight(false) {
};
};
class SimpleEdgeExpander {
private:
////////////////////////////////////////////////////////////////////////////////
/// @brief direction of expansion
////////////////////////////////////////////////////////////////////////////////
TRI_edge_direction_e direction;
////////////////////////////////////////////////////////////////////////////////
/// @brief edge collection
////////////////////////////////////////////////////////////////////////////////
TRI_document_collection_t* edgeCollection;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection name and /
////////////////////////////////////////////////////////////////////////////////
string edgeIdPrefix;
////////////////////////////////////////////////////////////////////////////////
/// @brief the collection name resolver
////////////////////////////////////////////////////////////////////////////////
CollectionNameResolver* resolver;
////////////////////////////////////////////////////////////////////////////////
/// @brief this is the information required to compute weight by a given
/// attribute. It contains an indicator if weight should be used.
/// Also it includes a default weight and the name of the weight
/// attribute.
////////////////////////////////////////////////////////////////////////////////
WeightInfo weightInfo;
public:
SimpleEdgeExpander(TRI_edge_direction_e direction,
TRI_document_collection_t* edgeCollection,
string edgeCollectionName,
CollectionNameResolver* resolver)
: direction(direction), edgeCollection(edgeCollection),
resolver(resolver)
{
edgeIdPrefix = edgeCollectionName + "/";
};
SimpleEdgeExpander(TRI_edge_direction_e direction,
TRI_document_collection_t* edgeCollection,
string edgeCollectionName,
CollectionNameResolver* resolver,
WeightInfo weightInfo)
: direction(direction), edgeCollection(edgeCollection),
resolver(resolver), weightInfo(weightInfo)
{
edgeIdPrefix = edgeCollectionName + "/";
};
Traverser::VertexId extractFromId(TRI_doc_mptr_copy_t& ptr) {
char const* key = TRI_EXTRACT_MARKER_FROM_KEY(&ptr);
TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_FROM_CID(&ptr);
string col = resolver->getCollectionName(cid);
col.append("/");
col.append(key);
return col;
};
Traverser::VertexId extractToId(TRI_doc_mptr_copy_t& ptr) {
char const* key = TRI_EXTRACT_MARKER_TO_KEY(&ptr);
TRI_voc_cid_t cid = TRI_EXTRACT_MARKER_TO_CID(&ptr);
string col = resolver->getCollectionName(cid);
col.append("/");
col.append(key);
return col;
};
Traverser::EdgeId extractEdgeId(TRI_doc_mptr_copy_t ptr) {
char const* key = TRI_EXTRACT_MARKER_KEY(ptr);
// AppendAndCopy
return edgeIdPrefix.append(key);
};
void operator() (Traverser::VertexId source,
vector<Traverser::Step>& result) {
std::vector<TRI_doc_mptr_copy_t> edges;
TransactionBase fake(true); // Fake a transaction to please checks.
// This is due to multi-threading
// Process Vertex Id!
size_t split;
char const* str = source.c_str();
if (!TRI_ValidateDocumentIdKeyGenerator(str, &split)) {
// TODO Error Handling
return;
}
string collectionName = source.substr(0, split);
auto col = resolver->getCollectionStruct(collectionName);
if (col == nullptr) {
// collection not found
throw TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND;
}
auto collectionCId = col->_cid;
edges = TRI_LookupEdgesDocumentCollection(edgeCollection, direction, collectionCId, const_cast<char*>(str + split + 1));
unordered_map<Traverser::VertexId, size_t> candidates;
Traverser::VertexId from;
Traverser::VertexId to;
if (weightInfo.usesWeight) {
for (size_t j = 0; j < edges.size(); ++j) {
from = extractFromId(edges[j]);
to = extractToId(edges[j]);
double currentWeight = weightInfo.defaultWeight;
if (from != source) {
auto cand = candidates.find(from);
if (cand == candidates.end()) {
// Add weight
result.emplace_back(to, from, currentWeight, extractEdgeId(edges[j]));
candidates.emplace(from, result.size() - 1);
} else {
// Compare weight
auto oldWeight = result[cand->second].weight();
if (currentWeight < oldWeight) {
result[cand->second].setWeight(currentWeight);
}
}
}
else if (to != source) {
auto cand = candidates.find(to);
if (cand == candidates.end()) {
// Add weight
result.emplace_back(to, from, currentWeight, extractEdgeId(edges[j]));
candidates.emplace(to, result.size() - 1);
} else {
auto oldWeight = result[cand->second].weight();
if (currentWeight < oldWeight) {
result[cand->second].setWeight(currentWeight);
}
}
}
}
}
else {
for (size_t j = 0; j < edges.size(); ++j) {
from = extractFromId(edges[j]);
to = extractFromId(edges[j]);
if (from != source) {
auto cand = candidates.find(from);
if (cand == candidates.end()) {
result.emplace_back(from, to, 1, extractEdgeId(edges[j]));
candidates.emplace(from, result.size()-1);
}
}
else if (to != source) {
auto cand = candidates.find(to);
if (cand == candidates.end()) {
result.emplace_back(to, from, 1, extractEdgeId(edges[j]));
candidates.emplace(to, result.size()-1);
}
}
}
}
}
};
static v8::Handle<v8::Value> pathIdsToV8(v8::Isolate* isolate, Traverser::Path& p) {
v8::EscapableHandleScope scope(isolate);
v8::Handle<v8::Object> result = v8::Object::New(isolate);
uint32_t const vn = static_cast<uint32_t>(p.vertices.size());
v8::Handle<v8::Array> vertices = v8::Array::New(isolate, static_cast<int>(vn));
for (size_t j = 0; j < vn; ++j) {
vertices->Set(static_cast<uint32_t>(j), TRI_V8_ASCII_STRING(p.vertices[j]));
}
result->Set("vertices", vertices);
uint32_t const en = static_cast<uint32_t>(p.edges.size());
v8::Handle<v8::Array> edges = v8::Array::New(isolate, static_cast<int>(en));
for (size_t j = 0; j < en; ++j) {
edges->Set(static_cast<uint32_t>(j), TRI_V8_ASCII_STRING(p.edges[j]));
}
result->Set(TRI_V8_STRING("edges"), edges);
result->Set(TRI_V8_STRING("distance"), v8::Number::New(isolate, p.weight));
return result;
};
struct LocalCollectionGuard {
LocalCollectionGuard (TRI_vocbase_col_t* collection)
: _collection(collection) {
}
~LocalCollectionGuard () {
if (_collection != nullptr && ! _collection->_isLocal) {
FreeCoordinatorCollection(_collection);
}
}
TRI_vocbase_col_t* _collection;
};
void TRI_RunDijkstraSearch (const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
if (args.Length() < 4 || args.Length() > 5) {
TRI_V8_THROW_EXCEPTION_USAGE("AQL_SHORTEST_PATH(<vertexcollection>, <edgecollection>, <start>, <end>, <options>)");
}
std::unique_ptr<char[]> key;
TRI_vocbase_t* vocbase;
TRI_vocbase_col_t const* col = nullptr;
vocbase = GetContextVocBase(isolate);
vector<string> readCollections;
vector<string> writeCollections;
TRI_voc_cid_t vertexCollectionCId;
TRI_voc_cid_t edgeCollectionCId;
TRI_voc_rid_t rid;
double lockTimeout = (double) (TRI_TRANSACTION_DEFAULT_LOCK_TIMEOUT / 1000000ULL);
bool embed = false;
bool waitForSync = false;
// get the vertex collection
if (! args[0]->IsString()) {
TRI_V8_THROW_TYPE_ERROR("expecting string for <vertexcollection>");
}
string vertexCollectionName = TRI_ObjectToString(args[0]);
// get the edge collection
if (! args[1]->IsString()) {
TRI_V8_THROW_TYPE_ERROR("expecting string for <edgecollection>");
}
string const edgeCollectionName = TRI_ObjectToString(args[1]);
vocbase = GetContextVocBase(isolate);
if (vocbase == nullptr) {
TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND);
}
V8ResolverGuard resolver(vocbase);
readCollections.push_back(vertexCollectionName);
readCollections.push_back(edgeCollectionName);
if (! args[2]->IsString()) {
TRI_V8_THROW_TYPE_ERROR("expecting string for <startVertex>");
}
string direction = "outbound";
bool useWeight = false;
string weightAttribute = "";
double defaultWeight = 1;
if (args.Length() == 5) {
if (! args[4]->IsObject()) {
TRI_V8_THROW_TYPE_ERROR("expecting json for <options>");
}
v8::Handle<v8::Object> options = args[4]->ToObject();
v8::Local<v8::String> keyDirection = TRI_V8_ASCII_STRING("direction");
v8::Local<v8::String> keyWeight= TRI_V8_ASCII_STRING("distance");
v8::Local<v8::String> keyDefaultWeight= TRI_V8_ASCII_STRING("defaultDistance");
if (options->Has(keyDirection) ) {
direction = TRI_ObjectToString(options->Get(keyDirection));
if ( direction != "outbound"
&& direction != "inbound"
&& direction != "any"
) {
TRI_V8_THROW_TYPE_ERROR("expecting direction to be 'outbound', 'inbound' or 'any'");
}
}
if (options->Has(keyWeight) && options->Has(keyDefaultWeight) ) {
useWeight = true;
weightAttribute = TRI_ObjectToString(options->Get(keyWeight));
defaultWeight = TRI_ObjectToDouble(options->Get(keyDefaultWeight));
}
}
// IHHF isCoordinator
// Start Transaction to collect all parts of the path
ExplicitTransaction trx(
vocbase,
readCollections,
writeCollections,
lockTimeout,
waitForSync,
embed
);
int res = trx.begin();
if (res != TRI_ERROR_NO_ERROR) {
TRI_V8_THROW_EXCEPTION(res);
}
col = resolver.getResolver()->getCollectionStruct(vertexCollectionName);
if (col == nullptr) {
// collection not found
TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
}
vertexCollectionCId = col->_cid;
if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
TRI_V8_THROW_EXCEPTION_MEMORY();
}
col = resolver.getResolver()->getCollectionStruct(edgeCollectionName);
if (col == nullptr) {
// collection not found
TRI_V8_THROW_EXCEPTION(TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
}
edgeCollectionCId = col->_cid;
if (trx.orderBarrier(trx.trxCollection(col->_cid)) == nullptr) {
TRI_V8_THROW_EXCEPTION_MEMORY();
}
TRI_document_collection_t* ecol = trx.trxCollection(col->_cid)->_collection->_collection;
CollectionNameResolver resolver1(vocbase);
CollectionNameResolver resolver2(vocbase);
TRI_edge_direction_e forward;
TRI_edge_direction_e backward;
if (direction == "outbound") {
forward = TRI_EDGE_OUT;
backward = TRI_EDGE_IN;
} else if (direction == "inbound") {
forward = TRI_EDGE_IN;
backward = TRI_EDGE_OUT;
} else {
forward = TRI_EDGE_ANY;
backward = TRI_EDGE_ANY;
}
unique_ptr<SimpleEdgeExpander> forwardExpander;
unique_ptr<SimpleEdgeExpander> backwardExpander;
if (useWeight) {
forwardExpander.reset(new SimpleEdgeExpander(forward, ecol, edgeCollectionName,
&resolver1, WeightInfo(weightAttribute, defaultWeight)));
backwardExpander.reset(new SimpleEdgeExpander(backward, ecol, edgeCollectionName,
&resolver2, WeightInfo(weightAttribute, defaultWeight)));
} else {
forwardExpander.reset(new SimpleEdgeExpander(forward, ecol, edgeCollectionName, &resolver1));
backwardExpander.reset(new SimpleEdgeExpander(backward, ecol, edgeCollectionName, &resolver2));
}
Traverser traverser(*forwardExpander, *backwardExpander);
unique_ptr<Traverser::Path> path(traverser.shortestPath(startVertex, targetVertex));
if (path.get() == nullptr) {
res = trx.finish(res);
v8::EscapableHandleScope scope(isolate);
TRI_V8_RETURN(scope.Escape<v8::Value>(v8::Object::New(isolate)));
}
auto result = pathIdsToV8(isolate, *path);
res = trx.finish(res);
TRI_V8_RETURN(result);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#include "../general/okina.hpp"
// *****************************************************************************
namespace mfem
{
// *****************************************************************************
// * Tests if adrs is a known address
// *****************************************************************************
static bool Known(const mm::mm_t& maps, const void *adrs)
{
const mm::memory_map_t::const_iterator found = maps.memories.find(adrs);
const bool known = found != maps.memories.end();
if (known) { return true; }
return false;
}
// *****************************************************************************
// * Looks if adrs is an alias of one memory
// *****************************************************************************
static const void* IsAlias(const mm::mm_t& maps, const void *adrs)
{
MFEM_ASSERT(!Known(maps, adrs), "Adrs is an already known address!");
for (mm::memory_map_t::const_iterator mem = maps.memories.begin();
mem != maps.memories.end(); mem++)
{
const void *b_ptr = mem->first;
if (b_ptr > adrs) { continue; }
const void *end = (char*)b_ptr + mem->second->bytes;
if (adrs < end) { return b_ptr; }
}
return NULL;
}
// *****************************************************************************
static const void* InsertAlias(mm::mm_t& maps,
const void *base,
const void *adrs)
{
mm::memory_t *mem = maps.memories.at(base);
const size_t offset = (char*)adrs - (char*)base;
const mm::alias_t *alias = new mm::alias_t{mem, offset};
maps.aliases[adrs] = alias;
mem->aliases.push_back(alias);
return adrs;
}
// *****************************************************************************
// * Tests if adrs is an alias address
// *****************************************************************************
static bool Alias(mm::mm_t& maps, const void *adrs)
{
const mm::alias_map_t::const_iterator found = maps.aliases.find(adrs);
const bool alias = found != maps.aliases.end();
if (alias) { return true; }
const void *base = IsAlias(maps, adrs);
if (!base) { return false; }
InsertAlias(maps, base, adrs);
return true;
}
// *****************************************************************************
// __attribute__((unused)) // VS doesn't like this in Appveyor
static void debugMode(void)
{
dbg("\033[1K\r%sMM %sHasBeenEnabled %sEnabled %sDisabled \
%sCPU %sGPU %sPA %sCUDA %sOCCA",
config::usingMM()?"\033[32m":"\033[31m",
config::gpuHasBeenEnabled()?"\033[32m":"\033[31m",
config::gpuEnabled()?"\033[32m":"\033[31m",
config::gpuDisabled()?"\033[32m":"\033[31m",
config::usingCpu()?"\033[32m":"\033[31m",
config::usingGpu()?"\033[32m":"\033[31m",
config::usingPA()?"\033[32m":"\033[31m",
config::usingCuda()?"\033[32m":"\033[31m",
config::usingOcca()?"\033[32m":"\033[31m");
}
// *****************************************************************************
// * Adds an address
// *****************************************************************************
void* mm::Insert(void *adrs, const size_t bytes)
{
if (!config::usingMM()) { return adrs; }
if (config::gpuDisabled()) { return adrs; }
const bool known = Known(maps, adrs);
MFEM_ASSERT(!known, "Trying to add already present address!");
dbg("\033[33m%p \033[35m(%ldb)", adrs, bytes);
maps.memories[adrs] = new memory_t(adrs,bytes);
return adrs;
}
// *****************************************************************************
// * Remove the address from the map, as well as all the address' aliases
// *****************************************************************************
void *mm::Erase(void *adrs)
{
if (!config::usingMM()) { return adrs; }
if (config::gpuDisabled()) { return adrs; }
const bool known = Known(maps, adrs);
// if (!known) { BUILTIN_TRAP; }
if (!known) { mfem_error("mm::Erase"); }
MFEM_ASSERT(known, "Trying to remove an unknown address!");
const memory_t *mem = maps.memories.at(adrs);
dbg("\033[33m %p \033[35m(%ldb)", adrs,mem->bytes);
for (const alias_t* const alias : mem->aliases)
{
maps.aliases.erase(alias);
delete alias;
}
maps.memories.erase(adrs);
return adrs;
}
// *****************************************************************************
static void* AdrsKnown(const mm::mm_t &maps, void *adrs)
{
mm::memory_t *base = maps.memories.at(adrs);
const bool host = base->host;
const bool device = !host;
const size_t bytes = base->bytes;
const bool gpu = config::usingGpu();
if (host && !gpu) { return adrs; }
if (!base->d_ptr) { cuMemAlloc(&base->d_ptr, bytes); }
if (device && gpu) { return base->d_ptr; }
if (device && !gpu) // Pull
{
cuMemcpyDtoH(adrs, base->d_ptr, bytes);
base->host = true;
return adrs;
}
// Push
assert(host && gpu);
cuMemcpyHtoD(base->d_ptr, adrs, bytes);
base->host = false;
return base->d_ptr;
}
// *****************************************************************************
static void* AdrsAlias(mm::mm_t &maps, void *adrs)
{
const bool gpu = config::usingGpu();
const mm::alias_t *alias = maps.aliases.at(adrs);
const mm::memory_t *base = alias->mem;
const bool host = base->host;
const bool device = !base->host;
const size_t bytes = base->bytes;
if (host && !gpu) { return adrs; }
if (!base->d_ptr) { cuMemAlloc(&alias->mem->d_ptr, bytes); }
void *a_ptr = (char*)base->d_ptr + alias->offset;
if (device && gpu) { return a_ptr; }
if (device && !gpu) // Pull
{
assert(base->d_ptr);
cuMemcpyDtoH(base->h_ptr, base->d_ptr, bytes);
alias->mem->host = true;
return adrs;
}
// Push
assert(host && gpu);
cuMemcpyHtoD(base->d_ptr, base->h_ptr, bytes);
alias->mem->host = false;
return a_ptr;
}
// *****************************************************************************
// * Turn an address to the right host or device one
// *****************************************************************************
void* mm::Adrs(void *adrs)
{
if (!config::usingMM()) { return adrs; }
if (config::gpuDisabled()) { return adrs; }
if (!config::gpuHasBeenEnabled()) { return adrs; }
if (Known(maps, adrs)) { return AdrsKnown(maps, adrs); }
const bool alias = Alias(maps, adrs);
// if (!alias) { BUILTIN_TRAP; }
if (!alias) { mfem_error("mm::Adrs"); }
MFEM_ASSERT(alias, "Unknown address!");
return AdrsAlias(maps, adrs);
}
// *****************************************************************************
const void* mm::Adrs(const void *adrs)
{
return (const void *) Adrs((void *)adrs);
}
// *****************************************************************************
static OccaMemory occaMemory(const mm::mm_t &maps, const void *adrs)
{
OccaDevice occaDevice = config::GetOccaDevice();
if (!config::usingMM())
{
OccaMemory o_ptr = occaWrapMemory(occaDevice, (void *)adrs, 0);
return o_ptr;
}
const bool known = Known(maps, adrs);
// if (!known) { BUILTIN_TRAP; }
if (!known) { mfem_error("occaMemory"); }
MFEM_ASSERT(known, "Unknown address!");
mm::memory_t *base = maps.memories.at(adrs);
const size_t bytes = base->bytes;
const bool gpu = config::usingGpu();
const bool occa = config::usingOcca();
MFEM_ASSERT(occa, "Using OCCA memory without OCCA mode!");
if (!base->d_ptr)
{
base->host = false; // This address is no more on the host
if (gpu)
{
cuMemAlloc(&base->d_ptr, bytes);
void *stream = config::Stream();
cuMemcpyHtoDAsync(base->d_ptr, base->h_ptr, bytes, stream);
}
else
{
base->o_ptr = occaDeviceMalloc(occaDevice, bytes);
base->d_ptr = occaMemoryPtr(base->o_ptr);
occaCopyFrom(base->o_ptr, base->h_ptr);
}
}
if (gpu)
{
return occaWrapMemory(occaDevice, base->d_ptr, bytes);
}
return base->o_ptr;
}
// *****************************************************************************
OccaMemory mm::Memory(const void *adrs)
{
return occaMemory(maps, adrs);
}
// *****************************************************************************
static void PushKnown(mm::mm_t &maps, const void *adrs, const size_t bytes)
{
mm::memory_t *base = maps.memories.at(adrs);
if (!base->d_ptr) { cuMemAlloc(&base->d_ptr, base->bytes); }
cuMemcpyHtoD(base->d_ptr, adrs, bytes == 0 ? base->bytes : bytes);
}
// *****************************************************************************
static void PushAlias(const mm::mm_t &maps, const void *adrs, const size_t bytes)
{
const mm::alias_t *alias = maps.aliases.at(adrs);
cuMemcpyHtoD((char*)alias->mem->d_ptr + alias->offset, adrs, bytes);
}
// *****************************************************************************
void mm::Push(const void *adrs, const size_t bytes)
{
if (config::gpuDisabled()) { return; }
if (!config::usingMM()) { return; }
if (!config::gpuHasBeenEnabled()) { return; }
if (Known(maps, adrs)) { return PushKnown(maps, adrs, bytes); }
assert(!config::usingOcca());
const bool alias = Alias(maps, adrs);
// if (!alias) { BUILTIN_TRAP; }
if (!alias) { mfem_error("mm::Push"); }
MFEM_ASSERT(alias, "Unknown address!");
return PushAlias(maps, adrs, bytes);
}
// *****************************************************************************
static void PullKnown(const mm::mm_t &maps, const void *adrs, const size_t bytes)
{
const mm::memory_t *base = maps.memories.at(adrs);
cuMemcpyDtoH(base->h_ptr, base->d_ptr, bytes == 0 ? base->bytes : bytes);
}
// *****************************************************************************
static void PullAlias(const mm::mm_t &maps, const void *adrs, const size_t bytes)
{
const mm::alias_t *alias = maps.aliases.at(adrs);
cuMemcpyDtoH((void *)adrs, (char*)alias->mem->d_ptr + alias->offset, bytes);
}
// *****************************************************************************
void mm::Pull(const void *adrs, const size_t bytes)
{
if (config::gpuDisabled()) { return; }
if (!config::usingMM()) { return; }
if (!config::gpuHasBeenEnabled()) { return; }
if (Known(maps, adrs)) { return PullKnown(maps, adrs, bytes); }
assert(!config::usingOcca());
const bool alias = Alias(maps, adrs);
// if (!alias) { BUILTIN_TRAP; }
if (!alias) { mfem_error("mm::Pull"); }
MFEM_ASSERT(alias, "Unknown address!");
return PullAlias(maps, adrs, bytes);
}
// *****************************************************************************
// __attribute__((unused)) // VS doesn't like this in Appveyor
static void Dump(mm::mm_t &maps)
{
if (!getenv("DBG")) { return; }
mm::memory_map_t &mem = maps.memories;
mm::alias_map_t &als = maps.aliases;
size_t k = 0;
for (mm::memory_map_t::iterator m = mem.begin(); m != mem.end(); m++)
{
const void *h_ptr = m->first;
assert(h_ptr == m->second->h_ptr);
const size_t bytes = m->second->bytes;
const void *d_ptr = m->second->d_ptr;
if (!d_ptr)
{
printf("\n[%ld] \033[33m%p \033[35m(%ld)", k, h_ptr, bytes);
}
else
{
printf("\n[%ld] \033[33m%p \033[35m (%ld) \033[32 -> %p",
k, h_ptr, bytes, d_ptr);
}
fflush(0);
k++;
}
k = 0;
for (mm::alias_map_t::iterator a = als.begin(); a != als.end(); a++)
{
const void *adrs = a->first;
const size_t offset = a->second->offset;
const void *base = a->second->mem->h_ptr;
printf("\n[%ld] \033[33m%p < (\033[37m%ld) < \033[33m%p",
k , base, offset, adrs);
fflush(0);
k++;
}
}
// *****************************************************************************
// * Data will be pushed/pulled before the copy happens on the H or the D
// *****************************************************************************
static void* d2d(void *dst, const void *src, size_t bytes, const bool async)
{
GET_PTR(src);
GET_PTR(dst);
const bool cpu = config::usingCpu();
if (cpu) { return std::memcpy(d_dst, d_src, bytes); }
if (!async) { return cuMemcpyDtoD(d_dst, (void *)d_src, bytes); }
return cuMemcpyDtoDAsync(d_dst, (void *)d_src, bytes, config::Stream());
}
// *****************************************************************************
void* mm::memcpy(void *dst, const void *src, size_t bytes, const bool async)
{
if (bytes == 0) { return dst; }
return d2d(dst, src, bytes, async);
}
// *****************************************************************************
} // namespace mfem
<commit_msg>Const'ing<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#include "../general/okina.hpp"
// *****************************************************************************
namespace mfem
{
// *****************************************************************************
// * Tests if adrs is a known address
// *****************************************************************************
static bool Known(const mm::mm_t& maps, const void *adrs)
{
const mm::memory_map_t::const_iterator found = maps.memories.find(adrs);
const bool known = found != maps.memories.end();
if (known) { return true; }
return false;
}
// *****************************************************************************
// * Looks if adrs is an alias of one memory
// *****************************************************************************
static const void* IsAlias(const mm::mm_t& maps, const void *adrs)
{
MFEM_ASSERT(!Known(maps, adrs), "Adrs is an already known address!");
for (mm::memory_map_t::const_iterator mem = maps.memories.begin();
mem != maps.memories.end(); mem++)
{
const void *b_ptr = mem->first;
if (b_ptr > adrs) { continue; }
const void *end = (char*)b_ptr + mem->second->bytes;
if (adrs < end) { return b_ptr; }
}
return NULL;
}
// *****************************************************************************
static const void* InsertAlias(mm::mm_t& maps,
const void *base,
const void *adrs)
{
mm::memory_t *mem = maps.memories.at(base);
const size_t offset = (char*)adrs - (char*)base;
const mm::alias_t *alias = new mm::alias_t{mem, offset};
maps.aliases[adrs] = alias;
mem->aliases.push_back(alias);
return adrs;
}
// *****************************************************************************
// * Tests if adrs is an alias address
// *****************************************************************************
static bool Alias(mm::mm_t& maps, const void *adrs)
{
const mm::alias_map_t::const_iterator found = maps.aliases.find(adrs);
const bool alias = found != maps.aliases.end();
if (alias) { return true; }
const void *base = IsAlias(maps, adrs);
if (!base) { return false; }
InsertAlias(maps, base, adrs);
return true;
}
// *****************************************************************************
// __attribute__((unused)) // VS doesn't like this in Appveyor
static void debugMode(void)
{
dbg("\033[1K\r%sMM %sHasBeenEnabled %sEnabled %sDisabled \
%sCPU %sGPU %sPA %sCUDA %sOCCA",
config::usingMM()?"\033[32m":"\033[31m",
config::gpuHasBeenEnabled()?"\033[32m":"\033[31m",
config::gpuEnabled()?"\033[32m":"\033[31m",
config::gpuDisabled()?"\033[32m":"\033[31m",
config::usingCpu()?"\033[32m":"\033[31m",
config::usingGpu()?"\033[32m":"\033[31m",
config::usingPA()?"\033[32m":"\033[31m",
config::usingCuda()?"\033[32m":"\033[31m",
config::usingOcca()?"\033[32m":"\033[31m");
}
// *****************************************************************************
// * Adds an address
// *****************************************************************************
void* mm::Insert(void *adrs, const size_t bytes)
{
if (!config::usingMM()) { return adrs; }
if (config::gpuDisabled()) { return adrs; }
const bool known = Known(maps, adrs);
MFEM_ASSERT(!known, "Trying to add already present address!");
dbg("\033[33m%p \033[35m(%ldb)", adrs, bytes);
maps.memories[adrs] = new memory_t(adrs,bytes);
return adrs;
}
// *****************************************************************************
// * Remove the address from the map, as well as all the address' aliases
// *****************************************************************************
void *mm::Erase(void *adrs)
{
if (!config::usingMM()) { return adrs; }
if (config::gpuDisabled()) { return adrs; }
const bool known = Known(maps, adrs);
// if (!known) { BUILTIN_TRAP; }
if (!known) { mfem_error("mm::Erase"); }
MFEM_ASSERT(known, "Trying to remove an unknown address!");
const memory_t *mem = maps.memories.at(adrs);
dbg("\033[33m %p \033[35m(%ldb)", adrs,mem->bytes);
for (const alias_t* const alias : mem->aliases)
{
maps.aliases.erase(alias);
delete alias;
}
maps.memories.erase(adrs);
return adrs;
}
// *****************************************************************************
static void* AdrsKnown(const mm::mm_t &maps, void *adrs)
{
mm::memory_t *base = maps.memories.at(adrs);
const bool host = base->host;
const bool device = !host;
const size_t bytes = base->bytes;
const bool gpu = config::usingGpu();
if (host && !gpu) { return adrs; }
if (!base->d_ptr) { cuMemAlloc(&base->d_ptr, bytes); }
if (device && gpu) { return base->d_ptr; }
if (device && !gpu) // Pull
{
cuMemcpyDtoH(adrs, base->d_ptr, bytes);
base->host = true;
return adrs;
}
// Push
assert(host && gpu);
cuMemcpyHtoD(base->d_ptr, adrs, bytes);
base->host = false;
return base->d_ptr;
}
// *****************************************************************************
static void* AdrsAlias(mm::mm_t &maps, void *adrs)
{
const bool gpu = config::usingGpu();
const mm::alias_t *alias = maps.aliases.at(adrs);
const mm::memory_t *base = alias->mem;
const bool host = base->host;
const bool device = !base->host;
const size_t bytes = base->bytes;
if (host && !gpu) { return adrs; }
if (!base->d_ptr) { cuMemAlloc(&alias->mem->d_ptr, bytes); }
void *a_ptr = (char*)base->d_ptr + alias->offset;
if (device && gpu) { return a_ptr; }
if (device && !gpu) // Pull
{
assert(base->d_ptr);
cuMemcpyDtoH(base->h_ptr, base->d_ptr, bytes);
alias->mem->host = true;
return adrs;
}
// Push
assert(host && gpu);
cuMemcpyHtoD(base->d_ptr, base->h_ptr, bytes);
alias->mem->host = false;
return a_ptr;
}
// *****************************************************************************
// * Turn an address to the right host or device one
// *****************************************************************************
void* mm::Adrs(void *adrs)
{
if (!config::usingMM()) { return adrs; }
if (config::gpuDisabled()) { return adrs; }
if (!config::gpuHasBeenEnabled()) { return adrs; }
if (Known(maps, adrs)) { return AdrsKnown(maps, adrs); }
const bool alias = Alias(maps, adrs);
// if (!alias) { BUILTIN_TRAP; }
if (!alias) { mfem_error("mm::Adrs"); }
MFEM_ASSERT(alias, "Unknown address!");
return AdrsAlias(maps, adrs);
}
// *****************************************************************************
const void* mm::Adrs(const void *adrs)
{
return (const void *) Adrs((void *)adrs);
}
// *****************************************************************************
static OccaMemory occaMemory(const mm::mm_t &maps, const void *adrs)
{
OccaDevice occaDevice = config::GetOccaDevice();
if (!config::usingMM())
{
OccaMemory o_ptr = occaWrapMemory(occaDevice, (void *)adrs, 0);
return o_ptr;
}
const bool known = Known(maps, adrs);
// if (!known) { BUILTIN_TRAP; }
if (!known) { mfem_error("occaMemory"); }
MFEM_ASSERT(known, "Unknown address!");
mm::memory_t *base = maps.memories.at(adrs);
const size_t bytes = base->bytes;
const bool gpu = config::usingGpu();
const bool occa = config::usingOcca();
MFEM_ASSERT(occa, "Using OCCA memory without OCCA mode!");
if (!base->d_ptr)
{
base->host = false; // This address is no more on the host
if (gpu)
{
cuMemAlloc(&base->d_ptr, bytes);
void *stream = config::Stream();
cuMemcpyHtoDAsync(base->d_ptr, base->h_ptr, bytes, stream);
}
else
{
base->o_ptr = occaDeviceMalloc(occaDevice, bytes);
base->d_ptr = occaMemoryPtr(base->o_ptr);
occaCopyFrom(base->o_ptr, base->h_ptr);
}
}
if (gpu)
{
return occaWrapMemory(occaDevice, base->d_ptr, bytes);
}
return base->o_ptr;
}
// *****************************************************************************
OccaMemory mm::Memory(const void *adrs)
{
return occaMemory(maps, adrs);
}
// *****************************************************************************
static void PushKnown(mm::mm_t &maps, const void *adrs, const size_t bytes)
{
mm::memory_t *base = maps.memories.at(adrs);
if (!base->d_ptr) { cuMemAlloc(&base->d_ptr, base->bytes); }
cuMemcpyHtoD(base->d_ptr, adrs, bytes == 0 ? base->bytes : bytes);
}
// *****************************************************************************
static void PushAlias(const mm::mm_t &maps, const void *adrs, const size_t bytes)
{
const mm::alias_t *alias = maps.aliases.at(adrs);
cuMemcpyHtoD((char*)alias->mem->d_ptr + alias->offset, adrs, bytes);
}
// *****************************************************************************
void mm::Push(const void *adrs, const size_t bytes)
{
if (config::gpuDisabled()) { return; }
if (!config::usingMM()) { return; }
if (!config::gpuHasBeenEnabled()) { return; }
if (Known(maps, adrs)) { return PushKnown(maps, adrs, bytes); }
assert(!config::usingOcca());
const bool alias = Alias(maps, adrs);
// if (!alias) { BUILTIN_TRAP; }
if (!alias) { mfem_error("mm::Push"); }
MFEM_ASSERT(alias, "Unknown address!");
return PushAlias(maps, adrs, bytes);
}
// *****************************************************************************
static void PullKnown(const mm::mm_t &maps, const void *adrs, const size_t bytes)
{
const mm::memory_t *base = maps.memories.at(adrs);
cuMemcpyDtoH(base->h_ptr, base->d_ptr, bytes == 0 ? base->bytes : bytes);
}
// *****************************************************************************
static void PullAlias(const mm::mm_t &maps, const void *adrs, const size_t bytes)
{
const mm::alias_t *alias = maps.aliases.at(adrs);
cuMemcpyDtoH((void *)adrs, (char*)alias->mem->d_ptr + alias->offset, bytes);
}
// *****************************************************************************
void mm::Pull(const void *adrs, const size_t bytes)
{
if (config::gpuDisabled()) { return; }
if (!config::usingMM()) { return; }
if (!config::gpuHasBeenEnabled()) { return; }
if (Known(maps, adrs)) { return PullKnown(maps, adrs, bytes); }
assert(!config::usingOcca());
const bool alias = Alias(maps, adrs);
// if (!alias) { BUILTIN_TRAP; }
if (!alias) { mfem_error("mm::Pull"); }
MFEM_ASSERT(alias, "Unknown address!");
return PullAlias(maps, adrs, bytes);
}
// *****************************************************************************
// __attribute__((unused)) // VS doesn't like this in Appveyor
static void Dump(const mm::mm_t &maps)
{
if (!getenv("DBG")) { return; }
const mm::memory_map_t &mem = maps.memories;
const mm::alias_map_t &als = maps.aliases;
size_t k = 0;
for (mm::memory_map_t::const_iterator m = mem.begin(); m != mem.end(); m++)
{
const void *h_ptr = m->first;
assert(h_ptr == m->second->h_ptr);
const size_t bytes = m->second->bytes;
const void *d_ptr = m->second->d_ptr;
if (!d_ptr)
{
printf("\n[%ld] \033[33m%p \033[35m(%ld)", k, h_ptr, bytes);
}
else
{
printf("\n[%ld] \033[33m%p \033[35m (%ld) \033[32 -> %p",
k, h_ptr, bytes, d_ptr);
}
fflush(0);
k++;
}
k = 0;
for (mm::alias_map_t::const_iterator a = als.begin(); a != als.end(); a++)
{
const void *adrs = a->first;
const size_t offset = a->second->offset;
const void *base = a->second->mem->h_ptr;
printf("\n[%ld] \033[33m%p < (\033[37m%ld) < \033[33m%p",
k , base, offset, adrs);
fflush(0);
k++;
}
}
// *****************************************************************************
// * Data will be pushed/pulled before the copy happens on the H or the D
// *****************************************************************************
static void* d2d(void *dst, const void *src, const size_t bytes, const bool async)
{
GET_PTR(src);
GET_PTR(dst);
const bool cpu = config::usingCpu();
if (cpu) { return std::memcpy(d_dst, d_src, bytes); }
if (!async) { return cuMemcpyDtoD(d_dst, (void *)d_src, bytes); }
return cuMemcpyDtoDAsync(d_dst, (void *)d_src, bytes, config::Stream());
}
// *****************************************************************************
void* mm::memcpy(void *dst, const void *src, const size_t bytes, const bool async)
{
if (bytes == 0) { return dst; }
return d2d(dst, src, bytes, async);
}
// *****************************************************************************
} // namespace mfem
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006 Zack Rusin <zack@kde.org>
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "ChromeClientQt.h"
#include "Frame.h"
#include "FrameView.h"
#include "FrameLoadRequest.h"
#include "qwebpage.h"
#define notImplemented() qDebug("FIXME: UNIMPLEMENTED: %s:%d (%s)", __FILE__, __LINE__, __FUNCTION__)
namespace WebCore
{
ChromeClientQt::ChromeClientQt(QWebPage* webPage)
: m_webPage(webPage)
{
}
ChromeClientQt::~ChromeClientQt()
{
}
void ChromeClientQt::setWindowRect(const FloatRect& rect)
{
if (!m_webPage)
return;
// m_webPage->emit setWindowRect(QRect(qRound(r.x()), qRound(r.y()),
// qRound(r.width()), qRound(r.height())));
}
FloatRect ChromeClientQt::windowRect()
{
if (!m_webPage)
return FloatRect();
return IntRect(m_webPage->topLevelWidget()->geometry());
}
FloatRect ChromeClientQt::pageRect()
{
if (!m_webPage)
return FloatRect();
return FloatRect(QRectF(m_webPage->rect()));
}
float ChromeClientQt::scaleFactor()
{
notImplemented();
return 1;
}
void ChromeClientQt::focus()
{
if (!m_webPage)
return;
m_webPage->setFocus();
}
void ChromeClientQt::unfocus()
{
if (!m_webPage)
return;
m_webPage->clearFocus();
}
bool ChromeClientQt::canTakeFocus(FocusDirection)
{
if (!m_webPage)
return false;
return m_webPage->focusPolicy() != Qt::NoFocus;
}
void ChromeClientQt::takeFocus(FocusDirection)
{
if (!m_webPage)
return;
m_webPage->clearFocus();
}
Page* ChromeClientQt::createWindow(const FrameLoadRequest& request)
{
//QWebPage *newPage = m_webPage->createWindow(...);
notImplemented();
return 0;
}
Page* ChromeClientQt::createModalDialog(const FrameLoadRequest&)
{
notImplemented();
return 0;
}
void ChromeClientQt::show()
{
if (!m_webPage)
return;
m_webPage->topLevelWidget()->show();
}
bool ChromeClientQt::canRunModal()
{
notImplemented();
return false;
}
void ChromeClientQt::runModal()
{
notImplemented();
}
void ChromeClientQt::setToolbarsVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::toolbarsVisible()
{
notImplemented();
return false;
}
void ChromeClientQt::setStatusbarVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::statusbarVisible()
{
notImplemented();
return false;
}
void ChromeClientQt::setScrollbarsVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::scrollbarsVisible()
{
notImplemented();
return true;
}
void ChromeClientQt::setMenubarVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::menubarVisible()
{
notImplemented();
return false;
}
void ChromeClientQt::setResizable(bool)
{
notImplemented();
}
void ChromeClientQt::addMessageToConsole(const String& message, unsigned int lineNumber,
const String& sourceID)
{
QString x = message;
QString y = sourceID;
m_webPage->consoleMessage(x, lineNumber, y);
}
void ChromeClientQt::chromeDestroyed()
{
notImplemented();
}
bool ChromeClientQt::canRunBeforeUnloadConfirmPanel()
{
notImplemented();
}
bool ChromeClientQt::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
{
notImplemented();
}
void ChromeClientQt::closeWindowSoon()
{
notImplemented();
}
void ChromeClientQt::runJavaScriptAlert(Frame*, const String& msg)
{
QString x = msg;
m_webPage->runJavaScriptAlert(0, x);
}
bool ChromeClientQt::runJavaScriptConfirm(Frame*, const String&)
{
notImplemented();
}
bool ChromeClientQt::runJavaScriptPrompt(Frame*, const String& message, const String& defaultValue, String& result)
{
notImplemented();
}
void ChromeClientQt::setStatusbarText(const String&)
{
notImplemented();
}
}
<commit_msg>Missed saving this file before the previous checkin.<commit_after>/*
* Copyright (C) 2006 Zack Rusin <zack@kde.org>
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "ChromeClientQt.h"
#include "Frame.h"
#include "FrameView.h"
#include "FrameLoadRequest.h"
#include "qwebpage.h"
#define notImplemented() qDebug("FIXME: UNIMPLEMENTED: %s:%d (%s)", __FILE__, __LINE__, __FUNCTION__)
namespace WebCore
{
ChromeClientQt::ChromeClientQt(QWebPage* webPage)
: m_webPage(webPage)
{
}
ChromeClientQt::~ChromeClientQt()
{
}
void ChromeClientQt::setWindowRect(const FloatRect& rect)
{
if (!m_webPage)
return;
// m_webPage->emit setWindowRect(QRect(qRound(r.x()), qRound(r.y()),
// qRound(r.width()), qRound(r.height())));
}
FloatRect ChromeClientQt::windowRect()
{
if (!m_webPage)
return FloatRect();
return IntRect(m_webPage->topLevelWidget()->geometry());
}
FloatRect ChromeClientQt::pageRect()
{
if (!m_webPage)
return FloatRect();
return FloatRect(QRectF(m_webPage->rect()));
}
float ChromeClientQt::scaleFactor()
{
notImplemented();
return 1;
}
void ChromeClientQt::focus()
{
if (!m_webPage)
return;
m_webPage->setFocus();
}
void ChromeClientQt::unfocus()
{
if (!m_webPage)
return;
m_webPage->clearFocus();
}
bool ChromeClientQt::canTakeFocus(FocusDirection)
{
if (!m_webPage)
return false;
return m_webPage->focusPolicy() != Qt::NoFocus;
}
void ChromeClientQt::takeFocus(FocusDirection)
{
if (!m_webPage)
return;
m_webPage->clearFocus();
}
Page* ChromeClientQt::createWindow(const FrameLoadRequest& request)
{
//QWebPage *newPage = m_webPage->createWindow(...);
notImplemented();
return 0;
}
Page* ChromeClientQt::createModalDialog(const FrameLoadRequest&)
{
notImplemented();
return 0;
}
void ChromeClientQt::show()
{
if (!m_webPage)
return;
m_webPage->topLevelWidget()->show();
}
bool ChromeClientQt::canRunModal()
{
notImplemented();
return false;
}
void ChromeClientQt::runModal()
{
notImplemented();
}
void ChromeClientQt::setToolbarsVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::toolbarsVisible()
{
notImplemented();
return false;
}
void ChromeClientQt::setStatusbarVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::statusbarVisible()
{
notImplemented();
return false;
}
void ChromeClientQt::setScrollbarsVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::scrollbarsVisible()
{
notImplemented();
return true;
}
void ChromeClientQt::setMenubarVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::menubarVisible()
{
notImplemented();
return false;
}
void ChromeClientQt::setResizable(bool)
{
notImplemented();
}
void ChromeClientQt::addMessageToConsole(const String& message, unsigned int lineNumber,
const String& sourceID)
{
QString x = message;
QString y = sourceID;
m_webPage->javaScriptConsoleMessage(x, lineNumber, y);
}
void ChromeClientQt::chromeDestroyed()
{
notImplemented();
}
bool ChromeClientQt::canRunBeforeUnloadConfirmPanel()
{
notImplemented();
}
bool ChromeClientQt::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
{
notImplemented();
}
void ChromeClientQt::closeWindowSoon()
{
notImplemented();
}
void ChromeClientQt::runJavaScriptAlert(Frame*, const String& msg)
{
QString x = msg;
m_webPage->runJavaScriptAlert(0, x);
}
bool ChromeClientQt::runJavaScriptConfirm(Frame*, const String&)
{
notImplemented();
}
bool ChromeClientQt::runJavaScriptPrompt(Frame*, const String& message, const String& defaultValue, String& result)
{
notImplemented();
}
void ChromeClientQt::setStatusbarText(const String&)
{
notImplemented();
}
}
<|endoftext|> |
<commit_before>#include "SecureSocket.hpp"
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sstream>
#include <iostream>
#include "Scope.hpp"
#include "Timer.hpp"
using namespace Kite;
//#define debugprintf(...) fprintf(stderr, __VA_ARGS__)
#define debugprintf(...)
//TODO: not thread safe
static std::map<SSL *, SecureSocket *> rebind_map;
class Kite::SecureSocketPrivate : public Kite::Evented, public Kite::Timer, public Kite::Scope {
public:
SSL_CTX *ssl_ctx;
BIO *bio;
SSL *ssl; //do note delete, is a ref from bio
SecureSocket::SocketState state;
std::string errorMessage;
bool useTls;
SecureSocket *p;
void d_connect();
SecureSocketPrivate(std::weak_ptr<Kite::EventLoop> ev)
: Kite::Evented(ev)
, Kite::Timer(ev)
{
KITE_TIMER_DEBUG_NAME(this, "Kite::SecureSocketPrivate::connectionTimout");
}
virtual bool onExpired() {
if (state == Kite::SecureSocket::Connecting) {
errorMessage = "Connection timed out";
state = SecureSocket::TransportErrror;
p->disconnect();
}
return false;
}
virtual void onActivated (int fd, int events)
{
if (events & Kite::Evented::Write) {
if (state == Kite::SecureSocket::Connecting) {
state = SecureSocket::Connected;
p->onConnected();
}
evRemove(fd);
evAdd(fd, Kite::Evented::Read);
return;
}
if (events & Kite::Evented::Read) {
if (state == Kite::SecureSocket::Connecting) {
d_connect();
} else if (state == Kite::SecureSocket::Connected) {
p->onActivated(Kite::Evented::Read);
if (BIO_pending(bio)) {
Timer::later(Evented::ev(), [this, fd](){
onActivated(fd, Kite::Evented::Read);
return false;
}, 1, this, "BIO_pending after read");
}
}
}
}
friend class Kite::SecureSocket;
};
void apps_ssl_info_callback(const SSL *s, int where, int ret)
{
const char *str;
int w;
w=where& ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) str="SSL_connect";
else if (w & SSL_ST_ACCEPT) str="SSL_accept";
else str="undefined";
if (where & SSL_CB_LOOP)
{
debugprintf("%s:%s\n",str,SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT)
{
str=(where & SSL_CB_READ)?"read":"write";
debugprintf("SSL3 alert %s:%s:%s\n",
str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT)
{
if (ret == 0)
debugprintf("%s:failed in %s\n",
str,SSL_state_string_long(s));
else if (ret < 0)
{
debugprintf("%s:error in %s\n",
str,SSL_state_string_long(s));
}
}
}
SecureSocket::SecureSocket(std::weak_ptr<Kite::EventLoop> ev)
: p(new SecureSocketPrivate(ev))
{
static bool sslIsInit = false;
if (!sslIsInit) {
SSL_load_error_strings();
SSL_library_init();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
}
p->p = this;
p->ssl_ctx = 0;
p->bio = 0;
p->ssl = 0;
p->state = Disconnected;
// init ssl context
p->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if (p->ssl_ctx == NULL)
{
ERR_print_errors_fp(stderr);
return;
}
SSL_CTX_set_info_callback(p->ssl_ctx, apps_ssl_info_callback);
}
SecureSocket::~SecureSocket()
{
debugprintf("~SecureSocket() destructing\n");
disconnect();
if (p->bio)
BIO_free_all(p->bio);
if (p->ssl_ctx)
SSL_CTX_free(p->ssl_ctx);
delete p;
debugprintf("~SecureSocket() dead\n");
}
bool SecureSocket::setCaDir (const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, NULL, path.c_str());
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setCaFile(const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, path.c_str(), NULL);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientCertificateFile(const std::string &path)
{
int r = SSL_CTX_use_certificate_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientKeyFile(const std::string &path)
{
int r = SSL_CTX_use_PrivateKey_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
void SecureSocket::disconnect()
{
debugprintf("SecureSocket::disconnect()\n");
onDisconnected(p->state);
if (p->state == Connected || p->state == Connecting) {
p->state = Disconnected;
}
int fd = 0;
BIO_get_fd(p->bio, &fd);
if (fd != 0) {
p->evRemove(fd);
}
if (p->ssl) {
auto e = rebind_map.find(p->ssl);
if (e != rebind_map.end())
rebind_map.erase(e);
}
if (p->bio)
BIO_ssl_shutdown(p->bio);
}
void SecureSocket::connect(const std::string &hostname, int port, uint64_t timeout, bool tls)
{
p->useTls = tls;
p->reset(timeout);
p->state = Connecting;
int r = 0;
if (p->useTls) {
p->bio = BIO_new_ssl_connect(p->ssl_ctx);
} else {
std::vector<char> host_c(hostname.begin(), hostname.end());
host_c.push_back('\0');
p->bio = BIO_new_connect(&host_c[0]);
}
if (!p->bio) {
p->errorMessage = "BIO_new_ssl_connect returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
BIO_set_nbio(p->bio, 1);
if (p->useTls) {
BIO_get_ssl(p->bio, &p->ssl);
if (!(p->ssl)) {
p->errorMessage = "BIO_get_ssl returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
rebind_map.insert(std::make_pair(p->ssl, this));
auto cb = [](SSL *ssl, X509 **x509, EVP_PKEY **pkey) {
SecureSocket *that = rebind_map[ssl];
that->p->errorMessage = "Client Certificate Requested\n";
that->p->state = SecureClientCertificateRequired;
that->disconnect();
return 0;
};
SSL_CTX_set_client_cert_cb(p->ssl_ctx, cb);
SSL_set_mode(p->ssl, SSL_MODE_AUTO_RETRY);
}
BIO_set_conn_hostname(p->bio, hostname.c_str());
BIO_set_conn_int_port(p->bio, &port);
p->d_connect();
}
void SecureSocketPrivate::d_connect()
{
debugprintf("d_connect\n");
int r = BIO_do_connect(bio);
if (r < 1) {
if (BIO_should_retry(bio)) {
debugprintf("retry\n");
// rety imidiately.
// this seems how to do it properly, but i cant get it working:
// https://github.com/jmckaskill/bio_poll/blob/master/poll.c
// probably because BIO_get_fd is garbage before connect?
Timer::later(Evented::ev(), [this](){
d_connect();
return false;
}, 100, this, "BIO_should_retry");
return;
}
if (state != SecureSocket::SecureClientCertificateRequired) {
const char *em = ERR_reason_error_string(ERR_get_error());
debugprintf("BIO_new_ssl_connect failed: %u (0x%x)\n", r, r);
debugprintf("Error: %s\n", em);
debugprintf("%s\n", ERR_error_string(ERR_get_error(), NULL));
if (useTls) {
debugprintf("p_ssl state: %s\n",SSL_state_string_long(ssl));
}
ERR_print_errors_fp(stderr);
errorMessage = std::string(em ? strdup(em) : "??");
state = SecureSocket::TransportErrror;
}
p->disconnect();
return;
}
if (useTls) {
auto result = SSL_get_verify_result(ssl);
if (result != X509_V_OK) {
std::stringstream str;
str << "Secure Peer Verification Errror " << result;
errorMessage = str.str();
state = SecureSocket::SecurePeerNotVerified;
p->disconnect();
return;
}
}
int fd = 0;
BIO_get_fd(bio, &fd);
if (fd == 0) {
errorMessage = "BIO_get_fd returned 0";
state = SecureSocket::SecureSetupError;
p->disconnect();
return;
}
if (useTls) {
state = SecureSocket::Connected;
evRemove(fd);
evAdd(fd, Kite::Evented::Read);
p->onConnected();
} else {
debugprintf("waiting for write ready\n");
evRemove(fd);
evAdd(fd, Kite::Evented::Read | Kite::Evented::Write);
}
}
int SecureSocket::write(const char *data, int len)
{
if (p->state != Connected)
return 0;
int r;
do {
r = BIO_write(p->bio, data, len);
} while (r < 0 && BIO_should_retry(p->bio));
return len;
}
int SecureSocket::read (char *data, int len)
{
if (p->state != Connected)
return 0;
int e = BIO_read(p->bio, data, len);
if (e > 0)
return e;
if (BIO_should_retry(p->bio))
return -1;
disconnect();
return 0;
}
const std::string &SecureSocket::errorMessage() const
{
return p->errorMessage;
}
void SecureSocket::flush()
{
BIO_flush(p->bio);
}
std::weak_ptr<EventLoop> SecureSocket::ev()
{
return p->Evented::ev();
}
<commit_msg>must call BIO_reset in disconnect<commit_after>#include "SecureSocket.hpp"
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sstream>
#include <iostream>
#include "Scope.hpp"
#include "Timer.hpp"
using namespace Kite;
//#define debugprintf(...) fprintf(stderr, __VA_ARGS__)
#define debugprintf(...)
//TODO: not thread safe
static std::map<SSL *, SecureSocket *> rebind_map;
class Kite::SecureSocketPrivate : public Kite::Evented, public Kite::Timer, public Kite::Scope {
public:
SSL_CTX *ssl_ctx;
BIO *bio;
SSL *ssl; //do note delete, is a ref from bio
SecureSocket::SocketState state;
std::string errorMessage;
bool useTls;
SecureSocket *p;
void d_connect();
SecureSocketPrivate(std::weak_ptr<Kite::EventLoop> ev)
: Kite::Evented(ev)
, Kite::Timer(ev)
{
KITE_TIMER_DEBUG_NAME(this, "Kite::SecureSocketPrivate::connectionTimout");
}
virtual bool onExpired() {
if (state == Kite::SecureSocket::Connecting) {
errorMessage = "Connection timed out";
state = SecureSocket::TransportErrror;
p->disconnect();
}
return false;
}
virtual void onActivated (int fd, int events)
{
if (events & Kite::Evented::Write) {
if (state == Kite::SecureSocket::Connecting) {
state = SecureSocket::Connected;
p->onConnected();
}
evRemove(fd);
evAdd(fd, Kite::Evented::Read);
return;
}
if (events & Kite::Evented::Read) {
if (state == Kite::SecureSocket::Connecting) {
d_connect();
} else if (state == Kite::SecureSocket::Connected) {
p->onActivated(Kite::Evented::Read);
if (BIO_pending(bio)) {
Timer::later(Evented::ev(), [this, fd](){
onActivated(fd, Kite::Evented::Read);
return false;
}, 1, this, "BIO_pending after read");
}
}
}
}
friend class Kite::SecureSocket;
};
void apps_ssl_info_callback(const SSL *s, int where, int ret)
{
const char *str;
int w;
w=where& ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) str="SSL_connect";
else if (w & SSL_ST_ACCEPT) str="SSL_accept";
else str="undefined";
if (where & SSL_CB_LOOP)
{
debugprintf("%s:%s\n",str,SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT)
{
str=(where & SSL_CB_READ)?"read":"write";
debugprintf("SSL3 alert %s:%s:%s\n",
str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT)
{
if (ret == 0)
debugprintf("%s:failed in %s\n",
str,SSL_state_string_long(s));
else if (ret < 0)
{
debugprintf("%s:error in %s\n",
str,SSL_state_string_long(s));
}
}
}
SecureSocket::SecureSocket(std::weak_ptr<Kite::EventLoop> ev)
: p(new SecureSocketPrivate(ev))
{
static bool sslIsInit = false;
if (!sslIsInit) {
SSL_load_error_strings();
SSL_library_init();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
}
p->p = this;
p->ssl_ctx = 0;
p->bio = 0;
p->ssl = 0;
p->state = Disconnected;
// init ssl context
p->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if (p->ssl_ctx == NULL)
{
ERR_print_errors_fp(stderr);
return;
}
SSL_CTX_set_info_callback(p->ssl_ctx, apps_ssl_info_callback);
}
SecureSocket::~SecureSocket()
{
debugprintf("~SecureSocket() destructing\n");
disconnect();
if (p->bio)
BIO_free_all(p->bio);
if (p->ssl_ctx)
SSL_CTX_free(p->ssl_ctx);
delete p;
debugprintf("~SecureSocket() dead\n");
}
bool SecureSocket::setCaDir (const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, NULL, path.c_str());
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setCaFile(const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, path.c_str(), NULL);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientCertificateFile(const std::string &path)
{
int r = SSL_CTX_use_certificate_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientKeyFile(const std::string &path)
{
int r = SSL_CTX_use_PrivateKey_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
void SecureSocket::disconnect()
{
debugprintf("SecureSocket::disconnect()\n");
int fd = 0;
BIO_get_fd(p->bio, &fd);
if (fd != 0) {
p->evRemove(fd);
}
if (p->ssl) {
auto e = rebind_map.find(p->ssl);
if (e != rebind_map.end())
rebind_map.erase(e);
}
if (p->bio) {
debugprintf("SecureSocket::BIO_ssl_shutdown\n");
BIO_set_close(p->bio, BIO_CLOSE);
BIO_reset(p->bio);
BIO_ssl_shutdown(p->bio);
}
if (p->state == Connected || p->state == Connecting) {
p->state = Disconnected;
onDisconnected(p->state);
}
}
void SecureSocket::connect(const std::string &hostname, int port, uint64_t timeout, bool tls)
{
disconnect();
p->useTls = tls;
p->reset(timeout);
p->state = Connecting;
int r = 0;
if (p->useTls) {
p->bio = BIO_new_ssl_connect(p->ssl_ctx);
} else {
std::vector<char> host_c(hostname.begin(), hostname.end());
host_c.push_back('\0');
p->bio = BIO_new_connect(&host_c[0]);
}
if (!p->bio) {
p->errorMessage = "BIO_new_ssl_connect returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
BIO_set_nbio(p->bio, 1);
if (p->useTls) {
BIO_get_ssl(p->bio, &p->ssl);
if (!(p->ssl)) {
p->errorMessage = "BIO_get_ssl returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
rebind_map.insert(std::make_pair(p->ssl, this));
auto cb = [](SSL *ssl, X509 **x509, EVP_PKEY **pkey) {
SecureSocket *that = rebind_map[ssl];
that->p->errorMessage = "Client Certificate Requested\n";
that->p->state = SecureClientCertificateRequired;
that->disconnect();
return 0;
};
SSL_CTX_set_client_cert_cb(p->ssl_ctx, cb);
SSL_set_mode(p->ssl, SSL_MODE_AUTO_RETRY);
}
BIO_set_conn_hostname(p->bio, hostname.c_str());
BIO_set_conn_int_port(p->bio, &port);
p->d_connect();
}
void SecureSocketPrivate::d_connect()
{
debugprintf("d_connect\n");
int r = BIO_do_connect(bio);
if (r < 1) {
if (BIO_should_retry(bio)) {
debugprintf("retry\n");
// rety imidiately.
// this seems how to do it properly, but i cant get it working:
// https://github.com/jmckaskill/bio_poll/blob/master/poll.c
// probably because BIO_get_fd is garbage before connect?
Timer::later(Evented::ev(), [this](){
d_connect();
return false;
}, 100, this, "BIO_should_retry");
return;
}
if (state != SecureSocket::SecureClientCertificateRequired) {
const char *em = ERR_reason_error_string(ERR_get_error());
debugprintf("BIO_new_ssl_connect failed: %u (0x%x)\n", r, r);
debugprintf("Error: %s\n", em);
debugprintf("%s\n", ERR_error_string(ERR_get_error(), NULL));
if (useTls) {
debugprintf("p_ssl state: %s\n",SSL_state_string_long(ssl));
}
ERR_print_errors_fp(stderr);
errorMessage = std::string(em ? strdup(em) : "??");
state = SecureSocket::TransportErrror;
}
p->disconnect();
return;
}
if (useTls) {
auto result = SSL_get_verify_result(ssl);
if (result != X509_V_OK) {
std::stringstream str;
str << "Secure Peer Verification Errror " << result;
errorMessage = str.str();
state = SecureSocket::SecurePeerNotVerified;
p->disconnect();
return;
}
}
int fd = 0;
BIO_get_fd(bio, &fd);
if (fd == 0) {
errorMessage = "BIO_get_fd returned 0";
state = SecureSocket::SecureSetupError;
p->disconnect();
return;
}
if (useTls) {
state = SecureSocket::Connected;
evRemove(fd);
evAdd(fd, Kite::Evented::Read);
p->onConnected();
} else {
debugprintf("waiting for write ready\n");
evRemove(fd);
evAdd(fd, Kite::Evented::Read | Kite::Evented::Write);
}
}
int SecureSocket::write(const char *data, int len)
{
if (p->state != Connected)
return 0;
int r;
do {
r = BIO_write(p->bio, data, len);
} while (r < 0 && BIO_should_retry(p->bio));
return len;
}
int SecureSocket::read (char *data, int len)
{
if (p->state != Connected)
return 0;
int e = BIO_read(p->bio, data, len);
if (e > 0)
return e;
if (BIO_should_retry(p->bio))
return -1;
disconnect();
return 0;
}
const std::string &SecureSocket::errorMessage() const
{
return p->errorMessage;
}
void SecureSocket::flush()
{
BIO_flush(p->bio);
}
std::weak_ptr<EventLoop> SecureSocket::ev()
{
return p->Evented::ev();
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "datastore.h"
#include "transaction.h"
#include "internal/internal_transaction.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/operations/erase_operation.h"
#include "dummy_values.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
TEST_METHOD(pushOperationsToTransaction) {
Transaction sut;
std::unique_ptr<Internal::IOperation> postOp =
std::make_unique<Internal::PostOperation>(0, task1);
sut->push(std::move(postOp));
Assert::AreEqual(1U, sut->operationsQueue.size());
std::unique_ptr<Internal::IOperation> putOp =
std::make_unique<Internal::PutOperation>(0, task2);
sut->push(std::move(putOp));
Assert::AreEqual(2U, sut->operationsQueue.size());
std::unique_ptr<Internal::IOperation> eraseOp =
std::make_unique<Internal::EraseOperation>(0);
sut->push(std::move(eraseOp));
Assert::AreEqual(3U, sut->operationsQueue.size());
}
TEST_METHOD(transactionRollback) {
Transaction sut;
std::unique_ptr<Internal::IOperation> postOp =
std::make_unique<Internal::PostOperation>(0, task1);
sut->push(std::move(postOp));
std::unique_ptr<Internal::IOperation> putOp =
std::make_unique<Internal::PutOperation>(0, task2);
sut->push(std::move(putOp));
std::unique_ptr<Internal::IOperation> eraseOp =
std::make_unique<Internal::EraseOperation>(0);
sut->push(std::move(eraseOp));
Assert::AreEqual(3U, sut->operationsQueue.size());
sut.rollback();
Assert::AreEqual(0U, sut->operationsQueue.size());
}
TEST_METHOD(constructTransactionWithDataStoreBegin) {
Transaction sut(DataStore::get().begin());
DataStore::get().post(0, task1);
Assert::AreEqual(1U, sut->operationsQueue.size());
DataStore::get().put(0, task2);
Assert::AreEqual(2U, sut->operationsQueue.size());
DataStore::get().erase(0);
Assert::AreEqual(3U, sut->operationsQueue.size());
sut.commit();
}
TEST_METHOD(commitTransaction) {
Transaction sut(DataStore::get().begin());
DataStore::get().post(0, task1);
DataStore::get().post(1, task2);
DataStore::get().erase(0);
sut.commit();
int size = DataStore::get().getAllTasks().size();
Assert::AreEqual(1, size);
}
TEST_METHOD(nestedTransaction) {
Transaction sut(DataStore::get().begin());
DataStore::get().post(0, task1);
Transaction sut2(DataStore::get().begin());
DataStore::get().post(1, task2);
sut2.commit();
std::vector<SerializedTask> allTask = DataStore::get().getAllTasks();
Assert::AreEqual(0U, allTask.size());
Transaction sut3(DataStore::get().begin());
DataStore::get().erase(0);
sut3.commit();
allTask = DataStore::get().getAllTasks();
Assert::AreEqual(0U, allTask.size());
sut.commit();
allTask = DataStore::get().getAllTasks();
Assert::AreEqual(1U, allTask.size());
}
};
} // namespace UnitTests
} // namespace DataStore
} // namespace You
<commit_msg>Clean up after every test that uses Internal::DataStore<commit_after>#include "stdafx.h"
#include "datastore.h"
#include "transaction.h"
#include "internal/internal_datastore.h"
#include "internal/internal_transaction.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/operations/erase_operation.h"
#include "dummy_values.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
TEST_METHOD(pushOperationsToTransaction) {
Transaction sut;
std::unique_ptr<Internal::IOperation> postOp =
std::make_unique<Internal::PostOperation>(0, task1);
sut->push(std::move(postOp));
Assert::AreEqual(1U, sut->operationsQueue.size());
std::unique_ptr<Internal::IOperation> putOp =
std::make_unique<Internal::PutOperation>(0, task2);
sut->push(std::move(putOp));
Assert::AreEqual(2U, sut->operationsQueue.size());
std::unique_ptr<Internal::IOperation> eraseOp =
std::make_unique<Internal::EraseOperation>(0);
sut->push(std::move(eraseOp));
Assert::AreEqual(3U, sut->operationsQueue.size());
}
TEST_METHOD(transactionRollback) {
Transaction sut;
std::unique_ptr<Internal::IOperation> postOp =
std::make_unique<Internal::PostOperation>(0, task1);
sut->push(std::move(postOp));
std::unique_ptr<Internal::IOperation> putOp =
std::make_unique<Internal::PutOperation>(0, task2);
sut->push(std::move(putOp));
std::unique_ptr<Internal::IOperation> eraseOp =
std::make_unique<Internal::EraseOperation>(0);
sut->push(std::move(eraseOp));
Assert::AreEqual(3U, sut->operationsQueue.size());
sut.rollback();
Assert::AreEqual(0U, sut->operationsQueue.size());
}
TEST_METHOD(constructTransactionWithDataStoreBegin) {
Transaction sut(DataStore::get().begin());
DataStore::get().post(0, task1);
Assert::AreEqual(1U, sut->operationsQueue.size());
DataStore::get().put(0, task2);
Assert::AreEqual(2U, sut->operationsQueue.size());
DataStore::get().erase(0);
Assert::AreEqual(3U, sut->operationsQueue.size());
sut.commit();
Internal::DataStore::get().document.reset();
}
TEST_METHOD(commitTransaction) {
Transaction sut(DataStore::get().begin());
DataStore::get().post(0, task1);
DataStore::get().post(1, task2);
DataStore::get().erase(0);
sut.commit();
int size = DataStore::get().getAllTasks().size();
Assert::AreEqual(1, size);
Internal::DataStore::get().document.reset();
}
TEST_METHOD(nestedTransaction) {
Transaction sut(DataStore::get().begin());
DataStore::get().post(0, task1);
Transaction sut2(DataStore::get().begin());
DataStore::get().post(1, task2);
sut2.commit();
std::vector<SerializedTask> allTask = DataStore::get().getAllTasks();
Assert::AreEqual(0U, allTask.size());
Transaction sut3(DataStore::get().begin());
DataStore::get().erase(0);
sut3.commit();
allTask = DataStore::get().getAllTasks();
Assert::AreEqual(0U, allTask.size());
sut.commit();
allTask = DataStore::get().getAllTasks();
Assert::AreEqual(1U, allTask.size());
Internal::DataStore::get().document.reset();
}
};
} // namespace UnitTests
} // namespace DataStore
} // namespace You
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "datastore.h"
#include "transaction.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
//TEST_METHOD(TestMethod1) {
// // TODO: Your test code here
//}
};
} // namespace UnitTests
} // namespace DataStore
} // namespace You
<commit_msg>First test for Transaction's push method<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
TEST_METHOD(pushOperationToTransaction) {
Transaction sut;
Internal::PostOperation postOp(0, task1);
sut.push(std::shared_ptr<Internal::IOperation>(&postOp));
}
};
} // namespace UnitTests
} // namespace DataStore
} // namespace You
<|endoftext|> |
<commit_before>//
// main.cpp
// parsetool
//
// Created by Andrew Hunter on 24/09/2011.
//
// Copyright (c) 2011-2012 Andrew Hunter
//
// 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 "TameParse/TameParse.h"
#include "boost_console.h"
#include <iostream>
#include <memory>
using namespace std;
using namespace util;
using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace tameparse;
using namespace language;
using namespace compiler;
int main (int argc, const char * argv[])
{
// Create the console
boost_console console(argc, argv);
console_container cons(&console, false);
try {
// Give up if the console is set not to start
if (!console.can_start()) {
return 1;
}
// Startup message
console.message_stream() << L"TameParse " << version::major_version << "." << version::minor_version << "." << version::revision << endl;
console.verbose_stream() << endl;
// Parse the input file
parser_stage parserStage(cons, console.input_file());
parserStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The definition file should exist
if (!parserStage.definition_file().item()) {
console.report_error(error(error::sev_bug, console.input_file(), L"BUG_NO_FILE_DATA", L"File did not produce any data", position(-1, -1, -1)));
return error::sev_bug;
}
// Parse any imported files
import_stage importStage(cons, console.input_file(), parserStage.definition_file());
importStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Run any tests that were specified
if (!console.get_option(L"run-tests").empty()) {
test_stage tests(cons, console.input_file(), parserStage.definition_file(), &importStage);
tests.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// If --run-tests is specified and no explicit options for generating an output file is supplied then stop here
if (console.get_option(L"output-file").empty()
&& console.get_option(L"start-symbol").empty()
&& console.get_option(L"output-language").empty()
&& console.get_option(L"test").empty()
&& console.get_option(L"show-parser").empty()) {
return console.exit_code();
}
}
// Convert to grammars & NDFAs
language_builder_stage builderStage(cons, console.input_file(), &importStage);
builderStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Work out the name of the language to build and the start symbols
wstring buildLanguageName = console.get_option(L"compile-language");
wstring buildClassName = console.get_option(L"class-name");
vector<wstring> startSymbols = console.get_option_list(L"start-symbol");
wstring targetLanguage = console.get_option(L"output-language");
wstring buildNamespaceName = console.get_option(L"namespace-name");
position parseBlockPosition = position(-1, -1, -1);
// Use the options by default
if (console.get_option(L"compile-language").empty()) {
// TODO: get information from the parser block
// TODO: the class-name option overrides the name specified in the parser block (but gives a warning)
// TODO: use the position of the parser block to report
// TODO: deal with multiple parser blocks somehow (error? generate multiple classes?)
}
// If there is only one language in the original file and none specified, then we will generate that
if (buildLanguageName.empty()) {
int languageCount = 0;
// Find all of the language blocks
for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {
if ((*defnBlock)->language()) {
++languageCount;
if (languageCount > 1) {
// Multiple languages: can't infer one
buildLanguageName.clear();
break;
} else {
// This is the first language: use its identifier as the language to build
buildLanguageName = (*defnBlock)->language()->identifier();
}
}
}
// Tell the user about this
if (!buildLanguageName.empty()) {
wstringstream msg;
msg << L"Language name not explicitly specified: will use '" << buildLanguageName << L"'";
console.report_error(error(error::sev_info, console.input_file(), L"INFERRED_LANGUAGE", msg.str(), parseBlockPosition));
}
}
// Error if there is no language specified
if (buildLanguageName.empty()) {
console.report_error(error(error::sev_error, console.input_file(), L"NO_LANGUAGE_SPECIFIED", L"Could not determine which language block to compile", parseBlockPosition));
return error::sev_error;
}
// Infer the class name to use if none is specified (same as the language name)
if (buildClassName.empty()) {
buildClassName = buildLanguageName;
}
// Get the language that we're going to compile
const language_block* compileLanguage = importStage.language_with_name(buildLanguageName);
language_stage* compileLanguageStage = builderStage.language_with_name(buildLanguageName);
if (!compileLanguage || !compileLanguageStage) {
// The language could not be found
wstringstream msg;
msg << L"Could not find the target language '" << buildLanguageName << L"'";
console.report_error(error(error::sev_error, console.input_file(), L"MISSING_TARGET_LANGUAGE", msg.str(), parseBlockPosition));
return error::sev_error;
}
// Report any unused symbols in the language
compileLanguageStage->report_unused_symbols();
// Infer the start symbols if there are none
if (startSymbols.empty()) {
// TODO: Use the first nonterminal defined in the language block
// TODO: warn if we establish a start symbol this way
}
if (startSymbols.empty()) {
// Error if we can't find any start symbols at all
console.report_error(error(error::sev_error, console.input_file(), L"NO_START_SYMBOLS", L"Could not determine a start symbol for the language (use the start-symbol option to specify one manually)", parseBlockPosition));
return error::sev_error;
}
// Generate the lexer for the target language
lexer_stage lexerStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage);
lexerStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Generate the parser
lr_parser_stage lrParserStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage, &lexerStage, startSymbols);
lrParserStage.compile();
// Write the parser out if requested
if (!console.get_option(L"show-parser").empty() || !console.get_option(L"show-parser-closure").empty()) {
wcout << endl << L"== Parser tables:" << endl << formatter::to_string(*lrParserStage.get_parser(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals(), !console.get_option(L"show-parser-closure").empty()) << endl;
}
// Display the propagation tables if requested
if (!console.get_option(L"show-propagation").empty()) {
// Get the parser builder
lalr_builder* builder = lrParserStage.get_parser();
typedef lalr_builder::lr_item_id lr_item_id;
if (builder) {
// Write out a header
wcout << endl << L"== Symbol propagation:" << endl;
// Iterate through the states
for (int stateId = 0; stateId < builder->machine().count_states(); stateId++) {
const lalr_state& state = *builder->machine().state_with_id(stateId);
// Write out the state ID
wcout << L"State #" << stateId << endl;
// Go through the items
for (int itemId = 0; itemId < state.count_items(); itemId++) {
// Get the spontaneous lookahead generation for this item
const set<lr_item_id>& spontaneous = builder->spontaneous_for_item(stateId, itemId);
const set<lr_item_id>& propagate = builder->propagations_for_item(stateId, itemId);
// Ignore any items that have no items in them
if (spontaneous.empty() && propagate.empty()) continue;
wcout << L" "
<< formatter::to_string(*state[itemId], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< L" " << formatter::to_string(state.lookahead_for(itemId), *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
// Write out which items generate spontaneous lookaheads
for (set<lr_item_id>::const_iterator spont = spontaneous.begin(); spont != spontaneous.end(); spont++) {
const item_set& lookahead = builder->lookahead_for_spontaneous(stateId, itemId, spont->state_id, spont->item_id);
wcout << L" Spontaneous -> state #" << spont->state_id << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(spont->state_id))[spont->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< L" " << formatter::to_string(lookahead, *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
// Write out which items propagate lookaheads
for (set<lr_item_id>::const_iterator prop = propagate.begin(); prop != propagate.end(); prop++) {
wcout << L" Propagate -> state #" << prop->state_id << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(prop->state_id))[prop->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
}
}
}
}
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The --test option sets the target language to 'test'
if (!console.get_option(L"test").empty()) {
targetLanguage = L"test";
}
// Target language is C++ if no language is specified
if (targetLanguage.empty()) {
targetLanguage = L"cplusplus";
}
// Work out the prefix filename
wstring prefixFilename = console.get_option(L"output-language");
if (prefixFilename.empty()) {
// Derive from the input file
// This works provided the target language
prefixFilename = console.input_file();
}
// Create the output stage
auto_ptr<output_stage> outputStage(NULL);
if (targetLanguage == L"cplusplus") {
// Use the C++ language generator
outputStage = auto_ptr<output_stage>(new output_cplusplus(cons, importStage.file_with_language(buildLanguageName), &lexerStage, compileLanguageStage, &lrParserStage, prefixFilename, buildClassName, buildNamespaceName));
} else if (targetLanguage == L"test") {
// Special case: read from stdin, and try to parse the source language
ast_parser parser(*lrParserStage.get_tables());
// Create the parser
lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);
ast_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));
// Parse stdin
if (stdInParser->parse()) {
console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} else {
position failPos(-1, -1, -1);
if (stdInParser->look().item()) {
failPos = stdInParser->look()->pos();
}
console.report_error(error(error::sev_error, L"stdin", L"TEST_PARSER_ERROR", L"Syntax error", failPos));
}
} else if (targetLanguage == L"test-trace") {
// Special case: same as for test, but use the debug version of the parser
typedef parser<astnode_container, ast_parser_actions, debug_parser_trace<1> > trace_parser;
trace_parser parser(*lrParserStage.get_tables());
// Create the parser
lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);
trace_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));
// Parse stdin
if (stdInParser->parse()) {
console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} else {
position failPos(-1, -1, -1);
if (stdInParser->look().item()) {
failPos = stdInParser->look()->pos();
}
console.report_error(error(error::sev_error, L"stdin", L"TEST_PARSER_ERROR", L"Syntax error", failPos));
// Report the stack at the point of failure
trace_parser::stack stack = stdInParser->get_stack();
console.verbose_stream() << endl << L"Stack:" << endl;
do {
console.verbose_stream() << formatter::to_string(*stack->item, *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} while (stack.pop());
}
} else {
// Unknown target language
wstringstream msg;
msg << L"Output language '" << targetLanguage << L"' is not known";
console.report_error(error(error::sev_error, console.input_file(), L"UNKNOWN_OUTPUT_LANGUAGE_TYPE", msg.str(), position(-1, -1, -1)));
return error::sev_error;
}
// Compile the final output
if (outputStage.get()) {
outputStage->compile();
}
// Done
return console.exit_code();
} catch (...) {
console.report_error(error(error::sev_bug, L"", L"BUG_UNCAUGHT_EXCEPTION", L"Uncaught exception", position(-1, -1, -1)));
throw;
}
}
<commit_msg>The contents of a parser block will now be respected when building a language<commit_after>//
// main.cpp
// parsetool
//
// Created by Andrew Hunter on 24/09/2011.
//
// Copyright (c) 2011-2012 Andrew Hunter
//
// 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 "TameParse/TameParse.h"
#include "boost_console.h"
#include <iostream>
#include <memory>
using namespace std;
using namespace util;
using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace tameparse;
using namespace language;
using namespace compiler;
int main (int argc, const char * argv[])
{
// Create the console
boost_console console(argc, argv);
console_container cons(&console, false);
try {
// Give up if the console is set not to start
if (!console.can_start()) {
return 1;
}
// Startup message
console.message_stream() << L"TameParse " << version::major_version << "." << version::minor_version << "." << version::revision << endl;
console.verbose_stream() << endl;
// Parse the input file
parser_stage parserStage(cons, console.input_file());
parserStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The definition file should exist
if (!parserStage.definition_file().item()) {
console.report_error(error(error::sev_bug, console.input_file(), L"BUG_NO_FILE_DATA", L"File did not produce any data", position(-1, -1, -1)));
return error::sev_bug;
}
// Parse any imported files
import_stage importStage(cons, console.input_file(), parserStage.definition_file());
importStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Run any tests that were specified
if (!console.get_option(L"run-tests").empty()) {
test_stage tests(cons, console.input_file(), parserStage.definition_file(), &importStage);
tests.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// If --run-tests is specified and no explicit options for generating an output file is supplied then stop here
if (console.get_option(L"output-file").empty()
&& console.get_option(L"start-symbol").empty()
&& console.get_option(L"output-language").empty()
&& console.get_option(L"test").empty()
&& console.get_option(L"show-parser").empty()) {
return console.exit_code();
}
}
// Convert to grammars & NDFAs
language_builder_stage builderStage(cons, console.input_file(), &importStage);
builderStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Work out the name of the language to build and the start symbols
wstring buildLanguageName = console.get_option(L"compile-language");
wstring buildClassName = console.get_option(L"class-name");
vector<wstring> startSymbols = console.get_option_list(L"start-symbol");
wstring targetLanguage = console.get_option(L"output-language");
wstring buildNamespaceName = console.get_option(L"namespace-name");
position parseBlockPosition = position(-1, -1, -1);
const parser_block* parserBlock = NULL;
// Use the options by default
if (console.get_option(L"compile-language").empty()) {
// TODO: get information from the parser block
// TODO: the class-name option overrides the name specified in the parser block (but gives a warning)
// TODO: use the position of the parser block to report
// TODO: deal with multiple parser blocks somehow (error? generate multiple classes?)
}
// Try to fetch a parser block from the input file
for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {
if ((*defnBlock)->parser()) {
if (parserBlock) {
// We only allow one parser block per file
console.report_error(error(error::sev_info, console.input_file(), L"MULTIPLE_PARSER_BLOCKS", L"Multiple parser blocks specified", (*defnBlock)->start_pos()));
parserBlock = NULL;
break;
} else {
// This is the parser block
parserBlock = (*defnBlock)->parser();
}
}
}
// If there are no start symbols or build languages specified on the command line, then pick them from the parser block
if (buildLanguageName.empty() && startSymbols.empty() && parserBlock) {
// Get the language name and start symbols from the block
buildLanguageName = parserBlock->language_name();
startSymbols = parserBlock->start_symbols();
// The class name is also specified in the block if not overridden on the command line
if (buildClassName.empty()) {
buildClassName = parserBlock->parser_name();
}
}
// If there is only one language in the original file and none specified on the command line, then we will generate that
if (buildLanguageName.empty()) {
int languageCount = 0;
// Find all of the language blocks
for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {
if ((*defnBlock)->language()) {
++languageCount;
if (languageCount > 1) {
// Multiple languages: can't infer one
buildLanguageName.clear();
break;
} else {
// This is the first language: use its identifier as the language to build
buildLanguageName = (*defnBlock)->language()->identifier();
}
}
}
// Tell the user about this
if (!buildLanguageName.empty()) {
wstringstream msg;
msg << L"Language name not explicitly specified: will use '" << buildLanguageName << L"'";
console.report_error(error(error::sev_info, console.input_file(), L"INFERRED_LANGUAGE", msg.str(), parseBlockPosition));
}
}
// Error if there is no language specified
if (buildLanguageName.empty()) {
console.report_error(error(error::sev_error, console.input_file(), L"NO_LANGUAGE_SPECIFIED", L"Could not determine which language block to compile", parseBlockPosition));
return error::sev_error;
}
// Infer the class name to use if none is specified (same as the language name)
if (buildClassName.empty()) {
buildClassName = buildLanguageName;
}
// Get the language that we're going to compile
const language_block* compileLanguage = importStage.language_with_name(buildLanguageName);
language_stage* compileLanguageStage = builderStage.language_with_name(buildLanguageName);
if (!compileLanguage || !compileLanguageStage) {
// The language could not be found
wstringstream msg;
msg << L"Could not find the target language '" << buildLanguageName << L"'";
console.report_error(error(error::sev_error, console.input_file(), L"MISSING_TARGET_LANGUAGE", msg.str(), parseBlockPosition));
return error::sev_error;
}
// Report any unused symbols in the language
compileLanguageStage->report_unused_symbols();
// Infer the start symbols if there are none
if (startSymbols.empty()) {
// TODO: Use the first nonterminal defined in the language block
// TODO: warn if we establish a start symbol this way
}
if (startSymbols.empty()) {
// Error if we can't find any start symbols at all
console.report_error(error(error::sev_error, console.input_file(), L"NO_START_SYMBOLS", L"Could not determine a start symbol for the language (use the start-symbol option to specify one manually)", parseBlockPosition));
return error::sev_error;
}
// Generate the lexer for the target language
lexer_stage lexerStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage);
lexerStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Generate the parser
lr_parser_stage lrParserStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage, &lexerStage, startSymbols);
lrParserStage.compile();
// Write the parser out if requested
if (!console.get_option(L"show-parser").empty() || !console.get_option(L"show-parser-closure").empty()) {
wcout << endl << L"== Parser tables:" << endl << formatter::to_string(*lrParserStage.get_parser(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals(), !console.get_option(L"show-parser-closure").empty()) << endl;
}
// Display the propagation tables if requested
if (!console.get_option(L"show-propagation").empty()) {
// Get the parser builder
lalr_builder* builder = lrParserStage.get_parser();
typedef lalr_builder::lr_item_id lr_item_id;
if (builder) {
// Write out a header
wcout << endl << L"== Symbol propagation:" << endl;
// Iterate through the states
for (int stateId = 0; stateId < builder->machine().count_states(); stateId++) {
const lalr_state& state = *builder->machine().state_with_id(stateId);
// Write out the state ID
wcout << L"State #" << stateId << endl;
// Go through the items
for (int itemId = 0; itemId < state.count_items(); itemId++) {
// Get the spontaneous lookahead generation for this item
const set<lr_item_id>& spontaneous = builder->spontaneous_for_item(stateId, itemId);
const set<lr_item_id>& propagate = builder->propagations_for_item(stateId, itemId);
// Ignore any items that have no items in them
if (spontaneous.empty() && propagate.empty()) continue;
wcout << L" "
<< formatter::to_string(*state[itemId], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< L" " << formatter::to_string(state.lookahead_for(itemId), *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
// Write out which items generate spontaneous lookaheads
for (set<lr_item_id>::const_iterator spont = spontaneous.begin(); spont != spontaneous.end(); spont++) {
const item_set& lookahead = builder->lookahead_for_spontaneous(stateId, itemId, spont->state_id, spont->item_id);
wcout << L" Spontaneous -> state #" << spont->state_id << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(spont->state_id))[spont->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< L" " << formatter::to_string(lookahead, *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
// Write out which items propagate lookaheads
for (set<lr_item_id>::const_iterator prop = propagate.begin(); prop != propagate.end(); prop++) {
wcout << L" Propagate -> state #" << prop->state_id << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(prop->state_id))[prop->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
}
}
}
}
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The --test option sets the target language to 'test'
if (!console.get_option(L"test").empty()) {
targetLanguage = L"test";
}
// Target language is C++ if no language is specified
if (targetLanguage.empty()) {
targetLanguage = L"cplusplus";
}
// Work out the prefix filename
wstring prefixFilename = console.get_option(L"output-language");
if (prefixFilename.empty()) {
// Derive from the input file
// This works provided the target language
prefixFilename = console.input_file();
}
// Create the output stage
auto_ptr<output_stage> outputStage(NULL);
if (targetLanguage == L"cplusplus") {
// Use the C++ language generator
outputStage = auto_ptr<output_stage>(new output_cplusplus(cons, importStage.file_with_language(buildLanguageName), &lexerStage, compileLanguageStage, &lrParserStage, prefixFilename, buildClassName, buildNamespaceName));
} else if (targetLanguage == L"test") {
// Special case: read from stdin, and try to parse the source language
ast_parser parser(*lrParserStage.get_tables());
// Create the parser
lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);
ast_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));
// Parse stdin
if (stdInParser->parse()) {
console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} else {
position failPos(-1, -1, -1);
if (stdInParser->look().item()) {
failPos = stdInParser->look()->pos();
}
console.report_error(error(error::sev_error, L"stdin", L"TEST_PARSER_ERROR", L"Syntax error", failPos));
}
} else if (targetLanguage == L"test-trace") {
// Special case: same as for test, but use the debug version of the parser
typedef parser<astnode_container, ast_parser_actions, debug_parser_trace<1> > trace_parser;
trace_parser parser(*lrParserStage.get_tables());
// Create the parser
lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);
trace_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));
// Parse stdin
if (stdInParser->parse()) {
console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} else {
position failPos(-1, -1, -1);
if (stdInParser->look().item()) {
failPos = stdInParser->look()->pos();
}
console.report_error(error(error::sev_error, L"stdin", L"TEST_PARSER_ERROR", L"Syntax error", failPos));
// Report the stack at the point of failure
trace_parser::stack stack = stdInParser->get_stack();
console.verbose_stream() << endl << L"Stack:" << endl;
do {
console.verbose_stream() << formatter::to_string(*stack->item, *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} while (stack.pop());
}
} else {
// Unknown target language
wstringstream msg;
msg << L"Output language '" << targetLanguage << L"' is not known";
console.report_error(error(error::sev_error, console.input_file(), L"UNKNOWN_OUTPUT_LANGUAGE_TYPE", msg.str(), position(-1, -1, -1)));
return error::sev_error;
}
// Compile the final output
if (outputStage.get()) {
outputStage->compile();
}
// Done
return console.exit_code();
} catch (...) {
console.report_error(error(error::sev_bug, L"", L"BUG_UNCAUGHT_EXCEPTION", L"Uncaught exception", position(-1, -1, -1)));
throw;
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/secureboot/trusted/trustedbootUtils.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2021 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file trustedbootUtils.C
*
* @brief Trusted boot utility functions
*/
// ----------------------------------------------
// Includes
// ----------------------------------------------
#include <string.h>
#include <sys/time.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>
#include <errl/errludstring.H>
#include <targeting/common/targetservice.H>
#include <devicefw/driverif.H>
#include <spi/tpmddif.H>
#include <secureboot/trustedbootif.H>
#include <spi/tpmddreasoncodes.H>
#include <secureboot/trustedboot_reasoncodes.H>
#include "trustedbootUtils.H"
#include "trustedbootCmds.H"
#include "trustedboot.H"
#include "trustedTypes.H"
#include <secureboot/service.H>
#include <spidd.H>
#include <p10_scom_proc_d.H>
#include <errl/errludlogregister.H>
#include <errl/errludattribute.H>
#include <errl/errludstring.H>
#include <kernel/bltohbdatamgr.H>
#include <bootloader/bootloaderif.H>
#include <bootloader/hbblreasoncodes.H>
#include <stdio.h>
#include <initservice/mboxRegs.H>
namespace TRUSTEDBOOT
{
errlHndl_t tpmTransmit(TpmTarget * io_target,
uint8_t* io_buffer,
size_t i_cmdSize,
size_t i_bufsize,
tpm_locality_t i_locality)
{
errlHndl_t err = NULL;
do
{
TRACDCOMP( g_trac_trustedboot,
">>TPM OP TRANSMIT : BufLen %d : %016llx, cmdSize = %d",
static_cast<int>(i_bufsize),
*(reinterpret_cast<uint64_t*>(io_buffer)),
static_cast<int>(i_cmdSize) );
// Send to the TPM
err = deviceRead(io_target,
io_buffer,
i_bufsize,
DEVICE_TPM_ADDRESS(TPMDD::TPM_OP_TRANSMIT,
i_cmdSize,
i_locality));
TRACDCOMP( g_trac_trustedboot,
"<<TPM OP TRANSMIT : BufLen %d : %016llx, cmdSize = %d DONE, rc=0x%X",
static_cast<int>(i_bufsize),
*(reinterpret_cast<uint64_t*>(io_buffer)),
static_cast<int>(i_cmdSize),
ERRL_GETRC_SAFE(err) );
if (NULL != err)
{
break;
}
} while ( 0 );
return err;
}
errlHndl_t tpmCreateErrorLog(
const uint8_t i_modId,
const uint16_t i_reasonCode,
const uint64_t i_user1,
const uint64_t i_user2,
const bool i_addSwCallout)
{
errlHndl_t pError =
new ERRORLOG::ErrlEntry(
ERRORLOG::ERRL_SEV_UNRECOVERABLE,
i_modId,
i_reasonCode,
i_user1,
i_user2,
i_addSwCallout);
pError->collectTrace(SECURE_COMP_NAME);
pError->collectTrace(TRBOOT_COMP_NAME);
return pError;
}
void addTpmFFDC(TpmTarget* i_pTpm,
errlHndl_t& io_errl)
{
do {
if(nullptr == io_errl)
{
TRACFCOMP(g_trac_trustedboot, "addTpmFFDC: nullptr was passed for io_errl. Will not add TPM FFDC.");
break;
}
// Add security regs
SECUREBOOT::addSecurityRegistersToErrlog(io_errl);
TARGETING::Target* l_proc = getImmediateParentByAffinity(i_pTpm);
// Add SPI status regs
SPI::addSpiStatusRegsToErrl(l_proc, SPI_ENGINE_TPM, io_errl);
// Mbox Scratch 11 contains the SBE TPM RC
ERRORLOG::ErrlUserDetailsLogRegister l_scratchReg(l_proc);
l_scratchReg.addData(DEVICE_SCOM_ADDRESS(INITSERVICE::SPLESS::MboxScratch11_t::REG_ADDR));
l_scratchReg.addToLog(io_errl);
// Add freq control reg that will help determine the PAU freq used
ERRORLOG::ErrlUserDetailsLogRegister l_pauFreqReg(l_proc);
l_pauFreqReg.addData(DEVICE_SCOM_ADDRESS(scomt::proc::TP_TPCHIP_TPC_DPLL_CNTL_PAU_REGS_FREQ));
l_pauFreqReg.addToLog(io_errl);
// Include ATTR_BOOT_PAU_DPLL_BYPASS
ERRORLOG::ErrlUserDetailsAttribute(l_proc, TARGETING::ATTR_BOOT_PAU_DPLL_BYPASS).addToLog(io_errl);
ERRORLOG::ErrlUserDetailsStringSet l_tdpSourceString;
TARGETING::Target* l_primaryProc = nullptr;
errlHndl_t l_errl = TARGETING::targetService().queryMasterProcChipTargetHandle(l_primaryProc);
if(l_errl)
{
TRACFCOMP(g_trac_trustedboot, ERR_MRK"addTpmFFDC: Could not get primary proc. Stopping FFDC collection.");
errlCommit(l_errl, SECURE_COMP_ID);
break;
}
// Get HBBL/SBE - related FFDC if it's the primary proc
if(l_proc == l_primaryProc)
{
// If the TDP bit is set in HBBL->HB comm area, then the issue happened
// in HBBL; else - in SBE.
if(g_BlToHbDataManager.getTdpSource() == Bootloader::TDP_BIT_SET_HBBL)
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by HBBL");
}
else if(g_BlToHbDataManager.getTdpSource() == Bootloader::TDP_BIT_SET_SBE)
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by SBE");
}
else if(l_proc->getAttr<TARGETING::ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM>())
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by Hostboot");
}
else
{
l_tdpSourceString.add("TDP Bit Source", "Unset/Unknown");
}
l_tdpSourceString.addToLog(io_errl);
// Add some RC-specific FFDC from the bootloader
if(g_BlToHbDataManager.getVersion() >= Bootloader::BLTOHB_TPM_FFDC)
{
ERRORLOG::ErrlUserDetailsStringSet l_hbblTpmRcString;
char l_hbblRcString[10]; // Actual RC is smaller than 10 chars
snprintf(l_hbblRcString, 10, "0x%x", g_BlToHbDataManager.getTpmRc());
l_hbblTpmRcString.add("HBBL TPM RC", l_hbblRcString);
l_hbblTpmRcString.addToLog(io_errl);
// If there was an XSCOM error, deconfig the proc
if(g_BlToHbDataManager.getTpmRc() == Bootloader::RC_XSCOM_OP_FAILED ||
g_BlToHbDataManager.getTpmRc() == Bootloader::RC_XSCOM_OP_TIMEOUT)
{
io_errl->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::DECONFIG,
HWAS::GARD_NULL);
}
}
}
// Bootloader didn't run for the backup proc, so we can only tell if the TDP
// bit was set by SBE
else
{
l_errl = checkTdpBit(i_pTpm);
if(l_errl)
{
// TDP bit is set by the SBE. Discard the error
delete l_errl;
l_errl = nullptr;
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by SBE");
}
else if(l_proc->getAttr<TARGETING::ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM>())
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by Hostboot");
}
else
{
l_tdpSourceString.add("TDP Bit Source", "Unset/Unknown");
}
l_tdpSourceString.addToLog(io_errl);
}
} while(0);
}
} // end TRUSTEDBOOT
<commit_msg>Save mailbox scratch register 14<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/secureboot/trusted/trustedbootUtils.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2021 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file trustedbootUtils.C
*
* @brief Trusted boot utility functions
*/
// ----------------------------------------------
// Includes
// ----------------------------------------------
#include <string.h>
#include <sys/time.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>
#include <errl/errludstring.H>
#include <targeting/common/targetservice.H>
#include <devicefw/driverif.H>
#include <spi/tpmddif.H>
#include <secureboot/trustedbootif.H>
#include <spi/tpmddreasoncodes.H>
#include <secureboot/trustedboot_reasoncodes.H>
#include "trustedbootUtils.H"
#include "trustedbootCmds.H"
#include "trustedboot.H"
#include "trustedTypes.H"
#include <secureboot/service.H>
#include <spidd.H>
#include <p10_scom_proc_d.H>
#include <errl/errludlogregister.H>
#include <errl/errludattribute.H>
#include <errl/errludstring.H>
#include <kernel/bltohbdatamgr.H>
#include <bootloader/bootloaderif.H>
#include <bootloader/hbblreasoncodes.H>
#include <stdio.h>
#include <initservice/mboxRegs.H>
namespace TRUSTEDBOOT
{
errlHndl_t tpmTransmit(TpmTarget * io_target,
uint8_t* io_buffer,
size_t i_cmdSize,
size_t i_bufsize,
tpm_locality_t i_locality)
{
errlHndl_t err = NULL;
do
{
TRACDCOMP( g_trac_trustedboot,
">>TPM OP TRANSMIT : BufLen %d : %016llx, cmdSize = %d",
static_cast<int>(i_bufsize),
*(reinterpret_cast<uint64_t*>(io_buffer)),
static_cast<int>(i_cmdSize) );
// Send to the TPM
err = deviceRead(io_target,
io_buffer,
i_bufsize,
DEVICE_TPM_ADDRESS(TPMDD::TPM_OP_TRANSMIT,
i_cmdSize,
i_locality));
TRACDCOMP( g_trac_trustedboot,
"<<TPM OP TRANSMIT : BufLen %d : %016llx, cmdSize = %d DONE, rc=0x%X",
static_cast<int>(i_bufsize),
*(reinterpret_cast<uint64_t*>(io_buffer)),
static_cast<int>(i_cmdSize),
ERRL_GETRC_SAFE(err) );
if (NULL != err)
{
break;
}
} while ( 0 );
return err;
}
errlHndl_t tpmCreateErrorLog(
const uint8_t i_modId,
const uint16_t i_reasonCode,
const uint64_t i_user1,
const uint64_t i_user2,
const bool i_addSwCallout)
{
errlHndl_t pError =
new ERRORLOG::ErrlEntry(
ERRORLOG::ERRL_SEV_UNRECOVERABLE,
i_modId,
i_reasonCode,
i_user1,
i_user2,
i_addSwCallout);
pError->collectTrace(SECURE_COMP_NAME);
pError->collectTrace(TRBOOT_COMP_NAME);
return pError;
}
void addTpmFFDC(TpmTarget* i_pTpm,
errlHndl_t& io_errl)
{
do {
if(nullptr == io_errl)
{
TRACFCOMP(g_trac_trustedboot, "addTpmFFDC: nullptr was passed for io_errl. Will not add TPM FFDC.");
break;
}
// Add security regs
SECUREBOOT::addSecurityRegistersToErrlog(io_errl);
TARGETING::Target* l_proc = getImmediateParentByAffinity(i_pTpm);
// Add SPI status regs
SPI::addSpiStatusRegsToErrl(l_proc, SPI_ENGINE_TPM, io_errl);
// Mbox Scratch 11 contains the SBE TPM RC
ERRORLOG::ErrlUserDetailsLogRegister l_scratchReg(l_proc);
l_scratchReg.addData(DEVICE_SCOM_ADDRESS(INITSERVICE::SPLESS::MboxScratch11_t::REG_ADDR));
// Mbox Scratch 14 provides additional FFDC when possible
l_scratchReg.addData(DEVICE_SCOM_ADDRESS(INITSERVICE::SPLESS::MboxScratch14_t::REG_ADDR));
l_scratchReg.addToLog(io_errl);
// Add freq control reg that will help determine the PAU freq used
ERRORLOG::ErrlUserDetailsLogRegister l_pauFreqReg(l_proc);
l_pauFreqReg.addData(DEVICE_SCOM_ADDRESS(scomt::proc::TP_TPCHIP_TPC_DPLL_CNTL_PAU_REGS_FREQ));
l_pauFreqReg.addToLog(io_errl);
// Include ATTR_BOOT_PAU_DPLL_BYPASS
ERRORLOG::ErrlUserDetailsAttribute(l_proc, TARGETING::ATTR_BOOT_PAU_DPLL_BYPASS).addToLog(io_errl);
ERRORLOG::ErrlUserDetailsStringSet l_tdpSourceString;
TARGETING::Target* l_primaryProc = nullptr;
errlHndl_t l_errl = TARGETING::targetService().queryMasterProcChipTargetHandle(l_primaryProc);
if(l_errl)
{
TRACFCOMP(g_trac_trustedboot, ERR_MRK"addTpmFFDC: Could not get primary proc. Stopping FFDC collection.");
errlCommit(l_errl, SECURE_COMP_ID);
break;
}
// Get HBBL/SBE - related FFDC if it's the primary proc
if(l_proc == l_primaryProc)
{
// If the TDP bit is set in HBBL->HB comm area, then the issue happened
// in HBBL; else - in SBE.
if(g_BlToHbDataManager.getTdpSource() == Bootloader::TDP_BIT_SET_HBBL)
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by HBBL");
}
else if(g_BlToHbDataManager.getTdpSource() == Bootloader::TDP_BIT_SET_SBE)
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by SBE");
}
else if(l_proc->getAttr<TARGETING::ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM>())
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by Hostboot");
}
else
{
l_tdpSourceString.add("TDP Bit Source", "Unset/Unknown");
}
l_tdpSourceString.addToLog(io_errl);
// Add some RC-specific FFDC from the bootloader
if(g_BlToHbDataManager.getVersion() >= Bootloader::BLTOHB_TPM_FFDC)
{
ERRORLOG::ErrlUserDetailsStringSet l_hbblTpmRcString;
char l_hbblRcString[10]; // Actual RC is smaller than 10 chars
snprintf(l_hbblRcString, 10, "0x%x", g_BlToHbDataManager.getTpmRc());
l_hbblTpmRcString.add("HBBL TPM RC", l_hbblRcString);
l_hbblTpmRcString.addToLog(io_errl);
// If there was an XSCOM error, deconfig the proc
if(g_BlToHbDataManager.getTpmRc() == Bootloader::RC_XSCOM_OP_FAILED ||
g_BlToHbDataManager.getTpmRc() == Bootloader::RC_XSCOM_OP_TIMEOUT)
{
io_errl->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::DECONFIG,
HWAS::GARD_NULL);
}
}
}
// Bootloader didn't run for the backup proc, so we can only tell if the TDP
// bit was set by SBE
else
{
l_errl = checkTdpBit(i_pTpm);
if(l_errl)
{
// TDP bit is set by the SBE. Discard the error
delete l_errl;
l_errl = nullptr;
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by SBE");
}
else if(l_proc->getAttr<TARGETING::ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM>())
{
l_tdpSourceString.add("TDP Bit Source", "TDP bit was set by Hostboot");
}
else
{
l_tdpSourceString.add("TDP Bit Source", "Unset/Unknown");
}
l_tdpSourceString.addToLog(io_errl);
}
} while(0);
}
} // end TRUSTEDBOOT
<|endoftext|> |
<commit_before>#include "World.h"
World::World() :
m_textures(TextureLoader("Build/Ressources/sprites/")),
m_building(Building(&m_textures, 1, 1))
{
m_building.loadToTileSet("Build/Levels/0.lvl");
}
World::~World()
{}
void World::draw(sf::RenderWindow *window) const
{
m_building.draw(window);
}
<commit_msg>warningfix: -Wreorder<commit_after>#include "World.h"
World::World() :
m_building(Building(&m_textures, 1, 1)),
m_textures(TextureLoader("Build/Ressources/sprites/"))
{
m_building.loadToTileSet("Build/Levels/0.lvl");
}
World::~World()
{}
void World::draw(sf::RenderWindow *window) const
{
m_building.draw(window);
}
<|endoftext|> |
<commit_before>#include "workerCL.hpp"
#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "log.hpp"
#include "reads.hpp"
using namespace std;
WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
/* GPU environment preparation */
//Get platforms (drivers) list and keep the one to be use
vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()){
//No platform ? Send error
string error = "OPENCL: no platforms found.";
throw(error);
}
m_platform = all_platforms[platform_id];
//Get devices list and keep the one to use
vector<cl::Device> devices;
m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(device_id >= devices.size()){
string error = "OPENCL: no device of id "+to_string(device_id)+
" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
throw(error);
}
m_device = devices[device_id];
//Create context
m_context = cl::Context({m_device});
//initialize commands queue
m_commandqueue = cl::CommandQueue(m_context, m_device);
//Build kernel sources
m_program = cl::Program(m_context, kernel_cmp_2_contigs);
if(m_program.build({m_device}) != CL_SUCCESS){
string error = "Error building: ";
error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
throw(error);
}
//Make the kernel
m_kernel = cl::Kernel(m_program, "cmp_2_contigs");
}
WorkerCL::~WorkerCL(){
}
void WorkerCL::run(Contigs contigs){
/*
Create the string containing all contigs sequences
and store the list of contigs size (in same orders)
to be able to retrieve contigs. Ssize is store in
an ulong to be sure it is 64bits as cl_ulong
*/
//Get list of contigs size and the total length of the
//contigs concatenation
unsigned long nbContigs = contigs.get_nbContigs();
unsigned long ultraSequenceSize = 0;
vector<unsigned long> contigs_size (nbContigs, 0);
for(unsigned long i=0; i < nbContigs; i++){
contigs_size[i] = contigs.get_sizeContig(i);
ultraSequenceSize += contigs_size[i];
}
//Create the ultraSequence
char* ultraSequence = new char[ultraSequenceSize];
unsigned long i = 0;
//Get each contigs sequence and add it in ultraSequence
for(unsigned long c=0; c < nbContigs; c++){
string seq = contigs.get_seqContig(c);
for(size_t j=0; j < seq.size();j++){
ultraSequence[i] = seq[j];
i++;
}
}
cout << "UltraSequence:" << endl;
cout << ultraSequence << endl;
//Prepare GPU buffers for the run
//infos (64bits): nbcontigs
cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, 64);
m_kernel.setArg(0, buf_infos);
//Clean the memory
delete ultraSequence;
}
void WorkerCL::list_infos(Log& output){
string txt;
//Get platforms
txt = "\n\t[Platforms list]";
output.write(txt);
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(!platforms.size()){
txt = "No platform detected";
output.write(txt);
return;
}
txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
output.write(txt);
for(size_t i=0; i < platforms.size(); i++){
cl::Platform& p = platforms[i];
txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
output.write(txt);
}
//Get devices
txt = "\n\t[Devices list]";
output.write(txt);
txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
output.write(txt);
for(size_t p = 0; p < platforms.size(); p++){
vector<cl::Device> devices;
platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
for(size_t d = 0; d < devices.size(); d++){
cl::Device& device = devices[d];
txt = to_string(p)+"\t"+to_string(d);
txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
output.write(txt);
}
}
}
/*
Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/
string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
kernel void cmp_2_contigs(){
int i = 0;
}
)CLCODE";
<commit_msg>Ajout du cl::Event, remplacement des unsigned long en uint64_t<commit_after>#include "workerCL.hpp"
#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "log.hpp"
#include "reads.hpp"
using namespace std;
WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
/* GPU environment preparation */
//Get platforms (drivers) list and keep the one to be use
vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()){
//No platform ? Send error
string error = "OPENCL: no platforms found.";
throw(error);
}
m_platform = all_platforms[platform_id];
//Get devices list and keep the one to use
vector<cl::Device> devices;
m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(device_id >= devices.size()){
string error = "OPENCL: no device of id "+to_string(device_id)+
" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
throw(error);
}
m_device = devices[device_id];
//Create context
m_context = cl::Context({m_device});
//initialize commands queue
m_commandqueue = cl::CommandQueue(m_context, m_device);
//Build kernel sources
m_program = cl::Program(m_context, kernel_cmp_2_contigs);
if(m_program.build({m_device}) != CL_SUCCESS){
string error = "Error building: ";
error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
throw(error);
}
//Make the kernel
m_kernel = cl::Kernel(m_program, "cmp_2_contigs");
}
WorkerCL::~WorkerCL(){
}
void WorkerCL::run(Contigs contigs){
/*
Create the string containing all contigs sequences
and store the list of contigs size (in same orders)
to be able to retrieve contigs. Size is store in
an uint64_t (ulong) to be sure it is 64bits as cl_ulong
*/
//Get list of contigs size and the total length of the
//contigs concatenation
uint64_t nbContigs = contigs.get_nbContigs();
uint64_t ultraSequenceSize = 0;
vector<uint64_t> contigs_size (nbContigs, 0);
for(uint64_t i=0; i < nbContigs; i++){
contigs_size[i] = contigs.get_sizeContig(i);
ultraSequenceSize += contigs_size[i];
}
//Create the ultraSequence
char* ultraSequence = new char[ultraSequenceSize];
uint64_t i = 0;
//Get each contigs sequence and add it in ultraSequence
for(uint64_t c=0; c < nbContigs; c++){
string seq = contigs.get_seqContig(c);
for(size_t j=0; j < seq.size();j++){
ultraSequence[i] = seq[j];
i++;
}
}
cout << "UltraSequence:" << endl;
cout << ultraSequence << endl;
//Prepare GPU for the run
cl::Event ev;
//infos buffer (64bits): nbcontigs
cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, 64);
m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, 64, ultraSequenceSize);
//Update the kernel (gpu function)
m_kernel.setArg(0, buf_infos);
//Run the kernel and wait the end
m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NullRange, cl::NullRange, NULL, &ev);
ev.wait();
//Clean the memory
delete ultraSequence;
}
void WorkerCL::list_infos(Log& output){
string txt;
//Get platforms
txt = "\n\t[Platforms list]";
output.write(txt);
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(!platforms.size()){
txt = "No platform detected";
output.write(txt);
return;
}
txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
output.write(txt);
for(size_t i=0; i < platforms.size(); i++){
cl::Platform& p = platforms[i];
txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
output.write(txt);
}
//Get devices
txt = "\n\t[Devices list]";
output.write(txt);
txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
output.write(txt);
for(size_t p = 0; p < platforms.size(); p++){
vector<cl::Device> devices;
platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
for(size_t d = 0; d < devices.size(); d++){
cl::Device& device = devices[d];
txt = to_string(p)+"\t"+to_string(d);
txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
output.write(txt);
}
}
}
/*
Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/
string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
kernel void cmp_2_contigs(){
int i = 0;
}
)CLCODE";
<|endoftext|> |
<commit_before>#ifndef GNR_URI_HPP
# define GNR_URI_HPP
# pragma once
#include <regex>
#include <string>
#include <utility>
namespace gnr
{
class uri
{
std::string uri_;
std::pair<std::string::size_type, std::string::size_type> scheme_;
std::pair<std::string::size_type, std::string::size_type> authority_;
std::pair<std::string::size_type, std::string::size_type> path_;
std::pair<std::string::size_type, std::string::size_type> query_;
std::pair<std::string::size_type, std::string::size_type> fragment_;
public:
template <typename A>
explicit uri(A&& a)
{
assign(std::forward<A>(a));
}
template <typename A>
auto& operator=(A&& a)
{
assign(std::forward<A>(a));
return *this;
}
bool is_valid() const noexcept;
operator std::string const& () const noexcept;
std::string const& to_string() const noexcept;
auto scheme() const;
auto authority() const;
auto path() const;
auto query() const;
auto fragment() const;
void assign(std::string);
};
//////////////////////////////////////////////////////////////////////////////
inline bool uri::is_valid() const noexcept
{
return uri_.size();
}
//////////////////////////////////////////////////////////////////////////////
inline uri::operator std::string const& () const noexcept
{
return uri_;
}
//////////////////////////////////////////////////////////////////////////////
inline std::string const& uri::to_string() const noexcept
{
return *this;
}
//////////////////////////////////////////////////////////////////////////////
inline auto uri::scheme() const
{
return is_valid() ?
std::string(uri_, scheme_.first, scheme_.second) :
std::string();
}
//////////////////////////////////////////////////////////////////////////////
inline auto uri::authority() const
{
return is_valid() ?
std::string(uri_, authority_.first, authority_.second) :
std::string();
}
//////////////////////////////////////////////////////////////////////////////
inline auto uri::path() const
{
return is_valid() ?
std::string(uri_, path_.first, path_.second) :
std::string();
}
//////////////////////////////////////////////////////////////////////////////
inline auto uri::query() const
{
return is_valid() ?
std::string(uri_, query_.first, query_.second) :
std::string();
}
//////////////////////////////////////////////////////////////////////////////
inline auto uri::fragment() const
{
return is_valid() ?
std::string(uri_, fragment_.first, fragment_.second) :
std::string();
}
//////////////////////////////////////////////////////////////////////////////
inline void uri::assign(std::string u)
{
//rfc3986
static std::regex const ex{
R"(^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)"
};
// extract uri info
std::cmatch what;
auto const c_str(u.c_str());
if (std::regex_match(c_str, what, ex))
{
scheme_ = {what[2].first - c_str, what[2].second - what[2].first};
authority_ = {what[4].first - c_str, what[4].second - what[4].first};
path_ = {what[5].first - c_str, what[5].second - what[5].first};
query_ = {what[7].first - c_str, what[7].second - what[7].first};
fragment_ = {what[9].first - c_str, what[9].second - what[9].first};
uri_ = std::move(u);
}
else
{
uri_.clear();
uri_.shrink_to_fit();
}
}
}
#endif // GNR_URI_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_URI_HPP
# define GNR_URI_HPP
# pragma once
#include <regex>
#include <string_view>
#include <utility>
namespace gnr
{
class uri
{
std::string uri_;
std::string_view scheme_;
std::string_view authority_;
std::string_view path_;
std::string_view query_;
std::string_view fragment_;
public:
template <typename A>
explicit uri(A&& a)
{
assign(std::forward<A>(a));
}
template <typename A>
auto& operator=(A&& a)
{
assign(std::forward<A>(a));
return *this;
}
bool is_valid() const noexcept;
operator std::string const& () const noexcept;
std::string const& to_string() const noexcept;
auto& scheme() const;
auto& authority() const;
auto& path() const;
auto& query() const;
auto& fragment() const;
void assign(std::string);
};
//////////////////////////////////////////////////////////////////////////////
inline bool uri::is_valid() const noexcept
{
return uri_.size();
}
//////////////////////////////////////////////////////////////////////////////
inline uri::operator std::string const& () const noexcept
{
return uri_;
}
//////////////////////////////////////////////////////////////////////////////
inline std::string const& uri::to_string() const noexcept
{
return *this;
}
//////////////////////////////////////////////////////////////////////////////
inline auto& uri::scheme() const
{
return scheme_;
}
//////////////////////////////////////////////////////////////////////////////
inline auto& uri::authority() const
{
return authority_;
}
//////////////////////////////////////////////////////////////////////////////
inline auto& uri::path() const
{
return path_;
}
//////////////////////////////////////////////////////////////////////////////
inline auto& uri::query() const
{
return query_;
}
//////////////////////////////////////////////////////////////////////////////
inline auto& uri::fragment() const
{
return fragment_;
}
//////////////////////////////////////////////////////////////////////////////
inline void uri::assign(std::string u)
{
//rfc3986
static std::regex const ex{
R"(^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)"
};
// extract uri info
std::cmatch what;
auto const c_str(u.c_str());
if (std::regex_match(c_str, what, ex))
{
scheme_ = std::string_view(what[2].first,
what[2].second - what[2].first
);
authority_ = std::string_view(what[4].first,
what[4].second - what[4].first
);
path_ = std::string_view(what[5].first,
what[5].second - what[5].first
);
query_ = std::string_view(what[7].first,
what[7].second - what[7].first
);
fragment_ = std::string_view(what[9].first,
what[9].second - what[9].first
);
uri_ = std::move(u);
}
else
{
uri_.clear();
scheme_ = {};
authority_ = {};
path_ = {};
query_ = {};
fragment_ = {};
uri_.shrink_to_fit();
}
}
}
#endif // GNR_URI_HPP
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "CTRByPositionServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/logging.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
#include "analytics/CTRByPositionQuery.h"
using namespace fnord;
namespace cm {
CTRByPositionServlet::CTRByPositionServlet(VFS* vfs) : vfs_(vfs) {}
void CTRByPositionServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
const auto& params = uri.queryParams();
auto end_time = WallClock::unixMicros();
auto start_time = end_time - 30 * kMicrosPerDay;
Set<String> test_groups;
Set<String> device_types;
/* arguments */
String customer;
if (!URI::getParam(params, "customer", &customer)) {
res->addBody("error: missing ?customer=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
for (const auto& p : params) {
if (p.first == "from") {
start_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "until") {
end_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "test_group") {
test_groups.emplace(p.second);
continue;
}
if (p.first == "device_type") {
device_types.emplace(p.second);
continue;
}
}
if (test_groups.size() == 0) {
test_groups.emplace("all");
}
if (device_types.size() == 0) {
device_types = Set<String> { "unknown", "desktop", "tablet", "phone" };
}
/* execute query*/
auto t0 = WallClock::unixMicros();
cm::CTRByPositionQueryResult result;
for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerHour * 4) {
auto table_file = StringUtil::format(
"/srv/cmdata/artifacts/$0_joined_sessions.$1.cstable",
customer,
i / (kMicrosPerHour * 4));
if (!FileUtil::exists(table_file)) {
fnord::logWarning(
"cm.ctrbypositionservlet",
"missing table: $0",
table_file);
continue;
}
cstable::CSTableReader reader(table_file);
cm::AnalyticsQuery aq;
cm::CTRByPositionQuery q(&aq, &result);
aq.scanTable(&reader);
}
uint64_t total_views = 0;
uint64_t total_clicks = 0;
for (const auto& c : result.counters) {
total_views += c.second.num_views;
total_clicks += c.second.num_clicks;
}
auto t1 = WallClock::unixMicros();
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("rows_scanned");
json.addInteger(result.rows_scanned);
json.addComma();
json.addObjectEntry("execution_time_ms");
json.addFloat((t1 - t0) / 1000.0f);
json.addComma();
json.addObjectEntry("results");
json.beginArray();
int n = 0;
for (const auto& c : result.counters) {
if (++n > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("position");
json.addInteger(c.first);
json.addComma();
json.addObjectEntry("views");
json.addInteger(c.second.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(c.second.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(c.second.num_clicks / (double) c.second.num_views);
json.addComma();
json.addObjectEntry("ctr_base");
json.addFloat(c.second.num_clicks / (double) total_views);
json.addComma();
json.addObjectEntry("clickshare");
json.addFloat(c.second.num_clicks / (double) total_clicks);
json.endObject();
}
json.endArray();
json.endObject();
}
}
<commit_msg>CTRByPositionQuery...<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "CTRByPositionServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/logging.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
#include "analytics/CTRByPositionQuery.h"
using namespace fnord;
namespace cm {
CTRByPositionServlet::CTRByPositionServlet(VFS* vfs) : vfs_(vfs) {}
void CTRByPositionServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
const auto& params = uri.queryParams();
auto end_time = WallClock::unixMicros();
auto start_time = end_time - 30 * kMicrosPerDay;
Set<String> test_groups;
Set<String> device_types;
/* arguments */
String customer;
if (!URI::getParam(params, "customer", &customer)) {
res->addBody("error: missing ?customer=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
for (const auto& p : params) {
if (p.first == "from") {
start_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "until") {
end_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "test_group") {
test_groups.emplace(p.second);
continue;
}
if (p.first == "device_type") {
device_types.emplace(p.second);
continue;
}
}
if (test_groups.size() == 0) {
test_groups.emplace("all");
}
if (device_types.size() == 0) {
device_types = Set<String> { "unknown", "desktop", "tablet", "phone" };
}
/* execute query*/
auto t0 = WallClock::unixMicros();
cm::CTRByPositionQueryResult result;
std::mutex mutex;
size_t num_threads;
std::condition_variable cv;
for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerHour * 4) {
auto table_file = StringUtil::format(
"/srv/cmdata/artifacts/$0_joined_sessions.$1.cstable",
customer,
i / (kMicrosPerHour * 4));
if (!FileUtil::exists(table_file)) {
fnord::logWarning(
"cm.ctrbypositionservlet",
"missing table: $0",
table_file);
continue;
}
cstable::CSTableReader reader(table_file);
cm::AnalyticsQuery aq;
cm::CTRByPositionQueryResult r;
cm::CTRByPositionQuery q(&aq, &r);
aq.scanTable(&reader);
std::unique_lock<std::mutex> lk(mutex);
result.merge(r);
--num_threads;
lk.unlock();
}
uint64_t total_views = 0;
uint64_t total_clicks = 0;
for (const auto& c : result.counters) {
total_views += c.second.num_views;
total_clicks += c.second.num_clicks;
}
auto t1 = WallClock::unixMicros();
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("rows_scanned");
json.addInteger(result.rows_scanned);
json.addComma();
json.addObjectEntry("execution_time_ms");
json.addFloat((t1 - t0) / 1000.0f);
json.addComma();
json.addObjectEntry("results");
json.beginArray();
int n = 0;
for (const auto& c : result.counters) {
if (++n > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("position");
json.addInteger(c.first);
json.addComma();
json.addObjectEntry("views");
json.addInteger(c.second.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(c.second.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(c.second.num_clicks / (double) c.second.num_views);
json.addComma();
json.addObjectEntry("ctr_base");
json.addFloat(c.second.num_clicks / (double) total_views);
json.addComma();
json.addObjectEntry("clickshare");
json.addFloat(c.second.num_clicks / (double) total_clicks);
json.endObject();
}
json.endArray();
json.endObject();
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, The Mineserver Project
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 The Mineserver Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <cstdlib>
#include <cstdio>
#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <string>
#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <string.h>
#endif
#include "logger.h"
#include "constants.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "config.h"
#include "physics.h"
Chat* Chat::mChat;
void Chat::free()
{
if (mChat)
{
delete mChat;
mChat = 0;
}
}
Chat::Chat()
{
registerStandardCommands();
}
void Chat::registerCommand(Command *command)
{
// Loop thru all the words for this command
std::string currentWord;
std::deque<std::string> words = command->names;
while(!words.empty())
{
currentWord = words[0];
words.pop_front();
if(IS_ADMIN(command->permissions)) {
adminCommands[currentWord] = command;
continue;
}
if(IS_OP(command->permissions)) {
opCommands[currentWord] = command;
adminCommands[currentWord] = command;
continue;
}
if(IS_MEMBER(command->permissions)) {
memberCommands[currentWord] = command;
opCommands[currentWord] = command;
adminCommands[currentWord] = command;
continue;
}
if(IS_GUEST(command->permissions)) {
// insert into all
guestCommands[currentWord] = command;
memberCommands[currentWord] = command;
opCommands[currentWord] = command;
adminCommands[currentWord] = command;
}
}
}
bool Chat::checkMotd(std::string motdFile)
{
//
// Create motdfile is it doesn't exist
//
std::ifstream ifs(motdFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << motdFile << " not found. Creating..." << std::endl;
std::ofstream motdofs(motdFile.c_str());
motdofs << MOTD_CONTENT << std::endl;
motdofs.close();
}
ifs.close();
return true;
}
bool Chat::loadRoles(std::string rolesFile)
{
// Clear current admin-vector
admins.clear();
ops.clear();
members.clear();
// Read admins to deque
std::ifstream ifs(rolesFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << rolesFile << " not found. Creating..." << std::endl;
std::ofstream adminofs(rolesFile.c_str());
adminofs << ROLES_CONTENT << std::endl;
adminofs.close();
return true;
}
std::deque<std::string> *role_list = &members; // default is member role
std::string temp;
while(getline(ifs, temp))
{
if(temp[0] == COMMENTPREFIX) {
temp = temp.substr(1); // ignore COMMENTPREFIX
temp.erase(std::remove(temp.begin(), temp.end(), ' '), temp.end());
// get the name of the role from the comment
if(temp == "admins") {
role_list = &admins;
}
if(temp == "ops") {
role_list = &ops;
}
if(temp == "members") {
role_list = &members;
}
} else {
temp.erase(std::remove(temp.begin(), temp.end(), ' '), temp.end());
if(temp != "") {
role_list->push_back(temp);
}
}
}
ifs.close();
#ifdef _DEBUG
std::cout << "Loaded roles from " << rolesFile << std::endl;
#endif
return true;
}
bool Chat::loadBanned(std::string bannedFile)
{
// Clear current banned-vector
banned.clear();
// Read banned to deque
std::ifstream ifs(bannedFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << bannedFile << " not found. Creating..." << std::endl;
std::ofstream bannedofs(bannedFile.c_str());
bannedofs << BANNED_CONTENT << std::endl;
bannedofs.close();
return true;
}
std::string temp;
while(getline(ifs, temp))
{
// If not commentline
if(temp[0] != COMMENTPREFIX)
banned.push_back(temp);
}
ifs.close();
#ifdef _DEBUG
std::cout << "Loaded banned users from " << bannedFile << std::endl;
#endif
return true;
}
bool Chat::loadWhitelist(std::string whitelistFile)
{
// Clear current whitelist-vector
whitelist.clear();
// Read whitelist to deque
std::ifstream ifs(whitelistFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << whitelistFile << " not found. Creating..." << std::endl;
std::ofstream whitelistofs(whitelistFile.c_str());
whitelistofs << WHITELIST_CONTENT << std::endl;
whitelistofs.close();
return true;
}
std::string temp;
while(getline(ifs, temp))
{
// If not commentline
if(temp[0] != COMMENTPREFIX)
whitelist.push_back(temp);
}
ifs.close();
#ifdef _DEBUG
std::cout << "Loaded whitelisted users from " << whitelistFile << std::endl;
#endif
return true;
}
bool Chat::sendUserlist(User *user)
{
this->sendMsg(user, COLOR_BLUE + "[ " + dtos(Users.size()) + " players online ]", USER);
for(unsigned int i = 0; i < Users.size(); i++)
{
std::string playerDesc = "> " + Users[i]->nick;
if(Users[i]->muted)
playerDesc += COLOR_YELLOW + " (muted)";
if(Users[i]->dnd)
playerDesc += COLOR_YELLOW + " (dnd)";
this->sendMsg(user, playerDesc, USER);
}
return true;
}
std::deque<std::string> Chat::parseCmd(std::string cmd)
{
int del;
std::deque<std::string> temp;
while(cmd.length() > 0)
{
while(cmd[0] == ' ')
cmd = cmd.substr(1);
del = cmd.find(' ');
if(del > -1)
{
temp.push_back(cmd.substr(0, del));
cmd = cmd.substr(del+1);
}
else
{
temp.push_back(cmd);
break;
}
}
if(temp.empty())
temp.push_back("empty");
return temp;
}
bool Chat::handleMsg(User *user, std::string msg)
{
// Timestamp
time_t rawTime = time(NULL);
struct tm *Tm = localtime(&rawTime);
std::string timeStamp (asctime(Tm));
timeStamp = timeStamp.substr(11, 5);
//
// Chat commands
//
// Servermsg (Admin-only)
if(msg[0] == SERVERMSGPREFIX && IS_ADMIN(user->permissions))
{
// Decorate server message
msg = COLOR_RED + "[!] " + COLOR_GREEN + msg.substr(1);
this->sendMsg(user, msg, ALL);
}
// Adminchat
else if(msg[0] == ADMINCHATPREFIX && IS_ADMIN(user->permissions))
{
msg = timeStamp + " @@ <"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + "> " + msg.substr(1);
this->sendMsg(user, msg, ADMINS);
}
// Command
else if(msg[0] == CHATCMDPREFIX)
{
std::deque<std::string> cmd = this->parseCmd(msg.substr(1));
std::string command = cmd[0];
cmd.pop_front();
// User commands
CommandList::iterator iter;
if((iter = memberCommands.find(command)) != memberCommands.end())
iter->second->callback(user, command, cmd);
else if(IS_ADMIN(user->permissions) && (iter = adminCommands.find(command)) != adminCommands.end())
iter->second->callback(user, command, cmd);
}
// Normal message
else
{
if(user->isAbleToCommunicate("chat") == false) {
return true;
}
else {
if(IS_ADMIN(user->permissions))
msg = timeStamp + " <"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + "> " + msg;
else
msg = timeStamp + " <"+ user->nick + "> " + msg;
}
LOG(msg);
this->sendMsg(user, msg, ALL);
}
return true;
}
bool Chat::sendMsg(User *user, std::string msg, MessageTarget action)
{
size_t tmpArrayLen = msg.size()+3;
uint8 *tmpArray = new uint8[tmpArrayLen];
tmpArray[0] = 0x03;
tmpArray[1] = 0;
tmpArray[2] = msg.size()&0xff;
for(unsigned int i = 0; i < msg.size(); i++)
tmpArray[i+3] = msg[i];
switch(action)
{
case ALL:
user->sendAll(tmpArray, tmpArrayLen);
break;
case USER:
user->buffer.addToWrite(tmpArray, tmpArrayLen);
break;
case ADMINS:
user->sendAdmins(tmpArray, tmpArrayLen);
break;
case OPS:
user->sendOps(tmpArray, tmpArrayLen);
break;
case GUESTS:
user->sendGuests(tmpArray, tmpArrayLen);
break;
case OTHERS:
user->sendOthers(tmpArray, tmpArrayLen);
break;
}
delete[] tmpArray;
return true;
}
void Chat::sendHelp(User *user, std::deque<std::string> args)
{
// TODO: Add paging support, since not all commands will fit into
// the screen at once.
CommandList *commandList = &guestCommands; // defaults
std::string commandColor = COLOR_BLUE;
if(IS_ADMIN(user->permissions)) {
commandList = &adminCommands;
commandColor = COLOR_RED; // different color for admin commands
} else if(IS_OP(user->permissions)) {
commandList = &opCommands;
commandColor = COLOR_GREEN;
} else if(IS_MEMBER(user->permissions)) {
commandList = &memberCommands;
}
if(args.size() == 0) {
for(CommandList::iterator it = commandList->begin();
it != commandList->end();
it++) {
std::string args = it->second->arguments;
std::string description = it->second->description;
sendMsg(user, commandColor + CHATCMDPREFIX + it->first + " " + args + " : " + COLOR_YELLOW + description, Chat::USER);
}
} else {
CommandList::iterator iter;
if((iter = commandList->find(args.front())) != commandList->end()) {
std::string args = iter->second->arguments;
std::string description = iter->second->description;
sendMsg(user, commandColor + CHATCMDPREFIX + iter->first + args, Chat::USER);
sendMsg(user, COLOR_YELLOW + CHATCMDPREFIX + description, Chat::USER);
} else {
sendMsg(user, COLOR_RED + "Unknown Command: " + args.front(), Chat::USER);
}
}
}
<commit_msg>Small display fix to help command.<commit_after>/*
Copyright (c) 2010, The Mineserver Project
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 The Mineserver Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <cstdlib>
#include <cstdio>
#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <string>
#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <string.h>
#endif
#include "logger.h"
#include "constants.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "config.h"
#include "physics.h"
Chat* Chat::mChat;
void Chat::free()
{
if (mChat)
{
delete mChat;
mChat = 0;
}
}
Chat::Chat()
{
registerStandardCommands();
}
void Chat::registerCommand(Command *command)
{
// Loop thru all the words for this command
std::string currentWord;
std::deque<std::string> words = command->names;
while(!words.empty())
{
currentWord = words[0];
words.pop_front();
if(IS_ADMIN(command->permissions)) {
adminCommands[currentWord] = command;
continue;
}
if(IS_OP(command->permissions)) {
opCommands[currentWord] = command;
adminCommands[currentWord] = command;
continue;
}
if(IS_MEMBER(command->permissions)) {
memberCommands[currentWord] = command;
opCommands[currentWord] = command;
adminCommands[currentWord] = command;
continue;
}
if(IS_GUEST(command->permissions)) {
// insert into all
guestCommands[currentWord] = command;
memberCommands[currentWord] = command;
opCommands[currentWord] = command;
adminCommands[currentWord] = command;
}
}
}
bool Chat::checkMotd(std::string motdFile)
{
//
// Create motdfile is it doesn't exist
//
std::ifstream ifs(motdFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << motdFile << " not found. Creating..." << std::endl;
std::ofstream motdofs(motdFile.c_str());
motdofs << MOTD_CONTENT << std::endl;
motdofs.close();
}
ifs.close();
return true;
}
bool Chat::loadRoles(std::string rolesFile)
{
// Clear current admin-vector
admins.clear();
ops.clear();
members.clear();
// Read admins to deque
std::ifstream ifs(rolesFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << rolesFile << " not found. Creating..." << std::endl;
std::ofstream adminofs(rolesFile.c_str());
adminofs << ROLES_CONTENT << std::endl;
adminofs.close();
return true;
}
std::deque<std::string> *role_list = &members; // default is member role
std::string temp;
while(getline(ifs, temp))
{
if(temp[0] == COMMENTPREFIX) {
temp = temp.substr(1); // ignore COMMENTPREFIX
temp.erase(std::remove(temp.begin(), temp.end(), ' '), temp.end());
// get the name of the role from the comment
if(temp == "admins") {
role_list = &admins;
}
if(temp == "ops") {
role_list = &ops;
}
if(temp == "members") {
role_list = &members;
}
} else {
temp.erase(std::remove(temp.begin(), temp.end(), ' '), temp.end());
if(temp != "") {
role_list->push_back(temp);
}
}
}
ifs.close();
#ifdef _DEBUG
std::cout << "Loaded roles from " << rolesFile << std::endl;
#endif
return true;
}
bool Chat::loadBanned(std::string bannedFile)
{
// Clear current banned-vector
banned.clear();
// Read banned to deque
std::ifstream ifs(bannedFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << bannedFile << " not found. Creating..." << std::endl;
std::ofstream bannedofs(bannedFile.c_str());
bannedofs << BANNED_CONTENT << std::endl;
bannedofs.close();
return true;
}
std::string temp;
while(getline(ifs, temp))
{
// If not commentline
if(temp[0] != COMMENTPREFIX)
banned.push_back(temp);
}
ifs.close();
#ifdef _DEBUG
std::cout << "Loaded banned users from " << bannedFile << std::endl;
#endif
return true;
}
bool Chat::loadWhitelist(std::string whitelistFile)
{
// Clear current whitelist-vector
whitelist.clear();
// Read whitelist to deque
std::ifstream ifs(whitelistFile.c_str());
// If file does not exist
if(ifs.fail())
{
std::cout << "> Warning: " << whitelistFile << " not found. Creating..." << std::endl;
std::ofstream whitelistofs(whitelistFile.c_str());
whitelistofs << WHITELIST_CONTENT << std::endl;
whitelistofs.close();
return true;
}
std::string temp;
while(getline(ifs, temp))
{
// If not commentline
if(temp[0] != COMMENTPREFIX)
whitelist.push_back(temp);
}
ifs.close();
#ifdef _DEBUG
std::cout << "Loaded whitelisted users from " << whitelistFile << std::endl;
#endif
return true;
}
bool Chat::sendUserlist(User *user)
{
this->sendMsg(user, COLOR_BLUE + "[ " + dtos(Users.size()) + " players online ]", USER);
for(unsigned int i = 0; i < Users.size(); i++)
{
std::string playerDesc = "> " + Users[i]->nick;
if(Users[i]->muted)
playerDesc += COLOR_YELLOW + " (muted)";
if(Users[i]->dnd)
playerDesc += COLOR_YELLOW + " (dnd)";
this->sendMsg(user, playerDesc, USER);
}
return true;
}
std::deque<std::string> Chat::parseCmd(std::string cmd)
{
int del;
std::deque<std::string> temp;
while(cmd.length() > 0)
{
while(cmd[0] == ' ')
cmd = cmd.substr(1);
del = cmd.find(' ');
if(del > -1)
{
temp.push_back(cmd.substr(0, del));
cmd = cmd.substr(del+1);
}
else
{
temp.push_back(cmd);
break;
}
}
if(temp.empty())
temp.push_back("empty");
return temp;
}
bool Chat::handleMsg(User *user, std::string msg)
{
// Timestamp
time_t rawTime = time(NULL);
struct tm *Tm = localtime(&rawTime);
std::string timeStamp (asctime(Tm));
timeStamp = timeStamp.substr(11, 5);
//
// Chat commands
//
// Servermsg (Admin-only)
if(msg[0] == SERVERMSGPREFIX && IS_ADMIN(user->permissions))
{
// Decorate server message
msg = COLOR_RED + "[!] " + COLOR_GREEN + msg.substr(1);
this->sendMsg(user, msg, ALL);
}
// Adminchat
else if(msg[0] == ADMINCHATPREFIX && IS_ADMIN(user->permissions))
{
msg = timeStamp + " @@ <"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + "> " + msg.substr(1);
this->sendMsg(user, msg, ADMINS);
}
// Command
else if(msg[0] == CHATCMDPREFIX)
{
std::deque<std::string> cmd = this->parseCmd(msg.substr(1));
std::string command = cmd[0];
cmd.pop_front();
// User commands
CommandList::iterator iter;
if((iter = memberCommands.find(command)) != memberCommands.end())
iter->second->callback(user, command, cmd);
else if(IS_ADMIN(user->permissions) && (iter = adminCommands.find(command)) != adminCommands.end())
iter->second->callback(user, command, cmd);
}
// Normal message
else
{
if(user->isAbleToCommunicate("chat") == false) {
return true;
}
else {
if(IS_ADMIN(user->permissions))
msg = timeStamp + " <"+ COLOR_DARK_MAGENTA + user->nick + COLOR_WHITE + "> " + msg;
else
msg = timeStamp + " <"+ user->nick + "> " + msg;
}
LOG(msg);
this->sendMsg(user, msg, ALL);
}
return true;
}
bool Chat::sendMsg(User *user, std::string msg, MessageTarget action)
{
size_t tmpArrayLen = msg.size()+3;
uint8 *tmpArray = new uint8[tmpArrayLen];
tmpArray[0] = 0x03;
tmpArray[1] = 0;
tmpArray[2] = msg.size()&0xff;
for(unsigned int i = 0; i < msg.size(); i++)
tmpArray[i+3] = msg[i];
switch(action)
{
case ALL:
user->sendAll(tmpArray, tmpArrayLen);
break;
case USER:
user->buffer.addToWrite(tmpArray, tmpArrayLen);
break;
case ADMINS:
user->sendAdmins(tmpArray, tmpArrayLen);
break;
case OPS:
user->sendOps(tmpArray, tmpArrayLen);
break;
case GUESTS:
user->sendGuests(tmpArray, tmpArrayLen);
break;
case OTHERS:
user->sendOthers(tmpArray, tmpArrayLen);
break;
}
delete[] tmpArray;
return true;
}
void Chat::sendHelp(User *user, std::deque<std::string> args)
{
// TODO: Add paging support, since not all commands will fit into
// the screen at once.
CommandList *commandList = &guestCommands; // defaults
std::string commandColor = COLOR_BLUE;
if(IS_ADMIN(user->permissions)) {
commandList = &adminCommands;
commandColor = COLOR_RED; // different color for admin commands
} else if(IS_OP(user->permissions)) {
commandList = &opCommands;
commandColor = COLOR_GREEN;
} else if(IS_MEMBER(user->permissions)) {
commandList = &memberCommands;
}
if(args.size() == 0) {
for(CommandList::iterator it = commandList->begin();
it != commandList->end();
it++) {
std::string args = it->second->arguments;
std::string description = it->second->description;
sendMsg(user, commandColor + CHATCMDPREFIX + it->first + " " + args + " : " + COLOR_YELLOW + description, Chat::USER);
}
} else {
CommandList::iterator iter;
if((iter = commandList->find(args.front())) != commandList->end()) {
std::string args = iter->second->arguments;
std::string description = iter->second->description;
sendMsg(user, commandColor + CHATCMDPREFIX + iter->first + " " + args, Chat::USER);
sendMsg(user, COLOR_YELLOW + CHATCMDPREFIX + description, Chat::USER);
} else {
sendMsg(user, COLOR_RED + "Unknown Command: " + args.front(), Chat::USER);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include <iostream>
#include <memory>
#include "zorbamisc/ns_consts.h"
#include "functions/library.h"
#include "functions/function.h"
#include "functions/signature.h"
#include "functions/func_accessors.h"
#include "functions/func_accessors_impl.h"
#include "functions/func_any_uri.h"
#include "functions/func_arithmetic.h"
#include "functions/func_base64.h"
#include "functions/func_booleans.h"
#include "functions/func_booleans_impl.h"
#include "functions/func_collections.h"
#include "functions/func_context.h"
#include "functions/func_other_diagnostics.h"
#include "functions/func_durations_dates_times.h"
#include "functions/func_durations_dates_times_impl.h"
#include "functions/func_enclosed.h"
#include "functions/func_errors_and_diagnostics.h"
#include "functions/func_fnput.h"
#include "functions/func_hoist.h"
#include "functions/func_index_ddl.h"
#include "functions/func_index_func.h"
#include "functions/func_ic_ddl.h"
#include "functions/func_maths.h"
#include "functions/func_nodes.h"
#include "functions/func_node_position.h"
#include "functions/func_node_sort_distinct.h"
#include "functions/func_numerics.h"
#include "functions/func_numerics_impl.h"
#include "functions/func_parsing_and_serializing.h"
#include "functions/func_parse_fragment.h"
#include "functions/func_parse_fragment_impl.h"
#include "functions/func_qnames.h"
#include "functions/func_random.h"
#include "functions/func_schema.h"
#include "functions/func_sctx.h"
#include "functions/func_sequences.h"
#include "functions/func_sequences_impl.h"
#include "functions/func_strings.h"
#include "functions/func_strings_impl.h"
#include "functions/func_uris.h"
#include "functions/func_json.h"
#include "functions/func_var_decl.h"
#include "functions/func_xqdoc.h"
#include "functions/func_documents.h"
#include "functions/func_maps.h"
#include "functions/func_eval.h"
#include "functions/func_reflection.h"
#include "functions/func_apply.h"
#include "functions/func_fetch.h"
#ifndef ZORBA_NO_FULL_TEXT
#include "functions/func_ft_module.h"
#include "runtime/full_text/ft_module_impl.h"
#endif /* ZORBA_NO_FULL_TEXT */
#include "functions/func_function_item_iter.h"
#include "zorbaserialization/archiver.h"
#ifdef ZORBA_WITH_JSON
#include "functions/func_jsoniq_functions.h"
#include "functions/func_jsoniq_functions_impl.h"
#endif
namespace zorba
{
function** BuiltinFunctionLibrary::theFunctions = NULL;
// clear static initializer state
// dummy function to tell the windows linker to keep the library.obj
// even though it contains no public objects or functions
// this is called at initializeZorba
void library_init()
{
}
void BuiltinFunctionLibrary::create(static_context* sctx)
{
#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
zorba::serialization::Archiver& ar = *::zorba::serialization::ClassSerializer::getInstance()->getArchiverForHardcodedObjects();
ar.set_loading_hardcoded_objects(true);
#endif
theFunctions = new function*[FunctionConsts::FN_MAX_FUNC];
populate_context_accessors(sctx);
populate_context_any_uri(sctx);
populate_context_accessors_impl(sctx);
populate_context_base64(sctx);
populate_context_booleans(sctx);
populate_context_booleans_impl(sctx);
populate_context_collections(sctx);
populate_context_context(sctx);
populate_context_durations_dates_times(sctx);
populate_context_durations_dates_times_impl(sctx);
populate_context_errors_and_diagnostics(sctx);
populate_context_fnput(sctx);
populate_context_index_ddl(sctx);
populate_context_index_func(sctx);
populate_context_ic_ddl(sctx);
populate_context_json(sctx);
populate_context_maths(sctx);
populate_context_nodes(sctx);
populate_context_node_position(sctx);
populate_context_numerics(sctx);
populate_context_other_diagnostics(sctx);
populate_context_parsing_and_serializing(sctx);
populate_context_parse_fragment(sctx);
populate_context_parse_fragment_impl(sctx);
populate_context_qnames(sctx);
populate_context_random(sctx);
populate_context_schema(sctx);
populate_context_sctx(sctx);
populate_context_strings(sctx);
populate_context_strings_impl(sctx);
populate_context_uris(sctx);
populate_context_sequences(sctx);
populate_context_sequences_impl(sctx);
populate_context_xqdoc(sctx);
populate_context_function_item_iter(sctx);
populate_context_documents(sctx);
populate_context_maps(sctx);
populateContext_Arithmetics(sctx);
populateContext_Numerics(sctx);
populateContext_DocOrder(sctx);
populateContext_Comparison(sctx);
populateContext_Constructors(sctx);
populateContext_VarDecl(sctx);
populateContext_Hoisting(sctx);
populate_context_eval(sctx);
populate_context_reflection(sctx);
populate_context_apply(sctx);
populate_context_fetch(sctx);
#ifndef ZORBA_NO_FULL_TEXT
populate_context_ft_module(sctx);
populate_context_ft_module_impl(sctx);
#endif /* ZORBA_NO_FULL_TEXT */
#ifdef ZORBA_WITH_JSON
populate_context_jsoniq_functions(sctx);
populate_context_jsoniq_functions_impl(sctx);
#endif
#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
ar.set_loading_hardcoded_objects(false);
#endif
}
void BuiltinFunctionLibrary::destroy()
{
delete [] theFunctions;
}
} /* namespace zorba */
/* vim:set et sw=2 ts=2: */
<commit_msg>Added call to populate_context_datetime.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include <iostream>
#include <memory>
#include "zorbamisc/ns_consts.h"
#include "functions/library.h"
#include "functions/function.h"
#include "functions/signature.h"
#include "functions/func_accessors.h"
#include "functions/func_accessors_impl.h"
#include "functions/func_any_uri.h"
#include "functions/func_apply.h"
#include "functions/func_arithmetic.h"
#include "functions/func_base64.h"
#include "functions/func_booleans.h"
#include "functions/func_booleans_impl.h"
#include "functions/func_collections.h"
#include "functions/func_context.h"
#include "functions/func_datetime.h"
#include "functions/func_documents.h"
#include "functions/func_durations_dates_times.h"
#include "functions/func_durations_dates_times_impl.h"
#include "functions/func_enclosed.h"
#include "functions/func_errors_and_diagnostics.h"
#include "functions/func_eval.h"
#include "functions/func_fetch.h"
#include "functions/func_fnput.h"
#include "functions/func_hoist.h"
#include "functions/func_ic_ddl.h"
#include "functions/func_index_ddl.h"
#include "functions/func_index_func.h"
#include "functions/func_json.h"
#include "functions/func_maps.h"
#include "functions/func_maths.h"
#include "functions/func_node_position.h"
#include "functions/func_node_sort_distinct.h"
#include "functions/func_nodes.h"
#include "functions/func_numerics.h"
#include "functions/func_numerics_impl.h"
#include "functions/func_other_diagnostics.h"
#include "functions/func_parse_fragment.h"
#include "functions/func_parse_fragment_impl.h"
#include "functions/func_parsing_and_serializing.h"
#include "functions/func_qnames.h"
#include "functions/func_random.h"
#include "functions/func_reflection.h"
#include "functions/func_schema.h"
#include "functions/func_sctx.h"
#include "functions/func_sequences.h"
#include "functions/func_sequences_impl.h"
#include "functions/func_strings.h"
#include "functions/func_strings_impl.h"
#include "functions/func_uris.h"
#include "functions/func_var_decl.h"
#include "functions/func_xqdoc.h"
#ifndef ZORBA_NO_FULL_TEXT
#include "functions/func_ft_module.h"
#include "runtime/full_text/ft_module_impl.h"
#endif /* ZORBA_NO_FULL_TEXT */
#include "functions/func_function_item_iter.h"
#include "zorbaserialization/archiver.h"
#ifdef ZORBA_WITH_JSON
#include "functions/func_jsoniq_functions.h"
#include "functions/func_jsoniq_functions_impl.h"
#endif
namespace zorba
{
function** BuiltinFunctionLibrary::theFunctions = NULL;
// clear static initializer state
// dummy function to tell the windows linker to keep the library.obj
// even though it contains no public objects or functions
// this is called at initializeZorba
void library_init()
{
}
void BuiltinFunctionLibrary::create(static_context* sctx)
{
#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
zorba::serialization::Archiver& ar = *::zorba::serialization::ClassSerializer::getInstance()->getArchiverForHardcodedObjects();
ar.set_loading_hardcoded_objects(true);
#endif
theFunctions = new function*[FunctionConsts::FN_MAX_FUNC];
populate_context_accessors(sctx);
populate_context_any_uri(sctx);
populate_context_accessors_impl(sctx);
populate_context_base64(sctx);
populate_context_booleans(sctx);
populate_context_booleans_impl(sctx);
populate_context_collections(sctx);
populate_context_context(sctx);
populate_context_datetime(sctx);
populate_context_durations_dates_times(sctx);
populate_context_durations_dates_times_impl(sctx);
populate_context_errors_and_diagnostics(sctx);
populate_context_fnput(sctx);
populate_context_index_ddl(sctx);
populate_context_index_func(sctx);
populate_context_ic_ddl(sctx);
populate_context_json(sctx);
populate_context_maths(sctx);
populate_context_nodes(sctx);
populate_context_node_position(sctx);
populate_context_numerics(sctx);
populate_context_other_diagnostics(sctx);
populate_context_parsing_and_serializing(sctx);
populate_context_parse_fragment(sctx);
populate_context_parse_fragment_impl(sctx);
populate_context_qnames(sctx);
populate_context_random(sctx);
populate_context_schema(sctx);
populate_context_sctx(sctx);
populate_context_strings(sctx);
populate_context_strings_impl(sctx);
populate_context_uris(sctx);
populate_context_sequences(sctx);
populate_context_sequences_impl(sctx);
populate_context_xqdoc(sctx);
populate_context_function_item_iter(sctx);
populate_context_documents(sctx);
populate_context_maps(sctx);
populateContext_Arithmetics(sctx);
populateContext_Numerics(sctx);
populateContext_DocOrder(sctx);
populateContext_Comparison(sctx);
populateContext_Constructors(sctx);
populateContext_VarDecl(sctx);
populateContext_Hoisting(sctx);
populate_context_eval(sctx);
populate_context_reflection(sctx);
populate_context_apply(sctx);
populate_context_fetch(sctx);
#ifndef ZORBA_NO_FULL_TEXT
populate_context_ft_module(sctx);
populate_context_ft_module_impl(sctx);
#endif /* ZORBA_NO_FULL_TEXT */
#ifdef ZORBA_WITH_JSON
populate_context_jsoniq_functions(sctx);
populate_context_jsoniq_functions_impl(sctx);
#endif
#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
ar.set_loading_hardcoded_objects(false);
#endif
}
void BuiltinFunctionLibrary::destroy()
{
delete [] theFunctions;
}
} /* namespace zorba */
/* vim:set et sw=2 ts=2: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: formattedcontrol.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2006-07-19 15:55: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
*
************************************************************************/
#ifndef TOOLKIT_FORMATTED_CONTROL_HXX
#include <toolkit/controls/formattedcontrol.hxx>
#endif
#ifndef _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#include <toolkit/helper/unopropertyarrayhelper.hxx>
#endif
#ifndef _TOOLKIT_HELPER_PROPERTY_HXX_
#include <toolkit/helper/property.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_XVCLWINDOWPEER_HPP_
#include <com/sun/star/awt/XVclWindowPeer.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//........................................................................
namespace toolkit
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
// ===================================================================
// = UnoControlFormattedFieldModel
// ===================================================================
// -------------------------------------------------------------------
UnoControlFormattedFieldModel::UnoControlFormattedFieldModel()
{
ImplRegisterProperty( BASEPROPERTY_ALIGN );
ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR );
ImplRegisterProperty( BASEPROPERTY_BORDER );
ImplRegisterProperty( BASEPROPERTY_BORDERCOLOR );
ImplRegisterProperty( BASEPROPERTY_DEFAULTCONTROL );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_DEFAULT );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_VALUE );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_MAX );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_MIN );
ImplRegisterProperty( BASEPROPERTY_ENABLED );
ImplRegisterProperty( BASEPROPERTY_FONTDESCRIPTOR );
ImplRegisterProperty( BASEPROPERTY_FORMATKEY );
ImplRegisterProperty( BASEPROPERTY_FORMATSSUPPLIER );
ImplRegisterProperty( BASEPROPERTY_HELPTEXT );
ImplRegisterProperty( BASEPROPERTY_HELPURL );
ImplRegisterProperty( BASEPROPERTY_MAXTEXTLEN );
ImplRegisterProperty( BASEPROPERTY_PRINTABLE );
ImplRegisterProperty( BASEPROPERTY_REPEAT );
ImplRegisterProperty( BASEPROPERTY_REPEAT_DELAY );
ImplRegisterProperty( BASEPROPERTY_READONLY );
ImplRegisterProperty( BASEPROPERTY_SPIN );
ImplRegisterProperty( BASEPROPERTY_STRICTFORMAT );
ImplRegisterProperty( BASEPROPERTY_TABSTOP );
ImplRegisterProperty( BASEPROPERTY_TEXT );
ImplRegisterProperty( BASEPROPERTY_TEXTCOLOR );
ImplRegisterProperty( BASEPROPERTY_HIDEINACTIVESELECTION );
ImplRegisterProperty( BASEPROPERTY_ENFORCE_FORMAT );
Any aTreatAsNumber;
aTreatAsNumber <<= (sal_Bool) sal_True;
ImplRegisterProperty( BASEPROPERTY_TREATASNUMBER, aTreatAsNumber );
}
// -------------------------------------------------------------------
::rtl::OUString UnoControlFormattedFieldModel::getServiceName() throw(RuntimeException)
{
return ::rtl::OUString::createFromAscii( szServiceName_UnoControlFormattedFieldModel );
}
// -------------------------------------------------------------------
sal_Bool UnoControlFormattedFieldModel::convertFastPropertyValue(
Any& rConvertedValue, Any& rOldValue, sal_Int32 nPropId,
const Any& rValue ) throw (IllegalArgumentException)
{
if ( BASEPROPERTY_EFFECTIVE_DEFAULT == nPropId )
{
sal_Bool bStreamed;
double dVal = 0;
sal_Int32 nVal = 0;
::rtl::OUString sVal;
if ( (bStreamed = (rValue >>= dVal)) )
rConvertedValue <<= dVal;
else if ( (bStreamed = (rValue >>= nVal)) )
rConvertedValue <<= static_cast<double>(nVal);
else if ( (bStreamed = (rValue >>= sVal)) )
rConvertedValue <<= sVal;
if ( bStreamed )
{
getFastPropertyValue( rOldValue, nPropId );
return !CompareProperties( rConvertedValue, rOldValue );
}
throw IllegalArgumentException(
( ::rtl::OUString::createFromAscii("Unable to convert the given value for the property ")
+= GetPropertyName((sal_uInt16)nPropId) )
+= ::rtl::OUString::createFromAscii(" (double, integer, or string expected)."),
static_cast< XPropertySet* >(this),
1);
}
return UnoControlModel::convertFastPropertyValue( rConvertedValue, rOldValue, nPropId, rValue );
}
// -------------------------------------------------------------------
Any UnoControlFormattedFieldModel::ImplGetDefaultValue( sal_uInt16 nPropId ) const
{
Any aReturn;
switch (nPropId)
{
case BASEPROPERTY_DEFAULTCONTROL: aReturn <<= ::rtl::OUString( ::rtl::OUString::createFromAscii( szServiceName_UnoControlFormattedField ) ); break;
case BASEPROPERTY_TREATASNUMBER: aReturn <<= (sal_Bool)sal_True; break;
case BASEPROPERTY_EFFECTIVE_DEFAULT:
case BASEPROPERTY_EFFECTIVE_VALUE:
case BASEPROPERTY_EFFECTIVE_MAX:
case BASEPROPERTY_EFFECTIVE_MIN:
case BASEPROPERTY_FORMATKEY:
case BASEPROPERTY_FORMATSSUPPLIER:
// (void)
break;
default : aReturn = UnoControlModel::ImplGetDefaultValue( nPropId ); break;
}
return aReturn;
}
// -------------------------------------------------------------------
::cppu::IPropertyArrayHelper& UnoControlFormattedFieldModel::getInfoHelper()
{
static UnoPropertyArrayHelper* pHelper = NULL;
if ( !pHelper )
{
Sequence<sal_Int32> aIDs = ImplGetPropertyIds();
pHelper = new UnoPropertyArrayHelper( aIDs );
}
return *pHelper;
}
// beans::XMultiPropertySet
// -------------------------------------------------------------------
Reference< XPropertySetInfo > UnoControlFormattedFieldModel::getPropertySetInfo( ) throw(RuntimeException)
{
static Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
// ===================================================================
// = UnoFormattedFieldControl
// ===================================================================
// -------------------------------------------------------------------
UnoFormattedFieldControl::UnoFormattedFieldControl()
{
}
// -------------------------------------------------------------------
::rtl::OUString UnoFormattedFieldControl::GetComponentServiceName()
{
return ::rtl::OUString::createFromAscii( "FormattedField" );
}
// -------------------------------------------------------------------
void UnoFormattedFieldControl::textChanged(const TextEvent& e) throw(RuntimeException)
{
Reference< XVclWindowPeer > xPeer(getPeer(), UNO_QUERY);
OSL_ENSURE(xPeer.is(), "UnoFormattedFieldControl::textChanged : what kind of peer do I have ?");
::rtl::OUString sTextPropertyName = GetPropertyName( BASEPROPERTY_TEXT );
ImplSetPropertyValue( sTextPropertyName, xPeer->getProperty( sTextPropertyName ), sal_False );
::rtl::OUString sEffectiveValue = GetPropertyName( BASEPROPERTY_EFFECTIVE_VALUE );
ImplSetPropertyValue( sEffectiveValue, xPeer->getProperty( sEffectiveValue ), sal_False );
if ( GetTextListeners().getLength() )
GetTextListeners().textChanged( e );
}
//........................................................................
} // namespace toolkit
//........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.24); FILE MERGED 2006/09/01 17:54:22 kaib 1.8.24.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: formattedcontrol.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-16 12:17:21 $
*
* 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_toolkit.hxx"
#ifndef TOOLKIT_FORMATTED_CONTROL_HXX
#include <toolkit/controls/formattedcontrol.hxx>
#endif
#ifndef _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#include <toolkit/helper/unopropertyarrayhelper.hxx>
#endif
#ifndef _TOOLKIT_HELPER_PROPERTY_HXX_
#include <toolkit/helper/property.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_XVCLWINDOWPEER_HPP_
#include <com/sun/star/awt/XVclWindowPeer.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//........................................................................
namespace toolkit
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
// ===================================================================
// = UnoControlFormattedFieldModel
// ===================================================================
// -------------------------------------------------------------------
UnoControlFormattedFieldModel::UnoControlFormattedFieldModel()
{
ImplRegisterProperty( BASEPROPERTY_ALIGN );
ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR );
ImplRegisterProperty( BASEPROPERTY_BORDER );
ImplRegisterProperty( BASEPROPERTY_BORDERCOLOR );
ImplRegisterProperty( BASEPROPERTY_DEFAULTCONTROL );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_DEFAULT );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_VALUE );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_MAX );
ImplRegisterProperty( BASEPROPERTY_EFFECTIVE_MIN );
ImplRegisterProperty( BASEPROPERTY_ENABLED );
ImplRegisterProperty( BASEPROPERTY_FONTDESCRIPTOR );
ImplRegisterProperty( BASEPROPERTY_FORMATKEY );
ImplRegisterProperty( BASEPROPERTY_FORMATSSUPPLIER );
ImplRegisterProperty( BASEPROPERTY_HELPTEXT );
ImplRegisterProperty( BASEPROPERTY_HELPURL );
ImplRegisterProperty( BASEPROPERTY_MAXTEXTLEN );
ImplRegisterProperty( BASEPROPERTY_PRINTABLE );
ImplRegisterProperty( BASEPROPERTY_REPEAT );
ImplRegisterProperty( BASEPROPERTY_REPEAT_DELAY );
ImplRegisterProperty( BASEPROPERTY_READONLY );
ImplRegisterProperty( BASEPROPERTY_SPIN );
ImplRegisterProperty( BASEPROPERTY_STRICTFORMAT );
ImplRegisterProperty( BASEPROPERTY_TABSTOP );
ImplRegisterProperty( BASEPROPERTY_TEXT );
ImplRegisterProperty( BASEPROPERTY_TEXTCOLOR );
ImplRegisterProperty( BASEPROPERTY_HIDEINACTIVESELECTION );
ImplRegisterProperty( BASEPROPERTY_ENFORCE_FORMAT );
Any aTreatAsNumber;
aTreatAsNumber <<= (sal_Bool) sal_True;
ImplRegisterProperty( BASEPROPERTY_TREATASNUMBER, aTreatAsNumber );
}
// -------------------------------------------------------------------
::rtl::OUString UnoControlFormattedFieldModel::getServiceName() throw(RuntimeException)
{
return ::rtl::OUString::createFromAscii( szServiceName_UnoControlFormattedFieldModel );
}
// -------------------------------------------------------------------
sal_Bool UnoControlFormattedFieldModel::convertFastPropertyValue(
Any& rConvertedValue, Any& rOldValue, sal_Int32 nPropId,
const Any& rValue ) throw (IllegalArgumentException)
{
if ( BASEPROPERTY_EFFECTIVE_DEFAULT == nPropId )
{
sal_Bool bStreamed;
double dVal = 0;
sal_Int32 nVal = 0;
::rtl::OUString sVal;
if ( (bStreamed = (rValue >>= dVal)) )
rConvertedValue <<= dVal;
else if ( (bStreamed = (rValue >>= nVal)) )
rConvertedValue <<= static_cast<double>(nVal);
else if ( (bStreamed = (rValue >>= sVal)) )
rConvertedValue <<= sVal;
if ( bStreamed )
{
getFastPropertyValue( rOldValue, nPropId );
return !CompareProperties( rConvertedValue, rOldValue );
}
throw IllegalArgumentException(
( ::rtl::OUString::createFromAscii("Unable to convert the given value for the property ")
+= GetPropertyName((sal_uInt16)nPropId) )
+= ::rtl::OUString::createFromAscii(" (double, integer, or string expected)."),
static_cast< XPropertySet* >(this),
1);
}
return UnoControlModel::convertFastPropertyValue( rConvertedValue, rOldValue, nPropId, rValue );
}
// -------------------------------------------------------------------
Any UnoControlFormattedFieldModel::ImplGetDefaultValue( sal_uInt16 nPropId ) const
{
Any aReturn;
switch (nPropId)
{
case BASEPROPERTY_DEFAULTCONTROL: aReturn <<= ::rtl::OUString( ::rtl::OUString::createFromAscii( szServiceName_UnoControlFormattedField ) ); break;
case BASEPROPERTY_TREATASNUMBER: aReturn <<= (sal_Bool)sal_True; break;
case BASEPROPERTY_EFFECTIVE_DEFAULT:
case BASEPROPERTY_EFFECTIVE_VALUE:
case BASEPROPERTY_EFFECTIVE_MAX:
case BASEPROPERTY_EFFECTIVE_MIN:
case BASEPROPERTY_FORMATKEY:
case BASEPROPERTY_FORMATSSUPPLIER:
// (void)
break;
default : aReturn = UnoControlModel::ImplGetDefaultValue( nPropId ); break;
}
return aReturn;
}
// -------------------------------------------------------------------
::cppu::IPropertyArrayHelper& UnoControlFormattedFieldModel::getInfoHelper()
{
static UnoPropertyArrayHelper* pHelper = NULL;
if ( !pHelper )
{
Sequence<sal_Int32> aIDs = ImplGetPropertyIds();
pHelper = new UnoPropertyArrayHelper( aIDs );
}
return *pHelper;
}
// beans::XMultiPropertySet
// -------------------------------------------------------------------
Reference< XPropertySetInfo > UnoControlFormattedFieldModel::getPropertySetInfo( ) throw(RuntimeException)
{
static Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
// ===================================================================
// = UnoFormattedFieldControl
// ===================================================================
// -------------------------------------------------------------------
UnoFormattedFieldControl::UnoFormattedFieldControl()
{
}
// -------------------------------------------------------------------
::rtl::OUString UnoFormattedFieldControl::GetComponentServiceName()
{
return ::rtl::OUString::createFromAscii( "FormattedField" );
}
// -------------------------------------------------------------------
void UnoFormattedFieldControl::textChanged(const TextEvent& e) throw(RuntimeException)
{
Reference< XVclWindowPeer > xPeer(getPeer(), UNO_QUERY);
OSL_ENSURE(xPeer.is(), "UnoFormattedFieldControl::textChanged : what kind of peer do I have ?");
::rtl::OUString sTextPropertyName = GetPropertyName( BASEPROPERTY_TEXT );
ImplSetPropertyValue( sTextPropertyName, xPeer->getProperty( sTextPropertyName ), sal_False );
::rtl::OUString sEffectiveValue = GetPropertyName( BASEPROPERTY_EFFECTIVE_VALUE );
ImplSetPropertyValue( sEffectiveValue, xPeer->getProperty( sEffectiveValue ), sal_False );
if ( GetTextListeners().getLength() )
GetTextListeners().textChanged( e );
}
//........................................................................
} // namespace toolkit
//........................................................................
<|endoftext|> |
<commit_before>// Original Author: Brian Bockelman
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ZipLZ4.h"
#include "lz4.h"
#include "lz4hc.h"
#include <stdio.h>
#include <cinttypes>
#include <cstdint>
#include <cstring>
#include <ROOT/RConfig.h>
// Pulled from liblz4; upstream library explicitly exposes the symbol but the default build
// excludes the header.
typedef unsigned long long XXH64_hash_t;
typedef struct {
unsigned char digest[8];
} XXH64_canonical_t;
#ifdef BUILTIN_LZ4
#define XXH64 LZ4_XXH64
#define XXH64_canonicalFromHash LZ4_XXH64_canonicalFromHash
#define XXH64_hashFromCanonical LZ4_XXH64_hashFromCanonical
#endif
extern "C" XXH64_hash_t XXH64(const void *input, size_t length, unsigned long long seed);
extern "C" void XXH64_canonicalFromHash(XXH64_canonical_t *dst, XXH64_hash_t hash);
extern "C" XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t *src);
// Header consists of:
// - 2 byte identifier "L4"
// - 1 byte LZ4 version string.
// - 3 bytes of uncompressed size
// - 3 bytes of compressed size
// - 8 byte checksum using xxhash 64.
static const int kChecksumOffset = 2 + 1 + 3 + 3;
static const int kChecksumSize = sizeof(XXH64_canonical_t);
static const int kHeaderSize = kChecksumOffset + kChecksumSize;
void R__zipLZ4(int cxlevel, int *srcsize, char *src, int *tgtsize, char *tgt, int *irep)
{
int LZ4_version = LZ4_versionNumber();
uint64_t out_size; /* compressed size */
uint64_t in_size = (unsigned)(*srcsize);
*irep = 0;
if (R__unlikely(*tgtsize <= 0)) {
return;
}
// Refuse to compress more than 16MB at a time -- we are only allowed 3 bytes for size info.
if (R__unlikely(*srcsize > 0xffffff || *srcsize < 0)) {
return;
}
int returnStatus;
if (cxlevel > 9) {
cxlevel = 9;
}
if (cxlevel >= 4) {
returnStatus = LZ4_compress_HC(src, &tgt[kHeaderSize], *srcsize, *tgtsize - kHeaderSize, cxlevel);
} else {
returnStatus = LZ4_compress_default(src, &tgt[kHeaderSize], *srcsize, *tgtsize - kHeaderSize);
}
if (R__unlikely(returnStatus == 0)) { /* LZ4 compression failed */
return;
}
XXH64_hash_t checksumResult = XXH64(tgt + kHeaderSize, returnStatus, 0);
tgt[0] = 'L';
tgt[1] = '4';
tgt[2] = (LZ4_version / (100 * 100));
out_size = returnStatus + kChecksumSize; /* compressed size, including the checksum. */
// NOTE: these next 6 bytes are required from the ROOT compressed buffer format;
// upper layers will assume they are laid out in a specific manner.
tgt[3] = (char)(out_size & 0xff);
tgt[4] = (char)((out_size >> 8) & 0xff);
tgt[5] = (char)((out_size >> 16) & 0xff);
tgt[6] = (char)(in_size & 0xff); /* decompressed size */
tgt[7] = (char)((in_size >> 8) & 0xff);
tgt[8] = (char)((in_size >> 16) & 0xff);
// Write out checksum.
XXH64_canonicalFromHash(reinterpret_cast<XXH64_canonical_t *>(tgt + kChecksumOffset), checksumResult);
*irep = (int)returnStatus + kHeaderSize;
}
void R__unzipLZ4(int *srcsize, unsigned char *src, int *tgtsize, unsigned char *tgt, int *irep)
{
// NOTE: We don't check that srcsize / tgtsize is reasonable or within the ROOT-imposed limits.
// This is assumed to be handled by the upper layers.
int LZ4_version = LZ4_versionNumber() / (100 * 100);
*irep = 0;
if (R__unlikely(src[0] != 'L' || src[1] != '4')) {
fprintf(stderr, "R__unzipLZ4: algorithm run against buffer with incorrect header (got %d%d; expected %d%d).\n",
src[0], src[1], 'L', '4');
return;
}
if (R__unlikely(src[2] != LZ4_version)) {
fprintf(stderr,
"R__unzipLZ4: This version of LZ4 is incompatible with the on-disk version (got %d; expected %d).\n",
src[2], LZ4_version);
return;
}
int inputBufferSize = *srcsize - kHeaderSize;
// TODO: The checksum followed by the decompression means we iterate through the buffer twice.
// We should perform some performance tests to see whether we can interleave the two -- i.e., at
// what size of chunks does interleaving (avoiding two fetches from RAM) improve enough for the
// extra function call costs? NOTE that ROOT limits the buffer size to 16MB.
XXH64_hash_t checksumResult = XXH64(src + kHeaderSize, inputBufferSize, 0);
XXH64_hash_t checksumFromFile =
XXH64_hashFromCanonical(reinterpret_cast<XXH64_canonical_t *>(src + kChecksumOffset));
if (R__unlikely(checksumFromFile != checksumResult)) {
fprintf(
stderr,
"R__unzipLZ4: Buffer corruption error! Calculated checksum %llu; checksum calculated in the file was %llu.\n",
checksumResult, checksumFromFile);
return;
}
int returnStatus = LZ4_decompress_safe((char *)(&src[kHeaderSize]), (char *)(tgt), inputBufferSize, *tgtsize);
if (R__unlikely(returnStatus < 0)) {
fprintf(stderr, "R__unzipLZ4: error in decompression around byte %d out of maximum %d.\n", -returnStatus,
*tgtsize);
return;
}
*irep = returnStatus;
}
<commit_msg>Use our own xxHash instead of the one bundled in LZ4<commit_after>// Original Author: Brian Bockelman
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ZipLZ4.h"
#include "ROOT/RConfig.h"
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <lz4.h>
#include <lz4hc.h>
#include <xxhash.h>
// Header consists of:
// - 2 byte identifier "L4"
// - 1 byte LZ4 version string.
// - 3 bytes of uncompressed size
// - 3 bytes of compressed size
// - 8 byte checksum using xxhash 64.
static const int kChecksumOffset = 2 + 1 + 3 + 3;
static const int kChecksumSize = sizeof(XXH64_canonical_t);
static const int kHeaderSize = kChecksumOffset + kChecksumSize;
void R__zipLZ4(int cxlevel, int *srcsize, char *src, int *tgtsize, char *tgt, int *irep)
{
int LZ4_version = LZ4_versionNumber();
uint64_t out_size; /* compressed size */
uint64_t in_size = (unsigned)(*srcsize);
*irep = 0;
if (R__unlikely(*tgtsize <= 0)) {
return;
}
// Refuse to compress more than 16MB at a time -- we are only allowed 3 bytes for size info.
if (R__unlikely(*srcsize > 0xffffff || *srcsize < 0)) {
return;
}
int returnStatus;
if (cxlevel > 9) {
cxlevel = 9;
}
if (cxlevel >= 4) {
returnStatus = LZ4_compress_HC(src, &tgt[kHeaderSize], *srcsize, *tgtsize - kHeaderSize, cxlevel);
} else {
returnStatus = LZ4_compress_default(src, &tgt[kHeaderSize], *srcsize, *tgtsize - kHeaderSize);
}
if (R__unlikely(returnStatus == 0)) { /* LZ4 compression failed */
return;
}
XXH64_hash_t checksumResult = XXH64(tgt + kHeaderSize, returnStatus, 0);
tgt[0] = 'L';
tgt[1] = '4';
tgt[2] = (LZ4_version / (100 * 100));
out_size = returnStatus + kChecksumSize; /* compressed size, including the checksum. */
// NOTE: these next 6 bytes are required from the ROOT compressed buffer format;
// upper layers will assume they are laid out in a specific manner.
tgt[3] = (char)(out_size & 0xff);
tgt[4] = (char)((out_size >> 8) & 0xff);
tgt[5] = (char)((out_size >> 16) & 0xff);
tgt[6] = (char)(in_size & 0xff); /* decompressed size */
tgt[7] = (char)((in_size >> 8) & 0xff);
tgt[8] = (char)((in_size >> 16) & 0xff);
// Write out checksum.
XXH64_canonicalFromHash(reinterpret_cast<XXH64_canonical_t *>(tgt + kChecksumOffset), checksumResult);
*irep = (int)returnStatus + kHeaderSize;
}
void R__unzipLZ4(int *srcsize, unsigned char *src, int *tgtsize, unsigned char *tgt, int *irep)
{
// NOTE: We don't check that srcsize / tgtsize is reasonable or within the ROOT-imposed limits.
// This is assumed to be handled by the upper layers.
int LZ4_version = LZ4_versionNumber() / (100 * 100);
*irep = 0;
if (R__unlikely(src[0] != 'L' || src[1] != '4')) {
fprintf(stderr, "R__unzipLZ4: algorithm run against buffer with incorrect header (got %d%d; expected %d%d).\n",
src[0], src[1], 'L', '4');
return;
}
if (R__unlikely(src[2] != LZ4_version)) {
fprintf(stderr,
"R__unzipLZ4: This version of LZ4 is incompatible with the on-disk version (got %d; expected %d).\n",
src[2], LZ4_version);
return;
}
int inputBufferSize = *srcsize - kHeaderSize;
// TODO: The checksum followed by the decompression means we iterate through the buffer twice.
// We should perform some performance tests to see whether we can interleave the two -- i.e., at
// what size of chunks does interleaving (avoiding two fetches from RAM) improve enough for the
// extra function call costs? NOTE that ROOT limits the buffer size to 16MB.
XXH64_hash_t checksumResult = XXH64(src + kHeaderSize, inputBufferSize, 0);
XXH64_hash_t checksumFromFile =
XXH64_hashFromCanonical(reinterpret_cast<XXH64_canonical_t *>(src + kChecksumOffset));
if (R__unlikely(checksumFromFile != checksumResult)) {
fprintf(
stderr,
"R__unzipLZ4: Buffer corruption error! Calculated checksum %llu; checksum calculated in the file was %llu.\n",
checksumResult, checksumFromFile);
return;
}
int returnStatus = LZ4_decompress_safe((char *)(&src[kHeaderSize]), (char *)(tgt), inputBufferSize, *tgtsize);
if (R__unlikely(returnStatus < 0)) {
fprintf(stderr, "R__unzipLZ4: error in decompression around byte %d out of maximum %d.\n", -returnStatus,
*tgtsize);
return;
}
*irep = returnStatus;
}
<|endoftext|> |
<commit_before>#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/BasicBlock.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/PassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/IRBuilder.h"
#include "llvm/DebugInfo.h"
#include <sstream>
#include <set>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include "accept.h"
using namespace llvm;
namespace {
// Command-line flags.
cl::opt<bool> optRelax ("accept-relax",
cl::desc("ACCEPT: enable relaxations"));
struct ACCEPTPass : public FunctionPass {
static char ID;
Constant *blockCountFunction;
Module *module;
std::map<int, int> relaxConfig; // ident -> param
std::map<int, std::string> configDesc; // ident -> description
int opportunityId;
raw_fd_ostream *log;
std::map<Function*, DISubprogram> funcDebugInfo;
ApproxInfo *AI;
ACCEPTPass() : FunctionPass(ID) {
module = 0;
opportunityId = 0;
log = 0;
}
virtual void getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<LoopInfo>();
Info.addRequired<ApproxInfo>();
if (acceptUseProfile)
Info.addRequired<ProfileInfo>();
}
bool shouldSkipFunc(Function &F) {
if (F.getName().startswith("accept_")) {
return true;
}
// If we're missing debug info for the function, give up.
if (!funcDebugInfo.count(&F)) {
return false;
}
DISubprogram funcInfo = funcDebugInfo[&F];
StringRef filename = funcInfo.getFilename();
if (filename.startswith("/usr/include/") ||
filename.startswith("/usr/lib/"))
return false; // true;
if (AI->markerAtLine(filename, funcInfo.getLineNumber()) == markerForbid) {
return true;
}
return false;
}
virtual bool runOnFunction(Function &F) {
AI = &getAnalysis<ApproxInfo>();
log = AI->log;
// Skip optimizing functions that seem to be in standard libraries.
if (shouldSkipFunc(F))
return false;
return optimizeLoops(F);
}
// Find the debug info for every "subprogram" (i.e., function).
// Inspired by DebugInfoFinder::procuessModule, but actually examines
// multiple compilation units.
void collectFuncDebug(Module &M) {
NamedMDNode *cuNodes = module->getNamedMetadata("llvm.dbg.cu");
if (!cuNodes) {
errs() << "ACCEPT: debug information not available\n";
return;
}
for (unsigned i = 0; i != cuNodes->getNumOperands(); ++i) {
DICompileUnit cu(cuNodes->getOperand(i));
DIArray spa = cu.getSubprograms();
for (unsigned j = 0; j != spa.getNumElements(); ++j) {
collectSubprogram(DISubprogram(spa.getElement(j)));
}
DIArray tya = cu.getRetainedTypes();
for (unsigned j = 0; j != tya.getNumElements(); ++j) {
collectType(DIType(spa.getElement(i)));
}
}
}
void collectSubprogram(DISubprogram sp) {
if (Function *func = sp.getFunction()) {
funcDebugInfo[func] = sp;
}
}
void collectType(DIType ty) {
if (ty.isCompositeType()) {
DICompositeType cty(ty);
collectType(cty.getTypeDerivedFrom());
DIArray da = cty.getTypeArray();
for (unsigned i = 0; i != da.getNumElements(); ++i) {
DIDescriptor d = da.getElement(i);
if (d.isType())
collectType(DIType(d));
else if (d.isSubprogram())
collectSubprogram(DISubprogram(d));
}
}
}
virtual bool doInitialization(Module &M) {
module = &M;
if (optRelax)
loadRelaxConfig();
collectFuncDebug(M);
return false;
}
virtual bool doFinalization(Module &M) {
if (!optRelax)
dumpRelaxConfig();
return false;
}
IntegerType *getNativeIntegerType() {
DataLayout layout(module->getDataLayout());
return Type::getIntNTy(module->getContext(),
layout.getPointerSizeInBits());
}
virtual const char *getPassName() const {
return "ACCEPT relaxation";
}
/**** RELAXATION CONFIGURATION ***/
typedef enum {
rkPerforate
} relaxKind;
void dumpRelaxConfig() {
std::ofstream configFile("accept_config.txt", std::ios_base::out);
for (std::map<int, int>::iterator i = relaxConfig.begin();
i != relaxConfig.end(); ++i) {
configFile << i->first << " "
<< i->second << "\n";
}
configFile.close();
std::ofstream descFile("accept_config_desc.txt", std::ios_base::out);
for (std::map<int, std::string>::iterator i = configDesc.begin();
i != configDesc.end(); ++i) {
descFile << i->first << " "
<< i->second << "\n";
}
descFile.close();
}
void loadRelaxConfig() {
std::ifstream configFile("accept_config.txt");;
if (!configFile.good()) {
errs() << "no config file; no optimizations will occur\n";
return;
}
while (configFile.good()) {
int ident;
int param;
configFile >> ident >> param;
relaxConfig[ident] = param;
}
configFile.close();
}
/**** EXPERIMENT ****/
// Attempt to optimize the loops in a function.
bool optimizeLoops(Function &F) {
int perforatedLoops = 0;
LoopInfo &loopInfo = getAnalysis<LoopInfo>();
for (LoopInfo::iterator li = loopInfo.begin();
li != loopInfo.end(); ++li) {
Loop *loop = *li;
optimizeLoopsHelper(loop, perforatedLoops);
}
return perforatedLoops > 0;
}
void optimizeLoopsHelper(Loop *loop, int &perforatedLoops) {
std::vector<Loop*> subLoops = loop->getSubLoops();
for (int i = 0; i < subLoops.size(); ++i)
// Recurse into subloops.
optimizeLoopsHelper(subLoops[i], perforatedLoops);
if (tryToOptimizeLoop(loop, opportunityId))
++perforatedLoops;
++opportunityId;;
}
// Assess whether a loop can be optimized and, if so, log some messages and
// update the configuration map. If optimization is turned on, the
// configuration map will be used to actually transform the loop. Returns a
// boolean indicating whether the code was changed (i.e., the loop
// perforated).
bool tryToOptimizeLoop(Loop *loop, int id) {
bool transformed = false;
std::stringstream ss;
ss << "loop at "
<< srcPosDesc(*module, loop->getHeader()->begin()->getDebugLoc());
std::string loopName = ss.str();
*log << "---\n" << loopName << "\n";
// We only consider loops for which there is a header (condition), a
// latch (increment, in "for"), and a preheader (initialization).
if (!loop->getHeader() || !loop->getLoopLatch()
|| !loop->getLoopPreheader()) {
*log << "loop not in perforatable form\n";
return false;
}
// Skip array constructor loops manufactured by Clang.
if (loop->getHeader()->getName().startswith("arrayctor.loop")) {
*log << "array constructor\n";
return false;
}
// Skip empty-body loops (where perforation would do nothing anyway).
if (loop->getNumBlocks() == 2
&& loop->getHeader() != loop->getLoopLatch()) {
BasicBlock *latch = loop->getLoopLatch();
if (&(latch->front()) == &(latch->back())) {
*log << "empty body\n";
return false;
}
}
/*
if (acceptUseProfile) {
ProfileInfo &PI = getAnalysis<ProfileInfo>();
double trips = PI.getExecutionCount(loop->getHeader());
*log << "trips: " << trips << "\n";
}
*/
// Determine whether this is a for-like or while-like loop. This informs
// the heuristic that determines which parts of the loop to perforate.
bool isForLike = false;
if (loop->getHeader()->getName().startswith("for.cond")) {
*log << "for-like loop\n";
isForLike = true;
} else {
*log << "while-like loop\n";
}
// Check whether the body of this loop is elidable (precise-pure).
std::set<BasicBlock*> loopBlocks;
for (Loop::block_iterator bi = loop->block_begin();
bi != loop->block_end(); ++bi) {
if (*bi == loop->getHeader()) {
// Even in perforated loops, the header gets executed every time. So we
// don't check it.
continue;
} else if (isForLike && *bi == loop->getLoopLatch()) {
// When perforating for-like loops, we also execute the latch each
// time.
continue;
}
loopBlocks.insert(*bi);
}
std::set<Instruction*> blockers = AI->preciseEscapeCheck(loopBlocks);
*log << "blockers: " << blockers.size() << "\n";
for (std::set<Instruction*>::iterator i = blockers.begin();
i != blockers.end(); ++i) {
*log << " * " << instDesc(*module, *i) << "\n";
}
if (!blockers.size()) {
*log << "can perforate loop " << id << "\n";
if (optRelax) {
int param = relaxConfig[id];
if (param) {
*log << "perforating with factor 2^" << param << "\n";
perforateLoop(loop, param, isForLike);
transformed = true;
}
} else {
relaxConfig[id] = 0;
configDesc[id] = loopName;
}
}
return transformed;
}
// Transform a loop to skip iterations.
// The loop should already be validated as perforatable, but checks will be
// performed nonetheless to ensure safety.
void perforateLoop(Loop *loop, int logfactor, bool isForLike) {
// Check whether this loop is perforatable.
// First, check for required blocks.
if (!loop->getHeader() || !loop->getLoopLatch()
|| !loop->getLoopPreheader() || !loop->getExitBlock()) {
errs() << "malformed loop\n";
return;
}
// Next, make sure the header (condition block) ends with a body/exit
// conditional branch.
BranchInst *condBranch = dyn_cast<BranchInst>(
loop->getHeader()->getTerminator()
);
if (!condBranch || condBranch->getNumSuccessors() != 2) {
errs() << "malformed loop condition\n";
return;
}
BasicBlock *bodyBlock;
if (condBranch->getSuccessor(0) == loop->getExitBlock()) {
bodyBlock = condBranch->getSuccessor(1);
} else if (condBranch->getSuccessor(1) == loop->getExitBlock()) {
bodyBlock = condBranch->getSuccessor(0);
} else {
errs() << "loop condition does not exit\n";
return;
}
// Get the shortcut for the destination. In for-like loop perforation, we
// shortcut to the latch (increment block). In while-like perforation, we
// jump to the header (condition block).
BasicBlock *shortcutDest;
if (isForLike) {
shortcutDest = loop->getLoopLatch();
} else {
shortcutDest = loop->getHeader();
}
IRBuilder<> builder(module->getContext());
Value *result;
// Allocate stack space for the counter.
// LLVM "alloca" instructions go in the function's entry block. Otherwise,
// they have to adjust the frame size dynamically (and, in my experience,
// can actually segfault!). And we only want one of these per static loop
// anyway.
builder.SetInsertPoint(
loop->getLoopPreheader()->getParent()->getEntryBlock().begin()
);
IntegerType *nativeInt = getNativeIntegerType();
AllocaInst *counterAlloca = builder.CreateAlloca(
nativeInt,
0,
"accept_counter"
);
// Initialize the counter in the preheader.
builder.SetInsertPoint(loop->getLoopPreheader()->getTerminator());
builder.CreateStore(
ConstantInt::get(nativeInt, 0, false),
counterAlloca
);
// Increment the counter in the latch.
builder.SetInsertPoint(loop->getLoopLatch()->getTerminator());
result = builder.CreateLoad(
counterAlloca,
"accept_tmp"
);
result = builder.CreateAdd(
result,
ConstantInt::get(nativeInt, 1, false),
"accept_inc"
);
builder.CreateStore(
result,
counterAlloca
);
// Get the first body block.
// Check the counter before the loop's body.
BasicBlock *checkBlock = BasicBlock::Create(
module->getContext(),
"accept_cond",
bodyBlock->getParent(),
bodyBlock
);
builder.SetInsertPoint(checkBlock);
result = builder.CreateLoad(
counterAlloca,
"accept_tmp"
);
// Check whether the low n bits of the counter are zero.
result = builder.CreateTrunc(
result,
Type::getIntNTy(module->getContext(), logfactor),
"accept_trunc"
);
result = builder.CreateIsNull(
result,
"accept_cmp"
);
result = builder.CreateCondBr(
result,
bodyBlock,
loop->getLoopLatch()
);
// Change the condition block to point to our new condition
// instead of the body.
condBranch->setSuccessor(0, checkBlock);
}
};
char ACCEPTPass::ID = 0;
}
FunctionPass *llvm::createAcceptTransformPass() {
return new ACCEPTPass();
}
<commit_msg>don't perforate loops with control flow<commit_after>#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/BasicBlock.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/PassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/IRBuilder.h"
#include "llvm/DebugInfo.h"
#include <sstream>
#include <set>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include "accept.h"
using namespace llvm;
namespace {
// Command-line flags.
cl::opt<bool> optRelax ("accept-relax",
cl::desc("ACCEPT: enable relaxations"));
struct ACCEPTPass : public FunctionPass {
static char ID;
Constant *blockCountFunction;
Module *module;
std::map<int, int> relaxConfig; // ident -> param
std::map<int, std::string> configDesc; // ident -> description
int opportunityId;
raw_fd_ostream *log;
std::map<Function*, DISubprogram> funcDebugInfo;
ApproxInfo *AI;
ACCEPTPass() : FunctionPass(ID) {
module = 0;
opportunityId = 0;
log = 0;
}
virtual void getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<LoopInfo>();
Info.addRequired<ApproxInfo>();
if (acceptUseProfile)
Info.addRequired<ProfileInfo>();
}
bool shouldSkipFunc(Function &F) {
if (F.getName().startswith("accept_")) {
return true;
}
// If we're missing debug info for the function, give up.
if (!funcDebugInfo.count(&F)) {
return false;
}
DISubprogram funcInfo = funcDebugInfo[&F];
StringRef filename = funcInfo.getFilename();
if (filename.startswith("/usr/include/") ||
filename.startswith("/usr/lib/"))
return false; // true;
if (AI->markerAtLine(filename, funcInfo.getLineNumber()) == markerForbid) {
return true;
}
return false;
}
virtual bool runOnFunction(Function &F) {
AI = &getAnalysis<ApproxInfo>();
log = AI->log;
// Skip optimizing functions that seem to be in standard libraries.
if (shouldSkipFunc(F))
return false;
return optimizeLoops(F);
}
// Find the debug info for every "subprogram" (i.e., function).
// Inspired by DebugInfoFinder::procuessModule, but actually examines
// multiple compilation units.
void collectFuncDebug(Module &M) {
NamedMDNode *cuNodes = module->getNamedMetadata("llvm.dbg.cu");
if (!cuNodes) {
errs() << "ACCEPT: debug information not available\n";
return;
}
for (unsigned i = 0; i != cuNodes->getNumOperands(); ++i) {
DICompileUnit cu(cuNodes->getOperand(i));
DIArray spa = cu.getSubprograms();
for (unsigned j = 0; j != spa.getNumElements(); ++j) {
collectSubprogram(DISubprogram(spa.getElement(j)));
}
DIArray tya = cu.getRetainedTypes();
for (unsigned j = 0; j != tya.getNumElements(); ++j) {
collectType(DIType(spa.getElement(i)));
}
}
}
void collectSubprogram(DISubprogram sp) {
if (Function *func = sp.getFunction()) {
funcDebugInfo[func] = sp;
}
}
void collectType(DIType ty) {
if (ty.isCompositeType()) {
DICompositeType cty(ty);
collectType(cty.getTypeDerivedFrom());
DIArray da = cty.getTypeArray();
for (unsigned i = 0; i != da.getNumElements(); ++i) {
DIDescriptor d = da.getElement(i);
if (d.isType())
collectType(DIType(d));
else if (d.isSubprogram())
collectSubprogram(DISubprogram(d));
}
}
}
virtual bool doInitialization(Module &M) {
module = &M;
if (optRelax)
loadRelaxConfig();
collectFuncDebug(M);
return false;
}
virtual bool doFinalization(Module &M) {
if (!optRelax)
dumpRelaxConfig();
return false;
}
IntegerType *getNativeIntegerType() {
DataLayout layout(module->getDataLayout());
return Type::getIntNTy(module->getContext(),
layout.getPointerSizeInBits());
}
virtual const char *getPassName() const {
return "ACCEPT relaxation";
}
/**** RELAXATION CONFIGURATION ***/
typedef enum {
rkPerforate
} relaxKind;
void dumpRelaxConfig() {
std::ofstream configFile("accept_config.txt", std::ios_base::out);
for (std::map<int, int>::iterator i = relaxConfig.begin();
i != relaxConfig.end(); ++i) {
configFile << i->first << " "
<< i->second << "\n";
}
configFile.close();
std::ofstream descFile("accept_config_desc.txt", std::ios_base::out);
for (std::map<int, std::string>::iterator i = configDesc.begin();
i != configDesc.end(); ++i) {
descFile << i->first << " "
<< i->second << "\n";
}
descFile.close();
}
void loadRelaxConfig() {
std::ifstream configFile("accept_config.txt");;
if (!configFile.good()) {
errs() << "no config file; no optimizations will occur\n";
return;
}
while (configFile.good()) {
int ident;
int param;
configFile >> ident >> param;
relaxConfig[ident] = param;
}
configFile.close();
}
/**** EXPERIMENT ****/
// Attempt to optimize the loops in a function.
bool optimizeLoops(Function &F) {
int perforatedLoops = 0;
LoopInfo &loopInfo = getAnalysis<LoopInfo>();
for (LoopInfo::iterator li = loopInfo.begin();
li != loopInfo.end(); ++li) {
Loop *loop = *li;
optimizeLoopsHelper(loop, perforatedLoops);
}
return perforatedLoops > 0;
}
void optimizeLoopsHelper(Loop *loop, int &perforatedLoops) {
std::vector<Loop*> subLoops = loop->getSubLoops();
for (int i = 0; i < subLoops.size(); ++i)
// Recurse into subloops.
optimizeLoopsHelper(subLoops[i], perforatedLoops);
if (tryToOptimizeLoop(loop, opportunityId))
++perforatedLoops;
++opportunityId;;
}
// Assess whether a loop can be optimized and, if so, log some messages and
// update the configuration map. If optimization is turned on, the
// configuration map will be used to actually transform the loop. Returns a
// boolean indicating whether the code was changed (i.e., the loop
// perforated).
bool tryToOptimizeLoop(Loop *loop, int id) {
bool transformed = false;
std::stringstream ss;
ss << "loop at "
<< srcPosDesc(*module, loop->getHeader()->begin()->getDebugLoc());
std::string loopName = ss.str();
*log << "---\n" << loopName << "\n";
// We only consider loops for which there is a header (condition), a
// latch (increment, in "for"), and a preheader (initialization).
if (!loop->getHeader() || !loop->getLoopLatch()
|| !loop->getLoopPreheader()) {
*log << "loop not in perforatable form\n";
return false;
}
// Skip array constructor loops manufactured by Clang.
if (loop->getHeader()->getName().startswith("arrayctor.loop")) {
*log << "array constructor\n";
return false;
}
// Skip empty-body loops (where perforation would do nothing anyway).
if (loop->getNumBlocks() == 2
&& loop->getHeader() != loop->getLoopLatch()) {
BasicBlock *latch = loop->getLoopLatch();
if (&(latch->front()) == &(latch->back())) {
*log << "empty body\n";
return false;
}
}
/*
if (acceptUseProfile) {
ProfileInfo &PI = getAnalysis<ProfileInfo>();
double trips = PI.getExecutionCount(loop->getHeader());
*log << "trips: " << trips << "\n";
}
*/
// Determine whether this is a for-like or while-like loop. This informs
// the heuristic that determines which parts of the loop to perforate.
bool isForLike = false;
if (loop->getHeader()->getName().startswith("for.cond")) {
*log << "for-like loop\n";
isForLike = true;
} else {
*log << "while-like loop\n";
}
// Get the body blocks of the loop: those that will not be executed during
// some iterations of a perforated loop.
std::set<BasicBlock*> bodyBlocks;
for (Loop::block_iterator bi = loop->block_begin();
bi != loop->block_end(); ++bi) {
if (*bi == loop->getHeader()) {
// Even in perforated loops, the header gets executed every time. So we
// don't check it.
continue;
} else if (isForLike && *bi == loop->getLoopLatch()) {
// When perforating for-like loops, we also execute the latch each
// time.
continue;
}
bodyBlocks.insert(*bi);
}
// Check for control flow in the loop body. We don't perforate anything
// with a break, continue, return, etc.
for (std::set<BasicBlock*>::iterator i = bodyBlocks.begin();
i != bodyBlocks.end(); ++i) {
if (loop->isLoopExiting(*i)) {
*log << "contains loop exit\n";
return false;
}
}
// Check whether the body of this loop is elidable (precise-pure).
std::set<Instruction*> blockers = AI->preciseEscapeCheck(bodyBlocks);
*log << "blockers: " << blockers.size() << "\n";
for (std::set<Instruction*>::iterator i = blockers.begin();
i != blockers.end(); ++i) {
*log << " * " << instDesc(*module, *i) << "\n";
}
if (!blockers.size()) {
*log << "can perforate loop " << id << "\n";
if (optRelax) {
int param = relaxConfig[id];
if (param) {
*log << "perforating with factor 2^" << param << "\n";
perforateLoop(loop, param, isForLike);
transformed = true;
}
} else {
relaxConfig[id] = 0;
configDesc[id] = loopName;
}
}
return transformed;
}
// Transform a loop to skip iterations.
// The loop should already be validated as perforatable, but checks will be
// performed nonetheless to ensure safety.
void perforateLoop(Loop *loop, int logfactor, bool isForLike) {
// Check whether this loop is perforatable.
// First, check for required blocks.
if (!loop->getHeader() || !loop->getLoopLatch()
|| !loop->getLoopPreheader() || !loop->getExitBlock()) {
errs() << "malformed loop\n";
return;
}
// Next, make sure the header (condition block) ends with a body/exit
// conditional branch.
BranchInst *condBranch = dyn_cast<BranchInst>(
loop->getHeader()->getTerminator()
);
if (!condBranch || condBranch->getNumSuccessors() != 2) {
errs() << "malformed loop condition\n";
return;
}
BasicBlock *bodyBlock;
if (condBranch->getSuccessor(0) == loop->getExitBlock()) {
bodyBlock = condBranch->getSuccessor(1);
} else if (condBranch->getSuccessor(1) == loop->getExitBlock()) {
bodyBlock = condBranch->getSuccessor(0);
} else {
errs() << "loop condition does not exit\n";
return;
}
// Get the shortcut for the destination. In for-like loop perforation, we
// shortcut to the latch (increment block). In while-like perforation, we
// jump to the header (condition block).
BasicBlock *shortcutDest;
if (isForLike) {
shortcutDest = loop->getLoopLatch();
} else {
shortcutDest = loop->getHeader();
}
IRBuilder<> builder(module->getContext());
Value *result;
// Allocate stack space for the counter.
// LLVM "alloca" instructions go in the function's entry block. Otherwise,
// they have to adjust the frame size dynamically (and, in my experience,
// can actually segfault!). And we only want one of these per static loop
// anyway.
builder.SetInsertPoint(
loop->getLoopPreheader()->getParent()->getEntryBlock().begin()
);
IntegerType *nativeInt = getNativeIntegerType();
AllocaInst *counterAlloca = builder.CreateAlloca(
nativeInt,
0,
"accept_counter"
);
// Initialize the counter in the preheader.
builder.SetInsertPoint(loop->getLoopPreheader()->getTerminator());
builder.CreateStore(
ConstantInt::get(nativeInt, 0, false),
counterAlloca
);
// Increment the counter in the latch.
builder.SetInsertPoint(loop->getLoopLatch()->getTerminator());
result = builder.CreateLoad(
counterAlloca,
"accept_tmp"
);
result = builder.CreateAdd(
result,
ConstantInt::get(nativeInt, 1, false),
"accept_inc"
);
builder.CreateStore(
result,
counterAlloca
);
// Get the first body block.
// Check the counter before the loop's body.
BasicBlock *checkBlock = BasicBlock::Create(
module->getContext(),
"accept_cond",
bodyBlock->getParent(),
bodyBlock
);
builder.SetInsertPoint(checkBlock);
result = builder.CreateLoad(
counterAlloca,
"accept_tmp"
);
// Check whether the low n bits of the counter are zero.
result = builder.CreateTrunc(
result,
Type::getIntNTy(module->getContext(), logfactor),
"accept_trunc"
);
result = builder.CreateIsNull(
result,
"accept_cmp"
);
result = builder.CreateCondBr(
result,
bodyBlock,
loop->getLoopLatch()
);
// Change the condition block to point to our new condition
// instead of the body.
condBranch->setSuccessor(0, checkBlock);
}
};
char ACCEPTPass::ID = 0;
}
FunctionPass *llvm::createAcceptTransformPass() {
return new ACCEPTPass();
}
<|endoftext|> |
<commit_before>/***************************************************************************
copyright : (C) 2002 by Scott Wheeler
email : wheeler@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 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 *
***************************************************************************/
namespace TagLib {
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
template <class Key, class T>
template <class KeyP, class TP> class Map<Key, T>::MapPrivate : public RefCounter
{
public:
MapPrivate() : RefCounter() {}
MapPrivate(const std::map<KeyP, TP> &m) : RefCounter(), map(m) {}
std::map<KeyP, TP> map;
};
template <class Key, class T>
Map<Key, T>::Map()
{
d = new MapPrivate<Key, T>;
}
template <class Key, class T>
Map<Key, T>::Map(const Map<Key, T> &m) : d(m.d)
{
d->ref();
}
template <class Key, class T>
Map<Key, T>::~Map()
{
if(d->deref())
delete(d);
}
template <class Key, class T>
typename Map<Key, T>::Iterator Map<Key, T>::begin()
{
detach();
return d->map.begin();
}
template <class Key, class T>
typename Map<Key, T>::ConstIterator Map<Key, T>::begin() const
{
return d->map.begin();
}
template <class Key, class T>
typename Map<Key, T>::Iterator Map<Key, T>::end()
{
detach();
return d->map.end();
}
template <class Key, class T>
typename Map<Key, T>::ConstIterator Map<Key, T>::end() const
{
return d->map.end();
}
template <class Key, class T>
Map<Key, T> &Map<Key, T>::insert(const Key &key, const T &value)
{
detach();
std::pair<Key, T> item(key, value);
d->map.insert(item);
return *this;
}
template <class Key, class T>
Map<Key, T> &Map<Key, T>::clear()
{
detach();
d->map.clear();
return *this;
}
template <class Key, class T>
bool Map<Key, T>::isEmpty() const
{
return d->map.empty();
}
template <class Key, class T>
typename Map<Key, T>::Iterator Map<Key, T>::find(const Key &key)
{
detach();
return d->map.find(key);
}
template <class Key, class T>
typename Map<Key,T>::ConstIterator Map<Key, T>::find(const Key &key) const
{
return d->map.find(key);
}
template <class Key, class T>
bool Map<Key, T>::contains(const Key &key) const
{
return d->map.find(key) != d->map.end();
}
template <class Key, class T>
Map<Key, T> &Map<Key,T>::erase(Iterator it)
{
detach();
d->map.erase(it);
return *this;
}
template <class Key, class T>
Map<Key, T> &Map<Key,T>::erase(const Key &key)
{
detach();
d->map.erase(find(key));
return *this;
}
template <class Key, class T>
TagLib::uint Map<Key, T>::size() const
{
return d->map.size();
}
template <class Key, class T>
const T &Map<Key, T>::operator[](const Key &key) const
{
return d->map[key];
}
template <class Key, class T>
T &Map<Key, T>::operator[](const Key &key)
{
detach();
return d->map[key];
}
template <class Key, class T>
Map<Key, T> &Map<Key, T>::operator=(const Map<Key, T> &m)
{
if(&m == this)
return *this;
if(d->deref())
delete(d);
d = m.d;
d->ref();
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
template <class Key, class T>
void Map<Key, T>::detach()
{
if(d->count() > 1) {
d->deref();
d = new MapPrivate<Key, T>(d->map);
}
}
} // namespace TagLib
<commit_msg>Don't try to erase a key that isn't there.<commit_after>/***************************************************************************
copyright : (C) 2002 by Scott Wheeler
email : wheeler@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 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 *
***************************************************************************/
namespace TagLib {
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
template <class Key, class T>
template <class KeyP, class TP> class Map<Key, T>::MapPrivate : public RefCounter
{
public:
MapPrivate() : RefCounter() {}
MapPrivate(const std::map<KeyP, TP> &m) : RefCounter(), map(m) {}
std::map<KeyP, TP> map;
};
template <class Key, class T>
Map<Key, T>::Map()
{
d = new MapPrivate<Key, T>;
}
template <class Key, class T>
Map<Key, T>::Map(const Map<Key, T> &m) : d(m.d)
{
d->ref();
}
template <class Key, class T>
Map<Key, T>::~Map()
{
if(d->deref())
delete(d);
}
template <class Key, class T>
typename Map<Key, T>::Iterator Map<Key, T>::begin()
{
detach();
return d->map.begin();
}
template <class Key, class T>
typename Map<Key, T>::ConstIterator Map<Key, T>::begin() const
{
return d->map.begin();
}
template <class Key, class T>
typename Map<Key, T>::Iterator Map<Key, T>::end()
{
detach();
return d->map.end();
}
template <class Key, class T>
typename Map<Key, T>::ConstIterator Map<Key, T>::end() const
{
return d->map.end();
}
template <class Key, class T>
Map<Key, T> &Map<Key, T>::insert(const Key &key, const T &value)
{
detach();
std::pair<Key, T> item(key, value);
d->map.insert(item);
return *this;
}
template <class Key, class T>
Map<Key, T> &Map<Key, T>::clear()
{
detach();
d->map.clear();
return *this;
}
template <class Key, class T>
bool Map<Key, T>::isEmpty() const
{
return d->map.empty();
}
template <class Key, class T>
typename Map<Key, T>::Iterator Map<Key, T>::find(const Key &key)
{
detach();
return d->map.find(key);
}
template <class Key, class T>
typename Map<Key,T>::ConstIterator Map<Key, T>::find(const Key &key) const
{
return d->map.find(key);
}
template <class Key, class T>
bool Map<Key, T>::contains(const Key &key) const
{
return d->map.find(key) != d->map.end();
}
template <class Key, class T>
Map<Key, T> &Map<Key,T>::erase(Iterator it)
{
detach();
d->map.erase(it);
return *this;
}
template <class Key, class T>
Map<Key, T> &Map<Key,T>::erase(const Key &key)
{
detach();
Iterator it = d->map.find(key);
if(it != d->map.end())
d->map.erase(it);
return *this;
}
template <class Key, class T>
TagLib::uint Map<Key, T>::size() const
{
return d->map.size();
}
template <class Key, class T>
const T &Map<Key, T>::operator[](const Key &key) const
{
return d->map[key];
}
template <class Key, class T>
T &Map<Key, T>::operator[](const Key &key)
{
detach();
return d->map[key];
}
template <class Key, class T>
Map<Key, T> &Map<Key, T>::operator=(const Map<Key, T> &m)
{
if(&m == this)
return *this;
if(d->deref())
delete(d);
d = m.d;
d->ref();
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
template <class Key, class T>
void Map<Key, T>::detach()
{
if(d->count() > 1) {
d->deref();
d = new MapPrivate<Key, T>(d->map);
}
}
} // namespace TagLib
<|endoftext|> |
<commit_before>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"
#include <sstream>
#define _STRING(x) #x
#define STRING(x) _STRING(x)
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name) _getcwd(name)
#endif
v8::Handle<v8::Array> __onexit;
void die(int code) {
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
exit(code);
}
v8::Handle<v8::String> read_file(const char* name) {
printf("%s",name);
FILE* file = fopen(name, "rb");
if (file == NULL) return v8::Handle<v8::String>();
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
void report_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
std::string tmp;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
ss >> tmp;
msgstring += tmp;
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
v8::String::Utf8Value sourceline(message->GetSourceLine());
msgstring += *sourceline;
msgstring += "\n";
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
msgstring += " ";
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
msgstring += "^";
}
msgstring += "\n";
}
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(msgstring.c_str());
fun->Call(context->ToObject(), 1, data);
}
int execute_file(const char * str) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = read_file(str);
if (source.IsEmpty()) {
printf("Error reading '%s'\n", str);
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
report_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr(str, '/');
if (end == NULL) {
end = strrchr(str, '\\');
}
if (end != NULL) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
report_exception(&try_catch);
return 1;
}
}
return 0;
}
int library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
return execute_file(path.c_str());
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = execute_file(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
die(args[0]->Int32Value());
return v8::Undefined();
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
int library_autoload() {
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (library(*name)) { return 1; }
}
return 0;
}
void init(char * cfg) {
int result = execute_file(cfg);
if (result) {
printf("Cannot load configuration, quitting...\n");
die(1);
}
result = library_autoload();
if (result) {
printf("Cannot load default libraries, quitting...\n");
die(1);
}
}
int main(int argc, char ** argv, char ** envp) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
__onexit = v8::Array::New();
context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
context->Global()->Set(JS_STR("global"), context->Global());
context->Global()->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, context->Global());
setup_io(context->Global());
#ifdef HAVE_MYSQL
setup_mysql(context->Global());
#endif
#ifdef HAVE_GD
setup_gd(context->Global());
#endif
char * cfg = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfg = argv[i+1];
argptr = 0;
i++;
}
}
init(cfg);
if (!argptr) {
// try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value name(pt);
int result = execute_file(*name);
if (result) { die(result); }
} else {
printf("Nothing to do.\n");
}
} else {
int result = execute_file(argv[argptr]);
if (result) { die(result); }
}
die(0);
}
<commit_msg>chdir, getcwd for msve<commit_after>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"
#include <sstream>
#define _STRING(x) #x
#define STRING(x) _STRING(x)
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit;
void die(int code) {
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
exit(code);
}
v8::Handle<v8::String> read_file(const char* name) {
printf("%s",name);
FILE* file = fopen(name, "rb");
if (file == NULL) return v8::Handle<v8::String>();
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
void report_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
std::string tmp;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
ss >> tmp;
msgstring += tmp;
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
v8::String::Utf8Value sourceline(message->GetSourceLine());
msgstring += *sourceline;
msgstring += "\n";
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
msgstring += " ";
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
msgstring += "^";
}
msgstring += "\n";
}
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(msgstring.c_str());
fun->Call(context->ToObject(), 1, data);
}
int execute_file(const char * str) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = read_file(str);
if (source.IsEmpty()) {
printf("Error reading '%s'\n", str);
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
report_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr(str, '/');
if (end == NULL) {
end = strrchr(str, '\\');
}
if (end != NULL) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
report_exception(&try_catch);
return 1;
}
}
return 0;
}
int library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
return execute_file(path.c_str());
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = execute_file(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
die(args[0]->Int32Value());
return v8::Undefined();
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
int library_autoload() {
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (library(*name)) { return 1; }
}
return 0;
}
void init(char * cfg) {
int result = execute_file(cfg);
if (result) {
printf("Cannot load configuration, quitting...\n");
die(1);
}
result = library_autoload();
if (result) {
printf("Cannot load default libraries, quitting...\n");
die(1);
}
}
int main(int argc, char ** argv, char ** envp) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
__onexit = v8::Array::New();
context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
context->Global()->Set(JS_STR("global"), context->Global());
context->Global()->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, context->Global());
setup_io(context->Global());
#ifdef HAVE_MYSQL
setup_mysql(context->Global());
#endif
#ifdef HAVE_GD
setup_gd(context->Global());
#endif
char * cfg = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfg = argv[i+1];
argptr = 0;
i++;
}
}
init(cfg);
if (!argptr) {
// try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value name(pt);
int result = execute_file(*name);
if (result) { die(result); }
} else {
printf("Nothing to do.\n");
}
} else {
int result = execute_file(argv[argptr]);
if (result) { die(result); }
}
die(0);
}
<|endoftext|> |
<commit_before>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#define _STRING(x) #x
#define STRING(x) _STRING(x)
#include <sstream>
#include <stdlib.h>
#include <v8.h>
#include <map>
#ifdef FASTCGI
# include <fcgi_stdio.h>
#endif
#include "js_system.h"
#include "js_io.h"
#include "js_socket.h"
#include "js_common.h"
#include "js_macros.h"
#include "js_cache.h"
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
#endif
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit; /* what to do on exit */
const char * cfgfile = NULL; /* config file */
const char * execfile = NULL; /* command-line specified file */
Cache cache;
int total = 0; /* fcgi debug */
void js_error(const char * message) {
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(message);
fun->Call(context->ToObject(), 1, data);
}
void js_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
msgstring += ss.str();
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
}
js_error(msgstring.c_str());
}
v8::Handle<v8::String> js_read(const char* name) {
std::string n = name;
std::string source = cache.getJS(n);
return JS_STR(source.c_str());
}
int js_execute(const char * str, bool change) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = js_read(str);
if (source.IsEmpty()) {
std::string s = "Error reading '";
s += str;
s += "'\n";
js_error(s.c_str());
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
js_exception(&try_catch);
return 1;
} else {
std::string oldcwd = getcwd(NULL, 0);
std::string newcwd = str;
size_t pos = newcwd.find_last_of('/');
if (pos == std::string::npos) { pos = newcwd.find_last_of('\\'); }
if (pos != std::string::npos && change) {
newcwd.erase(pos, newcwd.length()-pos);
chdir(newcwd.c_str());
}
v8::Handle<v8::Value> result = script->Run();
if (change) { chdir(oldcwd.c_str()); }
if (result.IsEmpty()) {
js_exception(&try_catch);
return 1;
}
}
return 0;
}
int js_library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
std::string error;
path += *pfx;
path += "/";
path += name;
if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
void * handle = cache.getHandle(path);
if (handle == NULL) {
error = "Cannot load shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
void (*func) (v8::Handle<v8::Object>);
func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init"));
if (!func) {
error = "Cannot initialize shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
func(v8::Context::GetCurrent()->Global());
return 0;
} else {
return js_execute(path.c_str(), false);
}
}
int js_autoload() {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (js_library(*name)) { return 1; }
}
return 0;
}
JS_METHOD(_include) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_execute(*file, true);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
JS_METHOD(_library) {
v8::HandleScope handle_scope;
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
JS_METHOD(_onexit) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
void main_terminate() {
}
void main_finish() {
v8::HandleScope handle_scope;
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
}
int main_execute() {
v8::HandleScope handle_scope;
const char * name = execfile;
if (name == NULL) { // try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value jsname(pt);
name = *jsname;
}
}
if (name == NULL) {
js_error("Nothing to do.\n");
return 1;
} else {
return js_execute(name, true);
}
}
int main_prepare(char ** envp) {
__onexit = v8::Array::New();
v8::Handle<v8::Object> g = v8::Context::GetCurrent()->Global();
g->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
g->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
g->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
g->Set(JS_STR("total"), JS_INT(total++));
g->Set(JS_STR("global"), g);
g->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, g);
setup_io(g);
setup_socket(g);
if (js_execute(cfgfile, false)) {
js_error("Cannot load configuration, quitting...\n");
return 1;
}
if (js_autoload()) {
js_error("Cannot load default libraries, quitting...\n");
return 1;
}
return 0;
}
int main_initialize(int argc, char ** argv) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
cfgfile = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfgfile = argv[i+1];
argptr = 0;
i++;
}
}
if (argptr) { execfile = argv[argptr]; }
FILE* file = fopen(cfgfile, "rb");
if (file == NULL) {
printf("Invalid configuration file.\n");
return 1;
}
fclose(file);
return 0;
}
int main_cycle(char ** envp) {
int result = 0;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
result = main_prepare(envp);
if (result == 0) {
result = main_execute();
}
main_finish();
return result;
}
int main(int argc, char ** argv, char ** envp) {
int result = 0;
result = main_initialize(argc, argv);
if (result) { exit(1); }
#ifdef FASTCGI
while(FCGI_Accept() >= 0) {
#endif
result = main_cycle(envp);
#ifdef FASTCGI
FCGI_SetExitStatus(result);
#endif
#ifdef FASTCGI
}
#endif
main_terminate();
return result;
}
<commit_msg>getcwd() leak<commit_after>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#define _STRING(x) #x
#define STRING(x) _STRING(x)
#include <sstream>
#include <stdlib.h>
#include <v8.h>
#include <map>
#ifdef FASTCGI
# include <fcgi_stdio.h>
#endif
#include "js_system.h"
#include "js_io.h"
#include "js_socket.h"
#include "js_common.h"
#include "js_macros.h"
#include "js_cache.h"
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
#endif
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit; /* what to do on exit */
const char * cfgfile = NULL; /* config file */
const char * execfile = NULL; /* command-line specified file */
Cache cache;
int total = 0; /* fcgi debug */
void js_error(const char * message) {
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(message);
fun->Call(context->ToObject(), 1, data);
}
void js_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
msgstring += ss.str();
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
}
js_error(msgstring.c_str());
}
v8::Handle<v8::String> js_read(const char* name) {
std::string n = name;
std::string source = cache.getJS(n);
return JS_STR(source.c_str());
}
int js_execute(const char * str, bool change) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = js_read(str);
if (source.IsEmpty()) {
std::string s = "Error reading '";
s += str;
s += "'\n";
js_error(s.c_str());
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
js_exception(&try_catch);
return 1;
} else {
char * tmp = getcwd(NULL, 0);
std::string oldcwd = tmp;
free(tmp);
std::string newcwd = str;
size_t pos = newcwd.find_last_of('/');
if (pos == std::string::npos) { pos = newcwd.find_last_of('\\'); }
if (pos != std::string::npos && change) {
newcwd.erase(pos, newcwd.length()-pos);
chdir(newcwd.c_str());
}
v8::Handle<v8::Value> result = script->Run();
if (change) { chdir(oldcwd.c_str()); }
if (result.IsEmpty()) {
js_exception(&try_catch);
return 1;
}
}
return 0;
}
int js_library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
std::string error;
path += *pfx;
path += "/";
path += name;
if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
void * handle = cache.getHandle(path);
if (handle == NULL) {
error = "Cannot load shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
void (*func) (v8::Handle<v8::Object>);
func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init"));
if (!func) {
error = "Cannot initialize shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
func(v8::Context::GetCurrent()->Global());
return 0;
} else {
return js_execute(path.c_str(), false);
}
}
int js_autoload() {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (js_library(*name)) { return 1; }
}
return 0;
}
JS_METHOD(_include) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_execute(*file, true);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
JS_METHOD(_library) {
v8::HandleScope handle_scope;
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
JS_METHOD(_onexit) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
void main_terminate() {
}
void main_finish() {
v8::HandleScope handle_scope;
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
}
int main_execute() {
v8::HandleScope handle_scope;
const char * name = execfile;
if (name == NULL) { // try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value jsname(pt);
name = *jsname;
}
}
if (name == NULL) {
js_error("Nothing to do.\n");
return 1;
} else {
return js_execute(name, true);
}
}
int main_prepare(char ** envp) {
__onexit = v8::Array::New();
v8::Handle<v8::Object> g = v8::Context::GetCurrent()->Global();
g->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
g->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
g->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
g->Set(JS_STR("total"), JS_INT(total++));
g->Set(JS_STR("global"), g);
g->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, g);
setup_io(g);
setup_socket(g);
if (js_execute(cfgfile, false)) {
js_error("Cannot load configuration, quitting...\n");
return 1;
}
if (js_autoload()) {
js_error("Cannot load default libraries, quitting...\n");
return 1;
}
return 0;
}
int main_initialize(int argc, char ** argv) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
cfgfile = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfgfile = argv[i+1];
argptr = 0;
i++;
}
}
if (argptr) { execfile = argv[argptr]; }
FILE* file = fopen(cfgfile, "rb");
if (file == NULL) {
printf("Invalid configuration file.\n");
return 1;
}
fclose(file);
return 0;
}
int main_cycle(char ** envp) {
int result = 0;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
result = main_prepare(envp);
if (result == 0) {
result = main_execute();
}
main_finish();
return result;
}
int main(int argc, char ** argv, char ** envp) {
int result = 0;
result = main_initialize(argc, argv);
if (result) { exit(1); }
#ifdef FASTCGI
while(FCGI_Accept() >= 0) {
#endif
result = main_cycle(envp);
#ifdef FASTCGI
FCGI_SetExitStatus(result);
#endif
#ifdef FASTCGI
}
#endif
main_terminate();
return result;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StatisticsHelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:46:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CHART2_STATISTICSHELPER_HXX
#define CHART2_STATISTICSHELPER_HXX
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
namespace chart
{
class StatisticsHelper
{
public:
/** Calculates 1/n * sum (x_i - x_mean)^2.
@see http://mathworld.wolfram.com/Variance.html
@param bUnbiasedEstimator
If true, 1/(n-1) * sum (x_i - x_mean)^2 is returned.
*/
static double getVariance( const ::com::sun::star::uno::Sequence< double > & rData,
bool bUnbiasedEstimator = false );
// square root of the variance
static double getStandardDeviation( const ::com::sun::star::uno::Sequence< double > & rData );
// also called "Standard deviation of the mean (SDOM)"
static double getStandardError( const ::com::sun::star::uno::Sequence< double > & rData );
private:
// not implemented
StatisticsHelper();
};
} // namespace chart
// CHART2_STATISTICSHELPER_HXX
#endif
<commit_msg>INTEGRATION: CWS chart20_DEV300 (1.2.228); FILE MERGED 2008/02/22 16:51:28 bm 1.2.228.2: #i366# +removeErrorBars() 2008/02/21 15:59:27 bm 1.2.228.1: #i366# error bars from ranges<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StatisticsHelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-06 17:09:22 $
*
* 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 CHART2_STATISTICSHELPER_HXX
#define CHART2_STATISTICSHELPER_HXX
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/chart2/data/XDataSource.hpp>
#include <com/sun/star/chart2/data/XDataProvider.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
namespace chart
{
class StatisticsHelper
{
public:
/** Calculates 1/n * sum (x_i - x_mean)^2.
@see http://mathworld.wolfram.com/Variance.html
@param bUnbiasedEstimator
If true, 1/(n-1) * sum (x_i - x_mean)^2 is returned.
*/
static double getVariance( const ::com::sun::star::uno::Sequence< double > & rData,
bool bUnbiasedEstimator = false );
// square root of the variance
static double getStandardDeviation( const ::com::sun::star::uno::Sequence< double > & rData );
// also called "Standard deviation of the mean (SDOM)"
static double getStandardError( const ::com::sun::star::uno::Sequence< double > & rData );
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence >
getErrorLabeledDataSequenceFromDataSource(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > & xDataSource,
bool bPositiveValue,
bool bYError = true );
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSequence >
getErrorDataSequenceFromDataSource(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > & xDataSource,
bool bPositiveValue,
bool bYError = true );
static double getErrorFromDataSource(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > & xDataSource,
sal_Int32 nIndex,
bool bPositiveValue,
bool bYError = true );
static void setErrorDataSequence(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > & xDataSource,
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataProvider > & xDataProvider,
const ::rtl::OUString & rNewRange,
bool bPositiveValue,
bool bYError = true,
::rtl::OUString * pXMLRange = 0 );
/// @return the newly created or existing error bar object
static ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet >
addErrorBars(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > & xContext,
sal_Int32 nStyle,
bool bYError = true );
static ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet >
getErrorBars(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries,
bool bYError = true );
static bool hasErrorBars(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries,
bool bYError = true );
static void removeErrorBars(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries,
bool bYError = true );
static bool usesErrorBarRanges(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xDataSeries,
bool bYError = true );
private:
// not implemented
StatisticsHelper();
};
} // namespace chart
// CHART2_STATISTICSHELPER_HXX
#endif
<|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/app_modal_dialog.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/message_box_flags.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "grit/generated_resources.h"
namespace {
// We stash pointers to widgets on the gtk_dialog so we can refer to them
// after dialog creation.
const char kPromptTextId[] = "chrome_prompt_text";
const char kSuppressCheckboxId[] = "chrome_suppress_checkbox";
// If there's a text entry in the dialog, get the text from the first one and
// return it.
std::wstring GetPromptText(GtkDialog* dialog) {
GtkWidget* widget = static_cast<GtkWidget*>(
g_object_get_data(G_OBJECT(dialog), kPromptTextId));
if (widget)
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(widget)));
return std::wstring();
}
// If there's a toggle button in the dialog, return the toggled state.
// Otherwise, return false.
bool ShouldSuppressJSDialogs(GtkDialog* dialog) {
GtkWidget* widget = static_cast<GtkWidget*>(
g_object_get_data(G_OBJECT(dialog), kSuppressCheckboxId));
if (widget)
return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
return false;
}
void OnDialogResponse(GtkDialog* dialog, gint response_id,
AppModalDialog* app_modal_dialog) {
switch (response_id) {
case GTK_RESPONSE_OK:
// The first arg is the prompt text and the second is true if we want to
// suppress additional popups from the page.
app_modal_dialog->OnAccept(GetPromptText(dialog),
ShouldSuppressJSDialogs(dialog));
break;
case GTK_RESPONSE_CANCEL:
case GTK_RESPONSE_DELETE_EVENT: // User hit the X on the dialog.
app_modal_dialog->OnCancel();
break;
default:
NOTREACHED();
}
gtk_widget_destroy(GTK_WIDGET(dialog));
delete app_modal_dialog;
}
} // namespace
AppModalDialog::~AppModalDialog() {
}
void AppModalDialog::CreateAndShowDialog() {
GtkButtonsType buttons = GTK_BUTTONS_NONE;
GtkMessageType message_type = GTK_MESSAGE_OTHER;
// We add in the OK button manually later because we want to focus it
// explicitly.
switch (dialog_flags_) {
case MessageBoxFlags::kIsJavascriptAlert:
buttons = GTK_BUTTONS_NONE;
message_type = GTK_MESSAGE_WARNING;
break;
case MessageBoxFlags::kIsJavascriptConfirm:
if (is_before_unload_dialog_) {
// onbeforeunload also uses a confirm prompt, it just has custom
// buttons. We add the buttons using gtk_dialog_add_button below.
buttons = GTK_BUTTONS_NONE;
} else {
buttons = GTK_BUTTONS_CANCEL;
}
message_type = GTK_MESSAGE_QUESTION;
break;
case MessageBoxFlags::kIsJavascriptPrompt:
buttons = GTK_BUTTONS_CANCEL;
message_type = GTK_MESSAGE_QUESTION;
break;
default:
NOTREACHED();
}
GtkWindow* window = tab_contents_->view()->GetTopLevelNativeWindow();
dialog_ = gtk_message_dialog_new(window, GTK_DIALOG_MODAL,
message_type, buttons, "%s", WideToUTF8(message_text_).c_str());
gtk_window_set_title(GTK_WINDOW(dialog_), WideToUTF8(title_).c_str());
// Adjust content area as needed.
if (MessageBoxFlags::kIsJavascriptPrompt == dialog_flags_) {
// TODO(tc): Replace with gtk_dialog_get_content_area() when using GTK 2.14+
GtkWidget* contents_vbox = GTK_DIALOG(dialog_)->vbox;
GtkWidget* text_box = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(text_box),
WideToUTF8(default_prompt_text_).c_str());
gtk_box_pack_start(GTK_BOX(contents_vbox), text_box, TRUE, TRUE, 0);
g_object_set_data(G_OBJECT(dialog_), kPromptTextId, text_box);
}
if (display_suppress_checkbox_) {
GtkWidget* contents_vbox = GTK_DIALOG(dialog_)->vbox;
GtkWidget* check_box = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(
IDS_JAVASCRIPT_MESSAGEBOX_SUPPRESS_OPTION).c_str());
gtk_box_pack_start(GTK_BOX(contents_vbox), check_box, TRUE, TRUE, 0);
g_object_set_data(G_OBJECT(dialog_), kSuppressCheckboxId, check_box);
}
// Adjust buttons/action area as needed.
if (is_before_unload_dialog_) {
std::string button_text = l10n_util::GetStringUTF8(
IDS_BEFOREUNLOAD_MESSAGEBOX_OK_BUTTON_LABEL);
gtk_dialog_add_button(GTK_DIALOG(dialog_), button_text.c_str(),
GTK_RESPONSE_OK);
button_text = l10n_util::GetStringUTF8(
IDS_BEFOREUNLOAD_MESSAGEBOX_CANCEL_BUTTON_LABEL);
gtk_dialog_add_button(GTK_DIALOG(dialog_), button_text.c_str(),
GTK_RESPONSE_CANCEL);
} else {
// Add the OK button and focus it.
GtkWidget* ok_button = gtk_dialog_add_button(GTK_DIALOG(dialog_),
GTK_STOCK_OK, GTK_RESPONSE_OK);
if (MessageBoxFlags::kIsJavascriptPrompt != dialog_flags_)
gtk_widget_grab_focus(ok_button);
}
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK);
g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponse), this);
gtk_widget_show_all(GTK_WIDGET(GTK_DIALOG(dialog_)));
}
void AppModalDialog::ActivateModalDialog() {
gtk_window_present(GTK_WINDOW(dialog_));
}
void AppModalDialog::CloseModalDialog() {
OnDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_DELETE_EVENT, this);
}
int AppModalDialog::GetDialogButtons() {
switch (dialog_flags_) {
case MessageBoxFlags::kIsJavascriptAlert:
return MessageBoxFlags::DIALOGBUTTON_OK;
case MessageBoxFlags::kIsJavascriptConfirm:
return MessageBoxFlags::DIALOGBUTTON_OK |
MessageBoxFlags::DIALOGBUTTON_CANCEL;
case MessageBoxFlags::kIsJavascriptPrompt:
return MessageBoxFlags::DIALOGBUTTON_OK;
default:
NOTREACHED();
return 0;
}
}
void AppModalDialog::AcceptWindow() {
OnDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_OK, this);
}
void AppModalDialog::CancelWindow() {
OnDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_CANCEL, this);
}
<commit_msg>Pressing "enter" while the JS prompt text entry has focus should accept the user's text.<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/app_modal_dialog.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/message_box_flags.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "grit/generated_resources.h"
namespace {
// We stash pointers to widgets on the gtk_dialog so we can refer to them
// after dialog creation.
const char kPromptTextId[] = "chrome_prompt_text";
const char kSuppressCheckboxId[] = "chrome_suppress_checkbox";
// If there's a text entry in the dialog, get the text from the first one and
// return it.
std::wstring GetPromptText(GtkDialog* dialog) {
GtkWidget* widget = static_cast<GtkWidget*>(
g_object_get_data(G_OBJECT(dialog), kPromptTextId));
if (widget)
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(widget)));
return std::wstring();
}
// If there's a toggle button in the dialog, return the toggled state.
// Otherwise, return false.
bool ShouldSuppressJSDialogs(GtkDialog* dialog) {
GtkWidget* widget = static_cast<GtkWidget*>(
g_object_get_data(G_OBJECT(dialog), kSuppressCheckboxId));
if (widget)
return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
return false;
}
void OnDialogResponse(GtkDialog* dialog, gint response_id,
AppModalDialog* app_modal_dialog) {
switch (response_id) {
case GTK_RESPONSE_OK:
// The first arg is the prompt text and the second is true if we want to
// suppress additional popups from the page.
app_modal_dialog->OnAccept(GetPromptText(dialog),
ShouldSuppressJSDialogs(dialog));
break;
case GTK_RESPONSE_CANCEL:
case GTK_RESPONSE_DELETE_EVENT: // User hit the X on the dialog.
app_modal_dialog->OnCancel();
break;
default:
NOTREACHED();
}
gtk_widget_destroy(GTK_WIDGET(dialog));
delete app_modal_dialog;
}
} // namespace
AppModalDialog::~AppModalDialog() {
}
void AppModalDialog::CreateAndShowDialog() {
GtkButtonsType buttons = GTK_BUTTONS_NONE;
GtkMessageType message_type = GTK_MESSAGE_OTHER;
// We add in the OK button manually later because we want to focus it
// explicitly.
switch (dialog_flags_) {
case MessageBoxFlags::kIsJavascriptAlert:
buttons = GTK_BUTTONS_NONE;
message_type = GTK_MESSAGE_WARNING;
break;
case MessageBoxFlags::kIsJavascriptConfirm:
if (is_before_unload_dialog_) {
// onbeforeunload also uses a confirm prompt, it just has custom
// buttons. We add the buttons using gtk_dialog_add_button below.
buttons = GTK_BUTTONS_NONE;
} else {
buttons = GTK_BUTTONS_CANCEL;
}
message_type = GTK_MESSAGE_QUESTION;
break;
case MessageBoxFlags::kIsJavascriptPrompt:
buttons = GTK_BUTTONS_CANCEL;
message_type = GTK_MESSAGE_QUESTION;
break;
default:
NOTREACHED();
}
GtkWindow* window = tab_contents_->view()->GetTopLevelNativeWindow();
dialog_ = gtk_message_dialog_new(window, GTK_DIALOG_MODAL,
message_type, buttons, "%s", WideToUTF8(message_text_).c_str());
gtk_window_set_title(GTK_WINDOW(dialog_), WideToUTF8(title_).c_str());
// Adjust content area as needed. Set up the prompt text entry or
// suppression check box.
if (MessageBoxFlags::kIsJavascriptPrompt == dialog_flags_) {
// TODO(tc): Replace with gtk_dialog_get_content_area() when using GTK 2.14+
GtkWidget* contents_vbox = GTK_DIALOG(dialog_)->vbox;
GtkWidget* text_box = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(text_box),
WideToUTF8(default_prompt_text_).c_str());
gtk_box_pack_start(GTK_BOX(contents_vbox), text_box, TRUE, TRUE, 0);
g_object_set_data(G_OBJECT(dialog_), kPromptTextId, text_box);
gtk_entry_set_activates_default(GTK_ENTRY(text_box), TRUE);
}
if (display_suppress_checkbox_) {
GtkWidget* contents_vbox = GTK_DIALOG(dialog_)->vbox;
GtkWidget* check_box = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(
IDS_JAVASCRIPT_MESSAGEBOX_SUPPRESS_OPTION).c_str());
gtk_box_pack_start(GTK_BOX(contents_vbox), check_box, TRUE, TRUE, 0);
g_object_set_data(G_OBJECT(dialog_), kSuppressCheckboxId, check_box);
}
// Adjust buttons/action area as needed.
if (is_before_unload_dialog_) {
std::string button_text = l10n_util::GetStringUTF8(
IDS_BEFOREUNLOAD_MESSAGEBOX_OK_BUTTON_LABEL);
gtk_dialog_add_button(GTK_DIALOG(dialog_), button_text.c_str(),
GTK_RESPONSE_OK);
button_text = l10n_util::GetStringUTF8(
IDS_BEFOREUNLOAD_MESSAGEBOX_CANCEL_BUTTON_LABEL);
gtk_dialog_add_button(GTK_DIALOG(dialog_), button_text.c_str(),
GTK_RESPONSE_CANCEL);
} else {
// Add the OK button and focus it.
GtkWidget* ok_button = gtk_dialog_add_button(GTK_DIALOG(dialog_),
GTK_STOCK_OK, GTK_RESPONSE_OK);
if (MessageBoxFlags::kIsJavascriptPrompt != dialog_flags_)
gtk_widget_grab_focus(ok_button);
}
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK);
g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponse), this);
gtk_widget_show_all(GTK_WIDGET(GTK_DIALOG(dialog_)));
}
void AppModalDialog::ActivateModalDialog() {
gtk_window_present(GTK_WINDOW(dialog_));
}
void AppModalDialog::CloseModalDialog() {
OnDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_DELETE_EVENT, this);
}
int AppModalDialog::GetDialogButtons() {
switch (dialog_flags_) {
case MessageBoxFlags::kIsJavascriptAlert:
return MessageBoxFlags::DIALOGBUTTON_OK;
case MessageBoxFlags::kIsJavascriptConfirm:
return MessageBoxFlags::DIALOGBUTTON_OK |
MessageBoxFlags::DIALOGBUTTON_CANCEL;
case MessageBoxFlags::kIsJavascriptPrompt:
return MessageBoxFlags::DIALOGBUTTON_OK;
default:
NOTREACHED();
return 0;
}
}
void AppModalDialog::AcceptWindow() {
OnDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_OK, this);
}
void AppModalDialog::CancelWindow() {
OnDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_CANCEL, this);
}
<|endoftext|> |
<commit_before>/* *************************************************************************************************************
*
* Title: Tric Trac Troe (a Tic Tac Toe game)
* Author: shubham Gupta
* Description: A tic tac toe game based machine learning System
* contact: shubham0075+mlp@gmail.com
*
***************************************************************************************************************/
#include <iostream>
#include <stdlib.h>
using namespace std;
class position
{
public:
int id; //used to identify a position of tic tac toe
int next_moves[3]; //used to store the human learned move
int box[10]; //actual storage of elements of tic tac toe
//int moves; //number of moves in the current position. This has been started from a min 4 to max 9
int skill_counter; //keeps count of entreis into next_moves...useful for getting skill rating of AI
position(){
next_moves[0]=next_moves[1]=next_moves[2]=-1;
skill_counter=0;
int i=9;
while(i >0)
{box[i]=0;
i--;
}
box[i]=99;}
void disp(){ //main display function used.It also has the tic tac toe grid display and it is used to display by default
cout<<endl<<" "<<render(this->box[1])<<" | "<<render(this->box[2])<<" | "<<render(this->box[3])<<endl;
char a[]="------------";
cout<<" "<<a;
cout<<endl<<" "<<render(this->box[4])<<" | "<<render(this->box[5])<<" | "<<render(this->box[6])<<endl;
cout<<" "<<a;
cout<<endl<<" "<<render(this->box[7])<<" | "<<render(this->box[8])<<" | "<<render(this->box[9])<<endl;
}
char render(int digit){
if(digit==0)
return ' ';
else if(digit==1)
return 'X';
else
return 'O';}
void raw_disp(){
//mainly for diagnostic use, it displays the ternary number corresponding to the position of the tic tactoe game's position.
cout<<endl<<" "<<this->box[1]<<this->box[2]<<this->box[3]<<this->box[4]<<this->box[5]<<this->box[6]<<this->box[7]<<this->box[8]<<this->box[9];}
bool isValid(){
//checks invalid positions by comparing number of x and o's since the difference can't be higher than one in a valid game
int x=0,o=0,i=1;
while (i<10){
if (this->box[i]==1)
x++;
if (this->box[i]==2)
o++;
i++;}
//checks fo multiple wins //only one win is possible in a valid game
int win=0,count=1;
//rows win check
while(count<8){
if(this->box[count]==this->box[count+1] && this->box[count+1]==this->box[count+2] && this->box[count]!=0)
{win++;}
count+=3; }
//column win check
count=1;
while(count<4){
if(this->box[count]==this->box[count+3] && this->box[count+3]==this->box[count+6] && this->box[count]!=0)
{win++;}
count++;}
//diagonal win check
count=1;
if(this->box[count]==this->box[count+4] && this->box[count+4]==this->box[count+8] && this->box[count]!=0)
{win++;}
//other diagonal win check
count=3;
if(this->box[count]==this->box[count+2] && this->box[count+2]==this->box[count+4] && this->box[count]!=0)
{win++;}
//valid or invalid result return //sums up all of the previous check conditions in the function.
if((o-x)>1||(x-o)>1 || win>1 || (o+x)<4 )
return false;
else
return true;
}
bool isEqual(position c){//to compare two positions and return true if they are equal.
int i=1;
while(i<10)
{if(this->box[i]!=c.box[i])
break;
i++;}
if (i==10)
return true;
else
return false;
}
bool isWin()
{//checks for a winner
int win=0,count=1;
//rows win check
while(count<8){
if(this->box[count]==this->box[count+1] && this->box[count+1]==this->box[count+2] && this->box[count]!=0)
{win++;}
count+=3; }
//column win check
count=1;
while(count<4){
if(this->box[count]==this->box[count+3] && this->box[count+3]==this->box[count+6] && this->box[count]!=0)
{win++;}
count++;}
//diagonal win check
count=1;
if(this->box[count]==this->box[count+4] && this->box[count+4]==this->box[count+8] && this->box[count]!=0)
{win++;}
//other diagonal win check
count=3;
if(this->box[count]==this->box[count+2] && this->box[count+2]==this->box[count+4] && this->box[count]!=0)
{win++;}
if(win==1)
return true;
else
return false;
}
};
position a[20000]; //global declaration of position array that contains all the possible valid positions of tic tac toe
class game: public position {
public:
void play(int play_mode)
{ int i=1,move;
while(i<10){//play main loop
system("clear");
int current_player=(i%2)==1?1:2;
this->disp();
int currentid,nextid;
currentid=this->getId();
cout<<endl<<render(current_player)<<" to move\n";
cin>>move;
if(move<10 && move>0 && this->box[move]==0)
{this->box[move]= (i%2)==1?1:2;
nextid=this->getId();
a[currentid].next_moves[0]=nextid;
a[currentid].skill_counter++;
this->learn();
if(this->isWin()){
{ system("clear");
this->disp();
cout<<"Winner is "<<render(current_player);
break;}
}
i++;
}
else
{cout<<endl<<"move not valid\n";}
}
if (i==10 && this->isWin()!=true){
system("clear");
this->disp();
cout<<"\n This Game is Drawn\n";}}
int getId(){
int counter=0,climit=19684;
while(counter<climit)
{
if(this->isEqual(a[counter]))
{return a[counter].id;}
counter++;
}
}
void learn(){
int counter=0,climit=19684;
while(counter<climit)
{
if(this->isEqual(a[counter]))
{cout<<"\n Position id is : "<<a[counter].id;
break;}
counter++;
}
}
};
position trinary(int counter1){
//converts the decimal number into a ternary number of base 3 (I incorrectly named it trinary based on binary)
//this function also asssigns the number to a position after ternary conversion and that position is ultimately returned.
//using this ternary system i am able to represent 0 as a blank, 1 as X and 2 as O. the render() function is responsible for converting
//the numbers to these symbols while displaying the numbers.
position b;
int i=1;
while(i<10 && counter1!=0){
b.box[i]=counter1 % 3;
counter1=counter1 / 3;
i++;}
return b;
}
void generate_positions(){
int counter=19683,countofvalid=0;
while(counter>0){
a[counter]=trinary(counter);
a[counter].id=counter;
if(a[counter].isValid()){
cout<<a[counter].id<<" \t ";
a[counter].disp();
countofvalid++;}
counter--;}
//cout<<"\n Number of valid positions "<<countofvalid;
}
int main(){
//some testing code used to generate the different valid tic tac toe positions posible in a game
generate_positions();
game g;
g.play(play_mode);
}
<commit_msg>added computer against computer playmode and moves_sequnce storing system<commit_after>/* *************************************************************************************************************
*
* Title: Tric Trac Troe (a Tic Tac Toe game)
* Author: shubham Gupta
* Description: A tic tac toe game based machine learning System
* contact: shubham0075+mlp@gmail.com
*
***************************************************************************************************************/
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
class position
{
public:
int id; //used to identify a position of tic tac toe
int next_moves[3]; //used to store the human learned move
int box[10]; //actual storage of elements of tic tac toe
//int moves; //number of moves in the current position. This has been started from a min 4 to max 9
int skill_counter; //keeps count of entreis into next_moves...useful for getting skill rating of AI
position(){
next_moves[0]=next_moves[1]=next_moves[2]=-1;
skill_counter=0;
int i=9;
while(i >0)
{box[i]=0;
i--;
}
box[i]=99;}
void disp(){ //main display function used.It also has the tic tac toe grid display and it is used to display by default
cout<<endl<<" "<<render(this->box[1])<<" | "<<render(this->box[2])<<" | "<<render(this->box[3])<<endl;
char a[]="------------";
cout<<" "<<a;
cout<<endl<<" "<<render(this->box[4])<<" | "<<render(this->box[5])<<" | "<<render(this->box[6])<<endl;
cout<<" "<<a;
cout<<endl<<" "<<render(this->box[7])<<" | "<<render(this->box[8])<<" | "<<render(this->box[9])<<endl;
}
char render(int digit){
if(digit==0)
return ' ';
else if(digit==1)
return 'X';
else
return 'O';}
void raw_disp(){
//mainly for diagnostic use, it displays the ternary number corresponding to the position of the tic tactoe game's position.
cout<<endl<<" "<<this->box[1]<<this->box[2]<<this->box[3]<<this->box[4]<<this->box[5]<<this->box[6]<<this->box[7]<<this->box[8]<<this->box[9];}
bool isValid(){
//checks invalid positions by comparing number of x and o's since the difference can't be higher than one in a valid game
int x=0,o=0,i=1;
while (i<10){
if (this->box[i]==1)
x++;
if (this->box[i]==2)
o++;
i++;}
//checks fo multiple wins //only one win is possible in a valid game
int win=0,count=1;
//rows win check
while(count<8){
if(this->box[count]==this->box[count+1] && this->box[count+1]==this->box[count+2] && this->box[count]!=0)
{win++;}
count+=3; }
//column win check
count=1;
while(count<4){
if(this->box[count]==this->box[count+3] && this->box[count+3]==this->box[count+6] && this->box[count]!=0)
{win++;}
count++;}
//diagonal win check
count=1;
if(this->box[count]==this->box[count+4] && this->box[count+4]==this->box[count+8] && this->box[count]!=0)
{win++;}
//other diagonal win check
count=3;
if(this->box[count]==this->box[count+2] && this->box[count+2]==this->box[count+4] && this->box[count]!=0)
{win++;}
//valid or invalid result return //sums up all of the previous check conditions in the function.
if((o-x)>1||(x-o)>1 || win>1 || (o+x)<4 )
return false;
else
return true;
}
bool isEqual(position c){//to compare two positions and return true if they are equal.
int i=1;
while(i<10)
{if(this->box[i]!=c.box[i])
break;
i++;}
if (i==10)
return true;
else
return false;
}
bool isWin()
{//checks for a winner
int win=0,count=1;
//rows win check
while(count<8){
if(this->box[count]==this->box[count+1] && this->box[count+1]==this->box[count+2] && this->box[count]!=0)
{win++;}
count+=3; }
//column win check
count=1;
while(count<4){
if(this->box[count]==this->box[count+3] && this->box[count+3]==this->box[count+6] && this->box[count]!=0)
{win++;}
count++;}
//diagonal win check
count=1;
if(this->box[count]==this->box[count+4] && this->box[count+4]==this->box[count+8] && this->box[count]!=0)
{win++;}
//other diagonal win check
count=3;
if(this->box[count]==this->box[count+2] && this->box[count+2]==this->box[count+4] && this->box[count]!=0)
{win++;}
if(win==1)
return true;
else
return false;
}
};
position a[20000]; //global declaration of position array that contains all the possible valid positions of tic tac toe
class game: public position {
public:
int game_sequence[11];//use to store all the position ids of the game's moves which will be further analysed in case of win or draw
// index 0 is not used,index 1 will always be 0, from index 2 to 10 are the actual Position ids that matter
game(){
int count=0;
while(count<12)
{game_sequence[count]=-1;
count++;
}
}
void play(int play_mode)
{ if(play_mode==1)
{int i=1,move;
while(i<10){//play main loop
system("clear");
int current_player=(i%2)==1?1:2;
this->disp();
int currentid,nextid;
currentid=this->getId();
cout<<endl<<render(current_player)<<" to move\n";
cin>>move;
if(move<10 && move>0 && this->box[move]==0) //conditions for a valid move
{this->box[move]= (i%2)==1?1:2;
this->game_sequence[move]=currentid;
nextid=this->getId();
a[currentid].next_moves[0]=nextid;
a[currentid].skill_counter++;
if(this->isWin()){
{ this->game_sequence[move+1]=nextid;
system("clear");
this->disp();
cout<<"Winner is "<<render(current_player)<<endl;
break;}
}
i++;
}
else
{cout<<endl<<"move not valid\n";}
}
if (i==10 && this->isWin()!=true){
system("clear");
this->disp();
cout<<"\n This Game is Drawn\n";
this->game_sequence[move+1]=this->getId();
}}
//playmode 3 refine
if(play_mode==3)
{int i=1,move;
while(i<10){//play main loop
system("clear");
int current_player=(i%2)==1?1:2;
this->disp();
int currentid,nextid;
currentid=this->getId();
cout<<endl<<render(current_player)<<" to move\n";
move=rand() % 9 + 1;//random function used cstdlib
if(move<10 && move>0 && this->box[move]==0) //conditions for a valid move
{this->box[move]= (i%2)==1?1:2;
nextid=this->getId();
a[currentid].next_moves[0]=nextid;
a[currentid].skill_counter++;
if(this->isWin()){
{ system("clear");
this->disp();
cout<<"Winner is "<<render(current_player);
break;}
}
i++;
}
else
{cout<<endl<<"move not valid\n";}
}
if (i==10 && this->isWin()!=true){
system("clear");
this->disp();
cout<<"\n This Game is Drawn\n";}}
}
int getId(){
int counter=0,climit=19684;
while(counter<climit)
{
if(this->isEqual(a[counter]))
{return a[counter].id;}
counter++;
}
}
/* void learn(){
int counter=0,climit=19684;
while(counter<climit)
{
if(this->isEqual(a[counter]))
{cout<<"\n Position id is : "<<a[counter].id;
break;}
counter++;
}
}*/
};
position trinary(int counter1){
//converts the decimal number into a ternary number of base 3 (I incorrectly named it trinary based on binary)
//this function also asssigns the number to a position after ternary conversion and that position is ultimately returned.
//using this ternary system i am able to represent 0 as a blank, 1 as X and 2 as O. the render() function is responsible for converting
//the numbers to these symbols while displaying the numbers.
position b;
int i=1;
while(i<10 && counter1!=0){
b.box[i]=counter1 % 3;
counter1=counter1 / 3;
i++;}
return b;
}
void generate_positions(){
int counter=19683,countofvalid=0;
while(counter>0){
a[counter]=trinary(counter);
a[counter].id=counter;
if(a[counter].isValid()){
cout<<a[counter].id<<" \t ";
a[counter].disp();
countofvalid++;}
counter--;}
//cout<<"\n Number of valid positions "<<countofvalid;
}
int main(){
//some testing code used to generate the different valid tic tac toe positions posible in a game
generate_positions();
int play_mode=-1;
char carryon='y';
while(carryon=='y' || carryon=='Y'){
cout<<"Enter game modes\n(1)human vs Human\n(2)Humaan vs Nobrains\n(3) Two crazy Nobrains \n";
cin>>play_mode;
game* g = new game;
g->play(play_mode);
cout<<"\ncarry on ? ";
cin>>carryon;}
}
<|endoftext|> |
<commit_before>#include "makefilewritter.h"
#include "data.h"
#include "error.h"
#include "stringtools.h"
#include <QString>
#include <QTextStream>
#include <QObject>
#include <QRegExp>
#include <QVariantList>
#include <QVariant>
QString generateMakeFile()
{
QString str;
QTextStream ts(&str,QIODevice::WriteOnly);
checkVariableSize("TEMPLATE",1,1);
QVariantList Template = Data::getVariable("TEMPLATE");
QString option;
if (checkVariableSize("DEFINE",1,100000,Error::DO_NOTHING))
{
QVariantList var=Data::getVariable("DEFINE");
for(const QVariant& i:var)
{
option.append(QString(" -D%1").arg(i.toString()));
}
}
if (checkVariableSize("STD",1,10000,Error::DO_NOTHING))
{
QString var=Data::getVariable("STD").at(0).toString();
if (var=="c++11" || var=="c++0x") option.append(" -std=c++11");
else if(var=="c++14") option.append(" -std=c++14");
else if (var=="c++17" || var=="c++1z") option.append(" -std=c++17");
else if (var=="c++98") option.append(" -std=c++98");
else
{
//TODO: throw warning
}
}
if (checkVariableSize("DEBUG_MODE",1,10000,Error::DO_NOTHING))
{
QVariant var=Data::getVariable("DEBUG_MODE").at(0);
if (var.toString()=="true")
{
option.append(" -g");
}
else if (var.toString()=="false");
else
{
//TODO: throw warning
}
}
QString optimize="1";
if (checkVariableSize("OPTIMIZE",1,10000,Error::DO_NOTHING))
{
optimize=Data::getVariable("OPTIMIZE").at(0).toString();
}
option.push_back(QString(" -O%1").arg(optimize));
if (Template[0].toString()=="default")
{
checkVariableSize("OUTPUT",1,1);
const QString output=Data::getVariable("OUTPUT").at(0).toString();
checkVariableSize("SOURCES",1,10000);
const QVariantList& sources=Data::getVariable("SOURCES");
ts<<QString("%1 :").arg(output);
for(const QVariant &i:sources)
{
QString objFileName=removeExtension(i.toString())+".o";
ts<<QString(" %1").arg(objFileName);
}
#ifdef Q_OS_WIN
QString stack;
if (checkVariableSize("STACK",1,10000,Error::DO_NOTHING))
{
bool ok;
int var=Data::getVariable("DEBUG_MODE").at(0).toInt(&ok);
if (!ok)
{
//TODO: throw warning
}
else
{
stack=QString(" -Wl,--stack=%1").arg(var);
}
}
#endif
ts<<QString("\n\tg++ -o %1").arg(output);
for(const QVariant &i:sources)
{
QString objFileName=removeExtension(i.toString())+".o";
ts<<QString(" %1").arg(objFileName);
}
#ifdef Q_OS_WIN
ts<<stack;
#endif
ts<<option;
ts<<'\n';
for(const QVariant &i:sources)
{
QString objFileName=removeExtension(i.toString())+".o";
ts<<QString("%1 : %2\n\tg++ -c %2").arg(objFileName,i.toString());
ts<<option;
ts<<"\n";
}
QStringList rmList;
rmList << output+".Makefile";
for(const QVariant &i:sources)
{
rmList << removeExtension(i.toString())+".o";
}
#ifdef Q_OS_LINUX
ts<<QString("clean:\n\trm");
for(const QString &i:rmList)
{
ts<<QString(" %1").arg(i);
}
ts<<"\n";
rmList << output;
ts<<QString("full_clean:\n\trm");
for(const QString &i:rmList)
{
ts<<QString(" %1").arg(i);
}
#elif defined(Q_OS_WIN)
ts<<QString("clean:");
for(const QString &i:rmList)
{
ts<<QString("\n\tdel %1 /q").arg(i);
}
ts<<"\n";
rmList << output;
ts<<QString("clean:");
for(const QString &i:rmList)
{
ts<<QString("\n\tdel %1 /q").arg(i);
}
#endif
}
else Error(QObject::tr("Unknown value %2 in variable %1").arg("TEMPLATE",Template[0].toString()));
return str;
}
bool checkVariableSize(const QString& name,int min,int max,int mode)
{
if (mode==Error::DO_NOTHING)
{
if (!Data::isVariable(name)) return false;
const QVariantList& var = Data::getVariable(name);
if (var.size()>max) return false;
if (var.size()<min) return false;
return true;
}
if (!Data::isVariable(name)) throw Error(QObject::tr("varibale %1 not foud").arg(name));
const QVariantList& var = Data::getVariable(name);
if (var.size()>max) throw Error(QObject::tr("too much value in varibale %1").arg(name));
if (var.size()<min) throw Error(QObject::tr("too few value in varibale %1").arg(name));
return true;
}
<commit_msg>增加新参数CXX_FLAGS<commit_after>#include "makefilewritter.h"
#include "data.h"
#include "error.h"
#include "stringtools.h"
#include <QString>
#include <QTextStream>
#include <QObject>
#include <QRegExp>
#include <QVariantList>
#include <QVariant>
QString generateMakeFile()
{
QString str;
QTextStream ts(&str,QIODevice::WriteOnly);
checkVariableSize("TEMPLATE",1,1);
QVariantList Template = Data::getVariable("TEMPLATE");
QString option;
if (checkVariableSize("DEFINE",1,100000,Error::DO_NOTHING))
{
QVariantList var=Data::getVariable("DEFINE");
for(const QVariant& i:var)
{
option.append(QString(" -D%1").arg(i.toString()));
}
}
if (checkVariableSize("STD",1,10000,Error::DO_NOTHING))
{
QString var=Data::getVariable("STD").at(0).toString();
if (var=="c++11" || var=="c++0x") option.append(" -std=c++11");
else if(var=="c++14") option.append(" -std=c++14");
else if (var=="c++17" || var=="c++1z") option.append(" -std=c++17");
else if (var=="c++98") option.append(" -std=c++98");
else
{
//TODO: throw warning
}
}
if (checkVariableSize("DEBUG_MODE",1,10000,Error::DO_NOTHING))
{
QVariant var=Data::getVariable("DEBUG_MODE").at(0);
if (var.toString()=="true")
{
option.append(" -g");
}
else if (var.toString()=="false");
else
{
//TODO: throw warning
}
}
QString optimize="1";
if (checkVariableSize("OPTIMIZE",1,10000,Error::DO_NOTHING))
{
optimize=Data::getVariable("OPTIMIZE").at(0).toString();
}
option.push_back(QString(" -O%1").arg(optimize));
if (checkVariableSize("CXX_FLAGS",1,100000,Error::DO_NOTHING))
{
const QVariantList& cxx_flags=Data::getVariable("CXX_FLAGS");
for(const QVariant& i:cxx_flags)
{
option.push_back(" "+i.toString());
}
}
if (Template[0].toString()=="default")
{
checkVariableSize("OUTPUT",1,1);
const QString output=Data::getVariable("OUTPUT").at(0).toString();
checkVariableSize("SOURCES",1,10000);
const QVariantList& sources=Data::getVariable("SOURCES");
ts<<QString("%1 :").arg(output);
for(const QVariant &i:sources)
{
QString objFileName=removeExtension(i.toString())+".o";
ts<<QString(" %1").arg(objFileName);
}
#ifdef Q_OS_WIN
QString stack;
if (checkVariableSize("STACK",1,10000,Error::DO_NOTHING))
{
bool ok;
int var=Data::getVariable("DEBUG_MODE").at(0).toInt(&ok);
if (!ok)
{
//TODO: throw warning
}
else
{
stack=QString(" -Wl,--stack=%1").arg(var);
}
}
#endif
ts<<QString("\n\tg++ -o %1").arg(output);
for(const QVariant &i:sources)
{
QString objFileName=removeExtension(i.toString())+".o";
ts<<QString(" %1").arg(objFileName);
}
#ifdef Q_OS_WIN
ts<<stack;
#endif
ts<<option;
ts<<'\n';
for(const QVariant &i:sources)
{
QString objFileName=removeExtension(i.toString())+".o";
ts<<QString("%1 : %2\n\tg++ -c %2").arg(objFileName,i.toString());
ts<<option;
ts<<"\n";
}
QStringList rmList;
rmList << output+".Makefile";
for(const QVariant &i:sources)
{
rmList << removeExtension(i.toString())+".o";
}
#ifdef Q_OS_LINUX
ts<<QString("clean:\n\trm");
for(const QString &i:rmList)
{
ts<<QString(" %1").arg(i);
}
ts<<"\n";
rmList << output;
ts<<QString("full_clean:\n\trm");
for(const QString &i:rmList)
{
ts<<QString(" %1").arg(i);
}
#elif defined(Q_OS_WIN)
ts<<QString("clean:");
for(const QString &i:rmList)
{
ts<<QString("\n\tdel %1 /q").arg(i);
}
ts<<"\n";
rmList << output;
ts<<QString("clean:");
for(const QString &i:rmList)
{
ts<<QString("\n\tdel %1 /q").arg(i);
}
#endif
}
else Error(QObject::tr("Unknown value %2 in variable %1").arg("TEMPLATE",Template[0].toString()));
return str;
}
bool checkVariableSize(const QString& name,int min,int max,int mode)
{
if (mode==Error::DO_NOTHING)
{
if (!Data::isVariable(name)) return false;
const QVariantList& var = Data::getVariable(name);
if (var.size()>max) return false;
if (var.size()<min) return false;
return true;
}
if (!Data::isVariable(name)) throw Error(QObject::tr("varibale %1 not foud").arg(name));
const QVariantList& var = Data::getVariable(name);
if (var.size()>max) throw Error(QObject::tr("too much value in varibale %1").arg(name));
if (var.size()<min) throw Error(QObject::tr("too few value in varibale %1").arg(name));
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: astobserves.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: jsc $ $Date: 2001-03-15 12:23:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IDLC_ASTOBSERVES_HXX_
#define _IDLC_ASTOBSERVES_HXX_
#ifndef _IDLC_ASTINTERFACE_HXX_
#include <idlc/astinterface.hxx>
#endif
class AstObserves : public AstDeclaration
{
public:
AstObserves(AstInterface* pRealInterface, const ::rtl::OString& name, AstScope* pScope)
: AstDeclaration(NT_observes, name, pScope)
, m_pRealInterface(pRealInterface)
{}
virtual ~AstObserves() {}
AstInterface* getRealInterface()
{ return m_pRealInterface; }
private:
AstInterface* m_pRealInterface;
};
#endif // _IDLC_ASTOBSERVES_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.150); FILE MERGED 2005/09/05 17:39:32 rt 1.1.150.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: astobserves.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:58:57 $
*
* 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 _IDLC_ASTOBSERVES_HXX_
#define _IDLC_ASTOBSERVES_HXX_
#ifndef _IDLC_ASTINTERFACE_HXX_
#include <idlc/astinterface.hxx>
#endif
class AstObserves : public AstDeclaration
{
public:
AstObserves(AstInterface* pRealInterface, const ::rtl::OString& name, AstScope* pScope)
: AstDeclaration(NT_observes, name, pScope)
, m_pRealInterface(pRealInterface)
{}
virtual ~AstObserves() {}
AstInterface* getRealInterface()
{ return m_pRealInterface; }
private:
AstInterface* m_pRealInterface;
};
#endif // _IDLC_ASTOBSERVES_HXX_
<|endoftext|> |
<commit_before>// @(#)root/utils:$Id$
// Author: Philippe Canal 27/08/2003
/*************************************************************************
* Copyright (C) 1995-2003, Rene Brun, Fons Rademakers, and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS *
*************************************************************************/
#include "RConfigure.h"
#include "RConfig.h"
#include "Api.h"
#include "RStl.h"
#include "TClassEdit.h"
using namespace TClassEdit;
#include <stdio.h>
using namespace std;
// From the not-existing yet rootcint.h
void WriteClassInit(G__ClassInfo &cl);
void WriteAuxFunctions(G__ClassInfo &cl);
int ElementStreamer(G__TypeInfo &ti,const char *R__t,int rwmode,const char *tcl=0);
#ifndef ROOT_Varargs
#include "Varargs.h"
#endif
void Error(const char *location, const char *va_(fmt), ...);
void Warning(const char *location, const char *va_(fmt), ...);
//
// ROOT::RStl is the rootcint STL handling class.
//
ROOT::RStl& ROOT::RStl::Instance()
{
// Return the singleton ROOT::RStl.
static ROOT::RStl instance;
return instance;
}
void ROOT::RStl::GenerateTClassFor(const string& stlclassname)
{
// Force the generation of the TClass for the given class.
G__ClassInfo cl(TClassEdit::ShortType(stlclassname.c_str(),
TClassEdit::kDropTrailStar).c_str());
if ( ! cl.IsValid() ) {
Error("RStl::GenerateTClassFor","%s not in the CINT dictionary",
stlclassname.c_str());
return;
}
string registername( TClassEdit::ShortType(cl.Name(),
TClassEdit::kDropStlDefault ) );
// fprintf(stderr,"registering %s as %s %s\n",
// stlclassname.c_str(), cl.Name(), registername.c_str());
int nestedLoc=0;
vector<string> splitName;
TClassEdit::GetSplit(registername.c_str(),splitName,nestedLoc);
if ( TClassEdit::STLKind( splitName[0].c_str() ) == TClassEdit::kVector ) {
if ( splitName[1] == "bool" || splitName[1]=="Bool_t") {
Warning("std::vector<bool>", " is not fully supported yet!\nUse std::vector<char> or std::deque<bool> instead.\n");
}
}
fList.insert(registername);
// We also should register the template arguments if they are STL.
for(unsigned int i=1 ; i<splitName.size(); ++i) {
if ( TClassEdit::IsSTLCont( splitName[i].c_str()) != 0 ) {
GenerateTClassFor( splitName[i] );
}
}
// fprintf(stderr,"ROOT::RStl registered %s as %s\n",stlclassname.c_str(),registername.c_str());
}
void ROOT::RStl::Print()
{
// Print the content of the object
fprintf(stderr,"ROOT::RStl singleton\n");
set<string>::iterator iter;
for(iter = fList.begin(); iter != fList.end(); ++iter) {
fprintf(stderr, "need TClass for %s\n", (*iter).c_str());
}
}
string ROOT::RStl::DropDefaultArg(const string &classname)
{
// Remove the default argument from the stl container.
G__ClassInfo cl(classname.c_str());
if ( cl.TmpltName() == 0 ) return classname;
if ( TClassEdit::STLKind( cl.TmpltName() ) == 0 ) return classname;
return TClassEdit::ShortType( cl.Fullname(),
TClassEdit::kDropStlDefault );
}
void ROOT::RStl::WriteClassInit(FILE* /*file*/)
{
// This function writes the TGeneraticClassInfo initialiser
// and the auxiliary functions (new and delete wrappers) for
// each of the STL containers that have been registered
set<string>::iterator iter;
G__ClassInfo cl;
for(iter = fList.begin(); iter != fList.end(); ++iter) {
cl.Init( (*iter).c_str() );
::WriteClassInit( cl );
::WriteAuxFunctions( cl );
}
}
void ROOT::RStl::WriteStreamer(FILE *file, G__ClassInfo &stlcl)
{
// Write the free standing streamer function for the given
// STL container class.
string streamerName = "stl_streamer_";
string shortTypeName = GetLong64_Name( TClassEdit::ShortType(stlcl.Name(),TClassEdit::kDropStlDefault) );
string noConstTypeName( TClassEdit::CleanType(shortTypeName.c_str(),2) );
streamerName += G__map_cpp_name((char *)shortTypeName.c_str());
string typedefName = G__map_cpp_name((char *)shortTypeName.c_str());
int nestedLoc=0;
vector<string> splitName;
TClassEdit::GetSplit(shortTypeName.c_str(),splitName,nestedLoc);
int stltype = TClassEdit::STLKind(splitName[0].c_str());
G__TypeInfo firstType(splitName[1].c_str());
G__TypeInfo secondType;
const char *tclFirst=0,*tclSecond=0;
string firstFullName, secondFullName;
if (ElementStreamer(firstType,0,0)) {
tclFirst = "R__tcl1";
const char *name = firstType.Fullname();
if (name) {
// the value return by ti.Fullname is a static buffer
// so we have to copy it immeditately
firstFullName = TClassEdit::ShortType(name,TClassEdit::kDropStlDefault);
} else {
// ti is a simple type name
firstFullName = firstType.TrueName();
}
}
if (stltype==kMap || stltype==kMultiMap) {
secondType.Init( splitName[2].c_str());
if (ElementStreamer(secondType,0,0)) {
tclSecond="R__tcl2";
const char *name = secondType.Fullname();
if (name) {
// the value return by ti.Fullname is a static buffer
// so we have to copy it immeditately
secondFullName = TClassEdit::ShortType(name,TClassEdit::kDropStlDefault);
} else {
// ti is a simple type name
secondFullName = secondType.TrueName();
}
}
}
fprintf(file, "//___________________________________________________________");
fprintf(file, "_____________________________________________________________\n");
fprintf(file, "namespace ROOT {\n");
fprintf(file, " typedef %s %s;\n",shortTypeName.c_str(), typedefName.c_str());
fprintf(file, " static void %s(TBuffer &R__b, void *R__p)\n",streamerName.c_str());
fprintf(file, " {\n");
fprintf(file, " if (gDebug>1) Info(__FILE__,\"Running compiled streamer for %s at %%p\",R__p);\n",shortTypeName.c_str());
fprintf(file, " %s &R__stl = *(%s *)R__p;\n",shortTypeName.c_str(),shortTypeName.c_str());
fprintf(file, " if (R__b.IsReading()) {\n");
fprintf(file, " R__stl.clear();\n");
if (tclFirst)
fprintf(file, " TClass *R__tcl1 = TBuffer::GetClass(typeid(%s));\n",
firstFullName.c_str());
if (tclSecond)
fprintf(file, " TClass *R__tcl2 = TBuffer::GetClass(typeid(%s));\n",
secondFullName.c_str());
fprintf(file, " int R__i, R__n;\n");
fprintf(file, " R__b >> R__n;\n");
if (stltype==kVector) {
fprintf(file," R__stl.reserve(R__n);\n");
}
fprintf(file, " for (R__i = 0; R__i < R__n; R__i++) {\n");
ElementStreamer(firstType,"R__t",0,tclFirst);
if (stltype == kMap || stltype == kMultiMap) { //Second Arg
ElementStreamer(secondType,"R__t2",0,tclSecond);
}
switch (stltype) {
case kMap:
case kMultiMap:
fprintf(file, " R__stl.insert(make_pair(R__t,R__t2));\n");
break;
case kSet:
case kMultiSet:
fprintf(file, " R__stl.insert(R__t);\n");
break;
case kVector:
case kList:
case kDeque:
fprintf(file, " R__stl.push_back(R__t);\n");
break;
default:
assert(0);
}
fprintf(file, " }\n");
fprintf(file, " } else {\n");
fprintf(file, " int R__n=(&R__stl) ? int(R__stl.size()) : 0;\n");
fprintf(file, " R__b << R__n;\n");
fprintf(file, " if(R__n) {\n");
if (tclFirst) {
fprintf(file, " TClass *R__tcl1 = TBuffer::GetClass(typeid(%s));\n",
firstFullName.c_str());
fprintf(file, " if (R__tcl1==0) {\n");
fprintf(file, " Error(\"%s streamer\",\"Missing the TClass object for %s!\");\n",
shortTypeName.c_str(), firstFullName.c_str());
fprintf(file, " return;\n");
fprintf(file, " }\n");
}
if (tclSecond) {
fprintf(file, " TClass *R__tcl2 = TBuffer::GetClass(typeid(%s));\n",
secondFullName.c_str());
fprintf(file, " if (R__tcl2==0) {\n");
fprintf(file, " Error(\"%s streamer\",\"Missing the TClass object for %s!\");\n",
shortTypeName.c_str(), secondFullName.c_str());
fprintf(file, " return;\n");
fprintf(file, " }\n");
}
fprintf(file, " %s::iterator R__k;\n", shortTypeName.c_str());
fprintf(file, " for (R__k = R__stl.begin(); R__k != R__stl.end(); ++R__k) {\n");
if (stltype == kMap || stltype == kMultiMap) {
ElementStreamer(firstType ,"((*R__k).first )",1,tclFirst);
ElementStreamer(secondType,"((*R__k).second)",1,tclSecond);
} else {
ElementStreamer(firstType ,"(*R__k)" ,1,tclFirst);
}
fprintf(file, " }\n");
fprintf(file, " }\n");
fprintf(file, " }\n");
fprintf(file, " } // end of %s streamer\n",stlcl.Fullname());
fprintf(file, "} // close namespace ROOT\n\n");
fprintf(file, "// Register the streamer (a typedef is used to avoid problem with macro parameters\n");
//if ( 0 != ::getenv("MY_ROOT") && ::getenv("MY_ROOT")[0]>'1' ) {
// fprintf(file, "// Disabled due customized build:\n// ");
//}
fprintf(file, "RootStlStreamer(%s,%s)\n", typedefName.c_str(), streamerName.c_str());
fprintf(file, "\n");
}
void ROOT::RStl::WriteStreamer(FILE *file)
{
// Write the free standing streamer function for the registereed
// STL container classes
set<string>::iterator iter;
G__ClassInfo cl;
for(iter = fList.begin(); iter != fList.end(); ++iter) {
cl.Init( (*iter).c_str() );
WriteStreamer(file,cl);
}
}
<commit_msg>Try to make MSVC++ happy<commit_after>// @(#)root/utils:$Id$
// Author: Philippe Canal 27/08/2003
/*************************************************************************
* Copyright (C) 1995-2003, Rene Brun, Fons Rademakers, and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS *
*************************************************************************/
#include "RConfigure.h"
#include "RConfig.h"
#include "Api.h"
#include "RStl.h"
#include "TClassEdit.h"
using namespace TClassEdit;
#include <stdio.h>
// From the not-existing yet rootcint.h
void WriteClassInit(G__ClassInfo &cl);
void WriteAuxFunctions(G__ClassInfo &cl);
int ElementStreamer(G__TypeInfo &ti,const char *R__t,int rwmode,const char *tcl=0);
#ifndef ROOT_Varargs
#include "Varargs.h"
#endif
void Error(const char *location, const char *va_(fmt), ...);
void Warning(const char *location, const char *va_(fmt), ...);
//
// ROOT::RStl is the rootcint STL handling class.
//
ROOT::RStl& ROOT::RStl::Instance()
{
// Return the singleton ROOT::RStl.
static ROOT::RStl instance;
return instance;
}
void ROOT::RStl::GenerateTClassFor(const std::string& stlclassname)
{
// Force the generation of the TClass for the given class.
G__ClassInfo cl(TClassEdit::ShortType(stlclassname.c_str(),
TClassEdit::kDropTrailStar).c_str());
if ( ! cl.IsValid() ) {
Error("RStl::GenerateTClassFor","%s not in the CINT dictionary",
stlclassname.c_str());
return;
}
std::string registername( TClassEdit::ShortType(cl.Name(),
TClassEdit::kDropStlDefault ) );
// fprintf(stderr,"registering %s as %s %s\n",
// stlclassname.c_str(), cl.Name(), registername.c_str());
int nestedLoc=0;
std::vector<std::string> splitName;
TClassEdit::GetSplit(registername.c_str(),splitName,nestedLoc);
if ( TClassEdit::STLKind( splitName[0].c_str() ) == TClassEdit::kVector ) {
if ( splitName[1] == "bool" || splitName[1]=="Bool_t") {
Warning("std::vector<bool>", " is not fully supported yet!\nUse std::vector<char> or std::deque<bool> instead.\n");
}
}
fList.insert(registername);
// We also should register the template arguments if they are STL.
for(unsigned int i=1 ; i<splitName.size(); ++i) {
if ( TClassEdit::IsSTLCont( splitName[i].c_str()) != 0 ) {
GenerateTClassFor( splitName[i] );
}
}
// fprintf(stderr,"ROOT::RStl registered %s as %s\n",stlclassname.c_str(),registername.c_str());
}
void ROOT::RStl::Print()
{
// Print the content of the object
fprintf(stderr,"ROOT::RStl singleton\n");
std::set<std::string>::iterator iter;
for(iter = fList.begin(); iter != fList.end(); ++iter) {
fprintf(stderr, "need TClass for %s\n", (*iter).c_str());
}
}
std::string ROOT::RStl::DropDefaultArg(const std::string &classname)
{
// Remove the default argument from the stl container.
G__ClassInfo cl(classname.c_str());
if ( cl.TmpltName() == 0 ) return classname;
if ( TClassEdit::STLKind( cl.TmpltName() ) == 0 ) return classname;
return TClassEdit::ShortType( cl.Fullname(),
TClassEdit::kDropStlDefault );
}
void ROOT::RStl::WriteClassInit(FILE* /*file*/)
{
// This function writes the TGeneraticClassInfo initialiser
// and the auxiliary functions (new and delete wrappers) for
// each of the STL containers that have been registered
std::set<std::string>::iterator iter;
G__ClassInfo cl;
for(iter = fList.begin(); iter != fList.end(); ++iter) {
cl.Init( (*iter).c_str() );
::WriteClassInit( cl );
::WriteAuxFunctions( cl );
}
}
void ROOT::RStl::WriteStreamer(FILE *file, G__ClassInfo &stlcl)
{
// Write the free standing streamer function for the given
// STL container class.
std::string streamerName = "stl_streamer_";
std::string shortTypeName = GetLong64_Name( TClassEdit::ShortType(stlcl.Name(),TClassEdit::kDropStlDefault) );
std::string noConstTypeName( TClassEdit::CleanType(shortTypeName.c_str(),2) );
streamerName += G__map_cpp_name((char *)shortTypeName.c_str());
std::string typedefName = G__map_cpp_name((char *)shortTypeName.c_str());
int nestedLoc=0;
std::vector<std::string> splitName;
TClassEdit::GetSplit(shortTypeName.c_str(),splitName,nestedLoc);
int stltype = TClassEdit::STLKind(splitName[0].c_str());
G__TypeInfo firstType(splitName[1].c_str());
G__TypeInfo secondType;
const char *tclFirst=0,*tclSecond=0;
std::string firstFullName, secondFullName;
if (ElementStreamer(firstType,0,0)) {
tclFirst = "R__tcl1";
const char *name = firstType.Fullname();
if (name) {
// the value return by ti.Fullname is a static buffer
// so we have to copy it immeditately
firstFullName = TClassEdit::ShortType(name,TClassEdit::kDropStlDefault);
} else {
// ti is a simple type name
firstFullName = firstType.TrueName();
}
}
if (stltype==kMap || stltype==kMultiMap) {
secondType.Init( splitName[2].c_str());
if (ElementStreamer(secondType,0,0)) {
tclSecond="R__tcl2";
const char *name = secondType.Fullname();
if (name) {
// the value return by ti.Fullname is a static buffer
// so we have to copy it immeditately
secondFullName = TClassEdit::ShortType(name,TClassEdit::kDropStlDefault);
} else {
// ti is a simple type name
secondFullName = secondType.TrueName();
}
}
}
fprintf(file, "//___________________________________________________________");
fprintf(file, "_____________________________________________________________\n");
fprintf(file, "namespace ROOT {\n");
fprintf(file, " typedef %s %s;\n",shortTypeName.c_str(), typedefName.c_str());
fprintf(file, " static void %s(TBuffer &R__b, void *R__p)\n",streamerName.c_str());
fprintf(file, " {\n");
fprintf(file, " if (gDebug>1) Info(__FILE__,\"Running compiled streamer for %s at %%p\",R__p);\n",shortTypeName.c_str());
fprintf(file, " %s &R__stl = *(%s *)R__p;\n",shortTypeName.c_str(),shortTypeName.c_str());
fprintf(file, " if (R__b.IsReading()) {\n");
fprintf(file, " R__stl.clear();\n");
if (tclFirst)
fprintf(file, " TClass *R__tcl1 = TBuffer::GetClass(typeid(%s));\n",
firstFullName.c_str());
if (tclSecond)
fprintf(file, " TClass *R__tcl2 = TBuffer::GetClass(typeid(%s));\n",
secondFullName.c_str());
fprintf(file, " int R__i, R__n;\n");
fprintf(file, " R__b >> R__n;\n");
if (stltype==kVector) {
fprintf(file," R__stl.reserve(R__n);\n");
}
fprintf(file, " for (R__i = 0; R__i < R__n; R__i++) {\n");
ElementStreamer(firstType,"R__t",0,tclFirst);
if (stltype == kMap || stltype == kMultiMap) { //Second Arg
ElementStreamer(secondType,"R__t2",0,tclSecond);
}
switch (stltype) {
case kMap:
case kMultiMap:
fprintf(file, " R__stl.insert(make_pair(R__t,R__t2));\n");
break;
case kSet:
case kMultiSet:
fprintf(file, " R__stl.insert(R__t);\n");
break;
case kVector:
case kList:
case kDeque:
fprintf(file, " R__stl.push_back(R__t);\n");
break;
default:
assert(0);
}
fprintf(file, " }\n");
fprintf(file, " } else {\n");
fprintf(file, " int R__n=(&R__stl) ? int(R__stl.size()) : 0;\n");
fprintf(file, " R__b << R__n;\n");
fprintf(file, " if(R__n) {\n");
if (tclFirst) {
fprintf(file, " TClass *R__tcl1 = TBuffer::GetClass(typeid(%s));\n",
firstFullName.c_str());
fprintf(file, " if (R__tcl1==0) {\n");
fprintf(file, " Error(\"%s streamer\",\"Missing the TClass object for %s!\");\n",
shortTypeName.c_str(), firstFullName.c_str());
fprintf(file, " return;\n");
fprintf(file, " }\n");
}
if (tclSecond) {
fprintf(file, " TClass *R__tcl2 = TBuffer::GetClass(typeid(%s));\n",
secondFullName.c_str());
fprintf(file, " if (R__tcl2==0) {\n");
fprintf(file, " Error(\"%s streamer\",\"Missing the TClass object for %s!\");\n",
shortTypeName.c_str(), secondFullName.c_str());
fprintf(file, " return;\n");
fprintf(file, " }\n");
}
fprintf(file, " %s::iterator R__k;\n", shortTypeName.c_str());
fprintf(file, " for (R__k = R__stl.begin(); R__k != R__stl.end(); ++R__k) {\n");
if (stltype == kMap || stltype == kMultiMap) {
ElementStreamer(firstType ,"((*R__k).first )",1,tclFirst);
ElementStreamer(secondType,"((*R__k).second)",1,tclSecond);
} else {
ElementStreamer(firstType ,"(*R__k)" ,1,tclFirst);
}
fprintf(file, " }\n");
fprintf(file, " }\n");
fprintf(file, " }\n");
fprintf(file, " } // end of %s streamer\n",stlcl.Fullname());
fprintf(file, "} // close namespace ROOT\n\n");
fprintf(file, "// Register the streamer (a typedef is used to avoid problem with macro parameters\n");
//if ( 0 != ::getenv("MY_ROOT") && ::getenv("MY_ROOT")[0]>'1' ) {
// fprintf(file, "// Disabled due customized build:\n// ");
//}
fprintf(file, "RootStlStreamer(%s,%s)\n", typedefName.c_str(), streamerName.c_str());
fprintf(file, "\n");
}
void ROOT::RStl::WriteStreamer(FILE *file)
{
// Write the free standing streamer function for the registereed
// STL container classes
std::set<std::string>::iterator iter;
G__ClassInfo cl;
for(iter = fList.begin(); iter != fList.end(); ++iter) {
cl.Init( (*iter).c_str() );
WriteStreamer(file,cl);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
// #define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"
using namespace std;
void helloword(const httplib::Request& req, httplib::Response& rsp)
{
printf("httplib server recv a req: %s %s\n ", req.path.c_str(), req.remote_addr.c_str());
// std::string str = R "( <html lang= ><h1> 武汉, 加油!</h1></html>)";
// std::string s1 = R "a(C:\Users\Administrator\Desktop\RWtest\write.txt)a";
std::string s= R"foo(
C:\Users\Administrator\Desktop\RWtes
)foo";
const char* s1 = R"foo(
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<h1> 武汉, 加油!</h1></html>
)foo";
rsp.set_content(s, "text/html"); //最后一个参数是正文类型
rsp.status = 200;
}
void helloword1(const httplib::Request& req, httplib::Response& rsp)
{
printf("httplib server recv a req: %s %s\n ", req.path.c_str(), req.remote_addr.c_str());
// std::string str = R "( <html lang= ><h1> 武汉, 加油!</h1></html>)";
// std::string s1 = R "a(C:\Users\Administrator\Desktop\RWtest\write.txt)a";
std::string s= R"foo(
C:\Users\Administrator\Desktop\RWtes
)foo";
const char* s1 = R"AAA(
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<h1> 武汉, 加油!</h1></html>
)AAA";
rsp.set_content(s1, "text/html"); //最后一个参数是正文类型
rsp.status = 200;
}
int main(int argc, char** argv)
{
httplib::SSLServer srv;
srv.Get("/", helloword1);
srv.Get("^/.*$", helloword);
srv.listen("0.0.0.0", 9000);
getchar();
return 0;
}<commit_msg>github ci aarch64 try fix Could NOT find OpenSSL remove CPPHTTPLIB_OPENSSL_SUPPORT 1<commit_after>#include <iostream>
#include <string>
// #define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"
using namespace std;
void helloword(const httplib::Request& req, httplib::Response& rsp)
{
printf("httplib server recv a req: %s %s\n ", req.path.c_str(), req.remote_addr.c_str());
// std::string str = R "( <html lang= ><h1> 武汉, 加油!</h1></html>)";
// std::string s1 = R "a(C:\Users\Administrator\Desktop\RWtest\write.txt)a";
std::string s= R"foo(
C:\Users\Administrator\Desktop\RWtes
)foo";
const char* s1 = R"foo(
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<h1> 武汉, 加油!</h1></html>
)foo";
rsp.set_content(s, "text/html"); //最后一个参数是正文类型
rsp.status = 200;
}
void helloword1(const httplib::Request& req, httplib::Response& rsp)
{
printf("httplib server recv a req: %s %s\n ", req.path.c_str(), req.remote_addr.c_str());
// std::string str = R "( <html lang= ><h1> 武汉, 加油!</h1></html>)";
// std::string s1 = R "a(C:\Users\Administrator\Desktop\RWtest\write.txt)a";
std::string s= R"foo(
C:\Users\Administrator\Desktop\RWtes
)foo";
const char* s1 = R"AAA(
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<h1> 武汉, 加油!</h1></html>
)AAA";
rsp.set_content(s1, "text/html"); //最后一个参数是正文类型
rsp.status = 200;
}
int main(int argc, char** argv)
{
httplib::Server srv;
srv.Get("/", helloword1);
srv.Get("^/.*$", helloword);
srv.listen("0.0.0.0", 9000);
getchar();
return 0;
}<|endoftext|> |
<commit_before>/**
* @file Cosa/RTC.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2012-2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/RTC.hh"
#include "Cosa/Power.hh"
// Real-Time Clock configuration
#define COUNT 250
#define PRESCALE 64
#define US_PER_TIMER_CYCLE (PRESCALE / I_CPU)
#define US_PER_TICK (COUNT * US_PER_TIMER_CYCLE)
#define US_PER_MS 1000
#define MS_PER_SEC 1000
#define MS_PER_TICK (US_PER_TICK / 1000)
// Initiated state
bool RTC::s_initiated = false;
// Timer ticks counter
volatile uint32_t RTC::s_uticks = 0UL;
// Milli-seconds counter
volatile uint32_t RTC::s_ms = 0UL;
// Seconds counter with milli-seconds fraction
volatile uint16_t RTC::s_msec = 0;
volatile clock_t RTC::s_sec = 0UL;
// Timer interrupt extension
RTC::InterruptHandler RTC::s_handler = NULL;
void* RTC::s_env = NULL;
bool
RTC::begin()
{
if (UNLIKELY(s_initiated)) return (false);
synchronized {
// Set prescaling to 64
TCCR0B = (_BV(CS01) | _BV(CS00));
// Clear Timer on Compare Match
TCCR0A = _BV(WGM01);
OCR0A = COUNT;
// And enable interrupt on match
TIMSK0 = _BV(OCIE0A);
// Reset the counter and clear interrupts
TCNT0 = 0;
TIFR0 = 0;
}
// Install delay function and mark as initiated
::delay = RTC::delay;
s_initiated = true;
return (true);
}
bool
RTC::end()
{
// Check if initiated
if (UNLIKELY(!s_initiated)) return (false);
// Disable the timer interrupts and mark as not initiated
synchronized TIMSK0 = 0;
s_initiated = false;
return (true);
}
uint16_t
RTC::us_per_tick()
{
return (US_PER_TICK);
}
uint16_t
RTC::us_per_timer_cycle()
{
return (US_PER_TIMER_CYCLE);
}
uint32_t
RTC::micros()
{
uint32_t res;
uint8_t cnt;
// Read tick count and hardware counter. Adjust if pending interrupt
synchronized {
res = s_uticks;
cnt = TCNT0;
if ((TIFR0 & _BV(OCF0A)) && cnt < COUNT) res += US_PER_TICK;
}
// Convert ticks to micro-seconds
res += ((uint32_t) cnt) * US_PER_TIMER_CYCLE;
return (res);
}
void
RTC::delay(uint32_t ms)
{
uint32_t start = RTC::millis();
ms += 1;
while (RTC::since(start) < ms) yield();
}
int
RTC::await(volatile bool &condvar, uint32_t ms)
{
if (ms != 0) {
uint32_t start = millis();
ms += 1;
while (!condvar && since(start) < ms) yield();
if (UNLIKELY(!condvar)) return (ETIME);
}
else {
while (!condvar) yield();
}
return (0);
}
ISR(TIMER0_COMPA_vect)
{
// Increment most significant part of micro seconds counter
RTC::s_uticks += US_PER_TICK;
// Increment milli-seconds counter
RTC::s_ms += MS_PER_TICK;
// Increment milli-seconds fraction of seconds counter
RTC::s_msec += MS_PER_TICK;
// Check for increment of seconds counter
if (UNLIKELY(RTC::s_msec >= MS_PER_SEC)) {
RTC::s_msec -= MS_PER_SEC;
RTC::s_sec += 1;
}
// Check for extension of the interrupt handler
RTC::InterruptHandler fn = RTC::s_handler;
void* env = RTC::s_env;
if (UNLIKELY(fn == NULL)) return;
// Callback to extension function
fn(env);
}
<commit_msg>Do not adjust delay parameter.<commit_after>/**
* @file Cosa/RTC.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2012-2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/RTC.hh"
#include "Cosa/Power.hh"
// Real-Time Clock configuration
#define COUNT 250
#define PRESCALE 64
#define US_PER_TIMER_CYCLE (PRESCALE / I_CPU)
#define US_PER_TICK (COUNT * US_PER_TIMER_CYCLE)
#define US_PER_MS 1000
#define MS_PER_SEC 1000
#define MS_PER_TICK (US_PER_TICK / 1000)
// Initiated state
bool RTC::s_initiated = false;
// Timer ticks counter
volatile uint32_t RTC::s_uticks = 0UL;
// Milli-seconds counter
volatile uint32_t RTC::s_ms = 0UL;
// Seconds counter with milli-seconds fraction
volatile uint16_t RTC::s_msec = 0;
volatile clock_t RTC::s_sec = 0UL;
// Timer interrupt extension
RTC::InterruptHandler RTC::s_handler = NULL;
void* RTC::s_env = NULL;
bool
RTC::begin()
{
if (UNLIKELY(s_initiated)) return (false);
synchronized {
// Set prescaling to 64
TCCR0B = (_BV(CS01) | _BV(CS00));
// Clear Timer on Compare Match
TCCR0A = _BV(WGM01);
OCR0A = COUNT;
// And enable interrupt on match
TIMSK0 = _BV(OCIE0A);
// Reset the counter and clear interrupts
TCNT0 = 0;
TIFR0 = 0;
}
// Install delay function and mark as initiated
::delay = RTC::delay;
s_initiated = true;
return (true);
}
bool
RTC::end()
{
// Check if initiated
if (UNLIKELY(!s_initiated)) return (false);
// Disable the timer interrupts and mark as not initiated
synchronized TIMSK0 = 0;
s_initiated = false;
return (true);
}
uint16_t
RTC::us_per_tick()
{
return (US_PER_TICK);
}
uint16_t
RTC::us_per_timer_cycle()
{
return (US_PER_TIMER_CYCLE);
}
uint32_t
RTC::micros()
{
uint32_t res;
uint8_t cnt;
// Read tick count and hardware counter. Adjust if pending interrupt
synchronized {
res = s_uticks;
cnt = TCNT0;
if ((TIFR0 & _BV(OCF0A)) && cnt < COUNT) res += US_PER_TICK;
}
// Convert ticks to micro-seconds
res += ((uint32_t) cnt) * US_PER_TIMER_CYCLE;
return (res);
}
void
RTC::delay(uint32_t ms)
{
uint32_t start = RTC::millis();
while (RTC::since(start) < ms) yield();
}
int
RTC::await(volatile bool &condvar, uint32_t ms)
{
if (ms != 0) {
uint32_t start = millis();
while (!condvar && since(start) < ms) yield();
if (UNLIKELY(!condvar)) return (ETIME);
}
else {
while (!condvar) yield();
}
return (0);
}
ISR(TIMER0_COMPA_vect)
{
// Increment most significant part of micro seconds counter
RTC::s_uticks += US_PER_TICK;
// Increment milli-seconds counter
RTC::s_ms += MS_PER_TICK;
// Increment milli-seconds fraction of seconds counter
RTC::s_msec += MS_PER_TICK;
// Check for increment of seconds counter
if (UNLIKELY(RTC::s_msec >= MS_PER_SEC)) {
RTC::s_msec -= MS_PER_SEC;
RTC::s_sec += 1;
}
// Check for extension of the interrupt handler
RTC::InterruptHandler fn = RTC::s_handler;
void* env = RTC::s_env;
if (UNLIKELY(fn == NULL)) return;
// Callback to extension function
fn(env);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <CellColorHandler.hxx>
#include <PropertyMap.hxx>
#include <doctok/resourceids.hxx>
#include <ConversionHelper.hxx>
#include <ooxml/resourceids.hxx>
#include <com/sun/star/drawing/ShadingPattern.hpp>
#include <sal/macros.h>
#include "dmapperLoggers.hxx"
#define OOXML_COLOR_AUTO 0x0a //todo: AutoColor needs symbol
namespace writerfilter {
namespace dmapper {
using namespace ::com::sun::star::drawing;
using namespace ::writerfilter;
CellColorHandler::CellColorHandler() :
LoggedProperties(dmapper_logger, "CellColorHandler"),
m_nShadingPattern( ShadingPattern::CLEAR ),
m_nColor( 0xffffffff ),
m_nFillColor( 0xffffffff ),
m_OutputFormat( Form )
{
}
CellColorHandler::~CellColorHandler()
{
}
void CellColorHandler::lcl_attribute(Id rName, Value & rVal)
{
OUString stringValue = rVal.getString();
sal_Int32 nIntValue = rVal.getInt();
switch( rName )
{
case NS_rtf::LN_cellTopColor:
case NS_rtf::LN_cellLeftColor:
case NS_rtf::LN_cellBottomColor:
case NS_rtf::LN_cellRightColor:
// nIntValue contains the color, directly
break;
case NS_ooxml::LN_CT_Shd_val:
{
//might be clear, pct5...90, some hatch types
//TODO: The values need symbolic names!
m_nShadingPattern = nIntValue; //clear == 0, solid: 1, pct5: 2, pct50:8, pct95: x3c, horzStripe:0x0e, thinVertStripe: 0x15
}
break;
case NS_ooxml::LN_CT_Shd_fill:
if( nIntValue == OOXML_COLOR_AUTO )
nIntValue = 0xffffff; //fill color auto means white
m_nFillColor = nIntValue;
break;
case NS_ooxml::LN_CT_Shd_color:
if( nIntValue == OOXML_COLOR_AUTO )
nIntValue = 0; //shading color auto means black
//color of the shading
m_nColor = nIntValue;
break;
case NS_ooxml::LN_CT_Shd_themeFill:
case NS_ooxml::LN_CT_Shd_themeFillTint:
case NS_ooxml::LN_CT_Shd_themeFillShade:
// ignored
break;
default:
OSL_FAIL( "unknown attribute");
}
}
void CellColorHandler::lcl_sprm(Sprm & rSprm)
{
(void)rSprm;
}
TablePropertyMapPtr CellColorHandler::getProperties()
{
TablePropertyMapPtr pPropertyMap(new TablePropertyMap);
// Code from binary word filter (the values are out of 1000)
static const sal_Int32 eMSGrayScale[] =
{
// Clear-Brush
0, // 0 clear
// Solid-Brush
1000, // 1 solid
// Percent values
50, // 2 pct5
100, // 3 pct10
200, // 4 pct20
250, // 5 pct25
300, // 6 pct30
400, // 7 pct40
500, // 8 pct50
600, // 9 pct60
700, // 10 pct70
750, // 11 pct75
800, // 12 pct80
900, // 13 pct90
// Special cases
333, // 14 Dark Horizontal
333, // 15 Dark Vertical
333, // 16 Dark Forward Diagonal
333, // 17 Dark Backward Diagonal
333, // 18 Dark Cross
333, // 19 Dark Diagonal Cross
333, // 20 Horizontal
333, // 21 Vertical
333, // 22 Forward Diagonal
333, // 23 Backward Diagonal
333, // 24 Cross
333, // 25 Diagonal Cross
// Undefined values in DOC spec-sheet
500, // 26
500, // 27
500, // 28
500, // 29
500, // 30
500, // 31
500, // 32
500, // 33
500, // 34
// Different shading types
25, // 35 [available in DOC, not available in DOCX]
75, // 36 [available in DOC, not available in DOCX]
125, // 37 pct12
150, // 38 pct15
175, // 39 [available in DOC, not available in DOCX]
225, // 40 [available in DOC, not available in DOCX]
275, // 41 [available in DOC, not available in DOCX]
325, // 42 [available in DOC, not available in DOCX]
350, // 43 pct35
375, // 44 pct37
425, // 45 [available in DOC, not available in DOCX]
450, // 46 pct45
475, // 47 [available in DOC, not available in DOCX]
525, // 48 [available in DOC, not available in DOCX]
550, // 49 pct55
575, // 50 [available in DOC, not available in DOCX]
625, // 51 pct62
650, // 52 pct65
675, // 53 [available in DOC, not available in DOCX]
725, // 54 [available in DOC, not available in DOCX]
775, // 55 [available in DOC, not available in DOCX]
825, // 56 [available in DOC, not available in DOCX]
850, // 57 pct85
875, // 58 pct87
925, // 59 [available in DOC, not available in DOCX]
950, // 60 pct95
975 // 61 [available in DOC, not available in DOCX]
};// 62
if( m_nShadingPattern >= (sal_Int32)SAL_N_ELEMENTS( eMSGrayScale ) )
m_nShadingPattern = 0;
sal_Int32 nWW8BrushStyle = eMSGrayScale[m_nShadingPattern];
sal_Int32 nApplyColor = 0;
if( !nWW8BrushStyle )
{
// Clear-Brush
nApplyColor = m_nFillColor;
}
else
{
sal_Int32 nFore = m_nColor;
sal_Int32 nBack = m_nFillColor;
sal_uInt32 nRed = ((nFore & 0xff0000)>>0x10) * nWW8BrushStyle;
sal_uInt32 nGreen = ((nFore & 0xff00)>>0x8) * nWW8BrushStyle;
sal_uInt32 nBlue = (nFore & 0xff) * nWW8BrushStyle;
nRed += ((nBack & 0xff0000)>>0x10) * (1000L - nWW8BrushStyle);
nGreen += ((nBack & 0xff00)>>0x8)* (1000L - nWW8BrushStyle);
nBlue += (nBack & 0xff) * (1000L - nWW8BrushStyle);
nApplyColor = ( (nRed/1000) << 0x10 ) + ((nGreen/1000) << 8) + nBlue/1000;
}
// Check if it is a 'Character'
if (m_OutputFormat == Character)
{
static sal_Int32 aWWShadingPatterns[ ] =
{
ShadingPattern::CLEAR,
ShadingPattern::SOLID,
ShadingPattern::PCT5,
ShadingPattern::PCT10,
ShadingPattern::PCT20,
ShadingPattern::PCT25,
ShadingPattern::PCT30,
ShadingPattern::PCT40,
ShadingPattern::PCT50,
ShadingPattern::PCT60,
ShadingPattern::PCT70,
ShadingPattern::PCT75,
ShadingPattern::PCT80,
ShadingPattern::PCT90,
ShadingPattern::HORZ_STRIPE,
ShadingPattern::VERT_STRIPE,
ShadingPattern::REVERSE_DIAG_STRIPE,
ShadingPattern::DIAG_STRIPE,
ShadingPattern::HORZ_CROSS,
ShadingPattern::DIAG_CROSS,
ShadingPattern::THIN_HORZ_STRIPE,
ShadingPattern::THIN_VERT_STRIPE,
ShadingPattern::THIN_REVERSE_DIAG_STRIPE,
ShadingPattern::THIN_DIAG_STRIPE,
ShadingPattern::THIN_HORZ_CROSS,
ShadingPattern::THIN_DIAG_CROSS,
ShadingPattern::UNUSED_1,
ShadingPattern::UNUSED_2,
ShadingPattern::UNUSED_3,
ShadingPattern::UNUSED_4,
ShadingPattern::UNUSED_5,
ShadingPattern::UNUSED_6,
ShadingPattern::UNUSED_7,
ShadingPattern::UNUSED_8,
ShadingPattern::UNUSED_9,
ShadingPattern::PCT2,
ShadingPattern::PCT7,
ShadingPattern::PCT12,
ShadingPattern::PCT15,
ShadingPattern::PCT17,
ShadingPattern::PCT22,
ShadingPattern::PCT27,
ShadingPattern::PCT32,
ShadingPattern::PCT35,
ShadingPattern::PCT37,
ShadingPattern::PCT42,
ShadingPattern::PCT45,
ShadingPattern::PCT47,
ShadingPattern::PCT52,
ShadingPattern::PCT55,
ShadingPattern::PCT57,
ShadingPattern::PCT62,
ShadingPattern::PCT65,
ShadingPattern::PCT67,
ShadingPattern::PCT72,
ShadingPattern::PCT77,
ShadingPattern::PCT82,
ShadingPattern::PCT85,
ShadingPattern::PCT87,
ShadingPattern::PCT92,
ShadingPattern::PCT95,
ShadingPattern::PCT97
};
// Write the shading pattern property
pPropertyMap->Insert(PROP_CHAR_SHADING_VALUE, false, uno::makeAny( aWWShadingPatterns[m_nShadingPattern] ));
}
pPropertyMap->Insert( m_OutputFormat == Form ? PROP_BACK_COLOR
: m_OutputFormat == Paragraph ? PROP_PARA_BACK_COLOR
: PROP_CHAR_BACK_COLOR, false, uno::makeAny( nApplyColor ));
return pPropertyMap;
}
} //namespace dmapper
} //namespace writerfilter
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>remove unused variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <CellColorHandler.hxx>
#include <PropertyMap.hxx>
#include <doctok/resourceids.hxx>
#include <ConversionHelper.hxx>
#include <ooxml/resourceids.hxx>
#include <com/sun/star/drawing/ShadingPattern.hpp>
#include <sal/macros.h>
#include "dmapperLoggers.hxx"
#define OOXML_COLOR_AUTO 0x0a //todo: AutoColor needs symbol
namespace writerfilter {
namespace dmapper {
using namespace ::com::sun::star::drawing;
using namespace ::writerfilter;
CellColorHandler::CellColorHandler() :
LoggedProperties(dmapper_logger, "CellColorHandler"),
m_nShadingPattern( ShadingPattern::CLEAR ),
m_nColor( 0xffffffff ),
m_nFillColor( 0xffffffff ),
m_OutputFormat( Form )
{
}
CellColorHandler::~CellColorHandler()
{
}
void CellColorHandler::lcl_attribute(Id rName, Value & rVal)
{
sal_Int32 nIntValue = rVal.getInt();
switch( rName )
{
case NS_rtf::LN_cellTopColor:
case NS_rtf::LN_cellLeftColor:
case NS_rtf::LN_cellBottomColor:
case NS_rtf::LN_cellRightColor:
// nIntValue contains the color, directly
break;
case NS_ooxml::LN_CT_Shd_val:
{
//might be clear, pct5...90, some hatch types
//TODO: The values need symbolic names!
m_nShadingPattern = nIntValue; //clear == 0, solid: 1, pct5: 2, pct50:8, pct95: x3c, horzStripe:0x0e, thinVertStripe: 0x15
}
break;
case NS_ooxml::LN_CT_Shd_fill:
if( nIntValue == OOXML_COLOR_AUTO )
nIntValue = 0xffffff; //fill color auto means white
m_nFillColor = nIntValue;
break;
case NS_ooxml::LN_CT_Shd_color:
if( nIntValue == OOXML_COLOR_AUTO )
nIntValue = 0; //shading color auto means black
//color of the shading
m_nColor = nIntValue;
break;
case NS_ooxml::LN_CT_Shd_themeFill:
case NS_ooxml::LN_CT_Shd_themeFillTint:
case NS_ooxml::LN_CT_Shd_themeFillShade:
// ignored
break;
default:
OSL_FAIL( "unknown attribute");
}
}
void CellColorHandler::lcl_sprm(Sprm & rSprm)
{
(void)rSprm;
}
TablePropertyMapPtr CellColorHandler::getProperties()
{
TablePropertyMapPtr pPropertyMap(new TablePropertyMap);
// Code from binary word filter (the values are out of 1000)
static const sal_Int32 eMSGrayScale[] =
{
// Clear-Brush
0, // 0 clear
// Solid-Brush
1000, // 1 solid
// Percent values
50, // 2 pct5
100, // 3 pct10
200, // 4 pct20
250, // 5 pct25
300, // 6 pct30
400, // 7 pct40
500, // 8 pct50
600, // 9 pct60
700, // 10 pct70
750, // 11 pct75
800, // 12 pct80
900, // 13 pct90
// Special cases
333, // 14 Dark Horizontal
333, // 15 Dark Vertical
333, // 16 Dark Forward Diagonal
333, // 17 Dark Backward Diagonal
333, // 18 Dark Cross
333, // 19 Dark Diagonal Cross
333, // 20 Horizontal
333, // 21 Vertical
333, // 22 Forward Diagonal
333, // 23 Backward Diagonal
333, // 24 Cross
333, // 25 Diagonal Cross
// Undefined values in DOC spec-sheet
500, // 26
500, // 27
500, // 28
500, // 29
500, // 30
500, // 31
500, // 32
500, // 33
500, // 34
// Different shading types
25, // 35 [available in DOC, not available in DOCX]
75, // 36 [available in DOC, not available in DOCX]
125, // 37 pct12
150, // 38 pct15
175, // 39 [available in DOC, not available in DOCX]
225, // 40 [available in DOC, not available in DOCX]
275, // 41 [available in DOC, not available in DOCX]
325, // 42 [available in DOC, not available in DOCX]
350, // 43 pct35
375, // 44 pct37
425, // 45 [available in DOC, not available in DOCX]
450, // 46 pct45
475, // 47 [available in DOC, not available in DOCX]
525, // 48 [available in DOC, not available in DOCX]
550, // 49 pct55
575, // 50 [available in DOC, not available in DOCX]
625, // 51 pct62
650, // 52 pct65
675, // 53 [available in DOC, not available in DOCX]
725, // 54 [available in DOC, not available in DOCX]
775, // 55 [available in DOC, not available in DOCX]
825, // 56 [available in DOC, not available in DOCX]
850, // 57 pct85
875, // 58 pct87
925, // 59 [available in DOC, not available in DOCX]
950, // 60 pct95
975 // 61 [available in DOC, not available in DOCX]
};// 62
if( m_nShadingPattern >= (sal_Int32)SAL_N_ELEMENTS( eMSGrayScale ) )
m_nShadingPattern = 0;
sal_Int32 nWW8BrushStyle = eMSGrayScale[m_nShadingPattern];
sal_Int32 nApplyColor = 0;
if( !nWW8BrushStyle )
{
// Clear-Brush
nApplyColor = m_nFillColor;
}
else
{
sal_Int32 nFore = m_nColor;
sal_Int32 nBack = m_nFillColor;
sal_uInt32 nRed = ((nFore & 0xff0000)>>0x10) * nWW8BrushStyle;
sal_uInt32 nGreen = ((nFore & 0xff00)>>0x8) * nWW8BrushStyle;
sal_uInt32 nBlue = (nFore & 0xff) * nWW8BrushStyle;
nRed += ((nBack & 0xff0000)>>0x10) * (1000L - nWW8BrushStyle);
nGreen += ((nBack & 0xff00)>>0x8)* (1000L - nWW8BrushStyle);
nBlue += (nBack & 0xff) * (1000L - nWW8BrushStyle);
nApplyColor = ( (nRed/1000) << 0x10 ) + ((nGreen/1000) << 8) + nBlue/1000;
}
// Check if it is a 'Character'
if (m_OutputFormat == Character)
{
static sal_Int32 aWWShadingPatterns[ ] =
{
ShadingPattern::CLEAR,
ShadingPattern::SOLID,
ShadingPattern::PCT5,
ShadingPattern::PCT10,
ShadingPattern::PCT20,
ShadingPattern::PCT25,
ShadingPattern::PCT30,
ShadingPattern::PCT40,
ShadingPattern::PCT50,
ShadingPattern::PCT60,
ShadingPattern::PCT70,
ShadingPattern::PCT75,
ShadingPattern::PCT80,
ShadingPattern::PCT90,
ShadingPattern::HORZ_STRIPE,
ShadingPattern::VERT_STRIPE,
ShadingPattern::REVERSE_DIAG_STRIPE,
ShadingPattern::DIAG_STRIPE,
ShadingPattern::HORZ_CROSS,
ShadingPattern::DIAG_CROSS,
ShadingPattern::THIN_HORZ_STRIPE,
ShadingPattern::THIN_VERT_STRIPE,
ShadingPattern::THIN_REVERSE_DIAG_STRIPE,
ShadingPattern::THIN_DIAG_STRIPE,
ShadingPattern::THIN_HORZ_CROSS,
ShadingPattern::THIN_DIAG_CROSS,
ShadingPattern::UNUSED_1,
ShadingPattern::UNUSED_2,
ShadingPattern::UNUSED_3,
ShadingPattern::UNUSED_4,
ShadingPattern::UNUSED_5,
ShadingPattern::UNUSED_6,
ShadingPattern::UNUSED_7,
ShadingPattern::UNUSED_8,
ShadingPattern::UNUSED_9,
ShadingPattern::PCT2,
ShadingPattern::PCT7,
ShadingPattern::PCT12,
ShadingPattern::PCT15,
ShadingPattern::PCT17,
ShadingPattern::PCT22,
ShadingPattern::PCT27,
ShadingPattern::PCT32,
ShadingPattern::PCT35,
ShadingPattern::PCT37,
ShadingPattern::PCT42,
ShadingPattern::PCT45,
ShadingPattern::PCT47,
ShadingPattern::PCT52,
ShadingPattern::PCT55,
ShadingPattern::PCT57,
ShadingPattern::PCT62,
ShadingPattern::PCT65,
ShadingPattern::PCT67,
ShadingPattern::PCT72,
ShadingPattern::PCT77,
ShadingPattern::PCT82,
ShadingPattern::PCT85,
ShadingPattern::PCT87,
ShadingPattern::PCT92,
ShadingPattern::PCT95,
ShadingPattern::PCT97
};
// Write the shading pattern property
pPropertyMap->Insert(PROP_CHAR_SHADING_VALUE, false, uno::makeAny( aWWShadingPatterns[m_nShadingPattern] ));
}
pPropertyMap->Insert( m_OutputFormat == Form ? PROP_BACK_COLOR
: m_OutputFormat == Paragraph ? PROP_PARA_BACK_COLOR
: PROP_CHAR_BACK_COLOR, false, uno::makeAny( nApplyColor ));
return pPropertyMap;
}
} //namespace dmapper
} //namespace writerfilter
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/data/xml/XmlBindingInputStream.h"
using namespace std;
using namespace db::data;
using namespace db::data::xml;
using namespace db::io;
using namespace db::rt;
XmlBindingInputStream::XmlBindingInputStream(DataBinding* db, int bufferSize) :
mReadBuffer(bufferSize),
mReadBufferStream(&mReadBuffer, false),
mIgnoreStream(&mReadBufferStream, false)
{
// create read state for root data binding
ReadState rs;
populateReadState(rs, db);
mStateStack.push_front(rs);
mElementDataPending = false;
}
XmlBindingInputStream::~XmlBindingInputStream()
{
// clean up all read state children lists
for(list<ReadState>::iterator i = mStateStack.begin();
i != mStateStack.end(); i++)
{
freeReadState(*i);
}
}
void XmlBindingInputStream::populateReadState(ReadState& rs, DataBinding* db)
{
// set data binding, not started read yet
rs.db = db;
rs.started = false;
// notify binding of serialization start
db->serializationStarted();
// get initial data name
rs.dn = db->getDataNames().begin();
// no children yet
rs.children = NULL;
}
void XmlBindingInputStream::freeReadState(ReadState& rs)
{
if(rs.children != NULL)
{
delete rs.children;
rs.children = NULL;
}
}
void XmlBindingInputStream::writeElementData(ReadState& rs)
{
// write out remaining data to read buffer
if(mXmlWriter.writeElementData(
rs.db->getDataMapping(*rs.dn), rs.db->getSetGetObject(*rs.dn),
&mIgnoreStream))
{
// write out end element if dealing with non-root
if(!rs.db->getDataName()->equals(*rs.dn))
{
mXmlWriter.writeEndElement(&mIgnoreStream);
}
// element data no longer pending
mElementDataPending = false;
// increment data name
rs.dn++;
}
else
{
// set ignore count, get remaining unwritten bytes
IOException* e = dynamic_cast<IOException*>(Exception::getLast());
if(e != NULL)
{
mIgnoreStream.setIgnoreCount(e->getUsedBytes());
mElementDataPending = true;
// clear exception
Exception::clearLast();
}
}
}
int XmlBindingInputStream::read(char* b, int length)
{
int rval = 0;
// clear last exception
Exception::clearLast();
// read from buffer as much as possible
if(!mReadBuffer.isEmpty())
{
rval = mReadBuffer.get(b, length);
}
else if(!mStateStack.empty())
{
// get current read state
ReadState* rs = &mStateStack.front();
// start read if not started
if(!rs->started)
{
// get root data name
DataName* root = rs->db->getDataName();
if(root == NULL)
{
Exception::setLast(
new IOException("No root element for DataBinding!"));
rval = -1;
}
else
{
// write start element
mXmlWriter.writeStartElement(root, &mIgnoreStream);
rs->started = true;
}
}
else if(mElementDataPending)
{
// write out element data
writeElementData(*rs);
}
else
{
// get current data name
if(rs->dn == rs->db->getDataNames().end())
{
// free read state and pop off stack
freeReadState(*rs);
mStateStack.pop_front();
// no more data names, write end element
mXmlWriter.writeEndElement(&mIgnoreStream);
if(!mStateStack.empty())
{
// if element was a child, increment child
rs = &mStateStack.front();
if(rs->children != NULL)
{
rs->child++;
}
}
}
else
{
// check data mapping for data name
DataMapping* dm = rs->db->getDataMapping(*rs->dn);
if(!dm->isChildMapping())
{
if(rs->db->getDataName()->equals(*rs->dn))
{
// write out element data for root element
writeElementData(*rs);
}
else
{
// only write element if it is verbose or has data
if((*rs->dn)->verbose ||
dm->hasData(rs->db->getSetGetObject(*rs->dn)))
{
if((*rs->dn)->major)
{
// write start element, indicate data is pending
mXmlWriter.writeStartElement(*rs->dn, &mIgnoreStream);
mElementDataPending = true;
}
else
{
// write attribute
mXmlWriter.writeAttribute(
*rs->dn, dm, rs->db->getSetGetObject(*rs->dn),
&mIgnoreStream);
// increment data name
rs->dn++;
}
}
else
{
// skip data name, it has no data and isn't verbose
rs->dn++;
}
}
}
else
{
// get children if they do not already exist
if(rs->children == NULL)
{
rs->children = new list<void*>();
rs->db->getChildren(*rs->dn, *rs->children);
rs->child = rs->children->begin();
// increment data name
rs->dn++;
}
// get current child
if(rs->child != rs->children->end())
{
// get data binding for child
DataBinding* db = rs->db->getDataBinding(*rs->dn);
// set data binding's object to child
db->setObject(*rs->child);
// create read state and push onto stack
ReadState rs2;
populateReadState(rs2, db);
mStateStack.push_front(rs2);
// recurse
rval = read(b, length);
}
else
{
// increment data name
rs->dn++;
// clean up children
delete rs->children;
rs->children = NULL;
}
}
}
}
if(rval == 0 && !Exception::hasLast())
{
if(!mReadBuffer.isEmpty())
{
// read from read buffer
rval = mReadBuffer.get(b, length);
}
else if(!mStateStack.empty())
{
// if no data has been written to the read buffer, recurse to
// write out more xml
rval = read(b, length);
}
}
}
return rval;
}
void XmlBindingInputStream::setIndentation(int level, int spaces)
{
mXmlWriter.setIndentation(level, spaces);
}
<commit_msg>Added patch to maintain the last exception in xml binding input stream.<commit_after>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/data/xml/XmlBindingInputStream.h"
using namespace std;
using namespace db::data;
using namespace db::data::xml;
using namespace db::io;
using namespace db::rt;
XmlBindingInputStream::XmlBindingInputStream(DataBinding* db, int bufferSize) :
mReadBuffer(bufferSize),
mReadBufferStream(&mReadBuffer, false),
mIgnoreStream(&mReadBufferStream, false)
{
// create read state for root data binding
ReadState rs;
populateReadState(rs, db);
mStateStack.push_front(rs);
mElementDataPending = false;
}
XmlBindingInputStream::~XmlBindingInputStream()
{
// clean up all read state children lists
for(list<ReadState>::iterator i = mStateStack.begin();
i != mStateStack.end(); i++)
{
freeReadState(*i);
}
}
void XmlBindingInputStream::populateReadState(ReadState& rs, DataBinding* db)
{
// set data binding, not started read yet
rs.db = db;
rs.started = false;
// notify binding of serialization start
db->serializationStarted();
// get initial data name
rs.dn = db->getDataNames().begin();
// no children yet
rs.children = NULL;
}
void XmlBindingInputStream::freeReadState(ReadState& rs)
{
if(rs.children != NULL)
{
delete rs.children;
rs.children = NULL;
}
}
void XmlBindingInputStream::writeElementData(ReadState& rs)
{
// write out remaining data to read buffer
if(mXmlWriter.writeElementData(
rs.db->getDataMapping(*rs.dn), rs.db->getSetGetObject(*rs.dn),
&mIgnoreStream))
{
// write out end element if dealing with non-root
if(!rs.db->getDataName()->equals(*rs.dn))
{
mXmlWriter.writeEndElement(&mIgnoreStream);
}
// element data no longer pending
mElementDataPending = false;
// increment data name
rs.dn++;
}
else
{
// set ignore count, get remaining unwritten bytes
IOException* e = dynamic_cast<IOException*>(Exception::getLast());
if(e != NULL)
{
mIgnoreStream.setIgnoreCount(e->getUsedBytes());
mElementDataPending = true;
// clear exception
Exception::clearLast();
}
}
}
int XmlBindingInputStream::read(char* b, int length)
{
int rval = 0;
// clear last exception
Exception* last = Exception::getLast();
Exception::clearLast(false);
// read from buffer as much as possible
if(!mReadBuffer.isEmpty())
{
rval = mReadBuffer.get(b, length);
}
else if(!mStateStack.empty())
{
// get current read state
ReadState* rs = &mStateStack.front();
// start read if not started
if(!rs->started)
{
// get root data name
DataName* root = rs->db->getDataName();
if(root == NULL)
{
Exception::setLast(
new IOException("No root element for DataBinding!"));
rval = -1;
}
else
{
// write start element
mXmlWriter.writeStartElement(root, &mIgnoreStream);
rs->started = true;
}
}
else if(mElementDataPending)
{
// write out element data
writeElementData(*rs);
}
else
{
// get current data name
if(rs->dn == rs->db->getDataNames().end())
{
// free read state and pop off stack
freeReadState(*rs);
mStateStack.pop_front();
// no more data names, write end element
mXmlWriter.writeEndElement(&mIgnoreStream);
if(!mStateStack.empty())
{
// if element was a child, increment child
rs = &mStateStack.front();
if(rs->children != NULL)
{
rs->child++;
}
}
}
else
{
// check data mapping for data name
DataMapping* dm = rs->db->getDataMapping(*rs->dn);
if(!dm->isChildMapping())
{
if(rs->db->getDataName()->equals(*rs->dn))
{
// write out element data for root element
writeElementData(*rs);
}
else
{
// only write element if it is verbose or has data
if((*rs->dn)->verbose ||
dm->hasData(rs->db->getSetGetObject(*rs->dn)))
{
if((*rs->dn)->major)
{
// write start element, indicate data is pending
mXmlWriter.writeStartElement(*rs->dn, &mIgnoreStream);
mElementDataPending = true;
}
else
{
// write attribute
mXmlWriter.writeAttribute(
*rs->dn, dm, rs->db->getSetGetObject(*rs->dn),
&mIgnoreStream);
// increment data name
rs->dn++;
}
}
else
{
// skip data name, it has no data and isn't verbose
rs->dn++;
}
}
}
else
{
// get children if they do not already exist
if(rs->children == NULL)
{
rs->children = new list<void*>();
rs->db->getChildren(*rs->dn, *rs->children);
rs->child = rs->children->begin();
// increment data name
rs->dn++;
}
// get current child
if(rs->child != rs->children->end())
{
// get data binding for child
DataBinding* db = rs->db->getDataBinding(*rs->dn);
// set data binding's object to child
db->setObject(*rs->child);
// create read state and push onto stack
ReadState rs2;
populateReadState(rs2, db);
mStateStack.push_front(rs2);
// recurse
rval = read(b, length);
}
else
{
// increment data name
rs->dn++;
// clean up children
delete rs->children;
rs->children = NULL;
}
}
}
}
if(rval == 0 && !Exception::hasLast())
{
if(!mReadBuffer.isEmpty())
{
// read from read buffer
rval = mReadBuffer.get(b, length);
}
else if(!mStateStack.empty())
{
// if no data has been written to the read buffer, recurse to
// write out more xml
rval = read(b, length);
}
}
}
// restore old exception
if(!Exception::hasLast())
{
Exception::setLast(last);
}
else if(last != NULL)
{
// clean up old exception
delete last;
}
return rval;
}
void XmlBindingInputStream::setIndentation(int level, int spaces)
{
mXmlWriter.setIndentation(level, spaces);
}
<|endoftext|> |
<commit_before>/*
* File: wafr.cpp
* Author: Isaac Yochelson
*
* Created on March 24, 2014, 3:22 PM
*/
#include <moveit/move_group_interface/move_group.h>
#include <moveit_msgs/RobotTrajectory.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <trajectory_msgs/MultiDOFJointTrajectory.h>
#include <geometry_msgs/Pose.h>
#include <baxter_core_msgs/EndpointState.h>
#include <cstdlib> //standard library for C/C++
#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>
using namespace std;
ofstream outFile;
void openOutput(string filename);
void closeOutput();
int main(int argc, char** argv)
{
if (arc < 4) {
cout << "usage: wafr <# lines / file> <ms per step> <input filename>\n";
return -1;
}
else {
ros::init(argc, argv, "WAFR_Node");
// start a ROS spinning thread
ros::AsyncSpinner spinner(1);
spinner.start();
// Create MoveGroup instances for each arm, set them to PRM*, and create a pointer to be assigned
// to the correct arm to be used for each target.
move_group_interface::MoveGroup leftGroup("left_arm");
leftGroup.setPlannerId("PRMstarkConfigDefault");
leftGroup.setStartStateToCurrentState();
// New functionality goes here.
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> commaDelimited(",");
string keyLine = "left_s0,left_s1,left_e0,left_e1,left_w0,left_w1,left_w2";
map<string, double> goal;
ifstream configs;
configs.open(argv[3].c_str());
int count = 0;
string configString;
while (getline(configs, configString)) {
if ((count % lines) == 0) {
if (count != 0) {
closeOutput();
system("rosrun baxter_examples joint_trajectory_file_playback -f temp.trj");
}
tokenizer keys(keyLine, commaDelimited);
tokenizer config(configString, commaDelimited);
tokenizer::iterator config_iter = config.begin();
for (tokenizer::iterator key_iter = keys.begin(); key_iter != keys.end();
++key_iter) {
goal[*key_iter] = atof((*config_iter).c_str());
++config_iter;
}
leftGroup.setJointValueTarget(goal);
leftGroup.move();
if (atof(*config_iter) > 0) {
system("rosrun drogon_interface gripper.py open left");
} else {
system("rosrun drogon_interface gripper.py close left");
}
openOutput("temp.trj");
}
}
return 0;
}
}
void fillMap(map<string, vector<double> > &goals, string filename)
{
cout << "filling map: " << filename << endl;
ifstream goalInput;
goalInput.open(filename.c_str());
double value;
string keyLine = "left_s0,left_s1,left_e0,left_e1,left_w0,left_w1,left_w2,left_gripper";
string valueLine;
cout << keyLine << endl;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> commaDelimited(",");
tokenizer keys(keyLine, commaDelimited);
int count = 0;
while (getline(goalInput, valueLine)) {
tokenizer values(valueLine, commaDelimited);
tokenizer::iterator value_iter = values.begin();
for (tokenizer::iterator key_iter = keys.begin();
key_iter != keys.end() && value_iter != values.end(); ++key_iter)
{
value = atof((*value_iter).c_str());
goals[*key_iter].push_back(value);
++value_iter;
}
++count;
}
goalInput.close();
cout << "fillMap finished: " << count << " lines" << endl;
}
void openOutput(string filename)
{
outFile.open(filename.c_str());
outFIle << "time,left_s0,left_s1,left_e0,left_e1,left_w0,left_w1,left_w2,left_gripper,right_s0,right_s1,right_e0,right_e1,right_w0,right_w1,right_w2,right_gripper\n";
}
void closeOutput()
{
outFile.close();
}
<commit_msg>finished coding wafr, time to debug now<commit_after>/*
* File: wafr.cpp
* Author: Isaac Yochelson
*
* Created on March 24, 2014, 3:22 PM
*/
#include <moveit/move_group_interface/move_group.h>
#include <moveit_msgs/RobotTrajectory.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <trajectory_msgs/MultiDOFJointTrajectory.h>
#include <geometry_msgs/Pose.h>
#include <baxter_core_msgs/EndpointState.h>
#include <cstdlib> //standard library for C/C++
#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>
using namespace std;
ofstream outFile;
void openOutput(string filename);
void closeOutput();
int main(int argc, char** argv)
{
if (arc < 4) {
cout << "usage: wafr <# lines / file> <ms per step> <input filename>\n";
return -1;
}
else {
ros::init(argc, argv, "WAFR_Node");
// start a ROS spinning thread
ros::AsyncSpinner spinner(1);
spinner.start();
// Create MoveGroup instances for each arm, set them to PRM*, and create a pointer to be assigned
// to the correct arm to be used for each target.
move_group_interface::MoveGroup leftGroup("left_arm");
leftGroup.setPlannerId("PRMstarkConfigDefault");
leftGroup.setStartStateToCurrentState();
// New functionality goes here.
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> commaDelimited(",");
string keyLine = "left_s0,left_s1,left_e0,left_e1,left_w0,left_w1,left_w2";
string defaults = "-0.708699123193,-0.980980712732,-0.282635959845,1.13859723851,0.141509727521,1.31922347607,-0.00498543755493,0.0\n";
map<string, double> goal;
ifstream configs;
int lines = atoi(argv[1].c_str());
int step = atoi(argv[2].c_str());
configs.open(argv[3].c_str());
int count = 0;
string configString;
bool open = true;
tokenizer keys(keyLine, commaDelimited);
while (getline(configs, configString)) {
if ((count % lines) == 0) {
if (count != 0) {
closeOutput();
system("rosrun baxter_examples joint_trajectory_file_playback -f temp.trj");
}
tokenizer config(configString, commaDelimited);
tokenizer::iterator config_iter = config.begin();
for (tokenizer::iterator key_iter = keys.begin(); key_iter != keys.end();
++key_iter) {
goal[*key_iter] = atof((*config_iter).c_str());
++config_iter;
}
leftGroup.setJointValueTarget(goal);
leftGroup.move();
if (atoi(*config_iter) == 1) {
open = true;
system("rosrun drogon_interface gripper.py open left");
} else {
system("rosrun drogon_interface gripper.py close left");
open = false;
}
openOutput("temp.trj");
outFile << (count * step) << ",";
for (tokenizer::iterator key_iter = keys.begin(); key_iter != keys.end();
++key_iter) {
outFile << goal[*key_iter] << ",";
}
if (open) {
outFile << "100.0,";
} else {
outFile << "0.0,";
}
outfile << defaults;
} else {
tokenizer config(configString, commaDelimited);
outFile << (count * step) << ",";
tokenizer::iterator config_iter = config.begin();
for (size_t i=0; i<7; ++i) {
outFile << *config_iter << ",";
++config_iter;
}
if (atoi(*config_iter) == 1) {
outFile << "100.0,";
} else {
outFile << "0.0,";
}
outFile << defaults;
}
}
return 0;
}
}
void fillMap(map<string, vector<double> > &goals, string filename)
{
cout << "filling map: " << filename << endl;
ifstream goalInput;
goalInput.open(filename.c_str());
double value;
string keyLine = "left_s0,left_s1,left_e0,left_e1,left_w0,left_w1,left_w2,left_gripper";
string valueLine;
cout << keyLine << endl;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> commaDelimited(",");
tokenizer keys(keyLine, commaDelimited);
int count = 0;
while (getline(goalInput, valueLine)) {
tokenizer values(valueLine, commaDelimited);
tokenizer::iterator value_iter = values.begin();
for (tokenizer::iterator key_iter = keys.begin();
key_iter != keys.end() && value_iter != values.end(); ++key_iter)
{
value = atof((*value_iter).c_str());
goals[*key_iter].push_back(value);
++value_iter;
}
++count;
}
goalInput.close();
cout << "fillMap finished: " << count << " lines" << endl;
}
void openOutput(string filename)
{
outFile.open(filename.c_str());
outFIle << "time,left_s0,left_s1,left_e0,left_e1,left_w0,left_w1,left_w2,left_gripper,right_s0,right_s1,right_e0,right_e1,right_w0,right_w1,right_w2,right_gripper\n";
}
void closeOutput()
{
outFile.close();
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#include "saiga/core/util/fileChecker.h"
#include "saiga/core/util/directory.h"
#include "internal/noGraphicsAPI.h"
#include <fstream>
namespace Saiga
{
FileChecker::FileChecker()
{
searchPathes.push_back("");
searchPathes.push_back(".");
}
std::string FileChecker::getFile(const std::string& file)
{
if (file.empty()) return "";
for (std::string& path : searchPathes)
{
// Do not generate a double '/'
std::string fullName = file.front() == '/' ? path + file : path + "/" + file;
if (existsFile(fullName))
{
return fullName;
}
}
return "";
}
std::string FileChecker::getRelative(const std::string& baseFile, const std::string& file)
{
// first check at path relative to the parent
auto parent = getParentDirectory(baseFile);
std::string relativeName = parent + file;
if (existsFile(relativeName))
{
return relativeName;
}
return getFile(file);
}
std::string FileChecker::getParentDirectory(const std::string& file)
{
// search last '/' from the end
for (auto it = file.rbegin(); it != file.rend(); ++it)
{
if (*it == '/')
{
auto d = std::distance(it, file.rend());
return file.substr(0, d);
}
}
return "";
}
std::string FileChecker::getFileName(const std::string& file)
{
// search last '/' from the end
for (auto it = file.rbegin(); it != file.rend(); ++it)
{
if (*it == '/')
{
auto d = std::distance(it, file.rend());
return file.substr(d);
}
}
return "";
}
void FileChecker::getFiles(std::vector<std::string>& out, const std::string& predir, const std::string& ending)
{
for (std::string& path : searchPathes)
{
std::string dir = path + "/" + predir;
cout << dir << endl;
Directory d(dir);
std::vector<std::string> tmp;
d.getFiles(tmp, ending);
for (auto& s : tmp)
{
s = dir + "/" + s;
}
out.insert(out.end(), tmp.begin(), tmp.end());
}
}
void FileChecker::addSearchPath(const std::string& path)
{
searchPathes.push_back(path);
}
void FileChecker::addSearchPath(const std::vector<std::string>& paths)
{
for (auto& s : paths) addSearchPath(s);
}
bool FileChecker::existsFile(const std::string& file)
{
std::ifstream infile(file);
return infile.good();
}
std::ostream& operator<<(std::ostream& os, const FileChecker& fc)
{
os << "File Checker - Search Pathes:" << endl;
for (auto s : fc.searchPathes)
{
os << " '" << s << "'" << endl;
}
return os;
}
namespace SearchPathes
{
FileChecker shader;
FileChecker image;
FileChecker model;
FileChecker font;
FileChecker data;
} // namespace SearchPathes
} // namespace Saiga
<commit_msg>fixed file checker absolute path<commit_after>/**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#include "saiga/core/util/fileChecker.h"
#include "saiga/core/util/directory.h"
#include "internal/noGraphicsAPI.h"
#include <fstream>
namespace Saiga
{
FileChecker::FileChecker()
{
searchPathes.push_back("");
searchPathes.push_back(".");
}
std::string FileChecker::getFile(const std::string& file)
{
if (file.empty()) return "";
// Check without search pathes
if (existsFile(file))
return file;
for (std::string& path : searchPathes)
{
// Do not generate a double '/'
std::string fullName = file.front() == '/' ? path + file : path + "/" + file;
cout << "check " << fullName << endl;
if (existsFile(fullName))
{
return fullName;
}
}
return "";
}
std::string FileChecker::getRelative(const std::string& baseFile, const std::string& file)
{
// first check at path relative to the parent
auto parent = getParentDirectory(baseFile);
std::string relativeName = parent + file;
if (existsFile(relativeName))
{
return relativeName;
}
return getFile(file);
}
std::string FileChecker::getParentDirectory(const std::string& file)
{
// search last '/' from the end
for (auto it = file.rbegin(); it != file.rend(); ++it)
{
if (*it == '/')
{
auto d = std::distance(it, file.rend());
return file.substr(0, d);
}
}
return "";
}
std::string FileChecker::getFileName(const std::string& file)
{
// search last '/' from the end
for (auto it = file.rbegin(); it != file.rend(); ++it)
{
if (*it == '/')
{
auto d = std::distance(it, file.rend());
return file.substr(d);
}
}
return "";
}
void FileChecker::getFiles(std::vector<std::string>& out, const std::string& predir, const std::string& ending)
{
for (std::string& path : searchPathes)
{
std::string dir = path + "/" + predir;
cout << dir << endl;
Directory d(dir);
std::vector<std::string> tmp;
d.getFiles(tmp, ending);
for (auto& s : tmp)
{
s = dir + "/" + s;
}
out.insert(out.end(), tmp.begin(), tmp.end());
}
}
void FileChecker::addSearchPath(const std::string& path)
{
searchPathes.push_back(path);
}
void FileChecker::addSearchPath(const std::vector<std::string>& paths)
{
for (auto& s : paths) addSearchPath(s);
}
bool FileChecker::existsFile(const std::string& file)
{
std::ifstream infile(file);
return infile.good();
}
std::ostream& operator<<(std::ostream& os, const FileChecker& fc)
{
os << "File Checker - Search Pathes:" << endl;
for (auto s : fc.searchPathes)
{
os << " '" << s << "'" << endl;
}
return os;
}
namespace SearchPathes
{
FileChecker shader;
FileChecker image;
FileChecker model;
FileChecker font;
FileChecker data;
} // namespace SearchPathes
} // namespace Saiga
<|endoftext|> |
<commit_before>#ifndef SDCINFO_HPP
#define SDCINFO_HPP
#include <qglobal.h>
#include <QString>
struct SDcInfo {
SDcInfo(const QString &newIpAddress = QString(), const quint32 &newPort = 0) :
id(0),
ipAddress(newIpAddress),
port(newPort) { }
SDcInfo(const SDcInfo &anotherInfo) :
id(anotherInfo.id),
hostName(anotherInfo.hostName),
ipAddress(anotherInfo.ipAddress),
port(anotherInfo.port) { }
SDcInfo &operator=(const SDcInfo &anotherInfo) {
id = anotherInfo.id;
hostName = anotherInfo.hostName;
ipAddress = anotherInfo.ipAddress;
port = anotherInfo.port;
return *this;
}
quint32 id;
QString hostName;
QString ipAddress;
quint32 port;
};
#endif // SDCINFO_HPP
<commit_msg>TelegramQt/SDcInfo: Added isValid() method.<commit_after>#ifndef SDCINFO_HPP
#define SDCINFO_HPP
#include <qglobal.h>
#include <QString>
struct SDcInfo {
SDcInfo(const QString &newIpAddress = QString(), const quint32 &newPort = 0) :
id(0),
ipAddress(newIpAddress),
port(newPort) { }
bool isValid() const {
return (port > 0) && !ipAddress.isEmpty();
}
SDcInfo(const SDcInfo &anotherInfo) :
id(anotherInfo.id),
hostName(anotherInfo.hostName),
ipAddress(anotherInfo.ipAddress),
port(anotherInfo.port) { }
SDcInfo &operator=(const SDcInfo &anotherInfo) {
id = anotherInfo.id;
hostName = anotherInfo.hostName;
ipAddress = anotherInfo.ipAddress;
port = anotherInfo.port;
return *this;
}
quint32 id;
QString hostName;
QString ipAddress;
quint32 port;
};
#endif // SDCINFO_HPP
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/logging.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stringprintf.h"
static ::tensorflow::string BuildMessage(const char* fmt, va_list args) {
::tensorflow::string message;
::tensorflow::strings::Appendv(&message, fmt, args);
return message;
}
void TF_Log(TF_LogLevel level, const char* fmt, ...) {
if (level < TF_INFO || level > TF_FATAL) return;
va_list args;
va_start(args, fmt);
auto message = BuildMessage(fmt, args);
switch (level) {
case TF_INFO:
LOG(INFO) << message;
break;
case TF_WARNING:
LOG(WARNING) << message;
break;
case TF_ERROR:
LOG(ERROR) << message;
break;
case TF_FATAL:
LOG(FATAL) << message;
break;
}
}
void TF_VLog(int level, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
auto message = BuildMessage(fmt, args);
VLOG(level) << message;
}
void TF_DVLog(int level, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
auto message = BuildMessage(fmt, args);
DVLOG(level) << message;
}
<commit_msg>Add va_end to TF_Log<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/logging.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stringprintf.h"
static ::tensorflow::string BuildMessage(const char* fmt, va_list args) {
::tensorflow::string message;
::tensorflow::strings::Appendv(&message, fmt, args);
return message;
}
void TF_Log(TF_LogLevel level, const char* fmt, ...) {
if (level < TF_INFO || level > TF_FATAL) return;
va_list args;
va_start(args, fmt);
auto message = BuildMessage(fmt, args);
va_end(args);
switch (level) {
case TF_INFO:
LOG(INFO) << message;
break;
case TF_WARNING:
LOG(WARNING) << message;
break;
case TF_ERROR:
LOG(ERROR) << message;
break;
case TF_FATAL:
LOG(FATAL) << message;
break;
}
}
void TF_VLog(int level, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
auto message = BuildMessage(fmt, args);
va_end(args);
VLOG(level) << message;
}
void TF_DVLog(int level, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
auto message = BuildMessage(fmt, args);
va_end(args);
DVLOG(level) << message;
}
<|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// C++ includes
// Local Includes
#include "mesh_base.h"
#include "elem.h"
#include "point_locator_list.h"
// typedefs
typedef std::vector<Point>::const_iterator const_list_iterator;
//------------------------------------------------------------------
// PointLocator methods
PointLocatorList::PointLocatorList (const MeshBase& mesh,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_list (NULL)
{
// This code will only work if your mesh is the Voroni mesh of it's
// own elements' centroids. If your mesh is that regular you might
// as well hand-code an O(1) algorithm for locating points within
// it. - RHS
libmesh_experimental();
this->init();
}
PointLocatorList::~PointLocatorList ()
{
this->clear ();
}
void PointLocatorList::clear ()
{
// only delete the list when we are the master
if (this->_list != NULL)
{
if (this->_master == NULL)
{
// we own the list
this->_list->clear();
delete this->_list;
}
else
// someone else owns and therefore deletes the list
this->_list = NULL;
}
}
void PointLocatorList::init ()
{
libmesh_assert (this->_list == NULL);
if (this->_initialized)
{
std::cerr << "ERROR: Already initialized! Will ignore this call..."
<< std::endl;
}
else
{
if (this->_master == NULL)
{
// We are the master, so we have to build the list.
// First create it, then get a handy reference, and
// then try to speed up by reserving space...
this->_list = new std::vector<std::pair<Point, const Elem *> >;
std::vector<std::pair<Point, const Elem *> >& my_list = *(this->_list);
my_list.clear();
my_list.reserve(this->_mesh.n_active_elem());
// fill our list with the centroids and element
// pointers of the mesh. For this use the handy
// element iterators.
// const_active_elem_iterator el (this->_mesh.elements_begin());
// const const_active_elem_iterator end(this->_mesh.elements_end());
MeshBase::const_element_iterator el = _mesh.active_elements_begin();
const MeshBase::const_element_iterator end = _mesh.active_elements_end();
for (; el!=end; ++el)
my_list.push_back(std::make_pair((*el)->centroid(), *el));
}
else
{
// We are _not_ the master. Let our _list point to
// the master's list. But for this we first transform
// the master in a state for which we are friends
// (this should also beware of a bad master pointer?).
// And make sure the master @e has a list!
const PointLocatorList* my_master =
libmesh_cast_ptr<const PointLocatorList*>(this->_master);
if (my_master->initialized())
this->_list = my_master->_list;
else
{
std::cerr << "ERROR: Initialize master first, then servants!"
<< std::endl;
libmesh_error();
}
}
}
// ready for take-off
this->_initialized = true;
}
const Elem* PointLocatorList::operator() (const Point& p) const
{
libmesh_assert (this->_initialized);
// Ask the list. This is quite expensive, since
// we loop through the whole list to try to find
// the @e nearest element.
// However, there is not much else to do: when
// we would use bounding boxes like in a tree,
// it may happen that a surface element is just
// in plane with a bounding box face, and quite
// close to it. But when a point comes, this
// point may belong to the bounding box (where the
// coplanar element does @e not belong to). Then
// we would search through the elements in this
// bounding box, while the other bounding box'es
// element is closer, but we simply don't consider
// it!
//
// We _can_, however, use size_sq() instead of size()
// here to avoid repeated calls to std::sqrt(), which is
// pretty expensive.
{
std::vector<std::pair<Point, const Elem *> >& my_list = *(this->_list);
Real last_distance_sq = Point(my_list[0].first -p).size_sq();
const Elem * last_elem = NULL;
const unsigned int max_index = my_list.size();
for (unsigned int n=1; n<max_index; n++)
{
const Real current_distance_sq = Point(my_list[n].first -p).size_sq();
if (current_distance_sq < last_distance_sq)
{
last_distance_sq = current_distance_sq;
last_elem = my_list[n].second;
}
}
// the element should be active
libmesh_assert (last_elem->active());
// return the element
return (last_elem);
}
}
void PointLocatorList::enable_out_of_mesh_mode (void)
{
/* This functionality is not yet implemented for PointLocatorList. */
libmesh_error();
}
void PointLocatorList::disable_out_of_mesh_mode (void)
{
/* This functionality is not yet implemented for PointLocatorList. */
libmesh_error();
}
<commit_msg>Using newer not_implemented() error<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// C++ includes
// Local Includes
#include "mesh_base.h"
#include "elem.h"
#include "point_locator_list.h"
// typedefs
typedef std::vector<Point>::const_iterator const_list_iterator;
//------------------------------------------------------------------
// PointLocator methods
PointLocatorList::PointLocatorList (const MeshBase& mesh,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_list (NULL)
{
// This code will only work if your mesh is the Voroni mesh of it's
// own elements' centroids. If your mesh is that regular you might
// as well hand-code an O(1) algorithm for locating points within
// it. - RHS
libmesh_experimental();
this->init();
}
PointLocatorList::~PointLocatorList ()
{
this->clear ();
}
void PointLocatorList::clear ()
{
// only delete the list when we are the master
if (this->_list != NULL)
{
if (this->_master == NULL)
{
// we own the list
this->_list->clear();
delete this->_list;
}
else
// someone else owns and therefore deletes the list
this->_list = NULL;
}
}
void PointLocatorList::init ()
{
libmesh_assert (this->_list == NULL);
if (this->_initialized)
{
std::cerr << "ERROR: Already initialized! Will ignore this call..."
<< std::endl;
}
else
{
if (this->_master == NULL)
{
// We are the master, so we have to build the list.
// First create it, then get a handy reference, and
// then try to speed up by reserving space...
this->_list = new std::vector<std::pair<Point, const Elem *> >;
std::vector<std::pair<Point, const Elem *> >& my_list = *(this->_list);
my_list.clear();
my_list.reserve(this->_mesh.n_active_elem());
// fill our list with the centroids and element
// pointers of the mesh. For this use the handy
// element iterators.
// const_active_elem_iterator el (this->_mesh.elements_begin());
// const const_active_elem_iterator end(this->_mesh.elements_end());
MeshBase::const_element_iterator el = _mesh.active_elements_begin();
const MeshBase::const_element_iterator end = _mesh.active_elements_end();
for (; el!=end; ++el)
my_list.push_back(std::make_pair((*el)->centroid(), *el));
}
else
{
// We are _not_ the master. Let our _list point to
// the master's list. But for this we first transform
// the master in a state for which we are friends
// (this should also beware of a bad master pointer?).
// And make sure the master @e has a list!
const PointLocatorList* my_master =
libmesh_cast_ptr<const PointLocatorList*>(this->_master);
if (my_master->initialized())
this->_list = my_master->_list;
else
{
std::cerr << "ERROR: Initialize master first, then servants!"
<< std::endl;
libmesh_error();
}
}
}
// ready for take-off
this->_initialized = true;
}
const Elem* PointLocatorList::operator() (const Point& p) const
{
libmesh_assert (this->_initialized);
// Ask the list. This is quite expensive, since
// we loop through the whole list to try to find
// the @e nearest element.
// However, there is not much else to do: when
// we would use bounding boxes like in a tree,
// it may happen that a surface element is just
// in plane with a bounding box face, and quite
// close to it. But when a point comes, this
// point may belong to the bounding box (where the
// coplanar element does @e not belong to). Then
// we would search through the elements in this
// bounding box, while the other bounding box'es
// element is closer, but we simply don't consider
// it!
//
// We _can_, however, use size_sq() instead of size()
// here to avoid repeated calls to std::sqrt(), which is
// pretty expensive.
{
std::vector<std::pair<Point, const Elem *> >& my_list = *(this->_list);
Real last_distance_sq = Point(my_list[0].first -p).size_sq();
const Elem * last_elem = NULL;
const unsigned int max_index = my_list.size();
for (unsigned int n=1; n<max_index; n++)
{
const Real current_distance_sq = Point(my_list[n].first -p).size_sq();
if (current_distance_sq < last_distance_sq)
{
last_distance_sq = current_distance_sq;
last_elem = my_list[n].second;
}
}
// the element should be active
libmesh_assert (last_elem->active());
// return the element
return (last_elem);
}
}
void PointLocatorList::enable_out_of_mesh_mode (void)
{
/* This functionality is not yet implemented for PointLocatorList. */
libmesh_not_implemented();
}
void PointLocatorList::disable_out_of_mesh_mode (void)
{
/* This functionality is not yet implemented for PointLocatorList. */
libmesh_not_implemented();
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int lado = atoi(argv[1]);
for(int fila=0; fila<lado; fila++){
for (int cuadrado=0; cuadrado<lado; cuadrado++)
for(int col=0; col<lado; col++)
if (cuadrado % 2 == 0)
printf("*");
else
printf(" ");
printf("\n");
}
return EXIT_SUCCESS;
}
<commit_msg>Delete tira2.cpp<commit_after><|endoftext|> |
<commit_before>// @(#)root/eve7:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007, 2018
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_REveDataCollection
#define ROOT7_REveDataCollection
#include <ROOT/REveElement.hxx>
#include <ROOT/REveCompound.hxx>
#include <ROOT/REveSecondarySelectable.hxx>
#include <functional>
#include <vector>
#include <iostream>
class TClass;
namespace ROOT {
namespace Experimental {
class REveDataItem;
//==============================================================================
// could be a nested class ???
struct REveDataItem
{
void* fDataPtr{nullptr};
Bool_t fRnrSelf{true};
Color_t fColor{0};
Bool_t fFiltered{false};
REveDataItem(void* d, Color_t c): fDataPtr(d), fColor(c){}
Bool_t GetRnrSelf() const { return fRnrSelf; }
Color_t GetMainColor() const { return fColor; }
Bool_t GetFiltered() const { return fFiltered; }
void SetFiltered(Bool_t i) { fFiltered = i; }
void SetMainColor(Color_t i) { fColor = i; }
void SetRnrSelf(Bool_t i) { fRnrSelf = i; }
};
//==============================================================================
class REveDataItemList: public REveElement,
public REveSecondarySelectable
{
friend class REveDataCollection;
protected:
std::vector<REveDataItem*> fItems;
std::function<void (REveDataItemList*, const std::vector<int>&)> _handler_items_change;
std::function<void (REveDataItemList*, Set_t& impSel)> _handler_fillimp;
public:
REveDataItemList(const std::string& n = "Items", const std::string& t = "");
virtual ~REveDataItemList() {}
Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override;
virtual void ItemChanged(REveDataItem *item);
virtual void ItemChanged(Int_t idx);
void FillImpliedSelectedSet(Set_t &impSelSet) override;
void SetItemVisible(Int_t idx, Bool_t visible);
void SetItemColorRGB(Int_t idx, UChar_t r, UChar_t g, UChar_t b);
void SetItemsChangeDelegate (std::function<void (REveDataItemList*, const std::vector<int>&)> handler_func)
{
_handler_items_change = handler_func;
}
void SetFillImpliedSelectedDelegate (std::function<void (REveDataItemList*, Set_t& impSelSet)> handler_func)
{
_handler_fillimp = handler_func;
}
Bool_t SingleRnrState() const override { return kTRUE; }
Bool_t SetRnrState(Bool_t) override;
void ProcessSelection(ElementId_t id, bool multi, bool secondary, const std::set<int>& in_secondary_idcs);
};
//==============================================================================
class REveDataCollection : public REveElement
{
private:
REveDataItemList* fItemList{nullptr};
public:
typedef std::vector<int> Ids_t;
static Color_t fgDefaultColor;
TClass *fItemClass{nullptr}; // so far only really need class name
TString fFilterExpr;
std::function<bool(void *)> fFilterFoo = [](void *) { return true; };
REveDataCollection(const std::string& n = "REveDataCollection", const std::string& t = "");
virtual ~REveDataCollection() {}
void ReserveItems(Int_t items_size) { fItemList->fItems.reserve(items_size); }
void AddItem(void *data_ptr, const std::string& n, const std::string& t);
void ClearItems() { fItemList->fItems.clear(); }
Bool_t SingleRnrState() const override { return kTRUE; }
Bool_t SetRnrState(Bool_t) override;
TClass *GetItemClass() const { return fItemClass; }
void SetItemClass(TClass *cls) { fItemClass = cls;
}
REveDataItemList* GetItemList() {return fItemList;}
void SetFilterExpr(const TString &filter);
void ApplyFilter();
Int_t GetNItems() const { return (Int_t) fItemList->fItems.size(); }
void *GetDataPtr(Int_t i) const { return fItemList->fItems[i]->fDataPtr; }
// const REveDataItem& RefDataItem(Int_t i) const { return fItems[i]; }
const REveDataItem* GetDataItem(Int_t i) const { return fItemList->fItems[i]; }
void StreamPublicMethods(nlohmann::json &cj);
Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override;
void SetMainColor(Color_t) override;
};
} // namespace Experimental
} // namespace ROOT
#endif
<commit_msg>Add getter for visibility state<commit_after>// @(#)root/eve7:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007, 2018
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_REveDataCollection
#define ROOT7_REveDataCollection
#include <ROOT/REveElement.hxx>
#include <ROOT/REveCompound.hxx>
#include <ROOT/REveSecondarySelectable.hxx>
#include <functional>
#include <vector>
#include <iostream>
class TClass;
namespace ROOT {
namespace Experimental {
class REveDataItem;
//==============================================================================
// could be a nested class ???
struct REveDataItem
{
void* fDataPtr{nullptr};
Bool_t fRnrSelf{true};
Color_t fColor{0};
Bool_t fFiltered{false};
REveDataItem(void* d, Color_t c): fDataPtr(d), fColor(c){}
Bool_t GetRnrSelf() const { return fRnrSelf; }
Color_t GetMainColor() const { return fColor; }
Bool_t GetFiltered() const { return fFiltered; }
Bool_t GetVisible() const { return (!fFiltered) && fRnrSelf; }
void SetFiltered(Bool_t i) { fFiltered = i; }
void SetMainColor(Color_t i) { fColor = i; }
void SetRnrSelf(Bool_t i) { fRnrSelf = i; }
};
//==============================================================================
class REveDataItemList: public REveElement,
public REveSecondarySelectable
{
friend class REveDataCollection;
protected:
std::vector<REveDataItem*> fItems;
std::function<void (REveDataItemList*, const std::vector<int>&)> _handler_items_change;
std::function<void (REveDataItemList*, Set_t& impSel)> _handler_fillimp;
public:
REveDataItemList(const std::string& n = "Items", const std::string& t = "");
virtual ~REveDataItemList() {}
Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override;
virtual void ItemChanged(REveDataItem *item);
virtual void ItemChanged(Int_t idx);
void FillImpliedSelectedSet(Set_t &impSelSet) override;
void SetItemVisible(Int_t idx, Bool_t visible);
void SetItemColorRGB(Int_t idx, UChar_t r, UChar_t g, UChar_t b);
void SetItemsChangeDelegate (std::function<void (REveDataItemList*, const std::vector<int>&)> handler_func)
{
_handler_items_change = handler_func;
}
void SetFillImpliedSelectedDelegate (std::function<void (REveDataItemList*, Set_t& impSelSet)> handler_func)
{
_handler_fillimp = handler_func;
}
Bool_t SingleRnrState() const override { return kTRUE; }
Bool_t SetRnrState(Bool_t) override;
void ProcessSelection(ElementId_t id, bool multi, bool secondary, const std::set<int>& in_secondary_idcs);
};
//==============================================================================
class REveDataCollection : public REveElement
{
private:
REveDataItemList* fItemList{nullptr};
public:
typedef std::vector<int> Ids_t;
static Color_t fgDefaultColor;
TClass *fItemClass{nullptr}; // so far only really need class name
TString fFilterExpr;
std::function<bool(void *)> fFilterFoo = [](void *) { return true; };
REveDataCollection(const std::string& n = "REveDataCollection", const std::string& t = "");
virtual ~REveDataCollection() {}
void ReserveItems(Int_t items_size) { fItemList->fItems.reserve(items_size); }
void AddItem(void *data_ptr, const std::string& n, const std::string& t);
void ClearItems() { fItemList->fItems.clear(); }
Bool_t SingleRnrState() const override { return kTRUE; }
Bool_t SetRnrState(Bool_t) override;
TClass *GetItemClass() const { return fItemClass; }
void SetItemClass(TClass *cls) { fItemClass = cls;
}
REveDataItemList* GetItemList() {return fItemList;}
void SetFilterExpr(const TString &filter);
void ApplyFilter();
Int_t GetNItems() const { return (Int_t) fItemList->fItems.size(); }
void *GetDataPtr(Int_t i) const { return fItemList->fItems[i]->fDataPtr; }
// const REveDataItem& RefDataItem(Int_t i) const { return fItems[i]; }
const REveDataItem* GetDataItem(Int_t i) const { return fItemList->fItems[i]; }
void StreamPublicMethods(nlohmann::json &cj);
Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override;
void SetMainColor(Color_t) override;
};
} // namespace Experimental
} // namespace ROOT
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/basic_serial_port.hpp>
#include <boost/asio/mockup_serial_port_service.hpp>
#include <pre/chrono/chrono_suffixes.hpp>
int main(int argc, char** argv) {
using namespace boost::asio;
using namespace pre::chrono::boost;
{
boost::thread t1([](){
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC1"};
std::string buffer = "Hello";
boost::this_thread::sleep_for(500_ms);
size_t tries = 5;
std::cout << "Writing to SLC BUS" << std::endl;
boost::function<void(const boost::system::error_code& ec, std::size_t bytes_transferred)> write_handler = [&tries, &port, &buffer, &write_handler](const boost::system::error_code& ec, std::size_t bytes_transferred) {
--tries;
buffer = "Holla";
boost::this_thread::sleep_for(100_ms);
if (tries > 0) {
std::cout << "Write done, scheduling next write" << std::endl;
boost::asio::async_write(port, boost::asio::buffer(buffer.data(), buffer.size()), write_handler);
} else {
std::cout << "Write done, finishing" << std::endl;
}
};
//port.write_some(boost::asio::buffer(buffer.data(), buffer.size()));
boost::asio::async_write(port, boost::asio::buffer(buffer.data(), buffer.size()), write_handler);
ios.run();
});
boost::thread t2([](){
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC1"};
size_t tries = 5;
char buffer[255];
while (tries > 0) {
std::cout << "Registering 5 bytes read from SLC BUS" << std::endl;
boost::asio::async_read(port, boost::asio::buffer(buffer, 5),
[&buffer](const boost::system::error_code& ec, std::size_t bytes_transferred) {
std::cout << "Read " << bytes_transferred << " bytes : " << buffer << std::endl;
}
);
--tries;
}
ios.run();
});
t2.join();
t1.join();
}
{
boost::thread producer([]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
boost::this_thread::sleep_for(1_sec);
for (size_t trie = 0; trie < 10; ++trie) {
std::cout << "Sending message " << trie << std::endl;
std::string message = str(boost::format("This is a message %1%") % trie);
boost::asio::write(port, buffer(message.data(), message.size()));
std::string message_end = ", and this ends here.||";
boost::asio::write(port, buffer(message_end.data(), message_end.size()));
boost::this_thread::sleep_for(100_ms);
}
});
boost::thread consumer([]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
streambuf receive_buf;
size_t retries = 10;
boost::function<void (const boost::system::error_code& ec, size_t bytes_read)> readHandler =
[&receive_buf, &readHandler, &port, &retries](const boost::system::error_code& ec, size_t bytes_read) {
--retries;
std::cout << "message arrived of size " << bytes_read << std::endl;
std::string received_message(bytes_read, '\0');
std::istream is(&receive_buf);
is.readsome(&received_message[0], received_message.size());
std::cout << "bytes_read are : " << bytes_read << ", stream input size :" << receive_buf.size() << std::endl;
std::cout << "Message is \"" << received_message << "\"" << std::endl;
if (retries > 0) {
boost::asio::async_read_until(port, receive_buf, "||", readHandler);
}
};
boost::asio::async_read_until(port, receive_buf, "||", readHandler);
ios.run();
});
producer.join();
consumer.join();
}
{
boost::thread producer([]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
for (size_t trie = 0 ; trie < 10; ++trie) {
std::cout << "Sending " << trie << std::endl;
std::string message = str(boost::format("This is a message %1% without end...") % trie);
boost::asio::write(port, buffer(message.data(), message.size()));
boost::this_thread::sleep_for(10_ms);
}
});
boost::thread safe_consumer([]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
streambuf receive_buf;
boost::function<void (const boost::system::error_code& ec, size_t bytes_read)> readHandler =
[&](const boost::system::error_code& ec, size_t bytes_read) {
std::cout << "message arrived of size " << bytes_read << " and error : " << ec << std::endl;
std::string received_message(bytes_read, '\0');
std::istream is(&receive_buf);
is.readsome(&received_message[0], received_message.size());
};
boost::asio::steady_timer timeout{ios};
timeout.expires_from_now(std::chrono::milliseconds(1000));
timeout.async_wait([&port](const boost::system::error_code& ec){
if (ec != boost::asio::error::operation_aborted) {
std::cout << "Cancelling all read !" << std::endl;
port.cancel();
}
});
boost::asio::async_read_until(port, receive_buf, "||", readHandler);
ios.run();
});
producer.join();
safe_consumer.join();
}
return 0;
}
<commit_msg>TEST: Add correct testing of behaviour of mockup_serial_port_service_test with Boost.Test.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE asio_mockup_serial_port_service_test
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/basic_serial_port.hpp>
#include <pre/boost/asio/mockup_serial_port_service.hpp>
#include <pre/chrono/chrono_suffixes.hpp>
BOOST_AUTO_TEST_CASE (asio_mockup_serial_port_service_test_simplereadwrite) {
using namespace boost::asio;
using namespace pre::chrono::boost;
{
const size_t try_count = 5;
boost::thread t1([try_count](){
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC1"};
std::string buffer = "Hello";
boost::this_thread::sleep_for(500_ms);
size_t tries = try_count;
size_t called = 0;
std::cout << "Writing to SLC BUS" << std::endl;
boost::function<void(const boost::system::error_code& ec, std::size_t bytes_transferred)> write_handler
= [&tries, &called, &port, &buffer, &write_handler]
(const boost::system::error_code& ec, std::size_t bytes_transferred) {
BOOST_ASSERT(!ec);
--tries; ++called;
buffer = "Holla";
boost::this_thread::sleep_for(100_ms);
if (tries > 0) {
std::cout << "Write done, scheduling next write" << std::endl;
boost::asio::async_write(port, boost::asio::buffer(buffer.data(), buffer.size()), write_handler);
} else {
std::cout << "Write done, finishing" << std::endl;
}
};
//port.write_some(boost::asio::buffer(buffer.data(), buffer.size()));
boost::asio::async_write(port, boost::asio::buffer(buffer.data(), buffer.size()), write_handler);
ios.run();
BOOST_ASSERT(called == try_count);
});
boost::thread t2([try_count](){
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC1"};
size_t tries = try_count;
size_t called = 0;
char buffer[255];
while (tries > 0) {
std::cout << "Registering 5 bytes read from SLC BUS" << std::endl;
boost::asio::async_read(port, boost::asio::buffer(buffer, 5),
[try_count, tries, &buffer, &called](const boost::system::error_code& ec, std::size_t bytes_transferred) {
std::cout << "Read " << bytes_transferred << " bytes : " << buffer << std::endl;
BOOST_ASSERT(bytes_transferred == 5);
BOOST_ASSERT(!ec);
if (tries == try_count) {
BOOST_ASSERT(std::string(buffer, bytes_transferred) == "Hello");
} else {
BOOST_ASSERT(std::string(buffer, bytes_transferred) == "Holla");
}
++called;
}
);
--tries;
}
ios.run();
BOOST_ASSERT(called == try_count);
});
t2.join();
t1.join();
}
{
const size_t try_count = 10;
boost::thread producer([try_count]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
boost::this_thread::sleep_for(1_sec);
for (size_t trie = 0; trie < try_count; ++trie) {
std::cout << "Sending message " << trie << std::endl;
std::string message = str(boost::format("This is a message %1%") % trie);
auto bytes_written = boost::asio::write(port, buffer(message.data(), message.size()));
BOOST_ASSERT(bytes_written == message.size());
std::string message_end = ", and this ends here.||";
bytes_written = boost::asio::write(port, buffer(message_end.data(), message_end.size()));
BOOST_ASSERT(bytes_written == message_end.size());
boost::this_thread::sleep_for(100_ms);
}
});
boost::thread consumer([try_count]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
streambuf receive_buf;
size_t retries = try_count;
boost::function<void (const boost::system::error_code& ec, size_t bytes_read)> readHandler =
[&receive_buf, &readHandler, &port, &retries](const boost::system::error_code& ec, size_t bytes_read) {
BOOST_ASSERT(!ec);
--retries;
std::cout << "message arrived of size " << bytes_read << std::endl;
std::string received_message(bytes_read, '\0');
std::istream is(&receive_buf);
is.readsome(&received_message[0], received_message.size());
std::cout << "bytes_read are : " << bytes_read << ", stream input size :" << receive_buf.size() << std::endl;
std::cout << "Message is \"" << received_message << "\"" << std::endl;
if (retries > 0) {
boost::asio::async_read_until(port, receive_buf, "||", readHandler);
}
};
boost::asio::async_read_until(port, receive_buf, "||", readHandler);
ios.run();
BOOST_ASSERT_MSG(retries == 0, "Not all message where given back");
});
producer.join();
consumer.join();
}
{
boost::thread producer([]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
for (size_t trie = 0 ; trie < 10; ++trie) {
std::cout << "Sending " << trie << std::endl;
std::string message = str(boost::format("This is a message %1% without end...") % trie);
auto bytes = boost::asio::write(port, buffer(message.data(), message.size()));
BOOST_ASSERT(bytes == message.size());
boost::this_thread::sleep_for(10_ms);
}
});
boost::thread safe_consumer([]() {
io_service ios;
basic_serial_port<mockup_serial_port_service> port{ios, "SLC0"};
streambuf receive_buf;
boost::function<void (const boost::system::error_code& ec, size_t bytes_read)> readHandler =
[&](const boost::system::error_code& ec, size_t bytes_read) {
BOOST_ASSERT(ec == boost::asio::error::operation_aborted);
BOOST_ASSERT(bytes_read == 0);
};
boost::asio::steady_timer timeout{ios};
timeout.expires_from_now(std::chrono::milliseconds(1000));
timeout.async_wait([&port](const boost::system::error_code& ec){
if (ec != boost::asio::error::operation_aborted) {
std::cout << "Cancelling all read !" << std::endl;
port.cancel();
}
});
boost::asio::async_read_until(port, receive_buf, "||", readHandler);
ios.run();
});
producer.join();
safe_consumer.join();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 offa
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions.
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include <gmock/gmock.h>
using namespace danek;
using namespace testing;
class ConfigItemTest : public testing::Test
{
};
TEST_F(ConfigItemTest, stringItem)
{
ConfigItem item{"name_s", "value"};
EXPECT_EQ(ConfType::String, item.type());
EXPECT_THAT(item.name(), StrEq("name_s"));
EXPECT_THAT(item.stringVal(), StrEq("value"));
}
TEST_F(ConfigItemTest, stringItemThrowsOnInvalidTypeAccess)
{
ConfigItem item{"bad", std::vector<std::string>{}};
EXPECT_THROW(item.stringVal(), std::domain_error);
}
TEST_F(ConfigItemTest, stringListItem)
{
const std::vector<std::string> v{"a1", "a2"};
ConfigItem item{"name_l", v};
EXPECT_EQ(ConfType::List, item.type());
EXPECT_THAT(item.name(), StrEq("name_l"));
const auto& ref = item.listVal();
EXPECT_THAT(ref[0], StrEq("a1"));
EXPECT_THAT(ref[1], StrEq("a2"));
}
TEST_F(ConfigItemTest, stringListItemThrowsOnInvalidTypeAccess)
{
ConfigItem item{"bad", "value"};
EXPECT_THROW(item.listVal(), std::domain_error);
}
TEST_F(ConfigItemTest, scopeItem)
{
const char c = '\0';
ConfigItem item{"name_cs", std::make_unique<ConfigScope>(nullptr, &c)};
EXPECT_EQ(ConfType::Scope, item.type());
EXPECT_THAT(item.name(), StrEq("name_cs"));
EXPECT_THAT(item.scopeVal(), Not(nullptr));
}
TEST_F(ConfigItemTest, scopeItemThrowsOnInvalidTypeAccess)
{
ConfigItem item{"bad", "value"};
EXPECT_THROW(item.scopeVal(), std::domain_error);
}
<commit_msg>Test refactored.<commit_after>// Copyright (c) 2017 offa
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions.
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include <gmock/gmock.h>
using namespace danek;
using namespace testing;
class ConfigItemTest : public testing::Test
{
};
TEST_F(ConfigItemTest, stringItem)
{
const ConfigItem item{"name_s", "value"};
EXPECT_EQ(ConfType::String, item.type());
EXPECT_THAT(item.name(), StrEq("name_s"));
EXPECT_THAT(item.stringVal(), StrEq("value"));
}
TEST_F(ConfigItemTest, stringItemThrowsOnInvalidTypeAccess)
{
const ConfigItem item{"bad", std::vector<std::string>{}};
EXPECT_THROW(item.stringVal(), std::domain_error);
}
TEST_F(ConfigItemTest, stringListItem)
{
const std::vector<std::string> v{"a1", "a2"};
ConfigItem item{"name_l", v};
EXPECT_EQ(ConfType::List, item.type());
EXPECT_THAT(item.name(), StrEq("name_l"));
const auto& ref = item.listVal();
EXPECT_THAT(ref[0], StrEq("a1"));
EXPECT_THAT(ref[1], StrEq("a2"));
}
TEST_F(ConfigItemTest, stringListItemThrowsOnInvalidTypeAccess)
{
const ConfigItem item{"bad", "value"};
EXPECT_THROW(item.listVal(), std::domain_error);
}
TEST_F(ConfigItemTest, scopeItem)
{
const char c = '\0';
const ConfigItem item{"name_cs", std::make_unique<ConfigScope>(nullptr, &c)};
EXPECT_EQ(ConfType::Scope, item.type());
EXPECT_THAT(item.name(), StrEq("name_cs"));
EXPECT_THAT(item.scopeVal(), Not(nullptr));
}
TEST_F(ConfigItemTest, scopeItemThrowsOnInvalidTypeAccess)
{
const ConfigItem item{"bad", "value"};
EXPECT_THROW(item.scopeVal(), std::domain_error);
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iomanip>
#include <string>
#include <stdexcept>
#ifndef LOG_HPP
#define LOG_HPP
#define LOG( log, message ) \
(log).logMessage( \
static_cast< std::ostringstream& >( \
std::ostringstream().flush() << (message) \
).str() \
)
#define LOG_COND( log, cond, message ) \
if ( cond ) LOG( log, message )
// TODO: confirm that I havn't made any mistakes in this file
namespace Log
{
class Log
{
public:
Log( const std::string& filename, bool add_header = true )
: filename_( filename )
, out_file_( filename, std::ios_base::out | std::ios_base::trunc )
{
// check if we've succesfully opened the file
if ( !out_file_.is_open() )
{
std::cerr << "\x1b[31;1m Unable to create folder/file to log to: " << filename << "\x1b[37m \n";
throw std::invalid_argument( "filename must be write-openable" );
}
if ( add_header )
{
time_t rawtime;
tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime( buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo );
out_file_ << buffer << std::endl;
}
}
/** Copy constructor */
Log( const Log& other )
: filename_( other.filename_ )
, out_file_( filename_, std::ios_base::out | std::ios_base::app )
{
}
/** Move constructor */
Log( Log&& other )
: filename_( other.filename_ )
, out_file_( filename_, std::ios_base::out | std::ios_base::app )
{
other.out_file_.close();
}
/** Destructor */
~Log()
{
if ( out_file_.is_open() )
{
out_file_.close();
}
}
/** Copy assignment operator */
Log& operator= ( const Log& other )
{
Log tmp( other ); // re-use copy-constructor
*this = std::move( tmp ); // re-use move-assignment
return *this;
}
/** Move assignment operator */
Log& operator= ( Log&& other)
{
std::swap( filename_, other.filename_ );
other.out_file_.close();
if ( out_file_.is_open() )
{
out_file_.close();
}
out_file_.open( filename_, std::ios_base::out | std::ios_base::app );
return *this;
}
void logMessage( const std::string& message )
{
out_file_ << message << std::endl;
}
private:
std::string filename_;
std::ofstream out_file_;
};
}
#endif // LOG_HPP
<commit_msg>Updated LOG functionality to use more precision.<commit_after>#include <fstream>
#include <iomanip>
#include <string>
#include <stdexcept>
#ifndef LOG_HPP
#define LOG_HPP
#define LOG( log, message ) \
(log).logMessage( \
static_cast< std::ostringstream& >( \
std::ostringstream().flush() \
<< std::setprecision(12) \
<< (message) \
).str() \
)
#define LOG_COND( log, cond, message ) \
if ( cond ) LOG( log, message )
// TODO: confirm that I havn't made any mistakes in this file
namespace Log
{
class Log
{
public:
Log( const std::string& filename, bool add_header = true )
: filename_( filename )
, out_file_( filename, std::ios_base::out | std::ios_base::trunc )
{
// check if we've succesfully opened the file
if ( !out_file_.is_open() )
{
std::cerr << "\x1b[31;1m Unable to create folder/file to log to: " << filename << "\x1b[37m \n";
throw std::invalid_argument( "filename must be write-openable" );
}
if ( add_header )
{
time_t rawtime;
tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime( buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo );
out_file_ << buffer << std::endl;
}
}
/** Copy constructor */
Log( const Log& other )
: filename_( other.filename_ )
, out_file_( filename_, std::ios_base::out | std::ios_base::app )
{
}
/** Move constructor */
Log( Log&& other )
: filename_( other.filename_ )
, out_file_( filename_, std::ios_base::out | std::ios_base::app )
{
other.out_file_.close();
}
/** Destructor */
~Log()
{
if ( out_file_.is_open() )
{
out_file_.close();
}
}
/** Copy assignment operator */
Log& operator= ( const Log& other )
{
Log tmp( other ); // re-use copy-constructor
*this = std::move( tmp ); // re-use move-assignment
return *this;
}
/** Move assignment operator */
Log& operator= ( Log&& other)
{
std::swap( filename_, other.filename_ );
other.out_file_.close();
if ( out_file_.is_open() )
{
out_file_.close();
}
out_file_.open( filename_, std::ios_base::out | std::ios_base::app );
return *this;
}
void logMessage( const std::string& message )
{
out_file_ << message << std::endl;
}
private:
std::string filename_;
std::ofstream out_file_;
};
}
#endif // LOG_HPP
<|endoftext|> |
<commit_before>/**
* \file Tools.hpp
* \brief Main header for tools module.
*
* This header provides forward declarations for all memebers of this module.
*/
#ifndef ATLAS_INCLDUE_ATLAS_TOOLS_TOOLS_HPP
#define ATLAS_INCLUDE_ATLAS_TOOLS_TOOLS_HPP
#pragma once
namespace atlas
{
namespace tools
{
class ModellingScene;
class MayaCamera;
class Grid;
}
}
#endif<commit_msg>fixed typo in guard<commit_after>/**
* \file Tools.hpp
* \brief Main header for tools module.
*
* This header provides forward declarations for all memebers of this module.
*/
#ifndef ATLAS_INCLUDE_ATLAS_TOOLS_TOOLS_HPP
#define ATLAS_INCLUDE_ATLAS_TOOLS_TOOLS_HPP
#pragma once
namespace atlas
{
namespace tools
{
class ModellingScene;
class MayaCamera;
class Grid;
}
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Eval Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include <ironbee/predicate/eval.hpp>
#include <ironbee/rule_engine.h>
using namespace std;
namespace IronBee {
namespace Predicate {
namespace {
static IronBee::ScopedMemoryPoolLite c_static_pool;
static const Value
c_empty_string(
IronBee::Field::create_byte_string(
c_static_pool,
"", 0,
IronBee::ByteString::create(c_static_pool)
)
);
}
// NodeEvalState
NodeEvalState::NodeEvalState() :
m_finished(false),
m_phase(IB_PHASE_NONE)
{
// nop
}
void NodeEvalState::forward(const node_p& to)
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't forward a forwarded node."
)
);
}
if (is_aliased()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't forward an aliased node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish an already finished node."
)
);
}
if (m_local_values) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't combine existing values with local values."
)
);
}
m_forward = to;
}
void NodeEvalState::set_phase(ib_rule_phase_num_t phase)
{
m_phase = phase;
}
void NodeEvalState::setup_local_list(MemoryManager mm)
{
return setup_local_list(mm, "", 0);
}
void NodeEvalState::setup_local_list(
MemoryManager mm,
const char* name,
size_t name_length
)
{
if (is_aliased()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Cannot setup local values on aliased node."
)
);
}
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Cannot setup local values on forwarded node."
)
);
}
if (m_value) {
// do nothing
return;
}
m_local_values = List<Value>::create(mm);
m_value = Value::alias_list(mm, name, name_length, m_local_values);
}
void NodeEvalState::append_to_list(Value value)
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't add value to forwarded node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't add value to finished node."
)
);
}
if (! m_local_values) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Attempting to add value before setting up local list."
)
);
}
m_local_values.push_back(value);
}
void NodeEvalState::finish()
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish a forwarded node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish an already finished node."
)
);
}
m_finished = true;
}
void NodeEvalState::finish(Value v)
{
if (m_value) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish a valued node with a value."
)
);
}
// Call finish first to do normal finish checks.
finish();
m_value = v;
}
void NodeEvalState::alias(Value other)
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias a forwarded node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias a finished node."
)
);
}
if (m_local_values) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias a local valued node."
)
);
}
if (m_value) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias an aliased node."
)
);
}
m_value = other;
}
void NodeEvalState::finish_true(EvalContext eval_context)
{
finish(c_empty_string);
}
// GraphEvalState
GraphEvalState::GraphEvalState(size_t index_limit) :
m_vector(index_limit)
{
// nop
}
const NodeEvalState& GraphEvalState::final(size_t index) const
{
while (m_vector[index].is_forwarding()) {
index = m_vector[index].forwarded_to()->index();
}
return m_vector[index];
}
Value GraphEvalState::value(size_t index) const
{
return final(index).value();
}
ib_rule_phase_num_t GraphEvalState::phase(size_t index) const
{
return final(index).phase();
}
bool GraphEvalState::is_finished(size_t index) const
{
return final(index).is_finished();
}
void GraphEvalState::initialize(const node_cp& node, EvalContext context)
{
assert(! m_vector[node->index()].is_forwarding());
node->eval_initialize(*this, context);
}
void GraphEvalState::eval(const node_cp& node, EvalContext context)
{
// In certain cases, e.g., literals, we run without a context or
// rule_exec. Then, always calculate.
ib_rule_phase_num_t phase = IB_PHASE_NONE;
if (context.ib() && context.ib()->rule_exec) {
phase = context.ib()->rule_exec->phase;
}
// Handle forwarding.
node_cp final_node = node;
while (m_vector[final_node->index()].is_forwarding()) {
final_node = m_vector[final_node->index()].forwarded_to();
}
NodeEvalState& node_eval_state = m_vector[final_node->index()];
assert(! node_eval_state.is_forwarding());
if (
! node_eval_state.is_finished() &&
(node_eval_state.phase() != phase || phase == IB_PHASE_NONE)
) {
node_eval_state.set_phase(phase);
final_node->eval_calculate(*this, context);
}
}
// Doxygen confused by this code.
#ifndef DOXYGEN_SKIP
namespace Impl {
make_indexer_helper_t::make_indexer_helper_t(size_t& index_limit) :
m_index_limit(index_limit)
{
// nop
}
void make_indexer_helper_t::operator()(const node_p& node)
{
node->set_index(m_index_limit);
++m_index_limit;
}
make_initializer_helper_t::make_initializer_helper_t(
GraphEvalState& graph_eval_state,
EvalContext context
) :
m_graph_eval_state(graph_eval_state),
m_context(context)
{
// nop
}
void make_initializer_helper_t::operator()(const node_cp& node)
{
m_graph_eval_state.initialize(node, m_context);
}
}
#endif
boost::function_output_iterator<Impl::make_indexer_helper_t>
make_indexer(size_t& index_limit)
{
index_limit = 0;
return boost::function_output_iterator<Impl::make_indexer_helper_t>(
Impl::make_indexer_helper_t(index_limit)
);
}
boost::function_output_iterator<Impl::make_initializer_helper_t>
make_initializer(GraphEvalState& graph_eval_state, EvalContext context)
{
return boost::function_output_iterator<Impl::make_initializer_helper_t>(
Impl::make_initializer_helper_t(graph_eval_state, context)
);
}
} // Predicate
} // IronBee
<commit_msg>predicate/eval.cpp: Add optional tracing code.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Eval Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
// Define EVAL_TRACE to output information to cout at beginning and end
// of every eval() call.
//#define EVAL_TRACE
#include <ironbee/predicate/eval.hpp>
#include <ironbee/rule_engine.h>
using namespace std;
namespace IronBee {
namespace Predicate {
namespace {
static IronBee::ScopedMemoryPoolLite c_static_pool;
static const Value
c_empty_string(
IronBee::Field::create_byte_string(
c_static_pool,
"", 0,
IronBee::ByteString::create(c_static_pool)
)
);
}
// NodeEvalState
NodeEvalState::NodeEvalState() :
m_finished(false),
m_phase(IB_PHASE_NONE)
{
// nop
}
void NodeEvalState::forward(const node_p& to)
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't forward a forwarded node."
)
);
}
if (is_aliased()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't forward an aliased node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish an already finished node."
)
);
}
if (m_local_values) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't combine existing values with local values."
)
);
}
m_forward = to;
}
void NodeEvalState::set_phase(ib_rule_phase_num_t phase)
{
m_phase = phase;
}
void NodeEvalState::setup_local_list(MemoryManager mm)
{
return setup_local_list(mm, "", 0);
}
void NodeEvalState::setup_local_list(
MemoryManager mm,
const char* name,
size_t name_length
)
{
if (is_aliased()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Cannot setup local values on aliased node."
)
);
}
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Cannot setup local values on forwarded node."
)
);
}
if (m_value) {
// do nothing
return;
}
m_local_values = List<Value>::create(mm);
m_value = Value::alias_list(mm, name, name_length, m_local_values);
}
void NodeEvalState::append_to_list(Value value)
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't add value to forwarded node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't add value to finished node."
)
);
}
if (! m_local_values) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Attempting to add value before setting up local list."
)
);
}
m_local_values.push_back(value);
}
void NodeEvalState::finish()
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish a forwarded node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish an already finished node."
)
);
}
m_finished = true;
}
void NodeEvalState::finish(Value v)
{
if (m_value) {
BOOST_THROW_EXCEPTION(
IronBee::einval() << errinfo_what(
"Can't finish a valued node with a value."
)
);
}
// Call finish first to do normal finish checks.
finish();
m_value = v;
}
void NodeEvalState::alias(Value other)
{
if (is_forwarding()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias a forwarded node."
)
);
}
if (is_finished()) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias a finished node."
)
);
}
if (m_local_values) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias a local valued node."
)
);
}
if (m_value) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"Can't alias an aliased node."
)
);
}
m_value = other;
}
void NodeEvalState::finish_true(EvalContext eval_context)
{
finish(c_empty_string);
}
// GraphEvalState
GraphEvalState::GraphEvalState(size_t index_limit) :
m_vector(index_limit)
{
// nop
}
const NodeEvalState& GraphEvalState::final(size_t index) const
{
while (m_vector[index].is_forwarding()) {
index = m_vector[index].forwarded_to()->index();
}
return m_vector[index];
}
Value GraphEvalState::value(size_t index) const
{
return final(index).value();
}
ib_rule_phase_num_t GraphEvalState::phase(size_t index) const
{
return final(index).phase();
}
bool GraphEvalState::is_finished(size_t index) const
{
return final(index).is_finished();
}
void GraphEvalState::initialize(const node_cp& node, EvalContext context)
{
assert(! m_vector[node->index()].is_forwarding());
node->eval_initialize(*this, context);
}
void GraphEvalState::eval(const node_cp& node, EvalContext context)
{
#ifdef EVAL_TRACE
cout << "EVAL " << node->to_s() << endl;
#endif
// In certain cases, e.g., literals, we run without a context or
// rule_exec. Then, always calculate.
ib_rule_phase_num_t phase = IB_PHASE_NONE;
if (context.ib() && context.ib()->rule_exec) {
phase = context.ib()->rule_exec->phase;
}
// Handle forwarding.
node_cp final_node = node;
while (m_vector[final_node->index()].is_forwarding()) {
final_node = m_vector[final_node->index()].forwarded_to();
}
NodeEvalState& node_eval_state = m_vector[final_node->index()];
assert(! node_eval_state.is_forwarding());
if (
! node_eval_state.is_finished() &&
(node_eval_state.phase() != phase || phase == IB_PHASE_NONE)
) {
node_eval_state.set_phase(phase);
final_node->eval_calculate(*this, context);
}
#ifdef EVAL_TRACE
cout << "VALUE " << node->to_s() << " = " << value(node->index()) << endl;
#endif
}
// Doxygen confused by this code.
#ifndef DOXYGEN_SKIP
namespace Impl {
make_indexer_helper_t::make_indexer_helper_t(size_t& index_limit) :
m_index_limit(index_limit)
{
// nop
}
void make_indexer_helper_t::operator()(const node_p& node)
{
node->set_index(m_index_limit);
++m_index_limit;
}
make_initializer_helper_t::make_initializer_helper_t(
GraphEvalState& graph_eval_state,
EvalContext context
) :
m_graph_eval_state(graph_eval_state),
m_context(context)
{
// nop
}
void make_initializer_helper_t::operator()(const node_cp& node)
{
m_graph_eval_state.initialize(node, m_context);
}
}
#endif
boost::function_output_iterator<Impl::make_indexer_helper_t>
make_indexer(size_t& index_limit)
{
index_limit = 0;
return boost::function_output_iterator<Impl::make_indexer_helper_t>(
Impl::make_indexer_helper_t(index_limit)
);
}
boost::function_output_iterator<Impl::make_initializer_helper_t>
make_initializer(GraphEvalState& graph_eval_state, EvalContext context)
{
return boost::function_output_iterator<Impl::make_initializer_helper_t>(
Impl::make_initializer_helper_t(graph_eval_state, context)
);
}
} // Predicate
} // IronBee
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007-2008, Python File Format Interface
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 Python File Format Interface
project 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include "pyffi/object_models/meta_struct.hpp"
#include "pyffi/exceptions.hpp"
using namespace pyffi;
using namespace pyffi::object_models;
BOOST_AUTO_TEST_SUITE(meta_struct_test_suite)
BOOST_AUTO_TEST_CASE(create_test)
{
// we basically test the following declarations:
// class TestClass1
// class TestClass2(TestClass1):
// class TestClass3
// class TestClass4(TestClass3)
// class TestClass5(TestClass1)
PMetaStruct ms0;
PMetaStruct ms1;
PMetaStruct ms2;
PMetaStruct ms3;
PMetaStruct ms4;
PMetaStruct ms5;
BOOST_CHECK_NO_THROW(ms0 = MetaStruct::create());
BOOST_CHECK_NO_THROW(ms1 = MetaStruct::create(ms0, "TestClass1"));
BOOST_CHECK_NO_THROW(ms2 = MetaStruct::create(ms0, "TestClass2", ms1));
BOOST_CHECK_NO_THROW(ms3 = MetaStruct::create(ms2, "TestClass3"));
BOOST_CHECK_NO_THROW(ms4 = MetaStruct::create(ms2, "TestClass4", ms3));
BOOST_CHECK_NO_THROW(ms5 = MetaStruct::create(ms2, "TestClass5", ms1));
// check that class cannot be added again
BOOST_CHECK_THROW(MetaStruct::create(ms0, "TestClass1"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms0, "TestClass2"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms2, "TestClass3"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms2, "TestClass4"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms2, "TestClass5"), value_error);
}
BOOST_AUTO_TEST_CASE(add_test)
{
PMetaStruct ms = MetaStruct::create();
PMetaAttribute ma1(new MetaAttribute(5));
PMetaAttribute ma2(new MetaAttribute('y'));
PMetaAttribute ma3(new MetaAttribute(std::string("Hello world!")));
// add arguments of various types
BOOST_CHECK_NO_THROW(ms->add("arg1", ma1));
BOOST_CHECK_NO_THROW(ms->add("arg2", ma2));
BOOST_CHECK_NO_THROW(ms->add("arg3", ma3));
// check that argument cannot be added again
PMetaAttribute ma4(new MetaAttribute(999));
BOOST_CHECK_THROW(ms->add("arg1", ma4), value_error);
BOOST_CHECK_THROW(ms->add("arg2", ma4), value_error);
BOOST_CHECK_THROW(ms->add("arg3", ma4), value_error);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Added regression test for MetaStruct::get.<commit_after>/*
Copyright (c) 2007-2008, Python File Format Interface
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 Python File Format Interface
project 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include "pyffi/object_models/meta_struct.hpp"
#include "pyffi/exceptions.hpp"
using namespace pyffi;
using namespace pyffi::object_models;
BOOST_AUTO_TEST_SUITE(meta_struct_test_suite)
BOOST_AUTO_TEST_CASE(create_test)
{
// we basically test the following declarations:
// class TestClass1
// class TestClass2(TestClass1):
// class TestClass3
// class TestClass4(TestClass3)
// class TestClass5(TestClass1)
PMetaStruct ms0;
PMetaStruct ms1;
PMetaStruct ms2;
PMetaStruct ms3;
PMetaStruct ms4;
PMetaStruct ms5;
BOOST_CHECK_NO_THROW(ms0 = MetaStruct::create());
BOOST_CHECK_NO_THROW(ms1 = MetaStruct::create(ms0, "TestClass1"));
BOOST_CHECK_NO_THROW(ms2 = MetaStruct::create(ms0, "TestClass2", ms1));
BOOST_CHECK_NO_THROW(ms3 = MetaStruct::create(ms2, "TestClass3"));
BOOST_CHECK_NO_THROW(ms4 = MetaStruct::create(ms2, "TestClass4", ms3));
BOOST_CHECK_NO_THROW(ms5 = MetaStruct::create(ms2, "TestClass5", ms1));
// check that class cannot be added again
BOOST_CHECK_THROW(MetaStruct::create(ms0, "TestClass1"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms0, "TestClass2"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms2, "TestClass3"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms2, "TestClass4"), value_error);
BOOST_CHECK_THROW(MetaStruct::create(ms2, "TestClass5"), value_error);
}
BOOST_AUTO_TEST_CASE(add_test)
{
PMetaStruct ms = MetaStruct::create();
PMetaAttribute ma1(new MetaAttribute(5));
PMetaAttribute ma2(new MetaAttribute('y'));
PMetaAttribute ma3(new MetaAttribute(std::string("Hello world!")));
// add arguments of various types
BOOST_CHECK_NO_THROW(ms->add("arg1", ma1));
BOOST_CHECK_NO_THROW(ms->add("arg2", ma2));
BOOST_CHECK_NO_THROW(ms->add("arg3", ma3));
// check that argument cannot be added again
PMetaAttribute ma4(new MetaAttribute(999));
BOOST_CHECK_THROW(ms->add("arg1", ma4), value_error);
BOOST_CHECK_THROW(ms->add("arg2", ma4), value_error);
BOOST_CHECK_THROW(ms->add("arg3", ma4), value_error);
}
BOOST_AUTO_TEST_CASE(get_test)
{
PMetaStruct ms0;
PMetaStruct ms1;
PMetaStruct ms2;
BOOST_CHECK_NO_THROW(ms0 = MetaStruct::create());
BOOST_CHECK_NO_THROW(ms1 = MetaStruct::create(ms0, "TestClass1"));
BOOST_CHECK_NO_THROW(ms2 = MetaStruct::create(ms0, "TestClass2", ms1));
// check if we get back the right classes
BOOST_CHECK_EQUAL(ms0->get("TestClass1"), ms1);
BOOST_CHECK_EQUAL(ms0->get("TestClass2"), ms2);
// check that we cannot get something that hasn't been added yet
BOOST_CHECK_THROW(ms0->get("TestClass3"), name_error);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <memory>
#include <functional>
namespace audio_io {
/**Note: all strings are encoded as UTF8.
This library will decode as necessary.*/
/**Call initialize first; call shutdown last.
These are primarily for setting up logging. The main interface of the library is through getOutputDevice factory and similar.*/
void initialize();
void shutdown();
/**A physical output.*/
class OutputDevice {
public:
virtual ~OutputDevice() {}
};
class OutputDeviceFactory {
public:
OutputDeviceFactory() = default;
virtual ~OutputDeviceFactory() {}
virtual std::vector<std::string> getOutputNames() = 0;
virtual std::vector<int> getOutputMaxChannels() = 0;
virtual std::shared_ptr<OutputDevice> createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) = 0;
virtual unsigned int getOutputCount() = 0;
virtual std::string getName() = 0;
};
std::shared_ptr<OutputDeviceFactory> getOutputDeviceFactory();
/**Remix a buffer. These can be used without initialization.
- The standard channel counts 1, 2, 6 (5.1) and 8 (7.1) are mixed between each other appropriately.
- Otherwise, if input is mono and output is not mono, the input is copied to all channels.
- Otherwise, we keep min(inputChannels, outputChannels) channels of audio data, and fill any remaining output channels with zero.
These functions come in two variants.
- The uninterleaved version expects audio data as contiguous frames.
- The interleaved version expects audio data as an array of buffers.
In-place usage is not safe.
zeroFirst is intended for applications that need to accumulate data; if true (the default) buffers are zeroed before use.
*/
void remixAudioInterleaved(int frames, int inputChannels, float* input, int outputChannels, float* output, bool zeroFirst = true);
void remixAudioUninterleaved(int frames, int inputChannels, float** inputs, int outputChannels, float** outputs, bool zeroFirst = true);
}<commit_msg>Document that we need to delete objects before calling shutdown.<commit_after>#pragma once
#include <vector>
#include <memory>
#include <functional>
namespace audio_io {
/**Note: all strings are encoded as UTF8.
This library will decode as necessary.*/
/**Call initialize first; call shutdown last.
These are primarily for setting up logging. The main interface of the library is through getOutputDevice factory and similar.
Be sure that you delete all objects that you got from this library before calling shutdown. Failure to do so will cause breakage as some destructors try to log.*/
void initialize();
void shutdown();
/**A physical output.*/
class OutputDevice {
public:
virtual ~OutputDevice() {}
};
class OutputDeviceFactory {
public:
OutputDeviceFactory() = default;
virtual ~OutputDeviceFactory() {}
virtual std::vector<std::string> getOutputNames() = 0;
virtual std::vector<int> getOutputMaxChannels() = 0;
virtual std::shared_ptr<OutputDevice> createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) = 0;
virtual unsigned int getOutputCount() = 0;
virtual std::string getName() = 0;
};
std::shared_ptr<OutputDeviceFactory> getOutputDeviceFactory();
/**Remix a buffer. These can be used without initialization.
- The standard channel counts 1, 2, 6 (5.1) and 8 (7.1) are mixed between each other appropriately.
- Otherwise, if input is mono and output is not mono, the input is copied to all channels.
- Otherwise, we keep min(inputChannels, outputChannels) channels of audio data, and fill any remaining output channels with zero.
These functions come in two variants.
- The uninterleaved version expects audio data as contiguous frames.
- The interleaved version expects audio data as an array of buffers.
In-place usage is not safe.
zeroFirst is intended for applications that need to accumulate data; if true (the default) buffers are zeroed before use.
*/
void remixAudioInterleaved(int frames, int inputChannels, float* input, int outputChannels, float* output, bool zeroFirst = true);
void remixAudioUninterleaved(int frames, int inputChannels, float** inputs, int outputChannels, float** outputs, bool zeroFirst = true);
}<|endoftext|> |
<commit_before>#include "wlcjs.h"
namespace wlcjs {
wlc_event_source* timer = NULL;
uv_timer_t async_run_timer;
SimplePersistent<Function> persistent_log_handler;
int run_uv_loop(void *args) {
uv_run(uv_default_loop(), UV_RUN_NOWAIT);
wlc_event_source_timer_update(timer, 1);
return 1;
}
void log_handler(enum wlc_log_type type, const char *str) {
if (persistent_log_handler.IsEmpty()) return;
Isolate* isolate = persistent_log_handler.GetIsolate();
HandleScope scope(isolate);
Local<Function> log_handler = Local<Function>::New(isolate, persistent_log_handler);
Local<Value> arguments[] = {
S(enum_to_string(type)),
S(str),
};
log_handler->Call(Null(isolate), 2, arguments);
}
void Init(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (is_initalized()) THROW(Error, "Can't call init twice");
if (args.Length() < 1) THROW(TypeError, "'interface' argument required");
if (!args[0]->IsObject()) THROW(TypeError, "'interface' must be an object");
Local<Array> jsArgv = isolate->GetCurrentContext()->Global()
->Get(S("process")).As<Object>()
->Get(S("argv")).As<Array>();
int argc = jsArgv->Length();
char *argv[argc];
for (int i = 0; i < argc; i += 1) {
String::Utf8Value v(jsArgv->Get(i)->ToString());
argv[i] = new char[v.length() + 1];
memcpy(argv[i], *v, v.length() + 1);
}
wlc_log_set_handler(log_handler);
wlc_init(get_wlc_interface(args[0]->ToObject()), argc, argv);
}
void run_cb(uv_timer_t* handle) {
timer = wlc_event_loop_add_timer(run_uv_loop, NULL);
wlc_event_source_timer_update(timer, 1);
wlc_run();
}
void Run(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (!is_initalized()) THROW(Error, "Call init first");
uv_timer_init(uv_default_loop(), &async_run_timer);
uv_timer_start(&async_run_timer, run_cb, 0, 0);
}
void SetLogHandler(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.Length() < 1) THROW(TypeError, "'handler' argument required");
if (!args[0]->IsFunction()) THROW(TypeError, "'handler' must be a function");
persistent_log_handler.Reset(args[0].As<Function>());
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "init", Init);
NODE_SET_METHOD(exports, "run", Run);
NODE_SET_METHOD(exports, "setLogHandler", SetLogHandler);
}
NODE_MODULE(addon, init)
}
<commit_msg>There is no such thing as "too much macros"<commit_after>#include "wlcjs.h"
namespace wlcjs {
wlc_event_source* timer = NULL;
uv_timer_t async_run_timer;
SimplePersistent<Function> persistent_log_handler;
#define ARG(I, TYPE, NAME) \
if (args.Length() <= I) THROW(TypeError, "Argument " #I " is required");\
if (!args[I]->Is ## TYPE ()) THROW(TypeError, "Argument " #I " must be a " #TYPE);\
Local<TYPE> NAME = args[I].As<TYPE>();
#define RETURN(V) \
args.GetReturnValue().Set(V);\
return;
#define FN(NAME, CODE) \
void NAME (const FunctionCallbackInfo<Value>& args) {\
Isolate* isolate = args.GetIsolate();\
CODE\
}
int run_uv_loop(void *args) {
uv_run(uv_default_loop(), UV_RUN_NOWAIT);
wlc_event_source_timer_update(timer, 1);
return 1;
}
void log_handler(enum wlc_log_type type, const char *str) {
if (persistent_log_handler.IsEmpty()) return;
Isolate* isolate = persistent_log_handler.GetIsolate();
HandleScope scope(isolate);
Local<Function> log_handler = Local<Function>::New(isolate, persistent_log_handler);
Local<Value> arguments[] = {
S(enum_to_string(type)),
S(str),
};
log_handler->Call(Null(isolate), 2, arguments);
}
FN(Init,
ARG(0, Object, interface);
if (is_initalized()) THROW(Error, "Can't call init twice");
Local<Array> jsArgv = isolate->GetCurrentContext()->Global()
->Get(S("process")).As<Object>()
->Get(S("argv")).As<Array>();
int argc = jsArgv->Length();
char *argv[argc];
for (int i = 0; i < argc; i += 1) {
String::Utf8Value v(jsArgv->Get(i)->ToString());
argv[i] = new char[v.length() + 1];
memcpy(argv[i], *v, v.length() + 1);
}
wlc_log_set_handler(log_handler);
wlc_init(get_wlc_interface(interface), argc, argv);
)
void run_cb(uv_timer_t* handle) {
timer = wlc_event_loop_add_timer(run_uv_loop, NULL);
wlc_event_source_timer_update(timer, 1);
wlc_run();
}
FN(Run,
if (!is_initalized()) THROW(Error, "Call init first");
uv_timer_init(uv_default_loop(), &async_run_timer);
uv_timer_start(&async_run_timer, run_cb, 0, 0);
)
FN(SetLogHandler,
ARG(0, Function, handler);
persistent_log_handler.Reset(handler);
)
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "init", Init);
NODE_SET_METHOD(exports, "run", Run);
NODE_SET_METHOD(exports, "setLogHandler", SetLogHandler);
}
NODE_MODULE(addon, init)
}
<|endoftext|> |
<commit_before>/*
* SnapFind (Release 0.9)
* An interactive image search application
*
* Copyright (c) 2002-2005, Intel Corporation
* All Rights Reserved
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <dlfcn.h>
#include <gtk/gtk.h>
#include <opencv/cv.h>
#include <opencv/cvaux.h>
#include <sys/stat.h>
#include "queue.h"
#include "rgb.h"
#include "lib_results.h"
#include "snapfind_consts.h"
#include "img_search.h"
#include "ocv_search.h"
#include "opencv_face_tools.h"
#include "search_set.h"
#include "factory.h"
#include "snapfind_config.h"
#define MAX_DISPLAY_NAME 64
/* config tokens */
#define NUMFACE_ID "NUMFACE"
#define SUPPORT_ID "SUPPORT"
ocv_search::ocv_search(const char *name, char *descr)
: window_search(name, descr)
{
set_count(1);
set_support(2);
edit_window = NULL;
count_widget = NULL;
support_widget = NULL;
}
ocv_search::~ocv_search()
{
free((char *) get_auxiliary_data());
free(cascade_file_name);
return;
}
int
ocv_search::get_count()
{
return(count);
}
void
ocv_search::set_count(char *data)
{
int new_count = atoi(data);
set_count(new_count);
return;
}
void
ocv_search::set_count(int new_count)
{
if (new_count < 0) {
new_count = 0;
}
count = new_count;
return;
}
int
ocv_search::get_support()
{
return(support_matches);
}
void
ocv_search::set_support(char *data)
{
int new_count = atoi(data);
set_support(new_count);
return;
}
void
ocv_search::set_support(int new_count)
{
if (new_count < 0) {
new_count = 0;
}
support_matches = new_count;
return;
}
void
ocv_search::set_classifier(char *name)
{
int fd;
int rc;
char *cascade_bytes;
struct stat stats;
size_t nbytes;
fprintf(stderr, "set_classified !!! \n");
cascade_file_name = (char *) malloc(SF_MAX_PATH);
strcpy(cascade_file_name, sfconf_get_plugin_dir());
strcat(cascade_file_name, "/");
strcat(cascade_file_name, name);
strcat(cascade_file_name, ".xml");
printf("opening %s\n", cascade_file_name);
fd = open(cascade_file_name, O_RDONLY);
assert(fd >=0);
rc = fstat(fd, &stats);
if (rc < 0) {
close(fd);
assert(0);
}
cascade_bytes = (char *) malloc(stats.st_size);
if (cascade_bytes == NULL) {
close(fd);
assert(0);
}
nbytes = read(fd, cascade_bytes, stats.st_size);
if (nbytes < stats.st_size) {
close(fd);
assert(0);
}
set_auxiliary_data((void *) cascade_bytes);
set_auxiliary_data_length(nbytes);
close(fd);
}
static GtkWidget *
create_slider_entry(char *name, float min, float max, int dec, float initial,
float step, GtkObject **adjp)
{
GtkWidget *container;
GtkWidget *scale;
GtkWidget *button;
GtkWidget *label;
container = gtk_hbox_new(FALSE, 10);
label = gtk_label_new(name);
gtk_box_pack_start(GTK_BOX(container), label, FALSE, FALSE, 0);
if (max <= 1.0) {
max += 0.1;
*adjp = gtk_adjustment_new(min, min, max, step, 0.1, 0.1);
} else if (max < 50) {
max++;
*adjp = gtk_adjustment_new(min, min, max, step, 1.0, 1.0);
} else {
max+= 10;
*adjp = gtk_adjustment_new(min, min, max, step, 10.0, 10.0);
}
gtk_adjustment_set_value(GTK_ADJUSTMENT(*adjp), initial);
scale = gtk_hscale_new(GTK_ADJUSTMENT(*adjp));
gtk_widget_set_size_request (GTK_WIDGET(scale), 200, -1);
gtk_range_set_update_policy (GTK_RANGE(scale), GTK_UPDATE_CONTINUOUS);
gtk_scale_set_draw_value (GTK_SCALE(scale), FALSE);
gtk_box_pack_start (GTK_BOX(container), scale, TRUE, TRUE, 0);
gtk_widget_set_size_request(scale, 120, 0);
button = gtk_spin_button_new(GTK_ADJUSTMENT(*adjp), step, dec);
gtk_box_pack_start(GTK_BOX(container), button, FALSE, FALSE, 0);
gtk_widget_show(container);
gtk_widget_show(label);
gtk_widget_show(scale);
gtk_widget_show(button);
return(container);
}
static void
cb_close_edit_window(GtkWidget* item, gpointer data)
{
ocv_search * search;
search = (ocv_search *)data;
search->close_edit_win();
}
void
ocv_search::close_edit_win()
{
/* save any changes from the edit windows */
save_edits();
/* call the parent class to give them change to cleanup */
window_search::close_edit_win();
edit_window = NULL;
}
static void
edit_search_done_cb(GtkButton *item, gpointer data)
{
GtkWidget * widget = (GtkWidget *)data;
gtk_widget_destroy(widget);
}
void
ocv_search::edit_search()
{
GtkWidget * widget;
GtkWidget * box;
GtkWidget * frame;
GtkWidget * hbox;
GtkWidget * container;
char name[MAX_DISPLAY_NAME];
/* see if it already exists */
if (edit_window != NULL) {
/* raise to top ??? */
gdk_window_raise(GTK_WIDGET(edit_window)->window);
return;
}
edit_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
snprintf(name, MAX_DISPLAY_NAME - 1, "Edit %s", get_name());
name[MAX_DISPLAY_NAME -1] = '\0';
gtk_window_set_title(GTK_WINDOW(edit_window), name);
//gtk_window_set_default_size(GTK_WINDOW(edit_window), 750, 350);
g_signal_connect(G_OBJECT(edit_window), "destroy",
G_CALLBACK(cb_close_edit_window), this);
box = gtk_vbox_new(FALSE, 10);
hbox = gtk_hbox_new(FALSE, 10);
gtk_box_pack_start(GTK_BOX(box), hbox, FALSE, TRUE, 0);
widget = gtk_button_new_with_label("Close");
g_signal_connect(G_OBJECT(widget), "clicked",
G_CALLBACK(edit_search_done_cb), edit_window);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_DEFAULT);
gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
/*
* Get the controls from the img_search.
*/
widget = img_search_display();
gtk_box_pack_start(GTK_BOX(box), widget, FALSE, TRUE, 0);
/*
* Create the texture parameters.
*/
frame = gtk_frame_new("OpenCV Search");
container = gtk_vbox_new(FALSE, 10);
gtk_container_add(GTK_CONTAINER(frame), container);
widget = create_slider_entry("Number of Objects", 0.0, 20.0, 0,
count, 1.0, &count_widget);
gtk_box_pack_start(GTK_BOX(container), widget, FALSE, TRUE, 0);
widget = create_slider_entry("Num Supporting", 0.0, 20.0, 0,
support_matches, 1.0, &support_widget);
gtk_box_pack_start(GTK_BOX(container), widget, FALSE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(box), frame, FALSE, TRUE, 0);
gtk_widget_show(container);
/*
* Get the controls from the window search class.
*/
widget = get_window_cntrl();
gtk_box_pack_start(GTK_BOX(box), widget, FALSE, TRUE, 0);
gtk_container_add(GTK_CONTAINER(edit_window), box);
//gtk_window_set_default_size(GTK_WINDOW(edit_window), 400, 500);
gtk_widget_show_all(edit_window);
}
/*
* This method reads the values from the current edit
* window if there is an active one.
*/
void
ocv_search::save_edits()
{
int val;
/* no active edit window, so return */
if (edit_window == NULL) {
return;
}
val = (int)gtk_adjustment_get_value(GTK_ADJUSTMENT(count_widget));
set_count(val);
val = (int)gtk_adjustment_get_value(GTK_ADJUSTMENT(support_widget));
/* XXX use accessor method ?? */
support_matches = val;
/* call the parent class */
window_search::save_edits();
}
/*
* This write the relevant section of the filter specification file
* for this search.
*/
void
ocv_search::write_fspec(FILE *ostream)
{
img_search * rgb;
img_factory * ifac;
/*
* Write the remainder of the header.
*/
fprintf(ostream, "THRESHOLD %d \n", count);
fprintf(ostream, "ARG %s # name \n", get_name());
/*
* Next we write call the parent to write out the releated args,
* not that since the args are passed as a vector of strings
* we need keep the order the args are written constant or silly
* things will happen.
*/
window_search::write_fspec(ostream);
fprintf(ostream, "ARG %d # support \n", support_matches);
/* XXX can we use the integrate somehow in opencv ?? */
fprintf(ostream, "REQUIRES RGB # dependancies \n");
fprintf(ostream, "MERIT 10 # some relative cost \n");
fprintf(ostream, "\n");
ifac = find_support_factory("rgb_image");
assert(ifac != NULL);
rgb = ifac->create("RGB image");
(this->get_parent())->add_dep(rgb);
}
void
ocv_search::region_match(RGBImage *img, bbox_list_t *blist)
{
opencv_fdetect_t fconfig;
int pass;
save_edits();
fconfig.name = strdup(get_name());
assert(fconfig.name != NULL);
fconfig.scale_mult = get_scale();
fconfig.xsize = get_testx();
fconfig.ysize = get_testy();
fconfig.stride = get_stride();
fconfig.support = support_matches;
fconfig.haar_cascade = cvLoadHaarClassifierCascade(
cascade_file_name, cvSize(fconfig.xsize, fconfig.ysize));
pass = opencv_face_scan(img, blist, &fconfig);
cvReleaseHaarClassifierCascade(&fconfig.haar_cascade);
free(fconfig.name);
return;
}
int
ocv_search::handle_config(int nconf, char **data)
{
int err;
if (strcmp(NUMFACE_ID, data[0]) == 0) {
assert(nconf > 1);
set_count(data[1]);
err = 0;
} else if (strcmp(SUPPORT_ID, data[0]) == 0) {
assert(nconf > 1);
set_support(data[1]);
err = 0;
} else {
err = window_search::handle_config(nconf, data);
}
return(err);
}
<commit_msg>remove old debugging code<commit_after>/*
* SnapFind (Release 0.9)
* An interactive image search application
*
* Copyright (c) 2002-2005, Intel Corporation
* All Rights Reserved
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <dlfcn.h>
#include <gtk/gtk.h>
#include <opencv/cv.h>
#include <opencv/cvaux.h>
#include <sys/stat.h>
#include "queue.h"
#include "rgb.h"
#include "lib_results.h"
#include "snapfind_consts.h"
#include "img_search.h"
#include "ocv_search.h"
#include "opencv_face_tools.h"
#include "search_set.h"
#include "factory.h"
#include "snapfind_config.h"
#define MAX_DISPLAY_NAME 64
/* config tokens */
#define NUMFACE_ID "NUMFACE"
#define SUPPORT_ID "SUPPORT"
ocv_search::ocv_search(const char *name, char *descr)
: window_search(name, descr)
{
set_count(1);
set_support(2);
edit_window = NULL;
count_widget = NULL;
support_widget = NULL;
}
ocv_search::~ocv_search()
{
free((char *) get_auxiliary_data());
free(cascade_file_name);
return;
}
int
ocv_search::get_count()
{
return(count);
}
void
ocv_search::set_count(char *data)
{
int new_count = atoi(data);
set_count(new_count);
return;
}
void
ocv_search::set_count(int new_count)
{
if (new_count < 0) {
new_count = 0;
}
count = new_count;
return;
}
int
ocv_search::get_support()
{
return(support_matches);
}
void
ocv_search::set_support(char *data)
{
int new_count = atoi(data);
set_support(new_count);
return;
}
void
ocv_search::set_support(int new_count)
{
if (new_count < 0) {
new_count = 0;
}
support_matches = new_count;
return;
}
void
ocv_search::set_classifier(char *name)
{
int fd;
int rc;
char *cascade_bytes;
struct stat stats;
size_t nbytes;
cascade_file_name = (char *) malloc(SF_MAX_PATH);
strcpy(cascade_file_name, sfconf_get_plugin_dir());
strcat(cascade_file_name, "/");
strcat(cascade_file_name, name);
strcat(cascade_file_name, ".xml");
printf("opening %s\n", cascade_file_name);
fd = open(cascade_file_name, O_RDONLY);
assert(fd >=0);
rc = fstat(fd, &stats);
if (rc < 0) {
close(fd);
assert(0);
}
cascade_bytes = (char *) malloc(stats.st_size);
if (cascade_bytes == NULL) {
close(fd);
assert(0);
}
nbytes = read(fd, cascade_bytes, stats.st_size);
if (nbytes < stats.st_size) {
close(fd);
assert(0);
}
set_auxiliary_data((void *) cascade_bytes);
set_auxiliary_data_length(nbytes);
close(fd);
}
static GtkWidget *
create_slider_entry(char *name, float min, float max, int dec, float initial,
float step, GtkObject **adjp)
{
GtkWidget *container;
GtkWidget *scale;
GtkWidget *button;
GtkWidget *label;
container = gtk_hbox_new(FALSE, 10);
label = gtk_label_new(name);
gtk_box_pack_start(GTK_BOX(container), label, FALSE, FALSE, 0);
if (max <= 1.0) {
max += 0.1;
*adjp = gtk_adjustment_new(min, min, max, step, 0.1, 0.1);
} else if (max < 50) {
max++;
*adjp = gtk_adjustment_new(min, min, max, step, 1.0, 1.0);
} else {
max+= 10;
*adjp = gtk_adjustment_new(min, min, max, step, 10.0, 10.0);
}
gtk_adjustment_set_value(GTK_ADJUSTMENT(*adjp), initial);
scale = gtk_hscale_new(GTK_ADJUSTMENT(*adjp));
gtk_widget_set_size_request (GTK_WIDGET(scale), 200, -1);
gtk_range_set_update_policy (GTK_RANGE(scale), GTK_UPDATE_CONTINUOUS);
gtk_scale_set_draw_value (GTK_SCALE(scale), FALSE);
gtk_box_pack_start (GTK_BOX(container), scale, TRUE, TRUE, 0);
gtk_widget_set_size_request(scale, 120, 0);
button = gtk_spin_button_new(GTK_ADJUSTMENT(*adjp), step, dec);
gtk_box_pack_start(GTK_BOX(container), button, FALSE, FALSE, 0);
gtk_widget_show(container);
gtk_widget_show(label);
gtk_widget_show(scale);
gtk_widget_show(button);
return(container);
}
static void
cb_close_edit_window(GtkWidget* item, gpointer data)
{
ocv_search * search;
search = (ocv_search *)data;
search->close_edit_win();
}
void
ocv_search::close_edit_win()
{
/* save any changes from the edit windows */
save_edits();
/* call the parent class to give them change to cleanup */
window_search::close_edit_win();
edit_window = NULL;
}
static void
edit_search_done_cb(GtkButton *item, gpointer data)
{
GtkWidget * widget = (GtkWidget *)data;
gtk_widget_destroy(widget);
}
void
ocv_search::edit_search()
{
GtkWidget * widget;
GtkWidget * box;
GtkWidget * frame;
GtkWidget * hbox;
GtkWidget * container;
char name[MAX_DISPLAY_NAME];
/* see if it already exists */
if (edit_window != NULL) {
/* raise to top ??? */
gdk_window_raise(GTK_WIDGET(edit_window)->window);
return;
}
edit_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
snprintf(name, MAX_DISPLAY_NAME - 1, "Edit %s", get_name());
name[MAX_DISPLAY_NAME -1] = '\0';
gtk_window_set_title(GTK_WINDOW(edit_window), name);
//gtk_window_set_default_size(GTK_WINDOW(edit_window), 750, 350);
g_signal_connect(G_OBJECT(edit_window), "destroy",
G_CALLBACK(cb_close_edit_window), this);
box = gtk_vbox_new(FALSE, 10);
hbox = gtk_hbox_new(FALSE, 10);
gtk_box_pack_start(GTK_BOX(box), hbox, FALSE, TRUE, 0);
widget = gtk_button_new_with_label("Close");
g_signal_connect(G_OBJECT(widget), "clicked",
G_CALLBACK(edit_search_done_cb), edit_window);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_DEFAULT);
gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
/*
* Get the controls from the img_search.
*/
widget = img_search_display();
gtk_box_pack_start(GTK_BOX(box), widget, FALSE, TRUE, 0);
/*
* Create the texture parameters.
*/
frame = gtk_frame_new("OpenCV Search");
container = gtk_vbox_new(FALSE, 10);
gtk_container_add(GTK_CONTAINER(frame), container);
widget = create_slider_entry("Number of Objects", 0.0, 20.0, 0,
count, 1.0, &count_widget);
gtk_box_pack_start(GTK_BOX(container), widget, FALSE, TRUE, 0);
widget = create_slider_entry("Num Supporting", 0.0, 20.0, 0,
support_matches, 1.0, &support_widget);
gtk_box_pack_start(GTK_BOX(container), widget, FALSE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(box), frame, FALSE, TRUE, 0);
gtk_widget_show(container);
/*
* Get the controls from the window search class.
*/
widget = get_window_cntrl();
gtk_box_pack_start(GTK_BOX(box), widget, FALSE, TRUE, 0);
gtk_container_add(GTK_CONTAINER(edit_window), box);
//gtk_window_set_default_size(GTK_WINDOW(edit_window), 400, 500);
gtk_widget_show_all(edit_window);
}
/*
* This method reads the values from the current edit
* window if there is an active one.
*/
void
ocv_search::save_edits()
{
int val;
/* no active edit window, so return */
if (edit_window == NULL) {
return;
}
val = (int)gtk_adjustment_get_value(GTK_ADJUSTMENT(count_widget));
set_count(val);
val = (int)gtk_adjustment_get_value(GTK_ADJUSTMENT(support_widget));
/* XXX use accessor method ?? */
support_matches = val;
/* call the parent class */
window_search::save_edits();
}
/*
* This write the relevant section of the filter specification file
* for this search.
*/
void
ocv_search::write_fspec(FILE *ostream)
{
img_search * rgb;
img_factory * ifac;
/*
* Write the remainder of the header.
*/
fprintf(ostream, "THRESHOLD %d \n", count);
fprintf(ostream, "ARG %s # name \n", get_name());
/*
* Next we write call the parent to write out the releated args,
* not that since the args are passed as a vector of strings
* we need keep the order the args are written constant or silly
* things will happen.
*/
window_search::write_fspec(ostream);
fprintf(ostream, "ARG %d # support \n", support_matches);
/* XXX can we use the integrate somehow in opencv ?? */
fprintf(ostream, "REQUIRES RGB # dependancies \n");
fprintf(ostream, "MERIT 10 # some relative cost \n");
fprintf(ostream, "\n");
ifac = find_support_factory("rgb_image");
assert(ifac != NULL);
rgb = ifac->create("RGB image");
(this->get_parent())->add_dep(rgb);
}
void
ocv_search::region_match(RGBImage *img, bbox_list_t *blist)
{
opencv_fdetect_t fconfig;
int pass;
save_edits();
fconfig.name = strdup(get_name());
assert(fconfig.name != NULL);
fconfig.scale_mult = get_scale();
fconfig.xsize = get_testx();
fconfig.ysize = get_testy();
fconfig.stride = get_stride();
fconfig.support = support_matches;
fconfig.haar_cascade = cvLoadHaarClassifierCascade(
cascade_file_name, cvSize(fconfig.xsize, fconfig.ysize));
pass = opencv_face_scan(img, blist, &fconfig);
cvReleaseHaarClassifierCascade(&fconfig.haar_cascade);
free(fconfig.name);
return;
}
int
ocv_search::handle_config(int nconf, char **data)
{
int err;
if (strcmp(NUMFACE_ID, data[0]) == 0) {
assert(nconf > 1);
set_count(data[1]);
err = 0;
} else if (strcmp(SUPPORT_ID, data[0]) == 0) {
assert(nconf > 1);
set_support(data[1]);
err = 0;
} else {
err = window_search::handle_config(nconf, data);
}
return(err);
}
<|endoftext|> |
<commit_before>#ifndef __CALCULATE_WRAPPER_HPP__
#define __CALCULATE_WRAPPER_HPP__
#include <memory>
#include <type_traits>
#include <tuple>
#include <vector>
#include <utility>
#include "exception.hpp"
namespace calculate {
namespace detail {
template<typename Function, typename... Args>
struct NoExcept {
static constexpr bool value =
noexcept(std::declval<Function>()(std::declval<Args>()...));
};
template<typename Type, typename = void>
struct Traits : Traits<decltype(&Type::operator())> {};
template<typename Result, typename... Args>
struct Traits<std::function<Result(Args...)>, void> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...),
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const,
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Function>
using Result = typename Traits<Function>::result;
template<typename Function>
using Arguments = typename Traits<Function>::arguments;
template<typename Function>
struct Argc {
static constexpr std::size_t value =
std::tuple_size<typename Traits<Function>::arguments>::value;
};
template<typename Function>
struct IsConst {
static constexpr bool value = Traits<Function>::constant;
};
template<typename Type, typename Target>
struct NotSame {
static constexpr bool value =
!std::is_same<std::decay_t<Type>, Target>::value &&
!std::is_base_of<Target, std::decay_t<Type>>::value;
};
template<typename Type, std::size_t>
using ExtractType = Type;
template<typename, std::size_t n, typename = std::make_index_sequence<n>>
struct Repeat {};
template<typename Type, std::size_t n, std::size_t... indices>
struct Repeat<Type, n, std::index_sequence<indices...>> {
using type = std::tuple<ExtractType<Type, indices>...>;
};
template<typename Type, std::size_t n>
using Repeated = typename Repeat<Type, n>::type;
}
template<typename Type, typename Source>
struct WrapperConcept {
virtual std::shared_ptr<WrapperConcept> copy() const noexcept = 0;
virtual std::size_t argc() const noexcept = 0;
virtual bool is_const() const noexcept = 0;
virtual Type evaluate(const std::vector<Source>&) const = 0;
virtual Type evaluate(const std::vector<Source>&) = 0;
virtual ~WrapperConcept() {}
};
template<typename Type, typename Source = Type>
class Wrapper {
friend struct std::hash<Wrapper>;
using WrapperConcept = WrapperConcept<Type, Source>;
template<typename Callable>
struct Inspect {
static constexpr bool not_me =
detail::NotSame<Callable, Wrapper>::value;
static constexpr bool is_model =
std::is_base_of<WrapperConcept, Callable>::value;
};
template<typename Callable, typename Adapter, std::size_t n, bool constant>
class WrapperModel final : public WrapperConcept {
Callable _callable;
Adapter _adapter;
template<std::size_t... indices>
Type _evaluate(
std::integral_constant<bool, true>::type,
const std::vector<Source>& args
) const {
return const_cast<WrapperModel*>(this)
->_evaluate(args, std::make_index_sequence<n>{});
}
template<std::size_t... indices>
Type _evaluate(
std::integral_constant<bool, false>::type,
const std::vector<Source>&
) const { throw AccessViolation{}; }
template<std::size_t... indices>
Type _evaluate(
const std::vector<Source>& args,
std::index_sequence<indices...>
) {
if (args.size() != n)
throw ArgumentsMismatch{n, args.size()};
return _callable(_adapter(args[indices])...);
}
public:
WrapperModel(Callable callable, Adapter adapter) :
_callable{callable},
_adapter{adapter}
{}
std::shared_ptr<WrapperConcept> copy() const noexcept override {
return std::make_shared<WrapperModel>(*this);
}
std::size_t argc() const noexcept override { return n; }
bool is_const() const noexcept override { return constant; }
Type evaluate(const std::vector<Source>& args) const override {
return _evaluate(std::integral_constant<bool, constant>{}, args);
}
Type evaluate(const std::vector<Source>& args) override {
return _evaluate(args, std::make_index_sequence<n>{});
}
};
template<typename Callable, typename Adapter>
using ModelType = WrapperModel<
Callable,
Adapter,
detail::Argc<Callable>::value,
detail::IsConst<Callable>::value
>;
std::shared_ptr<WrapperConcept> _callable;
Wrapper(std::shared_ptr<WrapperConcept>&& callable) :
_callable{std::move(callable)}
{}
public:
template<typename Callable, typename Adapter>
Wrapper(Callable&& callable, Adapter&& adapter) :
_callable{
std::make_shared<ModelType<Callable, Adapter>>(
std::forward<Callable>(callable),
std::forward<Adapter>(adapter)
)
}
{
static_assert(
std::is_copy_constructible<Callable>::value,
"Non copy-constructible callable"
);
static_assert(
std::is_copy_constructible<Adapter>::value,
"Non copy-constructible adapter"
);
static_assert(
std::is_same<
detail::Arguments<Callable>,
detail::Repeated<Type, detail::Argc<Callable>::value>
>::value,
"Wrong arguments types"
);
static_assert(
std::is_same<detail::Result<Callable>, Type>::value,
"Wrong return type"
);
static_assert(
std::is_same<
detail::Arguments<Adapter>,
detail::Repeated<Source, 1>
>::value,
"Wrong adapter arguments types"
);
static_assert(
std::is_same<detail::Result<Adapter>, Type>::value,
"Wrong adapter return type"
);
static_assert(
detail::IsConst<Adapter>::value,
"Non constant adapter function"
);
}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::not_me>* = nullptr,
std::enable_if_t<!Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable=[]() { return Type(); }) :
Wrapper{
std::forward<Callable>(callable),
[](const Source& x) { return Type{x}; }
}
{}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable) :
_callable{
std::make_shared<Callable>(
std::forward<Callable>(callable)
)
}
{}
Type operator()(const std::vector<Source>& args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->evaluate(args);
}
Type operator()(const std::vector<Source>& args) {
return _callable->evaluate(args);
}
template<typename... Args>
Type operator()(Args&&... args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->evaluate(std::vector<Source>{std::forward<Args>(args)...});
}
template<typename... Args>
Type operator()(Args&&... args) {
return _callable
->evaluate(std::vector<Source>{std::forward<Args>(args)...});
}
bool operator==(const Wrapper& other) const noexcept {
return _callable == other._callable;
}
Wrapper copy() const noexcept { return Wrapper{_callable->copy()}; }
std::size_t argc() const noexcept { return _callable->argc(); }
bool is_const() const noexcept { return _callable->is_const(); }
};
}
namespace std {
template<typename Type, typename Source>
struct hash<calculate::Wrapper<Type, Source>> {
size_t operator()(const calculate::Wrapper<Type, Source>& wrapper) const {
return hash<std::shared_ptr<calculate::WrapperConcept<Type, Source>>>{}(
wrapper._callable
);
}
};
}
#endif
<commit_msg>Bring 'hotfix/wrapper' from develop into 'feature/symbols'<commit_after>#ifndef __CALCULATE_WRAPPER_HPP__
#define __CALCULATE_WRAPPER_HPP__
#include <memory>
#include <type_traits>
#include <tuple>
#include <vector>
#include <utility>
#include "exception.hpp"
namespace calculate {
namespace detail {
template<typename Function, typename... Args>
struct NoExcept {
static constexpr bool value =
noexcept(std::declval<Function>()(std::declval<Args>()...));
};
template<typename Type, typename = void>
struct Traits : Traits<decltype(&Type::operator())> {};
template<typename Result, typename... Args>
struct Traits<std::function<Result(Args...)>, void> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(*)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...) noexcept,
std::enable_if_t<NoExcept<Result(*)(Args...) noexcept, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Result, typename... Args>
struct Traits<
Result(* const)(Args...),
std::enable_if_t<!NoExcept<Result(*)(Args...), Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...),
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = false;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const noexcept,
std::enable_if_t<NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Type, typename Result, typename... Args>
struct Traits<
Result(Type::*)(Args...) const,
std::enable_if_t<!NoExcept<Type, Args...>::value>
> {
using result = Result;
using arguments = std::tuple<std::decay_t<Args>...>;
static constexpr bool constant = true;
};
template<typename Function>
using Result = typename Traits<Function>::result;
template<typename Function>
using Arguments = typename Traits<Function>::arguments;
template<typename Function>
struct Argc {
static constexpr std::size_t value =
std::tuple_size<typename Traits<Function>::arguments>::value;
};
template<typename Function>
struct IsConst {
static constexpr bool value = Traits<Function>::constant;
};
template<typename Type, typename Target>
struct NotSame {
static constexpr bool value =
!std::is_same<std::decay_t<Type>, Target>::value &&
!std::is_base_of<Target, std::decay_t<Type>>::value;
};
template<typename Type, std::size_t>
using ExtractType = Type;
template<typename, std::size_t n, typename = std::make_index_sequence<n>>
struct Repeat {};
template<typename Type, std::size_t n, std::size_t... indices>
struct Repeat<Type, n, std::index_sequence<indices...>> {
using type = std::tuple<ExtractType<Type, indices>...>;
};
template<typename Type, std::size_t n>
using Repeated = typename Repeat<Type, n>::type;
}
template<typename Type, typename Source>
struct WrapperConcept {
virtual std::shared_ptr<WrapperConcept> copy() const noexcept = 0;
virtual std::size_t argc() const noexcept = 0;
virtual bool is_const() const noexcept = 0;
virtual Type evaluate(const std::vector<Source>&) const = 0;
virtual Type evaluate(const std::vector<Source>&) = 0;
virtual ~WrapperConcept() {}
};
template<typename Type, typename Source = Type>
class Wrapper {
friend struct std::hash<Wrapper>;
using WrapperConcept = calculate::WrapperConcept<Type, Source>;
template<typename Callable>
struct Inspect {
static constexpr bool not_me =
detail::NotSame<Callable, Wrapper>::value;
static constexpr bool is_model =
std::is_base_of<WrapperConcept, Callable>::value;
};
template<typename Callable, typename Adapter, std::size_t n, bool constant>
class WrapperModel final : public WrapperConcept {
Callable _callable;
Adapter _adapter;
template<std::size_t... indices>
Type _evaluate(
std::integral_constant<bool, true>::type,
const std::vector<Source>& args
) const {
return const_cast<WrapperModel*>(this)
->_evaluate(args, std::make_index_sequence<n>{});
}
template<std::size_t... indices>
Type _evaluate(
std::integral_constant<bool, false>::type,
const std::vector<Source>&
) const { throw AccessViolation{}; }
template<std::size_t... indices>
Type _evaluate(
const std::vector<Source>& args,
std::index_sequence<indices...>
) {
if (args.size() != n)
throw ArgumentsMismatch{n, args.size()};
return _callable(_adapter(args[indices])...);
}
public:
WrapperModel(Callable callable, Adapter adapter) :
_callable{callable},
_adapter{adapter}
{}
std::shared_ptr<WrapperConcept> copy() const noexcept override {
return std::make_shared<WrapperModel>(*this);
}
std::size_t argc() const noexcept override { return n; }
bool is_const() const noexcept override { return constant; }
Type evaluate(const std::vector<Source>& args) const override {
return _evaluate(std::integral_constant<bool, constant>{}, args);
}
Type evaluate(const std::vector<Source>& args) override {
return _evaluate(args, std::make_index_sequence<n>{});
}
};
template<typename Callable, typename Adapter>
using ModelType = WrapperModel<
Callable,
Adapter,
detail::Argc<Callable>::value,
detail::IsConst<Callable>::value
>;
std::shared_ptr<WrapperConcept> _callable;
Wrapper(std::shared_ptr<WrapperConcept>&& callable) :
_callable{std::move(callable)}
{}
public:
template<typename Callable, typename Adapter>
Wrapper(Callable&& callable, Adapter&& adapter) :
_callable{
std::make_shared<ModelType<Callable, Adapter>>(
std::forward<Callable>(callable),
std::forward<Adapter>(adapter)
)
}
{
static_assert(
std::is_copy_constructible<Callable>::value,
"Non copy-constructible callable"
);
static_assert(
std::is_copy_constructible<Adapter>::value,
"Non copy-constructible adapter"
);
static_assert(
std::is_same<
detail::Arguments<Callable>,
detail::Repeated<Type, detail::Argc<Callable>::value>
>::value,
"Wrong arguments types"
);
static_assert(
std::is_same<detail::Result<Callable>, Type>::value,
"Wrong return type"
);
static_assert(
std::is_same<
detail::Arguments<Adapter>,
detail::Repeated<Source, 1>
>::value,
"Wrong adapter arguments types"
);
static_assert(
std::is_same<detail::Result<Adapter>, Type>::value,
"Wrong adapter return type"
);
static_assert(
detail::IsConst<Adapter>::value,
"Non constant adapter function"
);
}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::not_me>* = nullptr,
std::enable_if_t<!Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable=[]() { return Type(); }) :
Wrapper{
std::forward<Callable>(callable),
[](const Source& x) { return Type{x}; }
}
{}
template<
typename Callable,
std::enable_if_t<Inspect<Callable>::is_model>* = nullptr
>
Wrapper(Callable&& callable) :
_callable{
std::make_shared<Callable>(
std::forward<Callable>(callable)
)
}
{}
Type operator()(const std::vector<Source>& args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->evaluate(args);
}
Type operator()(const std::vector<Source>& args) {
return _callable->evaluate(args);
}
template<typename... Args>
Type operator()(Args&&... args) const {
return const_cast<const WrapperConcept*>(_callable.get())
->evaluate(std::vector<Source>{std::forward<Args>(args)...});
}
template<typename... Args>
Type operator()(Args&&... args) {
return _callable
->evaluate(std::vector<Source>{std::forward<Args>(args)...});
}
bool operator==(const Wrapper& other) const noexcept {
return _callable == other._callable;
}
Wrapper copy() const noexcept { return Wrapper{_callable->copy()}; }
std::size_t argc() const noexcept { return _callable->argc(); }
bool is_const() const noexcept { return _callable->is_const(); }
};
}
namespace std {
template<typename Type, typename Source>
struct hash<calculate::Wrapper<Type, Source>> {
size_t operator()(const calculate::Wrapper<Type, Source>& wrapper) const {
return hash<std::shared_ptr<calculate::WrapperConcept<Type, Source>>>{}(
wrapper._callable
);
}
};
}
#endif
<|endoftext|> |
<commit_before>/**
* @file keyed_vector.hpp
*
* A keyed vector is a random-access sequential container, whose
* elements can be referred to by a key (*e.g.* name).
*/
#ifndef CLUE_KEYED_VECTOR__
#define CLUE_KEYED_VECTOR__
#include <clue/container_common.hpp>
#include <vector>
#include <unordered_map>
namespace clue {
template<class T,
class Key,
class Hash=std::hash<Key>,
class Allocator=std::allocator<T>
>
class keyed_vector {
private:
using vector_type = std::vector<T, Allocator>;
using map_type = std::unordered_map<
Key,
size_t,
Hash,
std::equal_to<Key>,
typename Allocator::template rebind<std::pair<const Key, size_t>>::other>;
public:
using value_type = T;
using key_type = Key;
using size_type = size_t;
using difference_type = ptrdiff_t;
using hasher = Hash;
using allocator_type = Allocator;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer = typename std::allocator_traits<Allocator>::const_pointer;
using iterator = typename vector_type::iterator;
using const_iterator = typename vector_type::const_iterator;
using reverse_iterator = typename vector_type::reverse_iterator;
using const_reverse_iterator = typename vector_type::const_reverse_iterator;
private:
vector_type vec_;
map_type imap_;
public:
keyed_vector() = default;
keyed_vector(const keyed_vector& other)
: vec_(other.vec_)
, imap_(other.imap_) {}
keyed_vector(keyed_vector&& other)
: vec_(std::move(other.vec_))
, imap_(std::move(other.imap_)) {}
template<class InputIter>
keyed_vector(InputIter first, InputIter last) {
extend(first, last);
}
keyed_vector(std::initializer_list<std::pair<Key, T>> ilist) {
extend(ilist);
}
keyed_vector& operator=(const keyed_vector& other) {
if (this != &other) {
vec_ = other.vec_;
imap_ = other.imap_;
}
return *this;
}
keyed_vector& operator=(keyed_vector&& other) {
if (this != &other) {
vec_ = std::move(other.vec_);
imap_ = std::move(other.imap_);
}
return *this;
}
void swap(keyed_vector& other) {
vec_.swap(other.vec_);
imap_.swap(other.imap_);
}
public:
bool empty() const noexcept {
return vec_.empty();
}
size_type size() const noexcept {
return vec_.size();
}
size_type max_size() const noexcept {
return vec_.max_size();
}
size_type capacity() const noexcept {
return vec_.capacity();
}
iterator begin() { return vec_.begin(); }
iterator end() { return vec_.end(); }
const_iterator begin() const { return vec_.begin(); }
const_iterator end() const { return vec_.end(); }
const_iterator cbegin() const { return vec_.cbegin(); }
const_iterator cend() const { return vec_.cend(); }
reverse_iterator rbegin() { return vec_.rbegin(); }
reverse_iterator rend() { return vec_.rend(); }
const_reverse_iterator rbegin() const { return vec_.rbegin(); }
const_reverse_iterator rend() const { return vec_.rend(); }
const_reverse_iterator crbegin() const { return vec_.crbegin(); }
const_reverse_iterator crend() const { return vec_.crend(); }
bool operator==(const keyed_vector& other) const {
return vec_ == other.vec_;
}
bool operator!=(const keyed_vector& other) const {
return !(operator==(other));
}
public:
const T* data() const noexcept { return vec_.data(); }
T* data() noexcept { return vec_.data(); }
const T& front() const { return vec_.front(); }
T& front() { return vec_.front(); }
const T& back() const { return vec_.back(); }
T& back() { return vec_.back(); }
const T& at(size_type i) const { return vec_.at(i); }
T& at(size_type i) { return vec_.at(i); }
const T& operator[](size_type i) const { return vec_[i]; }
T& operator[](size_type i) { return vec_[i]; }
const T& by(const key_type& k) const { return vec_[imap_.at(k)]; }
T& by(const key_type& k) { return vec_[imap_.at(k)]; }
const_iterator find(const key_type& k) const {
auto it = imap_.find(k);
return it == imap_.end() ? vec_.end() : vec_.begin() + it->second;
}
iterator find(const key_type& k) {
auto it = imap_.find(k);
return it == imap_.end() ? vec_.end() : vec_.begin() + it->second;
}
public:
void clear() {
vec_.clear();
imap_.clear();
}
void reserve(size_t c) {
vec_.reserve(c);
imap_.reserve(c);
}
void push_back(const key_type& k, const value_type& v) {
check_dupkey(k);
vec_.push_back(v);
imap_.emplace(k, vec_.size() - 1);
}
void push_back(const key_type& k, value_type&& v) {
check_dupkey(k);
vec_.push_back(std::move(v));
imap_.emplace(k, vec_.size() - 1);
}
void push_back(key_type&& k, const value_type& v) {
check_dupkey(k);
vec_.push_back(v);
imap_.emplace(std::move(k), vec_.size() - 1);
}
void push_back(key_type&& k, value_type&& v) {
check_dupkey(k);
vec_.push_back(std::move(v));
imap_.emplace(std::move(k), vec_.size() - 1);
}
template<class... Args>
void emplace_back(const key_type& k, Args&&... args) {
check_dupkey(k);
vec_.emplace_back(std::forward<Args>(args)...);
imap_.emplace(k, vec_.size() - 1);
}
template<class... Args>
void emplace_back(key_type&& k, Args&&... args) {
check_dupkey(k);
vec_.emplace_back(std::forward<Args>(args)...);
imap_.emplace(std::move(k), vec_.size() - 1);
}
template<class InputIter>
void extend(InputIter first, InputIter last) {
using tag_t = typename std::iterator_traits<InputIter>::iterator_category;
try_reserve_for_range(first, last, tag_t{});
for(; first != last; ++first) {
push_back(first->first, first->second);
}
}
void extend(std::initializer_list<std::pair<Key, T>> ilist) {
reserve(size() + ilist.size());
for (const auto& e: ilist) {
push_back(e.first, e.second);
}
}
private:
void check_dupkey(const key_type& k) const {
if (imap_.find(k) != imap_.end()) {
throw std::invalid_argument(
"keyed_vector: the inserted key already existed.");
}
}
template<class InputIter, typename tag_t>
void try_reserve_for_range(InputIter, InputIter, tag_t) {}
template<class InputIter>
void try_reserve_for_range(InputIter first, InputIter last,
std::random_access_iterator_tag) {
reserve(size() + static_cast<size_t>(last - first));
}
}; // end class keyed_vector
template<class T, class Key, class Hash, class Allocator>
inline void swap(keyed_vector<T, Key, Hash, Allocator>& lhs,
keyed_vector<T, Key, Hash, Allocator>& rhs) {
lhs.swap(rhs);
}
} // end namespace clue
#endif
<commit_msg>fixed equality comparison for keyed_vector<commit_after>/**
* @file keyed_vector.hpp
*
* A keyed vector is a random-access sequential container, whose
* elements can be referred to by a key (*e.g.* name).
*/
#ifndef CLUE_KEYED_VECTOR__
#define CLUE_KEYED_VECTOR__
#include <clue/container_common.hpp>
#include <vector>
#include <unordered_map>
namespace clue {
template<class T,
class Key,
class Hash=std::hash<Key>,
class Allocator=std::allocator<T>
>
class keyed_vector {
private:
using vector_type = std::vector<T, Allocator>;
using map_type = std::unordered_map<
Key,
size_t,
Hash,
std::equal_to<Key>,
typename Allocator::template rebind<std::pair<const Key, size_t>>::other>;
public:
using value_type = T;
using key_type = Key;
using size_type = size_t;
using difference_type = ptrdiff_t;
using hasher = Hash;
using allocator_type = Allocator;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer = typename std::allocator_traits<Allocator>::const_pointer;
using iterator = typename vector_type::iterator;
using const_iterator = typename vector_type::const_iterator;
using reverse_iterator = typename vector_type::reverse_iterator;
using const_reverse_iterator = typename vector_type::const_reverse_iterator;
private:
vector_type vec_;
map_type imap_;
public:
keyed_vector() = default;
keyed_vector(const keyed_vector& other)
: vec_(other.vec_)
, imap_(other.imap_) {}
keyed_vector(keyed_vector&& other)
: vec_(std::move(other.vec_))
, imap_(std::move(other.imap_)) {}
template<class InputIter>
keyed_vector(InputIter first, InputIter last) {
extend(first, last);
}
keyed_vector(std::initializer_list<std::pair<Key, T>> ilist) {
extend(ilist);
}
keyed_vector& operator=(const keyed_vector& other) {
if (this != &other) {
vec_ = other.vec_;
imap_ = other.imap_;
}
return *this;
}
keyed_vector& operator=(keyed_vector&& other) {
if (this != &other) {
vec_ = std::move(other.vec_);
imap_ = std::move(other.imap_);
}
return *this;
}
void swap(keyed_vector& other) {
vec_.swap(other.vec_);
imap_.swap(other.imap_);
}
public:
bool empty() const noexcept {
return vec_.empty();
}
size_type size() const noexcept {
return vec_.size();
}
size_type max_size() const noexcept {
return vec_.max_size();
}
size_type capacity() const noexcept {
return vec_.capacity();
}
iterator begin() { return vec_.begin(); }
iterator end() { return vec_.end(); }
const_iterator begin() const { return vec_.begin(); }
const_iterator end() const { return vec_.end(); }
const_iterator cbegin() const { return vec_.cbegin(); }
const_iterator cend() const { return vec_.cend(); }
reverse_iterator rbegin() { return vec_.rbegin(); }
reverse_iterator rend() { return vec_.rend(); }
const_reverse_iterator rbegin() const { return vec_.rbegin(); }
const_reverse_iterator rend() const { return vec_.rend(); }
const_reverse_iterator crbegin() const { return vec_.crbegin(); }
const_reverse_iterator crend() const { return vec_.crend(); }
bool operator==(const keyed_vector& other) const {
return vec_ == other.vec_ &&
imap_ == other.imap_;
}
bool operator!=(const keyed_vector& other) const {
return !(operator==(other));
}
public:
const T* data() const noexcept { return vec_.data(); }
T* data() noexcept { return vec_.data(); }
const T& front() const { return vec_.front(); }
T& front() { return vec_.front(); }
const T& back() const { return vec_.back(); }
T& back() { return vec_.back(); }
const T& at(size_type i) const { return vec_.at(i); }
T& at(size_type i) { return vec_.at(i); }
const T& operator[](size_type i) const { return vec_[i]; }
T& operator[](size_type i) { return vec_[i]; }
const T& by(const key_type& k) const { return vec_[imap_.at(k)]; }
T& by(const key_type& k) { return vec_[imap_.at(k)]; }
const_iterator find(const key_type& k) const {
auto it = imap_.find(k);
return it == imap_.end() ? vec_.end() : vec_.begin() + it->second;
}
iterator find(const key_type& k) {
auto it = imap_.find(k);
return it == imap_.end() ? vec_.end() : vec_.begin() + it->second;
}
public:
void clear() {
vec_.clear();
imap_.clear();
}
void reserve(size_t c) {
vec_.reserve(c);
imap_.reserve(c);
}
void push_back(const key_type& k, const value_type& v) {
check_dupkey(k);
vec_.push_back(v);
imap_.emplace(k, vec_.size() - 1);
}
void push_back(const key_type& k, value_type&& v) {
check_dupkey(k);
vec_.push_back(std::move(v));
imap_.emplace(k, vec_.size() - 1);
}
void push_back(key_type&& k, const value_type& v) {
check_dupkey(k);
vec_.push_back(v);
imap_.emplace(std::move(k), vec_.size() - 1);
}
void push_back(key_type&& k, value_type&& v) {
check_dupkey(k);
vec_.push_back(std::move(v));
imap_.emplace(std::move(k), vec_.size() - 1);
}
template<class... Args>
void emplace_back(const key_type& k, Args&&... args) {
check_dupkey(k);
vec_.emplace_back(std::forward<Args>(args)...);
imap_.emplace(k, vec_.size() - 1);
}
template<class... Args>
void emplace_back(key_type&& k, Args&&... args) {
check_dupkey(k);
vec_.emplace_back(std::forward<Args>(args)...);
imap_.emplace(std::move(k), vec_.size() - 1);
}
template<class InputIter>
void extend(InputIter first, InputIter last) {
using tag_t = typename std::iterator_traits<InputIter>::iterator_category;
try_reserve_for_range(first, last, tag_t{});
for(; first != last; ++first) {
push_back(first->first, first->second);
}
}
void extend(std::initializer_list<std::pair<Key, T>> ilist) {
reserve(size() + ilist.size());
for (const auto& e: ilist) {
push_back(e.first, e.second);
}
}
private:
void check_dupkey(const key_type& k) const {
if (imap_.find(k) != imap_.end()) {
throw std::invalid_argument(
"keyed_vector: the inserted key already existed.");
}
}
template<class InputIter, typename tag_t>
void try_reserve_for_range(InputIter, InputIter, tag_t) {}
template<class InputIter>
void try_reserve_for_range(InputIter first, InputIter last,
std::random_access_iterator_tag) {
reserve(size() + static_cast<size_t>(last - first));
}
}; // end class keyed_vector
template<class T, class Key, class Hash, class Allocator>
inline void swap(keyed_vector<T, Key, Hash, Allocator>& lhs,
keyed_vector<T, Key, Hash, Allocator>& rhs) {
lhs.swap(rhs);
}
} // end namespace clue
#endif
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP
#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "array.hpp"
#include "native_function.hpp"
#include "local_root_scope.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/binding.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#include <boost/parameter/config.hpp>
namespace flusspferd {
class native_object_base;
class function;
class native_function_base;
#ifndef IN_DOXYGEN
namespace detail {
object create_native_object(object const &proto);
object create_native_enumerable_object(object const &proto);
}
#endif
/**
* @name Creating values
* @addtogroup create
*/
//@{
/**
* Create a simple object.
*
* Creates a new object with prototype @p proto. If proto is @c null,
* @c Object.prototype will be used.
*
* @param proto The object to use as prototype.
* @return The new object.
*/
object create_object(object const &proto = object());
#ifndef IN_DOXYGEN
#define FLUSSPFERD_FN_CREATE_NATIVE_OBJECT(z, n_args, d) \
template< \
typename T \
BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
> \
typename boost::enable_if< boost::mpl::not_< \
typename T::class_info::custom_enumerate >, \
T& >::type \
create_native_object( \
object proto \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \
) { \
if (proto.is_null()) \
proto = current_context().prototype<T>(); \
local_root_scope scope; \
object obj = detail::create_native_object(proto); \
return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \
} \
\
template< \
typename T \
BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
> \
typename boost::enable_if< \
typename T::class_info::custom_enumerate, \
T& >::type \
create_native_object( \
object proto \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \
) { \
if (proto.is_null()) \
proto = current_context().prototype<T>(); \
local_root_scope scope; \
object obj = detail::create_native_enumerable_object(proto); \
return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \
} \
/* */
BOOST_PP_REPEAT(
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
FLUSSPFERD_FN_CREATE_NATIVE_OBJECT,
~
)
#else
/**
* Create a new native object of type @p T.
*
* @param T The type of the object's class.
* @param proto The prototype to be used. If @p null, the class' default
* prototype will be used.
* @param ... The parameters to the constructor of @p T.
* @return The new object.
*/
template<typename T>
T &create_native_object(object const &proto, ...);
#endif
//@}
/**
* @name Creating functions
* @addtogroup create_function
*/
//@{
function create_function(
std::string const &name,
unsigned n_args,
std::vector<std::string> argnames,
flusspferd::string const &body,
std::string const &file,
unsigned line);
/**
* Create a new native function.
*
* @p ptr will be <code>delete</code>d by Flusspferd.
*
* @param ptr The native function object.
* @return The new function.
*/
function create_native_function(native_function_base *ptr);
/**
* Create a new native function as method of an object.
*
* The new method of object @p o will have the name @c ptr->name().
*
* @param o The object to add the method to.
* @param ptr The native function object.
* @return The new method.
*/
function create_native_function(object const &o, native_function_base *ptr);
#ifndef IN_DOXYGEN
#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \
template< \
typename T \
BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
> \
object create_native_functor_function( \
object const &o \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \
typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \
) { \
return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \
} \
/* */
BOOST_PP_REPEAT(
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,
~
)
#else
/**
* Create a new native function of type @p F as method of an object.
*
* @p F must inherit from #native_function_base.
*
* The new method of object @p o will have the name @c ptr->name().
*
* @param F The functor type.
* @param o The object to add the method to.
* @param ... The parameters to pass to the constructor of @p F.
* @return The new method.
*/
template<typename F>
object create_native_functor_function(object const &o, ...);
#endif
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param fn The functor to call.
* @param arity The function arity.
* @return The new function.
*/
inline function create_native_function(
object const &o,
std::string const &name,
boost::function<void (call_context &)> const &fn,
unsigned arity = 0)
{
return create_native_functor_function<native_function<void> >(
o, fn, arity, name);
}
/**
* Create a new native method of an object.
*
* @param T The function signature to use.
* @param o The object to add the method to.
* @param name The function name.
* @param fn The functor to call.
* @return The new function.
*/
template<typename T>
function create_native_function(
object const &o,
std::string const &name,
boost::function<T> const &fn)
{
return create_native_functor_function<native_function<T,false> >(o, fn, name);
}
/**
* Create a new native method of an object.
*
* The first parameter passed will be 'this'.
*
* @param T The function signature to use.
* @param o The object to add the method to.
* @param name The function name.
* @param fn The functor to call.
* @return The new function.
*/
template<typename T>
function create_native_method(
object const &o,
std::string const &name,
boost::function<T> const &fn)
{
return create_native_functor_function<native_function<T,true> >(o, fn, name);
}
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param fnptr The function to call (also determines the function signature).
* @return The new method.
*/
template<typename T>
function create_native_function(
object const &o,
std::string const &name,
T *fnptr,
typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
return create_native_function<T>(o, name, boost::function<T>(fnptr));
}
/**
* Create a new native method of an object.
*
* The first parameter passed will be 'this'.
*
* @param o The object to add the method to.
* @param name The method name.
* @param fnptr The function to call (also determines the function signature).
* @return The new method.
*/
template<typename T>
function create_native_method(
object const &o,
std::string const &name,
T *fnptr,
typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
return create_native_method<T>(o, name, boost::function<T>(fnptr));
}
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param memfnptr The member function to call.
* @return The new function.
*/
template<typename T>
function create_native_method(
object const &o,
std::string const &name,
void (T::*memfnptr)(call_context &),
unsigned arity = 0)
{
return create_native_functor_function<native_member_function<void, T> >(
o, memfnptr, arity, name);
}
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param memfnptr The member function to call (also determines the function
* signature).
* @return The new function.
*/
template<typename R, typename T>
function create_native_method(
object const &o,
std::string const &name,
R T::*memfnptr)
{
return create_native_functor_function<native_member_function<R, T> >(
o, memfnptr, name);
}
//@}
namespace param {
BOOST_PARAMETER_NAME(length)
BOOST_PARAMETER_NAME(contents)
}
namespace detail {
flusspferd::array create_length_array(std::size_t length);
template<typename Class>
struct create_traits;
template<typename T, typename C = void>
struct is_boost_range_impl {
typedef boost::mpl::false_ type;
};
template<>
struct create_traits<flusspferd::array> {
typedef flusspferd::array result_type;
typedef boost::parameter::parameters<
boost::parameter::optional<
boost::parameter::deduced<param::tag::length>,
boost::is_integral<boost::mpl::_>
>,
boost::parameter::optional<
boost::parameter::deduced<param::tag::contents>,
boost::mpl::not_<boost::is_integral<boost::mpl::_> >
>
>
parameters;
static flusspferd::array create() {
return create_length_array(0);
}
template<typename ArgPack>
static
typename boost::enable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::contents,
void
>::type,
void
>,
flusspferd::array
>::type
create(ArgPack const &arg) {
return create_length_array(arg[param::_length | 0]);
}
template<typename ArgPack>
static
typename boost::disable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::contents,
void
>::type,
void
>,
flusspferd::array
>::type
create(ArgPack const &arg) {
typedef typename boost::parameter::value_type<
ArgPack,
param::tag::contents
>::type
Range;
typedef typename boost::range_iterator<Range>::type iterator;
Range const &r = arg[param::_contents];
local_root_scope scope;
array arr = create_length_array(0);
iterator first = boost::begin(r);
iterator last = boost::end(r);
for (iterator it = first; it != last; ++it)
arr.push(*it);
return arr;
}
};
}
template<typename Class>
typename detail::create_traits<Class>::result_type
create()
{
return detail::create_traits<Class>::create();
}
#define FLUSSPFERD_CREATE(z, n, d) \
template< \
typename Class, \
BOOST_PP_ENUM_PARAMS(n, typename T) \
> \
typename detail::create_traits<Class>::result_type \
create( \
BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \
typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \
{ \
typedef detail::create_traits<Class> traits; \
return traits::create(kw(BOOST_PP_ENUM_PARAMS(n, x))); \
} \
/* */
BOOST_PP_REPEAT_FROM_TO(
1,
BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),
FLUSSPFERD_CREATE,
~)
#undef FLUSSPFERD_CREATE
}
#endif
<commit_msg>new_create: remove unused code<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP
#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "array.hpp"
#include "native_function.hpp"
#include "local_root_scope.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/binding.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#include <boost/parameter/config.hpp>
namespace flusspferd {
class native_object_base;
class function;
class native_function_base;
#ifndef IN_DOXYGEN
namespace detail {
object create_native_object(object const &proto);
object create_native_enumerable_object(object const &proto);
}
#endif
/**
* @name Creating values
* @addtogroup create
*/
//@{
/**
* Create a simple object.
*
* Creates a new object with prototype @p proto. If proto is @c null,
* @c Object.prototype will be used.
*
* @param proto The object to use as prototype.
* @return The new object.
*/
object create_object(object const &proto = object());
#ifndef IN_DOXYGEN
#define FLUSSPFERD_FN_CREATE_NATIVE_OBJECT(z, n_args, d) \
template< \
typename T \
BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
> \
typename boost::enable_if< boost::mpl::not_< \
typename T::class_info::custom_enumerate >, \
T& >::type \
create_native_object( \
object proto \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \
) { \
if (proto.is_null()) \
proto = current_context().prototype<T>(); \
local_root_scope scope; \
object obj = detail::create_native_object(proto); \
return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \
} \
\
template< \
typename T \
BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
> \
typename boost::enable_if< \
typename T::class_info::custom_enumerate, \
T& >::type \
create_native_object( \
object proto \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \
) { \
if (proto.is_null()) \
proto = current_context().prototype<T>(); \
local_root_scope scope; \
object obj = detail::create_native_enumerable_object(proto); \
return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \
} \
/* */
BOOST_PP_REPEAT(
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
FLUSSPFERD_FN_CREATE_NATIVE_OBJECT,
~
)
#else
/**
* Create a new native object of type @p T.
*
* @param T The type of the object's class.
* @param proto The prototype to be used. If @p null, the class' default
* prototype will be used.
* @param ... The parameters to the constructor of @p T.
* @return The new object.
*/
template<typename T>
T &create_native_object(object const &proto, ...);
#endif
//@}
/**
* @name Creating functions
* @addtogroup create_function
*/
//@{
function create_function(
std::string const &name,
unsigned n_args,
std::vector<std::string> argnames,
flusspferd::string const &body,
std::string const &file,
unsigned line);
/**
* Create a new native function.
*
* @p ptr will be <code>delete</code>d by Flusspferd.
*
* @param ptr The native function object.
* @return The new function.
*/
function create_native_function(native_function_base *ptr);
/**
* Create a new native function as method of an object.
*
* The new method of object @p o will have the name @c ptr->name().
*
* @param o The object to add the method to.
* @param ptr The native function object.
* @return The new method.
*/
function create_native_function(object const &o, native_function_base *ptr);
#ifndef IN_DOXYGEN
#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \
template< \
typename T \
BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
> \
object create_native_functor_function( \
object const &o \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \
typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \
) { \
return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \
} \
/* */
BOOST_PP_REPEAT(
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,
~
)
#else
/**
* Create a new native function of type @p F as method of an object.
*
* @p F must inherit from #native_function_base.
*
* The new method of object @p o will have the name @c ptr->name().
*
* @param F The functor type.
* @param o The object to add the method to.
* @param ... The parameters to pass to the constructor of @p F.
* @return The new method.
*/
template<typename F>
object create_native_functor_function(object const &o, ...);
#endif
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param fn The functor to call.
* @param arity The function arity.
* @return The new function.
*/
inline function create_native_function(
object const &o,
std::string const &name,
boost::function<void (call_context &)> const &fn,
unsigned arity = 0)
{
return create_native_functor_function<native_function<void> >(
o, fn, arity, name);
}
/**
* Create a new native method of an object.
*
* @param T The function signature to use.
* @param o The object to add the method to.
* @param name The function name.
* @param fn The functor to call.
* @return The new function.
*/
template<typename T>
function create_native_function(
object const &o,
std::string const &name,
boost::function<T> const &fn)
{
return create_native_functor_function<native_function<T,false> >(o, fn, name);
}
/**
* Create a new native method of an object.
*
* The first parameter passed will be 'this'.
*
* @param T The function signature to use.
* @param o The object to add the method to.
* @param name The function name.
* @param fn The functor to call.
* @return The new function.
*/
template<typename T>
function create_native_method(
object const &o,
std::string const &name,
boost::function<T> const &fn)
{
return create_native_functor_function<native_function<T,true> >(o, fn, name);
}
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param fnptr The function to call (also determines the function signature).
* @return The new method.
*/
template<typename T>
function create_native_function(
object const &o,
std::string const &name,
T *fnptr,
typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
return create_native_function<T>(o, name, boost::function<T>(fnptr));
}
/**
* Create a new native method of an object.
*
* The first parameter passed will be 'this'.
*
* @param o The object to add the method to.
* @param name The method name.
* @param fnptr The function to call (also determines the function signature).
* @return The new method.
*/
template<typename T>
function create_native_method(
object const &o,
std::string const &name,
T *fnptr,
typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
return create_native_method<T>(o, name, boost::function<T>(fnptr));
}
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param memfnptr The member function to call.
* @return The new function.
*/
template<typename T>
function create_native_method(
object const &o,
std::string const &name,
void (T::*memfnptr)(call_context &),
unsigned arity = 0)
{
return create_native_functor_function<native_member_function<void, T> >(
o, memfnptr, arity, name);
}
/**
* Create a new native method of an object.
*
* @param o The object to add the method to.
* @param name The method name.
* @param memfnptr The member function to call (also determines the function
* signature).
* @return The new function.
*/
template<typename R, typename T>
function create_native_method(
object const &o,
std::string const &name,
R T::*memfnptr)
{
return create_native_functor_function<native_member_function<R, T> >(
o, memfnptr, name);
}
//@}
namespace param {
BOOST_PARAMETER_NAME(length)
BOOST_PARAMETER_NAME(contents)
}
namespace detail {
flusspferd::array create_length_array(std::size_t length);
template<typename Class>
struct create_traits;
template<>
struct create_traits<flusspferd::array> {
typedef flusspferd::array result_type;
typedef boost::parameter::parameters<
boost::parameter::optional<
boost::parameter::deduced<param::tag::length>,
boost::is_integral<boost::mpl::_>
>,
boost::parameter::optional<
boost::parameter::deduced<param::tag::contents>,
boost::mpl::not_<boost::is_integral<boost::mpl::_> >
>
>
parameters;
static flusspferd::array create() {
return create_length_array(0);
}
template<typename ArgPack>
static
typename boost::enable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::contents,
void
>::type,
void
>,
flusspferd::array
>::type
create(ArgPack const &arg) {
return create_length_array(arg[param::_length | 0]);
}
template<typename ArgPack>
static
typename boost::disable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::contents,
void
>::type,
void
>,
flusspferd::array
>::type
create(ArgPack const &arg) {
typedef typename boost::parameter::value_type<
ArgPack,
param::tag::contents
>::type
Range;
typedef typename boost::range_iterator<Range>::type iterator;
Range const &r = arg[param::_contents];
local_root_scope scope;
array arr = create_length_array(0);
iterator first = boost::begin(r);
iterator last = boost::end(r);
for (iterator it = first; it != last; ++it)
arr.push(*it);
return arr;
}
};
}
template<typename Class>
typename detail::create_traits<Class>::result_type
create()
{
return detail::create_traits<Class>::create();
}
#define FLUSSPFERD_CREATE(z, n, d) \
template< \
typename Class, \
BOOST_PP_ENUM_PARAMS(n, typename T) \
> \
typename detail::create_traits<Class>::result_type \
create( \
BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \
typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \
{ \
typedef detail::create_traits<Class> traits; \
return traits::create(kw(BOOST_PP_ENUM_PARAMS(n, x))); \
} \
/* */
BOOST_PP_REPEAT_FROM_TO(
1,
BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),
FLUSSPFERD_CREATE,
~)
#undef FLUSSPFERD_CREATE
}
#endif
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type, boost::mpl::vector<std::string, int>> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
template<typename L>
class SimpleLexer : public lex::lexer<L> {
private:
public:
SimpleLexer() {
//Define keywords
for_ = "for";
while_ = "while";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
word = "[a-zA-Z]+";
integer = "[0-9]+";
litteral = "\\\"[^\\\"]*\\\"";
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
swap = "<=>";
assign = '=';
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += comma | stop;
this->self += assign | swap | addition | subtraction | multiplication | division | modulo;
this->self += for_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += integer | word | litteral;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
StringToken word, litteral;
IntegerToken integer;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma;
ConsumedToken assign, swap;
//Keywords
ConsumedToken if_, else_, for_, while_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
} //end of eddic
#endif
<commit_msg>Add const as a keyword in the lexer<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type, boost::mpl::vector<std::string, int>> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
template<typename L>
class SimpleLexer : public lex::lexer<L> {
private:
public:
SimpleLexer() {
//Define keywords
for_ = "for";
while_ = "while";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
return_ = "const";
word = "[a-zA-Z]+";
integer = "[0-9]+";
litteral = "\\\"[^\\\"]*\\\"";
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
swap = "<=>";
assign = '=';
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += comma | stop;
this->self += assign | swap | addition | subtraction | multiplication | division | modulo;
this->self += for_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += integer | word | litteral;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
StringToken word, litteral;
IntegerToken integer;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma;
ConsumedToken assign, swap;
//Keywords
ConsumedToken if_, else_, for_, while_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_;
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
} //end of eddic
#endif
<|endoftext|> |
<commit_before>#pragma once
#ifndef SIPL_MATRIX_MATRIXBASE_H
#define SIPL_MATRIX_MATRIXBASE_H
#include <array>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include "Constants.hpp"
#include "matrix/Common.hpp"
namespace sipl
{
// Statically-sized matrices
template <typename Dtype, int32_t Rows, int32_t Cols, typename Container>
class MatrixBase
{
public:
// XXX revisit to try and make const?
std::array<int32_t, 2> dims;
MatrixBase()
: dims({Rows, Cols})
, nelements_(Rows * Cols)
, nbytes_(nelements_ * int32_t(sizeof(Dtype)))
, data_(Rows * Cols)
{
}
MatrixBase(const MatrixBase& other)
: dims(other.dims)
, nelements_(other.nelements_)
, nbytes_(other.nbytes_)
, data_(other.data_)
{
}
MatrixBase(MatrixBase&& other)
: dims(std::move(other.dims))
, nelements_(other.nelements_)
, nbytes_(other.nbytes_)
, data_(std::move(other.data_))
{
}
// Iterator & element access
Dtype* begin() { return std::begin(data_); }
const Dtype* begin() const { return std::begin(data_); }
Dtype* end() { return std::end(data_); }
const Dtype* end() const { return std::end(data_); }
Dtype& front() { return data_.front(); }
const Dtype& front() const { return data_.front(); }
Dtype& back() { return data_.back(); }
const Dtype& back() const { return data_.back(); }
const Dtype& operator()(int32_t row, int32_t col) const
{
assert(row >= 0 && row < dims[0] && "out of range");
assert(col >= 0 && col < dims[1] && "out of range");
return data_[row * dims[1] + col];
}
Dtype& operator()(int32_t row, int32_t col)
{
assert(row >= 0 && row < dims[0] && "out of range");
assert(col >= 0 && col < dims[1] && "out of range");
return data_[row * dims[1] + col];
}
// Access elements by single index
const Dtype& operator[](int32_t index) const
{
assert(index >= 0 && index < nelements_ && "out of range");
return data_[index];
}
Dtype& operator[](int32_t index)
{
assert(index >= 0 && index < nelements_ && "out of range");
return data_[index];
}
// Raw accessor for data buffer
const Dtype* data(void) const
{
return reinterpret_cast<const Dtype*>(data_.data());
}
Dtype* data(void) { return reinterpret_cast<Dtype*>(data_.data()); }
// Serialization to byte array
const char* as_bytes(void) const
{
return reinterpret_cast<const char*>(data_.data());
}
char* as_bytes(void) { return reinterpret_cast<char*>(data_.data()); }
int32_t size(void) const { return nelements_; }
int32_t size_in_bytes(void) const { return nbytes_; }
template <typename Functor>
void apply(Functor f)
{
std::transform(std::begin(data_), std::end(data_), std::begin(data_),
f);
}
// Scalar math manipulation
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator/=(Scalar s)
{
apply([s](Dtype e) { return e / s; });
return *this;
}
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator*=(Scalar s)
{
apply([s](Dtype e) { return e * s; });
return *this;
}
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator+=(Scalar s)
{
apply([s](Dtype e) { return e + s; });
return *this;
}
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator-=(Scalar s)
{
apply([s](Dtype e) { return e - s; });
return *this;
}
std::string str() const
{
std::stringstream ss;
ss << "[";
for (int32_t i = 0; i < dims[0] - 1; ++i) {
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(i, j) << " ";
}
ss << (*this)(i, dims[1] - 1) << ";" << std::endl;
}
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(dims[0] - 1, j) << " ";
}
ss << (*this)(dims[0] - 1, dims[1] - 1) << "]";
return ss.str();
}
Dtype abssum() const
{
return std::accumulate(
std::begin(data_), std::end(data_), Dtype(0),
[](Dtype sum, Dtype e) { return sum + std::abs(e); });
}
// Conversion operator
template <typename T>
operator MatrixBase<T, Rows, Cols, Container>() const
{
MatrixBase<T, Rows, Cols, Container> new_m(dims);
new_m.apply([](auto e) { return T(e); });
return new_m;
}
friend std::ostream& operator<<(std::ostream& s, const MatrixBase& m)
{
return s << m.str();
}
// Min/max operations
Dtype max(void) const
{
return *std::max_element(std::begin(data_), std::end(data_));
}
Dtype min(void) const
{
return *std::min_element(std::begin(data_), std::end(data_));
}
int32_t argmax() const
{
auto m = std::max_element(std::begin(data_), std::end(data_));
return m - std::begin(data_);
}
int32_t argmin() const
{
auto m = std::min_element(std::begin(data_), std::end(data_));
return m - std::begin(data_);
}
protected:
int32_t nelements_;
int32_t nbytes_;
Container data_;
// Helper functions to clamp a row/col index to in-bounds
int32_t clamp_row_index(int32_t index) const
{
if (index < 0) {
return 0;
} else if (index >= dims[0]) {
return dims[0] - 1;
} else {
return index;
}
}
int32_t clamp_col_index(int32_t index) const
{
if (index < 0) {
return 0;
} else if (index >= dims[1]) {
return dims[1] - 1;
} else {
return index;
}
}
};
}
#endif
<commit_msg>Add value_type so we can easily get at the type of a matrix<commit_after>#pragma once
#ifndef SIPL_MATRIX_MATRIXBASE_H
#define SIPL_MATRIX_MATRIXBASE_H
#include <array>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include "Constants.hpp"
#include "matrix/Common.hpp"
namespace sipl
{
// Statically-sized matrices
template <typename Dtype, int32_t Rows, int32_t Cols, typename Container>
class MatrixBase
{
public:
using value_type = Dtype;
// XXX revisit to try and make const?
std::array<int32_t, 2> dims;
MatrixBase()
: dims({Rows, Cols})
, nelements_(Rows * Cols)
, nbytes_(nelements_ * int32_t(sizeof(Dtype)))
, data_(Rows * Cols)
{
}
MatrixBase(const MatrixBase& other)
: dims(other.dims)
, nelements_(other.nelements_)
, nbytes_(other.nbytes_)
, data_(other.data_)
{
}
MatrixBase(MatrixBase&& other)
: dims(std::move(other.dims))
, nelements_(other.nelements_)
, nbytes_(other.nbytes_)
, data_(std::move(other.data_))
{
}
// Iterator & element access
Dtype* begin() { return std::begin(data_); }
const Dtype* begin() const { return std::begin(data_); }
Dtype* end() { return std::end(data_); }
const Dtype* end() const { return std::end(data_); }
Dtype& front() { return data_.front(); }
const Dtype& front() const { return data_.front(); }
Dtype& back() { return data_.back(); }
const Dtype& back() const { return data_.back(); }
const Dtype& operator()(int32_t row, int32_t col) const
{
assert(row >= 0 && row < dims[0] && "out of range");
assert(col >= 0 && col < dims[1] && "out of range");
return data_[row * dims[1] + col];
}
Dtype& operator()(int32_t row, int32_t col)
{
assert(row >= 0 && row < dims[0] && "out of range");
assert(col >= 0 && col < dims[1] && "out of range");
return data_[row * dims[1] + col];
}
// Access elements by single index
const Dtype& operator[](int32_t index) const
{
assert(index >= 0 && index < nelements_ && "out of range");
return data_[index];
}
Dtype& operator[](int32_t index)
{
assert(index >= 0 && index < nelements_ && "out of range");
return data_[index];
}
// Raw accessor for data buffer
const Dtype* data(void) const
{
return reinterpret_cast<const Dtype*>(data_.data());
}
Dtype* data(void) { return reinterpret_cast<Dtype*>(data_.data()); }
// Serialization to byte array
const char* as_bytes(void) const
{
return reinterpret_cast<const char*>(data_.data());
}
char* as_bytes(void) { return reinterpret_cast<char*>(data_.data()); }
int32_t size(void) const { return nelements_; }
int32_t size_in_bytes(void) const { return nbytes_; }
template <typename Functor>
void apply(Functor f)
{
std::transform(std::begin(data_), std::end(data_), std::begin(data_),
f);
}
// Scalar math manipulation
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator/=(Scalar s)
{
apply([s](Dtype e) { return e / s; });
return *this;
}
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator*=(Scalar s)
{
apply([s](Dtype e) { return e * s; });
return *this;
}
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator+=(Scalar s)
{
apply([s](Dtype e) { return e + s; });
return *this;
}
template <typename Scalar>
MatrixBase<Dtype, Rows, Cols, Container>& operator-=(Scalar s)
{
apply([s](Dtype e) { return e - s; });
return *this;
}
std::string str() const
{
std::stringstream ss;
ss << "[";
for (int32_t i = 0; i < dims[0] - 1; ++i) {
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(i, j) << " ";
}
ss << (*this)(i, dims[1] - 1) << ";" << std::endl;
}
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(dims[0] - 1, j) << " ";
}
ss << (*this)(dims[0] - 1, dims[1] - 1) << "]";
return ss.str();
}
Dtype abssum() const
{
return std::accumulate(
std::begin(data_), std::end(data_), Dtype(0),
[](Dtype sum, Dtype e) { return sum + std::abs(e); });
}
// Conversion operator
template <typename T>
operator MatrixBase<T, Rows, Cols, Container>() const
{
MatrixBase<T, Rows, Cols, Container> new_m(dims);
new_m.apply([](auto e) { return T(e); });
return new_m;
}
friend std::ostream& operator<<(std::ostream& s, const MatrixBase& m)
{
return s << m.str();
}
// Min/max operations
Dtype max(void) const
{
return *std::max_element(std::begin(data_), std::end(data_));
}
Dtype min(void) const
{
return *std::min_element(std::begin(data_), std::end(data_));
}
int32_t argmax() const
{
auto m = std::max_element(std::begin(data_), std::end(data_));
return m - std::begin(data_);
}
int32_t argmin() const
{
auto m = std::min_element(std::begin(data_), std::end(data_));
return m - std::begin(data_);
}
protected:
int32_t nelements_;
int32_t nbytes_;
Container data_;
// Helper functions to clamp a row/col index to in-bounds
int32_t clamp_row_index(int32_t index) const
{
if (index < 0) {
return 0;
} else if (index >= dims[0]) {
return dims[0] - 1;
} else {
return index;
}
}
int32_t clamp_col_index(int32_t index) const
{
if (index < 0) {
return 0;
} else if (index >= dims[1]) {
return dims[1] - 1;
} else {
return index;
}
}
};
}
#endif
<|endoftext|> |
<commit_before>#include <gtest/gtest.h> // gtest must be included first...!
#include <string>
#include <qi/serialization/serializable.hpp>
#include <qi/serialization/serializer.hpp>
using namespace qi::serialization;
struct Inner : Serializable {
Inner() : text("hello"), number(42) {}
std::string text;
int number;
void accept(Serializer& v) {
v.visit(text);
v.visit(number);
}
};
struct Outer : Serializable {
Outer() : floatNumber(42.2f) {}
float floatNumber;
Inner inner;
void accept(Serializer& v) {
v.visit(floatNumber);
v.visit(inner);
v.visit(inner);
}
};
struct Hard : Serializable {
std::vector<std::map<std::string, int> > content;
void accept(Serializer& v) {
v.visit(content);
}
};
struct Harder : Serializable {
std::vector<std::map<std::string, Inner> > content;
void accept(Serializer& v) {
v.visit(content);
}
};
TEST(testSerializable, simpleStruct) {
Inner t;
t.number = 1;
t.text = "hello world";
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Inner t2;
t2.accept(deserializer);
}
TEST(testSerializable, multiLayer) {
Outer t;
t.floatNumber = 1.111f;
t.inner.number = 1;
t.inner.text = "shtuff";
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Outer t2;
t2.accept(deserializer);
}
TEST(testSerializable, hard) {
Hard t;
std::vector<std::map<std::string, int> > shtuff;
std::map<std::string, int> map;
map.insert(std::make_pair("oink", 1));
map.insert(std::make_pair("oink2", 2));
shtuff.push_back(map);
t.content = shtuff;
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Hard t2;
t2.accept(deserializer);
}
TEST(testSerializable, harder) {
Harder t;
std::vector<std::map<std::string, Inner> > shtuff;
std::map<std::string, Inner> map;
Inner inner1;
inner1.number = 5;
Inner inner2;
inner2.number = 6;
map.insert(std::make_pair("oink", inner1));
map.insert(std::make_pair("oink2", inner2));
shtuff.push_back(map);
t.content = shtuff;
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Harder t2;
t2.accept(deserializer);
}<commit_msg>Extended serializer tests<commit_after>#include <gtest/gtest.h> // gtest must be included first...!
#include <string>
#include <qi/serialization/serializable.hpp>
#include <qi/serialization/serializer.hpp>
using namespace qi::serialization;
struct Inner : Serializable {
Inner() : text("hello"), number(42) {}
std::string text;
int number;
void accept(Serializer& v) {
v.visit(text);
v.visit(number);
}
};
struct Outer : Serializable {
Outer() : floatNumber(42.2f) {}
float floatNumber;
Inner inner;
void accept(Serializer& v) {
v.visit(floatNumber);
v.visit(inner);
v.visit(inner);
}
};
struct Hard : Serializable {
std::vector<std::map<std::string, int> > content;
void accept(Serializer& v) {
v.visit(content);
}
};
struct Harder : Serializable {
std::vector<std::map<std::string, Inner> > content;
void accept(Serializer& v) {
v.visit(content);
}
};
TEST(testSerializable, simpleStruct) {
Inner t;
t.number = 1;
t.text = "hello world";
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Inner t2;
t2.accept(deserializer);
}
TEST(testSerializable, multiLayer) {
Outer t;
t.floatNumber = 1.111f;
t.inner.number = 1;
t.inner.text = "shtuff";
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Outer t2;
t2.accept(deserializer);
}
TEST(testSerializable, hard) {
Hard t;
std::vector<std::map<std::string, int> > shtuff;
std::map<std::string, int> map;
map.insert(std::make_pair("oink", 1));
map.insert(std::make_pair("oink2", 2));
shtuff.push_back(map);
t.content = shtuff;
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Hard t2;
t2.accept(deserializer);
}
TEST(testSerializable, harder) {
Harder t;
std::vector<std::map<std::string, Inner> > shtuff;
std::map<std::string, Inner> map;
Inner inner1;
inner1.number = 5;
Inner inner2;
inner2.number = 6;
map.insert(std::make_pair("oink", inner1));
map.insert(std::make_pair("oink2", inner2));
shtuff.push_back(map);
t.content = shtuff;
qi::serialization::Message m;
Serializer serializer(ACTION_SERIALIZE, m);
t.accept(serializer);
Serializer deserializer(ACTION_DESERIALIZE, m);
Harder t2;
t2.accept(deserializer);
}
struct Point2D : Serializable {
int x;
int y;
void accept(Serializer& s) {
s.visit(x, y);
}
};
struct TimeStamp : Serializable {
int seconds;
int nanoseconds;
void accept(Serializer& s) {
s.visit(seconds);
s.visit(nanoseconds);
}
};
struct StampedPoint2D : Serializable {
Point2D point;
TimeStamp time;
void accept(Serializer& s) {
s.visit(point, time);
}
};
TEST(testSerializable, points) {
Point2D point;
point.x = 1;
point.y = 2;
TimeStamp timestamp;
timestamp.seconds = 10001;
timestamp.nanoseconds = 999;
StampedPoint2D stampedPoint;
stampedPoint.point = point;
stampedPoint.time = timestamp;
// ---- code that will never be seen, and needs a little clearup
qi::serialization::Message pointMessage;
Serializer s1(ACTION_SERIALIZE, pointMessage);
point.accept(s1);
qi::serialization::Message stampedPointMessage;
Serializer s2(ACTION_SERIALIZE, stampedPointMessage);
stampedPoint.accept(s2);
qi::serialization::Message stampedPointMessageAgain;
Serializer s3(ACTION_SERIALIZE, stampedPointMessageAgain);
stampedPoint.accept(s3);
// -- Get a Point2D from a Point2D message
Serializer s4(ACTION_DESERIALIZE, pointMessage);
Point2D resultPoint1;
resultPoint1.accept(s4);
// -- Get a Point2D from a StampedPoint2D message
Serializer s5(ACTION_DESERIALIZE, stampedPointMessageAgain);
Point2D resultPoint2;
// This only works because the first two serialized fields are x and y
resultPoint2.accept(s5);
// -- Get a StampedPoint2D from a StampedPoint2D message
Serializer s6(ACTION_DESERIALIZE, stampedPointMessage);
StampedPoint2D resultStampedPoint;
resultStampedPoint.accept(s6);
// ---------------------------------------------------
ASSERT_EQ(point.x, resultPoint1.x);
ASSERT_EQ(point.y, resultPoint1.y);
ASSERT_EQ(point.x, resultPoint2.x);
ASSERT_EQ(point.y, resultPoint2.y);
ASSERT_EQ(point.x, resultStampedPoint.point.x);
ASSERT_EQ(point.y, resultStampedPoint.point.y);
ASSERT_EQ(timestamp.seconds, resultStampedPoint.time.seconds);
ASSERT_EQ(timestamp.nanoseconds, resultStampedPoint.time.nanoseconds);
}<|endoftext|> |
<commit_before>/* This file is part of the Tufão project
Copyright (C) 2011 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any
later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "priv/httpserverrequest.h"
namespace Tufao {
const http_parser_settings HttpServerRequest::Priv::httpSettingsInstance
= HttpServerRequest::Priv::httpSettings();
HttpServerRequest::HttpServerRequest(QAbstractSocket &socket, QObject *parent) :
QObject(parent),
priv(new Priv(this, socket))
{
connect(&socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(&socket, SIGNAL(disconnected()), this, SIGNAL(close()));
connect(&priv->timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
if (priv->timeout)
priv->timer.start(priv->timeout);
}
HttpServerRequest::~HttpServerRequest()
{
delete priv;
}
QByteArray HttpServerRequest::method() const
{
return priv->method;
}
void HttpServerRequest::setUrl(const QUrl &url)
{
priv->url = url;
}
QUrl HttpServerRequest::url() const
{
return priv->url;
}
Headers HttpServerRequest::headers() const
{
return priv->headers;
}
Headers &HttpServerRequest::headers()
{
return priv->headers;
}
Headers HttpServerRequest::trailers() const
{
return priv->trailers;
}
HttpVersion HttpServerRequest::httpVersion() const
{
return priv->httpVersion;
}
QByteArray HttpServerRequest::readBody()
{
QByteArray body;
body.swap(priv->body);
return body;
}
QAbstractSocket &HttpServerRequest::socket() const
{
return priv->socket;
}
void HttpServerRequest::setTimeout(int msecs)
{
priv->timeout = msecs;
if (priv->timeout)
priv->timer.start(priv->timeout);
else
priv->timer.stop();
}
int HttpServerRequest::timeout() const
{
return priv->timeout;
}
HttpServerResponse::Options HttpServerRequest::responseOptions() const
{
return priv->responseOptions;
}
QVariant HttpServerRequest::customData() const
{
return priv->customData;
}
void HttpServerRequest::setCustomData(const QVariant &data)
{
priv->customData = data;
}
void HttpServerRequest::onReadyRead()
{
if (priv->timeout)
priv->timer.start(priv->timeout);
priv->buffer += priv->socket.readAll();
size_t nparsed = http_parser_execute(&priv->parser,
&Priv::httpSettingsInstance,
priv->buffer.constData(),
priv->buffer.size());
if (priv->parser.http_errno) {
priv->socket.close();
return;
}
if (priv->whatEmit.testFlag(Priv::READY)) {
priv->whatEmit &= ~Priv::Signals(Priv::READY);
this->disconnect(SIGNAL(data()));
this->disconnect(SIGNAL(end()));
emit ready();
}
if (priv->whatEmit.testFlag(Priv::DATA)) {
priv->whatEmit &= ~Priv::Signals(Priv::DATA);
emit data();
}
priv->buffer.remove(0, nparsed);
if (priv->whatEmit.testFlag(Priv::END)) {
priv->whatEmit &= ~Priv::Signals(Priv::END);
emit end();
return;
}
if (priv->parser.upgrade) {
disconnect(&priv->socket, SIGNAL(readyRead()),
this, SLOT(onReadyRead()));
disconnect(&priv->socket, SIGNAL(disconnected()),
this, SIGNAL(close()));
disconnect(&priv->timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
priv->body.swap(priv->buffer);
emit upgrade();
}
}
void HttpServerRequest::onTimeout()
{
priv->socket.close();
}
inline void HttpServerRequest::clearBuffer()
{
priv->buffer.clear();
priv->urlData.clear();
priv->lastHeader.clear();
priv->lastWasValue = true;
priv->useTrailers = false;
}
inline void HttpServerRequest::clearRequest()
{
priv->method.clear();
priv->url.clear();
priv->headers.clear();
priv->body.clear();
priv->trailers.clear();
priv->customData.clear();
}
http_parser_settings HttpServerRequest::Priv::httpSettings()
{
http_parser_settings settings;
settings.on_message_begin
= Tufao::HttpServerRequest::Priv::on_message_begin;
settings.on_url = Tufao::HttpServerRequest::Priv::on_url;
settings.on_header_field = Tufao::HttpServerRequest::Priv::on_header_field;
settings.on_header_value = Tufao::HttpServerRequest::Priv::on_header_value;
settings.on_headers_complete
= Tufao::HttpServerRequest::Priv::on_headers_complete;
settings.on_body = Tufao::HttpServerRequest::Priv::on_body;
settings.on_message_complete
= Tufao::HttpServerRequest::Priv::on_message_complete;
return settings;
}
int HttpServerRequest::Priv::on_message_begin(http_parser *parser)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->clearRequest();
return 0;
}
int HttpServerRequest::Priv::on_url(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->priv->urlData.append(at, length);
return 0;
}
int HttpServerRequest::Priv::on_header_field(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
if (request->priv->lastWasValue) {
request->priv->lastHeader = QByteArray(at, length);
request->priv->lastWasValue = false;
} else {
request->priv->lastHeader.append(at, length);
}
return 0;
}
int HttpServerRequest::Priv::on_header_value(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
if (request->priv->lastWasValue) {
if (request->priv->useTrailers) {
request->priv->trailers
.replace(request->priv->lastHeader,
request->priv->trailers.value(request->priv
->lastHeader)
+ QByteArray(at, length));
} else {
request->priv->headers
.replace(request->priv->lastHeader,
request->priv->headers.value(request->priv
->lastHeader)
+ QByteArray(at, length));
}
} else {
if (request->priv->useTrailers) {
request->priv->trailers
.insert(request->priv->lastHeader, QByteArray(at, length));
} else {
request->priv->headers
.insert(request->priv->lastHeader, QByteArray(at, length));
}
request->priv->lastWasValue = true;
}
return 0;
}
int HttpServerRequest::Priv::on_headers_complete(http_parser *parser)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->priv->url = request->priv->urlData;
request->priv->urlData.clear();
request->priv->lastHeader.clear();
request->priv->lastWasValue = true;
request->priv->useTrailers = true;
{
typedef RawData MT;
static const MT methods[] {
MT{"DELETE"},
MT{"GET"},
MT{"HEAD"},
MT{"POST"},
MT{"PUT"},
MT{"CONNECT"},
MT{"OPTIONS"},
MT{"TRACE"},
MT{"COPY"},
MT{"LOCK"},
MT{"MKCOL"},
MT{"MOVE"},
MT{"PROPFIND"},
MT{"PROPPATCH"},
MT{"SEARCH"},
MT{"UNLOCK"},
MT{"REPORT"},
MT{"MKACTIVITY"},
MT{"CHECKOUT"},
MT{"MERGE"},
MT{"M-SEARCH"},
MT{"NOTIFY"},
MT{"SUBSCRIBE"},
MT{"UNSUBSCRIBE"},
MT{"PATCH"},
MT{"PURGE"}
};
const auto &m = methods[parser->method];
request->priv->method.setRawData(m.data, m.size);
}
{
static const char errorMessage[]
= "HTTP/1.1 505 HTTP Version Not Supported\r\n"
"Connection: close\r\n"
"\r\n"
"This server only offers support to HTTP/1.0 and HTTP/1.1\n";
switch (parser->http_major) {
case 1:
switch (parser->http_minor) {
case 0:
request->priv->httpVersion = HttpVersion::HTTP_1_0;
break;
case 1:
request->priv->httpVersion = HttpVersion::HTTP_1_1;
break;
default:
request->priv->socket.write(errorMessage,
sizeof(errorMessage) - 1);
request->clearBuffer();
request->clearRequest();
return -1;
}
break;
default:
request->priv->socket.write(errorMessage, sizeof(errorMessage) - 1);
request->clearBuffer();
request->clearRequest();
return -1;
}
}
request->priv->responseOptions = 0;
if (parser->http_minor == 1)
request->priv->responseOptions |= HttpServerResponse::HTTP_1_1;
else
request->priv->responseOptions |= HttpServerResponse::HTTP_1_0;
if (http_should_keep_alive(&request->priv->parser))
request->priv->responseOptions |= HttpServerResponse::KEEP_ALIVE;
if (!parser->upgrade)
request->priv->whatEmit = READY;
return 0;
}
int HttpServerRequest::Priv::on_body(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->priv->body.append(at, length);
request->priv->whatEmit |= Priv::DATA;
return 0;
}
int HttpServerRequest::Priv::on_message_complete(http_parser *parser)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
if (!parser->upgrade) {
request->clearBuffer();
request->priv->whatEmit |= Priv::END;
}
return 0;
}
void HttpServerRequest::setContext(const QString context)
{
priv->context = context;
}
QString HttpServerRequest::context(void) const
{
return priv->context;
}
} // namespace Tufao
<commit_msg>Fixing identation issue introduced in commit a6fa289820d5b1828abd3a4f16c863cf3f851026<commit_after>/* This file is part of the Tufão project
Copyright (C) 2011 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any
later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "priv/httpserverrequest.h"
namespace Tufao {
const http_parser_settings HttpServerRequest::Priv::httpSettingsInstance
= HttpServerRequest::Priv::httpSettings();
HttpServerRequest::HttpServerRequest(QAbstractSocket &socket, QObject *parent) :
QObject(parent),
priv(new Priv(this, socket))
{
connect(&socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(&socket, SIGNAL(disconnected()), this, SIGNAL(close()));
connect(&priv->timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
if (priv->timeout)
priv->timer.start(priv->timeout);
}
HttpServerRequest::~HttpServerRequest()
{
delete priv;
}
QByteArray HttpServerRequest::method() const
{
return priv->method;
}
void HttpServerRequest::setUrl(const QUrl &url)
{
priv->url = url;
}
QUrl HttpServerRequest::url() const
{
return priv->url;
}
Headers HttpServerRequest::headers() const
{
return priv->headers;
}
Headers &HttpServerRequest::headers()
{
return priv->headers;
}
Headers HttpServerRequest::trailers() const
{
return priv->trailers;
}
HttpVersion HttpServerRequest::httpVersion() const
{
return priv->httpVersion;
}
QByteArray HttpServerRequest::readBody()
{
QByteArray body;
body.swap(priv->body);
return body;
}
QAbstractSocket &HttpServerRequest::socket() const
{
return priv->socket;
}
void HttpServerRequest::setTimeout(int msecs)
{
priv->timeout = msecs;
if (priv->timeout)
priv->timer.start(priv->timeout);
else
priv->timer.stop();
}
int HttpServerRequest::timeout() const
{
return priv->timeout;
}
HttpServerResponse::Options HttpServerRequest::responseOptions() const
{
return priv->responseOptions;
}
QVariant HttpServerRequest::customData() const
{
return priv->customData;
}
void HttpServerRequest::setCustomData(const QVariant &data)
{
priv->customData = data;
}
void HttpServerRequest::onReadyRead()
{
if (priv->timeout)
priv->timer.start(priv->timeout);
priv->buffer += priv->socket.readAll();
size_t nparsed = http_parser_execute(&priv->parser,
&Priv::httpSettingsInstance,
priv->buffer.constData(),
priv->buffer.size());
if (priv->parser.http_errno) {
priv->socket.close();
return;
}
if (priv->whatEmit.testFlag(Priv::READY)) {
priv->whatEmit &= ~Priv::Signals(Priv::READY);
this->disconnect(SIGNAL(data()));
this->disconnect(SIGNAL(end()));
emit ready();
}
if (priv->whatEmit.testFlag(Priv::DATA)) {
priv->whatEmit &= ~Priv::Signals(Priv::DATA);
emit data();
}
priv->buffer.remove(0, nparsed);
if (priv->whatEmit.testFlag(Priv::END)) {
priv->whatEmit &= ~Priv::Signals(Priv::END);
emit end();
return;
}
if (priv->parser.upgrade) {
disconnect(&priv->socket, SIGNAL(readyRead()),
this, SLOT(onReadyRead()));
disconnect(&priv->socket, SIGNAL(disconnected()),
this, SIGNAL(close()));
disconnect(&priv->timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
priv->body.swap(priv->buffer);
emit upgrade();
}
}
void HttpServerRequest::onTimeout()
{
priv->socket.close();
}
inline void HttpServerRequest::clearBuffer()
{
priv->buffer.clear();
priv->urlData.clear();
priv->lastHeader.clear();
priv->lastWasValue = true;
priv->useTrailers = false;
}
inline void HttpServerRequest::clearRequest()
{
priv->method.clear();
priv->url.clear();
priv->headers.clear();
priv->body.clear();
priv->trailers.clear();
priv->customData.clear();
}
http_parser_settings HttpServerRequest::Priv::httpSettings()
{
http_parser_settings settings;
settings.on_message_begin
= Tufao::HttpServerRequest::Priv::on_message_begin;
settings.on_url = Tufao::HttpServerRequest::Priv::on_url;
settings.on_header_field = Tufao::HttpServerRequest::Priv::on_header_field;
settings.on_header_value = Tufao::HttpServerRequest::Priv::on_header_value;
settings.on_headers_complete
= Tufao::HttpServerRequest::Priv::on_headers_complete;
settings.on_body = Tufao::HttpServerRequest::Priv::on_body;
settings.on_message_complete
= Tufao::HttpServerRequest::Priv::on_message_complete;
return settings;
}
int HttpServerRequest::Priv::on_message_begin(http_parser *parser)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->clearRequest();
return 0;
}
int HttpServerRequest::Priv::on_url(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->priv->urlData.append(at, length);
return 0;
}
int HttpServerRequest::Priv::on_header_field(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
if (request->priv->lastWasValue) {
request->priv->lastHeader = QByteArray(at, length);
request->priv->lastWasValue = false;
} else {
request->priv->lastHeader.append(at, length);
}
return 0;
}
int HttpServerRequest::Priv::on_header_value(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
if (request->priv->lastWasValue) {
if (request->priv->useTrailers) {
request->priv->trailers
.replace(request->priv->lastHeader,
request->priv->trailers.value(request->priv
->lastHeader)
+ QByteArray(at, length));
} else {
request->priv->headers
.replace(request->priv->lastHeader,
request->priv->headers.value(request->priv
->lastHeader)
+ QByteArray(at, length));
}
} else {
if (request->priv->useTrailers) {
request->priv->trailers
.insert(request->priv->lastHeader, QByteArray(at, length));
} else {
request->priv->headers
.insert(request->priv->lastHeader, QByteArray(at, length));
}
request->priv->lastWasValue = true;
}
return 0;
}
int HttpServerRequest::Priv::on_headers_complete(http_parser *parser)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->priv->url = request->priv->urlData;
request->priv->urlData.clear();
request->priv->lastHeader.clear();
request->priv->lastWasValue = true;
request->priv->useTrailers = true;
{
typedef RawData MT;
static const MT methods[] {
MT{"DELETE"},
MT{"GET"},
MT{"HEAD"},
MT{"POST"},
MT{"PUT"},
MT{"CONNECT"},
MT{"OPTIONS"},
MT{"TRACE"},
MT{"COPY"},
MT{"LOCK"},
MT{"MKCOL"},
MT{"MOVE"},
MT{"PROPFIND"},
MT{"PROPPATCH"},
MT{"SEARCH"},
MT{"UNLOCK"},
MT{"REPORT"},
MT{"MKACTIVITY"},
MT{"CHECKOUT"},
MT{"MERGE"},
MT{"M-SEARCH"},
MT{"NOTIFY"},
MT{"SUBSCRIBE"},
MT{"UNSUBSCRIBE"},
MT{"PATCH"},
MT{"PURGE"}
};
const auto &m = methods[parser->method];
request->priv->method.setRawData(m.data, m.size);
}
{
static const char errorMessage[]
= "HTTP/1.1 505 HTTP Version Not Supported\r\n"
"Connection: close\r\n"
"\r\n"
"This server only offers support to HTTP/1.0 and HTTP/1.1\n";
switch (parser->http_major) {
case 1:
switch (parser->http_minor) {
case 0:
request->priv->httpVersion = HttpVersion::HTTP_1_0;
break;
case 1:
request->priv->httpVersion = HttpVersion::HTTP_1_1;
break;
default:
request->priv->socket.write(errorMessage,
sizeof(errorMessage) - 1);
request->clearBuffer();
request->clearRequest();
return -1;
}
break;
default:
request->priv->socket.write(errorMessage, sizeof(errorMessage) - 1);
request->clearBuffer();
request->clearRequest();
return -1;
}
}
request->priv->responseOptions = 0;
if (parser->http_minor == 1)
request->priv->responseOptions |= HttpServerResponse::HTTP_1_1;
else
request->priv->responseOptions |= HttpServerResponse::HTTP_1_0;
if (http_should_keep_alive(&request->priv->parser))
request->priv->responseOptions |= HttpServerResponse::KEEP_ALIVE;
if (!parser->upgrade)
request->priv->whatEmit = READY;
return 0;
}
int HttpServerRequest::Priv::on_body(http_parser *parser, const char *at,
size_t length)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
request->priv->body.append(at, length);
request->priv->whatEmit |= Priv::DATA;
return 0;
}
int HttpServerRequest::Priv::on_message_complete(http_parser *parser)
{
Tufao::HttpServerRequest *request = static_cast<Tufao::HttpServerRequest *>
(parser->data);
Q_ASSERT(request);
if (!parser->upgrade) {
request->clearBuffer();
request->priv->whatEmit |= Priv::END;
}
return 0;
}
void HttpServerRequest::setContext(const QString context)
{
priv->context = context;
}
QString HttpServerRequest::context(void) const
{
return priv->context;
}
} // namespace Tufao
<|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/shell_content_browser_client.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/nw/src/browser/printing/printing_message_filter.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/renderer_preferences.h"
#include "content/public/common/url_constants.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/browser/printing/print_job_manager.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/browser/shell_resource_dispatcher_host_delegate.h"
#include "content/nw/src/media/media_internals.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/nw_version.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_browser_main_parts.h"
#include "geolocation/shell_access_token_store.h"
#include "googleurl/src/gurl.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/common/dom_storage/dom_storage_map.h"
#include "webkit/common/webpreferences.h"
#include "webkit/common/user_agent/user_agent_util.h"
#include "webkit/plugins/npapi/plugin_list.h"
namespace content {
ShellContentBrowserClient::ShellContentBrowserClient()
: shell_browser_main_parts_(NULL),
master_rph_(NULL) {
}
ShellContentBrowserClient::~ShellContentBrowserClient() {
}
BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(
const MainFunctionParams& parameters) {
shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);
return shell_browser_main_parts_;
}
WebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView(
WebContents* web_contents,
RenderViewHostDelegateView** render_view_host_delegate_view) {
std::string user_agent, rules;
nw::Package* package = shell_browser_main_parts()->package();
content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs();
if (package->root()->GetString(switches::kmUserAgent, &user_agent)) {
std::string name, version;
package->root()->GetString(switches::kmName, &name);
package->root()->GetString("version", &version);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%name", name);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%ver", version);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%nwver", NW_VERSION_STRING);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%webkit_ver", webkit_glue::GetWebKitVersion());
ReplaceSubstringsAfterOffset(&user_agent, 0, "%osinfo", webkit_glue::BuildOSInfo());
prefs->user_agent_override = user_agent;
}
if (package->root()->GetString(switches::kmRemotePages, &rules))
prefs->nw_remote_page_rules = rules;
prefs->nw_app_root_path = package->path();
return NULL;
}
std::string ShellContentBrowserClient::GetApplicationLocale() {
return l10n_util::GetApplicationLocale("en-US");
}
void ShellContentBrowserClient::AppendExtraCommandLineSwitches(
CommandLine* command_line,
int child_process_id) {
if (command_line->GetSwitchValueASCII("type") != "renderer")
return;
if (child_process_id > 0) {
content::RenderWidgetHost::List widgets =
content::RenderWidgetHost::GetRenderWidgetHosts();
for (size_t i = 0; i < widgets.size(); ++i) {
if (widgets[i]->GetProcess()->GetID() != child_process_id)
continue;
if (!widgets[i]->IsRenderView())
continue;
const content::RenderWidgetHost* widget = widgets[i];
DCHECK(widget);
content::RenderViewHost* host = content::RenderViewHost::From(
const_cast<content::RenderWidgetHost*>(widget));
content::Shell* shell = content::Shell::FromRenderViewHost(host);
if (shell) {
if (!shell->nodejs())
return;
if (shell->is_devtools()) {
// DevTools should have powerful permissions to load local
// files by XHR (e.g. for source map)
command_line->AppendSwitch(switches::kNodejs);
return;
}
}
}
}
nw::Package* package = shell_browser_main_parts()->package();
if (package && package->GetUseNode()) {
// Allow node.js
command_line->AppendSwitch(switches::kNodejs);
// Set cwd
command_line->AppendSwitchPath(switches::kWorkingDirectory,
package->path());
// Check if we have 'node-main'.
std::string node_main;
if (package->root()->GetString(switches::kNodeMain, &node_main))
command_line->AppendSwitchASCII(switches::kNodeMain, node_main);
std::string snapshot_path;
if (package->root()->GetString(switches::kSnapshot, &snapshot_path))
command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path);
int dom_storage_quota_mb;
if (package->root()->GetInteger("dom_storage_quota", &dom_storage_quota_mb)) {
dom_storage::DomStorageMap::SetQuotaOverride(dom_storage_quota_mb * 1024 * 1024);
command_line->AppendSwitchASCII(switches::kDomStorageQuota, base::IntToString(dom_storage_quota_mb));
}
}
// without the switch, the destructor of the shell object will
// shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and
// destory rph immediately. Then the channel error msg is caught by
// SuicideOnChannelErrorFilter and the renderer is killed
// immediately
#if defined(OS_POSIX)
command_line->AppendSwitch(switches::kChildCleanExit);
#endif
}
void ShellContentBrowserClient::ResourceDispatcherHostCreated() {
resource_dispatcher_host_delegate_.reset(
new ShellResourceDispatcherHostDelegate());
ResourceDispatcherHost::Get()->SetDelegate(
resource_dispatcher_host_delegate_.get());
}
std::string ShellContentBrowserClient::GetDefaultDownloadName() {
return "download";
}
MediaObserver* ShellContentBrowserClient::GetMediaObserver() {
return MediaInternals::GetInstance();
}
void ShellContentBrowserClient::BrowserURLHandlerCreated(
BrowserURLHandler* handler) {
}
ShellBrowserContext* ShellContentBrowserClient::browser_context() {
return shell_browser_main_parts_->browser_context();
}
ShellBrowserContext*
ShellContentBrowserClient::off_the_record_browser_context() {
return shell_browser_main_parts_->off_the_record_browser_context();
}
AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {
return new ShellAccessTokenStore(browser_context());
}
void ShellContentBrowserClient::OverrideWebkitPrefs(
RenderViewHost* render_view_host,
const GURL& url,
WebPreferences* prefs) {
nw::Package* package = shell_browser_main_parts()->package();
// Disable web security.
prefs->dom_paste_enabled = true;
prefs->javascript_can_access_clipboard = true;
prefs->web_security_enabled = true;
prefs->allow_file_access_from_file_urls = true;
// Open experimental features.
prefs->css_sticky_position_enabled = true;
prefs->css_shaders_enabled = true;
prefs->css_variables_enabled = true;
// Disable plugins and cache by default.
prefs->plugins_enabled = false;
prefs->java_enabled = false;
base::DictionaryValue* webkit;
if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {
webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);
webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);
FilePath plugins_dir = package->path();
//PathService::Get(base::DIR_CURRENT, &plugins_dir);
plugins_dir = plugins_dir.AppendASCII("plugins");
webkit::npapi::PluginList::Singleton()->AddExtraPluginDir(plugins_dir);
}
}
bool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost(
BrowserContext* browser_context, const GURL& url) {
ShellBrowserContext* shell_browser_context =
static_cast<ShellBrowserContext*>(browser_context);
if (shell_browser_context->pinning_renderer())
return true;
else
return false;
}
bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,
const GURL& site_url) {
return process_host == master_rph_;
}
net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(
BrowserContext* content_browser_context,
ProtocolHandlerMap* protocol_handlers) {
ShellBrowserContext* shell_browser_context =
ShellBrowserContextForBrowserContext(content_browser_context);
return shell_browser_context->CreateRequestContext(protocol_handlers);
}
net::URLRequestContextGetter*
ShellContentBrowserClient::CreateRequestContextForStoragePartition(
BrowserContext* content_browser_context,
const base::FilePath& partition_path,
bool in_memory,
ProtocolHandlerMap* protocol_handlers) {
ShellBrowserContext* shell_browser_context =
ShellBrowserContextForBrowserContext(content_browser_context);
return shell_browser_context->CreateRequestContextForStoragePartition(
partition_path, in_memory, protocol_handlers);
}
ShellBrowserContext*
ShellContentBrowserClient::ShellBrowserContextForBrowserContext(
BrowserContext* content_browser_context) {
if (content_browser_context == browser_context())
return browser_context();
DCHECK_EQ(content_browser_context, off_the_record_browser_context());
return off_the_record_browser_context();
}
printing::PrintJobManager* ShellContentBrowserClient::print_job_manager() {
return shell_browser_main_parts_->print_job_manager();
}
void ShellContentBrowserClient::RenderProcessHostCreated(
RenderProcessHost* host) {
int id = host->GetID();
if (!master_rph_)
master_rph_ = host;
// Grant file: scheme to the whole process, since we impose
// per-view access checks.
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
host->GetID(), chrome::kFileScheme);
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
host->GetID(), "app");
#if defined(ENABLE_PRINTING)
host->GetChannel()->AddFilter(new PrintingMessageFilter(id));
#endif
}
bool ShellContentBrowserClient::IsHandledURL(const GURL& url) {
if (!url.is_valid())
return false;
DCHECK_EQ(url.scheme(), StringToLowerASCII(url.scheme()));
// Keep in sync with ProtocolHandlers added by
// ShellURLRequestContextGetter::GetURLRequestContext().
static const char* const kProtocolList[] = {
chrome::kFileSystemScheme,
chrome::kFileScheme,
"app",
};
for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
if (url.scheme() == kProtocolList[i])
return true;
}
return false;
}
void ShellContentBrowserClient::AllowCertificateError(
int render_process_id,
int render_view_id,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
ResourceType::Type resource_type,
bool overridable,
bool strict_enforcement,
const base::Callback<void(bool)>& callback,
content::CertificateRequestResultType* result) {
VLOG(1) << "AllowCertificateError: " << request_url;
*result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
return;
}
} // namespace content
<commit_msg>Fix #904: support 'ignore-certificate-errors' in some cases<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/shell_content_browser_client.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/nw/src/browser/printing/printing_message_filter.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/renderer_preferences.h"
#include "content/public/common/url_constants.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/browser/printing/print_job_manager.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/browser/shell_resource_dispatcher_host_delegate.h"
#include "content/nw/src/media/media_internals.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/nw_version.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_browser_main_parts.h"
#include "geolocation/shell_access_token_store.h"
#include "googleurl/src/gurl.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/common/dom_storage/dom_storage_map.h"
#include "webkit/common/webpreferences.h"
#include "webkit/common/user_agent/user_agent_util.h"
#include "webkit/plugins/npapi/plugin_list.h"
namespace content {
ShellContentBrowserClient::ShellContentBrowserClient()
: shell_browser_main_parts_(NULL),
master_rph_(NULL) {
}
ShellContentBrowserClient::~ShellContentBrowserClient() {
}
BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(
const MainFunctionParams& parameters) {
shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);
return shell_browser_main_parts_;
}
WebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView(
WebContents* web_contents,
RenderViewHostDelegateView** render_view_host_delegate_view) {
std::string user_agent, rules;
nw::Package* package = shell_browser_main_parts()->package();
content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs();
if (package->root()->GetString(switches::kmUserAgent, &user_agent)) {
std::string name, version;
package->root()->GetString(switches::kmName, &name);
package->root()->GetString("version", &version);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%name", name);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%ver", version);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%nwver", NW_VERSION_STRING);
ReplaceSubstringsAfterOffset(&user_agent, 0, "%webkit_ver", webkit_glue::GetWebKitVersion());
ReplaceSubstringsAfterOffset(&user_agent, 0, "%osinfo", webkit_glue::BuildOSInfo());
prefs->user_agent_override = user_agent;
}
if (package->root()->GetString(switches::kmRemotePages, &rules))
prefs->nw_remote_page_rules = rules;
prefs->nw_app_root_path = package->path();
return NULL;
}
std::string ShellContentBrowserClient::GetApplicationLocale() {
return l10n_util::GetApplicationLocale("en-US");
}
void ShellContentBrowserClient::AppendExtraCommandLineSwitches(
CommandLine* command_line,
int child_process_id) {
if (command_line->GetSwitchValueASCII("type") != "renderer")
return;
if (child_process_id > 0) {
content::RenderWidgetHost::List widgets =
content::RenderWidgetHost::GetRenderWidgetHosts();
for (size_t i = 0; i < widgets.size(); ++i) {
if (widgets[i]->GetProcess()->GetID() != child_process_id)
continue;
if (!widgets[i]->IsRenderView())
continue;
const content::RenderWidgetHost* widget = widgets[i];
DCHECK(widget);
content::RenderViewHost* host = content::RenderViewHost::From(
const_cast<content::RenderWidgetHost*>(widget));
content::Shell* shell = content::Shell::FromRenderViewHost(host);
if (shell) {
if (!shell->nodejs())
return;
if (shell->is_devtools()) {
// DevTools should have powerful permissions to load local
// files by XHR (e.g. for source map)
command_line->AppendSwitch(switches::kNodejs);
return;
}
}
}
}
nw::Package* package = shell_browser_main_parts()->package();
if (package && package->GetUseNode()) {
// Allow node.js
command_line->AppendSwitch(switches::kNodejs);
// Set cwd
command_line->AppendSwitchPath(switches::kWorkingDirectory,
package->path());
// Check if we have 'node-main'.
std::string node_main;
if (package->root()->GetString(switches::kNodeMain, &node_main))
command_line->AppendSwitchASCII(switches::kNodeMain, node_main);
std::string snapshot_path;
if (package->root()->GetString(switches::kSnapshot, &snapshot_path))
command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path);
int dom_storage_quota_mb;
if (package->root()->GetInteger("dom_storage_quota", &dom_storage_quota_mb)) {
dom_storage::DomStorageMap::SetQuotaOverride(dom_storage_quota_mb * 1024 * 1024);
command_line->AppendSwitchASCII(switches::kDomStorageQuota, base::IntToString(dom_storage_quota_mb));
}
}
// without the switch, the destructor of the shell object will
// shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and
// destory rph immediately. Then the channel error msg is caught by
// SuicideOnChannelErrorFilter and the renderer is killed
// immediately
#if defined(OS_POSIX)
command_line->AppendSwitch(switches::kChildCleanExit);
#endif
}
void ShellContentBrowserClient::ResourceDispatcherHostCreated() {
resource_dispatcher_host_delegate_.reset(
new ShellResourceDispatcherHostDelegate());
ResourceDispatcherHost::Get()->SetDelegate(
resource_dispatcher_host_delegate_.get());
}
std::string ShellContentBrowserClient::GetDefaultDownloadName() {
return "download";
}
MediaObserver* ShellContentBrowserClient::GetMediaObserver() {
return MediaInternals::GetInstance();
}
void ShellContentBrowserClient::BrowserURLHandlerCreated(
BrowserURLHandler* handler) {
}
ShellBrowserContext* ShellContentBrowserClient::browser_context() {
return shell_browser_main_parts_->browser_context();
}
ShellBrowserContext*
ShellContentBrowserClient::off_the_record_browser_context() {
return shell_browser_main_parts_->off_the_record_browser_context();
}
AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {
return new ShellAccessTokenStore(browser_context());
}
void ShellContentBrowserClient::OverrideWebkitPrefs(
RenderViewHost* render_view_host,
const GURL& url,
WebPreferences* prefs) {
nw::Package* package = shell_browser_main_parts()->package();
// Disable web security.
prefs->dom_paste_enabled = true;
prefs->javascript_can_access_clipboard = true;
prefs->web_security_enabled = true;
prefs->allow_file_access_from_file_urls = true;
// Open experimental features.
prefs->css_sticky_position_enabled = true;
prefs->css_shaders_enabled = true;
prefs->css_variables_enabled = true;
// Disable plugins and cache by default.
prefs->plugins_enabled = false;
prefs->java_enabled = false;
base::DictionaryValue* webkit;
if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {
webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);
webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);
FilePath plugins_dir = package->path();
//PathService::Get(base::DIR_CURRENT, &plugins_dir);
plugins_dir = plugins_dir.AppendASCII("plugins");
webkit::npapi::PluginList::Singleton()->AddExtraPluginDir(plugins_dir);
}
}
bool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost(
BrowserContext* browser_context, const GURL& url) {
ShellBrowserContext* shell_browser_context =
static_cast<ShellBrowserContext*>(browser_context);
if (shell_browser_context->pinning_renderer())
return true;
else
return false;
}
bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,
const GURL& site_url) {
return process_host == master_rph_;
}
net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(
BrowserContext* content_browser_context,
ProtocolHandlerMap* protocol_handlers) {
ShellBrowserContext* shell_browser_context =
ShellBrowserContextForBrowserContext(content_browser_context);
return shell_browser_context->CreateRequestContext(protocol_handlers);
}
net::URLRequestContextGetter*
ShellContentBrowserClient::CreateRequestContextForStoragePartition(
BrowserContext* content_browser_context,
const base::FilePath& partition_path,
bool in_memory,
ProtocolHandlerMap* protocol_handlers) {
ShellBrowserContext* shell_browser_context =
ShellBrowserContextForBrowserContext(content_browser_context);
return shell_browser_context->CreateRequestContextForStoragePartition(
partition_path, in_memory, protocol_handlers);
}
ShellBrowserContext*
ShellContentBrowserClient::ShellBrowserContextForBrowserContext(
BrowserContext* content_browser_context) {
if (content_browser_context == browser_context())
return browser_context();
DCHECK_EQ(content_browser_context, off_the_record_browser_context());
return off_the_record_browser_context();
}
printing::PrintJobManager* ShellContentBrowserClient::print_job_manager() {
return shell_browser_main_parts_->print_job_manager();
}
void ShellContentBrowserClient::RenderProcessHostCreated(
RenderProcessHost* host) {
int id = host->GetID();
if (!master_rph_)
master_rph_ = host;
// Grant file: scheme to the whole process, since we impose
// per-view access checks.
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
host->GetID(), chrome::kFileScheme);
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
host->GetID(), "app");
#if defined(ENABLE_PRINTING)
host->GetChannel()->AddFilter(new PrintingMessageFilter(id));
#endif
}
bool ShellContentBrowserClient::IsHandledURL(const GURL& url) {
if (!url.is_valid())
return false;
DCHECK_EQ(url.scheme(), StringToLowerASCII(url.scheme()));
// Keep in sync with ProtocolHandlers added by
// ShellURLRequestContextGetter::GetURLRequestContext().
static const char* const kProtocolList[] = {
chrome::kFileSystemScheme,
chrome::kFileScheme,
"app",
};
for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
if (url.scheme() == kProtocolList[i])
return true;
}
return false;
}
void ShellContentBrowserClient::AllowCertificateError(
int render_process_id,
int render_view_id,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
ResourceType::Type resource_type,
bool overridable,
bool strict_enforcement,
const base::Callback<void(bool)>& callback,
content::CertificateRequestResultType* result) {
VLOG(1) << "AllowCertificateError: " << request_url;
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (cmd_line->HasSwitch(switches::kIgnoreCertificateErrors)) {
*result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE;
}
else
*result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
return;
}
} // namespace content
<|endoftext|> |
<commit_before>/*
* libtins is a net packet wrapper library for crafting and
* interpreting sniffed packets.
*
* Copyright (C) 2011 Nasel
*
* 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 <stdexcept>
#include <cstring>
#include <cassert>
#include "utils.h"
#include "dhcp.h"
#include "ethernetII.h"
const uint32_t Tins::DHCP::MAX_DHCP_SIZE = 312;
using namespace std;
/* Magic cookie: uint32_t.
* end of options: 1 byte. */
Tins::DHCP::DHCP() : _size(sizeof(uint32_t) + 1) {
opcode(BOOTREQUEST);
htype(1); //ethernet
hlen(EthernetII::ADDR_SIZE);
}
Tins::DHCP::DHCP(const uint8_t *buffer, uint32_t total_sz) : BootP(buffer, total_sz, 0), _size(sizeof(uint32_t) + 1){
buffer += BootP::header_size() - vend_size();
total_sz -= BootP::header_size() - vend_size();
uint8_t args[2] = {0};
if(total_sz < sizeof(uint32_t) || *(uint32_t*)buffer != Utils::net_to_host_l(0x63825363))
throw std::runtime_error("Not enough size for a DHCP header in the buffer.");
buffer += sizeof(uint32_t);
total_sz -= sizeof(uint32_t);
while(total_sz) {
for(unsigned i(0); i < 2; ++i) {
args[i] = *(buffer++);
total_sz--;
if(args[0] == END || args[0] == PAD)
i = 2;
else if(!total_sz)
throw std::runtime_error("Not enough size for a DHCP header in the buffer.");
}
// If the END-OF-OPTIONS was not found...
if(args[0] != END && args[0] != PAD) {
// Not enough size for this option
if(total_sz < args[1])
throw std::runtime_error("Not enough size for a DHCP header in the buffer.");
add_option((Options)args[0], args[1], buffer);
buffer += args[1];
total_sz -= args[1];
}
// Otherwise, break the loop.
else
total_sz = 0;
}
}
Tins::DHCP::DHCP(const DHCP &other) : BootP(other) {
copy_fields(&other);
}
Tins::DHCP &Tins::DHCP::operator= (const DHCP &other) {
copy_fields(&other);
copy_inner_pdu(other);
return *this;
}
Tins::DHCP::~DHCP() {
while(_options.size()) {
delete[] _options.front().value;
_options.pop_front();
}
}
Tins::DHCP::DHCPOption::DHCPOption(uint8_t opt, uint8_t len, const uint8_t *val) : option(opt), length(len) {
if(len) {
value = new uint8_t[len];
std::memcpy(value, val, len);
}
else
value = 0;
}
bool Tins::DHCP::add_option(Options opt, uint8_t len, const uint8_t *val) {
uint32_t opt_size = len + (sizeof(uint8_t) << 1);
if(_size + opt_size > MAX_DHCP_SIZE)
return false;
_options.push_back(DHCPOption((uint8_t)opt, len, val));
_size += opt_size;
return true;
}
const Tins::DHCP::DHCPOption *Tins::DHCP::search_option(Options opt) const{
for(std::list<DHCPOption>::const_iterator it = _options.begin(); it != _options.end(); ++it) {
if(it->option == opt)
return &(*it);
}
return 0;
}
bool Tins::DHCP::add_type_option(Flags type) {
return add_option(DHCP_MESSAGE_TYPE, sizeof(uint8_t), (const uint8_t*)&type);
}
bool Tins::DHCP::search_type_option(uint8_t *value) {
return generic_search(DHCP_MESSAGE_TYPE, value);
}
bool Tins::DHCP::add_server_identifier(uint32_t ip) {
return add_option(DHCP_SERVER_IDENTIFIER, sizeof(uint32_t), (const uint8_t*)&ip);
}
bool Tins::DHCP::search_server_identifier(uint32_t *value) {
return generic_search(DHCP_SERVER_IDENTIFIER, value);
}
bool Tins::DHCP::add_lease_time(uint32_t time) {
time = Utils::net_to_host_l(time);
return add_option(DHCP_LEASE_TIME, sizeof(uint32_t), (const uint8_t*)&time);
}
bool Tins::DHCP::search_lease_time(uint32_t *value) {
if(generic_search(DHCP_LEASE_TIME, value)) {
*value = Utils::net_to_host_l(*value);
return true;
}
return false;
}
bool Tins::DHCP::add_renewal_time(uint32_t time) {
time = Utils::net_to_host_l(time);
return add_option(DHCP_RENEWAL_TIME, sizeof(uint32_t), (const uint8_t*)&time);
}
bool Tins::DHCP::search_renewal_time(uint32_t *value) {
if(generic_search(DHCP_RENEWAL_TIME, value)) {
*value = Utils::net_to_host_l(*value);
return true;
}
return false;
}
bool Tins::DHCP::add_subnet_mask(uint32_t mask) {
return add_option(SUBNET_MASK, sizeof(uint32_t), (const uint8_t*)&mask);
}
bool Tins::DHCP::search_subnet_mask(uint32_t *value) {
return generic_search(SUBNET_MASK, value);
}
bool Tins::DHCP::add_routers_option(const list<uint32_t> &routers) {
uint32_t size;
uint8_t *buffer = serialize_list(routers, size);
bool ret = add_option(ROUTERS, size, buffer);
delete[] buffer;
return ret;
}
bool Tins::DHCP::search_routers_option(std::list<uint32_t> *routers) {
return generic_search(ROUTERS, routers);
}
bool Tins::DHCP::add_dns_option(const list<uint32_t> &dns) {
uint32_t size;
uint8_t *buffer = serialize_list(dns, size);
bool ret = add_option(DOMAIN_NAME_SERVERS, size, buffer);
delete[] buffer;
return ret;
}
bool Tins::DHCP::search_dns_option(std::list<uint32_t> *dns) {
return generic_search(DOMAIN_NAME_SERVERS, dns);
}
bool Tins::DHCP::add_broadcast_option(uint32_t addr) {
return add_option(BROADCAST_ADDRESS, 4, (uint8_t*)&addr);
}
bool Tins::DHCP::search_broadcast_option(uint32_t *value) {
return generic_search(BROADCAST_ADDRESS, value);
}
bool Tins::DHCP::add_domain_name(const string &name) {
return add_option(DOMAIN_NAME, name.size(), (const uint8_t*)name.c_str());
}
bool Tins::DHCP::search_domain_name(std::string *value) {
return generic_search(DOMAIN_NAME, value);
}
uint8_t *Tins::DHCP::serialize_list(const list<uint32_t> &int_list, uint32_t &sz) {
uint8_t *buffer = new uint8_t[int_list.size() * sizeof(uint32_t)];
uint32_t *ptr = (uint32_t*)buffer;
for(list<uint32_t>::const_iterator it = int_list.begin(); it != int_list.end(); ++it)
*(ptr++) = *it;
sz = sizeof(uint32_t) * int_list.size();
return buffer;
}
uint32_t Tins::DHCP::header_size() const {
return BootP::header_size() - vend_size() + _size;
}
void Tins::DHCP::write_serialization(uint8_t *buffer, uint32_t total_sz, const PDU *parent) {
assert(total_sz >= header_size());
uint8_t *result = 0;
if(_size) {
result = new uint8_t[_size];
uint8_t *ptr = result + sizeof(uint32_t);
// Magic cookie
*((uint32_t*)result) = Utils::net_to_host_l(0x63825363);
for(std::list<DHCPOption>::const_iterator it = _options.begin(); it != _options.end(); ++it) {
*(ptr++) = it->option;
*(ptr++) = it->length;
if(it->length)
std::memcpy(ptr, it->value, it->length);
ptr += it->length;
}
// End of options
result[_size-1] = END;
vend(result, _size);
}
BootP::write_serialization(buffer, total_sz, parent);
delete[] result;
}
void Tins::DHCP::copy_fields(const DHCP *other) {
BootP::copy_bootp_fields(other);
_size = other->_size;
for(std::list<DHCPOption>::const_iterator it = other->_options.begin(); it != other->_options.end(); ++it)
_options.push_back(DHCPOption(it->option, it->length, it->value));
}
Tins::PDU *Tins::DHCP::clone_pdu() const {
DHCP *new_pdu = new DHCP();
new_pdu->copy_fields(this);
return new_pdu;
}
bool Tins::DHCP::generic_search(Options opt, std::list<uint32_t> *container) {
const DHCPOption *option = search_option(opt);
if(!option)
return false;
const uint32_t *ptr = (const uint32_t*)option->value;
uint32_t len = option->length;
if((len % sizeof(uint32_t)) != 0)
return false;
while(len) {
container->push_back(*(ptr++));
len -= sizeof(uint32_t);
}
return true;
}
bool Tins::DHCP::generic_search(Options opt, std::string *str) {
const DHCPOption *option = search_option(opt);
if(!option)
return false;
*str = string((const char*)option->value, option->length);
return true;
}
<commit_msg>Fixed endianness in some DHCP options.<commit_after>/*
* libtins is a net packet wrapper library for crafting and
* interpreting sniffed packets.
*
* Copyright (C) 2011 Nasel
*
* 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 <stdexcept>
#include <cstring>
#include <cassert>
#include "utils.h"
#include "dhcp.h"
#include "ethernetII.h"
const uint32_t Tins::DHCP::MAX_DHCP_SIZE = 312;
using namespace std;
/* Magic cookie: uint32_t.
* end of options: 1 byte. */
Tins::DHCP::DHCP() : _size(sizeof(uint32_t) + 1) {
opcode(BOOTREQUEST);
htype(1); //ethernet
hlen(EthernetII::ADDR_SIZE);
}
Tins::DHCP::DHCP(const uint8_t *buffer, uint32_t total_sz) : BootP(buffer, total_sz, 0), _size(sizeof(uint32_t) + 1){
buffer += BootP::header_size() - vend_size();
total_sz -= BootP::header_size() - vend_size();
uint8_t args[2] = {0};
if(total_sz < sizeof(uint32_t) || *(uint32_t*)buffer != Utils::net_to_host_l(0x63825363))
throw std::runtime_error("Not enough size for a DHCP header in the buffer.");
buffer += sizeof(uint32_t);
total_sz -= sizeof(uint32_t);
while(total_sz) {
for(unsigned i(0); i < 2; ++i) {
args[i] = *(buffer++);
total_sz--;
if(args[0] == END || args[0] == PAD)
i = 2;
else if(!total_sz)
throw std::runtime_error("Not enough size for a DHCP header in the buffer.");
}
// If the END-OF-OPTIONS was not found...
if(args[0] != END && args[0] != PAD) {
// Not enough size for this option
if(total_sz < args[1])
throw std::runtime_error("Not enough size for a DHCP header in the buffer.");
add_option((Options)args[0], args[1], buffer);
buffer += args[1];
total_sz -= args[1];
}
// Otherwise, break the loop.
else
total_sz = 0;
}
}
Tins::DHCP::DHCP(const DHCP &other) : BootP(other) {
copy_fields(&other);
}
Tins::DHCP &Tins::DHCP::operator= (const DHCP &other) {
copy_fields(&other);
copy_inner_pdu(other);
return *this;
}
Tins::DHCP::~DHCP() {
while(_options.size()) {
delete[] _options.front().value;
_options.pop_front();
}
}
Tins::DHCP::DHCPOption::DHCPOption(uint8_t opt, uint8_t len, const uint8_t *val) : option(opt), length(len) {
if(len) {
value = new uint8_t[len];
std::memcpy(value, val, len);
}
else
value = 0;
}
bool Tins::DHCP::add_option(Options opt, uint8_t len, const uint8_t *val) {
uint32_t opt_size = len + (sizeof(uint8_t) << 1);
if(_size + opt_size > MAX_DHCP_SIZE)
return false;
_options.push_back(DHCPOption((uint8_t)opt, len, val));
_size += opt_size;
return true;
}
const Tins::DHCP::DHCPOption *Tins::DHCP::search_option(Options opt) const{
for(std::list<DHCPOption>::const_iterator it = _options.begin(); it != _options.end(); ++it) {
if(it->option == opt)
return &(*it);
}
return 0;
}
bool Tins::DHCP::add_type_option(Flags type) {
return add_option(DHCP_MESSAGE_TYPE, sizeof(uint8_t), (const uint8_t*)&type);
}
bool Tins::DHCP::search_type_option(uint8_t *value) {
return generic_search(DHCP_MESSAGE_TYPE, value);
}
bool Tins::DHCP::add_server_identifier(uint32_t ip) {
ip = Utils::net_to_host_l(ip);
return add_option(DHCP_SERVER_IDENTIFIER, sizeof(uint32_t), (const uint8_t*)&ip);
}
bool Tins::DHCP::search_server_identifier(uint32_t *value) {
if(generic_search(DHCP_SERVER_IDENTIFIER, value)) {
*value = Utils::net_to_host_l(*value);
return true;
}
return false;
}
bool Tins::DHCP::add_lease_time(uint32_t time) {
time = Utils::net_to_host_l(time);
return add_option(DHCP_LEASE_TIME, sizeof(uint32_t), (const uint8_t*)&time);
}
bool Tins::DHCP::search_lease_time(uint32_t *value) {
if(generic_search(DHCP_LEASE_TIME, value)) {
*value = Utils::net_to_host_l(*value);
return true;
}
return false;
}
bool Tins::DHCP::add_renewal_time(uint32_t time) {
time = Utils::net_to_host_l(time);
return add_option(DHCP_RENEWAL_TIME, sizeof(uint32_t), (const uint8_t*)&time);
}
bool Tins::DHCP::search_renewal_time(uint32_t *value) {
if(generic_search(DHCP_RENEWAL_TIME, value)) {
*value = Utils::net_to_host_l(*value);
return true;
}
return false;
}
bool Tins::DHCP::add_subnet_mask(uint32_t mask) {
return add_option(SUBNET_MASK, sizeof(uint32_t), (const uint8_t*)&mask);
}
bool Tins::DHCP::search_subnet_mask(uint32_t *value) {
return generic_search(SUBNET_MASK, value);
}
bool Tins::DHCP::add_routers_option(const list<uint32_t> &routers) {
uint32_t size;
uint8_t *buffer = serialize_list(routers, size);
bool ret = add_option(ROUTERS, size, buffer);
delete[] buffer;
return ret;
}
bool Tins::DHCP::search_routers_option(std::list<uint32_t> *routers) {
return generic_search(ROUTERS, routers);
}
bool Tins::DHCP::add_dns_option(const list<uint32_t> &dns) {
uint32_t size;
uint8_t *buffer = serialize_list(dns, size);
bool ret = add_option(DOMAIN_NAME_SERVERS, size, buffer);
delete[] buffer;
return ret;
}
bool Tins::DHCP::search_dns_option(std::list<uint32_t> *dns) {
return generic_search(DOMAIN_NAME_SERVERS, dns);
}
bool Tins::DHCP::add_broadcast_option(uint32_t addr) {
return add_option(BROADCAST_ADDRESS, 4, (uint8_t*)&addr);
}
bool Tins::DHCP::search_broadcast_option(uint32_t *value) {
return generic_search(BROADCAST_ADDRESS, value);
}
bool Tins::DHCP::add_domain_name(const string &name) {
return add_option(DOMAIN_NAME, name.size(), (const uint8_t*)name.c_str());
}
bool Tins::DHCP::search_domain_name(std::string *value) {
return generic_search(DOMAIN_NAME, value);
}
uint8_t *Tins::DHCP::serialize_list(const list<uint32_t> &int_list, uint32_t &sz) {
uint8_t *buffer = new uint8_t[int_list.size() * sizeof(uint32_t)];
uint32_t *ptr = (uint32_t*)buffer;
for(list<uint32_t>::const_iterator it = int_list.begin(); it != int_list.end(); ++it)
*(ptr++) = Utils::net_to_host_l(*it);
sz = sizeof(uint32_t) * int_list.size();
return buffer;
}
uint32_t Tins::DHCP::header_size() const {
return BootP::header_size() - vend_size() + _size;
}
void Tins::DHCP::write_serialization(uint8_t *buffer, uint32_t total_sz, const PDU *parent) {
assert(total_sz >= header_size());
uint8_t *result = 0;
if(_size) {
result = new uint8_t[_size];
uint8_t *ptr = result + sizeof(uint32_t);
// Magic cookie
*((uint32_t*)result) = Utils::net_to_host_l(0x63825363);
for(std::list<DHCPOption>::const_iterator it = _options.begin(); it != _options.end(); ++it) {
*(ptr++) = it->option;
*(ptr++) = it->length;
if(it->length)
std::memcpy(ptr, it->value, it->length);
ptr += it->length;
}
// End of options
result[_size-1] = END;
vend(result, _size);
}
BootP::write_serialization(buffer, total_sz, parent);
delete[] result;
}
void Tins::DHCP::copy_fields(const DHCP *other) {
BootP::copy_bootp_fields(other);
_size = other->_size;
for(std::list<DHCPOption>::const_iterator it = other->_options.begin(); it != other->_options.end(); ++it)
_options.push_back(DHCPOption(it->option, it->length, it->value));
}
Tins::PDU *Tins::DHCP::clone_pdu() const {
DHCP *new_pdu = new DHCP();
new_pdu->copy_fields(this);
return new_pdu;
}
bool Tins::DHCP::generic_search(Options opt, std::list<uint32_t> *container) {
const DHCPOption *option = search_option(opt);
if(!option)
return false;
const uint32_t *ptr = (const uint32_t*)option->value;
uint32_t len = option->length;
if((len % sizeof(uint32_t)) != 0)
return false;
while(len) {
container->push_back(*(ptr++));
len -= sizeof(uint32_t);
}
return true;
}
bool Tins::DHCP::generic_search(Options opt, std::string *str) {
const DHCPOption *option = search_option(opt);
if(!option)
return false;
*str = string((const char*)option->value, option->length);
return true;
}
<|endoftext|> |
<commit_before>#include "../Block_Info.hxx"
#include "../../compute_block_grid_mapping.hxx"
Block_Info::Block_Info(const boost::filesystem::path &sdp_directory,
const size_t &procs_per_node)
{
boost::filesystem::ifstream block_stream(sdp_directory / "blocks");
if(!block_stream.good())
{
throw std::runtime_error("Could not open '"
+ (sdp_directory / "blocks").string() + "'");
}
read_vector(block_stream, dimensions);
read_vector(block_stream, degrees);
read_vector(block_stream, schur_block_sizes);
read_vector(block_stream, psd_matrix_block_sizes);
read_vector(block_stream, bilinear_pairing_block_sizes);
const size_t num_procs(El::mpi::Size(El::mpi::COMM_WORLD));
std::vector<Block_Cost> block_costs;
// Assume that the cost of a block is about N^3
for(size_t ii = 0; ii < schur_block_sizes.size(); ++ii)
{
block_costs.emplace_back(schur_block_sizes[ii] * schur_block_sizes[ii]
* schur_block_sizes[ii],
ii);
}
// Reverse sort, with largest first
std::sort(block_costs.rbegin(), block_costs.rend());
if(num_procs % procs_per_node != 0)
{
throw std::runtime_error(
"Incompatible number of processes and processes per node. "
"procs_per_node must evenly divide num_procs:\n\tnum_procs: "
+ std::to_string(num_procs)
+ "\n\tprocs_per_node: " + std::to_string(procs_per_node));
}
const size_t num_nodes(num_procs / procs_per_node);
std::vector<std::vector<Block_Map>> mapping(
compute_block_grid_mapping(procs_per_node, num_nodes, block_costs));
// Create an mpi::Group for each set of processors.
El::mpi::Group default_mpi_group;
El::mpi::CommGroup(El::mpi::COMM_WORLD, default_mpi_group);
int rank(El::mpi::Rank(El::mpi::COMM_WORLD));
if(rank==0)
{
std::stringstream ss;
ss << "Block Grid Mapping\n"
<< "Node\tNum Procs\tCost\t\tBlock List\n"
<< "==================================================\n";
for(size_t node = 0; node < mapping.size(); ++node)
{
for(auto &m : mapping[node])
{
ss << node << "\t" << m.num_procs << "\t\t"
<< m.cost / static_cast<double>(m.num_procs) << "\t{";
for(size_t ii = 0; ii < m.block_indices.size(); ++ii)
{
if(ii != 0)
{
ss << ",";
}
ss << m.block_indices[ii];
}
ss << "}\n";
}
ss << "\n";
}
El::Output(ss.str());
}
int rank_begin(0), rank_end(0);
for(auto &block_vector : mapping)
{
for(auto &block_map : block_vector)
{
rank_begin = rank_end;
rank_end += block_map.num_procs;
if(rank_end > rank)
{
block_indices = block_map.block_indices;
break;
}
}
if(!block_indices.empty())
{
break;
}
}
// If we have more nodes than blocks, we can end up with empty
// nodes. In that case, assign that node to a group by itself.
if(!(rank_end > rank))
{
rank_begin = rank;
rank_end = rank + 1;
}
{
std::vector<int> group_ranks(rank_end - rank_begin);
std::iota(group_ranks.begin(), group_ranks.end(), rank_begin);
El::mpi::Incl(default_mpi_group, group_ranks.size(), group_ranks.data(),
mpi_group);
}
El::mpi::Create(El::mpi::COMM_WORLD, mpi_group, mpi_comm);
}
<commit_msg>Use an N^2 cost model instead of N^3<commit_after>#include "../Block_Info.hxx"
#include "../../compute_block_grid_mapping.hxx"
Block_Info::Block_Info(const boost::filesystem::path &sdp_directory,
const size_t &procs_per_node)
{
boost::filesystem::ifstream block_stream(sdp_directory / "blocks");
if(!block_stream.good())
{
throw std::runtime_error("Could not open '"
+ (sdp_directory / "blocks").string() + "'");
}
read_vector(block_stream, dimensions);
read_vector(block_stream, degrees);
read_vector(block_stream, schur_block_sizes);
read_vector(block_stream, psd_matrix_block_sizes);
read_vector(block_stream, bilinear_pairing_block_sizes);
const size_t num_procs(El::mpi::Size(El::mpi::COMM_WORLD));
std::vector<Block_Cost> block_costs;
// The dominant cost is squaring schur_off_diag to compute Q. Each
// block of schur_off_diag has dimensions
//
// schur_block_sizes[ii] * Q.Height()
//
// So the total cost for squaring that particular block is
//
// schur_block_sizes[ii] * (schur_block_sizes[ii] * Q.Height())
//
// Q.Height() is the same for all blocks, so we can factor it out.
// This means that the cost scales as the square of the size of the
// block.
for(size_t ii = 0; ii < schur_block_sizes.size(); ++ii)
{
block_costs.emplace_back(schur_block_sizes[ii] * schur_block_sizes[ii],
ii);
}
// for(size_t rank = 0; rank < num_procs; ++rank)
// {
// for(size_t ii = rank; ii < schur_block_sizes.size(); ii += num_procs)
// {
// block_costs.emplace_back(1, ii);
// }
// }
// Reverse sort, with largest first
std::sort(block_costs.rbegin(), block_costs.rend());
if(num_procs % procs_per_node != 0)
{
throw std::runtime_error(
"Incompatible number of processes and processes per node. "
"procs_per_node must evenly divide num_procs:\n\tnum_procs: "
+ std::to_string(num_procs)
+ "\n\tprocs_per_node: " + std::to_string(procs_per_node));
}
const size_t num_nodes(num_procs / procs_per_node);
std::vector<std::vector<Block_Map>> mapping(
compute_block_grid_mapping(procs_per_node, num_nodes, block_costs));
// Create an mpi::Group for each set of processors.
El::mpi::Group default_mpi_group;
El::mpi::CommGroup(El::mpi::COMM_WORLD, default_mpi_group);
int rank(El::mpi::Rank(El::mpi::COMM_WORLD));
if(rank == 0)
{
std::stringstream ss;
ss << "Block Grid Mapping\n"
<< "Node\tNum Procs\tCost\t\tBlock List\n"
<< "==================================================\n";
for(size_t node = 0; node < mapping.size(); ++node)
{
for(auto &m : mapping[node])
{
ss << node << "\t" << m.num_procs << "\t\t"
<< m.cost / static_cast<double>(m.num_procs) << "\t{";
for(size_t ii = 0; ii < m.block_indices.size(); ++ii)
{
if(ii != 0)
{
ss << ",";
}
ss << m.block_indices[ii];
}
ss << "}\n";
}
ss << "\n";
}
El::Output(ss.str());
}
int rank_begin(0), rank_end(0);
for(auto &block_vector : mapping)
{
for(auto &block_map : block_vector)
{
rank_begin = rank_end;
rank_end += block_map.num_procs;
if(rank_end > rank)
{
block_indices = block_map.block_indices;
break;
}
}
if(!block_indices.empty())
{
break;
}
}
// If we have more nodes than blocks, we can end up with empty
// nodes. In that case, assign that node to a group by itself.
if(!(rank_end > rank))
{
rank_begin = rank;
rank_end = rank + 1;
}
{
std::vector<int> group_ranks(rank_end - rank_begin);
std::iota(group_ranks.begin(), group_ranks.end(), rank_begin);
El::mpi::Incl(default_mpi_group, group_ranks.size(), group_ranks.data(),
mpi_group);
}
El::mpi::Create(El::mpi::COMM_WORLD, mpi_group, mpi_comm);
}
<|endoftext|> |
<commit_before>#include "../Block_Info.hxx"
#include "../../compute_block_grid_mapping.hxx"
Block_Info::Block_Info(const boost::filesystem::path &sdp_directory,
const size_t &procs_per_node)
{
boost::filesystem::ifstream block_stream(sdp_directory / "blocks");
if(!block_stream.good())
{
throw std::runtime_error("Could not open '"
+ (sdp_directory / "blocks").string() + "'");
}
read_vector(block_stream, dimensions);
read_vector(block_stream, degrees);
read_vector(block_stream, schur_block_sizes);
read_vector(block_stream, psd_matrix_block_sizes);
read_vector(block_stream, bilinear_pairing_block_sizes);
const size_t num_procs(El::mpi::Size(El::mpi::COMM_WORLD));
std::vector<Block_Cost> block_costs;
// The dominant cost is squaring schur_off_diag to compute Q. Each
// block of schur_off_diag has dimensions
//
// schur_block_sizes[ii] * Q.Height()
//
// So the total cost for squaring that particular block is
//
// schur_block_sizes[ii] * (schur_block_sizes[ii] * Q.Height())
//
// Q.Height() is the same for all blocks, so we can factor it out.
// This means that the cost scales as the square of the size of the
// block.
for(size_t ii = 0; ii < schur_block_sizes.size(); ++ii)
{
block_costs.emplace_back(schur_block_sizes[ii] * schur_block_sizes[ii],
ii);
}
// for(size_t rank = 0; rank < num_procs; ++rank)
// {
// for(size_t ii = rank; ii < schur_block_sizes.size(); ii += num_procs)
// {
// block_costs.emplace_back(1, ii);
// }
// }
// Reverse sort, with largest first
std::sort(block_costs.rbegin(), block_costs.rend());
if(num_procs % procs_per_node != 0)
{
throw std::runtime_error(
"Incompatible number of processes and processes per node. "
"procs_per_node must evenly divide num_procs:\n\tnum_procs: "
+ std::to_string(num_procs)
+ "\n\tprocs_per_node: " + std::to_string(procs_per_node));
}
const size_t num_nodes(num_procs / procs_per_node);
std::vector<std::vector<Block_Map>> mapping(
compute_block_grid_mapping(procs_per_node, num_nodes, block_costs));
// Create an mpi::Group for each set of processors.
El::mpi::Group default_mpi_group;
El::mpi::CommGroup(El::mpi::COMM_WORLD, default_mpi_group);
int rank(El::mpi::Rank(El::mpi::COMM_WORLD));
if(rank == 0)
{
std::stringstream ss;
ss << "Block Grid Mapping\n"
<< "Node\tNum Procs\tCost\t\tBlock List\n"
<< "==================================================\n";
for(size_t node = 0; node < mapping.size(); ++node)
{
for(auto &m : mapping[node])
{
ss << node << "\t" << m.num_procs << "\t\t"
<< m.cost / static_cast<double>(m.num_procs) << "\t{";
for(size_t ii = 0; ii < m.block_indices.size(); ++ii)
{
if(ii != 0)
{
ss << ",";
}
ss << m.block_indices[ii];
}
ss << "}\n";
}
ss << "\n";
}
El::Output(ss.str());
}
int rank_begin(0), rank_end(0);
for(auto &block_vector : mapping)
{
for(auto &block_map : block_vector)
{
rank_begin = rank_end;
rank_end += block_map.num_procs;
if(rank_end > rank)
{
block_indices = block_map.block_indices;
break;
}
}
if(!block_indices.empty())
{
break;
}
}
// If we have more nodes than blocks, we can end up with empty
// nodes. In that case, assign that node to a group by itself.
if(!(rank_end > rank))
{
rank_begin = rank;
rank_end = rank + 1;
}
{
std::vector<int> group_ranks(rank_end - rank_begin);
std::iota(group_ranks.begin(), group_ranks.end(), rank_begin);
El::mpi::Incl(default_mpi_group, group_ranks.size(), group_ranks.data(),
mpi_group);
}
El::mpi::Create(El::mpi::COMM_WORLD, mpi_group, mpi_comm);
}
<commit_msg>Update scaling costs in Block_Info to be n*(q + n)<commit_after>#include "../Block_Info.hxx"
#include "../../compute_block_grid_mapping.hxx"
Block_Info::Block_Info(const boost::filesystem::path &sdp_directory,
const size_t &procs_per_node)
{
boost::filesystem::ifstream block_stream(sdp_directory / "blocks");
if(!block_stream.good())
{
throw std::runtime_error("Could not open '"
+ (sdp_directory / "blocks").string() + "'");
}
read_vector(block_stream, dimensions);
read_vector(block_stream, degrees);
read_vector(block_stream, schur_block_sizes);
read_vector(block_stream, psd_matrix_block_sizes);
read_vector(block_stream, bilinear_pairing_block_sizes);
boost::filesystem::ifstream objective_stream(sdp_directory / "objectives");
double temp;
size_t q;
objective_stream >> temp >> q;
if(!objective_stream.good())
{
throw std::runtime_error(
"Could not read the size of the dual objective from '"
+ (sdp_directory / "objectives").string() + "'");
}
const size_t num_procs(El::mpi::Size(El::mpi::COMM_WORLD));
std::vector<Block_Cost> block_costs;
// Two large costs are
// 1) Solving for schur_off_diag.
// 2) Squaring schur_off_diag to compute Q.
//
// If 'n' is the size o3 the schur block, and 'q' is the size of Q,
// then the cost of 1) is
//
// alpha*n*n*q
//
// while the cost of 2) is proportional to
//
// beta*n*q*q
//
// where alpha and beta are scaling constants. The total cost is then
//
// q*n*(beta*q + alpha*n)
//
// We are only interested in the cost of blocks relative to each
// other, so we can ignore the overall scaling of q
//
// n*(beta*q + alpha*n)
//
// The ratio of beta/alpha depends on things like the precision and
// the exact CPU being used. Empirically, I have measured values
// for beta/alpha between 1.05 and 1.17, so we use 1.1. To keep
// everything as integers, we set beta=11, alpha=10.
const size_t beta(11), alpha(10);
for(size_t block = 0; block < schur_block_sizes.size(); ++block)
{
block_costs.emplace_back(
schur_block_sizes[block]
* (beta * q + alpha * schur_block_sizes[block]),
block);
}
// This simulates round-robin by making everything cost the same but
// with a round-robin order.
// for(size_t rank = 0; rank < num_procs; ++rank)
// {
// for(size_t block = rank; block < schur_block_sizes.size(); block +=
// num_procs)
// {
// block_costs.emplace_back(1, block);
// }
// }
// Reverse sort, with largest first
std::sort(block_costs.rbegin(), block_costs.rend());
if(num_procs % procs_per_node != 0)
{
throw std::runtime_error(
"Incompatible number of processes and processes per node. "
"procs_per_node must evenly divide num_procs:\n\tnum_procs: "
+ std::to_string(num_procs)
+ "\n\tprocs_per_node: " + std::to_string(procs_per_node));
}
const size_t num_nodes(num_procs / procs_per_node);
std::vector<std::vector<Block_Map>> mapping(
compute_block_grid_mapping(procs_per_node, num_nodes, block_costs));
// Create an mpi::Group for each set of processors.
El::mpi::Group default_mpi_group;
El::mpi::CommGroup(El::mpi::COMM_WORLD, default_mpi_group);
int rank(El::mpi::Rank(El::mpi::COMM_WORLD));
if(rank == 0)
{
std::stringstream ss;
ss << "Block Grid Mapping\n"
<< "Node\tNum Procs\tCost\t\tBlock List\n"
<< "==================================================\n";
for(size_t node = 0; node < mapping.size(); ++node)
{
for(auto &m : mapping[node])
{
ss << node << "\t" << m.num_procs << "\t\t"
<< m.cost / static_cast<double>(m.num_procs) << "\t{";
for(size_t ii = 0; ii < m.block_indices.size(); ++ii)
{
if(ii != 0)
{
ss << ",";
}
ss << m.block_indices[ii];
}
ss << "}\n";
}
ss << "\n";
}
El::Output(ss.str());
}
int rank_begin(0), rank_end(0);
for(auto &block_vector : mapping)
{
for(auto &block_map : block_vector)
{
rank_begin = rank_end;
rank_end += block_map.num_procs;
if(rank_end > rank)
{
block_indices = block_map.block_indices;
break;
}
}
if(!block_indices.empty())
{
break;
}
}
// If we have more nodes than blocks, we can end up with empty
// nodes. In that case, assign that node to a group by itself.
if(!(rank_end > rank))
{
rank_begin = rank;
rank_end = rank + 1;
}
{
std::vector<int> group_ranks(rank_end - rank_begin);
std::iota(group_ranks.begin(), group_ranks.end(), rank_begin);
El::mpi::Incl(default_mpi_group, group_ranks.size(), group_ranks.data(),
mpi_group);
}
El::mpi::Create(El::mpi::COMM_WORLD, mpi_group, mpi_comm);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: mbilog - logging for mitk / openCherry
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 <list>
#include <ctime>
#include <string>
#include <iomanip>
#include "mbilog.h"
static std::list<mbilog::AbstractBackend*> backends;
namespace mbilog {
static const std::string NA_STRING = "n/a";
}
void mbilog::RegisterBackend(mbilog::AbstractBackend* backend)
{
backends.push_back(backend);
}
void mbilog::UnregisterBackend(mbilog::AbstractBackend* backend)
{
backends.remove(backend);
}
static bool warningNoBackend = false;
void mbilog::DistributeToBackends(const mbilog::LogMessage &l)
{
if(backends.empty())
{
if(!warningNoBackend)
{
warningNoBackend = true;
std::cout << "mbilog ... receiving log messages, but still no backend registered, sending to std::cout\n";
}
mbilog::BackendCout::FormatFull(l);
return;
}
std::list<mbilog::AbstractBackend*>::iterator i;
for(i = backends.begin(); i != backends.end(); i++)
(*i)->ProcessMessage(l);
}
mbilog::BackendCout::BackendCout()
{
useFullOutput=false;
}
mbilog::BackendCout::~BackendCout()
{
}
void mbilog::BackendCout::SetFull(bool full)
{
useFullOutput = full;
}
void mbilog::BackendCout::ProcessMessage(const mbilog::LogMessage& l)
{
if(useFullOutput)
FormatFull(l);
else
FormatSmart(l);
}
void mbilog::BackendCout::FormatSmart(const LogMessage &l,int threadID)
{
switch(l.level)
{
case mbilog::Info:
std::cout << "INFO";
break;
case mbilog::Warn:
std::cout << "WARN";
break;
case mbilog::Error:
std::cout << "ERROR";
break;
case mbilog::Fatal:
std::cout << "FATAL";
break;
case mbilog::Debug:
std::cout << "DEBUG";
break;
}
std::cout << "[" << std::setw(7) << std::setprecision(3) << ((double)clock())/CLOCKS_PER_SEC;
if(threadID)
{
std::cout << ":" << std::hex << threadID;
}
if(!l.category.empty())
{
std::cout << ":" << l.category;
}
else
{
if(NA_STRING != l.moduleName)
{
std::cout << ":" << std::string(l.moduleName);
}
}
std::cout << "] ";
std::string msg(l.message);
int s=msg.size();
while(s>0 && msg[s-1]=='\n')
msg = msg.substr(0,--s);
std::cout << msg << std::endl;
}
void mbilog::BackendCout::FormatFull(const LogMessage &l,int threadID)
{
printf("%s(%d)",l.filePath,l.lineNumber);
printf(" func '%s'",l.functionName);
if(threadID)
{
printf(" thread %x",threadID);
}
if(strcmp(l.moduleName,"n/a"))
{
printf(" module '%s'",l.moduleName);
}
if(l.category.size()>0)
{
printf(" category '%s'",l.category.c_str());
}
printf(" %.3fs\n",((double)clock())/CLOCKS_PER_SEC);
switch(l.level)
{
case mbilog::Info:
printf("INFO: ");
break;
case mbilog::Warn:
printf("WARN: ");
break;
case mbilog::Error:
printf("ERROR: ");
break;
case mbilog::Fatal:
printf("FATAL: ");
break;
case mbilog::Debug:
printf("DEBUG: ");
break;
}
std::string msg=l.message;
int s=msg.size();
if(s>0)
if(msg[s-1]=='\n')
msg = msg.substr(0,s-1);
printf("%s\n",msg.c_str());
}
<commit_msg>COMP: removed another strcmp and all other printf statements<commit_after>/*=========================================================================
Program: mbilog - logging for mitk / openCherry
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 <list>
#include <ctime>
#include <string>
#include <iomanip>
#include "mbilog.h"
static std::list<mbilog::AbstractBackend*> backends;
namespace mbilog {
static const std::string NA_STRING = "n/a";
}
void mbilog::RegisterBackend(mbilog::AbstractBackend* backend)
{
backends.push_back(backend);
}
void mbilog::UnregisterBackend(mbilog::AbstractBackend* backend)
{
backends.remove(backend);
}
static bool warningNoBackend = false;
void mbilog::DistributeToBackends(const mbilog::LogMessage &l)
{
if(backends.empty())
{
if(!warningNoBackend)
{
warningNoBackend = true;
std::cout << "mbilog ... receiving log messages, but still no backend registered, sending to std::cout\n";
}
mbilog::BackendCout::FormatFull(l);
return;
}
std::list<mbilog::AbstractBackend*>::iterator i;
for(i = backends.begin(); i != backends.end(); i++)
(*i)->ProcessMessage(l);
}
mbilog::BackendCout::BackendCout()
{
useFullOutput=false;
}
mbilog::BackendCout::~BackendCout()
{
}
void mbilog::BackendCout::SetFull(bool full)
{
useFullOutput = full;
}
void mbilog::BackendCout::ProcessMessage(const mbilog::LogMessage& l)
{
if(useFullOutput)
FormatFull(l);
else
FormatSmart(l);
}
void mbilog::BackendCout::FormatSmart(const LogMessage &l,int threadID)
{
switch(l.level)
{
case mbilog::Info:
std::cout << "INFO";
break;
case mbilog::Warn:
std::cout << "WARN";
break;
case mbilog::Error:
std::cout << "ERROR";
break;
case mbilog::Fatal:
std::cout << "FATAL";
break;
case mbilog::Debug:
std::cout << "DEBUG";
break;
}
std::cout << "[" << std::setw(7) << std::setprecision(3) << ((double)std::clock())/CLOCKS_PER_SEC;
if(threadID)
{
std::cout << ":" << std::hex << threadID;
}
if(!l.category.empty())
{
std::cout << ":" << l.category;
}
else
{
if(NA_STRING != l.moduleName)
{
std::cout << ":" << std::string(l.moduleName);
}
}
std::cout << "] ";
std::size_t i = l.message.find_last_not_of(" \t\f\v\n\r");
std::cout << ((i =! std::string::npos) ? l.message.substr(0, i+1) : "") << std::endl;
}
void mbilog::BackendCout::FormatFull(const LogMessage &l,int threadID)
{
std::cout << std::string(l.filePath) << "(" << l.lineNumber << ")";
std::cout << " func '" << std::string(l.functionName) << "'";
if(threadID)
{
std::cout << " thread " << std::hex << threadID;
}
if(NA_STRING != l.moduleName)
{
std::cout << " module '" << std::string(l.moduleName) << "'";
}
if(!l.category.empty())
{
std::cout << " category '" << l.category << "'";
}
std::cout << std::setprecision(3) << ((double)std::clock())/CLOCKS_PER_SEC << "s\n";
switch(l.level)
{
case mbilog::Info:
std::cout << "INFO: ";
break;
case mbilog::Warn:
std::cout << "WARN: ";
break;
case mbilog::Error:
std::cout << "ERROR: ";
break;
case mbilog::Fatal:
std::cout << "FATAL: ";
break;
case mbilog::Debug:
std::cout << "DEBUG: ";
break;
}
std::size_t i = l.message.find_last_not_of(" \t\f\v\n\r");
std::cout << ((i =! std::string::npos) ? l.message.substr(0, i+1) : "") << std::endl;
}
<|endoftext|> |
<commit_before>/**
* @file llblocklist.cpp
* @brief List of the blocked avatars and objects.
*
* $LicenseInfo:firstyear=2012&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llblocklist.h"
#include "llavataractions.h"
#include "llblockedlistitem.h"
#include "llfloatersidepanelcontainer.h"
#include "llviewermenu.h"
static LLDefaultChildRegistry::Register<LLBlockList> r("block_list");
static const LLBlockListNameComparator NAME_COMPARATOR;
static const LLBlockListNameTypeComparator NAME_TYPE_COMPARATOR;
LLBlockList::LLBlockList(const Params& p)
: LLFlatListViewEx(p),
mSelectedItem(NULL),
mDirty(true)
{
LLMuteList::getInstance()->addObserver(this);
// Set up context menu.
LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
registrar.add ("Block.Action", boost::bind(&LLBlockList::onCustomAction, this, _2));
enable_registrar.add("Block.Enable", boost::bind(&LLBlockList::isActionEnabled, this, _2));
LLToggleableMenu* context_menu = LLUICtrlFactory::getInstance()->createFromFile<LLToggleableMenu>(
"menu_people_blocked_gear.xml",
gMenuHolder,
LLViewerMenuHolderGL::child_registry_t::instance());
if(context_menu)
{
mContextMenu = context_menu->getHandle();
}
}
LLBlockList::~LLBlockList()
{
if (mContextMenu.get())
{
mContextMenu.get()->die();
}
LLMuteList::getInstance()->removeObserver(this);
}
BOOL LLBlockList::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
BOOL handled = LLUICtrl::handleRightMouseDown(x, y, mask);
LLToggleableMenu* context_menu = mContextMenu.get();
if (context_menu && size())
{
context_menu->buildDrawLabels();
context_menu->updateParent(LLMenuGL::sMenuContainer);
LLMenuGL::showPopup(this, context_menu, x, y);
}
return handled;
}
void LLBlockList::setNameFilter(const std::string& filter)
{
std::string filter_upper = filter;
LLStringUtil::toUpper(filter_upper);
if (mNameFilter != filter_upper)
{
mNameFilter = filter_upper;
setDirty();
}
}
void LLBlockList::sortByName()
{
setComparator(&NAME_COMPARATOR);
sort();
}
void LLBlockList::sortByType()
{
setComparator(&NAME_TYPE_COMPARATOR);
sort();
}
void LLBlockList::draw()
{
if (mDirty)
{
refresh();
}
LLFlatListView::draw();
}
void LLBlockList::addNewItem(const LLMute* mute)
{
LLBlockedListItem* item = new LLBlockedListItem(mute);
if (!mNameFilter.empty())
{
item->highlightName(mNameFilter);
}
addItem(item, item->getUUID(), ADD_BOTTOM);
}
void LLBlockList::refresh()
{
bool have_filter = !mNameFilter.empty();
// save selection to restore it after list rebuilt
LLUUID selected = getSelectedUUID();
// calling refresh may be initiated by removing currently selected item
// so select next item and save the selection to restore it after list rebuilt
if (!selectNextItemPair(false, true))
{
selectNextItemPair(true, true);
}
LLUUID next_selected = getSelectedUUID();
clear();
std::vector<LLMute> mutes = LLMuteList::instance().getMutes();
std::vector<LLMute>::const_iterator mute_it = mutes.begin();
for (; mute_it != mutes.end(); ++mute_it)
{
if (have_filter && !findInsensitive(mute_it->mName, mNameFilter))
continue;
addNewItem(&*mute_it);
}
if (getItemPair(selected))
{
// restore previously selected item
selectItemPair(getItemPair(selected), true);
}
else if (getItemPair(next_selected))
{
// previously selected item was removed, so select next item
selectItemPair(getItemPair(next_selected), true);
}
// Sort the list.
sort();
setDirty(false);
}
bool LLBlockList::findInsensitive(std::string haystack, const std::string& needle_upper)
{
LLStringUtil::toUpper(haystack);
return haystack.find(needle_upper) != std::string::npos;
}
LLBlockedListItem* LLBlockList::getBlockedItem() const
{
LLPanel* panel = LLFlatListView::getSelectedItem();
LLBlockedListItem* item = dynamic_cast<LLBlockedListItem*>(panel);
return item;
}
bool LLBlockList::isActionEnabled(const LLSD& userdata)
{
bool action_enabled = true;
const std::string command_name = userdata.asString();
if ("unblock_item" == command_name || "profile_item" == command_name)
{
action_enabled = getSelectedItem() != NULL;
}
return action_enabled;
}
void LLBlockList::onCustomAction(const LLSD& userdata)
{
if (!isActionEnabled(userdata))
{
return;
}
LLBlockedListItem* item = getBlockedItem();
const std::string command_name = userdata.asString();
if ("unblock_item" == command_name)
{
LLMute mute(item->getUUID(), item->getName());
LLMuteList::getInstance()->remove(mute);
}
else if ("profile_item" == command_name)
{
switch(item->getType())
{
case LLMute::AGENT:
LLAvatarActions::showProfile(item->getUUID());
break;
case LLMute::OBJECT:
LLFloaterSidePanelContainer::showPanel("inventory", LLSD().with("id", item->getUUID()));
break;
default:
break;
}
}
}
bool LLBlockListItemComparator::compare(const LLPanel* item1, const LLPanel* item2) const
{
const LLBlockedListItem* blocked_item1 = dynamic_cast<const LLBlockedListItem*>(item1);
const LLBlockedListItem* blocked_item2 = dynamic_cast<const LLBlockedListItem*>(item2);
if (!blocked_item1 || !blocked_item2)
{
llerror("blocked_item1 and blocked_item2 cannot be null", 0);
return true;
}
return doCompare(blocked_item1, blocked_item2);
}
bool LLBlockListNameComparator::doCompare(const LLBlockedListItem* blocked_item1, const LLBlockedListItem* blocked_item2) const
{
std::string name1 = blocked_item1->getName();
std::string name2 = blocked_item2->getName();
LLStringUtil::toUpper(name1);
LLStringUtil::toUpper(name2);
return name1 < name2;
}
bool LLBlockListNameTypeComparator::doCompare(const LLBlockedListItem* blocked_item1, const LLBlockedListItem* blocked_item2) const
{
LLMute::EType type1 = blocked_item1->getType();
LLMute::EType type2 = blocked_item2->getType();
// if mute type is LLMute::BY_NAME or LLMute::OBJECT it means that this mute is an object
bool both_mutes_are_objects = (LLMute::OBJECT == type1 || LLMute::BY_NAME == type1) && (LLMute::OBJECT == type2 || LLMute::BY_NAME == type2);
// mute types may be different, but since both LLMute::BY_NAME and LLMute::OBJECT types represent objects
// it's needed to perform additional checking of both_mutes_are_objects variable
if (type1 != type2 && !both_mutes_are_objects)
{
// objects in block list go first, so return true if mute type is not an avatar
return LLMute::AGENT != type1;
}
return NAME_COMPARATOR.compare(blocked_item1, blocked_item2);
}
<commit_msg>CHUI-136 ADDITIONAL FIX (Implement new design for blocked list on the people floater)<commit_after>/**
* @file llblocklist.cpp
* @brief List of the blocked avatars and objects.
*
* $LicenseInfo:firstyear=2012&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llblocklist.h"
#include "llavataractions.h"
#include "llblockedlistitem.h"
#include "llfloatersidepanelcontainer.h"
#include "llviewermenu.h"
static LLDefaultChildRegistry::Register<LLBlockList> r("block_list");
static const LLBlockListNameComparator NAME_COMPARATOR;
static const LLBlockListNameTypeComparator NAME_TYPE_COMPARATOR;
LLBlockList::LLBlockList(const Params& p)
: LLFlatListViewEx(p),
mSelectedItem(NULL),
mDirty(true)
{
LLMuteList::getInstance()->addObserver(this);
// Set up context menu.
LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
registrar.add ("Block.Action", boost::bind(&LLBlockList::onCustomAction, this, _2));
enable_registrar.add("Block.Enable", boost::bind(&LLBlockList::isActionEnabled, this, _2));
LLToggleableMenu* context_menu = LLUICtrlFactory::getInstance()->createFromFile<LLToggleableMenu>(
"menu_people_blocked_gear.xml",
gMenuHolder,
LLViewerMenuHolderGL::child_registry_t::instance());
if(context_menu)
{
mContextMenu = context_menu->getHandle();
}
}
LLBlockList::~LLBlockList()
{
if (mContextMenu.get())
{
mContextMenu.get()->die();
}
LLMuteList::getInstance()->removeObserver(this);
}
BOOL LLBlockList::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
BOOL handled = LLUICtrl::handleRightMouseDown(x, y, mask);
LLToggleableMenu* context_menu = mContextMenu.get();
if (context_menu && size())
{
context_menu->buildDrawLabels();
context_menu->updateParent(LLMenuGL::sMenuContainer);
LLMenuGL::showPopup(this, context_menu, x, y);
}
return handled;
}
void LLBlockList::setNameFilter(const std::string& filter)
{
std::string filter_upper = filter;
LLStringUtil::toUpper(filter_upper);
if (mNameFilter != filter_upper)
{
mNameFilter = filter_upper;
setDirty();
}
}
void LLBlockList::sortByName()
{
setComparator(&NAME_COMPARATOR);
sort();
}
void LLBlockList::sortByType()
{
setComparator(&NAME_TYPE_COMPARATOR);
sort();
}
void LLBlockList::draw()
{
if (mDirty)
{
refresh();
}
LLFlatListView::draw();
}
void LLBlockList::addNewItem(const LLMute* mute)
{
LLBlockedListItem* item = new LLBlockedListItem(mute);
if (!mNameFilter.empty())
{
item->highlightName(mNameFilter);
}
addItem(item, item->getUUID(), ADD_BOTTOM);
}
void LLBlockList::refresh()
{
bool have_filter = !mNameFilter.empty();
// save selection to restore it after list rebuilt
LLUUID selected = getSelectedUUID();
// calling refresh may be initiated by removing currently selected item
// so select next item and save the selection to restore it after list rebuilt
if (!selectNextItemPair(false, true))
{
selectNextItemPair(true, true);
}
LLUUID next_selected = getSelectedUUID();
clear();
std::vector<LLMute> mutes = LLMuteList::instance().getMutes();
std::vector<LLMute>::const_iterator mute_it = mutes.begin();
for (; mute_it != mutes.end(); ++mute_it)
{
if (have_filter && !findInsensitive(mute_it->mName, mNameFilter))
continue;
addNewItem(&*mute_it);
}
if (getItemPair(selected))
{
// restore previously selected item
selectItemPair(getItemPair(selected), true);
}
else if (getItemPair(next_selected))
{
// previously selected item was removed, so select next item
selectItemPair(getItemPair(next_selected), true);
}
// Sort the list.
sort();
setDirty(false);
}
bool LLBlockList::findInsensitive(std::string haystack, const std::string& needle_upper)
{
LLStringUtil::toUpper(haystack);
return haystack.find(needle_upper) != std::string::npos;
}
LLBlockedListItem* LLBlockList::getBlockedItem() const
{
LLPanel* panel = LLFlatListView::getSelectedItem();
LLBlockedListItem* item = dynamic_cast<LLBlockedListItem*>(panel);
return item;
}
bool LLBlockList::isActionEnabled(const LLSD& userdata)
{
bool action_enabled = true;
const std::string command_name = userdata.asString();
if ("profile_item" == command_name)
{
LLBlockedListItem* item = getBlockedItem();
action_enabled = item && (LLMute::AGENT == item->getType());
}
if ("unblock_item" == command_name)
{
action_enabled = getSelectedItem() != NULL;
}
return action_enabled;
}
void LLBlockList::onCustomAction(const LLSD& userdata)
{
if (!isActionEnabled(userdata))
{
return;
}
LLBlockedListItem* item = getBlockedItem();
const std::string command_name = userdata.asString();
if ("unblock_item" == command_name)
{
LLMute mute(item->getUUID(), item->getName());
LLMuteList::getInstance()->remove(mute);
}
else if ("profile_item" == command_name)
{
switch(item->getType())
{
case LLMute::AGENT:
LLAvatarActions::showProfile(item->getUUID());
break;
default:
break;
}
}
}
bool LLBlockListItemComparator::compare(const LLPanel* item1, const LLPanel* item2) const
{
const LLBlockedListItem* blocked_item1 = dynamic_cast<const LLBlockedListItem*>(item1);
const LLBlockedListItem* blocked_item2 = dynamic_cast<const LLBlockedListItem*>(item2);
if (!blocked_item1 || !blocked_item2)
{
llerror("blocked_item1 and blocked_item2 cannot be null", 0);
return true;
}
return doCompare(blocked_item1, blocked_item2);
}
bool LLBlockListNameComparator::doCompare(const LLBlockedListItem* blocked_item1, const LLBlockedListItem* blocked_item2) const
{
std::string name1 = blocked_item1->getName();
std::string name2 = blocked_item2->getName();
LLStringUtil::toUpper(name1);
LLStringUtil::toUpper(name2);
return name1 < name2;
}
bool LLBlockListNameTypeComparator::doCompare(const LLBlockedListItem* blocked_item1, const LLBlockedListItem* blocked_item2) const
{
LLMute::EType type1 = blocked_item1->getType();
LLMute::EType type2 = blocked_item2->getType();
// if mute type is LLMute::BY_NAME or LLMute::OBJECT it means that this mute is an object
bool both_mutes_are_objects = (LLMute::OBJECT == type1 || LLMute::BY_NAME == type1) && (LLMute::OBJECT == type2 || LLMute::BY_NAME == type2);
// mute types may be different, but since both LLMute::BY_NAME and LLMute::OBJECT types represent objects
// it's needed to perform additional checking of both_mutes_are_objects variable
if (type1 != type2 && !both_mutes_are_objects)
{
// objects in block list go first, so return true if mute type is not an avatar
return LLMute::AGENT != type1;
}
return NAME_COMPARATOR.compare(blocked_item1, blocked_item2);
}
<|endoftext|> |
<commit_before><commit_msg>STYLE<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.