text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.
#include <iostream>
#include <fstream>
#include <libOL/Chunks.h>
#include <libOL/Rofl.h>
#include <libOL/Keyframe.h>
void test_keyframe()
{
std::ifstream ifs("../../lol-spec/analysis2/keyframes/EUW1.1617523548.1.keyframe", std::ios::binary);
libol::Keyframe frame = libol::Keyframe::decode(ifs);
for(auto& player : frame.players) {
std::cout << player.summonerName << " as " << player.championName << std::endl;
}
}
void test_rofl() {
std::ifstream ifs("/Users/toulouse/code/lol/lmao/rofl/22923174.rofl", std::ios::binary);
libol::Rofl rofl = libol::Rofl::decode(ifs);
auto header0 = rofl.chunkHeaders[0];
auto chunk = rofl.getDecryptedChunk(ifs, header0);
}
int main(int argc, const char * argv[])
{
test_keyframe();
return 0;
}
<commit_msg>Fuck spaces<commit_after>// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.
#include <iostream>
#include <fstream>
#include <libOL/Chunks.h>
#include <libOL/Rofl.h>
#include <libOL/Keyframe.h>
void test_keyframe()
{
std::ifstream ifs("../../lol-spec/analysis2/keyframes/EUW1.1617523548.1.keyframe", std::ios::binary);
libol::Keyframe frame = libol::Keyframe::decode(ifs);
for(auto& player : frame.players) {
std::cout << player.summonerName << " as " << player.championName << std::endl;
}
}
void test_rofl() {
std::ifstream ifs("/Users/toulouse/code/lol/lmao/rofl/22923174.rofl", std::ios::binary);
libol::Rofl rofl = libol::Rofl::decode(ifs);
auto header0 = rofl.chunkHeaders[0];
auto chunk = rofl.getDecryptedChunk(ifs, header0);
}
int main(int argc, const char * argv[])
{
test_keyframe();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef slic3r_Utils_hpp_
#define slic3r_Utils_hpp_
#include <locale>
#include "libslic3r.h"
namespace Slic3r {
extern void set_logging_level(unsigned int level);
extern void trace(unsigned int level, const char *message);
extern void disable_multi_threading();
// Set a path with GUI resource files.
void set_var_dir(const std::string &path);
// Return a full path to the GUI resource files.
const std::string& var_dir();
// Return a full resource path for a file_name.
std::string var(const std::string &file_name);
// Set a path with various static definition data (for example the initial config bundles).
void set_resources_dir(const std::string &path);
// Return a full path to the resources directory.
const std::string& resources_dir();
// Set a path with GUI localization files.
void set_local_dir(const std::string &path);
// Return a full path to the localization directory.
const std::string& localization_dir();
// Set a path with preset files.
void set_data_dir(const std::string &path);
// Return a full path to the GUI resource files.
const std::string& data_dir();
// A special type for strings encoded in the local Windows 8-bit code page.
// This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.
typedef std::string local_encoded_string;
// Convert an UTF-8 encoded string into local coding.
// On Windows, the UTF-8 string is converted to a local 8-bit code page.
// On OSX and Linux, this function does no conversion and returns a copy of the source string.
extern local_encoded_string encode_path(const char *src);
extern std::string decode_path(const char *src);
extern std::string normalize_utf8_nfc(const char *src);
// Safely rename a file even if the target exists.
// On Windows, the file explorer (or anti-virus or whatever else) often locks the file
// for a short while, so the file may not be movable. Retry while we see recoverable errors.
extern int rename_file(const std::string &from, const std::string &to);
// Copy a file, adjust the access attributes, so that the target is writable.
extern int copy_file(const std::string &from, const std::string &to);
// File path / name / extension splitting utilities, working with UTF-8,
// to be published to Perl.
namespace PerlUtils {
// Get a file name including the extension.
extern std::string path_to_filename(const char *src);
// Get a file name without the extension.
extern std::string path_to_stem(const char *src);
// Get just the extension.
extern std::string path_to_extension(const char *src);
// Get a directory without the trailing slash.
extern std::string path_to_parent_path(const char *src);
};
// Timestamp formatted for header_slic3r_generated().
extern std::string timestamp_str();
// Standard "generated by Slic3r version xxx timestamp xxx" header string,
// to be placed at the top of Slic3r generated files.
inline std::string header_slic3r_generated() { return std::string("generated by " SLIC3R_FORK_NAME " " SLIC3R_VERSION " " ) + timestamp_str(); }
// getpid platform wrapper
extern unsigned get_current_pid();
template <typename Real>
Real round_nearest(Real value, unsigned int decimals)
{
Real res = (Real)0;
if (decimals == 0)
res = ::round(value);
else
{
Real power = ::pow((Real)10, (int)decimals);
res = ::round(value * power + (Real)0.5) / power;
}
return res;
}
// Compute the next highest power of 2 of 32-bit v
// http://graphics.stanford.edu/~seander/bithacks.html
inline uint16_t next_highest_power_of_2(uint16_t v)
{
if (v != 0)
-- v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
return ++ v;
}
inline uint32_t next_highest_power_of_2(uint32_t v)
{
if (v != 0)
-- v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return ++ v;
}
inline uint64_t next_highest_power_of_2(uint64_t v)
{
if (v != 0)
-- v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
return ++ v;
}
#ifdef __clang__
// On clang, the size_t is a type of its own, so we need to overload for size_t.
// On MSC, the size_t type aliases to uint64_t / uint32_t, so the following code
// gives a duplicate symbol error.
inline size_t next_highest_power_of_2(size_t v)
{
#if SSIZE_MAX == 9223372036854775807
static_assert(sizeof(size_t) == sizeof(uint64_t), "sizeof(size_t) == sizeof(uint64_t)");
return next_highest_power_of_2(uint64_t(v));
#else
static_assert(sizeof(size_t) == sizeof(uint32_t), "sizeof(size_t) == sizeof(uint32_t)");
return next_highest_power_of_2(uint32_t(v));
#endif
}
#endif
extern std::string xml_escape(std::string text);
} // namespace Slic3r
#endif // slic3r_Utils_hpp_
<commit_msg>Fix clang build / detect standalone size_t<commit_after>#ifndef slic3r_Utils_hpp_
#define slic3r_Utils_hpp_
#include <locale>
#include <type_traits>
#include "libslic3r.h"
namespace Slic3r {
extern void set_logging_level(unsigned int level);
extern void trace(unsigned int level, const char *message);
extern void disable_multi_threading();
// Set a path with GUI resource files.
void set_var_dir(const std::string &path);
// Return a full path to the GUI resource files.
const std::string& var_dir();
// Return a full resource path for a file_name.
std::string var(const std::string &file_name);
// Set a path with various static definition data (for example the initial config bundles).
void set_resources_dir(const std::string &path);
// Return a full path to the resources directory.
const std::string& resources_dir();
// Set a path with GUI localization files.
void set_local_dir(const std::string &path);
// Return a full path to the localization directory.
const std::string& localization_dir();
// Set a path with preset files.
void set_data_dir(const std::string &path);
// Return a full path to the GUI resource files.
const std::string& data_dir();
// A special type for strings encoded in the local Windows 8-bit code page.
// This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.
typedef std::string local_encoded_string;
// Convert an UTF-8 encoded string into local coding.
// On Windows, the UTF-8 string is converted to a local 8-bit code page.
// On OSX and Linux, this function does no conversion and returns a copy of the source string.
extern local_encoded_string encode_path(const char *src);
extern std::string decode_path(const char *src);
extern std::string normalize_utf8_nfc(const char *src);
// Safely rename a file even if the target exists.
// On Windows, the file explorer (or anti-virus or whatever else) often locks the file
// for a short while, so the file may not be movable. Retry while we see recoverable errors.
extern int rename_file(const std::string &from, const std::string &to);
// Copy a file, adjust the access attributes, so that the target is writable.
extern int copy_file(const std::string &from, const std::string &to);
// File path / name / extension splitting utilities, working with UTF-8,
// to be published to Perl.
namespace PerlUtils {
// Get a file name including the extension.
extern std::string path_to_filename(const char *src);
// Get a file name without the extension.
extern std::string path_to_stem(const char *src);
// Get just the extension.
extern std::string path_to_extension(const char *src);
// Get a directory without the trailing slash.
extern std::string path_to_parent_path(const char *src);
};
// Timestamp formatted for header_slic3r_generated().
extern std::string timestamp_str();
// Standard "generated by Slic3r version xxx timestamp xxx" header string,
// to be placed at the top of Slic3r generated files.
inline std::string header_slic3r_generated() { return std::string("generated by " SLIC3R_FORK_NAME " " SLIC3R_VERSION " " ) + timestamp_str(); }
// getpid platform wrapper
extern unsigned get_current_pid();
template <typename Real>
Real round_nearest(Real value, unsigned int decimals)
{
Real res = (Real)0;
if (decimals == 0)
res = ::round(value);
else
{
Real power = ::pow((Real)10, (int)decimals);
res = ::round(value * power + (Real)0.5) / power;
}
return res;
}
// Compute the next highest power of 2 of 32-bit v
// http://graphics.stanford.edu/~seander/bithacks.html
inline uint16_t next_highest_power_of_2(uint16_t v)
{
if (v != 0)
-- v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
return ++ v;
}
inline uint32_t next_highest_power_of_2(uint32_t v)
{
if (v != 0)
-- v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return ++ v;
}
inline uint64_t next_highest_power_of_2(uint64_t v)
{
if (v != 0)
-- v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
return ++ v;
}
// On some implementations (such as some versions of clang), the size_t is a type of its own, so we need to overload for size_t.
// Typically, though, the size_t type aliases to uint64_t / uint32_t.
// We distinguish that here and provide implementation for size_t if and only if it is a distinct type
template<class T> size_t next_highest_power_of_2(T v,
typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, // T is size_t
typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, // T is not uint64_t
typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, // T is not uint32_t
typename std::enable_if<sizeof(T) == 8, T>::type = 0) // T is 64 bits
{
return next_highest_power_of_2(uint64_t(v));
}
template<class T> size_t next_highest_power_of_2(T v,
typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, // T is size_t
typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, // T is not uint64_t
typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, // T is not uint32_t
typename std::enable_if<sizeof(T) == 4, T>::type = 0) // T is 32 bits
{
return next_highest_power_of_2(uint32_t(v));
}
extern std::string xml_escape(std::string text);
} // namespace Slic3r
#endif // slic3r_Utils_hpp_
<|endoftext|> |
<commit_before>#include "globals.hh"
#include "util.hh"
#include "archive.hh"
#include "args.hh"
#include <algorithm>
#include <map>
#include <thread>
#include <dlfcn.h>
namespace nix {
/* The default location of the daemon socket, relative to nixStateDir.
The socket is in a directory to allow you to control access to the
Nix daemon by setting the mode/ownership of the directory
appropriately. (This wouldn't work on the socket itself since it
must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"
/* chroot-like behavior from Apple's sandbox */
#if __APPLE__
#define DEFAULT_ALLOWED_IMPURE_PREFIXES "/System/Library /usr/lib /dev /bin/sh"
#else
#define DEFAULT_ALLOWED_IMPURE_PREFIXES ""
#endif
Settings settings;
static GlobalConfig::Register r1(&settings);
Settings::Settings()
: nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR").value_or(NIX_LIBEXEC_DIR)))
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(nixStateDir + DEFAULT_SOCKET_PATH))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) {
caFile = fn;
break;
}
}
/* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s) {
Strings ss;
for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p);
builders = concatStringsSep(" ", ss);
}
#if defined(__linux__) && defined(SANDBOX_SHELL)
sandboxPaths = tokenizeString<StringSet>("/bin/sh=" SANDBOX_SHELL);
#endif
allowedImpureHostPrefixes = tokenizeString<StringSet>(DEFAULT_ALLOWED_IMPURE_PREFIXES);
}
void loadConfFile()
{
globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf");
/* We only want to send overrides to the daemon, i.e. stuff from
~/.nix/nix.conf or the command line. */
globalConfig.resetOverriden();
auto dirs = getConfigDirs();
// Iterate over them in reverse so that the ones appearing first in the path take priority
for (auto dir = dirs.rbegin(); dir != dirs.rend(); dir++) {
globalConfig.applyConfigFile(*dir + "/nix/nix.conf");
}
}
unsigned int Settings::getDefaultCores()
{
return std::max(1U, std::thread::hardware_concurrency());
}
StringSet Settings::getDefaultSystemFeatures()
{
/* For backwards compatibility, accept some "features" that are
used in Nixpkgs to route builds to certain machines but don't
actually require anything special on the machines. */
StringSet features{"nixos-test", "benchmark", "big-parallel", "recursive-nix"};
#if __linux__
if (access("/dev/kvm", R_OK | W_OK) == 0)
features.insert("kvm");
#endif
return features;
}
bool Settings::isExperimentalFeatureEnabled(const std::string & name)
{
auto & f = experimentalFeatures.get();
return std::find(f.begin(), f.end(), name) != f.end();
}
void Settings::requireExperimentalFeature(const std::string & name)
{
if (!isExperimentalFeatureEnabled(name))
throw Error("experimental Nix feature '%s' is disabled", name);
}
bool Settings::isWSL1()
{
struct utsname utsbuf;
uname(&utsbuf);
// WSL1 uses -Microsoft suffix
// WSL2 uses -microsoft-standard suffix
return hasSuffix(utsbuf.release, "-Microsoft");
}
const string nixVersion = PACKAGE_VERSION;
template<> void BaseSetting<SandboxMode>::set(const std::string & str)
{
if (str == "true") value = smEnabled;
else if (str == "relaxed") value = smRelaxed;
else if (str == "false") value = smDisabled;
else throw UsageError("option '%s' has invalid value '%s'", name, str);
}
template<> std::string BaseSetting<SandboxMode>::to_string() const
{
if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false";
else abort();
}
template<> void BaseSetting<SandboxMode>::toJSON(JSONPlaceholder & out)
{
AbstractSetting::toJSON(out);
}
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{
args.mkFlag()
.longName(name)
.description("Enable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smEnabled); })
.category(category);
args.mkFlag()
.longName("no-" + name)
.description("Disable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smDisabled); })
.category(category);
args.mkFlag()
.longName("relaxed-" + name)
.description("Enable sandboxing, but allow builds to disable it.")
.handler([=](std::vector<std::string> ss) { override(smRelaxed); })
.category(category);
}
void MaxBuildJobsSetting::set(const std::string & str)
{
if (str == "auto") value = std::max(1U, std::thread::hardware_concurrency());
else if (!string2Int(str, value))
throw UsageError("configuration setting '%s' should be 'auto' or an integer", name);
}
void initPlugins()
{
for (const auto & pluginFile : settings.pluginFiles.get()) {
Paths pluginFiles;
try {
auto ents = readDirectory(pluginFile);
for (const auto & ent : ents)
pluginFiles.emplace_back(pluginFile + "/" + ent.name);
} catch (SysError & e) {
if (e.errNo != ENOTDIR)
throw;
pluginFiles.emplace_back(pluginFile);
}
for (const auto & file : pluginFiles) {
/* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */
void *handle =
dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
throw Error("could not dynamically open plugin file '%s': %s", file, dlerror());
}
}
/* Since plugins can add settings, try to re-apply previously
unknown settings. */
globalConfig.reapplyUnknownSettings();
globalConfig.warnUnknownSettings();
}
}
<commit_msg>globals: Add missing include for uname()<commit_after>#include "globals.hh"
#include "util.hh"
#include "archive.hh"
#include "args.hh"
#include <algorithm>
#include <map>
#include <thread>
#include <dlfcn.h>
#include <sys/utsname.h>
namespace nix {
/* The default location of the daemon socket, relative to nixStateDir.
The socket is in a directory to allow you to control access to the
Nix daemon by setting the mode/ownership of the directory
appropriately. (This wouldn't work on the socket itself since it
must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"
/* chroot-like behavior from Apple's sandbox */
#if __APPLE__
#define DEFAULT_ALLOWED_IMPURE_PREFIXES "/System/Library /usr/lib /dev /bin/sh"
#else
#define DEFAULT_ALLOWED_IMPURE_PREFIXES ""
#endif
Settings settings;
static GlobalConfig::Register r1(&settings);
Settings::Settings()
: nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR").value_or(NIX_LIBEXEC_DIR)))
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(nixStateDir + DEFAULT_SOCKET_PATH))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) {
caFile = fn;
break;
}
}
/* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s) {
Strings ss;
for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p);
builders = concatStringsSep(" ", ss);
}
#if defined(__linux__) && defined(SANDBOX_SHELL)
sandboxPaths = tokenizeString<StringSet>("/bin/sh=" SANDBOX_SHELL);
#endif
allowedImpureHostPrefixes = tokenizeString<StringSet>(DEFAULT_ALLOWED_IMPURE_PREFIXES);
}
void loadConfFile()
{
globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf");
/* We only want to send overrides to the daemon, i.e. stuff from
~/.nix/nix.conf or the command line. */
globalConfig.resetOverriden();
auto dirs = getConfigDirs();
// Iterate over them in reverse so that the ones appearing first in the path take priority
for (auto dir = dirs.rbegin(); dir != dirs.rend(); dir++) {
globalConfig.applyConfigFile(*dir + "/nix/nix.conf");
}
}
unsigned int Settings::getDefaultCores()
{
return std::max(1U, std::thread::hardware_concurrency());
}
StringSet Settings::getDefaultSystemFeatures()
{
/* For backwards compatibility, accept some "features" that are
used in Nixpkgs to route builds to certain machines but don't
actually require anything special on the machines. */
StringSet features{"nixos-test", "benchmark", "big-parallel", "recursive-nix"};
#if __linux__
if (access("/dev/kvm", R_OK | W_OK) == 0)
features.insert("kvm");
#endif
return features;
}
bool Settings::isExperimentalFeatureEnabled(const std::string & name)
{
auto & f = experimentalFeatures.get();
return std::find(f.begin(), f.end(), name) != f.end();
}
void Settings::requireExperimentalFeature(const std::string & name)
{
if (!isExperimentalFeatureEnabled(name))
throw Error("experimental Nix feature '%s' is disabled", name);
}
bool Settings::isWSL1()
{
struct utsname utsbuf;
uname(&utsbuf);
// WSL1 uses -Microsoft suffix
// WSL2 uses -microsoft-standard suffix
return hasSuffix(utsbuf.release, "-Microsoft");
}
const string nixVersion = PACKAGE_VERSION;
template<> void BaseSetting<SandboxMode>::set(const std::string & str)
{
if (str == "true") value = smEnabled;
else if (str == "relaxed") value = smRelaxed;
else if (str == "false") value = smDisabled;
else throw UsageError("option '%s' has invalid value '%s'", name, str);
}
template<> std::string BaseSetting<SandboxMode>::to_string() const
{
if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false";
else abort();
}
template<> void BaseSetting<SandboxMode>::toJSON(JSONPlaceholder & out)
{
AbstractSetting::toJSON(out);
}
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{
args.mkFlag()
.longName(name)
.description("Enable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smEnabled); })
.category(category);
args.mkFlag()
.longName("no-" + name)
.description("Disable sandboxing.")
.handler([=](std::vector<std::string> ss) { override(smDisabled); })
.category(category);
args.mkFlag()
.longName("relaxed-" + name)
.description("Enable sandboxing, but allow builds to disable it.")
.handler([=](std::vector<std::string> ss) { override(smRelaxed); })
.category(category);
}
void MaxBuildJobsSetting::set(const std::string & str)
{
if (str == "auto") value = std::max(1U, std::thread::hardware_concurrency());
else if (!string2Int(str, value))
throw UsageError("configuration setting '%s' should be 'auto' or an integer", name);
}
void initPlugins()
{
for (const auto & pluginFile : settings.pluginFiles.get()) {
Paths pluginFiles;
try {
auto ents = readDirectory(pluginFile);
for (const auto & ent : ents)
pluginFiles.emplace_back(pluginFile + "/" + ent.name);
} catch (SysError & e) {
if (e.errNo != ENOTDIR)
throw;
pluginFiles.emplace_back(pluginFile);
}
for (const auto & file : pluginFiles) {
/* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */
void *handle =
dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
throw Error("could not dynamically open plugin file '%s': %s", file, dlerror());
}
}
/* Since plugins can add settings, try to re-apply previously
unknown settings. */
globalConfig.reapplyUnknownSettings();
globalConfig.warnUnknownSettings();
}
}
<|endoftext|> |
<commit_before>#include "globals.hh"
#include "util.hh"
#include "archive.hh"
#include "args.hh"
#include <algorithm>
#include <map>
#include <thread>
#include <dlfcn.h>
#include <sys/utsname.h>
namespace nix {
/* The default location of the daemon socket, relative to nixStateDir.
The socket is in a directory to allow you to control access to the
Nix daemon by setting the mode/ownership of the directory
appropriately. (This wouldn't work on the socket itself since it
must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"
Settings settings;
static GlobalConfig::Register r1(&settings);
Settings::Settings()
: nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixUserConfFiles(getUserConfigFiles())
, nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR").value_or(NIX_LIBEXEC_DIR)))
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(nixStateDir + DEFAULT_SOCKET_PATH))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) {
caFile = fn;
break;
}
}
/* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s) {
Strings ss;
for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p);
builders = concatStringsSep(" ", ss);
}
#if defined(__linux__) && defined(SANDBOX_SHELL)
sandboxPaths = tokenizeString<StringSet>("/bin/sh=" SANDBOX_SHELL);
#endif
/* chroot-like behavior from Apple's sandbox */
#if __APPLE__
sandboxPaths = tokenizeString<StringSet>("/System/Library/Frameworks /System/Library/PrivateFrameworks /bin/sh /bin/bash /private/tmp /private/var/tmp /usr/lib");
allowedImpureHostPrefixes = tokenizeString<StringSet>("/System/Library /usr/lib /dev /bin/sh");
#endif
}
void loadConfFile()
{
globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf");
/* We only want to send overrides to the daemon, i.e. stuff from
~/.nix/nix.conf or the command line. */
globalConfig.resetOverriden();
auto files = settings.nixUserConfFiles;
for (auto file = files.rbegin(); file != files.rend(); file++) {
globalConfig.applyConfigFile(*file);
}
}
std::vector<Path> getUserConfigFiles()
{
// Use the paths specified in NIX_USER_CONF_FILES if it has been defined
auto nixConfFiles = getEnv("NIX_USER_CONF_FILES");
if (nixConfFiles.has_value()) {
return tokenizeString<std::vector<string>>(nixConfFiles.value(), ":");
}
// Use the paths specified by the XDG spec
std::vector<Path> files;
auto dirs = getConfigDirs();
for (auto & dir : dirs) {
files.insert(files.end(), dir + "/nix/nix.conf");
}
return files;
}
unsigned int Settings::getDefaultCores()
{
return std::max(1U, std::thread::hardware_concurrency());
}
StringSet Settings::getDefaultSystemFeatures()
{
/* For backwards compatibility, accept some "features" that are
used in Nixpkgs to route builds to certain machines but don't
actually require anything special on the machines. */
StringSet features{"nixos-test", "benchmark", "big-parallel", "recursive-nix"};
#if __linux__
if (access("/dev/kvm", R_OK | W_OK) == 0)
features.insert("kvm");
#endif
return features;
}
bool Settings::isExperimentalFeatureEnabled(const std::string & name)
{
auto & f = experimentalFeatures.get();
return std::find(f.begin(), f.end(), name) != f.end();
}
void Settings::requireExperimentalFeature(const std::string & name)
{
if (!isExperimentalFeatureEnabled(name))
throw Error("experimental Nix feature '%s' is disabled", name);
}
bool Settings::isWSL1()
{
struct utsname utsbuf;
uname(&utsbuf);
// WSL1 uses -Microsoft suffix
// WSL2 uses -microsoft-standard suffix
return hasSuffix(utsbuf.release, "-Microsoft");
}
const string nixVersion = PACKAGE_VERSION;
template<> void BaseSetting<SandboxMode>::set(const std::string & str)
{
if (str == "true") value = smEnabled;
else if (str == "relaxed") value = smRelaxed;
else if (str == "false") value = smDisabled;
else throw UsageError("option '%s' has invalid value '%s'", name, str);
}
template<> std::string BaseSetting<SandboxMode>::to_string() const
{
if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false";
else abort();
}
template<> void BaseSetting<SandboxMode>::toJSON(JSONPlaceholder & out)
{
AbstractSetting::toJSON(out);
}
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{
args.addFlag({
.longName = name,
.description = "Enable sandboxing.",
.category = category,
.handler = {[=]() { override(smEnabled); }}
});
args.addFlag({
.longName = "no-" + name,
.description = "Disable sandboxing.",
.category = category,
.handler = {[=]() { override(smDisabled); }}
});
args.addFlag({
.longName = "relaxed-" + name,
.description = "Enable sandboxing, but allow builds to disable it.",
.category = category,
.handler = {[=]() { override(smRelaxed); }}
});
}
void MaxBuildJobsSetting::set(const std::string & str)
{
if (str == "auto") value = std::max(1U, std::thread::hardware_concurrency());
else if (!string2Int(str, value))
throw UsageError("configuration setting '%s' should be 'auto' or an integer", name);
}
void initPlugins()
{
for (const auto & pluginFile : settings.pluginFiles.get()) {
Paths pluginFiles;
try {
auto ents = readDirectory(pluginFile);
for (const auto & ent : ents)
pluginFiles.emplace_back(pluginFile + "/" + ent.name);
} catch (SysError & e) {
if (e.errNo != ENOTDIR)
throw;
pluginFiles.emplace_back(pluginFile);
}
for (const auto & file : pluginFiles) {
/* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */
void *handle =
dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
throw Error("could not dynamically open plugin file '%s': %s", file, dlerror());
}
}
/* Since plugins can add settings, try to re-apply previously
unknown settings. */
globalConfig.reapplyUnknownSettings();
globalConfig.warnUnknownSettings();
}
}
<commit_msg>Show hint how to enable experimental features<commit_after>#include "globals.hh"
#include "util.hh"
#include "archive.hh"
#include "args.hh"
#include <algorithm>
#include <map>
#include <thread>
#include <dlfcn.h>
#include <sys/utsname.h>
namespace nix {
/* The default location of the daemon socket, relative to nixStateDir.
The socket is in a directory to allow you to control access to the
Nix daemon by setting the mode/ownership of the directory
appropriately. (This wouldn't work on the socket itself since it
must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"
Settings settings;
static GlobalConfig::Register r1(&settings);
Settings::Settings()
: nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixUserConfFiles(getUserConfigFiles())
, nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR").value_or(NIX_LIBEXEC_DIR)))
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(nixStateDir + DEFAULT_SOCKET_PATH))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) {
caFile = fn;
break;
}
}
/* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s) {
Strings ss;
for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p);
builders = concatStringsSep(" ", ss);
}
#if defined(__linux__) && defined(SANDBOX_SHELL)
sandboxPaths = tokenizeString<StringSet>("/bin/sh=" SANDBOX_SHELL);
#endif
/* chroot-like behavior from Apple's sandbox */
#if __APPLE__
sandboxPaths = tokenizeString<StringSet>("/System/Library/Frameworks /System/Library/PrivateFrameworks /bin/sh /bin/bash /private/tmp /private/var/tmp /usr/lib");
allowedImpureHostPrefixes = tokenizeString<StringSet>("/System/Library /usr/lib /dev /bin/sh");
#endif
}
void loadConfFile()
{
globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf");
/* We only want to send overrides to the daemon, i.e. stuff from
~/.nix/nix.conf or the command line. */
globalConfig.resetOverriden();
auto files = settings.nixUserConfFiles;
for (auto file = files.rbegin(); file != files.rend(); file++) {
globalConfig.applyConfigFile(*file);
}
}
std::vector<Path> getUserConfigFiles()
{
// Use the paths specified in NIX_USER_CONF_FILES if it has been defined
auto nixConfFiles = getEnv("NIX_USER_CONF_FILES");
if (nixConfFiles.has_value()) {
return tokenizeString<std::vector<string>>(nixConfFiles.value(), ":");
}
// Use the paths specified by the XDG spec
std::vector<Path> files;
auto dirs = getConfigDirs();
for (auto & dir : dirs) {
files.insert(files.end(), dir + "/nix/nix.conf");
}
return files;
}
unsigned int Settings::getDefaultCores()
{
return std::max(1U, std::thread::hardware_concurrency());
}
StringSet Settings::getDefaultSystemFeatures()
{
/* For backwards compatibility, accept some "features" that are
used in Nixpkgs to route builds to certain machines but don't
actually require anything special on the machines. */
StringSet features{"nixos-test", "benchmark", "big-parallel", "recursive-nix"};
#if __linux__
if (access("/dev/kvm", R_OK | W_OK) == 0)
features.insert("kvm");
#endif
return features;
}
bool Settings::isExperimentalFeatureEnabled(const std::string & name)
{
auto & f = experimentalFeatures.get();
return std::find(f.begin(), f.end(), name) != f.end();
}
void Settings::requireExperimentalFeature(const std::string & name)
{
if (!isExperimentalFeatureEnabled(name))
throw Error("experimental Nix feature '%1%' is disabled; use '--experimental-features %1%' to override", name);
}
bool Settings::isWSL1()
{
struct utsname utsbuf;
uname(&utsbuf);
// WSL1 uses -Microsoft suffix
// WSL2 uses -microsoft-standard suffix
return hasSuffix(utsbuf.release, "-Microsoft");
}
const string nixVersion = PACKAGE_VERSION;
template<> void BaseSetting<SandboxMode>::set(const std::string & str)
{
if (str == "true") value = smEnabled;
else if (str == "relaxed") value = smRelaxed;
else if (str == "false") value = smDisabled;
else throw UsageError("option '%s' has invalid value '%s'", name, str);
}
template<> std::string BaseSetting<SandboxMode>::to_string() const
{
if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false";
else abort();
}
template<> void BaseSetting<SandboxMode>::toJSON(JSONPlaceholder & out)
{
AbstractSetting::toJSON(out);
}
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{
args.addFlag({
.longName = name,
.description = "Enable sandboxing.",
.category = category,
.handler = {[=]() { override(smEnabled); }}
});
args.addFlag({
.longName = "no-" + name,
.description = "Disable sandboxing.",
.category = category,
.handler = {[=]() { override(smDisabled); }}
});
args.addFlag({
.longName = "relaxed-" + name,
.description = "Enable sandboxing, but allow builds to disable it.",
.category = category,
.handler = {[=]() { override(smRelaxed); }}
});
}
void MaxBuildJobsSetting::set(const std::string & str)
{
if (str == "auto") value = std::max(1U, std::thread::hardware_concurrency());
else if (!string2Int(str, value))
throw UsageError("configuration setting '%s' should be 'auto' or an integer", name);
}
void initPlugins()
{
for (const auto & pluginFile : settings.pluginFiles.get()) {
Paths pluginFiles;
try {
auto ents = readDirectory(pluginFile);
for (const auto & ent : ents)
pluginFiles.emplace_back(pluginFile + "/" + ent.name);
} catch (SysError & e) {
if (e.errNo != ENOTDIR)
throw;
pluginFiles.emplace_back(pluginFile);
}
for (const auto & file : pluginFiles) {
/* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */
void *handle =
dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
throw Error("could not dynamically open plugin file '%s': %s", file, dlerror());
}
}
/* Since plugins can add settings, try to re-apply previously
unknown settings. */
globalConfig.reapplyUnknownSettings();
globalConfig.warnUnknownSettings();
}
}
<|endoftext|> |
<commit_before>/*
* grass.cpp
*
* Created on: 2017年1月6日
* Author: zhuqian
*/
#include <materials/glass.h>
#include "paramset.h"
GlassMaterial* CreateGlassMaterial(const TextureParams&mp) {
std::shared_ptr<Texture<Float>>eta = mp.GetFloatTexture("eta", (1.0f));
std::shared_ptr<Texture<Spectrum>> r = mp.GetSpectrumTexture("Kr", Spectrum(1.0f));
std::shared_ptr<Texture<Spectrum>> t = mp.GetSpectrumTexture("Kt", Spectrum(1.0f));
std::shared_ptr<Texture<Float>> roughnessX = mp.GetFloatTexture("roughnessX", 1.0f);
std::shared_ptr<Texture<Float>> roughnessY = mp.GetFloatTexture("roughnessY", 1.0f);
Debug("[CreateGrassMaterial]");
return new GlassMaterial(r,t,eta,roughnessX,roughnessY);
}
<commit_msg>修改玻璃的默认粗糙度<commit_after>/*
* grass.cpp
*
* Created on: 2017年1月6日
* Author: zhuqian
*/
#include <materials/glass.h>
#include "paramset.h"
GlassMaterial* CreateGlassMaterial(const TextureParams&mp) {
std::shared_ptr<Texture<Float>>eta = mp.GetFloatTexture("eta", (1.0f));
std::shared_ptr<Texture<Spectrum>> r = mp.GetSpectrumTexture("Kr", Spectrum(1.0f));
std::shared_ptr<Texture<Spectrum>> t = mp.GetSpectrumTexture("Kt", Spectrum(1.0f));
std::shared_ptr<Texture<Float>> roughnessX = mp.GetFloatTexture("roughnessX", 0.0f);
std::shared_ptr<Texture<Float>> roughnessY = mp.GetFloatTexture("roughnessY", 0.0f);
Debug("[CreateGrassMaterial]");
return new GlassMaterial(r,t,eta,roughnessX,roughnessY);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Christian Menard
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#include "debug/Dtu.hh"
#include "debug/DtuBuf.hh"
#include "debug/DtuDetail.hh"
#include "debug/DtuPackets.hh"
#include "debug/DtuSysCalls.hh"
#include "debug/DtuPower.hh"
#include "mem/dtu/msg_unit.hh"
#include "mem/dtu/noc_addr.hh"
static const char *syscallNames[] = {
"CREATESRV",
"CREATESESS",
"CREATEGATE",
"CREATEVPE",
"ATTACHRB",
"DETACHRB",
"EXCHANGE",
"VPECTRL",
"DELEGATE",
"OBTAIN",
"ACTIVATE",
"REQMEM",
"DERIVEMEM",
"REVOKE",
"EXIT",
"NOOP",
};
void
MessageUnit::startTransmission(const Dtu::Command& cmd)
{
unsigned epid = cmd.epId;
Addr messageAddr = dtu.regs().get(CmdReg::DATA_ADDR);
Addr messageSize = dtu.regs().get(CmdReg::DATA_SIZE);
bool isReply = cmd.opcode == Dtu::CommandOpcode::REPLY;
/*
* If this endpoint is configured to send messages, we need to check
* credits. If it is configured to receive messages we do a reply and don't
* need to check credits.
*/
if (!isReply)
{
unsigned credits = dtu.regs().get(epid, EpReg::CREDITS);
unsigned maxMessageSize = dtu.regs().get(epid, EpReg::MAX_MSG_SIZE);
// TODO error handling
// TODO atm, we can send (nearly) arbitrary large replies
assert(messageSize + sizeof(Dtu::MessageHeader) <= maxMessageSize);
if (credits < maxMessageSize)
{
warn("pe%u.ep%u: Ignore send message command because there are not "
"enough credits", dtu.coreId, epid);
dtu.scheduleFinishOp(Cycles(1));
return;
}
DPRINTFS(DtuDetail, (&dtu), "EP%u pays %u credits\n",
epid, maxMessageSize);
// Pay some credits
credits -= maxMessageSize;
dtu.regs().set(epid, EpReg::CREDITS, credits);
}
unsigned targetCoreId;
unsigned targetEpId;
unsigned replyEpId;
uint64_t label;
uint64_t replyLabel;
if (isReply)
{
// pay for the functional request; TODO
/*
* We need to read the header of the received message from local memory
* to determine target core and enspoint ID. This would introduce a
* second local memory request and would make the control flow more
* complicated. To simplify things a functional request is used and an
* additional delay is payed.
*/
auto pkt = dtu.generateRequest(
dtu.translate(dtu.regs().get(epid, EpReg::BUF_RD_PTR)),
sizeof(Dtu::MessageHeader),
MemCmd::ReadReq);
dtu.sendFunctionalMemRequest(pkt);
auto h = pkt->getPtr<Dtu::MessageHeader>();
assert(h->flags & Dtu::REPLY_ENABLED);
targetCoreId = h->senderCoreId;
targetEpId = h->replyEpId; // send message to the reply EP
replyEpId = h->senderEpId; // and grant credits to the sender
// the receiver of the reply should get the label that he has set
label = h->replyLabel;
// replies don't have replies. so, we don't need that
replyLabel = 0;
// disable replies for this message
auto hpkt = dtu.generateRequest(
dtu.translate(dtu.regs().get(epid, EpReg::BUF_RD_PTR)),
sizeof(h->flags), MemCmd::WriteReq);
h->flags &= ~Dtu::REPLY_ENABLED;
memcpy(hpkt->getPtr<uint8_t>(), &h->flags, sizeof(h->flags));
dtu.sendFunctionalMemRequest(hpkt);
dtu.freeRequest(hpkt);
dtu.freeRequest(pkt);
}
else
{
targetCoreId = dtu.regs().get(epid, EpReg::TGT_COREID);
targetEpId = dtu.regs().get(epid, EpReg::TGT_EPID);
label = dtu.regs().get(epid, EpReg::LABEL);
replyLabel = dtu.regs().get(CmdReg::REPLY_LABEL);
replyEpId = dtu.regs().get(CmdReg::REPLY_EPID);
M5_VAR_USED unsigned maxMessageSize = dtu.regs().get(epid, EpReg::MAX_MSG_SIZE);
assert(messageSize + sizeof(Dtu::MessageHeader) <= maxMessageSize);
}
DPRINTFS(Dtu, (&dtu), "\e[1m[%s -> %u]\e[0m with EP%u of %#018lx:%lu\n",
isReply ? "rp" : "sd",
targetCoreId, epid, dtu.regs().get(CmdReg::DATA_ADDR), messageSize);
DPRINTFS(Dtu, (&dtu), " header: tgtEP=%u, lbl=%#018lx, rpLbl=%#018lx, rpEP=%u\n",
targetEpId, label, replyLabel, replyEpId);
Dtu::MessageHeader* header = new Dtu::MessageHeader;
if (isReply)
header->flags = Dtu::REPLY_FLAG | Dtu::GRANT_CREDITS_FLAG;
else
header->flags = Dtu::REPLY_ENABLED; // normal message
header->senderCoreId = static_cast<uint8_t>(dtu.coreId);
header->senderEpId = static_cast<uint8_t>(epid);
header->replyEpId = static_cast<uint8_t>(replyEpId);
header->length = static_cast<uint16_t>(messageSize);
header->label = static_cast<uint64_t>(label);
header->replyLabel = static_cast<uint64_t>(replyLabel);
assert(messageSize + sizeof(Dtu::MessageHeader) <= dtu.maxNocPacketSize);
// start the transfer of the payload
dtu.startTransfer(Dtu::TransferType::LOCAL_READ,
NocAddr(targetCoreId, targetEpId),
messageAddr,
messageSize,
NULL,
header,
dtu.startMsgTransferDelay);
}
void
MessageUnit::incrementReadPtr(unsigned epId)
{
Addr readPtr = dtu.regs().get(epId, EpReg::BUF_RD_PTR);
Addr bufferAddr = dtu.regs().get(epId, EpReg::BUF_ADDR);
Addr bufferSize = dtu.regs().get(epId, EpReg::BUF_SIZE);
Addr messageCount = dtu.regs().get(epId, EpReg::BUF_MSG_CNT);
unsigned maxMessageSize = dtu.regs().get(epId, EpReg::BUF_MSG_SIZE);
readPtr += maxMessageSize;
if (readPtr >= bufferAddr + bufferSize * maxMessageSize)
readPtr = bufferAddr;
DPRINTFS(DtuBuf, (&dtu), "EP%u: increment read pointer to %#018lx (msgCount=%u)\n",
epId,
readPtr,
messageCount - 1);
// TODO error handling
assert(messageCount != 0);
/*
* XXX Actually an additianally cycle is needed to update the register.
* We ignore this delay as it should have no or a very small influence
* on the performance of the simulated system.
*/
dtu.regs().set(epId, EpReg::BUF_RD_PTR, readPtr);
dtu.regs().set(epId, EpReg::BUF_MSG_CNT, messageCount - 1);
dtu.updateSuspendablePin();
}
bool
MessageUnit::incrementWritePtr(unsigned epId)
{
Addr writePtr = dtu.regs().get(epId, EpReg::BUF_WR_PTR);
Addr bufferAddr = dtu.regs().get(epId, EpReg::BUF_ADDR);
Addr bufferSize = dtu.regs().get(epId, EpReg::BUF_SIZE);
Addr messageCount = dtu.regs().get(epId, EpReg::BUF_MSG_CNT);
unsigned maxMessageSize = dtu.regs().get(epId, EpReg::BUF_MSG_SIZE);
writePtr += maxMessageSize;
if (writePtr >= bufferAddr + bufferSize * maxMessageSize)
writePtr = bufferAddr;
DPRINTFS(DtuBuf, (&dtu), "EP%u: increment write pointer to %#018lx (msgCount=%u)\n",
epId,
writePtr,
messageCount + 1);
if(messageCount == bufferSize)
{
warn("EP%u: Buffer full!\n", epId);
return false;
}
dtu.regs().set(epId, EpReg::BUF_WR_PTR, writePtr);
dtu.regs().set(epId, EpReg::BUF_MSG_CNT, messageCount + 1);
dtu.updateSuspendablePin();
dtu.wakeupCore();
return true;
}
void
MessageUnit::recvFromNoc(PacketPtr pkt)
{
assert(pkt->isWrite());
assert(pkt->hasData());
NocAddr addr(pkt->getAddr());
unsigned epId = addr.epId;
Addr localAddr = dtu.regs().get(epId, EpReg::BUF_WR_PTR);
Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>();
DPRINTFS(Dtu, (&dtu), "\e[1m[rv <- %u]\e[0m %lu bytes on EP%u to %#018lx\n",
header->senderCoreId, header->length, epId, localAddr);
dtu.printPacket(pkt);
if(dtu.coreId == 0 && epId == 0)
{
size_t sysNo = pkt->getPtr<uint8_t>()[0];
DPRINTFS(DtuSysCalls, (&dtu), " syscall: %s\n",
sysNo < (sizeof(syscallNames) / sizeof(syscallNames[0])) ? syscallNames[sysNo] : "Unknown");
}
Addr bufferSize = dtu.regs().get(epId, EpReg::BUF_SIZE);
Addr messageCount = dtu.regs().get(epId, EpReg::BUF_MSG_CNT);
if(messageCount < bufferSize)
{
Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>();
// Note that replyEpId is the Id of *our* sending EP
if (header->flags & Dtu::REPLY_FLAG &&
header->flags & Dtu::GRANT_CREDITS_FLAG &&
header->replyEpId < dtu.numEndpoints)
{
unsigned maxMessageSize = dtu.regs().get(header->replyEpId, EpReg::MAX_MSG_SIZE);
DPRINTFS(DtuDetail, (&dtu), "Grant EP%u %u credits\n", header->replyEpId, maxMessageSize);
unsigned credits = dtu.regs().get(header->replyEpId, EpReg::CREDITS);
credits += maxMessageSize;
dtu.regs().set(header->replyEpId, EpReg::CREDITS, credits);
}
// the message is transferred piece by piece; we can start as soon as we have the header
Cycles delay = dtu.ticksToCycles(pkt->headerDelay);
pkt->headerDelay = 0;
delay += dtu.nocToTransferLatency;
dtu.startTransfer(Dtu::TransferType::REMOTE_WRITE,
NocAddr(0, 0),
localAddr,
pkt->getSize(),
pkt,
NULL,
delay);
incrementWritePtr(epId);
}
// ignore messages if there is not enough space
else
{
pkt->makeResponse();
if (!dtu.atomicMode)
{
Cycles delay = dtu.ticksToCycles(pkt->headerDelay + pkt->payloadDelay);
delay += dtu.nocToTransferLatency;
pkt->headerDelay = 0;
pkt->payloadDelay = 0;
dtu.schedNocResponse(pkt, dtu.clockEdge(delay));
}
}
}
<commit_msg>DTU: formatting.<commit_after>/*
* Copyright (c) 2015, Christian Menard
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#include "debug/Dtu.hh"
#include "debug/DtuBuf.hh"
#include "debug/DtuDetail.hh"
#include "debug/DtuPackets.hh"
#include "debug/DtuSysCalls.hh"
#include "debug/DtuPower.hh"
#include "mem/dtu/msg_unit.hh"
#include "mem/dtu/noc_addr.hh"
static const char *syscallNames[] = {
"CREATESRV",
"CREATESESS",
"CREATEGATE",
"CREATEVPE",
"ATTACHRB",
"DETACHRB",
"EXCHANGE",
"VPECTRL",
"DELEGATE",
"OBTAIN",
"ACTIVATE",
"REQMEM",
"DERIVEMEM",
"REVOKE",
"EXIT",
"NOOP",
};
void
MessageUnit::startTransmission(const Dtu::Command& cmd)
{
unsigned epid = cmd.epId;
Addr messageAddr = dtu.regs().get(CmdReg::DATA_ADDR);
Addr messageSize = dtu.regs().get(CmdReg::DATA_SIZE);
bool isReply = cmd.opcode == Dtu::CommandOpcode::REPLY;
/*
* If this endpoint is configured to send messages, we need to check
* credits. If it is configured to receive messages we do a reply and don't
* need to check credits.
*/
if (!isReply)
{
unsigned credits = dtu.regs().get(epid, EpReg::CREDITS);
unsigned maxMessageSize = dtu.regs().get(epid, EpReg::MAX_MSG_SIZE);
// TODO error handling
// TODO atm, we can send (nearly) arbitrary large replies
assert(messageSize + sizeof(Dtu::MessageHeader) <= maxMessageSize);
if (credits < maxMessageSize)
{
warn("pe%u.ep%u: Ignore send message command because there are not "
"enough credits", dtu.coreId, epid);
dtu.scheduleFinishOp(Cycles(1));
return;
}
DPRINTFS(DtuDetail, (&dtu), "EP%u pays %u credits\n",
epid, maxMessageSize);
// Pay some credits
credits -= maxMessageSize;
dtu.regs().set(epid, EpReg::CREDITS, credits);
}
unsigned targetCoreId;
unsigned targetEpId;
unsigned replyEpId;
uint64_t label;
uint64_t replyLabel;
if (isReply)
{
// pay for the functional request; TODO
/*
* We need to read the header of the received message from local memory
* to determine target core and enspoint ID. This would introduce a
* second local memory request and would make the control flow more
* complicated. To simplify things a functional request is used and an
* additional delay is payed.
*/
Addr msgAddr = dtu.regs().get(epid, EpReg::BUF_RD_PTR);
auto pkt = dtu.generateRequest(dtu.translate(msgAddr),
sizeof(Dtu::MessageHeader),
MemCmd::ReadReq);
dtu.sendFunctionalMemRequest(pkt);
auto h = pkt->getPtr<Dtu::MessageHeader>();
assert(h->flags & Dtu::REPLY_ENABLED);
targetCoreId = h->senderCoreId;
targetEpId = h->replyEpId; // send message to the reply EP
replyEpId = h->senderEpId; // and grant credits to the sender
// the receiver of the reply should get the label that he has set
label = h->replyLabel;
// replies don't have replies. so, we don't need that
replyLabel = 0;
// disable replies for this message
auto hpkt = dtu.generateRequest(dtu.translate(msgAddr),
sizeof(h->flags),
MemCmd::WriteReq);
h->flags &= ~Dtu::REPLY_ENABLED;
memcpy(hpkt->getPtr<uint8_t>(), &h->flags, sizeof(h->flags));
dtu.sendFunctionalMemRequest(hpkt);
dtu.freeRequest(hpkt);
dtu.freeRequest(pkt);
}
else
{
targetCoreId = dtu.regs().get(epid, EpReg::TGT_COREID);
targetEpId = dtu.regs().get(epid, EpReg::TGT_EPID);
label = dtu.regs().get(epid, EpReg::LABEL);
replyLabel = dtu.regs().get(CmdReg::REPLY_LABEL);
replyEpId = dtu.regs().get(CmdReg::REPLY_EPID);
M5_VAR_USED unsigned maxMessageSize = dtu.regs().get(epid, EpReg::MAX_MSG_SIZE);
assert(messageSize + sizeof(Dtu::MessageHeader) <= maxMessageSize);
}
DPRINTFS(Dtu, (&dtu), "\e[1m[%s -> %u]\e[0m with EP%u of %#018lx:%lu\n",
isReply ? "rp" : "sd",
targetCoreId, epid, dtu.regs().get(CmdReg::DATA_ADDR), messageSize);
DPRINTFS(Dtu, (&dtu), " header: tgtEP=%u, lbl=%#018lx, rpLbl=%#018lx, rpEP=%u\n",
targetEpId, label, replyLabel, replyEpId);
Dtu::MessageHeader* header = new Dtu::MessageHeader;
if (isReply)
header->flags = Dtu::REPLY_FLAG | Dtu::GRANT_CREDITS_FLAG;
else
header->flags = Dtu::REPLY_ENABLED; // normal message
header->senderCoreId = static_cast<uint8_t>(dtu.coreId);
header->senderEpId = static_cast<uint8_t>(epid);
header->replyEpId = static_cast<uint8_t>(replyEpId);
header->length = static_cast<uint16_t>(messageSize);
header->label = static_cast<uint64_t>(label);
header->replyLabel = static_cast<uint64_t>(replyLabel);
assert(messageSize + sizeof(Dtu::MessageHeader) <= dtu.maxNocPacketSize);
// start the transfer of the payload
dtu.startTransfer(Dtu::TransferType::LOCAL_READ,
NocAddr(targetCoreId, targetEpId),
messageAddr,
messageSize,
NULL,
header,
dtu.startMsgTransferDelay);
}
void
MessageUnit::incrementReadPtr(unsigned epId)
{
Addr readPtr = dtu.regs().get(epId, EpReg::BUF_RD_PTR);
Addr bufferAddr = dtu.regs().get(epId, EpReg::BUF_ADDR);
Addr bufferSize = dtu.regs().get(epId, EpReg::BUF_SIZE);
Addr messageCount = dtu.regs().get(epId, EpReg::BUF_MSG_CNT);
unsigned maxMessageSize = dtu.regs().get(epId, EpReg::BUF_MSG_SIZE);
readPtr += maxMessageSize;
if (readPtr >= bufferAddr + bufferSize * maxMessageSize)
readPtr = bufferAddr;
DPRINTFS(DtuBuf, (&dtu), "EP%u: increment read pointer to %#018lx (msgCount=%u)\n",
epId,
readPtr,
messageCount - 1);
// TODO error handling
assert(messageCount != 0);
/*
* XXX Actually an additianally cycle is needed to update the register.
* We ignore this delay as it should have no or a very small influence
* on the performance of the simulated system.
*/
dtu.regs().set(epId, EpReg::BUF_RD_PTR, readPtr);
dtu.regs().set(epId, EpReg::BUF_MSG_CNT, messageCount - 1);
dtu.updateSuspendablePin();
}
bool
MessageUnit::incrementWritePtr(unsigned epId)
{
Addr writePtr = dtu.regs().get(epId, EpReg::BUF_WR_PTR);
Addr bufferAddr = dtu.regs().get(epId, EpReg::BUF_ADDR);
Addr bufferSize = dtu.regs().get(epId, EpReg::BUF_SIZE);
Addr messageCount = dtu.regs().get(epId, EpReg::BUF_MSG_CNT);
unsigned maxMessageSize = dtu.regs().get(epId, EpReg::BUF_MSG_SIZE);
writePtr += maxMessageSize;
if (writePtr >= bufferAddr + bufferSize * maxMessageSize)
writePtr = bufferAddr;
DPRINTFS(DtuBuf, (&dtu), "EP%u: increment write pointer to %#018lx (msgCount=%u)\n",
epId,
writePtr,
messageCount + 1);
if(messageCount == bufferSize)
{
warn("EP%u: Buffer full!\n", epId);
return false;
}
dtu.regs().set(epId, EpReg::BUF_WR_PTR, writePtr);
dtu.regs().set(epId, EpReg::BUF_MSG_CNT, messageCount + 1);
dtu.updateSuspendablePin();
dtu.wakeupCore();
return true;
}
void
MessageUnit::recvFromNoc(PacketPtr pkt)
{
assert(pkt->isWrite());
assert(pkt->hasData());
NocAddr addr(pkt->getAddr());
unsigned epId = addr.epId;
Addr localAddr = dtu.regs().get(epId, EpReg::BUF_WR_PTR);
Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>();
DPRINTFS(Dtu, (&dtu), "\e[1m[rv <- %u]\e[0m %lu bytes on EP%u to %#018lx\n",
header->senderCoreId, header->length, epId, localAddr);
dtu.printPacket(pkt);
if(dtu.coreId == 0 && epId == 0)
{
size_t sysNo = pkt->getPtr<uint8_t>()[0];
DPRINTFS(DtuSysCalls, (&dtu), " syscall: %s\n",
sysNo < (sizeof(syscallNames) / sizeof(syscallNames[0])) ? syscallNames[sysNo] : "Unknown");
}
Addr bufferSize = dtu.regs().get(epId, EpReg::BUF_SIZE);
Addr messageCount = dtu.regs().get(epId, EpReg::BUF_MSG_CNT);
if(messageCount < bufferSize)
{
Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>();
// Note that replyEpId is the Id of *our* sending EP
if (header->flags & Dtu::REPLY_FLAG &&
header->flags & Dtu::GRANT_CREDITS_FLAG &&
header->replyEpId < dtu.numEndpoints)
{
unsigned maxMessageSize = dtu.regs().get(header->replyEpId, EpReg::MAX_MSG_SIZE);
DPRINTFS(DtuDetail, (&dtu), "Grant EP%u %u credits\n", header->replyEpId, maxMessageSize);
unsigned credits = dtu.regs().get(header->replyEpId, EpReg::CREDITS);
credits += maxMessageSize;
dtu.regs().set(header->replyEpId, EpReg::CREDITS, credits);
}
// the message is transferred piece by piece; we can start as soon as we have the header
Cycles delay = dtu.ticksToCycles(pkt->headerDelay);
pkt->headerDelay = 0;
delay += dtu.nocToTransferLatency;
dtu.startTransfer(Dtu::TransferType::REMOTE_WRITE,
NocAddr(0, 0),
localAddr,
pkt->getSize(),
pkt,
NULL,
delay);
incrementWritePtr(epId);
}
// ignore messages if there is not enough space
else
{
pkt->makeResponse();
if (!dtu.atomicMode)
{
Cycles delay = dtu.ticksToCycles(pkt->headerDelay + pkt->payloadDelay);
delay += dtu.nocToTransferLatency;
pkt->headerDelay = 0;
pkt->payloadDelay = 0;
dtu.schedNocResponse(pkt, dtu.clockEdge(delay));
}
}
}
<|endoftext|> |
<commit_before>/**
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <[email protected]>, Hugo Boyer ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
**/
#include "abstractable.h"
using namespace mgl;
using namespace std;
#include "log.h"
#ifdef __APPLE__
#include <CFBundle.h>
#endif
#ifdef WIN32
#include <Windows.h>
#include <Shlobj.h>
#else
#include <sys/types.h>
#include <pwd.h>
#endif
#include <fstream>
std::ostream &MyComputer::log()
{
return cout;
}
#ifdef QT_CORE_LIB
int FileSystemAbstractor::guarenteeDirectoryExists(const char* )//pathname )
{
Log::info() << "not supported on QT" << endl;
return -1;
#else
int FileSystemAbstractor::guarenteeDirectoryExists(const char* pathname)
{
int status = 0;
#ifdef WIN32
DWORD attrib = GetFileAttributesA(pathname);
if (attrib == INVALID_FILE_ATTRIBUTES) {
BOOL result = CreateDirectoryA(pathname, NULL);
if (!result)
status = -1; //creation fail
}
else if (!(attrib & FILE_ATTRIBUTE_DIRECTORY))
status = -1;
#else //WIN32
// mode_t does not work under QT
mode_t mode = (S_IREAD|S_IWRITE |S_IRGRP|S_IWGRP |S_IROTH);
struct stat st;
if(stat(pathname,&st) != 0){
mode_t process_mask = umask(0);
int result_code = mkdir(pathname, mode);
umask(process_mask);
if(result_code != 0)
status = -1 ; //creation fail
}
else if (!S_ISDIR(st.st_mode))
status = -1;
return status;
#endif //!WIN32
#endif //!QT_CORE_LIB
}
string FileSystemAbstractor::pathJoin(string path, string filename) const
{
#ifdef WIN32
return path + "\\" + filename;
#else
return path + "/" + filename;
#endif
}
char FileSystemAbstractor::getPathSeparatorCharacter() const
{
#ifdef WIN32
return '\\';
#else
return '/'; // Linux & Mac, works on Windows most times
#endif
}
string FileSystemAbstractor::ExtractDirectory(const char *directoryPath) const
{
const string path(directoryPath);
return path.substr(0, path.find_last_of(getPathSeparatorCharacter()) + 1);
}
string FileSystemAbstractor::ExtractFilename(const char* filename) const
{
std::string path(filename);
return path.substr(path.find_last_of(getPathSeparatorCharacter()) + 1);
}
string FileSystemAbstractor::ChangeExtension(const char* filename, const char* extension) const
{
const string path(filename);
const string ext(extension);
std::string filenameStr = ExtractFilename(path.c_str());
return ExtractDirectory(path.c_str())
+ filenameStr.substr(0, filenameStr.find_last_of('.')) + ext;
}
string FileSystemAbstractor::removeExtension(const char *filename) const
{
const string path(filename);
string filenameStr = ExtractFilename(path.c_str());
return ExtractDirectory(path.c_str())
+ filenameStr.substr(0, filenameStr.find_last_of('.'));
}
bool FileSystemAbstractor::fileReadable(const char *filename) const {
ifstream testfile(filename, ifstream::in);
bool readable = !testfile.fail();
testfile.close();
return readable;
}
string FileSystemAbstractor::getDataFile(const char *filename) const {
string found = getUserDataFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
found = getSystemDataFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
return string();
}
string FileSystemAbstractor::getConfigFile(const char *filename) const {
string found = getUserConfigFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
found = getSystemConfigFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
return string();
}
string FileSystemAbstractor::getUserDataFile(const char *filename) const {
#ifdef __APPLE__
char pwbuff[1024];
struct passwd pw;
struct passwd *tempptr;
if (getpwuid_r(getuid(), &pw, pwbuff, 1024, &tempptr) == 0) {
return pathJoin(pathJoin(string(pw.pw_dir),
"Library/Makerbot/Miracle-Grue"),
filename);
}
else {
return string();
}
#else
/*other platforms should be fine putting user data files in the same
dir as user config files*/
return getUserConfigFile(filename);
#endif
}
string FileSystemAbstractor::getSystemDataFile(const char *filename) const {
#ifdef __linux__
return pathJoin(string("/usr/share/makerbot"), filename);
#else
return getSystemConfigFile(filename);
#endif
}
string FileSystemAbstractor::getSystemConfigFile(const char *filename) const {
#ifdef WIN32
char app_path[1024];
GetModuleFileNameA(0, app_path, sizeof(app_path) - 1);
// Extract directory
std::string app_dir = ExtractDirectory(app_path);
return pathJoin(app_dir, filename);
#elif defined __APPLE__
CFBundleRef mainBundle;
mainBundle = CFBundleGetMainBundle();
if(!mainBundle)
return string();
CFURLRef resourceURL;
resourceURL =
CFBundleCopyResourceURL(mainBundle,
CFStringCreateWithCString(NULL,
filename,
kCFStringEncodingASCII),
NULL,
NULL);
if (!resourceURL)
return string();
char fileurl[1024];
if(!CFURLGetFileSystemRepresentation(resourceURL,
true,
(UInt8*)
fileurl,
1024)) {
return string();
}
return string(fileurl);
#else //linux
return pathJoin(string("/etc/xdg/makerbot"), filename);
#endif
}
string FileSystemAbstractor::getUserConfigFile(const char *filename) const {
#ifdef WIN32
char app_data[1024];
if(SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0,
app_data))) {
return pathJoin(pathJoin(string(app_data), "Makerbot"),
filename);
}
#else //linux or apple
char pwbuff[1024];
struct passwd pw;
struct passwd *tempptr;
if (getpwuid_r(getuid(), &pw, pwbuff, 1024, &tempptr) == 0) {
#ifdef __APPLE__
return pathJoin(pathJoin(string(pw.pw_dir),
"Library/Preferences/Makerbot/Miracle-Grue"),
filename);
#else //linux
return pathJoin(pathJoin(string(pw.pw_dir), ".config/makerbot"),
filename);
#endif //linux
}
#endif //win32
return string();
}
ProgressLog::ProgressLog(unsigned int count)
:ProgressBar(count,"")
{
reset(count);
std::cout << ":";
}
void ProgressLog::onTick(const char* taskName, unsigned int count, unsigned int ticks)
{
if (ticks == 0) {
this->deltaTicks = 0;
this->deltaProgress = 0;
this->delta = count / 10;
std::cout << taskName;
Log::info() << " [" << deltaProgress * 10 << "%] ";
}
if (deltaTicks >= this->delta)
{
deltaProgress++;
std::cout << " [" << deltaProgress * 10 << "%] ";
std::cout.flush();
Log::info() << " [" << deltaProgress * 10 << "%] ";
this->deltaTicks = 0;
}
if ( ticks >= count -1 ) {
string now = myPc.clock.now();
Log::info() << now;
std::cout << now << endl;
}
deltaTicks++;
}
<commit_msg>[finishes: 30862131] Fall back to cwd if a default:// file isn't found in the system dirs<commit_after>/**
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <[email protected]>, Hugo Boyer ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
**/
#include "abstractable.h"
using namespace mgl;
using namespace std;
#include "log.h"
#ifdef __APPLE__
#include <CFBundle.h>
#endif
#ifdef WIN32
#include <Windows.h>
#include <Shlobj.h>
#else
#include <sys/types.h>
#include <pwd.h>
#endif
#include <fstream>
std::ostream &MyComputer::log()
{
return cout;
}
#ifdef QT_CORE_LIB
int FileSystemAbstractor::guarenteeDirectoryExists(const char* )//pathname )
{
Log::info() << "not supported on QT" << endl;
return -1;
#else
int FileSystemAbstractor::guarenteeDirectoryExists(const char* pathname)
{
int status = 0;
#ifdef WIN32
DWORD attrib = GetFileAttributesA(pathname);
if (attrib == INVALID_FILE_ATTRIBUTES) {
BOOL result = CreateDirectoryA(pathname, NULL);
if (!result)
status = -1; //creation fail
}
else if (!(attrib & FILE_ATTRIBUTE_DIRECTORY))
status = -1;
#else //WIN32
// mode_t does not work under QT
mode_t mode = (S_IREAD|S_IWRITE |S_IRGRP|S_IWGRP |S_IROTH);
struct stat st;
if(stat(pathname,&st) != 0){
mode_t process_mask = umask(0);
int result_code = mkdir(pathname, mode);
umask(process_mask);
if(result_code != 0)
status = -1 ; //creation fail
}
else if (!S_ISDIR(st.st_mode))
status = -1;
return status;
#endif //!WIN32
#endif //!QT_CORE_LIB
}
string FileSystemAbstractor::pathJoin(string path, string filename) const
{
#ifdef WIN32
return path + "\\" + filename;
#else
return path + "/" + filename;
#endif
}
char FileSystemAbstractor::getPathSeparatorCharacter() const
{
#ifdef WIN32
return '\\';
#else
return '/'; // Linux & Mac, works on Windows most times
#endif
}
string FileSystemAbstractor::ExtractDirectory(const char *directoryPath) const
{
const string path(directoryPath);
return path.substr(0, path.find_last_of(getPathSeparatorCharacter()) + 1);
}
string FileSystemAbstractor::ExtractFilename(const char* filename) const
{
std::string path(filename);
return path.substr(path.find_last_of(getPathSeparatorCharacter()) + 1);
}
string FileSystemAbstractor::ChangeExtension(const char* filename, const char* extension) const
{
const string path(filename);
const string ext(extension);
std::string filenameStr = ExtractFilename(path.c_str());
return ExtractDirectory(path.c_str())
+ filenameStr.substr(0, filenameStr.find_last_of('.')) + ext;
}
string FileSystemAbstractor::removeExtension(const char *filename) const
{
const string path(filename);
string filenameStr = ExtractFilename(path.c_str());
return ExtractDirectory(path.c_str())
+ filenameStr.substr(0, filenameStr.find_last_of('.'));
}
bool FileSystemAbstractor::fileReadable(const char *filename) const {
ifstream testfile(filename, ifstream::in);
bool readable = !testfile.fail();
testfile.close();
return readable;
}
string FileSystemAbstractor::getDataFile(const char *filename) const {
string found = getUserDataFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
found = getSystemDataFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
if (fileReadable(filename)) //fall back to current working directory
return string(filename);
return string();
}
string FileSystemAbstractor::getConfigFile(const char *filename) const {
string found = getUserConfigFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
found = getSystemConfigFile(filename);
if (found.length() > 0 && fileReadable(found.c_str()))
return found;
return string();
}
string FileSystemAbstractor::getUserDataFile(const char *filename) const {
#ifdef __APPLE__
char pwbuff[1024];
struct passwd pw;
struct passwd *tempptr;
if (getpwuid_r(getuid(), &pw, pwbuff, 1024, &tempptr) == 0) {
return pathJoin(pathJoin(string(pw.pw_dir),
"Library/Makerbot/Miracle-Grue"),
filename);
}
else {
return string();
}
#else
/*other platforms should be fine putting user data files in the same
dir as user config files*/
return getUserConfigFile(filename);
#endif
}
string FileSystemAbstractor::getSystemDataFile(const char *filename) const {
#ifdef __linux__
return pathJoin(string("/usr/share/makerbot"), filename);
#else
return getSystemConfigFile(filename);
#endif
}
string FileSystemAbstractor::getSystemConfigFile(const char *filename) const {
#ifdef WIN32
char app_path[1024];
GetModuleFileNameA(0, app_path, sizeof(app_path) - 1);
// Extract directory
std::string app_dir = ExtractDirectory(app_path);
return pathJoin(app_dir, filename);
#elif defined __APPLE__
CFBundleRef mainBundle;
mainBundle = CFBundleGetMainBundle();
if(!mainBundle)
return string();
CFURLRef resourceURL;
resourceURL =
CFBundleCopyResourceURL(mainBundle,
CFStringCreateWithCString(NULL,
filename,
kCFStringEncodingASCII),
NULL,
NULL);
if (!resourceURL)
return string();
char fileurl[1024];
if(!CFURLGetFileSystemRepresentation(resourceURL,
true,
(UInt8*)
fileurl,
1024)) {
return string();
}
return string(fileurl);
#else //linux
return pathJoin(string("/etc/xdg/makerbot"), filename);
#endif
}
string FileSystemAbstractor::getUserConfigFile(const char *filename) const {
#ifdef WIN32
char app_data[1024];
if(SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0,
app_data))) {
return pathJoin(pathJoin(string(app_data), "Makerbot"),
filename);
}
#else //linux or apple
char pwbuff[1024];
struct passwd pw;
struct passwd *tempptr;
if (getpwuid_r(getuid(), &pw, pwbuff, 1024, &tempptr) == 0) {
#ifdef __APPLE__
return pathJoin(pathJoin(string(pw.pw_dir),
"Library/Preferences/Makerbot/Miracle-Grue"),
filename);
#else //linux
return pathJoin(pathJoin(string(pw.pw_dir), ".config/makerbot"),
filename);
#endif //linux
}
#endif //win32
return string();
}
ProgressLog::ProgressLog(unsigned int count)
:ProgressBar(count,"")
{
reset(count);
std::cout << ":";
}
void ProgressLog::onTick(const char* taskName, unsigned int count, unsigned int ticks)
{
if (ticks == 0) {
this->deltaTicks = 0;
this->deltaProgress = 0;
this->delta = count / 10;
std::cout << taskName;
Log::info() << " [" << deltaProgress * 10 << "%] ";
}
if (deltaTicks >= this->delta)
{
deltaProgress++;
std::cout << " [" << deltaProgress * 10 << "%] ";
std::cout.flush();
Log::info() << " [" << deltaProgress * 10 << "%] ";
this->deltaTicks = 0;
}
if ( ticks >= count -1 ) {
string now = myPc.clock.now();
Log::info() << now;
std::cout << now << endl;
}
deltaTicks++;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <memory>
#include <map>
#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>
#include <Checker.hpp>
#include <ExprStmt.hpp>
#include <RefExpr.hpp>
#include <IdRef.hpp>
/*
* WHERE I LEFT OFF: vars can be referenced on their own.
*
* WHAT I NEED TO ADD:
* - id checking to ALL expression types
* - ability to reference vars
*
*/
int main() {
std::string input_line;
double ans = 0;
auto id_table = std::make_shared<std::map<std::string, double>>();
std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl;
std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl;
std::cout << std::endl;
while (true) {
std::cout << ">>> ";
std::getline(std::cin, input_line);
if (std::cin.eof()) {
std::cout << std::endl;
break;
}
if (input_line == "quit" || input_line == "exit")
break;
else if (input_line == "ans") {
std::cout << "ans =" << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
continue;
} else if (input_line == "") {
continue;
} else if (input_line == "who") {
// TODO: I'll format this nicer later
for (auto var : *id_table)
std::cout << var.first << " = " << var.second << std::endl;
continue;
}
auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>();
miniMAT::lexer::Lexer lexer(input_line, reporter);
miniMAT::parser::Parser parser(lexer, reporter);
auto ast = parser.Parse();
miniMAT::checker::Checker checker(id_table, reporter);
ast = checker.check(ast);
if (reporter->HasErrors()) {
reporter->ReportErrors();
std::cout << std::endl;
} else {
//ast->VisitDisplay("");
ans = ast->VisitEvaluate();
if (!parser.SuppressedOutput()) {
if (ast->GetClassName() == "ExprStmt") {
auto exprstmt = std::dynamic_pointer_cast<miniMAT::ast::ExprStmt>(ast);
if (exprstmt->expr->GetClassName() == "RefExpr") {
auto refexpr = std::dynamic_pointer_cast<miniMAT::ast::RefExpr>(exprstmt->expr);
auto varname = std::dynamic_pointer_cast<miniMAT::ast::IdRef>(refexpr->ref)->id->GetSpelling();
std::cout << varname << " =" << std::endl << std::endl;
std::cout << " " << id_table->at(varname) << std::endl << std::endl;
} else {
std::cout << "ans =" << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
}
} else if (ast->GetClassName() == "AssignStmt") {
auto assign_stmt = std::dynamic_pointer_cast<miniMAT::ast::AssignStmt>(ast);
if (assign_stmt->ref->GetClassName() == "IdRef") {
;
}
}
}
}
}
return 0;
}
<commit_msg>Fix lexer error reporting bug<commit_after>#include <iostream>
#include <string>
#include <memory>
#include <map>
#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>
#include <Checker.hpp>
#include <ExprStmt.hpp>
#include <RefExpr.hpp>
#include <IdRef.hpp>
/*
* WHERE I LEFT OFF: vars can be referenced on their own.
*
* WHAT I NEED TO ADD:
* - id checking to ALL expression types
* - ability to reference vars
*
*/
int main() {
std::string input_line;
double ans = 0;
auto id_table = std::make_shared<std::map<std::string, double>>();
std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl;
std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl;
std::cout << std::endl;
while (true) {
std::cout << ">>> ";
std::getline(std::cin, input_line);
if (std::cin.eof()) {
std::cout << std::endl;
break;
}
if (input_line == "quit" || input_line == "exit")
break;
else if (input_line == "ans") {
std::cout << "ans =" << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
continue;
} else if (input_line == "") {
continue;
} else if (input_line == "who") {
// TODO: I'll format this nicer later
for (auto var : *id_table)
std::cout << var.first << " = " << var.second << std::endl;
continue;
}
auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>();
miniMAT::lexer::Lexer lexer(input_line, reporter);
miniMAT::parser::Parser parser(lexer, reporter);
auto ast = parser.Parse();
if (reporter->HasErrors()) {
reporter->ReportErrors();
std::cout << std::endl;
continue;
}
miniMAT::checker::Checker checker(id_table, reporter);
ast = checker.check(ast);
if (reporter->HasErrors()) {
reporter->ReportErrors();
std::cout << std::endl;
} else {
//ast->VisitDisplay("");
ans = ast->VisitEvaluate();
if (!parser.SuppressedOutput()) {
if (ast->GetClassName() == "ExprStmt") {
auto exprstmt = std::dynamic_pointer_cast<miniMAT::ast::ExprStmt>(ast);
if (exprstmt->expr->GetClassName() == "RefExpr") {
auto refexpr = std::dynamic_pointer_cast<miniMAT::ast::RefExpr>(exprstmt->expr);
auto varname = std::dynamic_pointer_cast<miniMAT::ast::IdRef>(refexpr->ref)->id->GetSpelling();
std::cout << varname << " =" << std::endl << std::endl;
std::cout << " " << id_table->at(varname) << std::endl << std::endl;
} else {
std::cout << "ans =" << std::endl << std::endl;
std::cout << " " << ans << std::endl << std::endl;
}
} else if (ast->GetClassName() == "AssignStmt") {
auto assign_stmt = std::dynamic_pointer_cast<miniMAT::ast::AssignStmt>(ast);
if (assign_stmt->ref->GetClassName() == "IdRef") {
;
}
}
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>
// pcsc
#include <winscard.h>
// libc
#include <cstdio>
#include <cstdlib>
#include <cstring>
// std
#include <memory>
#include <vector>
#include <iostream>
#include <iomanip>
#include <sstream>
namespace{ // move functions in separate module
// not defined in winscard...
using scard_res = decltype(SCARD_S_SUCCESS);
inline std::string err_to_str(const scard_res err){
std::stringstream ss;
switch (err) {
#ifdef FEK_CASE_ERR
#error "FEK_CASE_ERR already defined"
#endif
#define FEK_CASE_ERR(err_) case err_: ss << ""#err_; break;
FEK_CASE_ERR(SCARD_S_SUCCESS);
FEK_CASE_ERR(SCARD_F_INTERNAL_ERROR);
FEK_CASE_ERR(SCARD_E_CANCELLED);
FEK_CASE_ERR(SCARD_E_INVALID_HANDLE);
FEK_CASE_ERR(SCARD_E_INVALID_PARAMETER);
FEK_CASE_ERR(SCARD_E_INVALID_TARGET);
FEK_CASE_ERR(SCARD_E_NO_MEMORY);
FEK_CASE_ERR(SCARD_F_WAITED_TOO_LONG);
FEK_CASE_ERR(SCARD_E_INSUFFICIENT_BUFFER);
FEK_CASE_ERR(SCARD_E_UNKNOWN_READER);
FEK_CASE_ERR(SCARD_E_TIMEOUT);
FEK_CASE_ERR(SCARD_E_SHARING_VIOLATION);
FEK_CASE_ERR(SCARD_E_NO_SMARTCARD);
FEK_CASE_ERR(SCARD_E_UNKNOWN_CARD);
FEK_CASE_ERR(SCARD_E_CANT_DISPOSE);
FEK_CASE_ERR(SCARD_E_PROTO_MISMATCH);
FEK_CASE_ERR(SCARD_E_NOT_READY);
FEK_CASE_ERR(SCARD_E_INVALID_VALUE);
FEK_CASE_ERR(SCARD_E_SYSTEM_CANCELLED);
FEK_CASE_ERR(SCARD_F_COMM_ERROR);
FEK_CASE_ERR(SCARD_F_UNKNOWN_ERROR);
FEK_CASE_ERR(SCARD_E_INVALID_ATR);
FEK_CASE_ERR(SCARD_E_READER_UNAVAILABLE);
FEK_CASE_ERR(SCARD_P_SHUTDOWN);
FEK_CASE_ERR(SCARD_E_PCI_TOO_SMALL);
FEK_CASE_ERR(SCARD_E_READER_UNSUPPORTED);
FEK_CASE_ERR(SCARD_E_DUPLICATE_READER);
FEK_CASE_ERR(SCARD_E_CARD_UNSUPPORTED);
FEK_CASE_ERR(SCARD_E_NO_SERVICE);
FEK_CASE_ERR(SCARD_E_SERVICE_STOPPED);
FEK_CASE_ERR(SCARD_E_ICC_CREATEORDER);
FEK_CASE_ERR(SCARD_E_DIR_NOT_FOUND);
FEK_CASE_ERR(SCARD_E_NO_DIR);
FEK_CASE_ERR(SCARD_E_NO_FILE);
FEK_CASE_ERR(SCARD_E_NO_ACCESS);
FEK_CASE_ERR(SCARD_E_WRITE_TOO_MANY);
FEK_CASE_ERR(SCARD_E_BAD_SEEK);
FEK_CASE_ERR(SCARD_E_INVALID_CHV);
FEK_CASE_ERR(SCARD_E_UNKNOWN_RES_MNG);
FEK_CASE_ERR(SCARD_E_NO_SUCH_CERTIFICATE);
FEK_CASE_ERR(SCARD_E_CERTIFICATE_UNAVAILABLE);
FEK_CASE_ERR(SCARD_E_NO_READERS_AVAILABLE);
FEK_CASE_ERR(SCARD_E_COMM_DATA_LOST);
FEK_CASE_ERR(SCARD_E_NO_KEY_CONTAINER);
FEK_CASE_ERR(SCARD_E_SERVER_TOO_BUSY);
FEK_CASE_ERR(SCARD_W_UNSUPPORTED_CARD);
FEK_CASE_ERR(SCARD_W_UNRESPONSIVE_CARD);
FEK_CASE_ERR(SCARD_W_UNPOWERED_CARD);
FEK_CASE_ERR(SCARD_W_RESET_CARD);
FEK_CASE_ERR(SCARD_W_REMOVED_CARD);
FEK_CASE_ERR(SCARD_W_SECURITY_VIOLATION);
FEK_CASE_ERR(SCARD_W_WRONG_CHV);
FEK_CASE_ERR(SCARD_W_CHV_BLOCKED);
FEK_CASE_ERR(SCARD_W_EOF);
FEK_CASE_ERR(SCARD_W_CANCELLED_BY_USER);
FEK_CASE_ERR(SCARD_W_CARD_NOT_AUTHENTICATED);
#undef FEK_CASE_ERR
default:{
// handling SCARD_E_UNEXPECTED and SCARD_E_UNSUPPORTED_FEATURE here since on gnu/linux
// they have the same value and it would not be possible to handle in the switch case
if(err == SCARD_E_UNEXPECTED){
ss << "SCARD_E_UNEXPECTED";
} else if(err == SCARD_E_UNSUPPORTED_FEATURE){
ss << "SCARD_E_UNEXPECTED";
} else{
ss << "unknown SCARD error value";
}
}
}
ss << " (0x" << std::hex << std::setfill('0')<< std::setw(sizeof(err)) << err << ")";
auto res = ss.str();
return res;
}
enum class close_mode : DWORD {
// shoudl be decltype (SCARD_LEAVE_CARD) instead of DWORD, but SCardDisconnect takes a DWORD...
leave_card = SCARD_LEAVE_CARD,
reset_card = SCARD_RESET_CARD,
unpower_card = SCARD_UNPOWER_CARD,
eject_card = SCARD_EJECT_CARD,
};
// data structures similar for unique_ptr, but for smartcard handles
const SCARDCONTEXT invalid_handle = {}; // assuming the 0-init handle is an "invalid" handle
struct SCARDHANDLE_handle {
SCARDHANDLE handle = invalid_handle;
close_mode m = close_mode::leave_card;
SCARDHANDLE_handle() = default;
explicit SCARDHANDLE_handle(const SCARDHANDLE h, close_mode m_ = close_mode::leave_card) : handle(h), m(m_){}
// copy
SCARDHANDLE_handle(const SCARDHANDLE_handle&) = delete;
SCARDHANDLE_handle& operator=( const SCARDHANDLE_handle& ) = delete;
// move
SCARDHANDLE_handle( SCARDHANDLE_handle&& o ) : handle(o.handle), m(o.m){
o.handle = invalid_handle;
}
SCARDHANDLE_handle& operator=( SCARDHANDLE_handle&& o ){
reset(o.release());
handle = o.handle;
m = o.m;
o.handle = invalid_handle;
return *this;
}
~SCARDHANDLE_handle(){
using u_type = std::underlying_type<close_mode>::type;
const auto res = ::SCardDisconnect(handle, static_cast<u_type>(m));
(void) res;
}
// modifiers
SCARDHANDLE release(){
const auto old = handle;
handle = invalid_handle;
return old;
}
void reset(SCARDHANDLE h = {}){
const auto old = handle;
handle = h;
if(old != invalid_handle){
using u_type = std::underlying_type<close_mode>::type;
const auto res = ::SCardDisconnect(old, static_cast<u_type>(m));
(void) res;
}
}
void swap(SCARDHANDLE_handle& o){
std::swap(handle, o.handle);
std::swap(m, o.m);
}
// observers
SCARDHANDLE get() const noexcept {
return handle;
}
explicit operator bool() const{
return handle != invalid_handle;
}
};
const SCARDCONTEXT invalid_context = {}; // assuming the 0-init context is an "invalid" context
struct SCARDCONTEXT_handle {
SCARDCONTEXT context = invalid_context;
SCARDCONTEXT_handle() = default;
explicit SCARDCONTEXT_handle(const SCARDCONTEXT c) : context(c){}
// copy
SCARDCONTEXT_handle(const SCARDCONTEXT_handle&) = delete;
SCARDCONTEXT_handle& operator=( const SCARDCONTEXT_handle& ) = delete;
// move
SCARDCONTEXT_handle( SCARDCONTEXT_handle&& o ) : context(o.context){
o.context = invalid_context;
}
SCARDCONTEXT_handle& operator=( SCARDCONTEXT_handle&& o ){
reset(o.release());
context = o.context;
o.context = invalid_context;
return *this;
}
~SCARDCONTEXT_handle(){
const auto res = ::SCardReleaseContext(context);
(void) res;
}
// modifiers
SCARDCONTEXT release(){
const auto old = context;
context = invalid_context;
return old;
}
void reset(SCARDCONTEXT h = {}){
const auto old = context;
context = h;
if(old != invalid_context){
const auto res = ::SCardReleaseContext(old);
(void) res;
}
}
void swap(SCARDCONTEXT_handle& o){
std::swap(context, o.context);
}
// observers
SCARDCONTEXT get() const noexcept {
return context;
}
explicit operator bool() const{
return context != invalid_context;
}
};
// non owning "view" of data (can be inside array, contigous container, pointed, ...)
struct arr_view{
const BYTE* data = nullptr;
const size_t size = 0;
arr_view() noexcept = default;
// if c++14 we could use a templated container with std::size...
template<size_t N>
arr_view(const BYTE (&data_)[N]) noexcept : data(data_), size(N){}
arr_view(const BYTE* data_, const size_t size_) noexcept : data(data_), size(size_){}
template<class seq_container>
arr_view(const seq_container& c) : data{c.data()}, size{c.size()} {}
};
// like SCardTransmit, but takes an arr_view
struct scard_transmit_res{
scard_res res{};
std::vector<BYTE> response;
};
scard_transmit_res scard_transmit(SCARDHANDLE hCard, const SCARD_IO_REQUEST *pioSendPci, const arr_view& sendbuffer, SCARD_IO_REQUEST *pioRecvPci){
scard_transmit_res toreturn;
std::vector<BYTE> response(256);
DWORD size = response.size();
toreturn.res = SCardTransmit(hCard, pioSendPci, sendbuffer.data, sendbuffer.size, pioRecvPci, response.data(), &size);
if(toreturn.res == SCARD_S_SUCCESS){
response.resize(size);
toreturn.response = response;
}
return toreturn;
}
using scard_protocol = decltype(SCARD_PROTOCOL_UNDEFINED);
struct scard_connect_res{
scard_res res{};
SCARDHANDLE_handle handle{};
scard_protocol protocol{};
};
scard_connect_res scard_connect(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, DWORD dwPreferredProtocols){
scard_connect_res toreturn;
SCARDHANDLE h;
DWORD protocol{};
toreturn.res = SCardConnect(hContext, szReader, dwShareMode, dwPreferredProtocols, &h, &protocol);
if(toreturn.res == SCARD_S_SUCCESS){
toreturn.protocol = static_cast<DWORD>(protocol);
toreturn.handle.reset(h);
}
return toreturn;
}
struct scard_establish_context_res{
scard_res res{};
SCARDCONTEXT_handle handle{};
};
scard_establish_context_res scard_establish_context(const DWORD dwScope){
scard_establish_context_res toreturn;
SCARDCONTEXT context;
toreturn.res = SCardEstablishContext(dwScope, nullptr, nullptr, &context);
if(toreturn.res == SCARD_S_SUCCESS){
toreturn.handle.reset(context);
}
return toreturn;
}
}
int main()
{
auto res1 = scard_establish_context(SCARD_SCOPE_SYSTEM);
if(res1.res != SCARD_S_SUCCESS){
std::cerr << err_to_str(res1.res) << "\n";
return 1;
}
SCARDCONTEXT_handle hContext = std::move(res1.handle);
// FIXME: move SCardListReaders to a single function call that handles the memory
DWORD bufsize = 0;
const auto res2 = SCardListReaders(hContext.get(), nullptr, nullptr, &bufsize);
if(res2 != SCARD_S_SUCCESS){
std::cerr << err_to_str(res2) << "\n";
return 1;
}
std::vector<char> buffer(bufsize);
const auto res3 = SCardListReaders(hContext.get(), nullptr, buffer.data(), &bufsize);
if(res3 != SCARD_S_SUCCESS){
std::cerr << err_to_str(res3) << "\n";
return 1;
}
buffer.resize(bufsize); // buffer is double - '\0' -terminated
std::vector<std::string> readers;
{
auto pdata = buffer.data();
while(*pdata != '\0'){
const auto len = std::strlen(pdata);
if(len > 0){
std::string tmp(pdata, len);
readers.push_back(tmp);
}
pdata += (len + 1);
}
}
auto res4 = scard_connect(hContext.get(), readers.at(0).c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1);
if(res4.res != SCARD_S_SUCCESS){
std::cerr << err_to_str(res4.res) << "\n";
return 1;
}
SCARDHANDLE_handle hCard = std::move(res4.handle);
SCARD_IO_REQUEST pioSendPci{};
switch(res4.protocol)
{
case SCARD_PROTOCOL_T0:
pioSendPci = *SCARD_PCI_T0;
break;
case SCARD_PROTOCOL_T1:
pioSendPci = *SCARD_PCI_T1;
break;
case SCARD_PROTOCOL_RAW:
pioSendPci = *SCARD_PCI_RAW;
break;
case SCARD_PROTOCOL_UNDEFINED:
std::cerr << "Protocol not defined\n";
return 1;
default:
std::cerr << "unknown protocol\n";
return 1;
}
/*
BYTE cmd1[] = { }; // message to send
const auto res5 = scard_transmit(hCard.get(), &pioSendPci, cmd1, nullptr);
if(res5.res != SCARD_S_SUCCESS){
std::cerr << err_to_str(res5.res) << "\n";
return 1;
}
*/
return 0;
}
<commit_msg>renamed structures for memory management<commit_after>
// pcsc
#include <winscard.h>
// libc
#include <cstdio>
#include <cstdlib>
#include <cstring>
// std
#include <memory>
#include <vector>
#include <iostream>
#include <iomanip>
#include <sstream>
namespace{ // move functions in separate module
// not defined in winscard...
using scard_res = decltype(SCARD_S_SUCCESS);
inline std::string err_to_str(const scard_res err){
std::stringstream ss;
switch (err) {
#ifdef FEK_CASE_ERR
#error "FEK_CASE_ERR already defined"
#endif
#define FEK_CASE_ERR(err_) case err_: ss << ""#err_; break;
FEK_CASE_ERR(SCARD_S_SUCCESS);
FEK_CASE_ERR(SCARD_F_INTERNAL_ERROR);
FEK_CASE_ERR(SCARD_E_CANCELLED);
FEK_CASE_ERR(SCARD_E_INVALID_HANDLE);
FEK_CASE_ERR(SCARD_E_INVALID_PARAMETER);
FEK_CASE_ERR(SCARD_E_INVALID_TARGET);
FEK_CASE_ERR(SCARD_E_NO_MEMORY);
FEK_CASE_ERR(SCARD_F_WAITED_TOO_LONG);
FEK_CASE_ERR(SCARD_E_INSUFFICIENT_BUFFER);
FEK_CASE_ERR(SCARD_E_UNKNOWN_READER);
FEK_CASE_ERR(SCARD_E_TIMEOUT);
FEK_CASE_ERR(SCARD_E_SHARING_VIOLATION);
FEK_CASE_ERR(SCARD_E_NO_SMARTCARD);
FEK_CASE_ERR(SCARD_E_UNKNOWN_CARD);
FEK_CASE_ERR(SCARD_E_CANT_DISPOSE);
FEK_CASE_ERR(SCARD_E_PROTO_MISMATCH);
FEK_CASE_ERR(SCARD_E_NOT_READY);
FEK_CASE_ERR(SCARD_E_INVALID_VALUE);
FEK_CASE_ERR(SCARD_E_SYSTEM_CANCELLED);
FEK_CASE_ERR(SCARD_F_COMM_ERROR);
FEK_CASE_ERR(SCARD_F_UNKNOWN_ERROR);
FEK_CASE_ERR(SCARD_E_INVALID_ATR);
FEK_CASE_ERR(SCARD_E_READER_UNAVAILABLE);
FEK_CASE_ERR(SCARD_P_SHUTDOWN);
FEK_CASE_ERR(SCARD_E_PCI_TOO_SMALL);
FEK_CASE_ERR(SCARD_E_READER_UNSUPPORTED);
FEK_CASE_ERR(SCARD_E_DUPLICATE_READER);
FEK_CASE_ERR(SCARD_E_CARD_UNSUPPORTED);
FEK_CASE_ERR(SCARD_E_NO_SERVICE);
FEK_CASE_ERR(SCARD_E_SERVICE_STOPPED);
FEK_CASE_ERR(SCARD_E_ICC_CREATEORDER);
FEK_CASE_ERR(SCARD_E_DIR_NOT_FOUND);
FEK_CASE_ERR(SCARD_E_NO_DIR);
FEK_CASE_ERR(SCARD_E_NO_FILE);
FEK_CASE_ERR(SCARD_E_NO_ACCESS);
FEK_CASE_ERR(SCARD_E_WRITE_TOO_MANY);
FEK_CASE_ERR(SCARD_E_BAD_SEEK);
FEK_CASE_ERR(SCARD_E_INVALID_CHV);
FEK_CASE_ERR(SCARD_E_UNKNOWN_RES_MNG);
FEK_CASE_ERR(SCARD_E_NO_SUCH_CERTIFICATE);
FEK_CASE_ERR(SCARD_E_CERTIFICATE_UNAVAILABLE);
FEK_CASE_ERR(SCARD_E_NO_READERS_AVAILABLE);
FEK_CASE_ERR(SCARD_E_COMM_DATA_LOST);
FEK_CASE_ERR(SCARD_E_NO_KEY_CONTAINER);
FEK_CASE_ERR(SCARD_E_SERVER_TOO_BUSY);
FEK_CASE_ERR(SCARD_W_UNSUPPORTED_CARD);
FEK_CASE_ERR(SCARD_W_UNRESPONSIVE_CARD);
FEK_CASE_ERR(SCARD_W_UNPOWERED_CARD);
FEK_CASE_ERR(SCARD_W_RESET_CARD);
FEK_CASE_ERR(SCARD_W_REMOVED_CARD);
FEK_CASE_ERR(SCARD_W_SECURITY_VIOLATION);
FEK_CASE_ERR(SCARD_W_WRONG_CHV);
FEK_CASE_ERR(SCARD_W_CHV_BLOCKED);
FEK_CASE_ERR(SCARD_W_EOF);
FEK_CASE_ERR(SCARD_W_CANCELLED_BY_USER);
FEK_CASE_ERR(SCARD_W_CARD_NOT_AUTHENTICATED);
#undef FEK_CASE_ERR
default:{
// handling SCARD_E_UNEXPECTED and SCARD_E_UNSUPPORTED_FEATURE here since on gnu/linux
// they have the same value and it would not be possible to handle in the switch case
if(err == SCARD_E_UNEXPECTED){
ss << "SCARD_E_UNEXPECTED";
} else if(err == SCARD_E_UNSUPPORTED_FEATURE){
ss << "SCARD_E_UNEXPECTED";
} else{
ss << "unknown SCARD error value";
}
}
}
ss << " (0x" << std::hex << std::setfill('0')<< std::setw(sizeof(err)) << err << ")";
auto res = ss.str();
return res;
}
enum class close_mode : DWORD {
// shoudl be decltype (SCARD_LEAVE_CARD) instead of DWORD, but SCardDisconnect takes a DWORD...
leave_card = SCARD_LEAVE_CARD,
reset_card = SCARD_RESET_CARD,
unpower_card = SCARD_UNPOWER_CARD,
eject_card = SCARD_EJECT_CARD,
};
// data structures similar for unique_ptr, but for smartcard handles
const SCARDCONTEXT invalid_handle = {}; // assuming the 0-init handle is an "invalid" handle
struct unique_SCARDHANDLE {
SCARDHANDLE handle = invalid_handle;
close_mode m = close_mode::leave_card;
unique_SCARDHANDLE() = default;
explicit unique_SCARDHANDLE(const SCARDHANDLE h, close_mode m_ = close_mode::leave_card) : handle(h), m(m_){}
// copy
unique_SCARDHANDLE(const unique_SCARDHANDLE&) = delete;
unique_SCARDHANDLE& operator=( const unique_SCARDHANDLE& ) = delete;
// move
unique_SCARDHANDLE( unique_SCARDHANDLE&& o ) : handle(o.handle), m(o.m){
o.handle = invalid_handle;
}
unique_SCARDHANDLE& operator=( unique_SCARDHANDLE&& o ){
reset(o.release());
handle = o.handle;
m = o.m;
o.handle = invalid_handle;
return *this;
}
~unique_SCARDHANDLE(){
using u_type = std::underlying_type<close_mode>::type;
const auto res = ::SCardDisconnect(handle, static_cast<u_type>(m));
(void) res;
}
// modifiers
SCARDHANDLE release(){
const auto old = handle;
handle = invalid_handle;
return old;
}
void reset(SCARDHANDLE h = {}){
const auto old = handle;
handle = h;
if(old != invalid_handle){
using u_type = std::underlying_type<close_mode>::type;
const auto res = ::SCardDisconnect(old, static_cast<u_type>(m));
(void) res;
}
}
void swap(unique_SCARDHANDLE& o){
std::swap(handle, o.handle);
std::swap(m, o.m);
}
// observers
SCARDHANDLE get() const noexcept {
return handle;
}
explicit operator bool() const{
return handle != invalid_handle;
}
};
const SCARDCONTEXT invalid_context = {}; // assuming the 0-init context is an "invalid" context
struct unique_SCARDCONTEXT {
SCARDCONTEXT context = invalid_context;
unique_SCARDCONTEXT() = default;
explicit unique_SCARDCONTEXT(const SCARDCONTEXT c) : context(c){}
// copy
unique_SCARDCONTEXT(const unique_SCARDCONTEXT&) = delete;
unique_SCARDCONTEXT& operator=( const unique_SCARDCONTEXT& ) = delete;
// move
unique_SCARDCONTEXT( unique_SCARDCONTEXT&& o ) : context(o.context){
o.context = invalid_context;
}
unique_SCARDCONTEXT& operator=( unique_SCARDCONTEXT&& o ){
reset(o.release());
context = o.context;
o.context = invalid_context;
return *this;
}
~unique_SCARDCONTEXT(){
const auto res = ::SCardReleaseContext(context);
(void) res;
}
// modifiers
SCARDCONTEXT release(){
const auto old = context;
context = invalid_context;
return old;
}
void reset(SCARDCONTEXT h = {}){
const auto old = context;
context = h;
if(old != invalid_context){
const auto res = ::SCardReleaseContext(old);
(void) res;
}
}
void swap(unique_SCARDCONTEXT& o){
std::swap(context, o.context);
}
// observers
SCARDCONTEXT get() const noexcept {
return context;
}
explicit operator bool() const{
return context != invalid_context;
}
};
// non owning "view" of data (can be inside array, contigous container, pointed, ...)
struct arr_view{
const BYTE* data = nullptr;
const size_t size = 0;
arr_view() noexcept = default;
// if c++14 we could use a templated container with std::size...
template<size_t N>
arr_view(const BYTE (&data_)[N]) noexcept : data(data_), size(N){}
arr_view(const BYTE* data_, const size_t size_) noexcept : data(data_), size(size_){}
template<class seq_container>
arr_view(const seq_container& c) : data{c.data()}, size{c.size()} {}
};
// like SCardTransmit, but takes an arr_view
struct scard_transmit_res{
scard_res res{};
std::vector<BYTE> response;
};
scard_transmit_res scard_transmit(SCARDHANDLE hCard, const SCARD_IO_REQUEST *pioSendPci, const arr_view& sendbuffer, SCARD_IO_REQUEST *pioRecvPci){
scard_transmit_res toreturn;
std::vector<BYTE> response(256);
DWORD size = response.size();
toreturn.res = SCardTransmit(hCard, pioSendPci, sendbuffer.data, sendbuffer.size, pioRecvPci, response.data(), &size);
if(toreturn.res == SCARD_S_SUCCESS){
response.resize(size);
toreturn.response = response;
}
return toreturn;
}
using scard_protocol = decltype(SCARD_PROTOCOL_UNDEFINED);
struct scard_connect_res{
scard_res res{};
unique_SCARDHANDLE handle{};
scard_protocol protocol{};
};
scard_connect_res scard_connect(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, DWORD dwPreferredProtocols){
scard_connect_res toreturn;
SCARDHANDLE h;
DWORD protocol{};
toreturn.res = SCardConnect(hContext, szReader, dwShareMode, dwPreferredProtocols, &h, &protocol);
if(toreturn.res == SCARD_S_SUCCESS){
toreturn.protocol = static_cast<DWORD>(protocol);
toreturn.handle.reset(h);
}
return toreturn;
}
struct scard_establish_context_res{
scard_res res{};
unique_SCARDCONTEXT handle{};
};
scard_establish_context_res scard_establish_context(const DWORD dwScope){
scard_establish_context_res toreturn;
SCARDCONTEXT context;
toreturn.res = SCardEstablishContext(dwScope, nullptr, nullptr, &context);
if(toreturn.res == SCARD_S_SUCCESS){
toreturn.handle.reset(context);
}
return toreturn;
}
}
int main()
{
auto res1 = scard_establish_context(SCARD_SCOPE_SYSTEM);
if(res1.res != SCARD_S_SUCCESS){
std::cerr << err_to_str(res1.res) << "\n";
return 1;
}
unique_SCARDCONTEXT hContext = std::move(res1.handle);
// FIXME: move SCardListReaders to a single function call that handles the memory
DWORD bufsize = 0;
const auto res2 = SCardListReaders(hContext.get(), nullptr, nullptr, &bufsize);
if(res2 != SCARD_S_SUCCESS){
std::cerr << err_to_str(res2) << "\n";
return 1;
}
std::vector<char> buffer(bufsize);
const auto res3 = SCardListReaders(hContext.get(), nullptr, buffer.data(), &bufsize);
if(res3 != SCARD_S_SUCCESS){
std::cerr << err_to_str(res3) << "\n";
return 1;
}
buffer.resize(bufsize); // buffer is double - '\0' -terminated
std::vector<std::string> readers;
{
auto pdata = buffer.data();
while(*pdata != '\0'){
const auto len = std::strlen(pdata);
if(len > 0){
std::string tmp(pdata, len);
readers.push_back(tmp);
}
pdata += (len + 1);
}
}
auto res4 = scard_connect(hContext.get(), readers.at(0).c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1);
if(res4.res != SCARD_S_SUCCESS){
std::cerr << err_to_str(res4.res) << "\n";
return 1;
}
unique_SCARDHANDLE hCard = std::move(res4.handle);
SCARD_IO_REQUEST pioSendPci{};
switch(res4.protocol)
{
case SCARD_PROTOCOL_T0:
pioSendPci = *SCARD_PCI_T0;
break;
case SCARD_PROTOCOL_T1:
pioSendPci = *SCARD_PCI_T1;
break;
case SCARD_PROTOCOL_RAW:
pioSendPci = *SCARD_PCI_RAW;
break;
case SCARD_PROTOCOL_UNDEFINED:
std::cerr << "Protocol not defined\n";
return 1;
default:
std::cerr << "unknown protocol\n";
return 1;
}
/*
BYTE cmd1[] = { }; // message to send
const auto res5 = scard_transmit(hCard.get(), &pioSendPci, cmd1, nullptr);
if(res5.res != SCARD_S_SUCCESS){
std::cerr << err_to_str(res5.res) << "\n";
return 1;
}
*/
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2005-2007, Thorvald Natvig <[email protected]>
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 Mumble Developers 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 FOUNDATION 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 "MainWindow.h"
#include "AudioWizard.h"
#include "AudioInput.h"
#include "ConnectDialog.h"
#include "Player.h"
#include "Channel.h"
#include "ACLEditor.h"
#include "BanEditor.h"
#include "Connection.h"
#include "ServerHandler.h"
#include "About.h"
#include "GlobalShortcut.h"
#include "VersionCheck.h"
#include "PlayerModel.h"
#include "AudioStats.h"
#include "Plugins.h"
#include "Log.h"
#include "Overlay.h"
#include "Global.h"
#include "Database.h"
#include "ViewCert.h"
void MainWindow::msgServerJoin(Connection *, MessageServerJoin *msg) {
ClientPlayer *p = pmModel->addPlayer(msg->uiSession, msg->qsPlayerName);
p->iId = msg->iId;
g.l->log(Log::PlayerJoin, MainWindow::tr("Joined server: %1.").arg(p->qsName));
}
#define MSG_INIT \
ClientPlayer *pSrc=ClientPlayer::get(msg->uiSession); \
Q_UNUSED(pSrc);
#define VICTIM_INIT \
ClientPlayer *pDst=ClientPlayer::get(msg->uiVictim); \
if (! pDst) { \
qWarning("MainWindow: Message for nonexistant victim %d.", msg->uiVictim); \
return; \
}
void MainWindow::msgServerLeave(Connection *, MessageServerLeave *msg) {
MSG_INIT;
if (! pSrc)
return;
g.l->log(Log::PlayerLeave, MainWindow::tr("Left server: %1.").arg(pSrc->qsName));
pmModel->removePlayer(pSrc);
}
void MainWindow::msgServerBanList(Connection *, MessageServerBanList *msg) {
if (banEdit) {
banEdit->reject();
delete banEdit;
banEdit = NULL;
}
banEdit = new BanEditor(msg, this);
banEdit->show();
}
void MainWindow::msgSpeex(Connection *, MessageSpeex *) {
}
void MainWindow::msgPlayerSelfMuteDeaf(Connection *, MessagePlayerSelfMuteDeaf *msg) {
MSG_INIT;
if (! pSrc)
return;
pSrc->setSelfMuteDeaf(msg->bMute, msg->bDeaf);
if (msg->uiSession == g.uiSession || ! g.uiSession)
return;
if (pSrc->cChannel != ClientPlayer::get(g.uiSession)->cChannel)
return;
QString name = pSrc->qsName;
if (msg->bMute && msg->bDeaf)
g.l->log(Log::OtherSelfMute, MainWindow::tr("%1 is now muted and deafened.").arg(name));
else if (msg->bMute)
g.l->log(Log::OtherSelfMute, MainWindow::tr("%1 is now muted.").arg(name));
else
g.l->log(Log::OtherSelfMute, MainWindow::tr("%1 is now unmuted.").arg(name));
}
void MainWindow::msgPlayerMute(Connection *, MessagePlayerMute *msg) {
MSG_INIT;
VICTIM_INIT;
pDst->setMute(msg->bMute);
if (!g.uiSession || pDst->cChannel != ClientPlayer::get(g.uiSession)->cChannel)
return;
QString vic = pDst->qsName;
QString admin = pSrc ? pSrc->qsName : MainWindow::tr("server");
if (msg->uiVictim == g.uiSession)
g.l->log(Log::YouMuted, msg->bMute ? MainWindow::tr("You were muted by %1.").arg(admin) : MainWindow::tr("You were unmuted by %1.").arg(admin));
else
g.l->log((msg->uiSession == g.uiSession) ? Log::YouMutedOther : Log::OtherMutedOther, msg->bMute ? MainWindow::tr("%1 muted by %2.").arg(vic).arg(admin) : MainWindow::tr("%1 unmuted by %2.").arg(vic).arg(admin));
}
void MainWindow::msgPlayerDeaf(Connection *, MessagePlayerDeaf *msg) {
MSG_INIT;
VICTIM_INIT;
pDst->setDeaf(msg->bDeaf);
if (!g.uiSession || pDst->cChannel != ClientPlayer::get(g.uiSession)->cChannel)
return;
QString vic = pDst->qsName;
QString admin = pSrc ? pSrc->qsName : MainWindow::tr("server");
if (msg->uiVictim == g.uiSession)
g.l->log(Log::YouMuted, msg->bDeaf ? MainWindow::tr("You were deafened by %1.").arg(admin) : MainWindow::tr("You were undeafened by %1.").arg(admin));
else
g.l->log((msg->uiSession == g.uiSession) ? Log::YouMutedOther : Log::OtherMutedOther, msg->bDeaf ? MainWindow::tr("%1 deafened by %2.").arg(vic).arg(admin) : MainWindow::tr("%1 undeafened by %2.").arg(vic).arg(admin));
}
void MainWindow::msgPlayerKick(Connection *, MessagePlayerKick *msg) {
MSG_INIT;
VICTIM_INIT;
QString admin = pSrc ? pSrc->qsName : QLatin1String("server");
if (msg->uiVictim == g.uiSession) {
g.l->log(Log::YouKicked, MainWindow::tr("You were kicked from the server by %1: %2.").arg(admin).arg(msg->qsReason));
g.l->setIgnore(Log::ServerDisconnected, 1);
} else {
g.l->setIgnore(Log::PlayerLeave, 1);
g.l->log((msg->uiSession == g.uiSession) ? Log::YouKicked : Log::PlayerKicked, MainWindow::tr("%3 was kicked from the server by %1: %2.").arg(admin).arg(msg->qsReason).arg(pDst->qsName));
}
}
void MainWindow::msgPlayerBan(Connection *, MessagePlayerBan *msg) {
MSG_INIT;
VICTIM_INIT;
QString admin = pSrc ? pSrc->qsName : QLatin1String("server");
if (msg->uiVictim == g.uiSession) {
g.l->log(Log::YouKicked, MainWindow::tr("You were kicked and banned from the server by %1: %2.").arg(admin).arg(msg->qsReason));
g.l->setIgnore(Log::ServerDisconnected, 1);
} else {
g.l->setIgnore(Log::PlayerLeave, 1);
g.l->log((msg->uiSession == g.uiSession) ? Log::YouKicked : Log::PlayerKicked, MainWindow::tr("%3 was kicked and banned from the server by %1: %2.").arg(admin).arg(msg->qsReason).arg(pDst->qsName));
}
}
void MainWindow::msgPlayerMove(Connection *, MessagePlayerMove *msg) {
MSG_INIT;
VICTIM_INIT;
bool log = true;
if ((msg->uiVictim == g.uiSession) && (msg->uiSession == msg->uiVictim))
log = false;
if (g.uiSession == 0)
log = false;
QString pname = pDst->qsName;
QString admin = pSrc ? pSrc->qsName : QLatin1String("server");
if (log && (pDst->cChannel == ClientPlayer::get(g.uiSession)->cChannel)) {
if (pDst == pSrc || (!pSrc))
g.l->log(Log::ChannelJoin, MainWindow::tr("%1 left channel.").arg(pname));
else
g.l->log(Log::ChannelJoin, MainWindow::tr("%1 moved out by %2.").arg(pname).arg(admin));
}
Channel *c = Channel::get(msg->iChannelId);
if (!c) {
qWarning("MessagePlayerMove for unknown channel.");
c = Channel::get(0);
}
pmModel->movePlayer(pDst, c);
if (log && (pDst->cChannel == ClientPlayer::get(g.uiSession)->cChannel)) {
if (pDst == pSrc || (!pSrc))
g.l->log(Log::ChannelLeave, MainWindow::tr("%1 entered channel.").arg(pname));
else
g.l->log(Log::ChannelLeave, MainWindow::tr("%1 moved in by %2.").arg(pname).arg(admin));
}
}
void MainWindow::msgPlayerRename(Connection *, MessagePlayerRename *msg) {
MSG_INIT;
if (pSrc)
pmModel->renamePlayer(pSrc, msg->qsName);
}
void MainWindow::msgChannelAdd(Connection *, MessageChannelAdd *msg) {
Channel *p = Channel::get(msg->iParent);
if (p)
pmModel->addChannel(msg->iId, p, msg->qsName);
}
void MainWindow::msgChannelRemove(Connection *, MessageChannelRemove *msg) {
Channel *c = Channel::get(msg->iId);
if (c)
pmModel->removeChannel(c);
}
void MainWindow::msgChannelMove(Connection *, MessageChannelMove *msg) {
Channel *c = Channel::get(msg->iId);
Channel *p = Channel::get(msg->iParent);
if (c && p)
pmModel->moveChannel(c, p);
}
void MainWindow::msgChannelRename(Connection *, MessageChannelRename *msg) {
Channel *c = Channel::get(msg->iId);
if (c && c->cParent)
pmModel->renameChannel(c, msg->qsName);
}
void MainWindow::msgChannelLink(Connection *, MessageChannelLink *msg) {
Channel *c = Channel::get(msg->iId);
if (!c)
return;
QList<Channel *> qlChans;
foreach(int id, msg->qlTargets) {
Channel *l = Channel::get(id);
if (l)
qlChans << l;
}
switch (msg->ltType) {
case MessageChannelLink::Link:
pmModel->linkChannels(c, qlChans);
break;
case MessageChannelLink::Unlink:
pmModel->unlinkChannels(c, qlChans);
break;
case MessageChannelLink::UnlinkAll:
pmModel->unlinkAll(c);
break;
default:
qFatal("Unknown link message");
}
}
void MainWindow::msgServerAuthenticate(Connection *, MessageServerAuthenticate *) {
}
void MainWindow::msgServerReject(Connection *, MessageServerReject *msg) {
rtLast = msg->rtType;
g.l->log(Log::ServerDisconnected, MainWindow::tr("Server connection rejected: %1.").arg(msg->qsReason));
g.l->setIgnore(Log::ServerDisconnected, 1);
}
void MainWindow::msgPermissionDenied(Connection *, MessagePermissionDenied *msg) {
g.l->log(Log::PermissionDenied, MainWindow::tr("Denied: %1.").arg(msg->qsReason));
}
void MainWindow::msgServerSync(Connection *, MessageServerSync *msg) {
MSG_INIT;
g.iMaxBandwidth = msg->iMaxBandwidth;
g.uiSession = msg->uiSession;
g.l->clearIgnore();
g.l->log(Log::Information, msg->qsWelcomeText);
pmModel->ensureSelfVisible();
bool found = false;
QStringList qlChans = qsDesiredChannel.split(QLatin1String("/"));
Channel *chan = Channel::get(0);
while (chan && qlChans.count() > 0) {
QString str = qlChans.takeFirst().toLower();
if (str.isEmpty())
continue;
foreach(Channel *c, chan->qlChannels) {
if (c->qsName.toLower() == str) {
found = true;
chan = c;
break;
}
}
}
if (found && (chan != ClientPlayer::get(g.uiSession)->cChannel)) {
MessagePlayerMove mpm;
mpm.uiVictim = g.uiSession;
mpm.iChannelId = chan->iId;
g.sh->sendMessage(&mpm);
}
}
void MainWindow::msgTextMessage(Connection *, MessageTextMessage *msg) {
MSG_INIT;
if (! pSrc)
return;
g.l->log(Log::TextMessage, MainWindow::tr("From %1: %2").arg(pSrc->qsName).arg(msg->qsMessage),
MainWindow::tr("Message from %1").arg(pSrc->qsName));
}
void MainWindow::msgEditACL(Connection *, MessageEditACL *msg) {
if (aclEdit) {
aclEdit->reject();
delete aclEdit;
aclEdit = NULL;
}
aclEdit = new ACLEditor(msg, this);
aclEdit->show();
}
void MainWindow::msgQueryUsers(Connection *, MessageQueryUsers *msg) {
if (aclEdit)
aclEdit->returnQuery(msg);
}
void MainWindow::msgPing(Connection *, MessagePing *) {
}
void MainWindow::msgTexture(Connection *, MessageTexture *msg) {
if (! msg->qbaTexture.isEmpty())
g.o->textureResponse(msg->iPlayerId,msg->qbaTexture);
}
void MainWindow::msgCryptSetup(Connection *, MessageCryptSetup *msg) {
ConnectionPtr c= g.sh->cConnection;
if (! c)
return;
c->csCrypt.setKey(reinterpret_cast<const unsigned char *>(msg->qbaKey.constData()), reinterpret_cast<const unsigned char *>(msg->qbaClientNonce.constData()), reinterpret_cast<const unsigned char *>(msg->qbaServerNonce.constData()));
}
void MainWindow::msgCryptSync(Connection *, MessageCryptSync *msg) {
ConnectionPtr c= g.sh->cConnection;
if (! c)
return;
if (msg->qbaNonce.isEmpty()) {
msg->qbaNonce = QByteArray(reinterpret_cast<const char *>(c->csCrypt.encrypt_iv), AES_BLOCK_SIZE);
g.sh->sendMessage(msg);
} else if (msg->qbaNonce.size() == AES_BLOCK_SIZE) {
memcpy(c->csCrypt.decrypt_iv, msg->qbaNonce.constData(), AES_BLOCK_SIZE);
}
}
<commit_msg>Strip HTML from incoming TextMessage<commit_after>/* Copyright (C) 2005-2007, Thorvald Natvig <[email protected]>
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 Mumble Developers 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 FOUNDATION 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 "MainWindow.h"
#include "AudioWizard.h"
#include "AudioInput.h"
#include "ConnectDialog.h"
#include "Player.h"
#include "Channel.h"
#include "ACLEditor.h"
#include "BanEditor.h"
#include "Connection.h"
#include "ServerHandler.h"
#include "About.h"
#include "GlobalShortcut.h"
#include "VersionCheck.h"
#include "PlayerModel.h"
#include "AudioStats.h"
#include "Plugins.h"
#include "Log.h"
#include "Overlay.h"
#include "Global.h"
#include "Database.h"
#include "ViewCert.h"
void MainWindow::msgServerJoin(Connection *, MessageServerJoin *msg) {
ClientPlayer *p = pmModel->addPlayer(msg->uiSession, msg->qsPlayerName);
p->iId = msg->iId;
g.l->log(Log::PlayerJoin, MainWindow::tr("Joined server: %1.").arg(p->qsName));
}
#define MSG_INIT \
ClientPlayer *pSrc=ClientPlayer::get(msg->uiSession); \
Q_UNUSED(pSrc);
#define VICTIM_INIT \
ClientPlayer *pDst=ClientPlayer::get(msg->uiVictim); \
if (! pDst) { \
qWarning("MainWindow: Message for nonexistant victim %d.", msg->uiVictim); \
return; \
}
void MainWindow::msgServerLeave(Connection *, MessageServerLeave *msg) {
MSG_INIT;
if (! pSrc)
return;
g.l->log(Log::PlayerLeave, MainWindow::tr("Left server: %1.").arg(pSrc->qsName));
pmModel->removePlayer(pSrc);
}
void MainWindow::msgServerBanList(Connection *, MessageServerBanList *msg) {
if (banEdit) {
banEdit->reject();
delete banEdit;
banEdit = NULL;
}
banEdit = new BanEditor(msg, this);
banEdit->show();
}
void MainWindow::msgSpeex(Connection *, MessageSpeex *) {
}
void MainWindow::msgPlayerSelfMuteDeaf(Connection *, MessagePlayerSelfMuteDeaf *msg) {
MSG_INIT;
if (! pSrc)
return;
pSrc->setSelfMuteDeaf(msg->bMute, msg->bDeaf);
if (msg->uiSession == g.uiSession || ! g.uiSession)
return;
if (pSrc->cChannel != ClientPlayer::get(g.uiSession)->cChannel)
return;
QString name = pSrc->qsName;
if (msg->bMute && msg->bDeaf)
g.l->log(Log::OtherSelfMute, MainWindow::tr("%1 is now muted and deafened.").arg(name));
else if (msg->bMute)
g.l->log(Log::OtherSelfMute, MainWindow::tr("%1 is now muted.").arg(name));
else
g.l->log(Log::OtherSelfMute, MainWindow::tr("%1 is now unmuted.").arg(name));
}
void MainWindow::msgPlayerMute(Connection *, MessagePlayerMute *msg) {
MSG_INIT;
VICTIM_INIT;
pDst->setMute(msg->bMute);
if (!g.uiSession || pDst->cChannel != ClientPlayer::get(g.uiSession)->cChannel)
return;
QString vic = pDst->qsName;
QString admin = pSrc ? pSrc->qsName : MainWindow::tr("server");
if (msg->uiVictim == g.uiSession)
g.l->log(Log::YouMuted, msg->bMute ? MainWindow::tr("You were muted by %1.").arg(admin) : MainWindow::tr("You were unmuted by %1.").arg(admin));
else
g.l->log((msg->uiSession == g.uiSession) ? Log::YouMutedOther : Log::OtherMutedOther, msg->bMute ? MainWindow::tr("%1 muted by %2.").arg(vic).arg(admin) : MainWindow::tr("%1 unmuted by %2.").arg(vic).arg(admin));
}
void MainWindow::msgPlayerDeaf(Connection *, MessagePlayerDeaf *msg) {
MSG_INIT;
VICTIM_INIT;
pDst->setDeaf(msg->bDeaf);
if (!g.uiSession || pDst->cChannel != ClientPlayer::get(g.uiSession)->cChannel)
return;
QString vic = pDst->qsName;
QString admin = pSrc ? pSrc->qsName : MainWindow::tr("server");
if (msg->uiVictim == g.uiSession)
g.l->log(Log::YouMuted, msg->bDeaf ? MainWindow::tr("You were deafened by %1.").arg(admin) : MainWindow::tr("You were undeafened by %1.").arg(admin));
else
g.l->log((msg->uiSession == g.uiSession) ? Log::YouMutedOther : Log::OtherMutedOther, msg->bDeaf ? MainWindow::tr("%1 deafened by %2.").arg(vic).arg(admin) : MainWindow::tr("%1 undeafened by %2.").arg(vic).arg(admin));
}
void MainWindow::msgPlayerKick(Connection *, MessagePlayerKick *msg) {
MSG_INIT;
VICTIM_INIT;
QString admin = pSrc ? pSrc->qsName : QLatin1String("server");
if (msg->uiVictim == g.uiSession) {
g.l->log(Log::YouKicked, MainWindow::tr("You were kicked from the server by %1: %2.").arg(admin).arg(msg->qsReason));
g.l->setIgnore(Log::ServerDisconnected, 1);
} else {
g.l->setIgnore(Log::PlayerLeave, 1);
g.l->log((msg->uiSession == g.uiSession) ? Log::YouKicked : Log::PlayerKicked, MainWindow::tr("%3 was kicked from the server by %1: %2.").arg(admin).arg(msg->qsReason).arg(pDst->qsName));
}
}
void MainWindow::msgPlayerBan(Connection *, MessagePlayerBan *msg) {
MSG_INIT;
VICTIM_INIT;
QString admin = pSrc ? pSrc->qsName : QLatin1String("server");
if (msg->uiVictim == g.uiSession) {
g.l->log(Log::YouKicked, MainWindow::tr("You were kicked and banned from the server by %1: %2.").arg(admin).arg(msg->qsReason));
g.l->setIgnore(Log::ServerDisconnected, 1);
} else {
g.l->setIgnore(Log::PlayerLeave, 1);
g.l->log((msg->uiSession == g.uiSession) ? Log::YouKicked : Log::PlayerKicked, MainWindow::tr("%3 was kicked and banned from the server by %1: %2.").arg(admin).arg(msg->qsReason).arg(pDst->qsName));
}
}
void MainWindow::msgPlayerMove(Connection *, MessagePlayerMove *msg) {
MSG_INIT;
VICTIM_INIT;
bool log = true;
if ((msg->uiVictim == g.uiSession) && (msg->uiSession == msg->uiVictim))
log = false;
if (g.uiSession == 0)
log = false;
QString pname = pDst->qsName;
QString admin = pSrc ? pSrc->qsName : QLatin1String("server");
if (log && (pDst->cChannel == ClientPlayer::get(g.uiSession)->cChannel)) {
if (pDst == pSrc || (!pSrc))
g.l->log(Log::ChannelJoin, MainWindow::tr("%1 left channel.").arg(pname));
else
g.l->log(Log::ChannelJoin, MainWindow::tr("%1 moved out by %2.").arg(pname).arg(admin));
}
Channel *c = Channel::get(msg->iChannelId);
if (!c) {
qWarning("MessagePlayerMove for unknown channel.");
c = Channel::get(0);
}
pmModel->movePlayer(pDst, c);
if (log && (pDst->cChannel == ClientPlayer::get(g.uiSession)->cChannel)) {
if (pDst == pSrc || (!pSrc))
g.l->log(Log::ChannelLeave, MainWindow::tr("%1 entered channel.").arg(pname));
else
g.l->log(Log::ChannelLeave, MainWindow::tr("%1 moved in by %2.").arg(pname).arg(admin));
}
}
void MainWindow::msgPlayerRename(Connection *, MessagePlayerRename *msg) {
MSG_INIT;
if (pSrc)
pmModel->renamePlayer(pSrc, msg->qsName);
}
void MainWindow::msgChannelAdd(Connection *, MessageChannelAdd *msg) {
Channel *p = Channel::get(msg->iParent);
if (p)
pmModel->addChannel(msg->iId, p, msg->qsName);
}
void MainWindow::msgChannelRemove(Connection *, MessageChannelRemove *msg) {
Channel *c = Channel::get(msg->iId);
if (c)
pmModel->removeChannel(c);
}
void MainWindow::msgChannelMove(Connection *, MessageChannelMove *msg) {
Channel *c = Channel::get(msg->iId);
Channel *p = Channel::get(msg->iParent);
if (c && p)
pmModel->moveChannel(c, p);
}
void MainWindow::msgChannelRename(Connection *, MessageChannelRename *msg) {
Channel *c = Channel::get(msg->iId);
if (c && c->cParent)
pmModel->renameChannel(c, msg->qsName);
}
void MainWindow::msgChannelLink(Connection *, MessageChannelLink *msg) {
Channel *c = Channel::get(msg->iId);
if (!c)
return;
QList<Channel *> qlChans;
foreach(int id, msg->qlTargets) {
Channel *l = Channel::get(id);
if (l)
qlChans << l;
}
switch (msg->ltType) {
case MessageChannelLink::Link:
pmModel->linkChannels(c, qlChans);
break;
case MessageChannelLink::Unlink:
pmModel->unlinkChannels(c, qlChans);
break;
case MessageChannelLink::UnlinkAll:
pmModel->unlinkAll(c);
break;
default:
qFatal("Unknown link message");
}
}
void MainWindow::msgServerAuthenticate(Connection *, MessageServerAuthenticate *) {
}
void MainWindow::msgServerReject(Connection *, MessageServerReject *msg) {
rtLast = msg->rtType;
g.l->log(Log::ServerDisconnected, MainWindow::tr("Server connection rejected: %1.").arg(msg->qsReason));
g.l->setIgnore(Log::ServerDisconnected, 1);
}
void MainWindow::msgPermissionDenied(Connection *, MessagePermissionDenied *msg) {
g.l->log(Log::PermissionDenied, MainWindow::tr("Denied: %1.").arg(msg->qsReason));
}
void MainWindow::msgServerSync(Connection *, MessageServerSync *msg) {
MSG_INIT;
g.iMaxBandwidth = msg->iMaxBandwidth;
g.uiSession = msg->uiSession;
g.l->clearIgnore();
g.l->log(Log::Information, msg->qsWelcomeText);
pmModel->ensureSelfVisible();
bool found = false;
QStringList qlChans = qsDesiredChannel.split(QLatin1String("/"));
Channel *chan = Channel::get(0);
while (chan && qlChans.count() > 0) {
QString str = qlChans.takeFirst().toLower();
if (str.isEmpty())
continue;
foreach(Channel *c, chan->qlChannels) {
if (c->qsName.toLower() == str) {
found = true;
chan = c;
break;
}
}
}
if (found && (chan != ClientPlayer::get(g.uiSession)->cChannel)) {
MessagePlayerMove mpm;
mpm.uiVictim = g.uiSession;
mpm.iChannelId = chan->iId;
g.sh->sendMessage(&mpm);
}
}
void MainWindow::msgTextMessage(Connection *, MessageTextMessage *msg) {
MSG_INIT;
if (! pSrc)
return;
QTextDocument td;
td.setHtml(msg->qsMessage);
g.l->log(Log::TextMessage, MainWindow::tr("From %1: %2").arg(pSrc->qsName).arg(td.toPlainText()),
MainWindow::tr("Message from %1").arg(pSrc->qsName));
}
void MainWindow::msgEditACL(Connection *, MessageEditACL *msg) {
if (aclEdit) {
aclEdit->reject();
delete aclEdit;
aclEdit = NULL;
}
aclEdit = new ACLEditor(msg, this);
aclEdit->show();
}
void MainWindow::msgQueryUsers(Connection *, MessageQueryUsers *msg) {
if (aclEdit)
aclEdit->returnQuery(msg);
}
void MainWindow::msgPing(Connection *, MessagePing *) {
}
void MainWindow::msgTexture(Connection *, MessageTexture *msg) {
if (! msg->qbaTexture.isEmpty())
g.o->textureResponse(msg->iPlayerId,msg->qbaTexture);
}
void MainWindow::msgCryptSetup(Connection *, MessageCryptSetup *msg) {
ConnectionPtr c= g.sh->cConnection;
if (! c)
return;
c->csCrypt.setKey(reinterpret_cast<const unsigned char *>(msg->qbaKey.constData()), reinterpret_cast<const unsigned char *>(msg->qbaClientNonce.constData()), reinterpret_cast<const unsigned char *>(msg->qbaServerNonce.constData()));
}
void MainWindow::msgCryptSync(Connection *, MessageCryptSync *msg) {
ConnectionPtr c= g.sh->cConnection;
if (! c)
return;
if (msg->qbaNonce.isEmpty()) {
msg->qbaNonce = QByteArray(reinterpret_cast<const char *>(c->csCrypt.encrypt_iv), AES_BLOCK_SIZE);
g.sh->sendMessage(msg);
} else if (msg->qbaNonce.size() == AES_BLOCK_SIZE) {
memcpy(c->csCrypt.decrypt_iv, msg->qbaNonce.constData(), AES_BLOCK_SIZE);
}
}
<|endoftext|> |
<commit_before>/*********************************************************************************************************
* Phoenix.cpp
* Note: Phoenix Main
* Date: @2014.08
* E-mail:<[email protected]>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#ifndef _WIN32
#error "Only Support Windows"
#endif
#include <Phoenix.h>
#include <Processthreadsapi.h>
#include <wchar.h>
#include <string>
#include <map>
#include <Shobjidl.h>
#include <vector>
#include "UIWindow.h"
#include "Header.hpp"
#include "Arguments.hpp"
#include "TaskProcess.hpp"
#include <iostream>
//class UIWindow;
static std::map<int,HINSTANCE> ChildProcessMap;
int WINAPI UIChannelProviders(ProcessParameters &processParameters)
{
if(!(processParameters.cmdMode&OptionLevel_New))
{
if(!CreateMutexProviders())
{
return 1;
}
}
SetCurrentProcessExplicitAppUserModelID(PHOENX_EDITOR_APPID);
UIWindow windowUI;
windowUI.Runable();
//while()
return 0;
}
///<summary>
// int WINAPI TaskChannelProviders
///</summary>
int WINAPI TaskChannelProviders()
{
return 0;
}
int WINAPI wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
ProcessParameters processParameters;
if(!ArgumentsFlow(processParameters))
{
return 1;
}
if(processParameters.taskMode==InstanceLevel_Task)
return TaskChannelProviders();
return UIChannelProviders(processParameters);
}
<commit_msg>Phoenix add Option<commit_after>/*********************************************************************************************************
* Phoenix.cpp
* Note: Phoenix Main
* Date: @2014.08
* E-mail:<[email protected]>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#ifndef _WIN32
#error "Only Support Windows"
#endif
#include <Phoenix.h>
#include <Processthreadsapi.h>
#include <wchar.h>
#include <string>
#include <map>
#include <Shobjidl.h>
#include <vector>
#include "UIWindow.h"
#include "Header.hpp"
#include "Arguments.hpp"
#include "TaskProcess.hpp"
#include <iostream>
//class UIWindow;
static std::map<int,HINSTANCE> ChildProcessMap;
int WINAPI UIChannelProviders(ProcessParameters &processParameters)
{
if(!(processParameters.cmdMode&OptionLevel_New))
{
if(!CreateMutexProviders())
{
return 1;
}
}
SetCurrentProcessExplicitAppUserModelID(PHOENX_EDITOR_APPID);
UIWindow windowUI;
windowUI.Runable();
//while()
return 0;
}
///<summary>
// int WINAPI TaskChannelProviders
// TaskProcess Parser New Style CommandLine
///</summary>
int WINAPI TaskChannelProviders()
{
return 0;
}
int WINAPI wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
ProcessParameters processParameters;
if(!ArgumentsFlow(processParameters))
{
return 1;
}
if(processParameters.taskMode==InstanceLevel_Task)
return TaskChannelProviders();
if((processParameters.cmdMode&OptionLevel_Version)){
///Do Print Phoenix version
}
if((processParameters.cmdMode&OptionLevel_Usage)){
//
}
if((processParameters.cmdMode&OptionLevel_Init)){
//
}
return UIChannelProviders(processParameters);
}
<|endoftext|> |
<commit_before>#include "yaml-cpp/ostream_wrapper.h"
#include <cstring>
#include <iostream>
namespace YAML
{
ostream_wrapper::ostream_wrapper(): m_buffer(1), m_pStream(0), m_pos(0), m_row(0), m_col(0), m_comment(false)
{
}
ostream_wrapper::ostream_wrapper(std::ostream& stream): m_pStream(&stream), m_pos(0), m_row(0), m_col(0), m_comment(false)
{
}
ostream_wrapper::~ostream_wrapper()
{
}
void ostream_wrapper::write(const std::string& str)
{
if(m_pStream) {
m_pStream->write(str.c_str(), str.size());
} else {
m_buffer.resize(std::max(m_buffer.size(), m_pos + str.size() + 1));
std::copy(str.begin(), str.end(), &m_buffer[m_pos]);
}
for(std::size_t i=0;i<str.size();i++)
update_pos(str[i]);
}
void ostream_wrapper::write(const char *str, std::size_t size)
{
if(m_pStream) {
m_pStream->write(str, size);
} else {
m_buffer.resize(std::max(m_buffer.size(), m_pos + size + 1));
std::copy(str, str + size, &m_buffer[m_pos]);
}
for(std::size_t i=0;i<size;i++)
update_pos(str[i]);
}
void ostream_wrapper::update_pos(char ch)
{
m_pos++;
m_col++;
if(ch == '\n') {
m_row++;
m_col = 0;
m_comment = false;
}
}
}
<commit_msg>Fixed missing header.<commit_after>#include "yaml-cpp/ostream_wrapper.h"
#include <cstring>
#include <iostream>
#include <algorithm>
namespace YAML
{
ostream_wrapper::ostream_wrapper(): m_buffer(1), m_pStream(0), m_pos(0), m_row(0), m_col(0), m_comment(false)
{
}
ostream_wrapper::ostream_wrapper(std::ostream& stream): m_pStream(&stream), m_pos(0), m_row(0), m_col(0), m_comment(false)
{
}
ostream_wrapper::~ostream_wrapper()
{
}
void ostream_wrapper::write(const std::string& str)
{
if(m_pStream) {
m_pStream->write(str.c_str(), str.size());
} else {
m_buffer.resize(std::max(m_buffer.size(), m_pos + str.size() + 1));
std::copy(str.begin(), str.end(), &m_buffer[m_pos]);
}
for(std::size_t i=0;i<str.size();i++)
update_pos(str[i]);
}
void ostream_wrapper::write(const char *str, std::size_t size)
{
if(m_pStream) {
m_pStream->write(str, size);
} else {
m_buffer.resize(std::max(m_buffer.size(), m_pos + size + 1));
std::copy(str, str + size, &m_buffer[m_pos]);
}
for(std::size_t i=0;i<size;i++)
update_pos(str[i]);
}
void ostream_wrapper::update_pos(char ch)
{
m_pos++;
m_col++;
if(ch == '\n') {
m_row++;
m_col = 0;
m_comment = false;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Instruments code to check for incorrect heap access. This checks
// for dereferencing 0 (null pointer access), reading past the valid
// top of sbrk()-addressible memory, and incorrect alignment notation.
//
#include "asm_v_wasm.h"
#include "asmjs/shared-constants.h"
#include "ir/bits.h"
#include "ir/function-type-utils.h"
#include "ir/import-utils.h"
#include "ir/load-utils.h"
#include "pass.h"
#include "wasm-builder.h"
#include "wasm.h"
namespace wasm {
const Name DYNAMICTOP_PTR_IMPORT("DYNAMICTOP_PTR");
const Name GET_SBRK_PTR_IMPORT("emscripten_get_sbrk_ptr");
const Name SEGFAULT_IMPORT("segfault");
const Name ALIGNFAULT_IMPORT("alignfault");
static Name getLoadName(Load* curr) {
std::string ret = "SAFE_HEAP_LOAD_";
ret += printType(curr->type);
ret += "_" + std::to_string(curr->bytes) + "_";
if (LoadUtils::isSignRelevant(curr) && !curr->signed_) {
ret += "U_";
}
if (curr->isAtomic) {
ret += "A";
} else {
ret += std::to_string(curr->align);
}
return ret;
}
static Name getStoreName(Store* curr) {
std::string ret = "SAFE_HEAP_STORE_";
ret += printType(curr->valueType);
ret += "_" + std::to_string(curr->bytes) + "_";
if (curr->isAtomic) {
ret += "A";
} else {
ret += std::to_string(curr->align);
}
return ret;
}
struct AccessInstrumenter : public WalkerPass<PostWalker<AccessInstrumenter>> {
bool isFunctionParallel() override { return true; }
AccessInstrumenter* create() override { return new AccessInstrumenter; }
void visitLoad(Load* curr) {
if (curr->type == unreachable) {
return;
}
Builder builder(*getModule());
replaceCurrent(
builder.makeCall(getLoadName(curr),
{
curr->ptr,
builder.makeConst(Literal(int32_t(curr->offset))),
},
curr->type));
}
void visitStore(Store* curr) {
if (curr->type == unreachable) {
return;
}
Builder builder(*getModule());
replaceCurrent(
builder.makeCall(getStoreName(curr),
{
curr->ptr,
builder.makeConst(Literal(int32_t(curr->offset))),
curr->value,
},
none));
}
};
struct SafeHeap : public Pass {
PassOptions options;
void run(PassRunner* runner, Module* module) override {
options = runner->options;
// add imports
addImports(module);
// instrument loads and stores
AccessInstrumenter().run(runner, module);
// add helper checking funcs and imports
addGlobals(module, module->features);
}
Name dynamicTopPtr, getSbrkPtr, segfault, alignfault;
void addImports(Module* module) {
ImportInfo info(*module);
// Older emscripten imports env.DYNAMICTOP_PTR.
// Newer emscripten imports emscripten_get_sbrk_ptr(), which is later
// optimized to have the number in the binary.
if (auto* existing = info.getImportedGlobal(ENV, DYNAMICTOP_PTR_IMPORT)) {
dynamicTopPtr = existing->name;
} else if (auto* existing =
info.getImportedFunction(ENV, GET_SBRK_PTR_IMPORT)) {
getSbrkPtr = existing->name;
} else {
auto* import = new Function;
import->name = getSbrkPtr = GET_SBRK_PTR_IMPORT;
import->module = ENV;
import->base = GET_SBRK_PTR_IMPORT;
auto* functionType = ensureFunctionType("i", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
if (auto* existing = info.getImportedFunction(ENV, SEGFAULT_IMPORT)) {
segfault = existing->name;
} else {
auto* import = new Function;
import->name = segfault = SEGFAULT_IMPORT;
import->module = ENV;
import->base = SEGFAULT_IMPORT;
auto* functionType = ensureFunctionType("v", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
if (auto* existing = info.getImportedFunction(ENV, ALIGNFAULT_IMPORT)) {
alignfault = existing->name;
} else {
auto* import = new Function;
import->name = alignfault = ALIGNFAULT_IMPORT;
import->module = ENV;
import->base = ALIGNFAULT_IMPORT;
auto* functionType = ensureFunctionType("v", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
}
bool
isPossibleAtomicOperation(Index align, Index bytes, bool shared, Type type) {
return align == bytes && shared && isIntegerType(type);
}
void addGlobals(Module* module, FeatureSet features) {
// load funcs
Load load;
for (auto type : {i32, i64, f32, f64, v128}) {
if (type == v128 && !features.hasSIMD()) {
continue;
}
load.type = type;
for (Index bytes : {1, 2, 4, 8, 16}) {
load.bytes = bytes;
if (bytes > getTypeSize(type) || (type == f32 && bytes != 4) ||
(type == f64 && bytes != 8) || (type == v128 && bytes != 16)) {
continue;
}
for (auto signed_ : {true, false}) {
load.signed_ = signed_;
if (isFloatType(type) && signed_) {
continue;
}
for (Index align : {1, 2, 4, 8, 16}) {
load.align = align;
if (align > bytes) {
continue;
}
for (auto isAtomic : {true, false}) {
load.isAtomic = isAtomic;
if (isAtomic && !isPossibleAtomicOperation(
align, bytes, module->memory.shared, type)) {
continue;
}
addLoadFunc(load, module);
}
}
}
}
}
// store funcs
Store store;
for (auto valueType : {i32, i64, f32, f64, v128}) {
if (valueType == v128 && !features.hasSIMD()) {
continue;
}
store.valueType = valueType;
store.type = none;
for (Index bytes : {1, 2, 4, 8, 16}) {
store.bytes = bytes;
if (bytes > getTypeSize(valueType) ||
(valueType == f32 && bytes != 4) ||
(valueType == f64 && bytes != 8) ||
(valueType == v128 && bytes != 16)) {
continue;
}
for (Index align : {1, 2, 4, 8, 16}) {
store.align = align;
if (align > bytes) {
continue;
}
for (auto isAtomic : {true, false}) {
store.isAtomic = isAtomic;
if (isAtomic && !isPossibleAtomicOperation(
align, bytes, module->memory.shared, valueType)) {
continue;
}
addStoreFunc(store, module);
}
}
}
}
}
// creates a function for a particular style of load
void addLoadFunc(Load style, Module* module) {
auto name = getLoadName(&style);
if (module->getFunctionOrNull(name)) {
return;
}
auto* func = new Function;
func->name = name;
func->params.push_back(i32); // pointer
func->params.push_back(i32); // offset
func->vars.push_back(i32); // pointer + offset
func->result = style.type;
Builder builder(*module);
auto* block = builder.makeBlock();
block->list.push_back(builder.makeLocalSet(
2,
builder.makeBinary(
AddInt32, builder.makeLocalGet(0, i32), builder.makeLocalGet(1, i32))));
// check for reading past valid memory: if pointer + offset + bytes
block->list.push_back(makeBoundsCheck(style.type, builder, 2, style.bytes));
// check proper alignment
if (style.align > 1) {
block->list.push_back(makeAlignCheck(style.align, builder, 2));
}
// do the load
auto* load = module->allocator.alloc<Load>();
*load = style; // basically the same as the template we are given!
load->ptr = builder.makeLocalGet(2, i32);
Expression* last = load;
if (load->isAtomic && load->signed_) {
// atomic loads cannot be signed, manually sign it
last = Bits::makeSignExt(load, load->bytes, *module);
load->signed_ = false;
}
block->list.push_back(last);
block->finalize(style.type);
func->body = block;
module->addFunction(func);
}
// creates a function for a particular type of store
void addStoreFunc(Store style, Module* module) {
auto name = getStoreName(&style);
if (module->getFunctionOrNull(name)) {
return;
}
auto* func = new Function;
func->name = name;
func->params.push_back(i32); // pointer
func->params.push_back(i32); // offset
func->params.push_back(style.valueType); // value
func->vars.push_back(i32); // pointer + offset
func->result = none;
Builder builder(*module);
auto* block = builder.makeBlock();
block->list.push_back(builder.makeLocalSet(
3,
builder.makeBinary(
AddInt32, builder.makeLocalGet(0, i32), builder.makeLocalGet(1, i32))));
// check for reading past valid memory: if pointer + offset + bytes
block->list.push_back(
makeBoundsCheck(style.valueType, builder, 3, style.bytes));
// check proper alignment
if (style.align > 1) {
block->list.push_back(makeAlignCheck(style.align, builder, 3));
}
// do the store
auto* store = module->allocator.alloc<Store>();
*store = style; // basically the same as the template we are given!
store->ptr = builder.makeLocalGet(3, i32);
store->value = builder.makeLocalGet(2, style.valueType);
block->list.push_back(store);
block->finalize(none);
func->body = block;
module->addFunction(func);
}
Expression* makeAlignCheck(Address align, Builder& builder, Index local) {
return builder.makeIf(
builder.makeBinary(AndInt32,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(align - 1)))),
builder.makeCall(alignfault, {}, none));
}
Expression*
makeBoundsCheck(Type type, Builder& builder, Index local, Index bytes) {
auto upperOp = options.lowMemoryUnused ? LtUInt32 : EqInt32;
auto upperBound = options.lowMemoryUnused ? PassOptions::LowMemoryBound : 0;
Expression* sbrkPtr;
if (dynamicTopPtr.is()) {
sbrkPtr = builder.makeGlobalGet(dynamicTopPtr, i32);
} else {
sbrkPtr = builder.makeCall(getSbrkPtr, {}, i32);
}
return builder.makeIf(
builder.makeBinary(
OrInt32,
builder.makeBinary(upperOp,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(upperBound)))),
builder.makeBinary(
GtUInt32,
builder.makeBinary(AddInt32,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(bytes)))),
builder.makeLoad(4, false, 0, 4, sbrkPtr, i32))),
builder.makeCall(segfault, {}, none));
}
};
Pass* createSafeHeapPass() { return new SafeHeap(); }
} // namespace wasm
<commit_msg>Handle sbrk import by emscripten+upstream in SafeHeap (#2332)<commit_after>/*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Instruments code to check for incorrect heap access. This checks
// for dereferencing 0 (null pointer access), reading past the valid
// top of sbrk()-addressible memory, and incorrect alignment notation.
//
#include "asm_v_wasm.h"
#include "asmjs/shared-constants.h"
#include "ir/bits.h"
#include "ir/function-type-utils.h"
#include "ir/import-utils.h"
#include "ir/load-utils.h"
#include "pass.h"
#include "wasm-builder.h"
#include "wasm.h"
namespace wasm {
static const Name DYNAMICTOP_PTR_IMPORT("DYNAMICTOP_PTR");
static const Name GET_SBRK_PTR_IMPORT("emscripten_get_sbrk_ptr");
static const Name SBRK("sbrk");
static const Name SEGFAULT_IMPORT("segfault");
static const Name ALIGNFAULT_IMPORT("alignfault");
static Name getLoadName(Load* curr) {
std::string ret = "SAFE_HEAP_LOAD_";
ret += printType(curr->type);
ret += "_" + std::to_string(curr->bytes) + "_";
if (LoadUtils::isSignRelevant(curr) && !curr->signed_) {
ret += "U_";
}
if (curr->isAtomic) {
ret += "A";
} else {
ret += std::to_string(curr->align);
}
return ret;
}
static Name getStoreName(Store* curr) {
std::string ret = "SAFE_HEAP_STORE_";
ret += printType(curr->valueType);
ret += "_" + std::to_string(curr->bytes) + "_";
if (curr->isAtomic) {
ret += "A";
} else {
ret += std::to_string(curr->align);
}
return ret;
}
struct AccessInstrumenter : public WalkerPass<PostWalker<AccessInstrumenter>> {
bool isFunctionParallel() override { return true; }
AccessInstrumenter* create() override { return new AccessInstrumenter; }
void visitLoad(Load* curr) {
if (curr->type == unreachable) {
return;
}
Builder builder(*getModule());
replaceCurrent(
builder.makeCall(getLoadName(curr),
{
curr->ptr,
builder.makeConst(Literal(int32_t(curr->offset))),
},
curr->type));
}
void visitStore(Store* curr) {
if (curr->type == unreachable) {
return;
}
Builder builder(*getModule());
replaceCurrent(
builder.makeCall(getStoreName(curr),
{
curr->ptr,
builder.makeConst(Literal(int32_t(curr->offset))),
curr->value,
},
none));
}
};
struct SafeHeap : public Pass {
PassOptions options;
void run(PassRunner* runner, Module* module) override {
options = runner->options;
// add imports
addImports(module);
// instrument loads and stores
AccessInstrumenter().run(runner, module);
// add helper checking funcs and imports
addGlobals(module, module->features);
}
Name dynamicTopPtr, getSbrkPtr, sbrk, segfault, alignfault;
void addImports(Module* module) {
ImportInfo info(*module);
// Older emscripten imports env.DYNAMICTOP_PTR.
// Newer emscripten imports emscripten_get_sbrk_ptr(), which is later
// optimized to have the number in the binary.
if (auto* existing = info.getImportedGlobal(ENV, DYNAMICTOP_PTR_IMPORT)) {
dynamicTopPtr = existing->name;
} else if (auto* existing =
info.getImportedFunction(ENV, GET_SBRK_PTR_IMPORT)) {
getSbrkPtr = existing->name;
} else if (auto* existing = info.getImportedFunction(ENV, SBRK)) {
sbrk = existing->name;
} else {
auto* import = new Function;
import->name = getSbrkPtr = GET_SBRK_PTR_IMPORT;
import->module = ENV;
import->base = GET_SBRK_PTR_IMPORT;
auto* functionType = ensureFunctionType("i", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
if (auto* existing = info.getImportedFunction(ENV, SEGFAULT_IMPORT)) {
segfault = existing->name;
} else {
auto* import = new Function;
import->name = segfault = SEGFAULT_IMPORT;
import->module = ENV;
import->base = SEGFAULT_IMPORT;
auto* functionType = ensureFunctionType("v", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
if (auto* existing = info.getImportedFunction(ENV, ALIGNFAULT_IMPORT)) {
alignfault = existing->name;
} else {
auto* import = new Function;
import->name = alignfault = ALIGNFAULT_IMPORT;
import->module = ENV;
import->base = ALIGNFAULT_IMPORT;
auto* functionType = ensureFunctionType("v", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
}
bool
isPossibleAtomicOperation(Index align, Index bytes, bool shared, Type type) {
return align == bytes && shared && isIntegerType(type);
}
void addGlobals(Module* module, FeatureSet features) {
// load funcs
Load load;
for (auto type : {i32, i64, f32, f64, v128}) {
if (type == v128 && !features.hasSIMD()) {
continue;
}
load.type = type;
for (Index bytes : {1, 2, 4, 8, 16}) {
load.bytes = bytes;
if (bytes > getTypeSize(type) || (type == f32 && bytes != 4) ||
(type == f64 && bytes != 8) || (type == v128 && bytes != 16)) {
continue;
}
for (auto signed_ : {true, false}) {
load.signed_ = signed_;
if (isFloatType(type) && signed_) {
continue;
}
for (Index align : {1, 2, 4, 8, 16}) {
load.align = align;
if (align > bytes) {
continue;
}
for (auto isAtomic : {true, false}) {
load.isAtomic = isAtomic;
if (isAtomic && !isPossibleAtomicOperation(
align, bytes, module->memory.shared, type)) {
continue;
}
addLoadFunc(load, module);
}
}
}
}
}
// store funcs
Store store;
for (auto valueType : {i32, i64, f32, f64, v128}) {
if (valueType == v128 && !features.hasSIMD()) {
continue;
}
store.valueType = valueType;
store.type = none;
for (Index bytes : {1, 2, 4, 8, 16}) {
store.bytes = bytes;
if (bytes > getTypeSize(valueType) ||
(valueType == f32 && bytes != 4) ||
(valueType == f64 && bytes != 8) ||
(valueType == v128 && bytes != 16)) {
continue;
}
for (Index align : {1, 2, 4, 8, 16}) {
store.align = align;
if (align > bytes) {
continue;
}
for (auto isAtomic : {true, false}) {
store.isAtomic = isAtomic;
if (isAtomic && !isPossibleAtomicOperation(
align, bytes, module->memory.shared, valueType)) {
continue;
}
addStoreFunc(store, module);
}
}
}
}
}
// creates a function for a particular style of load
void addLoadFunc(Load style, Module* module) {
auto name = getLoadName(&style);
if (module->getFunctionOrNull(name)) {
return;
}
auto* func = new Function;
func->name = name;
func->params.push_back(i32); // pointer
func->params.push_back(i32); // offset
func->vars.push_back(i32); // pointer + offset
func->result = style.type;
Builder builder(*module);
auto* block = builder.makeBlock();
block->list.push_back(builder.makeLocalSet(
2,
builder.makeBinary(
AddInt32, builder.makeLocalGet(0, i32), builder.makeLocalGet(1, i32))));
// check for reading past valid memory: if pointer + offset + bytes
block->list.push_back(makeBoundsCheck(style.type, builder, 2, style.bytes));
// check proper alignment
if (style.align > 1) {
block->list.push_back(makeAlignCheck(style.align, builder, 2));
}
// do the load
auto* load = module->allocator.alloc<Load>();
*load = style; // basically the same as the template we are given!
load->ptr = builder.makeLocalGet(2, i32);
Expression* last = load;
if (load->isAtomic && load->signed_) {
// atomic loads cannot be signed, manually sign it
last = Bits::makeSignExt(load, load->bytes, *module);
load->signed_ = false;
}
block->list.push_back(last);
block->finalize(style.type);
func->body = block;
module->addFunction(func);
}
// creates a function for a particular type of store
void addStoreFunc(Store style, Module* module) {
auto name = getStoreName(&style);
if (module->getFunctionOrNull(name)) {
return;
}
auto* func = new Function;
func->name = name;
func->params.push_back(i32); // pointer
func->params.push_back(i32); // offset
func->params.push_back(style.valueType); // value
func->vars.push_back(i32); // pointer + offset
func->result = none;
Builder builder(*module);
auto* block = builder.makeBlock();
block->list.push_back(builder.makeLocalSet(
3,
builder.makeBinary(
AddInt32, builder.makeLocalGet(0, i32), builder.makeLocalGet(1, i32))));
// check for reading past valid memory: if pointer + offset + bytes
block->list.push_back(
makeBoundsCheck(style.valueType, builder, 3, style.bytes));
// check proper alignment
if (style.align > 1) {
block->list.push_back(makeAlignCheck(style.align, builder, 3));
}
// do the store
auto* store = module->allocator.alloc<Store>();
*store = style; // basically the same as the template we are given!
store->ptr = builder.makeLocalGet(3, i32);
store->value = builder.makeLocalGet(2, style.valueType);
block->list.push_back(store);
block->finalize(none);
func->body = block;
module->addFunction(func);
}
Expression* makeAlignCheck(Address align, Builder& builder, Index local) {
return builder.makeIf(
builder.makeBinary(AndInt32,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(align - 1)))),
builder.makeCall(alignfault, {}, none));
}
Expression*
makeBoundsCheck(Type type, Builder& builder, Index local, Index bytes) {
auto upperOp = options.lowMemoryUnused ? LtUInt32 : EqInt32;
auto upperBound = options.lowMemoryUnused ? PassOptions::LowMemoryBound : 0;
Expression* brkLocation;
if (sbrk.is()) {
brkLocation =
builder.makeCall(sbrk, {builder.makeConst(Literal(int32_t(0)))}, i32);
} else {
Expression* sbrkPtr;
if (dynamicTopPtr.is()) {
sbrkPtr = builder.makeGlobalGet(dynamicTopPtr, i32);
} else {
sbrkPtr = builder.makeCall(getSbrkPtr, {}, i32);
}
brkLocation = builder.makeLoad(4, false, 0, 4, sbrkPtr, i32);
}
return builder.makeIf(
builder.makeBinary(
OrInt32,
builder.makeBinary(upperOp,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(upperBound)))),
builder.makeBinary(
GtUInt32,
builder.makeBinary(AddInt32,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(bytes)))),
brkLocation)),
builder.makeCall(segfault, {}, none));
}
};
Pass* createSafeHeapPass() { return new SafeHeap(); }
} // namespace wasm
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/menu/menu_config.h"
#include "grit/ui_resources.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/native_theme/native_theme_aura.h"
#include "ui/views/controls/menu/menu_image_util.h"
namespace views {
namespace {
#if defined(OS_CHROMEOS)
static const int kMenuCornerRadiusForAura = 2;
#else
static const int kMenuCornerRadiusForAura = 0;
#endif
} // namespace
#if !defined(OS_WIN)
void MenuConfig::Init(const ui::NativeTheme* theme) {
InitAura(theme);
}
#endif
void MenuConfig::InitAura(const ui::NativeTheme* theme) {
text_color = theme->GetSystemColor(
ui::NativeTheme::kColorId_EnabledMenuItemForegroundColor);
submenu_horizontal_inset = 1;
arrow_to_edge_padding = 20;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
arrow_width =
rb.GetImageNamed(IDR_MENU_HIERARCHY_ARROW).ToImageSkia()->width();
gfx::ImageSkia check = GetMenuCheckImage(false);
check_height = check.height();
item_min_height = 29;
separator_spacing_height = 7;
separator_lower_height = 8;
separator_upper_height = 8;
font = rb.GetFont(ResourceBundle::BaseFont);
label_to_arrow_padding = 20;
label_to_minor_text_padding = 20;
always_use_icon_to_label_padding = true;
align_arrow_and_shortcut = true;
offset_context_menus = true;
corner_radius = kMenuCornerRadiusForAura;
}
#if !defined(OS_WIN)
// static
const MenuConfig& MenuConfig::instance(const ui::NativeTheme* theme) {
static MenuConfig* views_instance = NULL;
if (!views_instance)
views_instance = new MenuConfig(theme ?
theme : ui::NativeTheme::instance());
return *views_instance;
}
#endif
} // namespace views
<commit_msg>linux_aura: Only call MenuConfig::InitAura() when using NativeThemeAura.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/menu/menu_config.h"
#include "grit/ui_resources.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/native_theme/native_theme_aura.h"
#include "ui/views/controls/menu/menu_image_util.h"
namespace views {
namespace {
#if defined(OS_CHROMEOS)
static const int kMenuCornerRadiusForAura = 2;
#else
static const int kMenuCornerRadiusForAura = 0;
#endif
} // namespace
#if !defined(OS_WIN)
void MenuConfig::Init(const ui::NativeTheme* theme) {
if (theme == ui::NativeThemeAura::instance())
InitAura(theme);
}
#endif
void MenuConfig::InitAura(const ui::NativeTheme* theme) {
text_color = theme->GetSystemColor(
ui::NativeTheme::kColorId_EnabledMenuItemForegroundColor);
submenu_horizontal_inset = 1;
arrow_to_edge_padding = 20;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
arrow_width =
rb.GetImageNamed(IDR_MENU_HIERARCHY_ARROW).ToImageSkia()->width();
gfx::ImageSkia check = GetMenuCheckImage(false);
check_height = check.height();
item_min_height = 29;
separator_spacing_height = 7;
separator_lower_height = 8;
separator_upper_height = 8;
font = rb.GetFont(ResourceBundle::BaseFont);
label_to_arrow_padding = 20;
label_to_minor_text_padding = 20;
always_use_icon_to_label_padding = true;
align_arrow_and_shortcut = true;
offset_context_menus = true;
corner_radius = kMenuCornerRadiusForAura;
}
#if !defined(OS_WIN)
// static
const MenuConfig& MenuConfig::instance(const ui::NativeTheme* theme) {
static MenuConfig* views_instance = NULL;
if (!views_instance)
views_instance = new MenuConfig(theme ?
theme : ui::NativeTheme::instance());
return *views_instance;
}
#endif
} // namespace views
<|endoftext|> |
<commit_before>/******************************************************************************
* AutonomousMode2.cpp - Autonomous sub-routine
*
* Copyright (c) 2013 FIRST Team 316, LuNaTeCs. All rights reserved.
*
* Code for our 2013 Robot, Sure Shot SAM
* for the FRC game Ultimate Ascent
*
* Shoot 3, pickup & fire frisbees from center line - Dead reckoning
*
******************************************************************************/
#include "Team316Robot.h"
#include "Autonomous.h"
//***********************************************************
//
// AUTONOMOUS MODE 2 - SHOOOT 3 FRISBEES THEN BACKUP AND PICK UP 2 FRISBEES OFF LINE THEN SHOOT THEM - use dead reckoning
//
//***********************************************************
void Team316Robot::AutonomousMode2()
{
switch (step)
{
case 1: // Turn the motor on and wait till we're up to speed
cout << "auto 2:1 -shooter speed = " << (shooterSpeedCounter->GetRPM() )<< ". time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
//during testing this only achieves about 3600 rpm by 2.5 seconds
if ( (shooterSpeedCounter->PIDGet() > 3800)
|| ((GetClock() - startTime) > 2.5) ) {
step++;
startTime = GetClock();
}
break;
case 2: // Fire the first shot
cout << "auto 2:2 - Fire the first shot. Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05) {
step++;
startTime = GetClock();
}
break;
case 3: // Wait for the motor to come back up to speed
//we lose approximately 500rpm in the shot - it takes approx 500ms to recover that
cout << "auto 2:3 - shooter speed = " << (shooterSpeedCounter->GetRPM() )<<" Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(false);
if ( ( (shooterSpeedCounter->PIDGet() > 3800) && (GetClock() - startTime > 0.2) )
|| ((GetClock() - startTime) > 1.5) ) {
step++;
startTime = GetClock();
}
break;
case 4: // Fire the second shot
cout << "auto 2:4 - Fire the second shot. Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05) {
step++;
startTime = GetClock();
}
break;
case 5:// Wait for the motor to come back up to speed
cout << "auto 2:5 - shooter speed = " << (shooterSpeedCounter->GetRPM() )<<" Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(false);
if ( ( (shooterSpeedCounter->PIDGet() > 3800) &&(GetClock() - startTime > 0.2) )
|| ((GetClock() - startTime) > 1.5) ) {
step++;
startTime = GetClock();
}
break;
case 6: // Fire the third shot
cout << "auto 2:6 - Fire the third shot. Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05) {
step++;
startTime = GetClock();
}
break;
case 7://pause so we do not disrupt the frisbee exiting the shooter
cout << "auto 2:7 - Pause so we do not disrupt the exiting frisbee. Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
shooterPistonSolenoid->Set(false);
shooterSpeedController->Disable();
if ((GetClock() - startTime) > 0.05) {
step++;
startTime = GetClock();
}
break;
case 8: // it takes exactly 4 second to lower the shooter from
// shooting position to loading position
cout << "auto 2:8 - shooter angle = " << (shooterAnglePot->GetAverageVoltage()) << ". time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
shooterPistonSolenoid->Set(false);
shooterSpeedController->Disable();
shooterAngleController->SetSetpoint(SHOOTER_LOWEST_HEIGHT);
shooterAngleController->Enable();
if (GetClock() - startTime > .5) {
step++;
startTime = GetClock();
}
break;
case 9: // here we are still continuing to lower the shooter
// but now that it is out of the way we can also lower the pickup arm
cout << "auto 2:9 - shooter angle = " << (shooterAnglePot->GetAverageVoltage()) << ". time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
shooterPistonSolenoid->Set(false);
shooterSpeedController->Disable();
shooterAngleController->SetSetpoint(SHOOTER_LOWEST_HEIGHT);
shooterAngleController->Enable();
pickupAngleMotor->Set(-1.0);
//TEST: this was a 3 second wait
if ( (GetClock() - startTime > 2.5)
|| ( shooterAnglePot->GetAverageVoltage() <= (SHOOTER_LOWEST_HEIGHT + .05) ) ) {
step++;
startTime = GetClock();
}
break;
case 10: // Drive backwards to pickup the frisbees - using dead reckoning and timing to know when to stop
cout << "auto 2:10 - Drive back. shooter angle = "<< (shooterAnglePot->GetAverageVoltage()) <<" time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
pickupMotor->Set(-0.9);
pickupAngleMotor->Set(-1.0);
shooterAngleController->SetSetpoint(SHOOTER_LOWEST_HEIGHT);
shooterAngleController->Enable();
frontLeftDriveMotor->Set(-0.5);
rearLeftDriveMotor->Set(-0.5);
frontRightDriveMotor->Set(0.5);
rearRightDriveMotor->Set(0.5);
if ((GetClock() - startTime) > 2.0) {
step++;
startTime = GetClock();
}
break;
case 11: // Stop the drive motors and wait for a moment
cout << "auto 2:11 - Pause and pickup. time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
pickupMotor->Set(-0.9);
pickupAngleMotor->Set(0.0); //we have to do this so that code does not lock
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
frontLeftDriveMotor->Set(0.0);
rearLeftDriveMotor->Set(0.0);
frontRightDriveMotor->Set(0.0);
rearRightDriveMotor->Set(0.0);
if ((GetClock() - startTime) > .15) {
step++;
startTime = GetClock();
}
break;
case 12: // Drive forwards to the goal
cout << "auto 2:12 - Drive forward. time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
pickupMotor->Set(-0.9);
pickupAngleMotor->Set(1.0);
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
frontLeftDriveMotor->Set(0.37); //it appears that the left drive is a little weaker in testing
rearLeftDriveMotor->Set(0.37);
frontRightDriveMotor->Set(-0.30);
rearRightDriveMotor->Set(-0.30);
if ((GetClock() - startTime) > 2.4) { //this allows the bot to coast into the stops
step++;
startTime = GetClock();
}
break;
case 13: // Stop the drive motors and wait till we're in position to fire
cout << "auto 2:13 - shooter angle = " << (shooterAnglePot->GetAverageVoltage()) << ". time = "<< (GetClock() - startTime)<< "Tot Time: " << (GetClock() - beginTime) <<endl;
pickupMotor->Set(-0.9);
pickupAngleMotor->Set(1.0);
frontLeftDriveMotor->Set(0.0);
rearLeftDriveMotor->Set(0.0);
frontRightDriveMotor->Set(0.0);
rearRightDriveMotor->Set(0.0);
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
//TEST: not sure if we should go with 4500 here to save time later on recoup but might be too strong?
shooterSpeedController->SetSetpoint(3800);
shooterSpeedController->Enable();
if (shooterAnglePot->GetAverageVoltage() >= (SHOOTER_TOP_HEIGHT - .05)
//TEST: this should actually take about 2.7 seconds or so
|| (GetClock() - startTime) > 3.2){
step++;
startTime = GetClock();
}
break;
case 14: // Fire the 4th shot
cout << "auto 2:14 - Fire the 4th shot. shooter speed = " << (shooterSpeedCounter->GetRPM() )<<" Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
pickupMotor->Set(0.0);
pickupAngleMotor->Set(1.0);
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05) {
step++;
startTime = GetClock();
}
break;
case 15: // Wait for the motor to come back up to speed
cout << "auto 2:15 - shooter speed = " << (shooterSpeedCounter->GetRPM() )<<" Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
pickupAngleMotor->Set(1.0);
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(false);
//TEST: we are almost out of time here so just throwing them up - in all likelyhood we only have 1 frisbee
if ( ( (shooterSpeedCounter->PIDGet() > 3800) && (GetClock() - startTime > 0.1) )
|| ((GetClock() - startTime) > 1.5) ) {
step++;
startTime = GetClock();
}
break;
case 16: // Fire the 5th shot
cout << "auto 2:16 - Fire the 5th shot. Time: " << (GetClock() - startTime) << "Tot Time: " << (GetClock() - beginTime) << endl;
pickupAngleMotor->Set(1.0);
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05) {
step++;
startTime = GetClock();
}
break;
case 17:
// Cleanup
cout << "auto 2:17 - cleanup" << "Tot Time: " << (GetClock() - beginTime) << endl;
pickupAngleMotor->Set(0.0);
shooterAngleController->Disable();
shooterPistonSolenoid->Set(false);
shooterSpeedController->Disable();
step++;
startTime = GetClock();
break;
case 18:
break;
default:
cout << "auto 2:default Error. You should not be here" << endl;
break;
}
}<commit_msg>Cleanup AutonomousMode2<commit_after>/******************************************************************************
* AutonomousMode2.cpp - Autonomous sub-routine
*
* Copyright (c) 2013 FIRST Team 316, LuNaTeCs. All rights reserved.
*
* Code for our 2013 Robot, Sure Shot SAM
* for the FRC game Ultimate Ascent
*
* Shoot 3, pickup & fire frisbees from center line - Dead reckoning
*
******************************************************************************/
#include "Team316Robot.h"
#include "Autonomous.h"
void Team316Robot::AutonomousMode2()
{
cout << "[Mode:2][Step:" << step <<"][SysTime:" << GetClock()
<< "ms][ElapsedTime:" << CURRENT_TIME << "ms] ";
switch (step)
{
case 1: // Turn the motor on and wait till we're up to speed
cout << "Setup - shooterSpeed: " << (shooterSpeedCounter->GetRPM()) << endl;
// Enable the shooter motor and angle controllers
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// during testing this only achieves about 3600 rpm by 2.5 seconds
if ((shooterSpeedCounter->PIDGet() > 3800) || ((GetClock() - startTime) > 2.5))
{
step++;
startTime = GetClock();
}
break;
case 2: // Fire the first shot
cout << "Fire the first shot" << endl;
// Update the shooter outputs
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Fire the frisbee
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05)
{
step++;
startTime = GetClock();
}
break;
case 3: // Wait for the motor to come back up to speed
cout << "Preparing for second shot - shooterSpeed: " << endl;
// Update the shooter outputs
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Retract the firing piston
shooterPistonSolenoid->Set(false);
// We lose approximately 500rpm in the shot - it takes approx 500ms to recover that
if ((shooterSpeedCounter->PIDGet() > 3800) || ((GetClock() - startTime) > 1.5) )
{
step++;
startTime = GetClock();
}
break;
case 4: // Fire the second shot
cout << "Fire the second shot" << endl;
// Update the shooter outputs
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Fire the frisbee
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05)
{
step++;
startTime = GetClock();
}
break;
case 5: // Wait for the motor to come back up to speed
cout << "Preparing for third shot - shooterSpeed: " << endl;
// Update the shooter outputs
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Retract the firing piston
shooterPistonSolenoid->Set(false);
if ((shooterSpeedCounter->PIDGet() > 3800)) || ((GetClock() - startTime) > 1.5) )
{
step++;
startTime = GetClock();
}
break;
case 6: // Fire the third shot
cout << "Fire the third shot" << endl;
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Fire the frisbee
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05)
{
step++;
startTime = GetClock();
}
break;
case 7: // pause so we do not disrupt the frisbee exiting the shooter
cout << "Brief pause to avoid disrupting the shot" << endl;
// Retract the firing piston
shooterPistonSolenoid->Set(false);
// Turn off the shooter motor
shooterSpeedController->Disable();
if ((GetClock() - startTime) > 0.05)
{
step++;
startTime = GetClock();
}
break;
case 8: // it takes exactly 4 second to lower the shooter from
// shooting position to loading position
cout << "shooterAngle: " << (shooterAnglePot->GetAverageVoltage()) << endl;
// Set the shooter to the pickup position
shooterAngleController->SetSetpoint(SHOOTER_LOWEST_HEIGHT);
shooterAngleController->Enable();
if (GetClock() - startTime > .5)
{
step++;
startTime = GetClock();
}
break;
case 9: // here we are still continuing to lower the shooter
// but now that it is out of the way we can also lower the pickup arm
cout << "shooterAngle = " << (shooterAnglePot->GetAverageVoltage()) << endl;
// Start lowering the pickup
pickupAngleMotor->Set(-1.0);
if ((GetClock() - startTime > 2.5) ||
(shooterAnglePot->GetAverageVoltage() <= (SHOOTER_LOWEST_HEIGHT + .05)))
{
step++;
startTime = GetClock();
}
break;
case 10: // Drive backwards to pickup the frisbees - using dead reckoning and timing to know when to stop
cout << "Drive back - shooterAngle: " << (shooterAnglePot->GetAverageVoltage()) << endl;
// Activate the pickup belts
pickupMotor->Set(-0.9);
// Continue lowering the pickup
pickupAngleMotor->Set(-1.0);
// Continue to lower the shooter
shooterAngleController->SetSetpoint(SHOOTER_LOWEST_HEIGHT);
shooterAngleController->Enable();
// Start to drive backwards at 50% power
frontLeftDriveMotor->Set(-0.5);
rearLeftDriveMotor->Set(-0.5);
frontRightDriveMotor->Set(0.5);
rearRightDriveMotor->Set(0.5);
if ((GetClock() - startTime) > 2.0)
{
step++;
startTime = GetClock();
}
break;
case 11: // Stop the drive motors and wait for a moment
cout << "Pause and pickup" << endl;
// Continue running the pickup belts
pickupMotor->Set(-0.9);
// Stop lowering the pickup
pickupAngleMotor->Set(0.0); // we have to do this so that code does not lock (?)
// Start moving the shooter back to the firing position
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
// Stop the drive motors
frontLeftDriveMotor->Set(0.0);
rearLeftDriveMotor->Set(0.0);
frontRightDriveMotor->Set(0.0);
rearRightDriveMotor->Set(0.0);
if ((GetClock() - startTime) > .15) {
step++;
startTime = GetClock();
}
break;
case 12: // Drive forwards to the goal
cout << "Drive forward" << endl;
// Continue running the pickup belts
pickupMotor->Set(-0.9);
// Start to raise the pickup system
pickupAngleMotor->Set(1.0);
// Continue moving the shooter to the firing position
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
// Start to drive forwards towards the goal
frontLeftDriveMotor->Set(0.37); // it appears that the left drive is a little weaker in testing
rearLeftDriveMotor->Set(0.37);
frontRightDriveMotor->Set(-0.30);
rearRightDriveMotor->Set(-0.30);
if ((GetClock() - startTime) > 2.4) // this allows the bot to coast into the stops
{
step++;
startTime = GetClock();
}
break;
case 13: // Stop the drive motors and wait till we're in position to fire
cout << "shooterAngle: " << (shooterAnglePot->GetAverageVoltage()) << endl;
// Continue running the pickup belts
pickupMotor->Set(-0.9);
// Continue to raise the pickup
pickupAngleMotor->Set(1.0);
// Stop the drive motors
frontLeftDriveMotor->Set(0.0);
rearLeftDriveMotor->Set(0.0);
frontRightDriveMotor->Set(0.0);
rearRightDriveMotor->Set(0.0);
// Continue moving the shooter to the firing position
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
// TEST: not sure if we should go with 4500 here to save time later
// on recoup but might be too strong?
shooterSpeedController->SetSetpoint(3800);
shooterSpeedController->Enable();
// TEST: this should actually take about 2.7 seconds or so
if (shooterAnglePot->GetAverageVoltage() >= (SHOOTER_TOP_HEIGHT - .05) || (GetClock() - startTime) > 3.2)
{
step++;
startTime = GetClock();
}
break;
case 14: // Fire the 4th shot
cout << "Fire the 4th shot - shooterSpeed: " << (shooterSpeedCounter->GetRPM()) << endl;
// Disable the pickup belts
pickupMotor->Set(0.0);
// Continue to raise the pickup
pickupAngleMotor->Set(1.0);
// Continue to raise the shooter to the target position
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
// Run the shooter motor
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Fire the frisbee
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05)
{
step++;
startTime = GetClock();
}
break;
case 15: // Wait for the motor to come back up to speed
cout << "shooterSpeed: " << (shooterSpeedCounter->GetRPM()) << endl;
// Why is this here? Driving the pickup up until it hits the limit/breaks itself!?
pickupAngleMotor->Set(1.0);
// Redundant code is redundant; set values for angle and speed of the shooter yet again
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
shooterPistonSolenoid->Set(false);
// TEST: we are almost out of time here so just throwing them up
// - in all likelyhood we only have 1 frisbee
if ((shooterSpeedCounter->PIDGet() > 3800) || ((GetClock() - startTime) > 1.5))
{
step++;
startTime = GetClock();
}
break;
case 16: // Fire the 5th shot
cout << "Fire the 5th shot" << endl;
pickupAngleMotor->Set(1.0);
// Redundant code is still redundant; set values for angle and
// speed of shooters one last time... just to be sure :\
shooterAngleController->SetSetpoint(SHOOTER_TOP_HEIGHT);
shooterAngleController->Enable();
shooterSpeedController->SetSetpoint(4500);
shooterSpeedController->Enable();
// Fire the last shot
shooterPistonSolenoid->Set(true);
if ((GetClock() - startTime) > 0.05)
{
step++;
startTime = GetClock();
}
break;
case 17: // Cleanup
cout << "Cleanup\n";
pickupAngleMotor->Set(0.0);
shooterAngleController->Disable();
shooterSpeedController->Disable();
shooterPistonSolenoid->Set(false);
step++;
startTime = GetClock();
break;
case 18:
cout << "Done\n";
break;
default: // Should never be reached
cout << "Error: default case" << endl;
break;
}
}<|endoftext|> |
<commit_before>/*************************************************************************\
**
** tOutput.cpp: Functions for output classes tOutput and tLOutput
**
** (see tOutput.h for a description of these classes)
**
** $Id: tOutput.cpp,v 1.42 2000-06-24 20:19:21 daniel Exp $
\*************************************************************************/
#include <math.h> // For fmod function
#include "tOutput.h"
/*************************************************************************\
**
** Constructor
**
** The constructor takes two arguments, a pointer to the mesh and
** a reference to an open input file. It reads the base name for the
** output files from the input file, and opens and initializes these.
**
** Input: meshPtr -- pointer to a tMesh object (or descendant), assumed
** valid
** infile -- reference to an open input file, assumed valid
**
\*************************************************************************/
template< class tSubNode >
tOutput<tSubNode>::tOutput( tMesh<tSubNode> * meshPtr, tInputFile &infile )
{
assert( meshPtr > 0 );
m = meshPtr;
infile.ReadItem( baseName, "OUTFILENAME" );
CreateAndOpenFile( &nodeofs, ".nodes" );
CreateAndOpenFile( &edgofs, ".edges" );
CreateAndOpenFile( &triofs, ".tri" );
CreateAndOpenFile( &zofs, ".z" );
CreateAndOpenFile( &vaofs, ".varea" );
}
/*************************************************************************\
**
** tOutput::CreateAndOpenFile
**
** Opens the output file stream pointed to by theOFStream, giving it the
** name <baseName><extension>, and checks to make sure that the ofstream
** is valid.
**
** Input: theOFStream -- ptr to an ofstream object
** extension -- file name extension (e.g., ".nodes")
** Output: theOFStream is initialized to create an open output file
** Assumes: extension is a null-terminated string, and the length of
** baseName plus extension doesn't exceed kMaxNameSize+6
** (ie, the extension is expected to be <= 6 characters)
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,
char *extension )
{
char fullName[kMaxNameSize+6]; // name of file to be created
strcpy( fullName, baseName );
strcat( fullName, extension );
theOFStream->open( fullName );
if( !theOFStream->good() )
ReportFatalError(
"I can't create files for output. Storage space may be exhausted.");
}
/*************************************************************************\
**
** tOutput::WriteOutput
**
** This function writes information about the mesh to four files called
** name.nodes, name.edges, name.tri, and name.z, where "name" is a
** name that the user has specified in the input file and which is
** stored in the data member baseName.
**
** Input: time -- time of the current output time-slice
** Output: the node, edge, and triangle ID numbers are modified so that
** they are numbered according to their position on the list
** Assumes: the four file ofstreams have been opened by the constructor
** and are valid
**
** TODO: deal with option for once-only printing of mesh when mesh not
** deforming
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteOutput( double time )
{
tMeshListIter<tSubNode> niter( m->getNodeList() ); // node list iterator
tMeshListIter<tEdge> eiter( m->getEdgeList() ); // edge list iterator
tPtrListIter<tTriangle> titer( m->getTriList() ); // tri list iterator
tNode * cn; // current node
tEdge * ce; // current edge
tTriangle * ct; // current triangle
int id; // id of element (node, edge, or triangle)
int nnodes = m->getNodeList()->getSize(); // # of nodes on list
int nedges = m->getEdgeList()->getSize(); // " edges "
int ntri = m->getTriList()->getSize(); // " triangles "
cout << "tOutput::WriteOutput()\n" << flush;
// Renumber IDs in order by position on list
for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )
cn->setID( id );
for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )
ce->setID( id );
for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )
ct->setID( id );
// Write node file, z file, and varea file
nodeofs << " " << time << endl << nnodes << endl;
zofs << " " << time << endl << nnodes << endl;
vaofs << " " << time << endl << nnodes << endl;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
{
nodeofs << cn->getX() << " " << cn->getY() << " "
<< cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl;
zofs << cn->getZ() << endl;
vaofs << cn->getVArea() << endl;
}
// Write edge file
edgofs << " " << time << endl << nedges << endl;
for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )
edgofs << ce->getOriginPtrNC()->getID() << " "
<< ce->getDestinationPtrNC()->getID() << " "
<< ce->getCCWEdg()->getID() << endl;
// Write triangle file
int i;
triofs << " " << time << endl << ntri << endl;
for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )
{
for( i=0; i<=2; i++ )
triofs << ct->pPtr(i)->getID() << " ";
for( i=0; i<=2; i++ )
{
if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " ";
else triofs << "-1 ";
}
triofs << ct->ePtr(0)->getID() << " "
<< ct->ePtr(1)->getID() << " "
<< ct->ePtr(2)->getID() << endl;
}
// Call virtual function to write any additional data
WriteNodeData( time );
}
/*************************************************************************\
**
** tOutput::WriteNodeData
**
** This is a virtual function which can be overridden to write any
** additional node data. The base class version does nothing.
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteNodeData( double time )
{}
/*************************************************************************\
**
** tLOutput constructor
**
** Creates and opens a series of files for drainage areas, slopes, etc.
**
** Modifications:
** - 1/00 added "opOpt" and creation of veg output file (GT)
** - added flow depth output file (GT 1/00)
\*************************************************************************/
template< class tSubNode >
tLOutput<tSubNode>::tLOutput( tMesh<tSubNode> *meshPtr, tInputFile &infile )
: tOutput<tSubNode>( meshPtr, infile ) // call base-class constructor
{
int opOpt; // Optional modules: only output stuff when needed
int optTSOutput;
counter=0;
strcpy(nums, "0123456789");
CreateAndOpenFile( &drareaofs, ".area" );
CreateAndOpenFile( &netofs, ".net" );
CreateAndOpenFile( &slpofs, ".slp" );
CreateAndOpenFile( &qofs, ".q" );
CreateAndOpenFile( &texofs, ".tx" );
if( (opOpt = infile.ReadItem( opOpt, "OPTVEG" ) ) )
CreateAndOpenFile( &vegofs, ".veg" );
if( (opOpt = infile.ReadItem( opOpt, "OPTKINWAVE" ) ) )
CreateAndOpenFile( &flowdepofs, ".dep" );
if( (optTSOutput = infile.ReadItem( optTSOutput, "OPTTSOUTPUT" ) ) ) {
CreateAndOpenFile( &volsofs, ".vols" );
if( (opOpt = infile.ReadItem( opOpt, "OPTVEG" ) ) )
CreateAndOpenFile( &vegcovofs, ".vcov" );
CreateAndOpenFile( &tareaofs, ".tarea" );
}
}
/*************************************************************************\
**
** tLOutput::WriteNodeData
**
** This overridden virtual function writes output for tLNodes, including
** drainage areas, flow pathways, slopes, discharges, layer info, etc.
**
** Modifications:
** - 1/00 added output to veg output file (GT)
** - added output of flow depth; made slope output for all nodes (GT 1/00)
** - 6/00 layer info for each time step written to a different file (NG)
\*************************************************************************/
//TODO: should output boundary points as well so they'll map up with nodes
// for plotting. Means changing getSlope so it returns zero if flowedg
// undefined
template< class tSubNode >
void tLOutput<tSubNode>::WriteNodeData( double time )
{
tMeshListIter<tSubNode> ni( m->getNodeList() ); // node list iterator
tSubNode *cn; // current node
int nActiveNodes = m->getNodeList()->getActiveSize(); // # active nodes
int nnodes = m->getNodeList()->getSize(); // total # nodes
int i, j; // counters
//taking care of layer file, since new one each time step
char ext[7];
strcpy( ext, ".lay");
if(counter<10)
strncat( ext, &nums[counter], 1);
else if(counter>=10){
strncat(ext, &nums[counter/10], 1);
strncat(ext, &nums[(int) fmod((double)counter,10.0)], 1);
}
CreateAndOpenFile( &layofs, ext );
counter++;
// Write current time in each file
drareaofs << " " << time << "\n " << nActiveNodes << endl;
netofs << " " << time << "\n " << nActiveNodes << endl;
slpofs << " " << time << "\n " << nnodes << endl;
qofs << " " << time << "\n " << nnodes << endl;
layofs << " " << time << "\n" << nActiveNodes << endl;
texofs << " " << time << "\n" << nnodes << endl;
if( vegofs.good() ) vegofs << " " << time << "\n" << nnodes << endl;
if( flowdepofs.good() ) flowdepofs << " " << time << "\n" << nnodes << endl;
// Write data, including layer info
for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
{
assert( cn>0 );
drareaofs << cn->getDrArea() << endl;
if( cn->getDownstrmNbr() )
netofs << cn->getDownstrmNbr()->getID() << endl;
layofs << " " << cn->getNumLayer() << endl;
i=0;
while(i<cn->getNumLayer()){
layofs << cn->getLayerCtime(i) << " " << cn->getLayerRtime(i) << " " << cn->getLayerEtime(i) << endl;
layofs << cn->getLayerDepth(i) << " " << cn->getLayerErody(i) << " " << cn->getLayerSed(i) << endl;
j=0;
while(j<cn->getNumg()){
layofs << cn->getLayerDgrade(i,j) << " ";
j++;
}
layofs << endl;
i++;
}
}
// Write discharge, vegetation, & texture data
for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() )
{
if( !cn->getBoundaryFlag() ) slpofs << cn->getSlope() << endl;
else slpofs << 0 << endl;
qofs << cn->getQ() << endl;
if( vegofs.good() ) vegofs << cn->getVegCover().getVeg() << endl;
if( flowdepofs.good() )
flowdepofs << cn->getHydrDepth() << endl;
if( cn->getNumg()>1 ) // temporary hack TODO
{
texofs << cn->getLayerDgrade(0,0)/cn->getLayerDepth(0) << endl;
}
}
layofs.close();
}
/*************************************************************************\
**
** tOutput::WriteTSOutput
** This function writes the total volume of the DEM above the datum to
** a file called name.vols, where "name" is a name that the user has
** specified in the input file and which is stored in the data member
** baseName.
**
\*************************************************************************/
template< class tSubNode >
void tLOutput<tSubNode>::WriteTSOutput()
{
tMeshListIter<tSubNode> niter( m->getNodeList() ); // node list iterator
tSubNode * cn; // current node
double volume = 0,
area = 0,
cover = 0;
cout << "tLOutput::WriteTSOutput()\n" << flush;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) {
volume += cn->getZ()*cn->getVArea();
area += cn->getVArea();
}
volsofs << volume << endl;
tareaofs << area << endl;
if( vegofs.good() ) {
for( cn = niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
cover += cn->getVegCover().getVeg()*cn->getVArea();
vegcovofs << cover/area << endl;
}
}
<commit_msg>Node count fn; better to go in tSubNode.<commit_after>/*************************************************************************\
**
** tOutput.cpp: Functions for output classes tOutput and tLOutput
**
** (see tOutput.h for a description of these classes)
**
** $Id: tOutput.cpp,v 1.43 2000-07-04 04:44:54 daniel Exp $
\*************************************************************************/
#include <math.h> // For fmod function
#include "tOutput.h"
/*************************************************************************\
**
** Constructor
**
** The constructor takes two arguments, a pointer to the mesh and
** a reference to an open input file. It reads the base name for the
** output files from the input file, and opens and initializes these.
**
** Input: meshPtr -- pointer to a tMesh object (or descendant), assumed
** valid
** infile -- reference to an open input file, assumed valid
**
\*************************************************************************/
template< class tSubNode >
tOutput<tSubNode>::tOutput( tMesh<tSubNode> * meshPtr, tInputFile &infile )
{
assert( meshPtr > 0 );
m = meshPtr;
infile.ReadItem( baseName, "OUTFILENAME" );
CreateAndOpenFile( &nodeofs, ".nodes" );
CreateAndOpenFile( &edgofs, ".edges" );
CreateAndOpenFile( &triofs, ".tri" );
CreateAndOpenFile( &zofs, ".z" );
CreateAndOpenFile( &vaofs, ".varea" );
}
/*************************************************************************\
**
** tOutput::CreateAndOpenFile
**
** Opens the output file stream pointed to by theOFStream, giving it the
** name <baseName><extension>, and checks to make sure that the ofstream
** is valid.
**
** Input: theOFStream -- ptr to an ofstream object
** extension -- file name extension (e.g., ".nodes")
** Output: theOFStream is initialized to create an open output file
** Assumes: extension is a null-terminated string, and the length of
** baseName plus extension doesn't exceed kMaxNameSize+6
** (ie, the extension is expected to be <= 6 characters)
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,
char *extension )
{
char fullName[kMaxNameSize+6]; // name of file to be created
strcpy( fullName, baseName );
strcat( fullName, extension );
theOFStream->open( fullName );
if( !theOFStream->good() )
ReportFatalError(
"I can't create files for output. Storage space may be exhausted.");
}
/*************************************************************************\
**
** tOutput::WriteOutput
**
** This function writes information about the mesh to four files called
** name.nodes, name.edges, name.tri, and name.z, where "name" is a
** name that the user has specified in the input file and which is
** stored in the data member baseName.
**
** Input: time -- time of the current output time-slice
** Output: the node, edge, and triangle ID numbers are modified so that
** they are numbered according to their position on the list
** Assumes: the four file ofstreams have been opened by the constructor
** and are valid
**
** TODO: deal with option for once-only printing of mesh when mesh not
** deforming
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteOutput( double time )
{
tMeshListIter<tSubNode> niter( m->getNodeList() ); // node list iterator
tMeshListIter<tEdge> eiter( m->getEdgeList() ); // edge list iterator
tPtrListIter<tTriangle> titer( m->getTriList() ); // tri list iterator
tNode * cn; // current node
tEdge * ce; // current edge
tTriangle * ct; // current triangle
int id; // id of element (node, edge, or triangle)
int nnodes = m->getNodeList()->getSize(); // # of nodes on list
int nedges = m->getEdgeList()->getSize(); // " edges "
int ntri = m->getTriList()->getSize(); // " triangles "
cout << "tOutput::WriteOutput()\n" << flush;
// Renumber IDs in order by position on list
for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )
cn->setID( id );
for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )
ce->setID( id );
for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )
ct->setID( id );
// Write node file, z file, and varea file
nodeofs << " " << time << endl << nnodes << endl;
zofs << " " << time << endl << nnodes << endl;
vaofs << " " << time << endl << nnodes << endl;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
{
nodeofs << cn->getX() << " " << cn->getY() << " "
<< cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl;
zofs << cn->getZ() << endl;
vaofs << cn->getVArea() << endl;
}
// Write edge file
edgofs << " " << time << endl << nedges << endl;
for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )
edgofs << ce->getOriginPtrNC()->getID() << " "
<< ce->getDestinationPtrNC()->getID() << " "
<< ce->getCCWEdg()->getID() << endl;
// Write triangle file
int i;
triofs << " " << time << endl << ntri << endl;
for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )
{
for( i=0; i<=2; i++ )
triofs << ct->pPtr(i)->getID() << " ";
for( i=0; i<=2; i++ )
{
if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " ";
else triofs << "-1 ";
}
triofs << ct->ePtr(0)->getID() << " "
<< ct->ePtr(1)->getID() << " "
<< ct->ePtr(2)->getID() << endl;
}
// Call virtual function to write any additional data
WriteNodeData( time );
}
/*************************************************************************\
**
** tOutput::WriteNodeData
**
** This is a virtual function which can be overridden to write any
** additional node data. The base class version does nothing.
**
\*************************************************************************/
template< class tSubNode >
void tOutput<tSubNode>::WriteNodeData( double time )
{}
/*************************************************************************\
**
** tLOutput constructor
**
** Creates and opens a series of files for drainage areas, slopes, etc.
**
** Modifications:
** - 1/00 added "opOpt" and creation of veg output file (GT)
** - added flow depth output file (GT 1/00)
\*************************************************************************/
template< class tSubNode >
tLOutput<tSubNode>::tLOutput( tMesh<tSubNode> *meshPtr, tInputFile &infile )
: tOutput<tSubNode>( meshPtr, infile ) // call base-class constructor
{
int opOpt; // Optional modules: only output stuff when needed
int optTSOutput;
counter=0;
strcpy(nums, "0123456789");
CreateAndOpenFile( &drareaofs, ".area" );
CreateAndOpenFile( &netofs, ".net" );
CreateAndOpenFile( &slpofs, ".slp" );
CreateAndOpenFile( &qofs, ".q" );
CreateAndOpenFile( &texofs, ".tx" );
if( (opOpt = infile.ReadItem( opOpt, "OPTVEG" ) ) )
CreateAndOpenFile( &vegofs, ".veg" );
if( (opOpt = infile.ReadItem( opOpt, "OPTKINWAVE" ) ) )
CreateAndOpenFile( &flowdepofs, ".dep" );
if( (optTSOutput = infile.ReadItem( optTSOutput, "OPTTSOUTPUT" ) ) ) {
CreateAndOpenFile( &volsofs, ".vols" );
if( (opOpt = infile.ReadItem( opOpt, "OPTVEG" ) ) )
CreateAndOpenFile( &vegcovofs, ".vcov" );
CreateAndOpenFile( &tareaofs, ".tarea" );
}
}
/*************************************************************************\
**
** tLOutput::WriteNodeData
**
** This overridden virtual function writes output for tLNodes, including
** drainage areas, flow pathways, slopes, discharges, layer info, etc.
**
** Modifications:
** - 1/00 added output to veg output file (GT)
** - added output of flow depth; made slope output for all nodes (GT 1/00)
** - 6/00 layer info for each time step written to a different file (NG)
\*************************************************************************/
//TODO: should output boundary points as well so they'll map up with nodes
// for plotting. Means changing getSlope so it returns zero if flowedg
// undefined
template< class tSubNode >
void tLOutput<tSubNode>::WriteNodeData( double time )
{
tMeshListIter<tSubNode> ni( m->getNodeList() ); // node list iterator
tSubNode *cn; // current node
int nActiveNodes = m->getNodeList()->getActiveSize(); // # active nodes
int nnodes = m->getNodeList()->getSize(); // total # nodes
int i, j; // counters
//taking care of layer file, since new one each time step
char ext[7];
strcpy( ext, ".lay");
if(counter<10)
strncat( ext, &nums[counter], 1);
else if(counter>=10){
strncat(ext, &nums[counter/10], 1);
strncat(ext, &nums[(int) fmod((double)counter,10.0)], 1);
}
CreateAndOpenFile( &layofs, ext );
counter++;
// Write current time in each file
drareaofs << " " << time << "\n " << nActiveNodes << endl;
netofs << " " << time << "\n " << nActiveNodes << endl;
slpofs << " " << time << "\n " << nnodes << endl;
qofs << " " << time << "\n " << nnodes << endl;
layofs << " " << time << "\n" << nActiveNodes << endl;
texofs << " " << time << "\n" << nnodes << endl;
if( vegofs.good() ) vegofs << " " << time << "\n" << nnodes << endl;
if( flowdepofs.good() ) flowdepofs << " " << time << "\n" << nnodes << endl;
// Write data, including layer info
for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
{
assert( cn>0 );
drareaofs << cn->getDrArea() << endl;
if( cn->getDownstrmNbr() )
netofs << cn->getDownstrmNbr()->getID() << endl;
layofs << " " << cn->getNumLayer() << endl;
i=0;
while(i<cn->getNumLayer()){
layofs << cn->getLayerCtime(i) << " " << cn->getLayerRtime(i) << " " << cn->getLayerEtime(i) << endl;
layofs << cn->getLayerDepth(i) << " " << cn->getLayerErody(i) << " " << cn->getLayerSed(i) << endl;
j=0;
while(j<cn->getNumg()){
layofs << cn->getLayerDgrade(i,j) << " ";
j++;
}
layofs << endl;
i++;
}
}
// Write discharge, vegetation, & texture data
for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() )
{
if( !cn->getBoundaryFlag() ) slpofs << cn->getSlope() << endl;
else slpofs << 0 << endl;
qofs << cn->getQ() << endl;
if( vegofs.good() ) vegofs << cn->getVegCover().getVeg() << endl;
if( flowdepofs.good() )
flowdepofs << cn->getHydrDepth() << endl;
if( cn->getNumg()>1 ) // temporary hack TODO
{
texofs << cn->getLayerDgrade(0,0)/cn->getLayerDepth(0) << endl;
}
}
layofs.close();
}
/*************************************************************************\
**
** tOutput::WriteTSOutput
** This function writes the total volume of the DEM above the datum to
** a file called name.vols, where "name" is a name that the user has
** specified in the input file and which is stored in the data member
** baseName.
**
\*************************************************************************/
template< class tSubNode >
void tLOutput<tSubNode>::WriteTSOutput()
{
tMeshListIter<tSubNode> niter( m->getNodeList() ); // node list iterator
tSubNode * cn; // current node
double volume = 0,
area = 0,
cover = 0;
cout << "tLOutput::WriteTSOutput()\n" << flush;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) {
volume += cn->getZ()*cn->getVArea();
area += cn->getVArea();
}
volsofs << volume << endl;
tareaofs << area << endl;
if( vegofs.good() ) {
for( cn = niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )
cover += cn->getVegCover().getVeg()*cn->getVArea();
vegcovofs << cover/area << endl;
}
}
template< class tSubNode >
int tLOutput<tSubNode>::NodeCount()
{
tMeshListIter<tSubNode> niter( m->getNodeList() ); // node list iterator
tSubNode * cn; // current node
int count = 0;
for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) {
count++;
}
return count;
}
<|endoftext|> |
<commit_before>/*
* author: Max Kellermann <[email protected]>
*/
#ifndef PG_PARAM_WRAPPER_HXX
#define PG_PARAM_WRAPPER_HXX
#include "BinaryValue.hxx"
#include <iterator>
#include <cstdio>
#include <cstddef>
template<typename T>
struct PgParamWrapper {
PgParamWrapper(const T &t);
const char *GetValue() const;
/**
* Is the buffer returned by GetValue() binary? If so, the method
* GetSize() must return the size of the value.
*/
bool IsBinary() const;
/**
* Returns the size of the value in bytes. Only applicable if
* IsBinary() returns true and the value is non-nullptr.
*/
size_t GetSize() const;
};
template<>
struct PgParamWrapper<PgBinaryValue> {
PgBinaryValue value;
constexpr PgParamWrapper(PgBinaryValue _value)
:value(_value) {}
constexpr const char *GetValue() const {
return (const char *)value.value;
}
static constexpr bool IsBinary() {
return true;
}
constexpr size_t GetSize() const {
return value.size;
}
};
template<>
struct PgParamWrapper<const char *> {
const char *value;
constexpr PgParamWrapper(const char *_value):value(_value) {}
constexpr const char *GetValue() const {
return value;
}
static constexpr bool IsBinary() {
return false;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<>
struct PgParamWrapper<int> {
char buffer[16];
PgParamWrapper(int i) {
sprintf(buffer, "%i", i);
}
const char *GetValue() const {
return buffer;
}
static constexpr bool IsBinary() {
return false;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<>
struct PgParamWrapper<unsigned> {
char buffer[16];
PgParamWrapper(unsigned i) {
sprintf(buffer, "%u", i);
}
const char *GetValue() const {
return buffer;
}
static constexpr bool IsBinary() {
return false;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<>
struct PgParamWrapper<bool> {
const char *value;
constexpr PgParamWrapper(bool _value):value(_value ? "t" : "f") {}
static constexpr bool IsBinary() {
return false;
}
constexpr const char *GetValue() const {
return value;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<typename... Params>
class PgParamCollector;
template<typename T>
class PgParamCollector<T> {
PgParamWrapper<T> wrapper;
public:
explicit PgParamCollector(const T &t):wrapper(t) {}
static constexpr size_t Count() {
return 1;
}
template<typename O, typename S, typename F>
size_t Fill(O output, S size, F format) const {
*output = wrapper.GetValue();
*size = wrapper.GetSize();
*format = wrapper.IsBinary();
return 1;
}
template<typename O>
size_t Fill(O output) const {
static_assert(!wrapper.IsBinary(),
"Binary values not allowed in this overload");
*output = wrapper.GetValue();
return 1;
}
};
template<typename T, typename... Rest>
class PgParamCollector<T, Rest...> {
PgParamCollector<T> first;
PgParamCollector<Rest...> rest;
public:
explicit PgParamCollector(const T &t, Rest... _rest)
:first(t), rest(_rest...) {}
static constexpr size_t Count() {
return decltype(first)::Count() + decltype(rest)::Count();
}
template<typename O, typename S, typename F>
size_t Fill(O output, S size, F format) const {
const size_t nf = first.Fill(output, size, format);
std::advance(output, nf);
std::advance(size, nf);
std::advance(format, nf);
const size_t nr = rest.Fill(output, size, format);
return nf + nr;
}
template<typename O>
size_t Fill(O output) const {
const size_t nf = first.Fill(output);
std::advance(output, nf);
const size_t nr = rest.Fill(output);
return nf + nr;
}
};
template<typename... Params>
class PgTextParamArray {
PgParamCollector<Params...> collector;
public:
static constexpr size_t count = decltype(collector)::Count();
const char *values[count];
explicit PgTextParamArray(Params... params):collector(params...) {
collector.Fill(values);
}
};
template<typename... Params>
class PgBinaryParamArray {
PgParamCollector<Params...> collector;
public:
static constexpr size_t count = decltype(collector)::Count();
const char *values[count];
int lengths[count], formats[count];
explicit PgBinaryParamArray(Params... params):collector(params...) {
collector.Fill(values, lengths, formats);
}
};
#endif
<commit_msg>pg/ParamWrapper: call static method IsBinary() explicitly to avoid clang error<commit_after>/*
* author: Max Kellermann <[email protected]>
*/
#ifndef PG_PARAM_WRAPPER_HXX
#define PG_PARAM_WRAPPER_HXX
#include "BinaryValue.hxx"
#include <iterator>
#include <cstdio>
#include <cstddef>
template<typename T>
struct PgParamWrapper {
PgParamWrapper(const T &t);
const char *GetValue() const;
/**
* Is the buffer returned by GetValue() binary? If so, the method
* GetSize() must return the size of the value.
*/
bool IsBinary() const;
/**
* Returns the size of the value in bytes. Only applicable if
* IsBinary() returns true and the value is non-nullptr.
*/
size_t GetSize() const;
};
template<>
struct PgParamWrapper<PgBinaryValue> {
PgBinaryValue value;
constexpr PgParamWrapper(PgBinaryValue _value)
:value(_value) {}
constexpr const char *GetValue() const {
return (const char *)value.value;
}
static constexpr bool IsBinary() {
return true;
}
constexpr size_t GetSize() const {
return value.size;
}
};
template<>
struct PgParamWrapper<const char *> {
const char *value;
constexpr PgParamWrapper(const char *_value):value(_value) {}
constexpr const char *GetValue() const {
return value;
}
static constexpr bool IsBinary() {
return false;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<>
struct PgParamWrapper<int> {
char buffer[16];
PgParamWrapper(int i) {
sprintf(buffer, "%i", i);
}
const char *GetValue() const {
return buffer;
}
static constexpr bool IsBinary() {
return false;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<>
struct PgParamWrapper<unsigned> {
char buffer[16];
PgParamWrapper(unsigned i) {
sprintf(buffer, "%u", i);
}
const char *GetValue() const {
return buffer;
}
static constexpr bool IsBinary() {
return false;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<>
struct PgParamWrapper<bool> {
const char *value;
constexpr PgParamWrapper(bool _value):value(_value ? "t" : "f") {}
static constexpr bool IsBinary() {
return false;
}
constexpr const char *GetValue() const {
return value;
}
size_t GetSize() const {
/* ignored for text columns */
return 0;
}
};
template<typename... Params>
class PgParamCollector;
template<typename T>
class PgParamCollector<T> {
PgParamWrapper<T> wrapper;
public:
explicit PgParamCollector(const T &t):wrapper(t) {}
static constexpr size_t Count() {
return 1;
}
template<typename O, typename S, typename F>
size_t Fill(O output, S size, F format) const {
*output = wrapper.GetValue();
*size = wrapper.GetSize();
*format = wrapper.IsBinary();
return 1;
}
template<typename O>
size_t Fill(O output) const {
static_assert(!decltype(wrapper)::IsBinary(),
"Binary values not allowed in this overload");
*output = wrapper.GetValue();
return 1;
}
};
template<typename T, typename... Rest>
class PgParamCollector<T, Rest...> {
PgParamCollector<T> first;
PgParamCollector<Rest...> rest;
public:
explicit PgParamCollector(const T &t, Rest... _rest)
:first(t), rest(_rest...) {}
static constexpr size_t Count() {
return decltype(first)::Count() + decltype(rest)::Count();
}
template<typename O, typename S, typename F>
size_t Fill(O output, S size, F format) const {
const size_t nf = first.Fill(output, size, format);
std::advance(output, nf);
std::advance(size, nf);
std::advance(format, nf);
const size_t nr = rest.Fill(output, size, format);
return nf + nr;
}
template<typename O>
size_t Fill(O output) const {
const size_t nf = first.Fill(output);
std::advance(output, nf);
const size_t nr = rest.Fill(output);
return nf + nr;
}
};
template<typename... Params>
class PgTextParamArray {
PgParamCollector<Params...> collector;
public:
static constexpr size_t count = decltype(collector)::Count();
const char *values[count];
explicit PgTextParamArray(Params... params):collector(params...) {
collector.Fill(values);
}
};
template<typename... Params>
class PgBinaryParamArray {
PgParamCollector<Params...> collector;
public:
static constexpr size_t count = decltype(collector)::Count();
const char *values[count];
int lengths[count], formats[count];
explicit PgBinaryParamArray(Params... params):collector(params...) {
collector.Fill(values, lengths, formats);
}
};
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/pdal_internal.hpp>
#include <pdal/plang/Parser.hpp>
#include <pdal/plang/AstNode.hpp>
#include <pdal/plang/Program.hpp>
#include <pdal/plang/SymbolTable.hpp>
#ifdef PDAL_COMPILER_MSVC
# pragma warning(push)
# pragma warning(disable: 4512) // assignment operator could not be generated
# pragma warning(disable: 4127) // conditional expression is constant
# pragma warning(disable: 4100) // unreferenced formal
#endif
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#ifdef PDAL_COMPILER_MSVC
# pragma warning(pop)
#endif
#include <iostream>
#include <string>
#include <complex>
#include <vector>
namespace qi = boost::spirit::qi;
#ifdef PDAL_EMBED_BOOST
namespace pho = boost::pdalboostphoenix;
#else
namespace pho = boost::phoenix;
#endif
namespace ascii = boost::spirit::ascii;
namespace pdal { namespace plang {
struct PlangParser : qi::grammar<std::string::const_iterator, Program*(), ascii::space_type>
{
PlangParser();
qi::rule<std::string::const_iterator, Program*(), ascii::space_type> program;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> assignments;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> assignment;
qi::rule<std::string::const_iterator, SymbolTable*(), ascii::space_type> declarations;
qi::rule<std::string::const_iterator, Symbol*(), ascii::space_type> declaration;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> lhs;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> rhs;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> constant;
qi::rule<std::string::const_iterator, SymbolName*(), ascii::space_type> variable;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> predicate;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> predicate_tail;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> predicate_tail_star;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> expr;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> expr_tail;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> expr_tail_star;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> term;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> term_tail;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> term_tail_star;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> factor;
};
PlangParser::PlangParser() : PlangParser::base_type(program)
{
#define SET_P(T, p) qi::_val = pho::new_<T>(p)
#define SET_1(T) qi::_val = pho::new_<T>(qi::_1)
#define SET_1_P(T, p) qi::_val = pho::new_<T>(qi::_1, p)
#define SET_1_2(T) qi::_val = pho::new_<T>(qi::_1, qi::_2)
#define SET_1_2_P(T, p) qi::_val = pho::new_<T>(qi::_1, qi::_2, p)
#define PASS qi::_val = qi::_1
qi::real_parser<float, qi::strict_real_policies<float> > strict_float;
qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
constant = ( ("0x" >> qi::hex >> 'l') [ SET_1(AstConstant) ]
| ("0x" >> qi::hex) [ SET_1(AstConstant) ]
| (strict_float >> 'f') [ SET_1(AstConstant) ]
| strict_double [ SET_1(AstConstant) ]
| (qi::ulong_long >> "ul") [ SET_1(AstConstant) ]
| (qi::ulong_long >> "lu") [ SET_1(AstConstant) ]
| (qi::long_long >> 'l') [ SET_1(AstConstant) ]
| (qi::uint_ >> 'u') [ SET_1(AstConstant) ]
| qi::int_ [ SET_1(AstConstant) ]
| qi::lit("true") [ SET_P(AstConstant, true) ]
| qi::lit("false") [ SET_P(AstConstant, false) ]
)
;
// (letter or _) followed by *(letter or number or _)
variable = ( (qi::alpha|qi::char_('_')) >> *(qi::alpha | qi::digit | qi::char_('_'))) [ SET_1_2(SymbolName) ]
;
predicate_tail = ( ">" >> expr [ SET_1_P(AstTempOp1, NodeType_Greater1) ]
| ">=" >> expr [ SET_1_P(AstTempOp1, NodeType_GreaterEq1) ]
| "<" >> expr [ SET_1_P(AstTempOp1, NodeType_Less1) ]
| "<=" >> expr [ SET_1_P(AstTempOp1, NodeType_LessEq1) ]
| "==" >> expr [ SET_1_P(AstTempOp1, NodeType_Equal1) ]
| "!=" >> expr [ SET_1_P(AstTempOp1, NodeType_NotEqual1) ]
| "&&" >> expr [ SET_1_P(AstTempOp1, NodeType_LogicalAnd1) ]
| "||" >> expr [ SET_1_P(AstTempOp1, NodeType_LogicalOr1) ]
)
;
predicate_tail_star = (*predicate_tail) [ SET_1(AstTempVector) ]
;
predicate = (expr >> predicate_tail_star) [ SET_1_2(AstTempVector) ]
;
expr_tail = ( '+' >> term [ SET_1_P(AstTempOp1, NodeType_Add1) ]
| '-' >> term [ SET_1_P(AstTempOp1, NodeType_Subtract1) ]
| '^' >> term [ SET_1_P(AstTempOp1, NodeType_ArithXor1) ]
| '|' >> term [ SET_1_P(AstTempOp1, NodeType_ArithOr1) ]
| '&' >> term [ SET_1_P(AstTempOp1, NodeType_ArithAnd1) ]
)
;
expr_tail_star = (*expr_tail) [ SET_1(AstTempVector) ]
;
expr = (term >> expr_tail_star) [ SET_1_2(AstTempVector) ]
;
term_tail = ( '*' >> factor [ SET_1_P(AstTempOp1, NodeType_Multiply1) ]
| '/' >> factor [ SET_1_P(AstTempOp1, NodeType_Divide1) ]
)
;
term_tail_star = (*term_tail) [ SET_1(AstTempVector) ]
;
term = (factor >> term_tail_star) [ SET_1_2(AstTempVector) ]
;
factor = ( constant [ PASS ]
| ("uint8(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint8) ]
| ("uint16(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint16) ]
| ("uint32(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint32) ]
| ("uint64(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint64) ]
| ("int8(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int8) ]
| ("int16(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int16) ]
| ("int32(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int32) ]
| ("int64(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int64) ]
| ("float32(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Float32) ]
| ("float64(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Float64) ]
| variable [ SET_1(AstVariableUse) ]
| ('(' >> expr >> ')') [ PASS ]
| ('-' >> factor) [ SET_1(AstNegate) ]
| ('+' >> factor) [ PASS ]
)
;
rhs = predicate [ PASS ]
;
assignment = (variable >> '=' >> rhs ) [ SET_1_2(AstVariableDef) ]
;
declaration = ( ("uint8" >> variable) [ SET_1_P(Symbol, DataType_Uint8) ]
| ("uint16" >> variable) [ SET_1_P(Symbol, DataType_Uint16) ]
| ("uint32" >> variable) [ SET_1_P(Symbol, DataType_Uint32) ]
| ("uint64" >> variable) [ SET_1_P(Symbol, DataType_Uint64) ]
| ("int8" >> variable) [ SET_1_P(Symbol, DataType_Int8) ]
| ("int16" >> variable) [ SET_1_P(Symbol, DataType_Int16) ]
| ("int32" >> variable) [ SET_1_P(Symbol, DataType_Int32) ]
| ("int64" >> variable) [ SET_1_P(Symbol, DataType_Int64) ]
| ("float32" >> variable) [ SET_1_P(Symbol, DataType_Float32) ]
| ("float64" >> variable) [ SET_1_P(Symbol, DataType_Float64) ]
| ("bool" >> variable) [ SET_1_P(Symbol, DataType_Bool) ]
)
;
declarations = (*(declaration >> ';')) [ SET_1(SymbolTable) ]
;
assignments = (*(assignment >> ';')) [ SET_1(AstTempVector) ]
;
program = (declarations >> assignments) [ SET_1_2(Program) ]
;
return;
}
bool Parser::parse()
{
std::string::const_iterator iter = m_text.begin();
std::string::const_iterator end = m_text.end();
using boost::spirit::ascii::space;
PlangParser parser;
bool ok = qi::phrase_parse(iter, end, parser, space, m_program);
m_parsed = (ok && iter==end);
return m_parsed;
}
} } // namespaces
<commit_msg>turn off 64bit integer types for plang for now<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/pdal_internal.hpp>
#include <pdal/plang/Parser.hpp>
#include <pdal/plang/AstNode.hpp>
#include <pdal/plang/Program.hpp>
#include <pdal/plang/SymbolTable.hpp>
#ifdef PDAL_COMPILER_MSVC
# pragma warning(push)
# pragma warning(disable: 4512) // assignment operator could not be generated
# pragma warning(disable: 4127) // conditional expression is constant
# pragma warning(disable: 4100) // unreferenced formal
#endif
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#ifdef PDAL_COMPILER_MSVC
# pragma warning(pop)
#endif
#include <iostream>
#include <string>
#include <complex>
#include <vector>
namespace qi = boost::spirit::qi;
#ifdef PDAL_EMBED_BOOST
namespace pho = boost::pdalboostphoenix;
#else
namespace pho = boost::phoenix;
#endif
namespace ascii = boost::spirit::ascii;
namespace pdal { namespace plang {
struct PlangParser : qi::grammar<std::string::const_iterator, Program*(), ascii::space_type>
{
PlangParser();
qi::rule<std::string::const_iterator, Program*(), ascii::space_type> program;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> assignments;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> assignment;
qi::rule<std::string::const_iterator, SymbolTable*(), ascii::space_type> declarations;
qi::rule<std::string::const_iterator, Symbol*(), ascii::space_type> declaration;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> lhs;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> rhs;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> constant;
qi::rule<std::string::const_iterator, SymbolName*(), ascii::space_type> variable;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> predicate;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> predicate_tail;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> predicate_tail_star;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> expr;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> expr_tail;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> expr_tail_star;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> term;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> term_tail;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> term_tail_star;
qi::rule<std::string::const_iterator, AstNode*(), ascii::space_type> factor;
};
PlangParser::PlangParser() : PlangParser::base_type(program)
{
#define SET_P(T, p) qi::_val = pho::new_<T>(p)
#define SET_1(T) qi::_val = pho::new_<T>(qi::_1)
#define SET_1_P(T, p) qi::_val = pho::new_<T>(qi::_1, p)
#define SET_1_2(T) qi::_val = pho::new_<T>(qi::_1, qi::_2)
#define SET_1_2_P(T, p) qi::_val = pho::new_<T>(qi::_1, qi::_2, p)
#define PASS qi::_val = qi::_1
qi::real_parser<float, qi::strict_real_policies<float> > strict_float;
qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
constant = ( ("0x" >> qi::hex >> 'l') [ SET_1(AstConstant) ]
| ("0x" >> qi::hex) [ SET_1(AstConstant) ]
| (strict_float >> 'f') [ SET_1(AstConstant) ]
| strict_double [ SET_1(AstConstant) ]
#if notdef
// This doesn't work on the jenkins build.
/* I'm getting an error of boost/variant/variant.hpp:1326:9: error: call of overloaded ‘initialize(void*, long long int&)’ is ambiguous and boost/variant/variant.hpp:1326:9: error: call of overloaded ‘initialize(void*, long long unsigned int&)’ is ambiguous yet BOOST_HAS_LONG_LONG is defined for my setup. Pointers to settings/macros other than BOOST_HAS_LONG_LONG that I might look at would be greatly appreciated
[10:49am] hobu: The note there says: "Compile error here indicates that the given type not is unambiguously convertible to one of the variant's types" but I'm not sure what that means...
[10:50am] hobu: http://stackoverflow.com/questions/6571837/why-does-boostspiritqiparse-not-set-this-boostvariants-value seems pertinent, as this is a qi situation for me as well
[10:54am] mdupont: hobu, cast it
[10:54am] mdupont: you have the tsecond param is either int& or unsigned int ^
[10:54am] mdupont: you have the tsecond param is either int& or unsigned int &
[10:54am] VeXocide: http://www.boost.org/doc/libs/1_48_0/libs/spirit/doc/html/spirit/qi/reference/auxiliary/attr_cast.html
[10:54am] mdupont: you can declare a variable of the right type before and pass that in
*/
| (qi::ulong_long >> "ul") [ SET_1(AstConstant) ]
| (qi::ulong_long >> "lu") [ SET_1(AstConstant) ]
| (qi::long_long >> 'l') [ SET_1(AstConstant) ]
#endif
| (qi::uint_ >> 'u') [ SET_1(AstConstant) ]
| qi::int_ [ SET_1(AstConstant) ]
| qi::lit("true") [ SET_P(AstConstant, true) ]
| qi::lit("false") [ SET_P(AstConstant, false) ]
)
;
// (letter or _) followed by *(letter or number or _)
variable = ( (qi::alpha|qi::char_('_')) >> *(qi::alpha | qi::digit | qi::char_('_'))) [ SET_1_2(SymbolName) ]
;
predicate_tail = ( ">" >> expr [ SET_1_P(AstTempOp1, NodeType_Greater1) ]
| ">=" >> expr [ SET_1_P(AstTempOp1, NodeType_GreaterEq1) ]
| "<" >> expr [ SET_1_P(AstTempOp1, NodeType_Less1) ]
| "<=" >> expr [ SET_1_P(AstTempOp1, NodeType_LessEq1) ]
| "==" >> expr [ SET_1_P(AstTempOp1, NodeType_Equal1) ]
| "!=" >> expr [ SET_1_P(AstTempOp1, NodeType_NotEqual1) ]
| "&&" >> expr [ SET_1_P(AstTempOp1, NodeType_LogicalAnd1) ]
| "||" >> expr [ SET_1_P(AstTempOp1, NodeType_LogicalOr1) ]
)
;
predicate_tail_star = (*predicate_tail) [ SET_1(AstTempVector) ]
;
predicate = (expr >> predicate_tail_star) [ SET_1_2(AstTempVector) ]
;
expr_tail = ( '+' >> term [ SET_1_P(AstTempOp1, NodeType_Add1) ]
| '-' >> term [ SET_1_P(AstTempOp1, NodeType_Subtract1) ]
| '^' >> term [ SET_1_P(AstTempOp1, NodeType_ArithXor1) ]
| '|' >> term [ SET_1_P(AstTempOp1, NodeType_ArithOr1) ]
| '&' >> term [ SET_1_P(AstTempOp1, NodeType_ArithAnd1) ]
)
;
expr_tail_star = (*expr_tail) [ SET_1(AstTempVector) ]
;
expr = (term >> expr_tail_star) [ SET_1_2(AstTempVector) ]
;
term_tail = ( '*' >> factor [ SET_1_P(AstTempOp1, NodeType_Multiply1) ]
| '/' >> factor [ SET_1_P(AstTempOp1, NodeType_Divide1) ]
)
;
term_tail_star = (*term_tail) [ SET_1(AstTempVector) ]
;
term = (factor >> term_tail_star) [ SET_1_2(AstTempVector) ]
;
factor = ( constant [ PASS ]
| ("uint8(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint8) ]
| ("uint16(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint16) ]
| ("uint32(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint32) ]
| ("uint64(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Uint64) ]
| ("int8(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int8) ]
| ("int16(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int16) ]
| ("int32(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int32) ]
| ("int64(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Int64) ]
| ("float32(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Float32) ]
| ("float64(" >> expr >> ')' ) [ SET_1_P(AstConvert, DataType_Float64) ]
| variable [ SET_1(AstVariableUse) ]
| ('(' >> expr >> ')') [ PASS ]
| ('-' >> factor) [ SET_1(AstNegate) ]
| ('+' >> factor) [ PASS ]
)
;
rhs = predicate [ PASS ]
;
assignment = (variable >> '=' >> rhs ) [ SET_1_2(AstVariableDef) ]
;
declaration = ( ("uint8" >> variable) [ SET_1_P(Symbol, DataType_Uint8) ]
| ("uint16" >> variable) [ SET_1_P(Symbol, DataType_Uint16) ]
| ("uint32" >> variable) [ SET_1_P(Symbol, DataType_Uint32) ]
| ("uint64" >> variable) [ SET_1_P(Symbol, DataType_Uint64) ]
| ("int8" >> variable) [ SET_1_P(Symbol, DataType_Int8) ]
| ("int16" >> variable) [ SET_1_P(Symbol, DataType_Int16) ]
| ("int32" >> variable) [ SET_1_P(Symbol, DataType_Int32) ]
| ("int64" >> variable) [ SET_1_P(Symbol, DataType_Int64) ]
| ("float32" >> variable) [ SET_1_P(Symbol, DataType_Float32) ]
| ("float64" >> variable) [ SET_1_P(Symbol, DataType_Float64) ]
| ("bool" >> variable) [ SET_1_P(Symbol, DataType_Bool) ]
)
;
declarations = (*(declaration >> ';')) [ SET_1(SymbolTable) ]
;
assignments = (*(assignment >> ';')) [ SET_1(AstTempVector) ]
;
program = (declarations >> assignments) [ SET_1_2(Program) ]
;
return;
}
bool Parser::parse()
{
std::string::const_iterator iter = m_text.begin();
std::string::const_iterator end = m_text.end();
using boost::spirit::ascii::space;
PlangParser parser;
bool ok = qi::phrase_parse(iter, end, parser, space, m_program);
m_parsed = (ok && iter==end);
return m_parsed;
}
} } // namespaces
<|endoftext|> |
<commit_before>//*****************************************************************************
//
// Application.cpp
//
// Core class that contains the high level application logic.
//
// Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu
// This code is licensed under BSD license (see LICENSE.txt for details)
//
// Created:
// December 20, 2015
//
// Modified:
// December 30, 2015
//
//*****************************************************************************
#include "Application.h"
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include "FrameRateManager.h"
#include "IPv4Address.h"
#include "LeapMotionManager.h"
#include "Network.h"
#include "TCPSocket.h"
#include "Window.h"
//*****************************************************************************
//
//! Constructor for Image. Acquires resources for SDL and window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Application::Application()
: _exit(false)
{
//
// Initialize application
//
if (!_initialize())
{
std::cerr << "[ERROR] Application::Application(): Failed to "\
"initialize." << std::endl;
return;
}
}
//*****************************************************************************
//
//! Destructor for Application. Releases resources used by SDL and window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Application::~Application()
{
_terminate();
}
//*****************************************************************************
//
//! Runs the application.
//!
//! \param None.
//!
//! \return Returns \b true if the application was run successfully and \b
//! false otherwise.
//
//*****************************************************************************
int Application::run()
{
FrameRateManager fpsManager;
LeapMotionManager leap;
Window window;
const unsigned short _MAX_PAYLOAD = 256;
unsigned char data[_MAX_PAYLOAD];
FingerPressureStruct fingerPressures;
//
// Register this object to be notified by window
//
window.addObserver(this);
//
// Receive IPv4 address and port as input from user
//
std::cout << "Enter the target IPv4 address: ";
char addressInput[16];
std::cin >> addressInput;
std::cout << "Enter the target port: ";
unsigned short port;
std::cin >> port;
//
// Constructs an IPv4 address using user input
//
IPv4Address address(addressInput, port);
//
// Constructs a TCP socket and connects to IPv4 address
//
TCPSocket tcpsocket;
tcpsocket.open();
tcpsocket.connect(&address);
//
// Main program logic
//
while (!_exit)
{
//
// Begins tracking fps
//
fpsManager.beginFrame();
//
// Fetches relevent data from Leap Motion Controller
//
leap.processFrame(data, _MAX_PAYLOAD);
//
// Send data to remote host
//
tcpsocket.send(data, _MAX_PAYLOAD);
//
// Populates FingerPressureStruct with finger pressure information
// TODO (Brandon): As of now, this populates structure with angle
// information. Must change to pressure information once we establish
// communication to microcontroller and receive feedback from sensors.
//
_populateFingerPressureStruct(fingerPressures, data, _MAX_PAYLOAD);
//
// Updates GUI
//
window.update(&fingerPressures);
//
// Ends frame and blocks until FPS elapses
//
fpsManager.endFrame();
}
return EXIT_SUCCESS;
}
//*****************************************************************************
//
//! Sets the exit flag if SDL_QUIT event is raised.
//!
//! \param event that was raised.
//!
//! \return None.
//
//*****************************************************************************
void Application::onNotify(int event)
{
if (event == SDL_QUIT)
{
_exit = true;
}
}
//*****************************************************************************
//
//! Initializes the application.
//!
//! \param None.
//!
//! \return Returns \b true if the application was initialized successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Application::_initialize()
{
//
// Initializes SDL
//
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cerr << "[ERROR] Application::_initialize(): SDL_Init() failed. "\
"SDL Error: " << SDL_GetError() << std::endl;
return false;
}
//
// Initializes SDL_image
//
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
std::cerr << "[ERROR] Application::_initialize(): IMG_Init() failed. "\
"SDL_image Error: " << IMG_GetError() << std::endl;
return false;
}
//
// Initializes socket API
//
if (!network::initialize())
{
std::cerr << "[ERROR] Application::_initialize(): "\
"network::initialize() failed." << std::endl;
return false;
}
return true;
}
//*****************************************************************************
//
//! Terminates the application.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Application::_terminate()
{
network::terminate();
IMG_Quit();
SDL_Quit();
}
//*****************************************************************************
//
//! Populates structure with pressure information decoded from buf.
//!
//! \param fingerPressures structure for storing results.
//! \param buf buffer with encoded pressure data.
//! \param buflen the size of the buffer.
//!
//! \return Returns \b true if the structure was populated successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Application::_populateFingerPressureStruct(FingerPressureStruct
&fingerPressures, unsigned char *buf, unsigned int buflen)
{
//
// Buffer needs to be at least this size
//
const int BITS_PER_BYTE = 8;
int pressureSize = sizeof(fingerPressures.pressure[0]);
assert(buflen >= pressureSize*NUM_FINGERS);
//
// Parses through buf and populate structure
//
unsigned int bufIndex = 0;
for (int i=0; i<NUM_FINGERS; i++)
{
fingerPressures.pressure[i] = buf[bufIndex++];
}
return true;
}
//*****************************************************************************
//
//! Creates and runs the application.
//!
//! \param None.
//!
//! \return Returns 0 on success, and a non-zero value otherwise.
//
//*****************************************************************************
int main(int argc, char *argv[])
{
Application app;
return app.run();
}
<commit_msg>Removed networking support for testing.<commit_after>//*****************************************************************************
//
// Application.cpp
//
// Core class that contains the high level application logic.
//
// Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu
// This code is licensed under BSD license (see LICENSE.txt for details)
//
// Created:
// December 20, 2015
//
// Modified:
// December 30, 2015
//
//*****************************************************************************
#include "Application.h"
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include "FrameRateManager.h"
#include "IPv4Address.h"
#include "LeapMotionManager.h"
#include "Network.h"
#include "TCPSocket.h"
#include "Window.h"
//*****************************************************************************
//
//! Constructor for Image. Acquires resources for SDL and window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Application::Application()
: _exit(false)
{
//
// Initialize application
//
if (!_initialize())
{
std::cerr << "[ERROR] Application::Application(): Failed to "\
"initialize." << std::endl;
return;
}
}
//*****************************************************************************
//
//! Destructor for Application. Releases resources used by SDL and window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Application::~Application()
{
_terminate();
}
//*****************************************************************************
//
//! Runs the application.
//!
//! \param None.
//!
//! \return Returns \b true if the application was run successfully and \b
//! false otherwise.
//
//*****************************************************************************
int Application::run()
{
FrameRateManager fpsManager;
LeapMotionManager leap;
const unsigned short _MAX_PAYLOAD = 256;
unsigned char data[_MAX_PAYLOAD];
FingerPressureStruct fingerPressures;
//
// Receive IPv4 address and port as input from user
//
/*std::cout << "Enter the target IPv4 address: ";
char addressInput[16];
std::cin >> addressInput;
std::cout << "Enter the target port: ";
unsigned short port;
std::cin >> port;
//
// Constructs an IPv4 address using user input
//
IPv4Address address(addressInput, port);
//
// Constructs a TCP socket and connects to IPv4 address
//
TCPSocket tcpsocket;
tcpsocket.open();
tcpsocket.connect(&address);*/
//
// Create window and register this object to be notified by window
//
Window window;
window.addObserver(this);
//
// Main program logic
//
while (!_exit)
{
//
// Begins tracking fps
//
fpsManager.beginFrame();
//
// Fetches relevent data from Leap Motion Controller
//
leap.processFrame(data, _MAX_PAYLOAD);
//
// Send data to remote host
//
/*tcpsocket.send(data, _MAX_PAYLOAD);*/
//
// Populates FingerPressureStruct with finger pressure information
// TODO (Brandon): As of now, this populates structure with angle
// information. Must change to pressure information once we establish
// communication to microcontroller and receive feedback from sensors.
//
_populateFingerPressureStruct(fingerPressures, data, _MAX_PAYLOAD);
//
// Updates GUI
//
window.update(&fingerPressures);
//
// Ends frame and blocks until FPS elapses
//
fpsManager.endFrame();
}
return EXIT_SUCCESS;
}
//*****************************************************************************
//
//! Sets the exit flag if SDL_QUIT event is raised.
//!
//! \param event that was raised.
//!
//! \return None.
//
//*****************************************************************************
void Application::onNotify(int event)
{
if (event == SDL_QUIT)
{
_exit = true;
}
}
//*****************************************************************************
//
//! Initializes the application.
//!
//! \param None.
//!
//! \return Returns \b true if the application was initialized successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Application::_initialize()
{
//
// Initializes SDL
//
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cerr << "[ERROR] Application::_initialize(): SDL_Init() failed. "\
"SDL Error: " << SDL_GetError() << std::endl;
return false;
}
//
// Initializes SDL_image
//
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
std::cerr << "[ERROR] Application::_initialize(): IMG_Init() failed. "\
"SDL_image Error: " << IMG_GetError() << std::endl;
return false;
}
//
// Initializes socket API
//
if (!network::initialize())
{
std::cerr << "[ERROR] Application::_initialize(): "\
"network::initialize() failed." << std::endl;
return false;
}
return true;
}
//*****************************************************************************
//
//! Terminates the application.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Application::_terminate()
{
network::terminate();
IMG_Quit();
SDL_Quit();
}
//*****************************************************************************
//
//! Populates structure with pressure information decoded from buf.
//!
//! \param fingerPressures structure for storing results.
//! \param buf buffer with encoded pressure data.
//! \param buflen the size of the buffer.
//!
//! \return Returns \b true if the structure was populated successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Application::_populateFingerPressureStruct(FingerPressureStruct
&fingerPressures, unsigned char *buf, unsigned int buflen)
{
//
// Buffer needs to be at least this size
//
const int BITS_PER_BYTE = 8;
int pressureSize = sizeof(fingerPressures.pressure[0]);
assert(buflen >= pressureSize*NUM_FINGERS);
//
// Parses through buf and populate structure
//
unsigned int bufIndex = 0;
for (int i=0; i<NUM_FINGERS; i++)
{
fingerPressures.pressure[i] = buf[bufIndex++];
}
return true;
}
//*****************************************************************************
//
//! Creates and runs the application.
//!
//! \param None.
//!
//! \return Returns 0 on success, and a non-zero value otherwise.
//
//*****************************************************************************
int main(int argc, char *argv[])
{
Application app;
return app.run();
}
<|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 <xmlscript/xmllib_imexp.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/xml/input/XRoot.hpp>
#include <vector>
using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace xmlscript
{
inline sal_Int32 toInt32( OUString const & rStr ) SAL_THROW(())
{
sal_Int32 nVal;
if (rStr.getLength() > 2 && rStr[ 0 ] == '0' && rStr[ 1 ] == 'x')
{
nVal = rStr.copy( 2 ).toUInt32( 16 );
}
else
{
nVal = rStr.toInt32();
}
return nVal;
}
inline bool getBoolAttr(
sal_Bool * pRet, OUString const & rAttrName,
Reference< xml::input::XAttributes > const & xAttributes, sal_Int32 uid )
{
OUString aValue(
xAttributes->getValueByUidName( uid, rAttrName ) );
if (!aValue.isEmpty())
{
if ( aValue == "true" )
{
*pRet = sal_True;
return true;
}
else if ( aValue == "false" )
{
*pRet = sal_False;
return true;
}
else
{
throw xml::sax::SAXException(rAttrName + ": no boolean value (true|false)!", Reference< XInterface >(), Any() );
}
}
return false;
}
inline bool getStringAttr(
OUString * pRet, OUString const & rAttrName,
Reference< xml::input::XAttributes > const & xAttributes, sal_Int32 uid )
{
*pRet = xAttributes->getValueByUidName( uid, rAttrName );
return (!pRet->isEmpty());
}
inline bool getLongAttr(
sal_Int32 * pRet, OUString const & rAttrName,
Reference< xml::input::XAttributes > const & xAttributes,
sal_Int32 uid )
{
OUString aValue(
xAttributes->getValueByUidName( uid, rAttrName ) );
if (!aValue.isEmpty())
{
*pRet = toInt32( aValue );
return true;
}
return false;
}
// Library import
struct LibraryImport
: public ::cppu::WeakImplHelper1< xml::input::XRoot >
{
friend class LibrariesElement;
friend class LibraryElement;
LibDescriptorArray* mpLibArray;
LibDescriptor* mpLibDesc; // Single library mode
sal_Int32 XMLNS_LIBRARY_UID;
sal_Int32 XMLNS_XLINK_UID;
public:
LibraryImport( LibDescriptorArray* pLibArray ) SAL_THROW(())
: mpLibArray(pLibArray)
, mpLibDesc(NULL)
, XMLNS_LIBRARY_UID(0)
, XMLNS_XLINK_UID(0)
{
}
// Single library mode
inline LibraryImport( LibDescriptor* pLibDesc )
SAL_THROW(())
: mpLibArray( NULL )
, mpLibDesc( pLibDesc ) {}
virtual ~LibraryImport()
SAL_THROW(());
// XRoot
virtual void SAL_CALL startDocument(
Reference< xml::input::XNamespaceMapping > const & xNamespaceMapping )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endDocument()
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL processingInstruction(
OUString const & rTarget, OUString const & rData )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL setDocumentLocator(
Reference< xml::sax::XLocator > const & xLocator )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual Reference< xml::input::XElement > SAL_CALL startRootElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
};
class LibElementBase
: public ::cppu::WeakImplHelper1< xml::input::XElement >
{
protected:
LibraryImport * _pImport;
LibElementBase * _pParent;
OUString _aLocalName;
Reference< xml::input::XAttributes > _xAttributes;
public:
LibElementBase(
OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW(());
virtual ~LibElementBase()
SAL_THROW(());
// XElement
virtual Reference< xml::input::XElement > SAL_CALL getParent()
throw (RuntimeException, std::exception);
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException, std::exception);
virtual sal_Int32 SAL_CALL getUid()
throw (RuntimeException, std::exception);
virtual Reference< xml::input::XAttributes > SAL_CALL getAttributes()
throw (RuntimeException, std::exception);
virtual void SAL_CALL ignorableWhitespace(
OUString const & rWhitespaces )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL characters( OUString const & rChars )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL processingInstruction(
OUString const & rTarget, OUString const & rData )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual Reference< xml::input::XElement > SAL_CALL startChildElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
};
class LibrariesElement : public LibElementBase
{
friend class LibraryElement;
protected:
vector< LibDescriptor > mLibDescriptors;
public:
virtual Reference< xml::input::XElement > SAL_CALL startChildElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException, std::exception);
LibrariesElement(
OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW(())
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
class LibraryElement : public LibElementBase
{
protected:
vector< OUString > mElements;
public:
virtual Reference< xml::input::XElement > SAL_CALL startChildElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException, std::exception);
LibraryElement(
OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW(())
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708732 Uninitialized scalar field<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 <xmlscript/xmllib_imexp.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/xml/input/XRoot.hpp>
#include <vector>
using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace xmlscript
{
inline sal_Int32 toInt32( OUString const & rStr ) SAL_THROW(())
{
sal_Int32 nVal;
if (rStr.getLength() > 2 && rStr[ 0 ] == '0' && rStr[ 1 ] == 'x')
{
nVal = rStr.copy( 2 ).toUInt32( 16 );
}
else
{
nVal = rStr.toInt32();
}
return nVal;
}
inline bool getBoolAttr(
sal_Bool * pRet, OUString const & rAttrName,
Reference< xml::input::XAttributes > const & xAttributes, sal_Int32 uid )
{
OUString aValue(
xAttributes->getValueByUidName( uid, rAttrName ) );
if (!aValue.isEmpty())
{
if ( aValue == "true" )
{
*pRet = sal_True;
return true;
}
else if ( aValue == "false" )
{
*pRet = sal_False;
return true;
}
else
{
throw xml::sax::SAXException(rAttrName + ": no boolean value (true|false)!", Reference< XInterface >(), Any() );
}
}
return false;
}
inline bool getStringAttr(
OUString * pRet, OUString const & rAttrName,
Reference< xml::input::XAttributes > const & xAttributes, sal_Int32 uid )
{
*pRet = xAttributes->getValueByUidName( uid, rAttrName );
return (!pRet->isEmpty());
}
inline bool getLongAttr(
sal_Int32 * pRet, OUString const & rAttrName,
Reference< xml::input::XAttributes > const & xAttributes,
sal_Int32 uid )
{
OUString aValue(
xAttributes->getValueByUidName( uid, rAttrName ) );
if (!aValue.isEmpty())
{
*pRet = toInt32( aValue );
return true;
}
return false;
}
// Library import
struct LibraryImport
: public ::cppu::WeakImplHelper1< xml::input::XRoot >
{
friend class LibrariesElement;
friend class LibraryElement;
LibDescriptorArray* mpLibArray;
LibDescriptor* mpLibDesc; // Single library mode
sal_Int32 XMLNS_LIBRARY_UID;
sal_Int32 XMLNS_XLINK_UID;
public:
LibraryImport( LibDescriptorArray* pLibArray ) SAL_THROW(())
: mpLibArray(pLibArray)
, mpLibDesc(NULL)
, XMLNS_LIBRARY_UID(0)
, XMLNS_XLINK_UID(0)
{
}
// Single library mode
LibraryImport(LibDescriptor* pLibDesc) SAL_THROW(())
: mpLibArray(NULL)
, mpLibDesc(pLibDesc)
, XMLNS_LIBRARY_UID(0)
, XMLNS_XLINK_UID(0)
{
}
virtual ~LibraryImport()
SAL_THROW(());
// XRoot
virtual void SAL_CALL startDocument(
Reference< xml::input::XNamespaceMapping > const & xNamespaceMapping )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endDocument()
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL processingInstruction(
OUString const & rTarget, OUString const & rData )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL setDocumentLocator(
Reference< xml::sax::XLocator > const & xLocator )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual Reference< xml::input::XElement > SAL_CALL startRootElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
};
class LibElementBase
: public ::cppu::WeakImplHelper1< xml::input::XElement >
{
protected:
LibraryImport * _pImport;
LibElementBase * _pParent;
OUString _aLocalName;
Reference< xml::input::XAttributes > _xAttributes;
public:
LibElementBase(
OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW(());
virtual ~LibElementBase()
SAL_THROW(());
// XElement
virtual Reference< xml::input::XElement > SAL_CALL getParent()
throw (RuntimeException, std::exception);
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException, std::exception);
virtual sal_Int32 SAL_CALL getUid()
throw (RuntimeException, std::exception);
virtual Reference< xml::input::XAttributes > SAL_CALL getAttributes()
throw (RuntimeException, std::exception);
virtual void SAL_CALL ignorableWhitespace(
OUString const & rWhitespaces )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL characters( OUString const & rChars )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL processingInstruction(
OUString const & rTarget, OUString const & rData )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual Reference< xml::input::XElement > SAL_CALL startChildElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
};
class LibrariesElement : public LibElementBase
{
friend class LibraryElement;
protected:
vector< LibDescriptor > mLibDescriptors;
public:
virtual Reference< xml::input::XElement > SAL_CALL startChildElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException, std::exception);
LibrariesElement(
OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW(())
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
class LibraryElement : public LibElementBase
{
protected:
vector< OUString > mElements;
public:
virtual Reference< xml::input::XElement > SAL_CALL startChildElement(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException, std::exception);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException, std::exception);
LibraryElement(
OUString const & rLocalName,
Reference< xml::input::XAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW(())
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: imp_share.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ab $ $Date: 2001-08-09 15:40:22 $
*
* 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 <vector>
#include <xmlscript/xmldlg_imexp.hxx>
#include <xmlscript/xmllib_imexp.hxx>
#include <xmlscript/xmlmod_imexp.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/xml/sax2/XExtendedAttributes.hpp>
#include <com/sun/star/xml/XImportContext.hpp>
#include <com/sun/star/xml/XImporter.hpp>
using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace xmlscript
{
//
inline sal_Int32 toInt32( OUString const & rStr ) SAL_THROW( () )
{
sal_Int32 nVal;
if (rStr.getLength() > 2 && rStr[ 0 ] == '0' && rStr[ 1 ] == 'x')
{
nVal = rStr.copy( 2 ).toInt32( 16 );
}
else
{
nVal = rStr.toInt32();
}
return nVal;
}
inline bool getBoolAttr(
sal_Bool * pRet, OUString const & rAttrName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
{
OUString aValue( xAttributes->getValueByUidName( XMLNS_LIBRARY_UID, rAttrName ) );
if (aValue.getLength())
{
if (aValue.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("true") ))
{
*pRet = sal_True;
return true;
}
else if (aValue.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("false") ))
{
*pRet = sal_False;
return true;
}
else
{
throw xml::sax::SAXException(
rAttrName + OUString( RTL_CONSTASCII_USTRINGPARAM(": no boolean value (true|false)!") ),
Reference< XInterface >(), Any() );
}
}
return false;
}
inline bool getStringAttr(
OUString * pRet, OUString const & rAttrName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
{
*pRet = xAttributes->getValueByUidName( XMLNS_LIBRARY_UID, rAttrName );
return (pRet->getLength() > 0);
}
inline bool getLongAttr(
sal_Int32 * pRet, OUString const & rAttrName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
{
OUString aValue( xAttributes->getValueByUidName( XMLNS_LIBRARY_UID, rAttrName ) );
if (aValue.getLength())
{
*pRet = toInt32( aValue );
return true;
}
return false;
}
//==================================================================================================
// Library import
//==================================================================================================
struct LibraryImport
: public ::cppu::WeakImplHelper1< xml::XImporter >
{
friend class LibrariesElement;
LibDescriptorArray* mpLibArray;
public:
inline LibraryImport( LibDescriptorArray* pLibArray )
SAL_THROW( () )
: mpLibArray( pLibArray ) {}
virtual ~LibraryImport()
SAL_THROW( () );
// XImporter
virtual void SAL_CALL startDocument()
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endDocument()
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL processingInstruction(
OUString const & rTarget, OUString const & rData )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL setDocumentLocator(
Reference< xml::sax::XLocator > const & xLocator )
throw (xml::sax::SAXException, RuntimeException);
virtual Reference< xml::XImportContext > SAL_CALL createRootContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
};
//==================================================================================================
class LibElementBase
: public ::cppu::WeakImplHelper1< xml::XImportContext >
{
protected:
LibraryImport * _pImport;
LibElementBase * _pParent;
OUString _aLocalName;
Reference< xml::sax2::XExtendedAttributes > _xAttributes;
public:
LibElementBase(
OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW( () );
virtual ~LibElementBase()
SAL_THROW( () );
// XImportContext
virtual Reference< xml::XImportContext > SAL_CALL getParent()
throw (RuntimeException);
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException);
virtual sal_Int32 SAL_CALL getUid()
throw (RuntimeException);
virtual Reference< xml::sax2::XExtendedAttributes > SAL_CALL getAttributes()
throw (RuntimeException);
virtual void SAL_CALL ignorableWhitespace(
OUString const & rWhitespaces )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL characters( OUString const & rChars )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException);
virtual Reference< xml::XImportContext > SAL_CALL createChildContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
};
//==================================================================================================
class LibrariesElement : public LibElementBase
{
friend class LibraryElement;
protected:
vector< LibDescriptor > mLibDescriptors;
public:
virtual Reference< xml::XImportContext > SAL_CALL createChildContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException);
LibrariesElement(
OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW( () )
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
//==================================================================================================
class LibraryElement : public LibElementBase
{
protected:
vector< OUString > mElements;
public:
virtual Reference< xml::XImportContext > SAL_CALL createChildContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException);
LibraryElement(
OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW( () )
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
};
<commit_msg>#86383# Library import<commit_after>/*************************************************************************
*
* $RCSfile: imp_share.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ab $ $Date: 2001-11-07 18:19:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vector>
#include <xmlscript/xmldlg_imexp.hxx>
#include <xmlscript/xmllib_imexp.hxx>
#include <xmlscript/xmlmod_imexp.hxx>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/xml/sax2/XExtendedAttributes.hpp>
#include <com/sun/star/xml/XImportContext.hpp>
#include <com/sun/star/xml/XImporter.hpp>
using namespace ::rtl;
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace xmlscript
{
//
inline sal_Int32 toInt32( OUString const & rStr ) SAL_THROW( () )
{
sal_Int32 nVal;
if (rStr.getLength() > 2 && rStr[ 0 ] == '0' && rStr[ 1 ] == 'x')
{
nVal = rStr.copy( 2 ).toInt32( 16 );
}
else
{
nVal = rStr.toInt32();
}
return nVal;
}
inline bool getBoolAttr(
sal_Bool * pRet, OUString const & rAttrName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
{
OUString aValue( xAttributes->getValueByUidName( XMLNS_LIBRARY_UID, rAttrName ) );
if (aValue.getLength())
{
if (aValue.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("true") ))
{
*pRet = sal_True;
return true;
}
else if (aValue.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("false") ))
{
*pRet = sal_False;
return true;
}
else
{
throw xml::sax::SAXException(
rAttrName + OUString( RTL_CONSTASCII_USTRINGPARAM(": no boolean value (true|false)!") ),
Reference< XInterface >(), Any() );
}
}
return false;
}
inline bool getStringAttr(
OUString * pRet, OUString const & rAttrName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
{
*pRet = xAttributes->getValueByUidName( XMLNS_LIBRARY_UID, rAttrName );
return (pRet->getLength() > 0);
}
inline bool getLongAttr(
sal_Int32 * pRet, OUString const & rAttrName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
{
OUString aValue( xAttributes->getValueByUidName( XMLNS_LIBRARY_UID, rAttrName ) );
if (aValue.getLength())
{
*pRet = toInt32( aValue );
return true;
}
return false;
}
//==================================================================================================
// Library import
//==================================================================================================
struct LibraryImport
: public ::cppu::WeakImplHelper1< xml::XImporter >
{
friend class LibrariesElement;
friend class LibraryElement;
LibDescriptorArray* mpLibArray;
LibDescriptor* mpLibDesc; // Single library mode
public:
inline LibraryImport( LibDescriptorArray* pLibArray )
SAL_THROW( () )
: mpLibArray( pLibArray )
, mpLibDesc( NULL ) {}
// Single library mode
inline LibraryImport( LibDescriptor* pLibDesc )
SAL_THROW( () )
: mpLibArray( NULL )
, mpLibDesc( pLibDesc ) {}
virtual ~LibraryImport()
SAL_THROW( () );
// XImporter
virtual void SAL_CALL startDocument()
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endDocument()
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL processingInstruction(
OUString const & rTarget, OUString const & rData )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL setDocumentLocator(
Reference< xml::sax::XLocator > const & xLocator )
throw (xml::sax::SAXException, RuntimeException);
virtual Reference< xml::XImportContext > SAL_CALL createRootContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
};
//==================================================================================================
class LibElementBase
: public ::cppu::WeakImplHelper1< xml::XImportContext >
{
protected:
LibraryImport * _pImport;
LibElementBase * _pParent;
OUString _aLocalName;
Reference< xml::sax2::XExtendedAttributes > _xAttributes;
public:
LibElementBase(
OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW( () );
virtual ~LibElementBase()
SAL_THROW( () );
// XImportContext
virtual Reference< xml::XImportContext > SAL_CALL getParent()
throw (RuntimeException);
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException);
virtual sal_Int32 SAL_CALL getUid()
throw (RuntimeException);
virtual Reference< xml::sax2::XExtendedAttributes > SAL_CALL getAttributes()
throw (RuntimeException);
virtual void SAL_CALL ignorableWhitespace(
OUString const & rWhitespaces )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL characters( OUString const & rChars )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException);
virtual Reference< xml::XImportContext > SAL_CALL createChildContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
};
//==================================================================================================
class LibrariesElement : public LibElementBase
{
friend class LibraryElement;
protected:
vector< LibDescriptor > mLibDescriptors;
public:
virtual Reference< xml::XImportContext > SAL_CALL createChildContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException);
LibrariesElement(
OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW( () )
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
//==================================================================================================
class LibraryElement : public LibElementBase
{
protected:
vector< OUString > mElements;
public:
virtual Reference< xml::XImportContext > SAL_CALL createChildContext(
sal_Int32 nUid, OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes )
throw (xml::sax::SAXException, RuntimeException);
virtual void SAL_CALL endElement()
throw (xml::sax::SAXException, RuntimeException);
LibraryElement(
OUString const & rLocalName,
Reference< xml::sax2::XExtendedAttributes > const & xAttributes,
LibElementBase * pParent, LibraryImport * pImport )
SAL_THROW( () )
: LibElementBase( rLocalName, xAttributes, pParent, pImport )
{}
};
};
<|endoftext|> |
<commit_before>#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(MBTC);
unitlist.append(kBTC);
unitlist.append(BTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case MBTC:
case kBTC:
case BTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case MBTC: return QString("MFLAP");
case kBTC: return QString("kFLAP");
case BTC: return QString("FLAP");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case MBTC: return QString("Million-Flappycoins (1 * 1,000,000)");
case kBTC: return QString("Thousand-Flappycoins (1 * 1,000)");
case BTC: return QString("Flappycoins");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case MBTC: return 100000000000000;
case kBTC: return 100000000000;
case BTC: return 100000000;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case MBTC: return 3; // 210 (# digits, without commas)
case kBTC: return 6; // 210,000 (# digits, without commas)
case BTC: return 9; // 210,000,000 (# digits, without commas)
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case MBTC: return 8;
case kBTC: return 8;
case BTC: return 8;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
<commit_msg>Update bitcoinunits.cpp<commit_after>#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(MBTC);
unitlist.append(kBTC);
unitlist.append(BTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case MBTC:
case kBTC:
case BTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case MBTC: return QString("MFLAP");
case kBTC: return QString("kFLAP");
case BTC: return QString("FLAP");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case MBTC: return QString("Million-Flappycoins (1 * 1,000,000)");
case kBTC: return QString("Thousand-Flappycoins (1 * 1,000)");
case BTC: return QString("Flappycoins");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case MBTC: return 100000000000000;
case kBTC: return 100000000000;
case BTC: return 100000000;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case MBTC: return 3; // 210 (# digits, without commas)
case kBTC: return 6; // 210,000 (# digits, without commas)
case BTC: return 9; // 210,000,000 (# digits, without commas)
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case MBTC: return 14;
case kBTC: return 11;
case BTC: return 8;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Robert Bosch LLC.
* 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 Robert Bosch 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.
*
*********************************************************************/
//\Author Kai Franke
#include "raspi_interface/raspi_interface.hpp"
/**********************************************************************/
// Constructor
/**********************************************************************/
RaspiInterface::RaspiInterface():
is_initialized_( false )
{
}
/**********************************************************************/
// Destructor
/**********************************************************************/
RaspiInterface::~RaspiInterface()
{
// close all serial connections
for (std::map<std::string,int>::iterator it=serial_devices_.begin(); it!=serial_devices_.end(); ++it)
{
serialClose(it->second);
}
}
/**********************************************************************/
// Initialize:
/**********************************************************************/
bool RaspiInterface::initialize()
{
// Prevent Double-initialization!
if( is_initialized_ == true )
{
ROS_INFO( "RaspiInterface::initialize(): WiringPi already initialized." );
return true;
}
// Setup WiringPi
int init_reply = wiringPiSetup ();
// Set all SPI channels not to use by default
for( ssize_t i = 0; i < MAX_SPI_CHANNELS; ++i )
{
use_spi[i] = false;
}
if( init_reply != 0 )
{
ROS_ERROR( "WiringPi not initialized properly. Returned %i", init_reply);
return false;
}
is_initialized_ = true;
ROS_INFO( "RaspiInterface::initialize(): WiringPi initialized." );
return true;
}
/**********************************************************************/
// Read
/**********************************************************************/
ssize_t RaspiInterface::read( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
int error_code = 0;
// Check initialization:
if( is_initialized_ == false )
{
return -1;
}
switch( protocol )
{
case GPIO:
{
error_code = raspiGpioRead( (uint8_t)flags[0], reg_address, data );
break;
}
case SPI:
{
error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes );
break;
}
case I2C:
{
error_code = raspiI2cRead( device_address, frequency, reg_address, data, num_bytes );
} break;
case RS232:
{
error_code = raspiRs232Read( frequency, flags[0], data, num_bytes );
} break;
default:
{
ROS_ERROR("Raspberry Pi does not support reading through this protocol.");
return -1;
}
}
return error_code;
}
/**********************************************************************/
// Write
/**********************************************************************/
ssize_t RaspiInterface::write( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
int error_code = 0;
// Check initialization:
if( is_initialized_ == false )
{
return -1;
}
switch( protocol )
{
case GPIO:
{
error_code = raspiGpioWrite( reg_address, (bool)data[0] );
break;
}
case SPI:
{
error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes );
break;
}
case RS232:
{
error_code = raspiRs232Write( frequency, data, num_bytes );
} break;
case I2C:
{
error_code = raspiI2cWrite( device_address, frequency, reg_address, data, num_bytes );
} break;
default:
{
ROS_ERROR( "Raspberry Pi does not support writing through this protocol." );
error_code = -1;
}
}
return error_code; // bytes written, or error.
}
/**********************************************************************/
// supportedProtocol
/**********************************************************************/
bool RaspiInterface::supportedProtocol( interface_protocol protocol )
{
switch( protocol )
{
case GPIO:
case SPI:
case RS232:
return true;
default:
return false;
}
}
/**********************************************************************/
std::string RaspiInterface::getID()
/**********************************************************************/
{
return "Raspberry Pi";
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiGpioWrite( uint8_t pin, bool value )
{
// check if selected pin is valid for Raspberry Pi
if( pin > 16 )
{
ROS_ERROR("The selected Pin number is not available for GPIO");
ROS_ERROR("Select Pins 0 through 16 instead");
return -1;
}
pinMode (pin, OUTPUT);
digitalWrite (pin, value);
return 1;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiGpioRead( uint8_t flags, uint8_t pin, uint8_t* value )
{
// check if selected pin is valid for Raspberry Pi
if( pin > 16 )
{
ROS_ERROR("The selected Pin number is not available for GPIO");
ROS_ERROR("Select Pins 0 through 16 instead");
return -1;
}
pinMode( pin, INPUT );
switch ((gpio_input_mode) flags )
{
case FLOATING:
{
pullUpDnControl( pin, PUD_OFF );
} break;
case PULLUP:
{
pullUpDnControl( pin, PUD_UP );
} break;
case PULLDOWN:
{
pullUpDnControl( pin, PUD_DOWN );
} break;
default:
{
ROS_ERROR("ArduinoInterface::arduinoGpioRead The selected input mode is not known");
return -1;
}
}
value[0] = digitalRead( pin );
return 1;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiSpi( int frequency, uint8_t flags, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
// Decrypt flags:
uint8_t spi_slave_select = (flags >> 4);
uint8_t bit_order = (flags>>2) & 0x01;
uint8_t mode = flags & 0x03;
// Sanity check for decrypted flags
if( mode != bosch_drivers_common::SPI_MODE_0 )
{
ROS_ERROR( "Only mode 0 is implemented in wiringPi at this point" );
return -1;
}
if( bit_order != 0 )
{
ROS_ERROR( "Only MSB first is implemented in wiringPi at this point" );
return -1;
}
if( spi_slave_select == bosch_drivers_common::NULL_DEVICE )
{
ROS_ERROR( "NULL_DEVICE functionality not implemented yet" );
return -1;
}
if( spi_slave_select >= MAX_SPI_CHANNELS )
{
ROS_ERROR( "Maximum SPI channel is %i, you asked for channel %i", MAX_SPI_CHANNELS-1, spi_slave_select );
return -1;
}
if( frequency < MIN_SPI_FREQUENCY || frequency > MAX_SPI_FREQUENCY )
{
ROS_WARN( "The requested frequency of %i is out of bounds. Setting frequency to 1MHz", frequency );
frequency = 1e6;
}
// setup SPI channel if it has not been setup yet
if( use_spi[spi_slave_select] == false )
{
if( wiringPiSPISetup (spi_slave_select, frequency) == -1 )
{
ROS_ERROR( "RaspiInterface::initializeSPI(): SPI channel 0 not initialized properly.");
return false;
}
use_spi[spi_slave_select] = true;
ROS_INFO( "SPI channel %u initialized.", spi_slave_select );
}
// transfer the address register:
wiringPiSPIDataRW( spi_slave_select, ®_address, 1 );
// read/write from/to SPI bus
wiringPiSPIDataRW( spi_slave_select, data, num_bytes );
return num_bytes;
}
ssize_t RaspiInterface::raspiRs232Write( int frequency, uint8_t* data, size_t num_bytes )
{
// convert uint8_t* to string
std::string complete( data, data + num_bytes );
// split string at first colon
size_t delimiter = complete.find_first_of( ':' );
if( delimiter == std::string::npos )
{
ROS_ERROR( "No colon found in data string! Example: /dev/ttyUSB0:helloWorld" );
return -1;
}
std::string device = complete.substr( 0, delimiter );
std::string command = complete.substr( delimiter + 1 );
char* cdevice = reinterpret_cast<char*>(&device[0]);
char* ccommand= reinterpret_cast<char*>(&command[0]);
// open new serial device if not opened yet
if( serial_devices_.count(device) != 1 )
{
// open serial interface using wiringPi
ROS_INFO("Opening serial interface %s...", cdevice );
int file_descriptor = serialOpen( cdevice, frequency );
// check if serial device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening serial device %s failed :(", cdevice );
return -1;
}
else
{
ROS_INFO( "Successfully opened serial port %s", cdevice );
}
// create new hash entry
serial_devices_[device] = file_descriptor;
}
// write command to RS232 connection
serialPuts( serial_devices_[device], ccommand );
return command.size();
}
ssize_t RaspiInterface::raspiRs232Read( int frequency, int device_name_length, uint8_t* data, size_t num_bytes )
{
std::string device( data, data + device_name_length );
char* cdevice = reinterpret_cast<char*>(&device[0]);
// open new serial device if not opened yet
if( serial_devices_.count(cdevice) != 1 )
{
// open serial interface using wiringPi
ROS_INFO("Opening serial interface %s...", cdevice );
int file_descriptor = serialOpen( cdevice, frequency );
// check if serial device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening serial device %s failed :(", cdevice );
return -1;
}
else
{
ROS_INFO( "Successfully opened serial port %s", cdevice );
}
// create new hash entry
serial_devices_[device] = file_descriptor;
}
// read from RS232
unsigned int index = 0;
int temp = 0;
while( temp != -1 && num_bytes-- > 0 )
{
temp = serialGetchar( serial_devices_[device] );
data[index++] = static_cast<uint8_t>(temp);
}
if( index != num_bytes )
{
ROS_WARN( "You asked for %zd bytes but I only read %i due to error or timeout", num_bytes, index );
}
return index;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiI2cWrite( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
switch( frequency )
{
case 100000: break;
default:
{
ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency");
}
}
// open new i2c device if not opened yet
if( i2c_devices_.count(device_address) != 1 )
{
// open i2c interface using wiringPi
int file_descriptor = wiringPiI2CSetup( device_address );
// check if i2c device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening i2c device %i failed :(", device_address );
return -1;
}
// create new hash entry
i2c_devices_[device_address] = file_descriptor;
ROS_INFO( "Successfully opened i2c device %i", device_address);
}
int error_code = -1;
switch( num_bytes )
{
case 1:
{
error_code = wiringPiI2CWriteReg8 (i2c_devices_[device_address], reg_address, data[0]);
} break;
case 2:
{
// compose 16 Bit value to transmit assuming data[1] is the MSB
int temp = ((int)data[1])*256 + data[0];
error_code = wiringPiI2CWriteReg16 (i2c_devices_[device_address], reg_address, temp);
} break;
default:
{
ROS_ERROR("Raspberry Pi can only transmit either one or two bytes");
}
}
if( error_code == -1 )
{
ROS_ERROR( "I2C Write failed" );
return error_code;
}
return num_bytes;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiI2cRead( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
switch( frequency )
{
case 100000: break;
default:
{
ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency");
}
}
// open new i2c device if not opened yet
if( i2c_devices_.count(device_address) != 1 )
{
// open i2c interface using wiringPi
int file_descriptor = wiringPiI2CSetup( device_address );
// check if i2c device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening i2c device %i failed :(", device_address );
return -1;
}
// create new hash entry
i2c_devices_[device_address] = file_descriptor;
ROS_INFO( "Successfully opened i2c device %i", device_address);
}
switch( num_bytes )
{
case 1:
{
data[0] = wiringPiI2CReadReg8( i2c_devices_[device_address], reg_address );
} break;
case 2:
{
int temp = wiringPiI2CReadReg16( i2c_devices_[device_address], reg_address );
data[0] = (uint8_t) temp;
data[1] = (uint8_t) ( temp / 256 );
} break;
default:
{
ROS_ERROR("Raspberry Pi can only read either one or two bytes");
return -1;
}
}
return num_bytes;
}
<commit_msg>I2C now also listed as supported protocol<commit_after>/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Robert Bosch LLC.
* 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 Robert Bosch 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.
*
*********************************************************************/
//\Author Kai Franke
#include "raspi_interface/raspi_interface.hpp"
/**********************************************************************/
// Constructor
/**********************************************************************/
RaspiInterface::RaspiInterface():
is_initialized_( false )
{
}
/**********************************************************************/
// Destructor
/**********************************************************************/
RaspiInterface::~RaspiInterface()
{
// close all serial connections
for (std::map<std::string,int>::iterator it=serial_devices_.begin(); it!=serial_devices_.end(); ++it)
{
serialClose(it->second);
}
}
/**********************************************************************/
// Initialize:
/**********************************************************************/
bool RaspiInterface::initialize()
{
// Prevent Double-initialization!
if( is_initialized_ == true )
{
ROS_INFO( "RaspiInterface::initialize(): WiringPi already initialized." );
return true;
}
// Setup WiringPi
int init_reply = wiringPiSetup ();
// Set all SPI channels not to use by default
for( ssize_t i = 0; i < MAX_SPI_CHANNELS; ++i )
{
use_spi[i] = false;
}
if( init_reply != 0 )
{
ROS_ERROR( "WiringPi not initialized properly. Returned %i", init_reply);
return false;
}
is_initialized_ = true;
ROS_INFO( "RaspiInterface::initialize(): WiringPi initialized." );
return true;
}
/**********************************************************************/
// Read
/**********************************************************************/
ssize_t RaspiInterface::read( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
int error_code = 0;
// Check initialization:
if( is_initialized_ == false )
{
return -1;
}
switch( protocol )
{
case GPIO:
{
error_code = raspiGpioRead( (uint8_t)flags[0], reg_address, data );
break;
}
case SPI:
{
error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes );
break;
}
case I2C:
{
error_code = raspiI2cRead( device_address, frequency, reg_address, data, num_bytes );
} break;
case RS232:
{
error_code = raspiRs232Read( frequency, flags[0], data, num_bytes );
} break;
default:
{
ROS_ERROR("Raspberry Pi does not support reading through this protocol.");
return -1;
}
}
return error_code;
}
/**********************************************************************/
// Write
/**********************************************************************/
ssize_t RaspiInterface::write( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
int error_code = 0;
// Check initialization:
if( is_initialized_ == false )
{
return -1;
}
switch( protocol )
{
case GPIO:
{
error_code = raspiGpioWrite( reg_address, (bool)data[0] );
break;
}
case SPI:
{
error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes );
break;
}
case RS232:
{
error_code = raspiRs232Write( frequency, data, num_bytes );
} break;
case I2C:
{
error_code = raspiI2cWrite( device_address, frequency, reg_address, data, num_bytes );
} break;
default:
{
ROS_ERROR( "Raspberry Pi does not support writing through this protocol." );
error_code = -1;
}
}
return error_code; // bytes written, or error.
}
/**********************************************************************/
// supportedProtocol
/**********************************************************************/
bool RaspiInterface::supportedProtocol( interface_protocol protocol )
{
switch( protocol )
{
case GPIO:
case SPI:
case RS232:
case I2C:
return true;
default:
return false;
}
}
/**********************************************************************/
std::string RaspiInterface::getID()
/**********************************************************************/
{
return "Raspberry Pi";
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiGpioWrite( uint8_t pin, bool value )
{
// check if selected pin is valid for Raspberry Pi
if( pin > 16 )
{
ROS_ERROR("The selected Pin number is not available for GPIO");
ROS_ERROR("Select Pins 0 through 16 instead");
return -1;
}
pinMode (pin, OUTPUT);
digitalWrite (pin, value);
return 1;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiGpioRead( uint8_t flags, uint8_t pin, uint8_t* value )
{
// check if selected pin is valid for Raspberry Pi
if( pin > 16 )
{
ROS_ERROR("The selected Pin number is not available for GPIO");
ROS_ERROR("Select Pins 0 through 16 instead");
return -1;
}
pinMode( pin, INPUT );
switch ((gpio_input_mode) flags )
{
case FLOATING:
{
pullUpDnControl( pin, PUD_OFF );
} break;
case PULLUP:
{
pullUpDnControl( pin, PUD_UP );
} break;
case PULLDOWN:
{
pullUpDnControl( pin, PUD_DOWN );
} break;
default:
{
ROS_ERROR("ArduinoInterface::arduinoGpioRead The selected input mode is not known");
return -1;
}
}
value[0] = digitalRead( pin );
return 1;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiSpi( int frequency, uint8_t flags, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
// Decrypt flags:
uint8_t spi_slave_select = (flags >> 4);
uint8_t bit_order = (flags>>2) & 0x01;
uint8_t mode = flags & 0x03;
// Sanity check for decrypted flags
if( mode != bosch_drivers_common::SPI_MODE_0 )
{
ROS_ERROR( "Only mode 0 is implemented in wiringPi at this point" );
return -1;
}
if( bit_order != 0 )
{
ROS_ERROR( "Only MSB first is implemented in wiringPi at this point" );
return -1;
}
if( spi_slave_select == bosch_drivers_common::NULL_DEVICE )
{
ROS_ERROR( "NULL_DEVICE functionality not implemented yet" );
return -1;
}
if( spi_slave_select >= MAX_SPI_CHANNELS )
{
ROS_ERROR( "Maximum SPI channel is %i, you asked for channel %i", MAX_SPI_CHANNELS-1, spi_slave_select );
return -1;
}
if( frequency < MIN_SPI_FREQUENCY || frequency > MAX_SPI_FREQUENCY )
{
ROS_WARN( "The requested frequency of %i is out of bounds. Setting frequency to 1MHz", frequency );
frequency = 1e6;
}
// setup SPI channel if it has not been setup yet
if( use_spi[spi_slave_select] == false )
{
if( wiringPiSPISetup (spi_slave_select, frequency) == -1 )
{
ROS_ERROR( "RaspiInterface::initializeSPI(): SPI channel 0 not initialized properly.");
return -1;
}
use_spi[spi_slave_select] = true;
ROS_INFO( "SPI channel %u initialized.", spi_slave_select );
}
// transfer the address register:
wiringPiSPIDataRW( spi_slave_select, ®_address, 1 );
// read/write from/to SPI bus
wiringPiSPIDataRW( spi_slave_select, data, num_bytes );
return num_bytes;
}
ssize_t RaspiInterface::raspiRs232Write( int frequency, uint8_t* data, size_t num_bytes )
{
// convert uint8_t* to string
std::string complete( data, data + num_bytes );
// split string at first colon
size_t delimiter = complete.find_first_of( ':' );
if( delimiter == std::string::npos )
{
ROS_ERROR( "No colon found in data string! Example: /dev/ttyUSB0:helloWorld" );
return -1;
}
std::string device = complete.substr( 0, delimiter );
std::string command = complete.substr( delimiter + 1 );
char* cdevice = reinterpret_cast<char*>(&device[0]);
char* ccommand= reinterpret_cast<char*>(&command[0]);
// open new serial device if not opened yet
if( serial_devices_.count(device) != 1 )
{
// open serial interface using wiringPi
ROS_INFO("Opening serial interface %s...", cdevice );
int file_descriptor = serialOpen( cdevice, frequency );
// check if serial device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening serial device %s failed :(", cdevice );
return -1;
}
else
{
ROS_INFO( "Successfully opened serial port %s", cdevice );
}
// create new hash entry
serial_devices_[device] = file_descriptor;
}
// write command to RS232 connection
serialPuts( serial_devices_[device], ccommand );
return command.size();
}
ssize_t RaspiInterface::raspiRs232Read( int frequency, int device_name_length, uint8_t* data, size_t num_bytes )
{
std::string device( data, data + device_name_length );
char* cdevice = reinterpret_cast<char*>(&device[0]);
// open new serial device if not opened yet
if( serial_devices_.count(cdevice) != 1 )
{
// open serial interface using wiringPi
ROS_INFO("Opening serial interface %s...", cdevice );
int file_descriptor = serialOpen( cdevice, frequency );
// check if serial device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening serial device %s failed :(", cdevice );
return -1;
}
else
{
ROS_INFO( "Successfully opened serial port %s", cdevice );
}
// create new hash entry
serial_devices_[device] = file_descriptor;
}
// read from RS232
unsigned int index = 0;
int temp = 0;
while( temp != -1 && num_bytes-- > 0 )
{
temp = serialGetchar( serial_devices_[device] );
data[index++] = static_cast<uint8_t>(temp);
}
if( index != num_bytes )
{
ROS_WARN( "You asked for %zd bytes but I only read %i due to error or timeout", num_bytes, index );
}
return index;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiI2cWrite( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
switch( frequency )
{
case 100000: break;
default:
{
ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency");
}
}
// open new i2c device if not opened yet
if( i2c_devices_.count(device_address) != 1 )
{
// open i2c interface using wiringPi
int file_descriptor = wiringPiI2CSetup( device_address );
// check if i2c device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening i2c device %i failed :(", device_address );
return -1;
}
// create new hash entry
i2c_devices_[device_address] = file_descriptor;
ROS_INFO( "Successfully opened i2c device %i", device_address);
}
int error_code = -1;
switch( num_bytes )
{
case 1:
{
error_code = wiringPiI2CWriteReg8 (i2c_devices_[device_address], reg_address, data[0]);
} break;
case 2:
{
// compose 16 Bit value to transmit assuming data[1] is the MSB
int temp = ((int)data[1])*256 + data[0];
error_code = wiringPiI2CWriteReg16 (i2c_devices_[device_address], reg_address, temp);
} break;
default:
{
ROS_ERROR("Raspberry Pi can only transmit either one or two bytes");
}
}
if( error_code == -1 )
{
ROS_ERROR( "I2C Write failed" );
return error_code;
}
return num_bytes;
}
/**********************************************************************/
/**********************************************************************/
ssize_t RaspiInterface::raspiI2cRead( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes )
{
switch( frequency )
{
case 100000: break;
default:
{
ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency");
}
}
// open new i2c device if not opened yet
if( i2c_devices_.count(device_address) != 1 )
{
// open i2c interface using wiringPi
int file_descriptor = wiringPiI2CSetup( device_address );
// check if i2c device was opened successfully
if( file_descriptor == -1 )
{
ROS_ERROR("Opening i2c device %i failed :(", device_address );
return -1;
}
// create new hash entry
i2c_devices_[device_address] = file_descriptor;
ROS_INFO( "Successfully opened i2c device %i", device_address);
}
switch( num_bytes )
{
case 1:
{
data[0] = wiringPiI2CReadReg8( i2c_devices_[device_address], reg_address );
} break;
case 2:
{
int temp = wiringPiI2CReadReg16( i2c_devices_[device_address], reg_address );
data[0] = (uint8_t) temp;
data[1] = (uint8_t) ( temp / 256 );
} break;
default:
{
ROS_ERROR("Raspberry Pi can only read either one or two bytes");
return -1;
}
}
return num_bytes;
}
<|endoftext|> |
<commit_before>#include <roerei/cpp14_fix.hpp>
#include <roerei/cli.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>
namespace roerei
{
int cli::read_options(cli_options& opt, int argc, char** argv)
{
std::string corpii, methods, strats;
boost::program_options::options_description o_general("Options");
o_general.add_options()
("help,h", "display this message")
("silent,s", "do not print progress")
("corpii,c", boost::program_options::value(&corpii), "select which corpii to sample or generate, possibly comma separated (default: all)")
("methods,m", boost::program_options::value(&methods), "select which methods to use, possibly comma separated (default: all)")
("strats,r", boost::program_options::value(&strats), "select which poset consistency strategies to use, possibly comma separated (default: all)")
("jobs,j", boost::program_options::value(&opt.jobs), "number of concurrent jobs (default: 1)");
boost::program_options::variables_map vm;
boost::program_options::positional_options_description pos;
pos.add("action", 1);
boost::program_options::options_description options("Allowed options");
options.add(o_general);
options.add_options()
("action", boost::program_options::value(&opt.action));
try
{
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(pos).run(), vm);
} catch(boost::program_options::unknown_option &e)
{
std::cerr << "Unknown option --" << e.get_option_name() << ", see --help." << std::endl;
return EXIT_FAILURE;
}
try
{
boost::program_options::notify(vm);
} catch(const boost::program_options::required_option &e)
{
std::cerr << "You forgot this: " << e.what() << std::endl;
return EXIT_FAILURE;
}
if(vm.count("help"))
{
std::cout
<< "Premise selection for Coq in OCaml/C++. [https://github.com/Wassasin/roerei]" << std::endl
<< "Usage: ./roerei [options] action" << std::endl
<< std::endl
<< "Actions:" << std::endl
<< " generate load repo.msgpack, convert and write to dataset.msgpack" << std::endl
<< " inspect inspect all objects" << std::endl
<< " measure run all scheduled tests and store the results" << std::endl
<< " report report on all results" << std::endl
<< std::endl
<< o_general;
return EXIT_FAILURE;
}
if(vm.count("silent"))
opt.silent = true;
if(!vm.count("action"))
{
std::cerr << "Please specify an action, see --help." << std::endl;
return EXIT_FAILURE;
}
if(!vm.count("corpii") || corpii == "all")
opt.corpii = {"Coq", "CoRN", "CoRN-legacy", "ch2o", "mathcomp", "MathClasses"}; // TODO automate
else
boost::algorithm::split(opt.corpii, corpii, boost::algorithm::is_any_of(","));
if(!vm.count("methods") || methods == "all")
opt.methods = {ml_type::knn, ml_type::knn_adaptive, ml_type::naive_bayes, ml_type::omniscient, ml_type::ensemble};
else
{
std::vector<std::string> methods_arr;
boost::algorithm::split(methods_arr, methods, boost::algorithm::is_any_of(","));
for(auto m : methods_arr)
opt.methods.emplace_back(to_ml_type(m));
}
if(!vm.count("strats") || strats == "all")
{
opt.strats = {posetcons_type::canonical, posetcons_type::optimistic, posetcons_type::pessimistic};
}
else
{
std::vector<std::string> strats_arr;
boost::algorithm::split(strats_arr, strats, boost::algorithm::is_any_of(","));
for(auto s : strats_arr)
opt.strats.emplace_back(to_posetcons_type(s));
}
return EXIT_SUCCESS;
}
}
<commit_msg>Add -h entries for 'legacy-export' and 'legacy-import'<commit_after>#include <roerei/cpp14_fix.hpp>
#include <roerei/cli.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>
namespace roerei
{
int cli::read_options(cli_options& opt, int argc, char** argv)
{
std::string corpii, methods, strats;
boost::program_options::options_description o_general("Options");
o_general.add_options()
("help,h", "display this message")
("silent,s", "do not print progress")
("corpii,c", boost::program_options::value(&corpii), "select which corpii to sample or generate, possibly comma separated (default: all)")
("methods,m", boost::program_options::value(&methods), "select which methods to use, possibly comma separated (default: all)")
("strats,r", boost::program_options::value(&strats), "select which poset consistency strategies to use, possibly comma separated (default: all)")
("jobs,j", boost::program_options::value(&opt.jobs), "number of concurrent jobs (default: 1)");
boost::program_options::variables_map vm;
boost::program_options::positional_options_description pos;
pos.add("action", 1);
boost::program_options::options_description options("Allowed options");
options.add(o_general);
options.add_options()
("action", boost::program_options::value(&opt.action));
try
{
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(pos).run(), vm);
} catch(boost::program_options::unknown_option &e)
{
std::cerr << "Unknown option --" << e.get_option_name() << ", see --help." << std::endl;
return EXIT_FAILURE;
}
try
{
boost::program_options::notify(vm);
} catch(const boost::program_options::required_option &e)
{
std::cerr << "You forgot this: " << e.what() << std::endl;
return EXIT_FAILURE;
}
if(vm.count("help"))
{
std::cout
<< "Premise selection for Coq in OCaml/C++. [https://github.com/Wassasin/roerei]" << std::endl
<< "Usage: ./roerei [options] action" << std::endl
<< std::endl
<< "Actions:" << std::endl
<< " generate load repo.msgpack, convert and write to dataset.msgpack" << std::endl
<< " inspect inspect all objects" << std::endl
<< " measure run all scheduled tests and store the results" << std::endl
<< " report report on all results" << std::endl
<< " legacy-export export dataset in the legacy format" << std::endl
<< " legacy-import import dataset in the legacy format" << std::endl
<< std::endl
<< o_general;
return EXIT_FAILURE;
}
if(vm.count("silent"))
opt.silent = true;
if(!vm.count("action"))
{
std::cerr << "Please specify an action, see --help." << std::endl;
return EXIT_FAILURE;
}
if(!vm.count("corpii") || corpii == "all")
opt.corpii = {"Coq", "CoRN", "CoRN-legacy", "ch2o", "mathcomp", "MathClasses"}; // TODO automate
else
boost::algorithm::split(opt.corpii, corpii, boost::algorithm::is_any_of(","));
if(!vm.count("methods") || methods == "all")
opt.methods = {ml_type::knn, ml_type::knn_adaptive, ml_type::naive_bayes, ml_type::omniscient, ml_type::ensemble};
else
{
std::vector<std::string> methods_arr;
boost::algorithm::split(methods_arr, methods, boost::algorithm::is_any_of(","));
for(auto m : methods_arr)
opt.methods.emplace_back(to_ml_type(m));
}
if(!vm.count("strats") || strats == "all")
{
opt.strats = {posetcons_type::canonical, posetcons_type::optimistic, posetcons_type::pessimistic};
}
else
{
std::vector<std::string> strats_arr;
boost::algorithm::split(strats_arr, strats, boost::algorithm::is_any_of(","));
for(auto s : strats_arr)
opt.strats.emplace_back(to_posetcons_type(s));
}
return EXIT_SUCCESS;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <iterator>
#include <cppconn/prepared_statement.h>
namespace rusql
{
/*! A prepared statement, which encapsulates the result as well.
While this class aims to be stateless, it does have some state, so... stay a while, and listen!
You can create a statement with placeholders, and fill them in with the stream-insertion-operator.
After you filled all the placeholders (the statement will 'friendly' remind you if you forgot one), you can execute/update/query the query.
An execute returns success/failure, you need to check this value yourself
An update returns the number of updated records
A query puts the statement in a different state. After the query, you can iterate over the statement (it has begin() and end() members) and then you get the rows!
The rows can be read with >>, if you just want the first N columns of the row. The other way is to use operator[string] on the row, which gets you that column.
*/
class statement
{
private:
std::unique_ptr<sql::PreparedStatement> stmt;
std::unique_ptr<sql::ResultSet> data;
mutable size_t set_i, get_i;
/*! Resets the (internal) state of the statement, which is used for keeping track of which placeholders to replace when users to >> and << */
void reset() const
{
set_i = 1;
get_i = 1;
}
private:
/*! An interface to a row, you can extract values from columns with >> as well as operator[string] as well as get_<type>(string column)
Currently has a reference to the statment (with the ResultSet), so it makes now copy. Changing the statement (eg calling .next()), changes this query_result_row. That's why this class is private (but we have auto now...).
TODO: consider copying the data?
*/
class query_result_row {
public:
query_result_row(statement& s)
: stmt(s)
{}
template <typename T>
const statement& operator>>(T& x) const {
return stmt >> x;
}
std::string get_string(const std::string col) const {
return stmt.get_string(col);
}
uint64_t get_uint64(const std::string col) const {
return stmt.get_uint64(col);
}
bool is_null(const std::string col) const {
return stmt.is_null(col);
}
private:
statement& stmt;
};
/*! An iterator that iterates over rows of a result. Knows when he has hit the last row. */
class query_iterator : public std::iterator<std::input_iterator_tag, query_result_row, std::ptrdiff_t, query_result_row, query_result_row> {
public:
query_iterator()
: stmt(nullptr)
{}
query_iterator(statement& s)
: stmt(&s)
{
//Advance to the first row
operator++();
}
bool operator ==(query_iterator const & rh) {
return stmt == rh.stmt;
}
bool operator !=(query_iterator const& rh) {
return !(stmt == rh.stmt);
}
query_iterator& operator++(){
if(!stmt->next())
stmt = nullptr;
return *this;
}
query_result_row operator*() {
return query_result_row(*stmt);
}
private:
statement* stmt;
};
public:
/* Initializes a statement, with a statement. The object takes ownership of the statement.
\todo Change the ctor to accept a std::string, which we give to sql and intialize ourselves with. This should be a private-ctor or something because we take ownership of the pointer.
*/
statement(sql::PreparedStatement* stmt)
: stmt(stmt)
, data()
, set_i(1)
, get_i(1)
{}
/*! Inserts the given argument in the current placeholder */
const statement& operator<<(const std::string value) const
{
stmt->setString(set_i++, value);
return *this;
}
/*! Inserts the given argument in the current placeholder */
const statement& operator<<(const uint64_t value) const
{
stmt->setUInt64(set_i++, value);
return *this;
}
/*! Extracts the value from the current placeholder */
const statement& operator>>(std::string& value) const
{
value = data->getString(get_i++);
return *this;
}
const statement& operator>>(uint64_t& value) const
{
value = data->getUInt64(get_i++);
return *this;
}
std::string get_string(const std::string col) const
{
return data->getString(col);
}
/*! Fetch the int at the given column
\param col Tells which column to use
\return The value in that row in the given column
*/
uint64_t get_uint64(const std::string col) const
{
return data->getUInt64(col);
}
bool is_null(const std::string col) const
{
return data->isNull(col);
}
/*! Advances the statement-result to the next row
\return Returns whether the statement-result is now on a row.
*/
bool next() const
{
reset();
return data->next();
}
query_iterator begin() {
return query_iterator(*this);
}
query_iterator end() {
return query_iterator();
}
void execute() const
{
auto r = stmt->execute();
// TODO: figure out when execute doesn't return 0.
// TODO: make better error handling.
if(r){
auto ptr = stmt->getWarnings();
if(ptr){
std::cout << "Fail: " << ptr->getMessage() << std::endl;
} else {
std::cout << "Fail without a message..." << std::endl;
}
}
reset();
}
int update() const
{
auto r = stmt->executeUpdate();
reset();
return r;
}
public:
statement& query()
{
data.reset(stmt->executeQuery());
reset();
return *this;
}
};
}
<commit_msg>Add missing inclusion.<commit_after>#pragma once
#include <memory>
#include <iterator>
#include <cppconn/prepared_statement.h>
#include <cppconn/warning.h>
namespace rusql
{
/*! A prepared statement, which encapsulates the result as well.
While this class aims to be stateless, it does have some state, so... stay a while, and listen!
You can create a statement with placeholders, and fill them in with the stream-insertion-operator.
After you filled all the placeholders (the statement will 'friendly' remind you if you forgot one), you can execute/update/query the query.
An execute returns success/failure, you need to check this value yourself
An update returns the number of updated records
A query puts the statement in a different state. After the query, you can iterate over the statement (it has begin() and end() members) and then you get the rows!
The rows can be read with >>, if you just want the first N columns of the row. The other way is to use operator[string] on the row, which gets you that column.
*/
class statement
{
private:
std::unique_ptr<sql::PreparedStatement> stmt;
std::unique_ptr<sql::ResultSet> data;
mutable size_t set_i, get_i;
/*! Resets the (internal) state of the statement, which is used for keeping track of which placeholders to replace when users to >> and << */
void reset() const
{
set_i = 1;
get_i = 1;
}
private:
/*! An interface to a row, you can extract values from columns with >> as well as operator[string] as well as get_<type>(string column)
Currently has a reference to the statment (with the ResultSet), so it makes now copy. Changing the statement (eg calling .next()), changes this query_result_row. That's why this class is private (but we have auto now...).
TODO: consider copying the data?
*/
class query_result_row {
public:
query_result_row(statement& s)
: stmt(s)
{}
template <typename T>
const statement& operator>>(T& x) const {
return stmt >> x;
}
std::string get_string(const std::string col) const {
return stmt.get_string(col);
}
uint64_t get_uint64(const std::string col) const {
return stmt.get_uint64(col);
}
bool is_null(const std::string col) const {
return stmt.is_null(col);
}
private:
statement& stmt;
};
/*! An iterator that iterates over rows of a result. Knows when he has hit the last row. */
class query_iterator : public std::iterator<std::input_iterator_tag, query_result_row, std::ptrdiff_t, query_result_row, query_result_row> {
public:
query_iterator()
: stmt(nullptr)
{}
query_iterator(statement& s)
: stmt(&s)
{
//Advance to the first row
operator++();
}
bool operator ==(query_iterator const & rh) {
return stmt == rh.stmt;
}
bool operator !=(query_iterator const& rh) {
return !(stmt == rh.stmt);
}
query_iterator& operator++(){
if(!stmt->next())
stmt = nullptr;
return *this;
}
query_result_row operator*() {
return query_result_row(*stmt);
}
private:
statement* stmt;
};
public:
/* Initializes a statement, with a statement. The object takes ownership of the statement.
\todo Change the ctor to accept a std::string, which we give to sql and intialize ourselves with. This should be a private-ctor or something because we take ownership of the pointer.
*/
statement(sql::PreparedStatement* stmt)
: stmt(stmt)
, data()
, set_i(1)
, get_i(1)
{}
/*! Inserts the given argument in the current placeholder */
const statement& operator<<(const std::string value) const
{
stmt->setString(set_i++, value);
return *this;
}
/*! Inserts the given argument in the current placeholder */
const statement& operator<<(const uint64_t value) const
{
stmt->setUInt64(set_i++, value);
return *this;
}
/*! Extracts the value from the current placeholder */
const statement& operator>>(std::string& value) const
{
value = data->getString(get_i++);
return *this;
}
const statement& operator>>(uint64_t& value) const
{
value = data->getUInt64(get_i++);
return *this;
}
std::string get_string(const std::string col) const
{
return data->getString(col);
}
/*! Fetch the int at the given column
\param col Tells which column to use
\return The value in that row in the given column
*/
uint64_t get_uint64(const std::string col) const
{
return data->getUInt64(col);
}
bool is_null(const std::string col) const
{
return data->isNull(col);
}
/*! Advances the statement-result to the next row
\return Returns whether the statement-result is now on a row.
*/
bool next() const
{
reset();
return data->next();
}
query_iterator begin() {
return query_iterator(*this);
}
query_iterator end() {
return query_iterator();
}
void execute() const
{
auto r = stmt->execute();
// TODO: figure out when execute doesn't return 0.
// TODO: make better error handling.
if(r){
auto ptr = stmt->getWarnings();
if(ptr){
std::cout << "Fail: " << ptr->getMessage() << std::endl;
} else {
std::cout << "Fail without a message..." << std::endl;
}
}
reset();
}
int update() const
{
auto r = stmt->executeUpdate();
reset();
return r;
}
public:
statement& query()
{
data.reset(stmt->executeQuery());
reset();
return *this;
}
};
}
<|endoftext|> |
<commit_before><commit_msg>GTK: fix DCHECK triggered when multiple ExtensionPopupGtks existed concurrently.<commit_after><|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Interactive Visualization and Data Analysis Group.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : OBJGeoConverter.cpp
//! Author : Jens Krueger
//! IVCI & DFKI & MMCI, Saarbruecken
//! SCI Institute, University of Utah
//! Date : July 2010
//
//! Copyright (C) 2010 DFKI, MMCI, SCI Institute
#include "OBJGeoConverter.h"
#include "Controller/Controller.h"
#include "SysTools.h"
#include "Mesh.h"
#include <fstream>
#include "TuvokIOError.h"
using namespace tuvok;
OBJGeoConverter::OBJGeoConverter() :
AbstrGeoConverter()
{
m_vConverterDesc = "Wavefront Object File";
m_vSupportedExt.push_back("OBJ");
m_vSupportedExt.push_back("OBJX");
}
inline int OBJGeoConverter::CountOccurences(const std::string& str, const std::string& substr) {
size_t found = str.find_first_of(substr);
int count = 0;
while (found!=std::string::npos)
{
count++;
found=str.find_first_of(substr,found+1);
}
return count;
}
Mesh* OBJGeoConverter::ConvertToMesh(const std::string& strFilename) {
bool bFlipVertices = false;
VertVec vertices;
NormVec normals;
TexCoordVec texcoords;
ColorVec colors;
IndexVec VertIndices;
IndexVec NormalIndices;
IndexVec TCIndices;
IndexVec COLIndices;
std::ifstream fs;
std::string line;
fs.open(strFilename.c_str());
if (fs.fail()) {
// hack, we really want some kind of 'file not found' exception.
throw tuvok::io::DSOpenFailed(strFilename.c_str(), __FILE__, __LINE__);
}
float x,y,z,w;
size_t iVerticesPerPoly = 0;
while (!fs.fail()) {
getline(fs, line);
if (fs.fail()) break; // no more lines to read
line = SysTools::ToLowerCase(SysTools::TrimStr(line));
// remove comments
size_t cPos = line.find_first_of('#');
if (cPos != std::string::npos) line = line.substr(0,cPos);
line = SysTools::TrimStr(line);
if (line.length() == 0) continue; // skips empty and comment lines
// find the linetype
size_t off = line.find_first_of(" \r\n\t");
if (off == std::string::npos) continue;
std::string linetype = SysTools::TrimStrRight(line.substr(0,off));
line = SysTools::TrimStr(line.substr(linetype.length()));
if (linetype == "o") {
WARNING("Skipping Object Tag in OBJ file");
} else
if (linetype == "mtllib") {
WARNING("Skipping Material Library Tag in OBJ file");
} else
if (linetype == "v") { // vertex attrib found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
z = float(atof(GetToken(line).c_str()));
vertices.push_back(FLOATVECTOR3(x,y,(bFlipVertices) ? -z : z));
} else
if (linetype == "vt") { // vertex texcoord found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
texcoords.push_back(FLOATVECTOR2(x,y));
} else
if (linetype == "vc") { // vertex color found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
z = float(atof(GetToken(line).c_str()));
w = float(atof(GetToken(line).c_str()));
colors.push_back(FLOATVECTOR4(x,y,z,w));
} else
if (linetype == "vn") { // vertex normal found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
z = float(atof(GetToken(line).c_str()));
FLOATVECTOR3 n(x,y,z);
n.normalize();
normals.push_back(n);
} else
if (linetype == "f" || linetype == "l") { // face or line found
size_t off = line.find_first_of(" \r\n\t");
if (off == std::string::npos) continue;
std::string analysis = SysTools::TrimStrRight(line.substr(0,off));
int count = CountOccurences(analysis,"/");
IndexVec v, n, t, c;
while (line.length() > 0) {
switch (count) {
case 0 : {
int vI = atoi(GetToken(line).c_str())-1;
v.push_back(vI);
break;
}
case 1 : {
int vI = atoi(GetToken(line,"/",true).c_str())-1;
v.push_back(vI);
int vT = atoi(GetToken(line).c_str())-1;
t.push_back(vT);
line = TrimToken(line);
break;
}
case 2 : {
int vI = atoi(GetToken(line,"/",true).c_str())-1;
v.push_back(vI);
if (line[0] != '/') {
int vT = atoi(GetToken(line,"/",true).c_str())-1;
t.push_back(vT);
}else line = TrimToken(line,"/",true);
int vN = atoi(GetToken(line).c_str())-1;
n.push_back(vN);
break;
}
case 3 : {
int vI = atoi(GetToken(line,"/",true).c_str())-1;
v.push_back(vI);
if (line[0] != '/') {
int vT = atoi(GetToken(line,"/",true).c_str())-1;
t.push_back(vT);
}else line = TrimToken(line,"/",true);
if (line[0] != '/') {
int vN = atoi(GetToken(line,"/",true).c_str())-1;
n.push_back(vN);
} else line = TrimToken(line,"/",true);
int vC = atoi(GetToken(line).c_str())-1;
c.push_back(vC);
break;
}
}
SysTools::TrimStrLeft(line);
}
if (v.size() == 1) {
WARNING("Skipping points in OBJ file");
continue;
}
if (iVerticesPerPoly == 0) iVerticesPerPoly = v.size();
if (v.size() == 2) {
if ( iVerticesPerPoly != 2 ) {
WARNING("Skipping a line in a file that also contains polygons");
continue;
}
AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
} else {
if ( iVerticesPerPoly == 2 ) {
WARNING("Skipping polygon in file that also contains lines");
continue;
}
AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
}
} else {
WARNING("Skipping unknown tag %s in OBJ file", linetype.c_str());
}
}
fs.close();
std::string desc = m_vConverterDesc + " data converted from " + SysTools::GetFilename(strFilename);
Mesh* m = new Mesh(vertices,normals,texcoords,colors,
VertIndices,NormalIndices,TCIndices,COLIndices,
false, false, desc,
((iVerticesPerPoly == 2)
? Mesh::MT_LINES
: Mesh::MT_TRIANGLES ));
return m;
}
bool OBJGeoConverter::ConvertToNative(const Mesh& m,
const std::string& strTargetFilename) {
bool bUseExtension = SysTools::ToUpperCase(
SysTools::GetExt(strTargetFilename)
) == "OBJX";
std::ofstream outStream(strTargetFilename.c_str());
if (outStream.fail()) return false;
std::stringstream statLine1, statLine2;
statLine1 << "Vertices: " << m.GetVertices().size();
statLine2 << "Primitives: " << m.GetVertexIndices().size()/
m.GetVerticesPerPoly();
size_t iCount = std::max(m.Name().size(),
std::max(statLine1.str().size(),
statLine2.str().size()
));
for (size_t i = 0;i<iCount+4;i++) outStream << "#";
outStream << std::endl;
outStream << "# " << m.Name();
for (size_t i = m.Name().size();i<iCount;i++) outStream << " ";
outStream << " #" << std::endl;
outStream << "# " << statLine1.str();
for (size_t i =statLine1.str().size();i<iCount;i++) outStream << " ";
outStream << " #" << std::endl;
outStream << "# " << statLine2.str();
for (size_t i = statLine2.str().size();i<iCount;i++) outStream << " ";
outStream << " #" << std::endl;
for (size_t i = 0;i<iCount+4;i++) outStream << "#";
outStream << std::endl;
// vertices
for (size_t i = 0;i<m.GetVertices().size();i++) {
outStream << "v "
<< m.GetVertices()[i].x << " "
<< m.GetVertices()[i].y << " "
<< m.GetVertices()[i].z << std::endl;;
}
for (size_t i = 0;i<m.GetNormals().size();i++) {
outStream << "vn "
<< m.GetNormals()[i].x << " "
<< m.GetNormals()[i].y << " "
<< m.GetNormals()[i].z << std::endl;
}
for (size_t i = 0;i<m.GetTexCoords().size();i++) {
outStream << "vt "
<< m.GetTexCoords()[i].x << " "
<< m.GetTexCoords()[i].y << std::endl;
}
if (bUseExtension) {
// this is our own extension, originally colors are
// not supported by OBJ files
for (size_t i = 0;i<m.GetColors().size();i++) {
outStream << "vc "
<< m.GetColors()[i].x << " "
<< m.GetColors()[i].y << " "
<< m.GetColors()[i].z << " "
<< m.GetColors()[i].w << std::endl;
}
} else {
if (!m.GetColors().empty())
WARNING("Ignoring mesh colors for standart OBJ files, "
"use OBJX files to also export colors.");
}
bool bHasTexCoords = m.GetTexCoordIndices().size() == m.GetVertexIndices().size();
bool bHasNormals = m.GetNormalIndices().size() == m.GetVertexIndices().size();
bool bHasColors = (bUseExtension && m.GetColorIndices().size() == m.GetVertexIndices().size());
size_t iVPP = m.GetVerticesPerPoly();
for (size_t i = 0;i<m.GetVertexIndices().size();i+=iVPP) {
if (iVPP == 1)
outStream << "p "; else
if (iVPP == 2)
outStream << "l ";
else
outStream << "f ";
for (size_t j = 0;j<iVPP;j++) {
outStream << m.GetVertexIndices()[i+j]+1;
if (bHasTexCoords || bHasNormals || bHasColors) {
outStream << "/";
if (m.GetTexCoordIndices().size() == m.GetVertexIndices().size()) {
outStream << m.GetTexCoordIndices()[i+j]+1;
}
}
if (bHasNormals || bHasColors) {
outStream << "/";
if (m.GetNormalIndices().size() == m.GetVertexIndices().size()) {
outStream << m.GetNormalIndices()[i+j]+1;
}
}
if (bHasColors) {
outStream << "/";
outStream << m.GetColorIndices()[i+j]+1;
}
if (j+1 < iVPP) outStream << " ";
}
outStream << std::endl;
}
outStream.close();
return true;
}
<commit_msg>added progress info when loading<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Interactive Visualization and Data Analysis Group.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : OBJGeoConverter.cpp
//! Author : Jens Krueger
//! IVCI & DFKI & MMCI, Saarbruecken
//! SCI Institute, University of Utah
//! Date : July 2010
//
//! Copyright (C) 2010 DFKI, MMCI, SCI Institute
#include "OBJGeoConverter.h"
#include "Controller/Controller.h"
#include "SysTools.h"
#include "Mesh.h"
#include <fstream>
#include "TuvokIOError.h"
using namespace tuvok;
OBJGeoConverter::OBJGeoConverter() :
AbstrGeoConverter()
{
m_vConverterDesc = "Wavefront Object File";
m_vSupportedExt.push_back("OBJ");
m_vSupportedExt.push_back("OBJX");
}
inline int OBJGeoConverter::CountOccurences(const std::string& str, const std::string& substr) {
size_t found = str.find_first_of(substr);
int count = 0;
while (found!=std::string::npos)
{
count++;
found=str.find_first_of(substr,found+1);
}
return count;
}
Mesh* OBJGeoConverter::ConvertToMesh(const std::string& strFilename) {
bool bFlipVertices = false;
VertVec vertices;
NormVec normals;
TexCoordVec texcoords;
ColorVec colors;
IndexVec VertIndices;
IndexVec NormalIndices;
IndexVec TCIndices;
IndexVec COLIndices;
std::ifstream fs;
std::string line;
fs.open(strFilename.c_str());
if (fs.fail()) {
// hack, we really want some kind of 'file not found' exception.
throw tuvok::io::DSOpenFailed(strFilename.c_str(), __FILE__, __LINE__);
}
float x,y,z,w;
size_t iVerticesPerPoly = 0;
fs.seekg(0,std::ios::end);
size_t iFileLength = fs.tellg();
fs.seekg(0,std::ios::beg);
size_t iBytesRead = 0;
size_t iLine = 0;
while (!fs.fail()) {
getline(fs, line);
iBytesRead += line.size() + 1;
iLine++;
if (fs.fail()) break; // no more lines to read
line = SysTools::ToLowerCase(SysTools::TrimStr(line));
// remove comments
size_t cPos = line.find_first_of('#');
if (cPos != std::string::npos) line = line.substr(0,cPos);
line = SysTools::TrimStr(line);
if (line.length() == 0) continue; // skips empty and comment lines
// find the linetype
size_t off = line.find_first_of(" \r\n\t");
if (off == std::string::npos) continue;
std::string linetype = SysTools::TrimStrRight(line.substr(0,off));
line = SysTools::TrimStr(line.substr(linetype.length()));
if (linetype == "o") {
WARNING("Skipping Object Tag in OBJ file");
} else
if (linetype == "mtllib") {
WARNING("Skipping Material Library Tag in OBJ file");
} else
if (linetype == "v") { // vertex attrib found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
z = float(atof(GetToken(line).c_str()));
vertices.push_back(FLOATVECTOR3(x,y,(bFlipVertices) ? -z : z));
} else
if (linetype == "vt") { // vertex texcoord found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
texcoords.push_back(FLOATVECTOR2(x,y));
} else
if (linetype == "vc") { // vertex color found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
z = float(atof(GetToken(line).c_str()));
w = float(atof(GetToken(line).c_str()));
colors.push_back(FLOATVECTOR4(x,y,z,w));
} else
if (linetype == "vn") { // vertex normal found
x = float(atof(GetToken(line).c_str()));
y = float(atof(GetToken(line).c_str()));
z = float(atof(GetToken(line).c_str()));
FLOATVECTOR3 n(x,y,z);
n.normalize();
normals.push_back(n);
} else
if (linetype == "f" || linetype == "l") { // face or line found
size_t off = line.find_first_of(" \r\n\t");
if (off == std::string::npos) continue;
std::string analysis = SysTools::TrimStrRight(line.substr(0,off));
int count = CountOccurences(analysis,"/");
IndexVec v, n, t, c;
while (line.length() > 0) {
switch (count) {
case 0 : {
int vI = atoi(GetToken(line).c_str())-1;
v.push_back(vI);
break;
}
case 1 : {
int vI = atoi(GetToken(line,"/",true).c_str())-1;
v.push_back(vI);
int vT = atoi(GetToken(line).c_str())-1;
t.push_back(vT);
line = TrimToken(line);
break;
}
case 2 : {
int vI = atoi(GetToken(line,"/",true).c_str())-1;
v.push_back(vI);
if (line[0] != '/') {
int vT = atoi(GetToken(line,"/",true).c_str())-1;
t.push_back(vT);
}else line = TrimToken(line,"/",true);
int vN = atoi(GetToken(line).c_str())-1;
n.push_back(vN);
break;
}
case 3 : {
int vI = atoi(GetToken(line,"/",true).c_str())-1;
v.push_back(vI);
if (line[0] != '/') {
int vT = atoi(GetToken(line,"/",true).c_str())-1;
t.push_back(vT);
}else line = TrimToken(line,"/",true);
if (line[0] != '/') {
int vN = atoi(GetToken(line,"/",true).c_str())-1;
n.push_back(vN);
} else line = TrimToken(line,"/",true);
int vC = atoi(GetToken(line).c_str())-1;
c.push_back(vC);
break;
}
}
SysTools::TrimStrLeft(line);
}
if (v.size() == 1) {
WARNING("Skipping points in OBJ file");
continue;
}
if (iVerticesPerPoly == 0) iVerticesPerPoly = v.size();
if (v.size() == 2) {
if ( iVerticesPerPoly != 2 ) {
WARNING("Skipping a line in a file that also contains polygons");
continue;
}
AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
} else {
if ( iVerticesPerPoly == 2 ) {
WARNING("Skipping polygon in file that also contains lines");
continue;
}
AddToMesh(vertices,v,n,t,c,VertIndices,NormalIndices,TCIndices,COLIndices);
}
} else {
WARNING("Skipping unknown tag %s in OBJ file", linetype.c_str());
}
if (iLine % 5000 == 0) {
MESSAGE("Reading line %u (%u / %u kb)", unsigned(iLine),
unsigned(iBytesRead/1024),unsigned(iFileLength/1024));
}
}
fs.close();
std::string desc = m_vConverterDesc + " data converted from " + SysTools::GetFilename(strFilename);
Mesh* m = new Mesh(vertices,normals,texcoords,colors,
VertIndices,NormalIndices,TCIndices,COLIndices,
false, false, desc,
((iVerticesPerPoly == 2)
? Mesh::MT_LINES
: Mesh::MT_TRIANGLES ));
return m;
}
bool OBJGeoConverter::ConvertToNative(const Mesh& m,
const std::string& strTargetFilename) {
bool bUseExtension = SysTools::ToUpperCase(
SysTools::GetExt(strTargetFilename)
) == "OBJX";
std::ofstream outStream(strTargetFilename.c_str());
if (outStream.fail()) return false;
std::stringstream statLine1, statLine2;
statLine1 << "Vertices: " << m.GetVertices().size();
statLine2 << "Primitives: " << m.GetVertexIndices().size()/
m.GetVerticesPerPoly();
size_t iCount = std::max(m.Name().size(),
std::max(statLine1.str().size(),
statLine2.str().size()
));
for (size_t i = 0;i<iCount+4;i++) outStream << "#";
outStream << std::endl;
outStream << "# " << m.Name();
for (size_t i = m.Name().size();i<iCount;i++) outStream << " ";
outStream << " #" << std::endl;
outStream << "# " << statLine1.str();
for (size_t i =statLine1.str().size();i<iCount;i++) outStream << " ";
outStream << " #" << std::endl;
outStream << "# " << statLine2.str();
for (size_t i = statLine2.str().size();i<iCount;i++) outStream << " ";
outStream << " #" << std::endl;
for (size_t i = 0;i<iCount+4;i++) outStream << "#";
outStream << std::endl;
// vertices
for (size_t i = 0;i<m.GetVertices().size();i++) {
outStream << "v "
<< m.GetVertices()[i].x << " "
<< m.GetVertices()[i].y << " "
<< m.GetVertices()[i].z << std::endl;;
}
for (size_t i = 0;i<m.GetNormals().size();i++) {
outStream << "vn "
<< m.GetNormals()[i].x << " "
<< m.GetNormals()[i].y << " "
<< m.GetNormals()[i].z << std::endl;
}
for (size_t i = 0;i<m.GetTexCoords().size();i++) {
outStream << "vt "
<< m.GetTexCoords()[i].x << " "
<< m.GetTexCoords()[i].y << std::endl;
}
if (bUseExtension) {
// this is our own extension, originally colors are
// not supported by OBJ files
for (size_t i = 0;i<m.GetColors().size();i++) {
outStream << "vc "
<< m.GetColors()[i].x << " "
<< m.GetColors()[i].y << " "
<< m.GetColors()[i].z << " "
<< m.GetColors()[i].w << std::endl;
}
} else {
if (!m.GetColors().empty())
WARNING("Ignoring mesh colors for standart OBJ files, "
"use OBJX files to also export colors.");
}
bool bHasTexCoords = m.GetTexCoordIndices().size() == m.GetVertexIndices().size();
bool bHasNormals = m.GetNormalIndices().size() == m.GetVertexIndices().size();
bool bHasColors = (bUseExtension && m.GetColorIndices().size() == m.GetVertexIndices().size());
size_t iVPP = m.GetVerticesPerPoly();
for (size_t i = 0;i<m.GetVertexIndices().size();i+=iVPP) {
if (iVPP == 1)
outStream << "p "; else
if (iVPP == 2)
outStream << "l ";
else
outStream << "f ";
for (size_t j = 0;j<iVPP;j++) {
outStream << m.GetVertexIndices()[i+j]+1;
if (bHasTexCoords || bHasNormals || bHasColors) {
outStream << "/";
if (m.GetTexCoordIndices().size() == m.GetVertexIndices().size()) {
outStream << m.GetTexCoordIndices()[i+j]+1;
}
}
if (bHasNormals || bHasColors) {
outStream << "/";
if (m.GetNormalIndices().size() == m.GetVertexIndices().size()) {
outStream << m.GetNormalIndices()[i+j]+1;
}
}
if (bHasColors) {
outStream << "/";
outStream << m.GetColorIndices()[i+j]+1;
}
if (j+1 < iVPP) outStream << " ";
}
outStream << std::endl;
}
outStream.close();
return true;
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "OSVRUpdateCallback.h"
#include "OSGMathInterop.h"
#include "OSVRInterfaceData.h"
#include "OSVRContext.h"
// Library/third-party includes
#include <osvr/ClientKit/ClientKit.h>
#include <osg/ref_ptr>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/NodeCallback>
#include <osg/LineWidth>
#include <osg/Version>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
// Standard includes
#include <iostream>
#include <cmath> // for floor
/// @brief A struct that does our casting for us.
struct CallbackHelper {
CallbackHelper(void *userdata)
: xform(static_cast<osg::MatrixTransform *>(userdata)),
iface(dynamic_cast<OSVRInterfaceData *>(xform->getUserData())) {}
osg::MatrixTransform *xform;
OSVRInterfaceData *iface;
};
void poseCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
const OSVR_PoseReport *report) {
CallbackHelper cb(userdata);
cb.xform->setMatrix(toMatrix(report->pose));
// std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}
void orientationCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
const OSVR_OrientationReport *report) {
CallbackHelper cb(userdata);
osg::Matrix mat = cb.xform->getMatrix();
mat.setRotate(toQuat(report->rotation));
cb.xform->setMatrix(mat);
// std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}
/// A little utility class to draw a simple grid.
class Grid : public osg::Group {
public:
Grid(unsigned int line_count = 49, float line_spacing = 1.0f,
unsigned int bold_every_n = 0) {
this->addChild(make_grid(line_count, line_spacing));
#if 0
std::cout << "Regular: count = " << line_count
<< ", spacing = " << line_spacing << std::endl;
#endif
// Bold grid
if (bold_every_n > 0) {
line_count = static_cast<unsigned int>(
std::floor(line_count / bold_every_n)) +
1;
line_spacing *= bold_every_n;
#if 0
std::cout << "Bold: count = " << line_count
<< ", spacing = " << line_spacing << std::endl;
#endif
osg::MatrixTransform *mt = make_grid(line_count, line_spacing);
osg::StateSet *stateset = new osg::StateSet();
osg::LineWidth *linewidth = new osg::LineWidth();
linewidth->setWidth(2.0f);
stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
mt->setStateSet(stateset);
this->addChild(mt);
}
// Heavy origin lines
this->addChild(make_axes(line_count, line_spacing));
}
osg::MatrixTransform *make_grid(const unsigned int line_count,
const float line_spacing) {
const unsigned int numVertices = 2 * 2 * line_count;
osg::Vec3Array *vertices = new osg::Vec3Array(numVertices);
float length = static_cast<float>(line_count - 1) * line_spacing;
osg::Vec3Array::size_type ptr = 0;
for (unsigned int i = 0; i < line_count; ++i) {
(*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
length / 2.0f, 0.0f);
(*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
-length / 2.0f, 0.0f);
}
for (unsigned int i = 0; i < line_count; ++i) {
(*vertices)[ptr++].set(length / 2.0f,
-length / 2.0f + i * line_spacing, 0.0f);
(*vertices)[ptr++].set(-length / 2.0f,
-length / 2.0f + i * line_spacing, 0.0f);
}
osg::Geometry *geometry = new osg::Geometry;
geometry->setVertexArray(vertices);
geometry->addPrimitiveSet(new osg::DrawArrays(
osg::PrimitiveSet::LINES, 0, static_cast<GLsizei>(numVertices)));
osg::Geode *geode = new osg::Geode;
geode->addDrawable(geometry);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);
osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
grid_transform->addChild(geode);
return grid_transform;
}
osg::MatrixTransform *make_axes(const unsigned int line_count,
const float line_spacing) {
const float length = (line_count - 1) * line_spacing;
const int num_vertices = 6;
osg::Vec3Array *vertices = new osg::Vec3Array(num_vertices);
(*vertices)[0].set(-length / 2.0f, 0.0f, 0.0f);
(*vertices)[1].set(length / 2.0f, 0.0f, 0.0f);
(*vertices)[2].set(0.0f, -length / 2.0f, 0.0f);
(*vertices)[3].set(0.0f, length / 2.0f, 0.0f);
(*vertices)[4].set(0.0f, 0.0f, -length / 2.0f);
(*vertices)[5].set(0.0f, 0.0f, length / 2.0f);
osg::Vec4Array *colors = new osg::Vec4Array(num_vertices);
(*colors)[0].set(1.0, 0.0, 0.0, 1.0);
(*colors)[1].set(1.0, 0.0, 0.0, 1.0);
(*colors)[2].set(0.0, 0.0, 1.0, 1.0);
(*colors)[3].set(0.0, 0.0, 1.0, 1.0);
(*colors)[4].set(0.0, 1.0, 0.0, 1.0);
(*colors)[5].set(0.0, 1.0, 0.0, 1.0);
osg::Geometry *geometry = new osg::Geometry;
geometry->setVertexArray(vertices);
geometry->addPrimitiveSet(
new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, num_vertices));
#if OSG_VERSION_GREATER_THAN(3, 1, 7)
geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
#else
geometry->setColorArray(colors);
geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
#endif
osg::Geode *geode = new osg::Geode;
geode->addDrawable(geometry);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);
osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
grid_transform->addChild(geode);
osg::StateSet *stateset = new osg::StateSet();
osg::LineWidth *linewidth = new osg::LineWidth();
linewidth->setWidth(4.0f);
stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
grid_transform->setStateSet(stateset);
return grid_transform;
}
};
static const char MODEL_FN[] = "RPAxes.osg";
class TrackerViewApp {
public:
static double worldAxesScale() { return 0.2; }
static double trackerAxesScale() { return 0.1; }
TrackerViewApp()
: m_ctx(new OSVRContext(
"org.osvr.trackerview")) /// Set up OSVR: making an OSG
/// ref-counted object hold
/// the context.
,
m_scene(new osg::PositionAttitudeTransform),
m_smallAxes(new osg::MatrixTransform), m_numTrackers(0) {
/// Transform into default OSVR coordinate system: z near.
m_scene->setAttitude(osg::Quat(90, osg::Vec3(1, 0, 0)));
/// Set the root node's update callback to run the OSVR update,
/// and give it the context ref
m_scene->setUpdateCallback(new OSVRUpdateCallback);
m_scene->setUserData(m_ctx.get());
/// Load the basic model for axes
osg::ref_ptr<osg::Node> axes = osgDB::readNodeFile(MODEL_FN);
if (!axes) {
std::cerr << "Error: Could not read model " << MODEL_FN
<< std::endl;
throw std::runtime_error("Could not load model");
}
/// Small axes for trackers
m_smallAxes->setMatrix(osg::Matrixd::scale(
trackerAxesScale(), trackerAxesScale(), trackerAxesScale()));
m_smallAxes->addChild(axes.get());
/// Grid
m_scene->addChild(new Grid(16, 0.1f, 5));
}
osg::ref_ptr<osg::PositionAttitudeTransform> getScene() { return m_scene; }
void addPoseTracker(std::string const &path) {
m_addTracker(&poseCallback, path);
m_numTrackers++;
}
void addOrientationTracker(std::string const &path) {
osg::ref_ptr<osg::MatrixTransform> node =
m_addTracker(&orientationCallback, path);
/*
/// Offset orientation-only trackers up by 1 unit (meter)
osg::Matrix mat;
mat.setTrans(0, 1, 0);
node->setMatrix(mat);
*/
m_numTrackers++;
}
int getNumTrackers() const { return m_numTrackers; }
private:
template <typename CallbackType>
osg::ref_ptr<osg::MatrixTransform> m_addTracker(CallbackType cb,
std::string const &path) {
/// Make scenegraph portion
osg::ref_ptr<osg::MatrixTransform> node = new osg::MatrixTransform;
node->addChild(m_smallAxes);
m_scene->addChild(node);
/// Get OSVR interface and set callback
osg::ref_ptr<OSVRInterfaceData> data = m_ctx->getInterface(path);
data->getInterface().registerCallback(cb,
static_cast<void *>(node.get()));
/// Transfer ownership of the interface holder to the node
node->setUserData(data.get());
return node;
}
osg::ref_ptr<OSVRContext> m_ctx;
osg::ref_ptr<osg::PositionAttitudeTransform> m_scene;
osg::ref_ptr<osg::MatrixTransform> m_smallAxes;
int m_numTrackers;
};
int main(int argc, char **argv) {
/// Parse arguments
osg::ArgumentParser args(&argc, argv);
args.getApplicationUsage()->setApplicationName(args.getApplicationName());
args.getApplicationUsage()->setDescription(
args.getApplicationName() +
" is a tool for visualizing tracking data from the OSVR system.");
args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName() +
" [options] osvrpath ...");
args.getApplicationUsage()->addCommandLineOption(
"--orientation <path>", "add an orientation tracker");
args.getApplicationUsage()->addCommandLineOption("--pose <path>",
"add a pose tracker");
/// Init the OSG viewer
osgViewer::Viewer viewer(args);
viewer.setUpViewInWindow(20, 20, 640, 480);
osg::ApplicationUsage::Type helpType;
if ((helpType = args.readHelpType()) != osg::ApplicationUsage::NO_HELP) {
args.getApplicationUsage()->write(std::cerr);
return 1;
}
if (args.errors()) {
args.writeErrorMessages(std::cerr);
return 1;
}
try {
TrackerViewApp app;
std::string path;
// Get pose paths
while (args.read("--pose", path)) {
app.addPoseTracker(path);
}
// Get orientation paths
while (args.read("--orientation", path)) {
app.addOrientationTracker(path);
}
// Assume free strings are pose paths
for (int pos = 1; pos < args.argc(); ++pos) {
if (args.isOption(pos))
continue;
app.addPoseTracker(args[pos]);
}
// If no trackers were specified, fall back on these defaults
if (0 == app.getNumTrackers()) {
std::cout << "\n\nTracker Viewer: No valid arguments passed: using "
"a default of --pose "
"/me/hands/left --pose /me/hands/right --pose "
"/me/head\nYou can specify --pose or --orientation "
"then a path for as many tracker sensors as you want. "
"Run with the command line argument --help "
"for more info.\n"
<< std::endl;
app.addPoseTracker("/me/hands/left");
app.addPoseTracker("/me/hands/right");
app.addPoseTracker("/me/head");
}
args.reportRemainingOptionsAsUnrecognized();
if (args.errors()) {
args.writeErrorMessages(std::cerr);
return 1;
}
viewer.setSceneData(app.getScene());
} catch (std::exception const &e) {
std::cerr << "Exception: " << e.what() << std::endl;
std::cerr << "Press enter to exit!" << std::endl;
std::cin.ignore();
return -1;
}
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.addEventHandler(new osgViewer::WindowSizeHandler);
/// Go!
viewer.realize();
return viewer.run();
}
<commit_msg>if we're leaving commented-out code, we do it with #if 0<commit_after>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "OSVRUpdateCallback.h"
#include "OSGMathInterop.h"
#include "OSVRInterfaceData.h"
#include "OSVRContext.h"
// Library/third-party includes
#include <osvr/ClientKit/ClientKit.h>
#include <osg/ref_ptr>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/NodeCallback>
#include <osg/LineWidth>
#include <osg/Version>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
// Standard includes
#include <iostream>
#include <cmath> // for floor
/// @brief A struct that does our casting for us.
struct CallbackHelper {
CallbackHelper(void *userdata)
: xform(static_cast<osg::MatrixTransform *>(userdata)),
iface(dynamic_cast<OSVRInterfaceData *>(xform->getUserData())) {}
osg::MatrixTransform *xform;
OSVRInterfaceData *iface;
};
void poseCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
const OSVR_PoseReport *report) {
CallbackHelper cb(userdata);
cb.xform->setMatrix(toMatrix(report->pose));
// std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}
void orientationCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
const OSVR_OrientationReport *report) {
CallbackHelper cb(userdata);
osg::Matrix mat = cb.xform->getMatrix();
mat.setRotate(toQuat(report->rotation));
cb.xform->setMatrix(mat);
// std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}
/// A little utility class to draw a simple grid.
class Grid : public osg::Group {
public:
Grid(unsigned int line_count = 49, float line_spacing = 1.0f,
unsigned int bold_every_n = 0) {
this->addChild(make_grid(line_count, line_spacing));
#if 0
std::cout << "Regular: count = " << line_count
<< ", spacing = " << line_spacing << std::endl;
#endif
// Bold grid
if (bold_every_n > 0) {
line_count = static_cast<unsigned int>(
std::floor(line_count / bold_every_n)) +
1;
line_spacing *= bold_every_n;
#if 0
std::cout << "Bold: count = " << line_count
<< ", spacing = " << line_spacing << std::endl;
#endif
osg::MatrixTransform *mt = make_grid(line_count, line_spacing);
osg::StateSet *stateset = new osg::StateSet();
osg::LineWidth *linewidth = new osg::LineWidth();
linewidth->setWidth(2.0f);
stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
mt->setStateSet(stateset);
this->addChild(mt);
}
// Heavy origin lines
this->addChild(make_axes(line_count, line_spacing));
}
osg::MatrixTransform *make_grid(const unsigned int line_count,
const float line_spacing) {
const unsigned int numVertices = 2 * 2 * line_count;
osg::Vec3Array *vertices = new osg::Vec3Array(numVertices);
float length = static_cast<float>(line_count - 1) * line_spacing;
osg::Vec3Array::size_type ptr = 0;
for (unsigned int i = 0; i < line_count; ++i) {
(*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
length / 2.0f, 0.0f);
(*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
-length / 2.0f, 0.0f);
}
for (unsigned int i = 0; i < line_count; ++i) {
(*vertices)[ptr++].set(length / 2.0f,
-length / 2.0f + i * line_spacing, 0.0f);
(*vertices)[ptr++].set(-length / 2.0f,
-length / 2.0f + i * line_spacing, 0.0f);
}
osg::Geometry *geometry = new osg::Geometry;
geometry->setVertexArray(vertices);
geometry->addPrimitiveSet(new osg::DrawArrays(
osg::PrimitiveSet::LINES, 0, static_cast<GLsizei>(numVertices)));
osg::Geode *geode = new osg::Geode;
geode->addDrawable(geometry);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);
osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
grid_transform->addChild(geode);
return grid_transform;
}
osg::MatrixTransform *make_axes(const unsigned int line_count,
const float line_spacing) {
const float length = (line_count - 1) * line_spacing;
const int num_vertices = 6;
osg::Vec3Array *vertices = new osg::Vec3Array(num_vertices);
(*vertices)[0].set(-length / 2.0f, 0.0f, 0.0f);
(*vertices)[1].set(length / 2.0f, 0.0f, 0.0f);
(*vertices)[2].set(0.0f, -length / 2.0f, 0.0f);
(*vertices)[3].set(0.0f, length / 2.0f, 0.0f);
(*vertices)[4].set(0.0f, 0.0f, -length / 2.0f);
(*vertices)[5].set(0.0f, 0.0f, length / 2.0f);
osg::Vec4Array *colors = new osg::Vec4Array(num_vertices);
(*colors)[0].set(1.0, 0.0, 0.0, 1.0);
(*colors)[1].set(1.0, 0.0, 0.0, 1.0);
(*colors)[2].set(0.0, 0.0, 1.0, 1.0);
(*colors)[3].set(0.0, 0.0, 1.0, 1.0);
(*colors)[4].set(0.0, 1.0, 0.0, 1.0);
(*colors)[5].set(0.0, 1.0, 0.0, 1.0);
osg::Geometry *geometry = new osg::Geometry;
geometry->setVertexArray(vertices);
geometry->addPrimitiveSet(
new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, num_vertices));
#if OSG_VERSION_GREATER_THAN(3, 1, 7)
geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
#else
geometry->setColorArray(colors);
geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
#endif
osg::Geode *geode = new osg::Geode;
geode->addDrawable(geometry);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);
osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
grid_transform->addChild(geode);
osg::StateSet *stateset = new osg::StateSet();
osg::LineWidth *linewidth = new osg::LineWidth();
linewidth->setWidth(4.0f);
stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
grid_transform->setStateSet(stateset);
return grid_transform;
}
};
static const char MODEL_FN[] = "RPAxes.osg";
class TrackerViewApp {
public:
static double worldAxesScale() { return 0.2; }
static double trackerAxesScale() { return 0.1; }
TrackerViewApp()
: m_ctx(new OSVRContext(
"org.osvr.trackerview")) /// Set up OSVR: making an OSG
/// ref-counted object hold
/// the context.
,
m_scene(new osg::PositionAttitudeTransform),
m_smallAxes(new osg::MatrixTransform), m_numTrackers(0) {
/// Transform into default OSVR coordinate system: z near.
m_scene->setAttitude(osg::Quat(90, osg::Vec3(1, 0, 0)));
/// Set the root node's update callback to run the OSVR update,
/// and give it the context ref
m_scene->setUpdateCallback(new OSVRUpdateCallback);
m_scene->setUserData(m_ctx.get());
/// Load the basic model for axes
osg::ref_ptr<osg::Node> axes = osgDB::readNodeFile(MODEL_FN);
if (!axes) {
std::cerr << "Error: Could not read model " << MODEL_FN
<< std::endl;
throw std::runtime_error("Could not load model");
}
/// Small axes for trackers
m_smallAxes->setMatrix(osg::Matrixd::scale(
trackerAxesScale(), trackerAxesScale(), trackerAxesScale()));
m_smallAxes->addChild(axes.get());
/// Grid
m_scene->addChild(new Grid(16, 0.1f, 5));
}
osg::ref_ptr<osg::PositionAttitudeTransform> getScene() { return m_scene; }
void addPoseTracker(std::string const &path) {
m_addTracker(&poseCallback, path);
m_numTrackers++;
}
void addOrientationTracker(std::string const &path) {
osg::ref_ptr<osg::MatrixTransform> node =
m_addTracker(&orientationCallback, path);
#if 0
/// Offset orientation-only trackers up by 1 unit (meter)
osg::Matrix mat;
mat.setTrans(0, 1, 0);
node->setMatrix(mat);
#endif
m_numTrackers++;
}
int getNumTrackers() const { return m_numTrackers; }
private:
template <typename CallbackType>
osg::ref_ptr<osg::MatrixTransform> m_addTracker(CallbackType cb,
std::string const &path) {
/// Make scenegraph portion
osg::ref_ptr<osg::MatrixTransform> node = new osg::MatrixTransform;
node->addChild(m_smallAxes);
m_scene->addChild(node);
/// Get OSVR interface and set callback
osg::ref_ptr<OSVRInterfaceData> data = m_ctx->getInterface(path);
data->getInterface().registerCallback(cb,
static_cast<void *>(node.get()));
/// Transfer ownership of the interface holder to the node
node->setUserData(data.get());
return node;
}
osg::ref_ptr<OSVRContext> m_ctx;
osg::ref_ptr<osg::PositionAttitudeTransform> m_scene;
osg::ref_ptr<osg::MatrixTransform> m_smallAxes;
int m_numTrackers;
};
int main(int argc, char **argv) {
/// Parse arguments
osg::ArgumentParser args(&argc, argv);
args.getApplicationUsage()->setApplicationName(args.getApplicationName());
args.getApplicationUsage()->setDescription(
args.getApplicationName() +
" is a tool for visualizing tracking data from the OSVR system.");
args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName() +
" [options] osvrpath ...");
args.getApplicationUsage()->addCommandLineOption(
"--orientation <path>", "add an orientation tracker");
args.getApplicationUsage()->addCommandLineOption("--pose <path>",
"add a pose tracker");
/// Init the OSG viewer
osgViewer::Viewer viewer(args);
viewer.setUpViewInWindow(20, 20, 640, 480);
osg::ApplicationUsage::Type helpType;
if ((helpType = args.readHelpType()) != osg::ApplicationUsage::NO_HELP) {
args.getApplicationUsage()->write(std::cerr);
return 1;
}
if (args.errors()) {
args.writeErrorMessages(std::cerr);
return 1;
}
try {
TrackerViewApp app;
std::string path;
// Get pose paths
while (args.read("--pose", path)) {
app.addPoseTracker(path);
}
// Get orientation paths
while (args.read("--orientation", path)) {
app.addOrientationTracker(path);
}
// Assume free strings are pose paths
for (int pos = 1; pos < args.argc(); ++pos) {
if (args.isOption(pos))
continue;
app.addPoseTracker(args[pos]);
}
// If no trackers were specified, fall back on these defaults
if (0 == app.getNumTrackers()) {
std::cout << "\n\nTracker Viewer: No valid arguments passed: using "
"a default of --pose "
"/me/hands/left --pose /me/hands/right --pose "
"/me/head\nYou can specify --pose or --orientation "
"then a path for as many tracker sensors as you want. "
"Run with the command line argument --help "
"for more info.\n"
<< std::endl;
app.addPoseTracker("/me/hands/left");
app.addPoseTracker("/me/hands/right");
app.addPoseTracker("/me/head");
}
args.reportRemainingOptionsAsUnrecognized();
if (args.errors()) {
args.writeErrorMessages(std::cerr);
return 1;
}
viewer.setSceneData(app.getScene());
} catch (std::exception const &e) {
std::cerr << "Exception: " << e.what() << std::endl;
std::cerr << "Press enter to exit!" << std::endl;
std::cin.ignore();
return -1;
}
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.addEventHandler(new osgViewer::WindowSizeHandler);
/// Go!
viewer.realize();
return viewer.run();
}
<|endoftext|> |
<commit_before>#include "draw.h"
void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue);
void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue);
void drawOnPixelBuffer();
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue);
template<class T>
void print(T input)
{
std::cout << input << std::endl;
}
template<class Vec>
class Vector2D
{
Vec x_, y_;
};
//template<class element>
//class GeometricObject
//{
//public:
// element o_x, o_y, o_r, o_w; //coordinates, radious, line width of an object
//};
//
//class Box : GeometricObject<class element>
//{
//public:
// Box() {};
//
// void draw()
// {
// //instant GeometricObject info.
// o_x = 100;
// o_y = 100;
// o_r = 40;
// o_w = 3;
//
// drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x - (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
// drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y - (o_r / 2)), 1.0f, 0.0f, 0.0f);
// drawLine((o_x - (o_r / 2)), (o_y + (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
// drawLine((o_x + (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
// }
//
//};
//
//class Circle :GeometricObject<class element>
//{
//public:
// Circle() {};
//
// void draw()
// {
// //instant GeometricObject info.
// o_x = 300;
// o_y = 300;
// o_r = 40;
// o_w = 5;
//
// drawCircle(o_x, o_y, o_r, o_w, 0.0f, 0.0f, 1.0f);
// }
//};
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(width, height, "Week6 Templates", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glClearColor(1, 1, 1, 1); // while background
//Question 1 Part
print(1);
print(2.345f);
print("Hello World");
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
drawOnPixelBuffer();
glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
delete[] pixels; // or you may reuse pixels array
return 0;
}
void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue)
{
pixels[(i + width* j) * 3 + 0] = red;
pixels[(i + width* j) * 3 + 1] = green;
pixels[(i + width* j) * 3 + 2] = blue;
}
void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue)
{
if (i1 == i0) {
for (int j = j0; j < j1; j++)
drawPixel(i0, j, red, green, blue);
return;
}
for (int i = i0; i <= i1; i++) {
const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0;
drawPixel(i, j, red, green, blue);
}
}
void drawOnPixelBuffer()
{
//std::memset(pixels, 1.0f, sizeof(float)*width*height * 3); // doesn't work
std::fill_n(pixels, width*height * 3, 1.0f); // white background
// //Question 3 Part
//std::vector<GeometricObject<element>*> obj_list;
//obj_list.push_back(new GeometricObject<Circle>);
//obj_list.push_back(new GeometricObject<Box>);
//for (auto itr : obj_list)
// itr->draw();
}
//w is the width of the circle'outer shell
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue)
{
for (int a = 0; a < width; a++)
{
for (int b = 0; b < height; b++)
{
if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) <= r)
{
if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) >= r - w)
drawPixel(a, b, red, green, blue);
}
}
}
}
//void drawSquare()
//{
//
//
// //draw inner Square
// drawLine((x - (r / 2)), (y - (r / 2)), (x - (r / 2)), (y + (r / 2)), 1.0f, 0.0f, 0.0f);
// drawLine((x - (r / 2)), (y - (r / 2)), (x + (r / 2)), (y - (r / 2)), 1.0f, 0.0f, 0.0f);
// drawLine((x - (r / 2)), (y + (r / 2)), (x + (r / 2)), (y + (r / 2)), 1.0f, 0.0f, 0.0f);
// drawLine((x + (r / 2)), (y - (r / 2)), (x + (r / 2)), (y + (r / 2)), 1.0f, 0.0f, 0.0f);
//
//}
//
<commit_msg>Update main.cpp<commit_after>#include "draw.h"
void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue);
void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue);
void drawOnPixelBuffer();
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue);
template<class T>
void print(T input)
{
std::cout << input << std::endl;
}
template<class Vec>
class Vector2D
{
Vec x_, y_;
};
class GeometricObjectInterface
{
public:
virtual void draw() {}
};
template<class Shape>
class GeometricObject : public GeometricObjectInterface
{
public:
void draw()
{
Shape object;
object.draw();
}
};
class Box
{
private:
int o_x, o_y, o_r, o_w;
public:
void setElements(int x, int y, int r, int w)
{
o_x = x;
o_y = y;
o_r = r;
o_w = w;
}
void draw()
{
setElements(100, 100, 30, 3);
drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x - (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
drawLine((o_x - (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y - (o_r / 2)), 1.0f, 0.0f, 0.0f);
drawLine((o_x - (o_r / 2)), (o_y + (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
drawLine((o_x + (o_r / 2)), (o_y - (o_r / 2)), (o_x + (o_r / 2)), (o_y + (o_r / 2)), 1.0f, 0.0f, 0.0f);
}
};
class Circle
{
private:
int o_x, o_y, o_r, o_w;
public:
void setElements(int x, int y, int r, int w)
{
o_x = x;
o_y = y;
o_r = r;
o_w = w;
}
void draw()
{
setElements(300, 300, 30, 5);
drawCircle(o_x, o_y, o_r, o_w, 0.0f, 0.0f, 1.0f);
}
};
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(width, height, "Week6 Templates", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glClearColor(1, 1, 1, 1); // while background
//Question 1 Part
print(1);
print(2.345f);
print("Hello World");
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
drawOnPixelBuffer();
glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
delete[] pixels; // or you may reuse pixels array
return 0;
}
void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue)
{
pixels[(i + width* j) * 3 + 0] = red;
pixels[(i + width* j) * 3 + 1] = green;
pixels[(i + width* j) * 3 + 2] = blue;
}
void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue)
{
if (i1 == i0) {
for (int j = j0; j < j1; j++)
drawPixel(i0, j, red, green, blue);
return;
}
for (int i = i0; i <= i1; i++) {
const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0;
drawPixel(i, j, red, green, blue);
}
}
void drawOnPixelBuffer()
{
//std::memset(pixels, 1.0f, sizeof(float)*width*height * 3); // doesn't work
std::fill_n(pixels, width*height * 3, 1.0f); // white background
//Question 3 Part
std::vector<GeometricObjectInterface*> obj_list;
obj_list.push_back(new GeometricObject<Circle>);
obj_list.push_back(new GeometricObject<Box>);
for (auto itr : obj_list)
itr->draw();
}
//w is the width of the circle'outer shell
void drawCircle(const int x, const int y, const int r, const int w, const float red, const float green, const float blue)
{
for (int a = 0; a < width; a++)
{
for (int b = 0; b < height; b++)
{
if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) <= r)
{
if (sqrt((x - a)*(x - a) + (y - b)*(y - b)) >= r - w)
drawPixel(a, b, red, green, blue);
}
}
}
}
<|endoftext|> |
<commit_before>//
// Speaker.hpp
// Clock Signal
//
// Created by Thomas Harte on 12/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#ifndef Speaker_hpp
#define Speaker_hpp
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include "../SignalProcessing/Stepper.hpp"
#include "../SignalProcessing/FIRFilter.hpp"
namespace Outputs {
class Speaker {
public:
class Delegate {
public:
virtual void speaker_did_complete_samples(Speaker *speaker, const int16_t *buffer, int buffer_size) = 0;
};
void set_output_rate(int cycles_per_second, int buffer_size)
{
_output_cycles_per_second = cycles_per_second;
if(_buffer_size != buffer_size)
{
_buffer_in_progress = std::unique_ptr<int16_t>(new int16_t[buffer_size]);
_buffer_size = buffer_size;
}
set_needs_updated_filter_coefficients();
}
// void set_output_quality(int number_of_taps)
// {
// _number_of_taps = number_of_taps;
// set_needs_updated_filter_coefficients();
// }
void set_delegate(Delegate *delegate)
{
_delegate = delegate;
}
void set_input_rate(int cycles_per_second)
{
_input_cycles_per_second = cycles_per_second;
set_needs_updated_filter_coefficients();
}
Speaker() : _buffer_in_progress_pointer(0) {}
protected:
std::unique_ptr<int16_t> _buffer_in_progress;
int _buffer_size;
int _buffer_in_progress_pointer;
int _number_of_taps;
bool _coefficients_are_dirty;
Delegate *_delegate;
int _input_cycles_per_second, _output_cycles_per_second;
void set_needs_updated_filter_coefficients()
{
_coefficients_are_dirty = true;
}
};
template <class T> class Filter: public Speaker {
public:
void run_for_cycles(unsigned int input_cycles)
{
if(_coefficients_are_dirty) update_filter_coefficients();
// TODO: what if output rate is greater than input rate?
// fill up as much of the input buffer as possible
while(input_cycles)
{
unsigned int cycles_to_read = (unsigned int)std::min((int)input_cycles, _number_of_taps - _input_buffer_depth);
static_cast<T *>(this)->get_samples(cycles_to_read, &_input_buffer.get()[_input_buffer_depth]);
input_cycles -= cycles_to_read;
_input_buffer_depth += cycles_to_read;
if(_input_buffer_depth == _number_of_taps)
{
_buffer_in_progress.get()[_buffer_in_progress_pointer] = _filter->apply(_input_buffer.get());
_buffer_in_progress_pointer++;
// announce to delegate if full
if(_buffer_in_progress_pointer == _buffer_size)
{
_buffer_in_progress_pointer = 0;
if(_delegate)
{
_delegate->speaker_did_complete_samples(this, _buffer_in_progress.get(), _buffer_size);
}
}
// If the next loop around is going to reuse some of the samples just collected, use a memmove to
// preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip
// anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse.
uint64_t steps = _stepper->step();
if(steps < _number_of_taps)
{
int16_t *input_buffer = _input_buffer.get();
memmove(input_buffer, &input_buffer[steps], sizeof(int16_t) * ((size_t)_number_of_taps - (size_t)steps));
_input_buffer_depth -= steps;
}
else
{
if(steps > _number_of_taps)
static_cast<T *>(this)->skip_samples((unsigned int)steps - (unsigned int)_number_of_taps);
_input_buffer_depth = 0;
}
}
}
}
private:
std::unique_ptr<SignalProcessing::Stepper> _stepper;
std::unique_ptr<SignalProcessing::FIRFilter> _filter;
std::unique_ptr<int16_t> _input_buffer;
int _input_buffer_depth;
void update_filter_coefficients()
{
// make a guess at a good number of taps
_number_of_taps = (_input_cycles_per_second + _output_cycles_per_second) / _output_cycles_per_second;
_number_of_taps *= 2;
_number_of_taps |= 1;
_coefficients_are_dirty = false;
_buffer_in_progress_pointer = 0;
_stepper = std::unique_ptr<SignalProcessing::Stepper>(new SignalProcessing::Stepper((uint64_t)_input_cycles_per_second, (uint64_t)_output_cycles_per_second));
_filter = std::unique_ptr<SignalProcessing::FIRFilter>(new SignalProcessing::FIRFilter((unsigned int)_number_of_taps, (unsigned int)_input_cycles_per_second, 0.0, (float)_output_cycles_per_second / 2.0f, SignalProcessing::FIRFilter::DefaultAttenuation));
_input_buffer = std::unique_ptr<int16_t>(new int16_t[_number_of_taps]);
_input_buffer_depth = 0;
}
};
}
#endif /* Speaker_hpp */
<commit_msg>Number of taps can be specified explicitly if you desire.<commit_after>//
// Speaker.hpp
// Clock Signal
//
// Created by Thomas Harte on 12/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#ifndef Speaker_hpp
#define Speaker_hpp
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include "../SignalProcessing/Stepper.hpp"
#include "../SignalProcessing/FIRFilter.hpp"
namespace Outputs {
class Speaker {
public:
class Delegate {
public:
virtual void speaker_did_complete_samples(Speaker *speaker, const int16_t *buffer, int buffer_size) = 0;
};
void set_output_rate(int cycles_per_second, int buffer_size)
{
_output_cycles_per_second = cycles_per_second;
if(_buffer_size != buffer_size)
{
_buffer_in_progress = std::unique_ptr<int16_t>(new int16_t[buffer_size]);
_buffer_size = buffer_size;
}
set_needs_updated_filter_coefficients();
}
void set_output_quality(int number_of_taps)
{
_requested_number_of_taps = number_of_taps;
set_needs_updated_filter_coefficients();
}
void set_delegate(Delegate *delegate)
{
_delegate = delegate;
}
void set_input_rate(int cycles_per_second)
{
_input_cycles_per_second = cycles_per_second;
set_needs_updated_filter_coefficients();
}
Speaker() : _buffer_in_progress_pointer(0), _requested_number_of_taps(0) {}
protected:
std::unique_ptr<int16_t> _buffer_in_progress;
int _buffer_size;
int _buffer_in_progress_pointer;
int _number_of_taps, _requested_number_of_taps;
bool _coefficients_are_dirty;
Delegate *_delegate;
int _input_cycles_per_second, _output_cycles_per_second;
void set_needs_updated_filter_coefficients()
{
_coefficients_are_dirty = true;
}
};
template <class T> class Filter: public Speaker {
public:
void run_for_cycles(unsigned int input_cycles)
{
if(_coefficients_are_dirty) update_filter_coefficients();
// TODO: what if output rate is greater than input rate?
// fill up as much of the input buffer as possible
while(input_cycles)
{
unsigned int cycles_to_read = (unsigned int)std::min((int)input_cycles, _number_of_taps - _input_buffer_depth);
static_cast<T *>(this)->get_samples(cycles_to_read, &_input_buffer.get()[_input_buffer_depth]);
input_cycles -= cycles_to_read;
_input_buffer_depth += cycles_to_read;
if(_input_buffer_depth == _number_of_taps)
{
_buffer_in_progress.get()[_buffer_in_progress_pointer] = _filter->apply(_input_buffer.get());
_buffer_in_progress_pointer++;
// announce to delegate if full
if(_buffer_in_progress_pointer == _buffer_size)
{
_buffer_in_progress_pointer = 0;
if(_delegate)
{
_delegate->speaker_did_complete_samples(this, _buffer_in_progress.get(), _buffer_size);
}
}
// If the next loop around is going to reuse some of the samples just collected, use a memmove to
// preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip
// anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse.
uint64_t steps = _stepper->step();
if(steps < _number_of_taps)
{
int16_t *input_buffer = _input_buffer.get();
memmove(input_buffer, &input_buffer[steps], sizeof(int16_t) * ((size_t)_number_of_taps - (size_t)steps));
_input_buffer_depth -= steps;
}
else
{
if(steps > _number_of_taps)
static_cast<T *>(this)->skip_samples((unsigned int)steps - (unsigned int)_number_of_taps);
_input_buffer_depth = 0;
}
}
}
}
private:
std::unique_ptr<SignalProcessing::Stepper> _stepper;
std::unique_ptr<SignalProcessing::FIRFilter> _filter;
std::unique_ptr<int16_t> _input_buffer;
int _input_buffer_depth;
void update_filter_coefficients()
{
// make a guess at a good number of taps if this hasn't been provided explicitly
if(_requested_number_of_taps)
{
_number_of_taps = _requested_number_of_taps;
}
else
{
_number_of_taps = (_input_cycles_per_second + _output_cycles_per_second) / _output_cycles_per_second;
_number_of_taps *= 2;
_number_of_taps |= 1;
}
_coefficients_are_dirty = false;
_buffer_in_progress_pointer = 0;
_stepper = std::unique_ptr<SignalProcessing::Stepper>(new SignalProcessing::Stepper((uint64_t)_input_cycles_per_second, (uint64_t)_output_cycles_per_second));
_filter = std::unique_ptr<SignalProcessing::FIRFilter>(new SignalProcessing::FIRFilter((unsigned int)_number_of_taps, (unsigned int)_input_cycles_per_second, 0.0, (float)_output_cycles_per_second / 2.0f, SignalProcessing::FIRFilter::DefaultAttenuation));
_input_buffer = std::unique_ptr<int16_t>(new int16_t[_number_of_taps]);
_input_buffer_depth = 0;
}
};
}
#endif /* Speaker_hpp */
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#define COMPARE_CORNER(A,B) \
VERIFY_IS_EQUAL(matrix.A, matrix.B); \
VERIFY_IS_EQUAL(const_matrix.A, const_matrix.B);
template<typename MatrixType> void corners(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
Index r = ei_random<Index>(1,rows);
Index c = ei_random<Index>(1,cols);
MatrixType matrix = MatrixType::Random(rows,cols);
const MatrixType const_matrix = MatrixType::Random(rows,cols);
COMPARE_CORNER(topLeftCorner(r,c), block(0,0,r,c));
COMPARE_CORNER(topRightCorner(r,c), block(0,cols-c,r,c));
COMPARE_CORNER(bottomLeftCorner(r,c), block(rows-r,0,r,c));
COMPARE_CORNER(bottomRightCorner(r,c), block(rows-r,cols-c,r,c));
COMPARE_CORNER(topRows(r), block(0,0,r,cols));
COMPARE_CORNER(bottomRows(r), block(rows-r,0,r,cols));
COMPARE_CORNER(leftCols(c), block(0,0,rows,c));
COMPARE_CORNER(rightCols(c), block(0,cols-c,rows,c));
}
template<typename MatrixType, int CRows, int CCols> void corners_fixedsize()
{
MatrixType matrix = MatrixType::Random();
const MatrixType const_matrix = MatrixType::Random();
enum {
rows = MatrixType::RowsAtCompileTime,
cols = MatrixType::ColsAtCompileTime,
r = CRows,
c = CCols
};
VERIFY_IS_EQUAL((matrix.template topLeftCorner<r,c>()), (matrix.template block<r,c>(0,0)));
VERIFY_IS_EQUAL((matrix.template topRightCorner<r,c>()), (matrix.template block<r,c>(0,cols-c)));
VERIFY_IS_EQUAL((matrix.template bottomLeftCorner<r,c>()), (matrix.template block<r,c>(rows-r,0)));
VERIFY_IS_EQUAL((matrix.template bottomRightCorner<r,c>()), (matrix.template block<r,c>(rows-r,cols-c)));
VERIFY_IS_EQUAL((matrix.template topRows<r>()), (matrix.template block<r,cols>(0,0)));
VERIFY_IS_EQUAL((matrix.template bottomRows<r>()), (matrix.template block<r,cols>(rows-r,0)));
VERIFY_IS_EQUAL((matrix.template leftCols<c>()), (matrix.template block<rows,c>(0,0)));
VERIFY_IS_EQUAL((matrix.template rightCols<c>()), (matrix.template block<rows,c>(0,cols-c)));
VERIFY_IS_EQUAL((const_matrix.template topLeftCorner<r,c>()), (const_matrix.template block<r,c>(0,0)));
VERIFY_IS_EQUAL((const_matrix.template topRightCorner<r,c>()), (const_matrix.template block<r,c>(0,cols-c)));
VERIFY_IS_EQUAL((const_matrix.template bottomLeftCorner<r,c>()), (const_matrix.template block<r,c>(rows-r,0)));
VERIFY_IS_EQUAL((const_matrix.template bottomRightCorner<r,c>()), (const_matrix.template block<r,c>(rows-r,cols-c)));
VERIFY_IS_EQUAL((const_matrix.template topRows<r>()), (const_matrix.template block<r,cols>(0,0)));
VERIFY_IS_EQUAL((const_matrix.template bottomRows<r>()), (const_matrix.template block<r,cols>(rows-r,0)));
VERIFY_IS_EQUAL((const_matrix.template leftCols<c>()), (const_matrix.template block<rows,c>(0,0)));
VERIFY_IS_EQUAL((const_matrix.template rightCols<c>()), (const_matrix.template block<rows,c>(0,cols-c)));
}
void test_corners()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( corners(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( corners(Matrix4d()) );
CALL_SUBTEST_3( corners(Matrix<int,10,12>()) );
CALL_SUBTEST_4( corners(MatrixXcf(5, 7)) );
CALL_SUBTEST_5( corners(MatrixXf(21, 20)) );
CALL_SUBTEST_1(( corners_fixedsize<Matrix<float, 1, 1>, 1, 1>() ));
CALL_SUBTEST_2(( corners_fixedsize<Matrix4d,2,2>() ));
CALL_SUBTEST_3(( corners_fixedsize<Matrix<int,10,12>,4,7>() ));
}
}
<commit_msg>Included tests for middleRows() and middleCols()<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#define COMPARE_CORNER(A,B) \
VERIFY_IS_EQUAL(matrix.A, matrix.B); \
VERIFY_IS_EQUAL(const_matrix.A, const_matrix.B);
template<typename MatrixType> void corners(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
Index r = ei_random<Index>(1,rows);
Index c = ei_random<Index>(1,cols);
MatrixType matrix = MatrixType::Random(rows,cols);
const MatrixType const_matrix = MatrixType::Random(rows,cols);
COMPARE_CORNER(topLeftCorner(r,c), block(0,0,r,c));
COMPARE_CORNER(topRightCorner(r,c), block(0,cols-c,r,c));
COMPARE_CORNER(bottomLeftCorner(r,c), block(rows-r,0,r,c));
COMPARE_CORNER(bottomRightCorner(r,c), block(rows-r,cols-c,r,c));
Index sr = ei_random<Index>(1,rows) - 1;
Index nr = ei_random<Index>(1,rows-sr);
Index sc = ei_random<Index>(1,cols) - 1;
Index nc = ei_random<Index>(1,cols-sc);
COMPARE_CORNER(topRows(r), block(0,0,r,cols));
COMPARE_CORNER(middleRows(sr,nr), block(sr,0,nr,cols));
COMPARE_CORNER(bottomRows(r), block(rows-r,0,r,cols));
COMPARE_CORNER(leftCols(c), block(0,0,rows,c));
COMPARE_CORNER(middleCols(sc,nc), block(0,sc,rows,nc));
COMPARE_CORNER(rightCols(c), block(0,cols-c,rows,c));
}
template<typename MatrixType, int CRows, int CCols, int SRows, int SCols> void corners_fixedsize()
{
MatrixType matrix = MatrixType::Random();
const MatrixType const_matrix = MatrixType::Random();
enum {
rows = MatrixType::RowsAtCompileTime,
cols = MatrixType::ColsAtCompileTime,
r = CRows,
c = CCols,
sr = SRows,
sc = SCols
};
VERIFY_IS_EQUAL((matrix.template topLeftCorner<r,c>()), (matrix.template block<r,c>(0,0)));
VERIFY_IS_EQUAL((matrix.template topRightCorner<r,c>()), (matrix.template block<r,c>(0,cols-c)));
VERIFY_IS_EQUAL((matrix.template bottomLeftCorner<r,c>()), (matrix.template block<r,c>(rows-r,0)));
VERIFY_IS_EQUAL((matrix.template bottomRightCorner<r,c>()), (matrix.template block<r,c>(rows-r,cols-c)));
VERIFY_IS_EQUAL((matrix.template topRows<r>()), (matrix.template block<r,cols>(0,0)));
VERIFY_IS_EQUAL((matrix.template middleRows<r>(sr)), (matrix.template block<r,cols>(sr,0)));
VERIFY_IS_EQUAL((matrix.template bottomRows<r>()), (matrix.template block<r,cols>(rows-r,0)));
VERIFY_IS_EQUAL((matrix.template leftCols<c>()), (matrix.template block<rows,c>(0,0)));
VERIFY_IS_EQUAL((matrix.template middleCols<c>(sc)), (matrix.template block<rows,c>(0,sc)));
VERIFY_IS_EQUAL((matrix.template rightCols<c>()), (matrix.template block<rows,c>(0,cols-c)));
VERIFY_IS_EQUAL((const_matrix.template topLeftCorner<r,c>()), (const_matrix.template block<r,c>(0,0)));
VERIFY_IS_EQUAL((const_matrix.template topRightCorner<r,c>()), (const_matrix.template block<r,c>(0,cols-c)));
VERIFY_IS_EQUAL((const_matrix.template bottomLeftCorner<r,c>()), (const_matrix.template block<r,c>(rows-r,0)));
VERIFY_IS_EQUAL((const_matrix.template bottomRightCorner<r,c>()), (const_matrix.template block<r,c>(rows-r,cols-c)));
VERIFY_IS_EQUAL((const_matrix.template topRows<r>()), (const_matrix.template block<r,cols>(0,0)));
VERIFY_IS_EQUAL((const_matrix.template middleRows<r>(sr)), (const_matrix.template block<r,cols>(sr,0)));
VERIFY_IS_EQUAL((const_matrix.template bottomRows<r>()), (const_matrix.template block<r,cols>(rows-r,0)));
VERIFY_IS_EQUAL((const_matrix.template leftCols<c>()), (const_matrix.template block<rows,c>(0,0)));
VERIFY_IS_EQUAL((const_matrix.template middleCols<c>(sc)), (const_matrix.template block<rows,c>(0,sc)));
VERIFY_IS_EQUAL((const_matrix.template rightCols<c>()), (const_matrix.template block<rows,c>(0,cols-c)));
}
void test_corners()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( corners(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( corners(Matrix4d()) );
CALL_SUBTEST_3( corners(Matrix<int,10,12>()) );
CALL_SUBTEST_4( corners(MatrixXcf(5, 7)) );
CALL_SUBTEST_5( corners(MatrixXf(21, 20)) );
CALL_SUBTEST_1(( corners_fixedsize<Matrix<float, 1, 1>, 1, 1, 0, 0>() ));
CALL_SUBTEST_2(( corners_fixedsize<Matrix4d,2,2,1,1>() ));
CALL_SUBTEST_3(( corners_fixedsize<Matrix<int,10,12>,4,7,5,2>() ));
}
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <pqxx/connection>
#include <pqxx/subtransaction>
#include <pqxx/transaction>
using namespace PGSTD;
using namespace pqxx;
namespace
{
void test(connection_base &C, const string &desc)
{
cout << "Testing " << desc << ":" << endl;
// Trivial test: create subtransactions, and commit/abort
work T0(C, "T0");
cout << T0.exec("SELECT 'T0 starts'")[0][0].c_str() << endl;
subtransaction T0a(T0, "T0a");
T0a.commit();
subtransaction T0b(T0, "T0b");
T0b.abort();
cout << T0.exec("SELECT 'T0 ends'")[0][0].c_str() << endl;
T0.commit();
// Basic functionality: perform query in subtransaction; abort, continue
work T1(C, "T1");
cout << T1.exec("SELECT 'T1 starts'")[0][0].c_str() << endl;
subtransaction T1a(T1, "T1a");
cout << T1a.exec("SELECT ' a'")[0][0].c_str() << endl;
T1a.commit();
subtransaction T1b(T1, "T1b");
cout << T1b.exec("SELECT ' b'")[0][0].c_str() << endl;
T1b.abort();
subtransaction T1c(T1, "T1c");
cout << T1c.exec("SELECT ' c'")[0][0].c_str() << endl;
T1c.commit();
cout << T1.exec("SELECT 'T1 ends'")[0][0].c_str() << endl;
T1.commit();
}
bool test_and_catch(connection_base &C, const string &desc)
{
bool ok = false;
try
{
test(C,desc);
ok = true;
}
catch (const broken_connection &)
{
throw;
}
catch (const logic_error &)
{
throw;
}
catch (const exception &)
{
if (C.supports(connection_base::cap_nested_transactions))
throw;
cout << "Backend does not support nested transactions." << endl;
}
return ok;
}
} // namespace
// Test program for libpqxx. Attempt to perform nested queries on various types
// of connections.
//
// Usage: test089
int main()
{
try
{
asyncconnection A1;
const bool ok = test_and_catch(A1, "asyncconnection (virgin)");
asyncconnection A2;
A2.activate();
if (!A2.supports(connection_base::cap_nested_transactions))
{
if (ok)
throw logic_error("Initialized asyncconnection doesn't support "
"nested transactions, but a virgin one does!");
cout << "Backend does not support nested transactions. Skipping test."
<< endl;
return 0;
}
if (!ok)
throw logic_error("Virgin asyncconnection supports nested transactions, "
"but initialized one doesn't!");
try
{
test(A2, "asyncconnection (initialized)");
}
catch (const feature_not_supported &e)
{
cerr << e.what() << endl;
return 0;
}
lazyconnection L1;
test(L1, "lazyconnection (virgin)");
lazyconnection L2;
L2.activate();
test(L2, "lazyconnection (initialized)");
connection C;
C.activate();
C.deactivate();
test(C, "connection (deactivated)");
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<commit_msg>Account for alternate detection of "nested transactions" capability<commit_after>#include <cassert>
#include <iostream>
#include <pqxx/connection>
#include <pqxx/subtransaction>
#include <pqxx/transaction>
using namespace PGSTD;
using namespace pqxx;
namespace
{
void test(connection_base &C, const string &desc)
{
cout << "Testing " << desc << ":" << endl;
// Trivial test: create subtransactions, and commit/abort
work T0(C, "T0");
cout << T0.exec("SELECT 'T0 starts'")[0][0].c_str() << endl;
subtransaction T0a(T0, "T0a");
T0a.commit();
subtransaction T0b(T0, "T0b");
T0b.abort();
cout << T0.exec("SELECT 'T0 ends'")[0][0].c_str() << endl;
T0.commit();
// Basic functionality: perform query in subtransaction; abort, continue
work T1(C, "T1");
cout << T1.exec("SELECT 'T1 starts'")[0][0].c_str() << endl;
subtransaction T1a(T1, "T1a");
cout << T1a.exec("SELECT ' a'")[0][0].c_str() << endl;
T1a.commit();
subtransaction T1b(T1, "T1b");
cout << T1b.exec("SELECT ' b'")[0][0].c_str() << endl;
T1b.abort();
subtransaction T1c(T1, "T1c");
cout << T1c.exec("SELECT ' c'")[0][0].c_str() << endl;
T1c.commit();
cout << T1.exec("SELECT 'T1 ends'")[0][0].c_str() << endl;
T1.commit();
}
bool test_and_catch(connection_base &C, const string &desc)
{
bool ok = false;
try
{
test(C,desc);
ok = true;
}
catch (const broken_connection &)
{
throw;
}
catch (const logic_error &)
{
throw;
}
catch (const exception &)
{
if (C.supports(connection_base::cap_nested_transactions))
throw;
cout << "Backend does not support nested transactions." << endl;
}
return ok;
}
} // namespace
// Test program for libpqxx. Attempt to perform nested queries on various types
// of connections.
//
// Usage: test089
int main()
{
try
{
asyncconnection A1;
bool ok = test_and_catch(A1, "asyncconnection (virgin)");
asyncconnection A2;
A2.activate();
if (!A2.supports(connection_base::cap_nested_transactions))
{
if (ok)
{
/* A1 supported nested transactions but A2 says it doesn't. What may
* have happened is we weren't able to establish the connections'
* capabilities, and the capability for nested transactions was deduced
* from the fact that that first subtransaction actually worked.
* If so, try that again.
*/
try
{
work W(A2);
subtransaction s(W);
s.commit();
}
catch (const exception &)
{
throw logic_error("First asyncconnection supported nested "
"transactions, but second one doesn't!");
}
}
else
{
cout << "Backend does not support nested transactions. Skipping test."
<< endl;
return 0;
}
}
if (!ok)
throw logic_error("Virgin asyncconnection supports nested transactions, "
"but initialized one doesn't!");
try
{
test(A2, "asyncconnection (initialized)");
}
catch (const feature_not_supported &e)
{
cerr << e.what() << endl;
return 0;
}
lazyconnection L1;
test(L1, "lazyconnection (virgin)");
lazyconnection L2;
L2.activate();
test(L2, "lazyconnection (initialized)");
connection C;
C.activate();
C.deactivate();
test(C, "connection (deactivated)");
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include <cppcoro/when_all.hpp>
#include <cppcoro/task.hpp>
#include <cppcoro/shared_task.hpp>
#include <cppcoro/sync_wait.hpp>
#include <cppcoro/async_manual_reset_event.hpp>
#include "counted.hpp"
#include <functional>
#include <string>
#include <vector>
#include "doctest/doctest.h"
TEST_SUITE_BEGIN("when_all_ready");
template<template<typename T> class TASK, typename T>
TASK<T> when_event_set_return(cppcoro::async_manual_reset_event& event, T value)
{
co_await event;
co_return std::move(value);
}
TEST_CASE("when_all_ready() with no args")
{
[[maybe_unused]] std::tuple<> result = cppcoro::sync_wait(cppcoro::when_all_ready());
}
TEST_CASE("when_all_ready() with one task")
{
bool started = false;
auto f = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<>
{
started = true;
co_await event;
};
cppcoro::async_manual_reset_event event;
auto whenAllTask = cppcoro::when_all_ready(f(event));
CHECK(!started);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto&[t] = co_await whenAllTask;
CHECK(t.is_ready());
}(),
[&]() -> cppcoro::task<>
{
CHECK(started);
event.set();
CHECK(whenAllTask.is_ready());
co_return;
}()));
}
TEST_CASE("when_all_ready() with multiple task")
{
auto makeTask = [&](bool& started, cppcoro::async_manual_reset_event& event) -> cppcoro::task<>
{
started = true;
co_await event;
};
cppcoro::async_manual_reset_event event1;
cppcoro::async_manual_reset_event event2;
bool started1 = false;
bool started2 = false;
auto whenAllTask = cppcoro::when_all_ready(
makeTask(started1, event1),
makeTask(started2, event2));
CHECK(!started1);
CHECK(!started2);
bool whenAllTaskFinished = false;
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto[t1, t2] = co_await std::move(whenAllTask);
whenAllTaskFinished = true;
CHECK(t1.is_ready());
CHECK(t2.is_ready());
}(),
[&]() -> cppcoro::task<>
{
CHECK(started1);
CHECK(started2);
event2.set();
CHECK(!whenAllTaskFinished);
event1.set();
CHECK(whenAllTaskFinished);
co_return;
}()));
}
TEST_CASE("when_all_ready() with all task types")
{
cppcoro::async_manual_reset_event event;
auto t0 = when_event_set_return<cppcoro::task>(event, 1);
auto t1 = when_event_set_return<cppcoro::shared_task>(event, 2);
auto allTask = cppcoro::when_all_ready(std::move(t0), t1);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto [t0, t1] = co_await std::move(allTask);
CHECK(t0.is_ready());
CHECK(t1.is_ready());
CHECK(co_await t0 == 1);
CHECK(co_await t1 == 2);
}(),
[&]() -> cppcoro::task<>
{
event.set();
co_return;
}()));
}
TEST_CASE("when_all_ready() with all task types passed by ref")
{
cppcoro::async_manual_reset_event event;
auto t0 = when_event_set_return<cppcoro::task>(event, 1);
auto t1 = when_event_set_return<cppcoro::shared_task>(event, 2);
auto allTask = cppcoro::when_all_ready(
std::ref(t0),
std::ref(t1));
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto[u0, u1] = co_await allTask;
// Address of reference should be same as address of original task.
CHECK(&u0.get() == &t0);
CHECK(&u1.get() == &t1);
CHECK(co_await t0 == 1);
CHECK(co_await t1 == 2);
}(),
[&]() -> cppcoro::task<>
{
event.set();
co_return;
}()));
CHECK(allTask.is_ready());
}
TEST_CASE("when_all_ready() with std::vector<task<T>>")
{
cppcoro::async_manual_reset_event event;
std::uint32_t startedCount = 0;
std::uint32_t finishedCount = 0;
auto makeTask = [&]() -> cppcoro::task<>
{
++startedCount;
co_await event;
++finishedCount;
};
std::vector<cppcoro::task<>> tasks;
for (std::uint32_t i = 0; i < 10; ++i)
{
tasks.emplace_back(makeTask());
}
cppcoro::task<std::vector<cppcoro::task<>>> allTask =
cppcoro::when_all_ready(std::move(tasks));
// Shouldn't have started any tasks yet.
CHECK(startedCount == 0u);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto resultTasks = co_await std::move(allTask);
CHECK(resultTasks .size() == 10u);
for (auto& t : resultTasks)
{
CHECK(t.is_ready());
}
}(),
[&]() -> cppcoro::task<>
{
CHECK(startedCount == 10u);
CHECK(finishedCount == 0u);
event.set();
CHECK(finishedCount == 10u);
co_return;
}()));
}
TEST_CASE("when_all_ready() with std::vector<shared_task<T>>")
{
cppcoro::async_manual_reset_event event;
std::uint32_t startedCount = 0;
std::uint32_t finishedCount = 0;
auto makeTask = [&]() -> cppcoro::shared_task<>
{
++startedCount;
co_await event;
++finishedCount;
};
std::vector<cppcoro::shared_task<>> tasks;
for (std::uint32_t i = 0; i < 10; ++i)
{
tasks.emplace_back(makeTask());
}
cppcoro::task<std::vector<cppcoro::shared_task<>>> allTask =
cppcoro::when_all_ready(std::move(tasks));
// Shouldn't have started any tasks yet.
CHECK(startedCount == 0u);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto resultTasks = co_await std::move(allTask);
CHECK(resultTasks.size() == 10u);
for (auto& t : resultTasks)
{
CHECK(t.is_ready());
}
}(),
[&]() -> cppcoro::task<>
{
CHECK(startedCount == 10u);
CHECK(finishedCount == 0u);
event.set();
CHECK(finishedCount == 10u);
co_return;
}()));
}
TEST_CASE("when_all_ready() doesn't rethrow exceptions")
{
auto makeTask = [](bool throwException) -> cppcoro::task<int>
{
if (throwException)
{
throw std::exception{};
}
else
{
co_return 123;
}
};
cppcoro::sync_wait([&]() -> cppcoro::task<>
{
try
{
auto[t0, t1] = co_await cppcoro::when_all_ready(makeTask(true), makeTask(false));
// You can obtain the exceptions by re-awaiting the returned tasks.
CHECK_THROWS_AS((void)co_await t0, const std::exception&);
CHECK(co_await t1 == 123);
}
catch (...)
{
FAIL("Shouldn't throw");
}
}());
}
TEST_SUITE_END();
<commit_msg>Fix warning about shadowed variables.<commit_after>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include <cppcoro/when_all.hpp>
#include <cppcoro/task.hpp>
#include <cppcoro/shared_task.hpp>
#include <cppcoro/sync_wait.hpp>
#include <cppcoro/async_manual_reset_event.hpp>
#include "counted.hpp"
#include <functional>
#include <string>
#include <vector>
#include "doctest/doctest.h"
TEST_SUITE_BEGIN("when_all_ready");
template<template<typename T> class TASK, typename T>
TASK<T> when_event_set_return(cppcoro::async_manual_reset_event& event, T value)
{
co_await event;
co_return std::move(value);
}
TEST_CASE("when_all_ready() with no args")
{
[[maybe_unused]] std::tuple<> result = cppcoro::sync_wait(cppcoro::when_all_ready());
}
TEST_CASE("when_all_ready() with one task")
{
bool started = false;
auto f = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<>
{
started = true;
co_await event;
};
cppcoro::async_manual_reset_event event;
auto whenAllTask = cppcoro::when_all_ready(f(event));
CHECK(!started);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto&[t] = co_await whenAllTask;
CHECK(t.is_ready());
}(),
[&]() -> cppcoro::task<>
{
CHECK(started);
event.set();
CHECK(whenAllTask.is_ready());
co_return;
}()));
}
TEST_CASE("when_all_ready() with multiple task")
{
auto makeTask = [&](bool& started, cppcoro::async_manual_reset_event& event) -> cppcoro::task<>
{
started = true;
co_await event;
};
cppcoro::async_manual_reset_event event1;
cppcoro::async_manual_reset_event event2;
bool started1 = false;
bool started2 = false;
auto whenAllTask = cppcoro::when_all_ready(
makeTask(started1, event1),
makeTask(started2, event2));
CHECK(!started1);
CHECK(!started2);
bool whenAllTaskFinished = false;
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto[t1, t2] = co_await std::move(whenAllTask);
whenAllTaskFinished = true;
CHECK(t1.is_ready());
CHECK(t2.is_ready());
}(),
[&]() -> cppcoro::task<>
{
CHECK(started1);
CHECK(started2);
event2.set();
CHECK(!whenAllTaskFinished);
event1.set();
CHECK(whenAllTaskFinished);
co_return;
}()));
}
TEST_CASE("when_all_ready() with all task types")
{
cppcoro::async_manual_reset_event event;
auto t0 = when_event_set_return<cppcoro::task>(event, 1);
auto t1 = when_event_set_return<cppcoro::shared_task>(event, 2);
auto allTask = cppcoro::when_all_ready(std::move(t0), t1);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto [r0, r1] = co_await std::move(allTask);
CHECK(r0.is_ready());
CHECK(r1.is_ready());
CHECK(co_await r0 == 1);
CHECK(co_await r1 == 2);
}(),
[&]() -> cppcoro::task<>
{
event.set();
co_return;
}()));
}
TEST_CASE("when_all_ready() with all task types passed by ref")
{
cppcoro::async_manual_reset_event event;
auto t0 = when_event_set_return<cppcoro::task>(event, 1);
auto t1 = when_event_set_return<cppcoro::shared_task>(event, 2);
auto allTask = cppcoro::when_all_ready(
std::ref(t0),
std::ref(t1));
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto[u0, u1] = co_await allTask;
// Address of reference should be same as address of original task.
CHECK(&u0.get() == &t0);
CHECK(&u1.get() == &t1);
CHECK(co_await t0 == 1);
CHECK(co_await t1 == 2);
}(),
[&]() -> cppcoro::task<>
{
event.set();
co_return;
}()));
CHECK(allTask.is_ready());
}
TEST_CASE("when_all_ready() with std::vector<task<T>>")
{
cppcoro::async_manual_reset_event event;
std::uint32_t startedCount = 0;
std::uint32_t finishedCount = 0;
auto makeTask = [&]() -> cppcoro::task<>
{
++startedCount;
co_await event;
++finishedCount;
};
std::vector<cppcoro::task<>> tasks;
for (std::uint32_t i = 0; i < 10; ++i)
{
tasks.emplace_back(makeTask());
}
cppcoro::task<std::vector<cppcoro::task<>>> allTask =
cppcoro::when_all_ready(std::move(tasks));
// Shouldn't have started any tasks yet.
CHECK(startedCount == 0u);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto resultTasks = co_await std::move(allTask);
CHECK(resultTasks .size() == 10u);
for (auto& t : resultTasks)
{
CHECK(t.is_ready());
}
}(),
[&]() -> cppcoro::task<>
{
CHECK(startedCount == 10u);
CHECK(finishedCount == 0u);
event.set();
CHECK(finishedCount == 10u);
co_return;
}()));
}
TEST_CASE("when_all_ready() with std::vector<shared_task<T>>")
{
cppcoro::async_manual_reset_event event;
std::uint32_t startedCount = 0;
std::uint32_t finishedCount = 0;
auto makeTask = [&]() -> cppcoro::shared_task<>
{
++startedCount;
co_await event;
++finishedCount;
};
std::vector<cppcoro::shared_task<>> tasks;
for (std::uint32_t i = 0; i < 10; ++i)
{
tasks.emplace_back(makeTask());
}
cppcoro::task<std::vector<cppcoro::shared_task<>>> allTask =
cppcoro::when_all_ready(std::move(tasks));
// Shouldn't have started any tasks yet.
CHECK(startedCount == 0u);
cppcoro::sync_wait(cppcoro::when_all_ready(
[&]() -> cppcoro::task<>
{
auto resultTasks = co_await std::move(allTask);
CHECK(resultTasks.size() == 10u);
for (auto& t : resultTasks)
{
CHECK(t.is_ready());
}
}(),
[&]() -> cppcoro::task<>
{
CHECK(startedCount == 10u);
CHECK(finishedCount == 0u);
event.set();
CHECK(finishedCount == 10u);
co_return;
}()));
}
TEST_CASE("when_all_ready() doesn't rethrow exceptions")
{
auto makeTask = [](bool throwException) -> cppcoro::task<int>
{
if (throwException)
{
throw std::exception{};
}
else
{
co_return 123;
}
};
cppcoro::sync_wait([&]() -> cppcoro::task<>
{
try
{
auto[t0, t1] = co_await cppcoro::when_all_ready(makeTask(true), makeTask(false));
// You can obtain the exceptions by re-awaiting the returned tasks.
CHECK_THROWS_AS((void)co_await t0, const std::exception&);
CHECK(co_await t1 == 123);
}
catch (...)
{
FAIL("Shouldn't throw");
}
}());
}
TEST_SUITE_END();
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#define ENTDIM 8
#define COORDIM (ENTDIM-2)
#define PARAMDIM 5
namespace
{
int numofline (const char * fname)
{
int number_of_lines = 0;
std::string line;
std::ifstream myfile(fname);
while (std::getline(myfile, line))
++number_of_lines;
myfile.close();
return number_of_lines;
}
}
int main (int argc, char ** argv)
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl;
return 1;
}
int num_of_line = numofline(argv[1]);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << " " << num_of_ent << " entries " << std::endl;
// non perfomante ma easy to go
arma::mat paraminp = arma::zeros<arma::mat>(num_of_ent,PARAMDIM);
arma::mat coordinp = arma::zeros<arma::mat>(num_of_ent,3*COORDIM);
arma::mat layer, ladder, module;
layer.set_size(num_of_ent,COORDIM);
ladder.set_size(num_of_ent,COORDIM);
module.set_size(num_of_ent,COORDIM);
// leggere file coordinate tracce simulate plus parametri
std::string line;
std::ifstream mytfp;
mytfp.open (argv[1], std::ios::in);
std::getline (mytfp, line);
//std::cout << line << std::endl;
for (int i = 0; i < num_of_ent; ++i)
{
int fake1, fake2;
mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
std::cout << fake1 << " " << fake2 << std::endl;
#endif
for (int j = 0; j < COORDIM; ++j)
{
int a, b, c;
mytfp >> coordinp(i, j*3) >>
coordinp(i, j*3+1) >>
coordinp(i, j*3+2) >>
a >> b >> c;
layer(i, j) = a;
ladder(i, j) = b;
module(i, j) = c;
}
mytfp >> paraminp(i,0) >>
paraminp(i,1) >>
paraminp(i,2) >>
paraminp(i,3) >>
paraminp(i,4);
}
mytfp.close();
#ifdef DEBUG
for (int i = 0; i < num_of_ent; ++i)
{
for (int j = 0; j < COORDIM; ++j)
{
std::cout << coordinp(i, j*3) << " " <<
coordinp(i, j*3+1) << " " <<
coordinp(i, j*3+2) << " " <<
ladder(i, j) << std::endl;
}
std::cout << paraminp(i,0) << " " <<
paraminp(i,1) << " " <<
paraminp(i,2) << " " <<
paraminp(i,3) << " " <<
paraminp(i,4) << std::endl;
}
#endif
arma::mat param;
arma::mat coord;
int k = 0;
// to be used to select inly a ladder ....
for (int i = 0; i < num_of_ent; ++i)
{
bool todo = false;
if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) &&
(ladder(i, 2) == 2))
todo = true;
if (todo)
k++;
}
param.set_size(k,PARAMDIM);
coord.set_size(k,3*COORDIM);
k = 0;
// to be used to select inly a ladder ....
for (int i = 0; i < num_of_ent; ++i)
{
bool todo = false;
if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) &&
(ladder(i, 2) == 2))
todo = true;
if (todo)
{
for (int j = 0; j < 3*COORDIM; ++j)
coord(k,j) = coordinp(i,j);
for (int j = 0; j < PARAMDIM; ++j)
param(k,j) = paraminp(i,j);
k++;
}
}
num_of_ent = k;
std::cout << "we got " << num_of_ent << " tracks " << std::endl;
// projection
arma::mat score;
// ordered
arma::vec eigval;
// by row or by column ?
arma::mat eigvec;
arma::princomp(eigvec, score, eigval, coord);
//std::cout << score.n_rows << " " << score.n_cols << std::endl;
//for (int i=0; i<score.n_rows; ++i)
// std::cout << score(i,0) << " "
// << score(i,1) << " " << score(i,2) << std::endl;
double totval = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
totval += eigval(i);
std::cout << "Eigenvalues: " << std::endl;
double totvar = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
{
if (i < PARAMDIM)
totvar += 100.0e0*(eigval(i)/totval);
std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval)
<< "% value: " << eigval(i) << std::endl;
}
std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl;
arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
v = arma::cov(coord);
#ifdef DEBUG
/* correlation matrix ricorda su dati standardizzati coincide con la matrice
* di covarianza :
* z = x -<x> / sigma */
arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
corr(i,j) = v(i,j) / sqrt(v(i,i)*v(j,j));
std::cout << "Correlation matrix: " << std::endl;
std::cout << corr;
#endif
arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
vi = v.i();
#ifdef DEBUG
std::cout << "inverse by cov matrix: " << std::endl;
std::cout << v * vi ;
#endif
// and so on ...
arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM);
arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM);
arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM);
double sum = 1.0e0;
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm(i) += (coord(l,i)-coordm(i))/sum;
for (int i=0; i<PARAMDIM; ++i)
paramm(i) += (param(l,i)-paramm(i))/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<PARAMDIM; ++j)
{
hcap(i,j) += ((coord(l,i) - coordm(i))*
(param(l,j) - paramm(j))-
(sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0);
}
}
}
arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM);
for (int i=0; i<PARAMDIM; ++i)
for (int l=0; l<(3*COORDIM); ++l)
for (int m=0; m<(3*COORDIM); ++m)
cmtx(i,l) += vi(l,m) * hcap (m,i);
#ifdef DEBUG
std::cout << "C matrix: " << std::endl;
std::cout << cmtx;
#endif
arma::mat q = arma::zeros<arma::mat>(PARAMDIM);
for (int i=0; i<PARAMDIM; ++i)
{
q(i) = paramm(i);
for (int l=0; l<(3*COORDIM); ++l)
q(i) -= cmtx(i,l)*coordm[l];
}
#ifdef DEBUG
std::cout << "Q vector: " << std::endl;
for (int i=0; i<PARAMDIM; ++i)
std::cout << q(i) << std::endl;
#endif
//test back
arma::running_stat<double> chi2stats;
arma::running_stat<double> pc[PARAMDIM];
for (int l=0; l<num_of_ent; ++l)
{
std::cout << "Track: " << l+1 << std::endl;
for (int i=0; i<PARAMDIM; ++i)
{
double p = q(i);
for (int k=0; k<(3*COORDIM); ++k)
p += cmtx(i,k)*coord(l,k);
std::cout << " computed " << p << " real " << param(l,i) << std::endl;
pc[i](fabs(p - param(l,i))/(fabs(p + param(l,i))/2.0));
}
/* chi**2 */
double chi2 = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
chi2 += (coord(l,i) - coordm(i)) *
vi(i, j) * (coord(l,j) - coordm(j));
std::cout << " chi2: " << chi2 << std::endl;
chi2stats(chi2);
}
std::cout << "chi2 mean = " << chi2stats.mean() << std::endl;
std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl;
std::cout << "chi2 min = " << chi2stats.min() << std::endl;
std::cout << "chi2 max = " << chi2stats.max() << std::endl;
for (int i=0; i<PARAMDIM; ++i)
{
std::cout << pc[i].mean() << " " << pc[i].stddev() << std::endl;
arma::running_stat<double> stats;
for (int l=0; l<num_of_ent; ++l)
stats(param(l,i));
std::cout << " mean = " << stats.mean() << std::endl;
std::cout << " stdev = " << stats.stddev() << std::endl;
std::cout << " min = " << stats.min() << std::endl;
std::cout << " max = " << stats.max() << std::endl;
}
return 0;
}
<commit_msg>printout parameters in separate files<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#define ENTDIM 8
#define COORDIM (ENTDIM-2)
#define PARAMDIM 5
namespace
{
int numofline (const char * fname)
{
int number_of_lines = 0;
std::string line;
std::ifstream myfile(fname);
while (std::getline(myfile, line))
++number_of_lines;
myfile.close();
return number_of_lines;
}
void writetofile (const char * fname, int cidx,
const arma::mat & mat)
{
if (cidx < (int) mat.n_cols)
{
std::ofstream myfile(fname);
for (int i=0; i<(int)mat.n_rows; i++)
myfile << i << " " << mat(i,cidx) << std::endl;
myfile.close();
}
}
}
int main (int argc, char ** argv)
{
if (argc != 2)
{
std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl;
return 1;
}
int num_of_line = numofline(argv[1]);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << " " << num_of_ent << " entries " << std::endl;
// non perfomante ma easy to go
arma::mat paraminp = arma::zeros<arma::mat>(num_of_ent,PARAMDIM);
arma::mat coordinp = arma::zeros<arma::mat>(num_of_ent,3*COORDIM);
arma::mat layer, ladder, module;
layer.set_size(num_of_ent,COORDIM);
ladder.set_size(num_of_ent,COORDIM);
module.set_size(num_of_ent,COORDIM);
// leggere file coordinate tracce simulate plus parametri
std::string line;
std::ifstream mytfp;
mytfp.open (argv[1], std::ios::in);
std::getline (mytfp, line);
//std::cout << line << std::endl;
for (int i = 0; i < num_of_ent; ++i)
{
int fake1, fake2;
mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
std::cout << fake1 << " " << fake2 << std::endl;
#endif
for (int j = 0; j < COORDIM; ++j)
{
int a, b, c;
mytfp >> coordinp(i, j*3) >>
coordinp(i, j*3+1) >>
coordinp(i, j*3+2) >>
a >> b >> c;
layer(i, j) = a;
ladder(i, j) = b;
module(i, j) = c;
}
mytfp >> paraminp(i,0) >>
paraminp(i,1) >>
paraminp(i,2) >>
paraminp(i,3) >>
paraminp(i,4);
}
mytfp.close();
for (int i = 0; i < PARAMDIM; ++i)
{
switch (i)
{
case 0:
std::cout << i+1 << " pt" << std::endl;
break;
case 1:
std::cout << i+1 << " phi" << std::endl;
break;
case 2:
std::cout << i+1 << " d0" << std::endl;
break;
case 3:
std::cout << i+1 << " eta" << std::endl;
break;
case 4:
std::cout << i+1 << " z0" << std::endl;
break;
};
std::ostringstream fname;
fname << "p" << i+1 << ".txt";
writetofile(fname.str().c_str(), i, paraminp);
}
#ifdef DEBUG
for (int i = 0; i < num_of_ent; ++i)
{
for (int j = 0; j < COORDIM; ++j)
{
std::cout << coordinp(i, j*3) << " " <<
coordinp(i, j*3+1) << " " <<
coordinp(i, j*3+2) << " " <<
ladder(i, j) << std::endl;
}
std::cout << paraminp(i,0) << " " <<
paraminp(i,1) << " " <<
paraminp(i,2) << " " <<
paraminp(i,3) << " " <<
paraminp(i,4) << std::endl;
}
#endif
arma::mat param;
arma::mat coord;
int k = 0;
// to be used to select inly a ladder ....
for (int i = 0; i < num_of_ent; ++i)
{
bool todo = false;
//if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) &&
// (ladder(i, 2) == 2))
todo = true;
if (todo)
k++;
}
param.set_size(k,PARAMDIM);
coord.set_size(k,3*COORDIM);
k = 0;
// to be used to select inly a ladder ....
for (int i = 0; i < num_of_ent; ++i)
{
bool todo = false;
//if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) &&
// (ladder(i, 2) == 2))
todo = true;
if (todo)
{
for (int j = 0; j < 3*COORDIM; ++j)
coord(k,j) = coordinp(i,j);
for (int j = 0; j < PARAMDIM; ++j)
param(k,j) = paraminp(i,j);
k++;
}
}
num_of_ent = k;
std::cout << "we got " << num_of_ent << " tracks " << std::endl;
// projection
arma::mat score;
// ordered
arma::vec eigval;
// by row or by column ?
arma::mat eigvec;
arma::princomp(eigvec, score, eigval, coord);
//std::cout << score.n_rows << " " << score.n_cols << std::endl;
//for (int i=0; i<score.n_rows; ++i)
// std::cout << score(i,0) << " "
// << score(i,1) << " " << score(i,2) << std::endl;
double totval = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
totval += eigval(i);
std::cout << "Eigenvalues: " << std::endl;
double totvar = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
{
if (i < PARAMDIM)
totvar += 100.0e0*(eigval(i)/totval);
std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval)
<< "% value: " << eigval(i) << std::endl;
}
std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl;
arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
v = arma::cov(coord);
#ifdef DEBUG
/* correlation matrix ricorda su dati standardizzati coincide con la matrice
* di covarianza :
* z = x -<x> / sigma */
arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
corr(i,j) = v(i,j) / sqrt(v(i,i)*v(j,j));
std::cout << "Correlation matrix: " << std::endl;
std::cout << corr;
#endif
arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);
vi = v.i();
#ifdef DEBUG
std::cout << "inverse by cov matrix: " << std::endl;
std::cout << v * vi ;
#endif
// and so on ...
arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM);
arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM);
arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM);
double sum = 1.0e0;
for (int l=0; l<num_of_ent; ++l)
{
sum += 1.0e0;
for (int i=0; i<(3*COORDIM); ++i)
coordm(i) += (coord(l,i)-coordm(i))/sum;
for (int i=0; i<PARAMDIM; ++i)
paramm(i) += (param(l,i)-paramm(i))/sum;
for (int i=0; i<(3*COORDIM); ++i)
{
for (int j=0; j<PARAMDIM; ++j)
{
hcap(i,j) += ((coord(l,i) - coordm(i))*
(param(l,j) - paramm(j))-
(sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0);
}
}
}
arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM);
for (int i=0; i<PARAMDIM; ++i)
for (int l=0; l<(3*COORDIM); ++l)
for (int m=0; m<(3*COORDIM); ++m)
cmtx(i,l) += vi(l,m) * hcap (m,i);
#ifdef DEBUG
std::cout << "C matrix: " << std::endl;
std::cout << cmtx;
#endif
arma::mat q = arma::zeros<arma::mat>(PARAMDIM);
for (int i=0; i<PARAMDIM; ++i)
{
q(i) = paramm(i);
for (int l=0; l<(3*COORDIM); ++l)
q(i) -= cmtx(i,l)*coordm[l];
}
#ifdef DEBUG
std::cout << "Q vector: " << std::endl;
for (int i=0; i<PARAMDIM; ++i)
std::cout << q(i) << std::endl;
#endif
//test back
arma::running_stat<double> chi2stats;
arma::running_stat<double> pc[PARAMDIM];
for (int l=0; l<num_of_ent; ++l)
{
std::cout << "Track: " << l+1 << std::endl;
for (int i=0; i<PARAMDIM; ++i)
{
double p = q(i);
for (int k=0; k<(3*COORDIM); ++k)
p += cmtx(i,k)*coord(l,k);
std::cout << " computed " << p << " real " << param(l,i) << std::endl;
pc[i](fabs(p - param(l,i))/(fabs(p + param(l,i))/2.0));
}
/* chi**2 */
double chi2 = 0.0e0;
for (int i=0; i<(3*COORDIM); ++i)
for (int j=0; j<(3*COORDIM); ++j)
chi2 += (coord(l,i) - coordm(i)) *
vi(i, j) * (coord(l,j) - coordm(j));
std::cout << " chi2: " << chi2 << std::endl;
chi2stats(chi2);
}
std::cout << "chi2 mean = " << chi2stats.mean() << std::endl;
std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl;
std::cout << "chi2 min = " << chi2stats.min() << std::endl;
std::cout << "chi2 max = " << chi2stats.max() << std::endl;
for (int i=0; i<PARAMDIM; ++i)
{
std::cout << pc[i].mean() << " " << pc[i].stddev() << std::endl;
arma::running_stat<double> stats;
for (int l=0; l<num_of_ent; ++l)
stats(param(l,i));
std::cout << " mean = " << stats.mean() << std::endl;
std::cout << " stdev = " << stats.stddev() << std::endl;
std::cout << " min = " << stats.min() << std::endl;
std::cout << " max = " << stats.max() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postit.hxx,v $
*
* $Revision: 1.7 $
*
* 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 _POSTIT_HXX
#define _POSTIT_HXX
#include <postithelper.hxx>
#include <vcl/window.hxx>
#include <swrect.hxx>
#include <svx/sdr/overlay/overlayobject.hxx>
#include <vcl/lineinfo.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <svx/editstat.hxx>
class SwPostItMgr;
class SwPostItField;
class SwFmtFld;
class OutlinerView;
class Outliner;
class ScrollBar;
class SwEditWin;
class SwView;
class SwPostIt;
class Edit;
class MultiLineEdit;
class PopupMenu;
class SvxLanguageItem;
class SwPostItAnkor: public sdr::overlay::OverlayObjectWithBasePosition
{
protected:
/* 6------------7
1 /
/4\ ---------------5
2 - 3
*/
basegfx::B2DPoint maSecondPosition;
basegfx::B2DPoint maThirdPosition;
basegfx::B2DPoint maFourthPosition;
basegfx::B2DPoint maFifthPosition;
basegfx::B2DPoint maSixthPosition;
basegfx::B2DPoint maSeventhPosition;
// helpers to fill and reset geometry
void implEnsureGeometry();
void implResetGeometry();
// helpers to paint geometry
void implDrawGeometry(OutputDevice& rOutputDevice, Color aColor, double fOffX, double fOffY);
Color implBlendColor(const Color aOriginal, sal_Int16 nChange);
virtual void drawGeometry(OutputDevice& rOutputDevice);
virtual void createBaseRange(OutputDevice& rOutputDevice);
private:
// object's geometry
basegfx::B2DPolygon maTriangle;
basegfx::B2DPolygon maLine;
basegfx::B2DPolygon maLineTop;
LineInfo mLineInfo;
unsigned long mHeight;
bool mbShadowedEffect;
public:
SwPostItAnkor(const basegfx::B2DPoint& rBasePos,
const basegfx::B2DPoint& rSecondPos,
const basegfx::B2DPoint& rThirdPos,
const basegfx::B2DPoint& rFourthPos,
const basegfx::B2DPoint& rFifthPos,
const basegfx::B2DPoint& rSixthPos,
const basegfx::B2DPoint& rSeventhPos,
Color aBaseColor,
const LineInfo &aLineInfo,
bool bShadowedEffect);
virtual ~SwPostItAnkor();
const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; }
const basegfx::B2DPoint& GetThirdPosition() const { return maThirdPosition; }
const basegfx::B2DPoint& GetFourthPosition() const { return maFourthPosition; }
const basegfx::B2DPoint& GetFifthPosition() const { return maFifthPosition; }
const basegfx::B2DPoint& GetSixthPosition() const { return maSixthPosition; }
const basegfx::B2DPoint& GetSeventhPosition() const { return maSeventhPosition; }
void SetAllPosition(const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2, const basegfx::B2DPoint& rPoint3,
const basegfx::B2DPoint& rPoint4, const basegfx::B2DPoint& rPoint5, const basegfx::B2DPoint& rPoint6, const basegfx::B2DPoint& rPoint7);
void SetTriPosition(const basegfx::B2DPoint& rPoint1,const basegfx::B2DPoint& rPoint2,const basegfx::B2DPoint& rPoint3,
const basegfx::B2DPoint& rPoint4,const basegfx::B2DPoint& rPoint5);
void SetSixthPosition(const basegfx::B2DPoint& rNew);
void SetSeventhPosition(const basegfx::B2DPoint& rNew);
void SetLineInfo(const LineInfo &aLineInfo);
void SetHeight(const unsigned long aHeight) {mHeight = aHeight;};
bool getShadowedEffect() const { return mbShadowedEffect; }
virtual void Trigger(sal_uInt32 nTime);
//sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol) const;
// transform object coordinates. Transforms maBasePosition
// and invalidates on change
virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};
enum ShadowState {SS_NORMAL, SS_VIEW, SS_EDIT};
class SwPostItShadow: public sdr::overlay::OverlayObjectWithBasePosition
{
protected:
virtual void drawGeometry(OutputDevice& rOutputDevice);
virtual void createBaseRange(OutputDevice& rOutputDevice);
private:
basegfx::B2DPoint maSecondPosition;
ShadowState mShadowState;
public:
SwPostItShadow(const basegfx::B2DPoint& rBasePos, const basegfx::B2DPoint& rSecondPosition, Color aBaseColor,ShadowState aState);
virtual ~SwPostItShadow();
void SetShadowState(ShadowState aState);
ShadowState GetShadowState() {return mShadowState;}
const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; }
void SetSecondPosition(const basegfx::B2DPoint& rNew);
void SetPosition(const basegfx::B2DPoint& rPoint1,const basegfx::B2DPoint& rPoint2);
virtual void Trigger(sal_uInt32 nTime);
virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};
class PostItTxt : public Window
{
private:
OutlinerView* mpOutlinerView;
SwPostIt* mpPostIt;
bool mMouseOver;
BOOL mbShowPopup;
protected:
virtual void Paint( const Rectangle& rRect);
virtual void KeyInput( const KeyEvent& rKeyEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual void DataChanged( const DataChangedEvent& aData);
virtual void LoseFocus();
virtual void RequestHelp(const HelpEvent &rEvt);
public:
PostItTxt(Window* pParent, WinBits nBits);
~PostItTxt();
virtual void GetFocus();
void SetTextView( OutlinerView* aEditView ) { mpOutlinerView = aEditView; }
DECL_LINK( WindowEventListener, VclSimpleEvent* );
DECL_LINK( OnlineSpellCallback, SpellCallbackInfo*);
};
typedef sal_Int64 SwPostItBits;
#define PB_Preview ((SwPostItBits)0x00000001)
class SwPostIt : public Window
{
private:
SwView* mpView;
sdr::overlay::OverlayManager* pOverlayManager;
OutlinerView* mpOutlinerView;
Outliner* mpOutliner;
PostItTxt* mpPostItTxt;
MultiLineEdit* mpMeta;
ScrollBar* mpVScrollbar;
SwFmtFld* mpFmtFld;
SwPostItField* mpFld;
SwPostItAnkor* mpAnkor;
SwPostItShadow* mpShadow;
SwPostItMgr* mpMgr;
bool mbMeta;
bool mbReadonly;
Color mColorAnkor;
Color mColorDark;
Color mColorLight;
basegfx::B2DPolygon aPopupTriangle;
Rectangle mRectMetaButton;
PopupMenu* mpButtonPopup;
sal_Int32 mnEventId;
bool mbMarginSide;
Rectangle mPosSize;
SwRect mAnkorRect;
long mPageBorder;
SwPostItBits nFlags;
Color mChangeColor;
SwPostItHelper::SwLayoutStatus mStatus;
protected:
virtual void DataChanged( const DataChangedEvent& aEvent);
virtual void LoseFocus();
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void Paint( const Rectangle& rRect);
virtual void GetFocus();
void SetPosAndSize();
void SetSizePixel( const Size& rNewSize );
DECL_LINK(ModifyHdl, void*);
DECL_LINK(ScrollHdl, ScrollBar*);
void InitControls();
void CheckMetaText();
public:
SwPostIt( Window* pParent, WinBits nBits,SwFmtFld* aField,SwPostItMgr* aMgr,SwPostItBits aBits);
~SwPostIt();
void SetSize( const Size& rNewSize );
void SetPosSizePixelRect( long nX, long nY,long nWidth, long nHeight,const SwRect &aRect,const long PageBorder);
void TranslateTopPosition(const long aAmount);
void SetPostItText();
PostItTxt* PostItText() { return mpPostItTxt;}
ScrollBar* Scrollbar() { return mpVScrollbar;}
SwPostItAnkor* Ankor() { return mpAnkor;}
SwPostItShadow* Shadow() { return mpShadow;}
OutlinerView* View() { return mpOutlinerView;}
SwView* DocView() { return mpView;}
Outliner* Engine() { return mpOutliner;}
SwPostItMgr* Mgr() { return mpMgr; }
SwFmtFld* Field() { return mpFmtFld; }
SwRect GetAnkorRect() { return mAnkorRect; }
String GetAuthor() const;
SwEditWin* EditWin();
long GetPostItTextHeight();
void UpdateData();
void SwitchToPostIt(USHORT aDirection);
//void SwitchToPostIt(bool aDirection);
void SwitchToFieldPos(bool bAfter = true);
void ExecuteCommand(USHORT aSlot);
void Delete();
void HidePostIt();
void DoResize();
void ResizeIfNeccessary(long aOldHeight, long aNewHeight);
void SetVirtualPosSize( const Point& aPoint, const Size& aSize);
const Point VirtualPos() { return mPosSize.TopLeft(); }
const Size VirtualSize() { return mPosSize.GetSize(); }
void ShowAnkorOnly(const Point &aPoint);
void ShowNote();
void HideNote();
void ResetAttributes();
void SetLanguage(const SvxLanguageItem aNewItem);
void SetMarginSide(bool aMarginSide);
void SetReadonly(BOOL bSet);
BOOL IsReadOnly() { return mbReadonly;}
bool IsPreview() { return nFlags & PB_Preview;}
void SetColor(Color aColorDark,Color aColorLight, Color aColorAnkor);
Color ColorDark() { return mColorDark; }
Color ColorLight() { return mColorLight; }
void Rescale();
void SetShadowState(ShadowState bState);
sal_Int32 GetMetaHeight();
sal_Int32 GetMinimumSizeWithMeta();
sal_Int32 GetMinimumSizeWithoutMeta();
sal_Int32 GetMetaButtonAreaWidth();
sal_Int32 GetScrollbarWidth();
void SetSpellChecking();
void SetChangeTracking(SwPostItHelper::SwLayoutStatus& aStatus,Color aColor);
SwPostItHelper::SwLayoutStatus GetStatus() { return mStatus; }
Color GetChangeColor() { return mChangeColor; }
void ActivatePostIt();
void DeactivatePostIt();
};
#endif
<commit_msg>INTEGRATION: CWS notes6 (1.6.24); FILE MERGED 2008/06/26 21:46:52 mod 1.6.24.3: shell refactoring 2008/06/25 14:03:10 mod 1.6.24.2: #i91057# 2008/06/10 18:29:37 mod 1.6.24.1: notes5 import<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: postit.hxx,v $
*
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _POSTIT_HXX
#define _POSTIT_HXX
#include <postithelper.hxx>
#include <vcl/window.hxx>
#include <swrect.hxx>
#include <svx/sdr/overlay/overlayobject.hxx>
#include <vcl/lineinfo.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <svx/editstat.hxx>
class SwPostItMgr;
class SwPostItField;
class SwFmtFld;
class OutlinerView;
class Outliner;
class ScrollBar;
class SwEditWin;
class SwView;
class SwPostIt;
class Edit;
class MultiLineEdit;
class PopupMenu;
class SvxLanguageItem;
class SwPostItAnkor: public sdr::overlay::OverlayObjectWithBasePosition
{
protected:
/* 6------------7
1 /
/4\ ---------------5
2 - 3
*/
basegfx::B2DPoint maSecondPosition;
basegfx::B2DPoint maThirdPosition;
basegfx::B2DPoint maFourthPosition;
basegfx::B2DPoint maFifthPosition;
basegfx::B2DPoint maSixthPosition;
basegfx::B2DPoint maSeventhPosition;
// helpers to fill and reset geometry
void implEnsureGeometry();
void implResetGeometry();
// helpers to paint geometry
void implDrawGeometry(OutputDevice& rOutputDevice, Color aColor, double fOffX, double fOffY);
Color implBlendColor(const Color aOriginal, sal_Int16 nChange);
virtual void drawGeometry(OutputDevice& rOutputDevice);
virtual void createBaseRange(OutputDevice& rOutputDevice);
private:
// object's geometry
basegfx::B2DPolygon maTriangle;
basegfx::B2DPolygon maLine;
basegfx::B2DPolygon maLineTop;
LineInfo mLineInfo;
unsigned long mHeight;
bool mbShadowedEffect;
public:
SwPostItAnkor(const basegfx::B2DPoint& rBasePos,
const basegfx::B2DPoint& rSecondPos,
const basegfx::B2DPoint& rThirdPos,
const basegfx::B2DPoint& rFourthPos,
const basegfx::B2DPoint& rFifthPos,
const basegfx::B2DPoint& rSixthPos,
const basegfx::B2DPoint& rSeventhPos,
Color aBaseColor,
const LineInfo &aLineInfo,
bool bShadowedEffect);
virtual ~SwPostItAnkor();
const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; }
const basegfx::B2DPoint& GetThirdPosition() const { return maThirdPosition; }
const basegfx::B2DPoint& GetFourthPosition() const { return maFourthPosition; }
const basegfx::B2DPoint& GetFifthPosition() const { return maFifthPosition; }
const basegfx::B2DPoint& GetSixthPosition() const { return maSixthPosition; }
const basegfx::B2DPoint& GetSeventhPosition() const { return maSeventhPosition; }
void SetAllPosition(const basegfx::B2DPoint& rPoint1, const basegfx::B2DPoint& rPoint2, const basegfx::B2DPoint& rPoint3,
const basegfx::B2DPoint& rPoint4, const basegfx::B2DPoint& rPoint5, const basegfx::B2DPoint& rPoint6, const basegfx::B2DPoint& rPoint7);
void SetTriPosition(const basegfx::B2DPoint& rPoint1,const basegfx::B2DPoint& rPoint2,const basegfx::B2DPoint& rPoint3,
const basegfx::B2DPoint& rPoint4,const basegfx::B2DPoint& rPoint5);
void SetSixthPosition(const basegfx::B2DPoint& rNew);
void SetSeventhPosition(const basegfx::B2DPoint& rNew);
void SetLineInfo(const LineInfo &aLineInfo);
void SetHeight(const unsigned long aHeight) {mHeight = aHeight;};
bool getShadowedEffect() const { return mbShadowedEffect; }
virtual void Trigger(sal_uInt32 nTime);
//sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol) const;
// transform object coordinates. Transforms maBasePosition
// and invalidates on change
virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};
enum ShadowState {SS_NORMAL, SS_VIEW, SS_EDIT};
class SwPostItShadow: public sdr::overlay::OverlayObjectWithBasePosition
{
protected:
virtual void drawGeometry(OutputDevice& rOutputDevice);
virtual void createBaseRange(OutputDevice& rOutputDevice);
private:
basegfx::B2DPoint maSecondPosition;
ShadowState mShadowState;
public:
SwPostItShadow(const basegfx::B2DPoint& rBasePos, const basegfx::B2DPoint& rSecondPosition, Color aBaseColor,ShadowState aState);
virtual ~SwPostItShadow();
void SetShadowState(ShadowState aState);
ShadowState GetShadowState() {return mShadowState;}
const basegfx::B2DPoint& GetSecondPosition() const { return maSecondPosition; }
void SetSecondPosition(const basegfx::B2DPoint& rNew);
void SetPosition(const basegfx::B2DPoint& rPoint1,const basegfx::B2DPoint& rPoint2);
virtual void Trigger(sal_uInt32 nTime);
virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};
class PostItTxt : public Window
{
private:
OutlinerView* mpOutlinerView;
SwPostIt* mpPostIt;
bool mMouseOver;
BOOL mbShowPopup;
protected:
virtual void Paint( const Rectangle& rRect);
virtual void KeyInput( const KeyEvent& rKeyEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual void DataChanged( const DataChangedEvent& aData);
virtual void LoseFocus();
virtual void RequestHelp(const HelpEvent &rEvt);
public:
PostItTxt(Window* pParent, WinBits nBits);
~PostItTxt();
virtual void GetFocus();
void SetTextView( OutlinerView* aEditView ) { mpOutlinerView = aEditView; }
DECL_LINK( WindowEventListener, VclSimpleEvent* );
DECL_LINK( OnlineSpellCallback, SpellCallbackInfo*);
};
typedef sal_Int64 SwPostItBits;
#define PB_Preview ((SwPostItBits)0x00000001)
class SwPostIt : public Window
{
private:
SwView* mpView;
sdr::overlay::OverlayManager* pOverlayManager;
OutlinerView* mpOutlinerView;
Outliner* mpOutliner;
PostItTxt* mpPostItTxt;
MultiLineEdit* mpMeta;
ScrollBar* mpVScrollbar;
SwFmtFld* mpFmtFld;
SwPostItField* mpFld;
SwPostItAnkor* mpAnkor;
SwPostItShadow* mpShadow;
SwPostItMgr* mpMgr;
bool mbMeta;
bool mbReadonly;
Color mColorAnkor;
Color mColorDark;
Color mColorLight;
basegfx::B2DPolygon aPopupTriangle;
Rectangle mRectMetaButton;
PopupMenu* mpButtonPopup;
sal_Int32 mnEventId;
bool mbMarginSide;
Rectangle mPosSize;
SwRect mAnkorRect;
long mPageBorder;
SwPostItBits nFlags;
Color mChangeColor;
SwPostItHelper::SwLayoutStatus mStatus;
protected:
virtual void DataChanged( const DataChangedEvent& aEvent);
virtual void LoseFocus();
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void Paint( const Rectangle& rRect);
virtual void GetFocus();
void SetPosAndSize();
void SetSizePixel( const Size& rNewSize );
DECL_LINK(ModifyHdl, void*);
DECL_LINK(ScrollHdl, ScrollBar*);
void InitControls();
void CheckMetaText();
public:
SwPostIt( Window* pParent, WinBits nBits,SwFmtFld* aField,SwPostItMgr* aMgr,SwPostItBits aBits);
~SwPostIt();
void SetSize( const Size& rNewSize );
void SetPosSizePixelRect( long nX, long nY,long nWidth, long nHeight,const SwRect &aRect,const long PageBorder);
void TranslateTopPosition(const long aAmount);
void SetPostItText();
PostItTxt* PostItText() { return mpPostItTxt;}
ScrollBar* Scrollbar() { return mpVScrollbar;}
SwPostItAnkor* Ankor() { return mpAnkor;}
SwPostItShadow* Shadow() { return mpShadow;}
OutlinerView* View() { return mpOutlinerView;}
SwView* DocView() { return mpView;}
Outliner* Engine() { return mpOutliner;}
SwPostItMgr* Mgr() { return mpMgr; }
SwFmtFld* Field() { return mpFmtFld; }
SwRect GetAnkorRect() { return mAnkorRect; }
String GetAuthor() const;
SwEditWin* EditWin();
long GetPostItTextHeight();
void UpdateData();
void SwitchToPostIt(USHORT aDirection);
//void SwitchToPostIt(bool aDirection);
void SwitchToFieldPos(bool bAfter = true);
void ExecuteCommand(USHORT aSlot);
void Delete();
void HidePostIt();
void DoResize();
void ResizeIfNeccessary(long aOldHeight, long aNewHeight);
void SetScrollbar();
void SetVirtualPosSize( const Point& aPoint, const Size& aSize);
const Point VirtualPos() { return mPosSize.TopLeft(); }
const Size VirtualSize() { return mPosSize.GetSize(); }
void ShowAnkorOnly(const Point &aPoint);
void ShowNote();
void HideNote();
void ResetAttributes();
void SetLanguage(const SvxLanguageItem aNewItem);
void SetMarginSide(bool aMarginSide);
void SetReadonly(BOOL bSet);
BOOL IsReadOnly() { return mbReadonly;}
bool IsPreview() { return nFlags & PB_Preview;}
void SetColor(Color aColorDark,Color aColorLight, Color aColorAnkor);
Color ColorDark() { return mColorDark; }
Color ColorLight() { return mColorLight; }
void Rescale();
void SetShadowState(ShadowState bState);
sal_Int32 GetMetaHeight();
sal_Int32 GetMinimumSizeWithMeta();
sal_Int32 GetMinimumSizeWithoutMeta();
sal_Int32 GetMetaButtonAreaWidth();
sal_Int32 GetScrollbarWidth();
void SetSpellChecking();
void ToggleInsMode();
void SetChangeTracking(SwPostItHelper::SwLayoutStatus& aStatus,Color aColor);
SwPostItHelper::SwLayoutStatus GetStatus() { return mStatus; }
Color GetChangeColor() { return mChangeColor; }
void ActivatePostIt();
void DeactivatePostIt();
};
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <fstream>
#include "Matrix.hpp"
<commit_msg>Update Matrix.cpp<commit_after>#include <iostream>
#include "stack.hpp"
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/IServiceId.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/update/DefaultUpdateRequirement.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ServiceId>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMinimalVersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>register ts over ip transport in factory<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_IP
# include <stingray/platform/ip/tuners/TsOverIpTransport.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/IServiceId.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/update/DefaultUpdateRequirement.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_IP
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ServiceId>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMinimalVersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/ca/BasicSubscriptionLease.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/ca/SubscriptionBundle.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp3/Mp3MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/ContentDescription.h>
#include <stingray/mpeg/PvrDescription.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/EmuScanPerformerFactory.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/pushvod/pushvod_emu/PushVODEmulationMovie.h>
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanPerformerFactory.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/LybidScanPerformerFactory.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/TricolorScanPerformerFactory.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/BuiltinTimeSourceId.h>
#include <stingray/time/TDTTimeSourceId.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionLease);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Subscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionBundle);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BuiltinTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TDTTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>Added Dre4Provider to _FactoryClasses.cpp<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/ca/BasicSubscriptionLease.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/ca/SubscriptionBundle.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp3/Mp3MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/ContentDescription.h>
#include <stingray/mpeg/PvrDescription.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/EmuScanPerformerFactory.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/pushvod/pushvod_emu/PushVODEmulationMovie.h>
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DefaultScanPerformerFactory.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/LybidScanPerformerFactory.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/TricolorScanPerformerFactory.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/BuiltinTimeSourceId.h>
#include <stingray/time/TDTTimeSourceId.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionLease);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Provider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Subscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionBundle);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BuiltinTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TDTTimeSourceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::GenericRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSpaceLeftRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoStorageRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ProtectedChannelRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::StorageLostError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4SubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>update factory classes<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/RecordErrors.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/ca/BissConditionalAccess.h>
#include <stingray/ca/DreSubscription.h>
#include <stingray/crypto/DefaultCertificateExtension.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/SubstreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/CertificateRevocationList.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegSubstreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/StatisticChannelInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/time/TransportsTimeSourceObtainer.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::GenericRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSpaceLeftRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoStorageRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ProtectedChannelRecordError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::StorageLostError);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4SubscriptionClass);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultCertificateExtension);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/PushVideoOnDemand.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/StreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/ChannelViewingEventInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>register receiver traits classes<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/PushVideoOnDemand.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/StreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/ChannelViewingEventInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/PushVideoOnDemand.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/StreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/ChannelViewingEventInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>register activation intens classes<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/PushVideoOnDemand.h>
#include <stingray/app/activation_manager/ActivationIntent.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/crypto/PlainCipherKey.h>
#include <stingray/details/IReceiverTrait.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/StreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#ifdef PLATFORM_STAPI
# include <stingray/platform/stapi/crypto/HardwareCipherKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TerrestrialScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/terrestrial/TerrestrialServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/stats/ChannelViewingEventInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/VersionRequirement.h>
#include <stingray/update/system/CopyFile.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/MountFilesystem.h>
#include <stingray/update/system/MoveFile.h>
#include <stingray/update/system/RemoveFile.h>
#include <stingray/update/system/UnmountFilesystem.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
#ifdef PLATFORM_STAPI
TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|> |
<commit_before>// Copyright (C) 2015 National ICT Australia (NICTA)
//
// 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/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
#include <armadillo>
#include "catch.hpp"
using namespace arma;
TEST_CASE("fn_det_1")
{
mat A =
"\
0.061198 0.201990 0.019678 -0.493936 -0.126745 0.051408;\
0.437242 0.058956 -0.149362 -0.045465 0.296153 0.035437;\
-0.492474 -0.031309 0.314156 0.419733 0.068317 -0.454499;\
0.336352 0.411541 0.458476 -0.393139 -0.135040 0.373833;\
0.239585 -0.428913 -0.406953 -0.291020 -0.353768 0.258704;\
";
REQUIRE( det(A(0,0,size(0,0))) == Approx(+1.0 ) );
REQUIRE( det(A(0,0,size(1,1))) == Approx(+0.0611980000000000) );
REQUIRE( det(A(0,0,size(2,2))) == Approx(-0.0847105222920000) );
REQUIRE( det(A(0,0,size(3,3))) == Approx(-0.0117387923199772) );
REQUIRE( det(A(0,0,size(4,4))) == Approx(+0.0126070917169865) );
REQUIRE( det(A(0,0,size(5,5))) == Approx(+0.0100409091117668) );
REQUIRE_THROWS( det(A) );
}
TEST_CASE("fn_det_2")
{
mat A = toeplitz(linspace(1,5,6));
REQUIRE( det(A) == Approx(-31.45728) );
mat B(6, 6, fill::zeros); B.diag() = linspace(1,5,6);
REQUIRE( det(B) == Approx(334.152) );
REQUIRE( det(diagmat(B)) == Approx(334.152) );
mat C(5,6, fill::randu);
REQUIRE_THROWS( det(C) );
REQUIRE_THROWS( det(diagmat(C)) );
}
TEST_CASE("fn_det_")
{
mat A = toeplitz(linspace(1,5,6));
double val;
double sign;
log_det(val, sign, A);
REQUIRE( val == Approx(3.44863) );
REQUIRE( sign == Approx(-1.0) );
REQUIRE( (std::exp(val)*sign) == Approx( det(A) ) );
mat B(5,6, fill::randu);
REQUIRE_THROWS( log_det(val, sign, B) );
}
<commit_msg>fix test name<commit_after>// Copyright (C) 2015 National ICT Australia (NICTA)
//
// 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/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
#include <armadillo>
#include "catch.hpp"
using namespace arma;
TEST_CASE("fn_det_1")
{
mat A =
"\
0.061198 0.201990 0.019678 -0.493936 -0.126745 0.051408;\
0.437242 0.058956 -0.149362 -0.045465 0.296153 0.035437;\
-0.492474 -0.031309 0.314156 0.419733 0.068317 -0.454499;\
0.336352 0.411541 0.458476 -0.393139 -0.135040 0.373833;\
0.239585 -0.428913 -0.406953 -0.291020 -0.353768 0.258704;\
";
REQUIRE( det(A(0,0,size(0,0))) == Approx(+1.0 ) );
REQUIRE( det(A(0,0,size(1,1))) == Approx(+0.0611980000000000) );
REQUIRE( det(A(0,0,size(2,2))) == Approx(-0.0847105222920000) );
REQUIRE( det(A(0,0,size(3,3))) == Approx(-0.0117387923199772) );
REQUIRE( det(A(0,0,size(4,4))) == Approx(+0.0126070917169865) );
REQUIRE( det(A(0,0,size(5,5))) == Approx(+0.0100409091117668) );
REQUIRE_THROWS( det(A) );
}
TEST_CASE("fn_det_2")
{
mat A = toeplitz(linspace(1,5,6));
REQUIRE( det(A) == Approx(-31.45728) );
mat B(6, 6, fill::zeros); B.diag() = linspace(1,5,6);
REQUIRE( det(B) == Approx(334.152) );
REQUIRE( det(diagmat(B)) == Approx(334.152) );
mat C(5,6, fill::randu);
REQUIRE_THROWS( det(C) );
REQUIRE_THROWS( det(diagmat(C)) );
}
TEST_CASE("fn_det_3")
{
mat A = toeplitz(linspace(1,5,6));
double val;
double sign;
log_det(val, sign, A);
REQUIRE( val == Approx(3.44863) );
REQUIRE( sign == Approx(-1.0) );
REQUIRE( (std::exp(val)*sign) == Approx( det(A) ) );
mat B(5,6, fill::randu);
REQUIRE_THROWS( log_det(val, sign, B) );
}
<|endoftext|> |
<commit_before>#define FUTURE_TRACE 0
#include <cps/future.h>
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
using namespace cps;
using namespace std;
#define ok CHECK
SCENARIO("future as a shared pointer", "[shared]") {
GIVEN("an empty future") {
auto f = future<int>::create_shared("some future");
ok(!f->is_ready());
ok(!f->is_done());
ok(!f->is_failed());
ok(!f->is_cancelled());
ok(f->current_state() == "pending");
ok(f->label() == "some future");
WHEN("marked as done") {
f->done(123);
THEN("state is correct") {
ok( f->is_ready());
ok( f->is_done());
ok(!f->is_failed());
ok(!f->is_cancelled());
ok(f->current_state() == "done");
}
AND_THEN("elapsed is nonzero") {
ok(f->elapsed().count() > 0);
}
AND_THEN("description looks about right") {
ok(string::npos != f->describe().find("some future (done), "));
}
auto weak = std::weak_ptr<cps::future<int>>(f);
f.reset();
AND_THEN("shared_ptr goes away correctly") {
ok(weak.expired());
}
}
WHEN("marked as failed") {
f->fail("...");
THEN("state is correct") {
ok( f->is_ready());
ok(!f->is_done());
ok( f->is_failed());
ok(!f->is_cancelled());
ok(f->current_state() == "failed");
}
AND_THEN("elapsed is nonzero") {
ok(f->elapsed().count() > 0);
}
AND_THEN("description looks about right") {
ok(string::npos != f->describe().find("some future (failed), "));
}
auto weak = std::weak_ptr<cps::future<int>>(f);
f.reset();
AND_THEN("shared_ptr goes away correctly") {
ok(weak.expired());
}
}
WHEN("marked as cancelled") {
f->cancel();
THEN("state is correct") {
ok( f->is_ready());
ok(!f->is_done());
ok(!f->is_failed());
ok( f->is_cancelled());
ok(f->current_state() == "cancelled");
}
AND_THEN("elapsed is nonzero") {
ok(f->elapsed().count() > 0);
}
AND_THEN("description looks about right") {
ok(string::npos != f->describe().find("some future (cancelled), "));
}
auto weak = std::weak_ptr<cps::future<int>>(f);
f.reset();
AND_THEN("shared_ptr goes away correctly") {
ok(weak.expired());
}
}
}
}
SCENARIO("failed future handling", "[shared]") {
GIVEN("a failed future") {
auto f = future<int>::create_shared();
f->fail("some reason");
REQUIRE( f->is_ready());
REQUIRE(!f->is_done());
REQUIRE( f->is_failed());
REQUIRE(!f->is_cancelled());
WHEN("we call ->failure_reason") {
auto reason = f->failure_reason();
THEN("we get the failure reason") {
ok(reason == "some reason");
}
}
WHEN("we call ->value") {
THEN("we get an exception") {
REQUIRE_THROWS(f->value());
}
}
}
}
SCENARIO("successful future handling", "[shared]") {
GIVEN("a completed future") {
auto f = future<string>::create_shared();
f->done("all good");
REQUIRE( f->is_ready());
REQUIRE( f->is_done());
REQUIRE(!f->is_failed());
REQUIRE(!f->is_cancelled());
WHEN("we call ->failure_reason") {
THEN("we get an exception") {
REQUIRE_THROWS(f->failure_reason());
}
}
WHEN("we call ->value") {
THEN("we get the original value") {
ok(f->value() == "all good");
}
}
}
}
SCENARIO("cancelled future handling", "[shared]") {
GIVEN("a cancelled future") {
auto f = future<string>::create_shared();
f->cancel();
REQUIRE( f->is_ready());
REQUIRE(!f->is_done());
REQUIRE(!f->is_failed());
REQUIRE( f->is_cancelled());
WHEN("we call ->failure_reason") {
THEN("we get an exception") {
REQUIRE_THROWS(f->failure_reason());
}
}
WHEN("we call ->value") {
THEN("we get an exception") {
REQUIRE_THROWS(f->value());
}
}
}
}
SCENARIO("needs_all", "[composed][shared]") {
GIVEN("an empty list of futures") {
auto na = needs_all();
WHEN("we check status") {
THEN("it reports as complete") {
ok(na->is_done());
}
}
}
GIVEN("some pending futures") {
auto f1 = future<int>::create_shared();
auto f2 = future<int>::create_shared();
auto na = needs_all(f1, f2);
ok(!na->is_ready());
ok(!na->is_done());
ok(!na->is_failed());
ok(!na->is_cancelled());
WHEN("f1 marked as done") {
f1->done(123);
THEN("needs_all is still pending") {
ok(!na->is_ready());
}
}
WHEN("f2 marked as done") {
f2->done(123);
THEN("needs_all is still pending") {
ok(!na->is_ready());
}
}
WHEN("all dependents marked as done") {
f1->done(34);
f2->done(123);
THEN("needs_all is complete") {
ok(na->is_done());
}
}
WHEN("a dependent fails") {
f1->fail("...");
THEN("needs_all is now failed") {
ok(na->is_failed());
}
}
WHEN("a dependent is cancelled") {
f1->cancel();
THEN("needs_all is now failed") {
ok(na->is_failed());
}
}
}
}
SCENARIO("we can chain futures via ->then", "[composed][shared]") {
GIVEN("a simple ->then chain") {
auto f1 = cps::future<string>::create_shared();
auto f2 = cps::future<string>::create_shared();
bool called = false;
auto seq = f1->then([f2, &called](string v) -> shared_ptr<future<string>> {
ok(v == "input");
called = true;
return f2;
});
WHEN("dependent completes") {
f1->done("input");
THEN("our callback was called") {
ok(called);
}
AND_THEN("->then result is unchanged") {
ok(!seq->is_ready());
}
}
WHEN("dependent and inner future complete") {
f1->done("input");
THEN("our callback was called") {
ok(called);
}
f2->done("inner");
AND_THEN("->then is now complete") {
ok(seq->is_done());
}
AND_THEN("and propagated the value") {
ok(seq->value() == "inner");
}
}
WHEN("dependent fails") {
f1->fail("breakage");
THEN("our callback was not called") {
ok(!called);
}
AND_THEN("->then result is also failed") {
ok(seq->is_failed());
}
AND_THEN("failure reason was propagated") {
ok(seq->failure_reason() == f1->failure_reason());
}
}
WHEN("sequence future is cancelled") {
seq->cancel();
THEN("our callback was not called") {
ok(!called);
}
AND_THEN("->then result is cancelled") {
ok(seq->is_cancelled());
}
AND_THEN("leaf future was not touched") {
ok(!f1->is_ready());
}
}
}
GIVEN("a simple ->then chain with else handler") {
auto initial = cps::future<string>::create_shared();
auto success = cps::future<string>::create_shared();
auto failure = cps::future<string>::create_shared();
bool called = false;
bool errored = false;
auto seq = initial->then([success, &called](string v) -> shared_ptr<future<string>> {
ok(v == "input");
called = true;
return success;
}, [failure, &errored](string) {
errored = true;
return failure;
});
WHEN("dependent completes") {
auto weak = std::weak_ptr<cps::future<string>>(failure);
initial->done("input");
THEN("our callback was called") {
ok(called);
ok(!errored);
}
AND_THEN("->then result is unchanged") {
ok(!seq->is_ready());
}
failure.reset();
AND_THEN("other future pointer expired") {
ok(weak.expired());
}
}
WHEN("dependent fails") {
auto weak = std::weak_ptr<cps::future<string>>(success);
initial->fail("error");
THEN("our error handler was called") {
ok(!called);
ok(errored);
}
AND_THEN("->then result is unchanged") {
ok(!seq->is_ready());
}
success.reset();
AND_THEN("other future pointer expired") {
ok(weak.expired());
}
}
WHEN("->then cancelled") {
auto weak1 = std::weak_ptr<cps::future<string>>(success);
auto weak2 = std::weak_ptr<cps::future<string>>(failure);
seq->cancel();
THEN("neither handler was called") {
ok(!called);
ok(!errored);
}
AND_THEN("->then is marked as cancelled") {
ok(seq->is_cancelled());
}
success.reset();
failure.reset();
// FIXME These should expire immediately,
// we should not have to mark the initial
// future as ready first
initial->cancel();
AND_THEN("both future pointers expired") {
ok(weak1.expired());
ok(weak2.expired());
}
}
}
}
<commit_msg>We have main.cpp, no need for this any more<commit_after>#define FUTURE_TRACE 0
#include <cps/future.h>
#include "catch.hpp"
using namespace cps;
using namespace std;
#define ok CHECK
SCENARIO("future as a shared pointer", "[shared]") {
GIVEN("an empty future") {
auto f = future<int>::create_shared("some future");
ok(!f->is_ready());
ok(!f->is_done());
ok(!f->is_failed());
ok(!f->is_cancelled());
ok(f->current_state() == "pending");
ok(f->label() == "some future");
WHEN("marked as done") {
f->done(123);
THEN("state is correct") {
ok( f->is_ready());
ok( f->is_done());
ok(!f->is_failed());
ok(!f->is_cancelled());
ok(f->current_state() == "done");
}
AND_THEN("elapsed is nonzero") {
ok(f->elapsed().count() > 0);
}
AND_THEN("description looks about right") {
ok(string::npos != f->describe().find("some future (done), "));
}
auto weak = std::weak_ptr<cps::future<int>>(f);
f.reset();
AND_THEN("shared_ptr goes away correctly") {
ok(weak.expired());
}
}
WHEN("marked as failed") {
f->fail("...");
THEN("state is correct") {
ok( f->is_ready());
ok(!f->is_done());
ok( f->is_failed());
ok(!f->is_cancelled());
ok(f->current_state() == "failed");
}
AND_THEN("elapsed is nonzero") {
ok(f->elapsed().count() > 0);
}
AND_THEN("description looks about right") {
ok(string::npos != f->describe().find("some future (failed), "));
}
auto weak = std::weak_ptr<cps::future<int>>(f);
f.reset();
AND_THEN("shared_ptr goes away correctly") {
ok(weak.expired());
}
}
WHEN("marked as cancelled") {
f->cancel();
THEN("state is correct") {
ok( f->is_ready());
ok(!f->is_done());
ok(!f->is_failed());
ok( f->is_cancelled());
ok(f->current_state() == "cancelled");
}
AND_THEN("elapsed is nonzero") {
ok(f->elapsed().count() > 0);
}
AND_THEN("description looks about right") {
ok(string::npos != f->describe().find("some future (cancelled), "));
}
auto weak = std::weak_ptr<cps::future<int>>(f);
f.reset();
AND_THEN("shared_ptr goes away correctly") {
ok(weak.expired());
}
}
}
}
SCENARIO("failed future handling", "[shared]") {
GIVEN("a failed future") {
auto f = future<int>::create_shared();
f->fail("some reason");
REQUIRE( f->is_ready());
REQUIRE(!f->is_done());
REQUIRE( f->is_failed());
REQUIRE(!f->is_cancelled());
WHEN("we call ->failure_reason") {
auto reason = f->failure_reason();
THEN("we get the failure reason") {
ok(reason == "some reason");
}
}
WHEN("we call ->value") {
THEN("we get an exception") {
REQUIRE_THROWS(f->value());
}
}
}
}
SCENARIO("successful future handling", "[shared]") {
GIVEN("a completed future") {
auto f = future<string>::create_shared();
f->done("all good");
REQUIRE( f->is_ready());
REQUIRE( f->is_done());
REQUIRE(!f->is_failed());
REQUIRE(!f->is_cancelled());
WHEN("we call ->failure_reason") {
THEN("we get an exception") {
REQUIRE_THROWS(f->failure_reason());
}
}
WHEN("we call ->value") {
THEN("we get the original value") {
ok(f->value() == "all good");
}
}
}
}
SCENARIO("cancelled future handling", "[shared]") {
GIVEN("a cancelled future") {
auto f = future<string>::create_shared();
f->cancel();
REQUIRE( f->is_ready());
REQUIRE(!f->is_done());
REQUIRE(!f->is_failed());
REQUIRE( f->is_cancelled());
WHEN("we call ->failure_reason") {
THEN("we get an exception") {
REQUIRE_THROWS(f->failure_reason());
}
}
WHEN("we call ->value") {
THEN("we get an exception") {
REQUIRE_THROWS(f->value());
}
}
}
}
SCENARIO("needs_all", "[composed][shared]") {
GIVEN("an empty list of futures") {
auto na = needs_all();
WHEN("we check status") {
THEN("it reports as complete") {
ok(na->is_done());
}
}
}
GIVEN("some pending futures") {
auto f1 = future<int>::create_shared();
auto f2 = future<int>::create_shared();
auto na = needs_all(f1, f2);
ok(!na->is_ready());
ok(!na->is_done());
ok(!na->is_failed());
ok(!na->is_cancelled());
WHEN("f1 marked as done") {
f1->done(123);
THEN("needs_all is still pending") {
ok(!na->is_ready());
}
}
WHEN("f2 marked as done") {
f2->done(123);
THEN("needs_all is still pending") {
ok(!na->is_ready());
}
}
WHEN("all dependents marked as done") {
f1->done(34);
f2->done(123);
THEN("needs_all is complete") {
ok(na->is_done());
}
}
WHEN("a dependent fails") {
f1->fail("...");
THEN("needs_all is now failed") {
ok(na->is_failed());
}
}
WHEN("a dependent is cancelled") {
f1->cancel();
THEN("needs_all is now failed") {
ok(na->is_failed());
}
}
}
}
SCENARIO("we can chain futures via ->then", "[composed][shared]") {
GIVEN("a simple ->then chain") {
auto f1 = cps::future<string>::create_shared();
auto f2 = cps::future<string>::create_shared();
bool called = false;
auto seq = f1->then([f2, &called](string v) -> shared_ptr<future<string>> {
ok(v == "input");
called = true;
return f2;
});
WHEN("dependent completes") {
f1->done("input");
THEN("our callback was called") {
ok(called);
}
AND_THEN("->then result is unchanged") {
ok(!seq->is_ready());
}
}
WHEN("dependent and inner future complete") {
f1->done("input");
THEN("our callback was called") {
ok(called);
}
f2->done("inner");
AND_THEN("->then is now complete") {
ok(seq->is_done());
}
AND_THEN("and propagated the value") {
ok(seq->value() == "inner");
}
}
WHEN("dependent fails") {
f1->fail("breakage");
THEN("our callback was not called") {
ok(!called);
}
AND_THEN("->then result is also failed") {
ok(seq->is_failed());
}
AND_THEN("failure reason was propagated") {
ok(seq->failure_reason() == f1->failure_reason());
}
}
WHEN("sequence future is cancelled") {
seq->cancel();
THEN("our callback was not called") {
ok(!called);
}
AND_THEN("->then result is cancelled") {
ok(seq->is_cancelled());
}
AND_THEN("leaf future was not touched") {
ok(!f1->is_ready());
}
}
}
GIVEN("a simple ->then chain with else handler") {
auto initial = cps::future<string>::create_shared();
auto success = cps::future<string>::create_shared();
auto failure = cps::future<string>::create_shared();
bool called = false;
bool errored = false;
auto seq = initial->then([success, &called](string v) -> shared_ptr<future<string>> {
ok(v == "input");
called = true;
return success;
}, [failure, &errored](string) {
errored = true;
return failure;
});
WHEN("dependent completes") {
auto weak = std::weak_ptr<cps::future<string>>(failure);
initial->done("input");
THEN("our callback was called") {
ok(called);
ok(!errored);
}
AND_THEN("->then result is unchanged") {
ok(!seq->is_ready());
}
failure.reset();
AND_THEN("other future pointer expired") {
ok(weak.expired());
}
}
WHEN("dependent fails") {
auto weak = std::weak_ptr<cps::future<string>>(success);
initial->fail("error");
THEN("our error handler was called") {
ok(!called);
ok(errored);
}
AND_THEN("->then result is unchanged") {
ok(!seq->is_ready());
}
success.reset();
AND_THEN("other future pointer expired") {
ok(weak.expired());
}
}
WHEN("->then cancelled") {
auto weak1 = std::weak_ptr<cps::future<string>>(success);
auto weak2 = std::weak_ptr<cps::future<string>>(failure);
seq->cancel();
THEN("neither handler was called") {
ok(!called);
ok(!errored);
}
AND_THEN("->then is marked as cancelled") {
ok(seq->is_cancelled());
}
success.reset();
failure.reset();
// FIXME These should expire immediately,
// we should not have to mark the initial
// future as ready first
initial->cancel();
AND_THEN("both future pointers expired") {
ok(weak1.expired());
ok(weak2.expired());
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>add Event debug msg<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
* tests/api/operations_test.cpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <[email protected]>
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/api/allgather.hpp>
#include <c7a/api/bootstrap.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/generate.hpp>
#include <c7a/api/generate_from_file.hpp>
#include <c7a/api/lop_node.hpp>
#include <c7a/api/prefixsum.hpp>
#include <c7a/api/read.hpp>
#include <c7a/api/size.hpp>
#include <c7a/api/write.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <functional>
#include <random>
#include <string>
#include <vector>
using namespace c7a;
using c7a::api::Context;
using c7a::api::DIARef;
TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) {
std::vector<std::string> self = { "127.0.0.1:1234" };
core::JobManager jobMan;
jobMan.Connect(0, net::Endpoint::ParseEndpointList(self), 1);
Context ctx(jobMan, 0);
std::random_device random_device;
std::default_random_engine generator(random_device());
std::uniform_int_distribution<int> distribution(1000, 10000);
size_t generate_size = distribution(generator);
auto input = GenerateFromFile(
ctx,
"test1",
[](const std::string& line) {
return std::stoi(line);
},
generate_size);
size_t writer_size = 0;
input.Map(
[&writer_size](const int& item) {
//file contains ints between 1 and 15
//fails if wrong integer is generated
EXPECT_GE(item, 1);
EXPECT_GE(16, item);
writer_size++;
return std::to_string(item) + "\n";
})
.WriteToFileSystem("test1.out");
ASSERT_EQ(generate_size, writer_size);
}
TEST(Operations, ReadAndAllGatherElementsCorrect) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = ReadLines(
ctx,
"test1",
[](const std::string& line) {
return std::stoi(line);
});
std::vector<int> out_vec = integers.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_EQ(element, i++);
}
ASSERT_EQ((size_t)16, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, MapResultsCorrectChangingType) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index + 1;
},
16);
std::function<double(int)> double_elements =
[](int in) {
return (double)2 * in;
};
auto doubled = integers.Map(double_elements);
std::vector<double> out_vec = doubled.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_DOUBLE_EQ(element, (i++ *2));
}
ASSERT_EQ(16u, out_vec.size());
static_assert(std::is_same<decltype(doubled)::ValueType, double>::value, "DIA must be double");
static_assert(std::is_same<decltype(doubled)::StackInput, int>::value, "Node must be int");
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, FlatMapResultsCorrectChangingType) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index;
},
16);
auto flatmap_double = [](int in, auto emit) {
emit((double)2 * in);
emit((double)2 * (in + 16));
};
auto doubled = integers.FlatMap<double>(flatmap_double);
std::vector<double> out_vec = doubled.AllGather();
ASSERT_EQ(32u, out_vec.size());
for (size_t i = 0; i != out_vec.size() / 2; ++i) {
ASSERT_DOUBLE_EQ(out_vec[2 * i + 0], 2 * i);
ASSERT_DOUBLE_EQ(out_vec[2 * i + 1], 2 * (i + 16));
}
static_assert(
std::is_same<decltype(doubled)::ValueType, double>::value,
"DIA must be double");
static_assert(
std::is_same<decltype(doubled)::StackInput, int>::value,
"Node must be int");
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, PrefixSumCorrectResults) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& input) {
return input + 1;
},
16);
auto prefixsums = integers.PrefixSum();
std::vector<size_t> out_vec = prefixsums.AllGather();
size_t ctr = 0;
for (size_t i = 0; i < out_vec.size(); i++) {
ctr += i + 1;
ASSERT_EQ(out_vec[i], ctr);
}
ASSERT_EQ((size_t)16, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, PrefixSumFacultyCorrectResults) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& input) {
return input + 1;
},
10);
auto prefixsums = integers.PrefixSum(
[](size_t in1, size_t in2) {
return in1 * in2;
}, 1);
std::vector<size_t> out_vec = prefixsums.AllGather();
size_t ctr = 1;
for (size_t i = 0; i < out_vec.size(); i++) {
ctr *= i + 1;
ASSERT_EQ(out_vec[i], ctr);
}
ASSERT_EQ(10u, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, FilterResultsCorrectly) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) {
return (int)index + 1;
},
16);
std::function<bool(int)> even = [](int in) {
return (in % 2 == 0);
};
auto doubled = integers.Filter(even);
std::vector<int> out_vec = doubled.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_DOUBLE_EQ(element, (i++ *2));
}
ASSERT_EQ(8u, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, DIARefCasting) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto even = [](int in) {
return (in % 2 == 0);
};
auto integers = Generate(
ctx,
[](const size_t& index) {
return (int)index + 1;
},
16);
DIARef<int> doubled = integers.Filter(even).Collapse();
std::vector<int> out_vec = doubled.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_DOUBLE_EQ(element, (i++ *2));
}
ASSERT_EQ(8u, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, ForLoop) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index;
},
16);
auto flatmap_duplicate = [](int in, auto emit) {
emit(in);
emit(in);
};
auto map_multiply = [](int in) {
return 2 * in;
};
DIARef<int> squares = integers.Collapse();
// run loop four times, inflating DIA of 16 items -> 256
for (size_t i = 0; i < 4; ++i) {
auto pairs = squares.FlatMap(flatmap_duplicate);
auto multiplied = pairs.Map(map_multiply);
squares = multiplied.Collapse();
}
std::vector<int> out_vec = squares.AllGather();
ASSERT_EQ(256u, out_vec.size());
for (size_t i = 0; i != 256; ++i) {
ASSERT_EQ(out_vec[i], (int)(16 * (i / 16)));
}
ASSERT_EQ(256u, squares.Size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, WhileLoop) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index;
},
16);
auto flatmap_duplicate = [](int in, auto emit) {
emit(in);
emit(in);
};
auto map_multiply = [](int in) {
return 2 * in;
};
DIARef<int> squares = integers.Collapse();
unsigned int sum = 0;
// run loop four times, inflating DIA of 16 items -> 256
while (sum < 256) {
auto pairs = squares.FlatMap(flatmap_duplicate);
auto multiplied = pairs.Map(map_multiply);
squares = multiplied.Collapse();
sum = squares.Size();
}
std::vector<int> out_vec = squares.AllGather();
ASSERT_EQ(256u, out_vec.size());
for (size_t i = 0; i != 256; ++i) {
ASSERT_EQ(out_vec[i], (int)(16 * (i / 16)));
}
ASSERT_EQ(256u, squares.Size());
};
// api::ExecuteLocalTests(start_func);
api::ExecuteLocalThreadsTCP(1, 8080, start_func);
}
/******************************************************************************/
<commit_msg>Adding simple test for Generate() node.<commit_after>/*******************************************************************************
* tests/api/operations_test.cpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <[email protected]>
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/api/allgather.hpp>
#include <c7a/api/bootstrap.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/generate.hpp>
#include <c7a/api/generate_from_file.hpp>
#include <c7a/api/lop_node.hpp>
#include <c7a/api/prefixsum.hpp>
#include <c7a/api/read.hpp>
#include <c7a/api/size.hpp>
#include <c7a/api/write.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <functional>
#include <random>
#include <string>
#include <vector>
using namespace c7a;
using c7a::api::Context;
using c7a::api::DIARef;
TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) {
std::vector<std::string> self = { "127.0.0.1:1234" };
core::JobManager jobMan;
jobMan.Connect(0, net::Endpoint::ParseEndpointList(self), 1);
Context ctx(jobMan, 0);
std::random_device random_device;
std::default_random_engine generator(random_device());
std::uniform_int_distribution<int> distribution(1000, 10000);
size_t generate_size = distribution(generator);
auto input = GenerateFromFile(
ctx,
"test1",
[](const std::string& line) {
return std::stoi(line);
},
generate_size);
size_t writer_size = 0;
input.Map(
[&writer_size](const int& item) {
//file contains ints between 1 and 15
//fails if wrong integer is generated
EXPECT_GE(item, 1);
EXPECT_GE(16, item);
writer_size++;
return std::to_string(item) + "\n";
})
.WriteToFileSystem("test1.out");
ASSERT_EQ(generate_size, writer_size);
}
TEST(Operations, ReadAndAllGatherElementsCorrect) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = ReadLines(
ctx,
"test1",
[](const std::string& line) {
return std::stoi(line);
});
std::vector<int> out_vec = integers.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_EQ(element, i++);
}
ASSERT_EQ((size_t)16, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, GenerateIntegers) {
static const size_t test_size = 1000;
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) { return index; },
test_size);
std::vector<size_t> out_vec = integers.AllGather();
ASSERT_EQ(test_size, out_vec.size());
for (size_t i = 0; i < test_size; ++i) {
ASSERT_EQ(i, out_vec[i]);
}
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, MapResultsCorrectChangingType) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index + 1;
},
16);
std::function<double(int)> double_elements =
[](int in) {
return (double)2 * in;
};
auto doubled = integers.Map(double_elements);
std::vector<double> out_vec = doubled.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_DOUBLE_EQ(element, (i++ *2));
}
ASSERT_EQ(16u, out_vec.size());
static_assert(std::is_same<decltype(doubled)::ValueType, double>::value, "DIA must be double");
static_assert(std::is_same<decltype(doubled)::StackInput, int>::value, "Node must be int");
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, FlatMapResultsCorrectChangingType) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index;
},
16);
auto flatmap_double = [](int in, auto emit) {
emit((double)2 * in);
emit((double)2 * (in + 16));
};
auto doubled = integers.FlatMap<double>(flatmap_double);
std::vector<double> out_vec = doubled.AllGather();
ASSERT_EQ(32u, out_vec.size());
for (size_t i = 0; i != out_vec.size() / 2; ++i) {
ASSERT_DOUBLE_EQ(out_vec[2 * i + 0], 2 * i);
ASSERT_DOUBLE_EQ(out_vec[2 * i + 1], 2 * (i + 16));
}
static_assert(
std::is_same<decltype(doubled)::ValueType, double>::value,
"DIA must be double");
static_assert(
std::is_same<decltype(doubled)::StackInput, int>::value,
"Node must be int");
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, PrefixSumCorrectResults) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& input) {
return input + 1;
},
16);
auto prefixsums = integers.PrefixSum();
std::vector<size_t> out_vec = prefixsums.AllGather();
size_t ctr = 0;
for (size_t i = 0; i < out_vec.size(); i++) {
ctr += i + 1;
ASSERT_EQ(out_vec[i], ctr);
}
ASSERT_EQ((size_t)16, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, PrefixSumFacultyCorrectResults) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& input) {
return input + 1;
},
10);
auto prefixsums = integers.PrefixSum(
[](size_t in1, size_t in2) {
return in1 * in2;
}, 1);
std::vector<size_t> out_vec = prefixsums.AllGather();
size_t ctr = 1;
for (size_t i = 0; i < out_vec.size(); i++) {
ctr *= i + 1;
ASSERT_EQ(out_vec[i], ctr);
}
ASSERT_EQ(10u, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, FilterResultsCorrectly) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) {
return (int)index + 1;
},
16);
std::function<bool(int)> even = [](int in) {
return (in % 2 == 0);
};
auto doubled = integers.Filter(even);
std::vector<int> out_vec = doubled.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_DOUBLE_EQ(element, (i++ *2));
}
ASSERT_EQ(8u, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, DIARefCasting) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto even = [](int in) {
return (in % 2 == 0);
};
auto integers = Generate(
ctx,
[](const size_t& index) {
return (int)index + 1;
},
16);
DIARef<int> doubled = integers.Filter(even).Collapse();
std::vector<int> out_vec = doubled.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_DOUBLE_EQ(element, (i++ *2));
}
ASSERT_EQ(8u, out_vec.size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, ForLoop) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index;
},
16);
auto flatmap_duplicate = [](int in, auto emit) {
emit(in);
emit(in);
};
auto map_multiply = [](int in) {
return 2 * in;
};
DIARef<int> squares = integers.Collapse();
// run loop four times, inflating DIA of 16 items -> 256
for (size_t i = 0; i < 4; ++i) {
auto pairs = squares.FlatMap(flatmap_duplicate);
auto multiplied = pairs.Map(map_multiply);
squares = multiplied.Collapse();
}
std::vector<int> out_vec = squares.AllGather();
ASSERT_EQ(256u, out_vec.size());
for (size_t i = 0; i != 256; ++i) {
ASSERT_EQ(out_vec[i], (int)(16 * (i / 16)));
}
ASSERT_EQ(256u, squares.Size());
};
api::ExecuteLocalTests(start_func);
}
TEST(Operations, WhileLoop) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = Generate(
ctx,
[](const size_t& index) -> int {
return index;
},
16);
auto flatmap_duplicate = [](int in, auto emit) {
emit(in);
emit(in);
};
auto map_multiply = [](int in) {
return 2 * in;
};
DIARef<int> squares = integers.Collapse();
unsigned int sum = 0;
// run loop four times, inflating DIA of 16 items -> 256
while (sum < 256) {
auto pairs = squares.FlatMap(flatmap_duplicate);
auto multiplied = pairs.Map(map_multiply);
squares = multiplied.Collapse();
sum = squares.Size();
}
std::vector<int> out_vec = squares.AllGather();
ASSERT_EQ(256u, out_vec.size());
for (size_t i = 0; i != 256; ++i) {
ASSERT_EQ(out_vec[i], (int)(16 * (i / 16)));
}
ASSERT_EQ(256u, squares.Size());
};
// api::ExecuteLocalTests(start_func);
api::ExecuteLocalThreadsTCP(1, 8080, start_func);
}
/******************************************************************************/
<|endoftext|> |
<commit_before>//
// Author: Michael Cameron
// Email: [email protected]
//
// Libraries Include
#include "libraries.h"
// Local Includes
#include "constants.h"
#include "mathtypes.h"
#include "vector.h"
#include "geometry.h"
#include "brush.h"
#include "q3mapparser.h"
const std::string& GetBrushString(std::string& _rOutput, const TPolyBrush& _krBrush)
{
if(_krBrush.m_Faces.size() > 0)
{
std::stringstream ssOutput;
ssOutput << std::fixed;
ssOutput << "brush" << std::endl;
ssOutput << "\tvertices" << std::endl;
for(size_t i = 0; i < _krBrush.m_Vertices.size(); ++i)
{
ssOutput << "\t\t" << _krBrush.m_Vertices[i].m_dX << " " << _krBrush.m_Vertices[i].m_dZ << " " << -_krBrush.m_Vertices[i].m_dY << " " << std::endl;
}
ssOutput << "\tfaces" << std::endl;
for(size_t i = 0; i < _krBrush.m_Faces.size(); ++i)
{
ssOutput << "\t\t" << _krBrush.m_Faces[i].m_dTexCoordU << " "
<< _krBrush.m_Faces[i].m_dTexCoordV << " "
<< _krBrush.m_Faces[i].m_dTexScaleU << " "
<< _krBrush.m_Faces[i].m_dTexScaleV << " "
<< _krBrush.m_Faces[i].m_dTexRotation;
for(size_t j = 0; j < _krBrush.m_Faces[i].m_Indices.size(); ++j)
{
ssOutput << " " << _krBrush.m_Faces[i].m_Indices[j];
}
ssOutput << " " << _krBrush.m_Faces[i].m_Material << std::endl;
}
_rOutput = ssOutput.str();
}
return(_rOutput);
}
int main(const int _kiArgC, const char** _kppcArgv)
{
if(_kiArgC != 3)
{
return(3);
}
CQ3MapParser Parser;
const bool kbSuccess = Parser.ParseQ3Map(_kppcArgv[1]);
if(!kbSuccess)
{
return(1);
}
else
{
std::ofstream OutFile;
OutFile.open(_kppcArgv[2]);
if(!OutFile.is_open())
{
return(2);
}
std::vector<TPolyBrush> PolyBrushes(Parser.m_Brushes.size());
for(size_t i = 0; i < Parser.m_Brushes.size(); ++i)
{
const std::vector<std::vector<TVectorD3>> kPolysUnsorted = GetPolyFaces(std::vector<std::vector<TVectorD3>>(), Parser.m_Brushes[i]);
std::vector<std::vector<TVectorD3>> SortedPolys;
for(size_t j = 0; j < Parser.m_Brushes[i].m_Faces.size(); ++j)
{
if(kPolysUnsorted[j].size() >= 3)
{
const TVectorD3 kFaceNormal = GetFaceNormal(TVectorD3(), j, Parser.m_Brushes[i]);
const std::vector<TVectorD3> kSortedFaceVerts = SortFaceVerts(std::vector<TVectorD3>(), kPolysUnsorted[j], kFaceNormal, true);
SortedPolys.push_back(kSortedFaceVerts);
}
else
{
SortedPolys.push_back(std::vector<TVectorD3>());
}
}
std::vector<TVectorD3> UnmergedFaceVerts;
for(size_t n = 0; n < SortedPolys.size(); ++n)
{
for(size_t m = 0; m < SortedPolys[n].size(); ++m)
{
UnmergedFaceVerts.push_back(SortedPolys[n][m]);
}
}
std::vector<TVectorD3> MergedFaceVerts;
for(size_t n = 0; n < UnmergedFaceVerts.size(); ++n)
{
bool bUnique = true;
for(size_t m = 0; m < MergedFaceVerts.size(); ++m)
{
if(math::Equal(UnmergedFaceVerts[n], MergedFaceVerts[m], s_kdEpsilon))
{
bUnique = false;
}
}
if(bUnique)
{
MergedFaceVerts.push_back(UnmergedFaceVerts[n]);
}
}
PolyBrushes[i].m_Vertices = MergedFaceVerts;
PolyBrushes[i].m_Faces.resize(Parser.m_Brushes[i].m_Faces.size());
for(size_t j = 0; j < PolyBrushes[i].m_Faces.size(); ++j)
{
PolyBrushes[i].m_Faces[j].m_Material = Parser.m_Brushes[i].m_Faces[j].m_Material;
PolyBrushes[i].m_Faces[j].m_dTexCoordU = (double)Parser.m_Brushes[i].m_Faces[j].m_iTexCoordU;
PolyBrushes[i].m_Faces[j].m_dTexCoordV = (double)Parser.m_Brushes[i].m_Faces[j].m_iTexCoordV;
PolyBrushes[i].m_Faces[j].m_dTexScaleU = (double)Parser.m_Brushes[i].m_Faces[j].m_dTexScaleU;
PolyBrushes[i].m_Faces[j].m_dTexScaleV = (double)Parser.m_Brushes[i].m_Faces[j].m_dTexScaleV;
PolyBrushes[i].m_Faces[j].m_dTexRotation = (double)Parser.m_Brushes[i].m_Faces[j].m_dTexRotation;
PolyBrushes[i].m_Faces[j].m_Indices.resize(SortedPolys[j].size());
for(size_t n = 0; n < PolyBrushes[i].m_Faces[j].m_Indices.size(); ++n)
{
for(size_t m = 0; m < PolyBrushes[i].m_Vertices.size(); ++m)
{
if(math::Equal(SortedPolys[j][n], PolyBrushes[i].m_Vertices[m], s_kdEpsilon))
{
PolyBrushes[i].m_Faces[j].m_Indices[n] = m;
}
}
}
}
}
OutFile << "reflex map version 6\n"
<< "entity\n"
<< "\ttype WorldSpawn\n"
<< "\tColourXRGB32 clearColor ffffff\n"
<< "\tColourXRGB32 worldColor0 0\n"
<< "\tColourXRGB32 worldColor1 0\n";
for(size_t i = 0; i < PolyBrushes.size(); ++i)
{
const std::string BrushString = GetBrushString(std::string(), PolyBrushes[i]);
OutFile << BrushString;
}
OutFile.close();
}
return(0);
}<commit_msg>fixed coordinate transformation<commit_after>//
// Author: Michael Cameron
// Email: [email protected]
//
// Libraries Include
#include "libraries.h"
// Local Includes
#include "constants.h"
#include "mathtypes.h"
#include "vector.h"
#include "geometry.h"
#include "brush.h"
#include "q3mapparser.h"
const std::string& GetBrushString(std::string& _rOutput, const TPolyBrush& _krBrush)
{
if(_krBrush.m_Faces.size() > 0)
{
std::stringstream ssOutput;
ssOutput << std::fixed;
ssOutput << "brush" << std::endl;
ssOutput << "\tvertices" << std::endl;
for(size_t i = 0; i < _krBrush.m_Vertices.size(); ++i)
{
ssOutput << "\t\t" << _krBrush.m_Vertices[i].m_dX << " " << _krBrush.m_Vertices[i].m_dZ << " " << _krBrush.m_Vertices[i].m_dY << " " << std::endl;
}
ssOutput << "\tfaces" << std::endl;
for(size_t i = 0; i < _krBrush.m_Faces.size(); ++i)
{
ssOutput << "\t\t" << _krBrush.m_Faces[i].m_dTexCoordU << " "
<< _krBrush.m_Faces[i].m_dTexCoordV << " "
<< _krBrush.m_Faces[i].m_dTexScaleU << " "
<< _krBrush.m_Faces[i].m_dTexScaleV << " "
<< _krBrush.m_Faces[i].m_dTexRotation;
for(size_t j = 0; j < _krBrush.m_Faces[i].m_Indices.size(); ++j)
{
ssOutput << " " << _krBrush.m_Faces[i].m_Indices[j];
}
ssOutput << " " << _krBrush.m_Faces[i].m_Material << std::endl;
}
_rOutput = ssOutput.str();
}
return(_rOutput);
}
int main(const int _kiArgC, const char** _kppcArgv)
{
if(_kiArgC != 3)
{
return(3);
}
CQ3MapParser Parser;
const bool kbSuccess = Parser.ParseQ3Map(_kppcArgv[1]);
if(!kbSuccess)
{
return(1);
}
else
{
std::ofstream OutFile;
OutFile.open(_kppcArgv[2]);
if(!OutFile.is_open())
{
return(2);
}
std::vector<TPolyBrush> PolyBrushes(Parser.m_Brushes.size());
for(size_t i = 0; i < Parser.m_Brushes.size(); ++i)
{
const std::vector<std::vector<TVectorD3>> kPolysUnsorted = GetPolyFaces(std::vector<std::vector<TVectorD3>>(), Parser.m_Brushes[i]);
std::vector<std::vector<TVectorD3>> SortedPolys;
for(size_t j = 0; j < Parser.m_Brushes[i].m_Faces.size(); ++j)
{
if(kPolysUnsorted[j].size() >= 3)
{
const TVectorD3 kFaceNormal = GetFaceNormal(TVectorD3(), j, Parser.m_Brushes[i]);
const std::vector<TVectorD3> kSortedFaceVerts = SortFaceVerts(std::vector<TVectorD3>(), kPolysUnsorted[j], kFaceNormal, false);
SortedPolys.push_back(kSortedFaceVerts);
}
else
{
SortedPolys.push_back(std::vector<TVectorD3>());
}
}
std::vector<TVectorD3> UnmergedFaceVerts;
for(size_t n = 0; n < SortedPolys.size(); ++n)
{
for(size_t m = 0; m < SortedPolys[n].size(); ++m)
{
UnmergedFaceVerts.push_back(SortedPolys[n][m]);
}
}
std::vector<TVectorD3> MergedFaceVerts;
for(size_t n = 0; n < UnmergedFaceVerts.size(); ++n)
{
bool bUnique = true;
for(size_t m = 0; m < MergedFaceVerts.size(); ++m)
{
if(math::Equal(UnmergedFaceVerts[n], MergedFaceVerts[m], s_kdEpsilon))
{
bUnique = false;
}
}
if(bUnique)
{
MergedFaceVerts.push_back(UnmergedFaceVerts[n]);
}
}
PolyBrushes[i].m_Vertices = MergedFaceVerts;
PolyBrushes[i].m_Faces.resize(Parser.m_Brushes[i].m_Faces.size());
for(size_t j = 0; j < PolyBrushes[i].m_Faces.size(); ++j)
{
PolyBrushes[i].m_Faces[j].m_Material = Parser.m_Brushes[i].m_Faces[j].m_Material;
PolyBrushes[i].m_Faces[j].m_dTexCoordU = (double)Parser.m_Brushes[i].m_Faces[j].m_iTexCoordU;
PolyBrushes[i].m_Faces[j].m_dTexCoordV = (double)Parser.m_Brushes[i].m_Faces[j].m_iTexCoordV;
PolyBrushes[i].m_Faces[j].m_dTexScaleU = (double)Parser.m_Brushes[i].m_Faces[j].m_dTexScaleU;
PolyBrushes[i].m_Faces[j].m_dTexScaleV = (double)Parser.m_Brushes[i].m_Faces[j].m_dTexScaleV;
PolyBrushes[i].m_Faces[j].m_dTexRotation = (double)Parser.m_Brushes[i].m_Faces[j].m_dTexRotation;
PolyBrushes[i].m_Faces[j].m_Indices.resize(SortedPolys[j].size());
for(size_t n = 0; n < PolyBrushes[i].m_Faces[j].m_Indices.size(); ++n)
{
for(size_t m = 0; m < PolyBrushes[i].m_Vertices.size(); ++m)
{
if(math::Equal(SortedPolys[j][n], PolyBrushes[i].m_Vertices[m], s_kdEpsilon))
{
PolyBrushes[i].m_Faces[j].m_Indices[n] = m;
}
}
}
}
}
OutFile << "reflex map version 6\n"
<< "entity\n"
<< "\ttype WorldSpawn\n"
<< "\tColourXRGB32 clearColor ffffff\n"
<< "\tColourXRGB32 worldColor0 0\n"
<< "\tColourXRGB32 worldColor1 0\n";
for(size_t i = 0; i < PolyBrushes.size(); ++i)
{
const std::string BrushString = GetBrushString(std::string(), PolyBrushes[i]);
OutFile << BrushString;
}
OutFile.close();
}
return(0);
}<|endoftext|> |
<commit_before>/***************************************************************
QGVCore
Copyright (c) 2014, Bergont Nicolas, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 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.
***************************************************************/
#include <QGVNode.h>
#include <QGVCore.h>
#include <QGVScene.h>
#include <QGVGraphPrivate.h>
#include <QGVNodePrivate.h>
#include <QDebug>
#include <QPainter>
QGVNode::QGVNode(QGVNodePrivate *node, QGVScene *scene): _scene(scene), _node(node)
{
setFlag (QGraphicsItem::ItemIsSelectable, true);
setFlag (QGraphicsItem::ItemIsMovable, true);
setFlag (QGraphicsItem::ItemSendsGeometryChanges, true);
}
QGVNode::~QGVNode()
{
_scene->removeItem(this);
delete _node;
}
QString QGVNode::label() const
{
return getAttribute("label");
}
void QGVNode::setLabel(const QString &label)
{
setAttribute("label", label);
}
QRectF QGVNode::boundingRect() const
{
return _path.boundingRect();
}
void QGVNode::paint(QPainter * painter, const QStyleOptionGraphicsItem *, QWidget *)
{
painter->save();
painter->setPen(_pen);
if(isSelected())
{
QBrush tbrush(_brush);
tbrush.setColor(tbrush.color().darker(120));
painter->setBrush(tbrush);
}
else
painter->setBrush(_brush);
painter->drawPath(_path);
painter->setPen(QGVCore::toColor(getAttribute("labelfontcolor")));
const QRectF rect = boundingRect().adjusted(2,2,-2,-2); //Margin
if(_icon.isNull())
{
painter->drawText(rect, Qt::AlignCenter , QGVNode::label());
}
else
{
painter->drawText(rect.adjusted(0,0,0, -rect.height()*2/3), Qt::AlignCenter , QGVNode::label());
const QRectF img_rect = rect.adjusted(0, rect.height()/3,0, 0);
QImage img = _icon.scaled(img_rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
painter->drawImage(img_rect.topLeft() + QPointF((img_rect.width() - img.rect().width())/2, 0), img);
}
painter->restore();
}
void QGVNode::setAttribute(const QString &name, const QString &value)
{
char empty[] = "";
agsafeset(_node->node(), name.toLocal8Bit().data(), value.toLocal8Bit().data(), empty);
}
QString QGVNode::getAttribute(const QString &name) const
{
char* value = agget(_node->node(), name.toLocal8Bit().data());
if(value)
return value;
return QString();
}
QString QGVNode::posToAttributeString() const
{
qreal gheight = QGVCore::graphHeight(_scene->_graph->graph());
qreal width = ND_width(_node->node())*DotDefaultDPI;
qreal height = ND_height(_node->node())*DotDefaultDPI;
return QGVCore::qtToGvPos (QGVCore::centerToOrigin (pos(), -width, -height), gheight);
}
void QGVNode::setIcon(const QImage &icon)
{
_icon = icon;
}
QVariant QGVNode::itemChange (GraphicsItemChange change, const QVariant & value)
{
if (change == ItemPositionChange && _scene) {
// value is the new position.
QString oldStr = getAttribute(QString::fromLocal8Bit("pos"));
qreal gheight = QGVCore::graphHeight(_scene->_graph->graph());
QPointF newPos = value.toPointF();
qreal width = ND_width(_node->node())*DotDefaultDPI;
qreal height = ND_height(_node->node())*DotDefaultDPI;
QString newStr = QGVCore::qtToGvPos (QGVCore::centerToOrigin (newPos, -width, -height), gheight);
if (!newStr.isEmpty()) {
if (oldStr != newStr) {
setAttribute ("pos", newStr.toLocal8Bit().data());
}
return newPos;
}
} else if (change == ItemPositionHasChanged && _scene) {
emit _scene->nodeChanged (this);
return value;
}
return QGraphicsItem::itemChange(change, value);
}
void QGVNode::updateLayout()
{
prepareGeometryChange();
qreal width = ND_width(_node->node())*DotDefaultDPI;
qreal height = ND_height(_node->node())*DotDefaultDPI;
//Node Position (center)
qreal gheight = QGVCore::graphHeight(_scene->_graph->graph());
setPos(QGVCore::centerToOrigin(QGVCore::toPoint(ND_coord(_node->node()), gheight), width, height));
//Node on top
setZValue(1);
//Node path
_path = QGVCore::toPath(ND_shape(_node->node())->name, (polygon_t*)ND_shape_info(_node->node()), width, height);
_pen.setWidth(1);
_brush.setStyle(QGVCore::toBrushStyle(getAttribute("style")));
_brush.setColor(QGVCore::toColor(getAttribute("fillcolor")));
_pen.setColor(QGVCore::toColor(getAttribute("color")));
setToolTip(getAttribute("tooltip"));
}
<commit_msg>Node honors the 'style' attribute<commit_after>/***************************************************************
QGVCore
Copyright (c) 2014, Bergont Nicolas, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 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.
***************************************************************/
#include <QGVNode.h>
#include <QGVCore.h>
#include <QGVScene.h>
#include <QGVGraphPrivate.h>
#include <QGVNodePrivate.h>
#include <QDebug>
#include <QPainter>
QGVNode::QGVNode(QGVNodePrivate *node, QGVScene *scene): _scene(scene), _node(node)
{
setFlag (QGraphicsItem::ItemIsSelectable, true);
setFlag (QGraphicsItem::ItemIsMovable, true);
setFlag (QGraphicsItem::ItemSendsGeometryChanges, true);
}
QGVNode::~QGVNode()
{
_scene->removeItem(this);
delete _node;
}
QString QGVNode::label() const
{
return getAttribute("label");
}
void QGVNode::setLabel(const QString &label)
{
setAttribute("label", label);
}
QRectF QGVNode::boundingRect() const
{
return _path.boundingRect();
}
void QGVNode::paint(QPainter * painter, const QStyleOptionGraphicsItem *, QWidget *)
{
painter->save();
painter->setPen(_pen);
if(isSelected())
{
QBrush tbrush(_brush);
tbrush.setColor(tbrush.color().darker(120));
painter->setBrush(tbrush);
}
else
painter->setBrush(_brush);
painter->drawPath(_path);
painter->setPen(QGVCore::toColor(getAttribute("labelfontcolor")));
const QRectF rect = boundingRect().adjusted(2,2,-2,-2); //Margin
if(_icon.isNull())
{
painter->drawText(rect, Qt::AlignCenter , QGVNode::label());
}
else
{
painter->drawText(rect.adjusted(0,0,0, -rect.height()*2/3), Qt::AlignCenter , QGVNode::label());
const QRectF img_rect = rect.adjusted(0, rect.height()/3,0, 0);
QImage img = _icon.scaled(img_rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
painter->drawImage(img_rect.topLeft() + QPointF((img_rect.width() - img.rect().width())/2, 0), img);
}
painter->restore();
}
void QGVNode::setAttribute(const QString &name, const QString &value)
{
char empty[] = "";
agsafeset(_node->node(), name.toLocal8Bit().data(), value.toLocal8Bit().data(), empty);
}
QString QGVNode::getAttribute(const QString &name) const
{
char* value = agget(_node->node(), name.toLocal8Bit().data());
if(value)
return value;
return QString();
}
QString QGVNode::posToAttributeString() const
{
qreal gheight = QGVCore::graphHeight(_scene->_graph->graph());
qreal width = ND_width(_node->node())*DotDefaultDPI;
qreal height = ND_height(_node->node())*DotDefaultDPI;
return QGVCore::qtToGvPos (QGVCore::centerToOrigin (pos(), -width, -height), gheight);
}
void QGVNode::setIcon(const QImage &icon)
{
_icon = icon;
}
QVariant QGVNode::itemChange (GraphicsItemChange change, const QVariant & value)
{
if (change == ItemPositionChange && _scene) {
// value is the new position.
QString oldStr = getAttribute(QString::fromLocal8Bit("pos"));
qreal gheight = QGVCore::graphHeight(_scene->_graph->graph());
QPointF newPos = value.toPointF();
qreal width = ND_width(_node->node())*DotDefaultDPI;
qreal height = ND_height(_node->node())*DotDefaultDPI;
QString newStr = QGVCore::qtToGvPos (QGVCore::centerToOrigin (newPos, -width, -height), gheight);
if (!newStr.isEmpty()) {
if (oldStr != newStr) {
setAttribute ("pos", newStr.toLocal8Bit().data());
}
return newPos;
}
} else if (change == ItemPositionHasChanged && _scene) {
emit _scene->nodeChanged (this);
return value;
}
return QGraphicsItem::itemChange(change, value);
}
void QGVNode::updateLayout()
{
prepareGeometryChange();
qreal width = ND_width(_node->node())*DotDefaultDPI;
qreal height = ND_height(_node->node())*DotDefaultDPI;
//Node Position (center)
qreal gheight = QGVCore::graphHeight(_scene->_graph->graph());
setPos(QGVCore::centerToOrigin(QGVCore::toPoint(ND_coord(_node->node()), gheight), width, height));
//Node on top
setZValue(1);
//Node path
_path = QGVCore::toPath(ND_shape(_node->node())->name, (polygon_t*)ND_shape_info(_node->node()), width, height);
_pen.setWidth(1);
_brush.setStyle(QGVCore::toBrushStyle(getAttribute("style")));
_brush.setColor(QGVCore::toColor(getAttribute("fillcolor")));
_pen.setStyle(QGVCore::toPenStyle(getAttribute("style")));
_pen.setColor(QGVCore::toColor(getAttribute("color")));
setToolTip(getAttribute("tooltip"));
}
<|endoftext|> |
<commit_before>#ifndef VEXCL_GATHER_HPP
#define VEXCL_GATHER_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/gather.hpp
* \author Denis Demidov <[email protected]>
* \brief Gather scattered points from OpenCL device vector.
*/
#include <vector>
#include <numeric>
#include <cassert>
#include <vexcl/operations.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/vector_view.hpp>
namespace vex {
namespace detail {
template <class T>
class index_partition {
public:
index_partition(
const std::vector<backend::command_queue> &q,
size_t size, std::vector<size_t> indices
)
: queue(q), ptr(q.size() + 1, 0),
idx(q.size()), val(q.size())
{
assert(std::is_sorted(indices.begin(), indices.end()));
std::vector<size_t> part = partition(size, queue);
column_owner owner(part);
for(auto i = indices.begin(); i != indices.end(); ++i) {
size_t d = owner(*i);
*i -= part[d];
++ptr[d + 1];
}
std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());
for(unsigned d = 0; d < queue.size(); d++) {
if (size_t n = ptr[d + 1] - ptr[d]) {
val[d] = backend::device_vector<T>(queue[d], n, static_cast<const T*>(0));
idx[d] = backend::device_vector<size_t>(
queue[d], n, &indices[ptr[d]], backend::MEM_READ_ONLY);
}
}
for(unsigned d = 0; d < queue.size(); d++)
if (ptr[d + 1] - ptr[d]) queue[d].finish();
}
protected:
std::vector<backend::command_queue> queue;
std::vector< size_t > ptr;
std::vector< backend::device_vector<size_t> > idx;
std::vector< backend::device_vector<T> > val;
};
} // namespace detail
/// Gathers vector elements at specified indices.
template <typename T>
class gather : protected detail::index_partition<T> {
public:
/// Constructor.
/**
* \param queue VexCL context.
* \param indices Indices of elements to be gathered.
*/
gather(
const std::vector<backend::command_queue> &q,
size_t size, std::vector<size_t> indices
) : Base(q, size, indices)
{}
/// Gather elements of device vector into host vector.
template <class HostVector>
void operator()(const vex::vector<T> &src, HostVector &dst) {
using namespace detail;
static kernel_cache cache;
for(unsigned d = 0; d < Base::queue.size(); d++) {
if (size_t n = Base::ptr[d + 1] - Base::ptr[d]) {
vector<T> v(Base::queue[d], Base::val[d]);
vector<T> s(Base::queue[d], src(d));
vector<size_t> i(Base::queue[d], Base::idx[d]);
v = permutation(i)(s);
Base::val[d].read(Base::queue[d], 0, n, &dst[Base::ptr[d]]);
}
}
for(unsigned d = 0; d < Base::queue.size(); d++)
if (Base::ptr[d + 1] - Base::ptr[d]) Base::queue[d].finish();
}
private:
typedef detail::index_partition<T> Base;
};
/// Scatters vector elements to specified indices.
template <typename T>
class scatter : protected detail::index_partition<T> {
public:
/// Constructor.
/**
* \param queue VexCL context.
* \param indices Indices of elements to be gathered.
*/
scatter(
const std::vector<backend::command_queue> &q,
size_t size, std::vector<size_t> indices
) : Base(q, size, indices)
{}
/// Scatter elements of host vector to device vector.
template <class HostVector>
void operator()(const HostVector &src, vex::vector<T> &dst) {
using namespace detail;
static kernel_cache cache;
for(unsigned d = 0; d < Base::queue.size(); d++) {
if (size_t n = Base::ptr[d + 1] - Base::ptr[d]) {
Base::val[d].write(Base::queue[d], 0, n, &src[Base::ptr[d]]);
vector<T> v(Base::queue[d], Base::val[d]);
vector<T> s(Base::queue[d], dst(d));
vector<size_t> i(Base::queue[d], Base::idx[d]);
permutation(i)(s) = v;
}
}
for(unsigned d = 0; d < Base::queue.size(); d++)
if (Base::ptr[d + 1] - Base::ptr[d]) Base::queue[d].finish();
}
private:
typedef detail::index_partition<T> Base;
};
} // namespace vex
#endif
<commit_msg>Indices in gather have to be sorted only in multi-device contexts<commit_after>#ifndef VEXCL_GATHER_HPP
#define VEXCL_GATHER_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/gather.hpp
* \author Denis Demidov <[email protected]>
* \brief Gather scattered points from OpenCL device vector.
*/
#include <vector>
#include <numeric>
#include <cassert>
#include <vexcl/operations.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/vector_view.hpp>
namespace vex {
namespace detail {
template <class T>
class index_partition {
public:
index_partition(
const std::vector<backend::command_queue> &q,
size_t size, std::vector<size_t> &indices
)
: queue(q), ptr(q.size() + 1, 0),
idx(q.size()), val(q.size())
{
assert(queue.size() == 1 || std::is_sorted(indices.begin(), indices.end()));
std::vector<size_t> part = partition(size, queue);
column_owner owner(part);
for(auto i = indices.begin(); i != indices.end(); ++i) {
size_t d = owner(*i);
*i -= part[d];
++ptr[d + 1];
}
std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());
for(unsigned d = 0; d < queue.size(); d++) {
if (size_t n = ptr[d + 1] - ptr[d]) {
val[d] = backend::device_vector<T>(queue[d], n, static_cast<const T*>(0));
idx[d] = backend::device_vector<size_t>(
queue[d], n, &indices[ptr[d]], backend::MEM_READ_ONLY);
}
}
for(unsigned d = 0; d < queue.size(); d++)
if (ptr[d + 1] - ptr[d]) queue[d].finish();
}
protected:
std::vector<backend::command_queue> queue;
std::vector< size_t > ptr;
std::vector< backend::device_vector<size_t> > idx;
std::vector< backend::device_vector<T> > val;
};
} // namespace detail
/// Gathers vector elements at specified indices.
template <typename T>
class gather : protected detail::index_partition<T> {
public:
/// Constructor.
/**
* \param queue VexCL context.
* \param indices Indices of elements to be gathered.
*/
gather(
const std::vector<backend::command_queue> &q,
size_t size, std::vector<size_t> indices
) : Base(q, size, indices)
{}
/// Gather elements of device vector into host vector.
template <class HostVector>
void operator()(const vex::vector<T> &src, HostVector &dst) {
using namespace detail;
static kernel_cache cache;
for(unsigned d = 0; d < Base::queue.size(); d++) {
if (size_t n = Base::ptr[d + 1] - Base::ptr[d]) {
vector<T> v(Base::queue[d], Base::val[d]);
vector<T> s(Base::queue[d], src(d));
vector<size_t> i(Base::queue[d], Base::idx[d]);
v = permutation(i)(s);
Base::val[d].read(Base::queue[d], 0, n, &dst[Base::ptr[d]]);
}
}
for(unsigned d = 0; d < Base::queue.size(); d++)
if (Base::ptr[d + 1] - Base::ptr[d]) Base::queue[d].finish();
}
private:
typedef detail::index_partition<T> Base;
};
/// Scatters vector elements to specified indices.
template <typename T>
class scatter : protected detail::index_partition<T> {
public:
/// Constructor.
/**
* \param queue VexCL context.
* \param indices Indices of elements to be gathered.
*/
scatter(
const std::vector<backend::command_queue> &q,
size_t size, std::vector<size_t> indices
) : Base(q, size, indices)
{}
/// Scatter elements of host vector to device vector.
template <class HostVector>
void operator()(const HostVector &src, vex::vector<T> &dst) {
using namespace detail;
static kernel_cache cache;
for(unsigned d = 0; d < Base::queue.size(); d++) {
if (size_t n = Base::ptr[d + 1] - Base::ptr[d]) {
Base::val[d].write(Base::queue[d], 0, n, &src[Base::ptr[d]]);
vector<T> v(Base::queue[d], Base::val[d]);
vector<T> s(Base::queue[d], dst(d));
vector<size_t> i(Base::queue[d], Base::idx[d]);
permutation(i)(s) = v;
}
}
for(unsigned d = 0; d < Base::queue.size(); d++)
if (Base::ptr[d + 1] - Base::ptr[d]) Base::queue[d].finish();
}
private:
typedef detail::index_partition<T> Base;
};
} // namespace vex
#endif
<|endoftext|> |
<commit_before>/*
* VapourSynth D2V Plugin
*
* Copyright (c) 2012 Derek Buitenhuis
*
* This file is part of d2vsource.
*
* d2vsource 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.
*
* d2vsource 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 d2vsource; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" {
#include <stdint.h>
#include <stdlib.h>
}
#include <VapourSynth.h>
#include <VSHelper.h>
#include "d2v.hpp"
#include "d2vsource.hpp"
#include "decode.hpp"
#include "directrender.hpp"
void VS_CC d2vInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
vsapi->setVideoInfo(&d->vi, 1, node);
}
const VSFrameRef *VS_CC d2vGetFrame(int n, int activationReason, void **instanceData, void **frameData,
VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
VSFrameRef *s, *f;
string msg;
int ret;
/* Unreference the previously decoded frame. */
av_frame_unref(d->frame);
ret = decodeframe(n, d->d2v, d->dec, d->frame, msg);
if (ret < 0) {
vsapi->setFilterError(msg.c_str(), frameCtx);
return NULL;
}
/* Grab our direct-rendered frame. */
s = (VSFrameRef *) d->frame->opaque;
/* If our width and height are the same, just return it. */
if (d->vi.width == d->aligned_width && d->vi.height == d->aligned_height) {
f = (VSFrameRef *) vsapi->cloneFrameRef(s);
return f;
}
f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core);
/* Copy into VS's buffers. */
vs_bitblt(vsapi->getWritePtr(f, 0), vsapi->getStride(f, 0), vsapi->getWritePtr(s, 0), vsapi->getStride(s, 0),
d->vi.width, d->vi.height);
vs_bitblt(vsapi->getWritePtr(f, 1), vsapi->getStride(f, 1), vsapi->getWritePtr(s, 1), vsapi->getStride(s, 1),
d->vi.width >> d->vi.format->subSamplingW, d->vi.height >> d->vi.format->subSamplingH);
vs_bitblt(vsapi->getWritePtr(f, 2), vsapi->getStride(f, 2), vsapi->getWritePtr(s, 2), vsapi->getStride(s, 2),
d->vi.width >> d->vi.format->subSamplingW, d->vi.height >> d->vi.format->subSamplingH);
return f;
}
void VS_CC d2vFree(void *instanceData, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) instanceData;
d2vfreep(&d->d2v);
decodefreep(&d->dec);
av_frame_unref(d->frame);
av_freep(&d->frame);
free(d);
}
void VS_CC d2vCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)
{
d2vData *data;
string msg;
bool no_crop;
int err;
/* Allocate our private data. */
data = (d2vData *) malloc(sizeof(*data));
if (!data) {
vsapi->setError(out, "Cannot allocate private data.");
return;
}
data->d2v = d2vparse((char *) vsapi->propGetData(in, "input", 0, 0), msg);
if (!data->d2v) {
vsapi->setError(out, msg.c_str());
free(data);
return;
}
data->dec = decodeinit(data->d2v, msg);
if (!data->dec) {
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
free(data);
return;
}
/*
* Make our private data available to libavcodec, and
* set our custom get/release_buffer funcs.
*/
data->dec->avctx->opaque = (void *) data;
data->dec->avctx->get_buffer2 = VSGetBuffer;
/* Last frame is crashy right now. */
data->vi.numFrames = data->d2v->frames.size();
data->vi.width = data->d2v->width;
data->vi.height = data->d2v->height;
data->vi.fpsNum = data->d2v->fps_num;
data->vi.fpsDen = data->d2v->fps_den;
/* Stash the pointer to our core. */
data->core = core;
data->api = (VSAPI *) vsapi;
/*
* Stash our aligned width and height for use with our
* custom get_buffer, since it could require this.
*/
data->aligned_width = FFALIGN(data->vi.width, 16);
data->aligned_height = FFALIGN(data->vi.height, 32);
data->frame = av_frame_alloc();
if (!data->frame) {
vsapi->setError(out, "Cannot allocate AVFrame.");
d2vfreep(&data->d2v);
decodefreep(&data->dec);
free(data);
return;
}
/*
* Decode 1 frame to find out how the chroma is subampled.
* The first time our custom get_buffer is called, it will
* fill in data->vi.format.
*/
data->format_set = false;
err = decodeframe(0, data->d2v, data->dec, data->frame, msg);
if (err < 0) {
msg.insert(0, "Failed to decode test frame: ");
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
/* See if nocrop is enabled, and set the width/height accordingly. */
no_crop = !!vsapi->propGetInt(in, "nocrop", 0, &err);
if (err)
no_crop = false;
if (no_crop) {
data->vi.width = data->aligned_width;
data->vi.height = data->aligned_height;
}
vsapi->createFilter(in, out, "d2vsource", d2vInit, d2vGetFrame, d2vFree, fmSerial, 0, data, core);
int rff = !!vsapi->propGetInt(in, "rff", 0, &err);
if (err)
rff = 1;
if (rff) {
VSPlugin *d2vPlugin = vsapi->getPluginByNs("d2v", core);
VSNodeRef *before = vsapi->propGetNode(out, "clip", 0, NULL);
VSNodeRef *after;
VSMap *args = vsapi->createMap();
VSMap *ret;
const char *error;
vsapi->propSetNode(args, "clip", before, paReplace);
vsapi->freeNode(before);
vsapi->propSetData(args, "d2v", vsapi->propGetData(in, "input", 0, NULL), vsapi->propGetDataSize(in, "input", 0, NULL), paReplace);
ret = vsapi->invoke(d2vPlugin, "ApplyRFF", args);
vsapi->freeMap(args);
error = vsapi->getError(ret);
if (error) {
vsapi->setError(out, error);
vsapi->freeMap(ret);
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
after = vsapi->propGetNode(ret, "clip", 0, NULL);
vsapi->propSetNode(out, "clip", after, paReplace);
vsapi->freeNode(after);
vsapi->freeMap(ret);
}
}
<commit_msg>d2vsource: Use getPluginById<commit_after>/*
* VapourSynth D2V Plugin
*
* Copyright (c) 2012 Derek Buitenhuis
*
* This file is part of d2vsource.
*
* d2vsource 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.
*
* d2vsource 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 d2vsource; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" {
#include <stdint.h>
#include <stdlib.h>
}
#include <VapourSynth.h>
#include <VSHelper.h>
#include "d2v.hpp"
#include "d2vsource.hpp"
#include "decode.hpp"
#include "directrender.hpp"
void VS_CC d2vInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
vsapi->setVideoInfo(&d->vi, 1, node);
}
const VSFrameRef *VS_CC d2vGetFrame(int n, int activationReason, void **instanceData, void **frameData,
VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) *instanceData;
VSFrameRef *s, *f;
string msg;
int ret;
/* Unreference the previously decoded frame. */
av_frame_unref(d->frame);
ret = decodeframe(n, d->d2v, d->dec, d->frame, msg);
if (ret < 0) {
vsapi->setFilterError(msg.c_str(), frameCtx);
return NULL;
}
/* Grab our direct-rendered frame. */
s = (VSFrameRef *) d->frame->opaque;
/* If our width and height are the same, just return it. */
if (d->vi.width == d->aligned_width && d->vi.height == d->aligned_height) {
f = (VSFrameRef *) vsapi->cloneFrameRef(s);
return f;
}
f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core);
/* Copy into VS's buffers. */
vs_bitblt(vsapi->getWritePtr(f, 0), vsapi->getStride(f, 0), vsapi->getWritePtr(s, 0), vsapi->getStride(s, 0),
d->vi.width, d->vi.height);
vs_bitblt(vsapi->getWritePtr(f, 1), vsapi->getStride(f, 1), vsapi->getWritePtr(s, 1), vsapi->getStride(s, 1),
d->vi.width >> d->vi.format->subSamplingW, d->vi.height >> d->vi.format->subSamplingH);
vs_bitblt(vsapi->getWritePtr(f, 2), vsapi->getStride(f, 2), vsapi->getWritePtr(s, 2), vsapi->getStride(s, 2),
d->vi.width >> d->vi.format->subSamplingW, d->vi.height >> d->vi.format->subSamplingH);
return f;
}
void VS_CC d2vFree(void *instanceData, VSCore *core, const VSAPI *vsapi)
{
d2vData *d = (d2vData *) instanceData;
d2vfreep(&d->d2v);
decodefreep(&d->dec);
av_frame_unref(d->frame);
av_freep(&d->frame);
free(d);
}
void VS_CC d2vCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)
{
d2vData *data;
string msg;
bool no_crop;
int err;
/* Allocate our private data. */
data = (d2vData *) malloc(sizeof(*data));
if (!data) {
vsapi->setError(out, "Cannot allocate private data.");
return;
}
data->d2v = d2vparse((char *) vsapi->propGetData(in, "input", 0, 0), msg);
if (!data->d2v) {
vsapi->setError(out, msg.c_str());
free(data);
return;
}
data->dec = decodeinit(data->d2v, msg);
if (!data->dec) {
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
free(data);
return;
}
/*
* Make our private data available to libavcodec, and
* set our custom get/release_buffer funcs.
*/
data->dec->avctx->opaque = (void *) data;
data->dec->avctx->get_buffer2 = VSGetBuffer;
/* Last frame is crashy right now. */
data->vi.numFrames = data->d2v->frames.size();
data->vi.width = data->d2v->width;
data->vi.height = data->d2v->height;
data->vi.fpsNum = data->d2v->fps_num;
data->vi.fpsDen = data->d2v->fps_den;
/* Stash the pointer to our core. */
data->core = core;
data->api = (VSAPI *) vsapi;
/*
* Stash our aligned width and height for use with our
* custom get_buffer, since it could require this.
*/
data->aligned_width = FFALIGN(data->vi.width, 16);
data->aligned_height = FFALIGN(data->vi.height, 32);
data->frame = av_frame_alloc();
if (!data->frame) {
vsapi->setError(out, "Cannot allocate AVFrame.");
d2vfreep(&data->d2v);
decodefreep(&data->dec);
free(data);
return;
}
/*
* Decode 1 frame to find out how the chroma is subampled.
* The first time our custom get_buffer is called, it will
* fill in data->vi.format.
*/
data->format_set = false;
err = decodeframe(0, data->d2v, data->dec, data->frame, msg);
if (err < 0) {
msg.insert(0, "Failed to decode test frame: ");
vsapi->setError(out, msg.c_str());
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
/* See if nocrop is enabled, and set the width/height accordingly. */
no_crop = !!vsapi->propGetInt(in, "nocrop", 0, &err);
if (err)
no_crop = false;
if (no_crop) {
data->vi.width = data->aligned_width;
data->vi.height = data->aligned_height;
}
vsapi->createFilter(in, out, "d2vsource", d2vInit, d2vGetFrame, d2vFree, fmSerial, 0, data, core);
int rff = !!vsapi->propGetInt(in, "rff", 0, &err);
if (err)
rff = 1;
if (rff) {
VSPlugin *d2vPlugin = vsapi->getPluginById("com.sources.d2vsource", core);
VSNodeRef *before = vsapi->propGetNode(out, "clip", 0, NULL);
VSNodeRef *after;
VSMap *args = vsapi->createMap();
VSMap *ret;
const char *error;
vsapi->propSetNode(args, "clip", before, paReplace);
vsapi->freeNode(before);
vsapi->propSetData(args, "d2v", vsapi->propGetData(in, "input", 0, NULL), vsapi->propGetDataSize(in, "input", 0, NULL), paReplace);
ret = vsapi->invoke(d2vPlugin, "ApplyRFF", args);
vsapi->freeMap(args);
error = vsapi->getError(ret);
if (error) {
vsapi->setError(out, error);
vsapi->freeMap(ret);
d2vfreep(&data->d2v);
decodefreep(&data->dec);
av_frame_unref(data->frame);
av_freep(&data->frame);
free(data);
return;
}
after = vsapi->propGetNode(ret, "clip", 0, NULL);
vsapi->propSetNode(out, "clip", after, paReplace);
vsapi->freeNode(after);
vsapi->freeMap(ret);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "TestFile.hpp"
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include <ctime>
using namespace std;
using namespace nix;
using namespace valid;
void TestFile::setUp() {
statup_time = time(NULL);
file_open = File::open("test_file.h5", FileMode::Overwrite);
file_other = File::open("test_file_other.h5", FileMode::Overwrite);
file_null = nix::none;
}
void TestFile::tearDown() {
file_open.close();
file_other.close();
}
void TestFile::testValidate() {
valid::Result result = validate(file_open);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
}
void TestFile::testFormat() {
CPPUNIT_ASSERT(file_open.format() == "nix");
}
void TestFile::testLocation() {
CPPUNIT_ASSERT(file_open.location() == "test_file.h5");
CPPUNIT_ASSERT(file_other.location() == "test_file_other.h5");
}
void TestFile::testVersion() {
vector<int> version{1, 0, 0};
CPPUNIT_ASSERT(file_open.version() == version);
}
void TestFile::testCreatedAt() {
CPPUNIT_ASSERT(file_open.createdAt() >= statup_time);
time_t past_time = time(NULL) - 10000000;
file_open.forceCreatedAt(past_time);
CPPUNIT_ASSERT(file_open.createdAt() == past_time);
}
void TestFile::testUpdatedAt() {
CPPUNIT_ASSERT(file_open.updatedAt() >= statup_time);
}
void TestFile::testBlockAccess() {
vector<string> names = { "block_a", "block_b", "block_c", "block_d", "block_e" };
Block b;
CPPUNIT_ASSERT(file_open.blockCount() == 0);
CPPUNIT_ASSERT(file_open.blocks().size() == 0);
CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
CPPUNIT_ASSERT_EQUAL(false, file_open.hasBlock("invalid_id"));
CPPUNIT_ASSERT_THROW(file_open.hasBlock(b), std::runtime_error);
vector<string> ids;
for (const auto &name : names) {
Block bl = file_open.createBlock(name, "dataset");
CPPUNIT_ASSERT(bl.name() == name);
CPPUNIT_ASSERT(file_open.hasBlock(bl));
CPPUNIT_ASSERT(file_open.hasBlock(name));
ids.push_back(bl.id());
}
CPPUNIT_ASSERT_THROW(file_open.createBlock(names[0], "dataset"),
DuplicateName);
CPPUNIT_ASSERT(file_open.blockCount() == names.size());
CPPUNIT_ASSERT(file_open.blocks().size() == names.size());
for (const auto &name : names) {
Block bl_name = file_open.getBlock(name);
CPPUNIT_ASSERT(bl_name);
Block bl_id = file_open.getBlock(bl_name.id());
CPPUNIT_ASSERT(bl_id);
CPPUNIT_ASSERT_EQUAL(bl_name.name(), bl_id.name());
}
for (const auto &id: ids) {
Block bl = file_open.getBlock(id);
CPPUNIT_ASSERT(file_open.hasBlock(id) == true);
CPPUNIT_ASSERT(bl.id() == id);
file_open.deleteBlock(id);
}
CPPUNIT_ASSERT_THROW(file_open.deleteBlock(b), std::runtime_error);
b = file_open.createBlock("test","test");
CPPUNIT_ASSERT_NO_THROW(file_open.getBlock(0));
CPPUNIT_ASSERT_THROW(file_open.getBlock(file_open.blockCount()), nix::OutOfBounds);
CPPUNIT_ASSERT(file_open.deleteBlock(b));
CPPUNIT_ASSERT(file_open.blockCount() == 0);
CPPUNIT_ASSERT(file_open.blocks().size() == 0);
CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
}
void TestFile::testSectionAccess() {
vector<string> names = {"section_a", "section_b", "section_c", "section_d", "section_e" };
Section s;
CPPUNIT_ASSERT(file_open.sectionCount() == 0);
CPPUNIT_ASSERT(file_open.sections().size() == 0);
CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
CPPUNIT_ASSERT_THROW(file_open.hasSection(s), std::runtime_error);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); it++) {
Section sec = file_open.createSection(*it, "root section");
CPPUNIT_ASSERT(sec.name() == *it);
ids.push_back(sec.id());
}
CPPUNIT_ASSERT_THROW(file_open.createSection(names[0], "root section"),
DuplicateName);
CPPUNIT_ASSERT(file_open.sectionCount() == names.size());
CPPUNIT_ASSERT(file_open.sections().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); it++) {
Section sec = file_open.getSection(*it);
CPPUNIT_ASSERT(file_open.hasSection(*it) == true);
CPPUNIT_ASSERT(sec.id() == *it);
file_open.deleteSection(*it);
}
CPPUNIT_ASSERT_THROW(file_open.deleteSection(s), std::runtime_error);
s = file_open.createSection("test","test");
CPPUNIT_ASSERT_NO_THROW(file_open.getSection(0));
CPPUNIT_ASSERT_THROW(file_open.getSection(file_open.sectionCount()), nix::OutOfBounds);
CPPUNIT_ASSERT(file_open.hasSection(s));
CPPUNIT_ASSERT(file_open.deleteSection(s));
CPPUNIT_ASSERT(file_open.sectionCount() == 0);
CPPUNIT_ASSERT(file_open.sections().size() == 0);
CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
}
void TestFile::testOperators(){
CPPUNIT_ASSERT(file_null == false);
CPPUNIT_ASSERT(file_null == none);
CPPUNIT_ASSERT(file_open != false);
CPPUNIT_ASSERT(file_open != none);
CPPUNIT_ASSERT(file_open == file_open);
CPPUNIT_ASSERT(file_open != file_other);
file_other = file_open;
CPPUNIT_ASSERT(file_other == file_open);
file_other = none;
CPPUNIT_ASSERT(file_null == false);
CPPUNIT_ASSERT(file_null == none);
}
void TestFile::testReopen() {
//file_open is currently open
Block b = file_open.createBlock("a", "a");
b = none;
file_open.close();
file_open = nix::File::open("test_file_b.h5", FileMode::Overwrite);
b = file_open.createBlock("b", "b");
}
<commit_msg>[TestFile] change expected runtime_error to UninitializedEntity<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "TestFile.hpp"
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include <ctime>
using namespace std;
using namespace nix;
using namespace valid;
void TestFile::setUp() {
statup_time = time(NULL);
file_open = File::open("test_file.h5", FileMode::Overwrite);
file_other = File::open("test_file_other.h5", FileMode::Overwrite);
file_null = nix::none;
}
void TestFile::tearDown() {
file_open.close();
file_other.close();
}
void TestFile::testValidate() {
valid::Result result = validate(file_open);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
}
void TestFile::testFormat() {
CPPUNIT_ASSERT(file_open.format() == "nix");
}
void TestFile::testLocation() {
CPPUNIT_ASSERT(file_open.location() == "test_file.h5");
CPPUNIT_ASSERT(file_other.location() == "test_file_other.h5");
}
void TestFile::testVersion() {
vector<int> version{1, 0, 0};
CPPUNIT_ASSERT(file_open.version() == version);
}
void TestFile::testCreatedAt() {
CPPUNIT_ASSERT(file_open.createdAt() >= statup_time);
time_t past_time = time(NULL) - 10000000;
file_open.forceCreatedAt(past_time);
CPPUNIT_ASSERT(file_open.createdAt() == past_time);
}
void TestFile::testUpdatedAt() {
CPPUNIT_ASSERT(file_open.updatedAt() >= statup_time);
}
void TestFile::testBlockAccess() {
vector<string> names = { "block_a", "block_b", "block_c", "block_d", "block_e" };
Block b;
CPPUNIT_ASSERT(file_open.blockCount() == 0);
CPPUNIT_ASSERT(file_open.blocks().size() == 0);
CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
CPPUNIT_ASSERT_EQUAL(false, file_open.hasBlock("invalid_id"));
CPPUNIT_ASSERT_THROW(file_open.hasBlock(b), UninitializedEntity);
vector<string> ids;
for (const auto &name : names) {
Block bl = file_open.createBlock(name, "dataset");
CPPUNIT_ASSERT(bl.name() == name);
CPPUNIT_ASSERT(file_open.hasBlock(bl));
CPPUNIT_ASSERT(file_open.hasBlock(name));
ids.push_back(bl.id());
}
CPPUNIT_ASSERT_THROW(file_open.createBlock(names[0], "dataset"),
DuplicateName);
CPPUNIT_ASSERT(file_open.blockCount() == names.size());
CPPUNIT_ASSERT(file_open.blocks().size() == names.size());
for (const auto &name : names) {
Block bl_name = file_open.getBlock(name);
CPPUNIT_ASSERT(bl_name);
Block bl_id = file_open.getBlock(bl_name.id());
CPPUNIT_ASSERT(bl_id);
CPPUNIT_ASSERT_EQUAL(bl_name.name(), bl_id.name());
}
for (const auto &id: ids) {
Block bl = file_open.getBlock(id);
CPPUNIT_ASSERT(file_open.hasBlock(id) == true);
CPPUNIT_ASSERT(bl.id() == id);
file_open.deleteBlock(id);
}
CPPUNIT_ASSERT_THROW(file_open.deleteBlock(b), UninitializedEntity);
b = file_open.createBlock("test","test");
CPPUNIT_ASSERT_NO_THROW(file_open.getBlock(0));
CPPUNIT_ASSERT_THROW(file_open.getBlock(file_open.blockCount()), nix::OutOfBounds);
CPPUNIT_ASSERT(file_open.deleteBlock(b));
CPPUNIT_ASSERT(file_open.blockCount() == 0);
CPPUNIT_ASSERT(file_open.blocks().size() == 0);
CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
}
void TestFile::testSectionAccess() {
vector<string> names = {"section_a", "section_b", "section_c", "section_d", "section_e" };
Section s;
CPPUNIT_ASSERT(file_open.sectionCount() == 0);
CPPUNIT_ASSERT(file_open.sections().size() == 0);
CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
CPPUNIT_ASSERT_THROW(file_open.hasSection(s), UninitializedEntity);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); it++) {
Section sec = file_open.createSection(*it, "root section");
CPPUNIT_ASSERT(sec.name() == *it);
ids.push_back(sec.id());
}
CPPUNIT_ASSERT_THROW(file_open.createSection(names[0], "root section"),
DuplicateName);
CPPUNIT_ASSERT(file_open.sectionCount() == names.size());
CPPUNIT_ASSERT(file_open.sections().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); it++) {
Section sec = file_open.getSection(*it);
CPPUNIT_ASSERT(file_open.hasSection(*it) == true);
CPPUNIT_ASSERT(sec.id() == *it);
file_open.deleteSection(*it);
}
CPPUNIT_ASSERT_THROW(file_open.deleteSection(s), UninitializedEntity);
s = file_open.createSection("test","test");
CPPUNIT_ASSERT_NO_THROW(file_open.getSection(0));
CPPUNIT_ASSERT_THROW(file_open.getSection(file_open.sectionCount()), nix::OutOfBounds);
CPPUNIT_ASSERT(file_open.hasSection(s));
CPPUNIT_ASSERT(file_open.deleteSection(s));
CPPUNIT_ASSERT(file_open.sectionCount() == 0);
CPPUNIT_ASSERT(file_open.sections().size() == 0);
CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
}
void TestFile::testOperators(){
CPPUNIT_ASSERT(file_null == false);
CPPUNIT_ASSERT(file_null == none);
CPPUNIT_ASSERT(file_open != false);
CPPUNIT_ASSERT(file_open != none);
CPPUNIT_ASSERT(file_open == file_open);
CPPUNIT_ASSERT(file_open != file_other);
file_other = file_open;
CPPUNIT_ASSERT(file_other == file_open);
file_other = none;
CPPUNIT_ASSERT(file_null == false);
CPPUNIT_ASSERT(file_null == none);
}
void TestFile::testReopen() {
//file_open is currently open
Block b = file_open.createBlock("a", "a");
b = none;
file_open.close();
file_open = nix::File::open("test_file_b.h5", FileMode::Overwrite);
b = file_open.createBlock("b", "b");
}
<|endoftext|> |
<commit_before>/*
* GameKeeper Framework
*
* Copyright (C) 2013 Karol Herbst <[email protected]>
*
* 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 <gamekeeper/utils/containerutils.h>
#include <map>
#include <gtest/gtest.h>
class ContainerUtilsTest : public testing::Test{};
using namespace gamekeeper::utils;
TEST_F(ContainerUtilsTest, checkMissing_emptyContainer)
{
std::map<std::string,std::string> emptyMap;
std::vector<std::string> missingKeys{"missingKey"};
EXPECT_EQ(missingKeys, Containers::checkMissing(emptyMap, missingKeys));
}
TEST_F(ContainerUtilsTest, checkMissing_mixed)
{
std::map<std::string,std::string> emptyMap{{"existingKey", "string"}};
std::vector<std::string> keysToSearch{"existingKey", "missingKey"};
std::vector<std::string> missingKeys{"missingKey"};
EXPECT_EQ(missingKeys, Containers::checkMissing(emptyMap, keysToSearch));
}
<commit_msg>test/containerUtilsTest: make tests more generic, so we can test various container types<commit_after>/*
* GameKeeper Framework
*
* Copyright (C) 2013 Karol Herbst <[email protected]>
*
* 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 <gamekeeper/utils/containerutils.h>
#include <deque>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <gtest/gtest.h>
class ContainerUtilsTest : public testing::Test{};
using namespace gamekeeper::utils;
using std::deque;
using std::list;
using std::map;
using std::multimap;
using std::multiset;
using std::set;
using std::unordered_map;
using std::unordered_multimap;
using std::unordered_multiset;
using std::unordered_set;
using std::vector;
#define TEST_MACRO_MAP(type, mapType) \
TEST_F(ContainerUtilsTest, checkMissing_emptyContainer_##type##_##mapType) \
{ \
mapType<std::string,std::string> emptyMap; \
type<std::string> missingKeys{"missingKey"}; \
EXPECT_EQ(missingKeys, Containers::checkMissing(emptyMap, missingKeys)); \
} \
\
TEST_F(ContainerUtilsTest, checkMissing_mixed_##type##_##mapType) \
{ \
mapType<std::string,std::string> emptyMap{{"existingKey", "string"}}; \
type<std::string> keysToSearch{"existingKey", "missingKey"}; \
type<std::string> missingKeys{"missingKey"}; \
EXPECT_EQ(missingKeys, Containers::checkMissing(emptyMap, keysToSearch)); \
}
#define TEST_MACRO_SET(type, setType) \
TEST_F(ContainerUtilsTest, checkMissing_emptyContainer_##type##_##setType) \
{ \
setType<std::string> emptyMap; \
type<std::string> missingKeys{"missingKey"}; \
EXPECT_EQ(missingKeys, Containers::checkMissing(emptyMap, missingKeys)); \
} \
\
TEST_F(ContainerUtilsTest, checkMissing_mixed_##type##_##setType) \
{ \
setType<std::string> emptyMap{"existingKey"}; \
type<std::string> keysToSearch{"existingKey", "missingKey"}; \
type<std::string> missingKeys{"missingKey"}; \
EXPECT_EQ(missingKeys, Containers::checkMissing(emptyMap, keysToSearch)); \
}
#define TEST_MACRO_EXEC(type) \
TEST_MACRO_MAP(type, map) \
TEST_MACRO_MAP(type, multimap) \
TEST_MACRO_MAP(type, unordered_map) \
TEST_MACRO_MAP(type, unordered_multimap) \
TEST_MACRO_SET(type, set) \
TEST_MACRO_SET(type, multiset) \
TEST_MACRO_SET(type, unordered_set) \
TEST_MACRO_SET(type, unordered_multiset) \
TEST_MACRO_EXEC(deque)
TEST_MACRO_EXEC(list)
TEST_MACRO_EXEC(vector)
<|endoftext|> |
<commit_before>#include "packetcapturer.h"
#include <pcap.h>
#include <qdebug.h>
#include <QApplication>
#define ETHERTYPE_EAP (0x888e) /* eap authentication */
#define ETHER_ADDR_LEN 6
#define ETHERTYPE_IP (0x0800)
namespace packetprocess {
u_short recentFreq = 100;
QObject* parent;
#define TYPE_TCP (6)
/* Ethernet header */
struct sniff_ethernet {
u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
u_short ether_type; /* IP? ARP? RARP? etc */
};
/* IP header */
struct sniff_ip {
u_char ip_vhl; /* version << 4 | header length >> 2 */
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off; /* fragment offset field */
#define IP_RF 0x8000 /* reserved fragment flag */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
};
#define IP_HL(ip) (((ip)->ip_vhl) & 0x0f)
#define IP_V(ip) (((ip)->ip_vhl) >> 4)
/* TCP header */
typedef u_int tcp_seq;
struct sniff_tcp {
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
tcp_seq th_seq; /* sequence number */
tcp_seq th_ack; /* acknowledgement number */
u_char th_offx2; /* data offset, rsvd */
#define TH_OFF(th) (((th)->th_offx2 & 0xf0) >> 4)
u_char th_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECE 0x40
#define TH_CWR 0x80
#define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
u_short th_win; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
};
//static callback for libpcap
void Callback_ProcessPacket(u_char *useless, const pcap_pkthdr *pkthdr, const u_char *packet){
//just a pointer to avoid the extra casts later
PacketCapturer* p = ((PacketCapturer*)parent);
const struct sniff_ethernet *ethernet; /* The ethernet header */
const struct sniff_ip *ip; /* The IP header */
const struct sniff_tcp *tcp; /* The TCP header */
//const char *payload; /* Packet payload */
u_int size_ip;
u_int size_tcp;
//the beginning is ethernet header
ethernet = (struct sniff_ethernet*)(packet);
//QString("%1").arg(yourNumber, 5, 10, QChar('0'));
//qDebug() << "ethernet type:" << QString("%1").arg(ntohs(ethernet->ether_type), 4, 16).prepend("0x") << ntohs(ethernet->ether_type);
if(ntohs(ethernet->ether_type) == ETHERTYPE_EAP){
p->ChangeEmitter( 1200, 0);
p->ChangeEmitter( 1215, 0);
return;
}
if(ntohs(ethernet->ether_type) != ETHERTYPE_IP)
return;
//continuing UP the stack
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
if(ip->ip_p != TYPE_TCP ){
p->ChangeEmitter( 150, 0);
p->ChangeEmitter( 148+ip->ip_p, 0);
return;
}
size_ip = IP_HL(ip)*4;
if (size_ip < 20) {
qWarning() << "Invalid IP header length:" << size_ip;
return;
}
//The TCP header is after the ethernet and ip headers
tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
size_tcp = TH_OFF(tcp)*4;
if (size_tcp < 20) {
qWarning() << "Invalid TCP header length:" << size_tcp;
return;
}
//p->ChangeEmitter( ntohs(tcp->th_dport)&1023|ntohs(tcp->th_sport), 1);
//p->ChangeEmitter( ntohs(tcp->th_dport), 1);
int val = ntohs(tcp->th_sport);
if(val > 4096 )
val>>3;
p->ChangeEmitter( val, 1);
}
}//end packetprocess namespace
PacketCapturer::PacketCapturer(QObject *parent) : QObject(parent)
{
}
//constructor
PacketCapturer::PacketCapturer(const char *deviceName){
qDebug() << Q_FUNC_INFO << "setting filter";
//define my filter only care about ip stuff to and from this machine
char filter_exp[] = "ip";
//copy the deviceName into the device I'll be using
dev = (char*)malloc(10*sizeof(char));
strcpy(dev, deviceName);
//Open the session in promiscuous mode
qDebug() << Q_FUNC_INFO << "Opening Device" << dev;
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
qDebug() << Q_FUNC_INFO << "Couldn't open device" << dev << errbuf;
exit(-1);
}
// Compile the filter
qDebug() << Q_FUNC_INFO << "compiling filter";
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
qDebug() << Q_FUNC_INFO << "Couldn't parse filter" << filter_exp << pcap_geterr(handle);
exit(-1);
}
//setting the filter
if (pcap_setfilter(handle, &fp) == -1) {
qDebug() << Q_FUNC_INFO << "Couldn't install filter" << filter_exp << pcap_geterr(handle);
exit(-1);
}
//associating the object instance within this static function
/** \note seems like a bad design but it works */
packetprocess::parent = this;
qDebug() << Q_FUNC_INFO << " PCAP setup correctly";
}
//an object callback to send signals from the Static ProcessPacket function
void PacketCapturer::ChangeEmitter(int value, int often){
emit( SIG_NEW_TONE(value, often) );
}
//a slot is needed for multi thread interfacing
void PacketCapturer::SLOT_CAPTURE(){
qDebug() << Q_FUNC_INFO << " Setting up capture loop";
pcap_loop( handle, 0, ((pcap_handler)packetprocess::Callback_ProcessPacket), NULL);
}
PacketCapturer::~PacketCapturer()
{
/* And close the session */
pcap_close(handle);
}
<commit_msg>removed dumb redundant string copy<commit_after>#include "packetcapturer.h"
#include <pcap.h>
#include <qdebug.h>
#include <QApplication>
#define ETHERTYPE_EAP (0x888e) /* eap authentication */
#define ETHER_ADDR_LEN 6
#define ETHERTYPE_IP (0x0800)
namespace packetprocess {
u_short recentFreq = 100;
QObject* parent;
#define TYPE_TCP (6)
/* Ethernet header */
struct sniff_ethernet {
u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
u_short ether_type; /* IP? ARP? RARP? etc */
};
/* IP header */
struct sniff_ip {
u_char ip_vhl; /* version << 4 | header length >> 2 */
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off; /* fragment offset field */
#define IP_RF 0x8000 /* reserved fragment flag */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
};
#define IP_HL(ip) (((ip)->ip_vhl) & 0x0f)
#define IP_V(ip) (((ip)->ip_vhl) >> 4)
/* TCP header */
typedef u_int tcp_seq;
struct sniff_tcp {
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
tcp_seq th_seq; /* sequence number */
tcp_seq th_ack; /* acknowledgement number */
u_char th_offx2; /* data offset, rsvd */
#define TH_OFF(th) (((th)->th_offx2 & 0xf0) >> 4)
u_char th_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECE 0x40
#define TH_CWR 0x80
#define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
u_short th_win; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
};
//static callback for libpcap
void Callback_ProcessPacket(u_char *useless, const pcap_pkthdr *pkthdr, const u_char *packet){
//just a pointer to avoid the extra casts later
PacketCapturer* p = ((PacketCapturer*)parent);
const struct sniff_ethernet *ethernet; /* The ethernet header */
const struct sniff_ip *ip; /* The IP header */
const struct sniff_tcp *tcp; /* The TCP header */
//const char *payload; /* Packet payload */
u_int size_ip;
u_int size_tcp;
//the beginning is ethernet header
ethernet = (struct sniff_ethernet*)(packet);
//QString("%1").arg(yourNumber, 5, 10, QChar('0'));
//qDebug() << "ethernet type:" << QString("%1").arg(ntohs(ethernet->ether_type), 4, 16).prepend("0x") << ntohs(ethernet->ether_type);
if(ntohs(ethernet->ether_type) == ETHERTYPE_EAP){
p->ChangeEmitter( 1200, 0);
p->ChangeEmitter( 1215, 0);
return;
}
if(ntohs(ethernet->ether_type) != ETHERTYPE_IP)
return;
//continuing UP the stack
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
if(ip->ip_p != TYPE_TCP ){
p->ChangeEmitter( 150, 0);
p->ChangeEmitter( 148+ip->ip_p, 0);
return;
}
size_ip = IP_HL(ip)*4;
if (size_ip < 20) {
qWarning() << "Invalid IP header length:" << size_ip;
return;
}
//The TCP header is after the ethernet and ip headers
tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
size_tcp = TH_OFF(tcp)*4;
if (size_tcp < 20) {
qWarning() << "Invalid TCP header length:" << size_tcp;
return;
}
//p->ChangeEmitter( ntohs(tcp->th_dport)&1023|ntohs(tcp->th_sport), 1);
//p->ChangeEmitter( ntohs(tcp->th_dport), 1);
int val = ntohs(tcp->th_sport);
if(val > 4096 )
val>>3;
p->ChangeEmitter( val, 1);
}
}//end packetprocess namespace
PacketCapturer::PacketCapturer(QObject *parent) : QObject(parent)
{
}
//constructor
PacketCapturer::PacketCapturer(const char *deviceName){
qDebug() << Q_FUNC_INFO << "setting filter";
//define my filter only care about ip stuff to and from this machine
char filter_exp[] = "ip";
//copy the deviceName into the device I'll be using
dev = (char*)malloc(80*sizeof(char));
strcpy(dev, deviceName);
//Open the session in promiscuous mode
qDebug() << Q_FUNC_INFO << "Opening Device" << dev;
handle = pcap_open_live(deviceName, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
qDebug() << Q_FUNC_INFO << "Couldn't open device" << dev << errbuf;
exit(-1);
}
// Compile the filter
qDebug() << Q_FUNC_INFO << "compiling filter";
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
qDebug() << Q_FUNC_INFO << "Couldn't parse filter" << filter_exp << pcap_geterr(handle);
exit(-1);
}
//setting the filter
if (pcap_setfilter(handle, &fp) == -1) {
qDebug() << Q_FUNC_INFO << "Couldn't install filter" << filter_exp << pcap_geterr(handle);
exit(-1);
}
//associating the object instance within this static function
/** \note seems like a bad design but it works */
packetprocess::parent = this;
qDebug() << Q_FUNC_INFO << " PCAP setup correctly";
}
//an object callback to send signals from the Static ProcessPacket function
void PacketCapturer::ChangeEmitter(int value, int often){
emit( SIG_NEW_TONE(value, often) );
}
//a slot is needed for multi thread interfacing
void PacketCapturer::SLOT_CAPTURE(){
qDebug() << Q_FUNC_INFO << " Setting up capture loop";
int ret = pcap_loop( handle, 0, ((pcap_handler)packetprocess::Callback_ProcessPacket), NULL);
qDebug() << Q_FUNC_INFO << " Done Setting up capture loop";
}
PacketCapturer::~PacketCapturer()
{
/* And close the session */
pcap_close(handle);
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief SD カードの読み書き、サンプル
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2016 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "common/renesas.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
// DS3231 RTC を有効にする場合(ファイルの書き込み時間の設定)
#define WITH_RTC
#ifdef WITH_RTC
#include "chip/DS3231.hpp"
#endif
namespace {
// 送信、受信バッファの定義
typedef utils::fifo<uint8_t, 32> buffer;
// UART の定義(SAU2、SAU3)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
// インターバル・タイマー
device::itimer<uint16_t> itm_;
// CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0
typedef device::csi_io<device::SAU00> csi;
csi csi_;
// FatFS インターフェースの定義
typedef device::PORT<device::port_no::P0, device::bitpos::B0> card_select; ///< カード選択信号
typedef device::PORT<device::port_no::P0, device::bitpos::B1> card_power; ///< カード電源制御
typedef device::PORT<device::port_no::P14, device::bitpos::B6> card_detect; ///< カード検出
utils::sdc_io<csi, card_select, card_power, card_detect> sdc_(csi_);
utils::command<64> command_;
#ifdef WITH_RTC
typedef device::iica_io<device::IICA0> IICA;
IICA iica_;
chip::DS3231<IICA> rtc_(iica_);
#endif
}
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdc_.at_mmc().disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdc_.at_mmc().disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
#ifdef WITH_RTC
time_t t = 0;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
return utils::str::get_fattime(t);
#else
return 0;
#endif
}
void UART1_TX_intr(void)
{
uart_.send_task();
}
void UART1_RX_intr(void)
{
uart_.recv_task();
}
void UART1_ER_intr(void)
{
uart_.error_task();
}
void ITM_intr(void)
{
itm_.task();
}
};
namespace {
#ifdef WITH_RTC
void date_()
{
time_t t = 0;
struct tm *m;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
m = localtime(&t);
utils::format("%s %s %d %02d:%02d:%02d %4d\n")
% get_wday(m->tm_wday)
% get_mon(m->tm_mon)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec)
% static_cast<uint32_t>(m->tm_year + 1900);
}
#endif
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
bool create_test_file_(const char* fname, uint32_t size)
{
uint8_t buff[512];
FIL fp;
utils::format("SD Write test...\n");
for(uint16_t i = 0; i < sizeof(buff); ++i) {
buff[i] = rand_();
}
auto st = itm_.get_counter();
if(!sdc_.open(&fp, fname, FA_WRITE | FA_CREATE_ALWAYS)) {
utils::format("Can't create file: '%s'\n") % fname;
return false;
}
auto rs = size;
while(rs > 0) {
UINT sz = sizeof(buff);
if(sz > rs) sz = rs;
UINT bw;
f_write(&fp, buff, sz, &bw);
rs -= bw;
}
f_close(&fp);
auto ed = itm_.get_counter();
uint32_t len;
if(ed > st) len = ed - st;
else len = 65536 + ed - st;
utils::format("Write frame: %d\n") % len;
auto pbyte = size * 60 / len;
utils::format("Write: %d Bytes/Sec\n") % pbyte;
utils::format("Write: %d KBytes/Sec\n") % (pbyte / 1024);
return true;
}
void test_all_()
{
utils::format("SD Speed test start...\n");
const char* test_file = { "TEST.BIN" };
uint32_t size = 1024L * 1024L;
if(!create_test_file_(test_file, size)) {
return;
}
auto st = itm_.get_counter();
utils::format("SD Read test...\n");
FIL fp;
if(!sdc_.open(&fp, test_file, FA_READ)) {
utils::format("Can't read file: '%s'\n") % test_file;
}
auto rs = size;
while(rs > 0) {
uint8_t buff[512];
UINT rb;
UINT sz = sizeof(buff);
if(sz > rs) sz = rs;
f_read(&fp, buff, sz, &rb);
rs -= rb;
}
f_close(&fp);
auto ed = itm_.get_counter();
uint32_t len;
if(ed > st) len = ed - st;
else len = 65536 + ed - st;
utils::format("Read frame: %d\n") % len;
auto pbyte = size * 60 / len;
utils::format("Read: %d Bytes/Sec\n") % pbyte;
utils::format("Read: %d KBytes/Sec\n") % (pbyte / 1024);
}
}
int main(int argc, char* argv[])
{
using namespace device;
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
PM4.B3 = 0; // output
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
#ifdef WITH_RTC
// IICA 開始
{
uint8_t intr_level = 0;
if(!iica_.start(IICA::speed::fast, intr_level)) {
// if(!iica_.start(IICA::speed::standard, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
}
// DS3231(RTC) の開始
if(!rtc_.start()) {
utils::format("Stall DS3231 start (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
#endif
sdc_.initialize();
uart_.puts("Start RL78/G13 SD-CARD Access sample\n");
command_.set_prompt("# ");
uint8_t n = 0;
char tmp[64];
while(1) {
itm_.sync();
sdc_.service();
// コマンド入力と、コマンド解析
if(command_.service()) {
auto cmdn = command_.get_words();
if(cmdn >= 1) {
bool f = false;
if(command_.cmp_word(0, "dir")) { // dir [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
f = true;
} else if(command_.cmp_word(0, "cd")) { // cd [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
f = true;
} else if(command_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
f = true;
} else if(command_.cmp_word(0, "speed")) { // speed
test_all_();
f = true;
#ifdef WITH_RTC
} else if(command_.cmp_word(0, "date")) { // date
date_();
f = true;
}
#else
}
#endif
if(!f) {
command_.get_word(0, sizeof(tmp), tmp);
utils::format("Command error: '%s'\n") % tmp;
}
}
}
// TAB キーが押された場合の動作
// if(command_.probe_tab()) {
// command_.injection_tab("asdfghj");
// }
++n;
if(n >= 30) n = 0;
P4.B3 = n < 10 ? false : true;
}
}
<commit_msg>update include path<commit_after>//=====================================================================//
/*! @file
@brief SD カードの読み書き、サンプル
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2016 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "common/renesas.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/iica_io.hpp"
#include "common/csi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
// DS3231 RTC を有効にする場合(ファイルの書き込み時間の設定)
#define WITH_RTC
#ifdef WITH_RTC
#include "chip/DS3231.hpp"
#endif
namespace {
// 送信、受信バッファの定義
typedef utils::fifo<uint8_t, 32> buffer;
// UART の定義(SAU2、SAU3)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
// インターバル・タイマー
device::itimer<uint16_t> itm_;
// CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0
typedef device::csi_io<device::SAU00> csi;
csi csi_;
// FatFS インターフェースの定義
typedef device::PORT<device::port_no::P0, device::bitpos::B0> card_select; ///< カード選択信号
typedef device::PORT<device::port_no::P0, device::bitpos::B1> card_power; ///< カード電源制御
typedef device::PORT<device::port_no::P14, device::bitpos::B6> card_detect; ///< カード検出
utils::sdc_io<csi, card_select, card_power, card_detect> sdc_(csi_);
utils::command<64> command_;
#ifdef WITH_RTC
typedef device::iica_io<device::IICA0> IICA;
IICA iica_;
chip::DS3231<IICA> rtc_(iica_);
#endif
}
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdc_.at_mmc().disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdc_.at_mmc().disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
#ifdef WITH_RTC
time_t t = 0;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
return utils::str::get_fattime(t);
#else
return 0;
#endif
}
void UART1_TX_intr(void)
{
uart_.send_task();
}
void UART1_RX_intr(void)
{
uart_.recv_task();
}
void UART1_ER_intr(void)
{
uart_.error_task();
}
void ITM_intr(void)
{
itm_.task();
}
};
namespace {
#ifdef WITH_RTC
void date_()
{
time_t t = 0;
struct tm *m;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
m = localtime(&t);
utils::format("%s %s %d %02d:%02d:%02d %4d\n")
% get_wday(m->tm_wday)
% get_mon(m->tm_mon)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec)
% static_cast<uint32_t>(m->tm_year + 1900);
}
#endif
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
bool create_test_file_(const char* fname, uint32_t size)
{
uint8_t buff[512];
FIL fp;
utils::format("SD Write test...\n");
for(uint16_t i = 0; i < sizeof(buff); ++i) {
buff[i] = rand_();
}
auto st = itm_.get_counter();
if(!sdc_.open(&fp, fname, FA_WRITE | FA_CREATE_ALWAYS)) {
utils::format("Can't create file: '%s'\n") % fname;
return false;
}
auto rs = size;
while(rs > 0) {
UINT sz = sizeof(buff);
if(sz > rs) sz = rs;
UINT bw;
f_write(&fp, buff, sz, &bw);
rs -= bw;
}
f_close(&fp);
auto ed = itm_.get_counter();
uint32_t len;
if(ed > st) len = ed - st;
else len = 65536 + ed - st;
utils::format("Write frame: %d\n") % len;
auto pbyte = size * 60 / len;
utils::format("Write: %d Bytes/Sec\n") % pbyte;
utils::format("Write: %d KBytes/Sec\n") % (pbyte / 1024);
return true;
}
void test_all_()
{
utils::format("SD Speed test start...\n");
const char* test_file = { "TEST.BIN" };
uint32_t size = 1024L * 1024L;
if(!create_test_file_(test_file, size)) {
return;
}
auto st = itm_.get_counter();
utils::format("SD Read test...\n");
FIL fp;
if(!sdc_.open(&fp, test_file, FA_READ)) {
utils::format("Can't read file: '%s'\n") % test_file;
}
auto rs = size;
while(rs > 0) {
uint8_t buff[512];
UINT rb;
UINT sz = sizeof(buff);
if(sz > rs) sz = rs;
f_read(&fp, buff, sz, &rb);
rs -= rb;
}
f_close(&fp);
auto ed = itm_.get_counter();
uint32_t len;
if(ed > st) len = ed - st;
else len = 65536 + ed - st;
utils::format("Read frame: %d\n") % len;
auto pbyte = size * 60 / len;
utils::format("Read: %d Bytes/Sec\n") % pbyte;
utils::format("Read: %d KBytes/Sec\n") % (pbyte / 1024);
}
}
int main(int argc, char* argv[])
{
using namespace device;
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
PM4.B3 = 0; // output
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
#ifdef WITH_RTC
// IICA 開始
{
uint8_t intr_level = 0;
if(!iica_.start(IICA::speed::fast, intr_level)) {
// if(!iica_.start(IICA::speed::standard, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
}
// DS3231(RTC) の開始
if(!rtc_.start()) {
utils::format("Stall DS3231 start (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
#endif
sdc_.initialize();
uart_.puts("Start RL78/G13 SD-CARD Access sample\n");
command_.set_prompt("# ");
uint8_t n = 0;
char tmp[64];
while(1) {
itm_.sync();
sdc_.service();
// コマンド入力と、コマンド解析
if(command_.service()) {
auto cmdn = command_.get_words();
if(cmdn >= 1) {
bool f = false;
if(command_.cmp_word(0, "dir")) { // dir [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.dir(tmp);
} else {
sdc_.dir("");
}
f = true;
} else if(command_.cmp_word(0, "cd")) { // cd [xxx]
if(cmdn >= 2) {
command_.get_word(1, sizeof(tmp), tmp);
sdc_.cd(tmp);
} else {
sdc_.cd("/");
}
f = true;
} else if(command_.cmp_word(0, "pwd")) { // pwd
utils::format("%s\n") % sdc_.get_current();
f = true;
} else if(command_.cmp_word(0, "speed")) { // speed
test_all_();
f = true;
#ifdef WITH_RTC
} else if(command_.cmp_word(0, "date")) { // date
date_();
f = true;
}
#else
}
#endif
if(!f) {
command_.get_word(0, sizeof(tmp), tmp);
utils::format("Command error: '%s'\n") % tmp;
}
}
}
// TAB キーが押された場合の動作
// if(command_.probe_tab()) {
// command_.injection_tab("asdfghj");
// }
++n;
if(n >= 30) n = 0;
P4.B3 = n < 10 ? false : true;
}
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include <assert.h>
#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "CuTest.h"
#include "linked_list_queue.h"
#include "raft.h"
#include "raft_server.h"
typedef struct {
void* outbox;
void* inbox;
RaftServer* raft;
} sender_t;
typedef struct {
void* data;
int len;
/* what type of message is it? */
int type;
/* who sent this? */
int sender;
} msg_t;
static sender_t** __senders = NULL;
static int __nsenders = 0;
void senders_new()
{
__senders = NULL;
__nsenders = 0;
}
int sender_send(void* caller, void* udata, int peer, int type,
const unsigned char* data, int len)
{
sender_t* me = (sender_t*)caller;
msg_t* m;
m = (msg_t*)malloc(sizeof(msg_t));
m->type = type;
m->len = len;
m->data = malloc(len);
m->sender = reinterpret_cast<RaftServer*>(udata)->get_nodeid();
memcpy(m->data,data,len);
llqueue_offer((linked_list_queue_t*)me->outbox,m);
if (__nsenders > peer)
{
llqueue_offer((linked_list_queue_t*)__senders[peer]->inbox, m);
}
return 0;
}
void* sender_new(void* address)
{
sender_t* me;
me = (sender_t*) malloc(sizeof(sender_t));
me->outbox = llqueue_new();
me->inbox = llqueue_new();
__senders = (sender_t**)realloc(__senders,sizeof(sender_t*) * (++__nsenders));
__senders[__nsenders-1] = me;
return me;
}
void* sender_poll_msg_data(void* s)
{
sender_t* me = (sender_t*)s;
msg_t* msg;
msg = (msg_t*) llqueue_poll((linked_list_queue_t*)me->outbox);
return NULL != msg ? msg->data : NULL;
}
void sender_set_raft(void* s, void* r)
{
sender_t* me = (sender_t*)s;
me->raft = reinterpret_cast<RaftServer*>(r);
}
int sender_msgs_available(void* s)
{
sender_t* me = (sender_t*)s;
return 0 < llqueue_count((linked_list_queue_t*)me->inbox);
}
void sender_poll_msgs(void* s)
{
sender_t* me = (sender_t*)s;
msg_t* m;
while ((m = (msg_t*) llqueue_poll((linked_list_queue_t*)me->inbox)))
{
switch (m->type)
{
case RAFT_MSG_APPENDENTRIES:
me->raft->recv_appendentries(m->sender, (msg_appendentries_t*) m->data);
break;
case RAFT_MSG_APPENDENTRIES_RESPONSE:
me->raft->recv_appendentries_response(m->sender, (msg_appendentries_response_t*) m->data);
break;
case RAFT_MSG_REQUESTVOTE:
me->raft->recv_requestvote(m->sender, (msg_requestvote_t*) m->data);
break;
case RAFT_MSG_REQUESTVOTE_RESPONSE:
me->raft->recv_requestvote_response(m->sender, (msg_requestvote_response_t*) m->data);
break;
case RAFT_MSG_ENTRY:
me->raft->recv_entry(m->sender, (msg_entry_t*) m->data);
break;
case RAFT_MSG_ENTRY_RESPONSE:
//me->raft->recv_entry_response(m->sender, m->data);
break;
}
}
}
<commit_msg>removed linked list<commit_after>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include <assert.h>
#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <deque>
#include "CuTest.h"
#include "raft.h"
#include "raft_server.h"
typedef struct {
void* data;
int len;
/* what type of message is it? */
int type;
/* who sent this? */
int sender;
} msg_t;
typedef struct {
std::deque<msg_t*>* outbox;
std::deque<msg_t*>* inbox;
RaftServer* raft;
} sender_t;
static sender_t** __senders = NULL;
static int __nsenders = 0;
void senders_new()
{
__senders = NULL;
__nsenders = 0;
}
int sender_send(void* caller, void* udata, int peer, int type,
const unsigned char* data, int len)
{
sender_t* me = (sender_t*)caller;
msg_t* m;
m = (msg_t*)malloc(sizeof(msg_t));
m->type = type;
m->len = len;
m->data = malloc(len);
m->sender = reinterpret_cast<RaftServer*>(udata)->get_nodeid();
memcpy(m->data,data,len);
me->outbox->push_back(m);
if (__nsenders > peer)
{
__senders[peer]->inbox->push_back(m);
}
return 0;
}
void* sender_new(void* address)
{
sender_t* me;
me = (sender_t*) malloc(sizeof(sender_t));
me->outbox = new std::deque<msg_t*>();
me->inbox = new std::deque<msg_t*>();
__senders = (sender_t**)realloc(__senders,sizeof(sender_t*) * (++__nsenders));
__senders[__nsenders-1] = me;
return me;
}
void* sender_poll_msg_data(void* s)
{
sender_t* me = (sender_t*)s;
msg_t* msg;
void* retVal = !me->outbox->empty() ? me->outbox->back()->data : NULL;
if (!me->outbox->empty()) me->outbox->pop_back();
return retVal;
}
void sender_set_raft(void* s, void* r)
{
sender_t* me = (sender_t*)s;
me->raft = reinterpret_cast<RaftServer*>(r);
}
int sender_msgs_available(void* s)
{
sender_t* me = (sender_t*)s;
return !me->inbox->empty();
}
void sender_poll_msgs(void* s)
{
sender_t* me = (sender_t*)s;
msg_t* m;
while (!me->inbox->empty())
{
m = me->inbox->back();
switch (m->type)
{
case RAFT_MSG_APPENDENTRIES:
me->raft->recv_appendentries(m->sender, (msg_appendentries_t*) m->data);
break;
case RAFT_MSG_APPENDENTRIES_RESPONSE:
me->raft->recv_appendentries_response(m->sender, (msg_appendentries_response_t*) m->data);
break;
case RAFT_MSG_REQUESTVOTE:
me->raft->recv_requestvote(m->sender, (msg_requestvote_t*) m->data);
break;
case RAFT_MSG_REQUESTVOTE_RESPONSE:
me->raft->recv_requestvote_response(m->sender, (msg_requestvote_response_t*) m->data);
break;
case RAFT_MSG_ENTRY:
me->raft->recv_entry(m->sender, (msg_entry_t*) m->data);
break;
case RAFT_MSG_ENTRY_RESPONSE:
//me->raft->recv_entry_response(m->sender, m->data);
break;
}
me->inbox->pop_back();
}
}
<|endoftext|> |
<commit_before>// Copyright 2015 Google Inc. 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 <unistd.h>
#ifdef __APPLE__
#include <sys/time.h>
#endif
#include <iostream>
#include <ctime>
#include <cstdint>
#include <vector>
#include <map>
#include <cstdlib>
#include "test.h"
#include "../public/gemmlowp.h"
#if defined(__arm__) && !defined(GEMMLOWP_NEON)
#warning "Building without NEON support on ARM, check your compiler setup!"
#endif
namespace gemmlowp {
double time() {
#ifdef __APPLE__
timeval t;
gettimeofday(&t, nullptr);
return t.tv_sec + 1e-6 * t.tv_usec;
#else
timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv_sec + 1e-9 * t.tv_nsec;
#endif
}
const double min_accurate_duration = 1e-1;
const std::size_t min_working_set_size = 16 * 1024 * 1024;
template <typename Kernel, typename LhsType, typename RhsType,
typename ResultType>
double time_for_gemm_size(GemmContext* context, int rows, int depth,
int cols) {
typedef std::uint8_t Scalar;
// set up the matrix pool
const std::size_t combined_three_matrices_sizes =
sizeof(Scalar) * (rows * depth + depth * cols + rows * cols);
const std::size_t matrix_pool_size =
1 + min_working_set_size / combined_three_matrices_sizes;
std::vector<LhsType> lhs(matrix_pool_size);
std::vector<RhsType> rhs(matrix_pool_size);
std::vector<ResultType> result(matrix_pool_size);
lhs[0].Resize(rows, depth);
MakeConstant(&lhs[0], 128);
rhs[0].Resize(depth, cols);
MakeConstant(&rhs[0], 128);
result[0].Resize(rows, cols);
MakeZero(&result[0]);
for (std::size_t i = 1; i < matrix_pool_size; i++) {
lhs[i] = lhs[0];
rhs[i] = rhs[0];
result[i] = result[0];
}
const int depth_shift = static_cast<int>(
std::ceil(0.5 * std::log(static_cast<float>(depth)) / std::log(2.0f)));
// main benchmark loop
int iters_at_a_time = 1;
float time_per_iter = 0.0f;
std::size_t matrix_index = 0;
while (true) {
double starttime = time();
for (int i = 0; i < iters_at_a_time; i++) {
Gemm(context, lhs[matrix_index].const_map(),
rhs[matrix_index].const_map(), &result[matrix_index].map(), -75, -91,
74980, 123, 18 + depth_shift);
matrix_index++;
if (matrix_index == matrix_pool_size) {
matrix_index = 0;
}
}
double endtime = time();
const float timing = static_cast<float>(endtime - starttime);
if (timing >= min_accurate_duration) {
time_per_iter = timing / iters_at_a_time;
break;
}
iters_at_a_time *= 2;
}
return time_per_iter;
}
template <typename Kernel, typename LhsType, typename RhsType,
typename ResultType>
double gflops_for_gemm_size(GemmContext* context, int rows, int depth,
int cols) {
const double time_per_iter =
time_for_gemm_size<Kernel, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
return 2e-9 * rows * depth * cols / time_per_iter;
}
void benchmark(GemmContext* context) {
#ifdef GEMMLOWP_TEST_KERNEL
typedef gemmlowp::GEMMLOWP_TEST_KERNEL KernelForGEMM;
typedef gemmlowp::GEMMLOWP_TEST_KERNEL KernelForGEMV;
#else
typedef gemmlowp::DefaultKernelForGEMM KernelForGEMM;
typedef gemmlowp::DefaultKernelForGEMV KernelForGEMV;
#endif
std::map<std::tuple<int, int, int>, std::vector<double>> benchmark_results;
std::vector<std::tuple<int, int, int>> benchmark_sizes;
benchmark_sizes.emplace_back(10, 10, 10);
benchmark_sizes.emplace_back(20, 20, 20);
benchmark_sizes.emplace_back(30, 30, 30);
benchmark_sizes.emplace_back(40, 40, 40);
benchmark_sizes.emplace_back(50, 50, 50);
benchmark_sizes.emplace_back(60, 60, 60);
benchmark_sizes.emplace_back(64, 256, 147);
benchmark_sizes.emplace_back(100, 100, 1);
benchmark_sizes.emplace_back(100, 100, 100);
benchmark_sizes.emplace_back(100, 1000, 100);
benchmark_sizes.emplace_back(1000, 1000, 1);
benchmark_sizes.emplace_back(1000, 1000, 10);
benchmark_sizes.emplace_back(1000, 1000, 100);
benchmark_sizes.emplace_back(1000, 1000, 1000);
const int repeat = 2;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> ResultType;
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::RegisterCurrentThreadForProfiling();
gemmlowp::StartProfiling();
#endif
// We don't record the first repetition, it's just warm-up.
for (int r = 0; r < repeat + 1; r++) {
std::cout << "repetition " << r + 1 << "/" << repeat + 1 << "...\r"
<< std::flush;
for (auto s : benchmark_sizes) {
double gflops = 0;
int rows = std::get<0>(s);
int depth = std::get<1>(s);
int cols = std::get<2>(s);
if (cols > KernelForGEMM::Format::kCols / 2) {
gflops =
gflops_for_gemm_size<KernelForGEMM, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
} else {
gflops =
gflops_for_gemm_size<KernelForGEMV, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
}
if (r > 0) {
benchmark_results[s].emplace_back(gflops);
}
}
}
std::cout << " \r"
<< std::flush;
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::FinishProfiling();
#endif
std::cout.precision(4);
for (auto b : benchmark_results) {
sort(b.second.begin(), b.second.end());
std::cout << std::get<0>(b.first) << "x" << std::get<1>(b.first) << "x"
<< std::get<2>(b.first) << " : " << b.second.back() << " GFlops/s"
<< std::endl;
}
std::cout << std::endl;
}
void benchmark_googlenet(GemmContext* context) {
#ifdef GEMMLOWP_TEST_KERNEL
typedef gemmlowp::GEMMLOWP_TEST_KERNEL KernelForGEMM;
typedef gemmlowp::GEMMLOWP_TEST_KERNEL KernelForGEMV;
#else
typedef gemmlowp::DefaultKernelForGEMM KernelForGEMM;
typedef gemmlowp::DefaultKernelForGEMV KernelForGEMV;
#endif
// These are the m, n, k sizes for a typical GoogLeNet.
const int googlenet_gemm_sizes[] = {
12544, 64, 147,
3136, 64, 64,
3136, 192, 576,
784, 64, 192,
784, 96, 192,
784, 128, 864,
784, 16, 192,
784, 32, 400,
784, 32, 192,
784, 128, 256,
784, 128, 256,
784, 192, 1152,
784, 32, 256,
784, 96, 800,
784, 64, 256,
196, 192, 480,
196, 96, 480,
196, 204, 864,
196, 16, 480,
196, 48, 400,
196, 64, 480,
196, 160, 508,
196, 112, 508,
196, 224, 1008,
196, 24, 508,
196, 64, 600,
196, 64, 508,
196, 128, 512,
196, 128, 512,
196, 256, 1152,
196, 24, 512,
196, 64, 600,
196, 64, 512,
196, 112, 512,
196, 144, 512,
196, 288, 1296,
196, 32, 512,
196, 64, 800,
196, 64, 512,
196, 256, 528,
196, 160, 528,
196, 320, 1440,
196, 32, 528,
196, 128, 800,
196, 128, 528,
49, 256, 832,
49, 160, 832,
49, 320, 1440,
49, 48, 832,
49, 128, 1200,
49, 128, 832,
49, 384, 832,
49, 192, 832,
49, 384, 1728,
49, 48, 832,
49, 128, 1200,
49, 128, 832,
16, 128, 508,
1, 1024, 2048,
1, 1008, 1024,
16, 128, 528,
1, 1024, 2048,
1, 1008, 1024,
1, 1008, 1024,
};
const int param_count =
sizeof(googlenet_gemm_sizes) / sizeof(googlenet_gemm_sizes[0]);
const int gemm_count = param_count / 3;
const int repeat = 2;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> ResultType;
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::RegisterCurrentThreadForProfiling();
gemmlowp::StartProfiling();
#endif
float total_time = 0;
// We don't record the first repetition, it's just warm-up.
for (int r = 0; r < repeat + 1; r++) {
std::cout << "repetition " << r + 1 << "/" << repeat + 1 << "...\r"
<< std::flush;
for (int gemm_index = 0; gemm_index < gemm_count; ++gemm_index) {
float gemm_time = 0;
const int rows = googlenet_gemm_sizes[(gemm_index * 3) + 1];
const int cols = googlenet_gemm_sizes[(gemm_index * 3) + 0];
const int depth = googlenet_gemm_sizes[(gemm_index * 3) + 2];
if (cols > KernelForGEMM::Format::kCols / 2) {
gemm_time =
time_for_gemm_size<KernelForGEMM, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
} else {
gemm_time =
time_for_gemm_size<KernelForGEMV, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
}
if (r > 0) {
total_time += gemm_time;
}
}
}
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::FinishProfiling();
#endif
const float ms_per_network = (total_time / repeat) * 1000.0f;
std::cout.precision(4);
std::cout << "GoogLeNet GEMMs took " << ms_per_network << "ms" << std::endl;
}
} // end namespace gemmlowp
int main() {
{
gemmlowp::GemmContext context;
std::cout << "Benchmarking default mode (typically multi-threaded)..."
<< std::endl;
gemmlowp::benchmark(&context);
}
{
gemmlowp::GemmContext context;
context.set_max_num_threads(1);
std::cout << "Benchmarking single-threaded mode..." << std::endl;
gemmlowp::benchmark(&context);
}
{
gemmlowp::GemmContext context;
std::cout << "Benchmarking typical GoogLeNet GEMMs..." << std::endl;
gemmlowp::benchmark_googlenet(&context);
}
}
<commit_msg>unbreak compilation of the benchmark, allow benchmarking specific bit depths<commit_after>// Copyright 2015 Google Inc. 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 <unistd.h>
#ifdef __APPLE__
#include <sys/time.h>
#endif
#include <iostream>
#include <ctime>
#include <cstdint>
#include <vector>
#include <map>
#include <cstdlib>
#include "test.h"
#include "../public/gemmlowp.h"
#if defined(__arm__) && !defined(GEMMLOWP_NEON)
#warning "Building without NEON support on ARM, check your compiler setup!"
#endif
namespace gemmlowp {
double time() {
#ifdef __APPLE__
timeval t;
gettimeofday(&t, nullptr);
return t.tv_sec + 1e-6 * t.tv_usec;
#else
timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv_sec + 1e-9 * t.tv_nsec;
#endif
}
const double min_accurate_duration = 1e-1;
const std::size_t min_working_set_size = 16 * 1024 * 1024;
template <typename Kernel, typename LhsType, typename RhsType,
typename ResultType>
double time_for_gemm_size(GemmContext* context, int rows, int depth,
int cols) {
typedef std::uint8_t Scalar;
// set up the matrix pool
const std::size_t combined_three_matrices_sizes =
sizeof(Scalar) * (rows * depth + depth * cols + rows * cols);
const std::size_t matrix_pool_size =
1 + min_working_set_size / combined_three_matrices_sizes;
std::vector<LhsType> lhs(matrix_pool_size);
std::vector<RhsType> rhs(matrix_pool_size);
std::vector<ResultType> result(matrix_pool_size);
lhs[0].Resize(rows, depth);
MakeConstant(&lhs[0], 128);
rhs[0].Resize(depth, cols);
MakeConstant(&rhs[0], 128);
result[0].Resize(rows, cols);
MakeZero(&result[0]);
for (std::size_t i = 1; i < matrix_pool_size; i++) {
lhs[i] = lhs[0];
rhs[i] = rhs[0];
result[i] = result[0];
}
const int depth_shift = static_cast<int>(
std::ceil(0.5 * std::log(static_cast<float>(depth)) / std::log(2.0f)));
// main benchmark loop
int iters_at_a_time = 1;
float time_per_iter = 0.0f;
std::size_t matrix_index = 0;
while (true) {
double starttime = time();
for (int i = 0; i < iters_at_a_time; i++) {
Gemm<std::uint8_t, Kernel::kBitDepthSetting>(
context, lhs[matrix_index].const_map(),
rhs[matrix_index].const_map(), &result[matrix_index].map(), -75, -91,
74980, 123, 18 + depth_shift);
matrix_index++;
if (matrix_index == matrix_pool_size) {
matrix_index = 0;
}
}
double endtime = time();
const float timing = static_cast<float>(endtime - starttime);
if (timing >= min_accurate_duration) {
time_per_iter = timing / iters_at_a_time;
break;
}
iters_at_a_time *= 2;
}
return time_per_iter;
}
template <typename Kernel, typename LhsType, typename RhsType,
typename ResultType>
double gflops_for_gemm_size(GemmContext* context, int rows, int depth,
int cols) {
const double time_per_iter =
time_for_gemm_size<Kernel, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
return 2e-9 * rows * depth * cols / time_per_iter;
}
#ifndef GEMMLOWP_TEST_BIT_DEPTH
#define GEMMLOWP_TEST_BIT_DEPTH L8R8
#endif
#ifdef GEMMLOWP_TEST_KERNEL
typedef gemmlowp::GEMMLOWP_TEST_KERNEL KernelForGEMM;
typedef gemmlowp::GEMMLOWP_TEST_KERNEL KernelForGEMV;
#else
typedef gemmlowp::DefaultKernelForGemm<BitDepthSetting::GEMMLOWP_TEST_BIT_DEPTH> KernelForGEMM;
typedef gemmlowp::DefaultKernelForGemm<BitDepthSetting::GEMMLOWP_TEST_BIT_DEPTH> KernelForGEMV;
#endif
void benchmark(GemmContext* context) {
std::map<std::tuple<int, int, int>, std::vector<double>> benchmark_results;
std::vector<std::tuple<int, int, int>> benchmark_sizes;
benchmark_sizes.emplace_back(10, 10, 10);
benchmark_sizes.emplace_back(20, 20, 20);
benchmark_sizes.emplace_back(30, 30, 30);
benchmark_sizes.emplace_back(40, 40, 40);
benchmark_sizes.emplace_back(50, 50, 50);
benchmark_sizes.emplace_back(60, 60, 60);
benchmark_sizes.emplace_back(64, 256, 147);
benchmark_sizes.emplace_back(100, 100, 1);
benchmark_sizes.emplace_back(100, 100, 100);
benchmark_sizes.emplace_back(100, 1000, 100);
benchmark_sizes.emplace_back(1000, 1000, 1);
benchmark_sizes.emplace_back(1000, 1000, 10);
benchmark_sizes.emplace_back(1000, 1000, 100);
benchmark_sizes.emplace_back(1000, 1000, 1000);
const int repeat = 2;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> ResultType;
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::RegisterCurrentThreadForProfiling();
gemmlowp::StartProfiling();
#endif
// We don't record the first repetition, it's just warm-up.
for (int r = 0; r < repeat + 1; r++) {
std::cout << "repetition " << r + 1 << "/" << repeat + 1 << "...\r"
<< std::flush;
for (auto s : benchmark_sizes) {
double gflops = 0;
int rows = std::get<0>(s);
int depth = std::get<1>(s);
int cols = std::get<2>(s);
if (cols > KernelForGEMM::Format::kCols / 2) {
gflops =
gflops_for_gemm_size<KernelForGEMM, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
} else {
gflops =
gflops_for_gemm_size<KernelForGEMV, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
}
if (r > 0) {
benchmark_results[s].emplace_back(gflops);
}
}
}
std::cout << " \r"
<< std::flush;
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::FinishProfiling();
#endif
std::cout.precision(4);
for (auto b : benchmark_results) {
sort(b.second.begin(), b.second.end());
std::cout << std::get<0>(b.first) << "x" << std::get<1>(b.first) << "x"
<< std::get<2>(b.first) << " : " << b.second.back() << " GFlops/s"
<< std::endl;
}
std::cout << std::endl;
}
void benchmark_googlenet(GemmContext* context) {
// These are the m, n, k sizes for a typical GoogLeNet.
const int googlenet_gemm_sizes[] = {
12544, 64, 147,
3136, 64, 64,
3136, 192, 576,
784, 64, 192,
784, 96, 192,
784, 128, 864,
784, 16, 192,
784, 32, 400,
784, 32, 192,
784, 128, 256,
784, 128, 256,
784, 192, 1152,
784, 32, 256,
784, 96, 800,
784, 64, 256,
196, 192, 480,
196, 96, 480,
196, 204, 864,
196, 16, 480,
196, 48, 400,
196, 64, 480,
196, 160, 508,
196, 112, 508,
196, 224, 1008,
196, 24, 508,
196, 64, 600,
196, 64, 508,
196, 128, 512,
196, 128, 512,
196, 256, 1152,
196, 24, 512,
196, 64, 600,
196, 64, 512,
196, 112, 512,
196, 144, 512,
196, 288, 1296,
196, 32, 512,
196, 64, 800,
196, 64, 512,
196, 256, 528,
196, 160, 528,
196, 320, 1440,
196, 32, 528,
196, 128, 800,
196, 128, 528,
49, 256, 832,
49, 160, 832,
49, 320, 1440,
49, 48, 832,
49, 128, 1200,
49, 128, 832,
49, 384, 832,
49, 192, 832,
49, 384, 1728,
49, 48, 832,
49, 128, 1200,
49, 128, 832,
16, 128, 508,
1, 1024, 2048,
1, 1008, 1024,
16, 128, 528,
1, 1024, 2048,
1, 1008, 1024,
1, 1008, 1024,
};
const int param_count =
sizeof(googlenet_gemm_sizes) / sizeof(googlenet_gemm_sizes[0]);
const int gemm_count = param_count / 3;
const int repeat = 2;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> ResultType;
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::RegisterCurrentThreadForProfiling();
gemmlowp::StartProfiling();
#endif
float total_time = 0;
// We don't record the first repetition, it's just warm-up.
for (int r = 0; r < repeat + 1; r++) {
std::cout << "repetition " << r + 1 << "/" << repeat + 1 << "...\r"
<< std::flush;
for (int gemm_index = 0; gemm_index < gemm_count; ++gemm_index) {
float gemm_time = 0;
const int rows = googlenet_gemm_sizes[(gemm_index * 3) + 1];
const int cols = googlenet_gemm_sizes[(gemm_index * 3) + 0];
const int depth = googlenet_gemm_sizes[(gemm_index * 3) + 2];
if (cols > KernelForGEMM::Format::kCols / 2) {
gemm_time =
time_for_gemm_size<KernelForGEMM, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
} else {
gemm_time =
time_for_gemm_size<KernelForGEMV, LhsType, RhsType, ResultType>(
context, rows, depth, cols);
}
if (r > 0) {
total_time += gemm_time;
}
}
}
#ifdef GEMMLOWP_TEST_PROFILE
gemmlowp::FinishProfiling();
#endif
const float ms_per_network = (total_time / repeat) * 1000.0f;
std::cout.precision(4);
std::cout << "GoogLeNet GEMMs took " << ms_per_network << "ms" << std::endl;
}
} // end namespace gemmlowp
int main() {
{
gemmlowp::GemmContext context;
std::cout << "Benchmarking default mode (typically multi-threaded)..."
<< std::endl;
gemmlowp::benchmark(&context);
}
{
gemmlowp::GemmContext context;
context.set_max_num_threads(1);
std::cout << "Benchmarking single-threaded mode..." << std::endl;
gemmlowp::benchmark(&context);
}
{
gemmlowp::GemmContext context;
std::cout << "Benchmarking typical GoogLeNet GEMMs..." << std::endl;
gemmlowp::benchmark_googlenet(&context);
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <glib.h>
#include <sys/stat.h>
#include <boost/test/unit_test.hpp>
#include "ds3.h"
#include "ds3_net.h"
#include "test.h"
#define BUFF_SIZE 16
typedef struct {
uint8_t num_threads;
uint8_t thread_num;
ds3_client* client;
char* job_id;
char* src_object_name;
char* bucket_name;
ds3_master_object_list_response* chunks_list;
} test_put_chunks_args;
ds3_bulk_object_list_response* create_bulk_object_list_single_file(const char* file_name, size_t num_files) {
char put_filename[BUFF_SIZE];
struct stat file_info;
memset(&file_info, 0, sizeof(struct stat));
stat(file_name, &file_info);
printf("%s: %ld\n", file_name, file_info.st_size);
ds3_bulk_object_list_response* obj_list = ds3_init_bulk_object_list();
GPtrArray* ds3_bulk_object_response_array = g_ptr_array_new();
for (size_t index = 0; index < num_files; index++) {
g_snprintf(put_filename, BUFF_SIZE, "file_%05lu", index);
ds3_bulk_object_response* obj = g_new0(ds3_bulk_object_response, 1);
obj->name = ds3_str_init(put_filename);
obj->length = file_info.st_size;
g_ptr_array_add(ds3_bulk_object_response_array, obj);
}
obj_list->objects = (ds3_bulk_object_response**)ds3_bulk_object_response_array->pdata;
obj_list->num_objects = ds3_bulk_object_response_array->len;
g_ptr_array_free(ds3_bulk_object_response_array, FALSE);
return obj_list;
}
void put_chunks(void* args) {
test_put_chunks_args* put_chunks_args = (test_put_chunks_args*)args;
ds3_objects_response* chunk_object_list = NULL;
for (size_t chunk_index = 0; chunk_index < put_chunks_args->chunks_list->num_objects; chunk_index++) {
chunk_object_list = put_chunks_args->chunks_list->objects[chunk_index];
for (size_t object_index = 0; object_index < chunk_object_list->num_objects; object_index++) {
// Work distribution
if (object_index % put_chunks_args->num_threads == put_chunks_args->thread_num) {
ds3_bulk_object_response* object = chunk_object_list->objects[object_index];
FILE* file = fopen(put_chunks_args->src_object_name, "r");
if (file == NULL) {
printf("Unable to open %s for read (FILE NULL), skipping put to bucket %s!\n", put_chunks_args->src_object_name, put_chunks_args->bucket_name);
return;
}
ds3_request* request = ds3_init_put_object_request(put_chunks_args->bucket_name, object->name->value, object->length);
ds3_request_set_job(request, put_chunks_args->job_id);
printf("Thread %d PUT %s\n", put_chunks_args->thread_num, object->name->value);
ds3_error* error = ds3_put_object_request(put_chunks_args->client, request, file, ds3_read_from_file);
ds3_request_free(request);
fclose(file);
handle_error(error);
}
}
}
}
BOOST_AUTO_TEST_CASE( bulk_put_10k_very_small_files ) {
printf("-----Testing Bulk PUT of 10k very small files-------\n");
ds3_request* request = NULL;
const char* bucket_name = "test_bulk_put_10k_very_small_files_bucket";
const char* object_name = "resources/very_small_file.txt";
ds3_master_object_list_response* bulk_response = NULL;
ds3_bulk_object_list_response* object_list = create_bulk_object_list_single_file(object_name, 10000);
ds3_client* client = get_client();
ds3_error* error = create_bucket_with_data_policy(client, bucket_name, ids.data_policy_id->value);
request = ds3_init_put_bulk_job_spectra_s3_request(bucket_name, object_list);
error = ds3_put_bulk_job_spectra_s3_request(client, request, &bulk_response);
ds3_request_free(request);
ds3_bulk_object_list_response_free(object_list);
handle_error(error);
test_put_chunks_args* put_chunks_args = g_new0(test_put_chunks_args, 1);
put_chunks_args->client = client;
put_chunks_args->num_threads = 1;
put_chunks_args->thread_num = 0;
put_chunks_args->job_id = bulk_response->job_id->value;
put_chunks_args->src_object_name = (char*)object_name;
put_chunks_args->bucket_name = (char*)bucket_name;
put_chunks_args->chunks_list = ensure_available_chunks(client, bulk_response->job_id);
put_chunks(put_chunks_args);
ds3_master_object_list_response_free(put_chunks_args->chunks_list);
ds3_master_object_list_response_free(bulk_response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE( bulk_put_200_very_small_files_multithreaded ) {
printf("-----Testing Bulk PUT of 200 very small files in parallel-------\n");
const char* bucket_name = "test_bulk_put_200_very_small_files_multithreaded";
const char* object_name = "resources/very_small_file.txt";
ds3_request* request = NULL;
ds3_master_object_list_response* bulk_response = NULL;
ds3_bulk_object_list_response* object_list = create_bulk_object_list_single_file(object_name, 200);
ds3_client* client = get_client();
ds3_error* error = create_bucket_with_data_policy(client, bucket_name, ids.data_policy_id->value);
request = ds3_init_put_bulk_job_spectra_s3_request(bucket_name, object_list);
error = ds3_put_bulk_job_spectra_s3_request(client, request, &bulk_response);
ds3_request_free(request);
ds3_bulk_object_list_response_free(object_list);
handle_error(error);
ds3_master_object_list_response* chunk_response = ensure_available_chunks(client, bulk_response->job_id);
// send to child thread 1
test_put_chunks_args* put_odd_chunks_args = g_new0(test_put_chunks_args, 1);
put_odd_chunks_args->client = client;
put_odd_chunks_args->job_id = bulk_response->job_id->value;
put_odd_chunks_args->src_object_name = (char*)object_name;
put_odd_chunks_args->bucket_name = (char*)bucket_name;
put_odd_chunks_args->chunks_list = chunk_response;
put_odd_chunks_args->thread_num = 0;
put_odd_chunks_args->num_threads = 2;
// send to child thread 2
test_put_chunks_args* put_even_chunks_args = g_new0(test_put_chunks_args, 1);
put_even_chunks_args->client = client;
put_even_chunks_args->job_id = bulk_response->job_id->value;
put_even_chunks_args->src_object_name = (char*)object_name;
put_even_chunks_args->bucket_name = (char*)bucket_name;
put_even_chunks_args->chunks_list = chunk_response;
put_even_chunks_args->thread_num = 1;
put_even_chunks_args->num_threads = 2;
GThread* even_chunks_thread = g_thread_new("even_chunks", (GThreadFunc)put_chunks, put_even_chunks_args);
GThread* odd_chunks_thread = g_thread_new("odd_chunks", (GThreadFunc)put_chunks, put_odd_chunks_args);
g_thread_join(even_chunks_thread);
g_thread_join(odd_chunks_thread);
printf("Children worker threads done\n");
ds3_master_object_list_response_free(chunk_response);
ds3_master_object_list_response_free(bulk_response);
clear_bucket(client, bucket_name);
free_client(client);
}
<commit_msg>Fix memory leaks<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <glib.h>
#include <sys/stat.h>
#include <boost/test/unit_test.hpp>
#include "ds3.h"
#include "ds3_net.h"
#include "test.h"
#define BUFF_SIZE 16
typedef struct {
uint8_t num_threads;
uint8_t thread_num;
ds3_client* client;
char* job_id;
char* src_object_name;
char* bucket_name;
ds3_master_object_list_response* chunks_list;
} test_put_chunks_args;
ds3_bulk_object_list_response* create_bulk_object_list_single_file(const char* file_name, size_t num_files) {
char put_filename[BUFF_SIZE];
struct stat file_info;
memset(&file_info, 0, sizeof(struct stat));
stat(file_name, &file_info);
printf("%s: %ld\n", file_name, file_info.st_size);
ds3_bulk_object_list_response* obj_list = ds3_init_bulk_object_list();
GPtrArray* ds3_bulk_object_response_array = g_ptr_array_new();
for (size_t index = 0; index < num_files; index++) {
g_snprintf(put_filename, BUFF_SIZE, "file_%05lu", index);
ds3_bulk_object_response* obj = g_new0(ds3_bulk_object_response, 1);
obj->name = ds3_str_init(put_filename);
obj->length = file_info.st_size;
g_ptr_array_add(ds3_bulk_object_response_array, obj);
}
obj_list->objects = (ds3_bulk_object_response**)ds3_bulk_object_response_array->pdata;
obj_list->num_objects = ds3_bulk_object_response_array->len;
g_ptr_array_free(ds3_bulk_object_response_array, FALSE);
return obj_list;
}
void put_chunks(void* args) {
test_put_chunks_args* put_chunks_args = (test_put_chunks_args*)args;
ds3_objects_response* chunk_object_list = NULL;
for (size_t chunk_index = 0; chunk_index < put_chunks_args->chunks_list->num_objects; chunk_index++) {
chunk_object_list = put_chunks_args->chunks_list->objects[chunk_index];
for (size_t object_index = 0; object_index < chunk_object_list->num_objects; object_index++) {
// Work distribution
if (object_index % put_chunks_args->num_threads == put_chunks_args->thread_num) {
ds3_bulk_object_response* object = chunk_object_list->objects[object_index];
FILE* file = fopen(put_chunks_args->src_object_name, "r");
if (file == NULL) {
printf("Unable to open %s for read (FILE NULL), skipping put to bucket %s!\n", put_chunks_args->src_object_name, put_chunks_args->bucket_name);
return;
}
ds3_request* request = ds3_init_put_object_request(put_chunks_args->bucket_name, object->name->value, object->length);
ds3_request_set_job(request, put_chunks_args->job_id);
printf("Thread %d PUT %s\n", put_chunks_args->thread_num, object->name->value);
ds3_error* error = ds3_put_object_request(put_chunks_args->client, request, file, ds3_read_from_file);
ds3_request_free(request);
fclose(file);
handle_error(error);
}
}
}
}
BOOST_AUTO_TEST_CASE( bulk_put_10k_very_small_files ) {
printf("-----Testing Bulk PUT of 10k very small files-------\n");
ds3_request* request = NULL;
const char* bucket_name = "test_bulk_put_10k_very_small_files_bucket";
const char* object_name = "resources/very_small_file.txt";
ds3_master_object_list_response* bulk_response = NULL;
ds3_bulk_object_list_response* object_list = create_bulk_object_list_single_file(object_name, 10000);
ds3_client* client = get_client();
ds3_error* error = create_bucket_with_data_policy(client, bucket_name, ids.data_policy_id->value);
request = ds3_init_put_bulk_job_spectra_s3_request(bucket_name, object_list);
error = ds3_put_bulk_job_spectra_s3_request(client, request, &bulk_response);
ds3_request_free(request);
ds3_bulk_object_list_response_free(object_list);
handle_error(error);
test_put_chunks_args* put_chunks_args = g_new0(test_put_chunks_args, 1);
put_chunks_args->client = client;
put_chunks_args->num_threads = 1;
put_chunks_args->thread_num = 0;
put_chunks_args->job_id = bulk_response->job_id->value;
put_chunks_args->src_object_name = (char*)object_name;
put_chunks_args->bucket_name = (char*)bucket_name;
put_chunks_args->chunks_list = ensure_available_chunks(client, bulk_response->job_id);
put_chunks(put_chunks_args);
ds3_master_object_list_response_free(put_chunks_args->chunks_list);
ds3_master_object_list_response_free(bulk_response);
g_free(put_chunks_args);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE( bulk_put_200_very_small_files_multithreaded ) {
printf("-----Testing Bulk PUT of 200 very small files in parallel-------\n");
const char* bucket_name = "test_bulk_put_200_very_small_files_multithreaded";
const char* object_name = "resources/very_small_file.txt";
ds3_request* request = NULL;
ds3_master_object_list_response* bulk_response = NULL;
ds3_bulk_object_list_response* object_list = create_bulk_object_list_single_file(object_name, 200);
ds3_client* client = get_client();
ds3_error* error = create_bucket_with_data_policy(client, bucket_name, ids.data_policy_id->value);
request = ds3_init_put_bulk_job_spectra_s3_request(bucket_name, object_list);
error = ds3_put_bulk_job_spectra_s3_request(client, request, &bulk_response);
ds3_request_free(request);
ds3_bulk_object_list_response_free(object_list);
handle_error(error);
ds3_master_object_list_response* chunk_response = ensure_available_chunks(client, bulk_response->job_id);
// send to child thread 1
test_put_chunks_args* put_odd_chunks_args = g_new0(test_put_chunks_args, 1);
put_odd_chunks_args->client = client;
put_odd_chunks_args->job_id = bulk_response->job_id->value;
put_odd_chunks_args->src_object_name = (char*)object_name;
put_odd_chunks_args->bucket_name = (char*)bucket_name;
put_odd_chunks_args->chunks_list = chunk_response;
put_odd_chunks_args->thread_num = 0;
put_odd_chunks_args->num_threads = 2;
// send to child thread 2
test_put_chunks_args* put_even_chunks_args = g_new0(test_put_chunks_args, 1);
put_even_chunks_args->client = client;
put_even_chunks_args->job_id = bulk_response->job_id->value;
put_even_chunks_args->src_object_name = (char*)object_name;
put_even_chunks_args->bucket_name = (char*)bucket_name;
put_even_chunks_args->chunks_list = chunk_response;
put_even_chunks_args->thread_num = 1;
put_even_chunks_args->num_threads = 2;
GThread* even_chunks_thread = g_thread_new("even_chunks", (GThreadFunc)put_chunks, put_even_chunks_args);
GThread* odd_chunks_thread = g_thread_new("odd_chunks", (GThreadFunc)put_chunks, put_odd_chunks_args);
g_thread_join(even_chunks_thread);
g_thread_join(odd_chunks_thread);
printf("Children worker threads done\n");
ds3_master_object_list_response_free(chunk_response);
ds3_master_object_list_response_free(bulk_response);
g_free(put_odd_chunks_args);
g_free(put_even_chunks_args);
clear_bucket(client, bucket_name);
free_client(client);
}
<|endoftext|> |
<commit_before>// KMail Account Manager
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmacctmgr.h"
#include "kmacctmaildir.h"
#include "kmacctlocal.h"
#include "kmacctexppop.h"
#include "kmacctimap.h"
#include "kmacctcachedimap.h"
#include "kmkernel.h"
#include "kmbroadcaststatus.h"
#include "kmfiltermgr.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kconfig.h>
#include <qstringlist.h>
#include <qregexp.h>
//-----------------------------------------------------------------------------
KMAcctMgr::KMAcctMgr(): KMAcctMgrInherited()
{
mAcctList.setAutoDelete(TRUE);
checking = false;
moreThanOneAccount = false;
lastAccountChecked = 0;
mTotalNewMailsArrived=0;
}
//-----------------------------------------------------------------------------
KMAcctMgr::~KMAcctMgr()
{
writeConfig(FALSE);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::writeConfig(bool withSync)
{
KConfig* config = KMKernel::config();
QString groupName;
KConfigGroupSaver saver(config, "General");
config->writeEntry("accounts", mAcctList.count());
// first delete all account groups in the config file:
QStringList accountGroups =
config->groupList().grep( QRegExp( "Account \\d+" ) );
for ( QStringList::Iterator it = accountGroups.begin() ;
it != accountGroups.end() ; ++it )
config->deleteGroup( *it );
// now write new account groups:
int i = 1;
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it, ++i ) {
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
(*it)->writeConfig(*config);
}
if (withSync) config->sync();
}
//-----------------------------------------------------------------------------
void KMAcctMgr::readConfig(void)
{
KConfig* config = KMKernel::config();
KMAccount* acct;
QString acctType, acctName;
QCString groupName;
int i, num;
mAcctList.clear();
KConfigGroup general(config, "General");
num = general.readNumEntry("accounts", 0);
for (i=1; i<=num; i++)
{
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
acctType = config->readEntry("Type");
// Provide backwards compatibility
if (acctType == "advanced pop" || acctType == "experimental pop")
acctType = "pop";
acctName = config->readEntry("Name");
if (acctName.isEmpty()) acctName = i18n("Account %1").arg(i);
acct = create(acctType, acctName);
if (!acct) continue;
add(acct);
acct->readConfig(*config);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleCheckMail(KMAccount *account, bool _interactive)
{
newMailArrived = false;
interactive = _interactive;
if (!mAcctChecking.contains(account)) mAcctChecking.append(account);
if (checking) {
if (mAcctChecking.count() > 1) moreThanOneAccount = true;
// sorryCheckAlreadyInProgress(_interactive);
return;
}
// if (account->folder() == 0)
// {
// QString tmp; //Unsafe
// tmp = i18n("Account %1 has no mailbox defined!\n"
// "Mail checking aborted.\n"
// "Check your account settings!")
// .arg(account->name());
// KMessageBox::information(0,tmp);
// return;
// }
checking = true;
kdDebug(5006) << "checking mail, server busy" << endl;
kernel->serverReady (false);
lastAccountChecked = 0;
processNextCheck(false);
}
void KMAcctMgr::processNextCheck(bool _newMail)
{
KMAccount *curAccount = 0;
newMailArrived |= _newMail;
if (lastAccountChecked)
disconnect( lastAccountChecked, SIGNAL(finishedCheck(bool)),
this, SLOT(processNextCheck(bool)) );
if (mAcctChecking.isEmpty() ||
(((curAccount = mAcctChecking.take(0)) == lastAccountChecked))) {
kernel->filterMgr()->cleanup();
kdDebug(5006) << "checked mail, server ready" << endl;
kernel->serverReady (true);
checking = false;
if (mTotalNewMailsArrived > 0 && moreThanOneAccount)
KMBroadcastStatus::instance()->setStatusMsg(
i18n("Transmission completed, %n new message.",
"Transmission completed, %n new messages.", mTotalNewMailsArrived));
emit checkedMail(newMailArrived, interactive);
moreThanOneAccount = false;
mTotalNewMailsArrived = 0;
return;
}
connect( curAccount, SIGNAL(finishedCheck(bool)),
this, SLOT(processNextCheck(bool)) );
lastAccountChecked = curAccount;
if (curAccount->type() != "imap" && curAccount->folder() == 0)
{
QString tmp; //Unsafe
tmp = i18n("Account %1 has no mailbox defined!\n"
"Mail checking aborted.\n"
"Check your account settings!")
.arg(curAccount->name());
KMessageBox::information(0,tmp);
processNextCheck(false);
}
kdDebug(5006) << "processing next mail check, server busy" << endl;
curAccount->processNewMail(interactive);
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::create(const QString &aType, const QString &aName)
{
KMAccount* act = 0;
if (aType == "local")
act = new KMAcctLocal(this, aName);
if (aType == "maildir")
act = new KMAcctMaildir(this, aName);
else if (aType == "pop")
act = new KMAcctExpPop(this, aName);
else if (aType == "imap")
act = new KMAcctImap(this, aName);
else if (aType == "cachedimap")
act = new KMAcctCachedImap(this, aName);
if (act)
{
act->setFolder(kernel->inboxFolder());
connect( act, SIGNAL(newMailsProcessed(int)),
this, SLOT(addToTotalNewMailCount(int)) );
}
return act;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::add(KMAccount *account)
{
if (account)
mAcctList.append(account);
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::find(const QString &aName)
{
KMAccount* cur;
if (aName.isEmpty()) return 0;
for (cur=mAcctList.first(); cur; cur=mAcctList.next())
{
if (cur->name() == aName) return cur;
}
return 0;
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::first(void)
{
return mAcctList.first();
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::next(void)
{
return mAcctList.next();
}
//-----------------------------------------------------------------------------
bool KMAcctMgr::remove(KMAccount* acct)
{
//assert(acct != 0);
if(!acct)
return FALSE;
mAcctList.remove(acct);
return TRUE;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::checkMail(bool _interactive)
{
newMailArrived = false;
if (checking) {
kdDebug(5006) << "already checking mail" << endl;
if (lastAccountChecked)
kdDebug(5006) << "currently checking " << lastAccountChecked->name() << endl;
KMAccount* cur;
for (cur=mAcctList.first(); cur; cur=mAcctList.next())
kdDebug(5006) << "queued " << cur->name() << endl;
// sorryCheckAlreadyInProgress(_interactive);
return;
}
if (mAcctList.isEmpty())
{
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
mTotalNewMailsArrived=0;
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it )
{
if (!it.current()->checkExclude())
singleCheckMail(it.current(), _interactive);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleInvalidateIMAPFolders(KMAccount *account) {
account->invalidateIMAPFolders();
}
void KMAcctMgr::invalidateIMAPFolders()
{
if (mAcctList.isEmpty()) {
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
singleInvalidateIMAPFolders(it.current());
}
//-----------------------------------------------------------------------------
QStringList KMAcctMgr::getAccounts(bool noImap) {
KMAccount *cur;
QStringList strList;
for (cur=mAcctList.first(); cur; cur=mAcctList.next()) {
if (!noImap || cur->type() != "imap") strList.append(cur->name());
}
return strList;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::intCheckMail(int item, bool _interactive) {
KMAccount* cur;
newMailArrived = false;
if (checking)
return;
if (mAcctList.isEmpty())
{
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
int x = 0;
cur = mAcctList.first();
while (cur)
{
x++;
if (x > item) break;
cur=mAcctList.next();
}
if (cur->type() != "imap" && cur->folder() == 0)
{
QString tmp;
tmp = i18n("Account %1 has no mailbox defined!\n"
"Mail checking aborted.\n"
"Check your account settings!")
.arg(cur->name());
KMessageBox::information(0,tmp);
return;
}
singleCheckMail(cur, _interactive);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::addToTotalNewMailCount(int newmails)
{
if ( newmails==-1 ) mTotalNewMailsArrived=-1;
if ( mTotalNewMailsArrived==-1 ) return;
mTotalNewMailsArrived+=newmails;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::sorryCheckAlreadyInProgress(bool aInteractive)
{
if (aInteractive && lastAccountChecked)
KMessageBox::sorry(
0,
i18n( "Mail checking of the %1 account is already in progress."
).arg( lastAccountChecked->name() ));
}
//-----------------------------------------------------------------------------
#include "kmacctmgr.moc"
<commit_msg>Integrate from make_it_cool, check for cached imap.<commit_after>// KMail Account Manager
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmacctmgr.h"
#include "kmacctmaildir.h"
#include "kmacctlocal.h"
#include "kmacctexppop.h"
#include "kmacctimap.h"
#include "kmacctcachedimap.h"
#include "kmbroadcaststatus.h"
#include "kmkernel.h"
#include "kmfiltermgr.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kconfig.h>
#include <qstringlist.h>
#include <qregexp.h>
//-----------------------------------------------------------------------------
KMAcctMgr::KMAcctMgr(): KMAcctMgrInherited()
{
mAcctList.setAutoDelete(TRUE);
checking = false;
moreThanOneAccount = false;
lastAccountChecked = 0;
mTotalNewMailsArrived=0;
}
//-----------------------------------------------------------------------------
KMAcctMgr::~KMAcctMgr()
{
writeConfig(FALSE);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::writeConfig(bool withSync)
{
KConfig* config = KMKernel::config();
QString groupName;
KConfigGroupSaver saver(config, "General");
config->writeEntry("accounts", mAcctList.count());
// first delete all account groups in the config file:
QStringList accountGroups =
config->groupList().grep( QRegExp( "Account \\d+" ) );
for ( QStringList::Iterator it = accountGroups.begin() ;
it != accountGroups.end() ; ++it )
config->deleteGroup( *it );
// now write new account groups:
int i = 1;
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it, ++i ) {
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
(*it)->writeConfig(*config);
}
if (withSync) config->sync();
}
//-----------------------------------------------------------------------------
void KMAcctMgr::readConfig(void)
{
KConfig* config = KMKernel::config();
KMAccount* acct;
QString acctType, acctName;
QCString groupName;
int i, num;
mAcctList.clear();
KConfigGroup general(config, "General");
num = general.readNumEntry("accounts", 0);
for (i=1; i<=num; i++)
{
groupName.sprintf("Account %d", i);
KConfigGroupSaver saver(config, groupName);
acctType = config->readEntry("Type");
// Provide backwards compatibility
if (acctType == "advanced pop" || acctType == "experimental pop")
acctType = "pop";
acctName = config->readEntry("Name");
if (acctName.isEmpty()) acctName = i18n("Account %1").arg(i);
acct = create(acctType, acctName);
if (!acct) continue;
add(acct);
acct->readConfig(*config);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleCheckMail(KMAccount *account, bool _interactive)
{
newMailArrived = false;
interactive = _interactive;
if (!mAcctChecking.contains(account)) mAcctChecking.append(account);
if (checking) {
if (mAcctChecking.count() > 1) moreThanOneAccount = true;
// sorryCheckAlreadyInProgress(_interactive);
return;
}
// if (account->folder() == 0)
// {
// QString tmp; //Unsafe
// tmp = i18n("Account %1 has no mailbox defined!\n"
// "Mail checking aborted.\n"
// "Check your account settings!")
// .arg(account->name());
// KMessageBox::information(0,tmp);
// return;
// }
checking = true;
kdDebug(5006) << "checking mail, server busy" << endl;
kernel->serverReady (false);
lastAccountChecked = 0;
processNextCheck(false);
}
void KMAcctMgr::processNextCheck(bool _newMail)
{
KMAccount *curAccount = 0;
newMailArrived |= _newMail;
if (lastAccountChecked)
disconnect( lastAccountChecked, SIGNAL(finishedCheck(bool)),
this, SLOT(processNextCheck(bool)) );
if (mAcctChecking.isEmpty() ||
(((curAccount = mAcctChecking.take(0)) == lastAccountChecked))) {
kernel->filterMgr()->cleanup();
kdDebug(5006) << "checked mail, server ready" << endl;
kernel->serverReady (true);
checking = false;
if (mTotalNewMailsArrived > 0 && moreThanOneAccount)
KMBroadcastStatus::instance()->setStatusMsg(
i18n("Transmission completed, %n new message.",
"Transmission completed, %n new messages.", mTotalNewMailsArrived));
emit checkedMail(newMailArrived, interactive);
moreThanOneAccount = false;
mTotalNewMailsArrived = 0;
return;
}
connect( curAccount, SIGNAL(finishedCheck(bool)),
this, SLOT(processNextCheck(bool)) );
lastAccountChecked = curAccount;
if (curAccount->type() != "imap" && curAccount->type() != "cachedimap" && curAccount->folder() == 0)
{
QString tmp; //Unsafe
tmp = i18n("Account %1 has no mailbox defined!\n"
"Mail checking aborted.\n"
"Check your account settings!")
.arg(curAccount->name());
KMessageBox::information(0,tmp);
processNextCheck(false);
}
kdDebug(5006) << "processing next mail check, server busy" << endl;
curAccount->processNewMail(interactive);
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::create(const QString &aType, const QString &aName)
{
KMAccount* act = 0;
if (aType == "local")
act = new KMAcctLocal(this, aName);
if (aType == "maildir")
act = new KMAcctMaildir(this, aName);
else if (aType == "pop")
act = new KMAcctExpPop(this, aName);
else if (aType == "imap")
act = new KMAcctImap(this, aName);
else if (aType == "cachedimap")
act = new KMAcctCachedImap(this, aName);
else if (aType == "cachedimap")
act = new KMAcctCachedImap(this, aName);
if (act)
{
act->setFolder(kernel->inboxFolder());
connect( act, SIGNAL(newMailsProcessed(int)),
this, SLOT(addToTotalNewMailCount(int)) );
}
return act;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::add(KMAccount *account)
{
if (account)
mAcctList.append(account);
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::find(const QString &aName)
{
KMAccount* cur;
if (aName.isEmpty()) return 0;
for (cur=mAcctList.first(); cur; cur=mAcctList.next())
{
if (cur->name() == aName) return cur;
}
return 0;
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::first(void)
{
return mAcctList.first();
}
//-----------------------------------------------------------------------------
KMAccount* KMAcctMgr::next(void)
{
return mAcctList.next();
}
//-----------------------------------------------------------------------------
bool KMAcctMgr::remove(KMAccount* acct)
{
//assert(acct != 0);
if(!acct)
return FALSE;
mAcctList.remove(acct);
return TRUE;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::checkMail(bool _interactive)
{
newMailArrived = false;
if (checking) {
kdDebug(5006) << "already checking mail" << endl;
if (lastAccountChecked)
kdDebug(5006) << "currently checking " << lastAccountChecked->name() << endl;
KMAccount* cur;
for (cur=mAcctList.first(); cur; cur=mAcctList.next())
kdDebug(5006) << "queued " << cur->name() << endl;
// sorryCheckAlreadyInProgress(_interactive);
return;
}
if (mAcctList.isEmpty())
{
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
mTotalNewMailsArrived=0;
for ( QPtrListIterator<KMAccount> it(mAcctList) ;
it.current() ; ++it )
{
if (!it.current()->checkExclude())
singleCheckMail(it.current(), _interactive);
}
}
//-----------------------------------------------------------------------------
void KMAcctMgr::singleInvalidateIMAPFolders(KMAccount *account) {
account->invalidateIMAPFolders();
}
void KMAcctMgr::invalidateIMAPFolders()
{
if (mAcctList.isEmpty()) {
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )
singleInvalidateIMAPFolders(it.current());
}
//-----------------------------------------------------------------------------
QStringList KMAcctMgr::getAccounts(bool noImap) {
KMAccount *cur;
QStringList strList;
for (cur=mAcctList.first(); cur; cur=mAcctList.next()) {
if (!noImap || cur->type() != "imap") strList.append(cur->name());
}
return strList;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::intCheckMail(int item, bool _interactive) {
KMAccount* cur;
newMailArrived = false;
if (checking)
return;
if (mAcctList.isEmpty())
{
KMessageBox::information(0,i18n("You need to add an account in the network "
"section of the settings in order to "
"receive mail."));
return;
}
int x = 0;
cur = mAcctList.first();
while (cur)
{
x++;
if (x > item) break;
cur=mAcctList.next();
}
if (cur->type() != "imap" && cur->type() != "cachedimap" && cur->folder() == 0)
{
QString tmp;
tmp = i18n("Account %1 has no mailbox defined!\n"
"Mail checking aborted.\n"
"Check your account settings!")
.arg(cur->name());
KMessageBox::information(0,tmp);
return;
}
singleCheckMail(cur, _interactive);
}
//-----------------------------------------------------------------------------
void KMAcctMgr::addToTotalNewMailCount(int newmails)
{
if ( newmails==-1 ) mTotalNewMailsArrived=-1;
if ( mTotalNewMailsArrived==-1 ) return;
mTotalNewMailsArrived+=newmails;
}
//-----------------------------------------------------------------------------
void KMAcctMgr::sorryCheckAlreadyInProgress(bool aInteractive)
{
if (aInteractive && lastAccountChecked)
KMessageBox::sorry(
0,
i18n( "Mail checking of the %1 account is already in progress."
).arg( lastAccountChecked->name() ));
}
//-----------------------------------------------------------------------------
#include "kmacctmgr.moc"
<|endoftext|> |
<commit_before>#include "../element.h"
#include "gtest/gtest.h"
#include <sstream>
#include <string>
#include <iostream>
#include <array>
#include <vector>
TEST(ExceptionText, FromNum)
{
try
{
bson::Element e(4, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: int and BSON type: string"), std::string(e.what()));
}
try
{
bson::Element e(4l, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: long and BSON type: string"), std::string(e.what()));
}
try
{
bson::Element e(3.14, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: double and BSON type: string"), std::string(e.what()));
}
try
{
bson::Element e(static_cast<short>(4), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: short and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromBin)
{
try
{
bson::Element e(bson::binary({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<char, std::string> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromOID)
{
try
{
bson::Element e(bson::oid({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::array<unsigned char, 12> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromBool)
{
try
{
bson::Element e(true, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: bool and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromDocument)
{
try
{
bson::Element e(bson::Document({{}}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: bson::Document and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromJSON)
{
try
{
bson::Element e(bson::jscode_scope({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<std::string, bson::Document> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromRegex)
{
try
{
bson::Element e(bson::regex({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<std::string, std::string> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromDBPtr)
{
try
{
bson::Element e(bson::dbptr({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<std::string, std::array<unsigned char, 12>> and BSON type: string"), std::string(e.what()));
}
}<commit_msg>test void exception text<commit_after>#include "../element.h"
#include "gtest/gtest.h"
#include <sstream>
#include <string>
#include <iostream>
#include <array>
#include <vector>
TEST(ExceptionText, FromNum)
{
try
{
bson::Element e(4, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: int and BSON type: string"), std::string(e.what()));
}
try
{
bson::Element e(4l, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: long and BSON type: string"), std::string(e.what()));
}
try
{
bson::Element e(3.14, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: double and BSON type: string"), std::string(e.what()));
}
try
{
bson::Element e(static_cast<short>(4), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: short and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromBin)
{
try
{
bson::Element e(bson::binary({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<char, std::string> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromOID)
{
try
{
bson::Element e(bson::oid({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::array<unsigned char, 12> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromBool)
{
try
{
bson::Element e(true, bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: bool and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromDocument)
{
try
{
bson::Element e(bson::Document({{}}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: bson::Document and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromJSON)
{
try
{
bson::Element e(bson::jscode_scope({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<std::string, bson::Document> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromRegex)
{
try
{
bson::Element e(bson::regex({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<std::string, std::string> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromDBPtr)
{
try
{
bson::Element e(bson::dbptr({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::pair<std::string, std::array<unsigned char, 12>> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromArr)
{
try
{
bson::Element e(bson::array({}), bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: std::vector<bson::Element> and BSON type: string"), std::string(e.what()));
}
}
TEST(ExceptionText, FromVoid)
{
try
{
bson::Element e;
e.make_void(bson::STRING);
FAIL();
}
catch (bson::type_error & e)
{
ASSERT_EQ(std::string ("Invalid conversion between C++ type: void and BSON type: string"), std::string(e.what()));
}
}<|endoftext|> |
<commit_before>#include "Point.hpp"
#include <math.h>
namespace Slic3r {
void
Point::scale(double factor)
{
this->x *= factor;
this->y *= factor;
}
void
Point::translate(double x, double y)
{
this->x += x;
this->y += y;
}
void
Point::rotate(double angle, Point* center)
{
double cur_x = (double)this->x;
double cur_y = (double)this->y;
this->x = (long)round( (double)center->x + cos(angle) * (cur_x - (double)center->x) - sin(angle) * (cur_y - (double)center->y) );
this->y = (long)round( (double)center->y + cos(angle) * (cur_y - (double)center->y) + sin(angle) * (cur_x - (double)center->x) );
}
bool
Point::coincides_with(const Point* point) const
{
return this->x == point->x && this->y == point->y;
}
int
Point::nearest_point_index(const Points points) const
{
int idx = -1;
long distance = -1;
for (Points::const_iterator it = points.begin(); it != points.end(); ++it) {
/* If the X distance of the candidate is > than the total distance of the
best previous candidate, we know we don't want it */
long d = pow(this->x - (*it).x, 2);
if (distance != -1 && d > distance) continue;
/* If the Y distance of the candidate is > than the total distance of the
best previous candidate, we know we don't want it */
d += pow(this->y - (*it).y, 2);
if (distance != -1 && d > distance) continue;
idx = it - points.begin();
distance = d;
if (distance < EPSILON) break;
}
return idx;
}
Point*
Point::nearest_point(Points points) const
{
return &(points.at(this->nearest_point_index(points)));
}
double
Point::distance_to(const Point* point) const
{
double dx = ((double)point->x - this->x);
double dy = ((double)point->y - this->y);
return sqrt(dx*dx + dy*dy);
}
#ifdef SLIC3RXS
SV*
Point::to_SV_ref() {
SV* sv = newSV(0);
sv_setref_pv( sv, "Slic3r::Point::Ref", (void*)this );
return sv;
}
SV*
Point::to_SV_clone_ref() const {
SV* sv = newSV(0);
sv_setref_pv( sv, "Slic3r::Point", new Point(*this) );
return sv;
}
SV*
Point::to_SV_pureperl() const {
AV* av = newAV();
av_fill(av, 1);
av_store(av, 0, newSViv(this->x));
av_store(av, 1, newSViv(this->y));
return newRV_noinc((SV*)av);
}
void
Point::from_SV(SV* point_sv)
{
AV* point_av = (AV*)SvRV(point_sv);
this->x = (long)SvIV(*av_fetch(point_av, 0, 0));
this->y = (long)SvIV(*av_fetch(point_av, 1, 0));
}
void
Point::from_SV_check(SV* point_sv)
{
if (sv_isobject(point_sv) && (SvTYPE(SvRV(point_sv)) == SVt_PVMG)) {
*this = *(Point*)SvIV((SV*)SvRV( point_sv ));
} else {
this->from_SV(point_sv);
}
}
#endif
}
<commit_msg>Fix an overflow point causing wrong chained path<commit_after>#include "Point.hpp"
#include <math.h>
namespace Slic3r {
void
Point::scale(double factor)
{
this->x *= factor;
this->y *= factor;
}
void
Point::translate(double x, double y)
{
this->x += x;
this->y += y;
}
void
Point::rotate(double angle, Point* center)
{
double cur_x = (double)this->x;
double cur_y = (double)this->y;
this->x = (long)round( (double)center->x + cos(angle) * (cur_x - (double)center->x) - sin(angle) * (cur_y - (double)center->y) );
this->y = (long)round( (double)center->y + cos(angle) * (cur_y - (double)center->y) + sin(angle) * (cur_x - (double)center->x) );
}
bool
Point::coincides_with(const Point* point) const
{
return this->x == point->x && this->y == point->y;
}
int
Point::nearest_point_index(const Points points) const
{
int idx = -1;
double distance = -1; // double because long is limited to 2147483647 on some platforms and it's not enough
for (Points::const_iterator it = points.begin(); it != points.end(); ++it) {
/* If the X distance of the candidate is > than the total distance of the
best previous candidate, we know we don't want it */
double d = pow(this->x - (*it).x, 2);
if (distance != -1 && d > distance) continue;
/* If the Y distance of the candidate is > than the total distance of the
best previous candidate, we know we don't want it */
d += pow(this->y - (*it).y, 2);
if (distance != -1 && d > distance) continue;
idx = it - points.begin();
distance = d;
if (distance < EPSILON) break;
}
return idx;
}
Point*
Point::nearest_point(Points points) const
{
return &(points.at(this->nearest_point_index(points)));
}
double
Point::distance_to(const Point* point) const
{
double dx = ((double)point->x - this->x);
double dy = ((double)point->y - this->y);
return sqrt(dx*dx + dy*dy);
}
#ifdef SLIC3RXS
SV*
Point::to_SV_ref() {
SV* sv = newSV(0);
sv_setref_pv( sv, "Slic3r::Point::Ref", (void*)this );
return sv;
}
SV*
Point::to_SV_clone_ref() const {
SV* sv = newSV(0);
sv_setref_pv( sv, "Slic3r::Point", new Point(*this) );
return sv;
}
SV*
Point::to_SV_pureperl() const {
AV* av = newAV();
av_fill(av, 1);
av_store(av, 0, newSViv(this->x));
av_store(av, 1, newSViv(this->y));
return newRV_noinc((SV*)av);
}
void
Point::from_SV(SV* point_sv)
{
AV* point_av = (AV*)SvRV(point_sv);
this->x = (long)SvIV(*av_fetch(point_av, 0, 0));
this->y = (long)SvIV(*av_fetch(point_av, 1, 0));
}
void
Point::from_SV_check(SV* point_sv)
{
if (sv_isobject(point_sv) && (SvTYPE(SvRV(point_sv)) == SVt_PVMG)) {
*this = *(Point*)SvIV((SV*)SvRV( point_sv ));
} else {
this->from_SV(point_sv);
}
}
#endif
}
<|endoftext|> |
<commit_before>#include "sorter.h"
#include <QtQml>
namespace qqsfpm {
Sorter::Sorter(QObject *parent) : QObject(parent)
{
connect(this, &Sorter::sorterChanged, this, &Sorter::onSorterChanged);
}
Sorter::~Sorter() = default;
bool Sorter::enabled() const
{
return m_enabled;
}
void Sorter::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
emit enabledChanged();
emit sorterChanged();
}
bool Sorter::ascendingOrder() const
{
return m_ascendingOrder;
}
void Sorter::setAscendingOrder(bool ascendingOrder)
{
if (m_ascendingOrder == ascendingOrder)
return;
m_ascendingOrder = ascendingOrder;
emit ascendingOrderChanged();
emit sorterChanged();
}
int Sorter::compareRows(const QModelIndex &source_left, const QModelIndex &source_right) const
{
int comparison = compare(source_left, source_right);
return m_ascendingOrder ? comparison : -comparison;
}
QQmlSortFilterProxyModel* Sorter::proxyModel() const
{
return m_proxyModel;
}
int Sorter::compare(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
if (lessThan(sourceLeft, sourceRight))
return -1;
if (lessThan(sourceRight, sourceLeft))
return 1;
return 0;
}
bool Sorter::lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
Q_UNUSED(sourceLeft)
Q_UNUSED(sourceRight)
return false;
}
void Sorter::proxyModelCompleted()
{
}
void Sorter::onSorterChanged()
{
if (m_enabled)
emit invalidate();
}
const QString& RoleSorter::roleName() const
{
return m_roleName;
}
void RoleSorter::setRoleName(const QString& roleName)
{
if (m_roleName == roleName)
return;
m_roleName = roleName;
emit roleNameChanged();
emit sorterChanged();
}
int RoleSorter::compare(const QModelIndex &sourceLeft, const QModelIndex& sourceRight) const
{
QVariant leftValue = proxyModel()->sourceData(sourceLeft, m_roleName);
QVariant rightValue = proxyModel()->sourceData(sourceRight, m_roleName);
if (leftValue < rightValue)
return -1;
if (leftValue > rightValue)
return 1;
return 0;
}
}
<commit_msg>Register Sorters types to QML<commit_after>#include "sorter.h"
#include <QtQml>
namespace qqsfpm {
Sorter::Sorter(QObject *parent) : QObject(parent)
{
connect(this, &Sorter::sorterChanged, this, &Sorter::onSorterChanged);
}
Sorter::~Sorter() = default;
bool Sorter::enabled() const
{
return m_enabled;
}
void Sorter::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
emit enabledChanged();
emit sorterChanged();
}
bool Sorter::ascendingOrder() const
{
return m_ascendingOrder;
}
void Sorter::setAscendingOrder(bool ascendingOrder)
{
if (m_ascendingOrder == ascendingOrder)
return;
m_ascendingOrder = ascendingOrder;
emit ascendingOrderChanged();
emit sorterChanged();
}
int Sorter::compareRows(const QModelIndex &source_left, const QModelIndex &source_right) const
{
int comparison = compare(source_left, source_right);
return m_ascendingOrder ? comparison : -comparison;
}
QQmlSortFilterProxyModel* Sorter::proxyModel() const
{
return m_proxyModel;
}
int Sorter::compare(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
if (lessThan(sourceLeft, sourceRight))
return -1;
if (lessThan(sourceRight, sourceLeft))
return 1;
return 0;
}
bool Sorter::lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
{
Q_UNUSED(sourceLeft)
Q_UNUSED(sourceRight)
return false;
}
void Sorter::proxyModelCompleted()
{
}
void Sorter::onSorterChanged()
{
if (m_enabled)
emit invalidate();
}
const QString& RoleSorter::roleName() const
{
return m_roleName;
}
void RoleSorter::setRoleName(const QString& roleName)
{
if (m_roleName == roleName)
return;
m_roleName = roleName;
emit roleNameChanged();
emit sorterChanged();
}
int RoleSorter::compare(const QModelIndex &sourceLeft, const QModelIndex& sourceRight) const
{
QVariant leftValue = proxyModel()->sourceData(sourceLeft, m_roleName);
QVariant rightValue = proxyModel()->sourceData(sourceRight, m_roleName);
if (leftValue < rightValue)
return -1;
if (leftValue > rightValue)
return 1;
return 0;
}
void registerSorterTypes() {
qmlRegisterUncreatableType<Sorter>("SortFilterProxyModel", 0, 2, "Sorter", "Sorter is an abstract class");
qmlRegisterType<RoleSorter>("SortFilterProxyModel", 0, 2, "RoleSorter");
}
Q_COREAPP_STARTUP_FUNCTION(registerSorterTypes)
}
<|endoftext|> |
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_TYPE_HPP_
#define _QITYPE_TYPE_HPP_
#include <typeinfo>
#include <string>
#include <boost/preprocessor.hpp>
#include <boost/type_traits/is_function.hpp>
#include <boost/mpl/if.hpp>
#include <qi/log.hpp>
#include <qitype/api.hpp>
#include <qitype/fwd.hpp>
#include <qitype/signature.hpp>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4251 )
#endif
/* A lot of class are found in this headers... to kill circular dependencies.
Futhermore we need that all "default template" types are registered (included)
when type.hpp is used. (for typeOf to works reliably)
*/
namespace qi{
/** This class is used to uniquely identify a type.
*
*/
class QITYPE_API TypeInfo
{
public:
TypeInfo();
/// Construct a TypeInfo from a std::type_info
TypeInfo(const std::type_info& info);
/// Contruct a TypeInfo from a custom string.
TypeInfo(const std::string& ti);
std::string asString() const;
std::string asDemangledString() const;
//TODO: DIE
const char* asCString() const;
bool operator==(const TypeInfo& b) const;
bool operator!=(const TypeInfo& b) const;
bool operator<(const TypeInfo& b) const;
private:
const std::type_info* stdInfo;
// C4251
std::string customInfo;
};
/** Interface for all the operations we need on any type:
*
* - cloning/destruction in clone() and destroy()
* - Access to value from storage and storage creation in
* ptrFromStorage() and initializeStorage()
* - Type of specialized interface through kind()
*
* Our aim is to transport arbitrary values through:
* - synchronous calls: Nothing to do, values are just transported and
* converted.
* - asynchronous call/thread change: Values are copied.
* - process change: Values are serialized.
*
*/
class QITYPE_API Type
{
public:
virtual const TypeInfo& info() =0;
// Initialize and return a new storage, from nothing or a T*
virtual void* initializeStorage(void* ptr=0)=0;
// Get pointer to type from pointer to storage
// Use a pointer and not a reference to avoid the case where the compiler makes a copy on the stack
virtual void* ptrFromStorage(void**)=0;
virtual void* clone(void*)=0;
virtual void destroy(void*)=0;
enum Kind
{
Void,
Int,
Float,
String,
List,
Map,
Object,
Pointer,
Tuple,
Dynamic,
Raw,
Unknown,
};
virtual Kind kind() const;
//TODO: DIE
inline const char* infoString() { return info().asCString(); } // for easy gdb access
std::string signature(void* storage=0, bool resolveDynamic = false);
///@return a Type on which signature() returns sig.
static Type* fromSignature(const qi::Signature& sig);
};
/// Runtime Type factory getter. Used by typeOf<T>()
QITYPE_API Type* getType(const std::type_info& type);
/// Runtime Type factory setter.
QITYPE_API bool registerType(const std::type_info& typeId, Type* type);
/** Get type from a type. Will return a static TypeImpl<T> if T is not registered
*/
template<typename T> Type* typeOf();
/// Get type from a value. No need to delete the result
template<typename T> Type* typeOf(const T& v)
{
return typeOf<T>();
}
//MACROS
/// Declare that a type has no accessible default constructor.
#define QI_TYPE_NOT_CONSTRUCTIBLE(T) \
namespace qi { namespace detail { \
template<> struct TypeManager<T>: public TypeManagerNonDefaultConstructible<T> {};}}
/// Declare that a type has no metatype and cannot be used in a Value
#define QI_NO_TYPE(T) namespace qi {template<> class TypeImpl<T> {};}
/// Declare that a type has no accessible copy constructor
#define QI_TYPE_NOT_CLONABLE(T) \
namespace qi { namespace detail { \
template<> struct TypeManager<T>: public TypeManagerNull<T> {};}}
/// Register TypeImpl<t> in runtime type factory for 't'. Must be called from a .cpp file
#define QI_TYPE_REGISTER(t) \
QI_TYPE_REGISTER_CUSTOM(t, qi::TypeImpl<t>)
/// Register 'typeimpl' in runtime type factory for 'type'.
#define QI_TYPE_REGISTER_CUSTOM(type, typeimpl) \
static bool BOOST_PP_CAT(__qi_registration, __LINE__) = qi::registerType(typeid(type), new typeimpl)
class GenericListPtr;
class GenericMapPtr;
class GenericObjectPtr;
/** Class that holds any value, with informations to manipulate it.
* operator=() makes a shallow copy.
*
* \warning GenericValuePtr should not be used directly as call arguments.
* Use qi::GenericValue which has value semantics instead.
*
*/
class QITYPE_API GenericValuePtr
{
public:
GenericValuePtr();
/** Store type and allocate storage of value.
* @param type use this type for initialization
*/
GenericValuePtr(Type* type);
/** Create a generic value with type and a value who should have
* already been allocated.
* @param type type of this generic value
* @param value an already alloc place to store value
*/
GenericValuePtr(Type* type, void* value) : type(type), value(value) {}
/** Return the typed pointer behind a GenericValuePtr. T *must* be the type
* of the value.
* @return a pointer to the value as a T or 0 if value is not a T.
* @param check if false, does not validate type before converting
*/
template<typename T> T* ptr(bool check = true);
/// @return the pair (convertedValue, trueIfCopiedAndNeedsDestroy)
std::pair<GenericValuePtr, bool> convert(Type* targetType) const;
/// Helper function that converts and always clone
GenericValuePtr convertCopy(Type* targetType) const;
GenericValuePtr clone() const;
std::string signature(bool resolveDynamic = false) const;
void destroy();
Type::Kind kind() const;
int64_t asInt() const;
float asFloat() const;
double asDouble() const;
std::string asString() const;
GenericListPtr asList() const;
GenericMapPtr asMap() const;
ObjectPtr asObject() const;
template<typename T> T as() const;
// Helper function to obtain type T from a value. Argument value is not used.
template<typename T> T as(const T&) const;
template<typename T> static GenericValuePtr from(const T& t);
Type* type;
void* value;
};
QITYPE_API bool operator< (const qi::GenericValuePtr& a, const qi::GenericValuePtr& b);
/** Class that holds any value, with value semantics.
*/
class QITYPE_API GenericValue: public GenericValuePtr
{
public:
GenericValue() {}
GenericValue(const GenericValue& b)
{
*this = b;
}
GenericValue(const GenericValuePtr& b)
{
*(GenericValuePtr*)this = b.clone();
}
void operator = (const GenericValuePtr& b)
{
if (type) destroy();
*(GenericValuePtr*)this = b.clone();
}
void operator = (const GenericValue& b)
{
if (type) destroy();
*(GenericValuePtr*)this = b.clone();
}
~GenericValue()
{
if (type)
destroy();
}
};
/** Generates GenericValuePtr from everything transparently.
* To be used as type of meta-function call argument
*
* Example:
* void metaCall(ValueGen arg1, ValueGen arg2);
* can be called with any argument type:
* metaCall("foo", 12);
*/
class AutoGenericValuePtr: public GenericValuePtr
{
public:
AutoGenericValuePtr ();
AutoGenericValuePtr(const AutoGenericValuePtr & b);
template<typename T> AutoGenericValuePtr(const T& ptr);
};
template<typename T>
class GenericIteratorPtr: public GenericValuePtr
{
public:
void operator++();
void operator++(int);
T operator*();
bool operator==(const GenericIteratorPtr& b) const;
inline bool operator!=(const GenericIteratorPtr& b) const;
};
class GenericListIteratorPtr: public GenericIteratorPtr<GenericValuePtr>
{};
class GenericMapIteratorPtr: public GenericIteratorPtr<std::pair<GenericValuePtr, GenericValuePtr> >
{};
class TypeList;
class GenericListPtr: public GenericValuePtr
{
public:
GenericListPtr();
GenericListPtr(GenericValuePtr&);
GenericListPtr(TypeList* type, void* value);
size_t size();
GenericListIteratorPtr begin();
GenericListIteratorPtr end();
void pushBack(GenericValuePtr val);
Type* elementType();
};
class TypeMap;
class GenericMapPtr: public GenericValuePtr
{
public:
GenericMapPtr();
GenericMapPtr(GenericValuePtr&);
GenericMapPtr(TypeMap* type, void* value);
size_t size();
GenericMapIteratorPtr begin();
GenericMapIteratorPtr end();
void insert(GenericValuePtr key, GenericValuePtr val);
Type* keyType();
Type* elementType();
};
// Interfaces for specialized types
class QITYPE_API TypeInt: public Type
{
public:
virtual int64_t get(void* value) const = 0;
virtual unsigned int size() const = 0; // size in bytes
virtual bool isSigned() const = 0; // return if type is signed
virtual void set(void** storage, int64_t value) = 0;
virtual Kind kind() const { return Int;}
};
class QITYPE_API TypeFloat: public Type
{
public:
virtual double get(void* value) const = 0;
virtual unsigned int size() const = 0; // size in bytes
virtual void set(void** storage, double value) = 0;
virtual Kind kind() const { return Float;}
};
class Buffer;
class QITYPE_API TypeString: public Type
{
public:
std::string getString(void* storage) const;
virtual std::pair<char*, size_t> get(void* storage) const = 0;
void set(void** storage, const std::string& value);
virtual void set(void** storage, const char* ptr, size_t sz) = 0;
virtual Kind kind() const { return String; }
};
class QITYPE_API TypeRaw: public Type
{
public:
virtual Buffer get(void *storage) = 0;
virtual void set(void** storage, Buffer& value) = 0;
virtual Kind kind() const { return Raw; }
};
class QITYPE_API TypePointer: public Type
{
public:
virtual Type* pointedType() const = 0;
virtual GenericValuePtr dereference(void* storage) = 0; // must not be destroyed
virtual Kind kind() const { return Pointer; }
};
template<typename T>
class QITYPE_API TypeIterator: public Type
{
public:
virtual T dereference(void* storage) = 0; // must not be destroyed
virtual void next(void** storage) = 0;
virtual bool equals(void* s1, void* s2) = 0;
};
class QITYPE_API TypeListIterator: public TypeIterator<GenericValuePtr>
{};
class QITYPE_API TypeMapIterator: public TypeIterator<std::pair<GenericValuePtr, GenericValuePtr> >
{};
class QITYPE_API TypeList: public Type
{
public:
virtual Type* elementType() const = 0;
virtual size_t size(void* storage) = 0;
virtual GenericListIteratorPtr begin(void* storage) = 0; // Must be destroyed
virtual GenericListIteratorPtr end(void* storage) = 0; //idem
virtual void pushBack(void** storage, void* valueStorage) = 0;
virtual Kind kind() const { return List;}
};
class QITYPE_API TypeMap: public Type
{
public:
virtual Type* elementType() const = 0;
virtual Type* keyType() const = 0;
virtual size_t size(void* storage) = 0;
virtual GenericMapIteratorPtr begin(void* storage) = 0; // Must be destroyed
virtual GenericMapIteratorPtr end(void* storage) = 0; //idem
virtual void insert(void** storage, void* keyStorage, void* valueStorage) = 0;
virtual Kind kind() const { return Map; }
// Since our typesystem has no erased operator < or operator ==,
// TypeMap does not provide a find()
};
class QITYPE_API TypeTuple: public Type
{
public:
std::vector<GenericValuePtr> getValues(void* storage);
virtual std::vector<Type*> memberTypes() = 0;
virtual std::vector<void*> get(void* storage); // must not be destroyed
virtual void* get(void* storage, unsigned int index) = 0; // must not be destroyed
virtual void set(void** storage, std::vector<void*>);
virtual void set(void** storage, unsigned int index, void* valStorage) = 0; // will copy
virtual Kind kind() const { return Tuple; }
};
class QITYPE_API TypeDynamic: public Type
{
public:
// Convert storage to a GenericValuePtr, that must be destroyed if res.second is true
virtual std::pair<GenericValuePtr, bool> get(void* storage) = 0;
virtual void set(void** storage, GenericValuePtr source) = 0;
virtual Kind kind() const { return Dynamic; }
};
///@return a Type of kind List that can contains elements of type elementType.
QITYPE_API Type* makeListType(Type* elementType);
///@return a Type of kind Map with given key and element types
QITYPE_API Type* makeMapType(Type* keyType, Type* ElementType);
///@return a Type of kind Tuple with givent memberTypes
QITYPE_API Type* makeTupleType(std::vector<Type*> memberTypes);
///@return a Tuple made from copies of \param values
QITYPE_API GenericValuePtr makeGenericTuple(std::vector<GenericValuePtr> values);
}
#include <qitype/details/typeimpl.hxx>
#include <qitype/details/type.hxx>
#include <qitype/details/genericvaluespecialized.hxx>
#include <qitype/details/genericvalue.hxx>
#include <qitype/details/typelist.hxx>
#include <qitype/details/typemap.hxx>
#include <qitype/details/typestring.hxx>
#include <qitype/details/typepointer.hxx>
#include <qitype/details/typetuple.hxx>
#include <qitype/details/typebuffer.hxx>
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#endif // _QITYPE_TYPE_HPP_
<commit_msg>GenericValue::from: New, bounces to GenericValuePtr::from.<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_TYPE_HPP_
#define _QITYPE_TYPE_HPP_
#include <typeinfo>
#include <string>
#include <boost/preprocessor.hpp>
#include <boost/type_traits/is_function.hpp>
#include <boost/mpl/if.hpp>
#include <qi/log.hpp>
#include <qitype/api.hpp>
#include <qitype/fwd.hpp>
#include <qitype/signature.hpp>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4251 )
#endif
/* A lot of class are found in this headers... to kill circular dependencies.
Futhermore we need that all "default template" types are registered (included)
when type.hpp is used. (for typeOf to works reliably)
*/
namespace qi{
/** This class is used to uniquely identify a type.
*
*/
class QITYPE_API TypeInfo
{
public:
TypeInfo();
/// Construct a TypeInfo from a std::type_info
TypeInfo(const std::type_info& info);
/// Contruct a TypeInfo from a custom string.
TypeInfo(const std::string& ti);
std::string asString() const;
std::string asDemangledString() const;
//TODO: DIE
const char* asCString() const;
bool operator==(const TypeInfo& b) const;
bool operator!=(const TypeInfo& b) const;
bool operator<(const TypeInfo& b) const;
private:
const std::type_info* stdInfo;
// C4251
std::string customInfo;
};
/** Interface for all the operations we need on any type:
*
* - cloning/destruction in clone() and destroy()
* - Access to value from storage and storage creation in
* ptrFromStorage() and initializeStorage()
* - Type of specialized interface through kind()
*
* Our aim is to transport arbitrary values through:
* - synchronous calls: Nothing to do, values are just transported and
* converted.
* - asynchronous call/thread change: Values are copied.
* - process change: Values are serialized.
*
*/
class QITYPE_API Type
{
public:
virtual const TypeInfo& info() =0;
// Initialize and return a new storage, from nothing or a T*
virtual void* initializeStorage(void* ptr=0)=0;
// Get pointer to type from pointer to storage
// Use a pointer and not a reference to avoid the case where the compiler makes a copy on the stack
virtual void* ptrFromStorage(void**)=0;
virtual void* clone(void*)=0;
virtual void destroy(void*)=0;
enum Kind
{
Void,
Int,
Float,
String,
List,
Map,
Object,
Pointer,
Tuple,
Dynamic,
Raw,
Unknown,
};
virtual Kind kind() const;
//TODO: DIE
inline const char* infoString() { return info().asCString(); } // for easy gdb access
std::string signature(void* storage=0, bool resolveDynamic = false);
///@return a Type on which signature() returns sig.
static Type* fromSignature(const qi::Signature& sig);
};
/// Runtime Type factory getter. Used by typeOf<T>()
QITYPE_API Type* getType(const std::type_info& type);
/// Runtime Type factory setter.
QITYPE_API bool registerType(const std::type_info& typeId, Type* type);
/** Get type from a type. Will return a static TypeImpl<T> if T is not registered
*/
template<typename T> Type* typeOf();
/// Get type from a value. No need to delete the result
template<typename T> Type* typeOf(const T& v)
{
return typeOf<T>();
}
//MACROS
/// Declare that a type has no accessible default constructor.
#define QI_TYPE_NOT_CONSTRUCTIBLE(T) \
namespace qi { namespace detail { \
template<> struct TypeManager<T>: public TypeManagerNonDefaultConstructible<T> {};}}
/// Declare that a type has no metatype and cannot be used in a Value
#define QI_NO_TYPE(T) namespace qi {template<> class TypeImpl<T> {};}
/// Declare that a type has no accessible copy constructor
#define QI_TYPE_NOT_CLONABLE(T) \
namespace qi { namespace detail { \
template<> struct TypeManager<T>: public TypeManagerNull<T> {};}}
/// Register TypeImpl<t> in runtime type factory for 't'. Must be called from a .cpp file
#define QI_TYPE_REGISTER(t) \
QI_TYPE_REGISTER_CUSTOM(t, qi::TypeImpl<t>)
/// Register 'typeimpl' in runtime type factory for 'type'.
#define QI_TYPE_REGISTER_CUSTOM(type, typeimpl) \
static bool BOOST_PP_CAT(__qi_registration, __LINE__) = qi::registerType(typeid(type), new typeimpl)
class GenericListPtr;
class GenericMapPtr;
class GenericObjectPtr;
/** Class that holds any value, with informations to manipulate it.
* operator=() makes a shallow copy.
*
* \warning GenericValuePtr should not be used directly as call arguments.
* Use qi::GenericValue which has value semantics instead.
*
*/
class QITYPE_API GenericValuePtr
{
public:
GenericValuePtr();
/** Store type and allocate storage of value.
* @param type use this type for initialization
*/
GenericValuePtr(Type* type);
/** Create a generic value with type and a value who should have
* already been allocated.
* @param type type of this generic value
* @param value an already alloc place to store value
*/
GenericValuePtr(Type* type, void* value) : type(type), value(value) {}
/** Return the typed pointer behind a GenericValuePtr. T *must* be the type
* of the value.
* @return a pointer to the value as a T or 0 if value is not a T.
* @param check if false, does not validate type before converting
*/
template<typename T> T* ptr(bool check = true);
/// @return the pair (convertedValue, trueIfCopiedAndNeedsDestroy)
std::pair<GenericValuePtr, bool> convert(Type* targetType) const;
/// Helper function that converts and always clone
GenericValuePtr convertCopy(Type* targetType) const;
GenericValuePtr clone() const;
std::string signature(bool resolveDynamic = false) const;
void destroy();
Type::Kind kind() const;
int64_t asInt() const;
float asFloat() const;
double asDouble() const;
std::string asString() const;
GenericListPtr asList() const;
GenericMapPtr asMap() const;
ObjectPtr asObject() const;
template<typename T> T as() const;
// Helper function to obtain type T from a value. Argument value is not used.
template<typename T> T as(const T&) const;
template<typename T> static GenericValuePtr from(const T& t);
Type* type;
void* value;
};
QITYPE_API bool operator< (const qi::GenericValuePtr& a, const qi::GenericValuePtr& b);
/** Class that holds any value, with value semantics.
*/
class QITYPE_API GenericValue: public GenericValuePtr
{
public:
GenericValue() {}
GenericValue(const GenericValue& b)
{
*this = b;
}
GenericValue(const GenericValuePtr& b)
{
*(GenericValuePtr*)this = b.clone();
}
void operator = (const GenericValuePtr& b)
{
if (type) destroy();
*(GenericValuePtr*)this = b.clone();
}
void operator = (const GenericValue& b)
{
if (type) destroy();
*(GenericValuePtr*)this = b.clone();
}
template<typename T> static GenericValue from(const T& src)
{
return GenericValue(GenericValuePtr::from(src));
}
~GenericValue()
{
if (type)
destroy();
}
};
/** Generates GenericValuePtr from everything transparently.
* To be used as type of meta-function call argument
*
* Example:
* void metaCall(ValueGen arg1, ValueGen arg2);
* can be called with any argument type:
* metaCall("foo", 12);
*/
class AutoGenericValuePtr: public GenericValuePtr
{
public:
AutoGenericValuePtr ();
AutoGenericValuePtr(const AutoGenericValuePtr & b);
template<typename T> AutoGenericValuePtr(const T& ptr);
};
template<typename T>
class GenericIteratorPtr: public GenericValuePtr
{
public:
void operator++();
void operator++(int);
T operator*();
bool operator==(const GenericIteratorPtr& b) const;
inline bool operator!=(const GenericIteratorPtr& b) const;
};
class GenericListIteratorPtr: public GenericIteratorPtr<GenericValuePtr>
{};
class GenericMapIteratorPtr: public GenericIteratorPtr<std::pair<GenericValuePtr, GenericValuePtr> >
{};
class TypeList;
class GenericListPtr: public GenericValuePtr
{
public:
GenericListPtr();
GenericListPtr(GenericValuePtr&);
GenericListPtr(TypeList* type, void* value);
size_t size();
GenericListIteratorPtr begin();
GenericListIteratorPtr end();
void pushBack(GenericValuePtr val);
Type* elementType();
};
class TypeMap;
class GenericMapPtr: public GenericValuePtr
{
public:
GenericMapPtr();
GenericMapPtr(GenericValuePtr&);
GenericMapPtr(TypeMap* type, void* value);
size_t size();
GenericMapIteratorPtr begin();
GenericMapIteratorPtr end();
void insert(GenericValuePtr key, GenericValuePtr val);
Type* keyType();
Type* elementType();
};
// Interfaces for specialized types
class QITYPE_API TypeInt: public Type
{
public:
virtual int64_t get(void* value) const = 0;
virtual unsigned int size() const = 0; // size in bytes
virtual bool isSigned() const = 0; // return if type is signed
virtual void set(void** storage, int64_t value) = 0;
virtual Kind kind() const { return Int;}
};
class QITYPE_API TypeFloat: public Type
{
public:
virtual double get(void* value) const = 0;
virtual unsigned int size() const = 0; // size in bytes
virtual void set(void** storage, double value) = 0;
virtual Kind kind() const { return Float;}
};
class Buffer;
class QITYPE_API TypeString: public Type
{
public:
std::string getString(void* storage) const;
virtual std::pair<char*, size_t> get(void* storage) const = 0;
void set(void** storage, const std::string& value);
virtual void set(void** storage, const char* ptr, size_t sz) = 0;
virtual Kind kind() const { return String; }
};
class QITYPE_API TypeRaw: public Type
{
public:
virtual Buffer get(void *storage) = 0;
virtual void set(void** storage, Buffer& value) = 0;
virtual Kind kind() const { return Raw; }
};
class QITYPE_API TypePointer: public Type
{
public:
virtual Type* pointedType() const = 0;
virtual GenericValuePtr dereference(void* storage) = 0; // must not be destroyed
virtual Kind kind() const { return Pointer; }
};
template<typename T>
class QITYPE_API TypeIterator: public Type
{
public:
virtual T dereference(void* storage) = 0; // must not be destroyed
virtual void next(void** storage) = 0;
virtual bool equals(void* s1, void* s2) = 0;
};
class QITYPE_API TypeListIterator: public TypeIterator<GenericValuePtr>
{};
class QITYPE_API TypeMapIterator: public TypeIterator<std::pair<GenericValuePtr, GenericValuePtr> >
{};
class QITYPE_API TypeList: public Type
{
public:
virtual Type* elementType() const = 0;
virtual size_t size(void* storage) = 0;
virtual GenericListIteratorPtr begin(void* storage) = 0; // Must be destroyed
virtual GenericListIteratorPtr end(void* storage) = 0; //idem
virtual void pushBack(void** storage, void* valueStorage) = 0;
virtual Kind kind() const { return List;}
};
class QITYPE_API TypeMap: public Type
{
public:
virtual Type* elementType() const = 0;
virtual Type* keyType() const = 0;
virtual size_t size(void* storage) = 0;
virtual GenericMapIteratorPtr begin(void* storage) = 0; // Must be destroyed
virtual GenericMapIteratorPtr end(void* storage) = 0; //idem
virtual void insert(void** storage, void* keyStorage, void* valueStorage) = 0;
virtual Kind kind() const { return Map; }
// Since our typesystem has no erased operator < or operator ==,
// TypeMap does not provide a find()
};
class QITYPE_API TypeTuple: public Type
{
public:
std::vector<GenericValuePtr> getValues(void* storage);
virtual std::vector<Type*> memberTypes() = 0;
virtual std::vector<void*> get(void* storage); // must not be destroyed
virtual void* get(void* storage, unsigned int index) = 0; // must not be destroyed
virtual void set(void** storage, std::vector<void*>);
virtual void set(void** storage, unsigned int index, void* valStorage) = 0; // will copy
virtual Kind kind() const { return Tuple; }
};
class QITYPE_API TypeDynamic: public Type
{
public:
// Convert storage to a GenericValuePtr, that must be destroyed if res.second is true
virtual std::pair<GenericValuePtr, bool> get(void* storage) = 0;
virtual void set(void** storage, GenericValuePtr source) = 0;
virtual Kind kind() const { return Dynamic; }
};
///@return a Type of kind List that can contains elements of type elementType.
QITYPE_API Type* makeListType(Type* elementType);
///@return a Type of kind Map with given key and element types
QITYPE_API Type* makeMapType(Type* keyType, Type* ElementType);
///@return a Type of kind Tuple with givent memberTypes
QITYPE_API Type* makeTupleType(std::vector<Type*> memberTypes);
///@return a Tuple made from copies of \param values
QITYPE_API GenericValuePtr makeGenericTuple(std::vector<GenericValuePtr> values);
}
#include <qitype/details/typeimpl.hxx>
#include <qitype/details/type.hxx>
#include <qitype/details/genericvaluespecialized.hxx>
#include <qitype/details/genericvalue.hxx>
#include <qitype/details/typelist.hxx>
#include <qitype/details/typemap.hxx>
#include <qitype/details/typestring.hxx>
#include <qitype/details/typepointer.hxx>
#include <qitype/details/typetuple.hxx>
#include <qitype/details/typebuffer.hxx>
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#endif // _QITYPE_TYPE_HPP_
<|endoftext|> |
<commit_before>#include "cpu.h"
namespace dramsim3 {
CPU::CPU(BaseDRAMSystem& memory_system)
: memory_system_(memory_system), clk_(0) {}
RandomCPU::RandomCPU(BaseDRAMSystem& memory_system) : CPU(memory_system) {}
StreamCPU::StreamCPU(BaseDRAMSystem& memory_system) : CPU(memory_system) {}
void RandomCPU::ClockTick() {
// Create random CPU requests at full speed
// this is useful to exploit the parallelism of a DRAM protocol
// and is also immune to address mapping and scheduling policies
if (get_next_) {
last_addr_ = gen();
}
bool is_write = (gen() % 3 == 0); // R/W ratio 2:1
bool get_next_ = memory_system_.IsReqInsertable(last_addr_, is_write);
if (get_next_) {
memory_system_.InsertReq(last_addr_, is_write);
}
clk_++;
return;
}
void StreamCPU::ClockTick() {
// stream-add, read 2 arrays, add them up to the third array
// this is a very simple approximate but should be able to produce
// enough buffer hits
// moving on to next set of arrays
if (offset_ >= array_size_ || clk_ == 0) {
addr_a_ = gen();
addr_b_ = gen();
addr_c_ = gen();
offset_ = 0;
}
if (!inserted_a_ &&
memory_system_.IsReqInsertable(addr_a_ + offset_, false)) {
memory_system_.InsertReq(addr_a_ + offset_, false);
inserted_a_ = true;
} else {
inserted_a_ = false;
}
if (!inserted_b_ &&
memory_system_.IsReqInsertable(addr_b_ + offset_, false)) {
memory_system_.InsertReq(addr_b_ + offset_, false);
inserted_b_ = true;
} else {
inserted_b_ = false;
}
if (!inserted_c_ &&
memory_system_.IsReqInsertable(addr_c_ + offset_, true)) {
memory_system_.InsertReq(addr_c_ + offset_, true);
inserted_c_ = true;
} else {
inserted_c_ = false;
}
// moving on to next element
if (inserted_a_ && inserted_b_ && inserted_c_) {
offset_ += stride_;
}
clk_++;
return;
}
TraceBasedCPU::TraceBasedCPU(BaseDRAMSystem& memory_system,
std::string trace_file)
: CPU(memory_system) {
trace_file_.open(trace_file);
if (trace_file_.fail()) {
std::cerr << "Trace file does not exist" << std::endl;
AbruptExit(__FILE__, __LINE__);
}
}
void TraceBasedCPU::ClockTick() {
if (!trace_file_.eof()) {
if (get_next_) {
get_next_ = false;
trace_file_ >> access_;
}
if (access_.time_ <= clk_) {
bool is_write = access_.access_type_ == "WRITE";
bool get_next_ =
memory_system_.IsReqInsertable(access_.hex_addr_, is_write);
if (get_next_) {
memory_system_.InsertReq(access_.hex_addr_, is_write);
}
}
}
clk_++;
return;
}
} // namespace dramsim3
<commit_msg>fix minor bug in CPU<commit_after>#include "cpu.h"
namespace dramsim3 {
CPU::CPU(BaseDRAMSystem& memory_system)
: memory_system_(memory_system), clk_(0) {}
RandomCPU::RandomCPU(BaseDRAMSystem& memory_system) : CPU(memory_system) {}
StreamCPU::StreamCPU(BaseDRAMSystem& memory_system) : CPU(memory_system) {}
void RandomCPU::ClockTick() {
// Create random CPU requests at full speed
// this is useful to exploit the parallelism of a DRAM protocol
// and is also immune to address mapping and scheduling policies
if (get_next_) {
last_addr_ = gen();
}
bool is_write = (gen() % 3 == 0); // R/W ratio 2:1
get_next_ = memory_system_.IsReqInsertable(last_addr_, is_write);
if (get_next_) {
memory_system_.InsertReq(last_addr_, is_write);
}
clk_++;
return;
}
void StreamCPU::ClockTick() {
// stream-add, read 2 arrays, add them up to the third array
// this is a very simple approximate but should be able to produce
// enough buffer hits
// moving on to next set of arrays
if (offset_ >= array_size_ || clk_ == 0) {
addr_a_ = gen();
addr_b_ = gen();
addr_c_ = gen();
offset_ = 0;
}
if (!inserted_a_ &&
memory_system_.IsReqInsertable(addr_a_ + offset_, false)) {
memory_system_.InsertReq(addr_a_ + offset_, false);
inserted_a_ = true;
} else {
inserted_a_ = false;
}
if (!inserted_b_ &&
memory_system_.IsReqInsertable(addr_b_ + offset_, false)) {
memory_system_.InsertReq(addr_b_ + offset_, false);
inserted_b_ = true;
} else {
inserted_b_ = false;
}
if (!inserted_c_ &&
memory_system_.IsReqInsertable(addr_c_ + offset_, true)) {
memory_system_.InsertReq(addr_c_ + offset_, true);
inserted_c_ = true;
} else {
inserted_c_ = false;
}
// moving on to next element
if (inserted_a_ && inserted_b_ && inserted_c_) {
offset_ += stride_;
}
clk_++;
return;
}
TraceBasedCPU::TraceBasedCPU(BaseDRAMSystem& memory_system,
std::string trace_file)
: CPU(memory_system) {
trace_file_.open(trace_file);
if (trace_file_.fail()) {
std::cerr << "Trace file does not exist" << std::endl;
AbruptExit(__FILE__, __LINE__);
}
}
void TraceBasedCPU::ClockTick() {
if (!trace_file_.eof()) {
if (get_next_) {
get_next_ = false;
trace_file_ >> access_;
}
if (access_.time_ <= clk_) {
bool is_write = access_.access_type_ == "WRITE";
bool get_next_ =
memory_system_.IsReqInsertable(access_.hex_addr_, is_write);
if (get_next_) {
memory_system_.InsertReq(access_.hex_addr_, is_write);
}
}
}
clk_++;
return;
}
} // namespace dramsim3
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %s galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
std::vector<int> count;
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
//read the three input files
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
assign_priority_class(M);
//establish priority classes
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
//diagnostic
int count_ss=0;
int count_sf=0;
for(int g=0;g<M.size();++g){
if(M[g].SS) count_ss++;
if(M[g].SF) count_sf++;
}
printf(" number SS = %d number SF = %d\n",count_ss,count_sf);
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
printf(" future plates %d\n",P.size());
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);
not_done=false;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates after screening %d \n",F.NUsedplate);
//if(F.diagnose)diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
for (int i=0; i<1; i++) {
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
//printf(" before assign_sf_ss js= %d\n",js);
A.next_plate=js;
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
//printf("before assign_unused js= %d \n",js);
assign_unused(js,M,P,pp,F,A);
}
/*
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
*/
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
printf(" before pass = %d at %d tiles\n",i,update_intervals[i]);
//display_results("doc/figs/",G,P,pp,F,A,true);
//plan whole survey from this point out
A.next_plate=F.pass_intervals[i];
for (int jj=update_intervals[i]; jj<F.NUsedplate; jj++) {
int js = A.suborder[jj];
//printf(" next plate is %d \n",j);
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF
assign_unused(js,M,P,pp,F,A);
//A.next_plate++;
}
//update target information for interval i
//A.next_plate=F.pass_intervals[i];
for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) {
//int j = A.suborder[A.next_plate];
//int js=A.suborder[jj];
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n");
//A.next_plate++;
}
//if(A.next_plate<F.Nplate){
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
//}
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
/*
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
*/
// Results -------------------------------------------------------
if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>add print at start<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %s galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
std::vector<int> count;
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
//read the three input files
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
assign_priority_class(M);
//establish priority classes
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
//diagnostic
int count_ss=0;
int count_sf=0;
for(int g=0;g<M.size();++g){
if(M[g].SS) count_ss++;
if(M[g].SF) count_sf++;
}
printf(" number SS = %d number SF = %d\n",count_ss,count_sf);
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
printf(" future plates %d\n",P.size());
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);
not_done=false;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates after screening %d \n",F.NUsedplate);
//if(F.diagnose)diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
for (int i=0; i<1; i++) {
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
//printf(" before assign_sf_ss js= %d\n",js);
A.next_plate=js;
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
//printf("before assign_unused js= %d \n",js);
assign_unused(js,M,P,pp,F,A);
}
/*
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
*/
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
printf(" before pass = %d at %d tiles\n",i,update_intervals[i]);
//display_results("doc/figs/",G,P,pp,F,A,true);
//plan whole survey from this point out
A.next_plate=F.pass_intervals[i];
for (int jj=update_intervals[i]; jj<F.NUsedplate; jj++) {
int js = A.suborder[jj];
//printf(" next plate is %d \n",j);
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF
assign_unused(js,M,P,pp,F,A);
//A.next_plate++;
}
//update target information for interval i
//A.next_plate=F.pass_intervals[i];
for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) {
//int j = A.suborder[A.next_plate];
//int js=A.suborder[jj];
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n");
//A.next_plate++;
}
//if(A.next_plate<F.Nplate){
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
//}
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
/*
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
*/
// Results -------------------------------------------------------
if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include "gc.hpp"
#include "accounts.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
using namespace budget;
namespace {
template<typename Values>
std::size_t gc(Values& values){
std::sort(values.begin(), values.end(),
[](const typename Values::value_type& a, const typename Values::value_type& b){ return a.id < b.id; });
std::size_t next_id = 0;
for(auto& expense : values){
expense.id = ++next_id;
}
return ++next_id;
}
void gc_expenses(){
auto next_id = gc(all_expenses());
set_expenses_next_id(next_id);
set_expenses_changed();
}
void gc_earnings(){
auto next_id = gc(all_earnings());
set_earnings_next_id(next_id);
set_earnings_changed();
}
} //end of anonymous namespace
void budget::gc_module::load(){
load_accounts();
load_expenses();
load_earnings();
}
void budget::gc_module::unload(){
save_expenses();
save_earnings();
save_accounts();
}
void budget::gc_module::handle(const std::vector<std::string>& args){
if(args.size() > 1){
std::cout << "Too many parameters" << std::endl;
} else {
std::cout << "Make all IDs contiguous..." << std::endl;
gc_expenses();
gc_earnings();
std::cout << "...done" << std::endl;
}
}
<commit_msg>GC all common data<commit_after>//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include "gc.hpp"
#include "accounts.hpp"
#include "debts.hpp"
#include "earnings.hpp"
#include "expenses.hpp"
#include "fortune.hpp"
#include "wishes.hpp"
#include "objectives.hpp"
using namespace budget;
namespace {
template<typename Values>
std::size_t gc(Values& values){
std::sort(values.begin(), values.end(),
[](const typename Values::value_type& a, const typename Values::value_type& b){ return a.id < b.id; });
std::size_t next_id = 0;
for(auto& expense : values){
expense.id = ++next_id;
}
return ++next_id;
}
void gc_expenses(){
auto next_id = gc(all_expenses());
set_expenses_next_id(next_id);
set_expenses_changed();
}
void gc_earnings(){
auto next_id = gc(all_earnings());
set_earnings_next_id(next_id);
set_earnings_changed();
}
void gc_debts(){
auto next_id = gc(all_debts());
set_debts_next_id(next_id);
set_debts_changed();
}
void gc_fortunes(){
auto next_id = gc(all_fortunes());
set_fortunes_next_id(next_id);
set_fortunes_changed();
}
void gc_wishes(){
auto next_id = gc(all_wishes());
set_wishes_next_id(next_id);
set_wishes_changed();
}
void gc_objectives(){
auto next_id = gc(all_objectives());
set_objectives_next_id(next_id);
set_objectives_changed();
}
} //end of anonymous namespace
void budget::gc_module::load(){
load_accounts();
load_expenses();
load_earnings();
load_debts();
load_fortunes();
load_wishes();
load_objectives();
}
void budget::gc_module::unload(){
save_expenses();
save_earnings();
save_accounts();
save_debts();
save_fortunes();
save_wishes();
save_objectives();
}
void budget::gc_module::handle(const std::vector<std::string>& args){
if(args.size() > 1){
std::cout << "Too many parameters" << std::endl;
} else {
std::cout << "Make all IDs contiguous..." << std::endl;
gc_expenses();
gc_earnings();
gc_debts();
gc_fortunes();
gc_wishes();
gc_objectives();
std::cout << "...done" << std::endl;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
*
* Created by alex [email protected]
*
* Copyright (c) 2012
* 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 project's 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
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "basismethods.h"
#include "gui.h"
#include "myfilechooser.h"
//#include <iostream>
//#include <unistd.h>
#include <cstdlib>
#include <cassert>
#include <thread>
#include <vte/vte.h>
//#include <cerrno>
void execparted(gui *refback)
{
std::system("gparted");
refback->gpartmut.unlock();
}
void gui::chooseeditor()
{
if (graphicaleditor->get_active ())
{
std::string sum="EDITOR=gedit\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
else
{
//TODO:
//buggy;can't fetch the editor from the main system
//most probably because of missing environment variables
std::string sum="EDITOR="+system2("echo \"$EDITOR\"")+"\n";
std::cout << sum;
//so use my favourite
sum="EDITOR=nano\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
}
void gui::opengparted()
{
if (gpartmut.try_lock())
{
gpartthread=std::thread(execparted,this);
}
}
void gui::update()
{
std::string sum=bindir()+"/clonemecmd.sh update "+src->get_text()+" "+dest->get_text()+" "+home_path+" "+"installer_grub2"+"\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
void gui::install()
{
std::string sum=bindir()+"/clonemecmd.sh install "+src->get_text()+" "+dest->get_text()+" "+home_path+" "+"installer_grub2"+"\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
void gui::choosesrc()
{
myfilechooser select;
std::string temp=select.run();
if (!temp.empty())
{
src->set_text(temp);
srcdestobject.src=temp;
}
}
void gui::choosedest()
{
myfilechooser select;
std::string temp=select.run();
if (!temp.empty())
{
dest->set_text(temp);
srcdestobject.dest=temp;
}
}
void gui::updatedsrc()
{
srcdestobject.src=src->get_text();
std::string sum=sharedir()+"/sh/mountscript.sh mount "+srcdestobject.src;+" "+syncdir()+"/src";
std::cerr << "test";
//system2(sum);
}
void gui::updateddest()
{
srcdestobject.dest=dest->get_text();
std::string sum=sharedir()+"/sh/mountscript.sh mount "+srcdestobject.dest;+" "+syncdir()+"/dest";
//cerr <<
std::cerr << "test";
//system2(sum);
}
gui::gui(int argc, char** argv): kit(argc, argv),gpartthread()//,copydialog(this),createdialog(this)
{
//syncdir="";
home_path=argv[0];
builder = Gtk::Builder::create();
try
{
builder->add_from_file(sharedir()+"/ui/cloneme.ui");
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
throw(ex);
}
catch(const Glib::MarkupError& ex)
{
std::cerr << "MarkupError: " << ex.what() << std::endl;
throw(ex);
}
catch(const Gtk::BuilderError& ex)
{
std::cerr << "BuilderError: " << ex.what() << std::endl;
throw(ex);
}
main_win=transform_to_rptr<Gtk::Window>(builder->get_object("main_win"));
//Terminal
terminal=transform_to_rptr<Gtk::Alignment>(builder->get_object("termspace"));
vteterm=vte_terminal_new();
terminal->add(*Glib::wrap(vteterm));
char* startterm[2]={vte_get_user_shell (),0};
bool test=vte_terminal_fork_command_full(VTE_TERMINAL(vteterm),
VTE_PTY_DEFAULT,
0,
startterm,
0, //Environment
(GSpawnFlags)(G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH), //Spawnflags
0,
0,
0,
0);
if (!test)
{
std::cerr << "Terminal child didn't start.\n";
}
//initialize syncdir
std::cerr << system2(sharedir()+"/sh/prepsyncscript.sh "+syncdir()+"\n");
//Buttons
gparted=transform_to_rptr<Gtk::Button>(builder->get_object("gparted"));
gparted->signal_clicked ().connect(sigc::mem_fun(*this,&gui::opengparted));
if ( access("/usr/sbin/gparted",F_OK)!=0)
{
std::cerr << "gparted not found";
gparted->hide();
}
installb=transform_to_rptr<Gtk::Button>(builder->get_object("installb"));
installb->signal_clicked ().connect(sigc::mem_fun(*this,&gui::install));
updateb=transform_to_rptr<Gtk::Button>(builder->get_object("updateb"));
updateb->signal_clicked ().connect(sigc::mem_fun(*this,&gui::update));
//Filechooser
src=transform_to_rptr<Gtk::Entry>(builder->get_object("src"));
src->set_text("/");
//src->signal_changed( ).connect(sigc::mem_fun(*this,&gui::updatedsrc));
srcselect=transform_to_rptr<Gtk::Button>(builder->get_object("srcselect"));
srcselect->signal_clicked ().connect(sigc::mem_fun(*this,&gui::choosesrc));
dest=transform_to_rptr<Gtk::Entry>(builder->get_object("dest"));
dest->set_text("/dev/sdb1");
//dest->signal_changed( ).connect(sigc::mem_fun(*this,&gui::updateddest));
destselect=transform_to_rptr<Gtk::Button>(builder->get_object("destselect"));
destselect->signal_clicked ().connect(sigc::mem_fun(*this,&gui::choosedest));
graphicaleditor=transform_to_rptr<Gtk::CheckButton>(builder->get_object("graphicaleditor"));
graphicaleditor->signal_toggled ().connect(sigc::mem_fun(*this,&gui::chooseeditor));
main_win->show_all_children();
if (main_win!=0)
{
kit.run(*main_win.operator->());
}
}
gui::~gui()
{
//cleanup
std::cerr << system2(sharedir()+"/sh/umountsyncscript.sh "+syncdir()+"\n");
}
<commit_msg>add TODO: use unfocus<commit_after>/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
*
* Created by alex [email protected]
*
* Copyright (c) 2012
* 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 project's 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
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "basismethods.h"
#include "gui.h"
#include "myfilechooser.h"
//#include <iostream>
//#include <unistd.h>
#include <cstdlib>
#include <cassert>
#include <thread>
#include <vte/vte.h>
//#include <cerrno>
void execparted(gui *refback)
{
std::system("gparted");
refback->gpartmut.unlock();
}
void gui::chooseeditor()
{
if (graphicaleditor->get_active ())
{
std::string sum="EDITOR=gedit\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
else
{
//TODO:
//buggy;can't fetch the editor from the main system
//most probably because of missing environment variables
std::string sum="EDITOR="+system2("echo \"$EDITOR\"")+"\n";
std::cout << sum;
//so use my favourite
sum="EDITOR=nano\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
}
void gui::opengparted()
{
if (gpartmut.try_lock())
{
gpartthread=std::thread(execparted,this);
}
}
void gui::update()
{
std::string sum=bindir()+"/clonemecmd.sh update "+src->get_text()+" "+dest->get_text()+" "+home_path+" "+"installer_grub2"+"\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
void gui::install()
{
std::string sum=bindir()+"/clonemecmd.sh install "+src->get_text()+" "+dest->get_text()+" "+home_path+" "+"installer_grub2"+"\n";
vte_terminal_feed_child (VTE_TERMINAL(vteterm),sum.c_str(),sum.length());
}
void gui::choosesrc()
{
myfilechooser select;
std::string temp=select.run();
if (!temp.empty())
{
src->set_text(temp);
srcdestobject.src=temp;
}
}
void gui::choosedest()
{
myfilechooser select;
std::string temp=select.run();
if (!temp.empty())
{
dest->set_text(temp);
srcdestobject.dest=temp;
}
}
void gui::updatedsrc()
{
srcdestobject.src=src->get_text();
std::string sum=sharedir()+"/sh/mountscript.sh mount "+srcdestobject.src;+" "+syncdir()+"/src";
std::cerr << "test";
//system2(sum);
}
void gui::updateddest()
{
srcdestobject.dest=dest->get_text();
std::string sum=sharedir()+"/sh/mountscript.sh mount "+srcdestobject.dest;+" "+syncdir()+"/dest";
//cerr <<
std::cerr << "test";
//system2(sum);
}
gui::gui(int argc, char** argv): kit(argc, argv),gpartthread()//,copydialog(this),createdialog(this)
{
//syncdir="";
home_path=argv[0];
builder = Gtk::Builder::create();
try
{
builder->add_from_file(sharedir()+"/ui/cloneme.ui");
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
throw(ex);
}
catch(const Glib::MarkupError& ex)
{
std::cerr << "MarkupError: " << ex.what() << std::endl;
throw(ex);
}
catch(const Gtk::BuilderError& ex)
{
std::cerr << "BuilderError: " << ex.what() << std::endl;
throw(ex);
}
main_win=transform_to_rptr<Gtk::Window>(builder->get_object("main_win"));
//Terminal
terminal=transform_to_rptr<Gtk::Alignment>(builder->get_object("termspace"));
vteterm=vte_terminal_new();
terminal->add(*Glib::wrap(vteterm));
char* startterm[2]={vte_get_user_shell (),0};
bool test=vte_terminal_fork_command_full(VTE_TERMINAL(vteterm),
VTE_PTY_DEFAULT,
0,
startterm,
0, //Environment
(GSpawnFlags)(G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH), //Spawnflags
0,
0,
0,
0);
if (!test)
{
std::cerr << "Terminal child didn't start.\n";
}
//initialize syncdir
std::cerr << system2(sharedir()+"/sh/prepsyncscript.sh "+syncdir()+"\n");
//Buttons
gparted=transform_to_rptr<Gtk::Button>(builder->get_object("gparted"));
gparted->signal_clicked ().connect(sigc::mem_fun(*this,&gui::opengparted));
if ( access("/usr/sbin/gparted",F_OK)!=0)
{
std::cerr << "gparted not found";
gparted->hide();
}
installb=transform_to_rptr<Gtk::Button>(builder->get_object("installb"));
installb->signal_clicked ().connect(sigc::mem_fun(*this,&gui::install));
updateb=transform_to_rptr<Gtk::Button>(builder->get_object("updateb"));
updateb->signal_clicked ().connect(sigc::mem_fun(*this,&gui::update));
//Filechooser
src=transform_to_rptr<Gtk::Entry>(builder->get_object("src"));
src->set_text("/");
#TODO: use unfocus instead
//src->signal_changed( ).connect(sigc::mem_fun(*this,&gui::updatedsrc));
srcselect=transform_to_rptr<Gtk::Button>(builder->get_object("srcselect"));
srcselect->signal_clicked ().connect(sigc::mem_fun(*this,&gui::choosesrc));
dest=transform_to_rptr<Gtk::Entry>(builder->get_object("dest"));
dest->set_text("/dev/sdb1");
#TODO: use unfocus instead
//dest->signal_changed( ).connect(sigc::mem_fun(*this,&gui::updateddest));
destselect=transform_to_rptr<Gtk::Button>(builder->get_object("destselect"));
destselect->signal_clicked ().connect(sigc::mem_fun(*this,&gui::choosedest));
graphicaleditor=transform_to_rptr<Gtk::CheckButton>(builder->get_object("graphicaleditor"));
graphicaleditor->signal_toggled ().connect(sigc::mem_fun(*this,&gui::chooseeditor));
main_win->show_all_children();
if (main_win!=0)
{
kit.run(*main_win.operator->());
}
}
gui::~gui()
{
//cleanup
std::cerr << system2(sharedir()+"/sh/umountsyncscript.sh "+syncdir()+"\n");
}
<|endoftext|> |
<commit_before><commit_msg>Updated ls.cpp with -la functionality<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <iomanip>
#include <time.h>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
int fs_digits = 0;
void displayfile(string filename, struct stat* sb, int l_flag) {
if (l_flag != 0) {
struct passwd *pwd;
struct group *grp;
if (S_ISDIR(sb->st_mode))
cout << "d";
else
cout << "-";
// User permissions
if (S_IRUSR & sb->st_mode)
cout << "r";
else
cout << "-";
if (S_IWUSR & sb->st_mode)
cout << "w";
else
cout << "-";
if (S_IXUSR & sb->st_mode)
cout << "x";
else
cout << "-";
// Group permissions
if (S_IRGRP & sb->st_mode)
cout << "r";
else
cout << "-";
if (S_IWGRP & sb->st_mode)
cout << "w";
else
cout << "-";
if (S_IXGRP & sb->st_mode)
cout << "x";
else
cout << "-";
// Other permissions
if (S_IROTH & sb->st_mode)
cout << "r";
else
cout << "-";
if (S_IWOTH & sb->st_mode)
cout << "w";
else
cout << "-";
if (S_IXOTH & sb->st_mode)
cout << "x";
else
cout << "-";
// Output number of links
cout << " " << sb->st_nlink;
// Output owner name
if ((pwd = getpwuid(sb->st_uid)) != NULL)
cout << " " << pwd->pw_name;
else
perror("getpwuid");
// Output owner group
if ((grp = getgrgid(sb->st_gid)) != NULL)
cout << " " << grp->gr_name;
else
perror("getgrgid");
// Output file size
cout << " " << setw(fs_digits) << sb->st_size;
// Output last modified time
time_t t = sb->st_mtime;
struct tm * lt = gmtime(&t);
char date[80];
strftime(date, sizeof(date), "%h %d %R ", lt);
cout << " " << date << filename;
}
else {
cout << filename << " ";
}
cout << endl;
return;
}
int main(int argc, char ** argv) {
int flags = 0;
int status = 0;
vector<string> filename;
// Check for ls arguments
for (int i =1; i<argc; i++) {
if (argv[i][0]=='-') {
for (int j=1; argv[i][j]!=0; j++) {
if (argv[i][j] == 'a')
flags |= FLAG_a;
else if (argv[i][j] == 'l')
flags |= FLAG_l;
else if (argv[i][j] == 'R')
flags |= FLAG_R;
}
}
}
DIR * dp;
struct dirent *dt;
struct stat statbuf;
int largest_fsize;
// Open directory stream
if ((dp = opendir(".")) == NULL) {
perror("opendir");
return 0;
}
while ((dt = readdir(dp)) != NULL) {
filename.push_back(dt->d_name);
status = stat(dt->d_name, &statbuf);
if (status == -1)
perror ("stat");
if (statbuf.st_size > largest_fsize)
largest_fsize = statbuf.st_size;
}
// Keep track of how large the file size column must be
do {
largest_fsize /=10;
fs_digits++;
} while (largest_fsize != 0);
sort(filename.begin(), filename.end());
for (int i = 0; i<filename.size(); i++) {
status = stat(filename[i].c_str(), &statbuf);
if (status == -1)
perror("stat");
if (flags & FLAG_a && filename[i][0] == '.')
displayfile(filename[i], &statbuf, flags & FLAG_l);
else if (filename[i][0] != '.')
displayfile(filename[i], &statbuf, flags & FLAG_l);
}
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>//
// mc.cpp
//
// manage c++ code
//
// Created by Daniel Kozitza
//
#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sys/ioctl.h>
#include <omp.h>
#include "commands.hpp"
#include "tools.hpp"
#include "sorters.hpp"
using namespace tools;
typedef map<string, string>::iterator map_iter;
void build(vector<string>& argv);
void cnt();
void env();
void makefile(vector<string>& argv);
void mkreadme(vector<string>& argv);
void rebuild(vector<string>& argv);
void run(vector<string>& argv);
void runtime(vector<string>& argv);
void runtimeavg(vector<string>& argv);
int main(int argc, char *argv[]) {
vector<string> Argv(0);
string cmd_str;
signal(SIGINT, signals_callback_handler);
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
commands cmds;
cmds.set_program_name(string(argv[0]));
cmds.set_max_line_width(ws.ws_col);
cmds.set_cmds_help(
"\nmc is a tool for managing c++ source code.\n\n"
"Usage:\n\n mc command [arguments]\n");
cmds.handle(
"makefile",
makefile,
"Creates a make file by calling vfnmkmc [arguments].",
"makefile [arguments]");
cmds.handle(
"build",
build,
"Calls vfnmkmc [arguments] (if needed) then calls make.",
"build [arguments]");
cmds.handle(
"rebuild",
rebuild,
"Calls make clean, vfnmkmc [arguments] (if needed), then make.",
"rebuild [arguments]");
cmds.handle(
"run",
run,
"Calls vfnmkmc (if needed), make, then ./program [arguments].",
"run [arguments]");
cmds.handle(
"runtime",
runtime,
"Time the run command.",
"runtime [arguments]");
cmds.handle(
"runtimeavg",
runtimeavg,
"Get the average time of multiple run executions.",
"runtimeavg [RUNS=10, [arguments]]");
cmds.handle(
"env",
env,
"Displays the variables read from vfnmkmc.conf.",
"env");
cmds.handle(
"mkreadme",
mkreadme,
"Make a README.md file from ./program [arguments].",
"mkreadme");
cmds.handle(
"cnt",
cnt,
"Counts the number of lines in each of the source files.",
"cnt");
if (argc < 2)
cmd_str = "help";
else
cmd_str = argv[1];
for (int i = 2; i < argc; i++)
Argv.push_back(string(argv[i]));
cmds.run(cmd_str, Argv);
return 0;
}
void makefile(vector<string>& argv) {
string sys_call = "vfnmkmc";
for (int i = 0; i < argv.size(); i++)
sys_call += " \"" + argv[i] + "\"";
cout << "mc::makefile: calling `" << sys_call << "`." << endl;
require(system(sys_call.c_str()));
}
void build(vector<string>& argv) {
map<string, string> vfnconf;
if (!get_vfnmkmc_conf(vfnconf)) {
makefile(argv);
cout << "mc::build: reading vfnmkmc.conf." << endl;
require(get_vfnmkmc_conf(vfnconf));
vfnconf["src_files"] = get_src_files(vfnconf["src_directory"]);
save_vfnmkmc_conf(vfnconf);
}
else {
// vfnmkmc.conf was read, check if current source file listing matches
// the one in vfnconf.
string new_src_files = get_src_files(vfnconf["src_directory"]);
if (vfnconf["src_files"] != new_src_files) {
// if no match set new_src_files and call vfnmake
vfnconf["src_files"] = new_src_files;
save_vfnmkmc_conf(vfnconf);
makefile(argv);
}
}
cout << "mc::build: calling `make`." << endl;
require(system("make"));
}
void rebuild(vector<string>& argv) {
cout << "mc::rebuild: calling `make clean`.\n";
require(system("make clean"));
build(argv);
}
void run(vector<string>& argv) {
vector<string> empty_v;
build(empty_v);
map<string, string> vfnconf;
require(get_vfnmkmc_conf(vfnconf));
string system_call = "./";
system_call += vfnconf["name"];
for (int i = 0; i < argv.size(); i++)
system_call += " \"" + argv[i] + "\"";
cout << "mc::run: calling `" << system_call << "`.\n";
system(system_call.c_str());
}
void runtime(vector<string>& argv) {
double start, end;
vector<string> junk;
build(junk);
map<string, string> vfnconf;
require(get_vfnmkmc_conf(vfnconf));
string system_call = "./";
system_call += vfnconf["name"];
for (int i = 0; i < argv.size(); i++)
system_call += " \"" + argv[i] + "\"";
cout << "mc::runtime: calling `" << system_call << "`.\n";
start = omp_get_wtime();
system(system_call.c_str());
end = omp_get_wtime();
cout << "mc::runtime: execution time (seconds): `";
cout << end - start << "`.\n";
}
void runtimeavg(vector<string>& argv) {
double start, end, average = 0;
int runs;
vector<string> junk;
build(junk);
map<string, string> vfnconf;
require(get_vfnmkmc_conf(vfnconf));
if (argv.size() < 1)
runs = 10;
else
runs = atoi(argv[0].c_str());
string system_call = "./";
system_call += vfnconf["name"];
for (int z = 1; z < argv.size(); z++)
system_call += " \"" + argv[z] + "\"";
for(int j = 0; j < runs; ++j) {
cout << "mc::runtimeavg: starting run " << j + 1 << "/" << runs << ".\n";
cout << "mc::runtimeavg: calling `" << system_call << "`.\n";
start = omp_get_wtime();
system(system_call.c_str());
end = omp_get_wtime();
cout << "mc::runtimeavg: execution time for run " << j + 1 << "/";
cout << runs << " (seconds): `" << end - start << "`.\n";
if (average != 0)
average = (average + (end - start)) / 2;
else
average = end - start;
}
cout << "mc::runtimeavg: execution time average after ";
cout << runs << " runs (seconds): `";
cout << average << "`.\n";
}
void env() {
map<string, string> vfnconf;
cout << "mc::env: reading vfnmkmc.conf." << endl;
require(get_vfnmkmc_conf(vfnconf));
cout << "\nvfnmkmc.conf:\n\n";
//for (const auto item : vfnconf) {
// cout << item.first << ": " << item.second << "\n";
//}
for (map_iter it = vfnconf.begin(); it != vfnconf.end(); ++it)
cout << it->first << ": " << it->second << "\n";
cout << "\n";
}
void mkreadme(vector<string>& argv) {
map<string, string> vfnconf;
cout << "mc::mkreadme: reading vfnmkmc.conf." << endl;
require(get_vfnmkmc_conf(vfnconf));
string sys_call = "echo '# " + vfnconf["name"] + "' > README.md";
cout << "mc::mkreadme: calling `" << sys_call << "`.\n";
require(system(sys_call.c_str()));
sys_call = "./" + vfnconf["name"];
for (int i = 0; i < argv.size(); ++i)
sys_call += " \"" + argv[i] + "\"";
sys_call += " >> README.md";
cout << "mc::mkreadme: calling `" << sys_call << "`.\n";
system(sys_call.c_str());
}
void cnt() {
map<string, string> vfnconf;
vector<string> contents(0);
unsigned int total_lines = 0;
string src_dir;
if (get_vfnmkmc_conf(vfnconf))
src_dir = vfnconf["src_directory"];
else
src_dir = ".";
if (!list_dir_r(src_dir, contents)) {
cerr << "mc::cnt: vfnmkmc src_directory `" + src_dir;
cerr << "` does not exist\n";
return;
}
vector<string> new_contents(0);
for (int i = 0; i < contents.size(); ++i) {
if (pmatches(contents[i], "(\\.cpp|\\.c|\\.hpp|\\.h)$")) {
new_contents.push_back(contents[i]);
}
}
contents = new_contents;
new_contents.clear();
int longest = 0;
for (int i = 0; i < contents.size(); ++i) {
string fname = src_dir + "/" + contents[i];
if (fname.size() > longest)
longest = fname.size() + 1;
}
sorters::radix(contents);
ifstream fh;
for (int i = 0; i < contents.size(); ++i) {
string fname = src_dir + "/" + contents[i];
fh.open(fname.c_str(), ifstream::in);
if (!fh.is_open()) {
cout << "mc::cnt: could not open file: `" << fname << "`\n";
continue;
}
char c;
int file_lines = 0;
while (fh.peek() != EOF) {
fh.get(c);
if (c == '\n')
++file_lines;
}
fh.close();
total_lines += file_lines;
fname += ":";
cout << left << setw(longest) << fname;
cout << " " << file_lines << endl;
}
cout << endl << left << setw(longest) << "total_loc:";
cout << " " << total_lines << "\n\n";
}
<commit_msg>wording<commit_after>//
// mc.cpp
//
// manage c++ code
//
// Created by Daniel Kozitza
//
#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sys/ioctl.h>
#include <omp.h>
#include "commands.hpp"
#include "tools.hpp"
#include "sorters.hpp"
using namespace tools;
typedef map<string, string>::iterator map_iter;
void build(vector<string>& argv);
void cnt();
void env();
void makefile(vector<string>& argv);
void mkreadme(vector<string>& argv);
void rebuild(vector<string>& argv);
void run(vector<string>& argv);
void runtime(vector<string>& argv);
void runtimeavg(vector<string>& argv);
int main(int argc, char *argv[]) {
vector<string> Argv(0);
string cmd_str;
signal(SIGINT, signals_callback_handler);
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
commands cmds;
cmds.set_program_name(string(argv[0]));
cmds.set_max_line_width(ws.ws_col);
cmds.set_cmds_help(
"\nmc is a tool for managing c++ source code.\n\n"
"Usage:\n\n mc command [arguments]\n");
cmds.handle(
"makefile",
makefile,
"Creates a make file by calling vfnmkmc [arguments].",
"makefile [arguments]");
cmds.handle(
"build",
build,
"Calls vfnmkmc [arguments] (if needed) then calls make.",
"build [arguments]");
cmds.handle(
"rebuild",
rebuild,
"Calls make clean, vfnmkmc [arguments] (if needed), then make.",
"rebuild [arguments]");
cmds.handle(
"run",
run,
"Calls vfnmkmc (if needed), make, then ./program [arguments].",
"run [arguments]");
cmds.handle(
"runtime",
runtime,
"Time the run command.",
"runtime [arguments]");
cmds.handle(
"runtimeavg",
runtimeavg,
"Get the average time of multiple run executions.",
"runtimeavg [RUNS=10, [arguments]]");
cmds.handle(
"env",
env,
"Displays the variables read from vfnmkmc.conf.",
"env");
cmds.handle(
"mkreadme",
mkreadme,
"Make a README.md file from ./program [arguments].",
"mkreadme");
cmds.handle(
"cnt",
cnt,
"Counts the number of lines in each of the source files.",
"cnt");
if (argc < 2)
cmd_str = "help";
else
cmd_str = argv[1];
for (int i = 2; i < argc; i++)
Argv.push_back(string(argv[i]));
cmds.run(cmd_str, Argv);
return 0;
}
void makefile(vector<string>& argv) {
string sys_call = "vfnmkmc";
for (int i = 0; i < argv.size(); i++)
sys_call += " \"" + argv[i] + "\"";
cout << "mc::makefile: calling `" << sys_call << "`." << endl;
require(system(sys_call.c_str()));
}
void build(vector<string>& argv) {
map<string, string> vfnconf;
if (!get_vfnmkmc_conf(vfnconf)) {
makefile(argv);
cout << "mc::build: reading vfnmkmc.conf." << endl;
require(get_vfnmkmc_conf(vfnconf));
vfnconf["src_files"] = get_src_files(vfnconf["src_directory"]);
save_vfnmkmc_conf(vfnconf);
}
else {
// vfnmkmc.conf was read, check if current source file listing matches
// the one in vfnconf.
string new_src_files = get_src_files(vfnconf["src_directory"]);
if (vfnconf["src_files"] != new_src_files) {
// if no match set new_src_files and call vfnmake
vfnconf["src_files"] = new_src_files;
save_vfnmkmc_conf(vfnconf);
makefile(argv);
}
}
cout << "mc::build: calling `make`." << endl;
require(system("make"));
}
void rebuild(vector<string>& argv) {
cout << "mc::rebuild: calling `make clean`.\n";
require(system("make clean"));
build(argv);
}
void run(vector<string>& argv) {
vector<string> empty_v;
build(empty_v);
map<string, string> vfnconf;
require(get_vfnmkmc_conf(vfnconf));
string system_call = "./";
system_call += vfnconf["name"];
for (int i = 0; i < argv.size(); i++)
system_call += " \"" + argv[i] + "\"";
cout << "mc::run: calling `" << system_call << "`.\n";
system(system_call.c_str());
}
void runtime(vector<string>& argv) {
double start, end;
vector<string> empty_v;
build(empty_v);
map<string, string> vfnconf;
require(get_vfnmkmc_conf(vfnconf));
string system_call = "./";
system_call += vfnconf["name"];
for (int i = 0; i < argv.size(); i++)
system_call += " \"" + argv[i] + "\"";
cout << "mc::runtime: calling `" << system_call << "`.\n";
start = omp_get_wtime();
system(system_call.c_str());
end = omp_get_wtime();
cout << "mc::runtime: execution time (seconds): `";
cout << end - start << "`.\n";
}
void runtimeavg(vector<string>& argv) {
double start, end, average = 0;
int runs;
vector<string> empty_v;
build(empty_v);
map<string, string> vfnconf;
require(get_vfnmkmc_conf(vfnconf));
if (argv.size() < 1)
runs = 10;
else
runs = atoi(argv[0].c_str());
string system_call = "./";
system_call += vfnconf["name"];
for (int z = 1; z < argv.size(); z++)
system_call += " \"" + argv[z] + "\"";
for(int j = 0; j < runs; ++j) {
cout << "mc::runtimeavg: starting run " << j + 1 << "/" << runs << ".\n";
cout << "mc::runtimeavg: calling `" << system_call << "`.\n";
start = omp_get_wtime();
system(system_call.c_str());
end = omp_get_wtime();
cout << "mc::runtimeavg: execution time for run " << j + 1 << "/";
cout << runs << " (seconds): `" << end - start << "`.\n";
if (average != 0)
average = (average + (end - start)) / 2;
else
average = end - start;
}
cout << "mc::runtimeavg: execution time average after ";
cout << runs << " runs (seconds): `";
cout << average << "`.\n";
}
void env() {
map<string, string> vfnconf;
cout << "mc::env: reading vfnmkmc.conf." << endl;
require(get_vfnmkmc_conf(vfnconf));
cout << "\nvfnmkmc.conf:\n\n";
//for (const auto item : vfnconf) {
// cout << item.first << ": " << item.second << "\n";
//}
for (map_iter it = vfnconf.begin(); it != vfnconf.end(); ++it)
cout << it->first << ": " << it->second << "\n";
cout << "\n";
}
void mkreadme(vector<string>& argv) {
map<string, string> vfnconf;
cout << "mc::mkreadme: reading vfnmkmc.conf." << endl;
require(get_vfnmkmc_conf(vfnconf));
string sys_call = "echo '# " + vfnconf["name"] + "' > README.md";
cout << "mc::mkreadme: calling `" << sys_call << "`.\n";
require(system(sys_call.c_str()));
sys_call = "./" + vfnconf["name"];
for (int i = 0; i < argv.size(); ++i)
sys_call += " \"" + argv[i] + "\"";
sys_call += " >> README.md";
cout << "mc::mkreadme: calling `" << sys_call << "`.\n";
system(sys_call.c_str());
}
void cnt() {
map<string, string> vfnconf;
vector<string> contents(0);
unsigned int total_lines = 0;
string src_dir;
if (get_vfnmkmc_conf(vfnconf))
src_dir = vfnconf["src_directory"];
else
src_dir = ".";
if (!list_dir_r(src_dir, contents)) {
cerr << "mc::cnt: vfnmkmc src_directory `" + src_dir;
cerr << "` does not exist\n";
return;
}
vector<string> new_contents(0);
for (int i = 0; i < contents.size(); ++i) {
if (pmatches(contents[i], "(\\.cpp|\\.c|\\.hpp|\\.h)$")) {
new_contents.push_back(contents[i]);
}
}
contents = new_contents;
new_contents.clear();
int longest = 0;
for (int i = 0; i < contents.size(); ++i) {
string fname = src_dir + "/" + contents[i];
if (fname.size() > longest)
longest = fname.size() + 1;
}
sorters::radix(contents);
ifstream fh;
for (int i = 0; i < contents.size(); ++i) {
string fname = src_dir + "/" + contents[i];
fh.open(fname.c_str(), ifstream::in);
if (!fh.is_open()) {
cout << "mc::cnt: could not open file: `" << fname << "`\n";
continue;
}
char c;
int file_lines = 0;
while (fh.peek() != EOF) {
fh.get(c);
if (c == '\n')
++file_lines;
}
fh.close();
total_lines += file_lines;
fname += ":";
cout << left << setw(longest) << fname;
cout << " " << file_lines << endl;
}
cout << endl << left << setw(longest) << "total_loc:";
cout << " " << total_lines << "\n\n";
}
<|endoftext|> |
<commit_before>#include "mmu.h"
#include "boot.h"
#include "util/log.h"
#include "video/video.h"
#include <cstdlib>
MMU::MMU(Cartridge& inCartridge, Video& inVideo) :
cartridge(inCartridge),
video(inVideo)
{
memory = std::vector<u8>(0xFFFF);
}
u8 MMU::read(const Address address) const {
if (address.in_range(0x0, 0x7FFF)) {
if (address.in_range(0x0, 0xFF) && boot_rom_active()) {
return bootDMG[address.value()];
}
return cartridge.read(address);
}
/* VRAM */
if (address.in_range(0x8000, 0x9FFF)) {
return memory_read(address);
}
/* External (cartridge) RAM */
if (address.in_range(0xA000, 0xBFFF)) {
/* log_warn("Attempting to read from cartridge RAM"); */
return memory_read(address);
}
/* Internal work RAM */
if (address.in_range(0xC000, 0xDFFF)) {
return memory_read(address);
}
if (address.in_range(0xE000, 0xFDFF)) {
/* log_warn("Attempting to read from mirrored work RAM"); */
auto mirrored_address = Address(address.value() - 0x2000);
return memory_read(mirrored_address);
}
/* OAM */
if (address.in_range(0xFE00, 0xFE9F)) {
return memory_read(address);
}
if (address.in_range(0xFEA0, 0xFEFF)) {
log_warn("Attempting to read from unusable memory");
/* TODO: does this always return 0? */
return 0;
}
/* Mapped IO */
if (address.in_range(0xFF00, 0xFF7F)) {
return read_io(address);
}
/* Zero Page ram */
if (address.in_range(0xFF80, 0xFFFE)) {
return memory_read(address);
}
/* Interrupt Enable register */
if (address == 0xFFFF) {
return memory_read(address);
}
log_error("Attempted to read from unmapped memory address %X", address.value());
fatal_error();
}
u8 MMU::memory_read(const Address address) const {
return memory[address.value()];
}
u8 MMU::read_io(const Address address) const {
switch (address.value()) {
case 0xFF00:
log_warn("Attempted to read joypad register");
return 0xFF;
case 0xFF01:
log_warn("Attempted to read serial transfer data");
return 0xFF;
case 0xFF02:
log_warn("Attempted to read serial transfer control");
return 0xFF;
case 0xFF42:
return video.scroll_y.value();
case 0xFF44:
return video.line.value();
/* Disable boot rom switch */
case 0xFF50:
return memory_read(address);
default:
log_error("Read from unknown IO address 0x%x", address.value());
exit(1);
}
}
void MMU::write(const Address address, const u8 byte) {
if (address.in_range(0x0000, 0x7FFF)) {
log_warn("Attempting to write to cartridge ROM");
}
/* VRAM */
if (address.in_range(0x8000, 0x9FFF)) {
memory_write(address, byte);
return;
}
/* External (cartridge) RAM */
if (address.in_range(0xA000, 0xBFFF)) {
memory_write(address, byte);
return;
}
/* Internal work RAM */
if (address.in_range(0xC000, 0xDFFF)) {
memory_write(address, byte);
return;
}
/* Mirrored RAM */
if (address.in_range(0xE000, 0xFDFF)) {
log_warn("Attempting to write to mirrored work RAM");
auto mirrored_address = Address(address.value() - 0x2000);
memory_write(mirrored_address, byte);
return;
}
/* OAM */
if (address.in_range(0xFE00, 0xFE9F)) {
memory_write(address, byte);
return;
}
if (address.in_range(0xFEA0, 0xFEFF)) {
log_warn("Attempting to write to unusable memory");
}
/* Mapped IO */
if (address.in_range(0xFF00, 0xFF7F)) {
write_io(address, byte);
return;
}
/* Zero Page ram */
if (address.in_range(0xFF80, 0xFFFE)) {
memory_write(address, byte);
return;
}
/* Interrupt Enable register */
if (address == 0xFFFF) {
memory_write(address, byte);
return;
}
log_error("Attempted to write to unmapped memory address %X", address.value());
fatal_error();
}
void MMU::write_io(const Address address, const u8 byte) {
switch (address.value()) {
/* Serial data transfer (SB) */
case 0xFF01:
/* TODO */
/* log_warn("%c", byte); */
return;
case 0xFF11:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF12:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF13:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF14:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF24:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF25:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF26:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
/* Switch on LCD */
case 0xFF40:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
/* Vertical Scroll Register */
case 0xFF42:
video.scroll_y.set(byte);
return;
/* LY - Line Y coordinate */
case 0xFF44:
/* "Writing will reset the counter */
log_warn("Writing to FF44 will reset the line counter");
return;
case 0xFF47:
/* TODO */
video.bg_palette.set(byte);
log_warn("Set video palette: %x", byte);
return;
/* Disable boot rom switch */
case 0xFF50:
/* TODO */
memory_write(address, byte);
return;
}
}
void MMU::memory_write(const Address address, const u8 byte) {
memory[address.value()] = byte;
}
bool MMU::boot_rom_active() const {
return read(0xFF50) != 0x1;
}
<commit_msg>Do not exit if cartridge ROM was written to<commit_after>#include "mmu.h"
#include "boot.h"
#include "util/log.h"
#include "video/video.h"
#include <cstdlib>
MMU::MMU(Cartridge& inCartridge, Video& inVideo) :
cartridge(inCartridge),
video(inVideo)
{
memory = std::vector<u8>(0xFFFF);
}
u8 MMU::read(const Address address) const {
if (address.in_range(0x0, 0x7FFF)) {
if (address.in_range(0x0, 0xFF) && boot_rom_active()) {
return bootDMG[address.value()];
}
return cartridge.read(address);
}
/* VRAM */
if (address.in_range(0x8000, 0x9FFF)) {
return memory_read(address);
}
/* External (cartridge) RAM */
if (address.in_range(0xA000, 0xBFFF)) {
/* log_warn("Attempting to read from cartridge RAM"); */
return memory_read(address);
}
/* Internal work RAM */
if (address.in_range(0xC000, 0xDFFF)) {
return memory_read(address);
}
if (address.in_range(0xE000, 0xFDFF)) {
/* log_warn("Attempting to read from mirrored work RAM"); */
auto mirrored_address = Address(address.value() - 0x2000);
return memory_read(mirrored_address);
}
/* OAM */
if (address.in_range(0xFE00, 0xFE9F)) {
return memory_read(address);
}
if (address.in_range(0xFEA0, 0xFEFF)) {
log_warn("Attempting to read from unusable memory");
/* TODO: does this always return 0? */
return 0;
}
/* Mapped IO */
if (address.in_range(0xFF00, 0xFF7F)) {
return read_io(address);
}
/* Zero Page ram */
if (address.in_range(0xFF80, 0xFFFE)) {
return memory_read(address);
}
/* Interrupt Enable register */
if (address == 0xFFFF) {
return memory_read(address);
}
log_error("Attempted to read from unmapped memory address %X", address.value());
fatal_error();
}
u8 MMU::memory_read(const Address address) const {
return memory[address.value()];
}
u8 MMU::read_io(const Address address) const {
switch (address.value()) {
case 0xFF00:
log_warn("Attempted to read joypad register");
return 0xFF;
case 0xFF01:
log_warn("Attempted to read serial transfer data");
return 0xFF;
case 0xFF02:
log_warn("Attempted to read serial transfer control");
return 0xFF;
case 0xFF42:
return video.scroll_y.value();
case 0xFF44:
return video.line.value();
/* Disable boot rom switch */
case 0xFF50:
return memory_read(address);
default:
log_error("Read from unknown IO address 0x%x", address.value());
exit(1);
}
}
void MMU::write(const Address address, const u8 byte) {
if (address.in_range(0x0000, 0x7FFF)) {
log_warn("Attempting to write to cartridge ROM");
return;
}
/* VRAM */
if (address.in_range(0x8000, 0x9FFF)) {
memory_write(address, byte);
return;
}
/* External (cartridge) RAM */
if (address.in_range(0xA000, 0xBFFF)) {
memory_write(address, byte);
return;
}
/* Internal work RAM */
if (address.in_range(0xC000, 0xDFFF)) {
memory_write(address, byte);
return;
}
/* Mirrored RAM */
if (address.in_range(0xE000, 0xFDFF)) {
log_warn("Attempting to write to mirrored work RAM");
auto mirrored_address = Address(address.value() - 0x2000);
memory_write(mirrored_address, byte);
return;
}
/* OAM */
if (address.in_range(0xFE00, 0xFE9F)) {
memory_write(address, byte);
return;
}
if (address.in_range(0xFEA0, 0xFEFF)) {
log_warn("Attempting to write to unusable memory");
}
/* Mapped IO */
if (address.in_range(0xFF00, 0xFF7F)) {
write_io(address, byte);
return;
}
/* Zero Page ram */
if (address.in_range(0xFF80, 0xFFFE)) {
memory_write(address, byte);
return;
}
/* Interrupt Enable register */
if (address == 0xFFFF) {
memory_write(address, byte);
return;
}
log_error("Attempted to write to unmapped memory address %X", address.value());
fatal_error();
}
void MMU::write_io(const Address address, const u8 byte) {
switch (address.value()) {
/* Serial data transfer (SB) */
case 0xFF01:
/* TODO */
/* log_warn("%c", byte); */
return;
case 0xFF11:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF12:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF13:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF14:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF24:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF25:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
case 0xFF26:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
/* Switch on LCD */
case 0xFF40:
/* TODO */
log_warn("Wrote to unknown address 0x%x", address.value());
/* memory_write(address, byte); */
return;
/* Vertical Scroll Register */
case 0xFF42:
video.scroll_y.set(byte);
return;
/* LY - Line Y coordinate */
case 0xFF44:
/* "Writing will reset the counter */
log_warn("Writing to FF44 will reset the line counter");
return;
case 0xFF47:
/* TODO */
video.bg_palette.set(byte);
log_warn("Set video palette: %x", byte);
return;
/* Disable boot rom switch */
case 0xFF50:
/* TODO */
memory_write(address, byte);
return;
}
}
void MMU::memory_write(const Address address, const u8 byte) {
memory[address.value()] = byte;
}
bool MMU::boot_rom_active() const {
return read(0xFF50) != 0x1;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009, Regents of the University of Alaska
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 Geographic Information Network of Alaska 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.
This code was developed by Dan Stahlke for the Geographic Information Network of Alaska.
*/
#include <algorithm>
#include <boost/tokenizer.hpp>
#include "common.h"
#include "ndv.h"
void usage(const std::string &cmdname); // externally defined
namespace dangdal {
void NdvDef::printUsage() {
// FIXME
printf("\
No-data values:\n\
-ndv val Set a no-data value\n\
-ndv 'val val ...' Set a no-data value using all input bands\n\
-ndv 'min..max min..max ...' Set a range of no-data values\n\
(-Inf and Inf are allowed)\n\
-valid-range 'min..max min..max ...' Set a range of valid data values\n\
");
}
NdvInterval::NdvInterval(const std::string &s) {
if(VERBOSE >= 2) printf("minmax [%s]\n", s.c_str());
char *endptr;
double min, max;
size_t delim = s.find("..");
if(delim == std::string::npos) {
min = max = strtod(s.c_str(), &endptr);
if(*endptr) fatal_error("NDV value was not a number");
} else {
std::string s1 = s.substr(0, delim);
std::string s2 = s.substr(delim+2);
// FIXME - allow -Inf, Inf
min = strtod(s1.c_str(), &endptr);
if(*endptr) fatal_error("NDV value was not a number");
max = strtod(s2.c_str(), &endptr);
if(*endptr) fatal_error("NDV value was not a number");
}
first = min;
second = max;
}
NdvSlab::NdvSlab(const std::string &s) {
//printf("range [%s]\n", s.c_str());
boost::char_separator<char> sep(" ");
typedef boost::tokenizer<boost::char_separator<char> > toker;
toker tok(s, sep);
for(toker::iterator p=tok.begin(); p!=tok.end(); ++p) {
range_by_band.push_back(NdvInterval(*p));
}
if(range_by_band.empty()) {
fatal_error("could not parse given NDV term [%s]", s.c_str());
}
}
NdvDef::NdvDef(std::vector<std::string> &arg_list) :
invert(false)
{
std::vector<std::string> args_out;
const std::string cmdname = arg_list[0];
args_out.push_back(cmdname);
bool got_ndv=0, got_dv=0;
size_t argp = 1;
while(argp < arg_list.size()) {
const std::string &arg = arg_list[argp++];
if(arg[0] == '-') {
if(arg == "-ndv") {
if(argp == arg_list.size()) usage(cmdname);
slabs.push_back(NdvSlab(arg_list[argp++]));
got_ndv = 1;
} else if(arg == "-valid-range") {
if(argp == arg_list.size()) usage(cmdname);
slabs.push_back(NdvSlab(arg_list[argp++]));
got_dv = 1;
} else {
args_out.push_back(arg);
}
} else {
args_out.push_back(arg);
}
}
if(got_ndv && got_dv) {
fatal_error("you cannot use both -ndv and -valid-range options");
} else {
invert = got_dv;
}
if(VERBOSE >= 2) debugPrint();
arg_list = args_out;
}
void NdvDef::debugPrint() const {
printf("=== NDV\n");
for(size_t i=0; i<slabs.size(); i++) {
const NdvSlab &slab = slabs[i];
for(size_t j=0; j<slab.range_by_band.size(); j++) {
const NdvInterval &range = slab.range_by_band[j];
printf("range %zd,%zd = [%g,%g]\n", i, j, range.first, range.second);
}
}
printf("=== end NDV\n");
}
NdvDef::NdvDef(const GDALDatasetH ds, const std::vector<size_t> &bandlist) {
bool got_error = 0;
NdvSlab slab;
size_t band_count = GDALGetRasterCount(ds);
for(size_t bandlist_idx=0; bandlist_idx<bandlist.size(); bandlist_idx++) {
size_t band_idx = bandlist[bandlist_idx];
if(band_idx < 1 || band_idx > band_count) fatal_error("bandid out of range");
GDALRasterBandH band = GDALGetRasterBand(ds, band_idx);
int success;
double val = GDALGetRasterNoDataValue(band, &success);
if(success) {
slab.range_by_band.push_back(NdvInterval(val, val));
} else {
got_error = true;
}
}
if(!got_error) {
slabs.push_back(slab);
}
}
template<class T>
void flagMatches(
const NdvInterval range,
const T *in_data,
uint8_t *mask_out,
size_t nsamps
) {
for(size_t i=0; i<nsamps; i++) {
T val = in_data[i];
if(range.contains(val)) mask_out[i] = 1;
}
}
template<>
void flagMatches<uint8_t>(
const NdvInterval range,
const uint8_t *in_data,
uint8_t *mask_out,
size_t nsamps
) {
uint8_t min_byte = (uint8_t)std::max(ceil (range.first ), 0.0);
uint8_t max_byte = (uint8_t)std::min(floor(range.second), 255.0);
for(size_t i=0; i<nsamps; i++) {
uint8_t v = in_data[i];
uint8_t match = (v >= min_byte) && (v <= max_byte);
if(match) mask_out[i] = 1;
}
}
template<class T>
void flagNaN(
const T *in_data,
uint8_t *mask_out,
size_t nsamps
) {
for(size_t i=0; i<nsamps; i++) {
if(isnan(in_data[i])) mask_out[i] = 1;
}
}
template<>
void flagNaN<uint8_t>(
const uint8_t *in_data __attribute__((unused)),
uint8_t *mask_out __attribute__((unused)),
size_t nsamps __attribute__((unused))
) { } // no-op
template<class T>
void NdvDef::arrayCheckNdv(
size_t band, const T *in_data,
uint8_t *mask_out, size_t nsamps
) const {
for(size_t i=0; i<nsamps; i++) mask_out[i] = 0;
for(size_t slab_idx=0; slab_idx<slabs.size(); slab_idx++) {
const NdvSlab &slab = slabs[slab_idx];
NdvInterval range;
if(band > 0 && slab.range_by_band.size() == 1) {
// if only a single range is defined, use it for all bands
range = slab.range_by_band[0];
} else if(band < slab.range_by_band.size()) {
range = slab.range_by_band[band];
} else {
fatal_error("wrong number of bands in NDV def");
}
flagMatches(range, in_data, mask_out, nsamps);
}
if(invert) {
for(size_t i=0; i<nsamps; i++) {
mask_out[i] = mask_out[i] ? 0 : 1;
}
}
flagNaN(in_data, mask_out, nsamps);
}
void NdvDef::aggregateMask(
uint8_t *total_mask,
const uint8_t *band_mask,
size_t nsamps
) const {
if(invert) {
// pixel is valid only if all bands are within valid range
for(size_t i=0; i<nsamps; i++) {
if(band_mask[i]) total_mask[i] = 1;
}
} else {
// pixel is NDV only if all bands are NDV
for(size_t i=0; i<nsamps; i++) {
if(!band_mask[i]) total_mask[i] = 0;
}
}
}
template void NdvDef::arrayCheckNdv<uint8_t>(
size_t band, const uint8_t *in_data,
uint8_t *mask_out, size_t nsamps
) const;
template void NdvDef::arrayCheckNdv<double>(
size_t band, const double *in_data,
uint8_t *mask_out, size_t nsamps
) const;
} // namespace dangdal
<commit_msg>ndv fix<commit_after>/*
Copyright (c) 2009, Regents of the University of Alaska
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 Geographic Information Network of Alaska 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.
This code was developed by Dan Stahlke for the Geographic Information Network of Alaska.
*/
#include <algorithm>
#include <boost/tokenizer.hpp>
#include "common.h"
#include "ndv.h"
void usage(const std::string &cmdname); // externally defined
namespace dangdal {
void NdvDef::printUsage() {
// FIXME
printf("\
No-data values:\n\
-ndv val Set a no-data value\n\
-ndv 'val val ...' Set a no-data value using all input bands\n\
-ndv 'min..max min..max ...' Set a range of no-data values\n\
(-Inf and Inf are allowed)\n\
-valid-range 'min..max min..max ...' Set a range of valid data values\n\
");
}
NdvInterval::NdvInterval(const std::string &s) {
if(VERBOSE >= 2) printf("minmax [%s]\n", s.c_str());
char *endptr;
double min, max;
size_t delim = s.find("..");
if(delim == std::string::npos) {
min = max = strtod(s.c_str(), &endptr);
if(*endptr) fatal_error("NDV value was not a number");
} else {
std::string s1 = s.substr(0, delim);
std::string s2 = s.substr(delim+2);
// FIXME - allow -Inf, Inf
min = strtod(s1.c_str(), &endptr);
if(*endptr) fatal_error("NDV value was not a number");
max = strtod(s2.c_str(), &endptr);
if(*endptr) fatal_error("NDV value was not a number");
}
first = min;
second = max;
}
NdvSlab::NdvSlab(const std::string &s) {
//printf("range [%s]\n", s.c_str());
boost::char_separator<char> sep(" ");
typedef boost::tokenizer<boost::char_separator<char> > toker;
toker tok(s, sep);
for(toker::iterator p=tok.begin(); p!=tok.end(); ++p) {
range_by_band.push_back(NdvInterval(*p));
}
if(range_by_band.empty()) {
fatal_error("could not parse given NDV term [%s]", s.c_str());
}
}
NdvDef::NdvDef(std::vector<std::string> &arg_list) :
invert(false)
{
std::vector<std::string> args_out;
const std::string cmdname = arg_list[0];
args_out.push_back(cmdname);
bool got_ndv=0, got_dv=0;
size_t argp = 1;
while(argp < arg_list.size()) {
const std::string &arg = arg_list[argp++];
if(arg[0] == '-') {
if(arg == "-ndv") {
if(argp == arg_list.size()) usage(cmdname);
slabs.push_back(NdvSlab(arg_list[argp++]));
got_ndv = 1;
} else if(arg == "-valid-range") {
if(argp == arg_list.size()) usage(cmdname);
slabs.push_back(NdvSlab(arg_list[argp++]));
got_dv = 1;
} else {
args_out.push_back(arg);
}
} else {
args_out.push_back(arg);
}
}
if(got_ndv && got_dv) {
fatal_error("you cannot use both -ndv and -valid-range options");
} else {
invert = got_dv;
}
if(VERBOSE >= 2) debugPrint();
arg_list = args_out;
}
NdvDef::NdvDef(const GDALDatasetH ds, const std::vector<size_t> &bandlist) :
invert(false)
{
bool got_error = 0;
NdvSlab slab;
size_t band_count = GDALGetRasterCount(ds);
for(size_t bandlist_idx=0; bandlist_idx<bandlist.size(); bandlist_idx++) {
size_t band_idx = bandlist[bandlist_idx];
if(band_idx < 1 || band_idx > band_count) fatal_error("bandid out of range");
GDALRasterBandH band = GDALGetRasterBand(ds, band_idx);
int success;
double val = GDALGetRasterNoDataValue(band, &success);
if(success) {
slab.range_by_band.push_back(NdvInterval(val, val));
} else {
got_error = true;
}
}
if(!got_error) {
slabs.push_back(slab);
}
}
void NdvDef::debugPrint() const {
printf("=== NDV\n");
for(size_t i=0; i<slabs.size(); i++) {
const NdvSlab &slab = slabs[i];
for(size_t j=0; j<slab.range_by_band.size(); j++) {
const NdvInterval &range = slab.range_by_band[j];
printf("range %zd,%zd = [%g,%g]\n", i, j, range.first, range.second);
}
}
printf("=== end NDV\n");
}
template<class T>
void flagMatches(
const NdvInterval range,
const T *in_data,
uint8_t *mask_out,
size_t nsamps
) {
for(size_t i=0; i<nsamps; i++) {
T val = in_data[i];
if(range.contains(val)) mask_out[i] = 1;
}
}
template<>
void flagMatches<uint8_t>(
const NdvInterval range,
const uint8_t *in_data,
uint8_t *mask_out,
size_t nsamps
) {
uint8_t min_byte = (uint8_t)std::max(ceil (range.first ), 0.0);
uint8_t max_byte = (uint8_t)std::min(floor(range.second), 255.0);
for(size_t i=0; i<nsamps; i++) {
uint8_t v = in_data[i];
uint8_t match = (v >= min_byte) && (v <= max_byte);
if(match) mask_out[i] = 1;
}
}
template<class T>
void flagNaN(
const T *in_data,
uint8_t *mask_out,
size_t nsamps
) {
for(size_t i=0; i<nsamps; i++) {
if(isnan(in_data[i])) mask_out[i] = 1;
}
}
template<>
void flagNaN<uint8_t>(
const uint8_t *in_data __attribute__((unused)),
uint8_t *mask_out __attribute__((unused)),
size_t nsamps __attribute__((unused))
) { } // no-op
template<class T>
void NdvDef::arrayCheckNdv(
size_t band, const T *in_data,
uint8_t *mask_out, size_t nsamps
) const {
for(size_t i=0; i<nsamps; i++) mask_out[i] = 0;
for(size_t slab_idx=0; slab_idx<slabs.size(); slab_idx++) {
const NdvSlab &slab = slabs[slab_idx];
NdvInterval range;
if(band > 0 && slab.range_by_band.size() == 1) {
// if only a single range is defined, use it for all bands
range = slab.range_by_band[0];
} else if(band < slab.range_by_band.size()) {
range = slab.range_by_band[band];
} else {
fatal_error("wrong number of bands in NDV def");
}
flagMatches(range, in_data, mask_out, nsamps);
}
if(invert) {
for(size_t i=0; i<nsamps; i++) {
mask_out[i] = mask_out[i] ? 0 : 1;
}
}
//printf("XXX %d\n", mask_out[0]?1:0);
flagNaN(in_data, mask_out, nsamps);
}
void NdvDef::aggregateMask(
uint8_t *total_mask,
const uint8_t *band_mask,
size_t nsamps
) const {
if(invert) {
// pixel is valid only if all bands are within valid range
for(size_t i=0; i<nsamps; i++) {
if(band_mask[i]) total_mask[i] = 1;
}
} else {
// pixel is NDV only if all bands are NDV
for(size_t i=0; i<nsamps; i++) {
if(!band_mask[i]) total_mask[i] = 0;
}
}
}
template void NdvDef::arrayCheckNdv<uint8_t>(
size_t band, const uint8_t *in_data,
uint8_t *mask_out, size_t nsamps
) const;
template void NdvDef::arrayCheckNdv<double>(
size_t band, const double *in_data,
uint8_t *mask_out, size_t nsamps
) const;
} // namespace dangdal
<|endoftext|> |
<commit_before>/**
* pty.js
* Copyright (c) 2012, Christopher Jeffrey (MIT License)
*
* pty.cc:
* This file is responsible for starting processes
* with pseudo-terminal file descriptors.
*
* See:
* man pty
* man tty_ioctl
* man termios
* man forkpty
*/
#include <v8.h>
#include <node.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
/* forkpty */
/* http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html */
#if defined(__GLIBC__) || defined(__CYGWIN__)
#include <pty.h>
#elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__)
#include <util.h>
#elif defined(__FreeBSD__)
#include <libutil.h>
#elif defined(__sun)
#include <stropts.h> /* for I_PUSH */
#else
#include <pty.h>
#endif
#include <termios.h> /* tcgetattr, tty_ioctl */
/* environ for execvpe */
/* node/src/node_child_process.cc */
#if defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
extern char **environ;
#endif
/* for pty_getproc */
#if defined(__linux__)
#include <stdio.h>
#include <stdint.h>
#elif defined(__APPLE__)
#include <sys/sysctl.h>
#include <libproc.h>
#endif
using namespace std;
using namespace node;
using namespace v8;
static Handle<Value>
PtyFork(const Arguments&);
static Handle<Value>
PtyOpen(const Arguments&);
static Handle<Value>
PtyResize(const Arguments&);
static Handle<Value>
PtyGetProc(const Arguments&);
static int
pty_execvpe(const char *, char **, char **);
static int
pty_nonblock(int);
static char *
pty_getproc(int, char *);
static int
pty_openpty(int *, int *, char *,
const struct termios *,
const struct winsize *);
static pid_t
pty_forkpty(int *, char *,
const struct termios *,
const struct winsize *);
extern "C" void
init(Handle<Object>);
/**
* PtyFork
* pty.fork(file, args, env, cwd, cols, rows)
*/
static Handle<Value>
PtyFork(const Arguments& args) {
HandleScope scope;
if (args.Length() != 6
|| !args[0]->IsString()
|| !args[1]->IsArray()
|| !args[2]->IsArray()
|| !args[3]->IsString()
|| !args[4]->IsNumber()
|| !args[5]->IsNumber()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.fork(file, args, env, cwd, cols, rows)")));
}
// node/src/node_child_process.cc
// file
String::Utf8Value file(args[0]->ToString());
// args
int i = 0;
Local<Array> argv_ = Local<Array>::Cast(args[1]);
int argc = argv_->Length();
int argl = argc + 1 + 1;
char **argv = new char*[argl];
argv[0] = strdup(*file);
argv[argl-1] = NULL;
for (; i < argc; i++) {
String::Utf8Value arg(argv_->Get(Integer::New(i))->ToString());
argv[i+1] = strdup(*arg);
}
// env
i = 0;
Local<Array> env_ = Local<Array>::Cast(args[2]);
int envc = env_->Length();
char **env = new char*[envc+1];
env[envc] = NULL;
for (; i < envc; i++) {
String::Utf8Value pair(env_->Get(Integer::New(i))->ToString());
env[i] = strdup(*pair);
}
// cwd
String::Utf8Value cwd_(args[3]->ToString());
char *cwd = strdup(*cwd_);
// size
struct winsize winp;
winp.ws_col = args[4]->IntegerValue();
winp.ws_row = args[5]->IntegerValue();
winp.ws_xpixel = 0;
winp.ws_ypixel = 0;
// fork the pty
int master;
char name[40];
pid_t pid = pty_forkpty(&master, name, NULL, &winp);
if (pid) {
for (i = 0; i < argl; i++) free(argv[i]);
delete[] argv;
for (i = 0; i < envc; i++) free(env[i]);
delete[] env;
free(cwd);
}
switch (pid) {
case -1:
return ThrowException(Exception::Error(
String::New("forkpty(3) failed.")));
case 0:
if (strlen(cwd)) chdir(cwd);
pty_execvpe(argv[0], argv, env);
perror("execvp(3) failed.");
_exit(1);
default:
if (pty_nonblock(master) == -1) {
return ThrowException(Exception::Error(
String::New("Could not set master fd to nonblocking.")));
}
Local<Object> obj = Object::New();
obj->Set(String::New("fd"), Number::New(master));
obj->Set(String::New("pid"), Number::New(pid));
obj->Set(String::New("pty"), String::New(name));
return scope.Close(obj);
}
return Undefined();
}
/**
* PtyOpen
* pty.open(cols, rows)
*/
static Handle<Value>
PtyOpen(const Arguments& args) {
HandleScope scope;
if (args.Length() != 2
|| !args[0]->IsNumber()
|| !args[1]->IsNumber()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.open(cols, rows)")));
}
// size
struct winsize winp;
winp.ws_col = args[0]->IntegerValue();
winp.ws_row = args[1]->IntegerValue();
winp.ws_xpixel = 0;
winp.ws_ypixel = 0;
// pty
int master, slave;
char name[40];
int ret = pty_openpty(&master, &slave, name, NULL, &winp);
if (ret == -1) {
return ThrowException(Exception::Error(
String::New("openpty(3) failed.")));
}
if (pty_nonblock(master) == -1) {
return ThrowException(Exception::Error(
String::New("Could not set master fd to nonblocking.")));
}
if (pty_nonblock(slave) == -1) {
return ThrowException(Exception::Error(
String::New("Could not set slave fd to nonblocking.")));
}
Local<Object> obj = Object::New();
obj->Set(String::New("master"), Number::New(master));
obj->Set(String::New("slave"), Number::New(slave));
obj->Set(String::New("pty"), String::New(name));
return scope.Close(obj);
}
/**
* Resize Functionality
* pty.resize(fd, cols, rows)
*/
static Handle<Value>
PtyResize(const Arguments& args) {
HandleScope scope;
if (args.Length() != 3
|| !args[0]->IsNumber()
|| !args[1]->IsNumber()
|| !args[2]->IsNumber()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.resize(fd, cols, rows)")));
}
int fd = args[0]->IntegerValue();
struct winsize winp;
winp.ws_col = args[1]->IntegerValue();
winp.ws_row = args[2]->IntegerValue();
winp.ws_xpixel = 0;
winp.ws_ypixel = 0;
if (ioctl(fd, TIOCSWINSZ, &winp) == -1) {
return ThrowException(Exception::Error(
String::New("ioctl(2) failed.")));
}
return Undefined();
}
/**
* PtyGetProc
* Foreground Process Name
* pty.process(fd, tty)
*/
static Handle<Value>
PtyGetProc(const Arguments& args) {
HandleScope scope;
if (args.Length() != 2
|| !args[0]->IsNumber()
|| !args[1]->IsString()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.process(fd, tty)")));
}
int fd = args[0]->IntegerValue();
String::Utf8Value tty_(args[1]->ToString());
char *tty = strdup(*tty_);
char *name = pty_getproc(fd, tty);
free(tty);
if (name == NULL) {
return Undefined();
}
Local<String> name_ = String::New(name);
free(name);
return scope.Close(name_);
}
/**
* execvpe
*/
// execvpe(3) is not portable.
// http://www.gnu.org/software/gnulib/manual/html_node/execvpe.html
static int
pty_execvpe(const char *file, char **argv, char **envp) {
char **old = environ;
environ = envp;
int ret = execvp(file, argv);
environ = old;
return ret;
}
/**
* Nonblocking FD
*/
static int
pty_nonblock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return -1;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
/**
* pty_getproc
* Taken from tmux.
*/
// Taken from: tmux (http://tmux.sourceforge.net/)
// Copyright (c) 2009 Nicholas Marriott <[email protected]>
// Copyright (c) 2009 Joshua Elsasser <[email protected]>
// Copyright (c) 2009 Todd Carson <[email protected]>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#if defined(__linux__)
static char *
pty_getproc(int fd, char *tty) {
FILE *f;
char *path, *buf;
size_t len;
int ch;
pid_t pgrp;
int r;
if ((pgrp = tcgetpgrp(fd)) == -1) {
return NULL;
}
r = asprintf(&path, "/proc/%lld/cmdline", (long long)pgrp);
if (r == -1 || path == NULL) return NULL;
if ((f = fopen(path, "r")) == NULL) {
free(path);
return NULL;
}
free(path);
len = 0;
buf = NULL;
while ((ch = fgetc(f)) != EOF) {
if (ch == '\0') break;
buf = (char *)realloc(buf, len + 2);
if (buf == NULL) return NULL;
buf[len++] = ch;
}
if (buf != NULL) {
buf[len] = '\0';
}
fclose(f);
return buf;
}
#elif defined(__APPLE__)
static char *
pty_getproc(int fd, char *tty) {
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
size_t size;
struct kinfo_proc kp;
if ((mib[3] = tcgetpgrp(fd)) == -1) {
return NULL;
}
size = sizeof kp;
if (sysctl(mib, 4, &kp, &size, NULL, 0) == -1) {
return NULL;
}
if (*kp.kp_proc.p_comm == '\0') {
return NULL;
}
return strdup(kp.kp_proc.p_comm);
}
#else
static char *
pty_getproc(int fd, char *tty) {
return NULL;
}
#endif
/**
* openpty(3) / forkpty(3)
*/
static int
pty_openpty(int *amaster, int *aslave, char *name,
const struct termios *termp,
const struct winsize *winp) {
#if defined(__sun)
int master = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (master == -1) return -1;
if (amaster) *amaster = master;
if (grantpt(master) == -1) goto err;
if (unlockpt(master) == -1) goto err;
char *slave_name = ptsname(master);
if (slave_name == NULL) goto err;
if (name) strcpy(name, slave_name);
int slave = open(slave_name, O_RDWR | O_NOCTTY);
if (slave == -1) goto err;
if (aslave) *aslave = slave;
ioctl(slave, I_PUSH, "ptem");
ioctl(slave, I_PUSH, "ldterm");
ioctl(slave, I_PUSH, "ttcompat");
if (termp) tcsetattr(slave, TCSAFLUSH, termp);
if (winp) ioctl(slave, TIOCSWINSZ, winp);
return 0;
err:
close(master);
return -1;
#else
return openpty(amaster, aslave, name, (termios *)termp, (winsize *)winp);
#endif
}
static pid_t
pty_forkpty(int *amaster, char *name,
const struct termios *termp,
const struct winsize *winp) {
#if defined(__sun)
int master, slave;
int ret = pty_openpty(&master, &slave, name, termp, winp);
if (ret == -1) return -1;
if (amaster) *amaster = master;
pid_t pid = fork();
switch (pid) {
case -1:
close(master);
close(slave);
return -1;
case 0:
close(master);
setsid();
#if defined(TIOCSCTTY)
// glibc does this
if (ioctl(slave, TIOCSCTTY, NULL) == -1) _exit(1);
#endif
dup2(slave, 0);
dup2(slave, 1);
dup2(slave, 2);
if (slave > 2) close(slave);
return 0;
default:
close(slave);
return pid;
}
return -1;
#else
return forkpty(amaster, name, (termios *)termp, (winsize *)winp);
#endif
}
/**
* Init
*/
extern "C" void
init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "fork", PtyFork);
NODE_SET_METHOD(target, "open", PtyOpen);
NODE_SET_METHOD(target, "resize", PtyResize);
NODE_SET_METHOD(target, "process", PtyGetProc);
}
<commit_msg>fix an uninitialized variable compilation warning<commit_after>/**
* pty.js
* Copyright (c) 2012, Christopher Jeffrey (MIT License)
*
* pty.cc:
* This file is responsible for starting processes
* with pseudo-terminal file descriptors.
*
* See:
* man pty
* man tty_ioctl
* man termios
* man forkpty
*/
#include <v8.h>
#include <node.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
/* forkpty */
/* http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html */
#if defined(__GLIBC__) || defined(__CYGWIN__)
#include <pty.h>
#elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__)
#include <util.h>
#elif defined(__FreeBSD__)
#include <libutil.h>
#elif defined(__sun)
#include <stropts.h> /* for I_PUSH */
#else
#include <pty.h>
#endif
#include <termios.h> /* tcgetattr, tty_ioctl */
/* environ for execvpe */
/* node/src/node_child_process.cc */
#if defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
extern char **environ;
#endif
/* for pty_getproc */
#if defined(__linux__)
#include <stdio.h>
#include <stdint.h>
#elif defined(__APPLE__)
#include <sys/sysctl.h>
#include <libproc.h>
#endif
using namespace std;
using namespace node;
using namespace v8;
static Handle<Value>
PtyFork(const Arguments&);
static Handle<Value>
PtyOpen(const Arguments&);
static Handle<Value>
PtyResize(const Arguments&);
static Handle<Value>
PtyGetProc(const Arguments&);
static int
pty_execvpe(const char *, char **, char **);
static int
pty_nonblock(int);
static char *
pty_getproc(int, char *);
static int
pty_openpty(int *, int *, char *,
const struct termios *,
const struct winsize *);
static pid_t
pty_forkpty(int *, char *,
const struct termios *,
const struct winsize *);
extern "C" void
init(Handle<Object>);
/**
* PtyFork
* pty.fork(file, args, env, cwd, cols, rows)
*/
static Handle<Value>
PtyFork(const Arguments& args) {
HandleScope scope;
if (args.Length() != 6
|| !args[0]->IsString()
|| !args[1]->IsArray()
|| !args[2]->IsArray()
|| !args[3]->IsString()
|| !args[4]->IsNumber()
|| !args[5]->IsNumber()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.fork(file, args, env, cwd, cols, rows)")));
}
// node/src/node_child_process.cc
// file
String::Utf8Value file(args[0]->ToString());
// args
int i = 0;
Local<Array> argv_ = Local<Array>::Cast(args[1]);
int argc = argv_->Length();
int argl = argc + 1 + 1;
char **argv = new char*[argl];
argv[0] = strdup(*file);
argv[argl-1] = NULL;
for (; i < argc; i++) {
String::Utf8Value arg(argv_->Get(Integer::New(i))->ToString());
argv[i+1] = strdup(*arg);
}
// env
i = 0;
Local<Array> env_ = Local<Array>::Cast(args[2]);
int envc = env_->Length();
char **env = new char*[envc+1];
env[envc] = NULL;
for (; i < envc; i++) {
String::Utf8Value pair(env_->Get(Integer::New(i))->ToString());
env[i] = strdup(*pair);
}
// cwd
String::Utf8Value cwd_(args[3]->ToString());
char *cwd = strdup(*cwd_);
// size
struct winsize winp;
winp.ws_col = args[4]->IntegerValue();
winp.ws_row = args[5]->IntegerValue();
winp.ws_xpixel = 0;
winp.ws_ypixel = 0;
// fork the pty
int master = -1;
char name[40];
pid_t pid = pty_forkpty(&master, name, NULL, &winp);
if (pid) {
for (i = 0; i < argl; i++) free(argv[i]);
delete[] argv;
for (i = 0; i < envc; i++) free(env[i]);
delete[] env;
free(cwd);
}
switch (pid) {
case -1:
return ThrowException(Exception::Error(
String::New("forkpty(3) failed.")));
case 0:
if (strlen(cwd)) chdir(cwd);
pty_execvpe(argv[0], argv, env);
perror("execvp(3) failed.");
_exit(1);
default:
if (pty_nonblock(master) == -1) {
return ThrowException(Exception::Error(
String::New("Could not set master fd to nonblocking.")));
}
Local<Object> obj = Object::New();
obj->Set(String::New("fd"), Number::New(master));
obj->Set(String::New("pid"), Number::New(pid));
obj->Set(String::New("pty"), String::New(name));
return scope.Close(obj);
}
return Undefined();
}
/**
* PtyOpen
* pty.open(cols, rows)
*/
static Handle<Value>
PtyOpen(const Arguments& args) {
HandleScope scope;
if (args.Length() != 2
|| !args[0]->IsNumber()
|| !args[1]->IsNumber()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.open(cols, rows)")));
}
// size
struct winsize winp;
winp.ws_col = args[0]->IntegerValue();
winp.ws_row = args[1]->IntegerValue();
winp.ws_xpixel = 0;
winp.ws_ypixel = 0;
// pty
int master, slave;
char name[40];
int ret = pty_openpty(&master, &slave, name, NULL, &winp);
if (ret == -1) {
return ThrowException(Exception::Error(
String::New("openpty(3) failed.")));
}
if (pty_nonblock(master) == -1) {
return ThrowException(Exception::Error(
String::New("Could not set master fd to nonblocking.")));
}
if (pty_nonblock(slave) == -1) {
return ThrowException(Exception::Error(
String::New("Could not set slave fd to nonblocking.")));
}
Local<Object> obj = Object::New();
obj->Set(String::New("master"), Number::New(master));
obj->Set(String::New("slave"), Number::New(slave));
obj->Set(String::New("pty"), String::New(name));
return scope.Close(obj);
}
/**
* Resize Functionality
* pty.resize(fd, cols, rows)
*/
static Handle<Value>
PtyResize(const Arguments& args) {
HandleScope scope;
if (args.Length() != 3
|| !args[0]->IsNumber()
|| !args[1]->IsNumber()
|| !args[2]->IsNumber()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.resize(fd, cols, rows)")));
}
int fd = args[0]->IntegerValue();
struct winsize winp;
winp.ws_col = args[1]->IntegerValue();
winp.ws_row = args[2]->IntegerValue();
winp.ws_xpixel = 0;
winp.ws_ypixel = 0;
if (ioctl(fd, TIOCSWINSZ, &winp) == -1) {
return ThrowException(Exception::Error(
String::New("ioctl(2) failed.")));
}
return Undefined();
}
/**
* PtyGetProc
* Foreground Process Name
* pty.process(fd, tty)
*/
static Handle<Value>
PtyGetProc(const Arguments& args) {
HandleScope scope;
if (args.Length() != 2
|| !args[0]->IsNumber()
|| !args[1]->IsString()) {
return ThrowException(Exception::Error(
String::New("Usage: pty.process(fd, tty)")));
}
int fd = args[0]->IntegerValue();
String::Utf8Value tty_(args[1]->ToString());
char *tty = strdup(*tty_);
char *name = pty_getproc(fd, tty);
free(tty);
if (name == NULL) {
return Undefined();
}
Local<String> name_ = String::New(name);
free(name);
return scope.Close(name_);
}
/**
* execvpe
*/
// execvpe(3) is not portable.
// http://www.gnu.org/software/gnulib/manual/html_node/execvpe.html
static int
pty_execvpe(const char *file, char **argv, char **envp) {
char **old = environ;
environ = envp;
int ret = execvp(file, argv);
environ = old;
return ret;
}
/**
* Nonblocking FD
*/
static int
pty_nonblock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return -1;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
/**
* pty_getproc
* Taken from tmux.
*/
// Taken from: tmux (http://tmux.sourceforge.net/)
// Copyright (c) 2009 Nicholas Marriott <[email protected]>
// Copyright (c) 2009 Joshua Elsasser <[email protected]>
// Copyright (c) 2009 Todd Carson <[email protected]>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#if defined(__linux__)
static char *
pty_getproc(int fd, char *tty) {
FILE *f;
char *path, *buf;
size_t len;
int ch;
pid_t pgrp;
int r;
if ((pgrp = tcgetpgrp(fd)) == -1) {
return NULL;
}
r = asprintf(&path, "/proc/%lld/cmdline", (long long)pgrp);
if (r == -1 || path == NULL) return NULL;
if ((f = fopen(path, "r")) == NULL) {
free(path);
return NULL;
}
free(path);
len = 0;
buf = NULL;
while ((ch = fgetc(f)) != EOF) {
if (ch == '\0') break;
buf = (char *)realloc(buf, len + 2);
if (buf == NULL) return NULL;
buf[len++] = ch;
}
if (buf != NULL) {
buf[len] = '\0';
}
fclose(f);
return buf;
}
#elif defined(__APPLE__)
static char *
pty_getproc(int fd, char *tty) {
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
size_t size;
struct kinfo_proc kp;
if ((mib[3] = tcgetpgrp(fd)) == -1) {
return NULL;
}
size = sizeof kp;
if (sysctl(mib, 4, &kp, &size, NULL, 0) == -1) {
return NULL;
}
if (*kp.kp_proc.p_comm == '\0') {
return NULL;
}
return strdup(kp.kp_proc.p_comm);
}
#else
static char *
pty_getproc(int fd, char *tty) {
return NULL;
}
#endif
/**
* openpty(3) / forkpty(3)
*/
static int
pty_openpty(int *amaster, int *aslave, char *name,
const struct termios *termp,
const struct winsize *winp) {
#if defined(__sun)
int master = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (master == -1) return -1;
if (amaster) *amaster = master;
if (grantpt(master) == -1) goto err;
if (unlockpt(master) == -1) goto err;
char *slave_name = ptsname(master);
if (slave_name == NULL) goto err;
if (name) strcpy(name, slave_name);
int slave = open(slave_name, O_RDWR | O_NOCTTY);
if (slave == -1) goto err;
if (aslave) *aslave = slave;
ioctl(slave, I_PUSH, "ptem");
ioctl(slave, I_PUSH, "ldterm");
ioctl(slave, I_PUSH, "ttcompat");
if (termp) tcsetattr(slave, TCSAFLUSH, termp);
if (winp) ioctl(slave, TIOCSWINSZ, winp);
return 0;
err:
close(master);
return -1;
#else
return openpty(amaster, aslave, name, (termios *)termp, (winsize *)winp);
#endif
}
static pid_t
pty_forkpty(int *amaster, char *name,
const struct termios *termp,
const struct winsize *winp) {
#if defined(__sun)
int master, slave;
int ret = pty_openpty(&master, &slave, name, termp, winp);
if (ret == -1) return -1;
if (amaster) *amaster = master;
pid_t pid = fork();
switch (pid) {
case -1:
close(master);
close(slave);
return -1;
case 0:
close(master);
setsid();
#if defined(TIOCSCTTY)
// glibc does this
if (ioctl(slave, TIOCSCTTY, NULL) == -1) _exit(1);
#endif
dup2(slave, 0);
dup2(slave, 1);
dup2(slave, 2);
if (slave > 2) close(slave);
return 0;
default:
close(slave);
return pid;
}
return -1;
#else
return forkpty(amaster, name, (termios *)termp, (winsize *)winp);
#endif
}
/**
* Init
*/
extern "C" void
init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "fork", PtyFork);
NODE_SET_METHOD(target, "open", PtyOpen);
NODE_SET_METHOD(target, "resize", PtyResize);
NODE_SET_METHOD(target, "process", PtyGetProc);
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include <time.h>
#include <vector>
#include "base/gfx/convolver.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gfx {
namespace {
// Fills the given filter with impulse functions for the range 0->num_entries.
void FillImpulseFilter(int num_entries, ConvolusionFilter1D* filter) {
float one = 1.0f;
for (int i = 0; i < num_entries; i++)
filter->AddFilter(i, &one, 1);
}
// Filters the given input with the impulse function, and verifies that it
// does not change.
void TestImpulseConvolusion(const unsigned char* data, int width, int height) {
int byte_count = width * height * 4;
ConvolusionFilter1D filter_x;
FillImpulseFilter(width, &filter_x);
ConvolusionFilter1D filter_y;
FillImpulseFilter(height, &filter_y);
std::vector<unsigned char> output;
output.resize(byte_count);
BGRAConvolve2D(data, width * 4, true, filter_x, filter_y, &output[0]);
// Output should exactly match input.
EXPECT_EQ(0, memcmp(data, &output[0], byte_count));
}
// Fills the destination filter with a box filter averaging every two pixels
// to produce the output.
void FillBoxFilter(int size, ConvolusionFilter1D* filter) {
const float box[2] = { 0.5, 0.5 };
for (int i = 0; i < size; i++)
filter->AddFilter(i * 2, box, 2);
}
} // namespace
// Tests that each pixel, when set and run through the impulse filter, does
// not change.
TEST(Convolver, Impulse) {
// We pick an "odd" size that is not likely to fit on any boundaries so that
// we can see if all the widths and paddings are handled properly.
int width = 15;
int height = 31;
int byte_count = width * height * 4;
std::vector<unsigned char> input;
input.resize(byte_count);
unsigned char* input_ptr = &input[0];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
for (int channel = 0; channel < 3; channel++) {
memset(input_ptr, 0, byte_count);
input_ptr[(y * width + x) * 4 + channel] = 0xff;
// Always set the alpha channel or it will attempt to "fix" it for us.
input_ptr[(y * width + x) * 4 + 3] = 0xff;
TestImpulseConvolusion(input_ptr, width, height);
}
}
}
}
// Tests that using a box filter to halve an image results in every square of 4
// pixels in the original get averaged to a pixel in the output.
TEST(Convolver, Halve) {
static const int kSize = 16;
int src_width = kSize;
int src_height = kSize;
int src_row_stride = src_width * 4;
int src_byte_count = src_row_stride * src_height;
std::vector<unsigned char> input;
input.resize(src_byte_count);
int dest_width = src_width / 2;
int dest_height = src_height / 2;
int dest_byte_count = dest_width * dest_height * 4;
std::vector<unsigned char> output;
output.resize(dest_byte_count);
// First fill the array with a bunch of random data.
srand(static_cast<unsigned>(time(NULL)));
for (int i = 0; i < src_byte_count; i++)
input[i] = rand() * 255 / RAND_MAX;
// Compute the filters.
ConvolusionFilter1D filter_x, filter_y;
FillBoxFilter(dest_width, &filter_x);
FillBoxFilter(dest_height, &filter_y);
// Do the convolusion.
BGRAConvolve2D(&input[0], src_width, true, filter_x, filter_y, &output[0]);
// Compute the expected results and check, allowing for a small difference
// to account for rounding errors.
for (int y = 0; y < dest_height; y++) {
for (int x = 0; x < dest_width; x++) {
for (int channel = 0; channel < 4; channel++) {
int src_offset = (y * 2 * src_row_stride + x * 2 * 4) + channel;
int value = input[src_offset] + // Top left source pixel.
input[src_offset + 4] + // Top right source pixel.
input[src_offset + src_row_stride] + // Lower left.
input[src_offset + src_row_stride + 4]; // Lower right.
value /= 4; // Average.
int difference = value - output[(y * dest_width + x) * 4 + channel];
EXPECT_TRUE(difference >= -1 || difference <= 1);
}
}
}
}
} // namespace gfx<commit_msg>Add a EOL to the end of convolver_unittest.cc. This eliminates a GCC warning.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include <time.h>
#include <vector>
#include "base/gfx/convolver.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gfx {
namespace {
// Fills the given filter with impulse functions for the range 0->num_entries.
void FillImpulseFilter(int num_entries, ConvolusionFilter1D* filter) {
float one = 1.0f;
for (int i = 0; i < num_entries; i++)
filter->AddFilter(i, &one, 1);
}
// Filters the given input with the impulse function, and verifies that it
// does not change.
void TestImpulseConvolusion(const unsigned char* data, int width, int height) {
int byte_count = width * height * 4;
ConvolusionFilter1D filter_x;
FillImpulseFilter(width, &filter_x);
ConvolusionFilter1D filter_y;
FillImpulseFilter(height, &filter_y);
std::vector<unsigned char> output;
output.resize(byte_count);
BGRAConvolve2D(data, width * 4, true, filter_x, filter_y, &output[0]);
// Output should exactly match input.
EXPECT_EQ(0, memcmp(data, &output[0], byte_count));
}
// Fills the destination filter with a box filter averaging every two pixels
// to produce the output.
void FillBoxFilter(int size, ConvolusionFilter1D* filter) {
const float box[2] = { 0.5, 0.5 };
for (int i = 0; i < size; i++)
filter->AddFilter(i * 2, box, 2);
}
} // namespace
// Tests that each pixel, when set and run through the impulse filter, does
// not change.
TEST(Convolver, Impulse) {
// We pick an "odd" size that is not likely to fit on any boundaries so that
// we can see if all the widths and paddings are handled properly.
int width = 15;
int height = 31;
int byte_count = width * height * 4;
std::vector<unsigned char> input;
input.resize(byte_count);
unsigned char* input_ptr = &input[0];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
for (int channel = 0; channel < 3; channel++) {
memset(input_ptr, 0, byte_count);
input_ptr[(y * width + x) * 4 + channel] = 0xff;
// Always set the alpha channel or it will attempt to "fix" it for us.
input_ptr[(y * width + x) * 4 + 3] = 0xff;
TestImpulseConvolusion(input_ptr, width, height);
}
}
}
}
// Tests that using a box filter to halve an image results in every square of 4
// pixels in the original get averaged to a pixel in the output.
TEST(Convolver, Halve) {
static const int kSize = 16;
int src_width = kSize;
int src_height = kSize;
int src_row_stride = src_width * 4;
int src_byte_count = src_row_stride * src_height;
std::vector<unsigned char> input;
input.resize(src_byte_count);
int dest_width = src_width / 2;
int dest_height = src_height / 2;
int dest_byte_count = dest_width * dest_height * 4;
std::vector<unsigned char> output;
output.resize(dest_byte_count);
// First fill the array with a bunch of random data.
srand(static_cast<unsigned>(time(NULL)));
for (int i = 0; i < src_byte_count; i++)
input[i] = rand() * 255 / RAND_MAX;
// Compute the filters.
ConvolusionFilter1D filter_x, filter_y;
FillBoxFilter(dest_width, &filter_x);
FillBoxFilter(dest_height, &filter_y);
// Do the convolusion.
BGRAConvolve2D(&input[0], src_width, true, filter_x, filter_y, &output[0]);
// Compute the expected results and check, allowing for a small difference
// to account for rounding errors.
for (int y = 0; y < dest_height; y++) {
for (int x = 0; x < dest_width; x++) {
for (int channel = 0; channel < 4; channel++) {
int src_offset = (y * 2 * src_row_stride + x * 2 * 4) + channel;
int value = input[src_offset] + // Top left source pixel.
input[src_offset + 4] + // Top right source pixel.
input[src_offset + src_row_stride] + // Lower left.
input[src_offset + src_row_stride + 4]; // Lower right.
value /= 4; // Average.
int difference = value - output[(y * dest_width + x) * 4 + channel];
EXPECT_TRUE(difference >= -1 || difference <= 1);
}
}
}
}
} // namespace gfx
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/i18n/number_formatting.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "unicode/numfmt.h"
#include "unicode/ustring.h"
namespace base {
namespace {
struct NumberFormatWrapper {
NumberFormatWrapper() {
Reset();
}
void Reset() {
// There's no ICU call to destroy a NumberFormat object other than
// operator delete, so use the default Delete, which calls operator delete.
// This can cause problems if a different allocator is used by this file
// than by ICU.
UErrorCode status = U_ZERO_ERROR;
number_format.reset(icu::NumberFormat::createInstance(status));
DCHECK(U_SUCCESS(status));
}
scoped_ptr<icu::NumberFormat> number_format;
};
LazyInstance<NumberFormatWrapper> g_number_format_int =
LAZY_INSTANCE_INITIALIZER;
LazyInstance<NumberFormatWrapper> g_number_format_float =
LAZY_INSTANCE_INITIALIZER;
} // namespace
string16 FormatNumber(int64 number) {
icu::NumberFormat* number_format =
g_number_format_int.Get().number_format.get();
if (!number_format) {
// As a fallback, just return the raw number in a string.
return UTF8ToUTF16(StringPrintf("%" PRId64, number));
}
icu::UnicodeString ustr;
number_format->format(number, ustr);
return string16(ustr.getBuffer(), static_cast<size_t>(ustr.length()));
}
string16 FormatDouble(double number, int fractional_digits) {
icu::NumberFormat* number_format =
g_number_format_float.Get().number_format.get();
if (!number_format) {
// As a fallback, just return the raw number in a string.
return UTF8ToUTF16(StringPrintf("%f", number));
}
number_format->setMaximumFractionDigits(fractional_digits);
number_format->setMinimumFractionDigits(fractional_digits);
icu::UnicodeString ustr;
number_format->format(number, ustr);
return string16(ustr.getBuffer(), static_cast<size_t>(ustr.length()));
}
namespace testing {
void ResetFormatters() {
g_number_format_int.Get().Reset();
g_number_format_float.Get().Reset();
}
} // namespace testing
} // namespace base
<commit_msg>Add comment to NumberFormatWrapper.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/i18n/number_formatting.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "unicode/numfmt.h"
#include "unicode/ustring.h"
namespace base {
namespace {
// A simple wrapper around icu::NumberFormat that allows for resetting it
// (as LazyInstance does not).
struct NumberFormatWrapper {
NumberFormatWrapper() {
Reset();
}
void Reset() {
// There's no ICU call to destroy a NumberFormat object other than
// operator delete, so use the default Delete, which calls operator delete.
// This can cause problems if a different allocator is used by this file
// than by ICU.
UErrorCode status = U_ZERO_ERROR;
number_format.reset(icu::NumberFormat::createInstance(status));
DCHECK(U_SUCCESS(status));
}
scoped_ptr<icu::NumberFormat> number_format;
};
LazyInstance<NumberFormatWrapper> g_number_format_int =
LAZY_INSTANCE_INITIALIZER;
LazyInstance<NumberFormatWrapper> g_number_format_float =
LAZY_INSTANCE_INITIALIZER;
} // namespace
string16 FormatNumber(int64 number) {
icu::NumberFormat* number_format =
g_number_format_int.Get().number_format.get();
if (!number_format) {
// As a fallback, just return the raw number in a string.
return UTF8ToUTF16(StringPrintf("%" PRId64, number));
}
icu::UnicodeString ustr;
number_format->format(number, ustr);
return string16(ustr.getBuffer(), static_cast<size_t>(ustr.length()));
}
string16 FormatDouble(double number, int fractional_digits) {
icu::NumberFormat* number_format =
g_number_format_float.Get().number_format.get();
if (!number_format) {
// As a fallback, just return the raw number in a string.
return UTF8ToUTF16(StringPrintf("%f", number));
}
number_format->setMaximumFractionDigits(fractional_digits);
number_format->setMinimumFractionDigits(fractional_digits);
icu::UnicodeString ustr;
number_format->format(number, ustr);
return string16(ustr.getBuffer(), static_cast<size_t>(ustr.length()));
}
namespace testing {
void ResetFormatters() {
g_number_format_int.Get().Reset();
g_number_format_float.Get().Reset();
}
} // namespace testing
} // namespace base
<|endoftext|> |
<commit_before><commit_msg>moved main comment block to top<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
* thrill/common/stat_logger.hpp
*
* Logger for Stat-Lines, which creates basic JSON lines
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Alexander Noe <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_COMMON_STAT_LOGGER_HEADER
#define THRILL_COMMON_STAT_LOGGER_HEADER
#include <thrill/common/logger.hpp>
#include <iostream>
#include <string>
#include <type_traits>
namespace thrill {
namespace common {
static const bool stats_enabled = false;
template <bool Enabled>
class StatLogger
{ };
template <>
class StatLogger<true>
{
private:
//! collector stream
std::basic_ostringstream<
char, std::char_traits<char>, LoggerAllocator<char> > oss_;
size_t elements_ = 0;
public:
StatLogger() {
oss_ << "{";
}
//! output and escape std::string
StatLogger& operator << (const std::string& str) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
oss_ << "\"";
// from: http://stackoverflow.com/a/7725289
for (auto iter = str.begin(); iter != str.end(); iter++) {
switch (*iter) {
case '\\': oss_ << "\\\\";
break;
case '"': oss_ << "\\\"";
break;
case '/': oss_ << "\\/";
break;
case '\b': oss_ << "\\b";
break;
case '\f': oss_ << "\\f";
break;
case '\n': oss_ << "\\n";
break;
case '\r': oss_ << "\\r";
break;
case '\t': oss_ << "\\t";
break;
default: oss_ << *iter;
break;
}
}
elements_++;
oss_ << "\"";
return *this;
}
//! output any type, including io manipulators
template <typename AnyType>
StatLogger& operator << (const AnyType& at) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
elements_++;
if (std::is_integral<AnyType>::value || std::is_floating_point<AnyType>::value) {
oss_ << at;
}
else if (std::is_same<AnyType, bool>::value) {
if (at) {
oss_ << "true";
}
else {
oss_ << "false";
}
}
else {
oss_ << "\"" << at << "\"";
}
return *this;
}
//! destructor: output a } and a newline
~StatLogger() {
assert(elements_ % 2 == 0);
oss_ << "}\n";
std::cout << oss_.str();
}
};
template <>
class StatLogger<false>
{
public:
template <typename AnyType>
StatLogger& operator << (const AnyType&) {
return *this;
}
};
#define STAT_NO_RANK ::thrill::common::StatLogger<::thrill::common::stats_enabled>()
//! Creates a common::StatLogger with {"WorkerID":my rank in the beginning
#define STAT(ctx) ::thrill::common::StatLogger<::thrill::common::stats_enabled>() << "worker_id" << ctx.my_rank()
#define STATC ::thrill::common::StatLogger<::thrill::common::stats_enabled>() << "worker_id" << context_.my_rank()
#define STATC1 ::thrill::common::StatLogger<true>() << "worker_id" << context_.my_rank()
} // namespace common
} // namespace thrill
#endif // !THRILL_COMMON_STAT_LOGGER_HEADER
/******************************************************************************/
<commit_msg>stat_logger creates logfiles per worker<commit_after>/*******************************************************************************
* thrill/common/stat_logger.hpp
*
* Logger for Stat-Lines, which creates basic JSON lines
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Alexander Noe <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_COMMON_STAT_LOGGER_HEADER
#define THRILL_COMMON_STAT_LOGGER_HEADER
#include <thrill/common/logger.hpp>
#include <iostream>
#include <string>
#include <type_traits>
namespace thrill {
namespace common {
static const bool stats_enabled = false;
template <bool Enabled>
class StatLogger
{ };
template <>
class StatLogger<true>
{
private:
//! collector stream
std::basic_ostringstream<
char, std::char_traits<char>, LoggerAllocator<char> > oss_;
size_t elements_ = 0;
size_t my_rank_ = 0;
public:
StatLogger(size_t rank) :
my_rank_(rank) {
oss_ << "{";
}
//! output and escape std::string
StatLogger& operator << (const std::string& str) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
oss_ << "\"";
// from: http://stackoverflow.com/a/7725289
for (auto iter = str.begin(); iter != str.end(); iter++) {
switch (*iter) {
case '\\': oss_ << "\\\\";
break;
case '"': oss_ << "\\\"";
break;
case '/': oss_ << "\\/";
break;
case '\b': oss_ << "\\b";
break;
case '\f': oss_ << "\\f";
break;
case '\n': oss_ << "\\n";
break;
case '\r': oss_ << "\\r";
break;
case '\t': oss_ << "\\t";
break;
default: oss_ << *iter;
break;
}
}
elements_++;
oss_ << "\"";
return *this;
}
//! output any type, including io manipulators
template <typename AnyType>
StatLogger& operator << (const AnyType& at) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
elements_++;
if (std::is_integral<AnyType>::value || std::is_floating_point<AnyType>::value) {
oss_ << at;
}
else if (std::is_same<AnyType, bool>::value) {
if (at) {
oss_ << "true";
}
else {
oss_ << "false";
}
}
else {
oss_ << "\"" << at << "\"";
}
return *this;
}
//! destructor: output a } and a newline
~StatLogger() {
assert(elements_ % 2 == 0);
oss_ << "}\n";
std::ofstream logfile(
"logfile" + std::to_string(my_rank_) + ".txt", std::ios_base::out | std::ios_base::app );
logfile << oss_.str() << std::endl;
logfile.close();
}
};
template <>
class StatLogger<false>
{
public:
StatLogger(size_t) { }
template <typename AnyType>
StatLogger& operator << (const AnyType&) {
return *this;
}
};
#define STAT_NO_RANK ::thrill::common::StatLogger<::thrill::common::stats_enabled>(0u)
//! Creates a common::StatLogger with {"WorkerID":my rank in the beginning
#define STAT(ctx) ::thrill::common::StatLogger<::thrill::common::stats_enabled>(ctx.my_rank()) << "worker_id" << ctx.my_rank()
#define STATC ::thrill::common::StatLogger<::thrill::common::stats_enabled>(context_.my_rank()) << "worker_id" << context_.my_rank()
#define STATC1 ::thrill::common::StatLogger<true>(context_.my_rank()) << "worker_id" << context_.my_rank()
} // namespace common
} // namespace thrill
#endif // !THRILL_COMMON_STAT_LOGGER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>
int main()
{
}<commit_msg>started filling in movies<commit_after>// File: Source.cpp
// Purpose: Main driver file for this project.
// Project: ANN_MovieRatings
// Author: Ryan Amaral
// Created On: March 26, 2016
#include "Movie.h"
using namespace std;
int trainingMoviesLength = 16; // amount of movies
Movie** trainingMovies = new Movie*[trainingMoviesLength];
int testingMoviesLength = 5; // amount of movies
Movie** testingMovies = new Movie*[testingMoviesLength];
void CreateMovies()
{
// some are my actual ratings, but I am making sci-fi all highly rated to make it easier for network
trainingMovies[0] = new Movie(
"Star Wars: Episode IV - A New Hope",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.6, 0.1, 0.8, 0.0, 0.1, 0.3, 0.7, 0.8, 0.3, 0.1, 0.4, 0.0, 0.1, 1.0, 0.0, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, false, 1.0);
trainingMovies[1] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.25, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[2] = new Movie(
"Back to the Future",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.5, 0.4, 0.6, 0.1, 0.0, 0.8, 0.0, 0.6, 0.2, 0.1, 0.0, 0.8, 0.1, 0.9, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, false, 1.0);
trainingMovies[3] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.2, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[4] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.2, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[5] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[6] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[7] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[8] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[9] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[10] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[11] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[12] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[13] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[14] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
trainingMovies[15] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
// test on these ones
testingMovies[0] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
testingMovies[1] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
testingMovies[2] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
testingMovies[3] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
testingMovies[4] = new Movie(
"Spaceballs",
//ac cm fm nr hr rm wr ad cr dr ft hs ms sc th ws
0.7, 0.9, 0.5, 0.0, 0.0, 0.4, 0.5, 0.7, 0.6, 0.1, 0.0, 0.0, 0.1, 1.0, 0.1, 0.0,
//crt anime anim music sport bio doc parod rating
false, false, false, false, false, false, false, true, 1.0);
}
int main()
{
// ask for basic or not
// ask for topology of hidden layers
// ask for generations
// ask for organisms per generation
// ask for mutation probability
// ask for learning rate
}<|endoftext|> |
<commit_before>#define NONIUS_RUNNER
#include <nonius/main.h++>
#include "../include/dict/dict.hpp"
#include <unordered_map>
#include <random>
#include <functional>
#ifdef WITH_GOOGLE_BENCH
#include <sparsehash/dense_hash_map>
#endif
template <typename Map>
void insert_test(Map& map) {
for (int i = 0; i != 10000; ++i) {
map[i] = i;
}
}
NONIUS_BENCHMARK("dict insert", [](nonius::chronometer meter) {
boost::dict<int, int> d;
d.reserve(1000);
meter.measure([&] { insert_test(d); });
})
NONIUS_BENCHMARK("umap insert", [](nonius::chronometer meter) {
std::unordered_map<int, int> d;
d.reserve(1000);
meter.measure([&] { insert_test(d); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google insert", [](nonius::chronometer meter) {
google::dense_hash_map<int, int> d(1000);
d.set_empty_key(0);
meter.measure([&] { insert_test(d); });
})
#endif
#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_map_google(int size) {
Map d;
d.set_empty_key(0);
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
template <typename Map>
Map build_map_google_with_reserve(int size) {
Map d(size);
d.set_empty_key(0);
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
#endif
template <typename Map>
Map build_map(int size) {
Map d;
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
template <typename Map>
Map build_map_with_reserve(int size) {
Map d(size);
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
template <typename Map, typename Generator>
int lookup_test(Map& map, Generator& gen) {
int res = 0;
for (std::size_t i = 0; i < 100; i += 1) {
res += map[gen()];
}
return res;
}
const int lookup_test_size = 1000000;
NONIUS_BENCHMARK("dict lookup", [](nonius::chronometer meter) {
auto d = build_map<boost::dict<int, int>>(lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
NONIUS_BENCHMARK("umap lookup", [](nonius::chronometer meter) {
auto d = build_map<std::unordered_map<int, int>>(lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google lookup", [](nonius::chronometer meter) {
auto d =
build_map_google<google::dense_hash_map<int, int>>(lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif
const int build_test_size = 1000;
NONIUS_BENCHMARK("dict build", [] {
return build_map<boost::dict<int, int>>(build_test_size);
})
NONIUS_BENCHMARK("umap build", [] {
return build_map<std::unordered_map<int, int>>(build_test_size);
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build", [] {
return build_map_google<google::dense_hash_map<int, int>>(build_test_size);
})
#endif
NONIUS_BENCHMARK("dict build with reserve", [] {
return build_map_with_reserve<boost::dict<int, int>>(build_test_size);
})
NONIUS_BENCHMARK("umap build with reserve", [] {
return build_map_with_reserve<std::unordered_map<int, int>>(
build_test_size);
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with reserve", [] {
return build_map_google<google::dense_hash_map<int, int>>(build_test_size);
})
#endif
template <typename Map>
Map build_string_map(int size) {
Map d;
for (int i = 0; i != size; ++i) {
d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i)] = i;
}
return d;
}
#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_string_map_google(int size) {
Map d;
d.set_empty_key("");
for (int i = 0; i != size; ++i) {
d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i)] = i;
}
return d;
}
#endif
NONIUS_BENCHMARK("dict build with string key", [] {
return build_string_map<boost::dict<std::string, int>>(build_test_size);
})
NONIUS_BENCHMARK("umap build with string key", [] {
return build_string_map<std::unordered_map<std::string, int>>(
build_test_size);
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with string key", [] {
return build_string_map_google<google::dense_hash_map<std::string, int>>(
build_test_size);
})
#endif
template <typename Map, typename LookUpKeys>
int string_lookup_test(Map& map, const LookUpKeys& keys) {
int res = 0;
for (auto&& k : keys) {
res += map[k];
}
return res;
}
const int string_lookup_test_size = 1000;
NONIUS_BENCHMARK("dict string lookup", [](nonius::chronometer meter) {
auto d = build_string_map<boost::dict<std::string, int>>(
string_lookup_test_size);
std::vector<std::string> keys{ "1111111", "2222222", "3333333",
"4444444", "5555555", "6666666",
"7777777", "8888888", "9999999" };
meter.measure([&] { return string_lookup_test(d, keys); });
})
NONIUS_BENCHMARK("umap string lookup", [](nonius::chronometer meter) {
auto d = build_string_map<std::unordered_map<std::string, int>>(
string_lookup_test_size);
std::vector<std::string> keys{ "1111111", "2222222", "3333333",
"4444444", "5555555", "6666666",
"7777777", "8888888", "9999999" };
meter.measure([&] { return string_lookup_test(d, keys); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google string lookup", [](nonius::chronometer meter) {
auto d = build_string_map_google<google::dense_hash_map<std::string, int>>(
string_lookup_test_size);
std::vector<std::string> keys{ "1111111", "2222222", "3333333",
"4444444", "5555555", "6666666",
"7777777", "8888888", "9999999" };
meter.measure([&] { return string_lookup_test(d, keys); });
})
#endif
<commit_msg>added small dict look up test<commit_after>#define NONIUS_RUNNER
#include <nonius/main.h++>
#include "../include/dict/dict.hpp"
#include <unordered_map>
#include <random>
#include <functional>
#ifdef WITH_GOOGLE_BENCH
#include <sparsehash/dense_hash_map>
#endif
template <typename Map>
void insert_test(Map& map) {
for (int i = 0; i != 10000; ++i) {
map[i] = i;
}
}
NONIUS_BENCHMARK("dict insert", [](nonius::chronometer meter) {
boost::dict<int, int> d;
d.reserve(1000);
meter.measure([&] { insert_test(d); });
})
NONIUS_BENCHMARK("umap insert", [](nonius::chronometer meter) {
std::unordered_map<int, int> d;
d.reserve(1000);
meter.measure([&] { insert_test(d); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google insert", [](nonius::chronometer meter) {
google::dense_hash_map<int, int> d(1000);
d.set_empty_key(0);
meter.measure([&] { insert_test(d); });
})
#endif
#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_map_google(int size) {
Map d;
d.set_empty_key(0);
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
template <typename Map>
Map build_map_google_with_reserve(int size) {
Map d(size);
d.set_empty_key(0);
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
#endif
template <typename Map>
Map build_map(int size) {
Map d;
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
template <typename Map>
Map build_map_with_reserve(int size) {
Map d(size);
for (int i = 0; i != size; ++i) {
d[i] = i;
}
return d;
}
template <typename Map, typename Generator>
int lookup_test(Map& map, Generator& gen) {
int res = 0;
for (std::size_t i = 0; i < 100; i += 1) {
res += map[gen()];
}
return res;
}
const int small_lookup_test_size = 10;
NONIUS_BENCHMARK("small dict lookup", [](nonius::chronometer meter) {
auto d = build_map<boost::dict<int, int>>(small_lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
NONIUS_BENCHMARK("small umap lookup", [](nonius::chronometer meter) {
auto d = build_map<std::unordered_map<int, int>>(small_lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("small google lookup", [](nonius::chronometer meter) {
auto d =
build_map_google<google::dense_hash_map<int, int>>(small_lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif
const int lookup_test_size = 1000000;
NONIUS_BENCHMARK("dict lookup", [](nonius::chronometer meter) {
auto d = build_map<boost::dict<int, int>>(lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
NONIUS_BENCHMARK("umap lookup", [](nonius::chronometer meter) {
auto d = build_map<std::unordered_map<int, int>>(lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google lookup", [](nonius::chronometer meter) {
auto d =
build_map_google<google::dense_hash_map<int, int>>(lookup_test_size);
std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
std::mt19937 engine;
auto gen = std::bind(std::ref(normal), std::ref(engine));
meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif
const int build_test_size = 1000;
NONIUS_BENCHMARK("dict build", [] {
return build_map<boost::dict<int, int>>(build_test_size);
})
NONIUS_BENCHMARK("umap build", [] {
return build_map<std::unordered_map<int, int>>(build_test_size);
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build", [] {
return build_map_google<google::dense_hash_map<int, int>>(build_test_size);
})
#endif
NONIUS_BENCHMARK("dict build with reserve", [] {
return build_map_with_reserve<boost::dict<int, int>>(build_test_size);
})
NONIUS_BENCHMARK("umap build with reserve", [] {
return build_map_with_reserve<std::unordered_map<int, int>>(
build_test_size);
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with reserve", [] {
return build_map_google<google::dense_hash_map<int, int>>(build_test_size);
})
#endif
template <typename Map>
Map build_string_map(int size) {
Map d;
for (int i = 0; i != size; ++i) {
d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i)] = i;
}
return d;
}
#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_string_map_google(int size) {
Map d;
d.set_empty_key("");
for (int i = 0; i != size; ++i) {
d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i) + std::to_string(i) + std::to_string(i) +
std::to_string(i)] = i;
}
return d;
}
#endif
NONIUS_BENCHMARK("dict build with string key", [] {
return build_string_map<boost::dict<std::string, int>>(build_test_size);
})
NONIUS_BENCHMARK("umap build with string key", [] {
return build_string_map<std::unordered_map<std::string, int>>(
build_test_size);
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with string key", [] {
return build_string_map_google<google::dense_hash_map<std::string, int>>(
build_test_size);
})
#endif
template <typename Map, typename LookUpKeys>
int string_lookup_test(Map& map, const LookUpKeys& keys) {
int res = 0;
for (auto&& k : keys) {
res += map[k];
}
return res;
}
const int string_lookup_test_size = 1000;
NONIUS_BENCHMARK("dict string lookup", [](nonius::chronometer meter) {
auto d = build_string_map<boost::dict<std::string, int>>(
string_lookup_test_size);
std::vector<std::string> keys{ "1111111", "2222222", "3333333",
"4444444", "5555555", "6666666",
"7777777", "8888888", "9999999" };
meter.measure([&] { return string_lookup_test(d, keys); });
})
NONIUS_BENCHMARK("umap string lookup", [](nonius::chronometer meter) {
auto d = build_string_map<std::unordered_map<std::string, int>>(
string_lookup_test_size);
std::vector<std::string> keys{ "1111111", "2222222", "3333333",
"4444444", "5555555", "6666666",
"7777777", "8888888", "9999999" };
meter.measure([&] { return string_lookup_test(d, keys); });
})
#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google string lookup", [](nonius::chronometer meter) {
auto d = build_string_map_google<google::dense_hash_map<std::string, int>>(
string_lookup_test_size);
std::vector<std::string> keys{ "1111111", "2222222", "3333333",
"4444444", "5555555", "6666666",
"7777777", "8888888", "9999999" };
meter.measure([&] { return string_lookup_test(d, keys); });
})
#endif
<|endoftext|> |
<commit_before>#include "NotifyIcon.h"
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
#include "Logger.h"
int NotifyIcon::ids = 0;
NotifyIcon::NotifyIcon(HWND hWnd, std::wstring caption,
std::list<std::wstring> icons) :
_level(-1),
_caption(caption) {
using Gdiplus::Bitmap;
_id = NotifyIcon::ids++;
_nid = {};
_nid.cbSize = { sizeof(_nid) };
_nid.hWnd = hWnd;
_nid.uID = _id;
_nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
_nid.uCallbackMessage = MSG_NOTIFYICON;
HICON icon;
Bitmap *iconBmp = new Bitmap(L"Skins/Ignition/Notification Icons/0.ico");
iconBmp->GetHICON(&icon);
_nid.hIcon = icon;
wcscpy_s(_nid.szTip, 128, L"3rVX");
Shell_NotifyIcon(NIM_ADD, &_nid);
// _nid.uVersion = NOTIFYICON_VERSION_4;
// Shell_NotifyIcon(NIM_SETVERSION, &_nid);
_nii = {};
_nii.cbSize = { sizeof(_nii) };
_nii.hWnd = hWnd;
_nii.uID = _id;
}
NotifyIcon::~NotifyIcon() {
Shell_NotifyIcon(NIM_DELETE, &_nid);
}
NOTIFYICONDATA NotifyIcon::IconData() {
return _nid;
}
NOTIFYICONIDENTIFIER NotifyIcon::IconID() {
return _nii;
}<commit_msg>Fix typo<commit_after>#include "NotifyIcon.h"
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
#include "Logger.h"
int NotifyIcon::ids = 0;
NotifyIcon::NotifyIcon(HWND hWnd, std::wstring caption,
std::list<std::wstring> icons) :
_level(-1),
_caption(caption) {
using Gdiplus::Bitmap;
_id = NotifyIcon::ids++;
_nid = {};
_nid.cbSize = { sizeof(_nid) };
_nid.hWnd = hWnd;
_nid.uID = _id;
_nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
_nid.uCallbackMessage = MSG_NOTIFYICON;
HICON icon;
Bitmap *iconBmp = new Bitmap(L"Skins/Ignition/Notification Icons/0.ico");
iconBmp->GetHICON(&icon);
_nid.hIcon = icon;
wcscpy_s(_nid.szTip, 128, L"3RVX");
Shell_NotifyIcon(NIM_ADD, &_nid);
// _nid.uVersion = NOTIFYICON_VERSION_4;
// Shell_NotifyIcon(NIM_SETVERSION, &_nid);
_nii = {};
_nii.cbSize = { sizeof(_nii) };
_nii.hWnd = hWnd;
_nii.uID = _id;
}
NotifyIcon::~NotifyIcon() {
Shell_NotifyIcon(NIM_DELETE, &_nid);
}
NOTIFYICONDATA NotifyIcon::IconData() {
return _nid;
}
NOTIFYICONIDENTIFIER NotifyIcon::IconID() {
return _nii;
}<|endoftext|> |
<commit_before>#include "fpga.hpp"
#include <algorithm>
#include <rtos.h>
#include "logger.hpp"
#include "rj-macros.hpp"
#include "software-spi.hpp"
template <size_t SIGN_INDEX>
uint16_t toSignMag(int16_t val) {
return static_cast<uint16_t>((val < 0) ? ((-val) | 1 << SIGN_INDEX) : val);
}
template <size_t SIGN_INDEX>
int16_t fromSignMag(uint16_t val) {
if (val & 1 << SIGN_INDEX) {
val ^= 1 << SIGN_INDEX; // unset sign bit
val *= -1; // negate
}
return val;
}
FPGA* FPGA::Instance = nullptr;
namespace {
enum {
CMD_EN_DIS_MTRS = 0x30,
CMD_R_ENC_W_VEL = 0x80,
CMD_READ_ENC = 0x91,
CMD_READ_HALLS = 0x92,
CMD_READ_DUTY = 0x93,
CMD_READ_HASH1 = 0x94,
CMD_READ_HASH2 = 0x95,
CMD_CHECK_DRV = 0x96
};
}
FPGA::FPGA(std::shared_ptr<SharedSPI> sharedSPI, PinName nCs, PinName initB,
PinName progB, PinName done)
: SharedSPIDevice(sharedSPI, nCs, true),
_initB(initB),
_done(done),
_progB(progB, PIN_OUTPUT, OpenDrain, 1) {
setSPIFrequency(1000000);
}
bool FPGA::configure(const std::string& filepath) {
// make sure the binary exists before doing anything
FILE* fp = fopen(filepath.c_str(), "r");
if (fp == nullptr) {
LOG(FATAL, "No FPGA bitfile!");
return false;
}
fclose(fp);
// toggle PROG_B to clear out anything prior
_progB = 0;
Thread::wait(1);
_progB = 1;
// wait for the FPGA to tell us it's ready for the bitstream
bool fpgaReady = false;
for (int i = 0; i < 100; i++) {
Thread::wait(10);
// We're ready to start the configuration process when _initB goes high
if (_initB == true) {
fpgaReady = true;
break;
}
}
// show INIT_B error if it never went low
if (!fpgaReady) {
LOG(FATAL, "INIT_B pin timed out\t(PRE CONFIGURATION ERROR)");
return false;
}
// Configure the FPGA with the bitstream file, this returns false if file
// can't be opened
if (send_config(filepath)) {
// Wait some extra time in case the _done pin needs time to be asserted
bool configSuccess = false;
for (int i = 0; i < 1000; i++) {
Thread::wait(1);
if (_done == true) {
configSuccess = !_initB;
break;
}
}
if (configSuccess) {
// everything worked are we're good to go!
_isInit = true;
LOG(INF1, "DONE pin state:\t%s", _done ? "HIGH" : "LOW");
return true;
}
LOG(FATAL, "DONE pin timed out\t(POST CONFIGURATION ERROR)");
}
LOG(FATAL, "FPGA bitstream write error");
return false;
}
TODO(remove this hack once issue number 590 is closed)
#include "../../robot2015/src-ctrl/config/pins-ctrl-2015.hpp"
bool FPGA::send_config(const std::string& filepath) {
const uint8_t bufSize = 50;
// open the bitstream file
FILE* fp = fopen(filepath.c_str(), "r");
// send it out if successfully opened
if (fp != nullptr) {
size_t filesize;
char buf[bufSize];
chipSelect();
// MISO & MOSI are intentionally switched here
// defaults to 8 bit field size with CPOL = 0 & CPHA = 0
#warning FPGA configuration pins currently flipped due to PCB design errors, the final revision requires firmware updates.
SoftwareSPI softSpi(RJ_SPI_MISO, RJ_SPI_MOSI, RJ_SPI_SCK);
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
LOG(INF1, "Sending %s (%u bytes) out to the FPGA", filepath.c_str(),
filesize);
for (size_t i = 0; i < filesize; i++) {
bool breakOut = false;
size_t readSize = fread(buf, 1, bufSize, fp);
if (!readSize) break;
for (size_t j = 0; j < bufSize; j++) {
if (!_initB || _done) {
breakOut = true;
break;
}
softSpi.write(buf[j]);
}
if (breakOut) break;
}
SPI dummySPI(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
chipDeselect();
fclose(fp);
return true;
}
LOG(INIT, "FPGA configuration failed\r\n Unable to open %s",
filepath.c_str());
return false;
}
uint8_t FPGA::read_halls(uint8_t* halls, size_t size) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_READ_HALLS);
for (size_t i = 0; i < size; i++) halls[i] = _spi->write(0x00);
chipDeselect();
return status;
}
uint8_t FPGA::read_encs(int16_t* enc_counts, size_t size) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_READ_ENC);
for (size_t i = 0; i < size; i++) {
uint16_t enc = _spi->write(0x00) << 8;
enc |= _spi->write(0x00);
enc_counts[i] = static_cast<int16_t>(enc);
}
chipDeselect();
return status;
}
uint8_t FPGA::read_duty_cycles(int16_t* duty_cycles, size_t size) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_READ_DUTY);
for (size_t i = 0; i < size; i++) {
uint16_t dc = _spi->write(0x00) << 8;
dc |= _spi->write(0x00);
duty_cycles[i] = fromSignMag<9>(dc);
}
chipDeselect();
return status;
}
uint8_t FPGA::set_duty_cycles(int16_t* duty_cycles, size_t size) {
uint8_t status;
if (size != 5) {
LOG(WARN, "set_duty_cycles() requires input buffer to be of size 5");
}
// Check for valid duty cycles values
for (size_t i = 0; i < size; i++)
if (abs(duty_cycles[i]) > MAX_DUTY_CYCLE) return 0x7F;
chipSelect();
status = _spi->write(CMD_R_ENC_W_VEL);
for (size_t i = 0; i < size; i++) {
uint16_t dc = toSignMag<9>(duty_cycles[i]);
_spi->write(dc & 0xFF);
_spi->write(dc >> 8);
}
chipDeselect();
return status;
}
uint8_t FPGA::set_duty_get_enc(int16_t* duty_cycles, size_t size_dut,
int16_t* enc_deltas, size_t size_enc) {
uint8_t status;
if (size_dut != 5 || size_enc != 5) {
LOG(WARN, "set_duty_get_enc() requires input buffers to be of size 5");
}
// Check for valid duty cycles values
for (size_t i = 0; i < size_dut; i++) {
if (abs(duty_cycles[i]) > MAX_DUTY_CYCLE) return 0x7F;
}
chipSelect();
status = _spi->write(CMD_R_ENC_W_VEL);
for (size_t i = 0; i < 5; i++) {
uint16_t dc = toSignMag<9>(duty_cycles[i]);
uint16_t enc = _spi->write(dc & 0xFF) << 8;
enc |= _spi->write(dc >> 8);
enc_deltas[i] = static_cast<int16_t>(enc);
}
chipDeselect();
return status;
}
bool FPGA::git_hash(std::vector<uint8_t>& v) {
bool dirty_bit;
chipSelect();
_spi->write(CMD_READ_HASH1);
for (size_t i = 0; i < 10; i++) v.push_back(_spi->write(0x00));
chipDeselect();
chipSelect();
_spi->write(CMD_READ_HASH2);
for (size_t i = 0; i < 11; i++) v.push_back(_spi->write(0x00));
chipDeselect();
// store the dirty bit for returning
dirty_bit = (v.back() & 0x01);
// remove the last byte
v.pop_back();
// reverse the bytes
std::reverse(v.begin(), v.end());
return dirty_bit;
}
void FPGA::gate_drivers(std::vector<uint16_t>& v) {
chipSelect();
_spi->write(CMD_CHECK_DRV);
// each halfword is structured as follows (MSB -> LSB):
// | nibble 2: | GVDD_OV | FAULT | GVDD_UV | PVDD_UV |
// | nibble 1: | OTSD | OTW | FETHA_OC | FETLA_OC |
// | nibble 0: | FETHB_OC | FETLB_OC | FETHC_OC | FETLC_OC |
for (size_t i = 0; i < 10; i++) {
uint16_t tmp = _spi->write(0x00);
tmp |= (_spi->write(0x00) << 8);
v.push_back(tmp);
}
chipDeselect();
}
uint8_t FPGA::motors_en(bool state) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_EN_DIS_MTRS | (state << 7));
chipDeselect();
return status;
}
uint8_t FPGA::watchdog_reset() {
motors_en(false);
return motors_en(true);
}
bool FPGA::isReady() { return _isInit; }
<commit_msg>reduce fpga spi frequency in hopes of fixing comm issues<commit_after>#include "fpga.hpp"
#include <algorithm>
#include <rtos.h>
#include "logger.hpp"
#include "rj-macros.hpp"
#include "software-spi.hpp"
template <size_t SIGN_INDEX>
uint16_t toSignMag(int16_t val) {
return static_cast<uint16_t>((val < 0) ? ((-val) | 1 << SIGN_INDEX) : val);
}
template <size_t SIGN_INDEX>
int16_t fromSignMag(uint16_t val) {
if (val & 1 << SIGN_INDEX) {
val ^= 1 << SIGN_INDEX; // unset sign bit
val *= -1; // negate
}
return val;
}
FPGA* FPGA::Instance = nullptr;
namespace {
enum {
CMD_EN_DIS_MTRS = 0x30,
CMD_R_ENC_W_VEL = 0x80,
CMD_READ_ENC = 0x91,
CMD_READ_HALLS = 0x92,
CMD_READ_DUTY = 0x93,
CMD_READ_HASH1 = 0x94,
CMD_READ_HASH2 = 0x95,
CMD_CHECK_DRV = 0x96
};
}
FPGA::FPGA(std::shared_ptr<SharedSPI> sharedSPI, PinName nCs, PinName initB,
PinName progB, PinName done)
: SharedSPIDevice(sharedSPI, nCs, true),
_initB(initB),
_done(done),
_progB(progB, PIN_OUTPUT, OpenDrain, 1) {
setSPIFrequency(500000);
}
bool FPGA::configure(const std::string& filepath) {
// make sure the binary exists before doing anything
FILE* fp = fopen(filepath.c_str(), "r");
if (fp == nullptr) {
LOG(FATAL, "No FPGA bitfile!");
return false;
}
fclose(fp);
// toggle PROG_B to clear out anything prior
_progB = 0;
Thread::wait(1);
_progB = 1;
// wait for the FPGA to tell us it's ready for the bitstream
bool fpgaReady = false;
for (int i = 0; i < 100; i++) {
Thread::wait(10);
// We're ready to start the configuration process when _initB goes high
if (_initB == true) {
fpgaReady = true;
break;
}
}
// show INIT_B error if it never went low
if (!fpgaReady) {
LOG(FATAL, "INIT_B pin timed out\t(PRE CONFIGURATION ERROR)");
return false;
}
// Configure the FPGA with the bitstream file, this returns false if file
// can't be opened
if (send_config(filepath)) {
// Wait some extra time in case the _done pin needs time to be asserted
bool configSuccess = false;
for (int i = 0; i < 1000; i++) {
Thread::wait(1);
if (_done == true) {
configSuccess = !_initB;
break;
}
}
if (configSuccess) {
// everything worked are we're good to go!
_isInit = true;
LOG(INF1, "DONE pin state:\t%s", _done ? "HIGH" : "LOW");
return true;
}
LOG(FATAL, "DONE pin timed out\t(POST CONFIGURATION ERROR)");
}
LOG(FATAL, "FPGA bitstream write error");
return false;
}
TODO(remove this hack once issue number 590 is closed)
#include "../../robot2015/src-ctrl/config/pins-ctrl-2015.hpp"
bool FPGA::send_config(const std::string& filepath) {
const uint8_t bufSize = 50;
// open the bitstream file
FILE* fp = fopen(filepath.c_str(), "r");
// send it out if successfully opened
if (fp != nullptr) {
size_t filesize;
char buf[bufSize];
chipSelect();
// MISO & MOSI are intentionally switched here
// defaults to 8 bit field size with CPOL = 0 & CPHA = 0
#warning FPGA configuration pins currently flipped due to PCB design errors, the final revision requires firmware updates.
SoftwareSPI softSpi(RJ_SPI_MISO, RJ_SPI_MOSI, RJ_SPI_SCK);
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
LOG(INF1, "Sending %s (%u bytes) out to the FPGA", filepath.c_str(),
filesize);
for (size_t i = 0; i < filesize; i++) {
bool breakOut = false;
size_t readSize = fread(buf, 1, bufSize, fp);
if (!readSize) break;
for (size_t j = 0; j < bufSize; j++) {
if (!_initB || _done) {
breakOut = true;
break;
}
softSpi.write(buf[j]);
}
if (breakOut) break;
}
SPI dummySPI(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
chipDeselect();
fclose(fp);
return true;
}
LOG(INIT, "FPGA configuration failed\r\n Unable to open %s",
filepath.c_str());
return false;
}
uint8_t FPGA::read_halls(uint8_t* halls, size_t size) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_READ_HALLS);
for (size_t i = 0; i < size; i++) halls[i] = _spi->write(0x00);
chipDeselect();
return status;
}
uint8_t FPGA::read_encs(int16_t* enc_counts, size_t size) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_READ_ENC);
for (size_t i = 0; i < size; i++) {
uint16_t enc = _spi->write(0x00) << 8;
enc |= _spi->write(0x00);
enc_counts[i] = static_cast<int16_t>(enc);
}
chipDeselect();
return status;
}
uint8_t FPGA::read_duty_cycles(int16_t* duty_cycles, size_t size) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_READ_DUTY);
for (size_t i = 0; i < size; i++) {
uint16_t dc = _spi->write(0x00) << 8;
dc |= _spi->write(0x00);
duty_cycles[i] = fromSignMag<9>(dc);
}
chipDeselect();
return status;
}
uint8_t FPGA::set_duty_cycles(int16_t* duty_cycles, size_t size) {
uint8_t status;
if (size != 5) {
LOG(WARN, "set_duty_cycles() requires input buffer to be of size 5");
}
// Check for valid duty cycles values
for (size_t i = 0; i < size; i++)
if (abs(duty_cycles[i]) > MAX_DUTY_CYCLE) return 0x7F;
chipSelect();
status = _spi->write(CMD_R_ENC_W_VEL);
for (size_t i = 0; i < size; i++) {
uint16_t dc = toSignMag<9>(duty_cycles[i]);
_spi->write(dc & 0xFF);
_spi->write(dc >> 8);
}
chipDeselect();
return status;
}
uint8_t FPGA::set_duty_get_enc(int16_t* duty_cycles, size_t size_dut,
int16_t* enc_deltas, size_t size_enc) {
uint8_t status;
if (size_dut != 5 || size_enc != 5) {
LOG(WARN, "set_duty_get_enc() requires input buffers to be of size 5");
}
// Check for valid duty cycles values
for (size_t i = 0; i < size_dut; i++) {
if (abs(duty_cycles[i]) > MAX_DUTY_CYCLE) return 0x7F;
}
chipSelect();
status = _spi->write(CMD_R_ENC_W_VEL);
for (size_t i = 0; i < 5; i++) {
uint16_t dc = toSignMag<9>(duty_cycles[i]);
uint16_t enc = _spi->write(dc & 0xFF) << 8;
enc |= _spi->write(dc >> 8);
enc_deltas[i] = static_cast<int16_t>(enc);
}
chipDeselect();
return status;
}
bool FPGA::git_hash(std::vector<uint8_t>& v) {
bool dirty_bit;
chipSelect();
_spi->write(CMD_READ_HASH1);
for (size_t i = 0; i < 10; i++) v.push_back(_spi->write(0x00));
chipDeselect();
chipSelect();
_spi->write(CMD_READ_HASH2);
for (size_t i = 0; i < 11; i++) v.push_back(_spi->write(0x00));
chipDeselect();
// store the dirty bit for returning
dirty_bit = (v.back() & 0x01);
// remove the last byte
v.pop_back();
// reverse the bytes
std::reverse(v.begin(), v.end());
return dirty_bit;
}
void FPGA::gate_drivers(std::vector<uint16_t>& v) {
chipSelect();
_spi->write(CMD_CHECK_DRV);
// each halfword is structured as follows (MSB -> LSB):
// | nibble 2: | GVDD_OV | FAULT | GVDD_UV | PVDD_UV |
// | nibble 1: | OTSD | OTW | FETHA_OC | FETLA_OC |
// | nibble 0: | FETHB_OC | FETLB_OC | FETHC_OC | FETLC_OC |
for (size_t i = 0; i < 10; i++) {
uint16_t tmp = _spi->write(0x00);
tmp |= (_spi->write(0x00) << 8);
v.push_back(tmp);
}
chipDeselect();
}
uint8_t FPGA::motors_en(bool state) {
uint8_t status;
chipSelect();
status = _spi->write(CMD_EN_DIS_MTRS | (state << 7));
chipDeselect();
return status;
}
uint8_t FPGA::watchdog_reset() {
motors_en(false);
return motors_en(true);
}
bool FPGA::isReady() { return _isInit; }
<|endoftext|> |
<commit_before>// Copyright 2016-2020 Chris Conway (Koderz). All Rights Reserved.
#include "RuntimeMeshModifierAdjacency.h"
#include "MessageLog.h"
const uint32 EdgesPerTriangle = 3;
const uint32 IndicesPerTriangle = 3;
const uint32 VerticesPerTriangle = 3;
const uint32 DuplicateIndexCount = 3;
const uint32 PnAenDomCorner_IndicesPerPatch = 12;
DECLARE_CYCLE_STAT(TEXT("RML - Calculate Tessellation Indices"), STAT_RuntimeMeshLibrary_CalculateTessellationIndices, STATGROUP_RuntimeMesh);
URuntimeMeshModifierAdjacency::URuntimeMeshModifierAdjacency()
{
}
void URuntimeMeshModifierAdjacency::ApplyToMesh_Implementation(FRuntimeMeshRenderableMeshData& MeshData)
{
if (MeshData.TexCoords.Num() == MeshData.Positions.Num() && MeshData.Tangents.Num() == MeshData.Positions.Num())
{
CalculateTessellationIndices(MeshData);
}
else
{
FFormatNamedArguments Arguments;
Arguments.Add(TEXT("NumPositions"), MeshData.Positions.Num());
Arguments.Add(TEXT("NumNormals"), MeshData.Tangents.Num());
Arguments.Add(TEXT("NumTexCoords"), MeshData.TexCoords.Num());
FText Message = FText::Format(NSLOCTEXT("RuntimeMeshModifierAdjacency", "InvalidMeshDataForTessellation", "Supplied mesh doesn't contain enough data to calculate adjacency triangles for tessellation. All must be same length: Positions:{NumPositions} Normals:{NumNormals} TexCoords:{NumTexCoords}"), Arguments);
FMessageLog("RuntimeMesh").Error(Message);
}
}
void URuntimeMeshModifierAdjacency::CalculateTessellationIndices(FRuntimeMeshRenderableMeshData& MeshData)
{
SCOPE_CYCLE_COUNTER(STAT_RuntimeMeshLibrary_CalculateTessellationIndices);
int32 NumIndices = MeshData.Triangles.Num();
EdgeDictionary EdgeDict;
EdgeDict.Reserve(NumIndices);
PositionDictionary PosDict;
PosDict.Reserve(NumIndices);
MeshData.AdjacencyTriangles.SetNum(PnAenDomCorner_IndicesPerPatch * (NumIndices / IndicesPerTriangle));
ExpandIB(MeshData, EdgeDict, PosDict);
ReplacePlaceholderIndices(MeshData, EdgeDict, PosDict);
}
void URuntimeMeshModifierAdjacency::AddIfLeastUV(PositionDictionary& PosDict, const Vertex& Vert, uint32 Index)
{
auto* Pos = PosDict.Find(Vert.Position);
if (Pos == nullptr)
{
PosDict.Add(Vert.Position, Corner(Index, Vert.TexCoord));
}
else if (Vert.TexCoord < Pos->TexCoord)
{
PosDict[Vert.Position] = Corner(Index, Vert.TexCoord);
}
}
void URuntimeMeshModifierAdjacency::ReplacePlaceholderIndices(FRuntimeMeshRenderableMeshData& MeshData, EdgeDictionary& EdgeDict, PositionDictionary& PosDict)
{
int32 NumIndices = MeshData.Triangles.Num();
const uint32 TriangleCount = NumIndices / PnAenDomCorner_IndicesPerPatch;
for (uint32 U = 0; U < TriangleCount; U++)
{
const uint32 StartOutIndex = U * PnAenDomCorner_IndicesPerPatch;
const uint32 Index0 = MeshData.AdjacencyTriangles.GetVertexIndex(StartOutIndex + 0);
const uint32 Index1 = MeshData.AdjacencyTriangles.GetVertexIndex(StartOutIndex + 1);
const uint32 Index2 = MeshData.AdjacencyTriangles.GetVertexIndex(StartOutIndex + 2);
const Vertex Vertex0(MeshData.Positions.GetPosition(Index0), MeshData.TexCoords.GetTexCoord(Index0));
const Vertex Vertex1(MeshData.Positions.GetPosition(Index1), MeshData.TexCoords.GetTexCoord(Index1));
const Vertex Vertex2(MeshData.Positions.GetPosition(Index2), MeshData.TexCoords.GetTexCoord(Index2));
Triangle Tri(Index0, Index1, Index2, Vertex0, Vertex1, Vertex2);
Edge* Ed = EdgeDict.Find(Tri.GetEdge(0));
if (Ed != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 3, Ed->GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 4, Ed->GetIndex(1));
}
Ed = EdgeDict.Find(Tri.GetEdge(1));
if (Ed != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 5, Ed->GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 6, Ed->GetIndex(1));
}
Ed = EdgeDict.Find(Tri.GetEdge(2));
if (Ed != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 7, Ed->GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 8, Ed->GetIndex(1));
}
// Deal with dominant positions.
for (uint32 V = 0; V < VerticesPerTriangle; V++)
{
Corner* Corn = PosDict.Find(Tri.GetEdge(V).GetVertex(0).Position);
if (Corn != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 9 + V, Corn->Index);
}
}
}
}
void URuntimeMeshModifierAdjacency::ExpandIB(FRuntimeMeshRenderableMeshData& MeshData, EdgeDictionary& OutEdgeDict, PositionDictionary& OutPosDict)
{
int32 NumIndices = MeshData.Triangles.Num();
const uint32 TriangleCount = NumIndices / IndicesPerTriangle;
for (uint32 U = 0; U < TriangleCount; U++)
{
const uint32 StartInIndex = U * IndicesPerTriangle;
const uint32 StartOutIndex = U * PnAenDomCorner_IndicesPerPatch;
const uint32 Index0 = MeshData.Triangles.GetVertexIndex(U * 3 + 0);
const uint32 Index1 = MeshData.Triangles.GetVertexIndex(U * 3 + 1);
const uint32 Index2 = MeshData.Triangles.GetVertexIndex(U * 3 + 2);
const Vertex Vertex0(MeshData.Positions.GetPosition(Index0), MeshData.TexCoords.GetTexCoord(Index0));
const Vertex Vertex1(MeshData.Positions.GetPosition(Index1), MeshData.TexCoords.GetTexCoord(Index1));
const Vertex Vertex2(MeshData.Positions.GetPosition(Index2), MeshData.TexCoords.GetTexCoord(Index2));
Triangle Tri(Index0, Index1, Index2, Vertex0, Vertex1, Vertex2);
if ((uint32)MeshData.AdjacencyTriangles.Num() <= (StartOutIndex + PnAenDomCorner_IndicesPerPatch))
{
MeshData.AdjacencyTriangles.SetNum((StartOutIndex + PnAenDomCorner_IndicesPerPatch) + 1);
}
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 0, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 1, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 2, Tri.GetIndex(2));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 3, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 4, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 5, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 6, Tri.GetIndex(2));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 7, Tri.GetIndex(2));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 8, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 9, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 10, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 11, Tri.GetIndex(2));
Edge Rev0 = Tri.GetEdge(0).GetReverse();
Edge Rev1 = Tri.GetEdge(1).GetReverse();
Edge Rev2 = Tri.GetEdge(2).GetReverse();
OutEdgeDict.Add(Rev0, Rev0);
OutEdgeDict.Add(Rev1, Rev1);
OutEdgeDict.Add(Rev2, Rev2);
AddIfLeastUV(OutPosDict, Vertex0, Index0);
AddIfLeastUV(OutPosDict, Vertex1, Index1);
AddIfLeastUV(OutPosDict, Vertex2, Index2);
}
}
<commit_msg>Fixed include issues in RuntimeMeshModifierAdjacency.cpp<commit_after>// Copyright 2016-2020 Chris Conway (Koderz). All Rights Reserved.
#include "Modifiers/RuntimeMeshModifierAdjacency.h"
#include "Logging/MessageLog.h"
const uint32 EdgesPerTriangle = 3;
const uint32 IndicesPerTriangle = 3;
const uint32 VerticesPerTriangle = 3;
const uint32 DuplicateIndexCount = 3;
const uint32 PnAenDomCorner_IndicesPerPatch = 12;
DECLARE_CYCLE_STAT(TEXT("RML - Calculate Tessellation Indices"), STAT_RuntimeMeshLibrary_CalculateTessellationIndices, STATGROUP_RuntimeMesh);
URuntimeMeshModifierAdjacency::URuntimeMeshModifierAdjacency()
{
}
void URuntimeMeshModifierAdjacency::ApplyToMesh_Implementation(FRuntimeMeshRenderableMeshData& MeshData)
{
if (MeshData.TexCoords.Num() == MeshData.Positions.Num() && MeshData.Tangents.Num() == MeshData.Positions.Num())
{
CalculateTessellationIndices(MeshData);
}
else
{
FFormatNamedArguments Arguments;
Arguments.Add(TEXT("NumPositions"), MeshData.Positions.Num());
Arguments.Add(TEXT("NumNormals"), MeshData.Tangents.Num());
Arguments.Add(TEXT("NumTexCoords"), MeshData.TexCoords.Num());
FText Message = FText::Format(NSLOCTEXT("RuntimeMeshModifierAdjacency", "InvalidMeshDataForTessellation", "Supplied mesh doesn't contain enough data to calculate adjacency triangles for tessellation. All must be same length: Positions:{NumPositions} Normals:{NumNormals} TexCoords:{NumTexCoords}"), Arguments);
FMessageLog("RuntimeMesh").Error(Message);
}
}
void URuntimeMeshModifierAdjacency::CalculateTessellationIndices(FRuntimeMeshRenderableMeshData& MeshData)
{
SCOPE_CYCLE_COUNTER(STAT_RuntimeMeshLibrary_CalculateTessellationIndices);
int32 NumIndices = MeshData.Triangles.Num();
EdgeDictionary EdgeDict;
EdgeDict.Reserve(NumIndices);
PositionDictionary PosDict;
PosDict.Reserve(NumIndices);
MeshData.AdjacencyTriangles.SetNum(PnAenDomCorner_IndicesPerPatch * (NumIndices / IndicesPerTriangle));
ExpandIB(MeshData, EdgeDict, PosDict);
ReplacePlaceholderIndices(MeshData, EdgeDict, PosDict);
}
void URuntimeMeshModifierAdjacency::AddIfLeastUV(PositionDictionary& PosDict, const Vertex& Vert, uint32 Index)
{
auto* Pos = PosDict.Find(Vert.Position);
if (Pos == nullptr)
{
PosDict.Add(Vert.Position, Corner(Index, Vert.TexCoord));
}
else if (Vert.TexCoord < Pos->TexCoord)
{
PosDict[Vert.Position] = Corner(Index, Vert.TexCoord);
}
}
void URuntimeMeshModifierAdjacency::ReplacePlaceholderIndices(FRuntimeMeshRenderableMeshData& MeshData, EdgeDictionary& EdgeDict, PositionDictionary& PosDict)
{
int32 NumIndices = MeshData.Triangles.Num();
const uint32 TriangleCount = NumIndices / PnAenDomCorner_IndicesPerPatch;
for (uint32 U = 0; U < TriangleCount; U++)
{
const uint32 StartOutIndex = U * PnAenDomCorner_IndicesPerPatch;
const uint32 Index0 = MeshData.AdjacencyTriangles.GetVertexIndex(StartOutIndex + 0);
const uint32 Index1 = MeshData.AdjacencyTriangles.GetVertexIndex(StartOutIndex + 1);
const uint32 Index2 = MeshData.AdjacencyTriangles.GetVertexIndex(StartOutIndex + 2);
const Vertex Vertex0(MeshData.Positions.GetPosition(Index0), MeshData.TexCoords.GetTexCoord(Index0));
const Vertex Vertex1(MeshData.Positions.GetPosition(Index1), MeshData.TexCoords.GetTexCoord(Index1));
const Vertex Vertex2(MeshData.Positions.GetPosition(Index2), MeshData.TexCoords.GetTexCoord(Index2));
Triangle Tri(Index0, Index1, Index2, Vertex0, Vertex1, Vertex2);
Edge* Ed = EdgeDict.Find(Tri.GetEdge(0));
if (Ed != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 3, Ed->GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 4, Ed->GetIndex(1));
}
Ed = EdgeDict.Find(Tri.GetEdge(1));
if (Ed != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 5, Ed->GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 6, Ed->GetIndex(1));
}
Ed = EdgeDict.Find(Tri.GetEdge(2));
if (Ed != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 7, Ed->GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 8, Ed->GetIndex(1));
}
// Deal with dominant positions.
for (uint32 V = 0; V < VerticesPerTriangle; V++)
{
Corner* Corn = PosDict.Find(Tri.GetEdge(V).GetVertex(0).Position);
if (Corn != nullptr)
{
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 9 + V, Corn->Index);
}
}
}
}
void URuntimeMeshModifierAdjacency::ExpandIB(FRuntimeMeshRenderableMeshData& MeshData, EdgeDictionary& OutEdgeDict, PositionDictionary& OutPosDict)
{
int32 NumIndices = MeshData.Triangles.Num();
const uint32 TriangleCount = NumIndices / IndicesPerTriangle;
for (uint32 U = 0; U < TriangleCount; U++)
{
const uint32 StartInIndex = U * IndicesPerTriangle;
const uint32 StartOutIndex = U * PnAenDomCorner_IndicesPerPatch;
const uint32 Index0 = MeshData.Triangles.GetVertexIndex(U * 3 + 0);
const uint32 Index1 = MeshData.Triangles.GetVertexIndex(U * 3 + 1);
const uint32 Index2 = MeshData.Triangles.GetVertexIndex(U * 3 + 2);
const Vertex Vertex0(MeshData.Positions.GetPosition(Index0), MeshData.TexCoords.GetTexCoord(Index0));
const Vertex Vertex1(MeshData.Positions.GetPosition(Index1), MeshData.TexCoords.GetTexCoord(Index1));
const Vertex Vertex2(MeshData.Positions.GetPosition(Index2), MeshData.TexCoords.GetTexCoord(Index2));
Triangle Tri(Index0, Index1, Index2, Vertex0, Vertex1, Vertex2);
if ((uint32)MeshData.AdjacencyTriangles.Num() <= (StartOutIndex + PnAenDomCorner_IndicesPerPatch))
{
MeshData.AdjacencyTriangles.SetNum((StartOutIndex + PnAenDomCorner_IndicesPerPatch) + 1);
}
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 0, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 1, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 2, Tri.GetIndex(2));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 3, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 4, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 5, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 6, Tri.GetIndex(2));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 7, Tri.GetIndex(2));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 8, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 9, Tri.GetIndex(0));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 10, Tri.GetIndex(1));
MeshData.AdjacencyTriangles.SetVertexIndex(StartOutIndex + 11, Tri.GetIndex(2));
Edge Rev0 = Tri.GetEdge(0).GetReverse();
Edge Rev1 = Tri.GetEdge(1).GetReverse();
Edge Rev2 = Tri.GetEdge(2).GetReverse();
OutEdgeDict.Add(Rev0, Rev0);
OutEdgeDict.Add(Rev1, Rev1);
OutEdgeDict.Add(Rev2, Rev2);
AddIfLeastUV(OutPosDict, Vertex0, Index0);
AddIfLeastUV(OutPosDict, Vertex1, Index1);
AddIfLeastUV(OutPosDict, Vertex2, Index2);
}
}
<|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.
//
// This file contains the main() function for the impala daemon process,
// which exports the Thrift services ImpalaService and ImpalaInternalService.
#include <unistd.h>
#include <jni.h>
#include "common/logging.h"
#include "common/init.h"
#include "exec/hbase-table-scanner.h"
#include "exec/hbase-table-writer.h"
#include "exprs/hive-udf-call.h"
#include "exprs/timezone_db.h"
#include "runtime/hbase-table.h"
#include "codegen/llvm-codegen.h"
#include "common/status.h"
#include "runtime/coordinator.h"
#include "runtime/exec-env.h"
#include "util/jni-util.h"
#include "util/network-util.h"
#include "rpc/thrift-util.h"
#include "rpc/thrift-server.h"
#include "rpc/rpc-trace.h"
#include "service/impala-server.h"
#include "service/fe-support.h"
#include "gen-cpp/ImpalaService.h"
#include "gen-cpp/ImpalaInternalService.h"
#include "util/impalad-metrics.h"
#include "util/thread.h"
#include "common/names.h"
using namespace impala;
DECLARE_string(classpath);
DECLARE_bool(use_statestore);
DECLARE_int32(beeswax_port);
DECLARE_int32(hs2_port);
DECLARE_int32(be_port);
DECLARE_string(principal);
DECLARE_bool(enable_rm);
DECLARE_bool(is_coordinator);
int ImpaladMain(int argc, char** argv) {
InitCommonRuntime(argc, argv, true);
ABORT_IF_ERROR(TimezoneDatabase::Initialize());
ABORT_IF_ERROR(LlvmCodeGen::InitializeLlvm());
JniUtil::InitLibhdfs();
ABORT_IF_ERROR(HBaseTableScanner::Init());
ABORT_IF_ERROR(HBaseTable::InitJNI());
ABORT_IF_ERROR(HBaseTableWriter::InitJNI());
ABORT_IF_ERROR(HiveUdfCall::Init());
InitFeSupport();
if (FLAGS_enable_rm) {
// TODO: Remove in Impala 3.0.
LOG(WARNING) << "*****************************************************************";
LOG(WARNING) << "Llama support has been deprecated. FLAGS_enable_rm has no effect.";
LOG(WARNING) << "*****************************************************************";
}
// start backend service for the coordinator on be_port
ExecEnv exec_env;
StartThreadInstrumentation(exec_env.metrics(), exec_env.webserver(), true);
InitRpcEventTracing(exec_env.webserver());
ThriftServer* beeswax_server = NULL;
ThriftServer* hs2_server = NULL;
ThriftServer* be_server = NULL;
boost::shared_ptr<ImpalaServer> server;
ABORT_IF_ERROR(CreateImpalaServer(&exec_env, FLAGS_beeswax_port, FLAGS_hs2_port,
FLAGS_be_port, &beeswax_server, &hs2_server, &be_server, &server));
ABORT_IF_ERROR(be_server->Start());
if (FLAGS_is_coordinator) {
ABORT_IF_ERROR(beeswax_server->Start());
ABORT_IF_ERROR(hs2_server->Start());
}
Status status = exec_env.StartServices();
if (!status.ok()) {
LOG(ERROR) << "Impalad services did not start correctly, exiting. Error: "
<< status.GetDetail();
ShutdownLogging();
exit(1);
}
ImpaladMetrics::IMPALA_SERVER_READY->set_value(true);
LOG(INFO) << "Impala has started.";
be_server->Join();
delete be_server;
if (FLAGS_is_coordinator) {
// this blocks until the beeswax and hs2 servers terminate
beeswax_server->Join();
hs2_server->Join();
delete beeswax_server;
delete hs2_server;
}
return 0;
}
<commit_msg>IMPALA-5377: Impala may crash if given a fragment instance while restarting<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.
//
// This file contains the main() function for the impala daemon process,
// which exports the Thrift services ImpalaService and ImpalaInternalService.
#include <unistd.h>
#include <jni.h>
#include "common/logging.h"
#include "common/init.h"
#include "exec/hbase-table-scanner.h"
#include "exec/hbase-table-writer.h"
#include "exprs/hive-udf-call.h"
#include "exprs/timezone_db.h"
#include "runtime/hbase-table.h"
#include "codegen/llvm-codegen.h"
#include "common/status.h"
#include "runtime/coordinator.h"
#include "runtime/exec-env.h"
#include "util/jni-util.h"
#include "util/network-util.h"
#include "rpc/thrift-util.h"
#include "rpc/thrift-server.h"
#include "rpc/rpc-trace.h"
#include "service/impala-server.h"
#include "service/fe-support.h"
#include "gen-cpp/ImpalaService.h"
#include "gen-cpp/ImpalaInternalService.h"
#include "util/impalad-metrics.h"
#include "util/thread.h"
#include "common/names.h"
using namespace impala;
DECLARE_string(classpath);
DECLARE_bool(use_statestore);
DECLARE_int32(beeswax_port);
DECLARE_int32(hs2_port);
DECLARE_int32(be_port);
DECLARE_string(principal);
DECLARE_bool(enable_rm);
DECLARE_bool(is_coordinator);
int ImpaladMain(int argc, char** argv) {
InitCommonRuntime(argc, argv, true);
ABORT_IF_ERROR(TimezoneDatabase::Initialize());
ABORT_IF_ERROR(LlvmCodeGen::InitializeLlvm());
JniUtil::InitLibhdfs();
ABORT_IF_ERROR(HBaseTableScanner::Init());
ABORT_IF_ERROR(HBaseTable::InitJNI());
ABORT_IF_ERROR(HBaseTableWriter::InitJNI());
ABORT_IF_ERROR(HiveUdfCall::Init());
InitFeSupport();
if (FLAGS_enable_rm) {
// TODO: Remove in Impala 3.0.
LOG(WARNING) << "*****************************************************************";
LOG(WARNING) << "Llama support has been deprecated. FLAGS_enable_rm has no effect.";
LOG(WARNING) << "*****************************************************************";
}
// start backend service for the coordinator on be_port
ExecEnv exec_env;
StartThreadInstrumentation(exec_env.metrics(), exec_env.webserver(), true);
InitRpcEventTracing(exec_env.webserver());
ThriftServer* beeswax_server = NULL;
ThriftServer* hs2_server = NULL;
ThriftServer* be_server = NULL;
boost::shared_ptr<ImpalaServer> server;
ABORT_IF_ERROR(CreateImpalaServer(&exec_env, FLAGS_beeswax_port, FLAGS_hs2_port,
FLAGS_be_port, &beeswax_server, &hs2_server, &be_server, &server));
Status status = exec_env.StartServices();
if (!status.ok()) {
LOG(ERROR) << "Impalad services did not start correctly, exiting. Error: "
<< status.GetDetail();
ShutdownLogging();
exit(1);
}
DCHECK(exec_env.process_mem_tracker() != nullptr)
<< "ExecEnv::StartServices() must be called before starting RPC services";
ABORT_IF_ERROR(be_server->Start());
if (FLAGS_is_coordinator) {
ABORT_IF_ERROR(beeswax_server->Start());
ABORT_IF_ERROR(hs2_server->Start());
}
ImpaladMetrics::IMPALA_SERVER_READY->set_value(true);
LOG(INFO) << "Impala has started.";
be_server->Join();
delete be_server;
if (FLAGS_is_coordinator) {
// this blocks until the beeswax and hs2 servers terminate
beeswax_server->Join();
hs2_server->Join();
delete beeswax_server;
delete hs2_server;
}
return 0;
}
<|endoftext|> |
<commit_before>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <pthread.h>
#include "protocol.hpp"
#include "sqlite_protocol.hpp"
#include <stdint.h>
#include "assert.h"
#define update_salt 6830
using namespace std;
/* Information shared between clients */
struct shared_t {
public:
shared_t(config_t *_config)
: config(_config),
last_qps(0), n_op(1), n_tick(1), n_ops_so_far(0)
{
pthread_mutex_init(&mutex, NULL);
if(strcmp(config->qps_file, "-") == 0) {
qps_fd = stdout;
} else if(config->qps_file[0] != 0) {
qps_fd = fopen(config->qps_file, "wa");
} else {
qps_fd = NULL;
}
if(strcmp(config->latency_file, "-") == 0) {
latencies_fd = stdout;
} else if(config->latency_file[0] != 0) {
latencies_fd = fopen(config->latency_file, "wa");
} else {
latencies_fd = NULL;
}
value_buf = new char[config->values.max];
memset((void *) value_buf, 'A', config->values.max);
}
~shared_t() {
if(qps_fd && qps_fd != stdout) {
fclose(qps_fd);
}
if(latencies_fd && latencies_fd != stdout) {
fclose(latencies_fd);
}
pthread_mutex_destroy(&mutex);
delete value_buf;
}
void push_qps(int _qps, int tick) {
if(!qps_fd && !latencies_fd)
return;
lock();
// Collect qps info from all clients before attempting to print
if(config->clients > 1) {
int qps_count = 0, agg_qps = 0;
map<int, pair<int, int> >::iterator op = qps_map.find(tick);
if(op != qps_map.end()) {
qps_count = op->second.first;
agg_qps = op->second.second;
}
qps_count += 1;
agg_qps += _qps;
if(qps_count == config->clients) {
_qps = agg_qps;
qps_map.erase(op);
} else {
qps_map[tick] = pair<int, int>(qps_count, agg_qps);
unlock();
return;
}
}
last_qps = _qps;
if(!qps_fd) {
unlock();
return;
}
fprintf(qps_fd, "%d\t\t%d\n", n_tick, _qps);
n_tick++;
unlock();
}
void push_latency(float latency) {
lock();
n_ops_so_far++;
unlock();
/*
if(n_ops_so_far % 200000 == 0)
printf("%ld\n", n_ops_so_far);
*/
if(!latencies_fd || last_qps == 0)
return;
// We cannot possibly write every latency because that stalls
// the client, so we want to scale that by the number of qps
// (we'll sample latencies for roughly N random ops every
// second).
const int samples_per_second = 20;
if(rand() % (last_qps / samples_per_second) != 0) {
return;
}
lock();
fprintf(latencies_fd, "%ld\t\t%.2f\n", n_op, latency);
n_op++;
unlock();
}
private:
config_t *config;
map<int, pair<int, int> > qps_map;
FILE *qps_fd, *latencies_fd;
pthread_mutex_t mutex;
int last_qps;
long n_op;
int n_tick;
long n_ops_so_far;
public:
// We have one value shared among all the threads.
char *value_buf;
private:
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
};
/* Communication structure for main thread and clients */
struct client_data_t {
config_t *config;
server_t *server;
shared_t *shared;
protocol_t *proto;
sqlite_protocol_t *sqlite;
int id;
int min_seed, max_seed;
};
/* The function that does the work */
void* run_client(void* data) {
// Grab the config
client_data_t *client_data = (client_data_t*)data;
config_t *config = client_data->config;
server_t *server = client_data->server;
shared_t *shared = client_data->shared;
protocol_t *proto = client_data->proto;
sqlite_protocol_t *sqlite = client_data->sqlite;
if(sqlite)
sqlite->set_id(client_data->id);
const size_t per_key_size = config->keys.calculate_max_length(config->clients - 1);
// Perform the ops
ticks_t last_time = get_ticks(), start_time = last_time, last_qps_time = last_time, now_time;
int qps = 0, tick = 0;
int total_queries = 0;
int total_inserts = 0;
int total_deletes = 0;
bool keep_running = true;
while(keep_running) {
// Generate the command
load_t::load_op_t cmd = config->load.toss((config->batch_factor.min + config->batch_factor.max) / 2.0f);
payload_t op_keys[config->batch_factor.max];
char key_space[per_key_size * config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_keys[i].first = key_space + (per_key_size * i);
payload_t op_vals[config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_vals[i].first = shared->value_buf;
char val_verifcation_buffer[MAX_VALUE_SIZE];
char *old_val_buffer;
int j, k, l; // because we can't declare in the loop
int count;
int keyn; //same deal
uint64_t id_salt = client_data->id;
id_salt += id_salt << 32;
// TODO: If an workload contains contains no inserts and there are no keys available for a particular client (and the duration is specified in q/i), it'll just loop forever.
try {
switch(cmd) {
case load_t::delete_op:
if (client_data->min_seed == client_data->max_seed)
break;
config->keys.toss(op_keys, client_data->min_seed ^ id_salt, client_data->id, config->clients - 1);
// Delete it from the server
proto->remove(op_keys->first, op_keys->second);
if (sqlite && (client_data->min_seed % RELIABILITY) == 0)
sqlite->remove(op_keys->first, op_keys->second);
client_data->min_seed++;
qps++;
total_queries++;
total_deletes++;
break;
case load_t::update_op:
// Find the key and generate the payload
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt ^ update_salt);
// Send it to server
proto->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
// Free the value
qps++;
total_queries++;
break;
case load_t::insert_op:
// Generate the payload
config->keys.toss(op_keys, client_data->max_seed ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
// Send it to server
proto->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (client_data->max_seed % RELIABILITY) == 0)
sqlite->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
client_data->max_seed++;
// Free the value and save the key
qps++;
total_queries++;
total_inserts++;
break;
case load_t::read_op:
// Find the key
if(client_data->min_seed == client_data->max_seed)
break;
j = random(config->batch_factor.min, config->batch_factor.max);
j = std::min(j, client_data->max_seed - client_data->min_seed);
l = random(client_data->min_seed, client_data->max_seed - 1);
for (k = 0; k < j; k++) {
config->keys.toss(&op_keys[k], l ^ id_salt, client_data->id, config->clients - 1);
l++;
if(l >= client_data->max_seed)
l = client_data->min_seed;
}
// Read it from the server
proto->read(&op_keys[0], j);
qps += j;
total_queries += j;
break;
case load_t::append_op:
//TODO, this doesn't check if we'll be making the value too big. Gotta check for that.
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::prepend_op:
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::verify_op:
/* this is a very expensive operation it will first do a very
* expensive operation on the SQLITE reference db and then it will
* do several queries on the db that's being stressed (and only add
* 1 total query), it does not make sense to use this as part of a
* benchmarking run */
// we can't do anything without a reference
if (!sqlite)
break;
/* this is hacky but whatever */
old_val_buffer = op_vals[0].first;
op_vals[0].first = val_verifcation_buffer;
op_vals[0].second = 0;
sqlite->dump_start();
while (sqlite->dump_next(op_keys, op_vals)) {
proto->read(op_keys, 1, op_vals);
}
sqlite->dump_end();
op_vals[0].first = old_val_buffer;
qps++;
total_queries++;
break;
default:
fprintf(stderr, "Uknown operation\n");
exit(-1);
};
} catch (const protocol_error_t& e) {
fprintf(stderr, "Protocol error: %s\n", e.c_str());
exit(-1);
}
now_time = get_ticks();
// Deal with individual op latency
ticks_t latency = now_time - last_time;
shared->push_latency(ticks_to_us(latency));
last_time = now_time;
// Deal with QPS
if (ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
// First deal with missed QPS
int qps_to_write = ticks_to_secs(now_time - last_qps_time);
while (qps_to_write > 1) {
shared->push_qps(0, tick);
//last_qps_time = now_time;
last_qps_time = last_qps_time + secs_to_ticks(1.0f);
tick++;
--qps_to_write;
}
shared->push_qps(qps, tick);
//last_qps_time = now_time;
last_qps_time = last_qps_time + secs_to_ticks(1.0f);
qps = 0;
tick++;
}
// See if we should keep running
if (config->duration.duration != -1) {
switch(config->duration.units) {
case duration_t::queries_t:
keep_running = total_queries < config->duration.duration / config->clients;
break;
case duration_t::seconds_t:
//keep_running = ticks_to_secs(now_time - start_time) < config->duration.duration;
keep_running = tick < config->duration.duration;
break;
case duration_t::inserts_t:
keep_running = total_inserts - total_deletes < config->duration.duration / config->clients;
break;
default:
fprintf(stderr, "Unknown duration unit\n");
exit(-1);
}
}
}
}
#endif // __CLIENT_HPP__
<commit_msg>fflush() qps and latency data.<commit_after>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <pthread.h>
#include "protocol.hpp"
#include "sqlite_protocol.hpp"
#include <stdint.h>
#include "assert.h"
#define update_salt 6830
using namespace std;
/* Information shared between clients */
struct shared_t {
public:
shared_t(config_t *_config)
: config(_config),
last_qps(0), n_op(1), n_tick(1), n_ops_so_far(0)
{
pthread_mutex_init(&mutex, NULL);
if(strcmp(config->qps_file, "-") == 0) {
qps_fd = stdout;
} else if(config->qps_file[0] != 0) {
qps_fd = fopen(config->qps_file, "wa");
} else {
qps_fd = NULL;
}
if(strcmp(config->latency_file, "-") == 0) {
latencies_fd = stdout;
} else if(config->latency_file[0] != 0) {
latencies_fd = fopen(config->latency_file, "wa");
} else {
latencies_fd = NULL;
}
value_buf = new char[config->values.max];
memset((void *) value_buf, 'A', config->values.max);
}
~shared_t() {
if(qps_fd && qps_fd != stdout) {
fclose(qps_fd);
}
if(latencies_fd && latencies_fd != stdout) {
fclose(latencies_fd);
}
pthread_mutex_destroy(&mutex);
delete value_buf;
}
void push_qps(int _qps, int tick) {
if(!qps_fd && !latencies_fd)
return;
lock();
// Collect qps info from all clients before attempting to print
if(config->clients > 1) {
int qps_count = 0, agg_qps = 0;
map<int, pair<int, int> >::iterator op = qps_map.find(tick);
if(op != qps_map.end()) {
qps_count = op->second.first;
agg_qps = op->second.second;
}
qps_count += 1;
agg_qps += _qps;
if(qps_count == config->clients) {
_qps = agg_qps;
qps_map.erase(op);
} else {
qps_map[tick] = pair<int, int>(qps_count, agg_qps);
unlock();
return;
}
}
last_qps = _qps;
if(!qps_fd) {
unlock();
return;
}
fprintf(qps_fd, "%d\t\t%d\n", n_tick, _qps);
fflush(qps_fd);
n_tick++;
unlock();
}
void push_latency(float latency) {
lock();
n_ops_so_far++;
unlock();
/*
if(n_ops_so_far % 200000 == 0)
printf("%ld\n", n_ops_so_far);
*/
if(!latencies_fd || last_qps == 0)
return;
// We cannot possibly write every latency because that stalls
// the client, so we want to scale that by the number of qps
// (we'll sample latencies for roughly N random ops every
// second).
const int samples_per_second = 20;
if(rand() % (last_qps / samples_per_second) != 0) {
return;
}
lock();
fprintf(latencies_fd, "%ld\t\t%.2f\n", n_op, latency);
fflush(latencies_fd);
n_op++;
unlock();
}
private:
config_t *config;
map<int, pair<int, int> > qps_map;
FILE *qps_fd, *latencies_fd;
pthread_mutex_t mutex;
int last_qps;
long n_op;
int n_tick;
long n_ops_so_far;
public:
// We have one value shared among all the threads.
char *value_buf;
private:
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
};
/* Communication structure for main thread and clients */
struct client_data_t {
config_t *config;
server_t *server;
shared_t *shared;
protocol_t *proto;
sqlite_protocol_t *sqlite;
int id;
int min_seed, max_seed;
};
/* The function that does the work */
void* run_client(void* data) {
// Grab the config
client_data_t *client_data = (client_data_t*)data;
config_t *config = client_data->config;
server_t *server = client_data->server;
shared_t *shared = client_data->shared;
protocol_t *proto = client_data->proto;
sqlite_protocol_t *sqlite = client_data->sqlite;
if(sqlite)
sqlite->set_id(client_data->id);
const size_t per_key_size = config->keys.calculate_max_length(config->clients - 1);
// Perform the ops
ticks_t last_time = get_ticks(), start_time = last_time, last_qps_time = last_time, now_time;
int qps = 0, tick = 0;
int total_queries = 0;
int total_inserts = 0;
int total_deletes = 0;
bool keep_running = true;
while(keep_running) {
// Generate the command
load_t::load_op_t cmd = config->load.toss((config->batch_factor.min + config->batch_factor.max) / 2.0f);
payload_t op_keys[config->batch_factor.max];
char key_space[per_key_size * config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_keys[i].first = key_space + (per_key_size * i);
payload_t op_vals[config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_vals[i].first = shared->value_buf;
char val_verifcation_buffer[MAX_VALUE_SIZE];
char *old_val_buffer;
int j, k, l; // because we can't declare in the loop
int count;
int keyn; //same deal
uint64_t id_salt = client_data->id;
id_salt += id_salt << 32;
// TODO: If an workload contains contains no inserts and there are no keys available for a particular client (and the duration is specified in q/i), it'll just loop forever.
try {
switch(cmd) {
case load_t::delete_op:
if (client_data->min_seed == client_data->max_seed)
break;
config->keys.toss(op_keys, client_data->min_seed ^ id_salt, client_data->id, config->clients - 1);
// Delete it from the server
proto->remove(op_keys->first, op_keys->second);
if (sqlite && (client_data->min_seed % RELIABILITY) == 0)
sqlite->remove(op_keys->first, op_keys->second);
client_data->min_seed++;
qps++;
total_queries++;
total_deletes++;
break;
case load_t::update_op:
// Find the key and generate the payload
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt ^ update_salt);
// Send it to server
proto->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
// Free the value
qps++;
total_queries++;
break;
case load_t::insert_op:
// Generate the payload
config->keys.toss(op_keys, client_data->max_seed ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
// Send it to server
proto->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (client_data->max_seed % RELIABILITY) == 0)
sqlite->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
client_data->max_seed++;
// Free the value and save the key
qps++;
total_queries++;
total_inserts++;
break;
case load_t::read_op:
// Find the key
if(client_data->min_seed == client_data->max_seed)
break;
j = random(config->batch_factor.min, config->batch_factor.max);
j = std::min(j, client_data->max_seed - client_data->min_seed);
l = random(client_data->min_seed, client_data->max_seed - 1);
for (k = 0; k < j; k++) {
config->keys.toss(&op_keys[k], l ^ id_salt, client_data->id, config->clients - 1);
l++;
if(l >= client_data->max_seed)
l = client_data->min_seed;
}
// Read it from the server
proto->read(&op_keys[0], j);
qps += j;
total_queries += j;
break;
case load_t::append_op:
//TODO, this doesn't check if we'll be making the value too big. Gotta check for that.
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::prepend_op:
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::verify_op:
/* this is a very expensive operation it will first do a very
* expensive operation on the SQLITE reference db and then it will
* do several queries on the db that's being stressed (and only add
* 1 total query), it does not make sense to use this as part of a
* benchmarking run */
// we can't do anything without a reference
if (!sqlite)
break;
/* this is hacky but whatever */
old_val_buffer = op_vals[0].first;
op_vals[0].first = val_verifcation_buffer;
op_vals[0].second = 0;
sqlite->dump_start();
while (sqlite->dump_next(op_keys, op_vals)) {
proto->read(op_keys, 1, op_vals);
}
sqlite->dump_end();
op_vals[0].first = old_val_buffer;
qps++;
total_queries++;
break;
default:
fprintf(stderr, "Uknown operation\n");
exit(-1);
};
} catch (const protocol_error_t& e) {
fprintf(stderr, "Protocol error: %s\n", e.c_str());
exit(-1);
}
now_time = get_ticks();
// Deal with individual op latency
ticks_t latency = now_time - last_time;
shared->push_latency(ticks_to_us(latency));
last_time = now_time;
// Deal with QPS
if (ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
// First deal with missed QPS
int qps_to_write = ticks_to_secs(now_time - last_qps_time);
while (qps_to_write > 1) {
shared->push_qps(0, tick);
//last_qps_time = now_time;
last_qps_time = last_qps_time + secs_to_ticks(1.0f);
tick++;
--qps_to_write;
}
shared->push_qps(qps, tick);
//last_qps_time = now_time;
last_qps_time = last_qps_time + secs_to_ticks(1.0f);
qps = 0;
tick++;
}
// See if we should keep running
if (config->duration.duration != -1) {
switch(config->duration.units) {
case duration_t::queries_t:
keep_running = total_queries < config->duration.duration / config->clients;
break;
case duration_t::seconds_t:
//keep_running = ticks_to_secs(now_time - start_time) < config->duration.duration;
keep_running = tick < config->duration.duration;
break;
case duration_t::inserts_t:
keep_running = total_inserts - total_deletes < config->duration.duration / config->clients;
break;
default:
fprintf(stderr, "Unknown duration unit\n");
exit(-1);
}
}
}
}
#endif // __CLIENT_HPP__
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK
* Written by Pascal Giorgi <[email protected]>
*
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*.
*/
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/ffpack/ffpack.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "givaro/modular-integer.h"
int main(int argc, char** argv){
srand((int)time(NULL));
srand48(time(NULL));
static size_t iters = 3 ;
static Givaro::Integer q = -1 ;
static unsigned long b = 512 ;
static size_t m = 512 ;
static size_t n = 512 ;
static Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the random characteristic.", TYPE_INT , &b },
{ 'm', "-m M", "Set the dimension m of the matrix.", TYPE_INT , &m },
{ 'n', "-n N", "Set the dimension n of the matrix.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
size_t seed= time(NULL);
typedef Givaro::Modular<Givaro::Integer> Field;
FFLAS::Timer chrono;
double time=0.;
Givaro::Integer p;
for (size_t i=0;i<iters;i++) {
Givaro::Integer::random_exact_2exp(p, b);
prevprime(p,p);
Field F(p);
size_t lda;
lda=n;
typename Field::RandIter Rand(F,seed);
Field::Element_ptr A;
A= FFLAS::fflas_new(F,m,lda);
size_t * P = FFLAS::fflas_new<size_t>(n) ;
size_t * Q = FFLAS::fflas_new<size_t>(m) ;
for (size_t ii=0;ii<m*lda;++ii)
Rand.random(A[ii]);
Givaro::Integer alpha;
alpha=1;
chrono.clear();chrono.start();
FFPACK::LUdivine (F, FFLAS::FflasUnit, FFLAS::FflasNoTrans, m, n, A, lda, P, Q);
chrono.stop();
time+=chrono.usertime();
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(P);
FFLAS::fflas_delete(Q);
}
double Gflops=(2./3.*double(m)/1000.*double(m)/1000.*double(n)/1000.0) / chrono.usertime() * double(iters);
Gflops*=p.bitsize()/16.;
cout<<"Time: "<<time/iters<<" Gflops: "<<Gflops<<endl;
return 0;
}
<commit_msg>intprimedom<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK
* Written by Pascal Giorgi <[email protected]>
*
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*.
*/
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/ffpack/ffpack.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "givaro/modular-integer.h"
int main(int argc, char** argv){
srand((int)time(NULL));
srand48(time(NULL));
static size_t iters = 3 ;
static Givaro::Integer q = -1 ;
static unsigned long b = 512 ;
static size_t m = 512 ;
static size_t n = 512 ;
static Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the random characteristic.", TYPE_INT , &b },
{ 'm', "-m M", "Set the dimension m of the matrix.", TYPE_INT , &m },
{ 'n', "-n N", "Set the dimension n of the matrix.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
size_t seed= time(NULL);
typedef Givaro::Modular<Givaro::Integer> Field;
FFLAS::Timer chrono;
double time=0.;
Givaro::Integer p;
Givaro::IntPrimeDom IPD;
for (size_t i=0;i<iters;i++) {
Givaro::Integer::random_exact_2exp(p, b);
IPD.prevprimein(p);
Field F(p);
size_t lda;
lda=n;
typename Field::RandIter Rand(F,seed);
Field::Element_ptr A;
A= FFLAS::fflas_new(F,m,lda);
size_t * P = FFLAS::fflas_new<size_t>(n) ;
size_t * Q = FFLAS::fflas_new<size_t>(m) ;
for (size_t ii=0;ii<m*lda;++ii)
Rand.random(A[ii]);
Givaro::Integer alpha;
alpha=1;
chrono.clear();chrono.start();
FFPACK::LUdivine (F, FFLAS::FflasUnit, FFLAS::FflasNoTrans, m, n, A, lda, P, Q);
chrono.stop();
time+=chrono.usertime();
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(P);
FFLAS::fflas_delete(Q);
}
double Gflops=(2./3.*double(m)/1000.*double(m)/1000.*double(n)/1000.0) / chrono.usertime() * double(iters);
Gflops*=p.bitsize()/16.;
cout<<"Time: "<<time/iters<<" Gflops: "<<Gflops<<endl;
return 0;
}
<|endoftext|> |
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// Tests for the AISResources class.
#include <unistd.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
#include "AISResources.h"
#include "debug.h"
using namespace CppUnit;
class AISResourcesTest:public TestFixture {
private:
AISResources *ais;
string fnoc1, fnoc2, fnoc3;
string fnoc1_ais, fnoc2_ais, fnoc3_ais;
public:
AISResourcesTest() {}
~AISResourcesTest() {}
void setUp() {
fnoc1 = "http://localhost/dods-test/nph-dods/data/nc/fnoc1.nc";
fnoc2 = "http://localhost/dods-test/nph-dods/data/nc/fnoc2.nc";
fnoc3 = "http://localhost/dods-test/nph-dods/data/nc/fnoc3.nc";
fnoc1_ais = "http://localhost/ais/fnoc1.nc.das";
fnoc2_ais = "ais_testsuite/fnoc2_replace.das";
fnoc3_ais = "http://localhost/ais/fnoc3_fallback.das";
ais = new AISResources;
Resource r1(fnoc1_ais);
ais->add_resource(fnoc1, r1);
Resource r2(fnoc2_ais, fallback);
ais->add_resource(fnoc2, r2);
ais->add_resource(fnoc3, r1);
ais->add_resource(fnoc3, r2);
}
void tearDown() {
delete ais;
}
#if 0
bool re_match(Regex &r, const char *s) {
return r.match(s, strlen(s)) == (int)strlen(s);
}
#endif
CPPUNIT_TEST_SUITE( AISResourcesTest );
CPPUNIT_TEST(add_resource_test);
CPPUNIT_TEST(add_resource_vector_test);
CPPUNIT_TEST(has_resource_test);
CPPUNIT_TEST(get_resource_test);
CPPUNIT_TEST(read_database_test);
CPPUNIT_TEST(write_database_test);
CPPUNIT_TEST_SUITE_END();
void add_resource_test() {
// setUp() makes the add_resource calls. 02/13/03 jhrg
CPPUNIT_ASSERT(ais->d_db.find(fnoc1) != ais->d_db.end());
CPPUNIT_ASSERT(ais->d_db.find(fnoc1)->second.size() == 1);
CPPUNIT_ASSERT(ais->d_db.find(fnoc1)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc1)->second[0].get_rule() == overwrite);
CPPUNIT_ASSERT(ais->d_db.find(fnoc2) != ais->d_db.end());
CPPUNIT_ASSERT(ais->d_db.find(fnoc2)->second.size() == 1);
CPPUNIT_ASSERT(ais->d_db.find(fnoc2)->second[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc2)->second[0].get_rule() == fallback);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3) != ais->d_db.end());
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second.size() == 2);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[0].get_rule() == overwrite);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[1].get_rule() == fallback);
}
void add_resource_vector_test() {
AISResources *ais2 = new AISResources;
Resource r1(fnoc1_ais);
ResourceVector rv1(1, r1);
ais2->add_resource(fnoc2, rv1);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2) != ais2->d_db.end());
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second.size() == 1);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_rule() == overwrite);
Resource r2(fnoc2_ais, fallback);
ResourceVector rv2(1, r2);
ais2->add_resource(fnoc2, rv2);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2) != ais2->d_db.end());
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second.size() == 2);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_rule() == overwrite);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[1].get_rule() == fallback);
}
void has_resource_test() {
CPPUNIT_ASSERT(ais->has_resource(fnoc1));
CPPUNIT_ASSERT(ais->has_resource(fnoc2));
CPPUNIT_ASSERT(ais->has_resource(fnoc3));
}
void get_resource_test() {
ResourceVector trv1 = ais->get_resource(fnoc1);
CPPUNIT_ASSERT(trv1.size() == 1);
CPPUNIT_ASSERT(trv1[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv1[0].get_rule() == overwrite);
ResourceVector trv2 = ais->get_resource(fnoc2);
CPPUNIT_ASSERT(trv2.size() == 1);
CPPUNIT_ASSERT(trv2[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv2[0].get_rule() == fallback);
ResourceVector trv3 = ais->get_resource(fnoc3);
CPPUNIT_ASSERT(trv3.size() == 2);
CPPUNIT_ASSERT(trv3[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv3[0].get_rule() == overwrite);
CPPUNIT_ASSERT(trv3[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv3[1].get_rule() == fallback);
try {
ResourceVector trv4 = ais->get_resource("http://never");
CPPUNIT_ASSERT(!"get_resource() failed to throw NoSuchPrimaryResource");
}
catch (NoSuchPrimaryResource &nspr) {
CPPUNIT_ASSERT("get_resource() correctly threw NoSuchPrimaryResource");
}
}
void read_database_test() {
try {
AISResources *ais2 = new AISResources;
ais2->read_database("ais_testsuite/ais_database.xml");
ResourceVector trv1 = ais2->get_resource(fnoc1);
CPPUNIT_ASSERT(trv1.size() == 1);
CPPUNIT_ASSERT(trv1[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv1[0].get_rule() == overwrite);
ResourceVector trv2 = ais2->get_resource(fnoc2);
CPPUNIT_ASSERT(trv2.size() == 1);
CPPUNIT_ASSERT(trv2[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv2[0].get_rule() == replace);
ResourceVector trv3 = ais2->get_resource(fnoc3);
CPPUNIT_ASSERT(trv3.size() == 1);
CPPUNIT_ASSERT(trv3[0].get_url() == fnoc3_ais);
CPPUNIT_ASSERT(trv3[0].get_rule() == fallback);
}
catch (AISDatabaseReadFailed &adrf) {
CPPUNIT_ASSERT(!"Document not well formed and/or valid!");
}
}
void write_database_test() {
try {
ais->write_database("dummy.xml");
AISResources *ais2 = new AISResources;
ais2->read_database("ais_testsuite/ais_database.xml");
ResourceVector trv1 = ais2->get_resource(fnoc1);
CPPUNIT_ASSERT(trv1.size() == 1);
CPPUNIT_ASSERT(trv1[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv1[0].get_rule() == overwrite);
ResourceVector trv2 = ais2->get_resource(fnoc2);
CPPUNIT_ASSERT(trv2.size() == 1);
CPPUNIT_ASSERT(trv2[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv2[0].get_rule() == replace);
ResourceVector trv3 = ais2->get_resource(fnoc3);
CPPUNIT_ASSERT(trv3.size() == 1);
CPPUNIT_ASSERT(trv3[0].get_url() == fnoc3_ais);
CPPUNIT_ASSERT(trv3[0].get_rule() == fallback);
}
catch (AISDatabaseReadFailed &adrf) {
CPPUNIT_ASSERT(!"Document not well formed and/or valid!");
}
catch (AISDatabaseWriteFailed &adwf) {
CPPUNIT_ASSERT(!"Write failed!");
}
try {
ais->write_database("/dev/dummy.xml");
CPPUNIT_ASSERT(!"Write succeeded, but should not!");
}
catch (AISDatabaseWriteFailed &adwf) {
CPPUNIT_ASSERT("Write failed as intended");
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(AISResourcesTest);
int
main( int argc, char* argv[] )
{
CppUnit::TextTestRunner runner;
runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );
runner.run();
unlink("dummy.xml");
return 0;
}
// $Log: AISResourcesTest.cc,v $
// Revision 1.4 2003/02/26 00:38:57 jimg
// Changed is/has_resource_test to match the new name of the method:
// has_resource.
//
// Revision 1.3 2003/02/25 23:25:55 jimg
// Fixed for the latest rev of ais_database.xml.
//
// Revision 1.2 2003/02/21 00:14:24 jimg
// Repaired copyright.
//
// Revision 1.1 2003/02/20 23:05:57 jimg
// Added.
//
<commit_msg>Updated tests for write_database().<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2003 OPeNDAP, Inc.
// Author: James Gallagher <[email protected]>
//
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// Tests for the AISResources class.
#include <unistd.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
#include "AISResources.h"
#include "debug.h"
using namespace CppUnit;
class AISResourcesTest:public TestFixture {
private:
AISResources *ais;
string fnoc1, fnoc2, fnoc3;
string fnoc1_ais, fnoc2_ais, fnoc3_ais;
public:
AISResourcesTest() {}
~AISResourcesTest() {}
void setUp() {
fnoc1 = "http://localhost/dods-test/nph-dods/data/nc/fnoc1.nc";
fnoc2 = "http://localhost/dods-test/nph-dods/data/nc/fnoc2.nc";
fnoc3 = "http://localhost/dods-test/nph-dods/data/nc/fnoc3.nc";
fnoc1_ais = "http://localhost/ais/fnoc1.nc.das";
fnoc2_ais = "ais_testsuite/fnoc2_replace.das";
fnoc3_ais = "http://localhost/ais/fnoc3_fallback.das";
ais = new AISResources;
Resource r1(fnoc1_ais);
ais->add_resource(fnoc1, r1);
Resource r2(fnoc2_ais, fallback);
ais->add_resource(fnoc2, r2);
ais->add_resource(fnoc3, r1);
ais->add_resource(fnoc3, r2);
}
void tearDown() {
delete ais;
}
CPPUNIT_TEST_SUITE( AISResourcesTest );
CPPUNIT_TEST(add_resource_test);
CPPUNIT_TEST(add_resource_vector_test);
CPPUNIT_TEST(has_resource_test);
CPPUNIT_TEST(get_resource_test);
CPPUNIT_TEST(read_database_test);
CPPUNIT_TEST(write_database_test);
CPPUNIT_TEST_SUITE_END();
void add_resource_test() {
// setUp() makes the add_resource calls. 02/13/03 jhrg
CPPUNIT_ASSERT(ais->d_db.find(fnoc1) != ais->d_db.end());
CPPUNIT_ASSERT(ais->d_db.find(fnoc1)->second.size() == 1);
CPPUNIT_ASSERT(ais->d_db.find(fnoc1)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc1)->second[0].get_rule() == overwrite);
CPPUNIT_ASSERT(ais->d_db.find(fnoc2) != ais->d_db.end());
CPPUNIT_ASSERT(ais->d_db.find(fnoc2)->second.size() == 1);
CPPUNIT_ASSERT(ais->d_db.find(fnoc2)->second[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc2)->second[0].get_rule() == fallback);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3) != ais->d_db.end());
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second.size() == 2);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[0].get_rule() == overwrite);
CPPUNIT_ASSERT(ais->d_db.find(fnoc3)->second[1].get_rule() == fallback);
}
void add_resource_vector_test() {
AISResources *ais2 = new AISResources;
Resource r1(fnoc1_ais);
ResourceVector rv1(1, r1);
ais2->add_resource(fnoc2, rv1);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2) != ais2->d_db.end());
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second.size() == 1);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_rule() == overwrite);
Resource r2(fnoc2_ais, fallback);
ResourceVector rv2(1, r2);
ais2->add_resource(fnoc2, rv2);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2) != ais2->d_db.end());
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second.size() == 2);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[0].get_rule() == overwrite);
CPPUNIT_ASSERT(ais2->d_db.find(fnoc2)->second[1].get_rule() == fallback);
}
void has_resource_test() {
CPPUNIT_ASSERT(ais->has_resource(fnoc1));
CPPUNIT_ASSERT(ais->has_resource(fnoc2));
CPPUNIT_ASSERT(ais->has_resource(fnoc3));
}
void get_resource_test() {
ResourceVector trv1 = ais->get_resource(fnoc1);
CPPUNIT_ASSERT(trv1.size() == 1);
CPPUNIT_ASSERT(trv1[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv1[0].get_rule() == overwrite);
ResourceVector trv2 = ais->get_resource(fnoc2);
CPPUNIT_ASSERT(trv2.size() == 1);
CPPUNIT_ASSERT(trv2[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv2[0].get_rule() == fallback);
ResourceVector trv3 = ais->get_resource(fnoc3);
CPPUNIT_ASSERT(trv3.size() == 2);
CPPUNIT_ASSERT(trv3[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv3[0].get_rule() == overwrite);
CPPUNIT_ASSERT(trv3[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv3[1].get_rule() == fallback);
try {
ResourceVector trv4 = ais->get_resource("http://never");
CPPUNIT_ASSERT(!"get_resource() failed to throw NoSuchPrimaryResource");
}
catch (NoSuchPrimaryResource &nspr) {
CPPUNIT_ASSERT("get_resource() correctly threw NoSuchPrimaryResource");
}
}
void read_database_test() {
try {
AISResources *ais2 = new AISResources;
ais2->read_database("ais_testsuite/ais_database.xml");
ResourceVector trv1 = ais2->get_resource(fnoc1);
CPPUNIT_ASSERT(trv1.size() == 1);
CPPUNIT_ASSERT(trv1[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv1[0].get_rule() == overwrite);
ResourceVector trv2 = ais2->get_resource(fnoc2);
CPPUNIT_ASSERT(trv2.size() == 1);
CPPUNIT_ASSERT(trv2[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv2[0].get_rule() == replace);
ResourceVector trv3 = ais2->get_resource(fnoc3);
CPPUNIT_ASSERT(trv3.size() == 1);
CPPUNIT_ASSERT(trv3[0].get_url() == fnoc3_ais);
CPPUNIT_ASSERT(trv3[0].get_rule() == fallback);
}
catch (AISDatabaseReadFailed &adrf) {
CPPUNIT_ASSERT(!"Document not well formed and/or valid!");
}
}
void write_database_test() {
try {
ais->write_database("dummy.xml");
AISResources *ais2 = new AISResources;
ais2->read_database("dummy.xml");
ResourceVector trv1 = ais2->get_resource(fnoc1);
CPPUNIT_ASSERT(trv1.size() == 1);
CPPUNIT_ASSERT(trv1[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv1[0].get_rule() == overwrite);
ResourceVector trv2 = ais2->get_resource(fnoc2);
CPPUNIT_ASSERT(trv2.size() == 1);
CPPUNIT_ASSERT(trv2[0].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv2[0].get_rule() == fallback);
ResourceVector trv3 = ais2->get_resource(fnoc3);
CPPUNIT_ASSERT(trv3.size() == 2);
CPPUNIT_ASSERT(trv3[0].get_url() == fnoc1_ais);
CPPUNIT_ASSERT(trv3[0].get_rule() == overwrite);
CPPUNIT_ASSERT(trv3[1].get_url() == fnoc2_ais);
CPPUNIT_ASSERT(trv3[1].get_rule() == fallback);
}
catch (AISDatabaseReadFailed &adrf) {
CPPUNIT_ASSERT(!"Document not well formed and/or valid!");
}
catch (AISDatabaseWriteFailed &adwf) {
CPPUNIT_ASSERT(!"Write failed!");
}
try {
ais->write_database("/dev/dummy.xml");
CPPUNIT_ASSERT(!"Write succeeded, but should not!");
}
catch (AISDatabaseWriteFailed &adwf) {
CPPUNIT_ASSERT("Write failed as intended");
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(AISResourcesTest);
int
main( int argc, char* argv[] )
{
CppUnit::TextTestRunner runner;
runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );
runner.run();
unlink("dummy.xml");
return 0;
}
// $Log: AISResourcesTest.cc,v $
// Revision 1.5 2003/02/26 06:40:44 jimg
// Updated tests for write_database().
//
// Revision 1.4 2003/02/26 00:38:57 jimg
// Changed is/has_resource_test to match the new name of the method:
// has_resource.
//
// Revision 1.3 2003/02/25 23:25:55 jimg
// Fixed for the latest rev of ais_database.xml.
//
// Revision 1.2 2003/02/21 00:14:24 jimg
// Repaired copyright.
//
// Revision 1.1 2003/02/20 23:05:57 jimg
// Added.
//
<|endoftext|> |
<commit_before>#include <iostream>
#include <assert.h>
#include <cppdom/predicates.h>
int main()
{
cppdom::ContextPtr ctx( new cppdom::Context );
cppdom::Document doc( ctx );
std::string filename = "game.xml";
// load a xml document from a file
try
{
doc.loadFile( filename );
}
catch (cppdom::Error e)
{
std::cerr << "Error: " << e.getString() << std::endl;
if (e.getInfo().size())
{
std::cerr << "File: " << e.getInfo() << std::endl;
}
if (e.getError() != cppdom::xml_filename_invalid &&
e.getError() != cppdom::xml_file_access)
{
/*
e.show_error( ctx );
e.show_line( ctx, filename );
*/
std::cout << "Error: (need to impl the show functions)" << std::endl;
}
assert( false && "test failed" );
return false;
}
cppdom::NodePtr root = doc.getChild( "gameinput" );
// get all nodes with noattrs attributes...
cppdom::NodeList nl = root->getChildrenPred( cppdom::HasAttributeNamePredicate( "noattrs" ) );
assert( nl.size() == 1 && "test failed" );
// get all the nodes that set up Mouse devices
nl = root->getChildrenPred( cppdom::HasAttributeValuePredicate( "device", "Mouse" ) );
assert( nl.size() == 2 && "test failed" );
std::cout << "Tests Passed" << std::endl;
}
<commit_msg>Remove test that was moved to suite<commit_after><|endoftext|> |
<commit_before><commit_msg>worldserver: fix a bug with Protocol71::canSee<commit_after><|endoftext|> |
<commit_before>#include "Settings.h"
#include <Shlwapi.h>
#include <algorithm>
#include "Error.h"
#include "HotkeyActions.h"
#include "HotkeyInfo.h"
#include "Logger.h"
#include "Monitor.h"
#include "Skin.h"
#include "StringUtils.h"
#define XML_AUDIODEV "audioDeviceID"
#define XML_HIDE_WHENFULL "hideFullscreen"
#define XML_HIDEANIM "hideAnimation"
#define XML_HIDETIME "hideDelay"
#define XML_HIDESPEED "hideSpeed"
#define XML_LANGUAGE "language"
#define XML_MONITOR "monitor"
#define XML_NOTIFYICON "notifyIcon"
#define XML_ONTOP "onTop"
#define XML_OSD_OFFSET "osdEdgeOffset"
#define XML_OSD_POS "osdPosition"
#define XML_OSD_X "osdX"
#define XML_OSD_Y "osdY"
#define XML_SKIN "skin"
#define XML_SOUNDS "soundEffects"
std::wstring Settings::_appDir(L"");
Settings *Settings::instance;
std::vector<std::wstring> Settings::OSDPosNames = {
L"top",
L"left",
L"right",
L"bottom",
L"center",
L"top-left",
L"top-right",
L"bottom-left",
L"bottom-right",
L"custom"
};
std::vector<std::wstring> Settings::HideAnimNames = {
L"none",
L"fade"
};
Settings *Settings::Instance() {
if (instance == NULL) {
instance = new Settings();
}
return instance;
}
void Settings::Load() {
_file = AppDir() + L"\\Settings.xml";
CLOG(L"Loading settings file: %s", _file.c_str());
std::string u8FileName = StringUtils::Narrow(_file);
tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());
if (result != tinyxml2::XMLError::XML_SUCCESS) {
throw std::runtime_error("Failed to parse XML file");
}
_root = _xml.GetDocument()->FirstChildElement("settings");
if (_root == NULL) {
throw std::runtime_error("Could not find root XML element");
}
_skin = new Skin(SkinXML());
}
int Settings::Save() {
FILE *stream;
errno_t err = _wfopen_s(&stream, _file.c_str(), L"w");
if (err != 0) {
CLOG(L"Could not open settings file for writing!");
return 100 + err;
}
tinyxml2::XMLError result = _xml.SaveFile(stream);
fclose(stream);
return result;
}
std::wstring Settings::AppDir() {
if (_appDir.empty()) {
wchar_t path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
PathRemoveFileSpec(path);
_appDir = std::wstring(path);
}
return _appDir;
}
std::wstring Settings::SkinDir() {
return AppDir() + L"\\" + SKIN_DIR;
}
std::wstring Settings::SettingsApp() {
return Settings::AppDir() + L"\\" + SETTINGS_APP;
}
std::wstring Settings::LanguagesDir() {
return AppDir() + L"\\" + LANG_DIR;
}
void Settings::LaunchSettingsApp() {
std::wstring app = SettingsApp();
CLOG(L"Opening Settings App: %s", app.c_str());
int exec = (int) ShellExecute(
NULL, L"open", app.c_str(), NULL, NULL, SW_SHOWNORMAL);
if (exec <= 32) {
Error::ErrorMessage(GENERR_NOTFOUND, app);
}
}
std::wstring Settings::AudioDeviceID() {
return GetText(XML_AUDIODEV);
}
std::wstring Settings::LanguageName() {
std::wstring lang = GetText(XML_LANGUAGE);
if (lang == L"") {
return DEFAULT_LANGUAGE;
} else {
return lang;
}
}
bool Settings::AlwaysOnTop() {
return GetEnabled(XML_ONTOP);
}
void Settings::AlwaysOnTop(bool enable) {
SetEnabled(XML_ONTOP, enable);
}
bool Settings::HideFullscreen() {
return GetEnabled(XML_HIDE_WHENFULL);
}
void Settings::HideFullscreen(bool enable) {
SetEnabled(XML_HIDE_WHENFULL, enable);
}
std::wstring Settings::Monitor() {
return GetText(XML_MONITOR);
}
std::vector<HMONITOR> Settings::MonitorHandles() {
std::vector<HMONITOR> monitors;
std::wstring monitorStr = Monitor();
if (monitorStr == L"") {
/* Primary Monitor */
monitors.push_back(Monitor::Primary());
return monitors;
}
if (monitorStr == L"*") {
/* All Monitors */
std::unordered_map<std::wstring, HMONITOR> map = Monitor::MonitorMap();
for (auto it = map.begin(); it != map.end(); ++it) {
monitors.push_back(it->second);
}
return monitors;
}
/* Specific Monitor */
std::unordered_map<std::wstring, HMONITOR> map = Monitor::MonitorMap();
for (auto it = map.begin(); it != map.end(); ++it) {
if (monitorStr == it->first) {
monitors.push_back(it->second);
}
}
return monitors;
}
void Settings::Monitor(std::wstring monitorName) {
SetText(XML_MONITOR, StringUtils::Narrow(monitorName));
}
int Settings::OSDEdgeOffset() {
if (HasSetting(XML_OSD_OFFSET)) {
return GetInt(XML_OSD_OFFSET);
} else {
return DEFAULT_OSD_OFFSET;
}
}
void Settings::OSDEdgeOffset(int offset) {
SetInt(XML_OSD_OFFSET, offset);
}
Settings::OSDPos Settings::OSDPosition() {
std::wstring pos = GetText(XML_OSD_POS);
std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);
for (unsigned int i = 0; i < OSDPosNames.size(); ++i) {
if (pos == OSDPosNames[i]) {
return (Settings::OSDPos) i;
}
}
return DEFAULT_OSD_POS;
}
void Settings::OSDPosition(OSDPos pos) {
std::wstring posStr = OSDPosNames[(int) pos];
SetText(XML_OSD_POS, StringUtils::Narrow(posStr));
}
int Settings::OSDX() {
return GetInt(XML_OSD_X);
}
void Settings::OSDX(int x) {
SetInt(XML_OSD_X, x);
}
int Settings::OSDY() {
return GetInt(XML_OSD_Y);
}
void Settings::OSDY(int y) {
SetInt(XML_OSD_Y, y);
}
Skin *Settings::CurrentSkin() {
return _skin;
}
Settings::HideAnim Settings::HideAnimation() {
std::wstring anim = GetText(XML_HIDEANIM);
std::transform(anim.begin(), anim.end(), anim.begin(), ::tolower);
for (unsigned int i = 0; i < HideAnimNames.size(); ++i) {
if (anim == HideAnimNames[i]) {
return (Settings::HideAnim) i;
}
}
return DEFAULT_HIDE_ANIM;
}
void Settings::HideAnimation(Settings::HideAnim anim) {
std::wstring hideStr = HideAnimNames[(int) anim];
SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr));
}
int Settings::HideDelay() {
return GetInt(XML_HIDETIME);
}
void Settings::HideDelay(int delay) {
SetInt(XML_HIDETIME, delay);
}
int Settings::HideSpeed() {
return GetInt(XML_HIDESPEED);
}
void Settings::HideSpeed(int speed) {
SetInt(XML_HIDESPEED, speed);
}
bool Settings::CurrentSkin(std::wstring skinName) {
std::string name = StringUtils::Narrow(skinName);
std::wstring xml = SkinXML(skinName);
if (PathFileExists(xml.c_str()) == FALSE) {
return false;
}
SetText(XML_SKIN, name);
return true;
}
std::wstring Settings::SkinName() {
std::wstring name = GetText("skin");
if (name == L"") {
return DEFAULT_SKIN;
} else {
return name;
}
}
std::wstring Settings::SkinXML() {
return SkinXML(SkinName());
}
std::wstring Settings::SkinXML(std::wstring skinName) {
std::wstring skinXML = Settings::AppDir() + L"\\" + SKINS_DIR L"\\"
+ skinName + L"\\" SKIN_XML;
return skinXML;
}
std::unordered_map<int, HotkeyInfo> Settings::Hotkeys() {
std::unordered_map<int, HotkeyInfo> keyMappings;
tinyxml2::XMLElement *hotkeys = _root->FirstChildElement("hotkeys");
if (hotkeys == NULL) {
return keyMappings;
}
tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement("hotkey");
for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {
int action = -1;
hotkey->QueryIntAttribute("action", &action);
if (action == -1) {
CLOG(L"No action provided for hotkey; skipping");
continue;
}
int combination = -1;
hotkey->QueryIntAttribute("combination", &combination);
if (combination == -1) {
CLOG(L"No key combination provided for hotkey; skipping");
continue;
}
HotkeyInfo hki;
hki.action = action;
hki.keyCombination = combination;
/* Does this hotkey action have any arguments? */
tinyxml2::XMLElement *arg = hotkey->FirstChildElement("arg");
for (; arg != NULL; arg = arg->NextSiblingElement()) {
const char *argStr = arg->GetText();
hki.args.push_back(StringUtils::Widen(argStr));
}
/* Whew, we made it! */
CLOG(L"Adding hotkey mapping: %d -> %d", combination, action);
CLOG(L"%s", hki.ToString().c_str());
keyMappings[combination] = hki;
}
return keyMappings;
}
void Settings::Hotkeys(std::vector<HotkeyInfo> hotkeys) {
tinyxml2::XMLElement *hkElem = GetOrCreateElement("hotkeys");
hkElem->DeleteChildren();
for (HotkeyInfo hotkey : hotkeys) {
OutputDebugString(L"key");
tinyxml2::XMLElement *hk = _xml.NewElement("hotkey");
hk->SetAttribute("combination", hotkey.keyCombination);
hk->SetAttribute("action", hotkey.action);
if (hotkey.args.size() > 0) {
for (std::wstring arg : hotkey.args) {
tinyxml2::XMLElement *argElem = _xml.NewElement("arg");
argElem->SetText(StringUtils::Narrow(arg).c_str());
hk->InsertEndChild(argElem);
}
}
hkElem->InsertEndChild(hk);
}
}
bool Settings::NotifyIconEnabled() {
return GetEnabled(XML_NOTIFYICON);
}
void Settings::NotifyIconEnabled(bool enable) {
SetEnabled(XML_NOTIFYICON, enable);
}
bool Settings::SoundEffectsEnabled() {
return GetEnabled(XML_SOUNDS);
}
void Settings::SoundEffectsEnabled(bool enable) {
SetEnabled(XML_SOUNDS, enable);
}
bool Settings::HasSetting(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
return (el != NULL);
}
bool Settings::GetEnabled(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
CLOG(L"Warning: XML element '%s' not found", elementName.c_str());
return false;
} else {
bool val = false;
el->QueryBoolText(&val);
return val;
}
}
void Settings::SetEnabled(std::string elementName, bool enabled) {
tinyxml2::XMLElement *el = GetOrCreateElement(elementName);
el->SetText(enabled ? "true" : "false");
}
std::wstring Settings::GetText(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
CLOG(L"Warning: XML element %s not found",
StringUtils::Widen(elementName).c_str());
return L"";
}
const char* str = el->GetText();
if (str == NULL) {
return L"";
} else {
return StringUtils::Widen(str);
}
}
void Settings::SetText(std::string elementName, std::string text) {
tinyxml2::XMLElement *el = GetOrCreateElement(elementName);
el->SetText(text.c_str());
}
int Settings::GetInt(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
CLOG(L"Warning: XML element '%s' not found", elementName.c_str());
return 0;
}
int val = 0;
el->QueryIntText(&val);
return val;
}
void Settings::SetInt(std::string elementName, int value) {
tinyxml2::XMLElement *el = GetOrCreateElement(elementName);
el->SetText(value);
}
tinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
el = _xml.NewElement(elementName.c_str());
_root->InsertEndChild(el);
}
return el;
}<commit_msg>Remove debug string<commit_after>#include "Settings.h"
#include <Shlwapi.h>
#include <algorithm>
#include "Error.h"
#include "HotkeyActions.h"
#include "HotkeyInfo.h"
#include "Logger.h"
#include "Monitor.h"
#include "Skin.h"
#include "StringUtils.h"
#define XML_AUDIODEV "audioDeviceID"
#define XML_HIDE_WHENFULL "hideFullscreen"
#define XML_HIDEANIM "hideAnimation"
#define XML_HIDETIME "hideDelay"
#define XML_HIDESPEED "hideSpeed"
#define XML_LANGUAGE "language"
#define XML_MONITOR "monitor"
#define XML_NOTIFYICON "notifyIcon"
#define XML_ONTOP "onTop"
#define XML_OSD_OFFSET "osdEdgeOffset"
#define XML_OSD_POS "osdPosition"
#define XML_OSD_X "osdX"
#define XML_OSD_Y "osdY"
#define XML_SKIN "skin"
#define XML_SOUNDS "soundEffects"
std::wstring Settings::_appDir(L"");
Settings *Settings::instance;
std::vector<std::wstring> Settings::OSDPosNames = {
L"top",
L"left",
L"right",
L"bottom",
L"center",
L"top-left",
L"top-right",
L"bottom-left",
L"bottom-right",
L"custom"
};
std::vector<std::wstring> Settings::HideAnimNames = {
L"none",
L"fade"
};
Settings *Settings::Instance() {
if (instance == NULL) {
instance = new Settings();
}
return instance;
}
void Settings::Load() {
_file = AppDir() + L"\\Settings.xml";
CLOG(L"Loading settings file: %s", _file.c_str());
std::string u8FileName = StringUtils::Narrow(_file);
tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());
if (result != tinyxml2::XMLError::XML_SUCCESS) {
throw std::runtime_error("Failed to parse XML file");
}
_root = _xml.GetDocument()->FirstChildElement("settings");
if (_root == NULL) {
throw std::runtime_error("Could not find root XML element");
}
_skin = new Skin(SkinXML());
}
int Settings::Save() {
FILE *stream;
errno_t err = _wfopen_s(&stream, _file.c_str(), L"w");
if (err != 0) {
CLOG(L"Could not open settings file for writing!");
return 100 + err;
}
tinyxml2::XMLError result = _xml.SaveFile(stream);
fclose(stream);
return result;
}
std::wstring Settings::AppDir() {
if (_appDir.empty()) {
wchar_t path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
PathRemoveFileSpec(path);
_appDir = std::wstring(path);
}
return _appDir;
}
std::wstring Settings::SkinDir() {
return AppDir() + L"\\" + SKIN_DIR;
}
std::wstring Settings::SettingsApp() {
return Settings::AppDir() + L"\\" + SETTINGS_APP;
}
std::wstring Settings::LanguagesDir() {
return AppDir() + L"\\" + LANG_DIR;
}
void Settings::LaunchSettingsApp() {
std::wstring app = SettingsApp();
CLOG(L"Opening Settings App: %s", app.c_str());
int exec = (int) ShellExecute(
NULL, L"open", app.c_str(), NULL, NULL, SW_SHOWNORMAL);
if (exec <= 32) {
Error::ErrorMessage(GENERR_NOTFOUND, app);
}
}
std::wstring Settings::AudioDeviceID() {
return GetText(XML_AUDIODEV);
}
std::wstring Settings::LanguageName() {
std::wstring lang = GetText(XML_LANGUAGE);
if (lang == L"") {
return DEFAULT_LANGUAGE;
} else {
return lang;
}
}
bool Settings::AlwaysOnTop() {
return GetEnabled(XML_ONTOP);
}
void Settings::AlwaysOnTop(bool enable) {
SetEnabled(XML_ONTOP, enable);
}
bool Settings::HideFullscreen() {
return GetEnabled(XML_HIDE_WHENFULL);
}
void Settings::HideFullscreen(bool enable) {
SetEnabled(XML_HIDE_WHENFULL, enable);
}
std::wstring Settings::Monitor() {
return GetText(XML_MONITOR);
}
std::vector<HMONITOR> Settings::MonitorHandles() {
std::vector<HMONITOR> monitors;
std::wstring monitorStr = Monitor();
if (monitorStr == L"") {
/* Primary Monitor */
monitors.push_back(Monitor::Primary());
return monitors;
}
if (monitorStr == L"*") {
/* All Monitors */
std::unordered_map<std::wstring, HMONITOR> map = Monitor::MonitorMap();
for (auto it = map.begin(); it != map.end(); ++it) {
monitors.push_back(it->second);
}
return monitors;
}
/* Specific Monitor */
std::unordered_map<std::wstring, HMONITOR> map = Monitor::MonitorMap();
for (auto it = map.begin(); it != map.end(); ++it) {
if (monitorStr == it->first) {
monitors.push_back(it->second);
}
}
return monitors;
}
void Settings::Monitor(std::wstring monitorName) {
SetText(XML_MONITOR, StringUtils::Narrow(monitorName));
}
int Settings::OSDEdgeOffset() {
if (HasSetting(XML_OSD_OFFSET)) {
return GetInt(XML_OSD_OFFSET);
} else {
return DEFAULT_OSD_OFFSET;
}
}
void Settings::OSDEdgeOffset(int offset) {
SetInt(XML_OSD_OFFSET, offset);
}
Settings::OSDPos Settings::OSDPosition() {
std::wstring pos = GetText(XML_OSD_POS);
std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);
for (unsigned int i = 0; i < OSDPosNames.size(); ++i) {
if (pos == OSDPosNames[i]) {
return (Settings::OSDPos) i;
}
}
return DEFAULT_OSD_POS;
}
void Settings::OSDPosition(OSDPos pos) {
std::wstring posStr = OSDPosNames[(int) pos];
SetText(XML_OSD_POS, StringUtils::Narrow(posStr));
}
int Settings::OSDX() {
return GetInt(XML_OSD_X);
}
void Settings::OSDX(int x) {
SetInt(XML_OSD_X, x);
}
int Settings::OSDY() {
return GetInt(XML_OSD_Y);
}
void Settings::OSDY(int y) {
SetInt(XML_OSD_Y, y);
}
Skin *Settings::CurrentSkin() {
return _skin;
}
Settings::HideAnim Settings::HideAnimation() {
std::wstring anim = GetText(XML_HIDEANIM);
std::transform(anim.begin(), anim.end(), anim.begin(), ::tolower);
for (unsigned int i = 0; i < HideAnimNames.size(); ++i) {
if (anim == HideAnimNames[i]) {
return (Settings::HideAnim) i;
}
}
return DEFAULT_HIDE_ANIM;
}
void Settings::HideAnimation(Settings::HideAnim anim) {
std::wstring hideStr = HideAnimNames[(int) anim];
SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr));
}
int Settings::HideDelay() {
return GetInt(XML_HIDETIME);
}
void Settings::HideDelay(int delay) {
SetInt(XML_HIDETIME, delay);
}
int Settings::HideSpeed() {
return GetInt(XML_HIDESPEED);
}
void Settings::HideSpeed(int speed) {
SetInt(XML_HIDESPEED, speed);
}
bool Settings::CurrentSkin(std::wstring skinName) {
std::string name = StringUtils::Narrow(skinName);
std::wstring xml = SkinXML(skinName);
if (PathFileExists(xml.c_str()) == FALSE) {
return false;
}
SetText(XML_SKIN, name);
return true;
}
std::wstring Settings::SkinName() {
std::wstring name = GetText("skin");
if (name == L"") {
return DEFAULT_SKIN;
} else {
return name;
}
}
std::wstring Settings::SkinXML() {
return SkinXML(SkinName());
}
std::wstring Settings::SkinXML(std::wstring skinName) {
std::wstring skinXML = Settings::AppDir() + L"\\" + SKINS_DIR L"\\"
+ skinName + L"\\" SKIN_XML;
return skinXML;
}
std::unordered_map<int, HotkeyInfo> Settings::Hotkeys() {
std::unordered_map<int, HotkeyInfo> keyMappings;
tinyxml2::XMLElement *hotkeys = _root->FirstChildElement("hotkeys");
if (hotkeys == NULL) {
return keyMappings;
}
tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement("hotkey");
for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {
int action = -1;
hotkey->QueryIntAttribute("action", &action);
if (action == -1) {
CLOG(L"No action provided for hotkey; skipping");
continue;
}
int combination = -1;
hotkey->QueryIntAttribute("combination", &combination);
if (combination == -1) {
CLOG(L"No key combination provided for hotkey; skipping");
continue;
}
HotkeyInfo hki;
hki.action = action;
hki.keyCombination = combination;
/* Does this hotkey action have any arguments? */
tinyxml2::XMLElement *arg = hotkey->FirstChildElement("arg");
for (; arg != NULL; arg = arg->NextSiblingElement()) {
const char *argStr = arg->GetText();
hki.args.push_back(StringUtils::Widen(argStr));
}
/* Whew, we made it! */
CLOG(L"Adding hotkey mapping: %d -> %d", combination, action);
CLOG(L"%s", hki.ToString().c_str());
keyMappings[combination] = hki;
}
return keyMappings;
}
void Settings::Hotkeys(std::vector<HotkeyInfo> hotkeys) {
tinyxml2::XMLElement *hkElem = GetOrCreateElement("hotkeys");
hkElem->DeleteChildren();
for (HotkeyInfo hotkey : hotkeys) {
tinyxml2::XMLElement *hk = _xml.NewElement("hotkey");
hk->SetAttribute("combination", hotkey.keyCombination);
hk->SetAttribute("action", hotkey.action);
if (hotkey.args.size() > 0) {
for (std::wstring arg : hotkey.args) {
tinyxml2::XMLElement *argElem = _xml.NewElement("arg");
argElem->SetText(StringUtils::Narrow(arg).c_str());
hk->InsertEndChild(argElem);
}
}
hkElem->InsertEndChild(hk);
}
}
bool Settings::NotifyIconEnabled() {
return GetEnabled(XML_NOTIFYICON);
}
void Settings::NotifyIconEnabled(bool enable) {
SetEnabled(XML_NOTIFYICON, enable);
}
bool Settings::SoundEffectsEnabled() {
return GetEnabled(XML_SOUNDS);
}
void Settings::SoundEffectsEnabled(bool enable) {
SetEnabled(XML_SOUNDS, enable);
}
bool Settings::HasSetting(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
return (el != NULL);
}
bool Settings::GetEnabled(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
CLOG(L"Warning: XML element '%s' not found", elementName.c_str());
return false;
} else {
bool val = false;
el->QueryBoolText(&val);
return val;
}
}
void Settings::SetEnabled(std::string elementName, bool enabled) {
tinyxml2::XMLElement *el = GetOrCreateElement(elementName);
el->SetText(enabled ? "true" : "false");
}
std::wstring Settings::GetText(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
CLOG(L"Warning: XML element %s not found",
StringUtils::Widen(elementName).c_str());
return L"";
}
const char* str = el->GetText();
if (str == NULL) {
return L"";
} else {
return StringUtils::Widen(str);
}
}
void Settings::SetText(std::string elementName, std::string text) {
tinyxml2::XMLElement *el = GetOrCreateElement(elementName);
el->SetText(text.c_str());
}
int Settings::GetInt(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
CLOG(L"Warning: XML element '%s' not found", elementName.c_str());
return 0;
}
int val = 0;
el->QueryIntText(&val);
return val;
}
void Settings::SetInt(std::string elementName, int value) {
tinyxml2::XMLElement *el = GetOrCreateElement(elementName);
el->SetText(value);
}
tinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) {
tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());
if (el == NULL) {
el = _xml.NewElement(elementName.c_str());
_root->InsertEndChild(el);
}
return el;
}<|endoftext|> |
<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#define LOG_TAG "ArmnnDriver"
#include "ArmnnDriverImpl.hpp"
#include "ArmnnPreparedModel.hpp"
#ifdef ARMNN_ANDROID_NN_V1_2 // Using ::android::hardware::neuralnetworks::V1_2
#include "ArmnnPreparedModel_1_2.hpp"
#endif
#include "ModelToINetworkConverter.hpp"
#include "SystemPropertiesUtils.hpp"
#include <ValidateHal.h>
#include <log/log.h>
using namespace std;
using namespace android;
using namespace android::nn;
using namespace android::hardware;
namespace
{
void NotifyCallbackAndCheck(const sp<V1_0::IPreparedModelCallback>& callback,
ErrorStatus errorStatus,
const sp<V1_0::IPreparedModel>& preparedModelPtr)
{
Return<void> returned = callback->notify(errorStatus, preparedModelPtr);
// This check is required, if the callback fails and it isn't checked it will bring down the service
if (!returned.isOk())
{
ALOGE("ArmnnDriverImpl::prepareModel: hidl callback failed to return properly: %s ",
returned.description().c_str());
}
}
Return<ErrorStatus> FailPrepareModel(ErrorStatus error,
const string& message,
const sp<V1_0::IPreparedModelCallback>& callback)
{
ALOGW("ArmnnDriverImpl::prepareModel: %s", message.c_str());
NotifyCallbackAndCheck(callback, error, nullptr);
return error;
}
} // namespace
namespace armnn_driver
{
template<typename HalPolicy>
Return<ErrorStatus> ArmnnDriverImpl<HalPolicy>::prepareModel(
const armnn::IRuntimePtr& runtime,
const armnn::IGpuAccTunedParametersPtr& clTunedParameters,
const DriverOptions& options,
const HalModel& model,
const sp<V1_0::IPreparedModelCallback>& cb,
bool float32ToFloat16)
{
ALOGV("ArmnnDriverImpl::prepareModel()");
if (cb.get() == nullptr)
{
ALOGW("ArmnnDriverImpl::prepareModel: Invalid callback passed to prepareModel");
return ErrorStatus::INVALID_ARGUMENT;
}
if (!runtime)
{
return FailPrepareModel(ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb);
}
if (!android::nn::validateModel(model))
{
return FailPrepareModel(ErrorStatus::INVALID_ARGUMENT, "Invalid model passed as input", cb);
}
// Deliberately ignore any unsupported operations requested by the options -
// at this point we're being asked to prepare a model that we've already declared support for
// and the operation indices may be different to those in getSupportedOperations anyway.
set<unsigned int> unsupportedOperations;
ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(),
model,
unsupportedOperations);
if (modelConverter.GetConversionResult() != ConversionResult::Success)
{
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "ModelToINetworkConverter failed", cb);
return ErrorStatus::NONE;
}
// Optimize the network
armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr);
armnn::OptimizerOptions OptOptions;
OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16;
std::vector<std::string> errMessages;
try
{
optNet = armnn::Optimize(*modelConverter.GetINetwork(),
options.GetBackends(),
runtime->GetDeviceSpec(),
OptOptions,
errMessages);
}
catch (armnn::Exception &e)
{
stringstream message;
message << "armnn::Exception (" << e.what() << ") caught from optimize.";
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb);
return ErrorStatus::NONE;
}
// Check that the optimized network is valid.
if (!optNet)
{
stringstream message;
message << "Invalid optimized network";
for (const string& msg : errMessages)
{
message << "\n" << msg;
}
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb);
return ErrorStatus::NONE;
}
// Export the optimized network graph to a dot file if an output dump directory
// has been specified in the drivers' arguments.
ExportNetworkGraphToDotFile<HalModel>(*optNet, options.GetRequestInputsAndOutputsDumpDir(), model);
// Load it into the runtime.
armnn::NetworkId netId = 0;
try
{
if (runtime->LoadNetwork(netId, move(optNet)) != armnn::Status::Success)
{
return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be loaded", cb);
}
}
catch (armnn::Exception& e)
{
stringstream message;
message << "armnn::Exception (" << e.what()<< ") caught from LoadNetwork.";
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb);
return ErrorStatus::NONE;
}
unique_ptr<ArmnnPreparedModel<HalPolicy>> preparedModel(
new ArmnnPreparedModel<HalPolicy>(
netId,
runtime.get(),
model,
options.GetRequestInputsAndOutputsDumpDir(),
options.IsGpuProfilingEnabled()));
// Run a single 'dummy' inference of the model. This means that CL kernels will get compiled (and tuned if
// this is enabled) before the first 'real' inference which removes the overhead of the first inference.
if (!preparedModel->ExecuteWithDummyInputs())
{
return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be executed", cb);
}
if (clTunedParameters &&
options.GetClTunedParametersMode() == armnn::IGpuAccTunedParameters::Mode::UpdateTunedParameters)
{
// Now that we've done one inference the CL kernel parameters will have been tuned, so save the updated file.
try
{
clTunedParameters->Save(options.GetClTunedParametersFile().c_str());
}
catch (const armnn::Exception& error)
{
ALOGE("ArmnnDriverImpl::prepareModel: Failed to save CL tuned parameters file '%s': %s",
options.GetClTunedParametersFile().c_str(), error.what());
}
}
NotifyCallbackAndCheck(cb, ErrorStatus::NONE, preparedModel.release());
return ErrorStatus::NONE;
}
template<typename HalPolicy>
Return<void> ArmnnDriverImpl<HalPolicy>::getSupportedOperations(const armnn::IRuntimePtr& runtime,
const DriverOptions& options,
const HalModel& model,
HalGetSupportedOperations_cb cb)
{
ALOGV("ArmnnDriverImpl::getSupportedOperations()");
vector<bool> result;
if (!runtime)
{
cb(ErrorStatus::DEVICE_UNAVAILABLE, result);
return Void();
}
// Run general model validation, if this doesn't pass we shouldn't analyse the model anyway.
if (!android::nn::validateModel(model))
{
cb(ErrorStatus::INVALID_ARGUMENT, result);
return Void();
}
// Attempt to convert the model to an ArmNN input network (INetwork).
ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(),
model,
options.GetForcedUnsupportedOperations());
if (modelConverter.GetConversionResult() != ConversionResult::Success
&& modelConverter.GetConversionResult() != ConversionResult::UnsupportedFeature)
{
cb(ErrorStatus::GENERAL_FAILURE, result);
return Void();
}
// Check each operation if it was converted successfully and copy the flags
// into the result (vector<bool>) that we need to return to Android.
result.reserve(model.operations.size());
for (uint32_t operationIdx = 0; operationIdx < model.operations.size(); operationIdx++)
{
bool operationSupported = modelConverter.IsOperationSupported(operationIdx);
result.push_back(operationSupported);
}
cb(ErrorStatus::NONE, result);
return Void();
}
template<typename HalPolicy>
Return<DeviceStatus> ArmnnDriverImpl<HalPolicy>::getStatus()
{
ALOGV("ArmnnDriver::getStatus()");
return DeviceStatus::AVAILABLE;
}
///
/// Class template specializations
///
template class ArmnnDriverImpl<hal_1_0::HalPolicy>;
#ifdef ARMNN_ANDROID_NN_V1_1
template class ArmnnDriverImpl<hal_1_1::HalPolicy>;
#endif
#ifdef ARMNN_ANDROID_NN_V1_2
template class ArmnnDriverImpl<hal_1_1::HalPolicy>;
template class ArmnnDriverImpl<hal_1_2::HalPolicy>;
#endif
} // namespace armnn_driver
<commit_msg>IVGCVSW-3987 Fix for potential unique_ptr.release() bug<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#define LOG_TAG "ArmnnDriver"
#include "ArmnnDriverImpl.hpp"
#include "ArmnnPreparedModel.hpp"
#ifdef ARMNN_ANDROID_NN_V1_2 // Using ::android::hardware::neuralnetworks::V1_2
#include "ArmnnPreparedModel_1_2.hpp"
#endif
#include "ModelToINetworkConverter.hpp"
#include "SystemPropertiesUtils.hpp"
#include <ValidateHal.h>
#include <log/log.h>
using namespace std;
using namespace android;
using namespace android::nn;
using namespace android::hardware;
namespace
{
void NotifyCallbackAndCheck(const sp<V1_0::IPreparedModelCallback>& callback,
ErrorStatus errorStatus,
const sp<V1_0::IPreparedModel>& preparedModelPtr)
{
Return<void> returned = callback->notify(errorStatus, preparedModelPtr);
// This check is required, if the callback fails and it isn't checked it will bring down the service
if (!returned.isOk())
{
ALOGE("ArmnnDriverImpl::prepareModel: hidl callback failed to return properly: %s ",
returned.description().c_str());
}
}
Return<ErrorStatus> FailPrepareModel(ErrorStatus error,
const string& message,
const sp<V1_0::IPreparedModelCallback>& callback)
{
ALOGW("ArmnnDriverImpl::prepareModel: %s", message.c_str());
NotifyCallbackAndCheck(callback, error, nullptr);
return error;
}
} // namespace
namespace armnn_driver
{
template<typename HalPolicy>
Return<ErrorStatus> ArmnnDriverImpl<HalPolicy>::prepareModel(
const armnn::IRuntimePtr& runtime,
const armnn::IGpuAccTunedParametersPtr& clTunedParameters,
const DriverOptions& options,
const HalModel& model,
const sp<V1_0::IPreparedModelCallback>& cb,
bool float32ToFloat16)
{
ALOGV("ArmnnDriverImpl::prepareModel()");
if (cb.get() == nullptr)
{
ALOGW("ArmnnDriverImpl::prepareModel: Invalid callback passed to prepareModel");
return ErrorStatus::INVALID_ARGUMENT;
}
if (!runtime)
{
return FailPrepareModel(ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb);
}
if (!android::nn::validateModel(model))
{
return FailPrepareModel(ErrorStatus::INVALID_ARGUMENT, "Invalid model passed as input", cb);
}
// Deliberately ignore any unsupported operations requested by the options -
// at this point we're being asked to prepare a model that we've already declared support for
// and the operation indices may be different to those in getSupportedOperations anyway.
set<unsigned int> unsupportedOperations;
ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(),
model,
unsupportedOperations);
if (modelConverter.GetConversionResult() != ConversionResult::Success)
{
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "ModelToINetworkConverter failed", cb);
return ErrorStatus::NONE;
}
// Optimize the network
armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr);
armnn::OptimizerOptions OptOptions;
OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16;
std::vector<std::string> errMessages;
try
{
optNet = armnn::Optimize(*modelConverter.GetINetwork(),
options.GetBackends(),
runtime->GetDeviceSpec(),
OptOptions,
errMessages);
}
catch (armnn::Exception &e)
{
stringstream message;
message << "armnn::Exception (" << e.what() << ") caught from optimize.";
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb);
return ErrorStatus::NONE;
}
// Check that the optimized network is valid.
if (!optNet)
{
stringstream message;
message << "Invalid optimized network";
for (const string& msg : errMessages)
{
message << "\n" << msg;
}
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb);
return ErrorStatus::NONE;
}
// Export the optimized network graph to a dot file if an output dump directory
// has been specified in the drivers' arguments.
ExportNetworkGraphToDotFile<HalModel>(*optNet, options.GetRequestInputsAndOutputsDumpDir(), model);
// Load it into the runtime.
armnn::NetworkId netId = 0;
try
{
if (runtime->LoadNetwork(netId, move(optNet)) != armnn::Status::Success)
{
return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be loaded", cb);
}
}
catch (armnn::Exception& e)
{
stringstream message;
message << "armnn::Exception (" << e.what()<< ") caught from LoadNetwork.";
FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb);
return ErrorStatus::NONE;
}
sp<ArmnnPreparedModel<HalPolicy>> preparedModel(
new ArmnnPreparedModel<HalPolicy>(
netId,
runtime.get(),
model,
options.GetRequestInputsAndOutputsDumpDir(),
options.IsGpuProfilingEnabled()));
// Run a single 'dummy' inference of the model. This means that CL kernels will get compiled (and tuned if
// this is enabled) before the first 'real' inference which removes the overhead of the first inference.
if (!preparedModel->ExecuteWithDummyInputs())
{
return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be executed", cb);
}
if (clTunedParameters &&
options.GetClTunedParametersMode() == armnn::IGpuAccTunedParameters::Mode::UpdateTunedParameters)
{
// Now that we've done one inference the CL kernel parameters will have been tuned, so save the updated file.
try
{
clTunedParameters->Save(options.GetClTunedParametersFile().c_str());
}
catch (const armnn::Exception& error)
{
ALOGE("ArmnnDriverImpl::prepareModel: Failed to save CL tuned parameters file '%s': %s",
options.GetClTunedParametersFile().c_str(), error.what());
}
}
NotifyCallbackAndCheck(cb, ErrorStatus::NONE, preparedModel);
return ErrorStatus::NONE;
}
template<typename HalPolicy>
Return<void> ArmnnDriverImpl<HalPolicy>::getSupportedOperations(const armnn::IRuntimePtr& runtime,
const DriverOptions& options,
const HalModel& model,
HalGetSupportedOperations_cb cb)
{
ALOGV("ArmnnDriverImpl::getSupportedOperations()");
vector<bool> result;
if (!runtime)
{
cb(ErrorStatus::DEVICE_UNAVAILABLE, result);
return Void();
}
// Run general model validation, if this doesn't pass we shouldn't analyse the model anyway.
if (!android::nn::validateModel(model))
{
cb(ErrorStatus::INVALID_ARGUMENT, result);
return Void();
}
// Attempt to convert the model to an ArmNN input network (INetwork).
ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(),
model,
options.GetForcedUnsupportedOperations());
if (modelConverter.GetConversionResult() != ConversionResult::Success
&& modelConverter.GetConversionResult() != ConversionResult::UnsupportedFeature)
{
cb(ErrorStatus::GENERAL_FAILURE, result);
return Void();
}
// Check each operation if it was converted successfully and copy the flags
// into the result (vector<bool>) that we need to return to Android.
result.reserve(model.operations.size());
for (uint32_t operationIdx = 0; operationIdx < model.operations.size(); operationIdx++)
{
bool operationSupported = modelConverter.IsOperationSupported(operationIdx);
result.push_back(operationSupported);
}
cb(ErrorStatus::NONE, result);
return Void();
}
template<typename HalPolicy>
Return<DeviceStatus> ArmnnDriverImpl<HalPolicy>::getStatus()
{
ALOGV("ArmnnDriver::getStatus()");
return DeviceStatus::AVAILABLE;
}
///
/// Class template specializations
///
template class ArmnnDriverImpl<hal_1_0::HalPolicy>;
#ifdef ARMNN_ANDROID_NN_V1_1
template class ArmnnDriverImpl<hal_1_1::HalPolicy>;
#endif
#ifdef ARMNN_ANDROID_NN_V1_2
template class ArmnnDriverImpl<hal_1_1::HalPolicy>;
template class ArmnnDriverImpl<hal_1_2::HalPolicy>;
#endif
} // namespace armnn_driver
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: PagePropertySetContext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:21:13 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#define _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#ifndef _XMLOFF_XMLPROPERTYSETCONTEXT_HXX
#include "xmlprcon.hxx"
#endif
enum PageContextType
{
Page,
Header,
Footer
};
class PagePropertySetContext : public SvXMLPropertySetContext
{
PageContextType aType;
public:
PagePropertySetContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList >& xAttrList,
sal_uInt32 nFam,
::std::vector< XMLPropertyState > &rProps,
const UniReference < SvXMLImportPropertyMapper > &rMap,
sal_Int32 nStartIndex, sal_Int32 nEndIndex,
const PageContextType aType );
virtual ~PagePropertySetContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList,
::std::vector< XMLPropertyState > &rProperties,
const XMLPropertyState& rProp);
};
#endif // _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.298); FILE MERGED 2005/09/05 14:39:15 rt 1.3.298.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PagePropertySetContext.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:29:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#define _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#ifndef _XMLOFF_XMLPROPERTYSETCONTEXT_HXX
#include "xmlprcon.hxx"
#endif
enum PageContextType
{
Page,
Header,
Footer
};
class PagePropertySetContext : public SvXMLPropertySetContext
{
PageContextType aType;
public:
PagePropertySetContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList >& xAttrList,
sal_uInt32 nFam,
::std::vector< XMLPropertyState > &rProps,
const UniReference < SvXMLImportPropertyMapper > &rMap,
sal_Int32 nStartIndex, sal_Int32 nEndIndex,
const PageContextType aType );
virtual ~PagePropertySetContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList,
::std::vector< XMLPropertyState > &rProperties,
const XMLPropertyState& rProp);
};
#endif // _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EventOASISTContext.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2008-03-12 11:14:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif
#include <hash_map>
using ::rtl::OUString;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
class XMLTransformerOASISEventMap_Impl:
public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
NameHash_Impl, NameHash_Impl >
{
public:
XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
~XMLTransformerOASISEventMap_Impl();
};
XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
if( pInit )
{
XMLTransformerOASISEventMap_Impl::key_type aKey;
XMLTransformerOASISEventMap_Impl::data_type aData;
while( pInit->m_pOASISName )
{
aKey.m_nPrefix = pInit->m_nOASISPrefix;
aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);
OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );
aData = OUString::createFromAscii(pInit->m_pOOoName);
XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );
insert( aVal );
++pInit;
}
}
}
XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);
XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLRenameElemTransformerContext( rImp, rQName,
rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}
XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateFormEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}
void XMLEventOASISTransformerContext::FlushEventMap(
XMLTransformerOASISEventMap_Impl *p )
{
delete p;
}
OUString XMLEventOASISTransformerContext::GetEventName(
sal_uInt16 nPrefix,
const OUString& rName,
XMLTransformerOASISEventMap_Impl& rMap,
XMLTransformerOASISEventMap_Impl *pMap2)
{
XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
if( pMap2 )
{
XMLTransformerOASISEventMap_Impl::const_iterator aIter =
pMap2->find( aKey );
if( !(aIter == pMap2->end()) )
return (*aIter).second;
}
XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
if( aIter == rMap.end() )
return rName;
else
return (*aIter).second;
}
bool ParseURLAsString(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );
sal_Int32 params = rAttrValue.indexOf( '?' );
if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
{
return FALSE;
}
sal_Int32 start = SCHEME.getLength();
*pName = rAttrValue.copy( start, params - start );
OUString aToken;
OUString aLanguage;
params++;
do
{
aToken = rAttrValue.getToken( 0, '&', params );
sal_Int32 dummy = 0;
if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
{
aLanguage = aToken.getToken( 1, '=', dummy );
}
else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
{
OUString tmp = aToken.getToken( 1, '=', dummy );
if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
{
*pLocation = GetXMLToken( XML_DOCUMENT );
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
}
} while ( params >= 0 );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
return TRUE;
}
return FALSE;
}
bool ParseURL(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
return ParseURLAsString( rAttrValue, pName, pLocation );
#else
Reference< com::sun::star::lang::XMultiServiceFactory >
xSMgr = ::comphelper::getProcessServiceFactory();
Reference< com::sun::star::uri::XUriReferenceFactory >
xFactory( xSMgr->createInstance( OUString::createFromAscii(
"com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );
if ( xFactory.is() )
{
Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
xFactory->parse( rAttrValue ), UNO_QUERY );
if ( xUrl.is() )
{
OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
{
OUString aLanguage = xUrl->getParameter( aLanguageKey );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
*pName = xUrl->getName();
OUString tmp =
xUrl->getParameter( GetXMLToken( XML_LOCATION ) );
OUString doc = GetXMLToken( XML_DOCUMENT );
if ( tmp.equalsIgnoreAsciiCase( doc ) )
{
*pLocation = doc;
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
return TRUE;
}
}
}
return FALSE;
}
else
{
return ParseURLAsString( rAttrValue, pName, pLocation );
}
#endif
}
void XMLEventOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
OSL_TRACE("XMLEventOASISTransformerContext::StartElement");
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_HREF:
{
OUString aAttrValue( rAttrValue );
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->RemoveAttributeByIndex( i );
OUString aAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
}
break;
case XML_ATACTION_EVENT_NAME:
{
// Check if the event belongs to a form or control by
// cehcking the 2nd ancestor element, f.i.:
// <form:button><form:event-listeners><form:event-listener>
const XMLTransformerContext *pObjContext =
GetTransformer().GetAncestorContext( 1 );
sal_Bool bForm = pObjContext &&
pObjContext->HasNamespace(XML_NAMESPACE_FORM );
pMutableAttrList->SetValueByIndex( i,
GetTransformer().GetEventName( rAttrValue,
bForm ) );
}
break;
case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
{
OUString aAttrValue( rAttrValue );
sal_uInt16 nValPrefix =
static_cast<sal_uInt16>((*aIter).second.m_nParam1);
if( GetTransformer().RemoveNamespacePrefix(
aAttrValue, nValPrefix ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_MACRO_NAME:
{
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->SetValueByIndex( i, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
else
{
const OUString& rApp = GetXMLToken( XML_APPLICATION );
const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
OUString aAttrValue;
if( rAttrValue.getLength() > rApp.getLength()+1 &&
rAttrValue.copy(0,rApp.getLength()).
equalsIgnoreAsciiCase( rApp ) &&
':' == rAttrValue[rApp.getLength()] )
{
aLocation = rApp;
aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
}
else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
rAttrValue.copy(0,rDoc.getLength()).
equalsIgnoreAsciiCase( rDoc ) &&
':' == rAttrValue[rDoc.getLength()] )
{
aLocation= rDoc;
aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
}
if( aAttrValue.getLength() )
pMutableAttrList->SetValueByIndex( i,
aAttrValue );
if( aLocation.getLength() )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
// draw bug
aAttrQName = GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LIBRARY ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
}
}
}
break;
case XML_ATACTION_COPY:
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.18); FILE MERGED 2008/04/01 13:05:45 thb 1.8.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:50 rt 1.8.18.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EventOASISTContext.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "EventOASISTContext.hxx"
#include "EventMap.hxx"
#include "MutableAttrList.hxx"
#include "xmlnmspe.hxx"
#include "ActionMapTypesOASIS.hxx"
#include "AttrTransformerAction.hxx"
#include "TransformerActions.hxx"
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#include <comphelper/processfactory.hxx>
#endif
#include <hash_map>
using ::rtl::OUString;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
class XMLTransformerOASISEventMap_Impl:
public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
NameHash_Impl, NameHash_Impl >
{
public:
XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
~XMLTransformerOASISEventMap_Impl();
};
XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
if( pInit )
{
XMLTransformerOASISEventMap_Impl::key_type aKey;
XMLTransformerOASISEventMap_Impl::data_type aData;
while( pInit->m_pOASISName )
{
aKey.m_nPrefix = pInit->m_nOASISPrefix;
aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);
OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );
aData = OUString::createFromAscii(pInit->m_pOOoName);
XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );
insert( aVal );
++pInit;
}
}
}
XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);
XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLRenameElemTransformerContext( rImp, rQName,
rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}
XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateFormEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}
void XMLEventOASISTransformerContext::FlushEventMap(
XMLTransformerOASISEventMap_Impl *p )
{
delete p;
}
OUString XMLEventOASISTransformerContext::GetEventName(
sal_uInt16 nPrefix,
const OUString& rName,
XMLTransformerOASISEventMap_Impl& rMap,
XMLTransformerOASISEventMap_Impl *pMap2)
{
XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
if( pMap2 )
{
XMLTransformerOASISEventMap_Impl::const_iterator aIter =
pMap2->find( aKey );
if( !(aIter == pMap2->end()) )
return (*aIter).second;
}
XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
if( aIter == rMap.end() )
return rName;
else
return (*aIter).second;
}
bool ParseURLAsString(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );
sal_Int32 params = rAttrValue.indexOf( '?' );
if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
{
return FALSE;
}
sal_Int32 start = SCHEME.getLength();
*pName = rAttrValue.copy( start, params - start );
OUString aToken;
OUString aLanguage;
params++;
do
{
aToken = rAttrValue.getToken( 0, '&', params );
sal_Int32 dummy = 0;
if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
{
aLanguage = aToken.getToken( 1, '=', dummy );
}
else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
{
OUString tmp = aToken.getToken( 1, '=', dummy );
if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
{
*pLocation = GetXMLToken( XML_DOCUMENT );
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
}
} while ( params >= 0 );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
return TRUE;
}
return FALSE;
}
bool ParseURL(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
return ParseURLAsString( rAttrValue, pName, pLocation );
#else
Reference< com::sun::star::lang::XMultiServiceFactory >
xSMgr = ::comphelper::getProcessServiceFactory();
Reference< com::sun::star::uri::XUriReferenceFactory >
xFactory( xSMgr->createInstance( OUString::createFromAscii(
"com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );
if ( xFactory.is() )
{
Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
xFactory->parse( rAttrValue ), UNO_QUERY );
if ( xUrl.is() )
{
OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
{
OUString aLanguage = xUrl->getParameter( aLanguageKey );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
*pName = xUrl->getName();
OUString tmp =
xUrl->getParameter( GetXMLToken( XML_LOCATION ) );
OUString doc = GetXMLToken( XML_DOCUMENT );
if ( tmp.equalsIgnoreAsciiCase( doc ) )
{
*pLocation = doc;
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
return TRUE;
}
}
}
return FALSE;
}
else
{
return ParseURLAsString( rAttrValue, pName, pLocation );
}
#endif
}
void XMLEventOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
OSL_TRACE("XMLEventOASISTransformerContext::StartElement");
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_HREF:
{
OUString aAttrValue( rAttrValue );
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->RemoveAttributeByIndex( i );
OUString aAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
}
break;
case XML_ATACTION_EVENT_NAME:
{
// Check if the event belongs to a form or control by
// cehcking the 2nd ancestor element, f.i.:
// <form:button><form:event-listeners><form:event-listener>
const XMLTransformerContext *pObjContext =
GetTransformer().GetAncestorContext( 1 );
sal_Bool bForm = pObjContext &&
pObjContext->HasNamespace(XML_NAMESPACE_FORM );
pMutableAttrList->SetValueByIndex( i,
GetTransformer().GetEventName( rAttrValue,
bForm ) );
}
break;
case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
{
OUString aAttrValue( rAttrValue );
sal_uInt16 nValPrefix =
static_cast<sal_uInt16>((*aIter).second.m_nParam1);
if( GetTransformer().RemoveNamespacePrefix(
aAttrValue, nValPrefix ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_MACRO_NAME:
{
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->SetValueByIndex( i, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
else
{
const OUString& rApp = GetXMLToken( XML_APPLICATION );
const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
OUString aAttrValue;
if( rAttrValue.getLength() > rApp.getLength()+1 &&
rAttrValue.copy(0,rApp.getLength()).
equalsIgnoreAsciiCase( rApp ) &&
':' == rAttrValue[rApp.getLength()] )
{
aLocation = rApp;
aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
}
else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
rAttrValue.copy(0,rDoc.getLength()).
equalsIgnoreAsciiCase( rDoc ) &&
':' == rAttrValue[rDoc.getLength()] )
{
aLocation= rDoc;
aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
}
if( aAttrValue.getLength() )
pMutableAttrList->SetValueByIndex( i,
aAttrValue );
if( aLocation.getLength() )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
// draw bug
aAttrQName = GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LIBRARY ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
}
}
}
break;
case XML_ATACTION_COPY:
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Razer Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "ChaperoneData.h"
// Library/third-party includes
#include <json/reader.h>
#include <json/value.h>
#include <osvr/Util/Finally.h>
// Standard includes
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <sstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NO_MINMAX
#include <windows.h>
static inline std::string formatLastErrorAsString() {
char *lpMsgBuf = nullptr;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
nullptr, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
reinterpret_cast<LPSTR>(&lpMsgBuf), 0, nullptr);
/// Free that buffer when we're out of scope.
auto cleanupBuf = osvr::util::finally([&] { LocalFree(lpMsgBuf); });
auto errorMessage = std::string(lpMsgBuf);
return errorMessage;
}
static inline std::string
getFile(std::string const &fn,
std::function<void(std::string const &)> const &errorReport) {
/// Had trouble with "permission denied" errors using standard C++ iostreams
/// on the chaperone data, so had to go back down to Win32 API.
HANDLE f = CreateFileA(fn.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (INVALID_HANDLE_VALUE == f) {
errorReport("Could not open file: " + formatLastErrorAsString());
return std::string{};
}
auto closer = osvr::util::finally([&f] { CloseHandle(f); });
std::ostringstream os;
static const auto BUFSIZE = 1024;
std::array<char, BUFSIZE + 1> buf;
/// Null terminate for ease of use.
buf.back() = '\0';
bool keepReading = true;
while (1) {
DWORD bytesRead;
auto ret = ReadFile(f, buf.data(), buf.size() - 1, &bytesRead, nullptr);
if (ret) {
if (bytesRead == 0) {
// end of file
break;
} else {
// Null terminate this block and slide it in.
// std::cout << "read " << bytesRead << " bytes this time "
// << std::endl;
buf[bytesRead] = '\0';
os << buf.data();
}
} else {
errorReport("Error after reading " +
std::to_string(os.str().size()) + " bytes: " +
formatLastErrorAsString());
return std::string{};
}
}
return os.str();
}
#else
#include <cstring> // strerror
std::string
getFile(std::string const &fn,
std::function<void(std::string const &)> const &errorReport) {
std::ifstream s(fn, std::ios::in | std::ios::binary);
if (!s) {
std::ostringstream os;
os << "Could not open file ";
/// Sadly errno is far more useful in its error messages than
/// failbit-triggered exceptions, etc.
auto theErrno = errno;
os << " (Error code: " << theErrno << " - " << strerror(theErrno)
<< ")";
errorReport(os.str());
return std::string{};
}
std::ostringstream os;
std::string temp;
while (std::getline(s, temp)) {
os << temp;
}
return os.str();
}
#endif
namespace osvr {
namespace vive {
static const auto PREFIX = "[ChaperoneData] ";
static const auto CHAPERONE_DATA_FILENAME = "chaperone_info.vrchap";
#ifdef _WIN32
static const auto PATH_SEPARATOR = "\\";
#else
static const auto PATH_SEPARATOR = "/";
#endif
using UniverseDataMap =
std::map<std::uint64_t, ChaperoneData::UniverseData>;
using UniverseBaseSerials = std::vector<
std::pair<std::uint64_t, ChaperoneData::BaseStationSerials>>;
struct ChaperoneData::Impl {
Json::Value chaperoneInfo;
UniverseDataMap universes;
UniverseBaseSerials baseSerials;
};
void loadJsonIntoUniverseData(Json::Value const &obj,
ChaperoneData::UniverseData &data) {
data.yaw = obj["yaw"].asDouble();
auto &xlate = obj["translation"];
for (Json::Value::ArrayIndex i = 0; i < 3; ++i) {
data.translation[i] = xlate[i].asDouble();
}
}
ChaperoneData::ChaperoneData(std::string const &steamConfigDir)
: impl_(new Impl), configDir_(steamConfigDir) {
{
Json::Reader reader;
auto chapInfoFn =
configDir_ + PATH_SEPARATOR + CHAPERONE_DATA_FILENAME;
#if 0
std::ifstream chapInfoFile(configDir_,
std::ios::in | std::ios::binary);
if (!chapInfoFile) {
std::ostringstream os;
os << "Could not open chaperone info file, expected at "
<< chapInfoFn;
/// Sadly errno is far more useful in its error messages than
/// failbit-triggered exceptions, etc.
auto theErrno = errno;
os << " (Error code: " << theErrno << " - "
<< strerror(theErrno) << ")";
errorOut_(os.str());
return;
}
if (!chapInfoFile.good()) {
errorOut_("Could not open chaperone info file, expected at " +
chapInfoFn);
return;
}
#endif
std::string fileData =
getFile(chapInfoFn, [&](std::string const &message) {
std::ostringstream os;
os << "Could not open chaperone info file, expected at "
<< chapInfoFn;
os << " - details [" << message << "]";
errorOut_(os.str());
});
if (!valid()) {
/// this means our fail handler got called.
return;
}
if (!reader.parse(fileData, impl_->chaperoneInfo)) {
errorOut_("Could not parse JSON in chaperone info file at " +
chapInfoFn + ": " +
reader.getFormattedErrorMessages());
return;
}
/// Basic sanity checks
if (impl_->chaperoneInfo["jsonid"] != "chaperone_info") {
errorOut_("Chaperone info file at " + chapInfoFn +
" did not match expected format (no element "
"\"jsonid\": \"chaperone_info\" in top level "
"object)");
return;
}
if (impl_->chaperoneInfo["universes"].size() == 0) {
errorOut_("Chaperone info file at " + chapInfoFn +
" did not contain any known chaperone universes - "
"user must run Room Setup at least once");
return;
}
}
for (auto const &univ : impl_->chaperoneInfo["universes"]) {
auto univIdString = univ["universeID"].asString();
UniverseData data;
auto &standing = univ["standing"];
if (standing.isNull()) {
warn_("No standing calibration data for universe " +
univIdString + ", so had to look for seated data.");
auto &seated = univ["seated"];
if (seated.isNull()) {
warn_(
"No seated or standing calibration data for universe " +
univIdString + ", so had to skip it.");
continue;
} else {
data.type = CalibrationType::Seated;
loadJsonIntoUniverseData(seated, data);
}
} else {
data.type = CalibrationType::Standing;
loadJsonIntoUniverseData(standing, data);
}
/// Convert universe ID (64-bit int) from string, in JSON, to an int
/// again.
UniverseId id;
std::istringstream is(univIdString);
is >> id;
/// Add the universe data in.
impl_->universes.insert(std::make_pair(id, data));
BaseStationSerials serials;
for (auto const &tracker : univ["trackers"]) {
auto &serial = tracker["serial"];
if (serial.isString()) {
serials.push_back(serial.asString());
}
}
/// Add the serial data in.
impl_->baseSerials.emplace_back(id, std::move(serials));
}
}
ChaperoneData::~ChaperoneData() {}
bool ChaperoneData::valid() const { return static_cast<bool>(impl_); }
bool ChaperoneData::knowUniverseId(UniverseId universe) const {
if (0 == universe) {
return false;
}
return (impl_->universes.find(universe) != end(impl_->universes));
}
ChaperoneData::UniverseData
ChaperoneData::getDataForUniverse(UniverseId universe) const {
auto it = impl_->universes.find(universe);
if (it == end(impl_->universes)) {
return UniverseData();
}
return it->second;
}
std::size_t ChaperoneData::getNumberOfKnownUniverses() const {
return impl_->universes.size();
}
ChaperoneData::UniverseId ChaperoneData::guessUniverseIdFromBaseStations(
BaseStationSerials const &bases) {
auto providedSize = bases.size();
UniverseId ret = 0;
using UniverseRank = std::pair<float, UniverseId>;
/// Compare function for heap.
auto compare = [](UniverseRank const &a, UniverseRank const &b) {
return a.first < b.first;
};
/// Will contain heap of potential universes and their value (a fraction
/// of their base stations and provided base stations that were included
/// in the base station list provided to the function)
std::vector<UniverseRank> potentialUniverses;
auto push = [&](float value, UniverseId id) {
potentialUniverses.emplace_back(value, id);
std::push_heap(begin(potentialUniverses), end(potentialUniverses),
compare);
};
for (auto &univBaseSerial : impl_->baseSerials) {
auto const &baseSerials = univBaseSerial.second;
std::size_t hits = 0;
auto b = begin(baseSerials);
auto e = end(baseSerials);
/// Count the number of entries that we were given that are also in
/// this universe's list.
auto found = std::count_if(begin(bases), end(bases),
[&](std::string const &needle) {
return std::find(b, e, needle) != e;
});
if (found > 0) {
/// This is meant to combine the influence of "found" in both
/// providedSize and universe size, and the +1 in the
/// denominator is to avoid division by zero.
auto weight = 2.f * static_cast<float>(found) /
(baseSerials.size() + providedSize + 1);
#if 0
std::cout << "Guessing produced weight of " << weight << " for "
<< univBaseSerial.first << std::endl;
#endif
push(weight, univBaseSerial.first);
}
}
if (!potentialUniverses.empty()) {
/// it's a heap, so the best one is always on top.
return potentialUniverses.front().second;
}
return ret;
}
void ChaperoneData::errorOut_(std::string const &message) {
/// This reset may be redundant in some cases, but better to not miss
/// it, since it's also our error flag.
impl_.reset();
warn_("ERROR: " + message);
}
void ChaperoneData::warn_(std::string const &message) {
if (err_.empty()) {
/// First error
err_ = message;
return;
}
static const auto BEGIN_LIST = "[";
static const auto BEGIN_LIST_CH = BEGIN_LIST[0];
static const auto END_LIST = "]";
static const auto MIDDLE_LIST = "][";
if (BEGIN_LIST_CH == err_.front()) {
/// We've already started a list of errors, just tack one more on.
err_ += BEGIN_LIST + message + END_LIST;
return;
}
/// OK, so this is our exactly second error, wrap the first and second.
err_ = BEGIN_LIST + err_ + MIDDLE_LIST + message + END_LIST;
}
} // namespace vive
} // namespace osvr
<commit_msg>fix 64-bit build warning<commit_after>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Razer Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "ChaperoneData.h"
// Library/third-party includes
#include <json/reader.h>
#include <json/value.h>
#include <osvr/Util/Finally.h>
// Standard includes
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <sstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NO_MINMAX
#include <windows.h>
static inline std::string formatLastErrorAsString() {
char *lpMsgBuf = nullptr;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
nullptr, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
reinterpret_cast<LPSTR>(&lpMsgBuf), 0, nullptr);
/// Free that buffer when we're out of scope.
auto cleanupBuf = osvr::util::finally([&] { LocalFree(lpMsgBuf); });
auto errorMessage = std::string(lpMsgBuf);
return errorMessage;
}
static inline std::string
getFile(std::string const &fn,
std::function<void(std::string const &)> const &errorReport) {
/// Had trouble with "permission denied" errors using standard C++ iostreams
/// on the chaperone data, so had to go back down to Win32 API.
HANDLE f = CreateFileA(fn.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (INVALID_HANDLE_VALUE == f) {
errorReport("Could not open file: " + formatLastErrorAsString());
return std::string{};
}
auto closer = osvr::util::finally([&f] { CloseHandle(f); });
std::ostringstream os;
static const auto BUFSIZE = 1024;
std::array<char, BUFSIZE + 1> buf;
/// Null terminate for ease of use.
buf.back() = '\0';
bool keepReading = true;
while (1) {
DWORD bytesRead;
auto ret = ReadFile(f, buf.data(), static_cast<DWORD>(buf.size() - 1),
&bytesRead, nullptr);
if (ret) {
if (bytesRead == 0) {
// end of file
break;
} else {
// Null terminate this block and slide it in.
// std::cout << "read " << bytesRead << " bytes this time "
// << std::endl;
buf[bytesRead] = '\0';
os << buf.data();
}
} else {
errorReport("Error after reading " +
std::to_string(os.str().size()) + " bytes: " +
formatLastErrorAsString());
return std::string{};
}
}
return os.str();
}
#else
#include <cstring> // strerror
std::string
getFile(std::string const &fn,
std::function<void(std::string const &)> const &errorReport) {
std::ifstream s(fn, std::ios::in | std::ios::binary);
if (!s) {
std::ostringstream os;
os << "Could not open file ";
/// Sadly errno is far more useful in its error messages than
/// failbit-triggered exceptions, etc.
auto theErrno = errno;
os << " (Error code: " << theErrno << " - " << strerror(theErrno)
<< ")";
errorReport(os.str());
return std::string{};
}
std::ostringstream os;
std::string temp;
while (std::getline(s, temp)) {
os << temp;
}
return os.str();
}
#endif
namespace osvr {
namespace vive {
static const auto PREFIX = "[ChaperoneData] ";
static const auto CHAPERONE_DATA_FILENAME = "chaperone_info.vrchap";
#ifdef _WIN32
static const auto PATH_SEPARATOR = "\\";
#else
static const auto PATH_SEPARATOR = "/";
#endif
using UniverseDataMap =
std::map<std::uint64_t, ChaperoneData::UniverseData>;
using UniverseBaseSerials = std::vector<
std::pair<std::uint64_t, ChaperoneData::BaseStationSerials>>;
struct ChaperoneData::Impl {
Json::Value chaperoneInfo;
UniverseDataMap universes;
UniverseBaseSerials baseSerials;
};
void loadJsonIntoUniverseData(Json::Value const &obj,
ChaperoneData::UniverseData &data) {
data.yaw = obj["yaw"].asDouble();
auto &xlate = obj["translation"];
for (Json::Value::ArrayIndex i = 0; i < 3; ++i) {
data.translation[i] = xlate[i].asDouble();
}
}
ChaperoneData::ChaperoneData(std::string const &steamConfigDir)
: impl_(new Impl), configDir_(steamConfigDir) {
{
Json::Reader reader;
auto chapInfoFn =
configDir_ + PATH_SEPARATOR + CHAPERONE_DATA_FILENAME;
#if 0
std::ifstream chapInfoFile(configDir_,
std::ios::in | std::ios::binary);
if (!chapInfoFile) {
std::ostringstream os;
os << "Could not open chaperone info file, expected at "
<< chapInfoFn;
/// Sadly errno is far more useful in its error messages than
/// failbit-triggered exceptions, etc.
auto theErrno = errno;
os << " (Error code: " << theErrno << " - "
<< strerror(theErrno) << ")";
errorOut_(os.str());
return;
}
if (!chapInfoFile.good()) {
errorOut_("Could not open chaperone info file, expected at " +
chapInfoFn);
return;
}
#endif
std::string fileData =
getFile(chapInfoFn, [&](std::string const &message) {
std::ostringstream os;
os << "Could not open chaperone info file, expected at "
<< chapInfoFn;
os << " - details [" << message << "]";
errorOut_(os.str());
});
if (!valid()) {
/// this means our fail handler got called.
return;
}
if (!reader.parse(fileData, impl_->chaperoneInfo)) {
errorOut_("Could not parse JSON in chaperone info file at " +
chapInfoFn + ": " +
reader.getFormattedErrorMessages());
return;
}
/// Basic sanity checks
if (impl_->chaperoneInfo["jsonid"] != "chaperone_info") {
errorOut_("Chaperone info file at " + chapInfoFn +
" did not match expected format (no element "
"\"jsonid\": \"chaperone_info\" in top level "
"object)");
return;
}
if (impl_->chaperoneInfo["universes"].size() == 0) {
errorOut_("Chaperone info file at " + chapInfoFn +
" did not contain any known chaperone universes - "
"user must run Room Setup at least once");
return;
}
}
for (auto const &univ : impl_->chaperoneInfo["universes"]) {
auto univIdString = univ["universeID"].asString();
UniverseData data;
auto &standing = univ["standing"];
if (standing.isNull()) {
warn_("No standing calibration data for universe " +
univIdString + ", so had to look for seated data.");
auto &seated = univ["seated"];
if (seated.isNull()) {
warn_(
"No seated or standing calibration data for universe " +
univIdString + ", so had to skip it.");
continue;
} else {
data.type = CalibrationType::Seated;
loadJsonIntoUniverseData(seated, data);
}
} else {
data.type = CalibrationType::Standing;
loadJsonIntoUniverseData(standing, data);
}
/// Convert universe ID (64-bit int) from string, in JSON, to an int
/// again.
UniverseId id;
std::istringstream is(univIdString);
is >> id;
/// Add the universe data in.
impl_->universes.insert(std::make_pair(id, data));
BaseStationSerials serials;
for (auto const &tracker : univ["trackers"]) {
auto &serial = tracker["serial"];
if (serial.isString()) {
serials.push_back(serial.asString());
}
}
/// Add the serial data in.
impl_->baseSerials.emplace_back(id, std::move(serials));
}
}
ChaperoneData::~ChaperoneData() {}
bool ChaperoneData::valid() const { return static_cast<bool>(impl_); }
bool ChaperoneData::knowUniverseId(UniverseId universe) const {
if (0 == universe) {
return false;
}
return (impl_->universes.find(universe) != end(impl_->universes));
}
ChaperoneData::UniverseData
ChaperoneData::getDataForUniverse(UniverseId universe) const {
auto it = impl_->universes.find(universe);
if (it == end(impl_->universes)) {
return UniverseData();
}
return it->second;
}
std::size_t ChaperoneData::getNumberOfKnownUniverses() const {
return impl_->universes.size();
}
ChaperoneData::UniverseId ChaperoneData::guessUniverseIdFromBaseStations(
BaseStationSerials const &bases) {
auto providedSize = bases.size();
UniverseId ret = 0;
using UniverseRank = std::pair<float, UniverseId>;
/// Compare function for heap.
auto compare = [](UniverseRank const &a, UniverseRank const &b) {
return a.first < b.first;
};
/// Will contain heap of potential universes and their value (a fraction
/// of their base stations and provided base stations that were included
/// in the base station list provided to the function)
std::vector<UniverseRank> potentialUniverses;
auto push = [&](float value, UniverseId id) {
potentialUniverses.emplace_back(value, id);
std::push_heap(begin(potentialUniverses), end(potentialUniverses),
compare);
};
for (auto &univBaseSerial : impl_->baseSerials) {
auto const &baseSerials = univBaseSerial.second;
std::size_t hits = 0;
auto b = begin(baseSerials);
auto e = end(baseSerials);
/// Count the number of entries that we were given that are also in
/// this universe's list.
auto found = std::count_if(begin(bases), end(bases),
[&](std::string const &needle) {
return std::find(b, e, needle) != e;
});
if (found > 0) {
/// This is meant to combine the influence of "found" in both
/// providedSize and universe size, and the +1 in the
/// denominator is to avoid division by zero.
auto weight = 2.f * static_cast<float>(found) /
(baseSerials.size() + providedSize + 1);
#if 0
std::cout << "Guessing produced weight of " << weight << " for "
<< univBaseSerial.first << std::endl;
#endif
push(weight, univBaseSerial.first);
}
}
if (!potentialUniverses.empty()) {
/// it's a heap, so the best one is always on top.
return potentialUniverses.front().second;
}
return ret;
}
void ChaperoneData::errorOut_(std::string const &message) {
/// This reset may be redundant in some cases, but better to not miss
/// it, since it's also our error flag.
impl_.reset();
warn_("ERROR: " + message);
}
void ChaperoneData::warn_(std::string const &message) {
if (err_.empty()) {
/// First error
err_ = message;
return;
}
static const auto BEGIN_LIST = "[";
static const auto BEGIN_LIST_CH = BEGIN_LIST[0];
static const auto END_LIST = "]";
static const auto MIDDLE_LIST = "][";
if (BEGIN_LIST_CH == err_.front()) {
/// We've already started a list of errors, just tack one more on.
err_ += BEGIN_LIST + message + END_LIST;
return;
}
/// OK, so this is our exactly second error, wrap the first and second.
err_ = BEGIN_LIST + err_ + MIDDLE_LIST + message + END_LIST;
}
} // namespace vive
} // namespace osvr
<|endoftext|> |
<commit_before>#include "compiler.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <assert.h>
int main() {
std::ifstream input;
input.open("C:\\Users\\Lonnie\\Source\\Repos\\Compiler\\Compiler\\test.txt");
std::string token;
std::string lexeme;
std::cout << "Token\t\tLexeme" << std::endl;
lexer(input);
input.close();
return 0;
}<commit_msg>removed unnecessary main.cpp<commit_after><|endoftext|> |
<commit_before>
/* An example of the minimal Win32 & OpenGL program. It only works in
16 bit color modes or higher (since it doesn't create a
palette). */
// clang-format off
#include <stdio.h>
#include <windows.h> /* must include this before GL/gl.h */
#include <GL/gl.h> /* OpenGL header file */
#include <GL/glu.h> /* OpenGL utilities header file */
#include "gl_loader.h"
#include <iostream>
// clang-format on
void display()
{
/* rotate a triangle around */
glActiveTexture(GL_TEXTURE0);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(0, 1);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex2i(-1, -1);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2i(1, -1);
glEnd();
glFlush();
}
LONG WINAPI WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static PAINTSTRUCT ps;
switch (uMsg) {
case WM_PAINT:
display();
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
case WM_SIZE:
glViewport(0, 0, LOWORD(lParam), HIWORD(lParam));
PostMessage(hWnd, WM_PAINT, 0, 0);
return 0;
case WM_CHAR:
switch (wParam) {
case 27: /* ESC key */
PostQuitMessage(0);
break;
}
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
HWND CreateOpenGLWindow(char* title, int x, int y, int width, int height,
BYTE type, DWORD flags)
{
int pf;
HDC hDC;
HWND hWnd;
WNDCLASS wc;
PIXELFORMATDESCRIPTOR pfd;
static HINSTANCE hInstance = 0;
/* only register the window class once - use hInstance as a flag. */
if (!hInstance) {
hInstance = GetModuleHandle(NULL);
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)WindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = L"OpenGL";
if (!RegisterClass(&wc)) {
MessageBox(NULL, L"RegisterClass() failed: "
"Cannot register window class.",
L"Error", MB_OK);
return NULL;
}
}
hWnd = CreateWindow(L"OpenGL", L"Hej", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
x, y, width, height, NULL, NULL, hInstance, NULL);
if (hWnd == NULL) {
MessageBox(NULL, L"CreateWindow() failed: Cannot create a window.",
L"Error", MB_OK);
return NULL;
}
hDC = GetDC(hWnd);
/* there is no guarantee that the contents of the stack that become
the pfd are zeroed, therefore _make sure_ to clear these bits. */
memset(&pfd, 0, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | flags;
pfd.iPixelType = type;
pfd.cColorBits = 32;
pf = ChoosePixelFormat(hDC, &pfd);
if (pf == 0) {
MessageBox(NULL, L"ChoosePixelFormat() failed: "
"Cannot find a suitable pixel format.",
L"Error", MB_OK);
return 0;
}
if (SetPixelFormat(hDC, pf, &pfd) == FALSE) {
MessageBox(NULL, L"SetPixelFormat() failed: "
"Cannot set format specified.",
L"Error", MB_OK);
return 0;
}
DescribePixelFormat(hDC, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
ReleaseDC(hWnd, hDC);
return hWnd;
}
int main()
{
HDC hDC; /* device context */
HGLRC hRC; /* opengl context */
HWND hWnd; /* window */
MSG msg; /* message */
hWnd = CreateOpenGLWindow("minimal", 0, 0, 256, 256, PFD_TYPE_RGBA, 0);
if (hWnd == NULL)
exit(1);
hDC = GetDC(hWnd);
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);
load_gl_functions();
ShowWindow(hWnd, 1);
while (GetMessage(&msg, hWnd, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
wglMakeCurrent(NULL, NULL);
ReleaseDC(hWnd, hDC);
wglDeleteContext(hRC);
DestroyWindow(hWnd);
return msg.wParam;
}
<commit_msg>Linguist vendored c files<commit_after>
/* An example of the minimal Win32 & OpenGL program. It only works in
16 bit color modes or higher (since it doesn't create a
palette). */
// clang-format off
#include <stdio.h>
#include <windows.h> /* must include this before GL/gl.h */
#include <GL/gl.h> /* OpenGL header file */
#include <GL/glu.h> /* OpenGL utilities header file */
#include "gl_loader.h"
#include <iostream>
// clang-format on
void display()
{
/* rotate a triangle around */
glActiveTexture(GL_TEXTURE0);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2i(0, 1);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex2i(-1, -1);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2i(1, -1);
glEnd();
glFlush();
}
LONG WINAPI WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static PAINTSTRUCT ps;
switch (uMsg) {
case WM_PAINT:
display();
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
case WM_SIZE:
glViewport(0, 0, LOWORD(lParam), HIWORD(lParam));
PostMessage(hWnd, WM_PAINT, 0, 0);
return 0;
case WM_CHAR:
switch (wParam) {
case 27: /* ESC key */
PostQuitMessage(0);
break;
}
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
HWND CreateOpenGLWindow(char* title, int x, int y, int width, int height,
BYTE type, DWORD flags)
{
int pf;
HDC hDC;
HWND hWnd;
WNDCLASS wc;
PIXELFORMATDESCRIPTOR pfd;
static HINSTANCE hInstance = 0;
/* only register the window class once - use hInstance as a flag. */
if (!hInstance) {
hInstance = GetModuleHandle(NULL);
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)WindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = L"OpenGL";
if (!RegisterClass(&wc)) {
MessageBox(NULL, L"RegisterClass() failed: "
"Cannot register window class.",
L"Error", MB_OK);
return NULL;
}
}
hWnd = CreateWindow(L"OpenGL", L"Hej", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
x, y, width, height, NULL, NULL, hInstance, NULL);
if (hWnd == NULL) {
MessageBox(NULL, L"CreateWindow() failed: Cannot create a window.",
L"Error", MB_OK);
return NULL;
}
hDC = GetDC(hWnd);
/* there is no guarantee that the contents of the stack that become
the pfd are zeroed, therefore _make sure_ to clear these bits. */
memset(&pfd, 0, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | flags;
pfd.iPixelType = type;
pfd.cColorBits = 32;
pf = ChoosePixelFormat(hDC, &pfd);
if (pf == 0) {
MessageBox(NULL, L"ChoosePixelFormat() failed: "
"Cannot find a suitable pixel format.",
L"Error", MB_OK);
return 0;
}
if (SetPixelFormat(hDC, pf, &pfd) == FALSE) {
MessageBox(NULL, L"SetPixelFormat() failed: "
"Cannot set format specified.",
L"Error", MB_OK);
return 0;
}
DescribePixelFormat(hDC, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
ReleaseDC(hWnd, hDC);
return hWnd;
}
int main()
{
HDC hDC; /* device context */
HGLRC hRC; /* opengl context */
HWND hWnd; /* window */
MSG msg; /* message */
hWnd = CreateOpenGLWindow("minimal", 0, 0, 256, 256, PFD_TYPE_RGBA, 0);
if (hWnd == NULL)
exit(1);
hDC = GetDC(hWnd);
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);
std::cout << load_gl_functions();
ShowWindow(hWnd, 1);
while (GetMessage(&msg, hWnd, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
wglMakeCurrent(NULL, NULL);
ReleaseDC(hWnd, hDC);
wglDeleteContext(hRC);
DestroyWindow(hWnd);
return msg.wParam;
}
<|endoftext|> |
<commit_before>#include "LIBETC.H"
#include <stdio.h>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_opengl.h>
#include "EMULATOR.H"
#include "EMULATOR_GLOBALS.H"
void(*vsync_callback)(void) = NULL;
int ResetCallback(void)
{
return 0;
}
int VSync(int mode)
{
if (mode == 0)
{
if (vsync_callback != NULL)
{
vsync_callback();
}
while (lastTime - SDL_GetTicks() < (1000 / 60))
{
SDL_Delay(1);
}
Emulator_EndScene();
}
return 0;
}
int VSyncCallback(void(*f)(void))
{
vsync_callback = f;
return 0;
}
long GetVideoMode(void)
{
return 0;
}
<commit_msg>impl funcs in libetc<commit_after>#include "LIBETC.H"
#include <stdio.h>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_opengl.h>
#include "EMULATOR.H"
#include "EMULATOR_GLOBALS.H"
void(*vsync_callback)(void) = NULL;
int ResetCallback(void)
{
vsync_callback = NULL;
return 0;
}
int VSync(int mode)
{
if (mode == 0)
{
if (vsync_callback != NULL)
{
vsync_callback();
}
while (lastTime - SDL_GetTicks() < (1000 / 60))
{
SDL_Delay(1);
}
Emulator_EndScene();
}
return 0;
}
int VSyncCallback(void(*f)(void))
{
vsync_callback = f;
return 0;
}
long GetVideoMode(void)
{
return MODE_NTSC;
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include "SystemManager.hpp"
#include "Component.hpp"
#include "Entity.hpp"
namespace kengine {
class EntityManager : public SystemManager {
public:
EntityManager(size_t threads = 0) : SystemManager(threads) {
detail::components = &_components;
}
~EntityManager();
public:
template<typename Func> // Func: void(Entity &);
Entity createEntity(Func && postCreate) {
auto e = alloc();
postCreate(e);
SystemManager::registerEntity(e);
bool shouldActivate;
{
detail::ReadLock l(_entitiesMutex);
shouldActivate = _entities[e.id].shouldActivateAfterInit;
}
if (shouldActivate)
setEntityActive(e, true);
return e;
}
template<typename Func>
Entity operator+=(Func && postCreate) {
return createEntity(FWD(postCreate));
}
public:
Entity getEntity(Entity::ID id);
EntityView getEntity(Entity::ID id) const;
public:
void removeEntity(EntityView e);
void removeEntity(Entity::ID id);
public:
void setEntityActive(EntityView e, bool active);
void setEntityActive(Entity::ID id, bool active);
private:
struct Archetype {
Entity::Mask mask;
std::vector<Entity::ID> entities;
bool sorted = true;
mutable detail::Mutex mutex;
Archetype(Entity::Mask mask, Entity::ID firstEntity) : mask(mask), entities({ firstEntity }) {}
template<typename ... Comps>
bool matches() {
{
detail::ReadLock l(mutex);
if (entities.empty())
return false;
}
if (!sorted) {
detail::WriteLock l(mutex);
std::sort(entities.begin(), entities.end(), std::greater<Entity::ID>());
sorted = true;
}
bool good = true;
putils::for_each_type<Comps...>([&](auto && type) {
using CompType = putils_wrapped_type(type);
good &= mask.test(Component<CompType>::id());
});
return good;
}
Archetype() = default;
Archetype(Archetype && rhs) = default;
Archetype(const Archetype & rhs) {
mask = rhs.mask;
sorted = rhs.sorted;
detail::ReadLock l(rhs.mutex);
entities = rhs.entities;
}
};
struct EntityCollection {
struct EntityIterator {
EntityIterator & operator++();
bool operator!=(const EntityIterator & rhs) const;
Entity operator*() const;
size_t index;
EntityManager & em;
};
EntityIterator begin() const;
EntityIterator end() const;
EntityCollection(EntityManager & em);
~EntityCollection();
EntityManager & em;
};
public:
EntityCollection getEntities();
private:
template<typename ... Comps>
struct ComponentCollection {
struct ComponentIterator {
using iterator_category = std::forward_iterator_tag;
using value_type = std::tuple<Entity, Comps & ...>;
using reference = const value_type &;
using pointer = const value_type *;
using difference_type = size_t;
ComponentIterator & operator++() {
++currentEntity;
const auto & archetype = em._archetypes[currentType];
{
detail::ReadLock l(archetype.mutex);
if (currentEntity < archetype.entities.size())
{
detail::ReadLock l(em._entitiesMutex);
if (em._entities[archetype.entities[currentEntity]].active)
return *this;
}
}
currentEntity = 0;
{
detail::ReadLock l(em._archetypesMutex);
for (++currentType; currentType < em._archetypes.size(); ++currentType)
if (em._archetypes[currentType].matches<Comps...>())
break;
}
return *this;
}
// Use `<` as it will only be compared with `end()`, and there is a risk that new entities have been added since `end()` was called
bool operator!=(const ComponentIterator & rhs) const { return currentType < rhs.currentType || currentEntity < rhs.currentEntity; }
std::tuple<Entity, Comps &...> operator*() const {
detail::ReadLock l(em._archetypesMutex);
const auto & archetype = em._archetypes[currentType];
detail::ReadLock l2(archetype.mutex);
Entity e(archetype.entities[currentEntity], archetype.mask, &em);
return std::make_tuple(e, std::ref(e.get<Comps>())...);
}
kengine::EntityManager & em;
size_t currentType;
size_t currentEntity;
};
auto begin() const {
detail::ReadLock l(em._archetypesMutex);
size_t archetypeIndex = 0;
for (auto & archetype : em._archetypes) {
if (archetype.matches<Comps...>()) {
detail::ReadLock l(archetype.mutex);
detail::ReadLock l2(em._entitiesMutex);
size_t entityIndex = 0;
for (const auto entityID : archetype.entities) {
if (em._entities[entityID].active)
return ComponentIterator{ em, archetypeIndex, entityIndex };
++entityIndex;
}
}
++archetypeIndex;
}
return ComponentIterator{ em, em._archetypes.size(), 0 };
}
auto end() const {
detail::ReadLock l(em._archetypesMutex);
return ComponentIterator{ em, em._archetypes.size(), 0 };
}
ComponentCollection(EntityManager & em) : em(em) {
detail::WriteLock l(em._updatesMutex);
++em._updatesLocked;
}
~ComponentCollection() {
detail::WriteLock l(em._updatesMutex);
assert(em._updatesLocked != 0);
--em._updatesLocked;
if (em._updatesLocked == 0)
em.doAllUpdates();
}
EntityManager & em;
};
public:
template<typename ... Comps>
auto getEntities() {
return ComponentCollection<Comps...>{ *this };
}
public:
template<typename RegisterWith, typename ...Types>
void registerTypes() {
if constexpr (!std::is_same<RegisterWith, nullptr_t>::value) {
auto & s = getSystem<RegisterWith>();
s.template registerTypes<Types...>();
}
}
private:
Entity alloc();
private:
friend class Entity;
void addComponent(Entity::ID id, size_t component);
void removeComponent(Entity::ID id, size_t component);
void updateHasComponent(Entity::ID id, size_t component, bool newHasComponent);
void updateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask = false);
void doAllUpdates();
void doUpdateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask);
void doRemove(Entity::ID id);
private:
struct EntityMetadata {
bool active = false;
Entity::Mask mask = 0;
bool shouldActivateAfterInit = true;
};
std::vector<EntityMetadata> _entities;
mutable detail::Mutex _entitiesMutex;
std::vector<Archetype> _archetypes;
mutable detail::Mutex _archetypesMutex;
std::vector<Entity::ID> _toReuse;
bool _toReuseSorted = true;
mutable detail::Mutex _toReuseMutex;
struct Update {
Entity::ID id;
Entity::Mask newMask;
bool ignoreOldMask;
std::mutex mutex;
Update() = default;
Update(Update &&) = default;
Update(const Update & rhs) {
id = rhs.id;
newMask = rhs.newMask;
ignoreOldMask = rhs.ignoreOldMask;
}
};
std::vector<Update> _updates;
struct Removal {
Entity::ID id;
};
std::vector<Removal> _removals;
size_t _updatesLocked = 0;
mutable detail::Mutex _updatesMutex;
private:
mutable detail::GlobalCompMap _components; // Mutable to lock mutex
public: // Reserved to systems
detail::GlobalCompMap & __getComponentMap() { return _components; }
};
}
<commit_msg>add not<T> option for EntityManager::getEntities to filter out entities with a given component<commit_after>#pragma once
#include <vector>
#include "SystemManager.hpp"
#include "Component.hpp"
#include "Entity.hpp"
namespace kengine {
template<typename T>
struct not {
using CompType = T;
};
template<typename>
struct is_not : std::false_type {};
template<typename T>
struct is_not<not<T>> : std::true_type {};
class EntityManager : public SystemManager {
public:
EntityManager(size_t threads = 0) : SystemManager(threads) {
detail::components = &_components;
}
~EntityManager();
public:
template<typename Func> // Func: void(Entity &);
Entity createEntity(Func && postCreate) {
auto e = alloc();
postCreate(e);
SystemManager::registerEntity(e);
bool shouldActivate;
{
detail::ReadLock l(_entitiesMutex);
shouldActivate = _entities[e.id].shouldActivateAfterInit;
}
if (shouldActivate)
setEntityActive(e, true);
return e;
}
template<typename Func>
Entity operator+=(Func && postCreate) {
return createEntity(FWD(postCreate));
}
public:
Entity getEntity(Entity::ID id);
EntityView getEntity(Entity::ID id) const;
public:
void removeEntity(EntityView e);
void removeEntity(Entity::ID id);
public:
void setEntityActive(EntityView e, bool active);
void setEntityActive(Entity::ID id, bool active);
private:
struct Archetype {
Entity::Mask mask;
std::vector<Entity::ID> entities;
bool sorted = true;
mutable detail::Mutex mutex;
Archetype(Entity::Mask mask, Entity::ID firstEntity) : mask(mask), entities({ firstEntity }) {}
template<typename ... Comps>
bool matches() {
{
detail::ReadLock l(mutex);
if (entities.empty())
return false;
}
if (!sorted) {
detail::WriteLock l(mutex);
std::sort(entities.begin(), entities.end(), std::greater<Entity::ID>());
sorted = true;
}
bool good = true;
putils::for_each_type<Comps...>([&](auto && type) {
using T = putils_wrapped_type(type);
if constexpr (kengine::is_not<T>()) {
using CompType = typename T::CompType;
const bool hasComp = mask.test(Component<CompType>::id());
good &= !hasComp;
}
else {
const bool hasComp = mask.test(Component<T>::id());
good &= hasComp;
}
});
return good;
}
Archetype() = default;
Archetype(Archetype && rhs) = default;
Archetype(const Archetype & rhs) {
mask = rhs.mask;
sorted = rhs.sorted;
detail::ReadLock l(rhs.mutex);
entities = rhs.entities;
}
};
struct EntityCollection {
struct EntityIterator {
EntityIterator & operator++();
bool operator!=(const EntityIterator & rhs) const;
Entity operator*() const;
size_t index;
EntityManager & em;
};
EntityIterator begin() const;
EntityIterator end() const;
EntityCollection(EntityManager & em);
~EntityCollection();
EntityManager & em;
};
public:
EntityCollection getEntities();
private:
template<typename ... Comps>
struct ComponentCollection {
struct ComponentIterator {
using iterator_category = std::forward_iterator_tag;
using value_type = std::tuple<Entity, Comps & ...>;
using reference = const value_type &;
using pointer = const value_type *;
using difference_type = size_t;
ComponentIterator & operator++() {
++currentEntity;
const auto & archetype = em._archetypes[currentType];
{
detail::ReadLock l(archetype.mutex);
if (currentEntity < archetype.entities.size())
{
detail::ReadLock l(em._entitiesMutex);
if (em._entities[archetype.entities[currentEntity]].active)
return *this;
}
}
currentEntity = 0;
{
detail::ReadLock l(em._archetypesMutex);
for (++currentType; currentType < em._archetypes.size(); ++currentType)
if (em._archetypes[currentType].matches<Comps...>())
break;
}
return *this;
}
// Use `<` as it will only be compared with `end()`, and there is a risk that new entities have been added since `end()` was called
bool operator!=(const ComponentIterator & rhs) const { return currentType < rhs.currentType || currentEntity < rhs.currentEntity; }
template<typename T>
static T & get(Entity & e) {
if constexpr (kengine::is_not<T>()) {
static T ret;
return ret;
}
else
return e.get<T>();
};
std::tuple<Entity, Comps &...> operator*() const {
detail::ReadLock l(em._archetypesMutex);
const auto & archetype = em._archetypes[currentType];
detail::ReadLock l2(archetype.mutex);
Entity e(archetype.entities[currentEntity], archetype.mask, &em);
return std::make_tuple(e, std::ref(get<Comps>(e))...);
}
kengine::EntityManager & em;
size_t currentType;
size_t currentEntity;
};
auto begin() const {
detail::ReadLock l(em._archetypesMutex);
size_t archetypeIndex = 0;
for (auto & archetype : em._archetypes) {
if (archetype.matches<Comps...>()) {
detail::ReadLock l(archetype.mutex);
detail::ReadLock l2(em._entitiesMutex);
size_t entityIndex = 0;
for (const auto entityID : archetype.entities) {
if (em._entities[entityID].active)
return ComponentIterator{ em, archetypeIndex, entityIndex };
++entityIndex;
}
}
++archetypeIndex;
}
return ComponentIterator{ em, em._archetypes.size(), 0 };
}
auto end() const {
detail::ReadLock l(em._archetypesMutex);
return ComponentIterator{ em, em._archetypes.size(), 0 };
}
ComponentCollection(EntityManager & em) : em(em) {
detail::WriteLock l(em._updatesMutex);
++em._updatesLocked;
}
~ComponentCollection() {
detail::WriteLock l(em._updatesMutex);
assert(em._updatesLocked != 0);
--em._updatesLocked;
if (em._updatesLocked == 0)
em.doAllUpdates();
}
EntityManager & em;
};
public:
template<typename ... Comps>
auto getEntities() {
return ComponentCollection<Comps...>{ *this };
}
public:
template<typename RegisterWith, typename ...Types>
void registerTypes() {
if constexpr (!std::is_same<RegisterWith, nullptr_t>()) {
auto & s = getSystem<RegisterWith>();
s.template registerTypes<Types...>();
}
}
private:
Entity alloc();
private:
friend class Entity;
void addComponent(Entity::ID id, size_t component);
void removeComponent(Entity::ID id, size_t component);
void updateHasComponent(Entity::ID id, size_t component, bool newHasComponent);
void updateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask = false);
void doAllUpdates();
void doUpdateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask);
void doRemove(Entity::ID id);
private:
struct EntityMetadata {
bool active = false;
Entity::Mask mask = 0;
bool shouldActivateAfterInit = true;
};
std::vector<EntityMetadata> _entities;
mutable detail::Mutex _entitiesMutex;
std::vector<Archetype> _archetypes;
mutable detail::Mutex _archetypesMutex;
std::vector<Entity::ID> _toReuse;
bool _toReuseSorted = true;
mutable detail::Mutex _toReuseMutex;
struct Update {
Entity::ID id;
Entity::Mask newMask;
bool ignoreOldMask;
std::mutex mutex;
Update() = default;
Update(Update &&) = default;
Update(const Update & rhs) {
id = rhs.id;
newMask = rhs.newMask;
ignoreOldMask = rhs.ignoreOldMask;
}
};
std::vector<Update> _updates;
struct Removal {
Entity::ID id;
};
std::vector<Removal> _removals;
size_t _updatesLocked = 0;
mutable detail::Mutex _updatesMutex;
private:
mutable detail::GlobalCompMap _components; // Mutable to lock mutex
public: // Reserved to systems
detail::GlobalCompMap & __getComponentMap() { return _components; }
};
}
<|endoftext|> |
<commit_before><commit_msg>Don't read childPointers for leafNode<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapRegionCodec.h"
#include "SkAndroidCodec.h"
#include "SkCodecPriv.h"
#include "SkCodecTools.h"
SkBitmapRegionCodec::SkBitmapRegionCodec(SkAndroidCodec* codec)
: INHERITED(codec->getInfo().width(), codec->getInfo().height())
, fCodec(codec)
{}
bool SkBitmapRegionCodec::decodeRegion(SkBitmap* bitmap, SkBitmap::Allocator* allocator,
const SkIRect& desiredSubset, int sampleSize, SkColorType dstColorType,
bool requireUnpremul) {
// Fix the input sampleSize if necessary.
if (sampleSize < 1) {
sampleSize = 1;
}
// The size of the output bitmap is determined by the size of the
// requested subset, not by the size of the intersection of the subset
// and the image dimensions.
// If inputX is negative, we will need to place decoded pixels into the
// output bitmap starting at a left offset. Call this outX.
// If outX is non-zero, subsetX must be zero.
// If inputY is negative, we will need to place decoded pixels into the
// output bitmap starting at a top offset. Call this outY.
// If outY is non-zero, subsetY must be zero.
int outX;
int outY;
SkIRect subset = desiredSubset;
SubsetType type = adjust_subset_rect(fCodec->getInfo().dimensions(), &subset, &outX, &outY);
if (SubsetType::kOutside_SubsetType == type) {
return false;
}
// Ask the codec for a scaled subset
if (!fCodec->getSupportedSubset(&subset)) {
SkCodecPrintf("Error: Could not get subset.\n");
return false;
}
SkISize scaledSize = fCodec->getSampledSubsetDimensions(sampleSize, subset);
// Create the image info for the decode
SkAlphaType dstAlphaType = fCodec->getInfo().alphaType();
if (kOpaque_SkAlphaType != dstAlphaType) {
dstAlphaType = requireUnpremul ? kUnpremul_SkAlphaType : kPremul_SkAlphaType;
}
SkImageInfo decodeInfo = SkImageInfo::Make(scaledSize.width(), scaledSize.height(),
dstColorType, dstAlphaType);
// Construct a color table for the decode if necessary
SkAutoTUnref<SkColorTable> colorTable(nullptr);
SkPMColor* colorPtr = nullptr;
int* colorCountPtr = nullptr;
int maxColors = 256;
SkPMColor colors[256];
if (kIndex_8_SkColorType == dstColorType) {
// TODO (msarett): This performs a copy that is unnecessary since
// we have not yet initialized the color table.
// And then we need to use a const cast to get
// a pointer to the color table that we can
// modify during the decode. We could alternatively
// perform the decode before creating the bitmap and
// the color table. We still would need to copy the
// colors into the color table after the decode.
colorTable.reset(new SkColorTable(colors, maxColors));
colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
colorCountPtr = &maxColors;
}
// Initialize the destination bitmap
int scaledOutX = 0;
int scaledOutY = 0;
int scaledOutWidth = scaledSize.width();
int scaledOutHeight = scaledSize.height();
if (SubsetType::kPartiallyInside_SubsetType == type) {
scaledOutX = outX / sampleSize;
scaledOutY = outY / sampleSize;
// We need to be safe here because getSupportedSubset() may have modified the subset.
const int extraX = SkTMax(0, desiredSubset.width() - outX - subset.width());
const int extraY = SkTMax(0, desiredSubset.height() - outY - subset.height());
const int scaledExtraX = extraX / sampleSize;
const int scaledExtraY = extraY / sampleSize;
scaledOutWidth += scaledOutX + scaledExtraX;
scaledOutHeight += scaledOutY + scaledExtraY;
}
SkImageInfo outInfo = decodeInfo.makeWH(scaledOutWidth, scaledOutHeight);
bitmap->setInfo(outInfo, outInfo.minRowBytes());
if (!bitmap->tryAllocPixels(allocator, colorTable.get())) {
SkCodecPrintf("Error: Could not allocate pixels.\n");
return false;
}
// Zero the bitmap if the region is not completely within the image.
// TODO (msarett): Can we make this faster by implementing it to only
// zero parts of the image that we won't overwrite with
// pixels?
// TODO (msarett): This could be skipped if memory is zero initialized.
// This would matter if this code is moved to Android and
// uses Android bitmaps.
if (SubsetType::kPartiallyInside_SubsetType == type) {
void* pixels = bitmap->getPixels();
size_t bytes = outInfo.getSafeSize(bitmap->rowBytes());
memset(pixels, 0, bytes);
}
// Decode into the destination bitmap
SkAndroidCodec::AndroidOptions options;
options.fSampleSize = sampleSize;
options.fSubset = ⊂
options.fColorPtr = colorPtr;
options.fColorCount = colorCountPtr;
void* dst = bitmap->getAddr(scaledOutX, scaledOutY);
size_t rowBytes = bitmap->rowBytes();
SkCodec::Result result = fCodec->getAndroidPixels(decodeInfo, dst, rowBytes, &options);
if (SkCodec::kSuccess != result && SkCodec::kIncompleteInput != result) {
SkCodecPrintf("Error: Could not get pixels.\n");
return false;
}
return true;
}
bool SkBitmapRegionCodec::conversionSupported(SkColorType colorType) {
// FIXME: Call virtual function when it lands.
SkImageInfo info = SkImageInfo::Make(0, 0, colorType, fCodec->getInfo().alphaType(),
fCodec->getInfo().profileType());
return conversion_possible(info, fCodec->getInfo());
}
<commit_msg>SkBitmapRegionCodec needs to use the rowBytes on the pixel ref<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapRegionCodec.h"
#include "SkAndroidCodec.h"
#include "SkCodecPriv.h"
#include "SkCodecTools.h"
#include "SkPixelRef.h"
SkBitmapRegionCodec::SkBitmapRegionCodec(SkAndroidCodec* codec)
: INHERITED(codec->getInfo().width(), codec->getInfo().height())
, fCodec(codec)
{}
bool SkBitmapRegionCodec::decodeRegion(SkBitmap* bitmap, SkBitmap::Allocator* allocator,
const SkIRect& desiredSubset, int sampleSize, SkColorType dstColorType,
bool requireUnpremul) {
// Fix the input sampleSize if necessary.
if (sampleSize < 1) {
sampleSize = 1;
}
// The size of the output bitmap is determined by the size of the
// requested subset, not by the size of the intersection of the subset
// and the image dimensions.
// If inputX is negative, we will need to place decoded pixels into the
// output bitmap starting at a left offset. Call this outX.
// If outX is non-zero, subsetX must be zero.
// If inputY is negative, we will need to place decoded pixels into the
// output bitmap starting at a top offset. Call this outY.
// If outY is non-zero, subsetY must be zero.
int outX;
int outY;
SkIRect subset = desiredSubset;
SubsetType type = adjust_subset_rect(fCodec->getInfo().dimensions(), &subset, &outX, &outY);
if (SubsetType::kOutside_SubsetType == type) {
return false;
}
// Ask the codec for a scaled subset
if (!fCodec->getSupportedSubset(&subset)) {
SkCodecPrintf("Error: Could not get subset.\n");
return false;
}
SkISize scaledSize = fCodec->getSampledSubsetDimensions(sampleSize, subset);
// Create the image info for the decode
SkAlphaType dstAlphaType = fCodec->getInfo().alphaType();
if (kOpaque_SkAlphaType != dstAlphaType) {
dstAlphaType = requireUnpremul ? kUnpremul_SkAlphaType : kPremul_SkAlphaType;
}
SkImageInfo decodeInfo = SkImageInfo::Make(scaledSize.width(), scaledSize.height(),
dstColorType, dstAlphaType);
// Construct a color table for the decode if necessary
SkAutoTUnref<SkColorTable> colorTable(nullptr);
SkPMColor* colorPtr = nullptr;
int* colorCountPtr = nullptr;
int maxColors = 256;
SkPMColor colors[256];
if (kIndex_8_SkColorType == dstColorType) {
// TODO (msarett): This performs a copy that is unnecessary since
// we have not yet initialized the color table.
// And then we need to use a const cast to get
// a pointer to the color table that we can
// modify during the decode. We could alternatively
// perform the decode before creating the bitmap and
// the color table. We still would need to copy the
// colors into the color table after the decode.
colorTable.reset(new SkColorTable(colors, maxColors));
colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
colorCountPtr = &maxColors;
}
// Initialize the destination bitmap
int scaledOutX = 0;
int scaledOutY = 0;
int scaledOutWidth = scaledSize.width();
int scaledOutHeight = scaledSize.height();
if (SubsetType::kPartiallyInside_SubsetType == type) {
scaledOutX = outX / sampleSize;
scaledOutY = outY / sampleSize;
// We need to be safe here because getSupportedSubset() may have modified the subset.
const int extraX = SkTMax(0, desiredSubset.width() - outX - subset.width());
const int extraY = SkTMax(0, desiredSubset.height() - outY - subset.height());
const int scaledExtraX = extraX / sampleSize;
const int scaledExtraY = extraY / sampleSize;
scaledOutWidth += scaledOutX + scaledExtraX;
scaledOutHeight += scaledOutY + scaledExtraY;
}
SkImageInfo outInfo = decodeInfo.makeWH(scaledOutWidth, scaledOutHeight);
bitmap->setInfo(outInfo);
if (!bitmap->tryAllocPixels(allocator, colorTable.get())) {
SkCodecPrintf("Error: Could not allocate pixels.\n");
return false;
}
// Zero the bitmap if the region is not completely within the image.
// TODO (msarett): Can we make this faster by implementing it to only
// zero parts of the image that we won't overwrite with
// pixels?
// TODO (msarett): This could be skipped if memory is zero initialized.
// This would matter if this code is moved to Android and
// uses Android bitmaps.
if (SubsetType::kPartiallyInside_SubsetType == type) {
void* pixels = bitmap->getPixels();
size_t bytes = outInfo.getSafeSize(bitmap->rowBytes());
memset(pixels, 0, bytes);
}
// Decode into the destination bitmap
SkAndroidCodec::AndroidOptions options;
options.fSampleSize = sampleSize;
options.fSubset = ⊂
options.fColorPtr = colorPtr;
options.fColorCount = colorCountPtr;
void* dst = bitmap->getAddr(scaledOutX, scaledOutY);
// FIXME: skbug.com/4538
// It is important that we use the rowBytes on the pixelRef. They may not be
// set properly on the bitmap.
SkPixelRef* pr = SkRef(bitmap->pixelRef());
size_t rowBytes = pr->rowBytes();
bitmap->setInfo(outInfo, rowBytes);
bitmap->setPixelRef(pr)->unref();
SkCodec::Result result = fCodec->getAndroidPixels(decodeInfo, dst, rowBytes, &options);
if (SkCodec::kSuccess != result && SkCodec::kIncompleteInput != result) {
SkCodecPrintf("Error: Could not get pixels.\n");
return false;
}
return true;
}
bool SkBitmapRegionCodec::conversionSupported(SkColorType colorType) {
// FIXME: Call virtual function when it lands.
SkImageInfo info = SkImageInfo::Make(0, 0, colorType, fCodec->getInfo().alphaType(),
fCodec->getInfo().profileType());
return conversion_possible(info, fCodec->getInfo());
}
<|endoftext|> |
<commit_before>#include "cps/CPS_API.hpp"
#include "TestSuite.hpp"
#include "Utils.hpp"
#include <boost/program_options.hpp>
#include <iostream>
#include <cstdlib>
#include <memory>
#include <vector>
int main(int argc, char* argv[])
{
int result = EXIT_FAILURE;
try
{
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print this help message")
("host,c", po::value<std::string>(), "Clusterpoint host URL")
("db,d", po::value<std::string>(), "Clusterpoint database name")
("account,a", po::value<std::string>(), "Clusterpoint account id")
("user,u", po::value<std::string>(), "User name")
("password,p", po::value<std::string>(), "User password");
po::variables_map vm;
std::vector<string> additionalParameters;
po::parsed_options parsed = po::command_line_parser(argc, argv).
options(desc).allow_unregistered().run();
po::store(parsed, vm);
// Handle --help option
if (vm.count("help"))
{
std::cout << "Clusterpoint test app" << std::endl
<< desc
<< std::endl;
return EXIT_SUCCESS;
}
additionalParameters = po::collect_unrecognized(parsed.options,
po::include_positional);
po::notify(vm);
if (!additionalParameters.empty())
{
throw std::runtime_error(std::string("Unrecognized option: ") + additionalParameters[0]);
}
if (!vm.count("host"))
{
throw std::runtime_error("Clusterpoint host URL must be provided");
}
if (!vm.count("db"))
{
throw std::runtime_error("Clusterpoint database name must be provided");
}
if (!vm.count("user"))
{
throw std::runtime_error("User name must be provided");
}
if (!vm.count("password"))
{
throw std::runtime_error("User password must be provided");
}
if (!vm.count("account"))
{
throw std::runtime_error("Account Id must be provided");
}
std::map<std::string, std::string> account_info;
account_info["account"] = vm["account"].as<std::string>();
std::unique_ptr<CPS::Connection> conn(new CPS::Connection(
vm["host"].as<std::string>(),
vm["db"].as<std::string>(),
vm["user"].as<std::string>(),
vm["password"].as<std::string>(),
"document",
"document/id",
account_info));
conn->setDebug(true);
conn->setSocketTimeouts(10, 60, 180);
TestSuite(*conn).run();
result = EXIT_SUCCESS;
}
catch (CPS::Exception& e)
{
if (e.getResponse())
{
// Print out errors and related document ids
print_errors(std::cout, e.getResponse()->getErrors());
}
std::cerr << e.what() << std::endl;
std::cerr << boost::diagnostic_information(e) << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cerr << boost::diagnostic_information(e) << std::endl;
}
catch (...)
{
std::cerr << "Unhandled exception" << std::endl;
}
return result;
}
<commit_msg>Missing namespace for string type<commit_after>#include "cps/CPS_API.hpp"
#include "TestSuite.hpp"
#include "Utils.hpp"
#include <boost/program_options.hpp>
#include <iostream>
#include <cstdlib>
#include <memory>
#include <vector>
int main(int argc, char* argv[])
{
int result = EXIT_FAILURE;
try
{
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print this help message")
("host,c", po::value<std::string>(), "Clusterpoint host URL")
("db,d", po::value<std::string>(), "Clusterpoint database name")
("account,a", po::value<std::string>(), "Clusterpoint account id")
("user,u", po::value<std::string>(), "User name")
("password,p", po::value<std::string>(), "User password");
po::variables_map vm;
std::vector<std::string> additionalParameters;
po::parsed_options parsed = po::command_line_parser(argc, argv).
options(desc).allow_unregistered().run();
po::store(parsed, vm);
// Handle --help option
if (vm.count("help"))
{
std::cout << "Clusterpoint test app" << std::endl
<< desc
<< std::endl;
return EXIT_SUCCESS;
}
additionalParameters = po::collect_unrecognized(parsed.options,
po::include_positional);
po::notify(vm);
if (!additionalParameters.empty())
{
throw std::runtime_error(std::string("Unrecognized option: ") + additionalParameters[0]);
}
if (!vm.count("host"))
{
throw std::runtime_error("Clusterpoint host URL must be provided");
}
if (!vm.count("db"))
{
throw std::runtime_error("Clusterpoint database name must be provided");
}
if (!vm.count("user"))
{
throw std::runtime_error("User name must be provided");
}
if (!vm.count("password"))
{
throw std::runtime_error("User password must be provided");
}
if (!vm.count("account"))
{
throw std::runtime_error("Account Id must be provided");
}
std::map<std::string, std::string> account_info;
account_info["account"] = vm["account"].as<std::string>();
std::unique_ptr<CPS::Connection> conn(new CPS::Connection(
vm["host"].as<std::string>(),
vm["db"].as<std::string>(),
vm["user"].as<std::string>(),
vm["password"].as<std::string>(),
"document",
"document/id",
account_info));
conn->setDebug(true);
conn->setSocketTimeouts(10, 60, 180);
TestSuite(*conn).run();
result = EXIT_SUCCESS;
}
catch (CPS::Exception& e)
{
if (e.getResponse())
{
// Print out errors and related document ids
print_errors(std::cout, e.getResponse()->getErrors());
}
std::cerr << e.what() << std::endl;
std::cerr << boost::diagnostic_information(e) << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cerr << boost::diagnostic_information(e) << std::endl;
}
catch (...)
{
std::cerr << "Unhandled exception" << std::endl;
}
return result;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "BenchTimer.h"
#include "PictureBenchmark.h"
#include "SkBenchLogger.h"
#include "SkCanvas.h"
#include "SkGraphics.h"
#include "SkMath.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkTArray.h"
#include "picture_utils.h"
const int DEFAULT_REPEATS = 100;
static void usage(const char* argv0) {
SkDebugf("SkPicture benchmarking tool\n");
SkDebugf("\n"
"Usage: \n"
" %s <inputDir>...\n"
" [--logFile filename][--timers [wcgWC]*][--logPerIter 1|0][--min]\n"
" [--repeat] \n"
" [--mode pow2tile minWidth height[] (multi) | record | simple\n"
" | tile width[] height[] (multi) | playbackCreation]\n"
" [--pipe]\n"
" [--device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
"]"
, argv0);
SkDebugf("\n\n");
SkDebugf(
" inputDir: A list of directories and files to use as input. Files are\n"
" expected to have the .skp extension.\n\n"
" --logFile filename : destination for writing log output, in addition to stdout.\n");
SkDebugf(" --logPerIter 1|0 : "
"Log each repeat timer instead of mean, default is disabled.\n");
SkDebugf(" --min : Print the minimum times (instead of average).\n");
SkDebugf(" --timers [wcgWC]* : "
"Display wall, cpu, gpu, truncated wall or truncated cpu time for each picture.\n");
SkDebugf(
" --mode pow2tile minWidht height[] (multi) | record | simple\n"
" | tile width[] height[] (multi) | playbackCreation:\n"
" Run in the corresponding mode.\n"
" Default is simple.\n");
SkDebugf(
" pow2tile minWidth height[], Creates tiles with widths\n"
" that are all a power of two\n"
" such that they minimize the\n"
" amount of wasted tile space.\n"
" minWidth is the minimum width\n"
" of these tiles and must be a\n"
" power of two. Simple\n"
" rendering using these tiles\n"
" is benchmarked.\n"
" Append \"multi\" for multithreaded\n"
" drawing.\n");
SkDebugf(
" record, Benchmark picture to picture recording.\n");
SkDebugf(
" simple, Benchmark a simple rendering.\n");
SkDebugf(
" tile width[] height[], Benchmark simple rendering using\n"
" tiles with the given dimensions.\n"
" Append \"multi\" for multithreaded\n"
" drawing.\n");
SkDebugf(
" playbackCreation, Benchmark creation of the SkPicturePlayback.\n");
SkDebugf("\n");
SkDebugf(
" --pipe: Benchmark SkGPipe rendering. Compatible with tiled, multithreaded rendering.\n");
SkDebugf(
" --device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
": Use the corresponding device. Default is bitmap.\n");
SkDebugf(
" bitmap, Render to a bitmap.\n");
#if SK_SUPPORT_GPU
SkDebugf(
" gpu, Render to the GPU.\n");
#endif
SkDebugf("\n");
SkDebugf(
" --repeat: "
"Set the number of times to repeat each test."
" Default is %i.\n", DEFAULT_REPEATS);
}
SkBenchLogger gLogger;
static void run_single_benchmark(const SkString& inputPath,
sk_tools::PictureBenchmark& benchmark) {
SkFILEStream inputStream;
inputStream.setPath(inputPath.c_str());
if (!inputStream.isValid()) {
SkString err;
err.printf("Could not open file %s\n", inputPath.c_str());
gLogger.logError(err);
return;
}
SkPicture picture(&inputStream);
SkString filename;
sk_tools::get_basename(&filename, inputPath);
SkString result;
result.printf("running bench [%i %i] %s ", picture.width(), picture.height(),
filename.c_str());
gLogger.logProgress(result);
benchmark.run(&picture);
}
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
sk_tools::PictureBenchmark* benchmark) {
const char* argv0 = argv[0];
char* const* stop = argv + argc;
int repeats = DEFAULT_REPEATS;
sk_tools::PictureRenderer::SkDeviceTypes deviceType =
sk_tools::PictureRenderer::kBitmap_DeviceType;
sk_tools::PictureRenderer* renderer = NULL;
// Create a string to show our current settings.
// TODO: Make it prettier. Currently it just repeats the command line.
SkString commandLine("bench_pictures:");
for (int i = 1; i < argc; i++) {
commandLine.appendf(" %s", *(argv+i));
}
commandLine.append("\n");
bool usePipe = false;
bool multiThreaded = false;
bool useTiles = false;
const char* widthString = NULL;
const char* heightString = NULL;
bool isPowerOf2Mode = false;
const char* mode = NULL;
for (++argv; argv < stop; ++argv) {
if (0 == strcmp(*argv, "--repeat")) {
++argv;
if (argv < stop) {
repeats = atoi(*argv);
if (repeats < 1) {
gLogger.logError("--repeat must be given a value > 0\n");
exit(-1);
}
} else {
gLogger.logError("Missing arg for --repeat\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--pipe")) {
usePipe = true;
} else if (0 == strcmp(*argv, "--logFile")) {
argv++;
if (argv < stop) {
if (!gLogger.SetLogFile(*argv)) {
SkString str;
str.printf("Could not open %s for writing.", *argv);
gLogger.logError(str);
usage(argv0);
exit(-1);
}
} else {
gLogger.logError("Missing arg for --logFile\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--mode")) {
++argv;
if (argv >= stop) {
gLogger.logError("Missing mode for --mode\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "record")) {
renderer = SkNEW(sk_tools::RecordPictureRenderer);
} else if (0 == strcmp(*argv, "simple")) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
} else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
useTiles = true;
mode = *argv;
if (0 == strcmp(*argv, "pow2tile")) {
isPowerOf2Mode = true;
}
++argv;
if (argv >= stop) {
SkString err;
err.printf("Missing width for --mode %s\n", mode);
gLogger.logError(err);
usage(argv0);
exit(-1);
}
widthString = *argv;
++argv;
if (argv >= stop) {
gLogger.logError("Missing height for --mode tile\n");
usage(argv0);
exit(-1);
}
heightString = *argv;
++argv;
if (argv < stop && 0 == strcmp(*argv, "multi")) {
multiThreaded = true;
} else {
--argv;
}
} else if (0 == strcmp(*argv, "playbackCreation")) {
renderer = SkNEW(sk_tools::PlaybackCreationRenderer);
} else {
SkString err;
err.printf("%s is not a valid mode for --mode\n", *argv);
gLogger.logError(err);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--device")) {
++argv;
if (argv >= stop) {
gLogger.logError("Missing mode for --deivce\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "bitmap")) {
deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
}
#if SK_SUPPORT_GPU
else if (0 == strcmp(*argv, "gpu")) {
deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
}
#endif
else {
SkString err;
err.printf("%s is not a valid mode for --device\n", *argv);
gLogger.logError(err);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--timers")) {
++argv;
if (argv < stop) {
bool timerWall = false;
bool truncatedTimerWall = false;
bool timerCpu = false;
bool truncatedTimerCpu = false;
bool timerGpu = false;
for (char* t = *argv; *t; ++t) {
switch (*t) {
case 'w':
timerWall = true;
break;
case 'c':
timerCpu = true;
break;
case 'W':
truncatedTimerWall = true;
break;
case 'C':
truncatedTimerCpu = true;
break;
case 'g':
timerGpu = true;
break;
default: {
break;
}
}
}
benchmark->setTimersToShow(timerWall, truncatedTimerWall, timerCpu,
truncatedTimerCpu, timerGpu);
} else {
gLogger.logError("Missing arg for --timers\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--min")) {
benchmark->setPrintMin(true);
} else if (0 == strcmp(*argv, "--logPerIter")) {
++argv;
if (argv < stop) {
bool log = atoi(*argv) != 0;
benchmark->setLogPerIter(log);
} else {
gLogger.logError("Missing arg for --logPerIter\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) {
usage(argv0);
exit(0);
} else {
inputs->push_back(SkString(*argv));
}
}
if (useTiles) {
SkASSERT(NULL == renderer);
sk_tools::TiledPictureRenderer* tiledRenderer = SkNEW(sk_tools::TiledPictureRenderer);
if (isPowerOf2Mode) {
int minWidth = atoi(widthString);
if (!SkIsPow2(minWidth) || minWidth < 0) {
tiledRenderer->unref();
SkString err;
err.printf("-mode %s must be given a width"
" value that is a power of two\n", mode);
gLogger.logError(err);
exit(-1);
}
tiledRenderer->setTileMinPowerOf2Width(minWidth);
} else if (sk_tools::is_percentage(widthString)) {
tiledRenderer->setTileWidthPercentage(atof(widthString));
if (!(tiledRenderer->getTileWidthPercentage() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a width percentage > 0\n");
exit(-1);
}
} else {
tiledRenderer->setTileWidth(atoi(widthString));
if (!(tiledRenderer->getTileWidth() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a width > 0\n");
exit(-1);
}
}
if (sk_tools::is_percentage(heightString)) {
tiledRenderer->setTileHeightPercentage(atof(heightString));
if (!(tiledRenderer->getTileHeightPercentage() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a height percentage > 0\n");
exit(-1);
}
} else {
tiledRenderer->setTileHeight(atoi(heightString));
if (!(tiledRenderer->getTileHeight() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a height > 0\n");
exit(-1);
}
}
tiledRenderer->setMultiThreaded(multiThreaded);
tiledRenderer->setUsePipe(usePipe);
renderer = tiledRenderer;
} else if (usePipe) {
renderer = SkNEW(sk_tools::PipePictureRenderer);
}
if (inputs->count() < 1) {
SkDELETE(benchmark);
usage(argv0);
exit(-1);
}
if (NULL == renderer) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
}
benchmark->setRenderer(renderer)->unref();
benchmark->setRepeats(repeats);
benchmark->setDeviceType(deviceType);
benchmark->setLogger(&gLogger);
// Report current settings:
gLogger.logProgress(commandLine);
}
static void process_input(const SkString& input, sk_tools::PictureBenchmark& benchmark) {
SkOSFile::Iter iter(input.c_str(), "skp");
SkString inputFilename;
if (iter.next(&inputFilename)) {
do {
SkString inputPath;
sk_tools::make_filepath(&inputPath, input, inputFilename);
run_single_benchmark(inputPath, benchmark);
} while(iter.next(&inputFilename));
} else {
run_single_benchmark(input, benchmark);
}
}
int main(int argc, char* const argv[]) {
#ifdef SK_ENABLE_INST_COUNT
gPrintInstCount = true;
#endif
SkAutoGraphics ag;
SkTArray<SkString> inputs;
sk_tools::PictureBenchmark benchmark;
parse_commandline(argc, argv, &inputs, &benchmark);
for (int i = 0; i < inputs.count(); ++i) {
process_input(inputs[i], benchmark);
}
}
<commit_msg>Do not exit on failure to open logFile<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "BenchTimer.h"
#include "PictureBenchmark.h"
#include "SkBenchLogger.h"
#include "SkCanvas.h"
#include "SkGraphics.h"
#include "SkMath.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkTArray.h"
#include "picture_utils.h"
const int DEFAULT_REPEATS = 100;
static void usage(const char* argv0) {
SkDebugf("SkPicture benchmarking tool\n");
SkDebugf("\n"
"Usage: \n"
" %s <inputDir>...\n"
" [--logFile filename][--timers [wcgWC]*][--logPerIter 1|0][--min]\n"
" [--repeat] \n"
" [--mode pow2tile minWidth height[] (multi) | record | simple\n"
" | tile width[] height[] (multi) | playbackCreation]\n"
" [--pipe]\n"
" [--device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
"]"
, argv0);
SkDebugf("\n\n");
SkDebugf(
" inputDir: A list of directories and files to use as input. Files are\n"
" expected to have the .skp extension.\n\n"
" --logFile filename : destination for writing log output, in addition to stdout.\n");
SkDebugf(" --logPerIter 1|0 : "
"Log each repeat timer instead of mean, default is disabled.\n");
SkDebugf(" --min : Print the minimum times (instead of average).\n");
SkDebugf(" --timers [wcgWC]* : "
"Display wall, cpu, gpu, truncated wall or truncated cpu time for each picture.\n");
SkDebugf(
" --mode pow2tile minWidht height[] (multi) | record | simple\n"
" | tile width[] height[] (multi) | playbackCreation:\n"
" Run in the corresponding mode.\n"
" Default is simple.\n");
SkDebugf(
" pow2tile minWidth height[], Creates tiles with widths\n"
" that are all a power of two\n"
" such that they minimize the\n"
" amount of wasted tile space.\n"
" minWidth is the minimum width\n"
" of these tiles and must be a\n"
" power of two. Simple\n"
" rendering using these tiles\n"
" is benchmarked.\n"
" Append \"multi\" for multithreaded\n"
" drawing.\n");
SkDebugf(
" record, Benchmark picture to picture recording.\n");
SkDebugf(
" simple, Benchmark a simple rendering.\n");
SkDebugf(
" tile width[] height[], Benchmark simple rendering using\n"
" tiles with the given dimensions.\n"
" Append \"multi\" for multithreaded\n"
" drawing.\n");
SkDebugf(
" playbackCreation, Benchmark creation of the SkPicturePlayback.\n");
SkDebugf("\n");
SkDebugf(
" --pipe: Benchmark SkGPipe rendering. Compatible with tiled, multithreaded rendering.\n");
SkDebugf(
" --device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
": Use the corresponding device. Default is bitmap.\n");
SkDebugf(
" bitmap, Render to a bitmap.\n");
#if SK_SUPPORT_GPU
SkDebugf(
" gpu, Render to the GPU.\n");
#endif
SkDebugf("\n");
SkDebugf(
" --repeat: "
"Set the number of times to repeat each test."
" Default is %i.\n", DEFAULT_REPEATS);
}
SkBenchLogger gLogger;
static void run_single_benchmark(const SkString& inputPath,
sk_tools::PictureBenchmark& benchmark) {
SkFILEStream inputStream;
inputStream.setPath(inputPath.c_str());
if (!inputStream.isValid()) {
SkString err;
err.printf("Could not open file %s\n", inputPath.c_str());
gLogger.logError(err);
return;
}
SkPicture picture(&inputStream);
SkString filename;
sk_tools::get_basename(&filename, inputPath);
SkString result;
result.printf("running bench [%i %i] %s ", picture.width(), picture.height(),
filename.c_str());
gLogger.logProgress(result);
benchmark.run(&picture);
}
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
sk_tools::PictureBenchmark* benchmark) {
const char* argv0 = argv[0];
char* const* stop = argv + argc;
int repeats = DEFAULT_REPEATS;
sk_tools::PictureRenderer::SkDeviceTypes deviceType =
sk_tools::PictureRenderer::kBitmap_DeviceType;
sk_tools::PictureRenderer* renderer = NULL;
// Create a string to show our current settings.
// TODO: Make it prettier. Currently it just repeats the command line.
SkString commandLine("bench_pictures:");
for (int i = 1; i < argc; i++) {
commandLine.appendf(" %s", *(argv+i));
}
commandLine.append("\n");
bool usePipe = false;
bool multiThreaded = false;
bool useTiles = false;
const char* widthString = NULL;
const char* heightString = NULL;
bool isPowerOf2Mode = false;
const char* mode = NULL;
for (++argv; argv < stop; ++argv) {
if (0 == strcmp(*argv, "--repeat")) {
++argv;
if (argv < stop) {
repeats = atoi(*argv);
if (repeats < 1) {
gLogger.logError("--repeat must be given a value > 0\n");
exit(-1);
}
} else {
gLogger.logError("Missing arg for --repeat\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--pipe")) {
usePipe = true;
} else if (0 == strcmp(*argv, "--logFile")) {
argv++;
if (argv < stop) {
if (!gLogger.SetLogFile(*argv)) {
SkString str;
str.printf("Could not open %s for writing.", *argv);
gLogger.logError(str);
usage(argv0);
// TODO(borenet): We're disabling this for now, due to
// write-protected Android devices. The very short-term
// solution is to ignore the fact that we have no log file.
//exit(-1);
}
} else {
gLogger.logError("Missing arg for --logFile\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--mode")) {
++argv;
if (argv >= stop) {
gLogger.logError("Missing mode for --mode\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "record")) {
renderer = SkNEW(sk_tools::RecordPictureRenderer);
} else if (0 == strcmp(*argv, "simple")) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
} else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
useTiles = true;
mode = *argv;
if (0 == strcmp(*argv, "pow2tile")) {
isPowerOf2Mode = true;
}
++argv;
if (argv >= stop) {
SkString err;
err.printf("Missing width for --mode %s\n", mode);
gLogger.logError(err);
usage(argv0);
exit(-1);
}
widthString = *argv;
++argv;
if (argv >= stop) {
gLogger.logError("Missing height for --mode tile\n");
usage(argv0);
exit(-1);
}
heightString = *argv;
++argv;
if (argv < stop && 0 == strcmp(*argv, "multi")) {
multiThreaded = true;
} else {
--argv;
}
} else if (0 == strcmp(*argv, "playbackCreation")) {
renderer = SkNEW(sk_tools::PlaybackCreationRenderer);
} else {
SkString err;
err.printf("%s is not a valid mode for --mode\n", *argv);
gLogger.logError(err);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--device")) {
++argv;
if (argv >= stop) {
gLogger.logError("Missing mode for --device\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "bitmap")) {
deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
}
#if SK_SUPPORT_GPU
else if (0 == strcmp(*argv, "gpu")) {
deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
}
#endif
else {
SkString err;
err.printf("%s is not a valid mode for --device\n", *argv);
gLogger.logError(err);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--timers")) {
++argv;
if (argv < stop) {
bool timerWall = false;
bool truncatedTimerWall = false;
bool timerCpu = false;
bool truncatedTimerCpu = false;
bool timerGpu = false;
for (char* t = *argv; *t; ++t) {
switch (*t) {
case 'w':
timerWall = true;
break;
case 'c':
timerCpu = true;
break;
case 'W':
truncatedTimerWall = true;
break;
case 'C':
truncatedTimerCpu = true;
break;
case 'g':
timerGpu = true;
break;
default: {
break;
}
}
}
benchmark->setTimersToShow(timerWall, truncatedTimerWall, timerCpu,
truncatedTimerCpu, timerGpu);
} else {
gLogger.logError("Missing arg for --timers\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--min")) {
benchmark->setPrintMin(true);
} else if (0 == strcmp(*argv, "--logPerIter")) {
++argv;
if (argv < stop) {
bool log = atoi(*argv) != 0;
benchmark->setLogPerIter(log);
} else {
gLogger.logError("Missing arg for --logPerIter\n");
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) {
usage(argv0);
exit(0);
} else {
inputs->push_back(SkString(*argv));
}
}
if (useTiles) {
SkASSERT(NULL == renderer);
sk_tools::TiledPictureRenderer* tiledRenderer = SkNEW(sk_tools::TiledPictureRenderer);
if (isPowerOf2Mode) {
int minWidth = atoi(widthString);
if (!SkIsPow2(minWidth) || minWidth < 0) {
tiledRenderer->unref();
SkString err;
err.printf("-mode %s must be given a width"
" value that is a power of two\n", mode);
gLogger.logError(err);
exit(-1);
}
tiledRenderer->setTileMinPowerOf2Width(minWidth);
} else if (sk_tools::is_percentage(widthString)) {
tiledRenderer->setTileWidthPercentage(atof(widthString));
if (!(tiledRenderer->getTileWidthPercentage() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a width percentage > 0\n");
exit(-1);
}
} else {
tiledRenderer->setTileWidth(atoi(widthString));
if (!(tiledRenderer->getTileWidth() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a width > 0\n");
exit(-1);
}
}
if (sk_tools::is_percentage(heightString)) {
tiledRenderer->setTileHeightPercentage(atof(heightString));
if (!(tiledRenderer->getTileHeightPercentage() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a height percentage > 0\n");
exit(-1);
}
} else {
tiledRenderer->setTileHeight(atoi(heightString));
if (!(tiledRenderer->getTileHeight() > 0)) {
tiledRenderer->unref();
gLogger.logError("--mode tile must be given a height > 0\n");
exit(-1);
}
}
tiledRenderer->setMultiThreaded(multiThreaded);
tiledRenderer->setUsePipe(usePipe);
renderer = tiledRenderer;
} else if (usePipe) {
renderer = SkNEW(sk_tools::PipePictureRenderer);
}
if (inputs->count() < 1) {
SkDELETE(benchmark);
usage(argv0);
exit(-1);
}
if (NULL == renderer) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
}
benchmark->setRenderer(renderer)->unref();
benchmark->setRepeats(repeats);
benchmark->setDeviceType(deviceType);
benchmark->setLogger(&gLogger);
// Report current settings:
gLogger.logProgress(commandLine);
}
static void process_input(const SkString& input, sk_tools::PictureBenchmark& benchmark) {
SkOSFile::Iter iter(input.c_str(), "skp");
SkString inputFilename;
if (iter.next(&inputFilename)) {
do {
SkString inputPath;
sk_tools::make_filepath(&inputPath, input, inputFilename);
run_single_benchmark(inputPath, benchmark);
} while(iter.next(&inputFilename));
} else {
run_single_benchmark(input, benchmark);
}
}
int main(int argc, char* const argv[]) {
#ifdef SK_ENABLE_INST_COUNT
gPrintInstCount = true;
#endif
SkAutoGraphics ag;
SkTArray<SkString> inputs;
sk_tools::PictureBenchmark benchmark;
parse_commandline(argc, argv, &inputs, &benchmark);
for (int i = 0; i < inputs.count(); ++i) {
process_input(inputs[i], benchmark);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChartModelHelper.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 11:55:41 $
*
* 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_CONTROLLER_CHARTMODELHELPER_HXX
#define _CHART2_CONTROLLER_CHARTMODELHELPER_HXX
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_
#include <com/sun/star/chart2/XChartType.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATASERIES_HPP_
#include <com/sun/star/chart2/XDataSeries.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_
#include <com/sun/star/chart2/XDiagram.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart2/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#include <vector>
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class ChartModelHelper
{
public:
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >
findDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel );
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >
findDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument >& xChartDoc );
static ::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > > getDataSeries(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartDocument > & xChartDoc );
static ::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > > getDataSeries(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel > & xModel );
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType >
getChartTypeOfSeries(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel
, const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries >& xGivenDataSeries );
static ::com::sun::star::awt::Size getPageSize(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel );
static void setPageSize( const ::com::sun::star::awt::Size& rSize
, const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel );
static void triggerRangeHighlighting( const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel );
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.60); FILE MERGED 2008/04/01 10:50:27 thb 1.8.60.2: #i85898# Stripping all external header guards 2008/03/28 16:43:52 rt 1.8.60.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: ChartModelHelper.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CHART2_CONTROLLER_CHARTMODELHELPER_HXX
#define _CHART2_CONTROLLER_CHARTMODELHELPER_HXX
#include <com/sun/star/chart2/XChartType.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/chart2/XDiagram.hpp>
#include <com/sun/star/chart2/XChartDocument.hpp>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <vector>
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class ChartModelHelper
{
public:
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >
findDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel );
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >
findDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument >& xChartDoc );
static ::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > > getDataSeries(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartDocument > & xChartDoc );
static ::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > > getDataSeries(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel > & xModel );
static ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartType >
getChartTypeOfSeries(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel
, const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries >& xGivenDataSeries );
static ::com::sun::star::awt::Size getPageSize(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel );
static void setPageSize( const ::com::sun::star::awt::Size& rSize
, const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel );
static void triggerRangeHighlighting( const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xModel );
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/utils.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser_init.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/external_cookie_handler.h"
#include "chrome/browser/chromeos/login/authentication_notification_details.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "views/widget/widget_gtk.h"
namespace chromeos {
namespace login_utils {
void CompleteLogin(const std::string& username) {
LOG(INFO) << "LoginManagerView: OnLoginSuccess()";
UserManager::Get()->UserLoggedIn(username);
// Send notification of success
AuthenticationNotificationDetails details(true);
NotificationService::current()->Notify(
NotificationType::LOGIN_AUTHENTICATION,
NotificationService::AllSources(),
Details<AuthenticationNotificationDetails>(&details));
// Now launch the initial browser window.
BrowserInit browser_init;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ProfileManager* profile_manager = g_browser_process->profile_manager();
// The default profile will have been changed because the ProfileManager
// will process the notification that the UserManager sends out.
Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
int return_code;
ExternalCookieHandler::GetCookies(command_line, profile);
browser_init.LaunchBrowser(command_line, profile, std::wstring(), true,
&return_code);
}
} // namespace login_utils
} // namespace chromeos
<commit_msg>Code got moved out from under me, and when I merged, I missed a line. People not using my new code will be unaffected, but this change makes it so the new stuff works again. Review URL: http://codereview.chromium.org/826003<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/utils.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser_init.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/external_cookie_handler.h"
#include "chrome/browser/chromeos/login/authentication_notification_details.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "views/widget/widget_gtk.h"
namespace chromeos {
namespace login_utils {
void CompleteLogin(const std::string& username) {
LOG(INFO) << "LoginManagerView: OnLoginSuccess()";
UserManager::Get()->UserLoggedIn(username);
// Send notification of success
AuthenticationNotificationDetails details(true);
NotificationService::current()->Notify(
NotificationType::LOGIN_AUTHENTICATION,
NotificationService::AllSources(),
Details<AuthenticationNotificationDetails>(&details));
// Now launch the initial browser window.
BrowserInit browser_init;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ProfileManager* profile_manager = g_browser_process->profile_manager();
// The default profile will have been changed because the ProfileManager
// will process the notification that the UserManager sends out.
Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
int return_code;
if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kInChromeAuth))
ExternalCookieHandler::GetCookies(command_line, profile);
browser_init.LaunchBrowser(command_line, profile, std::wstring(), true,
&return_code);
}
} // namespace login_utils
} // namespace chromeos
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.